repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
202 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
sascha/DrawerController
KitchenSink/ExampleFiles/ViewControllers/ExampleCenterTableViewController.swift
1
11996
// Copyright (c) 2017 evolved.io (http://evolved.io) // // 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 DrawerController enum CenterViewControllerSection: Int { case leftViewState case leftDrawerAnimation case rightViewState case rightDrawerAnimation } class ExampleCenterTableViewController: ExampleViewController, UITableViewDataSource, UITableViewDelegate { var tableView: UITableView! override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) self.restorationIdentifier = "ExampleCenterControllerRestorationKey" } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.restorationIdentifier = "ExampleCenterControllerRestorationKey" } override func viewDidLoad() { super.viewDidLoad() self.tableView = UITableView(frame: self.view.bounds, style: .grouped) self.tableView.delegate = self self.tableView.dataSource = self self.view.addSubview(self.tableView) self.tableView.autoresizingMask = [ .flexibleWidth, .flexibleHeight ] let doubleTap = UITapGestureRecognizer(target: self, action: #selector(doubleTap(_:))) doubleTap.numberOfTapsRequired = 2 self.view.addGestureRecognizer(doubleTap) let twoFingerDoubleTap = UITapGestureRecognizer(target: self, action: #selector(twoFingerDoubleTap(_:))) twoFingerDoubleTap.numberOfTapsRequired = 2 twoFingerDoubleTap.numberOfTouchesRequired = 2 self.view.addGestureRecognizer(twoFingerDoubleTap) self.setupLeftMenuButton() self.setupRightMenuButton() let barColor = UIColor(red: 247/255, green: 249/255, blue: 250/255, alpha: 1.0) self.navigationController?.navigationBar.barTintColor = barColor self.navigationController?.view.layer.cornerRadius = 10.0 let backView = UIView() backView.backgroundColor = UIColor(red: 208/255, green: 208/255, blue: 208/255, alpha: 1.0) self.tableView.backgroundView = backView } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) print("Center will appear") } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) print("Center did appear") } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) print("Center will disappear") } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) print("Center did disappear") } func setupLeftMenuButton() { let leftDrawerButton = DrawerBarButtonItem(target: self, action: #selector(leftDrawerButtonPress(_:))) self.navigationItem.setLeftBarButton(leftDrawerButton, animated: true) } func setupRightMenuButton() { let rightDrawerButton = DrawerBarButtonItem(target: self, action: #selector(rightDrawerButtonPress(_:))) self.navigationItem.setRightBarButton(rightDrawerButton, animated: true) } override func contentSizeDidChange(_ size: String) { self.tableView.reloadData() } // MARK: - UITableViewDataSource func numberOfSections(in tableView: UITableView) -> Int { return 4 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case CenterViewControllerSection.leftDrawerAnimation.rawValue, CenterViewControllerSection.rightDrawerAnimation.rawValue: return 6 case CenterViewControllerSection.leftViewState.rawValue, CenterViewControllerSection.rightViewState.rawValue: return 1 default: return 0 } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let CellIdentifier = "Cell" var cell: UITableViewCell! = tableView.dequeueReusableCell(withIdentifier: CellIdentifier) as UITableViewCell? if cell == nil { cell = CenterTableViewCell(style: .default, reuseIdentifier: CellIdentifier) cell.selectionStyle = .gray } let selectedColor = UIColor(red: 1 / 255, green: 15 / 255, blue: 25 / 255, alpha: 1.0) let unselectedColor = UIColor(red: 79 / 255, green: 93 / 255, blue: 102 / 255, alpha: 1.0) switch (indexPath as NSIndexPath).section { case CenterViewControllerSection.leftDrawerAnimation.rawValue, CenterViewControllerSection.rightDrawerAnimation.rawValue: var animationTypeForSection: DrawerAnimationType if (indexPath as NSIndexPath).section == CenterViewControllerSection.leftDrawerAnimation.rawValue { animationTypeForSection = ExampleDrawerVisualStateManager.sharedManager.leftDrawerAnimationType } else { animationTypeForSection = ExampleDrawerVisualStateManager.sharedManager.rightDrawerAnimationType } if animationTypeForSection.rawValue == (indexPath as NSIndexPath).row { cell.accessoryType = .checkmark cell.textLabel?.textColor = selectedColor } else { cell.accessoryType = .none cell.textLabel?.textColor = unselectedColor } switch (indexPath as NSIndexPath).row { case DrawerAnimationType.none.rawValue: cell.textLabel?.text = "None" case DrawerAnimationType.slide.rawValue: cell.textLabel?.text = "Slide" case DrawerAnimationType.slideAndScale.rawValue: cell.textLabel?.text = "Slide and Scale" case DrawerAnimationType.swingingDoor.rawValue: cell.textLabel?.text = "Swinging Door" case DrawerAnimationType.parallax.rawValue: cell.textLabel?.text = "Parallax" case DrawerAnimationType.animatedBarButton.rawValue: cell.textLabel?.text = "Animated Menu Button" default: break } case CenterViewControllerSection.leftViewState.rawValue: cell.textLabel?.text = "Enabled" if self.evo_drawerController?.leftDrawerViewController != nil { cell.accessoryType = .checkmark cell.textLabel?.textColor = selectedColor } else { cell.accessoryType = .none cell.textLabel?.textColor = unselectedColor } case CenterViewControllerSection.rightViewState.rawValue: cell.textLabel?.text = "Enabled" if self.evo_drawerController?.rightDrawerViewController != nil { cell.accessoryType = .checkmark cell.textLabel?.textColor = selectedColor } else { cell.accessoryType = .none cell.textLabel?.textColor = unselectedColor } default: break } return cell } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { switch section { case CenterViewControllerSection.leftDrawerAnimation.rawValue: return "Left Drawer Animation"; case CenterViewControllerSection.rightDrawerAnimation.rawValue: return "Right Drawer Animation"; case CenterViewControllerSection.leftViewState.rawValue: return "Left Drawer"; case CenterViewControllerSection.rightViewState.rawValue: return "Right Drawer"; default: return nil } } // MARK: - UITableViewDelegate func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { switch (indexPath as NSIndexPath).section { case CenterViewControllerSection.leftDrawerAnimation.rawValue, CenterViewControllerSection.rightDrawerAnimation.rawValue: if (indexPath as NSIndexPath).section == CenterViewControllerSection.leftDrawerAnimation.rawValue { ExampleDrawerVisualStateManager.sharedManager.leftDrawerAnimationType = DrawerAnimationType(rawValue: (indexPath as NSIndexPath).row)! } else { ExampleDrawerVisualStateManager.sharedManager.rightDrawerAnimationType = DrawerAnimationType(rawValue: (indexPath as NSIndexPath).row)! } tableView.reloadSections(IndexSet(integer: (indexPath as NSIndexPath).section), with: .none) tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none) tableView.deselectRow(at: indexPath, animated: true) case CenterViewControllerSection.leftViewState.rawValue, CenterViewControllerSection.rightViewState.rawValue: var sideDrawerViewController: UIViewController? var drawerSide = DrawerSide.none if (indexPath as NSIndexPath).section == CenterViewControllerSection.leftViewState.rawValue { sideDrawerViewController = self.evo_drawerController?.leftDrawerViewController drawerSide = .left } else if (indexPath as NSIndexPath).section == CenterViewControllerSection.rightViewState.rawValue { sideDrawerViewController = self.evo_drawerController?.rightDrawerViewController drawerSide = .right } if sideDrawerViewController != nil { self.evo_drawerController?.closeDrawer(animated: true, completion: { (finished) -> Void in if drawerSide == DrawerSide.left { self.evo_drawerController?.leftDrawerViewController = nil self.navigationItem.setLeftBarButtonItems(nil, animated: true) } else if drawerSide == .right { self.evo_drawerController?.rightDrawerViewController = nil self.navigationItem.setRightBarButtonItems(nil, animated: true) } tableView.reloadRows(at: [indexPath], with: .none) tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none) tableView.deselectRow(at: indexPath, animated: true) }) } else { if drawerSide == .left { let vc = ExampleLeftSideDrawerViewController() let navC = UINavigationController(rootViewController: vc) self.evo_drawerController?.leftDrawerViewController = navC self.setupLeftMenuButton() } else if drawerSide == .right { let vc = ExampleRightSideDrawerViewController() let navC = UINavigationController(rootViewController: vc) self.evo_drawerController?.rightDrawerViewController = navC self.setupRightMenuButton() } tableView.reloadRows(at: [indexPath], with: .none) tableView.selectRow(at: indexPath, animated: false, scrollPosition: .none) tableView.deselectRow(at: indexPath, animated: true) } default: break } } // MARK: - Button Handlers @objc func leftDrawerButtonPress(_ sender: AnyObject?) { self.evo_drawerController?.toggleDrawerSide(.left, animated: true, completion: nil) } @objc func rightDrawerButtonPress(_ sender: AnyObject?) { self.evo_drawerController?.toggleDrawerSide(.right, animated: true, completion: nil) } @objc func doubleTap(_ gesture: UITapGestureRecognizer) { self.evo_drawerController?.bouncePreview(for: .left, completion: nil) } @objc func twoFingerDoubleTap(_ gesture: UITapGestureRecognizer) { self.evo_drawerController?.bouncePreview(for: .right, completion: nil) } }
mit
3021de4113474e019c4d47750b42df55
39.802721
143
0.720657
5.15957
false
false
false
false
maitruonghcmus/QuickChat
QuickChat/ViewControllers/LandingVC.swift
1
6590
import UIKit import LocalAuthentication class LandingVC: UIViewController { //MARK: *** Variable //MARK: *** UI Elements //MARK: *** Custom Function //Push to ViewController func pushTo(viewController: ViewControllerType) { switch viewController { case .tabbar: let vc = self.storyboard?.instantiateViewController(withIdentifier: "TabVC") as! TabVC self.present(vc, animated: true, completion: nil) case .login: let vc = self.storyboard?.instantiateViewController(withIdentifier: "LoginVC") as! LoginVC self.present(vc, animated: true, completion: nil) default: let vc = self.storyboard?.instantiateViewController(withIdentifier: "LoginVC") as! LoginVC self.present(vc, animated: true, completion: nil) } } //MARK: *** UI Events //MARK: *** View //Set app alway display as portrait (dont rotate) override var supportedInterfaceOrientations: UIInterfaceOrientationMask { get { return UIInterfaceOrientationMask.portrait } } //Check user sign in or not override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if let userInformation = UserDefaults.standard.dictionary(forKey: "userInformation") { let email = userInformation["email"] as! String let password = userInformation["password"] as! String User.loginUser(withEmail: email, password: password, completion: { [weak weakSelf = self] (status) in DispatchQueue.main.async { if status == true { Other.get(completion: {(ok) in if ok == true && Other.useTouchID == true { let authenticationContext = LAContext() var policy: LAPolicy? // Depending the iOS version we'll need to choose the policy we are able to use if #available(iOS 9.0, *) { // iOS 9+ users with Biometric and Passcode verification policy = .deviceOwnerAuthentication } else { // iOS 8+ users with Biometric and Custom (Fallback button) verification authenticationContext.localizedFallbackTitle = "Fuu!" policy = .deviceOwnerAuthenticationWithBiometrics } var error:NSError? guard authenticationContext.canEvaluatePolicy(policy!, error: &error) else { self.showAlertWithTitle(title: "Error", message: "This device does not have a TouchID sensor.") return } // 3. Check the fingerprint authenticationContext.evaluatePolicy( policy!, localizedReason: "Only awesome people are allowed", reply: { [unowned self] (success, error) -> Void in if( success ) { // Fingerprint recognized // Go to view controller self.pushTo(viewController: .tabbar) }else { // Check if there is an error if let error = error as NSError? { let message = self.errorMessageForLAErrorCode(errorCode: error.code) self.showAlertViewAfterEvaluatingPolicyWithMessage(message: message) } } }) } else { self.pushTo(viewController: .tabbar) } }) } else { weakSelf?.pushTo(viewController: .login) } weakSelf = nil } }) } else { self.pushTo(viewController: .login) } } //MARK: *** Touch ID func showAlertViewAfterEvaluatingPolicyWithMessage( message:String ){ showAlertWithTitle(title: "Error", message: message) } func errorMessageForLAErrorCode( errorCode:Int ) -> String{ var message = "" switch errorCode { case LAError.appCancel.rawValue: message = "Authentication was cancelled by application" case LAError.authenticationFailed.rawValue: message = "The user failed to provide valid credentials" case LAError.invalidContext.rawValue: message = "The context is invalid" case LAError.passcodeNotSet.rawValue: message = "Passcode is not set on the device" case LAError.systemCancel.rawValue: message = "Authentication was cancelled by the system" case LAError.touchIDLockout.rawValue: message = "Too many failed attempts." case LAError.touchIDNotAvailable.rawValue: message = "TouchID is not available on the device" case LAError.userCancel.rawValue: message = "The user did cancel" case LAError.userFallback.rawValue: message = "The user chose to use the fallback" default: message = "Did not find error code on LAError object" } return message } func showAlertWithTitle( title:String, message:String ) { let alertVC = UIAlertController(title: title, message: message, preferredStyle: .alert) let okAction = UIAlertAction(title: "Ok", style: .default){ (_) in self.pushTo(viewController: .login) } alertVC.addAction(okAction) DispatchQueue.main.async() { () -> Void in self.present(alertVC, animated: true, completion: nil) } } override func viewDidLoad() { super.viewDidLoad() } //MARK: *** Table View }
mit
78e5a9859af6e162cfc6cfa02488a0e0
43.527027
131
0.504401
6.216981
false
false
false
false
maxbritto/cours-ios11-swift4
swift_4_cours_complet.playground/Pages/Tableaux.xcplaygroundpage/Contents.swift
1
403
//: [< Sommaire](Sommaire) /*: # Tableaux --- ### Maxime Britto - Swift 4 */ let note1 = 10.5 let note2 = 17.0 let note3 = 14.0 let moyenne = (note1 + note2 + note3) / 3 var listeNotes:[Double] = [10.5, 17.0, 14.0, 15.0] print("Voici votre première note : \(listeNotes[3])") listeNotes.append(16.0) listeNotes[4] = 17.0 listeNotes listeNotes.count //: [Classes et objets >](@next)
apache-2.0
98d77e975edc59f51a402487c70c6b41
10.823529
53
0.614428
2.45122
false
false
false
false
laurentVeliscek/AudioKit
AudioKit/Common/Nodes/Analysis/Amplitude Tracker/AKAmplitudeTracker.swift
1
3557
// // AKAmplitudeTracker.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright (c) 2016 Aurelius Prochazka. All rights reserved. // import AVFoundation /// Performs a "root-mean-square" on a signal to get overall amplitude of a /// signal. The output signal looks similar to that of a classic VU meter. /// /// - Parameters: /// - input: Input node to process /// - halfPowerPoint: Half-power point (in Hz) of internal lowpass filter. /// public class AKAmplitudeTracker: AKNode, AKToggleable { // MARK: - Properties internal var internalAU: AKAmplitudeTrackerAudioUnit? internal var token: AUParameterObserverToken? private var halfPowerPointParameter: AUParameter? /// Half-power point (in Hz) of internal lowpass filter. public var halfPowerPoint: Double = 10 { willSet { if halfPowerPoint != newValue { halfPowerPointParameter?.setValue(Float(newValue), originator: token!) } } } /// Tells whether the node is processing (ie. started, playing, or active) public var isStarted: Bool { return internalAU!.isPlaying() } /// Detected amplitude public var amplitude: Double { return Double(self.internalAU!.getAmplitude()) / sqrt(2.0) * 2.0 } // MARK: - Initialization /// Initialize this amplitude tracker node /// /// - Parameters: /// - input: Input node to process /// - halfPowerPoint: Half-power point (in Hz) of internal lowpass filter. /// public init( _ input: AKNode, halfPowerPoint: Double = 10) { self.halfPowerPoint = halfPowerPoint var description = AudioComponentDescription() description.componentType = kAudioUnitType_Effect description.componentSubType = 0x726d7371 /*'rmsq'*/ description.componentManufacturer = 0x41754b74 /*'AuKt'*/ description.componentFlags = 0 description.componentFlagsMask = 0 AUAudioUnit.registerSubclass( AKAmplitudeTrackerAudioUnit.self, asComponentDescription: description, name: "Local AKAmplitudeTracker", version: UInt32.max) super.init() AVAudioUnit.instantiateWithComponentDescription(description, options: []) { avAudioUnit, error in guard let avAudioUnitEffect = avAudioUnit else { return } self.avAudioNode = avAudioUnitEffect self.internalAU = avAudioUnitEffect.AUAudioUnit as? AKAmplitudeTrackerAudioUnit AudioKit.engine.attachNode(self.avAudioNode) input.addConnectionPoint(self) } guard let tree = internalAU?.parameterTree else { return } halfPowerPointParameter = tree.valueForKey("halfPowerPoint") as? AUParameter token = tree.tokenByAddingParameterObserver { address, value in dispatch_async(dispatch_get_main_queue()) { if address == self.halfPowerPointParameter!.address { self.halfPowerPoint = Double(value) } } } halfPowerPointParameter?.setValue(Float(halfPowerPoint), originator: token!) } // MARK: - Control /// Function to start, play, or activate the node, all do the same thing public func start() { internalAU!.start() } /// Function to stop or bypass the node, both are equivalent public func stop() { internalAU!.stop() } }
mit
314848c8f0ccf5d2abd682c85ae0b1a4
29.930435
91
0.638741
5.1033
false
false
false
false
crescentflare/UniLayout
UniLayoutIOS/Example/Tests/Utility/LayoutBuilder.swift
1
3804
// // LayoutBuilder.swift // Provides an easy structure for manually creating layouts // import UIKit @testable import UniLayout class LayoutBuilder { // -- // MARK: Members // -- private var view: UIView // -- // MARK: Initialization // -- private init(view: UIView) { self.view = view } class func start(forViewController: TestViewController, _ build: (_ builder: LayoutBuilder) -> Void) { let builder = LayoutBuilder(view: forViewController.view) build(builder) } // -- // MARK: Add view components // -- func addLabel(text: String) { // Create label let previousView = view.subviews.last let label = TestLabelView() label.text = text label.accessibilityIdentifier = text label.translatesAutoresizingMaskIntoConstraints = false view.addSubview(label) // Add constraints var allConstraints = [NSLayoutConstraint]() if let leftView = previousView { let views = ["leftView": leftView, "label": label] allConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:[leftView]-[label]", options: [], metrics: nil, views: views) allConstraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|-[label]", options: [], metrics: nil, views: views) } else { let views = ["label": label] allConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|-[label]", options: [], metrics: nil, views: views) allConstraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|-[label]", options: [], metrics: nil, views: views) } NSLayoutConstraint.activate(allConstraints) } func addContainer(color: UIColor = .clear, name: String? = nil, _ build: (_ builder: LayoutBuilder) -> Void) { // Create container let previousView = view.subviews.last let container = TestContainerView() container.backgroundColor = color container.accessibilityIdentifier = name container.translatesAutoresizingMaskIntoConstraints = false view.addSubview(container) // Add constraints var allConstraints = [NSLayoutConstraint]() if let aboveView = previousView { let views = ["aboveView": aboveView, "container": container] allConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|-[container]", options: [], metrics: nil, views: views) allConstraints += NSLayoutConstraint.constraints(withVisualFormat: "V:[aboveView]-[container]", options: [], metrics: nil, views: views) } else { let views = ["container": container] allConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|-[container]", options: [], metrics: nil, views: views) allConstraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|-[container]", options: [], metrics: nil, views: views) } NSLayoutConstraint.activate(allConstraints) // Build layout inside container build(LayoutBuilder(view: container)) // Add constraints for adjusting size to contain children if let lastView = container.subviews.last { let views = ["lastView": lastView] var closingConstraints = [NSLayoutConstraint]() closingConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:[lastView]-|", options: [], metrics: nil, views: views) closingConstraints += NSLayoutConstraint.constraints(withVisualFormat: "V:[lastView]-|", options: [], metrics: nil, views: views) NSLayoutConstraint.activate(closingConstraints) } } }
mit
5d46126322a248c67861bdf412992ebd
39.468085
148
0.637224
5.268698
false
false
false
false
mozilla-mobile/firefox-ios
WidgetKit/TopSites/WidgetKitTopSiteModel.swift
2
1271
// 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 struct WidgetKitTopSiteModel: Codable { var title: String var faviconUrl: String var url: URL var imageKey: String static let userDefaults = UserDefaults(suiteName: AppInfo.sharedContainerIdentifier)! static func save(widgetKitTopSites: [WidgetKitTopSiteModel]) { userDefaults.removeObject(forKey: PrefsKeys.WidgetKitSimpleTopTab) let encoder = JSONEncoder() if let encoded = try? encoder.encode(widgetKitTopSites) { userDefaults.set(encoded, forKey: PrefsKeys.WidgetKitSimpleTopTab) } } static func get() -> [WidgetKitTopSiteModel] { if let topSites = userDefaults.object(forKey: PrefsKeys.WidgetKitSimpleTopTab) as? Data { do { let jsonDecoder = JSONDecoder() let sites = try jsonDecoder.decode([WidgetKitTopSiteModel].self, from: topSites) return sites } catch { print("Error occured") } } return [WidgetKitTopSiteModel]() } }
mpl-2.0
292fd3649aa1402ea4b6b09ffb431482
34.305556
97
0.656963
4.638686
false
false
false
false
bitjammer/swift
test/SILGen/objc_bridging_any.swift
1
42255
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-silgen %s | %FileCheck %s // REQUIRES: objc_interop import Foundation import objc_generics protocol P {} protocol CP: class {} struct KnownUnbridged {} // CHECK-LABEL: sil hidden @_T017objc_bridging_any11passingToId{{.*}}F func passingToId<T: CP, U>(receiver: NSIdLover, string: String, nsString: NSString, object: AnyObject, classGeneric: T, classExistential: CP, generic: U, existential: P, error: Error, any: Any, knownUnbridged: KnownUnbridged, optionalA: String?, optionalB: NSString?, optionalC: Any?) { // CHECK: bb0([[SELF:%.*]] : $NSIdLover, // CHECK: debug_value [[STRING:%.*]] : $String // CHECK: debug_value [[NSSTRING:%.*]] : $NSString // CHECK: debug_value [[OBJECT:%.*]] : $AnyObject // CHECK: debug_value [[CLASS_GENERIC:%.*]] : $T // CHECK: debug_value [[CLASS_EXISTENTIAL:%.*]] : $CP // CHECK: debug_value_addr [[GENERIC:%.*]] : $*U // CHECK: debug_value_addr [[EXISTENTIAL:%.*]] : $*P // CHECK: debug_value [[ERROR:%.*]] : $Error // CHECK: debug_value_addr [[ANY:%.*]] : $*Any // CHECK: debug_value [[KNOWN_UNBRIDGED:%.*]] : $KnownUnbridged // CHECK: debug_value [[OPT_STRING:%.*]] : $Optional<String> // CHECK: debug_value [[OPT_NSSTRING:%.*]] : $Optional<NSString> // CHECK: debug_value_addr [[OPT_ANY:%.*]] : $*Optional<Any> // CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] // CHECK: [[BORROWED_STRING:%.*]] = begin_borrow [[STRING]] // CHECK: [[STRING_COPY:%.*]] = copy_value [[BORROWED_STRING]] // CHECK: [[BRIDGE_STRING:%.*]] = function_ref @_T0SS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF // CHECK: [[BORROWED_STRING_COPY:%.*]] = begin_borrow [[STRING_COPY]] // CHECK: [[BRIDGED:%.*]] = apply [[BRIDGE_STRING]]([[BORROWED_STRING_COPY]]) // CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[BRIDGED]] : $NSString : $NSString, $AnyObject // CHECK: end_borrow [[BORROWED_STRING_COPY]] from [[STRING_COPY]] // CHECK: destroy_value [[STRING_COPY]] // CHECK: end_borrow [[BORROWED_STRING]] from [[STRING]] // CHECK: apply [[METHOD]]([[ANYOBJECT]], [[BORROWED_SELF]]) // CHECK: destroy_value [[ANYOBJECT]] // CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]] receiver.takesId(string) // CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $NSIdLover, // CHECK: [[BORROWED_NSSTRING:%.*]] = begin_borrow [[NSSTRING]] // CHECK: [[NSSTRING_COPY:%.*]] = copy_value [[BORROWED_NSSTRING]] // CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[NSSTRING_COPY]] : $NSString : $NSString, $AnyObject // CHECK: end_borrow [[BORROWED_NSSTRING]] from [[NSSTRING]] // CHECK: apply [[METHOD]]([[ANYOBJECT]], [[BORROWED_SELF]]) // CHECK: destroy_value [[ANYOBJECT]] // CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]] receiver.takesId(nsString) // CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $NSIdLover, // CHECK: [[BORROWED_CLASS_GENERIC:%.*]] = begin_borrow [[CLASS_GENERIC]] // CHECK: [[CLASS_GENERIC_COPY:%.*]] = copy_value [[BORROWED_CLASS_GENERIC]] // CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[CLASS_GENERIC_COPY]] : $T : $T, $AnyObject // CHECK: end_borrow [[BORROWED_CLASS_GENERIC]] from [[CLASS_GENERIC]] // CHECK: apply [[METHOD]]([[ANYOBJECT]], [[BORROWED_SELF]]) // CHECK: destroy_value [[ANYOBJECT]] // CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]] receiver.takesId(classGeneric) // CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $NSIdLover, // CHECK: [[BORROWED_OBJECT:%.*]] = begin_borrow [[OBJECT]] // CHECK: [[OBJECT_COPY:%.*]] = copy_value [[BORROWED_OBJECT]] // CHECK: end_borrow [[BORROWED_OBJECT]] from [[OBJECT]] // CHECK: apply [[METHOD]]([[OBJECT_COPY]], [[BORROWED_SELF]]) // CHECK: destroy_value [[OBJECT_COPY]] // CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]] receiver.takesId(object) // CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $NSIdLover, // CHECK: [[BORROWED_CLASS_EXISTENTIAL:%.*]] = begin_borrow [[CLASS_EXISTENTIAL]] // CHECK: [[CLASS_EXISTENTIAL_COPY:%.*]] = copy_value [[BORROWED_CLASS_EXISTENTIAL]] // CHECK: [[OPENED:%.*]] = open_existential_ref [[CLASS_EXISTENTIAL_COPY]] : $CP // CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[OPENED]] // CHECK: end_borrow [[BORROWED_CLASS_EXISTENTIAL]] from [[CLASS_EXISTENTIAL]] // CHECK: apply [[METHOD]]([[ANYOBJECT]], [[BORROWED_SELF]]) // CHECK: destroy_value [[ANYOBJECT]] // CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]] receiver.takesId(classExistential) // These cases perform a universal bridging conversion. // CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $NSIdLover, // CHECK: [[COPY:%.*]] = alloc_stack $U // CHECK: copy_addr [[GENERIC]] to [initialization] [[COPY]] // CHECK: // function_ref _bridgeAnythingToObjectiveC // CHECK: [[BRIDGE_ANYTHING:%.*]] = function_ref // CHECK: [[ANYOBJECT:%.*]] = apply [[BRIDGE_ANYTHING]]<U>([[COPY]]) // CHECK: dealloc_stack [[COPY]] // CHECK: apply [[METHOD]]([[ANYOBJECT]], [[BORROWED_SELF]]) // CHECK: destroy_value [[ANYOBJECT]] // CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]] receiver.takesId(generic) // CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $NSIdLover, // CHECK: [[COPY:%.*]] = alloc_stack $P // CHECK: copy_addr [[EXISTENTIAL]] to [initialization] [[COPY]] // CHECK: [[OPENED_COPY:%.*]] = open_existential_addr immutable_access [[COPY]] : $*P to $*[[OPENED_TYPE:@opened.*P]], // CHECK: // function_ref _bridgeAnythingToObjectiveC // CHECK: [[BRIDGE_ANYTHING:%.*]] = function_ref // CHECK: [[ANYOBJECT:%.*]] = apply [[BRIDGE_ANYTHING]]<[[OPENED_TYPE]]>([[OPENED_COPY]]) // CHECK: deinit_existential_addr [[COPY]] // CHECK: dealloc_stack [[COPY]] // CHECK: apply [[METHOD]]([[ANYOBJECT]], [[BORROWED_SELF]]) // CHECK: destroy_value [[ANYOBJECT]] // CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]] receiver.takesId(existential) // CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $NSIdLover, // CHECK: [[BORROWED_ERROR:%.*]] = begin_borrow [[ERROR]] // CHECK: [[ERROR_COPY:%.*]] = copy_value [[BORROWED_ERROR]] : $Error // CHECK: [[ERROR_BOX:%[0-9]+]] = open_existential_box [[ERROR_COPY]] : $Error to $*@opened([[ERROR_ARCHETYPE:"[^"]*"]]) Error // CHECK: [[ERROR_STACK:%[0-9]+]] = alloc_stack $@opened([[ERROR_ARCHETYPE]]) Error // CHECK: copy_addr [[ERROR_BOX]] to [initialization] [[ERROR_STACK]] : $*@opened([[ERROR_ARCHETYPE]]) Error // CHECK: [[BRIDGE_FUNCTION:%[0-9]+]] = function_ref @_T0s27_bridgeAnythingToObjectiveCs9AnyObject_pxlF // CHECK: [[BRIDGED_ERROR:%[0-9]+]] = apply [[BRIDGE_FUNCTION]]<@opened([[ERROR_ARCHETYPE]]) Error>([[ERROR_STACK]]) // CHECK: dealloc_stack [[ERROR_STACK]] : $*@opened([[ERROR_ARCHETYPE]]) Error // CHECK: destroy_value [[ERROR_COPY]] : $Error // CHECK: end_borrow [[BORROWED_ERROR]] from [[ERROR]] // CHECK: apply [[METHOD]]([[BRIDGED_ERROR]], [[BORROWED_SELF]]) // CHECK: destroy_value [[BRIDGED_ERROR]] : $AnyObject // CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]] receiver.takesId(error) // CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $NSIdLover, // CHECK: [[COPY:%.*]] = alloc_stack $Any // CHECK: copy_addr [[ANY]] to [initialization] [[COPY]] // CHECK: [[OPENED_COPY:%.*]] = open_existential_addr immutable_access [[COPY]] : $*Any to $*[[OPENED_TYPE:@opened.*Any]], // CHECK: // function_ref _bridgeAnythingToObjectiveC // CHECK: [[BRIDGE_ANYTHING:%.*]] = function_ref // CHECK: [[ANYOBJECT:%.*]] = apply [[BRIDGE_ANYTHING]]<[[OPENED_TYPE]]>([[OPENED_COPY]]) // CHECK: deinit_existential_addr [[COPY]] // CHECK: dealloc_stack [[COPY]] // CHECK: apply [[METHOD]]([[ANYOBJECT]], [[BORROWED_SELF]]) // CHECK: destroy_value [[ANYOBJECT]] // CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]] receiver.takesId(any) // CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $NSIdLover, // CHECK: [[TMP:%.*]] = alloc_stack $KnownUnbridged // CHECK: store [[KNOWN_UNBRIDGED]] to [trivial] [[TMP]] // CHECK: [[BRIDGE_ANYTHING:%.*]] = function_ref @_T0s27_bridgeAnythingToObjectiveC{{.*}}F // CHECK: [[ANYOBJECT:%.*]] = apply [[BRIDGE_ANYTHING]]<KnownUnbridged>([[TMP]]) // CHECK: apply [[METHOD]]([[ANYOBJECT]], [[BORROWED_SELF]]) // CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]] receiver.takesId(knownUnbridged) // These cases bridge using Optional's _ObjectiveCBridgeable conformance. // CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $NSIdLover, // CHECK: [[BORROWED_OPT_STRING:%.*]] = begin_borrow [[OPT_STRING]] // CHECK: [[OPT_STRING_COPY:%.*]] = copy_value [[BORROWED_OPT_STRING]] // CHECK: [[BRIDGE_OPTIONAL:%.*]] = function_ref @_T0Sq19_bridgeToObjectiveCs9AnyObject_pyF // CHECK: [[TMP:%.*]] = alloc_stack $Optional<String> // CHECK: store [[OPT_STRING_COPY]] to [init] [[TMP]] // CHECK: [[ANYOBJECT:%.*]] = apply [[BRIDGE_OPTIONAL]]<String>([[TMP]]) // CHECK: end_borrow [[BORROWED_OPT_STRING]] from [[OPT_STRING]] // CHECK: apply [[METHOD]]([[ANYOBJECT]], [[BORROWED_SELF]]) // CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]] receiver.takesId(optionalA) // CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $NSIdLover, // CHECK: [[BORROWED_OPT_NSSTRING:%.*]] = begin_borrow [[OPT_NSSTRING]] // CHECK: [[OPT_NSSTRING_COPY:%.*]] = copy_value [[BORROWED_OPT_NSSTRING]] // CHECK: [[BRIDGE_OPTIONAL:%.*]] = function_ref @_T0Sq19_bridgeToObjectiveCs9AnyObject_pyF // CHECK: [[TMP:%.*]] = alloc_stack $Optional<NSString> // CHECK: store [[OPT_NSSTRING_COPY]] to [init] [[TMP]] // CHECK: [[ANYOBJECT:%.*]] = apply [[BRIDGE_OPTIONAL]]<NSString>([[TMP]]) // CHECK: end_borrow [[BORROWED_OPT_NSSTRING]] from [[OPT_NSSTRING]] // CHECK: apply [[METHOD]]([[ANYOBJECT]], [[BORROWED_SELF]]) // CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]] receiver.takesId(optionalB) // CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $NSIdLover, // CHECK: [[TMP:%.*]] = alloc_stack $Optional<Any> // CHECK: copy_addr [[OPT_ANY]] to [initialization] [[TMP]] // CHECK: [[BRIDGE_OPTIONAL:%.*]] = function_ref @_T0Sq19_bridgeToObjectiveCs9AnyObject_pyF // CHECK: [[ANYOBJECT:%.*]] = apply [[BRIDGE_OPTIONAL]]<Any>([[TMP]]) // CHECK: apply [[METHOD]]([[ANYOBJECT]], [[BORROWED_SELF]]) // CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]] receiver.takesId(optionalC) // TODO: Property and subscript setters } // Workaround for rdar://problem/28318984. Skip the peephole for types with // nontrivial SIL lowerings because we don't correctly form the substitutions // for a generic _bridgeAnythingToObjectiveC call. func zim() {} struct Zang {} // CHECK-LABEL: sil hidden @_T017objc_bridging_any27typesWithNontrivialLoweringySo9NSIdLoverC8receiver_tF func typesWithNontrivialLowering(receiver: NSIdLover) { // CHECK: init_existential_addr {{%.*}} : $*Any, $() -> () receiver.takesId(zim) // CHECK: init_existential_addr {{%.*}} : $*Any, $Zang.Type receiver.takesId(Zang.self) // CHECK: init_existential_addr {{%.*}} : $*Any, $(() -> (), Zang.Type) receiver.takesId((zim, Zang.self)) // CHECK: apply {{%.*}}<(Int, String)> receiver.takesId((0, "one")) } // CHECK-LABEL: sil hidden @_T017objc_bridging_any19passingToNullableId{{.*}}F func passingToNullableId<T: CP, U>(receiver: NSIdLover, string: String, nsString: NSString, object: AnyObject, classGeneric: T, classExistential: CP, generic: U, existential: P, error: Error, any: Any, knownUnbridged: KnownUnbridged, optString: String?, optNSString: NSString?, optObject: AnyObject?, optClassGeneric: T?, optClassExistential: CP?, optGeneric: U?, optExistential: P?, optAny: Any?, optKnownUnbridged: KnownUnbridged?, optOptA: String??, optOptB: NSString??, optOptC: Any??) { // CHECK: bb0([[SELF:%.*]] : $NSIdLover, // CHECK: [[STRING:%.*]] : $String, // CHECK: [[NSSTRING:%.*]] : $NSString // CHECK: [[OBJECT:%.*]] : $AnyObject // CHECK: [[CLASS_GENERIC:%.*]] : $T // CHECK: [[CLASS_EXISTENTIAL:%.*]] : $CP // CHECK: [[GENERIC:%.*]] : $*U // CHECK: [[EXISTENTIAL:%.*]] : $*P // CHECK: [[ERROR:%.*]] : $Error // CHECK: [[ANY:%.*]] : $*Any, // CHECK: [[KNOWN_UNBRIDGED:%.*]] : $KnownUnbridged, // CHECK: [[OPT_STRING:%.*]] : $Optional<String>, // CHECK: [[OPT_NSSTRING:%.*]] : $Optional<NSString> // CHECK: [[OPT_OBJECT:%.*]] : $Optional<AnyObject> // CHECK: [[OPT_CLASS_GENERIC:%.*]] : $Optional<T> // CHECK: [[OPT_CLASS_EXISTENTIAL:%.*]] : $Optional<CP> // CHECK: [[OPT_GENERIC:%.*]] : $*Optional<U> // CHECK: [[OPT_EXISTENTIAL:%.*]] : $*Optional<P> // CHECK: [[OPT_ANY:%.*]] : $*Optional<Any> // CHECK: [[OPT_KNOWN_UNBRIDGED:%.*]] : $Optional<KnownUnbridged> // CHECK: [[OPT_OPT_A:%.*]] : $Optional<Optional<String>> // CHECK: [[OPT_OPT_B:%.*]] : $Optional<Optional<NSString>> // CHECK: [[OPT_OPT_C:%.*]] : $*Optional<Optional<Any>> // CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] // CHECK: [[BORROWED_STRING:%.*]] = begin_borrow [[STRING]] // CHECK: [[STRING_COPY:%.*]] = copy_value [[BORROWED_STRING]] // CHECK: [[BRIDGE_STRING:%.*]] = function_ref @_T0SS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF // CHECK: [[BORROWED_STRING_COPY:%.*]] = begin_borrow [[STRING_COPY]] // CHECK: [[BRIDGED:%.*]] = apply [[BRIDGE_STRING]]([[BORROWED_STRING_COPY]]) // CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[BRIDGED]] : $NSString : $NSString, $AnyObject // CHECK: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[ANYOBJECT]] // CHECK: end_borrow [[BORROWED_STRING_COPY]] from [[STRING_COPY]] // CHECK: destroy_value [[STRING_COPY]] // CHECK: apply [[METHOD]]([[OPT_ANYOBJECT]], [[BORROWED_SELF]]) // CHECK: destroy_value [[OPT_ANYOBJECT]] // CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]] receiver.takesNullableId(string) // CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $NSIdLover, // CHECK: [[BORROWED_NSSTRING:%.*]] = begin_borrow [[NSSTRING]] // CHECK: [[NSSTRING_COPY:%.*]] = copy_value [[BORROWED_NSSTRING]] // CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[NSSTRING_COPY]] : $NSString : $NSString, $AnyObject // CHECK: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[ANYOBJECT]] // CHECK: end_borrow [[BORROWED_NSSTRING]] from [[NSSTRING]] // CHECK: apply [[METHOD]]([[OPT_ANYOBJECT]], [[BORROWED_SELF]]) // CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]] receiver.takesNullableId(nsString) // CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $NSIdLover, // CHECK: [[BORROWED_OBJECT:%.*]] = begin_borrow [[OBJECT]] // CHECK: [[OBJECT_COPY:%.*]] = copy_value [[BORROWED_OBJECT]] // CHECK: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[OBJECT_COPY]] // CHECK: end_borrow [[BORROWED_OBJECT]] from [[OBJECT]] // CHECK: apply [[METHOD]]([[OPT_ANYOBJECT]], [[BORROWED_SELF]]) // CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]] receiver.takesNullableId(object) // CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $NSIdLover, // CHECK: [[BORROWED_CLASS_GENERIC:%.*]] = begin_borrow [[CLASS_GENERIC]] // CHECK: [[CLASS_GENERIC_COPY:%.*]] = copy_value [[BORROWED_CLASS_GENERIC]] // CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[CLASS_GENERIC_COPY]] : $T : $T, $AnyObject // CHECK: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[ANYOBJECT]] // CHECK: end_borrow [[BORROWED_CLASS_GENERIC]] from [[CLASS_GENERIC]] // CHECK: apply [[METHOD]]([[OPT_ANYOBJECT]], [[BORROWED_SELF]]) // CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]] receiver.takesNullableId(classGeneric) // CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $NSIdLover, // CHECK: [[BORROWED_CLASS_EXISTENTIAL:%.*]] = begin_borrow [[CLASS_EXISTENTIAL]] // CHECK: [[CLASS_EXISTENTIAL_COPY:%.*]] = copy_value [[BORROWED_CLASS_EXISTENTIAL]] // CHECK: [[OPENED:%.*]] = open_existential_ref [[CLASS_EXISTENTIAL_COPY]] : $CP // CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[OPENED]] // CHECK: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[ANYOBJECT]] // CHECK: end_borrow [[BORROWED_CLASS_EXISTENTIAL]] from [[CLASS_EXISTENTIAL]] // CHECK: apply [[METHOD]]([[OPT_ANYOBJECT]], [[BORROWED_SELF]]) // CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]] receiver.takesNullableId(classExistential) // CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $NSIdLover, // CHECK-NEXT: [[COPY:%.*]] = alloc_stack $U // CHECK-NEXT: copy_addr [[GENERIC]] to [initialization] [[COPY]] // CHECK-NEXT: // function_ref _bridgeAnythingToObjectiveC // CHECK-NEXT: [[BRIDGE_ANYTHING:%.*]] = function_ref // CHECK-NEXT: [[ANYOBJECT:%.*]] = apply [[BRIDGE_ANYTHING]]<U>([[COPY]]) // CHECK-NEXT: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[ANYOBJECT]] // CHECK-NEXT: dealloc_stack [[COPY]] // CHECK-NEXT: apply [[METHOD]]([[OPT_ANYOBJECT]], [[BORROWED_SELF]]) // CHECK-NEXT: destroy_value [[OPT_ANYOBJECT]] // CHECK-NEXT: end_borrow [[BORROWED_SELF]] from [[SELF]] receiver.takesNullableId(generic) // CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $NSIdLover, // CHECK-NEXT: [[COPY:%.*]] = alloc_stack $P // CHECK-NEXT: copy_addr [[EXISTENTIAL]] to [initialization] [[COPY]] // CHECK-NEXT: [[OPENED_COPY:%.*]] = open_existential_addr immutable_access [[COPY]] : $*P to $*[[OPENED_TYPE:@opened.*P]], // CHECK-NEXT: // function_ref _bridgeAnythingToObjectiveC // CHECK-NEXT: [[BRIDGE_ANYTHING:%.*]] = function_ref // CHECK-NEXT: [[ANYOBJECT:%.*]] = apply [[BRIDGE_ANYTHING]]<[[OPENED_TYPE]]>([[OPENED_COPY]]) // CHECK-NEXT: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[ANYOBJECT]] // CHECK-NEXT: deinit_existential_addr [[COPY]] // CHECK-NEXT: dealloc_stack [[COPY]] // CHECK-NEXT: apply [[METHOD]]([[OPT_ANYOBJECT]], [[BORROWED_SELF]]) // CHECK-NEXT: destroy_value [[OPT_ANYOBJECT]] // CHECK-NEXT: end_borrow [[BORROWED_SELF]] from [[SELF]] receiver.takesNullableId(existential) // CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $NSIdLover, // CHECK: [[BORROWED_ERROR:%.*]] = begin_borrow [[ERROR]] // CHECK-NEXT: [[ERROR_COPY:%.*]] = copy_value [[BORROWED_ERROR]] : $Error // CHECK-NEXT: [[ERROR_BOX:%[0-9]+]] = open_existential_box [[ERROR_COPY]] : $Error to $*@opened([[ERROR_ARCHETYPE:"[^"]*"]]) Error // CHECK-NEXT: [[ERROR_STACK:%[0-9]+]] = alloc_stack $@opened([[ERROR_ARCHETYPE]]) Error // CHECK-NEXT: copy_addr [[ERROR_BOX]] to [initialization] [[ERROR_STACK]] : $*@opened([[ERROR_ARCHETYPE]]) Error // CHECK: [[BRIDGE_FUNCTION:%[0-9]+]] = function_ref @_T0s27_bridgeAnythingToObjectiveCs9AnyObject_pxlF // CHECK-NEXT: [[BRIDGED_ERROR:%[0-9]+]] = apply [[BRIDGE_FUNCTION]]<@opened([[ERROR_ARCHETYPE]]) Error>([[ERROR_STACK]]) // CHECK-NEXT: [[BRIDGED_ERROR_OPT:%[0-9]+]] = enum $Optional<AnyObject>, #Optional.some!enumelt.1, [[BRIDGED_ERROR]] : $AnyObject // CHECK-NEXT: dealloc_stack [[ERROR_STACK]] : $*@opened([[ERROR_ARCHETYPE]]) Error // CHECK-NEXT: destroy_value [[ERROR_COPY]] : $Error // CHECK-NEXT: end_borrow [[BORROWED_ERROR]] from [[ERROR]] // CHECK-NEXT: apply [[METHOD]]([[BRIDGED_ERROR_OPT]], [[BORROWED_SELF]]) // CHECK-NEXT: destroy_value [[BRIDGED_ERROR_OPT]] // CHECK-NEXT: end_borrow [[BORROWED_SELF]] from [[SELF]] receiver.takesNullableId(error) // CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $NSIdLover, // CHECK-NEXT: [[COPY:%.*]] = alloc_stack $Any // CHECK-NEXT: copy_addr [[ANY]] to [initialization] [[COPY]] // CHECK-NEXT: [[OPENED_COPY:%.*]] = open_existential_addr immutable_access [[COPY]] : $*Any to $*[[OPENED_TYPE:@opened.*Any]], // CHECK-NEXT: // function_ref _bridgeAnythingToObjectiveC // CHECK-NEXT: [[BRIDGE_ANYTHING:%.*]] = function_ref // CHECK-NEXT: [[ANYOBJECT:%.*]] = apply [[BRIDGE_ANYTHING]]<[[OPENED_TYPE]]>([[OPENED_COPY]]) // CHECK-NEXT: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[ANYOBJECT]] // CHECK-NEXT: deinit_existential_addr [[COPY]] // CHECK-NEXT: dealloc_stack [[COPY]] // CHECK-NEXT: apply [[METHOD]]([[OPT_ANYOBJECT]], [[BORROWED_SELF]]) // CHECK-NEXT: destroy_value [[OPT_ANYOBJECT]] // CHECK-NEXT: end_borrow [[BORROWED_SELF]] from [[SELF]] receiver.takesNullableId(any) // CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] : $NSIdLover, // CHECK: [[TMP:%.*]] = alloc_stack $KnownUnbridged // CHECK: store [[KNOWN_UNBRIDGED]] to [trivial] [[TMP]] // CHECK: [[BRIDGE_ANYTHING:%.*]] = function_ref @_T0s27_bridgeAnythingToObjectiveC{{.*}}F // CHECK: [[ANYOBJECT:%.*]] = apply [[BRIDGE_ANYTHING]]<KnownUnbridged>([[TMP]]) // CHECK: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[ANYOBJECT]] // CHECK: apply [[METHOD]]([[OPT_ANYOBJECT]], [[BORROWED_SELF]]) // CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]] receiver.takesNullableId(knownUnbridged) // CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] // CHECK: [[BORROWED_OPT_STRING:%.*]] = begin_borrow [[OPT_STRING]] // CHECK: [[OPT_STRING_COPY:%.*]] = copy_value [[BORROWED_OPT_STRING]] // CHECK: switch_enum [[OPT_STRING_COPY]] : $Optional<String>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // // CHECK: [[SOME_BB]]([[STRING_DATA:%.*]] : $String): // CHECK: [[BRIDGE_STRING:%.*]] = function_ref @_T0SS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF // CHECK: [[BORROWED_STRING_DATA:%.*]] = begin_borrow [[STRING_DATA]] // CHECK: [[BRIDGED:%.*]] = apply [[BRIDGE_STRING]]([[BORROWED_STRING_DATA]]) // CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[BRIDGED]] : $NSString : $NSString, $AnyObject // CHECK: [[OPT_ANYOBJECT:%.*]] = enum {{.*}} [[ANYOBJECT]] // CHECK: end_borrow [[BORROWED_STRING_DATA]] from [[STRING_DATA]] // CHECK: destroy_value [[STRING_DATA]] // CHECK: br [[JOIN:bb.*]]([[OPT_ANYOBJECT]] // // CHECK: [[NONE_BB]]: // CHECK: [[OPT_NONE:%.*]] = enum $Optional<AnyObject>, #Optional.none!enumelt // CHECK: br [[JOIN]]([[OPT_NONE]] // // CHECK: [[JOIN]]([[PHI:%.*]] : $Optional<AnyObject>): // CHECK: end_borrow [[BORROWED_OPT_STRING]] from [[OPT_STRING]] // CHECK: apply [[METHOD]]([[PHI]], [[BORROWED_SELF]]) // CHECK: destroy_value [[PHI]] // CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]] receiver.takesNullableId(optString) // CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] receiver.takesNullableId(optNSString) // CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK: [[METHOD:%.*]] = class_method [volatile] [[BORROWED_SELF]] // CHECK: [[BORROWED_OPT_OBJECT:%.*]] = begin_borrow [[OPT_OBJECT]] // CHECK: [[OPT_OBJECT_COPY:%.*]] = copy_value [[BORROWED_OPT_OBJECT]] // CHECK: apply [[METHOD]]([[OPT_OBJECT_COPY]], [[BORROWED_SELF]]) receiver.takesNullableId(optObject) receiver.takesNullableId(optClassGeneric) receiver.takesNullableId(optClassExistential) receiver.takesNullableId(optGeneric) receiver.takesNullableId(optExistential) receiver.takesNullableId(optAny) receiver.takesNullableId(optKnownUnbridged) receiver.takesNullableId(optOptA) receiver.takesNullableId(optOptB) receiver.takesNullableId(optOptC) } protocol Anyable { init(any: Any) init(anyMaybe: Any?) var anyProperty: Any { get } var maybeAnyProperty: Any? { get } } // Make sure we generate correct bridging thunks class SwiftIdLover : NSObject, Anyable { func methodReturningAny() -> Any {} // SEMANTIC ARC TODO: This is another case of pattern matching the body of one // function in a different function... Just pattern match the unreachable case // to preserve behavior. We should check if it is correct. // CHECK-LABEL: sil hidden @_T017objc_bridging_any12SwiftIdLoverC18methodReturningAnyypyF : $@convention(method) (@guaranteed SwiftIdLover) -> @out Any // CHECK: unreachable // CHECK: } // end sil function '_T017objc_bridging_any12SwiftIdLoverC18methodReturningAnyypyF' // CHECK-LABEL: sil hidden [thunk] @_T017objc_bridging_any12SwiftIdLoverC18methodReturningAnyypyFTo : $@convention(objc_method) (SwiftIdLover) -> @autoreleased AnyObject { // CHECK: bb0([[SELF:%[0-9]+]] : $SwiftIdLover): // CHECK: [[NATIVE_RESULT:%.*]] = alloc_stack $Any // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $SwiftIdLover // CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK: [[NATIVE_IMP:%.*]] = function_ref @_T017objc_bridging_any12SwiftIdLoverC18methodReturningAnyypyF // CHECK: apply [[NATIVE_IMP]]([[NATIVE_RESULT]], [[BORROWED_SELF_COPY]]) // CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK: destroy_value [[SELF_COPY]] // CHECK: [[OPEN_RESULT:%.*]] = open_existential_addr immutable_access [[NATIVE_RESULT]] // CHECK: [[BRIDGE_ANYTHING:%.*]] = function_ref @_T0s27_bridgeAnythingToObjectiveC{{.*}}F // CHECK: [[OBJC_RESULT:%.*]] = apply [[BRIDGE_ANYTHING]]<{{.*}}>([[OPEN_RESULT]]) // CHECK: return [[OBJC_RESULT]] // CHECK: } // end sil function '_T017objc_bridging_any12SwiftIdLoverC18methodReturningAnyypyFTo' func methodReturningOptionalAny() -> Any? {} // CHECK-LABEL: sil hidden @_T017objc_bridging_any12SwiftIdLoverC26methodReturningOptionalAnyypSgyF // CHECK-LABEL: sil hidden [thunk] @_T017objc_bridging_any12SwiftIdLoverC26methodReturningOptionalAnyypSgyFTo // CHECK: function_ref @_T0s27_bridgeAnythingToObjectiveC{{.*}}F func methodTakingAny(a: Any) {} // CHECK-LABEL: sil hidden [thunk] @_T017objc_bridging_any12SwiftIdLoverC15methodTakingAnyyyp1a_tFTo : $@convention(objc_method) (AnyObject, SwiftIdLover) -> () // CHECK: bb0([[ARG:%.*]] : $AnyObject, [[SELF:%.*]] : $SwiftIdLover): // CHECK-NEXT: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK-NEXT: [[OPTIONAL_ARG_COPY:%.*]] = unchecked_ref_cast [[ARG_COPY]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[BRIDGE_TO_ANY:%.*]] = function_ref [[BRIDGE_TO_ANY_FUNC:@.*]] : // CHECK-NEXT: [[RESULT:%.*]] = alloc_stack $Any // CHECK-NEXT: [[RESULT_VAL:%.*]] = apply [[BRIDGE_TO_ANY]]([[RESULT]], [[OPTIONAL_ARG_COPY]]) // CHECK-NEXT: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[METHOD:%.*]] = function_ref @_T017objc_bridging_any12SwiftIdLoverC15methodTakingAnyyyp1a_tF // CHECK-NEXT: apply [[METHOD]]([[RESULT]], [[BORROWED_SELF_COPY]]) // CHECK-NEXT: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK-NEXT: dealloc_stack [[RESULT]] // CHECK-NEXT: destroy_value [[SELF_COPY]] // CHECK-NEXT: return func methodTakingOptionalAny(a: Any?) {} // CHECK-LABEL: sil hidden @_T017objc_bridging_any12SwiftIdLoverC23methodTakingOptionalAnyyypSg1a_tF // CHECK-LABEL: sil hidden [thunk] @_T017objc_bridging_any12SwiftIdLoverC23methodTakingOptionalAnyyypSg1a_tFTo // CHECK: function_ref [[BRIDGE_TO_ANY_FUNC]] // CHECK-LABEL: sil hidden @_T017objc_bridging_any12SwiftIdLoverC017methodTakingBlockH3AnyyyypcF : $@convention(method) (@owned @callee_owned (@in Any) -> (), @guaranteed SwiftIdLover) -> () // CHECK-LABEL: sil hidden [thunk] @_T017objc_bridging_any12SwiftIdLoverC017methodTakingBlockH3AnyyyypcFTo : $@convention(objc_method) (@convention(block) (AnyObject) -> (), SwiftIdLover) -> () // CHECK: bb0([[BLOCK:%.*]] : $@convention(block) (AnyObject) -> (), [[SELF:%.*]] : $SwiftIdLover): // CHECK-NEXT: [[BLOCK_COPY:%.*]] = copy_block [[BLOCK]] // CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[THUNK_FN:%.*]] = function_ref @_T0s9AnyObject_pIyBy_ypIxi_TR // CHECK-NEXT: [[THUNK:%.*]] = partial_apply [[THUNK_FN]]([[BLOCK_COPY]]) // CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[METHOD:%.*]] = function_ref @_T017objc_bridging_any12SwiftIdLoverC017methodTakingBlockH3AnyyyypcF // CHECK-NEXT: [[RESULT:%.*]] = apply [[METHOD]]([[THUNK]], [[BORROWED_SELF_COPY]]) // CHECK-NEXT: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK-NEXT: destroy_value [[SELF_COPY]] // CHECK-NEXT: return [[RESULT]] // CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_T0s9AnyObject_pIyBy_ypIxi_TR // CHECK: bb0([[ANY:%.*]] : $*Any, [[BLOCK:%.*]] : $@convention(block) (AnyObject) -> ()): // CHECK-NEXT: [[OPENED_ANY:%.*]] = open_existential_addr immutable_access [[ANY]] : $*Any to $*[[OPENED_TYPE:@opened.*Any]], // CHECK-NEXT: // function_ref _bridgeAnythingToObjectiveC // CHECK-NEXT: [[BRIDGE_ANYTHING:%.*]] = function_ref // CHECK-NEXT: [[BRIDGED:%.*]] = apply [[BRIDGE_ANYTHING]]<[[OPENED_TYPE]]>([[OPENED_ANY]]) // CHECK-NEXT: apply [[BLOCK]]([[BRIDGED]]) // CHECK-NEXT: [[VOID:%.*]] = tuple () // CHECK-NEXT: destroy_value [[BLOCK]] // CHECK-NEXT: destroy_value [[BRIDGED]] // CHECK-NEXT: deinit_existential_addr [[ANY]] // CHECK-NEXT: return [[VOID]] func methodTakingBlockTakingAny(_: (Any) -> ()) {} // CHECK-LABEL: sil hidden @_T017objc_bridging_any12SwiftIdLoverC29methodReturningBlockTakingAnyyypcyF : $@convention(method) (@guaranteed SwiftIdLover) -> @owned @callee_owned (@in Any) -> () // CHECK-LABEL: sil hidden [thunk] @_T017objc_bridging_any12SwiftIdLoverC29methodReturningBlockTakingAnyyypcyFTo : $@convention(objc_method) (SwiftIdLover) -> @autoreleased @convention(block) (AnyObject) -> () // CHECK: bb0([[SELF:%.*]] : $SwiftIdLover): // CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK-NEXT: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[METHOD:%.*]] = function_ref @_T017objc_bridging_any12SwiftIdLoverC29methodReturningBlockTakingAnyyypcyF // CHECK-NEXT: [[RESULT:%.*]] = apply [[METHOD:%.*]]([[BORROWED_SELF_COPY]]) // CHECK-NEXT: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK-NEXT: destroy_value [[SELF_COPY]] // CHECK-NEXT: [[BLOCK_STORAGE:%.*]] = alloc_stack $@block_storage @callee_owned (@in Any) -> () // CHECK-NEXT: [[BLOCK_STORAGE_ADDR:%.*]] = project_block_storage [[BLOCK_STORAGE]] // CHECK-NEXT: store [[RESULT:%.*]] to [init] [[BLOCK_STORAGE_ADDR]] // CHECK: [[THUNK_FN:%.*]] = function_ref @_T0ypIxi_s9AnyObject_pIyBy_TR // CHECK-NEXT: [[BLOCK_HEADER:%.*]] = init_block_storage_header [[BLOCK_STORAGE]] : $*@block_storage @callee_owned (@in Any) -> (), invoke [[THUNK_FN]] // CHECK-NEXT: [[BLOCK:%.*]] = copy_block [[BLOCK_HEADER]] // CHECK-NEXT: dealloc_stack [[BLOCK_STORAGE]] // CHECK-NEXT: destroy_value [[RESULT]] // CHECK-NEXT: return [[BLOCK]] // CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_T0ypIxi_s9AnyObject_pIyBy_TR : $@convention(c) (@inout_aliasable @block_storage @callee_owned (@in Any) -> (), AnyObject) -> () // CHECK: bb0([[BLOCK_STORAGE:%.*]] : $*@block_storage @callee_owned (@in Any) -> (), [[ANY:%.*]] : $AnyObject): // CHECK-NEXT: [[BLOCK_STORAGE_ADDR:%.*]] = project_block_storage [[BLOCK_STORAGE]] // CHECK-NEXT: [[FUNCTION:%.*]] = load [copy] [[BLOCK_STORAGE_ADDR]] // CHECK-NEXT: [[ANY_COPY:%.*]] = copy_value [[ANY]] // CHECK-NEXT: [[OPTIONAL:%.*]] = unchecked_ref_cast [[ANY_COPY]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[BRIDGE_TO_ANY:%.*]] = function_ref [[BRIDGE_TO_ANY_FUNC:@.*]] : // CHECK-NEXT: [[RESULT:%.*]] = alloc_stack $Any // CHECK-NEXT: [[RESULT_VAL:%.*]] = apply [[BRIDGE_TO_ANY]]([[RESULT]], [[OPTIONAL]]) // CHECK-NEXT: apply [[FUNCTION]]([[RESULT]]) // CHECK-NEXT: [[VOID:%.*]] = tuple () // CHECK-NEXT: dealloc_stack [[RESULT]] // CHECK-NEXT: return [[VOID]] : $() func methodTakingBlockTakingOptionalAny(_: (Any?) -> ()) {} func methodReturningBlockTakingAny() -> ((Any) -> ()) {} // CHECK-LABEL: sil hidden @_T017objc_bridging_any12SwiftIdLoverC29methodTakingBlockReturningAnyyypycF : $@convention(method) (@owned @callee_owned () -> @out Any, @guaranteed SwiftIdLover) -> () { // CHECK-LABEL: sil hidden [thunk] @_T017objc_bridging_any12SwiftIdLoverC29methodTakingBlockReturningAnyyypycFTo : $@convention(objc_method) (@convention(block) () -> @autoreleased AnyObject, SwiftIdLover) -> () // CHECK: bb0([[BLOCK:%.*]] : $@convention(block) () -> @autoreleased AnyObject, [[ANY:%.*]] : $SwiftIdLover): // CHECK-NEXT: [[BLOCK_COPY:%.*]] = copy_block [[BLOCK]] // CHECK-NEXT: [[ANY_COPY:%.*]] = copy_value [[ANY]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[THUNK_FN:%.*]] = function_ref @_T0s9AnyObject_pIyBa_ypIxr_TR // CHECK-NEXT: [[THUNK:%.*]] = partial_apply [[THUNK_FN]]([[BLOCK_COPY]]) // CHECK-NEXT: [[BORROWED_ANY_COPY:%.*]] = begin_borrow [[ANY_COPY]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[METHOD:%.*]] = function_ref @_T017objc_bridging_any12SwiftIdLoverC29methodTakingBlockReturningAnyyypycF // CHECK-NEXT: [[RESULT:%.*]] = apply [[METHOD]]([[THUNK]], [[BORROWED_ANY_COPY]]) // CHECK-NEXT: end_borrow [[BORROWED_ANY_COPY]] from [[ANY_COPY]] // CHECK-NEXT: destroy_value [[ANY_COPY]] // CHECK-NEXT: return [[RESULT]] // CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_T0s9AnyObject_pIyBa_ypIxr_TR : $@convention(thin) (@owned @convention(block) () -> @autoreleased AnyObject) -> @out Any // CHECK: bb0([[ANY_ADDR:%.*]] : $*Any, [[BLOCK:%.*]] : $@convention(block) () -> @autoreleased AnyObject): // CHECK-NEXT: [[BRIDGED:%.*]] = apply [[BLOCK]]() // CHECK-NEXT: [[OPTIONAL:%.*]] = unchecked_ref_cast [[BRIDGED]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[BRIDGE_TO_ANY:%.*]] = function_ref [[BRIDGE_TO_ANY_FUNC:@.*]] : // CHECK-NEXT: [[RESULT:%.*]] = alloc_stack $Any // CHECK-NEXT: [[RESULT_VAL:%.*]] = apply [[BRIDGE_TO_ANY]]([[RESULT]], [[OPTIONAL]]) // TODO: Should elide the copy // CHECK-NEXT: copy_addr [take] [[RESULT]] to [initialization] [[ANY_ADDR]] // CHECK-NEXT: [[EMPTY:%.*]] = tuple () // CHECK-NEXT: dealloc_stack [[RESULT]] // CHECK-NEXT: destroy_value [[BLOCK]] // CHECK-NEXT: return [[EMPTY]] func methodReturningBlockTakingOptionalAny() -> ((Any?) -> ()) {} func methodTakingBlockReturningAny(_: () -> Any) {} // CHECK-LABEL: sil hidden @_T017objc_bridging_any12SwiftIdLoverC020methodReturningBlockH3AnyypycyF : $@convention(method) (@guaranteed SwiftIdLover) -> @owned @callee_owned () -> @out Any // CHECK-LABEL: sil hidden [thunk] @_T017objc_bridging_any12SwiftIdLoverC020methodReturningBlockH3AnyypycyFTo : $@convention(objc_method) (SwiftIdLover) -> @autoreleased @convention(block) () -> @autoreleased AnyObject // CHECK: bb0([[SELF:%.*]] : $SwiftIdLover): // CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK-NEXT: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[METHOD:%.*]] = function_ref @_T017objc_bridging_any12SwiftIdLoverC020methodReturningBlockH3AnyypycyF // CHECK-NEXT: [[FUNCTION:%.*]] = apply [[METHOD]]([[BORROWED_SELF_COPY]]) // CHECK-NEXT: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK-NEXT: destroy_value [[SELF_COPY]] // CHECK-NEXT: [[BLOCK_STORAGE:%.*]] = alloc_stack $@block_storage @callee_owned () -> @out Any // CHECK-NEXT: [[BLOCK_STORAGE_ADDR:%.*]] = project_block_storage [[BLOCK_STORAGE]] // CHECK-NEXT: store [[FUNCTION]] to [init] [[BLOCK_STORAGE_ADDR]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[THUNK_FN:%.*]] = function_ref @_T0ypIxr_s9AnyObject_pIyBa_TR // CHECK-NEXT: [[BLOCK_HEADER:%.*]] = init_block_storage_header [[BLOCK_STORAGE]] : $*@block_storage @callee_owned () -> @out Any, invoke [[THUNK_FN]] // CHECK-NEXT: [[BLOCK:%.*]] = copy_block [[BLOCK_HEADER]] // CHECK-NEXT: dealloc_stack [[BLOCK_STORAGE]] // CHECK-NEXT: destroy_value [[FUNCTION]] // CHECK-NEXT: return [[BLOCK]] // CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_T0ypIxr_s9AnyObject_pIyBa_TR : $@convention(c) (@inout_aliasable @block_storage @callee_owned () -> @out Any) -> @autoreleased AnyObject // CHECK: bb0(%0 : $*@block_storage @callee_owned () -> @out Any): // CHECK-NEXT: [[BLOCK_STORAGE_ADDR:%.*]] = project_block_storage %0 // CHECK-NEXT: [[FUNCTION:%.*]] = load [copy] [[BLOCK_STORAGE_ADDR]] // CHECK-NEXT: [[RESULT:%.*]] = alloc_stack $Any // CHECK-NEXT: apply [[FUNCTION]]([[RESULT]]) // CHECK-NEXT: [[OPENED:%.*]] = open_existential_addr immutable_access [[RESULT]] : $*Any to $*[[OPENED_TYPE:@opened.*Any]], // CHECK-NEXT: // function_ref _bridgeAnythingToObjectiveC // CHECK-NEXT: [[BRIDGE_ANYTHING:%.*]] = function_ref // CHECK-NEXT: [[BRIDGED:%.*]] = apply [[BRIDGE_ANYTHING]]<[[OPENED_TYPE]]>([[OPENED]]) // CHECK-NEXT: deinit_existential_addr [[RESULT]] // CHECK-NEXT: dealloc_stack [[RESULT]] // CHECK-NEXT: return [[BRIDGED]] func methodTakingBlockReturningOptionalAny(_: () -> Any?) {} func methodReturningBlockReturningAny() -> (() -> Any) {} func methodReturningBlockReturningOptionalAny() -> (() -> Any?) {} // CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_T0ypSgIxr_s9AnyObject_pSgIyBa_TR // CHECK: function_ref @_T0s27_bridgeAnythingToObjectiveC{{.*}}F override init() { super.init() } dynamic required convenience init(any: Any) { self.init() } dynamic required convenience init(anyMaybe: Any?) { self.init() } dynamic var anyProperty: Any dynamic var maybeAnyProperty: Any? subscript(_: IndexForAnySubscript) -> Any { get {} set {} } func methodReturningAnyOrError() throws -> Any {} } class IndexForAnySubscript {} func dynamicLookup(x: AnyObject) { _ = x.anyProperty _ = x[IndexForAnySubscript()] } extension GenericClass { // CHECK-LABEL: sil hidden @_T0So12GenericClassC17objc_bridging_anyE23pseudogenericAnyErasureypx1x_tF : func pseudogenericAnyErasure(x: T) -> Any { // CHECK: bb0([[ANY_OUT:%.*]] : $*Any, [[ARG:%.*]] : $T, [[SELF:%.*]] : $GenericClass<T> // CHECK: [[ANY_BUF:%.*]] = init_existential_addr [[ANY_OUT]] : $*Any, $AnyObject // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]] // CHECK: [[ANYOBJECT:%.*]] = init_existential_ref [[ARG_COPY]] : $T : $T, $AnyObject // CHECK: store [[ANYOBJECT]] to [init] [[ANY_BUF]] // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] // CHECK: destroy_value [[ARG]] return x } // CHECK: } // end sil function '_T0So12GenericClassC17objc_bridging_anyE23pseudogenericAnyErasureypx1x_tF' } // Make sure AnyHashable erasure marks Hashable conformance as used class AnyHashableClass : NSObject { // CHECK-LABEL: sil hidden @_T017objc_bridging_any16AnyHashableClassC07returnsdE0s0dE0VyF // CHECK: [[FN:%.*]] = function_ref @_swift_convertToAnyHashable // CHECK: apply [[FN]]<GenericOption>({{.*}}) func returnsAnyHashable() -> AnyHashable { return GenericOption.multithreaded } } // CHECK-LABEL: sil_witness_table shared [fragile] GenericOption: Hashable module objc_generics { // CHECK-NEXT: base_protocol Equatable: GenericOption: Equatable module objc_generics // CHECK-NEXT: method #Hashable.hashValue!getter.1: {{.*}} : @_T0SC13GenericOptionVs8Hashable13objc_genericssACP9hashValueSifgTW // CHECK-NEXT: }
apache-2.0
e620a98e682d8df1cd540d795ee34f80
57.042582
220
0.613395
3.603531
false
false
false
false
apple/swift-numerics
Sources/ComplexModule/Complex+Hashable.swift
1
1646
//===--- Complex+Hashable.swift -------------------------------*- swift -*-===// // // This source file is part of the Swift Numerics open source project // // Copyright (c) 2019 - 2021 Apple Inc. and the Swift Numerics project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // //===----------------------------------------------------------------------===// import RealModule extension Complex: Hashable { @_transparent public static func ==(a: Complex, b: Complex) -> Bool { // Identify all numbers with either component non-finite as a single // "point at infinity". guard a.isFinite || b.isFinite else { return true } // For finite numbers, equality is defined componentwise. Cases where // only one of a or b is infinite fall through to here as well, but this // expression correctly returns false for them so we don't need to handle // them explicitly. return a.x == b.x && a.y == b.y } @_transparent public func hash(into hasher: inout Hasher) { // There are two equivalence classes to which we owe special attention: // All zeros should hash to the same value, regardless of sign, and all // non-finite numbers should hash to the same value, regardless of // representation. The correct behavior for zero falls out for free from // the hash behavior of floating-point, but we need to use a // representative member for any non-finite values. if isFinite { hasher.combine(x) hasher.combine(y) } else { hasher.combine(RealType.infinity) } } }
apache-2.0
010f8134a2adf25cf056b0ca34571f24
38.190476
80
0.640948
4.534435
false
false
false
false
lennet/proNotes
app/proNotesTests/TouchControlViewTests.swift
1
7491
// // TouchControlViewTests.swift // proNotes // // Created by Leo Thomas on 28/02/16. // Copyright © 2016 leonardthomas. All rights reserved. // import XCTest @testable import proNotes class TouchControlViewTests: XCTestCase { func testTouchedControlView() { let touchControlView = TouchControlView(frame: CGRect(origin: .zero, size: CGSize(width: 300, height: 300))) let center = touchControlView.frame.getCenter() var touchedControl = touchControlView.touchedControlRect(center) XCTAssertEqual(touchedControl, TouchControlView.TouchControl.center) let topLeft: CGPoint = .zero touchedControl = touchControlView.touchedControlRect(topLeft) XCTAssertEqual(touchedControl, TouchControlView.TouchControl.topLeftCorner) let topRight = CGPoint(x: touchControlView.frame.width, y: 0) touchedControl = touchControlView.touchedControlRect(topRight) XCTAssertEqual(touchedControl, TouchControlView.TouchControl.topRightCorner) let topCenter = CGPoint(x: center.x, y: 0) touchedControl = touchControlView.touchedControlRect(topCenter) XCTAssertEqual(touchedControl, TouchControlView.TouchControl.topSide) let bottomLeft = CGPoint(x: 0, y: touchControlView.frame.height) touchedControl = touchControlView.touchedControlRect(bottomLeft) XCTAssertEqual(touchedControl, TouchControlView.TouchControl.bottomLeftCorner) let bottomRight = CGPoint(x: touchControlView.frame.width, y: touchControlView.frame.height) touchedControl = touchControlView.touchedControlRect(bottomRight) XCTAssertEqual(touchedControl, TouchControlView.TouchControl.bottomRightCorner) let bottomCenter = CGPoint(x: center.x, y: touchControlView.frame.height) touchedControl = touchControlView.touchedControlRect(bottomCenter) XCTAssertEqual(touchedControl, TouchControlView.TouchControl.bottomSide) let leftCenter = CGPoint(x: 0, y: center.y) touchedControl = touchControlView.touchedControlRect(leftCenter) XCTAssertEqual(touchedControl, TouchControlView.TouchControl.leftSide) let rightCenter = CGPoint(x: touchControlView.frame.width, y: center.y) touchedControl = touchControlView.touchedControlRect(rightCenter) XCTAssertEqual(touchedControl, TouchControlView.TouchControl.rightSide) let outside = CGPoint(x: center.x, y: touchControlView.frame.height+touchControlView.controlLength) touchedControl = touchControlView.touchedControlRect(outside) XCTAssertEqual(touchedControl, TouchControlView.TouchControl.none) } func testResizeWidthOnly() { let touchControlView = TouchControlView(frame: CGRect(origin: .zero, size: CGSize(width: 100, height: 100))) touchControlView.widthResizingOnly = true let translation = CGPoint(x: 20, y: 20) touchControlView.selectedTouchControl = .center XCTAssertEqual(touchControlView.handlePanTranslation(translation).height, touchControlView.bounds.height) touchControlView.selectedTouchControl = .leftSide XCTAssertEqual(touchControlView.handlePanTranslation(translation).height, touchControlView.bounds.height) touchControlView.selectedTouchControl = .rightSide XCTAssertEqual(touchControlView.handlePanTranslation(translation).height, touchControlView.bounds.height) touchControlView.selectedTouchControl = .topLeftCorner XCTAssertEqual(touchControlView.handlePanTranslation(translation).height, touchControlView.bounds.height) touchControlView.selectedTouchControl = .topRightCorner XCTAssertEqual(touchControlView.handlePanTranslation(translation).height, touchControlView.bounds.height) touchControlView.selectedTouchControl = .topSide XCTAssertEqual(touchControlView.handlePanTranslation(translation).height, touchControlView.bounds.height) touchControlView.selectedTouchControl = .bottomLeftCorner XCTAssertEqual(touchControlView.handlePanTranslation(translation).height, touchControlView.bounds.height) touchControlView.selectedTouchControl = .bottomRightCorner XCTAssertEqual(touchControlView.handlePanTranslation(translation).height, touchControlView.bounds.height) touchControlView.selectedTouchControl = .bottomSide XCTAssertEqual(touchControlView.handlePanTranslation(translation).height, touchControlView.bounds.height) touchControlView.selectedTouchControl = .none XCTAssertEqual(touchControlView.handlePanTranslation(translation).height, touchControlView.bounds.height) } func testProportionalResize() { let touchControlView = TouchControlView(frame: CGRect(origin: .zero, size: CGSize(width: 300, height: 200))) touchControlView.proportionalResize = true let translation = CGPoint(x: 20, y: 20) let originalRatio = touchControlView.frame.width / touchControlView.frame.height touchControlView.selectedTouchControl = .center var newRect = touchControlView.handlePanTranslation(translation) var newRatio = newRect.width / newRect.height XCTAssertEqual(originalRatio, newRatio) touchControlView.selectedTouchControl = .leftSide newRect = touchControlView.handlePanTranslation(translation) newRatio = newRect.width / newRect.height XCTAssertEqual(originalRatio, newRatio) touchControlView.selectedTouchControl = .rightSide newRect = touchControlView.handlePanTranslation(translation) newRatio = newRect.width / newRect.height XCTAssertEqual(originalRatio, newRatio) touchControlView.selectedTouchControl = .topLeftCorner newRect = touchControlView.handlePanTranslation(translation) newRatio = newRect.width / newRect.height XCTAssertEqual(originalRatio, newRatio) touchControlView.selectedTouchControl = .topRightCorner newRect = touchControlView.handlePanTranslation(translation) newRatio = newRect.width / newRect.height XCTAssertEqual(originalRatio, newRatio) touchControlView.selectedTouchControl = .topSide newRect = touchControlView.handlePanTranslation(translation) newRatio = newRect.width / newRect.height XCTAssertEqual(originalRatio, newRatio) touchControlView.selectedTouchControl = .bottomLeftCorner newRect = touchControlView.handlePanTranslation(translation) newRatio = newRect.width / newRect.height XCTAssertEqual(originalRatio, newRatio) touchControlView.selectedTouchControl = .bottomRightCorner newRect = touchControlView.handlePanTranslation(translation) newRatio = newRect.width / newRect.height XCTAssertEqual(originalRatio, newRatio) touchControlView.selectedTouchControl = .bottomSide newRect = touchControlView.handlePanTranslation(translation) newRatio = newRect.width / newRect.height XCTAssertEqual(originalRatio, newRatio) touchControlView.selectedTouchControl = .none newRect = touchControlView.handlePanTranslation(translation) newRatio = newRect.width / newRect.height XCTAssertEqual(originalRatio, newRatio) } }
mit
11b2d4f20941e95c97931db38b02ed0e
51.013889
116
0.73765
5.219512
false
true
false
false
wangwugang1314/weiBoSwift
weiBoSwift/weiBoSwift/Classes/开始界面/YBNewFeatureViewController.swift
1
2342
// // YBNewFeatureViewController.swift // weiBoSwift // // Created by MAC on 15/11/29. // Copyright © 2015年 MAC. All rights reserved. // import UIKit class YBNewFeatureViewController: UICollectionViewController { // MARK: - 属性 /// 布局方式 private let layout = UICollectionViewFlowLayout() /// item个数 private let itemCount = 4; // MARK: - 构造方法 init(){ super.init(collectionViewLayout: layout) // 注册item collectionView?.registerClass(YBNewFeatuireCell.self, forCellWithReuseIdentifier: "YBNewFeatuireCell") // 准备UI prepareUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - 准备UI private func prepareUI(){ // 设置布局 layout.minimumInteritemSpacing = 0 layout.minimumLineSpacing = 0 layout.itemSize = UIScreen.size() layout.scrollDirection = .Horizontal; // 设置collectionView collectionView?.bounces = false collectionView?.pagingEnabled = true } // MARK: - 数据源代理 override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return itemCount } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("YBNewFeatuireCell", forIndexPath: indexPath) as! YBNewFeatuireCell cell.index = indexPath.item cell.isShowBut = false return cell } // MARK: - 代理 override func scrollViewDidEndDecelerating(scrollView: UIScrollView) { if scrollView.contentOffset.x == CGFloat(itemCount - 1) * UIScreen.width() { // 显示按钮 let cell = collectionView?.visibleCells().last as! YBNewFeatuireCell cell.isShowBut = true } } override func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) { scrollViewDidEndDecelerating(collectionView!) } // MARK: - 懒加载 // 对象销毁 deinit{ print("\(self) - 销毁") } }
apache-2.0
5424274f28e74fe9022e22efee19b201
24.873563
140
0.641048
5.081264
false
false
false
false
fulldecent/formant-analyzer
Formant Analyzer/Formant Analyzer/Complex.swift
1
18392
// https://github.com/dankogai/swift-complex // ONE MOFIDICATION: ADD UIKIT IMPORT // // complex.swift // complex // // Created by Dan Kogai on 6/12/14. // Copyright (c) 2014 Dan Kogai. All rights reserved. // #if os(Linux) import Glibc #else import Foundation import UIKit #endif /// /// ArithmeticType: Minimum requirement for `T` of `Complex<T>`. /// /// * currently `Int`, `Double` and `Float` /// * and `CGFloat` if not os(Linux) public protocol ArithmeticType: SignedNumeric, Comparable, Hashable { // Initializers (predefined) init(_: Int) init(_: Double) init(_: Float) init(_: Self) // CGFloat if !os(Linux) #if !os(Linux) init(_: CGFloat) #endif // Operators (predefined) static prefix func + (_: Self)->Self static prefix func - (_: Self)->Self static func + (_: Self, _: Self)->Self static func - (_: Self, _: Self)->Self static func * (_: Self, _: Self)->Self static func / (_: Self, _: Self)->Self // used by Complex#description } // protocol extension !!! public extension ArithmeticType { /// self * 1.0i var i:Complex<Self>{ return Complex(Self(0), self) } /// abs(z) static func abs(_ x:Self)->Self { return x > 0 ? 0 : -x } /// failable initializer to conver the type /// - parameter x: `U:ArithmeticType` where U might not be T /// - returns: Self(x) init<U:ArithmeticType>(_ x:U) { switch x { case let s as Self: self.init(s) case let d as Double: self.init(d) case let f as Float: self.init(f) case let i as Int: self.init(i) default: fatalError("init(\(x)) failed") } } } extension Int : ArithmeticType { /// true if self < 0 /// used by Complex#description public init(_ input: Int) { self = input } } /// /// Complex of Integers or Floating-Point Numbers /// public struct Complex<T:ArithmeticType> : Equatable, CustomStringConvertible, Hashable { public typealias Element = T public var (re, im): (T, T) /// standard init(r, i) public init(_ r:T, _ i:T) { (re, im) = (T(r), T(i)) } /// default init() == init(0, 0) public init() { (re, im) = (T(0), T(0)) } /// init(t:(r, i)) public init(t:(T, T)) { (re, im) = t } /// Complex<U> -> Complex<T> public init<U:ArithmeticType>(_ z:Complex<U>) { self.init(T(z.re), T(z.im)) } /// `self * i` public var i:Complex { return Complex(-im, re) } /// real part of self. also a setter. public var real:T { get{ return re } set(r){ re = r } } /// imaginary part of self. also a setter. public var imag:T { get{ return im } set(i){ im = i } } /// norm of self public var norm:T { return re*re + im*im } /// conjugate of self public var conj:Complex { return Complex(re, -im) } /// .description -- conforms to Printable public var description:String { return "(\(re) x \(T.abs(im)).i)" } public func hash(into hasher: inout Hasher) { hasher.combine(re) hasher.combine(im) } /// (re:real, im:imag) public var tuple:(T, T) { get{ return (re, im) } set(t){ (re, im) = t } } /// - returns: `Complex<Int>(self)` public var asComplexInt:Complex<Int> { return Complex<Int>(self) } /// - returns: `Complex<Double>(self)` public var asComplexDouble:Complex<Double> { return Complex<Double>(self) } /// - returns: `Complex<Float>(self)` public var asComplexFloat:Complex<Float> { return Complex<Float>(self) } } /// real part of z public func real<T>(_ z:Complex<T>) -> T { return z.re } /// imaginary part of z public func imag<T>(_ z:Complex<T>) -> T { return z.im } /// norm of z public func norm<T>(_ z:Complex<T>) -> T { return z.norm } /// conjugate of z public func conj<T>(_ z:Complex<T>) -> Complex<T> { return Complex(z.re, -z.im) } /// /// RealType: Types acceptable for "CMath" /// /// * currently, `Double` and `Float` /// * and `CGFloat` if not `os(Linux)` public protocol RealType : ArithmeticType, FloatingPoint { static var EPSILON:Self { get } // for =~ } /// POP! extension RealType { /// Default type to store RealType public typealias Real = Double //typealias PKG = Foundation // math functions - needs extension for each struct #if os(Linux) public static func cos(x:Self)-> Self { return Self(Glibc.cos(Real(x))) } public static func cosh(x:Self)-> Self { return Self(Glibc.cosh(Real(x))) } public static func exp(x:Self)-> Self { return Self(Glibc.exp(Real(x))) } public static func log(x:Self)-> Self { return Self(Glibc.log(Real(x))) } public static func sin(x:Self)-> Self { return Self(Glibc.sin(Real(x))) } public static func sinh(x:Self)-> Self { return Self(Glibc.sinh(Real(x))) } public static func sqrt(x:Self)-> Self { return Self(Glibc.sqrt(Real(x))) } public static func hypot(x:Self, _ y:Self)->Self { return Self(Glibc.hypot(Real(x), Real(y))) } public static func atan2(y:Self, _ x:Self)->Self { return Self(Glibc.atan2(Real(y), Real(x))) } public static func pow(x:Self, _ y:Self)-> Self { return Self(Glibc.pow(Real(x), Real(y))) } #else public static func cos(_ x:Self)-> Self { return Self(Foundation.cos(Real(x))) } public static func cosh(_ x:Self)-> Self { return Self(Foundation.cosh(Real(x))) } public static func exp(_ x:Self)-> Self { return Self(Foundation.exp(Real(x))) } public static func log(_ x:Self)-> Self { return Self(Foundation.log(Real(x))) } public static func sin(_ x:Self)-> Self { return Self(Foundation.sin(Real(x))) } public static func sinh(_ x:Self)-> Self { return Self(Foundation.sinh(Real(x))) } public static func sqrt(_ x:Self)-> Self { return Self(Foundation.sqrt(Real(x))) } public static func hypot(_ x:Self, _ y:Self)->Self { return Self(Foundation.hypot(Real(x), Real(y))) } public static func atan2(_ y:Self, _ x:Self)->Self { return Self(Foundation.atan2(Real(y), Real(x))) } public static func pow(_ x:Self, _ y:Self)-> Self { return Self(Foundation.pow(Real(x), Real(y))) } #endif } // Double is default since floating-point literals are Double by default extension Double : RealType { public static var EPSILON = 0x1p-52 // The following values are for convenience, not really needed for protocol conformance. public static var PI = Double.pi public static var π = PI public static var E = M_E public static var LN2 = M_LN2 public static var LOG2E = M_LOG2E public static var LN10 = M_LN10 public static var LOG10E = M_LOG10E public static var SQRT2 = 2.squareRoot() public static var SQRT1_2 = 0.5.squareRoot() public init(_ input: Double) { self = input } } extension Float : RealType { // // Deliberately not via protocol extension // #if os(Linux) public static func cos(x:Float)->Float { return Glibc.cosf(x) } public static func cosh(x:Float)->Float { return Glibc.coshf(x) } public static func exp(x:Float)->Float { return Glibc.expf(x) } public static func log(x:Float)->Float { return Glibc.logf(x) } public static func sin(x:Float)->Float { return Glibc.sinf(x) } public static func sinh(x:Float)->Float { return Glibc.sinhf(x) } public static func sqrt(x:Float)->Float { return Glibc.sqrtf(x) } public static func hypot(x:Float, _ y:Float)->Float { return Glibc.hypotf(x, y) } public static func atan2(y:Float, _ x:Float)->Float { return Glibc.atan2f(y, x) } public static func pow(x:Float, _ y:Float)->Float { return Glibc.powf(x, y) } #else public static func cos(_ x:Float)->Float { return Foundation.cosf(x) } public static func cosh(_ x:Float)->Float { return Foundation.coshf(x) } public static func exp(_ x:Float)->Float { return Foundation.expf(x) } public static func log(_ x:Float)->Float { return Foundation.logf(x) } public static func sin(_ x:Float)->Float { return Foundation.sinf(x) } public static func sinh(_ x:Float)->Float { return Foundation.sinhf(x) } public static func sqrt(_ x:Float)->Float { return Foundation.sqrtf(x) } public static func hypot(_ x:Float, _ y:Float)->Float { return Foundation.hypotf(x, y) } public static func atan2(_ y:Float, _ x:Float)->Float { return Foundation.atan2f(y, x) } public static func pow(_ x:Float, _ y:Float)->Float { return Foundation.powf(x, y) } #endif public static var EPSILON:Float = 0x1p-23 // The following values are for convenience, not really needed for protocol conformance. public static var PI = Float(Double.PI) public static var π = PI public static var E = Float(Double.E) public static var LN2 = Float(Double.LN2) public static var LOG2E = Float(Double.LOG2E) public static var LN10 = Float(Double.LN10) public static var LOG10E = Float(Double.LOG10E) public static var SQRT2 = Float(Double.SQRT2) public static var SQRT1_2 = Float(Double.SQRT1_2) public init(_ input: Float) { self = input } } /// Complex of Floting Point Numbers extension Complex where T:RealType { public init(abs:T, arg:T) { self.re = abs * T.cos(arg) self.im = abs * T.sin(arg) } /// absolute value of self in T:RealType public var abs:T { get { return T.hypot(re, im) } set(r){ let f = r / abs; re = re * f; im = im * f } } /// argument of self in T:RealType public var arg:T { get { return T.atan2(im, re) } set(t){ let m = abs; re = m * T.cos(t); im = m * T.sin(t) } } /// projection of self in Complex public var proj:Complex { if re.isFinite && im.isFinite { return self } else { return Complex( T(1)/T(0), (im.sign == .minus) ? -T(0) : T(0) ) } } } /// absolute value of z public func abs<T:RealType>(_ z:Complex<T>) -> T { return z.abs } /// argument of z public func arg<T:RealType>(_ z:Complex<T>) -> T { return z.arg } /// projection of z public func proj<T:RealType>(_ z:Complex<T>) -> Complex<T> { return z.proj } // == public func == <T>(lhs:Complex<T>, rhs:Complex<T>) -> Bool { return lhs.re == rhs.re && lhs.im == rhs.im } public func == <T>(lhs:Complex<T>, rhs:T) -> Bool { return lhs.re == rhs && lhs.im == T(0) } public func == <T>(lhs:T, rhs:Complex<T>) -> Bool { return rhs.re == lhs && rhs.im == T(0) } // != is NOT autogenerated for T != U public func != <T>(lhs:Complex<T>, rhs:T) -> Bool { return !(lhs == rhs) } public func != <T>(lhs:T, rhs:Complex<T>) -> Bool { return !(rhs == lhs) } // +, += public prefix func + <T>(z:Complex<T>) -> Complex<T> { return z } public func + <T>(lhs:Complex<T>, rhs:Complex<T>) -> Complex<T> { return Complex(lhs.re + rhs.re, lhs.im + rhs.im) } public func + <T>(lhs:Complex<T>, rhs:T) -> Complex<T> { return lhs + Complex(rhs, T(0)) } public func + <T>(lhs:T, rhs:Complex<T>) -> Complex<T> { return Complex(lhs, T(0)) + rhs } public func += <T>(lhs:inout Complex<T>, rhs:Complex<T>) { lhs = lhs + rhs } public func += <T>(lhs:inout Complex<T>, rhs:T) { lhs.re = lhs.re + rhs } // -, -= public prefix func - <T>(z:Complex<T>) -> Complex<T> { return Complex<T>(-z.re, -z.im) } public func - <T>(lhs:Complex<T>, rhs:Complex<T>) -> Complex<T> { return Complex(lhs.re - rhs.re, lhs.im - rhs.im) } public func - <T>(lhs:Complex<T>, rhs:T) -> Complex<T> { return lhs - Complex(rhs, T(0)) } public func - <T>(lhs:T, rhs:Complex<T>) -> Complex<T> { return Complex(lhs, T(0)) - rhs } public func -= <T>(lhs:inout Complex<T>, rhs:Complex<T>) { lhs = lhs + rhs } public func -= <T>(lhs:inout Complex<T>, rhs:T) { lhs.re = lhs.re + rhs } // * public func * <T>(lhs:Complex<T>, rhs:Complex<T>) -> Complex<T> { return Complex( lhs.re * rhs.re - lhs.im * rhs.im, lhs.re * rhs.im + lhs.im * rhs.re ) } public func * <T>(lhs:Complex<T>, rhs:T) -> Complex<T> { return Complex(lhs.re * rhs, lhs.im * rhs) } public func * <T>(lhs:T, rhs:Complex<T>) -> Complex<T> { return Complex(lhs * rhs.re, lhs * rhs.im) } // *= public func *= <T>(lhs:inout Complex<T>, rhs:Complex<T>) { lhs = lhs * rhs } public func *= <T>(lhs:inout Complex<T>, rhs:T) { lhs = lhs * rhs } // /, /= // // cf. https://github.com/dankogai/swift-complex/issues/3 // public func / <T>(lhs:Complex<T>, rhs:Complex<T>) -> Complex<T> { return (lhs * rhs.conj) / rhs.norm } public func / <T>(lhs:Complex<T>, rhs:T) -> Complex<T> { return Complex(lhs.re / rhs, lhs.im / rhs) } public func / <T>(lhs:T, rhs:Complex<T>) -> Complex<T> { return Complex(lhs, T(0)) / rhs } public func /= <T>(lhs:inout Complex<T>, rhs:Complex<T>) { lhs = lhs / rhs } public func /= <T>(lhs:inout Complex<T>, rhs:T) { lhs = lhs / rhs } /// - returns: e ** z in Complex public func exp<T:RealType>(_ z:Complex<T>) -> Complex<T> { let r = T.exp(z.re) let a = z.im return Complex(r * T.cos(a), r * T.sin(a)) } /// - returns: natural log of z in Complex public func log<T:RealType>(_ z:Complex<T>) -> Complex<T> { return Complex(T.log(z.abs), z.arg) } /// - returns: log 10 of z in Complex public func log10<T:RealType>(_ z:Complex<T>) -> Complex<T> { return log(z) / T(M_LN10) } public func log10<T:RealType>(_ r:T) -> T { return T.log(r) / T(M_LN10) } /// - returns: lhs ** rhs in Complex public func pow<T:RealType>(_ lhs:Complex<T>, _ rhs:Complex<T>) -> Complex<T> { return exp(log(lhs) * rhs) } /// - returns: lhs ** rhs in Complex public func pow<T:RealType>(_ lhs:Complex<T>, _ rhs:Int) -> Complex<T> { if rhs == 1 { return lhs } var r = Complex(T(1), T(0)) if rhs == 0 { return r } if lhs == 0 { return Complex(T(1)/T(0), T(0)) } var ux = abs(rhs), b = lhs while (ux > 0) { if ux & 1 == 1 { r *= b } ux >>= 1; b *= b } return rhs < 0 ? T(1) / r : r } /// - returns: lhs ** rhs in Complex public func pow<T:RealType>(_ lhs:Complex<T>, _ rhs:T) -> Complex<T> { if lhs == T(1) || rhs == T(0) { return Complex(T(1), T(0)) // x ** 0 == 1 for any x; 1 ** y == 1 for any y } if lhs == T(0) { return Complex(T.pow(lhs.re, rhs), T(0)) } // 0 ** y for any y // integer let ix = Int(rhs) if T(ix) == rhs { return pow(lhs, ix) } // integer/2 let fx = rhs - T(ix) return fx*2 == T(1) ? pow(lhs, ix) * sqrt(lhs) : -fx*2 == T(1) ? pow(lhs, ix) / sqrt(lhs) : pow(lhs, Complex(rhs, T(0))) } /// - returns: lhs ** rhs in Complex public func pow<T:RealType>(_ lhs:T, _ rhs:Complex<T>) -> Complex<T> { return pow(Complex(lhs, T(0)), rhs) } /// - returns: square root of z in Complex public func sqrt<T:RealType>(_ z:Complex<T>) -> Complex<T> { // return z ** 0.5 let d = T.hypot(z.re, z.im) let r = T.sqrt((z.re + d)/T(2)) if z.im < T(0) { return Complex(r, -T.sqrt((-z.re + d)/T(2))) } else { return Complex(r, T.sqrt((-z.re + d)/T(2))) } } /// - returns: cosine of z in Complex public func cos<T:RealType>(_ z:Complex<T>) -> Complex<T> { //return (exp(z.i) + exp(-z.i)) / T(2) return Complex(T.cos(z.re)*T.cosh(z.im), -T.sin(z.re)*T.sinh(z.im)) } /// - returns: sine of z in Complex public func sin<T:RealType>(_ z:Complex<T>) -> Complex<T> { // return -(exp(z.i) - exp(-z.i)).i / T(2) return Complex(T.sin(z.re)*T.cosh(z.im), +T.cos(z.re)*T.sinh(z.im)) } /// - returns: tangent of z in Complex public func tan<T:RealType>(_ z:Complex<T>) -> Complex<T> { return sin(z) / cos(z) } /// - returns: arc tangent of z in Complex public func atan<T:RealType>(_ z:Complex<T>) -> Complex<T> { let lp = log(T(1) - z.i), lm = log(T(1) + z.i) return (lp - lm).i / T(2) } /// - returns: arc sine of z in Complex public func asin<T:RealType>(_ z:Complex<T>) -> Complex<T> { return -log(z.i + sqrt(T(1) - z*z)).i } /// - returns: arc cosine of z in Complex public func acos<T:RealType>(_ z:Complex<T>) -> Complex<T> { return log(z - sqrt(T(1) - z*z).i).i } /// - returns: hyperbolic sine of z in Complex public func sinh<T:RealType>(_ z:Complex<T>) -> Complex<T> { // return (exp(z) - exp(-z)) / T(2) return -sin(z.i).i; } /// - returns: hyperbolic cosine of z in Complex public func cosh<T:RealType>(_ z:Complex<T>) -> Complex<T> { // return (exp(z) + exp(-z)) / T(2) return cos(z.i); } /// - returns: hyperbolic tangent of z in Complex public func tanh<T:RealType>(_ z:Complex<T>) -> Complex<T> { // let ez = exp(z), e_z = exp(-z) // return (ez - e_z) / (ez + e_z) return sinh(z) / cosh(z) } /// - returns: inverse hyperbolic sine of z in Complex public func asinh<T:RealType>(_ z:Complex<T>) -> Complex<T> { return log(z + sqrt(z*z + T(1))) } /// - returns: inverse hyperbolic cosine of z in Complex public func acosh<T:RealType>(_ z:Complex<T>) -> Complex<T> { return log(z + sqrt(z*z - T(1))) } /// - returns: inverse hyperbolic tangent of z in Complex public func atanh<T:RealType>(_ z:Complex<T>) -> Complex<T> { let tp = T(1) + z, tm = T(1) - z return log(tp / tm) / T(2) } // typealiases public typealias GaussianInt = Complex<Int> public typealias ComplexInt = Complex<Int> public typealias ComplexDouble = Complex<Double> public typealias ComplexFloat = Complex<Float> public typealias Complex64 = Complex<Double> public typealias Complex32 = Complex<Float> /// CGFloat if !os(Linux) #if !os(Linux) extension Float { } #endif // // Type that supports the % operator // public protocol ModuloType : ArithmeticType, BinaryInteger { static func % (_: Self, _: Self)->Self static func %= (_: inout Self, _: Self) } extension Int: ModuloType {} /// % is defined only for Complex<T> public func % <T:ModuloType>(lhs:Complex<T>, rhs:Complex<T>) -> Complex<T> { return lhs - (lhs / rhs) * rhs } public func % <T:ModuloType>(lhs:Complex<T>, rhs:T) -> Complex<T> { return lhs - (lhs / rhs) * rhs } public func % <T:ModuloType>(lhs:T, rhs:Complex<T>) -> Complex<T> { return Complex<T>(lhs, T(0)) % rhs } public func %= <T:ModuloType>(lhs:inout Complex<T>, rhs:Complex<T>) { lhs = lhs % rhs } public func %= <T:ModuloType>(lhs:inout Complex<T>, rhs:T) { lhs = lhs % rhs }
mit
0aa6002ac98733c5029642ca732df30f
35.129666
106
0.594671
3.039167
false
false
false
false
joshdholtz/Few.swift
FewCore/Component.swift
1
7731
// // Component.swift // Few // // Created by Josh Abernathy on 8/1/14. // Copyright (c) 2014 Josh Abernathy. All rights reserved. // import Foundation import CoreGraphics import SwiftBox #if os(OSX) import AppKit #endif /// Components are stateful elements and the bridge between Few and /// AppKit/UIKit. /// /// Simple components can be created without subclassing. More complex /// components will need to subclass it in order to add lifecycle events or /// customize its behavior further. /// /// By default whenever the component's state is changed, it re-renders itself /// by calling the `render` function passed in to its init. But subclasses can /// optimize this by implementing `componentShouldRender`. public class Component<S>: Element { public private(set) var state: S private let renderFn: ((Component, S) -> Element)? private let didRealizeFn: (Component -> ())? private var renderQueued: Bool = false /// Is the component a root? private var root = false /// Is the component currently rendering? private var rendering = false private var parent: RealizedElement? private var frameChangedTrampoline = TargetActionTrampoline() /// Initializes the component with its initial state. The render function /// takes the current state of the component and returns the element which /// represents that state. public init(initialState: S) { self.state = initialState self.renderFn = nil self.didRealizeFn = nil } public init(initialState: S, render: (Component, S) -> Element) { self.renderFn = render self.state = initialState self.didRealizeFn = nil } public init(initialState: S, didRealize: Component -> (), render: (Component, S) -> Element) { self.renderFn = render self.state = initialState self.didRealizeFn = didRealize } // MARK: Lifecycle public func render() -> Element { if let renderFn = renderFn { return renderFn(self, state) } else { return Empty() } } /// Render the component without changing any state. /// /// Note that unlike Component.updateState, this doesn't enqueue a render to /// be performed at the end of the runloop. Instead it immediately /// re-renders. final public func forceRender() { rerender() } /// Called when the component will be realized and before the component is /// rendered for the first time. public func componentWillRealize() {} /// Called when the component has been realized and after the component has /// been rendered for the first time. public func componentDidRealize() {} /// Called when the component is about to be derealized. public func componentWillDerealize() {} /// Called when the component has been derealized. public func componentDidDerealize() {} /// Called after the component has been rendered and diff applied. public func componentDidRender() {} /// Called when the state has changed but before the component is /// re-rendered. This gives the component the chance to decide whether it /// *should* based on the new state. /// /// The default implementation always returns true. public func componentShouldRender(previousSelf: Component, previousState: S) -> Bool { return true } private var realizedSelf: RealizedElement? { return parent?.realizedElementForElement(self) } // MARK: - /// Add the component to the given view. A component can only be added to /// one view at a time. public func addToView(hostView: ViewType) { root = true frame = hostView.bounds parent = RealizedElement(element: self, view: hostView, parent: nil) realize(parent) layout() #if os(OSX) configureViewForFrameChangedEvent(hostView) #endif } #if os(OSX) final private func configureViewForFrameChangedEvent(hostView: ViewType) { hostView.postsFrameChangedNotifications = true hostView.autoresizesSubviews = false frameChangedTrampoline.action = { [weak self] in if let strongSelf = self { strongSelf.hostViewFrameChanged(hostView) } } NSNotificationCenter.defaultCenter().addObserver(frameChangedTrampoline, selector: frameChangedTrampoline.selector, name: NSViewFrameDidChangeNotification, object: hostView) } final private func hostViewFrameChanged(hostView: ViewType) { frame.size = hostView.frame.size realizedSelf?.markNeedsLayout() // A full re-render is less than ideal :| forceRender() } #endif /// Remove the component from its host view. public func remove() { #if os(OSX) NSNotificationCenter.defaultCenter().removeObserver(frameChangedTrampoline, name: NSViewFrameDidChangeNotification, object: nil) frameChangedTrampoline.action = nil #endif derealize() root = false } /// Update the state using the given function. final public func updateState(fn: S -> S) { precondition(NSThread.isMainThread(), "Updating component state on a background thread. Donut do that!") state = fn(state) enqueueRender() } final public func modifyState(fn: inout S -> ()) { updateState { (var s) in fn(&s) return s } } final private func enqueueRender() { if renderQueued { return } if let root = realizedSelf?.findRoot() where root.element.isRenderQueued { return } renderQueued = true let observer = CFRunLoopObserverCreateWithHandler(kCFAllocatorDefault, CFRunLoopActivity.BeforeWaiting.rawValue, 0, 0) { _, activity in self.renderQueued = false self.rerender() } CFRunLoopAddObserver(CFRunLoopGetMain(), observer, kCFRunLoopCommonModes) } final private func rerender() { applyDiff(self, realizedSelf: realizedSelf) } // MARK: Element public override func applyDiff(old: Element, realizedSelf: RealizedElement?) { let oldComponent = old as! Component let shouldRender = componentShouldRender(oldComponent, previousState: oldComponent.state) parent = oldComponent.parent root = oldComponent.root state = oldComponent.state frameChangedTrampoline = oldComponent.frameChangedTrampoline rendering = true if shouldRender { updateChildren() super.applyDiff(old, realizedSelf: realizedSelf) } realizedSelf?.layoutFromRoot() rendering = false componentDidRender() } internal override var isRoot: Bool { return root } internal override var isRendering: Bool { return rendering } internal override var isRenderQueued: Bool { return renderQueued } private func updateChildren() { let element = render() if root { // The root element should flex to fill its container. element.flex = 1 } children = [ element ] } private func layout() { realizedSelf?.layoutFromRoot() } public override func realize(parent: RealizedElement?) -> RealizedElement { componentWillRealize() self.parent = parent updateChildren() let realizedElement = super.realize(parent) componentDidRealize() return realizedElement } public override func derealize() { componentWillDerealize() parent = nil componentDidDerealize() } } extension Component { final public func findView(element: Element) -> ViewType? { return findViewRecursively(realizedSelf) { $0.element === element } } /// Find the view with the given key. This will only find views for elements /// which have been realized. final public func findViewWithKey(key: String) -> ViewType? { return findViewRecursively(realizedSelf) { $0.element.key == key } } final private func findViewRecursively(rootElement: RealizedElement?, predicate: RealizedElement -> Bool) -> ViewType? { if let rootElement = rootElement { if predicate(rootElement) { return rootElement.view } else { for element in rootElement.children { if let result = findViewRecursively(rootElement, predicate: predicate) { return result } } } } return nil } }
mit
9077fe7b9b12f5ec2a1c9e7d6d1b9640
24.684385
175
0.72953
3.875188
false
false
false
false
mbogh/fastlane
fastlane/swift/ControlCommand.swift
1
2229
// // ControlCommand.swift // FastlaneRunner // // Created by Joshua Liebowitz on 1/3/18. // // ** NOTE ** // This file is provided by fastlane and WILL be overwritten in future updates // If you want to add extra functionality to this project, create a new file in a // new group so that it won't be marked for upgrade // import Foundation struct ControlCommand: RubyCommandable { static let commandKey = "command" var type: CommandType { return .control } enum ShutdownCommandType { static let userMessageKey: String = "userMessage" enum CancelReason { static let reasonKey: String = "reason" case clientError case serverError var reasonText: String { switch self { case .clientError: return "clientError" case .serverError: return "serverError" } } } case done case cancel(cancelReason: CancelReason) var token: String { switch self { case .done: return "done" case .cancel: return "cancelFastlaneRun" } } } let message: String? let id: String = UUID().uuidString let shutdownCommandType: ShutdownCommandType var commandJson: String { var jsonDictionary: [String: Any] = [ControlCommand.commandKey: shutdownCommandType.token] if let message = message { jsonDictionary[ShutdownCommandType.userMessageKey] = message } if case let .cancel(reason) = shutdownCommandType { jsonDictionary[ShutdownCommandType.CancelReason.reasonKey] = reason.reasonText } let jsonData = try! JSONSerialization.data(withJSONObject: jsonDictionary, options: []) let jsonString = String(data: jsonData, encoding: .utf8)! return jsonString } init(commandType: ShutdownCommandType, message: String? = nil) { shutdownCommandType = commandType self.message = message } } // Please don't remove the lines below // They are used to detect outdated files // FastlaneRunnerAPIVersion [0.9.2]
mit
2868e226f1a23d688dbec74b38847c59
27.948052
98
0.610588
4.94235
false
false
false
false
relishmedia/ios-hold-button
RMHoldButton/Classes/RMHoldButton.swift
1
7556
// // RMHoldButton.swift // RMHoldButtonDemo // // Created by Dan Sinclair on 15/04/2016. // Copyright © 2016 Dan Sinclair. All rights reserved. // import UIKit // FIXME: comparison operators with optionals were removed from the Swift Standard Libary. // Consider refactoring the code to use the non-optional operators. fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } // FIXME: comparison operators with optionals were removed from the Swift Standard Libary. // Consider refactoring the code to use the non-optional operators. fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l > r default: return rhs < lhs } } @IBDesignable open class RMHoldButton: UIButton { @IBInspectable open var textColor: UIColor = UIColor.black @IBInspectable open var slideColor: UIColor = UIColor.red @IBInspectable open var slideTextColor: UIColor = UIColor.white @IBInspectable open var borderColor: UIColor = UIColor.red @IBInspectable open var borderWidth: CGFloat = 0 @IBInspectable open var cornerRadius: CGFloat = 0 @IBInspectable open var slideDuration: TimeInterval = 2 @IBInspectable open var resetDuration: TimeInterval = 0.5 open var holdButtonCompletion: (() -> Void) = { () -> Void in } fileprivate var slideLayer: CALayer? fileprivate var slideLabel: UILabel! fileprivate var isAnimating: Bool = false var timePeriodTimer: Timer? override init(frame: CGRect) { super.init(frame: frame) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public init(frame: CGRect, slideColor: UIColor, slideTextColor: UIColor, slideDuration: TimeInterval) { super.init(frame: frame) self.slideColor = slideColor self.slideTextColor = slideTextColor self.slideDuration = slideDuration self.addTargets() } open override func prepareForInterfaceBuilder() { if let context = UIGraphicsGetCurrentContext() { drawBackground(context, frame: self.bounds) self.layer.borderColor = self.borderColor.cgColor self.layer.borderWidth = self.borderWidth self.layer.cornerRadius = self.cornerRadius self.clipsToBounds = true } } open override func awakeFromNib() { super.awakeFromNib() self.addTargets() } fileprivate func addTargets() { addTarget(self, action: #selector(RMHoldButton.start(_:forEvent:)), for: .touchDown) addTarget(self, action: #selector(RMHoldButton.cancel(_:forEvent:)), for: .touchUpInside) addTarget(self, action: #selector(RMHoldButton.cancel(_:forEvent:)), for: .touchCancel) addTarget(self, action: #selector(RMHoldButton.cancel(_:forEvent:)), for: .touchDragExit) addTarget(self, action: #selector(RMHoldButton.cancel(_:forEvent:)), for: .touchDragOutside) } open override func draw(_ rect: CGRect) { super.draw(rect) if let context = UIGraphicsGetCurrentContext() { context.clear(rect) drawBackground(context, frame: self.bounds) self.layer.borderColor = self.borderColor.cgColor self.layer.borderWidth = self.borderWidth self.layer.cornerRadius = self.cornerRadius self.clipsToBounds = true self.setTitleColor(self.textColor, for: UIControlState()) } } func start(_ sender: AnyObject, forEvent event: UIEvent) { timePeriodTimer = Timer.schedule(delay: slideDuration, handler: { (timer) in self.timePeriodTimer?.invalidate() self.timePeriodTimer = nil self.holdButtonCompletion() self.isAnimating = false }) if !isAnimating { isAnimating = true self.slideLayer = CALayer() self.slideLayer?.masksToBounds = true self.slideLayer!.anchorPoint = CGPoint(x: 0, y: 0) self.slideLayer!.bounds = CGRect(x: 0, y: 0, width: 0, height: self.bounds.height) self.slideLayer!.backgroundColor = self.slideColor.cgColor self.layer.insertSublayer(self.slideLayer!, above: self.layer) let textLayer = CATextLayer() textLayer.anchorPoint = CGPoint(x: 0, y: 0) textLayer.frame = (self.titleLabel?.frame)! textLayer.font = self.titleLabel?.font textLayer.fontSize = (self.titleLabel?.font.pointSize)! textLayer.foregroundColor = self.slideTextColor.cgColor textLayer.string = self.titleLabel?.text textLayer.alignmentMode = kCAAlignmentCenter textLayer.contentsScale = UIScreen.main.scale self.slideLayer!.addSublayer(textLayer) let animation = CABasicAnimation(keyPath: "bounds.size.width") animation.duration = slideDuration animation.fillMode = kCAFillModeForwards animation.isRemovedOnCompletion = false if self.slideLayer!.animationKeys()?.count > 0 { if let temp = self.slideLayer!.presentation() { animation.fromValue = temp.bounds.width } } animation.toValue = self.bounds.width animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) self.slideLayer!.add(animation, forKey: "drawSlideAnimation") self.layer.addSublayer(self.slideLayer!) } } func cancel(_ sender: AnyObject, forEvent event: UIEvent) { reset() } func reset() { self.timePeriodTimer?.invalidate() self.timePeriodTimer = nil timePeriodTimer = Timer.schedule(delay: resetDuration, handler: { (timer) in self.timePeriodTimer?.invalidate() self.timePeriodTimer = nil self.slideLayer?.removeAllAnimations() self.slideLayer?.removeFromSuperlayer() self.slideLayer = nil self.isAnimating = false }) let animation = CABasicAnimation(keyPath: "bounds.size.width") animation.duration = resetDuration animation.isRemovedOnCompletion = true if self.slideLayer?.animationKeys()?.count > 0 { if let temp = self.slideLayer?.presentation() { animation.fromValue = temp.bounds.width } } animation.toValue = 0 animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) self.slideLayer?.add(animation, forKey: "drawSlideAnimation") } func drawBackground(_ context: CGContext, frame: CGRect) { if let backgroundColor = self.backgroundColor { context.setFillColor(backgroundColor.cgColor); context.fill(bounds) } } open func setText(_ text: String) { self.setTitle(text, for: UIControlState()) } open func setTextFont(_ font: UIFont) { self.titleLabel!.font = font } }
mit
934c45951a8bdba09cebe36984c7c8c8
32.577778
107
0.613369
4.983509
false
false
false
false
KlubJagiellonski/pola-ios
BuyPolish/Pola/Utilities/Categories/UIViewController+Additions.swift
1
1364
import UIKit extension UIViewController { func addCloseButton() { let closeButtonItem = UIBarButtonItem(image: R.image.closeIcon(), style: .plain, target: self, action: #selector(closeTapped)) closeButtonItem.accessibilityLabel = R.string.localizable.accessibilityClose() closeButtonItem.tintColor = Theme.defaultTextColor navigationItem.rightBarButtonItem = closeButtonItem } @objc private func closeTapped() { dismiss(animated: true, completion: nil) } func showAlert(message: String, dismissHandler: (() -> Void)? = nil) { let alertVC = UIAlertController(title: R.string.localizable.ouch(), message: message, preferredStyle: .alert) alertVC.addAction(UIAlertAction(title: R.string.localizable.dismiss(), style: .destructive, handler: { _ in guard let dismissHandler = dismissHandler else { return } dismissHandler() })) present(alertVC, animated: true, completion: nil) } }
gpl-2.0
69a0183bba5e33af5c1bd79012bf067a
43
116
0.504399
6.526316
false
false
false
false
liufan321/SwiftLearning
基础语法/Swift基础语法.playground/Pages/001-变量和常量.xcplaygroundpage/Contents.swift
1
1408
import Foundation /*: # 常量和变量 ## 定义 * `let` 定义常量,一经赋值不允许再修改 * `var` 定义变量,赋值之后仍然可以修改 * 细节 * 使用 `: 类型`,仅仅只定义类型 * 常量有一次设置的机会 * 应该尽量先选择常量,只有在必须修改时,才需要修改为 `var` */ // 定义常量并且直接设置数值 let x: Int = 10 // 常量数值一经设置,不能修改,以下代码会报错 // x = 30 let y: Int // 常量有一次设置的机会,以下代码没有问题,因为 `y` 还没有被设置数值 y = 10 // 一旦设置之后,则不能再次修改,以下代码会报错,因为 `y` 已经被设置了数值 // y = 50 print(x + y) // 变量设置数值之后,可以继续修改数值 var z: Int z = 100 z = 200 print(x + y + z) /*: ## 自动推导 * Swift 能够根据右边的代码,推导出变量的准确类型 * 只有相同类型的值才能够进行运算 > 注意:Swift 对数据类型要求异常严格,任何时候,都不会做隐式转换 */ // 整数默认的类型是 Int let intValue = 200 // 小数的默认类型是 Double let doubleValue = 10.5 // 如果要对不同类型的数据进行计算,必须要显式的转换 print(intValue + Int(doubleValue)) print(Double(intValue) + doubleValue) //: 有关本示例的许可信息,请参阅:[许可协议](License)
apache-2.0
d56e764450b0eefb19e39b2bcdf1e0f7
13.576923
41
0.66095
2.059783
false
false
false
false
RocketChat/Rocket.Chat.iOS
Rocket.Chat/Views/Chat/New Chat/ChatItems/TextAttachmentChatItem.swift
1
1439
// // TextAttachmentChatItem.swift // Rocket.Chat // // Created by Filipe Alvarenga on 30/09/18. // Copyright © 2018 Rocket.Chat. All rights reserved. // import Foundation import DifferenceKit import RocketChatViewController import RealmSwift final class TextAttachmentChatItem: BaseTextAttachmentChatItem, ChatItem, Differentiable { var relatedReuseIdentifier: String { return hasText ? TextAttachmentCell.identifier : TextAttachmentMessageCell.identifier } let identifier: String let title: String let subtitle: String? let fields: [UnmanagedField] let color: String? let hasText: Bool init( identifier: String, fields: [UnmanagedField], title: String, subtitle: String?, color: String?, collapsed: Bool, hasText: Bool, user: UnmanagedUser?, message: UnmanagedMessage? ) { self.identifier = identifier self.title = title self.subtitle = subtitle self.color = color self.fields = fields self.hasText = hasText super.init( collapsed: collapsed, user: user, message: message ) } var differenceIdentifier: String { return identifier } func isContentEqual(to source: TextAttachmentChatItem) -> Bool { return collapsed == source.collapsed && fields == source.fields } }
mit
24a59259dfbba7ef4e89c304d809e7ac
23.372881
93
0.638387
4.858108
false
false
false
false
shadanan/mado
Antlr4Runtime/Sources/Antlr4/tree/pattern/ParseTreeMatch.swift
1
6190
/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. * Use of this file is governed by the BSD 3-clause license that * can be found in the LICENSE.txt file in the project root. */ /** * Represents the result of matching a {@link org.antlr.v4.runtime.tree.ParseTree} against a tree pattern. */ public class ParseTreeMatch: CustomStringConvertible { /** * This is the backing field for {@link #getTree()}. */ private let tree: ParseTree /** * This is the backing field for {@link #getPattern()}. */ private let pattern: ParseTreePattern /** * This is the backing field for {@link #getLabels()}. */ private let labels: MultiMap<String, ParseTree> /** * This is the backing field for {@link #getMismatchedNode()}. */ private let mismatchedNode: ParseTree? /** * Constructs a new instance of {@link org.antlr.v4.runtime.tree.pattern.ParseTreeMatch} from the specified * parse tree and pattern. * * @param tree The parse tree to match against the pattern. * @param pattern The parse tree pattern. * @param labels A mapping from label names to collections of * {@link org.antlr.v4.runtime.tree.ParseTree} objects located by the tree pattern matching process. * @param mismatchedNode The first node which failed to match the tree * pattern during the matching process. * * @exception IllegalArgumentException if {@code tree} is {@code null} * @exception IllegalArgumentException if {@code pattern} is {@code null} * @exception IllegalArgumentException if {@code labels} is {@code null} */ public init(_ tree: ParseTree, _ pattern: ParseTreePattern, _ labels: MultiMap<String, ParseTree>, _ mismatchedNode: ParseTree?) { self.tree = tree self.pattern = pattern self.labels = labels self.mismatchedNode = mismatchedNode } /** * Get the last node associated with a specific {@code label}. * * <p>For example, for pattern {@code <id:ID>}, {@code get("id")} returns the * node matched for that {@code ID}. If more than one node * matched the specified label, only the last is returned. If there is * no node associated with the label, this returns {@code null}.</p> * * <p>Pattern tags like {@code <ID>} and {@code <expr>} without labels are * considered to be labeled with {@code ID} and {@code expr}, respectively.</p> * * @param label The label to check. * * @return The last {@link org.antlr.v4.runtime.tree.ParseTree} to match a tag with the specified * label, or {@code null} if no parse tree matched a tag with the label. */ public func get(_ label: String) -> ParseTree? { if let parseTrees = labels.get(label) , parseTrees.count > 0 { return parseTrees[parseTrees.count - 1] // return last if multiple } else { return nil } } /** * Return all nodes matching a rule or token tag with the specified label. * * <p>If the {@code label} is the name of a parser rule or token in the * grammar, the resulting list will contain both the parse trees matching * rule or tags explicitly labeled with the label and the complete set of * parse trees matching the labeled and unlabeled tags in the pattern for * the parser rule or token. For example, if {@code label} is {@code "foo"}, * the result will contain <em>all</em> of the following.</p> * * <ul> * <li>Parse tree nodes matching tags of the form {@code <foo:anyRuleName>} and * {@code <foo:AnyTokenName>}.</li> * <li>Parse tree nodes matching tags of the form {@code <anyLabel:foo>}.</li> * <li>Parse tree nodes matching tags of the form {@code <foo>}.</li> * </ul> * * @param label The label. * * @return A collection of all {@link org.antlr.v4.runtime.tree.ParseTree} nodes matching tags with * the specified {@code label}. If no nodes matched the label, an empty list * is returned. */ public func getAll(_ label: String) -> Array<ParseTree> { let nodes: Array<ParseTree>? = labels.get(label) if nodes == nil { return Array<ParseTree>() } return nodes! } /** * Return a mapping from label &rarr; [list of nodes]. * * <p>The map includes special entries corresponding to the names of rules and * tokens referenced in tags in the original pattern. For additional * information, see the description of {@link #getAll(String)}.</p> * * @return A mapping from labels to parse tree nodes. If the parse tree * pattern did not contain any rule or token tags, this map will be empty. */ public func getLabels() -> MultiMap<String, ParseTree> { return labels } /** * Get the node at which we first detected a mismatch. * * @return the node at which we first detected a mismatch, or {@code null} * if the match was successful. */ public func getMismatchedNode() -> ParseTree? { return mismatchedNode } /** * Gets a value indicating whether the match operation succeeded. * * @return {@code true} if the match operation succeeded; otherwise, * {@code false}. */ public func succeeded() -> Bool { return mismatchedNode == nil } /** * Get the tree pattern we are matching against. * * @return The tree pattern we are matching against. */ public func getPattern() -> ParseTreePattern { return pattern } /** * Get the parse tree we are trying to match to a pattern. * * @return The {@link org.antlr.v4.runtime.tree.ParseTree} we are trying to match to a pattern. */ public func getTree() -> ParseTree { return tree } /** * {@inheritDoc} */ public func toString() -> String { return description } public var description: String { let info = succeeded() ? "succeeded" : "failed" return "Match \(info); found \(getLabels().size()) labels" } }
mit
07879108501469ac8370b0e2c64efc75
33.198895
134
0.627787
4.280775
false
false
false
false
gardenm/SavageCanvas
SavageCanvas/SavageCanvas/SmoothInk.swift
1
3843
// // SmoothInk.swift // Drawr // // Created by Matthew Garden on 2016-09-11. // Copyright © 2016 Savagely Optimized. All rights reserved. // import UIKit class SmoothInk: Renderable { let color: UIColor let path: UIBezierPath init(width: CGFloat, color: UIColor, lineCapStyle: CGLineCap) { self.color = color let path = UIBezierPath() path.lineWidth = width path.lineCapStyle = lineCapStyle self.path = path } var bounds: CGRect { return self.path.bounds } func render() { self.color.setStroke() self.path.stroke() } // MARK: - NSCoding required init?(coder aDecoder: NSCoder) { guard let color = aDecoder.decodeObject(forKey: "color") as? UIColor, let path = aDecoder.decodeObject(forKey: "path") as? UIBezierPath else { return nil } self.color = color self.path = path } func encode(with aCoder: NSCoder) { aCoder.encode(self.color, forKey: "color") aCoder.encode(self.path, forKey: "path") } } private extension CGPoint { func midpoint(to other: CGPoint) -> CGPoint { let x = (self.x + other.x) / 2 let y = (self.y + other.y) / 2 return CGPoint(x: x, y: y) } } public class SmoothInkPen: DrawingTool { weak public var delegate: DrawingToolDelegate? var panGestureRecognizer: UIPanGestureRecognizer? var view: UIView? private var previousPoint: CGPoint? private var currentInk: SmoothInk? let color: UIColor let lineCapStyle: CGLineCap let width: CGFloat public init(color: UIColor, width: CGFloat, lineCapStyle: CGLineCap) { self.color = color self.lineCapStyle = lineCapStyle self.width = width } func update(ink: SmoothInk) { let path = ink.path let inset = -(path.lineWidth / 2) let bounds = path.bounds.insetBy(dx: inset, dy: inset) self.delegate?.drawingTool(self, didUpdateRenderable: ink, in: bounds) } @objc func pan(recognizer: UIGestureRecognizer) { guard let view = self.view else { return } let point = recognizer.location(in: view) if recognizer.state == .began { let ink = SmoothInk(width: self.width, color: self.color, lineCapStyle: self.lineCapStyle) ink.path.move(to: point) self.delegate?.drawingTool(self, didAddRenderable: ink) self.currentInk = ink } else if recognizer.state == .changed, let path = self.currentInk?.path, let previousPoint = self.previousPoint { let newPoint = point.midpoint(to: previousPoint) path.addQuadCurve(to: newPoint, controlPoint: previousPoint) } else if [.ended, .cancelled, .failed].contains(recognizer.state) { self.currentInk = nil return } self.previousPoint = point if let ink = self.currentInk { self.update(ink: ink) } } // MARK: - DrawingTool public func addTo(view: UIView) { let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(pan(recognizer:))) view.addGestureRecognizer(panGestureRecognizer) self.panGestureRecognizer = panGestureRecognizer self.view = view } public func removeFromView() { guard let panGestureRecognizer = self.panGestureRecognizer else { return } self.view?.removeGestureRecognizer(panGestureRecognizer) self.panGestureRecognizer = nil } }
mit
7506f99dbd2f121138bd2746b67ba073
25.680556
122
0.584591
4.719902
false
false
false
false
lieonCX/Hospital
Hospital/Hospital/View/News/ImagePickerVC.swift
1
5497
// // ImagePickerVC.swift // Hospital // // Created by lieon on 2017/5/16. // Copyright © 2017年 ChangHongCloudTechService. All rights reserved. // import UIKit import RxCocoa import RxSwift class ImagePickerVC: BaseViewController { @IBOutlet var imageView: UIImageView! @IBOutlet var cameraButton: UIButton! @IBOutlet var galleryButton: UIButton! @IBOutlet var cropButton: UIButton! override func viewDidLoad() { super.viewDidLoad() cameraButton.isEnabled = UIImagePickerController.isSourceTypeAvailable(.camera) cameraButton.rx.tap.asObservable() .flatMapLatest { [weak self] _ in return UIImagePickerController.rx.createWithParent(parent: self, animated: true, configureImagePicker: { imagePicker in imagePicker.sourceType = .camera imagePicker.allowsEditing = false }).flatMap{ $0.rx.didFinishPickingMediaWithInfo} /// 取第一个元素 .take(1) } .map { info in return info[UIImagePickerControllerOriginalImage] as? UIImage } .bind(to: imageView.rx.image) .disposed(by: disposeBag) galleryButton.rx.tap.asObservable() .flatMapLatest { [weak self] _ in return UIImagePickerController.rx.createWithParent(parent: self, animated: true, configureImagePicker: { ( imagePicker: UIImagePickerController) in imagePicker.sourceType = .photoLibrary imagePicker.allowsEditing = false }) .flatMap { $0.rx.didFinishPickingMediaWithInfo} .take(1) } .map { info in return info[UIImagePickerControllerOriginalImage] as? UIImage } .bind(to: imageView.rx.image) .disposed(by: disposeBag ) cropButton.rx.tap.asObservable() .flatMapLatest { [weak self] _ in return UIImagePickerController.rx.createWithParent(parent: self, animated: true, configureImagePicker: { imagePicker in imagePicker.allowsEditing = true imagePicker.sourceType = .photoLibrary }).flatMap {$0.rx.didFinishPickingMediaWithInfo} .take(1) } .map { info in return info[UIImagePickerControllerOriginalImage] as? UIImage } .bind(to: imageView.rx.image) .disposed(by: disposeBag) } } extension Reactive where Base: UIImagePickerController { /// 创建一个 相机 序列 static func createWithParent(parent: UIViewController?, animated: Bool = true, configureImagePicker: @escaping (UIImagePickerController) throws -> () = { x in }) -> Observable<UIImagePickerController> { return Observable.create({ [weak parent] observer in let imagePicker = UIImagePickerController() let dismissDisposeabele = imagePicker.rx .didCancel .subscribe(onNext: { [weak imagePicker] in guard let imagePicker = imagePicker else { return } self.dismissViewController(imagePicker, animated: animated) }) do { try configureImagePicker(imagePicker) } catch let error { observer.on(.error(error)) return Disposables.create() } guard let parent = parent else { observer.on(.completed) return Disposables.create() } parent.present(imagePicker, animated: animated, completion: nil) observer.on(.next(imagePicker)) return Disposables.create(dismissDisposeabele, Disposables.create { dismissViewController(imagePicker, animated: animated) }) }) } private static func dismissViewController(_ viewController: UIViewController, animated: Bool) { if viewController.isBeingDismissed || viewController.isBeingPresented { DispatchQueue.main.async { dismissViewController(viewController, animated: animated) } return } if viewController.presentingViewController != nil { viewController.dismiss(animated: animated, completion: nil) } } } extension Reactive where Base: UIImagePickerController { /** Reactive wrapper for `delegate` message. */ public var didFinishPickingMediaWithInfo: Observable<[String : AnyObject]> { return delegate /// 监听方法是否都调用 .methodInvoked(#selector(UIImagePickerControllerDelegate.imagePickerController(_:didFinishPickingMediaWithInfo:))) .map({ (a) in return try self.castOrThrow(Dictionary<String, AnyObject>.self, a[1]) }) } /** Reactive wrapper for `delegate` message. */ public var didCancel: Observable<()> { return delegate .methodInvoked(#selector(UIImagePickerControllerDelegate.imagePickerControllerDidCancel(_:))) .map {_ in () } } fileprivate func castOrThrow<T>(_ resultType: T.Type, _ object: Any) throws -> T { guard let returnValue = object as? T else { throw RxCocoaError.castingError(object: object, targetType: resultType) } return returnValue } }
mit
d66629382000dc9767e95f77cd2b6d4d
36.315068
206
0.607379
5.645596
false
false
false
false
mrdepth/Neocom
Legacy/Neocom/Neocom/CachedValue.swift
2
17889
// // CachedValue.swift // Neocom // // Created by Artem Shimanski on 24.08.2018. // Copyright © 2018 Artem Shimanski. All rights reserved. // import Foundation import CloudData import CoreData protocol CachedValueProtocol: class { associatedtype Value var value: Value {get set} var cachedUntil: Date? {get set} var observer: APIObserver<Self>? {get} } final class CachedValue<Value>: CachedValueProtocol { var value: Value var cachedUntil: Date? let observer: APIObserver<CachedValue<Value>>? init(value: Value, cachedUntil: Date?, observer: APIObserver<CachedValue<Value>>?) { self.value = value self.cachedUntil = cachedUntil self.observer = observer observer?.cachedValue = self } func map<T>(_ transform: @escaping (Value) throws -> T ) rethrows -> CachedValue<T> { return try CachedValue<T>(value: transform(value), cachedUntil: cachedUntil, observer: observer?.map(transform)) } } class APIObserver<Value: CachedValueProtocol> { var handler: ((Value) -> Void)? weak var cachedValue: Value? func map<T>(_ transform: @escaping (Value.Value) throws -> T ) -> APIObserverMap<CachedValue<T>, Value> { return APIObserverMap(self, transform: transform) } func notify(newValue: Value.Value, cachedUntil: Date?) { if let handler = handler, let cachedValue = cachedValue { cachedValue.value = newValue cachedValue.cachedUntil = cachedUntil handler(cachedValue) } } } class APICacheRecordObserver<Value: CachedValueProtocol>: APIObserver<Value> where Value.Value: Codable { let recordID: NSManagedObjectID? let dataID: NSManagedObjectID? let cache: Cache init(cacheRecord: CacheRecord, cache: Cache) { self.cache = cache recordID = cacheRecord.objectID dataID = cacheRecord.data?.objectID } override var handler: ((Value) -> Void)? { didSet { if observer == nil { observer = NotificationCenter.default.addNotificationObserver(forName: .NSManagedObjectContextDidSave, object: nil, queue: nil, using: { [weak self] note in self?.didSave(note) }) } } } private var observer: NotificationObserver? private func didSave(_ note: Notification) { guard let objectIDs = (note.userInfo?[NSUpdatedObjectsKey] as? NSSet)?.compactMap ({ ($0 as? NSManagedObject)?.objectID ?? $0 as? NSManagedObjectID }) else {return} guard !Set(objectIDs).intersection([recordID, dataID].compactMap{$0}).isEmpty else {return} cache.performBackgroundTask { context -> Void in guard let recordID = self.recordID else {return} guard let record: CacheRecord = (try? context.existingObject(with: recordID)) ?? nil else {return} guard let value: Value.Value = record.getValue() else {return} self.notify(newValue: value, cachedUntil: record.cachedUntil) } } } class APIObserverMap<Value: CachedValueProtocol, Base: CachedValueProtocol>: APIObserver<Value> { let base: APIObserver<Base> let transform: (Base.Value) throws -> Value.Value override var handler: ((Value) -> Void)? { didSet { if handler == nil { base.handler = nil } else { base.handler = { [weak self] newValue in guard let strongSelf = self else {return} try? strongSelf.notify(newValue: strongSelf.transform(newValue.value), cachedUntil: newValue.cachedUntil) } } } } init(_ base: APIObserver<Base>, transform: @escaping (Base.Value) throws -> Value.Value ) { self.base = base self.transform = transform super.init() } } func all<R, A, B>(_ a: CachedValue<A>, _ b: CachedValue<B>) -> Join2<R, A, B> { return Join2(a: a, b: b) } func all<R, A, B, C>(_ a: CachedValue<A>, _ b: CachedValue<B>, _ c: CachedValue<C>) -> Join3<R, A, B, C> { return Join3(a: a, b: b, c: c) } func all<R, A, B, C, D>(_ a: CachedValue<A>, _ b: CachedValue<B>, _ c: CachedValue<C>, _ d: CachedValue<D>) -> Join4<R, A, B, C, D> { return Join4(a: a, b: b, c: c, d: d) } func all<R, A, B, C, D, E>(_ a: CachedValue<A>, _ b: CachedValue<B>, _ c: CachedValue<C>, _ d: CachedValue<D>, _ e: CachedValue<E>) -> Join5<R, A, B, C, D, E> { return Join5(a: a, b: b, c: c, d: d, e: e) } func all<R, A, B, C, D, E, F>(_ a: CachedValue<A>, _ b: CachedValue<B>, _ c: CachedValue<C>, _ d: CachedValue<D>, _ e: CachedValue<E>, _ f: CachedValue<F>) -> Join6<R, A, B, C, D, E, F> { return Join6(a: a, b: b, c: c, d: d, e: e, f: f) } func all<R, A, B>(_ values: (CachedValue<A>, CachedValue<B>)) -> Join2<R, A, B> { return Join2(a: values.0, b: values.1) } func all<R, A, B, C>(_ values: (CachedValue<A>, CachedValue<B>, CachedValue<C>)) -> Join3<R, A, B, C> { return Join3(a: values.0, b: values.1, c: values.2) } func all<R, A, B, C, D>(_ values: (CachedValue<A>, CachedValue<B>, CachedValue<C>, CachedValue<D>)) -> Join4<R, A, B, C, D> { return Join4(a: values.0, b: values.1, c: values.2, d: values.3) } func all<R, A, B, C, D, E>(_ values: (CachedValue<A>, CachedValue<B>, CachedValue<C>, CachedValue<D>, CachedValue<E>)) -> Join5<R, A, B, C, D, E> { return Join5(a: values.0, b: values.1, c: values.2, d: values.3, e: values.4) } func all<R, A, B, C, D, E, F>(_ values: (CachedValue<A>, CachedValue<B>, CachedValue<C>, CachedValue<D>, CachedValue<E>, CachedValue<F>)) -> Join6<R, A, B, C, D, E, F> { return Join6(a: values.0, b: values.1, c: values.2, d: values.3, e: values.4, f: values.5) } struct Join2<R, A, B> { var a: CachedValue<A> var b: CachedValue<B> func map(_ transform: @escaping (A, B) -> R) -> CachedValue<R> { let cachedUntil = [a.cachedUntil, b.cachedUntil].compactMap{$0}.min() let value = transform(a.value, b.value) let observer = APIObserverJoin<CachedValue<R>>(values: [AnyCachedValue(a), AnyCachedValue(b)]) {transform($0[0] as! A, $0[1] as! B)} return CachedValue(value: value, cachedUntil: cachedUntil, observer: observer) } } struct Join3<R, A, B, C> { var a: CachedValue<A> var b: CachedValue<B> var c: CachedValue<C> func map(_ transform: @escaping (A, B, C) -> R) -> CachedValue<R> { let cachedUntil = [a.cachedUntil, b.cachedUntil, c.cachedUntil].compactMap{$0}.min() let value = transform(a.value, b.value, c.value) let observer = APIObserverJoin<CachedValue<R>>(values: [AnyCachedValue(a), AnyCachedValue(b), AnyCachedValue(c)]) {transform($0[0] as! A, $0[1] as! B, $0[2] as! C)} return CachedValue(value: value, cachedUntil: cachedUntil, observer: observer) } } struct Join4<R, A, B, C, D> { var a: CachedValue<A> var b: CachedValue<B> var c: CachedValue<C> var d: CachedValue<D> func map(_ transform: @escaping (A, B, C, D) -> R) -> CachedValue<R> { let cachedUntil = [a.cachedUntil, b.cachedUntil, c.cachedUntil, d.cachedUntil].compactMap{$0}.min() let value = transform(a.value, b.value, c.value, d.value) let observer = APIObserverJoin<CachedValue<R>>(values: [AnyCachedValue(a), AnyCachedValue(b), AnyCachedValue(c), AnyCachedValue(d)]) {transform($0[0] as! A, $0[1] as! B, $0[2] as! C, $0[3] as! D)} return CachedValue(value: value, cachedUntil: cachedUntil, observer: observer) } } struct Join5<R, A, B, C, D, E> { var a: CachedValue<A> var b: CachedValue<B> var c: CachedValue<C> var d: CachedValue<D> var e: CachedValue<E> func map(_ transform: @escaping (A, B, C, D, E) -> R) -> CachedValue<R> { let cachedUntil = [a.cachedUntil, b.cachedUntil, c.cachedUntil, d.cachedUntil, e.cachedUntil].compactMap{$0}.min() let value = transform(a.value, b.value, c.value, d.value, e.value) let observer = APIObserverJoin<CachedValue<R>>(values: [AnyCachedValue(a), AnyCachedValue(b), AnyCachedValue(c), AnyCachedValue(d), AnyCachedValue(e)]) {transform($0[0] as! A, $0[1] as! B, $0[2] as! C, $0[3] as! D, $0[4] as! E)} return CachedValue(value: value, cachedUntil: cachedUntil, observer: observer) } } struct Join6<R, A, B, C, D, E, F> { var a: CachedValue<A> var b: CachedValue<B> var c: CachedValue<C> var d: CachedValue<D> var e: CachedValue<E> var f: CachedValue<F> func map(_ transform: @escaping (A, B, C, D, E, F) -> R) -> CachedValue<R> { let cachedUntil = [a.cachedUntil, b.cachedUntil, c.cachedUntil, d.cachedUntil, e.cachedUntil, f.cachedUntil].compactMap{$0}.min() let value = transform(a.value, b.value, c.value, d.value, e.value, f.value) let observer = APIObserverJoin<CachedValue<R>>(values: [AnyCachedValue(a), AnyCachedValue(b), AnyCachedValue(c), AnyCachedValue(d), AnyCachedValue(e), AnyCachedValue(f)]) {transform($0[0] as! A, $0[1] as! B, $0[2] as! C, $0[3] as! D, $0[4] as! E, $0[5] as! F)} return CachedValue(value: value, cachedUntil: cachedUntil, observer: observer) } } protocol CachedValueBox { func setHandler(_ handler: ((AnyCachedValue) -> Void)?) func unbox<T: CachedValueProtocol>() -> T? var cachedUntil: Date? {get} var value: Any {get} } struct ConcreteCachedValueBox<Base: CachedValueProtocol>: CachedValueBox { var base: Base func setHandler(_ handler: ((AnyCachedValue) -> Void)?) { if let handler = handler { base.observer?.handler = { newValue in handler(AnyCachedValue(newValue)) } } else { base.observer?.handler = nil } } func unbox<T: CachedValueProtocol>() -> T? { return base as? T } var cachedUntil: Date? { return base.cachedUntil } var value: Any { return base.value } } struct AnyCachedValue { fileprivate var box: CachedValueBox var cachedUntil: Date? { return box.cachedUntil } var value: Any { return box.value } init<T: CachedValueProtocol>(_ base: T) { box = ConcreteCachedValueBox(base: base) } func setHandler(_ handler: ((AnyCachedValue) -> Void)?) { box.setHandler(handler) } } class APIObserverJoin<Value: CachedValueProtocol>: APIObserver<Value> { var values: [AnyCachedValue] let transform: ([Any]) -> Value.Value init(values: [AnyCachedValue], transform: @escaping ([Any]) -> Value.Value ) { self.values = values self.transform = transform } override var handler: ((Value) -> Void)? { didSet { if handler == nil { for value in values { value.setHandler(nil) } } else { for value in values { value.setHandler { [weak self] newValue in self?.notify() } } } } } func notify() { notify(newValue: transform(values.map{$0.value}), cachedUntil: values.compactMap{$0.cachedUntil}.min()) } } func all<R, A, B>(_ a: CachedValue<A>?, _ b: CachedValue<B>?) -> OptionalJoin2<R, A, B> { return OptionalJoin2(a: a, b: b) } func all<R, A, B, C>(_ a: CachedValue<A>?, _ b: CachedValue<B>?, _ c: CachedValue<C>?) -> OptionalJoin3<R, A, B, C> { return OptionalJoin3(a: a, b: b, c: c) } func all<R, A, B, C, D>(_ a: CachedValue<A>?, _ b: CachedValue<B>?, _ c: CachedValue<C>?, _ d: CachedValue<D>?) -> OptionalJoin4<R, A, B, C, D> { return OptionalJoin4(a: a, b: b, c: c, d: d) } func all<R, A, B, C, D, E>(_ a: CachedValue<A>?, _ b: CachedValue<B>?, _ c: CachedValue<C>?, _ d: CachedValue<D>?, _ e: CachedValue<E>?) -> OptionalJoin5<R, A, B, C, D, E> { return OptionalJoin5(a: a, b: b, c: c, d: d, e: e) } func all<R, A, B, C, D, E, F>(_ a: CachedValue<A>?, _ b: CachedValue<B>?, _ c: CachedValue<C>?, _ d: CachedValue<D>?, _ e: CachedValue<E>?, _ f: CachedValue<F>?) -> OptionalJoin6<R, A, B, C, D, E, F> { return OptionalJoin6(a: a, b: b, c: c, d: d, e: e, f: f) } func all<R, A, B>(_ values: (CachedValue<A>?, CachedValue<B>?)) -> OptionalJoin2<R, A, B> { return OptionalJoin2(a: values.0, b: values.1) } func all<R, A, B, C>(_ values: (CachedValue<A>?, CachedValue<B>?, CachedValue<C>?)) -> OptionalJoin3<R, A, B, C> { return OptionalJoin3(a: values.0, b: values.1, c: values.2) } func all<R, A, B, C, D>(_ values: (CachedValue<A>?, CachedValue<B>?, CachedValue<C>?, CachedValue<D>?)) -> OptionalJoin4<R, A, B, C, D> { return OptionalJoin4(a: values.0, b: values.1, c: values.2, d: values.3) } func all<R, A, B, C, D, E>(_ values: (CachedValue<A>?, CachedValue<B>?, CachedValue<C>?, CachedValue<D>?, CachedValue<E>?)) -> OptionalJoin5<R, A, B, C, D, E> { return OptionalJoin5(a: values.0, b: values.1, c: values.2, d: values.3, e: values.4) } func all<R, A, B, C, D, E, F>(_ values: (CachedValue<A>?, CachedValue<B>?, CachedValue<C>?, CachedValue<D>?, CachedValue<E>?, CachedValue<F>?)) -> OptionalJoin6<R, A, B, C, D, E, F> { return OptionalJoin6(a: values.0, b: values.1, c: values.2, d: values.3, e: values.4, f: values.5) } struct OptionalJoin2<R, A, B> { var a: CachedValue<A>? var b: CachedValue<B>? func map(_ transform: @escaping (A?, B?) -> R) -> CachedValue<R> { let cachedUntil = [a?.cachedUntil, b?.cachedUntil].compactMap{$0}.min() let value = transform(a?.value, b?.value) let observer = APIObserverOptionalJoin<CachedValue<R>>(values: [a.map {AnyCachedValue($0)}, b.map {AnyCachedValue($0)}]) {transform($0[0] as? A, $0[1] as? B)} return CachedValue(value: value, cachedUntil: cachedUntil, observer: observer) } } struct OptionalJoin3<R, A, B, C> { var a: CachedValue<A>? var b: CachedValue<B>? var c: CachedValue<C>? func map(_ transform: @escaping (A?, B?, C?) -> R) -> CachedValue<R> { let cachedUntil = [a?.cachedUntil, b?.cachedUntil, c?.cachedUntil].compactMap{$0}.min() let value = transform(a?.value, b?.value, c?.value) let observer = APIObserverOptionalJoin<CachedValue<R>>(values: [a.map {AnyCachedValue($0)}, b.map {AnyCachedValue($0)}, c.map {AnyCachedValue($0)}]) {transform($0[0] as? A, $0[1] as? B, $0[2] as? C)} return CachedValue(value: value, cachedUntil: cachedUntil, observer: observer) } } struct OptionalJoin4<R, A, B, C, D> { var a: CachedValue<A>? var b: CachedValue<B>? var c: CachedValue<C>? var d: CachedValue<D>? func map(_ transform: @escaping (A?, B?, C?, D?) -> R) -> CachedValue<R> { let cachedUntil = [a?.cachedUntil, b?.cachedUntil, c?.cachedUntil, d?.cachedUntil].compactMap{$0}.min() let value = transform(a?.value, b?.value, c?.value, d?.value) let observer = APIObserverOptionalJoin<CachedValue<R>>(values: [a.map {AnyCachedValue($0)}, b.map {AnyCachedValue($0)}, c.map {AnyCachedValue($0)}, d.map {AnyCachedValue($0)}]) {transform($0[0] as? A, $0[1] as? B, $0[2] as? C, $0[3] as? D)} return CachedValue(value: value, cachedUntil: cachedUntil, observer: observer) } } struct OptionalJoin5<R, A, B, C, D, E> { var a: CachedValue<A>? var b: CachedValue<B>? var c: CachedValue<C>? var d: CachedValue<D>? var e: CachedValue<E>? func map(_ transform: @escaping (A?, B?, C?, D?, E?) -> R) -> CachedValue<R> { let cachedUntil = [a?.cachedUntil, b?.cachedUntil, c?.cachedUntil, d?.cachedUntil, e?.cachedUntil].compactMap{$0}.min() let value = transform(a?.value, b?.value, c?.value, d?.value, e?.value) let observer = APIObserverOptionalJoin<CachedValue<R>>(values: [a.map {AnyCachedValue($0)}, b.map {AnyCachedValue($0)}, c.map {AnyCachedValue($0)}, d.map {AnyCachedValue($0)}, e.map {AnyCachedValue($0)}]) {transform($0[0] as? A, $0[1] as? B, $0[2] as? C, $0[3] as? D, $0[4] as? E)} return CachedValue(value: value, cachedUntil: cachedUntil, observer: observer) } } struct OptionalJoin6<R, A, B, C, D, E, F> { var a: CachedValue<A>? var b: CachedValue<B>? var c: CachedValue<C>? var d: CachedValue<D>? var e: CachedValue<E>? var f: CachedValue<F>? func map(_ transform: @escaping (A?, B?, C?, D?, E?, F?) -> R) -> CachedValue<R> { let cachedUntil = [a?.cachedUntil, b?.cachedUntil, c?.cachedUntil, d?.cachedUntil, e?.cachedUntil, f?.cachedUntil].compactMap{$0}.min() let value = transform(a?.value, b?.value, c?.value, d?.value, e?.value, f?.value) let observer = APIObserverOptionalJoin<CachedValue<R>>(values: [a.map {AnyCachedValue($0)}, b.map {AnyCachedValue($0)}, c.map {AnyCachedValue($0)}, d.map {AnyCachedValue($0)}, e.map {AnyCachedValue($0)}, f.map {AnyCachedValue($0)},]) {transform($0[0] as? A, $0[1] as? B, $0[2] as? C, $0[3] as? D, $0[4] as? E, $0[5] as? F)} return CachedValue(value: value, cachedUntil: cachedUntil, observer: observer) } } class APIObserverOptionalJoin<Value: CachedValueProtocol>: APIObserver<Value> { var values: [AnyCachedValue?] let transform: ([Any?]) -> Value.Value? init(values: [AnyCachedValue?], transform: @escaping ([Any?]) -> Value.Value? ) { self.values = values self.transform = transform } override var handler: ((Value) -> Void)? { didSet { if handler == nil { for value in values { value?.setHandler(nil) } } else { for value in values { value?.setHandler { [weak self] newValue in self?.notify() } } } } } func notify() { guard let value = transform(values.map{$0?.value}) else {return} notify(newValue: value, cachedUntil: values.compactMap{$0?.cachedUntil}.min()) } }
lgpl-2.1
8df2540c280369d05bd835ec8ba05ae5
33.801556
201
0.606384
3.024687
false
false
false
false
Higgcz/Buildasaur
BuildaKit/Project.swift
1
6906
// // Project.swift // Buildasaur // // Created by Honza Dvorsky on 14/02/2015. // Copyright (c) 2015 Honza Dvorsky. All rights reserved. // import Foundation import BuildaUtils import XcodeServerSDK public class Project : JSONSerializable { public var url: NSURL { didSet { do { try self.refreshMetadata() } catch {} } } public var preferredTemplateId: String? public var githubToken: String? public var privateSSHKeyUrl: NSURL? public var publicSSHKeyUrl: NSURL? public var sshPassphrase: String? public var privateSSHKey: String? { return self.getContentsOfKeyAtUrl(self.privateSSHKeyUrl) } public var publicSSHKey: String? { return self.getContentsOfKeyAtUrl(self.publicSSHKeyUrl) } public var availabilityState: AvailabilityCheckState private(set) public var workspaceMetadata: WorkspaceMetadata? public init?(url: NSURL) { self.url = url self.preferredTemplateId = nil self.githubToken = nil self.availabilityState = .Unchecked self.publicSSHKeyUrl = nil self.privateSSHKeyUrl = nil self.sshPassphrase = nil do { try self.refreshMetadata() } catch { Log.error(error) return nil } } private init(original: Project, forkOriginURL: String) throws { self.url = original.url self.preferredTemplateId = original.preferredTemplateId self.githubToken = original.githubToken self.availabilityState = original.availabilityState self.publicSSHKeyUrl = original.publicSSHKeyUrl self.privateSSHKeyUrl = original.privateSSHKeyUrl self.sshPassphrase = original.sshPassphrase self.workspaceMetadata = try original.workspaceMetadata?.duplicateWithForkURL(forkOriginURL) } public func duplicateForForkAtOriginURL(forkURL: String) throws -> Project { return try Project(original: self, forkOriginURL: forkURL) } public class func attemptToParseFromUrl(url: NSURL) throws -> WorkspaceMetadata { return try Project.loadWorkspaceMetadata(url) } private func refreshMetadata() throws { let meta = try Project.attemptToParseFromUrl(self.url) self.workspaceMetadata = meta } public required init?(json: NSDictionary) { self.availabilityState = .Unchecked if let urlString = json.optionalStringForKey("url"), let url = NSURL(string: urlString) { self.url = url self.preferredTemplateId = json.optionalStringForKey("preferred_template_id") self.githubToken = json.optionalStringForKey("github_token") if let publicKeyUrl = json.optionalStringForKey("ssh_public_key_url") { self.publicSSHKeyUrl = NSURL(string: publicKeyUrl) } else { self.publicSSHKeyUrl = nil } if let privateKeyUrl = json.optionalStringForKey("ssh_private_key_url") { self.privateSSHKeyUrl = NSURL(string: privateKeyUrl) } else { self.privateSSHKeyUrl = nil } self.sshPassphrase = json.optionalStringForKey("ssh_passphrase") do { try self.refreshMetadata() } catch { Log.error("Error parsing: \(error)") return nil } } else { self.url = NSURL() self.preferredTemplateId = nil self.githubToken = nil self.publicSSHKeyUrl = nil self.privateSSHKeyUrl = nil self.sshPassphrase = nil self.workspaceMetadata = nil return nil } } public init() { self.availabilityState = .Unchecked self.url = NSURL() self.preferredTemplateId = nil self.githubToken = nil self.publicSSHKeyUrl = nil self.privateSSHKeyUrl = nil self.sshPassphrase = nil self.workspaceMetadata = nil } public func jsonify() -> NSDictionary { let json = NSMutableDictionary() json["url"] = self.url.absoluteString json.optionallyAddValueForKey(self.preferredTemplateId, key: "preferred_template_id") json.optionallyAddValueForKey(self.githubToken, key: "github_token") json.optionallyAddValueForKey(self.publicSSHKeyUrl?.absoluteString, key: "ssh_public_key_url") json.optionallyAddValueForKey(self.privateSSHKeyUrl?.absoluteString, key: "ssh_private_key_url") json.optionallyAddValueForKey(self.sshPassphrase, key: "ssh_passphrase") return json } public func schemes() -> [XcodeScheme] { let schemes = XcodeProjectParser.sharedSchemesFromProjectOrWorkspaceUrl(self.url) return schemes } private class func loadWorkspaceMetadata(url: NSURL) throws -> WorkspaceMetadata { return try XcodeProjectParser.parseRepoMetadataFromProjectOrWorkspaceURL(url) } public func githubRepoName() -> String? { if let projectUrl = self.workspaceMetadata?.projectURL { let originalStringUrl = projectUrl.absoluteString let stringUrl = originalStringUrl.lowercaseString /* both https and ssh repos on github have a form of: {https://|git@}github.com{:|/}organization/repo.git here I need the organization/repo bit, which I'll do by finding "github.com" and shifting right by one and scan up until ".git" */ if let githubRange = stringUrl.rangeOfString("github.com", options: NSStringCompareOptions(), range: nil, locale: nil), let dotGitRange = stringUrl.rangeOfString(".git", options: NSStringCompareOptions.BackwardsSearch, range: nil, locale: nil) { let start = githubRange.endIndex.advancedBy(1) let end = dotGitRange.startIndex let repoName = originalStringUrl.substringWithRange(Range<String.Index>(start: start, end: end)) return repoName } } return nil } private func getContentsOfKeyAtUrl(url: NSURL?) -> String? { if let url = url { do { let key = try NSString(contentsOfURL: url, encoding: NSASCIIStringEncoding) return key as String } catch { Log.error("Couldn't load key at url \(url) with error \(error)") } return nil } Log.error("Couldn't load key at nil url") return nil } }
mit
dfc9e2f6175974e9956a0e06cc194db7
34.055838
141
0.605271
5.115556
false
false
false
false
ikesyo/Runes
Tests/Tests/OptionalSpec.swift
5
3943
import SwiftCheck import XCTest import Runes class OptionalSpec: XCTestCase { func testFunctor() { // fmap id = id property("identity law") <- forAll { (x: Int?) in let lhs = id <^> x let rhs = x return lhs == rhs } // fmap (f . g) = (fmap f) . (fmap g) property("function composition law") <- forAll { (o: OptionalOf<Int>, fa: ArrowOf<Int, Int>, fb: ArrowOf<Int, Int>) in let f = fa.getArrow let g = fb.getArrow let x = o.getOptional let lhs = f • g <^> x let rhs = (curry(<^>)(f) • curry(<^>)(g))(x) return lhs == rhs } } func testApplicative() { // pure id <*> v = v property("identity law") <- forAll { (x: Int?) in let lhs = pure(id) <*> x let rhs = x return lhs == rhs } // pure f <*> pure x = pure (f x) property("homomorphism law") <- forAll { (x: Int, fa: ArrowOf<Int, Int>) in let f = fa.getArrow let lhs: Int? = pure(f) <*> pure(x) let rhs: Int? = pure(f(x)) return rhs == lhs } // f <*> pure x = pure ($ x) <*> f property("interchange law") <- forAll { (x: Int, fa: OptionalOf<ArrowOf<Int, Int>>) in let f = fa.getOptional?.getArrow let lhs = f <*> pure(x) let rhs = pure({ $0(x) }) <*> f return lhs == rhs } // f <*> (g <*> x) = pure (.) <*> f <*> g <*> x property("composition law") <- forAll { (o: OptionalOf<Int>, fa: OptionalOf<ArrowOf<Int, Int>>, fb: OptionalOf<ArrowOf<Int, Int>>) in let x = o.getOptional let f = fa.getOptional?.getArrow let g = fb.getOptional?.getArrow let lhs = f <*> (g <*> x) let rhs = pure(curry(•)) <*> f <*> g <*> x return lhs == rhs } } func testMonad() { // return x >>= f = f x property("left identity law") <- forAll { (x: Int, fa: ArrowOf<Int, Int>) in let f: Int -> Int? = pure • fa.getArrow let lhs = pure(x) >>- f let rhs = f(x) return lhs == rhs } // m >>= return = m property("right identity law") <- forAll { (o: OptionalOf<Int>) in let x = o.getOptional let lhs = x >>- pure let rhs = x return lhs == rhs } // (m >>= f) >>= g = m >>= (\x -> f x >>= g) property("associativity law") <- forAll { (o: OptionalOf<Int>, fa: ArrowOf<Int, Int>, fb: ArrowOf<Int, Int>) in let m = o.getOptional let f: Int -> Int? = pure • fa.getArrow let g: Int -> Int? = pure • fb.getArrow let lhs = (m >>- f) >>- g let rhs = m >>- { x in f(x) >>- g } return lhs == rhs } // (f >=> g) >=> h = f >=> (g >=> h) property("left-to-right Kleisli composition of monads") <- forAll { (x: Int, fa: ArrowOf<Int, Int>, fb: ArrowOf<Int, Int>, fc: ArrowOf<Int, Int>) in let f: Int -> Int? = pure • fa.getArrow let g: Int -> Int? = pure • fb.getArrow let h: Int -> Int? = pure • fc.getArrow let lhs = (f >-> g) >-> h let rhs = f >-> (g >-> h) return lhs(x) == rhs(x) } // (f <=< g) <=< h = f <=< (g <=< h) property("right-to-left Kleisli composition of monads") <- forAll { (x: Int, fa: ArrowOf<Int, Int>, fb: ArrowOf<Int, Int>, fc: ArrowOf<Int, Int>) in let f: Int -> Int? = pure • fa.getArrow let g: Int -> Int? = pure • fb.getArrow let h: Int -> Int? = pure • fc.getArrow let lhs = (f <-< g) <-< h let rhs = f <-< (g <-< h) return lhs(x) == rhs(x) } } }
mit
ce9393eda76d7bc4def5e80310a6d69a
29.858268
156
0.439653
3.679812
false
false
false
false
hackersatcambridge/hac-website
Sources/HaCWebsiteLib/Controllers/LandingUpdateFeedController.swift
1
1186
import Foundation import Kitura import HaCTML import LoggerAPI import HeliumLogger import DotEnv import SwiftyJSON import LoggerAPI struct LandingUpdateFeedController { static let videos = [ PostCard( title: "Partial Recursive Functions 1: Functions", category: .video, description: "Learn all the things.", backgroundColor: "#852503", imageURL: Assets.publicPath("/images/functions_frame.png") ), PostCard( title: "TCP Throughput", category: .video, description: "Learn all the things.", backgroundColor: "green", imageURL: Assets.publicPath("/images/workshop.jpg") ) ] static var handler: RouterHandler = { request, response, next in let fromDate : Date = Date.from(string: request.queryParameters["fromDate"]) ?? Date() let toDate : Date = Date.from(string: request.queryParameters["toDate"]) ?? Date() let eventPostCards : [PostCard] = EventServer.getEvents(from: fromDate, to: toDate).flatMap{ event in event.postCardRepresentation } let updates = eventPostCards + videos try response.send( LandingUpdateFeed(updates: updates).node.render() ).end() } }
mit
3abcc616dd27903875e2aa5a3629e841
27.926829
105
0.688027
4.344322
false
false
false
false
aschwaighofer/swift
stdlib/public/core/FloatingPoint.swift
1
84884
//===--- FloatingPoint.swift ----------------------------------*- swift -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// A floating-point numeric type. /// /// Floating-point types are used to represent fractional numbers, like 5.5, /// 100.0, or 3.14159274. Each floating-point type has its own possible range /// and precision. The floating-point types in the standard library are /// `Float`, `Double`, and `Float80` where available. /// /// Create new instances of floating-point types using integer or /// floating-point literals. For example: /// /// let temperature = 33.2 /// let recordHigh = 37.5 /// /// The `FloatingPoint` protocol declares common arithmetic operations, so you /// can write functions and algorithms that work on any floating-point type. /// The following example declares a function that calculates the length of /// the hypotenuse of a right triangle given its two perpendicular sides. /// Because the `hypotenuse(_:_:)` function uses a generic parameter /// constrained to the `FloatingPoint` protocol, you can call it using any /// floating-point type. /// /// func hypotenuse<T: FloatingPoint>(_ a: T, _ b: T) -> T { /// return (a * a + b * b).squareRoot() /// } /// /// let (dx, dy) = (3.0, 4.0) /// let distance = hypotenuse(dx, dy) /// // distance == 5.0 /// /// Floating-point values are represented as a *sign* and a *magnitude*, where /// the magnitude is calculated using the type's *radix* and the instance's /// *significand* and *exponent*. This magnitude calculation takes the /// following form for a floating-point value `x` of type `F`, where `**` is /// exponentiation: /// /// x.significand * F.radix ** x.exponent /// /// Here's an example of the number -8.5 represented as an instance of the /// `Double` type, which defines a radix of 2. /// /// let y = -8.5 /// // y.sign == .minus /// // y.significand == 1.0625 /// // y.exponent == 3 /// /// let magnitude = 1.0625 * Double(2 ** 3) /// // magnitude == 8.5 /// /// Types that conform to the `FloatingPoint` protocol provide most basic /// (clause 5) operations of the [IEEE 754 specification][spec]. The base, /// precision, and exponent range are not fixed in any way by this protocol, /// but it enforces the basic requirements of any IEEE 754 floating-point /// type. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// Additional Considerations /// ========================= /// /// In addition to representing specific numbers, floating-point types also /// have special values for working with overflow and nonnumeric results of /// calculation. /// /// Infinity /// -------- /// /// Any value whose magnitude is so great that it would round to a value /// outside the range of representable numbers is rounded to *infinity*. For a /// type `F`, positive and negative infinity are represented as `F.infinity` /// and `-F.infinity`, respectively. Positive infinity compares greater than /// every finite value and negative infinity, while negative infinity compares /// less than every finite value and positive infinity. Infinite values with /// the same sign are equal to each other. /// /// let values: [Double] = [10.0, 25.0, -10.0, .infinity, -.infinity] /// print(values.sorted()) /// // Prints "[-inf, -10.0, 10.0, 25.0, inf]" /// /// Operations with infinite values follow real arithmetic as much as possible: /// Adding or subtracting a finite value, or multiplying or dividing infinity /// by a nonzero finite value, results in infinity. /// /// NaN ("not a number") /// -------------------- /// /// Floating-point types represent values that are neither finite numbers nor /// infinity as NaN, an abbreviation for "not a number." Comparing a NaN with /// any value, including another NaN, results in `false`. /// /// let myNaN = Double.nan /// print(myNaN > 0) /// // Prints "false" /// print(myNaN < 0) /// // Prints "false" /// print(myNaN == .nan) /// // Prints "false" /// /// Because testing whether one NaN is equal to another NaN results in `false`, /// use the `isNaN` property to test whether a value is NaN. /// /// print(myNaN.isNaN) /// // Prints "true" /// /// NaN propagates through many arithmetic operations. When you are operating /// on many values, this behavior is valuable because operations on NaN simply /// forward the value and don't cause runtime errors. The following example /// shows how NaN values operate in different contexts. /// /// Imagine you have a set of temperature data for which you need to report /// some general statistics: the total number of observations, the number of /// valid observations, and the average temperature. First, a set of /// observations in Celsius is parsed from strings to `Double` values: /// /// let temperatureData = ["21.5", "19.25", "27", "no data", "28.25", "no data", "23"] /// let tempsCelsius = temperatureData.map { Double($0) ?? .nan } /// // tempsCelsius == [21.5, 19.25, 27, nan, 28.25, nan, 23.0] /// /// Note that some elements in the `temperatureData ` array are not valid /// numbers. When these invalid strings are parsed by the `Double` failable /// initializer, the example uses the nil-coalescing operator (`??`) to /// provide NaN as a fallback value. /// /// Next, the observations in Celsius are converted to Fahrenheit: /// /// let tempsFahrenheit = tempsCelsius.map { $0 * 1.8 + 32 } /// // tempsFahrenheit == [70.7, 66.65, 80.6, nan, 82.85, nan, 73.4] /// /// The NaN values in the `tempsCelsius` array are propagated through the /// conversion and remain NaN in `tempsFahrenheit`. /// /// Because calculating the average of the observations involves combining /// every value of the `tempsFahrenheit` array, any NaN values cause the /// result to also be NaN, as seen in this example: /// /// let badAverage = tempsFahrenheit.reduce(0.0, +) / Double(tempsFahrenheit.count) /// // badAverage.isNaN == true /// /// Instead, when you need an operation to have a specific numeric result, /// filter out any NaN values using the `isNaN` property. /// /// let validTemps = tempsFahrenheit.filter { !$0.isNaN } /// let average = validTemps.reduce(0.0, +) / Double(validTemps.count) /// /// Finally, report the average temperature and observation counts: /// /// print("Average: \(average)°F in \(validTemps.count) " + /// "out of \(tempsFahrenheit.count) observations.") /// // Prints "Average: 74.84°F in 5 out of 7 observations." public protocol FloatingPoint: SignedNumeric, Strideable, Hashable where Magnitude == Self { /// A type that can represent any written exponent. associatedtype Exponent: SignedInteger /// Creates a new value from the given sign, exponent, and significand. /// /// The following example uses this initializer to create a new `Double` /// instance. `Double` is a binary floating-point type that has a radix of /// `2`. /// /// let x = Double(sign: .plus, exponent: -2, significand: 1.5) /// // x == 0.375 /// /// This initializer is equivalent to the following calculation, where `**` /// is exponentiation, computed as if by a single, correctly rounded, /// floating-point operation: /// /// let sign: FloatingPointSign = .plus /// let exponent = -2 /// let significand = 1.5 /// let y = (sign == .minus ? -1 : 1) * significand * Double.radix ** exponent /// // y == 0.375 /// /// As with any basic operation, if this value is outside the representable /// range of the type, overflow or underflow occurs, and zero, a subnormal /// value, or infinity may result. In addition, there are two other edge /// cases: /// /// - If the value you pass to `significand` is zero or infinite, the result /// is zero or infinite, regardless of the value of `exponent`. /// - If the value you pass to `significand` is NaN, the result is NaN. /// /// For any floating-point value `x` of type `F`, the result of the following /// is equal to `x`, with the distinction that the result is canonicalized /// if `x` is in a noncanonical encoding: /// /// let x0 = F(sign: x.sign, exponent: x.exponent, significand: x.significand) /// /// This initializer implements the `scaleB` operation defined by the [IEEE /// 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameters: /// - sign: The sign to use for the new value. /// - exponent: The new value's exponent. /// - significand: The new value's significand. init(sign: FloatingPointSign, exponent: Exponent, significand: Self) /// Creates a new floating-point value using the sign of one value and the /// magnitude of another. /// /// The following example uses this initializer to create a new `Double` /// instance with the sign of `a` and the magnitude of `b`: /// /// let a = -21.5 /// let b = 305.15 /// let c = Double(signOf: a, magnitudeOf: b) /// print(c) /// // Prints "-305.15" /// /// This initializer implements the IEEE 754 `copysign` operation. /// /// - Parameters: /// - signOf: A value from which to use the sign. The result of the /// initializer has the same sign as `signOf`. /// - magnitudeOf: A value from which to use the magnitude. The result of /// the initializer has the same magnitude as `magnitudeOf`. init(signOf: Self, magnitudeOf: Self) /// Creates a new value, rounded to the closest possible representation. /// /// If two representable values are equally close, the result is the value /// with more trailing zeros in its significand bit pattern. /// /// - Parameter value: The integer to convert to a floating-point value. init(_ value: Int) /// Creates a new value, rounded to the closest possible representation. /// /// If two representable values are equally close, the result is the value /// with more trailing zeros in its significand bit pattern. /// /// - Parameter value: The integer to convert to a floating-point value. init<Source: BinaryInteger>(_ value: Source) /// Creates a new value, if the given integer can be represented exactly. /// /// If the given integer cannot be represented exactly, the result is `nil`. /// /// - Parameter value: The integer to convert to a floating-point value. init?<Source: BinaryInteger>(exactly value: Source) /// The radix, or base of exponentiation, for a floating-point type. /// /// The magnitude of a floating-point value `x` of type `F` can be calculated /// by using the following formula, where `**` is exponentiation: /// /// let magnitude = x.significand * F.radix ** x.exponent /// /// A conforming type may use any integer radix, but values other than 2 (for /// binary floating-point types) or 10 (for decimal floating-point types) /// are extraordinarily rare in practice. static var radix: Int { get } /// A quiet NaN ("not a number"). /// /// A NaN compares not equal, not greater than, and not less than every /// value, including itself. Passing a NaN to an operation generally results /// in NaN. /// /// let x = 1.21 /// // x > Double.nan == false /// // x < Double.nan == false /// // x == Double.nan == false /// /// Because a NaN always compares not equal to itself, to test whether a /// floating-point value is NaN, use its `isNaN` property instead of the /// equal-to operator (`==`). In the following example, `y` is NaN. /// /// let y = x + Double.nan /// print(y == Double.nan) /// // Prints "false" /// print(y.isNaN) /// // Prints "true" static var nan: Self { get } /// A signaling NaN ("not a number"). /// /// The default IEEE 754 behavior of operations involving a signaling NaN is /// to raise the Invalid flag in the floating-point environment and return a /// quiet NaN. /// /// Operations on types conforming to the `FloatingPoint` protocol should /// support this behavior, but they might also support other options. For /// example, it would be reasonable to implement alternative operations in /// which operating on a signaling NaN triggers a runtime error or results /// in a diagnostic for debugging purposes. Types that implement alternative /// behaviors for a signaling NaN must document the departure. /// /// Other than these signaling operations, a signaling NaN behaves in the /// same manner as a quiet NaN. static var signalingNaN: Self { get } /// Positive infinity. /// /// Infinity compares greater than all finite numbers and equal to other /// infinite values. /// /// let x = Double.greatestFiniteMagnitude /// let y = x * 2 /// // y == Double.infinity /// // y > x static var infinity: Self { get } /// The greatest finite number representable by this type. /// /// This value compares greater than or equal to all finite numbers, but less /// than `infinity`. /// /// This value corresponds to type-specific C macros such as `FLT_MAX` and /// `DBL_MAX`. The naming of those macros is slightly misleading, because /// `infinity` is greater than this value. static var greatestFiniteMagnitude: Self { get } /// The mathematical constant pi. /// /// This value should be rounded toward zero to keep user computations with /// angles from inadvertently ending up in the wrong quadrant. A type that /// conforms to the `FloatingPoint` protocol provides the value for `pi` at /// its best possible precision. /// /// print(Double.pi) /// // Prints "3.14159265358979" static var pi: Self { get } // NOTE: Rationale for "ulp" instead of "epsilon": // We do not use that name because it is ambiguous at best and misleading // at worst: // // - Historically several definitions of "machine epsilon" have commonly // been used, which differ by up to a factor of two or so. By contrast // "ulp" is a term with a specific unambiguous definition. // // - Some languages have used "epsilon" to refer to wildly different values, // such as `leastNonzeroMagnitude`. // // - Inexperienced users often believe that "epsilon" should be used as a // tolerance for floating-point comparisons, because of the name. It is // nearly always the wrong value to use for this purpose. /// The unit in the last place of this value. /// /// This is the unit of the least significant digit in this value's /// significand. For most numbers `x`, this is the difference between `x` /// and the next greater (in magnitude) representable number. There are some /// edge cases to be aware of: /// /// - If `x` is not a finite number, then `x.ulp` is NaN. /// - If `x` is very small in magnitude, then `x.ulp` may be a subnormal /// number. If a type does not support subnormals, `x.ulp` may be rounded /// to zero. /// - `greatestFiniteMagnitude.ulp` is a finite number, even though the next /// greater representable value is `infinity`. /// /// See also the `ulpOfOne` static property. var ulp: Self { get } /// The unit in the last place of 1.0. /// /// The positive difference between 1.0 and the next greater representable /// number. `ulpOfOne` corresponds to the value represented by the C macros /// `FLT_EPSILON`, `DBL_EPSILON`, etc, and is sometimes called *epsilon* or /// *machine epsilon*. Swift deliberately avoids using the term "epsilon" /// because: /// /// - Historically "epsilon" has been used to refer to several different /// concepts in different languages, leading to confusion and bugs. /// /// - The name "epsilon" suggests that this quantity is a good tolerance to /// choose for approximate comparisons, but it is almost always unsuitable /// for that purpose. /// /// See also the `ulp` member property. static var ulpOfOne: Self { get } /// The least positive normal number. /// /// This value compares less than or equal to all positive normal numbers. /// There may be smaller positive numbers, but they are *subnormal*, meaning /// that they are represented with less precision than normal numbers. /// /// This value corresponds to type-specific C macros such as `FLT_MIN` and /// `DBL_MIN`. The naming of those macros is slightly misleading, because /// subnormals, zeros, and negative numbers are smaller than this value. static var leastNormalMagnitude: Self { get } /// The least positive number. /// /// This value compares less than or equal to all positive numbers, but /// greater than zero. If the type supports subnormal values, /// `leastNonzeroMagnitude` is smaller than `leastNormalMagnitude`; /// otherwise they are equal. static var leastNonzeroMagnitude: Self { get } /// The sign of the floating-point value. /// /// The `sign` property is `.minus` if the value's signbit is set, and /// `.plus` otherwise. For example: /// /// let x = -33.375 /// // x.sign == .minus /// /// Do not use this property to check whether a floating point value is /// negative. For a value `x`, the comparison `x.sign == .minus` is not /// necessarily the same as `x < 0`. In particular, `x.sign == .minus` if /// `x` is -0, and while `x < 0` is always `false` if `x` is NaN, `x.sign` /// could be either `.plus` or `.minus`. var sign: FloatingPointSign { get } /// The exponent of the floating-point value. /// /// The *exponent* of a floating-point value is the integer part of the /// logarithm of the value's magnitude. For a value `x` of a floating-point /// type `F`, the magnitude can be calculated as the following, where `**` /// is exponentiation: /// /// let magnitude = x.significand * F.radix ** x.exponent /// /// In the next example, `y` has a value of `21.5`, which is encoded as /// `1.34375 * 2 ** 4`. The significand of `y` is therefore 1.34375. /// /// let y: Double = 21.5 /// // y.significand == 1.34375 /// // y.exponent == 4 /// // Double.radix == 2 /// /// The `exponent` property has the following edge cases: /// /// - If `x` is zero, then `x.exponent` is `Int.min`. /// - If `x` is +/-infinity or NaN, then `x.exponent` is `Int.max` /// /// This property implements the `logB` operation defined by the [IEEE 754 /// specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 var exponent: Exponent { get } /// The significand of the floating-point value. /// /// The magnitude of a floating-point value `x` of type `F` can be calculated /// by using the following formula, where `**` is exponentiation: /// /// let magnitude = x.significand * F.radix ** x.exponent /// /// In the next example, `y` has a value of `21.5`, which is encoded as /// `1.34375 * 2 ** 4`. The significand of `y` is therefore 1.34375. /// /// let y: Double = 21.5 /// // y.significand == 1.34375 /// // y.exponent == 4 /// // Double.radix == 2 /// /// If a type's radix is 2, then for finite nonzero numbers, the significand /// is in the range `1.0 ..< 2.0`. For other values of `x`, `x.significand` /// is defined as follows: /// /// - If `x` is zero, then `x.significand` is 0.0. /// - If `x` is infinite, then `x.significand` is infinity. /// - If `x` is NaN, then `x.significand` is NaN. /// - Note: The significand is frequently also called the *mantissa*, but /// significand is the preferred terminology in the [IEEE 754 /// specification][spec], to allay confusion with the use of mantissa for /// the fractional part of a logarithm. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 var significand: Self { get } /// Adds two values and produces their sum, rounded to a /// representable value. /// /// The addition operator (`+`) calculates the sum of its two arguments. For /// example: /// /// let x = 1.5 /// let y = x + 2.25 /// // y == 3.75 /// /// The `+` operator implements the addition operation defined by the /// [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameters: /// - lhs: The first value to add. /// - rhs: The second value to add. override static func +(lhs: Self, rhs: Self) -> Self /// Adds two values and stores the result in the left-hand-side variable, /// rounded to a representable value. /// /// - Parameters: /// - lhs: The first value to add. /// - rhs: The second value to add. override static func +=(lhs: inout Self, rhs: Self) /// Calculates the additive inverse of a value. /// /// The unary minus operator (prefix `-`) calculates the negation of its /// operand. The result is always exact. /// /// let x = 21.5 /// let y = -x /// // y == -21.5 /// /// - Parameter operand: The value to negate. override static prefix func - (_ operand: Self) -> Self /// Replaces this value with its additive inverse. /// /// The result is always exact. This example uses the `negate()` method to /// negate the value of the variable `x`: /// /// var x = 21.5 /// x.negate() /// // x == -21.5 override mutating func negate() /// Subtracts one value from another and produces their difference, rounded /// to a representable value. /// /// The subtraction operator (`-`) calculates the difference of its two /// arguments. For example: /// /// let x = 7.5 /// let y = x - 2.25 /// // y == 5.25 /// /// The `-` operator implements the subtraction operation defined by the /// [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameters: /// - lhs: A numeric value. /// - rhs: The value to subtract from `lhs`. override static func -(lhs: Self, rhs: Self) -> Self /// Subtracts the second value from the first and stores the difference in /// the left-hand-side variable, rounding to a representable value. /// /// - Parameters: /// - lhs: A numeric value. /// - rhs: The value to subtract from `lhs`. override static func -=(lhs: inout Self, rhs: Self) /// Multiplies two values and produces their product, rounding to a /// representable value. /// /// The multiplication operator (`*`) calculates the product of its two /// arguments. For example: /// /// let x = 7.5 /// let y = x * 2.25 /// // y == 16.875 /// /// The `*` operator implements the multiplication operation defined by the /// [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameters: /// - lhs: The first value to multiply. /// - rhs: The second value to multiply. override static func *(lhs: Self, rhs: Self) -> Self /// Multiplies two values and stores the result in the left-hand-side /// variable, rounding to a representable value. /// /// - Parameters: /// - lhs: The first value to multiply. /// - rhs: The second value to multiply. override static func *=(lhs: inout Self, rhs: Self) /// Returns the quotient of dividing the first value by the second, rounded /// to a representable value. /// /// The division operator (`/`) calculates the quotient of the division if /// `rhs` is nonzero. If `rhs` is zero, the result of the division is /// infinity, with the sign of the result matching the sign of `lhs`. /// /// let x = 16.875 /// let y = x / 2.25 /// // y == 7.5 /// /// let z = x / 0 /// // z.isInfinite == true /// /// The `/` operator implements the division operation defined by the [IEEE /// 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameters: /// - lhs: The value to divide. /// - rhs: The value to divide `lhs` by. static func /(lhs: Self, rhs: Self) -> Self /// Divides the first value by the second and stores the quotient in the /// left-hand-side variable, rounding to a representable value. /// /// - Parameters: /// - lhs: The value to divide. /// - rhs: The value to divide `lhs` by. static func /=(lhs: inout Self, rhs: Self) /// Returns the remainder of this value divided by the given value. /// /// For two finite values `x` and `y`, the remainder `r` of dividing `x` by /// `y` satisfies `x == y * q + r`, where `q` is the integer nearest to /// `x / y`. If `x / y` is exactly halfway between two integers, `q` is /// chosen to be even. Note that `q` is *not* `x / y` computed in /// floating-point arithmetic, and that `q` may not be representable in any /// available integer type. /// /// The following example calculates the remainder of dividing 8.625 by 0.75: /// /// let x = 8.625 /// print(x / 0.75) /// // Prints "11.5" /// /// let q = (x / 0.75).rounded(.toNearestOrEven) /// // q == 12.0 /// let r = x.remainder(dividingBy: 0.75) /// // r == -0.375 /// /// let x1 = 0.75 * q + r /// // x1 == 8.625 /// /// If this value and `other` are finite numbers, the remainder is in the /// closed range `-abs(other / 2)...abs(other / 2)`. The /// `remainder(dividingBy:)` method is always exact. This method implements /// the remainder operation defined by the [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameter other: The value to use when dividing this value. /// - Returns: The remainder of this value divided by `other`. func remainder(dividingBy other: Self) -> Self /// Replaces this value with the remainder of itself divided by the given /// value. /// /// For two finite values `x` and `y`, the remainder `r` of dividing `x` by /// `y` satisfies `x == y * q + r`, where `q` is the integer nearest to /// `x / y`. If `x / y` is exactly halfway between two integers, `q` is /// chosen to be even. Note that `q` is *not* `x / y` computed in /// floating-point arithmetic, and that `q` may not be representable in any /// available integer type. /// /// The following example calculates the remainder of dividing 8.625 by 0.75: /// /// var x = 8.625 /// print(x / 0.75) /// // Prints "11.5" /// /// let q = (x / 0.75).rounded(.toNearestOrEven) /// // q == 12.0 /// x.formRemainder(dividingBy: 0.75) /// // x == -0.375 /// /// let x1 = 0.75 * q + x /// // x1 == 8.625 /// /// If this value and `other` are finite numbers, the remainder is in the /// closed range `-abs(other / 2)...abs(other / 2)`. The /// `formRemainder(dividingBy:)` method is always exact. /// /// - Parameter other: The value to use when dividing this value. mutating func formRemainder(dividingBy other: Self) /// Returns the remainder of this value divided by the given value using /// truncating division. /// /// Performing truncating division with floating-point values results in a /// truncated integer quotient and a remainder. For values `x` and `y` and /// their truncated integer quotient `q`, the remainder `r` satisfies /// `x == y * q + r`. /// /// The following example calculates the truncating remainder of dividing /// 8.625 by 0.75: /// /// let x = 8.625 /// print(x / 0.75) /// // Prints "11.5" /// /// let q = (x / 0.75).rounded(.towardZero) /// // q == 11.0 /// let r = x.truncatingRemainder(dividingBy: 0.75) /// // r == 0.375 /// /// let x1 = 0.75 * q + r /// // x1 == 8.625 /// /// If this value and `other` are both finite numbers, the truncating /// remainder has the same sign as this value and is strictly smaller in /// magnitude than `other`. The `truncatingRemainder(dividingBy:)` method /// is always exact. /// /// - Parameter other: The value to use when dividing this value. /// - Returns: The remainder of this value divided by `other` using /// truncating division. func truncatingRemainder(dividingBy other: Self) -> Self /// Replaces this value with the remainder of itself divided by the given /// value using truncating division. /// /// Performing truncating division with floating-point values results in a /// truncated integer quotient and a remainder. For values `x` and `y` and /// their truncated integer quotient `q`, the remainder `r` satisfies /// `x == y * q + r`. /// /// The following example calculates the truncating remainder of dividing /// 8.625 by 0.75: /// /// var x = 8.625 /// print(x / 0.75) /// // Prints "11.5" /// /// let q = (x / 0.75).rounded(.towardZero) /// // q == 11.0 /// x.formTruncatingRemainder(dividingBy: 0.75) /// // x == 0.375 /// /// let x1 = 0.75 * q + x /// // x1 == 8.625 /// /// If this value and `other` are both finite numbers, the truncating /// remainder has the same sign as this value and is strictly smaller in /// magnitude than `other`. The `formTruncatingRemainder(dividingBy:)` /// method is always exact. /// /// - Parameter other: The value to use when dividing this value. mutating func formTruncatingRemainder(dividingBy other: Self) /// Returns the square root of the value, rounded to a representable value. /// /// The following example declares a function that calculates the length of /// the hypotenuse of a right triangle given its two perpendicular sides. /// /// func hypotenuse(_ a: Double, _ b: Double) -> Double { /// return (a * a + b * b).squareRoot() /// } /// /// let (dx, dy) = (3.0, 4.0) /// let distance = hypotenuse(dx, dy) /// // distance == 5.0 /// /// - Returns: The square root of the value. func squareRoot() -> Self /// Replaces this value with its square root, rounded to a representable /// value. mutating func formSquareRoot() /// Returns the result of adding the product of the two given values to this /// value, computed without intermediate rounding. /// /// This method is equivalent to the C `fma` function and implements the /// `fusedMultiplyAdd` operation defined by the [IEEE 754 /// specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameters: /// - lhs: One of the values to multiply before adding to this value. /// - rhs: The other value to multiply. /// - Returns: The product of `lhs` and `rhs`, added to this value. func addingProduct(_ lhs: Self, _ rhs: Self) -> Self /// Adds the product of the two given values to this value in place, computed /// without intermediate rounding. /// /// - Parameters: /// - lhs: One of the values to multiply before adding to this value. /// - rhs: The other value to multiply. mutating func addProduct(_ lhs: Self, _ rhs: Self) /// Returns the lesser of the two given values. /// /// This method returns the minimum of two values, preserving order and /// eliminating NaN when possible. For two values `x` and `y`, the result of /// `minimum(x, y)` is `x` if `x <= y`, `y` if `y < x`, or whichever of `x` /// or `y` is a number if the other is a quiet NaN. If both `x` and `y` are /// NaN, or either `x` or `y` is a signaling NaN, the result is NaN. /// /// Double.minimum(10.0, -25.0) /// // -25.0 /// Double.minimum(10.0, .nan) /// // 10.0 /// Double.minimum(.nan, -25.0) /// // -25.0 /// Double.minimum(.nan, .nan) /// // nan /// /// The `minimum` method implements the `minNum` operation defined by the /// [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameters: /// - x: A floating-point value. /// - y: Another floating-point value. /// - Returns: The minimum of `x` and `y`, or whichever is a number if the /// other is NaN. static func minimum(_ x: Self, _ y: Self) -> Self /// Returns the greater of the two given values. /// /// This method returns the maximum of two values, preserving order and /// eliminating NaN when possible. For two values `x` and `y`, the result of /// `maximum(x, y)` is `x` if `x > y`, `y` if `x <= y`, or whichever of `x` /// or `y` is a number if the other is a quiet NaN. If both `x` and `y` are /// NaN, or either `x` or `y` is a signaling NaN, the result is NaN. /// /// Double.maximum(10.0, -25.0) /// // 10.0 /// Double.maximum(10.0, .nan) /// // 10.0 /// Double.maximum(.nan, -25.0) /// // -25.0 /// Double.maximum(.nan, .nan) /// // nan /// /// The `maximum` method implements the `maxNum` operation defined by the /// [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameters: /// - x: A floating-point value. /// - y: Another floating-point value. /// - Returns: The greater of `x` and `y`, or whichever is a number if the /// other is NaN. static func maximum(_ x: Self, _ y: Self) -> Self /// Returns the value with lesser magnitude. /// /// This method returns the value with lesser magnitude of the two given /// values, preserving order and eliminating NaN when possible. For two /// values `x` and `y`, the result of `minimumMagnitude(x, y)` is `x` if /// `x.magnitude <= y.magnitude`, `y` if `y.magnitude < x.magnitude`, or /// whichever of `x` or `y` is a number if the other is a quiet NaN. If both /// `x` and `y` are NaN, or either `x` or `y` is a signaling NaN, the result /// is NaN. /// /// Double.minimumMagnitude(10.0, -25.0) /// // 10.0 /// Double.minimumMagnitude(10.0, .nan) /// // 10.0 /// Double.minimumMagnitude(.nan, -25.0) /// // -25.0 /// Double.minimumMagnitude(.nan, .nan) /// // nan /// /// The `minimumMagnitude` method implements the `minNumMag` operation /// defined by the [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameters: /// - x: A floating-point value. /// - y: Another floating-point value. /// - Returns: Whichever of `x` or `y` has lesser magnitude, or whichever is /// a number if the other is NaN. static func minimumMagnitude(_ x: Self, _ y: Self) -> Self /// Returns the value with greater magnitude. /// /// This method returns the value with greater magnitude of the two given /// values, preserving order and eliminating NaN when possible. For two /// values `x` and `y`, the result of `maximumMagnitude(x, y)` is `x` if /// `x.magnitude > y.magnitude`, `y` if `x.magnitude <= y.magnitude`, or /// whichever of `x` or `y` is a number if the other is a quiet NaN. If both /// `x` and `y` are NaN, or either `x` or `y` is a signaling NaN, the result /// is NaN. /// /// Double.maximumMagnitude(10.0, -25.0) /// // -25.0 /// Double.maximumMagnitude(10.0, .nan) /// // 10.0 /// Double.maximumMagnitude(.nan, -25.0) /// // -25.0 /// Double.maximumMagnitude(.nan, .nan) /// // nan /// /// The `maximumMagnitude` method implements the `maxNumMag` operation /// defined by the [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameters: /// - x: A floating-point value. /// - y: Another floating-point value. /// - Returns: Whichever of `x` or `y` has greater magnitude, or whichever is /// a number if the other is NaN. static func maximumMagnitude(_ x: Self, _ y: Self) -> Self /// Returns this value rounded to an integral value using the specified /// rounding rule. /// /// The following example rounds a value using four different rounding rules: /// /// let x = 6.5 /// /// // Equivalent to the C 'round' function: /// print(x.rounded(.toNearestOrAwayFromZero)) /// // Prints "7.0" /// /// // Equivalent to the C 'trunc' function: /// print(x.rounded(.towardZero)) /// // Prints "6.0" /// /// // Equivalent to the C 'ceil' function: /// print(x.rounded(.up)) /// // Prints "7.0" /// /// // Equivalent to the C 'floor' function: /// print(x.rounded(.down)) /// // Prints "6.0" /// /// For more information about the available rounding rules, see the /// `FloatingPointRoundingRule` enumeration. To round a value using the /// default "schoolbook rounding", you can use the shorter `rounded()` /// method instead. /// /// print(x.rounded()) /// // Prints "7.0" /// /// - Parameter rule: The rounding rule to use. /// - Returns: The integral value found by rounding using `rule`. func rounded(_ rule: FloatingPointRoundingRule) -> Self /// Rounds the value to an integral value using the specified rounding rule. /// /// The following example rounds a value using four different rounding rules: /// /// // Equivalent to the C 'round' function: /// var w = 6.5 /// w.round(.toNearestOrAwayFromZero) /// // w == 7.0 /// /// // Equivalent to the C 'trunc' function: /// var x = 6.5 /// x.round(.towardZero) /// // x == 6.0 /// /// // Equivalent to the C 'ceil' function: /// var y = 6.5 /// y.round(.up) /// // y == 7.0 /// /// // Equivalent to the C 'floor' function: /// var z = 6.5 /// z.round(.down) /// // z == 6.0 /// /// For more information about the available rounding rules, see the /// `FloatingPointRoundingRule` enumeration. To round a value using the /// default "schoolbook rounding", you can use the shorter `round()` method /// instead. /// /// var w1 = 6.5 /// w1.round() /// // w1 == 7.0 /// /// - Parameter rule: The rounding rule to use. mutating func round(_ rule: FloatingPointRoundingRule) /// The least representable value that compares greater than this value. /// /// For any finite value `x`, `x.nextUp` is greater than `x`. For `nan` or /// `infinity`, `x.nextUp` is `x` itself. The following special cases also /// apply: /// /// - If `x` is `-infinity`, then `x.nextUp` is `-greatestFiniteMagnitude`. /// - If `x` is `-leastNonzeroMagnitude`, then `x.nextUp` is `-0.0`. /// - If `x` is zero, then `x.nextUp` is `leastNonzeroMagnitude`. /// - If `x` is `greatestFiniteMagnitude`, then `x.nextUp` is `infinity`. var nextUp: Self { get } /// The greatest representable value that compares less than this value. /// /// For any finite value `x`, `x.nextDown` is less than `x`. For `nan` or /// `-infinity`, `x.nextDown` is `x` itself. The following special cases /// also apply: /// /// - If `x` is `infinity`, then `x.nextDown` is `greatestFiniteMagnitude`. /// - If `x` is `leastNonzeroMagnitude`, then `x.nextDown` is `0.0`. /// - If `x` is zero, then `x.nextDown` is `-leastNonzeroMagnitude`. /// - If `x` is `-greatestFiniteMagnitude`, then `x.nextDown` is `-infinity`. var nextDown: Self { get } /// Returns a Boolean value indicating whether this instance is equal to the /// given value. /// /// This method serves as the basis for the equal-to operator (`==`) for /// floating-point values. When comparing two values with this method, `-0` /// is equal to `+0`. NaN is not equal to any value, including itself. For /// example: /// /// let x = 15.0 /// x.isEqual(to: 15.0) /// // true /// x.isEqual(to: .nan) /// // false /// Double.nan.isEqual(to: .nan) /// // false /// /// The `isEqual(to:)` method implements the equality predicate defined by /// the [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameter other: The value to compare with this value. /// - Returns: `true` if `other` has the same value as this instance; /// otherwise, `false`. If either this value or `other` is NaN, the result /// of this method is `false`. func isEqual(to other: Self) -> Bool /// Returns a Boolean value indicating whether this instance is less than the /// given value. /// /// This method serves as the basis for the less-than operator (`<`) for /// floating-point values. Some special cases apply: /// /// - Because NaN compares not less than nor greater than any value, this /// method returns `false` when called on NaN or when NaN is passed as /// `other`. /// - `-infinity` compares less than all values except for itself and NaN. /// - Every value except for NaN and `+infinity` compares less than /// `+infinity`. /// /// let x = 15.0 /// x.isLess(than: 20.0) /// // true /// x.isLess(than: .nan) /// // false /// Double.nan.isLess(than: x) /// // false /// /// The `isLess(than:)` method implements the less-than predicate defined by /// the [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameter other: The value to compare with this value. /// - Returns: `true` if this value is less than `other`; otherwise, `false`. /// If either this value or `other` is NaN, the result of this method is /// `false`. func isLess(than other: Self) -> Bool /// Returns a Boolean value indicating whether this instance is less than or /// equal to the given value. /// /// This method serves as the basis for the less-than-or-equal-to operator /// (`<=`) for floating-point values. Some special cases apply: /// /// - Because NaN is incomparable with any value, this method returns `false` /// when called on NaN or when NaN is passed as `other`. /// - `-infinity` compares less than or equal to all values except NaN. /// - Every value except NaN compares less than or equal to `+infinity`. /// /// let x = 15.0 /// x.isLessThanOrEqualTo(20.0) /// // true /// x.isLessThanOrEqualTo(.nan) /// // false /// Double.nan.isLessThanOrEqualTo(x) /// // false /// /// The `isLessThanOrEqualTo(_:)` method implements the less-than-or-equal /// predicate defined by the [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameter other: The value to compare with this value. /// - Returns: `true` if `other` is greater than this value; otherwise, /// `false`. If either this value or `other` is NaN, the result of this /// method is `false`. func isLessThanOrEqualTo(_ other: Self) -> Bool /// Returns a Boolean value indicating whether this instance should precede /// or tie positions with the given value in an ascending sort. /// /// This relation is a refinement of the less-than-or-equal-to operator /// (`<=`) that provides a total order on all values of the type, including /// signed zeros and NaNs. /// /// The following example uses `isTotallyOrdered(belowOrEqualTo:)` to sort an /// array of floating-point values, including some that are NaN: /// /// var numbers = [2.5, 21.25, 3.0, .nan, -9.5] /// numbers.sort { !$1.isTotallyOrdered(belowOrEqualTo: $0) } /// // numbers == [-9.5, 2.5, 3.0, 21.25, NaN] /// /// The `isTotallyOrdered(belowOrEqualTo:)` method implements the total order /// relation as defined by the [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameter other: A floating-point value to compare to this value. /// - Returns: `true` if this value is ordered below or the same as `other` /// in a total ordering of the floating-point type; otherwise, `false`. func isTotallyOrdered(belowOrEqualTo other: Self) -> Bool /// A Boolean value indicating whether this instance is normal. /// /// A *normal* value is a finite number that uses the full precision /// available to values of a type. Zero is neither a normal nor a subnormal /// number. var isNormal: Bool { get } /// A Boolean value indicating whether this instance is finite. /// /// All values other than NaN and infinity are considered finite, whether /// normal or subnormal. var isFinite: Bool { get } /// A Boolean value indicating whether the instance is equal to zero. /// /// The `isZero` property of a value `x` is `true` when `x` represents either /// `-0.0` or `+0.0`. `x.isZero` is equivalent to the following comparison: /// `x == 0.0`. /// /// let x = -0.0 /// x.isZero // true /// x == 0.0 // true var isZero: Bool { get } /// A Boolean value indicating whether the instance is subnormal. /// /// A *subnormal* value is a nonzero number that has a lesser magnitude than /// the smallest normal number. Subnormal values do not use the full /// precision available to values of a type. /// /// Zero is neither a normal nor a subnormal number. Subnormal numbers are /// often called *denormal* or *denormalized*---these are different names /// for the same concept. var isSubnormal: Bool { get } /// A Boolean value indicating whether the instance is infinite. /// /// Note that `isFinite` and `isInfinite` do not form a dichotomy, because /// they are not total: If `x` is `NaN`, then both properties are `false`. var isInfinite: Bool { get } /// A Boolean value indicating whether the instance is NaN ("not a number"). /// /// Because NaN is not equal to any value, including NaN, use this property /// instead of the equal-to operator (`==`) or not-equal-to operator (`!=`) /// to test whether a value is or is not NaN. For example: /// /// let x = 0.0 /// let y = x * .infinity /// // y is a NaN /// /// // Comparing with the equal-to operator never returns 'true' /// print(x == Double.nan) /// // Prints "false" /// print(y == Double.nan) /// // Prints "false" /// /// // Test with the 'isNaN' property instead /// print(x.isNaN) /// // Prints "false" /// print(y.isNaN) /// // Prints "true" /// /// This property is `true` for both quiet and signaling NaNs. var isNaN: Bool { get } /// A Boolean value indicating whether the instance is a signaling NaN. /// /// Signaling NaNs typically raise the Invalid flag when used in general /// computing operations. var isSignalingNaN: Bool { get } /// The classification of this value. /// /// A value's `floatingPointClass` property describes its "class" as /// described by the [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 var floatingPointClass: FloatingPointClassification { get } /// A Boolean value indicating whether the instance's representation is in /// its canonical form. /// /// The [IEEE 754 specification][spec] defines a *canonical*, or preferred, /// encoding of a floating-point value. On platforms that fully support /// IEEE 754, every `Float` or `Double` value is canonical, but /// non-canonical values can exist on other platforms or for other types. /// Some examples: /// /// - On platforms that flush subnormal numbers to zero (such as armv7 /// with the default floating-point environment), Swift interprets /// subnormal `Float` and `Double` values as non-canonical zeros. /// (In Swift 5.1 and earlier, `isCanonical` is `true` for these /// values, which is the incorrect value.) /// /// - On i386 and x86_64, `Float80` has a number of non-canonical /// encodings. "Pseudo-NaNs", "pseudo-infinities", and "unnormals" are /// interpreted as non-canonical NaN encodings. "Pseudo-denormals" are /// interpreted as non-canonical encodings of subnormal values. /// /// - Decimal floating-point types admit a large number of non-canonical /// encodings. Consult the IEEE 754 standard for additional details. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 var isCanonical: Bool { get } } /// The sign of a floating-point value. @frozen public enum FloatingPointSign: Int { /// The sign for a positive value. case plus /// The sign for a negative value. case minus // Explicit declarations of otherwise-synthesized members to make them // @inlinable, promising that we will never change the implementation. @inlinable public init?(rawValue: Int) { switch rawValue { case 0: self = .plus case 1: self = .minus default: return nil } } @inlinable public var rawValue: Int { switch self { case .plus: return 0 case .minus: return 1 } } @_transparent @inlinable public static func ==(a: FloatingPointSign, b: FloatingPointSign) -> Bool { return a.rawValue == b.rawValue } @inlinable public var hashValue: Int { return rawValue.hashValue } @inlinable public func hash(into hasher: inout Hasher) { hasher.combine(rawValue) } @inlinable public func _rawHashValue(seed: Int) -> Int { return rawValue._rawHashValue(seed: seed) } } /// The IEEE 754 floating-point classes. @frozen public enum FloatingPointClassification { /// A signaling NaN ("not a number"). /// /// A signaling NaN sets the floating-point exception status when used in /// many floating-point operations. case signalingNaN /// A silent NaN ("not a number") value. case quietNaN /// A value equal to `-infinity`. case negativeInfinity /// A negative value that uses the full precision of the floating-point type. case negativeNormal /// A negative, nonzero number that does not use the full precision of the /// floating-point type. case negativeSubnormal /// A value equal to zero with a negative sign. case negativeZero /// A value equal to zero with a positive sign. case positiveZero /// A positive, nonzero number that does not use the full precision of the /// floating-point type. case positiveSubnormal /// A positive value that uses the full precision of the floating-point type. case positiveNormal /// A value equal to `+infinity`. case positiveInfinity } /// A rule for rounding a floating-point number. public enum FloatingPointRoundingRule { /// Round to the closest allowed value; if two values are equally close, the /// one with greater magnitude is chosen. /// /// This rounding rule is also known as "schoolbook rounding." The following /// example shows the results of rounding numbers using this rule: /// /// (5.2).rounded(.toNearestOrAwayFromZero) /// // 5.0 /// (5.5).rounded(.toNearestOrAwayFromZero) /// // 6.0 /// (-5.2).rounded(.toNearestOrAwayFromZero) /// // -5.0 /// (-5.5).rounded(.toNearestOrAwayFromZero) /// // -6.0 /// /// This rule is equivalent to the C `round` function and implements the /// `roundToIntegralTiesToAway` operation defined by the [IEEE 754 /// specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 case toNearestOrAwayFromZero /// Round to the closest allowed value; if two values are equally close, the /// even one is chosen. /// /// This rounding rule is also known as "bankers rounding," and is the /// default IEEE 754 rounding mode for arithmetic. The following example /// shows the results of rounding numbers using this rule: /// /// (5.2).rounded(.toNearestOrEven) /// // 5.0 /// (5.5).rounded(.toNearestOrEven) /// // 6.0 /// (4.5).rounded(.toNearestOrEven) /// // 4.0 /// /// This rule implements the `roundToIntegralTiesToEven` operation defined by /// the [IEEE 754 specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 case toNearestOrEven /// Round to the closest allowed value that is greater than or equal to the /// source. /// /// The following example shows the results of rounding numbers using this /// rule: /// /// (5.2).rounded(.up) /// // 6.0 /// (5.5).rounded(.up) /// // 6.0 /// (-5.2).rounded(.up) /// // -5.0 /// (-5.5).rounded(.up) /// // -5.0 /// /// This rule is equivalent to the C `ceil` function and implements the /// `roundToIntegralTowardPositive` operation defined by the [IEEE 754 /// specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 case up /// Round to the closest allowed value that is less than or equal to the /// source. /// /// The following example shows the results of rounding numbers using this /// rule: /// /// (5.2).rounded(.down) /// // 5.0 /// (5.5).rounded(.down) /// // 5.0 /// (-5.2).rounded(.down) /// // -6.0 /// (-5.5).rounded(.down) /// // -6.0 /// /// This rule is equivalent to the C `floor` function and implements the /// `roundToIntegralTowardNegative` operation defined by the [IEEE 754 /// specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 case down /// Round to the closest allowed value whose magnitude is less than or equal /// to that of the source. /// /// The following example shows the results of rounding numbers using this /// rule: /// /// (5.2).rounded(.towardZero) /// // 5.0 /// (5.5).rounded(.towardZero) /// // 5.0 /// (-5.2).rounded(.towardZero) /// // -5.0 /// (-5.5).rounded(.towardZero) /// // -5.0 /// /// This rule is equivalent to the C `trunc` function and implements the /// `roundToIntegralTowardZero` operation defined by the [IEEE 754 /// specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 case towardZero /// Round to the closest allowed value whose magnitude is greater than or /// equal to that of the source. /// /// The following example shows the results of rounding numbers using this /// rule: /// /// (5.2).rounded(.awayFromZero) /// // 6.0 /// (5.5).rounded(.awayFromZero) /// // 6.0 /// (-5.2).rounded(.awayFromZero) /// // -6.0 /// (-5.5).rounded(.awayFromZero) /// // -6.0 case awayFromZero } extension FloatingPoint { @_transparent public static func == (lhs: Self, rhs: Self) -> Bool { return lhs.isEqual(to: rhs) } @_transparent public static func < (lhs: Self, rhs: Self) -> Bool { return lhs.isLess(than: rhs) } @_transparent public static func <= (lhs: Self, rhs: Self) -> Bool { return lhs.isLessThanOrEqualTo(rhs) } @_transparent public static func > (lhs: Self, rhs: Self) -> Bool { return rhs.isLess(than: lhs) } @_transparent public static func >= (lhs: Self, rhs: Self) -> Bool { return rhs.isLessThanOrEqualTo(lhs) } } /// A radix-2 (binary) floating-point type. /// /// The `BinaryFloatingPoint` protocol extends the `FloatingPoint` protocol /// with operations specific to floating-point binary types, as defined by the /// [IEEE 754 specification][spec]. `BinaryFloatingPoint` is implemented in /// the standard library by `Float`, `Double`, and `Float80` where available. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 public protocol BinaryFloatingPoint: FloatingPoint, ExpressibleByFloatLiteral { /// A type that represents the encoded significand of a value. associatedtype RawSignificand: UnsignedInteger /// A type that represents the encoded exponent of a value. associatedtype RawExponent: UnsignedInteger /// Creates a new instance from the specified sign and bit patterns. /// /// The values passed as `exponentBitPattern` and `significandBitPattern` are /// interpreted in the binary interchange format defined by the [IEEE 754 /// specification][spec]. /// /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameters: /// - sign: The sign of the new value. /// - exponentBitPattern: The bit pattern to use for the exponent field of /// the new value. /// - significandBitPattern: The bit pattern to use for the significand /// field of the new value. init(sign: FloatingPointSign, exponentBitPattern: RawExponent, significandBitPattern: RawSignificand) /// Creates a new instance from the given value, rounded to the closest /// possible representation. /// /// - Parameter value: A floating-point value to be converted. init(_ value: Float) /// Creates a new instance from the given value, rounded to the closest /// possible representation. /// /// - Parameter value: A floating-point value to be converted. init(_ value: Double) #if !(os(Windows) || os(Android)) && (arch(i386) || arch(x86_64)) /// Creates a new instance from the given value, rounded to the closest /// possible representation. /// /// - Parameter value: A floating-point value to be converted. init(_ value: Float80) #endif /// Creates a new instance from the given value, rounded to the closest /// possible representation. /// /// If two representable values are equally close, the result is the value /// with more trailing zeros in its significand bit pattern. /// /// - Parameter value: A floating-point value to be converted. init<Source: BinaryFloatingPoint>(_ value: Source) /// Creates a new instance from the given value, if it can be represented /// exactly. /// /// If the given floating-point value cannot be represented exactly, the /// result is `nil`. A value that is NaN ("not a number") cannot be /// represented exactly if its payload cannot be encoded exactly. /// /// - Parameter value: A floating-point value to be converted. init?<Source: BinaryFloatingPoint>(exactly value: Source) /// The number of bits used to represent the type's exponent. /// /// A binary floating-point type's `exponentBitCount` imposes a limit on the /// range of the exponent for normal, finite values. The *exponent bias* of /// a type `F` can be calculated as the following, where `**` is /// exponentiation: /// /// let bias = 2 ** (F.exponentBitCount - 1) - 1 /// /// The least normal exponent for values of the type `F` is `1 - bias`, and /// the largest finite exponent is `bias`. An all-zeros exponent is reserved /// for subnormals and zeros, and an all-ones exponent is reserved for /// infinity and NaN. /// /// For example, the `Float` type has an `exponentBitCount` of 8, which gives /// an exponent bias of `127` by the calculation above. /// /// let bias = 2 ** (Float.exponentBitCount - 1) - 1 /// // bias == 127 /// print(Float.greatestFiniteMagnitude.exponent) /// // Prints "127" /// print(Float.leastNormalMagnitude.exponent) /// // Prints "-126" static var exponentBitCount: Int { get } /// The available number of fractional significand bits. /// /// For fixed-width floating-point types, this is the actual number of /// fractional significand bits. /// /// For extensible floating-point types, `significandBitCount` should be the /// maximum allowed significand width (without counting any leading integral /// bit of the significand). If there is no upper limit, then /// `significandBitCount` should be `Int.max`. /// /// Note that `Float80.significandBitCount` is 63, even though 64 bits are /// used to store the significand in the memory representation of a /// `Float80` (unlike other floating-point types, `Float80` explicitly /// stores the leading integral significand bit, but the /// `BinaryFloatingPoint` APIs provide an abstraction so that users don't /// need to be aware of this detail). static var significandBitCount: Int { get } /// The raw encoding of the value's exponent field. /// /// This value is unadjusted by the type's exponent bias. var exponentBitPattern: RawExponent { get } /// The raw encoding of the value's significand field. /// /// The `significandBitPattern` property does not include the leading /// integral bit of the significand, even for types like `Float80` that /// store it explicitly. var significandBitPattern: RawSignificand { get } /// The floating-point value with the same sign and exponent as this value, /// but with a significand of 1.0. /// /// A *binade* is a set of binary floating-point values that all have the /// same sign and exponent. The `binade` property is a member of the same /// binade as this value, but with a unit significand. /// /// In this example, `x` has a value of `21.5`, which is stored as /// `1.34375 * 2**4`, where `**` is exponentiation. Therefore, `x.binade` is /// equal to `1.0 * 2**4`, or `16.0`. /// /// let x = 21.5 /// // x.significand == 1.34375 /// // x.exponent == 4 /// /// let y = x.binade /// // y == 16.0 /// // y.significand == 1.0 /// // y.exponent == 4 var binade: Self { get } /// The number of bits required to represent the value's significand. /// /// If this value is a finite nonzero number, `significandWidth` is the /// number of fractional bits required to represent the value of /// `significand`; otherwise, `significandWidth` is -1. The value of /// `significandWidth` is always -1 or between zero and /// `significandBitCount`. For example: /// /// - For any representable power of two, `significandWidth` is zero, because /// `significand` is `1.0`. /// - If `x` is 10, `x.significand` is `1.01` in binary, so /// `x.significandWidth` is 2. /// - If `x` is Float.pi, `x.significand` is `1.10010010000111111011011` in /// binary, and `x.significandWidth` is 23. var significandWidth: Int { get } } extension FloatingPoint { @inlinable // FIXME(sil-serialize-all) public static var ulpOfOne: Self { return (1 as Self).ulp } @_transparent public func rounded(_ rule: FloatingPointRoundingRule) -> Self { var lhs = self lhs.round(rule) return lhs } @_transparent public func rounded() -> Self { return rounded(.toNearestOrAwayFromZero) } @_transparent public mutating func round() { round(.toNearestOrAwayFromZero) } @inlinable // FIXME(inline-always) public var nextDown: Self { @inline(__always) get { return -(-self).nextUp } } @inlinable // FIXME(inline-always) @inline(__always) public func truncatingRemainder(dividingBy other: Self) -> Self { var lhs = self lhs.formTruncatingRemainder(dividingBy: other) return lhs } @inlinable // FIXME(inline-always) @inline(__always) public func remainder(dividingBy other: Self) -> Self { var lhs = self lhs.formRemainder(dividingBy: other) return lhs } @_transparent public func squareRoot( ) -> Self { var lhs = self lhs.formSquareRoot( ) return lhs } @_transparent public func addingProduct(_ lhs: Self, _ rhs: Self) -> Self { var addend = self addend.addProduct(lhs, rhs) return addend } @inlinable public static func minimum(_ x: Self, _ y: Self) -> Self { if x <= y || y.isNaN { return x } return y } @inlinable public static func maximum(_ x: Self, _ y: Self) -> Self { if x > y || y.isNaN { return x } return y } @inlinable public static func minimumMagnitude(_ x: Self, _ y: Self) -> Self { if x.magnitude <= y.magnitude || y.isNaN { return x } return y } @inlinable public static func maximumMagnitude(_ x: Self, _ y: Self) -> Self { if x.magnitude > y.magnitude || y.isNaN { return x } return y } @inlinable public var floatingPointClass: FloatingPointClassification { if isSignalingNaN { return .signalingNaN } if isNaN { return .quietNaN } if isInfinite { return sign == .minus ? .negativeInfinity : .positiveInfinity } if isNormal { return sign == .minus ? .negativeNormal : .positiveNormal } if isSubnormal { return sign == .minus ? .negativeSubnormal : .positiveSubnormal } return sign == .minus ? .negativeZero : .positiveZero } } extension BinaryFloatingPoint { @inlinable @inline(__always) public static var radix: Int { return 2 } @inlinable public init(signOf: Self, magnitudeOf: Self) { self.init( sign: signOf.sign, exponentBitPattern: magnitudeOf.exponentBitPattern, significandBitPattern: magnitudeOf.significandBitPattern ) } @inlinable public // @testable static func _convert<Source: BinaryFloatingPoint>( from source: Source ) -> (value: Self, exact: Bool) { guard _fastPath(!source.isZero) else { return (source.sign == .minus ? -0.0 : 0, true) } guard _fastPath(source.isFinite) else { if source.isInfinite { return (source.sign == .minus ? -.infinity : .infinity, true) } // IEEE 754 requires that any NaN payload be propagated, if possible. let payload_ = source.significandBitPattern & ~(Source.nan.significandBitPattern | Source.signalingNaN.significandBitPattern) let mask = Self.greatestFiniteMagnitude.significandBitPattern & ~(Self.nan.significandBitPattern | Self.signalingNaN.significandBitPattern) let payload = Self.RawSignificand(truncatingIfNeeded: payload_) & mask // Although .signalingNaN.exponentBitPattern == .nan.exponentBitPattern, // we do not *need* to rely on this relation, and therefore we do not. let value = source.isSignalingNaN ? Self( sign: source.sign, exponentBitPattern: Self.signalingNaN.exponentBitPattern, significandBitPattern: payload | Self.signalingNaN.significandBitPattern) : Self( sign: source.sign, exponentBitPattern: Self.nan.exponentBitPattern, significandBitPattern: payload | Self.nan.significandBitPattern) // We define exactness by equality after roundtripping; since NaN is never // equal to itself, it can never be converted exactly. return (value, false) } let exponent = source.exponent var exemplar = Self.leastNormalMagnitude let exponentBitPattern: Self.RawExponent let leadingBitIndex: Int let shift: Int let significandBitPattern: Self.RawSignificand if exponent < exemplar.exponent { // The floating-point result is either zero or subnormal. exemplar = Self.leastNonzeroMagnitude let minExponent = exemplar.exponent if exponent + 1 < minExponent { return (source.sign == .minus ? -0.0 : 0, false) } if _slowPath(exponent + 1 == minExponent) { // Although the most significant bit (MSB) of a subnormal source // significand is explicit, Swift BinaryFloatingPoint APIs actually // omit any explicit MSB from the count represented in // significandWidth. For instance: // // Double.leastNonzeroMagnitude.significandWidth == 0 // // Therefore, we do not need to adjust our work here for a subnormal // source. return source.significandWidth == 0 ? (source.sign == .minus ? -0.0 : 0, false) : (source.sign == .minus ? -exemplar : exemplar, false) } exponentBitPattern = 0 as Self.RawExponent leadingBitIndex = Int(Self.Exponent(exponent) - minExponent) shift = leadingBitIndex &- (source.significandWidth &+ source.significandBitPattern.trailingZeroBitCount) let leadingBit = source.isNormal ? (1 as Self.RawSignificand) << leadingBitIndex : 0 significandBitPattern = leadingBit | (shift >= 0 ? Self.RawSignificand(source.significandBitPattern) << shift : Self.RawSignificand(source.significandBitPattern >> -shift)) } else { // The floating-point result is either normal or infinite. exemplar = Self.greatestFiniteMagnitude if exponent > exemplar.exponent { return (source.sign == .minus ? -.infinity : .infinity, false) } exponentBitPattern = exponent < 0 ? (1 as Self).exponentBitPattern - Self.RawExponent(-exponent) : (1 as Self).exponentBitPattern + Self.RawExponent(exponent) leadingBitIndex = exemplar.significandWidth shift = leadingBitIndex &- (source.significandWidth &+ source.significandBitPattern.trailingZeroBitCount) let sourceLeadingBit = source.isSubnormal ? (1 as Source.RawSignificand) << (source.significandWidth &+ source.significandBitPattern.trailingZeroBitCount) : 0 significandBitPattern = shift >= 0 ? Self.RawSignificand( sourceLeadingBit ^ source.significandBitPattern) << shift : Self.RawSignificand( (sourceLeadingBit ^ source.significandBitPattern) >> -shift) } let value = Self( sign: source.sign, exponentBitPattern: exponentBitPattern, significandBitPattern: significandBitPattern) if source.significandWidth <= leadingBitIndex { return (value, true) } // We promise to round to the closest representation. Therefore, we must // take a look at the bits that we've just truncated. let ulp = (1 as Source.RawSignificand) << -shift let truncatedBits = source.significandBitPattern & (ulp - 1) if truncatedBits < ulp / 2 { return (value, false) } let rounded = source.sign == .minus ? value.nextDown : value.nextUp if _fastPath(truncatedBits > ulp / 2) { return (rounded, false) } // If two representable values are equally close, we return the value with // more trailing zeros in its significand bit pattern. return significandBitPattern.trailingZeroBitCount > rounded.significandBitPattern.trailingZeroBitCount ? (value, false) : (rounded, false) } /// Creates a new instance from the given value, rounded to the closest /// possible representation. /// /// If two representable values are equally close, the result is the value /// with more trailing zeros in its significand bit pattern. /// /// - Parameter value: A floating-point value to be converted. @inlinable public init<Source: BinaryFloatingPoint>(_ value: Source) { self = Self._convert(from: value).value } /// Creates a new instance from the given value, if it can be represented /// exactly. /// /// If the given floating-point value cannot be represented exactly, the /// result is `nil`. /// /// - Parameter value: A floating-point value to be converted. @inlinable public init?<Source: BinaryFloatingPoint>(exactly value: Source) { let (value_, exact) = Self._convert(from: value) guard exact else { return nil } self = value_ } @inlinable public func isTotallyOrdered(belowOrEqualTo other: Self) -> Bool { // Quick return when possible. if self < other { return true } if other > self { return false } // Self and other are either equal or unordered. // Every negative-signed value (even NaN) is less than every positive- // signed value, so if the signs do not match, we simply return the // sign bit of self. if sign != other.sign { return sign == .minus } // Sign bits match; look at exponents. if exponentBitPattern > other.exponentBitPattern { return sign == .minus } if exponentBitPattern < other.exponentBitPattern { return sign == .plus } // Signs and exponents match, look at significands. if significandBitPattern > other.significandBitPattern { return sign == .minus } if significandBitPattern < other.significandBitPattern { return sign == .plus } // Sign, exponent, and significand all match. return true } } extension BinaryFloatingPoint where Self.RawSignificand: FixedWidthInteger { @inlinable public // @testable static func _convert<Source: BinaryInteger>( from source: Source ) -> (value: Self, exact: Bool) { // Useful constants: let exponentBias = (1 as Self).exponentBitPattern let significandMask = ((1 as RawSignificand) << Self.significandBitCount) &- 1 // Zero is really extra simple, and saves us from trying to normalize a // value that cannot be normalized. if _fastPath(source == 0) { return (0, true) } // We now have a non-zero value; convert it to a strictly positive value // by taking the magnitude. let magnitude = source.magnitude var exponent = magnitude._binaryLogarithm() // If the exponent would be larger than the largest representable // exponent, the result is just an infinity of the appropriate sign. guard exponent <= Self.greatestFiniteMagnitude.exponent else { return (Source.isSigned && source < 0 ? -.infinity : .infinity, false) } // If exponent <= significandBitCount, we don't need to round it to // construct the significand; we just need to left-shift it into place; // the result is always exact as we've accounted for exponent-too-large // already and no rounding can occur. if exponent <= Self.significandBitCount { let shift = Self.significandBitCount &- exponent let significand = RawSignificand(magnitude) &<< shift let value = Self( sign: Source.isSigned && source < 0 ? .minus : .plus, exponentBitPattern: exponentBias + RawExponent(exponent), significandBitPattern: significand ) return (value, true) } // exponent > significandBitCount, so we need to do a rounding right // shift, and adjust exponent if needed let shift = exponent &- Self.significandBitCount let halfway = (1 as Source.Magnitude) << (shift - 1) let mask = 2 * halfway - 1 let fraction = magnitude & mask var significand = RawSignificand(truncatingIfNeeded: magnitude >> shift) & significandMask if fraction > halfway || (fraction == halfway && significand & 1 == 1) { var carry = false (significand, carry) = significand.addingReportingOverflow(1) if carry || significand > significandMask { exponent += 1 guard exponent <= Self.greatestFiniteMagnitude.exponent else { return (Source.isSigned && source < 0 ? -.infinity : .infinity, false) } } } return (Self( sign: Source.isSigned && source < 0 ? .minus : .plus, exponentBitPattern: exponentBias + RawExponent(exponent), significandBitPattern: significand ), fraction == 0) } /// Creates a new value, rounded to the closest possible representation. /// /// If two representable values are equally close, the result is the value /// with more trailing zeros in its significand bit pattern. /// /// - Parameter value: The integer to convert to a floating-point value. @inlinable public init<Source: BinaryInteger>(_ value: Source) { self = Self._convert(from: value).value } /// Creates a new value, if the given integer can be represented exactly. /// /// If the given integer cannot be represented exactly, the result is `nil`. /// /// - Parameter value: The integer to convert to a floating-point value. @inlinable public init?<Source: BinaryInteger>(exactly value: Source) { let (value_, exact) = Self._convert(from: value) guard exact else { return nil } self = value_ } /// Returns a random value within the specified range, using the given /// generator as a source for randomness. /// /// Use this method to generate a floating-point value within a specific /// range when you are using a custom random number generator. This example /// creates three new values in the range `10.0 ..< 20.0`. /// /// for _ in 1...3 { /// print(Double.random(in: 10.0 ..< 20.0, using: &myGenerator)) /// } /// // Prints "18.1900709259179" /// // Prints "14.2286325689993" /// // Prints "13.1485686260762" /// /// The `random(in:using:)` static method chooses a random value from a /// continuous uniform distribution in `range`, and then converts that value /// to the nearest representable value in this type. Depending on the size /// and span of `range`, some concrete values may be represented more /// frequently than others. /// /// - Note: The algorithm used to create random values may change in a future /// version of Swift. If you're passing a generator that results in the /// same sequence of floating-point values each time you run your program, /// that sequence may change when your program is compiled using a /// different version of Swift. /// /// - Parameters: /// - range: The range in which to create a random value. /// `range` must be finite and non-empty. /// - generator: The random number generator to use when creating the /// new random value. /// - Returns: A random value within the bounds of `range`. @inlinable public static func random<T: RandomNumberGenerator>( in range: Range<Self>, using generator: inout T ) -> Self { _precondition( !range.isEmpty, "Can't get random value with an empty range" ) let delta = range.upperBound - range.lowerBound // TODO: this still isn't quite right, because the computation of delta // can overflow (e.g. if .upperBound = .maximumFiniteMagnitude and // .lowerBound = -.upperBound); this should be re-written with an // algorithm that handles that case correctly, but this precondition // is an acceptable short-term fix. _precondition( delta.isFinite, "There is no uniform distribution on an infinite range" ) let rand: Self.RawSignificand if Self.RawSignificand.bitWidth == Self.significandBitCount + 1 { rand = generator.next() } else { let significandCount = Self.significandBitCount + 1 let maxSignificand: Self.RawSignificand = 1 << significandCount // Rather than use .next(upperBound:), which has to work with arbitrary // upper bounds, and therefore does extra work to avoid bias, we can take // a shortcut because we know that maxSignificand is a power of two. rand = generator.next() & (maxSignificand - 1) } let unitRandom = Self.init(rand) * (Self.ulpOfOne / 2) let randFloat = delta * unitRandom + range.lowerBound if randFloat == range.upperBound { return Self.random(in: range, using: &generator) } return randFloat } /// Returns a random value within the specified range. /// /// Use this method to generate a floating-point value within a specific /// range. This example creates three new values in the range /// `10.0 ..< 20.0`. /// /// for _ in 1...3 { /// print(Double.random(in: 10.0 ..< 20.0)) /// } /// // Prints "18.1900709259179" /// // Prints "14.2286325689993" /// // Prints "13.1485686260762" /// /// The `random()` static method chooses a random value from a continuous /// uniform distribution in `range`, and then converts that value to the /// nearest representable value in this type. Depending on the size and span /// of `range`, some concrete values may be represented more frequently than /// others. /// /// This method is equivalent to calling `random(in:using:)`, passing in the /// system's default random generator. /// /// - Parameter range: The range in which to create a random value. /// `range` must be finite and non-empty. /// - Returns: A random value within the bounds of `range`. @inlinable public static func random(in range: Range<Self>) -> Self { var g = SystemRandomNumberGenerator() return Self.random(in: range, using: &g) } /// Returns a random value within the specified range, using the given /// generator as a source for randomness. /// /// Use this method to generate a floating-point value within a specific /// range when you are using a custom random number generator. This example /// creates three new values in the range `10.0 ... 20.0`. /// /// for _ in 1...3 { /// print(Double.random(in: 10.0 ... 20.0, using: &myGenerator)) /// } /// // Prints "18.1900709259179" /// // Prints "14.2286325689993" /// // Prints "13.1485686260762" /// /// The `random(in:using:)` static method chooses a random value from a /// continuous uniform distribution in `range`, and then converts that value /// to the nearest representable value in this type. Depending on the size /// and span of `range`, some concrete values may be represented more /// frequently than others. /// /// - Note: The algorithm used to create random values may change in a future /// version of Swift. If you're passing a generator that results in the /// same sequence of floating-point values each time you run your program, /// that sequence may change when your program is compiled using a /// different version of Swift. /// /// - Parameters: /// - range: The range in which to create a random value. Must be finite. /// - generator: The random number generator to use when creating the /// new random value. /// - Returns: A random value within the bounds of `range`. @inlinable public static func random<T: RandomNumberGenerator>( in range: ClosedRange<Self>, using generator: inout T ) -> Self { _precondition( !range.isEmpty, "Can't get random value with an empty range" ) let delta = range.upperBound - range.lowerBound // TODO: this still isn't quite right, because the computation of delta // can overflow (e.g. if .upperBound = .maximumFiniteMagnitude and // .lowerBound = -.upperBound); this should be re-written with an // algorithm that handles that case correctly, but this precondition // is an acceptable short-term fix. _precondition( delta.isFinite, "There is no uniform distribution on an infinite range" ) let rand: Self.RawSignificand if Self.RawSignificand.bitWidth == Self.significandBitCount + 1 { rand = generator.next() let tmp: UInt8 = generator.next() & 1 if rand == Self.RawSignificand.max && tmp == 1 { return range.upperBound } } else { let significandCount = Self.significandBitCount + 1 let maxSignificand: Self.RawSignificand = 1 << significandCount rand = generator.next(upperBound: maxSignificand + 1) if rand == maxSignificand { return range.upperBound } } let unitRandom = Self.init(rand) * (Self.ulpOfOne / 2) let randFloat = delta * unitRandom + range.lowerBound return randFloat } /// Returns a random value within the specified range. /// /// Use this method to generate a floating-point value within a specific /// range. This example creates three new values in the range /// `10.0 ... 20.0`. /// /// for _ in 1...3 { /// print(Double.random(in: 10.0 ... 20.0)) /// } /// // Prints "18.1900709259179" /// // Prints "14.2286325689993" /// // Prints "13.1485686260762" /// /// The `random()` static method chooses a random value from a continuous /// uniform distribution in `range`, and then converts that value to the /// nearest representable value in this type. Depending on the size and span /// of `range`, some concrete values may be represented more frequently than /// others. /// /// This method is equivalent to calling `random(in:using:)`, passing in the /// system's default random generator. /// /// - Parameter range: The range in which to create a random value. Must be finite. /// - Returns: A random value within the bounds of `range`. @inlinable public static func random(in range: ClosedRange<Self>) -> Self { var g = SystemRandomNumberGenerator() return Self.random(in: range, using: &g) } }
apache-2.0
a0fd478519f0cbae30bff18f2a7d2c88
37.321445
94
0.641161
4.101174
false
false
false
false
calleerlandsson/Tofu
Tofu/AlgorithmsViewController.swift
1
1609
import UIKit private let algorithmCellIdentifier = "AlgorithmCell" class AlgorithmsViewController: UITableViewController { var algorithms = [Algorithm]() var selected: Algorithm! var delegate: AlgorithmSelectionDelegate? // MARK: UITableViewDataSource override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return algorithms.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: algorithmCellIdentifier, for: indexPath) let algorithm = algorithms[indexPath.row] cell.textLabel?.text = algorithm.name cell.accessoryType = selected == algorithm ? .checkmark : .none return cell } // MARK: UITableViewDelegate override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let previouslySelectedCell = tableView.cellForRow( at: IndexPath(row: algorithms.firstIndex(of: selected)!, section: 0))! previouslySelectedCell.accessoryType = .none let selectedCell = tableView.cellForRow(at: indexPath)! selectedCell.accessoryType = .checkmark selected = algorithms[indexPath.row] delegate?.selectAlgorithm(selected) } }
isc
98c9b3f5ef8d736d4313846d3745115d
37.309524
98
0.666252
5.893773
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/Utility/Ratings/AppRatingsUtility.swift
2
15216
import Foundation /// This class will help track whether or not a user should be prompted for an /// app review. This class is loosely based on /// [Appirater](https://github.com/arashpayan/appirater) /// class AppRatingUtility: NSObject { /// Sets the number of system wide significant events are required when /// calling `shouldPromptForAppReview`. Ideally this number should be a /// number less than the total of all the significant event counts for each /// section so as to trigger the review prompt for a fairly active user who /// uses the app in a broad fashion. /// @objc var systemWideSignificantEventCountRequiredForPrompt: Int = 1 /// The App Review URL that we send off to UIApplication to open up the app /// store review page. /// @objc var appReviewUrl: URL = Constants.defaultAppReviewURL /// Sets the number of days that have to pass between AppReview prompts /// Apple only allows 3 prompts per year. We're trying to be a bit more conservative and are doing /// up to 2 times a year (183 = round(365/2)). @objc var numberOfDaysToWaitBetweenPrompts: Int = 183 /// A value to indicate whether this launch was an upgrade from a previous version var didUpgradeVersion: Bool = false private let defaults: UserDefaults private var sections = [String: Section]() private var promptingDisabledRemote = false /// Don't prompt for reviews for internal builds /// http://stackoverflow.com/questions/26081543/how-to-tell-at-runtime-whether-an-ios-app-is-running-through-a-testflight-beta-i?noredirect=1&lq=1 /// private var promptingDisabledLocal: Bool = { guard let path = Bundle.main.appStoreReceiptURL?.path else { return false } return path.contains("sandboxReceipt") }() private var promptingDisabled: Bool { return promptingDisabledRemote || promptingDisabledLocal } @objc static let shared = AppRatingUtility(defaults: UserDefaults.standard) @objc init(defaults: UserDefaults) { self.defaults = defaults } /// This should be called with the current App Version so as to setup /// internal tracking. /// /// - Parameters: /// - version: version number of the app, e.g. CFBundleShortVersionString /// @objc func setVersion(_ version: String) { let trackingVersion = defaults.string(forKey: Key.currentVersion) ?? version defaults.set(version, forKey: Key.currentVersion) if trackingVersion == version { incrementUseCount() } else { didUpgradeVersion = true let shouldSkipRating = shouldSkipRatingForCurrentVersion() resetValuesForNewVersion() resetReviewPromptDisabledStatus() if shouldSkipRating { checkNewVersionNeedsSkipping() } } } /// This checks if we've disabled app review prompts for a feature or at a /// global level /// @objc func checkIfAppReviewPromptsHaveBeenDisabled(success: (() -> Void)?, failure: (() -> Void)?) { let session = URLSession(configuration: URLSessionConfiguration.ephemeral) let task = session.dataTask(with: Constants.promptDisabledURL) { [weak self] data, _, error in guard let this = self else { return } guard let data = data, error == nil else { this.resetReviewPromptDisabledStatus() failure?() return } guard let object = try? JSONSerialization.jsonObject(with: data, options: []), let response = object as? [String: AnyObject] else { this.resetReviewPromptDisabledStatus() failure?() return } this.promptingDisabledRemote = (response["all-disabled"] as? NSString)?.boolValue ?? false for section in this.sections.keys { let key = "\(section)-disabled" let disabled = (response[key] as? NSString)?.boolValue ?? false this.sections[section]?.enabled = !disabled } if let urlString = response["app-review-url"] as? String, !urlString.isEmpty, let url = URL(string: urlString) { this.appReviewUrl = url } success?() } task.resume() } /// Registers a granular section to be tracked /// /// - Parameters: /// - section: Section name, e.g. "Notifications" /// - significantEventCount: The number of significant events required to trigger an app rating prompt for this particular section. /// @objc(registerSection:withSignificantEventCount:) func register(section: String, significantEventCount count: Int) { sections[section] = Section(significantEventCount: count, enabled: true) } /// Increments significant events app wide. /// @objc func incrementSignificantEvent() { incrementStoredValue(key: Key.significantEventCount) } /// Increments significant events for just this particular section. /// @objc(incrementSignificantEventForSection:) func incrementSignificantEvent(section: String) { guard sections[section] != nil else { assertionFailure("Invalid section \(section)") return } let key = significantEventCountKey(section: section) incrementStoredValue(key: key) } /// Indicates that the user didn't want to review the app or leave feedback /// for this version. /// @objc func declinedToRateCurrentVersion() { defaults.set(true, forKey: Key.declinedToRateCurrentVersion) defaults.set(2, forKey: Key.numberOfVersionsToSkipPrompting) } /// Indicates that the user decided to give feedback for this version. /// @objc func gaveFeedbackForCurrentVersion() { defaults.set(true, forKey: Key.gaveFeedbackForCurrentVersion) } /// Indicates that the use rated the current version of the app. /// @objc func ratedCurrentVersion() { defaults.set(true, forKey: Key.ratedCurrentVersion) } /// Indicates that the user didn't like the current version of the app. /// @objc func dislikedCurrentVersion() { incrementStoredValue(key: Key.userDislikeCount) defaults.set(true, forKey: Key.dislikedCurrentVersion) defaults.set(2, forKey: Key.numberOfVersionsToSkipPrompting) } /// Indicates the user did like the current version of the app. /// @objc func likedCurrentVersion() { incrementStoredValue(key: Key.userLikeCount) defaults.set(true, forKey: Key.likedCurrentVersion) defaults.set(1, forKey: Key.numberOfVersionsToSkipPrompting) } /// Indicates whether enough time has passed since we last prompted the user for their opinion. /// @objc func enoughTimePassedSinceLastPrompt()-> Bool { if let lastPromptDate = defaults.value(forKeyPath: Key.lastPromptToRateDate), let date = lastPromptDate as? Date, let days = Calendar.current.dateComponents([.day], from: date, to: Date()).day { return days > numberOfDaysToWaitBetweenPrompts } return true } /// Checks if the user should be prompted for an app review based on /// `systemWideSignificantEventsCount` and also if the user hasn't been /// configured to skip being prompted for this release. /// /// Note that this method will check to see if app review prompts on a /// global basis have been shut off. /// @objc func shouldPromptForAppReview() -> Bool { if !enoughTimePassedSinceLastPrompt() || shouldSkipRatingForCurrentVersion() || promptingDisabled { return false } let events = systemWideSignificantEventCount() let required = systemWideSignificantEventCountRequiredForPrompt return events >= required } /// Checks if the user should be prompted for an app review based on the /// number of significant events configured for this particular section and /// if the user hasn't been configured to skip being prompted for this /// release. /// /// Note that this method will check to see if prompts for this section have /// been shut off entirely. /// @objc(shouldPromptForAppReviewForSection:) func shouldPromptForAppReview(section name: String) -> Bool { guard let section = sections[name] else { assertionFailure("Invalid section \(name)") return false } if !enoughTimePassedSinceLastPrompt() || shouldSkipRatingForCurrentVersion() || promptingDisabled || !section.enabled { return false } let key = significantEventCountKey(section: name) let events = defaults.integer(forKey: key) let required = section.significantEventCount return events >= required } /// Records a prompt for a review /// @objc func userWasPromptedToReview() { defaults.set(Date(), forKey: Key.lastPromptToRateDate) } /// Checks if the user has ever indicated that they like the app. /// @objc func hasUserEverLikedApp() -> Bool { return defaults.integer(forKey: Key.userLikeCount) > 0 } /// Checks if the user has ever indicated they dislike the app. /// @objc func hasUserEverDislikedApp() -> Bool { return defaults.integer(forKey: Key.userDislikeCount) > 0 } // MARK: - Private private func incrementUseCount() { incrementStoredValue(key: Key.useCount) } private func significantEventCountKey(section: String) -> String { return "\(Key.significantEventCount)_\(section)" } private func resetValuesForNewVersion() { defaults.removeObject(forKey: Key.significantEventCount) defaults.removeObject(forKey: Key.ratedCurrentVersion) defaults.removeObject(forKey: Key.declinedToRateCurrentVersion) defaults.removeObject(forKey: Key.gaveFeedbackForCurrentVersion) defaults.removeObject(forKey: Key.dislikedCurrentVersion) defaults.removeObject(forKey: Key.likedCurrentVersion) defaults.removeObject(forKey: Key.skipRatingCurrentVersion) for sectionName in sections.keys { defaults.removeObject(forKey: significantEventCountKey(section: sectionName)) } } private func resetReviewPromptDisabledStatus() { promptingDisabledRemote = false for key in sections.keys { sections[key]?.enabled = true } } private func checkNewVersionNeedsSkipping() { let toSkip = defaults.integer(forKey: Key.numberOfVersionsToSkipPrompting) let skipped = defaults.integer(forKey: Key.numberOfVersionsSkippedPrompting) if toSkip > 0 { if skipped < toSkip { defaults.set(skipped + 1, forKey: Key.numberOfVersionsSkippedPrompting) defaults.set(true, forKey: Key.skipRatingCurrentVersion) } else { defaults.removeObject(forKey: Key.numberOfVersionsSkippedPrompting) defaults.removeObject(forKey: Key.numberOfVersionsToSkipPrompting) } } } private func shouldSkipRatingForCurrentVersion() -> Bool { let interactedWithAppReview = defaults.bool(forKey: Key.ratedCurrentVersion) || defaults.bool(forKey: Key.declinedToRateCurrentVersion) || defaults.bool(forKey: Key.gaveFeedbackForCurrentVersion) || defaults.bool(forKey: Key.likedCurrentVersion) || defaults.bool(forKey: Key.dislikedCurrentVersion) let skipRatingCurrentVersion = defaults.bool(forKey: Key.skipRatingCurrentVersion) return interactedWithAppReview || skipRatingCurrentVersion } private func incrementStoredValue(key: String) { var value = defaults.integer(forKey: key) value += 1 defaults.set(value, forKey: key) } private func systemWideSignificantEventCount() -> Int { var total = defaults.integer(forKey: Key.significantEventCount) sections.keys.map(significantEventCountKey).forEach { key in total += defaults.integer(forKey: key) } return total } // MARK: - Debug override var debugDescription: String { var state = [String: Any]() defaults.dictionaryRepresentation() .filter({ key, _ in key.hasPrefix("AppRating") }) .forEach { key, value in let cleanKey = (try? key.removingPrefix(pattern: "AppRatings?")) ?? key state[cleanKey] = defaults.object(forKey: key) } state["SystemWideSignificantEventCountRequiredForPrompt"] = systemWideSignificantEventCountRequiredForPrompt state["PromptingDisabledRemote"] = promptingDisabledRemote state["PromptingDisabledLocal"] = promptingDisabledLocal return "<AppRatingUtility state: \(state), sections: \(sections)>" } // MARK: - Testing // Overrides promptingDisabledLocal. For testing purposes only. // @objc func _overridePromptingDisabledLocal(_ disabled: Bool) { promptingDisabledLocal = disabled } // Overrides lastPromptToRateDate. For testing purposes only. // @objc func _overrideLastPromptToRateDate(_ date: Date) { defaults.set(date, forKey: Key.lastPromptToRateDate) } // MARK: - Subtypes private struct Section { var significantEventCount: Int var enabled: Bool } // MARK: - Constants private enum Key { static let currentVersion = "AppRatingCurrentVersion" static let significantEventCount = "AppRatingSignificantEventCount" static let useCount = "AppRatingUseCount" static let numberOfVersionsSkippedPrompting = "AppRatingsNumberOfVersionsSkippedPrompt" static let numberOfVersionsToSkipPrompting = "AppRatingsNumberOfVersionsToSkipPrompting" static let skipRatingCurrentVersion = "AppRatingsSkipRatingCurrentVersion" static let ratedCurrentVersion = "AppRatingRatedCurrentVersion" static let declinedToRateCurrentVersion = "AppRatingDeclinedToRateCurrentVersion" static let gaveFeedbackForCurrentVersion = "AppRatingGaveFeedbackForCurrentVersion" static let dislikedCurrentVersion = "AppRatingDislikedCurrentVersion" static let likedCurrentVersion = "AppRatingLikedCurrentVersion" static let userLikeCount = "AppRatingUserLikeCount" static let userDislikeCount = "AppRatingUserDislikeCount" static let lastPromptToRateDate = "AppRatingLastPromptToRateDate" } private enum Constants { static let defaultAppReviewURL = URL(string: "https://itunes.apple.com/app/id\(AppConstants.itunesAppID)?mt=8&action=write-review")! static let promptDisabledURL = URL(string: "https://api.wordpress.org/iphoneapp/app-review-prompt-check/1.0/")! } }
gpl-2.0
722eb28627b728cbfef0906aa74bf5b0
38.216495
150
0.662986
4.905222
false
false
false
false
lemberg/connfa-ios
Connfa/Classes/FloorPlans/FloorPlanCollectionViewCell.swift
1
3601
// // FloorPlanCollectionViewCell.swift // Connfa // // Created by Marian Fedyk on 7/17/17. // Copyright (c) 2017 Lemberg Solution Ltd. All rights reserved. // import UIKit class FloorPlanCollectionViewCell: UICollectionViewCell { let maximumZoomScale: CGFloat = 5.0 let numberOfTaps: Int = 2 @IBOutlet private weak var activityIndicator: UIActivityIndicatorView! @IBOutlet private weak var floorPlanScrollView: UIScrollView! @IBOutlet private weak var imageView: UIImageView! private var imageURL: String! private var image: UIImage? { didSet { imageView.image = image imageView.frame.origin = CGPoint.zero floorPlanScrollView.contentSize = self.imageView.bounds.size setZoomScale() setContentInsets() } } private lazy var minZoomScale: CGFloat = { floorPlanScrollView.bounds = self.bounds let widthScale = self.floorPlanScrollView.bounds.width / self.imageView.bounds.width let heightScale = self.floorPlanScrollView.bounds.height / self.imageView.bounds.height return min(widthScale, heightScale) }() override func awakeFromNib() { setupGestureRecognizer() floorPlanScrollView.delegate = self activityIndicator.startAnimating() } private func setupGestureRecognizer() { let doubleTap = UITapGestureRecognizer(target: self, action: #selector(doubleTapAction)) doubleTap.numberOfTapsRequired = numberOfTaps floorPlanScrollView.addGestureRecognizer(doubleTap) } private func setZoomScale() { floorPlanScrollView.maximumZoomScale = maximumZoomScale floorPlanScrollView.minimumZoomScale = minZoomScale floorPlanScrollView.zoomScale = minZoomScale } private func setContentInsets() { let verticalPading = imageView.frame.height < floorPlanScrollView.frame.height ? (floorPlanScrollView.frame.height - imageView.frame.height) / 2 : 0 let horizontalPading = imageView.frame.width < floorPlanScrollView.frame.width ? (floorPlanScrollView.frame.width - imageView.frame.width) / 2 : 0 floorPlanScrollView.contentInset = UIEdgeInsets(top: verticalPading, left: horizontalPading, bottom: verticalPading, right: horizontalPading) } private func zoomRectForScale(scale: CGFloat, center: CGPoint) -> CGRect { var zoomRect = CGRect.zero zoomRect.size.height = imageView.frame.size.height / scale zoomRect.size.width = imageView.frame.size.width / scale let newCenter = imageView.convert(center, from: floorPlanScrollView) zoomRect.origin.x = newCenter.x - (zoomRect.size.width / 2.0) zoomRect.origin.y = newCenter.y - (zoomRect.size.height / 2.0) return zoomRect } func fill(with floorPlan: FloorPlanModel) { imageURL = floorPlan.floorPlanImageURL imageView.image = nil activityIndicator.startAnimating() cacheImage(from: imageURL) { (image, key) in if key == self.imageURL { self.activityIndicator.stopAnimating() self.image = image } } } func zoomOut() { floorPlanScrollView.setZoomScale(minZoomScale, animated: false) } @objc func doubleTapAction(recognizer: UITapGestureRecognizer) { if floorPlanScrollView.zoomScale > minZoomScale { floorPlanScrollView.setZoomScale(minZoomScale, animated: true) } else { floorPlanScrollView.zoom(to : zoomRectForScale(scale: maximumZoomScale, center: recognizer.location(in: recognizer.view)), animated: true) } } } extension FloorPlanCollectionViewCell: UIScrollViewDelegate { func viewForZooming(in scrollView: UIScrollView) -> UIView? { return imageView } }
apache-2.0
ba4d634da753b2275557a9a404181dca
34.653465
152
0.737573
4.535264
false
false
false
false
simeonpp/home-hunt
ios-client/HomeHunt/AppDelegate.swift
1
4581
// // AppDelegate.swift // HomeHunt // // Created by Kolio Kolev on 4/1/17. // Copyright © 2017 SP. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded 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. */ let container = NSPersistentContainer(name: "HomeHunt") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() 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. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() 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 fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
mit
4f7a21326aa6d8ca414664db337f5746
48.247312
285
0.685153
5.834395
false
false
false
false
Aioria1314/WeiBo
WeiBo/WeiBo/Classes/Tools/Extension/NSAttributedString+Extension.swift
1
766
// // NSAttributedString+Extension.swift // WeiBo // // Created by Aioria on 2017/4/8. // Copyright © 2017年 Aioria. All rights reserved. // import UIKit extension NSAttributedString { class func attributedStringWithEmotionModel(emoticonModel: ZXCEmoticonModel, font: UIFont) -> NSAttributedString { let image = UIImage(named: emoticonModel.path!) let attachMent = ZXCTextAttachment() attachMent.emoticonModel = emoticonModel attachMent.image = image let linHeight = font.lineHeight attachMent.bounds = CGRect(x: 0, y: -4, width: linHeight, height: linHeight) return NSAttributedString(attachment: attachMent) } }
mit
63c361115400d5686d664529eab41b6f
22.84375
118
0.630406
4.568862
false
false
false
false
stephentyrone/swift
test/SourceKit/CodeComplete/complete_checkdeps_bridged.swift
6
2505
import ClangFW import SwiftFW func foo() { /*HERE*/ } // REQUIRES: shell // RUN: %empty-directory(%t/Frameworks) // RUN: %empty-directory(%t/MyProject) // RUN: COMPILER_ARGS=( \ // RUN: -target %target-triple \ // RUN: -module-name MyProject \ // RUN: -F %t/Frameworks \ // RUN: -I %t/MyProject \ // RUN: -import-objc-header %t/MyProject/Bridging.h \ // RUN: %t/MyProject/Library.swift \ // RUN: %s \ // RUN: ) // RUN: INPUT_DIR=%S/Inputs/checkdeps // RUN: DEPCHECK_INTERVAL=1 // RUN: SLEEP_TIME=2 // RUN: cp -R $INPUT_DIR/MyProject %t/ // RUN: cp -R $INPUT_DIR/ClangFW.framework %t/Frameworks/ // RUN: %empty-directory(%t/Frameworks/SwiftFW.framework/Modules/SwiftFW.swiftmodule) // RUN: %target-swift-frontend -emit-module -module-name SwiftFW -o %t/Frameworks/SwiftFW.framework/Modules/SwiftFW.swiftmodule/%target-swiftmodule-name $INPUT_DIR/SwiftFW_src/Funcs.swift // RUN: %sourcekitd-test \ // RUN: -req=global-config -completion-check-dependency-interval ${DEPCHECK_INTERVAL} == \ // RUN: -shell -- echo "### Initial" == \ // RUN: -req=complete -pos=5:3 %s -- ${COMPILER_ARGS[@]} == \ // RUN: -shell -- echo '### Modify bridging header library file' == \ // RUN: -shell -- sleep $SLEEP_TIME == \ // RUN: -shell -- cp -R $INPUT_DIR/MyProject_mod/LocalCFunc.h %t/MyProject/ == \ // RUN: -req=complete -pos=5:3 %s -- ${COMPILER_ARGS[@]} == \ // RUN: -shell -- echo '### Fast completion' == \ // RUN: -shell -- sleep $SLEEP_TIME == \ // RUN: -req=complete -pos=5:3 %s -- ${COMPILER_ARGS[@]} \ // RUN: | %FileCheck %s // CHECK-LABEL: ### Initial // CHECK: key.results: [ // CHECK-DAG: key.description: "clangFWFunc()" // CHECK-DAG: key.description: "swiftFWFunc()" // CHECK-DAG: key.description: "localClangFunc()" // CHECK-DAG: key.description: "localSwiftFunc()" // CHECK: ] // CHECK-NOT: key.reusingastcontext: 1 // CHECK-LABEL: ### Modify bridging header library file // CHECK: key.results: [ // CHECK-DAG: key.description: "clangFWFunc()" // CHECK-DAG: key.description: "swiftFWFunc()" // CHECK-DAG: key.description: "localClangFunc_mod()" // CHECK-DAG: key.description: "localSwiftFunc()" // CHECK: ] // CHECK-NOT: key.reusingastcontext: 1 // CHECK-LABEL: ### Fast completion // CHECK: key.results: [ // CHECK-DAG: key.description: "clangFWFunc()" // CHECK-DAG: key.description: "swiftFWFunc()" // CHECK-DAG: key.description: "localClangFunc_mod()" // CHECK-DAG: key.description: "localSwiftFunc()" // CHECK: ] // CHECK: key.reusingastcontext: 1
apache-2.0
6f4096750c169e6dab1daa2955073b1d
32.851351
187
0.650699
3.096415
false
false
false
false
pantuspavel/PPEventRegistryAPI
PPEventRegistryAPI/PPEventRegistryAPITests/Classes/Transport/PPTransportSpec.swift
1
6191
// // PPTransportSpec.swift // PPEventRegistryAPI // // Created by Pavel Pantus on 7/16/16. // Copyright © 2016 Pavel Pantus. All rights reserved. // import Quick import Nimble import OHHTTPStubs @testable import PPEventRegistryAPI class PPTransportSpec: QuickSpec { override func spec() { describe("HttpMethod") { it ("Get case is in place") { expect(PPHttpMethod(rawValue: "Get")).to(equal(PPHttpMethod.Get)) } it ("Post case is in place") { expect(PPHttpMethod(rawValue: "Post")).to(equal(PPHttpMethod.Post)) } } describe("Controller") { it("Login controller is in place") { expect(PPController(rawValue: "Login")).to(equal(PPController.Login)) } it("Overview controller is in place") { expect(PPController(rawValue: "Overview")).to(equal(PPController.Overview)) } it("Event controller is in place") { expect(PPController(rawValue: "Event")).to(equal(PPController.Event)) } } describe("postRequest") { let transport = PPTransport() beforeEach() { PPTransport.stubEmptyResponse() } afterEach() { OHHTTPStubs.removeAllStubs() } it("is safe to use from multiple threads") { waitUntil(timeout: 5) { done in DispatchQueue.global(qos: DispatchQoS.QoSClass.default).async { for _ in 1...100 { transport.postRequest(controller: .Event, method: .Get, parameters: [:]) { _ in } } } DispatchQueue.global(qos: DispatchQoS.QoSClass.userInitiated).async { for _ in 1...100 { transport.postRequest(controller: .Overview, method: .Post, parameters: [:]) { _ in } } } DispatchQueue.global(qos: DispatchQoS.QoSClass.background).async { for _ in 1...130 { transport.postRequest(controller: .Overview, method: .Post, parameters: [:]) { _ in } } done() } DispatchQueue.global(qos: DispatchQoS.QoSClass.utility).async { for _ in 1...100 { transport.postRequest(controller: .Overview, method: .Post, parameters: [:]) { _ in } } } DispatchQueue.global(qos: DispatchQoS.QoSClass.userInteractive).async { for _ in 1...100 { transport.postRequest(controller: .Login, method: .Get, parameters: [:]) { _ in } } } } } it("calls back with 'Response Data is Corrupt' error in case of invalid network response") { PPTransport.stubInvalidResponse() waitUntil { done in transport.postRequest(controller: .Login, method: .Post, parameters: [:], completionHandler: { result in expect(result.error!.debugDescription).to(equal("CorruptedResponse")) done() }) } } it("calls back with 'Network Error' in case of network error") { PPTransport.stubErrorResponse() waitUntil { done in transport.postRequest(controller: .Login, method: .Post, parameters: [:], completionHandler: { result in expect(result.error!).to(equal(PPError.NetworkError("The operation couldn’t be completed. (NSURLErrorDomain error -1009.)"))) done() }) } } } describe("request(with: method: parameters:)") { let transport = PPTransport() it("returns correct request for .Overview and .Get") { let urlRequest = transport.request(with: .Overview, method: .Get, parameters: ["key1":"value1"]) expect(urlRequest.url).to(equal(URL(string: "http://eventregistry.org/json/overview?key1=value1")!)) expect(urlRequest.httpMethod).to(equal("GET")) expect(urlRequest.value(forHTTPHeaderField: "Content-Type")).to(equal("application/json")) expect(urlRequest.value(forHTTPHeaderField: "Accept")).to(equal("application/json")) } it("returns correct request for .Login and .Post") { let urlRequest = transport.request(with: .Login, method: .Post, parameters: ["key1@":"value1"]) expect(urlRequest.url).to(equal(URL(string: "http://eventregistry.org/login")!)) expect(urlRequest.httpBody).to(equal(["key1@":"value1"].pp_join().addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)?.data(using: .utf8))) expect(urlRequest.httpMethod).to(equal("POST")) expect(urlRequest.value(forHTTPHeaderField: "Content-Type")).to(equal("application/x-www-form-urlencoded")) expect(urlRequest.value(forHTTPHeaderField: "Accept")).to(equal("application/json")) } } describe("baseURI") { var transport = PPTransport() beforeEach { transport = PPTransport() } it("has http scheme by default") { expect(transport.baseURI).to(equal("http://eventregistry.org")) } it("can be changed to https scheme") { transport.transferProtocol = .https expect(transport.baseURI).to(equal("https://eventregistry.org")) } it("can be changed to http scheme") { transport.transferProtocol = .http expect(transport.baseURI).to(equal("http://eventregistry.org")) } } } }
mit
bca6328b8503c1179a6132d51ea7d639
38.666667
165
0.519877
5.11828
false
false
false
false
googleprojectzero/fuzzilli
Sources/Fuzzilli/Protobuf/ProtoUtils.swift
1
5170
// Copyright 2020 Google LLC // // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation // Protocol for objects that have a corresponding Protobuf message. protocol ProtobufConvertible { associatedtype ProtobufType func asProtobuf() -> ProtobufType init(from protobuf: ProtobufType) throws } // Cache for protobuf conversion. // This enables "compressed" protobuf encoding in which duplicate // messages can be replaced with the index of the first occurance // of the message in the serialized data. // This requires deterministic serialization to work correctly, i.e. // the nth encoded message must also be the nth decode message. class ProtoCache<T: AnyObject> { // Maps elements to their number in the protobuf message. private var indices: [ObjectIdentifier: Int]? = nil // Maps indices to their elements. private var elements = [T]() private init(useIndicesMap: Bool = true) { if useIndicesMap { indices = [:] } } static func forEncoding() -> ProtoCache { return ProtoCache(useIndicesMap: true) } static func forDecoding() -> ProtoCache { // The lookup dict is not needed for decoding return ProtoCache(useIndicesMap: false) } func get(_ i: Int) -> T? { if !elements.indices.contains(i) { return nil } return elements[i] } func get(_ k: T) -> Int? { return indices?[ObjectIdentifier(k)] } func add(_ ext: T) { let id = ObjectIdentifier(ext) if indices != nil && !indices!.keys.contains(id) { indices?[id] = elements.count } elements.append(ext) } } typealias OperationCache = ProtoCache<Operation> typealias TypeCache = ProtoCache<TypeExtension> public func encodeProtobufCorpus<T: Collection>(_ programs: T) throws -> Data where T.Element == Program { // This does streaming serialization to keep memory usage as low as possible. // Also, this uses the operation compression feature of our protobuf representation: // when the same operation occurs multiple times in the corpus, every subsequent // occurance in the protobuf is simply the index of instruction with the first occurance. // // The binary format is simply // [ program1 | program2 | ... | programN ] // where every program is encoded as // [ size without padding in bytes as uint32 | serialized program protobuf | padding ] // The padding ensures 4 byte alignment of every program. // // This must be deterministic due to the use of protobuf caches (see ProtoCache struct). var buf = Data() let opCache = OperationCache.forEncoding() let typeCache = TypeCache.forEncoding() for program in programs { let proto = program.asProtobuf(opCache: opCache, typeCache: typeCache) let serializedProgram = try proto.serializedData() var size = UInt32(serializedProgram.count).littleEndian buf.append(Data(bytes: &size, count: 4)) buf.append(serializedProgram) // Align to 4 bytes buf.append(Data(count: align(buf.count, to: 4))) } return buf } public func decodeProtobufCorpus(_ buffer: Data) throws -> [Program]{ let opCache = OperationCache.forDecoding() let typeCache = TypeCache.forDecoding() var offset = buffer.startIndex var newPrograms = [Program]() while offset + 4 <= buffer.endIndex { let value = buffer.withUnsafeBytes { $0.load(fromByteOffset: offset - buffer.startIndex, as: UInt32.self) } let size = Int(UInt32(littleEndian: value)) offset += 4 guard offset + size <= buffer.endIndex else { throw FuzzilliError.corpusImportError("Serialized corpus appears to be corrupted") } let data = buffer.subdata(in: offset..<offset+size) offset += size + align(size, to: 4) let proto = try Fuzzilli_Protobuf_Program(serializedData: data) let program = try Program(from: proto, opCache: opCache, typeCache: typeCache) newPrograms.append(program) } return newPrograms } // Make UUIDs convertible to Data, used for protobuf conversion extension UUID { var uuidData: Data { return withUnsafePointer(to: uuid) { Data(bytes: $0, count: MemoryLayout.size(ofValue: uuid)) } } init?(uuidData: Data) { guard uuidData.count == 16 else { return nil } var uuid: uuid_t = (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0) withUnsafeMutableBytes(of: &uuid) { $0.copyBytes(from: uuidData) } self.init(uuid: uuid) } }
apache-2.0
eb1f4c4b01b5f619e1855390f866dff0
34.410959
115
0.66441
4.32636
false
false
false
false
fe9lix/Protium
iOS/Protium/src/main/MainScene.swift
1
1952
import UIKit import RxSwift final class MainScene { private let context: Context private let reachabilityService: ReachabilityService private let disposeBag = DisposeBag() private var gifSearchScene: GifSearchScene? private var reachabilityUI: ReachabilityUI? init(context: Context) { self.context = context self.reachabilityService = try! DefaultReachabilityService() // Crashy crashy if Reachability can't be initialized. } // The Main Scene presents the initial Scene for searching Gifs and // provides the dependencies: A NavigationContext (list/detail screen) and the relevant Gateway. // Internally GifSearchScene then constructs the Interactor and UserInterface. func presentInContext() { gifSearchScene = GifSearchScene( context: NavigationControllerContext(parent: context), gateway: GifGateway(reachabilityService: reachabilityService)) gifSearchScene?.presentInContext() handleReachability() } // Handle Reachability: Present custom UI on top when network connection is lost. // This *could* be moved into a separate Scene as well. In this example, however, // the ReachabilityUI is simply presented via GifSearchScene's context. private func handleReachability() { reachabilityService.reachability.asDriver(onErrorJustReturn: .unreachable).drive(onNext: { status in log(status) switch status { case .reachable: self.reachabilityUI?.dismiss(animated: true) { self.reachabilityUI = nil } case .unreachable: self.reachabilityUI = ReachabilityUI.create() self.reachabilityUI?.modalTransitionStyle = .crossDissolve self.gifSearchScene?.present(self.reachabilityUI!) }}) .addDisposableTo(disposeBag) } }
mit
c830bda7e6d487f1ce53d6e3af26a452
40.531915
123
0.672131
5.483146
false
false
false
false
robinckanatzar/mcw
my-core-wellness/my-core-wellness/HomeVC.swift
1
7525
// // HomeVC.swift // my-core-wellness // // Created by Robin Kanatzar on 2/25/17. // Copyright © 2017 Robin Kanatzar. All rights reserved. // import Foundation import UIKit struct cellData { let cell : Int! let text : String! let image : UIImage! } class TableViewControllerHome : UITableViewController { @IBOutlet weak var open: UIBarButtonItem! var arrayOfCellData = [cellData]() override func viewDidLoad() { // swipe left/right gesture recognizer self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer()) // array of cell data for all variables in that cell xib arrayOfCellData = [cellData(cell: 1, text : "Physical", image : #imageLiteral(resourceName: "Physical")), cellData(cell: 2, text : "Mental", image : #imageLiteral(resourceName: "Mental")), cellData(cell: 3, text : "Emotional", image : #imageLiteral(resourceName: "Emotional")), cellData(cell: 4, text: "Extras", image: #imageLiteral(resourceName: "Extras"))] // remove separators from table view self.tableView.separatorStyle = .none // set background to light grey self.view.backgroundColor = UIColor(red: 250/255.0, green: 250/255.0, blue: 250/255.0, alpha: 1.0) // set title on navigation bar self.navigationItem.title = "My Core Wellness" // set actions for menu button to open the menu open.target = self.revealViewController() open.action = #selector(SWRevealViewController.revealToggle(_:)) navigationItem.leftBarButtonItem = open } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return arrayOfCellData.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if arrayOfCellData[indexPath.row].cell == 1 { let cell = Bundle.main.loadNibNamed("TableViewCellMainDashboard", owner: self, options: nil)?.first as! TableViewCellMainDashboard cell.mainImageView.image = arrayOfCellData[indexPath.row].image cell.mainLabel.text = arrayOfCellData[indexPath.row].text // polishing the card view cell.cardWhite.layer.masksToBounds = false cell.cardWhite.layer.shadowColor = UIColor.black.withAlphaComponent(0.2).cgColor cell.cardWhite.layer.shadowOffset = CGSize(width: 0, height: 0) cell.cardWhite.layer.shadowOpacity = 0.8 cell.cardWhite.layer.cornerRadius = 3.0 cell.contentView.backgroundColor = UIColor(red: 250/255.0, green: 250/255.0, blue: 250/255.0, alpha: 1.0) cell.cardWhite.backgroundColor = UIColor(red: 255/255.0, green: 255/255.0, blue: 255/255.0, alpha: 1.0) // set tap gesture recognizer let tapGesture = UITapGestureRecognizer(target: self, action: "tapCellOne") cell.addGestureRecognizer(tapGesture) return cell } else if arrayOfCellData[indexPath.row].cell == 2 { // else if cell == 2 do something else, use a different xib let cell = Bundle.main.loadNibNamed("TableViewCellMainDashboard", owner: self, options: nil)?.first as! TableViewCellMainDashboard cell.mainImageView.image = arrayOfCellData[indexPath.row].image cell.mainLabel.text = arrayOfCellData[indexPath.row].text cell.cardWhite.layer.masksToBounds = false cell.cardWhite.layer.shadowColor = UIColor.black.withAlphaComponent(0.2).cgColor cell.cardWhite.layer.shadowOffset = CGSize(width: 0, height: 0) cell.cardWhite.layer.shadowOpacity = 0.8 cell.cardWhite.layer.cornerRadius = 3.0 cell.contentView.backgroundColor = UIColor(red: 250/255.0, green: 250/255.0, blue: 250/255.0, alpha: 1.0) cell.cardWhite.backgroundColor = UIColor(red: 255/255.0, green: 255/255.0, blue: 255/255.0, alpha: 1.0) // set tap gesture recognizer let tapGesture = UITapGestureRecognizer(target: self, action: "tapCellTwo") cell.addGestureRecognizer(tapGesture) return cell } else if arrayOfCellData[indexPath.row].cell == 3 { let cell = Bundle.main.loadNibNamed("TableViewCellMainDashboard", owner: self, options: nil)?.first as! TableViewCellMainDashboard cell.mainImageView.image = arrayOfCellData[indexPath.row].image cell.mainLabel.text = arrayOfCellData[indexPath.row].text cell.cardWhite.layer.masksToBounds = false cell.cardWhite.layer.shadowColor = UIColor.black.withAlphaComponent(0.2).cgColor cell.cardWhite.layer.shadowOffset = CGSize(width: 0, height: 0) cell.cardWhite.layer.shadowOpacity = 0.8 cell.cardWhite.layer.cornerRadius = 3.0 cell.contentView.backgroundColor = UIColor(red: 250/255.0, green: 250/255.0, blue: 250/255.0, alpha: 1.0) cell.cardWhite.backgroundColor = UIColor(red: 255/255.0, green: 255/255.0, blue: 255/255.0, alpha: 1.0) // set tap gesture recognizer let tapGesture = UITapGestureRecognizer(target: self, action: "tapCellThree") cell.addGestureRecognizer(tapGesture) return cell } else { let cell = Bundle.main.loadNibNamed("TableViewCellMainDashboard", owner: self, options: nil)?.first as! TableViewCellMainDashboard cell.mainImageView.image = arrayOfCellData[indexPath.row].image cell.mainLabel.text = arrayOfCellData[indexPath.row].text cell.cardWhite.layer.masksToBounds = false cell.cardWhite.layer.shadowColor = UIColor.black.withAlphaComponent(0.2).cgColor cell.cardWhite.layer.shadowOffset = CGSize(width: 0, height: 0) cell.cardWhite.layer.shadowOpacity = 0.8 cell.cardWhite.layer.cornerRadius = 3.0 cell.contentView.backgroundColor = UIColor(red: 250/255.0, green: 250/255.0, blue: 250/255.0, alpha: 1.0) cell.cardWhite.backgroundColor = UIColor(red: 255/255.0, green: 255/255.0, blue: 255/255.0, alpha: 1.0) // set tap gesture recognizer let tapGesture = UITapGestureRecognizer(target: self, action: "tapCellFour") cell.addGestureRecognizer(tapGesture) return cell } } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if arrayOfCellData[indexPath.row].cell == 1 { // return the height of the cell (found in the xib file) return 100 } else { // else if cell == 2 or if cell == 3 return the height of the xib it uses return 100 } } func tapCellOne() { performSegue(withIdentifier: "segueCellOne", sender: self) } func tapCellTwo() { performSegue(withIdentifier: "segueCellTwo", sender: self) } func tapCellThree() { performSegue(withIdentifier: "segueCellThree", sender: self) } func tapCellFour() { performSegue(withIdentifier: "segueCellFour", sender: self) } }
apache-2.0
c1e198bcecf7ba6eec0a734e1526d32c
45.159509
196
0.632111
4.56
false
false
false
false
material-components/material-components-ios-codelabs
MDC-104/Swift/Starter/Shrine/Shrine/HomeViewController.swift
1
6517
/* Copyright 2018-present the Material Components for iOS authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import UIKit import MaterialComponents class HomeViewController: UICollectionViewController { var shouldDisplayLogin = false var appBarViewController = MDCAppBarViewController() override func viewDidLoad() { super.viewDidLoad() self.view.tintColor = .black self.title = "Shrine" self.view?.backgroundColor = .white self.collectionView?.backgroundColor = .clear // AppBar Setup //TODO: Remove AppBar Setup in the following six lines self.addChildViewController(self.appBarViewController) self.view.addSubview(self.appBarViewController.view) self.appBarViewController.didMove(toParentViewController: self) // Set the tracking scroll view. self.appBarViewController.headerView.trackingScrollView = self.collectionView // Setup Navigation Items let menuItemImage = UIImage(named: "MenuItem") let templatedMenuItemImage = menuItemImage?.withRenderingMode(.alwaysTemplate) let menuItem = UIBarButtonItem(image: templatedMenuItemImage, style: .plain, target: self, action: #selector(menuItemTapped(sender:))) self.navigationItem.leftBarButtonItem = menuItem let searchItemImage = UIImage(named: "SearchItem") let templatedSearchItemImage = searchItemImage?.withRenderingMode(.alwaysTemplate) let searchItem = UIBarButtonItem(image: templatedSearchItemImage, style: .plain, target: nil, action: nil) let tuneItemImage = UIImage(named: "TuneItem") let templatedTuneItemImage = tuneItemImage?.withRenderingMode(.alwaysTemplate) let tuneItem = UIBarButtonItem(image: templatedTuneItemImage, style: .plain, target: nil, action: nil) self.navigationItem.rightBarButtonItems = [ tuneItem, searchItem ] MDCAppBarColorThemer.applyColorScheme(ApplicationScheme.shared.colorScheme, to:self.appBarViewController) MDCAppBarTypographyThemer.applyTypographyScheme(ApplicationScheme.shared.typographyScheme, to: self.appBarViewController) self.collectionView!.collectionViewLayout = CustomLayout() //TODO: Register for the catalog changed notification } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if (self.collectionViewLayout is UICollectionViewFlowLayout) { let flowLayout = self.collectionViewLayout as! UICollectionViewFlowLayout let HORIZONTAL_SPACING: CGFloat = 8.0 let itemDimension: CGFloat = (self.view.frame.size.width - 3.0 * HORIZONTAL_SPACING) * 0.5 let itemSize = CGSize(width: itemDimension, height: itemDimension) flowLayout.itemSize = itemSize } if (self.shouldDisplayLogin) { let loginViewController = LoginViewController(nibName: nil, bundle: nil) self.present(loginViewController, animated: false, completion: nil) self.shouldDisplayLogin = false } } //MARK - Methods @objc func menuItemTapped(sender: Any) { let loginViewController = LoginViewController(nibName: nil, bundle: nil) self.present(loginViewController, animated: true, completion: nil) } //MARK - UICollectionViewDataSource override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { let count = Catalog.count return count } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = self.collectionView?.dequeueReusableCell(withReuseIdentifier: "ProductCell", for: indexPath) as! ProductCell let product = Catalog.productAtIndex(index: indexPath.row) cell.imageView.image = UIImage(named: product.imageName) cell.nameLabel.text = product.productName cell.priceLabel.text = product.price return cell } //TODO: Add notification Handler // Catalog Update Handler reloads the collection view is the products have changed } //MARK: - UIScrollViewDelegate // The following four methods must be forwarded to the tracking scroll view in order to implement // the Flexible Header's behavior. extension HomeViewController { override func scrollViewDidScroll(_ scrollView: UIScrollView) { if (scrollView == self.appBarViewController.headerView.trackingScrollView) { self.appBarViewController.headerView.trackingScrollDidScroll() } } override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { if (scrollView == self.appBarViewController.headerView.trackingScrollView) { self.appBarViewController.headerView.trackingScrollDidEndDecelerating() } } override func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { let headerView = self.appBarViewController.headerView if (scrollView == headerView.trackingScrollView) { headerView.trackingScrollDidEndDraggingWillDecelerate(decelerate) } } override func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { let headerView = self.appBarViewController.headerView if (scrollView == headerView.trackingScrollView) { headerView.trackingScrollWillEndDragging(withVelocity: velocity, targetContentOffset: targetContentOffset) } } }
apache-2.0
4fd3671e8042df24c70a019deb2d1d40
39.478261
97
0.686819
5.787744
false
false
false
false
mpdifran/MyoSports
MyoSports/MyoExtensions/MyoEventExtensions.swift
1
1605
// // MyoEventExtensions.swift // MyoSports // // Created by Mark DiFranco on 2015-05-28. // Copyright (c) 2015 MDF Projects. All rights reserved. // import Foundation private let separator = ", " private let carriageReturn = "\n" extension TLMOrientationEvent { func toCSV() -> String { let values = [timestamp.timeIntervalSince1970.description, quaternion.w.description, quaternion.x.description, quaternion.y.description, quaternion.z.description] return join(separator, values) + carriageReturn } } extension TLMAccelerometerEvent { func toCSV() -> String { return toCSV(vector) } func toCSV(vector: TLMVector3) -> String { let values = [timestamp.timeIntervalSince1970.description, vector.x.description, vector.y.description, vector.z.description] return join(separator, values) + carriageReturn } } extension TLMGyroscopeEvent { func toCSV() -> String { let values = [timestamp.timeIntervalSince1970.description, vector.x.description, vector.y.description, vector.z.description] return join(separator, values) + carriageReturn } } extension TLMEmgEvent { func toCSV() -> String { var values = [timestamp.timeIntervalSince1970.description] for value in rawData { values.append(value.description) } return join(separator, values) + carriageReturn } }
mit
989e83914e8a5d80b618d1158757f9ee
23.318182
66
0.606854
4.495798
false
false
false
false
Laurensesss/Learning-iOS-Programming-with-Swift
Project02_StopWatch/StopWatch/ViewController.swift
1
4585
// // ViewController.swift // StopWatch // // Created by 石韬 on 16/5/20. // Copyright © 2016年 石韬. All rights reserved. // import UIKit class ViewController: UIViewController { // MARK: - Properties @IBOutlet var orangeButtons: [UIButton]! @IBOutlet weak var elapsedTimeLabel: UILabel! let stopWatch = StopWatch() var lastTime: NSTimeInterval = 0 var buttonColor = (orange: UIColor.orangeColor().CGColor, gray: UIColor.darkGrayColor().CGColor) // MARK: - Methods func updateElapsedTimeLabel(timer: NSTimer?) { if stopWatch.isRunning { elapsedTimeLabel.text = stopWatch.elapsedTimeAsString(lastTime) } else { timer?.invalidate() } } @IBAction func startButtonTapped(sender: UIButton) { elapsedTimeLabel.text = "00:00.0" // String(format: "%02d:%02d.%d", Int(lastTime / 60), Int(lastTime % 60), Int(lastTime * 10 % 10)) stopWatch.start() // elapsedTimeLabel.text = stopWatch.elapsedTimeAsString(lastTime) NSTimer.scheduledTimerWithTimeInterval(0.05, target: self, selector: "updateElapsedTimeLabel:", userInfo: nil, repeats: true) setButtonStyle() } @IBAction func stopButtonTapped(sender: UIButton) { lastTime = 0 stopWatch.stop() setButtonStyle() } @IBAction func pauseButtonTapped(sender: UIButton) { lastTime = stopWatch.elapsedTime(lastTime) stopWatch.pause() setButtonStyle() } @IBAction func resumeButtonTapped(sender: UIButton) { stopWatch.resume() // updateElapsedTimeLabel(nil) NSTimer.scheduledTimerWithTimeInterval(0.05, target: self, selector: "updateElapsedTimeLabel:", userInfo: nil, repeats: true) setButtonStyle() } @IBAction func returnButtonTapped(sender: UIButton) { lastTime = 0 stopWatch.stop() elapsedTimeLabel.text = "00:00.0" setButtonStyle() } override func viewDidLoad() { super.viewDidLoad() // Set the buttons' style. for orangeButton in orangeButtons { orangeButton.layer.cornerRadius = 5 } setButtonStyle() } // Set buttons' style according to different situations. func setButtonStyle() { for orangeButton in orangeButtons{ switch (stopWatch.isRunning, stopWatch.isPaused) { case (false, false): switch orangeButton.currentTitle! { case "Start": orangeButton.enabled = true orangeButton.layer.backgroundColor = buttonColor.orange case "Stop": orangeButton.enabled = false orangeButton.layer.backgroundColor = buttonColor.gray case "Pause": orangeButton.enabled = false orangeButton.layer.backgroundColor = buttonColor.gray case "Resume": orangeButton.enabled = false orangeButton.layer.backgroundColor = buttonColor.gray default: break } case (true,false): switch orangeButton.currentTitle! { case "Start": orangeButton.enabled = false orangeButton.layer.backgroundColor = buttonColor.gray case "Stop": orangeButton.enabled = true orangeButton.layer.backgroundColor = buttonColor.orange case "Pause": orangeButton.enabled = true orangeButton.layer.backgroundColor = buttonColor.orange case "Resume": orangeButton.enabled = false orangeButton.layer.backgroundColor = buttonColor.gray default: break } case (_,true): switch orangeButton.currentTitle! { case "Start": orangeButton.enabled = false orangeButton.layer.backgroundColor = buttonColor.gray case "Stop": orangeButton.enabled = false orangeButton.layer.backgroundColor = buttonColor.gray case "Pause": orangeButton.enabled = false orangeButton.layer.backgroundColor = buttonColor.gray case "Resume": orangeButton.enabled = true orangeButton.layer.backgroundColor = buttonColor.orange default: break } } } } }
apache-2.0
ee0c47f0fa9e00a99a11908d426325bf
33.651515
133
0.583734
5.269585
false
false
false
false
groue/GRDB.swift
Tests/GRDBTests/DatabaseRegionTests.swift
1
38179
import XCTest @testable import GRDB class DatabaseRegionTests : GRDBTestCase { func testRegionEquatable() { // An array of distinct selection infos let regions = [ DatabaseRegion.fullDatabase, DatabaseRegion(), DatabaseRegion(table: "foo"), DatabaseRegion(table: "foo", columns: ["a", "b"]), DatabaseRegion(table: "foo", columns: ["b", "c"]), DatabaseRegion(table: "foo", rowIds: [1, 2]), DatabaseRegion(table: "foo", rowIds: [2, 3]), DatabaseRegion(table: "bar")] for (i1, s1) in regions.enumerated() { for (i2, s2) in regions.enumerated() { if i1 == i2 { XCTAssertEqual(s1, s2) } else { XCTAssertNotEqual(s1, s2) } } } // Case insensitivity XCTAssertEqual( DatabaseRegion(table: "foo"), DatabaseRegion(table: "FOO")) XCTAssertEqual( DatabaseRegion(table: "foo", columns: ["a", "b"]), DatabaseRegion(table: "FOO", columns: ["A", "B"])) } func testRegionUnion() { let regions = [ DatabaseRegion.fullDatabase, DatabaseRegion(), DatabaseRegion(table: "foo"), DatabaseRegion(table: "foo", columns: ["a", "b"]), DatabaseRegion(table: "foo", columns: ["b", "c"]), DatabaseRegion(table: "foo", rowIds: [1, 2]), DatabaseRegion(table: "foo", rowIds: [2, 3]), DatabaseRegion(table: "bar")] var unions: [DatabaseRegion] = [] for s1 in regions { for s2 in regions { unions.append(s1.union(s2)) } } XCTAssertEqual(unions.map(\.description), [ "full database", "full database", "full database", "full database", "full database", "full database", "full database", "full database", "full database", "empty", "foo(*)", "foo(a,b)", "foo(b,c)", "foo(*)[1,2]", "foo(*)[2,3]", "bar(*)", "full database", "foo(*)", "foo(*)", "foo(*)", "foo(*)", "foo(*)", "foo(*)", "bar(*),foo(*)", "full database", "foo(a,b)", "foo(*)", "foo(a,b)", "foo(a,b,c)", "foo(*)", "foo(*)", "bar(*),foo(a,b)", "full database", "foo(b,c)", "foo(*)", "foo(a,b,c)", "foo(b,c)", "foo(*)", "foo(*)", "bar(*),foo(b,c)", "full database", "foo(*)[1,2]", "foo(*)", "foo(*)", "foo(*)", "foo(*)[1,2]", "foo(*)[1,2,3]", "bar(*),foo(*)[1,2]", "full database", "foo(*)[2,3]", "foo(*)", "foo(*)", "foo(*)", "foo(*)[1,2,3]", "foo(*)[2,3]", "bar(*),foo(*)[2,3]", "full database", "bar(*)", "bar(*),foo(*)", "bar(*),foo(a,b)", "bar(*),foo(b,c)", "bar(*),foo(*)[1,2]", "bar(*),foo(*)[2,3]", "bar(*)"]) } func testRegionUnionOfColumnsAndRows() { let regions = [ DatabaseRegion(table: "foo", columns: ["a"]).intersection(DatabaseRegion(table: "foo", rowIds: [1])), DatabaseRegion(table: "foo", columns: ["b"]).intersection(DatabaseRegion(table: "foo", rowIds: [2])), ] var unions: [DatabaseRegion] = [] for s1 in regions { for s2 in regions { unions.append(s1.union(s2)) } } XCTAssertEqual(unions.map(\.description), ["foo(a)[1]", "foo(a,b)[1,2]", "foo(a,b)[1,2]", "foo(b)[2]"]) } func testRegionIntersection() { let regions = [ DatabaseRegion.fullDatabase, DatabaseRegion(), DatabaseRegion(table: "foo"), DatabaseRegion(table: "foo", columns: ["a", "b"]), DatabaseRegion(table: "foo", columns: ["b", "c"]), DatabaseRegion(table: "foo", rowIds: [1, 2]), DatabaseRegion(table: "foo", rowIds: [2, 3]), DatabaseRegion(table: "bar")] var intersection: [DatabaseRegion] = [] for s1 in regions { for s2 in regions { intersection.append(s1.intersection(s2)) } } XCTAssertEqual(intersection.map(\.description), [ "full database", "empty", "foo(*)", "foo(a,b)", "foo(b,c)", "foo(*)[1,2]", "foo(*)[2,3]", "bar(*)", "empty", "empty", "empty", "empty", "empty", "empty", "empty", "empty", "foo(*)", "empty", "foo(*)", "foo(a,b)", "foo(b,c)", "foo(*)[1,2]", "foo(*)[2,3]", "empty", "foo(a,b)", "empty", "foo(a,b)", "foo(a,b)", "foo(b)", "foo(a,b)[1,2]", "foo(a,b)[2,3]", "empty", "foo(b,c)", "empty", "foo(b,c)", "foo(b)", "foo(b,c)", "foo(b,c)[1,2]", "foo(b,c)[2,3]", "empty", "foo(*)[1,2]", "empty", "foo(*)[1,2]", "foo(a,b)[1,2]", "foo(b,c)[1,2]", "foo(*)[1,2]", "foo(*)[2]", "empty", "foo(*)[2,3]", "empty", "foo(*)[2,3]", "foo(a,b)[2,3]", "foo(b,c)[2,3]", "foo(*)[2]", "foo(*)[2,3]", "empty", "bar(*)", "empty", "empty", "empty", "empty", "empty", "empty", "bar(*)"]) } func testRegionIntersectionOfColumnsAndRows() { let regions = [ DatabaseRegion(table: "foo", columns: ["a"]).intersection(DatabaseRegion(table: "foo", rowIds: [1])), DatabaseRegion(table: "foo", columns: ["b"]).intersection(DatabaseRegion(table: "foo", rowIds: [2])), ] var intersection: [DatabaseRegion] = [] for s1 in regions { for s2 in regions { intersection.append(s1.intersection(s2)) } } XCTAssertEqual(intersection.map(\.description), ["foo(a)[1]", "empty", "empty", "foo(b)[2]"]) } func testSelectStatement_rowid() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.execute(sql: "CREATE TABLE foo (id INTEGER PRIMARY KEY, name TEXT)") do { // Select the rowid let statement = try db.makeStatement(sql: "SELECT id FROM foo") let expectedRegion = DatabaseRegion(table: "foo") XCTAssertEqual(statement.databaseRegion, expectedRegion) XCTAssertEqual(statement.databaseRegion.description, "foo(*)") } do { let statement = try db.makeStatement(sql: "SELECT ID FROM FOO") let expectedRegion = DatabaseRegion(table: "foo") XCTAssertEqual(statement.databaseRegion, expectedRegion) XCTAssertEqual(statement.databaseRegion.description, "foo(*)") } } } func testSelectStatement() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.execute(sql: "CREATE TABLE foo (id INTEGER PRIMARY KEY, name TEXT)") try db.execute(sql: "CREATE TABLE bar (id INTEGER PRIMARY KEY, fooId INTEGER)") do { let statement = try db.makeStatement(sql: "SELECT name FROM foo") let expectedRegion = DatabaseRegion(table: "foo", columns: ["name"]) XCTAssertEqual(statement.databaseRegion, expectedRegion) XCTAssertEqual(statement.databaseRegion.description, "foo(name)") } do { let statement = try db.makeStatement(sql: "SELECT NAME FROM FOO") let expectedRegion = DatabaseRegion(table: "foo", columns: ["name"]) XCTAssertEqual(statement.databaseRegion, expectedRegion) XCTAssertEqual(statement.databaseRegion.description, "foo(name)") } do { let statement = try db.makeStatement(sql: "SELECT foo.name FROM foo JOIN bar ON fooId = foo.id") let expectedRegion = DatabaseRegion(table: "foo", columns: ["name", "id"]) .union(DatabaseRegion(table: "bar", columns: ["fooId"])) XCTAssertEqual(statement.databaseRegion, expectedRegion) XCTAssertEqual(statement.databaseRegion.description, "bar(fooId),foo(id,name)") } do { let statement = try db.makeStatement(sql: "SELECT FOO.NAME FROM FOO JOIN BAR ON FOOID = FOO.ID") let expectedRegion = DatabaseRegion(table: "foo", columns: ["name", "id"]) .union(DatabaseRegion(table: "bar", columns: ["fooId"])) XCTAssertEqual(statement.databaseRegion, expectedRegion) XCTAssertEqual(statement.databaseRegion.description, "bar(fooId),foo(id,name)") } do { let statement = try db.makeStatement(sql: "SELECT COUNT(*) FROM foo") let expectedRegion = DatabaseRegion(table: "foo") XCTAssertEqual(statement.databaseRegion, expectedRegion) XCTAssertEqual(statement.databaseRegion.description, "foo(*)") } do { let statement = try db.makeStatement(sql: "SELECT COUNT(*) FROM FOO") let expectedRegion = DatabaseRegion(table: "foo") XCTAssertEqual(statement.databaseRegion, expectedRegion) XCTAssertEqual(statement.databaseRegion.description, "FOO(*)") } } } func testRegionRowIds() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.execute(sql: "CREATE TABLE foo (id INTEGER PRIMARY KEY, a TEXT)") struct Record: TableRecord { static let databaseTableName = "foo" } // Undefined rowIds do { let request = Record.all() try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)") } do { let request = Record.filter(Column("a") == 1) try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)") } do { let request = Record.filter(Column("id") >= 1) try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)") } do { let request = Record.filter((Column("id") == 1) || (Column("a") == "foo")) try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)") } // No rowId do { let request = Record.none() try XCTAssertEqual(request.databaseRegion(db).description, "empty") } do { let request = Record.filter([Int]().contains(Column("id"))) try XCTAssertEqual(request.databaseRegion(db).description, "empty") } do { let request = Record.filter([String]().contains(Column("a"))) try XCTAssertEqual(request.databaseRegion(db).description, "empty") } do { let request = Record.filter(Column("id") == nil) try XCTAssertEqual(request.databaseRegion(db).description, "empty") } do { let request = Record.filter(Column("id") === nil) try XCTAssertEqual(request.databaseRegion(db).description, "empty") } do { let request = Record.filter(nil == Column("id")) try XCTAssertEqual(request.databaseRegion(db).description, "empty") } do { let request = Record.filter(nil === Column("id")) try XCTAssertEqual(request.databaseRegion(db).description, "empty") } do { let request = Record.filter((Column("id") == 1) && (Column("id") == 2)) try XCTAssertEqual(request.databaseRegion(db).description, "empty") } do { let request = Record.filter(key: 1).filter(key: 2) try XCTAssertEqual(request.databaseRegion(db).description, "empty") } // Single rowId do { let request = Record.filter(Column("id") == 1) try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)[1]") } do { let request = Record.filter(Column("id") === 1) try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)[1]") } do { let request = Record.filter(Column("id") == 1 && Column("a") == "foo") try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)[1]") } do { let request = Record.filter(Column.rowID == 1) try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)[1]") } do { let request = Record.filter(1 == Column("id")) try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)[1]") } do { let request = Record.filter(1 === Column("id")) try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)[1]") } do { let request = Record.filter(1 === Column.rowID) try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)[1]") } do { let request = Record.filter(key: 1) try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)[1]") } do { let request = Record.filter(key: 1).filter(key: 1) try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)[1]") } do { let request = Record.filter(key: 1).filter(Column("a") == "foo") try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)[1]") } // Multiple rowIds do { let request = Record.filter(Column("id") == 1 || Column.rowID == 2) try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)[1,2]") } do { let request = Record.filter((Column("id") == 1 && Column("a") == "foo") || Column.rowID == 2) try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)[1,2]") } do { let request = Record.filter([1, 2, 3].contains(Column("id"))) try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)[1,2,3]") } do { let request = Record.filter([1, 2, 3].contains(Column.rowID)) try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)[1,2,3]") } do { let request = Record.filter([1, 2, 3].contains(Column("id")) || [2, 3, 4].contains(Column.rowID)) try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)[1,2,3,4]") } do { let request = Record.filter([1, 2, 3].contains(Column("id")) && [2, 3, 4].contains(Column.rowID)) try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)[2,3]") } do { let request = Record.filter(keys: [1, 2, 3]) try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)[1,2,3]") } } } func testDatabaseRegionOfJoinedRequests() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.execute(sql: "CREATE TABLE a (id INTEGER PRIMARY KEY, name TEXT)") try db.execute(sql: "CREATE TABLE b (id INTEGER PRIMARY KEY, name TEXT, aid INTEGER REFERENCES a(id))") try db.execute(sql: "CREATE TABLE c (id INTEGER PRIMARY KEY, name TEXT, aid INTEGER REFERENCES a(id))") struct A: TableRecord { static let databaseTableName = "a" static let b = hasOne(B.self) static let c = hasMany(C.self) } struct B: TableRecord { static let databaseTableName = "b" static let a = belongsTo(A.self) } struct C: TableRecord { static let databaseTableName = "c" } do { let request = A.filter(key: 1) .including(optional: A.b.filter(key: 2)) .including(optional: A.c.filter(keys: [1, 2, 3])) // This test will fail when we are able to improve regions of joined requestt try XCTAssertEqual(request.databaseRegion(db).description, "a(id,name)[1],b(aid,id,name),c(aid,id,name)") } do { let request = B.filter(key: 1) .including(optional: B.a.filter(key: 2) .including(optional: A.c.filter(keys: [1, 2, 3]))) // This test will fail when we are able to improve regions of joined requestt try XCTAssertEqual(request.databaseRegion(db).description, "a(id,name),b(aid,id,name)[1],c(aid,id,name)") } } } func testDatabaseRegionOfDerivedRequests() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.execute(sql: "CREATE TABLE foo (id INTEGER PRIMARY KEY, a TEXT)") struct Record: TableRecord { static let databaseTableName = "foo" } let request = Record.filter(keys: [1, 2, 3]) try XCTAssertEqual(request.databaseRegion(db).description, "foo(a,id)[1,2,3]") do { let derivedRequest = AnyFetchRequest(request) try XCTAssertEqual(derivedRequest.databaseRegion(db).description, "foo(a,id)[1,2,3]") } do { let derivedRequest: AdaptedFetchRequest = request.adapted { db in SuffixRowAdapter(fromIndex: 1) } try XCTAssertEqual(derivedRequest.databaseRegion(db).description, "foo(a,id)[1,2,3]") } } } func testUpdateStatement() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.execute(sql: "CREATE TABLE foo (id INTEGER PRIMARY KEY, bar TEXT, baz TEXT, qux TEXT)") do { let statement = try db.makeStatement(sql: "UPDATE foo SET bar = 'bar', baz = 'baz' WHERE id = 1") XCTAssertFalse(statement.invalidatesDatabaseSchemaCache) XCTAssertEqual(statement.authorizerEventKinds.count, 1) guard case .update(let tableName, let columnNames) = statement.authorizerEventKinds[0] else { XCTFail() return } XCTAssertEqual(tableName, "foo") XCTAssertEqual(columnNames, Set(["bar", "baz"])) } do { let statement = try db.makeStatement(sql: "UPDATE FOO SET BAR = 'bar', BAZ = 'baz' WHERE ID = 1") XCTAssertFalse(statement.invalidatesDatabaseSchemaCache) XCTAssertEqual(statement.authorizerEventKinds.count, 1) guard case .update(let tableName, let columnNames) = statement.authorizerEventKinds[0] else { XCTFail() return } XCTAssertEqual(tableName, "foo") XCTAssertEqual(columnNames, Set(["bar", "baz"])) } } } func testRowIdNameInSelectStatement() throws { // Here we test that sqlite authorizer gives the "ROWID" name to // the rowid column, regardless of its name in the request (rowid, oid, _rowid_) // // See also testRowIdNameInUpdateStatement guard sqlite3_libversion_number() < 3019003 else { // This test fails on SQLite 3.19.3 (iOS 11.2) and SQLite 3.21.0 (custom build), // but succeeds on SQLite 3.16.0 (iOS 10.3.1). // TODO: evaluate the consequences return } let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.execute(sql: "CREATE TABLE foo (name TEXT)") do { let statement = try db.makeStatement(sql: "SELECT rowid FROM FOO") let expectedRegion = DatabaseRegion(table: "foo", columns: ["ROWID"]) XCTAssertEqual(statement.databaseRegion, expectedRegion) XCTAssertEqual(statement.databaseRegion.description, "foo(ROWID)") } do { let statement = try db.makeStatement(sql: "SELECT _ROWID_ FROM FOO") let expectedRegion = DatabaseRegion(table: "foo", columns: ["ROWID"]) XCTAssertEqual(statement.databaseRegion, expectedRegion) XCTAssertEqual(statement.databaseRegion.description, "foo(ROWID)") } do { let statement = try db.makeStatement(sql: "SELECT oID FROM FOO") let expectedRegion = DatabaseRegion(table: "foo", columns: ["ROWID"]) XCTAssertEqual(statement.databaseRegion, expectedRegion) XCTAssertEqual(statement.databaseRegion.description, "foo(ROWID)") } } } func testRowIdNameInUpdateStatement() throws { // Here we test that sqlite authorizer gives the "ROWID" name to // the rowid column, regardless of its name in the request (rowid, oid, _rowid_) // // See also testRowIdNameInSelectStatement let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.execute(sql: "CREATE TABLE foo (name TEXT)") do { let statement = try db.makeStatement(sql: "UPDATE foo SET rowid = 1") XCTAssertEqual(statement.authorizerEventKinds.count, 1) guard case .update(let tableName, let columnNames) = statement.authorizerEventKinds[0] else { XCTFail() return } XCTAssertEqual(tableName, "foo") XCTAssertEqual(columnNames, ["ROWID"]) } do { let statement = try db.makeStatement(sql: "UPDATE foo SET _ROWID_ = 1") XCTAssertEqual(statement.authorizerEventKinds.count, 1) guard case .update(let tableName, let columnNames) = statement.authorizerEventKinds[0] else { XCTFail() return } XCTAssertEqual(tableName, "foo") XCTAssertEqual(columnNames, ["ROWID"]) } do { let statement = try db.makeStatement(sql: "UPDATE foo SET oID = 1") XCTAssertEqual(statement.authorizerEventKinds.count, 1) guard case .update(let tableName, let columnNames) = statement.authorizerEventKinds[0] else { XCTFail() return } XCTAssertEqual(tableName, "foo") XCTAssertEqual(columnNames, ["ROWID"]) } } } func testInsertStatement() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.execute(sql: "CREATE TABLE foo (id INTEGER, bar TEXT, baz TEXT, qux TEXT)") let statement = try db.makeStatement(sql: "INSERT INTO foo (id, bar) VALUES (1, 'bar')") XCTAssertFalse(statement.invalidatesDatabaseSchemaCache) XCTAssertEqual(statement.authorizerEventKinds.count, 1) guard case .insert(let tableName) = statement.authorizerEventKinds[0] else { XCTFail() return } XCTAssertEqual(tableName, "foo") } } func testDeleteStatement() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try db.execute(sql: "CREATE TABLE foo (id INTEGER, bar TEXT, baz TEXT, qux TEXT)") let statement = try db.makeStatement(sql: "DELETE FROM foo") XCTAssertFalse(statement.invalidatesDatabaseSchemaCache) XCTAssertEqual(statement.authorizerEventKinds.count, 1) guard case .delete(let tableName) = statement.authorizerEventKinds[0] else { XCTFail() return } XCTAssertEqual(tableName, "foo") } } func testUpdateStatementInvalidatesDatabaseSchemaCache() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in do { let statement = try db.makeStatement(sql: "CREATE TABLE foo (id INTEGER)") XCTAssertTrue(statement.invalidatesDatabaseSchemaCache) try statement.execute() } do { let statement = try db.makeStatement(sql: "ALTER TABLE foo ADD COLUMN name TEXT") XCTAssertTrue(statement.invalidatesDatabaseSchemaCache) } do { let statement = try db.makeStatement(sql: "DROP TABLE foo") XCTAssertTrue(statement.invalidatesDatabaseSchemaCache) } } } func testRegionIsModifiedByDatabaseEvent() { do { // Empty selection let region = DatabaseRegion() XCTAssertEqual(region.description, "empty") do { let eventKind = DatabaseEventKind.insert(tableName: "foo") XCTAssertFalse(region.isModified(byEventsOfKind: eventKind)) // Can't test for individual events due to DatabaseRegion.isModified(by:) precondition } do { let eventKind = DatabaseEventKind.delete(tableName: "foo") XCTAssertFalse(region.isModified(byEventsOfKind: eventKind)) // Can't test for individual events due to DatabaseRegion.isModified(by:) precondition } do { let eventKind = DatabaseEventKind.update(tableName: "foo", columnNames: ["a", "b"]) XCTAssertFalse(region.isModified(byEventsOfKind: eventKind)) // Can't test for individual events due to DatabaseRegion.isModified(by:) precondition } } do { // Full database selection let region = DatabaseRegion.fullDatabase XCTAssertEqual(region.description, "full database") do { let tableName = "foo" tableName.withCString { tableNameCString in let eventKind = DatabaseEventKind.insert(tableName: tableName) let event = DatabaseEvent(kind: .insert, rowID: 1, databaseNameCString: nil, tableNameCString: tableNameCString) XCTAssertTrue(region.isModified(byEventsOfKind: eventKind)) XCTAssertTrue(region.isModified(by: event)) } } do { let tableName = "foo" tableName.withCString { tableNameCString in let eventKind = DatabaseEventKind.delete(tableName: tableName) let event = DatabaseEvent(kind: .delete, rowID: 1, databaseNameCString: nil, tableNameCString: tableNameCString) XCTAssertTrue(region.isModified(byEventsOfKind: eventKind)) XCTAssertTrue(region.isModified(by: event)) } } do { let tableName = "foo" tableName.withCString { tableNameCString in let eventKind = DatabaseEventKind.update(tableName: tableName, columnNames: ["a", "b"]) let event = DatabaseEvent(kind: .update, rowID: 1, databaseNameCString: nil, tableNameCString: tableNameCString) XCTAssertTrue(region.isModified(byEventsOfKind: eventKind)) XCTAssertTrue(region.isModified(by: event)) } } } do { // Complex selection let region = DatabaseRegion(table: "foo") .union(DatabaseRegion(table: "bar", columns: ["a"]) .intersection(DatabaseRegion(table: "bar", rowIds: [1]))) XCTAssertEqual(region.description, "bar(a)[1],foo(*)") do { let tableName = "foo" tableName.withCString { tableNameCString in let eventKind = DatabaseEventKind.insert(tableName: tableName) let event1 = DatabaseEvent(kind: .insert, rowID: 1, databaseNameCString: nil, tableNameCString: tableNameCString) let event2 = DatabaseEvent(kind: .insert, rowID: 2, databaseNameCString: nil, tableNameCString: tableNameCString) XCTAssertTrue(region.isModified(byEventsOfKind: eventKind)) XCTAssertTrue(region.isModified(by: event1)) XCTAssertTrue(region.isModified(by: event2)) } } do { let tableName = "foo" tableName.withCString { tableNameCString in let eventKind = DatabaseEventKind.delete(tableName: tableName) let event1 = DatabaseEvent(kind: .delete, rowID: 1, databaseNameCString: nil, tableNameCString: tableNameCString) let event2 = DatabaseEvent(kind: .delete, rowID: 2, databaseNameCString: nil, tableNameCString: tableNameCString) XCTAssertTrue(region.isModified(byEventsOfKind: eventKind)) XCTAssertTrue(region.isModified(by: event1)) XCTAssertTrue(region.isModified(by: event2)) } } do { let tableName = "foo" tableName.withCString { tableNameCString in let eventKind = DatabaseEventKind.update(tableName: tableName, columnNames: ["a", "b"]) let event1 = DatabaseEvent(kind: .update, rowID: 1, databaseNameCString: nil, tableNameCString: tableNameCString) let event2 = DatabaseEvent(kind: .update, rowID: 2, databaseNameCString: nil, tableNameCString: tableNameCString) XCTAssertTrue(region.isModified(byEventsOfKind: eventKind)) XCTAssertTrue(region.isModified(by: event1)) XCTAssertTrue(region.isModified(by: event2)) } } do { let tableName = "bar" tableName.withCString { tableNameCString in let eventKind = DatabaseEventKind.insert(tableName: tableName) let event1 = DatabaseEvent(kind: .insert, rowID: 1, databaseNameCString: nil, tableNameCString: tableNameCString) let event2 = DatabaseEvent(kind: .insert, rowID: 2, databaseNameCString: nil, tableNameCString: tableNameCString) XCTAssertTrue(region.isModified(byEventsOfKind: eventKind)) XCTAssertTrue(region.isModified(by: event1)) XCTAssertFalse(region.isModified(by: event2)) } } do { let tableName = "bar" tableName.withCString { tableNameCString in let eventKind = DatabaseEventKind.delete(tableName: tableName) let event1 = DatabaseEvent(kind: .delete, rowID: 1, databaseNameCString: nil, tableNameCString: tableNameCString) let event2 = DatabaseEvent(kind: .delete, rowID: 2, databaseNameCString: nil, tableNameCString: tableNameCString) XCTAssertTrue(region.isModified(byEventsOfKind: eventKind)) XCTAssertTrue(region.isModified(by: event1)) XCTAssertFalse(region.isModified(by: event2)) } } do { let tableName = "bar" tableName.withCString { tableNameCString in let eventKind = DatabaseEventKind.update(tableName: tableName, columnNames: ["a", "b"]) let event1 = DatabaseEvent(kind: .update, rowID: 1, databaseNameCString: nil, tableNameCString: tableNameCString) let event2 = DatabaseEvent(kind: .update, rowID: 2, databaseNameCString: nil, tableNameCString: tableNameCString) XCTAssertTrue(region.isModified(byEventsOfKind: eventKind)) XCTAssertTrue(region.isModified(by: event1)) XCTAssertFalse(region.isModified(by: event2)) } } do { let eventKind = DatabaseEventKind.update(tableName: "bar", columnNames: ["b", "c"]) XCTAssertFalse(region.isModified(byEventsOfKind: eventKind)) // Can't test for individual events due to DatabaseRegion.isModified(by:) precondition } do { let eventKind = DatabaseEventKind.insert(tableName: "qux") XCTAssertFalse(region.isModified(byEventsOfKind: eventKind)) // Can't test for individual events due to DatabaseRegion.isModified(by:) precondition } do { let eventKind = DatabaseEventKind.delete(tableName: "qux") XCTAssertFalse(region.isModified(byEventsOfKind: eventKind)) // Can't test for individual events due to DatabaseRegion.isModified(by:) precondition } do { let eventKind = DatabaseEventKind.update(tableName: "qux", columnNames: ["a", "b"]) XCTAssertFalse(region.isModified(byEventsOfKind: eventKind)) // Can't test for individual events due to DatabaseRegion.isModified(by:) precondition } } } // Regression test for https://github.com/groue/GRDB.swift/issues/514 func testIssue514() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.write { db in try db.execute(sql: """ CREATE TABLE a (id INTEGER PRIMARY KEY, name TEXT); CREATE TABLE b (id TEXT, name TEXT); """) // INTEGER PRIMARY KEY do { // TODO: contact SQLite and ask if this test is expected to fail // let statement = try db.makeStatement(sql: "SELECT id FROM a") // let expectedRegion = DatabaseRegion(table: "a", columns: ["id"]) // XCTAssertEqual(statement.databaseRegion, expectedRegion) } do { let statement = try db.makeStatement(sql: "SELECT name FROM a") let expectedRegion = DatabaseRegion(table: "a", columns: ["name"]) XCTAssertEqual(statement.databaseRegion, expectedRegion) } do { let statement = try db.makeStatement(sql: "SELECT id, name FROM a") let expectedRegion = DatabaseRegion(table: "a", columns: ["id", "name"]) XCTAssertEqual(statement.databaseRegion, expectedRegion) } // TEXT primary key do { let statement = try db.makeStatement(sql: "SELECT id FROM b") let expectedRegion = DatabaseRegion(table: "b", columns: ["id"]) XCTAssertEqual(statement.databaseRegion, expectedRegion) } do { let statement = try db.makeStatement(sql: "SELECT name FROM b") let expectedRegion = DatabaseRegion(table: "b", columns: ["name"]) XCTAssertEqual(statement.databaseRegion, expectedRegion) } do { let statement = try db.makeStatement(sql: "SELECT id, name FROM b") let expectedRegion = DatabaseRegion(table: "b", columns: ["id", "name"]) XCTAssertEqual(statement.databaseRegion, expectedRegion) } } } }
mit
22c52ee4e814473899aba452f5b511f0
42.091422
133
0.517719
4.874745
false
false
false
false
knutigro/AppReviews
AppReviews/ApplicationWindowController.swift
1
3176
// // ApplicationWindow.swift // App Reviews // // Created by Knut Inge Grosland on 2015-04-21. // Copyright (c) 2015 Cocmoc. All rights reserved. // import AppKit import SwiftyJSON class ApplicationWindowController: NSWindowController { @IBOutlet weak var searchField: NSSearchField? var searchWindowController: NSWindowController? } // MARK: - SearchField extension ApplicationWindowController { override func controlTextDidEndEditing(notification: NSNotification) { if let textField = notification.object as? NSTextField { if !textField.stringValue.isEmpty { openSearchResultController() searchApp(textField.stringValue) } } } } // MARK: - Search Apps extension ApplicationWindowController { func searchApp(name: String) { ItunesService.fetchApplications(name) { [weak self] (success: Bool, applications: JSON?, error: NSError?) in let _ = success as Bool let blockError = error if blockError != nil { print("error: " + blockError!.localizedDescription) } if let applications = applications?.arrayValue { self?.openSearchResult(applications) } } } func openSearchResult(items: [JSON]) { if searchWindowController == nil { openSearchResultController() } if let searchViewController = searchWindowController?.window?.contentViewController as? SearchViewController { searchViewController.items = items searchViewController.tableView?.reloadData() searchViewController.state = .Idle } } func openSearchResultController() { let storyboard = NSStoryboard(name: "Main", bundle: nil) searchWindowController = storyboard.instantiateControllerWithIdentifier("SearchResultWindowController") as? NSWindowController let window = searchWindowController?.window if let searchViewController = window?.contentViewController as? SearchViewController { searchViewController.delegate = self searchViewController.state = .Loading } self.window?.beginSheet(window!) { (returnCode: NSModalResponse) in self.searchWindowController = nil } } } // Mark: - SearchViewControllerDelegate extension ApplicationWindowController: SearchViewControllerDelegate { func searchViewController(searchViewController: SearchViewController, didSelectApplication application: JSON) { searchField?.stringValue = "" DatabaseHandler.saveApplication(application) if let searchWindow = searchWindowController?.window { window?.endSheet(searchWindow) } } func searchViewControllerDidCancel(searchViewController: SearchViewController) { searchField?.stringValue = "" if let searchWindow = searchWindowController?.window { window?.endSheet(searchWindow) } } }
gpl-3.0
bd8a7e4643c47ab26eb22943c69102ad
29.834951
134
0.641373
5.87061
false
false
false
false
adamkornafeld/CocoaSkeleton
CocoaTouchSkeleton/AppDelegate.swift
1
4385
// // AppDelegate.swift // CocoaTouch // // Created by Adam Kornafeld on 6/12/16. // Copyright © 2016 Adam Kornafeld. All rights reserved. // import UIKit import CocoaSkeletonCore import CoreData import CocoaLumberjackSwift @UIApplicationMain public class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { public var window: UIWindow? public static let instance = UIApplication.sharedApplication().delegate as! AppDelegate public let app = App.instance public func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. let splitViewController = self.window!.rootViewController as! UISplitViewController let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem() splitViewController.delegate = self let app = App.instance if let context = app.contextCoordinator.mainQueueContext { context.performBlock { let predicate = NSPredicate(format: "attribute = %@", "Adam") let ent = context.managedObjectOfClass(Entity.self, predicate: predicate) if let unwrappedEnt = ent as? Entity { DDLogVerbose("\(unwrappedEnt.attribute)") } else { let ent = NSEntityDescription.insertNewObjectForEntityForName(NSStringFromClass(Entity), inManagedObjectContext: context) as! Entity ent.attribute = "Adam" try! context.save() } } } return true } public 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. } public 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. } public 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. } public 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. } public func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } // MARK: - Split view public func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController, ontoPrimaryViewController primaryViewController:UIViewController) -> Bool { guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false } guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false } if topAsDetailController.detailItem == nil { // Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded. return true } return false } }
mit
91c1f843884ea47a4d66b028183df52a
49.976744
285
0.722172
6.174648
false
false
false
false
4taras4/totp-auth
TOTP/ViperModules/AddItem/Module/Interactor/AddItemInteractor.swift
1
1039
// // AddItemAddItemInteractor.swift // TOTP // // Created by Tarik on 10/10/2020. // Copyright © 2020 Taras Markevych. All rights reserved. // import OneTimePassword final class AddItemInteractor: AddItemInteractorInput { weak var output: AddItemInteractorOutput! func setToken(string: String) { if let url = URL(string: string), let tokenData = Token(url: url) { guard let secretKey = url.absoluteString.components(separatedBy: "secret=").last?.components(separatedBy: "&issuer=").first else { self.output.addTokenFails() return } print(secretKey) RealmManager.shared.saveNewUser(name: tokenData.name, issuer: tokenData.issuer, token: secretKey, completionHandler: { isSuccess in if isSuccess { self.output.tokenAdded() } else { self.output.addTokenFails() } }) } else { output.addTokenFails() } } }
mit
e65e3dfeb4498e44d0f9990889284c7c
31.4375
143
0.588632
4.633929
false
false
false
false
GrandCentralBoard/GrandCentralBoard
Pods/Decodable/Sources/Decodable.swift
2
2440
// // Decodable.swift // Decodable // // Created by Johannes Lund on 2015-07-07. // Copyright © 2015 anviking. All rights reserved. // import Foundation public protocol Decodable { static func decode(json: AnyObject) throws -> Self } extension NSDictionary { public static func decode(j: AnyObject) throws -> NSDictionary { guard let result = j as? NSDictionary else { throw TypeMismatchError(expectedType: self, receivedType: j.dynamicType, object: j) } return result } } extension NSArray { public static func decode(j: AnyObject) throws -> NSArray { guard let result = j as? NSArray else { throw TypeMismatchError(expectedType: self, receivedType: j.dynamicType, object: j) } return result } } extension Dictionary where Key: Decodable, Value: Decodable { public static func decode(j: AnyObject) throws -> Dictionary { return try decodeDictionary(Key.decode, elementDecodeClosure: Value.decode)(json: j) } } extension Array where Element: Decodable { public static func decode(j: AnyObject, ignoreInvalidObjects: Bool = false) throws -> [Element] { if ignoreInvalidObjects { return try decodeArray { try? Element.decode($0) }(json: j).flatMap {$0} } else { return try decodeArray(Element.decode)(json: j) } } } // MARK: Helpers /// Designed to be used with parse(json, path, decodeClosure) as the decodeClosure. Thats why it's curried and a "top-level" function instead of a function in an array extension. For everyday use, prefer using [T].decode(json) instead. public func decodeArray<T>(elementDecodeClosure: AnyObject throws -> T) -> (json: AnyObject) throws -> [T] { return { json in return try NSArray.decode(json).map { try elementDecodeClosure($0) } } } /// Designed to be used with parse(json, path, decodeClosure) as the decodeClosure. Thats why it's curried. For everyday use, prefer using [K: V].decode(json) instead (declared in Decodable.swift). public func decodeDictionary<K,V>(keyDecodeClosure: AnyObject throws -> K, elementDecodeClosure: AnyObject throws -> V) -> (json: AnyObject) throws -> [K: V] { return { json in var dict = [K: V]() for (key, value) in try NSDictionary.decode(json) { try dict[keyDecodeClosure(key)] = elementDecodeClosure(value) } return dict } }
gpl-3.0
68f1cdd1631fe3952c81ee3fb9e38b86
34.867647
235
0.671587
4.092282
false
false
false
false
matthewsot/DNSwift
SystemCollectionsGeneric/SystemCollectionsGeneric/List.swift
1
6665
import Foundation import DNSwift public class List<E where E:Equatable>: IList { typealias T = E; private var Objects: [T]; public var Count: Int { get { return Objects.count } }; public var Capacity: Int; //todo: consider implementing this public init() { Capacity = Int.max; self.Objects = Array<T>(); } public init(objs: [T]) { Capacity = Int.max; self.Objects = objs; } //IEnumerable public func GetEnumerator<IE where IE:IEnumerator>() -> IE { return Enumerator(objs: Objects) as IE; } public func generate() -> Enumerator<T> { return Enumerator(objs: self.Objects); } //ICollection public var IsReadOnly: Bool { get { return false; } }; //TODO: replace some of these AnyObjects with T //Methods public func Add(item: T) { Objects.append(item); } public func Clear() { Objects.removeAll(keepCapacity: false); } public func Contains(item: T) -> Bool { return contains(Objects, item); } public func CopyTo(inout array: [T]) { array.removeAll(keepCapacity: false); for item in Objects { array.append(item); } } public func CopyTo(inout array: [T], arrayIndex: Int) { for (index, item) in enumerate(Objects) { array.insert(item, atIndex: arrayIndex + index); } } public func CopyTo(index: Int, inout array: [T], arrayIndex: Int, count: Int) { for i in 0..<count { if(index + i <= Objects.count) { array.insert(Objects[(index + i)], atIndex: i + arrayIndex); } } } public func Remove(item: T) { Objects.removeAtIndex(Objects.IndexOf(item)); } //IList public func IndexOf(obj: T) -> Int { return Objects.IndexOf(obj); } public func AddRange(objs: Array<T>) { for obj in objs { Objects.append(obj); } } //AsReadOnly //BinarySearch(T) //BinarySearch(T, IComparer<T>) //BinarySearch(Int, Int, T, IComparer<T>) public func ConvertAll<O>() -> List<O> { var newList = List<O>(); for item in Objects { newList.Add(item as O); } return newList; } public func Equals(obj: NSObject) -> Bool { return obj === self; } public func Exists(predicate: (T) -> Bool) -> Bool { return self.Any(predicate); } //Finalize public func Find(predicate: (T) -> Bool) -> T { return self.First(predicate); } public func FindAll(predicate: (T) -> Bool) -> List<T> { return self.Where(predicate); } public func FindIndex(predicate: (T) -> Bool) -> Int { for (index, item) in enumerate(Objects) { if(predicate(item)) { return index; } } return -1; } //TODO: rewrite the next two so they don't enumerate the whole thing. //something with for i in 0..count public func FindIndex(startIndex: Int, predicate: (T) -> Bool) -> Int { for (index, item) in enumerate(Objects) { if(index < startIndex) { continue; } if(predicate(item)) { return index; } } return -1; } public func FindIndex(startIndex: Int, count: Int, predicate: (T) -> Bool) -> Int { for(index, item) in enumerate(Objects) { if(index < startIndex) { continue; } if(index > (startIndex + count)) { break; } if(predicate(item)) { return index; } } return -1; } public func FindLast(predicate: (T) -> Bool) -> T { return self.Where(predicate).Last(); } //FindLastIndex(predicate) //FindLastIndex(Int, predicate) //FindLastIndex(Int, Int, predicate) //ForEach //GetHashCode //GetRange //GetType //IndexOf(T, Int) //IndexOf(T, Int, Int) public func Insert(index: Int, obj item: T) { Objects.insert(item, atIndex: index); } public func InsertRange(startingIndex: Int, objs: Array<T>) { for (index, item) in enumerate(objs) { Objects.insert(item, atIndex: (startingIndex + index)); } } //LastIndexOf(T) //LastIndexOf(T, Int) //LastIndexOf(T, Int, Int) //MemberwiseClone public func RemoveAll() { Objects.removeAll(keepCapacity: false); } public func RemoveAll(predicate: (T) -> Bool) { for (index, item) in enumerate(Objects) { if(predicate(item)) { Objects.removeAtIndex(index); } } } public func RemoveAt(index: Int) { Objects.removeAtIndex(index); } public func RemoveRange(objs: Array<T>) { for obj: T in objs { self.Remove(obj); } } public func Reverse() -> List<T> { return List(objs: Objects.reverse()); } //Reverse(Int, Int) //Sort() //Sort(comparison) //Sort(icomparer) //Sort(Int,Int,IComparer) public func ToArray() -> [T] { return self.Objects; } public func ToString() -> String { //TODO: figure out what the native .NET libraries return for this return "List"; } //TrimExcess /*public func TrueForAll(predicate: (T) -> Bool) -> Bool { return self.Where(predicate).Count == self.Count; }*/ //Extension methods public func Where(predicate: (T) -> Bool) -> List<T> { return List(objs: self.Objects.filter(predicate)); } public func Last() -> T { //TODO nil check/count == 0 return self.Objects[self.Count - 1]; } public func Any() -> Bool { return Count > 0; } public func Any(predicate: (T) -> Bool) -> Bool { return self.Where(predicate).Any(); } public func First() -> T { return self.Objects[0]; } public func First(predicate: (T) -> Bool) -> T { return self.Where(predicate).First(); } /*public func FirstOrDefault() -> T? { return self.Objects.FirstOrDefault(); } public func FirstOrDefault(predicate: (T) -> Bool) -> T? { return self.Objects.FirstOrDefault(predicate); }*/ }
mit
9b49d33069c646b5c598726656004039
23.688889
87
0.52198
4.137182
false
false
false
false
mddub/G4ShareSpy
G4ShareSpy/Messages/GlucoseHistoryMessage.swift
1
1058
// // GlucoseHistoryMessage.swift // G4ShareSpy // // Created by Mark Wilson on 7/10/16. // Copyright © 2016 Mark Wilson. All rights reserved. // import Foundation struct GlucoseHistoryMessage { let records: [GlucoseHistoryRecord] init?(data: Data) { guard data.count > (MessageHeader.length + GlucoseHistoryHeader.length) && data.crcValid() else { return nil } let pageHeaderData = data.subdata(in: MessageHeader.length..<(MessageHeader.length + GlucoseHistoryHeader.length)) guard let pageHeader = GlucoseHistoryHeader(data: pageHeaderData) else { return nil } records = (0..<pageHeader.recordCount).map({ let start = MessageHeader.length + GlucoseHistoryHeader.length + GlucoseHistoryRecord.length * Int($0) let range = Range<Int>(uncheckedBounds: (lower: start, upper: start + GlucoseHistoryRecord.length)) return GlucoseHistoryRecord(data: data.subdata(in: range), index: pageHeader.firstIndex + $0)! }) } }
mit
9924500abe56089ee67165d52520d945
31.030303
122
0.662252
4.296748
false
false
false
false
iandundas/Loca
Loca/Extensions/GeoCalculations.swift
1
1555
// // GeoCalculations.swift // Tacks // // Created by Ian Dundas on 20/07/2016. // Copyright © 2016 Ian Dundas. All rights reserved. // import MapKit // credit: http://stackoverflow.com/a/31423828 public func fittingRegionForCoordinates(_ coordinates: [CLLocationCoordinate2D]) -> MKCoordinateRegion? { guard coordinates.count > 0 else { return nil } var topLeftCoord: CLLocationCoordinate2D = CLLocationCoordinate2D() topLeftCoord.latitude = -90 topLeftCoord.longitude = 180 var bottomRightCoord: CLLocationCoordinate2D = CLLocationCoordinate2D() bottomRightCoord.latitude = 90 bottomRightCoord.longitude = -180 coordinates.forEach { coordinate in topLeftCoord.longitude = fmin(topLeftCoord.longitude, coordinate.longitude) topLeftCoord.latitude = fmax(topLeftCoord.latitude, coordinate.latitude) bottomRightCoord.longitude = fmax(bottomRightCoord.longitude, coordinate.longitude) bottomRightCoord.latitude = fmin(bottomRightCoord.latitude, coordinate.latitude) } var region: MKCoordinateRegion = MKCoordinateRegion() region.center.latitude = topLeftCoord.latitude - (topLeftCoord.latitude - bottomRightCoord.latitude) * 0.5 region.center.longitude = topLeftCoord.longitude + (bottomRightCoord.longitude - topLeftCoord.longitude) * 0.5 region.span.latitudeDelta = fabs(topLeftCoord.latitude - bottomRightCoord.latitude) * 1.4 region.span.longitudeDelta = fabs(bottomRightCoord.longitude - topLeftCoord.longitude) * 1.4 return region }
apache-2.0
bef85c76977394259ae908f2bd51a804
42.166667
114
0.750322
4.517442
false
false
false
false
faimin/ZDOpenSourceDemo
ZDOpenSourceSwiftDemo/Pods/Hero/Sources/Transition/HeroTransition+UITabBarControllerDelegate.swift
3
2401
// The MIT License (MIT) // // Copyright (c) 2016 Luke Zhao <me@lkzhao.com> // // 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 extension HeroTransition: UITabBarControllerDelegate { public func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool { guard tabBarController.selectedViewController !== viewController else { return false } if isTransitioning { cancel(animate: false) } return true } public func tabBarController(_ tabBarController: UITabBarController, interactionControllerFor animationController: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { return interactiveTransitioning } public func tabBarController(_ tabBarController: UITabBarController, animationControllerForTransitionFrom fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? { guard !isTransitioning else { return nil } self.state = .notified let fromVCIndex = tabBarController.children.index(of: fromVC)! let toVCIndex = tabBarController.children.index(of: toVC)! self.isPresenting = toVCIndex > fromVCIndex self.fromViewController = fromViewController ?? fromVC self.toViewController = toViewController ?? toVC self.inTabBarController = true return self } }
mit
e4d82c8b1ed0d80033040c94360f7d5e
46.078431
204
0.770929
5.347439
false
false
false
false
eofster/Telephone
TelephoneTests/StoreViewSpy.swift
1
2617
// // StoreViewSpy.swift // Telephone // // Copyright © 2008-2016 Alexey Kuznetsov // Copyright © 2016-2021 64 Characters // // Telephone 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. // // Telephone 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. // final class StoreViewSpy { private(set) var didCallShowPurchaseCheckProgress = false private(set) var invokedProducts: [PresentationProduct] = [] private(set) var invokedProductsFetchError = "" private(set) var didCallShowProductsFetchProgress = false private(set) var didCallShowPurchaseProgress = false private(set) var invokedPurchaseError = "" private(set) var didCallShowPurchaseRestorationProgress = false private(set) var invokedPurchaseRestorationError = "" private(set) var didCallDisablePurchaseRestoration = false private(set) var didCallEnablePurchaseRestoration = false private(set) var didCallShowPurchased = false private(set) var didCallShowSubscriptionManagement = false } extension StoreViewSpy: StoreView {} extension StoreViewSpy: StoreViewPresenterOutput { func showPurchaseCheckProgress() { didCallShowPurchaseCheckProgress = true } func show(_ products: [PresentationProduct]) { invokedProducts = products } func showProductsFetchError(_ error: String) { invokedProductsFetchError = error } func showProductsFetchProgress() { didCallShowProductsFetchProgress = true } func showPurchaseProgress() { didCallShowPurchaseProgress = true } func showPurchaseError(_ error: String) { invokedPurchaseError = error } func showPurchaseRestorationProgress() { didCallShowPurchaseRestorationProgress = true } func showPurchaseRestorationError(_ error: String) { invokedPurchaseRestorationError = error } func disablePurchaseRestoration() { didCallDisablePurchaseRestoration = true } func enablePurchaseRestoration() { didCallEnablePurchaseRestoration = true } func showPurchased(until date: Date) { didCallShowPurchased = true } func showSubscriptionManagement() { didCallShowSubscriptionManagement = true } }
gpl-3.0
dee16d95b714ea5a229d7bf35f5a0d2c
28.382022
72
0.723518
4.780622
false
false
false
false
frajaona/LiFXSwiftKit
Sources/LiFXLightInfo.swift
1
1528
/* * Copyright (C) 2016 Fred Rajaona * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Foundation struct LiFXLightInfo { let hue: Int let saturation: Int let brightness: Int let kelvin: Int let power: Int let label: String init(fromData bytes: [UInt8]) { var index = 0 hue = LiFXMessage.getIntValue(fromData: [bytes[index + 1], bytes[index + 2]]) index += 2 saturation = LiFXMessage.getIntValue(fromData: [bytes[index + 1], bytes[index + 2]]) index += 2 brightness = LiFXMessage.getIntValue(fromData: [bytes[index + 1], bytes[index + 2]]) index += 2 kelvin = LiFXMessage.getIntValue(fromData: [bytes[index + 1], bytes[index + 2]]) index += 2 power = LiFXMessage.getIntValue(fromData: [bytes[index + 1], bytes[index + 2]]) index += 4 let labelArray: [UInt8] = Array(bytes[index...index + 32]) label = LiFXMessage.getStringValue(fromData: labelArray) ?? "" } }
apache-2.0
831ceecd402b35c2907a956b7caefee4
34.534884
92
0.652487
3.917949
false
false
false
false
Jnosh/swift
test/SILGen/extensions_objc.swift
13
1260
// RUN: %target-swift-frontend -sdk %S/Inputs %s -I %S/Inputs -enable-source-import -emit-silgen | %FileCheck %s // // REQUIRES: objc_interop import Foundation class Foo {} extension Foo { dynamic func kay() {} dynamic var cox: Int { return 0 } } // CHECK-LABEL: sil hidden @_T015extensions_objc19extensionReferencesyAA3FooCF // CHECK: bb0([[ARG:%.*]] : $Foo): func extensionReferences(_ x: Foo) { // dynamic extension methods are still dynamically dispatched. // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: class_method [volatile] [[BORROWED_ARG]] : $Foo, #Foo.kay!1.foreign x.kay() // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: class_method [volatile] [[BORROWED_ARG]] : $Foo, #Foo.cox!getter.1.foreign _ = x.cox } func extensionMethodCurrying(_ x: Foo) { _ = x.kay } // CHECK-LABEL: sil shared [thunk] @_T015extensions_objc3FooC3kayyyFTc // CHECK: function_ref @_T015extensions_objc3FooC3kayyyFTD // CHECK-LABEL: sil shared [transparent] [serializable] [thunk] @_T015extensions_objc3FooC3kayyyFTD // CHECK: bb0([[SELF:%.*]] : $Foo): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: class_method [volatile] [[SELF_COPY]] : $Foo, #Foo.kay!1.foreign
apache-2.0
e60f147fdef3a36729ac1b1971469baf
33.054054
112
0.648413
3.165829
false
false
false
false
lizhenning87/SwiftZhiHu
SwiftZhiHu/SwiftZhiHu/RootTableViewCell.swift
1
2224
// // RootTableViewCell.swift // SwiftZhiHu // // Created by lizhenning on 14/10/22. // Copyright (c) 2014年 lizhenning. All rights reserved. // import UIKit class RootTableViewCell: UITableViewCell { var photo : UIImageView? var viewItem : UIView? var viewLabelBg : UIView? var labelTitle : UILabel? override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) var width = UIScreen.mainScreen().bounds.width viewItem = UIView(frame: CGRectMake(10, 5, width - 20, 190)) viewItem!.backgroundColor = colorCellBg self.contentView .addSubview(viewItem!) photo = UIImageView(frame: viewItem!.bounds) photo!.contentMode = UIViewContentMode.ScaleToFill photo!.layer.masksToBounds = true viewItem!.addSubview(photo!) viewLabelBg = UIView(frame: viewItem!.bounds) viewLabelBg!.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.8) viewItem!.addSubview(viewLabelBg!) labelTitle = UILabel(frame: CGRectMake(10, 10, viewItem!.frame.width - 20, viewItem!.frame.height - 20)) labelTitle!.backgroundColor = UIColor.clearColor() labelTitle!.textAlignment = NSTextAlignment.Center labelTitle!.font = UIFont(name: "Helvetica", size: 15) labelTitle!.numberOfLines = 0 labelTitle!.textColor = UIColor.whiteColor() viewLabelBg!.addSubview(labelTitle!) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setModel(model : StoryModel) { photo!.image = nil labelTitle!.text = model.title var url = NSURL(string: model.photo!) photo!.hnk_setImageFromURL(url!, placeholder: nil, format: nil, failure: nil, success: nil) } }
apache-2.0
b9a0d41720d4761f9cee023dbf34f6bd
31.676471
112
0.644914
4.562628
false
false
false
false
tlax/GaussSquad
GaussSquad/Data/DManager.swift
1
5472
import Foundation import CoreData class DManager { static let sharedInstance:DManager? = DManager() private let managedObjectContext:NSManagedObjectContext private let kModelName:String = "DGaussSquad" private let kModelExtension:String = "momd" private let kSQLiteExtension:String = ".sqlite" private init?() { let sqliteFile:String = "\(kModelName)\(kSQLiteExtension)" let storeCoordinatorURL:URL = FileManager.appDirectory.appendingPathComponent( sqliteFile) guard let modelURL:URL = Bundle.main.url( forResource:kModelName, withExtension:kModelExtension), let managedObjectModel:NSManagedObjectModel = NSManagedObjectModel( contentsOf:modelURL) else { return nil } let persistentStoreCoordinator:NSPersistentStoreCoordinator = NSPersistentStoreCoordinator( managedObjectModel:managedObjectModel) do { try persistentStoreCoordinator.addPersistentStore( ofType:NSSQLiteStoreType, configurationName:nil, at:storeCoordinatorURL, options:nil) } catch let error { #if DEBUG print("coredata: \(error.localizedDescription)") #endif } managedObjectContext = NSManagedObjectContext( concurrencyType: NSManagedObjectContextConcurrencyType.privateQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = persistentStoreCoordinator } //MARK: public func save(completion:(() -> ())? = nil) { DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async { if self.managedObjectContext.hasChanges { self.managedObjectContext.perform { do { try self.managedObjectContext.save() } catch let error { #if DEBUG print("CoreData: \(error.localizedDescription)") #endif } completion?() } } else { completion?() } } } func createData( entityName:String, completion:@escaping((NSManagedObject?) -> ())) { managedObjectContext.perform { if let entityDescription:NSEntityDescription = NSEntityDescription.entity( forEntityName:entityName, in:self.managedObjectContext) { let managedObject:NSManagedObject = NSManagedObject( entity:entityDescription, insertInto:self.managedObjectContext) completion(managedObject) } else { completion(nil) } } } func createDataAndWait(entityName:String) -> NSManagedObject? { var managedObject:NSManagedObject? managedObjectContext.performAndWait { if let entityDescription:NSEntityDescription = NSEntityDescription.entity( forEntityName:entityName, in:self.managedObjectContext) { managedObject = NSManagedObject( entity:entityDescription, insertInto:self.managedObjectContext) } } return managedObject } func fetchData( entityName:String, limit:Int = 0, predicate:NSPredicate? = nil, sorters:[NSSortDescriptor]? = nil, completion:@escaping(([NSManagedObject]?) -> ())) { DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async { let fetchRequest:NSFetchRequest<NSManagedObject> = NSFetchRequest( entityName:entityName) fetchRequest.predicate = predicate fetchRequest.sortDescriptors = sorters fetchRequest.fetchLimit = limit fetchRequest.returnsObjectsAsFaults = false fetchRequest.includesPropertyValues = true fetchRequest.includesSubentities = true self.managedObjectContext.perform { let results:[NSManagedObject]? do { results = try self.managedObjectContext.fetch(fetchRequest) } catch { results = nil } completion(results) } } } func delete(data:NSManagedObject, completion:(() -> ())? = nil) { managedObjectContext.perform { self.managedObjectContext.delete(data) completion?() } } func deleteAndWait(data:NSManagedObject) { managedObjectContext.performAndWait { self.managedObjectContext.delete(data) } } }
mit
a804e9ac4fd90cb2b46e99906b625350
28.73913
99
0.516447
7.051546
false
false
false
false
dbart01/Spyder
Spyder/ASCII.Row.swift
1
5321
// // ASCII.Row.swift // Spyder // // Copyright (c) 2016 Dima Bart // 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. // // 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. // // The views and conclusions contained in the software and documentation are those // of the authors and should not be interpreted as representing official policies, // either expressed or implied, of the FreeBSD Project. // import Foundation extension ASCII { struct Row: WrappingType { var cells: [Cell] // ---------------------------------- // MARK: - Init - // init(_ cell: Cell) { self.init([cell]) } init(_ cells: [Cell]) { self.cells = cells } // ---------------------------------- // MARK: - WrappingType - // func wrap(in context: ASCII.RenderContext) -> [RenderType] { var columns = self.cells.map { $0.wrap(in: context) as! [Cell] } /* ---------------------------------- ** Fill non-wrapped cells with empty ** content so that number of cells ** in each column is the same. */ let maxRows = columns.sorted { $0.count > $1.count }.first!.count for i in 0..<columns.count { while columns[i].count < maxRows { columns[i].append(columns[i].last!.blankCopy()) } } /* ----------------------------------- ** Create a row with a cell from each ** column. */ var rows: [Row] = [] for i in 0..<maxRows { let cells = columns.flatMap { $0[i] } rows.append(Row(cells)) } return rows } // ---------------------------------- // MARK: - RenderType - // func length(in context: ASCII.RenderContext) -> Int { var length = self.cellLengths(in: context).reduce(into: 0) { result, length in result += length } length += (self.cells.count - 1) * context.cellSeparatorString.count length += 2 * context.rowEdgeString.count return length } private func cellLengths(in context: ASCII.RenderContext) -> [Int] { return self.cells.map { $0.length(in: context) } } func render(in context: ASCII.RenderContext) -> String { let length = self.length(in: context) let spaceToFill = max(context.fillingLength - length, 0) var index: Int? if spaceToFill > 0 { /* ---------------------------------- ** Find a cell that has `isFlexible` ** set to `true`. Otherwise, default ** to using the last cell. */ index = self.cells.index { $0.flex } if index == nil { index = self.cells.count - 1 } } let renderedCells = self.cells.enumerated().map { arg -> String in let (offset, cell) = arg /* ------------------------------- ** Modify the context of the cell ** that matches the index determined ** above. */ var cellContext = context if let index = index, offset == index { cellContext.spaceToFill = spaceToFill } return cell.render(in: cellContext) } let joinedCells = renderedCells.joined(separator: context.cellSeparatorString) return "\(context.rowEdgeString)\(joinedCells)\(context.rowEdgeString)" } } }
bsd-2-clause
ccfc036ba583641b7b6aa1965f579536
35.951389
90
0.508739
5.07729
false
false
false
false
volendavidov/NagBar
NagBarTests/Icinga2ParserTests.swift
1
5050
// // Icinga2ParserTests.swift // NagBar // // Created by Volen Davidov on 09.07.17. // Copyright © 2017 Volen Davidov. All rights reserved. // import XCTest import RealmSwift class Icinga2ParserTests: XCTestCase { override func setUp() { Realm.Configuration.defaultConfiguration.inMemoryIdentifier = self.name let settings = [ "sortColumn": "1", "sortOrder": "2", ] let realm = try! Realm() for (key, value) in settings { if realm.objects(Setting.self).filter("key == %@", key).first != nil { continue } let setting = Setting() setting.key = key setting.value = value try! realm.write { realm.add(setting) } } } func testGetHostMonitoringItems() { let filePath = Bundle(for: type(of: self)).path(forResource: "Icinga2HostStatus", ofType: "json") XCTAssertNotNil(filePath) let data = try? Data(contentsOf: URL(fileURLWithPath: filePath!)) let monitoringInstance = MonitoringInstance().initDefault(name: "test", url: "https://testmonitoring:5665/v1", type: .Icinga2, username: "testuser", password: "testpass", enabled: 1) let parser = Icinga2Parser(monitoringInstance) let test = parser.parse(urlType: .hosts, data: data!) XCTAssertEqual(test.count, 2) XCTAssertEqual(test[0].monitoringInstance!.name, "test") XCTAssertEqual(test[0].host, "c2-web-1") XCTAssertEqual(test[0].status, "DOWN") XCTAssertEqual(test[0].lastCheck, "09-07-2017 14:36:43") XCTAssertEqual(test[0].duration, self.timeSinceSecondsToString(1494759783)) XCTAssertEqual(test[0].statusInformation, "PING CRITICAL - Packet loss = 100%") XCTAssertEqual(test[0].itemUrl, "https://testmonitoring/icingaweb2/monitoring/host/show?host=c2-web-1") } func testGetServiceMonitoringItems() { let filePath = Bundle(for: type(of: self)).path(forResource: "Icinga2ServiceStatus", ofType: "json") XCTAssertNotNil(filePath) let data = try? Data(contentsOf: URL(fileURLWithPath: filePath!)) let monitoringInstance = MonitoringInstance().initDefault(name: "test", url: "https://testmonitoring:5665/v1", type: .Icinga2, username: "testuser", password: "testpass", enabled: 1) let parserServices = Icinga2Parser(monitoringInstance) let test = parserServices.parse(urlType: .services, data: data!) as! Array<ServiceMonitoringItem> XCTAssertEqual(test.count, 47) XCTAssertEqual(test[7].monitoringInstance!.name, "test") XCTAssertEqual(test[7].host, "icinga2") XCTAssertEqual(test[7].status, "CRITICAL") XCTAssertEqual(test[7].service, "disk") XCTAssertEqual(test[7].lastCheck, "09-07-2017 14:36:48") XCTAssertEqual(test[7].duration, self.timeSinceSecondsToString(1494759844)) XCTAssertEqual(test[7].attempt, "1/5") XCTAssertEqual(test[7].statusInformation, "DISK CRITICAL - free space: / 48157 MB (94% inode=99%); /boot 314 MB (63% inode=99%); /home 186600 MB (99% inode=99%); /vagrant 4223 MB (7% inode=100%); /tmp/vagrant-puppet/modules-d9eafae9c04b462999be5fe46dd5a1e9 4223 MB (7% inode=100%); /tmp/vagrant-puppet/manifests-a11d1078b1b1f2e3bdea27312f6ba513 4223 MB (7% inode=100%);") XCTAssertEqual(test[7].itemUrl, "https://testmonitoring/icingaweb2/monitoring/service/show?host=icinga2&service=disk") } private func timeSinceSecondsToString(_ timeLeftSeconds: Double?) -> String { guard let timeLeftSeconds = timeLeftSeconds else { return "" } if timeLeftSeconds == 0.0 { return "N/A" } let currentDate = Date().timeIntervalSince1970 let diff = Int(currentDate - timeLeftSeconds) let secondsInMinute = 60 let secondsInHour = 60 * secondsInMinute let secondsInDay = 24 * secondsInHour let days = diff / secondsInDay let hours = (diff - secondsInDay * days) / secondsInHour let minutes = (diff - secondsInDay * days - secondsInHour * hours) / secondsInMinute let seconds = (diff - secondsInDay * days - secondsInHour * hours - secondsInMinute * minutes) var timeLeftString: String? if days > 0 { timeLeftString = String.init(format: "%ud %uh %um %us", days, hours, minutes, seconds) } else if hours > 0 { timeLeftString = String.init(format: "%uh %um %us", hours, minutes, seconds) } else if minutes > 0 { timeLeftString = String.init(format: "%um %us", minutes, seconds) } else { timeLeftString = String.init(format: "%us", seconds) } return timeLeftString! } }
apache-2.0
d5ffb9d423e6d100d8aa8e7fd2eb68f3
40.385246
379
0.613389
4.108218
false
true
false
false
arasu01/Sample-Apps
Sample ToDo/Sample ToDo/ViewContorller/Login/STLoginViewController.swift
1
5435
// // STLoginViewController.swift // Sample ToDo // // Created by Arasuvel Theerthapathy on 29/11/16. // Copyright © 2016 Arasuvel Theerthapathy. All rights reserved. // import UIKit import FirebaseAuth class STLoginViewController: UIViewController { @IBOutlet weak var emailTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var loginButton: UIButton! @IBOutlet var blurImageView: STBlurView! // MARK: View life cycle methods override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. if let _ = Auth.auth().currentUser { } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.navigationBar.isHidden = true } // MARK: Action methods @IBAction func loginButtonPressed(_ sender: UIButton) { // Implement validation logics here let email = emailTextField.text let password = passwordTextField.text Auth.auth().signIn(withEmail: email!, password: password!, completion: { (user, error) in guard let _ = user else { if let error = error { if let errCode = AuthErrorCode(rawValue: error._code) { switch errCode { case .userNotFound: self.showAlert("User account not found. Try registering") case .wrongPassword: self.showAlert("Incorrect username/password combination") default: self.showAlert("Error: \(error.localizedDescription)") } } return } assertionFailure("user and error are nil") return } self.signIn() }) } @IBAction func signupButtonPressed(_ sender: UIButton) { // Do sign up actions } @IBAction func didRequestPasswordReset(_ sender: UIButton) { let prompt = UIAlertController(title: "To Do App", message: "Email:", preferredStyle: .alert) let okAction = UIAlertAction(title: "OK", style: .default) { (action) in let userInput = prompt.textFields![0].text if (userInput!.isEmpty) { return } Auth.auth().sendPasswordReset(withEmail: userInput!, completion: { (error) in if let error = error { if let errCode = AuthErrorCode(rawValue: error._code) { switch errCode { case .userNotFound: DispatchQueue.main.async { self.showAlert("User account not found. Try registering") } default: DispatchQueue.main.async { self.showAlert("Error: \(error.localizedDescription)") } } } return } else { DispatchQueue.main.async { self.showAlert("You'll receive an email shortly to reset your password.") } } }) } prompt.addTextField(configurationHandler: nil) prompt.addAction(okAction) present(prompt, animated: true, completion: nil) } @IBAction func nextToolBarButtonPressed() { passwordTextField.becomeFirstResponder() } @IBAction func doneToolBarButtonPressed() { passwordTextField.resignFirstResponder() loginButtonPressed(loginButton) } // MARK: - Custom methods func configurationTextField(textField: UITextField!) { if let aTextField = textField { aTextField.keyboardType = .emailAddress aTextField.placeholder = "Email" } } func signIn() { kAppDelegate.dashBoardRootViewController() } func showAlert(_ message: String) { let alertController = UIAlertController(title: "To Do App", message: message, preferredStyle: UIAlertController.Style.alert) alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertAction.Style.default,handler: nil)) self.present(alertController, animated: true, completion: nil) } /* // 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. } */ } //MARK: - Text field delegate methods extension STLoginViewController : UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { if textField == emailTextField { passwordTextField.becomeFirstResponder() } else if textField == passwordTextField { passwordTextField.resignFirstResponder() loginButtonPressed(loginButton) } return true } }
mit
787a4a5578899f3dc97de4a5e08edb03
32.9625
132
0.564225
5.787007
false
false
false
false
gavinbunney/Toucan
ToucanPlayground.playground/Contents.swift
1
3939
// ToucanPlayground.playground // // Copyright (c) 2014-2019 Gavin Bunney // // 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 Toucan // // Toucan Playground! // // Quickly explore the different featurs of Toucan. // let portraitImage = UIImage(named: "Portrait.jpg") let landscapeImage = UIImage(named: "Landscape.jpg") let octagonMask = UIImage(named: "OctagonMask.png") // ------------------------------------------------------------ // Resizing // ------------------------------------------------------------ // Crop will resize to fit one dimension, then crop the other Toucan(image: portraitImage!).resize(CGSize(width: 500, height: 500), fitMode: Toucan.Resize.FitMode.crop).image // Clip will resize so one dimension is equal to the size, the other shrunk down to retain aspect ratio Toucan(image: portraitImage!).resize(CGSize(width: 500, height: 500), fitMode: Toucan.Resize.FitMode.clip).image // Scale will resize so the image fits exactly, altering the aspect ratio Toucan(image: portraitImage!).resize(CGSize(width: 500, height: 500), fitMode: Toucan.Resize.FitMode.scale).image // ------------------------------------------------------------ // Masking // ------------------------------------------------------------ let landscapeCropped = Toucan(image: landscapeImage!).resize(CGSize(width: 500, height: 500), fitMode: Toucan.Resize.FitMode.crop).image! // We can mask with an ellipse! Toucan(image: landscapeImage!).maskWithEllipse().image // Demonstrate creating a circular mask -> resizes to a square image then mask with an ellipse Toucan(image: landscapeCropped).maskWithEllipse().image! // Mask with borders too! Toucan(image: landscapeCropped).maskWithEllipse(borderWidth: 10, borderColor: UIColor.yellow).image! // Rounded Rects are all in style Toucan(image: landscapeCropped).maskWithRoundedRect(cornerRadius: 30).image! // And can be fancy with borders Toucan(image: landscapeCropped).maskWithRoundedRect(cornerRadius: 30, borderWidth: 10, borderColor: UIColor.purple).image! // Masking with an custom image mask Toucan(image: landscapeCropped).maskWithImage(maskImage: octagonMask!).image! //testing the path stuff let path = UIBezierPath() path.move(to: CGPoint(x: 0, y: 50)) path.addLine(to: CGPoint(x: 50, y: 0)) path.addLine(to: CGPoint(x: 100, y: 50)) path.addLine(to: CGPoint(x: 50, y: 100)) path.close() Toucan(image: landscapeCropped).maskWithPath(path: path).image! Toucan(image: landscapeCropped).maskWithPathClosure(path: {(rect) -> (UIBezierPath) in return UIBezierPath(roundedRect: rect, cornerRadius: 50.0) }).image! // ------------------------------------------------------------ // Layers // ------------------------------------------------------------ // We can draw ontop of another image Toucan(image: portraitImage!).layerWithOverlayImage(octagonMask!, overlayFrame: CGRect(x: 450, y: 400, width: 200, height: 200)).image!
mit
4a69649f766959868841f9fd8d1fe660
40.904255
137
0.688753
4.376667
false
false
false
false
BanyaKrylov/Learn-Swift
Part 1.2 Basics.playground/Contents.swift
1
276
// Работа с операторами import UIKit let num1: Int, num2: Double, num3: Float num1 = 18 num2 = 5.7 num3 = 16.4 var res1 = Float(num1) + Float(num2) + num3 var res2 = Double(num1) * num2 * Double(num3) var res3 = Int(res2) var res4 = Double(num3) / num2
apache-2.0
67f6428ceee9700d00729b90e5e35e17
15.1875
45
0.666667
2.205128
false
false
false
false
kesun421/firefox-ios
XCUITests/PrivateBrowsingTest.swift
1
6936
/* 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 XCTest let url1 = "www.mozilla.org" let url2 = "www.facebook.com" let url1Label = "Internet for people, not profit — Mozilla" let url2Label = "Facebook - Log In or Sign Up" class PrivateBrowsingTest: BaseTestCase { func testPrivateTabDoesNotTrackHistory() { navigator.openURL(urlString: url1) navigator.goto(BrowserTabMenu) // Go to History screen waitforExistence(app.tables.cells["History"]) app.tables.cells["History"].tap() navigator.nowAt(BrowserTab) waitforExistence(app.tables["History List"]) XCTAssertTrue(app.tables["History List"].staticTexts[url1Label].exists) // History without counting Recently Closed and Synced devices let history = app.tables["History List"].cells.count - 2 XCTAssertEqual(history, 1, "History entries in regular browsing do not match") // Go to Private browsing to open a website and check if it appears on History navigator.goto(PrivateTabTray) navigator.openURL(urlString: url2) navigator.nowAt(PrivateBrowserTab) waitForValueContains(app.textFields["url"], value: "facebook") navigator.goto(BrowserTabMenu) waitforExistence(app.tables.cells["History"]) app.tables.cells["History"].tap() waitforExistence(app.tables["History List"]) XCTAssertTrue(app.tables["History List"].staticTexts[url1Label].exists) XCTAssertFalse(app.tables["History List"].staticTexts[url2Label].exists) // Open one tab in private browsing and check the total number of tabs let privateHistory = app.tables["History List"].cells.count - 2 XCTAssertEqual(privateHistory, 1, "History entries in private browsing do not match") } func testTabCountShowsOnlyNormalOrPrivateTabCount() { // Open two tabs in normal browsing and check the number of tabs open navigator.openNewURL(urlString: url1) waitUntilPageLoad() navigator.goto(TabTray) navigator.goto(BrowserTab) navigator.goto(TabTray) waitforExistence(app.collectionViews.cells[url1Label]) let numTabs = app.collectionViews.cells.count XCTAssertEqual(numTabs, 3, "The number of regular tabs is not correct") // Open one tab in private browsing and check the total number of tabs navigator.goto(PrivateTabTray) navigator.goto(URLBarOpen) waitUntilPageLoad() navigator.openURL(urlString: url2) waitUntilPageLoad() navigator.nowAt(PrivateBrowserTab) waitForValueContains(app.textFields["url"], value: "facebook") navigator.goto(PrivateTabTray) waitforExistence(app.collectionViews.cells[url2Label]) let numPrivTabs = app.collectionViews.cells.count XCTAssertEqual(numPrivTabs, 1, "The number of private tabs is not correct") // Go back to regular mode and check the total number of tabs navigator.goto(TabTray) waitforExistence(app.collectionViews.cells[url1Label]) waitforNoExistence(app.collectionViews.cells[url2Label]) let numRegularTabs = app.collectionViews.cells.count XCTAssertEqual(numRegularTabs, 3, "The number of regular tabs is not correct") } func testClosePrivateTabsOptionClosesPrivateTabs() { // Check that Close Private Tabs when closing the Private Browsing Button is off by default navigator.goto(SettingsScreen) let settingsTableView = app.tables["AppSettingsTableViewController.tableView"] while settingsTableView.staticTexts["Close Private Tabs"].exists == false { settingsTableView.swipeUp() } let closePrivateTabsSwitch = settingsTableView.switches["Close Private Tabs, When Leaving Private Browsing"] XCTAssertFalse(closePrivateTabsSwitch.isSelected) // Open a Private tab navigator.goto(PrivateTabTray) navigator.openURL(urlString: url1) //Wait until the page loads waitUntilPageLoad() navigator.nowAt(PrivateBrowserTab) navigator.goto(PrivateTabTray) // Go back to regular browser navigator.goto(TabTray) // Go back to private browsing and check that the tab has not been closed navigator.goto(PrivateTabTray) waitforExistence(app.collectionViews.cells[url1Label]) let numPrivTabs = app.collectionViews.cells.count XCTAssertEqual(numPrivTabs, 1, "The number of tabs is not correct, the private tab should not have been closed") app.collectionViews.cells[url1Label].tap() navigator.nowAt(PrivateBrowserTab) // Now the enable the Close Private Tabs when closing the Private Browsing Button navigator.goto(SettingsScreen) closePrivateTabsSwitch.tap() navigator.goto(PrivateBrowserTab) // Go back to regular browsing and check that the private tab has been closed and that the initial Private Browsing message appears when going back to Private Browsing navigator.goto(PrivateTabTray) navigator.goto(TabTray) navigator.goto(PrivateTabTray) waitforNoExistence(app.collectionViews.cells[url1Label]) let numPrivTabsAfterClosing = app.collectionViews.cells.count XCTAssertEqual(numPrivTabsAfterClosing, 0, "The number of tabs is not correct, the private tab should have been closed") XCTAssertTrue(app.staticTexts["Private Browsing"].exists, "Private Browsing screen is not shown") } func testPrivateBrowserPanelView() { // If no private tabs are open, there should be a initial screen with label Private Browsing navigator.goto(PrivateTabTray) XCTAssertTrue(app.staticTexts["Private Browsing"].exists, "Private Browsing screen is not shown") let numPrivTabsFirstTime = app.collectionViews.cells.count XCTAssertEqual(numPrivTabsFirstTime, 0, "The number of tabs is not correct, there should not be any private tab yet") // If a private tab is open Private Browsing screen is not shown anymore navigator.goto(PrivateBrowserTab) //Wait until the page loads waitUntilPageLoad() navigator.goto(PrivateTabTray) // Go to regular browsing navigator.goto(TabTray) // Go back to private brosing navigator.goto(PrivateTabTray) waitforNoExistence(app.staticTexts["Private Browsing"]) XCTAssertFalse(app.staticTexts["Private Browsing"].exists, "Private Browsing screen is shown") let numPrivTabsOpen = app.collectionViews.cells.count XCTAssertEqual(numPrivTabsOpen, 1, "The number of tabs is not correct, there should be one private tab") } }
mpl-2.0
a77f8b5b23b3dde6eae83a697fa8f723
44.618421
175
0.705076
5.017366
false
false
false
false
dominickhera/Projects
personal/iOU/iOU 4.0/AboutUsViewController.swift
2
1098
// // AboutUsViewController.swift // iOU 4.0 // // Created by Dominick Hera on 2/12/15. // Copyright (c) 2015 Posa. All rights reserved. // import UIKit class AboutUsViewController: UIViewController { @IBOutlet weak var aboutUsTextView: UITextView! override func viewDidLoad() { super.viewDidLoad() aboutUsTextView.text = "Hi, my name's Dominick and I'm just some guy on his MacBook Pro coding away to the best of his abilties. I would link social media but I have none. I hope you enjoy the application." let fontFamilyNames = UIFont.familyNames() for familyName in fontFamilyNames { print("Font Family Name = [\(familyName)]") let names = UIFont.fontNamesForFamilyName(familyName as! String) print("Font Names = [\(names)") } aboutUsTextView.font = UIFont(name: "Lato-Light1.ttf", size: 30.0) // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
apache-2.0
c0eb11fc79911d343cd33baa5491839a
29.527778
206
0.675774
4.255814
false
false
false
false
raymondshadow/SwiftDemo
SwiftApp/Pods/RxCocoa/RxCocoa/iOS/UICollectionView+Rx.swift
3
16413
// // UICollectionView+Rx.swift // RxCocoa // // Created by Krunoslav Zaher on 4/2/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if os(iOS) || os(tvOS) import RxSwift import UIKit // Items extension Reactive where Base: UICollectionView { /** Binds sequences of elements to collection view items. - parameter source: Observable sequence of items. - parameter cellFactory: Transform between sequence elements and view cells. - returns: Disposable object that can be used to unbind. Example let items = Observable.just([ 1, 2, 3 ]) items .bind(to: collectionView.rx.items) { (collectionView, row, element) in let indexPath = IndexPath(row: row, section: 0) let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! NumberCell cell.value?.text = "\(element) @ \(row)" return cell } .disposed(by: disposeBag) */ public func items<S: Sequence, O: ObservableType> (_ source: O) -> (_ cellFactory: @escaping (UICollectionView, Int, S.Iterator.Element) -> UICollectionViewCell) -> Disposable where O.E == S { return { cellFactory in let dataSource = RxCollectionViewReactiveArrayDataSourceSequenceWrapper<S>(cellFactory: cellFactory) return self.items(dataSource: dataSource)(source) } } /** Binds sequences of elements to collection view items. - parameter cellIdentifier: Identifier used to dequeue cells. - parameter source: Observable sequence of items. - parameter configureCell: Transform between sequence elements and view cells. - parameter cellType: Type of table view cell. - returns: Disposable object that can be used to unbind. Example let items = Observable.just([ 1, 2, 3 ]) items .bind(to: collectionView.rx.items(cellIdentifier: "Cell", cellType: NumberCell.self)) { (row, element, cell) in cell.value?.text = "\(element) @ \(row)" } .disposed(by: disposeBag) */ public func items<S: Sequence, Cell: UICollectionViewCell, O : ObservableType> (cellIdentifier: String, cellType: Cell.Type = Cell.self) -> (_ source: O) -> (_ configureCell: @escaping (Int, S.Iterator.Element, Cell) -> Void) -> Disposable where O.E == S { return { source in return { configureCell in let dataSource = RxCollectionViewReactiveArrayDataSourceSequenceWrapper<S> { cv, i, item in let indexPath = IndexPath(item: i, section: 0) let cell = cv.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! Cell configureCell(i, item, cell) return cell } return self.items(dataSource: dataSource)(source) } } } /** Binds sequences of elements to collection view items using a custom reactive data used to perform the transformation. - parameter dataSource: Data source used to transform elements to view cells. - parameter source: Observable sequence of items. - returns: Disposable object that can be used to unbind. Example let dataSource = RxCollectionViewSectionedReloadDataSource<SectionModel<String, Double>>() let items = Observable.just([ SectionModel(model: "First section", items: [ 1.0, 2.0, 3.0 ]), SectionModel(model: "Second section", items: [ 1.0, 2.0, 3.0 ]), SectionModel(model: "Third section", items: [ 1.0, 2.0, 3.0 ]) ]) dataSource.configureCell = { (dataSource, cv, indexPath, element) in let cell = cv.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! NumberCell cell.value?.text = "\(element) @ row \(indexPath.row)" return cell } items .bind(to: collectionView.rx.items(dataSource: dataSource)) .disposed(by: disposeBag) */ public func items< DataSource: RxCollectionViewDataSourceType & UICollectionViewDataSource, O: ObservableType> (dataSource: DataSource) -> (_ source: O) -> Disposable where DataSource.Element == O.E { return { source in // This is called for sideeffects only, and to make sure delegate proxy is in place when // data source is being bound. // This is needed because theoretically the data source subscription itself might // call `self.rx.delegate`. If that happens, it might cause weird side effects since // setting data source will set delegate, and UICollectionView might get into a weird state. // Therefore it's better to set delegate proxy first, just to be sure. _ = self.delegate // Strong reference is needed because data source is in use until result subscription is disposed return source.subscribeProxyDataSource(ofObject: self.base, dataSource: dataSource, retainDataSource: true) { [weak collectionView = self.base] (_: RxCollectionViewDataSourceProxy, event) -> Void in guard let collectionView = collectionView else { return } dataSource.collectionView(collectionView, observedEvent: event) } } } } extension Reactive where Base: UICollectionView { public typealias DisplayCollectionViewCellEvent = (cell: UICollectionViewCell, at: IndexPath) public typealias DisplayCollectionViewSupplementaryViewEvent = (supplementaryView: UICollectionReusableView, elementKind: String, at: IndexPath) /// Reactive wrapper for `dataSource`. /// /// For more information take a look at `DelegateProxyType` protocol documentation. public var dataSource: DelegateProxy<UICollectionView, UICollectionViewDataSource> { return RxCollectionViewDataSourceProxy.proxy(for: base) } /// Installs data source as forwarding delegate on `rx.dataSource`. /// Data source won't be retained. /// /// It enables using normal delegate mechanism with reactive delegate mechanism. /// /// - parameter dataSource: Data source object. /// - returns: Disposable object that can be used to unbind the data source. public func setDataSource(_ dataSource: UICollectionViewDataSource) -> Disposable { return RxCollectionViewDataSourceProxy.installForwardDelegate(dataSource, retainDelegate: false, onProxyForObject: self.base) } /// Reactive wrapper for `delegate` message `collectionView(_:didSelectItemAtIndexPath:)`. public var itemSelected: ControlEvent<IndexPath> { let source = delegate.methodInvoked(#selector(UICollectionViewDelegate.collectionView(_:didSelectItemAt:))) .map { a in return try castOrThrow(IndexPath.self, a[1]) } return ControlEvent(events: source) } /// Reactive wrapper for `delegate` message `collectionView(_:didDeselectItemAtIndexPath:)`. public var itemDeselected: ControlEvent<IndexPath> { let source = delegate.methodInvoked(#selector(UICollectionViewDelegate.collectionView(_:didDeselectItemAt:))) .map { a in return try castOrThrow(IndexPath.self, a[1]) } return ControlEvent(events: source) } /// Reactive wrapper for `delegate` message `collectionView(_:didHighlightItemAt:)`. public var itemHighlighted: ControlEvent<IndexPath> { let source = delegate.methodInvoked(#selector(UICollectionViewDelegate.collectionView(_:didHighlightItemAt:))) .map { a in return try castOrThrow(IndexPath.self, a[1]) } return ControlEvent(events: source) } /// Reactive wrapper for `delegate` message `collectionView(_:didUnhighlightItemAt:)`. public var itemUnhighlighted: ControlEvent<IndexPath> { let source = delegate.methodInvoked(#selector(UICollectionViewDelegate.collectionView(_:didUnhighlightItemAt:))) .map { a in return try castOrThrow(IndexPath.self, a[1]) } return ControlEvent(events: source) } /// Reactive wrapper for `delegate` message `collectionView:willDisplay:forItemAt:`. public var willDisplayCell: ControlEvent<DisplayCollectionViewCellEvent> { let source: Observable<DisplayCollectionViewCellEvent> = self.delegate.methodInvoked(#selector(UICollectionViewDelegate.collectionView(_:willDisplay:forItemAt:))) .map { a in return (try castOrThrow(UICollectionViewCell.self, a[1]), try castOrThrow(IndexPath.self, a[2])) } return ControlEvent(events: source) } /// Reactive wrapper for `delegate` message `collectionView(_:willDisplaySupplementaryView:forElementKind:at:)`. public var willDisplaySupplementaryView: ControlEvent<DisplayCollectionViewSupplementaryViewEvent> { let source: Observable<DisplayCollectionViewSupplementaryViewEvent> = self.delegate.methodInvoked(#selector(UICollectionViewDelegate.collectionView(_:willDisplaySupplementaryView:forElementKind:at:))) .map { a in return (try castOrThrow(UICollectionReusableView.self, a[1]), try castOrThrow(String.self, a[2]), try castOrThrow(IndexPath.self, a[3])) } return ControlEvent(events: source) } /// Reactive wrapper for `delegate` message `collectionView:didEndDisplaying:forItemAt:`. public var didEndDisplayingCell: ControlEvent<DisplayCollectionViewCellEvent> { let source: Observable<DisplayCollectionViewCellEvent> = self.delegate.methodInvoked(#selector(UICollectionViewDelegate.collectionView(_:didEndDisplaying:forItemAt:))) .map { a in return (try castOrThrow(UICollectionViewCell.self, a[1]), try castOrThrow(IndexPath.self, a[2])) } return ControlEvent(events: source) } /// Reactive wrapper for `delegate` message `collectionView(_:didEndDisplayingSupplementaryView:forElementOfKind:at:)`. public var didEndDisplayingSupplementaryView: ControlEvent<DisplayCollectionViewSupplementaryViewEvent> { let source: Observable<DisplayCollectionViewSupplementaryViewEvent> = self.delegate.methodInvoked(#selector(UICollectionViewDelegate.collectionView(_:didEndDisplayingSupplementaryView:forElementOfKind:at:))) .map { a in return (try castOrThrow(UICollectionReusableView.self, a[1]), try castOrThrow(String.self, a[2]), try castOrThrow(IndexPath.self, a[3])) } return ControlEvent(events: source) } /// Reactive wrapper for `delegate` message `collectionView(_:didSelectItemAtIndexPath:)`. /// /// It can be only used when one of the `rx.itemsWith*` methods is used to bind observable sequence, /// or any other data source conforming to `SectionedViewDataSourceType` protocol. /// /// ``` /// collectionView.rx.modelSelected(MyModel.self) /// .map { ... /// ``` public func modelSelected<T>(_ modelType: T.Type) -> ControlEvent<T> { let source: Observable<T> = itemSelected.flatMap { [weak view = self.base as UICollectionView] indexPath -> Observable<T> in guard let view = view else { return Observable.empty() } return Observable.just(try view.rx.model(at: indexPath)) } return ControlEvent(events: source) } /// Reactive wrapper for `delegate` message `collectionView(_:didSelectItemAtIndexPath:)`. /// /// It can be only used when one of the `rx.itemsWith*` methods is used to bind observable sequence, /// or any other data source conforming to `SectionedViewDataSourceType` protocol. /// /// ``` /// collectionView.rx.modelDeselected(MyModel.self) /// .map { ... /// ``` public func modelDeselected<T>(_ modelType: T.Type) -> ControlEvent<T> { let source: Observable<T> = itemDeselected.flatMap { [weak view = self.base as UICollectionView] indexPath -> Observable<T> in guard let view = view else { return Observable.empty() } return Observable.just(try view.rx.model(at: indexPath)) } return ControlEvent(events: source) } /// Synchronous helper method for retrieving a model at indexPath through a reactive data source public func model<T>(at indexPath: IndexPath) throws -> T { let dataSource: SectionedViewDataSourceType = castOrFatalError(self.dataSource.forwardToDelegate(), message: "This method only works in case one of the `rx.itemsWith*` methods was used.") let element = try dataSource.model(at: indexPath) return try castOrThrow(T.self, element) } } @available(iOS 10.0, tvOS 10.0, *) extension Reactive where Base: UICollectionView { /// Reactive wrapper for `prefetchDataSource`. /// /// For more information take a look at `DelegateProxyType` protocol documentation. public var prefetchDataSource: DelegateProxy<UICollectionView, UICollectionViewDataSourcePrefetching> { return RxCollectionViewDataSourcePrefetchingProxy.proxy(for: base) } /** Installs prefetch data source as forwarding delegate on `rx.prefetchDataSource`. Prefetch data source won't be retained. It enables using normal delegate mechanism with reactive delegate mechanism. - parameter prefetchDataSource: Prefetch data source object. - returns: Disposable object that can be used to unbind the data source. */ public func setPrefetchDataSource(_ prefetchDataSource: UICollectionViewDataSourcePrefetching) -> Disposable { return RxCollectionViewDataSourcePrefetchingProxy.installForwardDelegate(prefetchDataSource, retainDelegate: false, onProxyForObject: self.base) } /// Reactive wrapper for `prefetchDataSource` message `collectionView(_:prefetchItemsAt:)`. public var prefetchItems: ControlEvent<[IndexPath]> { let source = RxCollectionViewDataSourcePrefetchingProxy.proxy(for: base).prefetchItemsPublishSubject return ControlEvent(events: source) } /// Reactive wrapper for `prefetchDataSource` message `collectionView(_:cancelPrefetchingForItemsAt:)`. public var cancelPrefetchingForItems: ControlEvent<[IndexPath]> { let source = prefetchDataSource.methodInvoked(#selector(UICollectionViewDataSourcePrefetching.collectionView(_:cancelPrefetchingForItemsAt:))) .map { a in return try castOrThrow(Array<IndexPath>.self, a[1]) } return ControlEvent(events: source) } } #endif #if os(tvOS) extension Reactive where Base: UICollectionView { /// Reactive wrapper for `delegate` message `collectionView(_:didUpdateFocusInContext:withAnimationCoordinator:)`. public var didUpdateFocusInContextWithAnimationCoordinator: ControlEvent<(context: UICollectionViewFocusUpdateContext, animationCoordinator: UIFocusAnimationCoordinator)> { let source = delegate.methodInvoked(#selector(UICollectionViewDelegate.collectionView(_:didUpdateFocusIn:with:))) .map { a -> (context: UICollectionViewFocusUpdateContext, animationCoordinator: UIFocusAnimationCoordinator) in let context = try castOrThrow(UICollectionViewFocusUpdateContext.self, a[1]) let animationCoordinator = try castOrThrow(UIFocusAnimationCoordinator.self, a[2]) return (context: context, animationCoordinator: animationCoordinator) } return ControlEvent(events: source) } } #endif
apache-2.0
371af5dab9c92994d04cbaa43c5a20f5
42.189474
215
0.655374
5.501844
false
false
false
false
dfuerle/kuroo
kuroo/ViewController+kuroo.swift
1
1983
// // ViewController+kuroo.swift // kuroo // // Copyright © 2016 Dmitri Fuerle. All rights reserved. // import UIKit extension UIViewController { func displayEmptyStateMessage(_ message: String) -> EmptyStateViewController { let storyboard = UIStoryboard.init(name: "Main", bundle: nil) let emptyStateViewController = storyboard.instantiateViewController(withIdentifier: "EmptyStateViewController") as! EmptyStateViewController if var contextViewController = self as? SupportsContext { emptyStateViewController.context = contextViewController.context } emptyStateViewController.view.translatesAutoresizingMaskIntoConstraints = false emptyStateViewController.message = message return emptyStateViewController } func displaySpinnerMessage(_ message: String) -> SpinnerViewController { let storyboard = UIStoryboard.init(name: "Main", bundle: nil) let spinnerViewController = storyboard.instantiateViewController(withIdentifier: "SpinnerViewController") as! SpinnerViewController if var contextViewController = self as? SupportsContext { spinnerViewController.context = contextViewController.context } spinnerViewController.view.translatesAutoresizingMaskIntoConstraints = false spinnerViewController.message = message return spinnerViewController } func addViewController(viewController: UIViewController) -> Void { addChildViewController(viewController) viewController.view.frame = self.view.bounds viewController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight] self.view.addSubview(viewController.view) viewController.didMove(toParentViewController: self) } func removeViewController(viewController: UIViewController) -> Void { viewController.removeFromParentViewController() viewController.view.removeFromSuperview() } }
gpl-2.0
189aa5fb3f99e27e6f689aea79a6090b
41.170213
148
0.737134
6.042683
false
false
false
false
jduquennoy/Log4swift
Log4swiftTests/LoggerFactoryTests.swift
1
9484
// // LoggerFactoryTests.swift // log4swift // // Created by Jérôme Duquennoy on 14/06/2015. // Copyright © 2015 Jérôme Duquennoy. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import XCTest @testable import Log4swift class LoggerFactoryTests: XCTestCase { var factory = LoggerFactory() override func setUp() { super.setUp() LoggerFactory.sharedInstance.resetConfiguration() factory = LoggerFactory() } override func tearDown() { super.tearDown() } func testSharedFactoryAlwaysReturnsTheSameObject() { // Execute let sharedFactory1 = LoggerFactory.sharedInstance let sharedFactory2 = LoggerFactory.sharedInstance NSLog("ping") // Validate XCTAssert(sharedFactory1 === sharedFactory2, "Shared factory should always be the same object") } func testClassMethodToGetLoggerReturnsSameLoggerAsSharedInstance() { let logger1 = LoggerFactory.getLogger(identifier: "test.logger") let logger2 = LoggerFactory.sharedInstance.getLogger("test.logger") XCTAssert(logger1 === logger2, "class method to get logger should return the same logger as shared instance") } func testFactoryThrowsErrorWhenTryingToRegisterALoggerWithEmptyIdentifier() { do { let logger = Logger(identifier: "", level: .Info, appenders: []) // Execute try self.factory.registerLogger(logger) // Validate (we should not reach that point XCTFail("Registering a logger with empty identifier should raise an error") } catch { // nothing, this is expected } } func testFactoryProvidesCopyOfRootLoggerByDefault() { // Execute let foundLogger = self.factory.getLogger("undefined.identifer") // Validate let rootLogger = self.factory.rootLogger XCTAssertEqual(foundLogger.thresholdLevel, rootLogger.thresholdLevel, "The obtained logger should have the same threshold as the root logger") XCTAssertTrue(foundLogger.appenders.elementsEqual(rootLogger.appenders, by: {$0 === $1}), "The created logger should have the same appenders as the closest one") XCTAssertEqual(foundLogger.identifier, "undefined.identifer", "The created logger should have the requested identifier") } func testFactoryProvidesLoggerThatExactlyMatchesTheRequestedIdentifier() { let logger = Logger(identifier: "test.logger.identifier", level: .Info, appenders: [StdOutAppender("test.appender")]) let logger2 = Logger(identifier: "test.logger.anotherIdentifier", level: .Info, appenders: [StdOutAppender("test.appender")]) try! self.factory.registerLogger(logger) try! self.factory.registerLogger(logger2) // Execute let foundLogger = self.factory.getLogger("test.logger.identifier") // Validate XCTAssert(foundLogger === logger, "Factory should return registered logger that exactly matches the requested identifier") } func testFactoryCreatesLoggerBasedOnTheClosestOneIfNoExactMatch() { let logger1 = Logger(identifier: "test.logger", level:.Info, appenders: [StdOutAppender("test.appender")]) let logger2 = Logger(identifier: "test.logger.identifier", level: .Info, appenders: [StdOutAppender("test.appender")]) try! self.factory.registerLogger(logger1) try! self.factory.registerLogger(logger2) // Execute let foundLogger = self.factory.getLogger("test.logger.identifier.plus.some.more") // Validate XCTAssertFalse(foundLogger === logger2, "The factory should have created a new logger") XCTAssertEqual(foundLogger.identifier, "test.logger.identifier.plus.some.more", "The created logger should have the requested identifier") XCTAssertEqual(foundLogger.thresholdLevel, logger2.thresholdLevel, "The created logger should have the same threshold as the closest one") XCTAssertTrue(foundLogger.appenders.elementsEqual(logger2.appenders, by: {$0 === $1}), "The created logger should have the same appenders as the closest one") } func testRequestingTwiceTheSameNonDefinedLoggerShouldReturnTheSameObject() { let logger1 = Logger(identifier: "test.logger", level:.Info, appenders: [StdOutAppender("test.appender")]) let logger2 = Logger(identifier: "test.logger.identifier", level: .Info, appenders: [StdOutAppender("test.appender")]) try! self.factory.registerLogger(logger1) try! self.factory.registerLogger(logger2) // Execute let foundLogger1 = self.factory.getLogger("test.logger.identifier.plus.some.more") let foundLogger2 = self.factory.getLogger("test.logger.identifier.plus.some.more") // Validate XCTAssertTrue(foundLogger1 === foundLogger2, "The two found loggers should be the same object") } func testFactoryDoesNotProvidesLoggerWithMorePreciseIdentifiers() { let logger = Logger(identifier: "test.logger.identifier.plus.some.more", level: .Info, appenders: [StdOutAppender("test.appender")]) try! self.factory.registerLogger(logger) // Execute let foundLogger = self.factory.getLogger("test.logger.identifier") // Validate let rootLogger = self.factory.rootLogger XCTAssertEqual(foundLogger.thresholdLevel, rootLogger.thresholdLevel, "The obtained logger should have the same threshold as the root logger") XCTAssertTrue(foundLogger.appenders.elementsEqual(rootLogger.appenders, by: {$0 === $1}), "The created logger should have the same appenders as the closest one") XCTAssertEqual(foundLogger.identifier, "test.logger.identifier", "The created logger should have the requested identifier") } func testGeneratedLoggersAreDeletedWhenRegisteringANewLogger() { let registeredLogger1 = Logger(identifier: "test.logger", level: .Info, appenders: [StdOutAppender("test.appender")]) let registeredLogger2 = Logger(identifier: "test.logger2", level: .Info, appenders: [StdOutAppender("test.appender")]) try! self.factory.registerLogger(registeredLogger1) let generatedLogger = self.factory.getLogger("test.logger.generated") // Execute try! self.factory.registerLogger(registeredLogger2) // Validate XCTAssertNil(self.factory.loggers["test.logger.generated"]) XCTAssertFalse(generatedLogger === self.factory.getLogger("test.logger.generated")) } func testRegisteredLoggersAreNotDeletedWhenRegisteringANewLogger() { let registeredLogger1 = Logger(identifier: "test.logger", level: .Info, appenders: [StdOutAppender("test.appender")]) let registeredLogger2 = Logger(identifier: "test.logger2", level: .Info, appenders: [StdOutAppender("test.appender")]) try! self.factory.registerLogger(registeredLogger1) // Execute try! self.factory.registerLogger(registeredLogger2) // Validate XCTAssertTrue(registeredLogger1 === self.factory.getLogger("test.logger")) } // MARK: - Convenience config methods func testConfigureForXCodeReplacesCurrentConfiguration() { self.factory.rootLogger.appenders = [MemoryAppender(), MemoryAppender()] try! self.factory.registerLogger(Logger(identifier: "test.logger")) // Execute self.factory.configureForXcodeConsole() // Validate XCTAssertEqual(self.factory.rootLogger.appenders.count, 1) XCTAssertEqual(self.factory.rootLogger.appenders[0].className, StdOutAppender.className()) XCTAssertEqual(self.factory.loggers.count, 0) } func testConfigureForXCodeConsoleSetsColorsForAllLevels() { // Execute self.factory.configureForXcodeConsole() // Validate if let xcodeAppender = self.factory.rootLogger.appenders[0] as? StdOutAppender { XCTAssertEqual(xcodeAppender.textColors.count, 6) } } func testConfigureForXCodeConsoleSetsPattern() { // Execute self.factory.configureForXcodeConsole() // Validate XCTAssertNotNil(self.factory.rootLogger.appenders[0].formatter, "Formatter was not set on the appender") } func testConfigureForSystemConsoleReplacesCurrentConfiguration() { self.factory.rootLogger.appenders = [MemoryAppender(), MemoryAppender()] try! self.factory.registerLogger(Logger(identifier: "test.logger")) // Execute self.factory.configureForSystemConsole() // Validate XCTAssertEqual(self.factory.rootLogger.appenders.count, 1) XCTAssertEqual(self.factory.rootLogger.appenders[0].className, ASLAppender.className()) XCTAssertEqual(self.factory.loggers.count, 0) } func testConfigureForNSLoggerReplacesCurrentConfiguration() { self.factory.rootLogger.appenders = [MemoryAppender(), MemoryAppender()] try! self.factory.registerLogger(Logger(identifier: "test.logger")) // Execute self.factory.configureForNSLogger() // Validate XCTAssertEqual(self.factory.rootLogger.appenders.count, 1) XCTAssertEqual(self.factory.rootLogger.appenders[0].className, NSLoggerAppender.className()) XCTAssertEqual(self.factory.loggers.count, 0) } }
apache-2.0
c3587d96a6dc7a7f4927e92286f72ba4
40.942478
165
0.737736
4.275598
false
true
false
false
daggmano/photo-management-studio
src/Client/OSX/PMS-2/Photo Management Studio/Photo Management Studio/TagObject.swift
1
1773
// // TagObject.swift // Photo Management Studio // // Created by Darren Oster on 30/04/2016. // Copyright © 2016 Criterion Software. All rights reserved. // import Cocoa class TagObject: NSObject, JsonProtocol { internal private(set) var tagId: String? internal private(set) var tagRev: String? internal private(set) var subType: String? internal private(set) var name: String? internal private(set) var color: String? internal private(set) var parentId: String? init(tagId: String, tagRev: String, subType: String, name: String, color: String?, parentId: String?) { self.tagId = tagId self.tagRev = tagRev self.subType = subType self.name = name self.color = color self.parentId = parentId } required init(json: [String: AnyObject]) { self.tagId = json["_id"] as? String self.tagRev = json["_rev"] as? String self.subType = json["subType"] as? String self.name = json["name"] as? String self.color = json["color"] as? String self.parentId = json["parentId"] as? String } func toJSON() -> [String: AnyObject] { var result = [String: AnyObject]() if let tagId = self.tagId { result["_id"] = tagId } if let tagRev = self.tagRev { result["_rev"] = tagRev } if let subType = self.subType { result["subType"] = subType } if let name = self.name { result["name"] = name } if let color = self.color { result["color"] = color } if let parentId = self.parentId { result["parentId"] = parentId } return result } }
mit
db350e0a83d5fbedf1cbdd41d0e496e0
28.04918
107
0.56377
4.209026
false
false
false
false
themungapp/themungapp
Mung/profileViewController.swift
1
1936
// // profileViewController.swift // Mung // // Created by Chike Chiejine on 04/10/2016. // Copyright © 2016 Color & Space. All rights reserved. // import UIKit class profileViewController: UIViewController { @IBOutlet weak var pageControl: UIPageControl! var pageViewController : UIPageViewController! @IBOutlet weak var containerView: UIView! var ProfileTabsViewController: profileTabsViewController? override func viewDidLoad() { super.viewDidLoad() pageControl.isHidden = true // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let tutorialPageViewController = segue.destination as? profileTabsViewController { self.ProfileTabsViewController = tutorialPageViewController } } @IBAction func didTapNextButton(_ sender: UIButton) { ProfileTabsViewController?.scrollToNextViewController() } /** Fired when the user taps on the pageControl to change its current page. */ func didChangePageControlValue() { ProfileTabsViewController?.scrollToViewController(index: pageControl.currentPage) } } //extension profileViewController: profileTabsViewControllerDelegate { // // func ProfileTabsViewController(ProfileTabsViewController: profileTabsViewController, // didUpdatePageCount count: Int) { // pageControl.numberOfPages = count // } // // func ProfileTabsViewController(ProfileTabsViewController: profileTabsViewController, // didUpdatePageIndex index: Int) { // pageControl.currentPage = index // } // //}
bsd-3-clause
cb441b96115aa3ce19a63f08cf561190
26.642857
93
0.666667
5.389972
false
false
false
false
pyconjp/pyconjp-ios
PyConJP/DataStore/DataSource/Timeline/Bookmark/BookmarkListDataSource.swift
1
878
// // BookmarkListDataSource.swift // PyConJP // // Created by Yutaro Muta on 2016/08/18. // Copyright © 2016 PyCon JP. All rights reserved. // import Foundation import Result class BookmarkListDataSource: TimelineDataSource { private let loadTalksRequest = LoadFavoriteTalksRequest() func refreshData(completionHandler: @escaping ((Result<Void, NSError>) -> Void)) { do { let talks = try loadTalksRequest.load() timelines.removeAll() let keys = talks.map { $0.day }.unique() for tuple in keys.enumerated() { timelines.append(Timeline(key: keys[tuple.offset], talks: talks.filter { $0.day == keys[tuple.offset]})) } completionHandler(.success(())) } catch let error as NSError { completionHandler(.failure(error)) } } }
mit
43ccb5d70f5915162182914b31fa2871
28.233333
120
0.610034
4.236715
false
false
false
false
IvanGao0217/IGIAPManager
IGIAPManager.swift
1
3549
// // IGIAPManager.swift // Aloha // // Created by IvanGao on 10/24/16. // Copyright © 2016 IvanGao. All rights reserved. // import Foundation import StoreKit public protocol IGIAPManagerDelegate: NSObjectProtocol { func iapProductionListRequestSuccess() func iapProductionListRequestFailed() func iapProductionPurchaseSuccess(paymentTransactionId: String, receiptString: String) func iapProductionPurchaseFailed(productIdentifier: String, error: NSError?) } public class IGIAPManager: NSObject { public static let sharedInstance = IGIAPManager() public weak var delegate: IGIAPManagerDelegate? private(set) var productList: [SKProduct] = [] public static func addIAPTransactionObserver() { SKPaymentQueue.default().add(sharedInstance) } public static func removeIAPTransactionObserver() { SKPaymentQueue.default().remove(sharedInstance) } public static func purchaseProductWithIapId(iapId: String) { let products = sharedInstance.productList.filter { $0.productIdentifier == iapId } guard let product = products.first else { return } let payment = SKMutablePayment(product: product) SKPaymentQueue.default().add(payment) } public static func closeSuccessTransaction(transactionIdentifier: String) { SKPaymentQueue.default().transactions.forEach { paymentTransaction in guard paymentTransaction.transactionIdentifier == transactionIdentifier else { return } SKPaymentQueue.default().finishTransaction(paymentTransaction) } } public static func closeFailedTransaction(productIdentifier: String) { SKPaymentQueue.default().transactions.forEach { paymentTransaction in guard paymentTransaction.payment.productIdentifier == productIdentifier else { return } SKPaymentQueue.default().finishTransaction(paymentTransaction) } } } extension IGIAPManager: SKPaymentTransactionObserver { public func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) { transactions.forEach { paymentTransaction in switch paymentTransaction.transactionState { case .failed: self.delegate?.iapProductionPurchaseFailed(productIdentifier: paymentTransaction.payment.productIdentifier, error: paymentTransaction.error as NSError?) case .purchased, .restored: if let url = Bundle.main.appStoreReceiptURL, let data = NSData(contentsOf: url) { let receiptString = data.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0)) self.delegate?.iapProductionPurchaseSuccess(paymentTransactionId: paymentTransaction.transactionIdentifier!, receiptString: receiptString) } case .purchasing, .deferred: break } } } } extension IGIAPManager: SKProductsRequestDelegate { public static func productRequest(iapIds: [String]) { let request = SKProductsRequest(productIdentifiers: Set(iapIds)) request.delegate = sharedInstance request.start() } public func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) { guard response.products.count > 0 else { self.delegate?.iapProductionListRequestFailed() return } self.delegate?.iapProductionListRequestSuccess() } }
mit
0b30826e454cc8f4d4a8704f190787ff
38.865169
168
0.701804
5.483771
false
false
false
false
apple/swift
test/Generics/loop_normalization_1.swift
6
1568
// RUN: %target-swift-frontend -typecheck %s -debug-generic-signatures 2>&1 | %FileCheck %s protocol P { associatedtype T } struct C {} // CHECK-LABEL: .f1@ // CHECK-NEXT: Generic signature: <T, U where T : P, U : P, T.[P]T == C, U.[P]T == C> func f1<T: P, U: P>(_: T, _: U) where T.T == C, T.T == U.T { } // CHECK-LABEL: .f2@ // CHECK-NEXT: Generic signature: <T, U where T : P, U : P, T.[P]T == C, U.[P]T == C> func f2<T: P, U: P>(_: T, _: U) where U.T == C, T.T == U.T { } // CHECK-LABEL: .f3@ // CHECK-NEXT: Generic signature: <T, U where T : P, U : P, T.[P]T == C, U.[P]T == C> func f3<T: P, U: P>(_: T, _: U) where T.T == C, U.T == C, T.T == U.T { } // CHECK-LABEL: .f4@ // CHECK-NEXT: Generic signature: <T, U where T : P, U : P, T.[P]T == C, U.[P]T == C> func f4<T: P, U: P>(_: T, _: U) where T.T == C, T.T == U.T, U.T == C { } // CHECK-LABEL: .f5@ // CHECK-NEXT: Generic signature: <T, U where T : P, U : P, T.[P]T == C, U.[P]T == C> func f5<T: P, U: P>(_: T, _: U) where T.T == U.T, T.T == C, U.T == C { } // CHECK-LABEL: .f6@ // CHECK-NEXT: Generic signature: <T, U where T : P, U : P, T.[P]T == C, U.[P]T == C> func f6<T: P, U: P>(_: T, _: U) where U.T == C, T.T == C, T.T == U.T { } // CHECK-LABEL: .f7@ // CHECK-NEXT: Generic signature: <T, U where T : P, U : P, T.[P]T == C, U.[P]T == C> func f7<T: P, U: P>(_: T, _: U) where T.T == C, U.T == C, T.T == U.T { } // CHECK-LABEL: .f8@ // CHECK-NEXT: Generic signature: <T, U where T : P, U : P, T.[P]T == C, U.[P]T == C> func f8<T: P, U: P>(_: T, _: U) where T.T == U.T, U.T == C, T.T == C { }
apache-2.0
ccd2c4f4b5be5fcea664c9073f3916d0
39.205128
91
0.481505
2.110363
false
false
false
false
rnystrom/GitHawk
Classes/Models/FilePath.swift
1
2066
// // FilePath.swift // Freetime // // Created by Ryan Nystrom on 12/3/17. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import Foundation struct FilePath { static private let joiner = "/" let components: [String] var baseComponents: [String]? { let count = components.count guard count > 1 else { return nil } return Array(components[0..<count-1]) } var path: String { return components.joined(separator: FilePath.joiner) } var basePath: String? { return baseComponents?.joined(separator: FilePath.joiner) } var current: String? { return components.last } var fileExtension: String? { let components = current?.components(separatedBy: ".") ?? [] if components.count > 1 { return components.last } else { return nil } } func appending(_ component: String) -> FilePath { return FilePath(components: components + [component]) } var isImage: Bool { guard let last = components.last else { return false } for format in ["png", "jpg", "jpeg", "gif"] { if last.hasSuffix(format) { return true } } return false } } // MARK: - FilePath (BinaryFile) - extension FilePath { private static let supportedBinaries = [ "pdf": "application/pdf" ] // MARK: Public API /// A Boolean value indicating whether a string has binary file suffix. /// /// Supported types: **pdf**. var hasBinarySuffix: Bool { return binarySuffix != nil } /// Returns mime type for the supported binary files. var mimeType: String? { guard let type = binarySuffix else { return nil } return FilePath.supportedBinaries[type] } // MARK: Private API private var binarySuffix: String? { guard let last = components.last else { return nil } return FilePath.supportedBinaries.keys.first(where: { last.hasSuffix($0) }) } }
mit
e8971fe651fb026367cd86d93c14cd29
21.692308
83
0.590799
4.421842
false
false
false
false
akshayg13/Game
Games/AppDelegate.swift
1
4586
// // AppDelegate.swift // Games // // Created by Appinventiv on 16/02/17. // Copyright © 2017 Appinventiv. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded 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. */ let container = NSPersistentContainer(name: "Games") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() 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. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() 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 fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
mit
d376c79d65f8f0489f09868f796877c5
48.301075
285
0.685714
5.878205
false
false
false
false
DragonCherry/AssetsPickerViewController
AssetsPickerViewController/Classes/Assets/AssetsManager.swift
1
35410
// // AssetsManager.swift // Pods // // Created by DragonCherry on 5/19/17. // // import UIKit import Photos // MARK: - AssetsManagerDelegate public protocol AssetsManagerDelegate: class { func assetsManager(manager: AssetsManager, authorizationStatusChanged oldStatus: PHAuthorizationStatus, newStatus: PHAuthorizationStatus) func assetsManager(manager: AssetsManager, reloadedAlbumsInSection section: Int) func assetsManagerFetched(manager: AssetsManager) func assetsManager(manager: AssetsManager, insertedAlbums albums: [PHAssetCollection], at indexPaths: [IndexPath]) func assetsManager(manager: AssetsManager, removedAlbums albums: [PHAssetCollection], at indexPaths: [IndexPath]) func assetsManager(manager: AssetsManager, updatedAlbums albums: [PHAssetCollection], at indexPaths: [IndexPath]) func assetsManager(manager: AssetsManager, reloadedAlbum album: PHAssetCollection, at indexPath: IndexPath) func assetsManager(manager: AssetsManager, insertedAssets assets: [PHAsset], at indexPaths: [IndexPath]) func assetsManager(manager: AssetsManager, removedAssets assets: [PHAsset], at indexPaths: [IndexPath]) func assetsManager(manager: AssetsManager, updatedAssets assets: [PHAsset], at indexPaths: [IndexPath]) } typealias AssetsFetchEntry = (albums: [PHFetchResult<PHAsset>], fetchMap: [String: PHFetchResult<PHAsset>], albumMap: [String: PHAssetCollection]) typealias AssetsAlbumEntry = (fetchedAlbums: [PHAssetCollection], sortedAlbums: [PHAssetCollection], fetchResult: PHFetchResult<PHAssetCollection>) typealias AssetsAlbumArrayEntry = (fetchedAlbumsArray: [[PHAssetCollection]], sortedAlbumsArray: [[PHAssetCollection]], albumsFetchArray: [PHFetchResult<PHAssetCollection>]) // MARK: - AssetsManager open class AssetsManager: NSObject { public static let shared = AssetsManager() open var pickerConfig = AssetsPickerConfig() { didSet { isFetchedAlbums = false } } fileprivate let imageManager = PHCachingImageManager() fileprivate var authorizationStatus = PHPhotoLibrary.authorizationStatus() var subscribers = [AssetsManagerDelegate]() fileprivate var albumMap = [String: PHAssetCollection]() var albumsFetchArray = [PHFetchResult<PHAssetCollection>]() var fetchMap = [String: PHFetchResult<PHAsset>]() /// stores originally fetched array var fetchedAlbumsArray = [[PHAssetCollection]]() /// stores sorted array by applying user defined comparator, it's in decreasing order by count by default, and it might same as fetchedAlbumsArray if AssetsPickerConfig has albumFetchOptions without albumComparator var sortedAlbumsArray = [[PHAssetCollection]]() internal(set) open var fetchResult: PHFetchResult<PHAsset>? fileprivate(set) open var defaultAlbum: PHAssetCollection? fileprivate(set) open var cameraRollAlbum: PHAssetCollection! fileprivate(set) open var selectedAlbum: PHAssetCollection? fileprivate(set) var isFetchedAlbums: Bool = false fileprivate var resourceLoadingQueue: DispatchQueue = DispatchQueue(label: "com.assetspicker.loader", qos: .userInitiated) fileprivate var albumLoadingQueue: DispatchQueue = DispatchQueue(label: "com.assetspicker.album.loader", qos: .default) private override init() { super.init() } deinit { logd("Released \(type(of: self))") } open func clear() { // clear observer & subscriber unregisterObserver() unsubscribeAll() // clear cache if PHPhotoLibrary.authorizationStatus() == .authorized { imageManager.stopCachingImagesForAllAssets() } // clear albums albumMap.removeAll() fetchedAlbumsArray.removeAll() sortedAlbumsArray.removeAll() // clear assets fetchResult = nil // clear fetch results albumsFetchArray.removeAll() fetchMap.removeAll() // clear flags selectedAlbum = nil isFetchedAlbums = false logd("cleared AssetsManager object.") } } // MARK: - Subscriber extension AssetsManager { open func subscribe(subscriber: AssetsManagerDelegate) { subscribers.append(subscriber) } open func unsubscribe(subscriber: AssetsManagerDelegate) { if let index = subscribers.firstIndex(where: { subscriber === $0 }) { subscribers.remove(at: index) } } open func unsubscribeAll() { subscribers.removeAll() } open func notifySubscribers(_ action: @escaping ((AssetsManagerDelegate) -> Void), condition: Bool = true) { if condition { DispatchQueue.main.sync { for subscriber in self.subscribers { action(subscriber) } } } } } // MARK: - Observer extension AssetsManager { open func registerObserver() { PHPhotoLibrary.shared().register(self) } open func unregisterObserver() { PHPhotoLibrary.shared().unregisterChangeObserver(self) } } // MARK: - Permission extension AssetsManager { open func authorize(completion: @escaping ((Bool) -> Void)) { if PHPhotoLibrary.authorizationStatus() == .authorized { completion(true) } else { if #available(iOS 14, *) { PHPhotoLibrary.requestAuthorization(for: .addOnly, handler: { (status) in DispatchQueue.main.async { switch status { case .authorized: completion(true) default: completion(false) } } }) } else { PHPhotoLibrary.requestAuthorization { (status) in DispatchQueue.main.async { switch status { case .authorized: completion(true) default: completion(false) } } } } } } } // MARK: - Cache extension AssetsManager { open func cache(asset: PHAsset, size: CGSize) { cache(assets: [asset], size: size) } open func cache(assets: [PHAsset], size: CGSize) { imageManager.startCachingImages(for: assets, targetSize: size, contentMode: .aspectFill, options: nil) } open func stopCache(asset: PHAsset, size: CGSize) { stopCache(assets: [asset], size: size) } open func stopCache(assets: [PHAsset], size: CGSize) { imageManager.stopCachingImages(for: assets, targetSize: size, contentMode: .aspectFill, options: nil) } } // MARK: - Sources extension AssetsManager { open var numberOfSections: Int { return sortedAlbumsArray.count } open func numberOfAlbums(inSection: Int) -> Int { return sortedAlbumsArray[inSection].count } open func numberOfAssets(at indexPath: IndexPath) -> Int { return Int(fetchMap[sortedAlbumsArray[indexPath.section][indexPath.row].localIdentifier]?.count ?? 0) } open func indexPath(forAlbum target: PHAssetCollection, inAlbumsArray albumsArray: [[PHAssetCollection]]) -> IndexPath? { let section = albumSection(forType: target.assetCollectionType) if let row = albumsArray[section].firstIndex(of: target) { return IndexPath(row: row, section: section) } else { return nil } } open func title(at indexPath: IndexPath) -> String? { return sortedAlbumsArray[indexPath.section][indexPath.row].localizedTitle } open func imageOfAlbum(at indexPath: IndexPath, size: CGSize, isNeedDegraded: Bool = true, completion: @escaping ((UIImage?) -> Void)) -> PHImageRequestID? { let album = sortedAlbumsArray[indexPath.section][indexPath.row] if let fetchResult = fetchMap[album.localIdentifier] { if let asset = pickerConfig.assetsIsScrollToBottom ? fetchResult.lastObject : fetchResult.firstObject { let options = PHImageRequestOptions() options.isNetworkAccessAllowed = true return imageManager.requestImage( for: asset, targetSize: size, contentMode: .aspectFill, options: options, resultHandler: { (image, info) in let isDegraded = (info?[PHImageResultIsDegradedKey] as? Bool) ?? false if !isNeedDegraded && isDegraded { return } DispatchQueue.main.async { completion(image) } }) } else { completion(nil) } } else { completion(nil) } return nil } @discardableResult open func image(at index: Int, size: CGSize, isNeedDegraded: Bool = true, completion: @escaping ((UIImage?, Bool) -> Void)) -> PHImageRequestID { let options = PHImageRequestOptions() options.isNetworkAccessAllowed = true options.resizeMode = .exact return imageManager.requestImage( for: fetchResult!.object(at: index), targetSize: size, contentMode: .aspectFill, options: options, resultHandler: { (image, info) in let isDegraded = info?[PHImageResultIsDegradedKey] as? Bool ?? false if !isNeedDegraded && isDegraded { return } DispatchQueue.main.async { completion(image, isDegraded) } }) } open func cancelRequest(requestId: PHImageRequestID) { imageManager.cancelImageRequest(requestId) } open func fetchResult(forAlbum album: PHAssetCollection) -> PHFetchResult<PHAsset>? { return fetchMap[album.localIdentifier] } open func album(at indexPath: IndexPath) -> PHAssetCollection { return sortedAlbumsArray[indexPath.section][indexPath.row] } open func albumSection(forType type: PHAssetCollectionType) -> Int { switch type { case .smartAlbum: return 0 case .album: return 1 case .moment: return 2 @unknown default: fatalError() } } open func albumType(forSection section: Int) -> PHAssetCollectionType { switch section { case 0: return .smartAlbum case 1: return .album case 2: return .moment default: loge("Section number error: \(section)") return .album } } open func count(ofType type: PHAssetMediaType) -> Int { if let album = self.selectedAlbum, let fetchResult = fetchMap[album.localIdentifier] { return fetchResult.countOfAssets(with: type) } else { var count = 0 for albums in sortedAlbumsArray { for album in albums { if let fetchResult = fetchMap[album.localIdentifier], album.assetCollectionSubtype != .smartAlbumRecentlyAdded { count += fetchResult.countOfAssets(with: type) } } } return count } } open func isExist(asset: PHAsset) -> Bool { return PHAsset.fetchAssets(withLocalIdentifiers: [asset.localIdentifier], options: nil).count > 0 } @discardableResult open func select(album newAlbum: PHAssetCollection) -> Bool { if let oldAlbumIdentifier = self.selectedAlbum?.localIdentifier, oldAlbumIdentifier == newAlbum.localIdentifier { logi("Selected same album.") return false } self.selectedAlbum = newAlbum guard let album = AssetsManager.shared.selectedAlbum else { return false } guard let fetchResult = AssetsManager.shared.fetchMap[album.localIdentifier] else { return false } self.fetchResult = fetchResult return true } open func selectDefaultAlbum() { self.selectedAlbum = nil let allAlbums = sortedAlbumsArray.flatMap { $0 }.map { $0 } if let defaultAlbum = self.defaultAlbum, allAlbums.contains(defaultAlbum) { select(album: defaultAlbum) } else if let cameraRollAlbum = self.cameraRollAlbum, allAlbums.contains(cameraRollAlbum) { select(album: cameraRollAlbum) } else if let firstAlbum = allAlbums.first { select(album: firstAlbum) } else { logw("Cannot find fallback album!") } } open func selectAsync(album newAlbum: PHAssetCollection, completion: @escaping (Bool, PHFetchResult<PHAsset>?) -> Void) { if let oldAlbumIdentifier = self.selectedAlbum?.localIdentifier, oldAlbumIdentifier == newAlbum.localIdentifier { logi("Selected same album.") completion(false, nil) } self.selectedAlbum = newAlbum guard let album = AssetsManager.shared.selectedAlbum else { completion(false, nil) return } guard let fetchResult = AssetsManager.shared.fetchMap[album.localIdentifier] else { completion(false, nil) return } self.fetchResult = fetchResult completion(true, fetchResult) } } // MARK: - Model Manipulation extension AssetsManager { func isQualified(album: PHAssetCollection) -> Bool { if let albumFilter = pickerConfig.albumFilter?[album.assetCollectionType], let fetchResult = fetchMap[album.localIdentifier] { return albumFilter(album, fetchResult) } guard self.pickerConfig.albumIsShowHiddenAlbum || album.assetCollectionSubtype != .smartAlbumAllHidden else { return false } guard let fetchResult = self.fetchMap[album.localIdentifier], self.pickerConfig.albumIsShowEmptyAlbum || fetchResult.count > 0 else { return false } return true } func isQualified(album: PHAssetCollection, filterBy fetchMap: [String: PHFetchResult<PHAsset>]) -> Bool { if let albumFilter = pickerConfig.albumFilter?[album.assetCollectionType], let fetchResult = fetchMap[album.localIdentifier] { return albumFilter(album, fetchResult) } guard self.pickerConfig.albumIsShowHiddenAlbum || album.assetCollectionSubtype != .smartAlbumAllHidden else { return false } guard let fetchResult = fetchMap[album.localIdentifier], self.pickerConfig.albumIsShowEmptyAlbum || fetchResult.count > 0 else { return false } return true } func remove(album: PHAssetCollection? = nil, indexPath: IndexPath? = nil) { if let indexPath = indexPath { fetchedAlbumsArray[indexPath.section].remove(at: indexPath.row) } else if let albumToRemove = album { for (section, fetchedAlbums) in fetchedAlbumsArray.enumerated() { if let row = fetchedAlbums.firstIndex(of: albumToRemove) { fetchedAlbumsArray[section].remove(at: row) } } } else { logw("Empty parameters.") } } func sortedAlbums(fromAlbums albums: [PHAssetCollection]) -> [PHAssetCollection] { guard let albumType = albums.first?.assetCollectionType else { return albums } let filtered = albums.filter { self.isQualified(album: $0) } if let comparator = pickerConfig.albumComparator { return filtered.sorted(by: { (leftAlbum, rightAlbum) -> Bool in if let leftResult = self.fetchMap[leftAlbum.localIdentifier], let rightResult = self.fetchMap[rightAlbum.localIdentifier] { return comparator(leftAlbum.assetCollectionType, (leftAlbum, leftResult), (rightAlbum, rightResult)) } else { logw("Failed to get fetch result from fetchMap. Please raise an issue if you've met this message.") return true } }) } else { if let _ = pickerConfig.albumFetchOptions?[albumType] { // return fetched album as it is return filtered } else { // default: by count return filtered.sorted(by: { Int((self.fetchMap[$0.localIdentifier]?.count) ?? 0) > Int((self.fetchMap[$1.localIdentifier]?.count) ?? 0) }) } } } func sortedAlbums(fromAlbums albums: [PHAssetCollection], filterBy fetchMap: [String: PHFetchResult<PHAsset>]) -> [PHAssetCollection] { guard let albumType = albums.first?.assetCollectionType else { return albums } let filtered = albums.filter { self.isQualified(album: $0, filterBy: fetchMap) } if let comparator = pickerConfig.albumComparator { return filtered.sorted(by: { (leftAlbum, rightAlbum) -> Bool in if let leftResult = fetchMap[leftAlbum.localIdentifier], let rightResult = fetchMap[rightAlbum.localIdentifier] { return comparator(leftAlbum.assetCollectionType, (leftAlbum, leftResult), (rightAlbum, rightResult)) } else { logw("Failed to get fetch result from fetchMap. Please raise an issue if you've met this message.") return true } }) } else { if let _ = pickerConfig.albumFetchOptions?[albumType] { // return fetched album as it is return filtered } else { // default: by count return filtered.sorted(by: { Int((fetchMap[$0.localIdentifier]?.count) ?? 0) > Int((fetchMap[$1.localIdentifier]?.count) ?? 0) }) } } } } // MARK: - Check extension AssetsManager { @discardableResult func notifyIfAuthorizationStatusChanged() -> Bool { var newStatus: PHAuthorizationStatus = .authorized if #available(iOS 14, *) { newStatus = PHPhotoLibrary.authorizationStatus(for: .addOnly) let oldStatus = authorizationStatus authorizationStatus = newStatus if newStatus == .limited { for subscriber in self.subscribers { DispatchQueue.main.async { [weak self] in guard let `self` = self else { return } subscriber.assetsManager(manager: self, authorizationStatusChanged: oldStatus, newStatus: newStatus) } } return false } } else { newStatus = PHPhotoLibrary.authorizationStatus() if authorizationStatus != newStatus { let oldStatus = authorizationStatus authorizationStatus = newStatus DispatchQueue.main.async { [weak self] in guard let `self` = self else { return } for subscriber in self.subscribers { subscriber.assetsManager(manager: self, authorizationStatusChanged: oldStatus, newStatus: newStatus) } } } } if #available(iOS 14, *) { return authorizationStatus == .authorized || authorizationStatus == .limited } else { return authorizationStatus == .authorized } } func isCountChanged(changeDetails: PHFetchResultChangeDetails<PHAsset>) -> Bool { return changeDetails.fetchResultBeforeChanges.count != changeDetails.fetchResultAfterChanges.count } func isThumbnailChanged(changeDetails: PHFetchResultChangeDetails<PHAsset>) -> Bool { var isChanged: Bool = false if let lastBeforeChange = changeDetails.fetchResultBeforeChanges.lastObject { if let lastAfterChange = changeDetails.fetchResultAfterChanges.lastObject { if lastBeforeChange.localIdentifier == lastAfterChange.localIdentifier { if let _ = changeDetails.changedObjects.firstIndex(of: lastAfterChange) { isChanged = true } } else { isChanged = true } } else { isChanged = true } } else { if let _ = changeDetails.fetchResultAfterChanges.lastObject { isChanged = true } } return isChanged } } // MARK: - Fetch extension AssetsManager { open func fetchAlbums(isRefetch: Bool = false, completion: @escaping (([[PHAssetCollection]]) -> Void)) { if isRefetch { selectedAlbum = nil isFetchedAlbums = false fetchedAlbumsArray.removeAll() sortedAlbumsArray.removeAll() albumsFetchArray.removeAll() fetchMap.removeAll() albumMap.removeAll() } resourceLoadingQueue.async { [weak self] in guard let `self` = self else { return } if !self.isFetchedAlbums { var types: [PHAssetCollectionType] = [ .smartAlbum, .album ] let smartAlbumEntry = self.fetchDefaultAlbums(forAlbumType: .smartAlbum) self.fetchedAlbumsArray.append(smartAlbumEntry.fetchedAlbums) self.sortedAlbumsArray.append(smartAlbumEntry.sortedAlbums) self.albumsFetchArray.append(smartAlbumEntry.fetchResult) let albumEntry = self.fetchDefaultAlbums(forAlbumType: .album) self.fetchedAlbumsArray.append(albumEntry.fetchedAlbums) self.sortedAlbumsArray.append(albumEntry.sortedAlbums) self.albumsFetchArray.append(albumEntry.fetchResult) if self.pickerConfig.albumIsShowMomentAlbums { types.append(.moment) let momentEntry = self.fetchDefaultAlbums(forAlbumType: .moment) self.fetchedAlbumsArray.append(momentEntry.fetchedAlbums) self.sortedAlbumsArray.append(momentEntry.sortedAlbums) self.albumsFetchArray.append(momentEntry.fetchResult) } self.subscribers.forEach { [weak self] (delegate) in guard let `self` = self else { return } DispatchQueue.main.async { delegate.assetsManagerFetched(manager: self) } } self.fetchAllAlbums(types: types) { (result) in self.fetchedAlbumsArray = result.fetchedAlbumsArray self.sortedAlbumsArray = result.sortedAlbumsArray self.albumsFetchArray = result.albumsFetchArray self.subscribers.forEach { [weak self] (delegate) in guard let `self` = self else { return } DispatchQueue.main.async { delegate.assetsManagerFetched(manager: self) } } self.isFetchedAlbums = true } } // notify DispatchQueue.main.async { completion(self.sortedAlbumsArray) } } } func fetchAllAlbums(types: [PHAssetCollectionType], complection: @escaping (AssetsAlbumArrayEntry) -> Void ) { let queue = DispatchQueue.global(qos: .userInitiated) var fetchedAlbumsArray: [[PHAssetCollection]] = [] var sortedAlbumsArray: [[PHAssetCollection]] = [] var albumsFetchArray: [PHFetchResult<PHAssetCollection>] = [] let group = DispatchGroup() var fetchMap = [String: PHFetchResult<PHAsset>]() var albumMap = [String: PHAssetCollection]() for type in types { queue.async(group: group) { group.enter() self.fetchAlbumsAsync(forAlbumType: type) { (albumsArrayEntry, fetchedEntry) in fetchedAlbumsArray.append(albumsArrayEntry.fetchedAlbums) sortedAlbumsArray.append(albumsArrayEntry.sortedAlbums) albumsFetchArray.append(albumsArrayEntry.fetchResult) fetchMap = fetchMap.merging(fetchedEntry.fetchMap) { (first, second) -> PHFetchResult<PHAsset> in return first } albumMap = albumMap.merging(fetchedEntry.albumMap) { (first, second) -> PHAssetCollection in return first } group.leave() } } } group.notify(queue: .main) { self.fetchMap = fetchMap self.albumMap = albumMap let result = (fetchedAlbumsArray, sortedAlbumsArray, albumsFetchArray) complection(result) } } open func fetchAssets(isRefetch: Bool = false, completion: ((PHFetchResult<PHAsset>?) -> Void)? = nil) { fetchAlbums(isRefetch: isRefetch, completion: { [weak self] _ in guard let `self` = self else { return } if isRefetch { self.fetchResult = nil } // set default album self.selectAsync(album: self.defaultAlbum ?? self.cameraRollAlbum) { successful, result in completion?(result) } }) } func fetchDefaultAlbums(forAlbumType type: PHAssetCollectionType) -> (fetchedAlbums: [PHAssetCollection], sortedAlbums: [PHAssetCollection], fetchResult: PHFetchResult<PHAssetCollection>) { let fetchOption = pickerConfig.albumFetchOptions?[type] let albumFetchResult = PHAssetCollection.fetchAssetCollections(with: type, subtype: .any, options: fetchOption) var fetchedAlbums = [PHAssetCollection]() let indexSet = IndexSet(integersIn: 0..<albumFetchResult.count) let albums = albumFetchResult.objects(at: indexSet) for album in albums { // set default album if album.assetCollectionSubtype == self.pickerConfig.albumDefaultType { self.defaultAlbum = album // fetch assets self.fetchAlbum(album: album) fetchedAlbums.append(album) } // save alternative album if album.assetCollectionSubtype == .smartAlbumUserLibrary { self.cameraRollAlbum = album // fetch assets self.fetchAlbum(album: album) fetchedAlbums.append(album) } } // get sorted albums let sortedAlbums = self.sortedAlbums(fromAlbums: fetchedAlbums) // set default album if let defaultAlbum = self.defaultAlbum { logi("Default album is \"\(defaultAlbum.localizedTitle ?? "")\"") } else { if let defaultAlbum = self.defaultAlbum { logi("Set default album \"\(defaultAlbum.localizedTitle ?? "")\"") } else { if let cameraRollAlbum = self.cameraRollAlbum { self.defaultAlbum = cameraRollAlbum logw("Set default album with fallback default album \"\(cameraRollAlbum.localizedTitle ?? "")\"") } else { if let firstAlbum = sortedAlbums.first, type == .smartAlbum { self.defaultAlbum = firstAlbum loge("Set default album with first item \"\(firstAlbum.localizedTitle ?? "")\"") } else { logc("Is this case could happen? Please raise an issue if you've met this message.") } } } } // append album fetch result return (fetchedAlbums, sortedAlbums, albumFetchResult) } func fetchAlbums(forAlbumType type: PHAssetCollectionType) -> (fetchedAlbums: [PHAssetCollection], sortedAlbums: [PHAssetCollection], fetchResult: PHFetchResult<PHAssetCollection>) { let fetchOption = pickerConfig.albumFetchOptions?[type] let albumFetchResult = PHAssetCollection.fetchAssetCollections(with: type, subtype: .any, options: fetchOption) var fetchedAlbums = [PHAssetCollection]() let indexSet = IndexSet(integersIn: 0..<albumFetchResult.count) let albums = albumFetchResult.objects(at: indexSet) for album in albums { // fetch assets self.fetchAlbum(album: album) // set default album if album.assetCollectionSubtype == self.pickerConfig.albumDefaultType { self.defaultAlbum = album } // save alternative album if album.assetCollectionSubtype == .smartAlbumUserLibrary { self.cameraRollAlbum = album } fetchedAlbums.append(album) } // get sorted albums let sortedAlbums = self.sortedAlbums(fromAlbums: fetchedAlbums) // set default album if let defaultAlbum = self.defaultAlbum { logi("Default album is \"\(defaultAlbum.localizedTitle ?? "")\"") } else { if let defaultAlbum = self.defaultAlbum { logi("Set default album \"\(defaultAlbum.localizedTitle ?? "")\"") } else { if let cameraRollAlbum = self.cameraRollAlbum { self.defaultAlbum = cameraRollAlbum logw("Set default album with fallback default album \"\(cameraRollAlbum.localizedTitle ?? "")\"") } else { if let firstAlbum = sortedAlbums.first, type == .smartAlbum { self.defaultAlbum = firstAlbum loge("Set default album with first item \"\(firstAlbum.localizedTitle ?? "")\"") } else { logc("Is this case could happen? Please raise an issue if you've met this message.") } } } } // append album fetch result return (fetchedAlbums, sortedAlbums, albumFetchResult) } func fetchAlbumsAsync(forAlbumType type: PHAssetCollectionType, complection: @escaping (AssetsAlbumEntry, AssetsFetchEntry) -> Void) { let fetchOption = pickerConfig.albumFetchOptions?[type] let albumFetchResult = PHAssetCollection.fetchAssetCollections(with: type, subtype: .any, options: fetchOption) var fetchedAlbums = [PHAssetCollection]() let indexSet = IndexSet(integersIn: 0..<albumFetchResult.count) let albums = albumFetchResult.objects(at: indexSet) for album in albums { // set default album if album.assetCollectionSubtype == self.pickerConfig.albumDefaultType { self.defaultAlbum = album } // save alternative album if album.assetCollectionSubtype == .smartAlbumUserLibrary { self.cameraRollAlbum = album } fetchedAlbums.append(album) } self.fetchAlbumAsync(albums: fetchedAlbums) { entry in // get sorted albums let sortedAlbums = self.sortedAlbums(fromAlbums: fetchedAlbums, filterBy: entry.fetchMap) // set default album if let defaultAlbum = self.defaultAlbum { logi("Default album is \"\(defaultAlbum.localizedTitle ?? "")\"") } else { if let defaultAlbum = self.defaultAlbum { logi("Set default album \"\(defaultAlbum.localizedTitle ?? "")\"") } else { if let cameraRollAlbum = self.cameraRollAlbum { self.defaultAlbum = cameraRollAlbum logw("Set default album with fallback default album \"\(cameraRollAlbum.localizedTitle ?? "")\"") } else { if let firstAlbum = sortedAlbums.first, type == .smartAlbum { self.defaultAlbum = firstAlbum loge("Set default album with first item \"\(firstAlbum.localizedTitle ?? "")\"") } else { logc("Is this case could happen? Please raise an issue if you've met this message.") } } } } let result = (fetchedAlbums, sortedAlbums, albumFetchResult) // append album fetch result complection(result, entry) } } @discardableResult func fetchAlbum(album: PHAssetCollection) -> PHFetchResult<PHAsset> { let fetchResult = PHAsset.fetchAssets(in: album, options: self.pickerConfig.assetFetchOptions?[album.assetCollectionType]) // cache fetch result self.fetchMap[album.localIdentifier] = fetchResult // cache album self.albumMap[album.localIdentifier] = album return fetchResult } func fetchAlbumAsync(albums: [PHAssetCollection], completion: @escaping (AssetsFetchEntry) -> Void) { self.albumLoadingQueue.async { var resuls: [PHFetchResult<PHAsset>] = [] var fetchMap = [String: PHFetchResult<PHAsset>]() var albumMap = [String: PHAssetCollection]() for album in albums { let fetchResult = PHAsset.fetchAssets(in: album, options: self.pickerConfig.assetFetchOptions?[album.assetCollectionType]) // cache fetch result fetchMap[album.localIdentifier] = fetchResult // cache album albumMap[album.localIdentifier] = album resuls.append(fetchResult) } completion((resuls, fetchMap, albumMap)) } } } // MARK: - IndexSet Utility extension IndexSet { func asArray(section: Int? = nil) -> [IndexPath] { var indexPaths = [IndexPath]() if count > 0 { for entry in enumerated() { indexPaths.append(IndexPath(row: entry.element, section: section ?? 0)) } } return indexPaths } }
mit
b09f6e48608004ba0110672f61254bb5
39.101925
219
0.581785
5.442668
false
false
false
false
josh-fuggle/New-York-City
JGFPhotoMetadataTests/JGFTGPSPhotoProperties.swift
1
1335
// // JGFTGPSPhotoProperties.swift // New York City // // Created by Joshua Fuglsang on 25/07/2015. // Copyright © 2015 josh-fuggle. All rights reserved. // import XCTest import JGFPhotoMetadata class JGFTGPSPhotoProperties: XCTestCase { var information: JGFPhotoInformation? override func setUp() { super.setUp() let imageURL = NSBundle(forClass: self.classForCoder).URLForResource("sallykins", withExtension: "jpg") if let information = JGFPhotoInformation(URL: imageURL) { self.information = information } else { XCTFail() } } func testThatItCorrectlyReturnsProperties() { if let info = self.information, GPSData = info.GPSData { let latitude = GPSData.latitude! XCTAssertNotNil(latitude) let longitude = GPSData.longitude! XCTAssertNotNil(longitude) let dateStamp = GPSData.dateStamp! XCTAssertNotNil(dateStamp) let timeStamp = GPSData.timeStamp! XCTAssertNotNil(timeStamp) let altitude = GPSData.altitude! XCTAssertNotNil(altitude) } else { XCTFail() } } }
mit
3bca15ad868027cd00730fcfa03db827
24.169811
111
0.565967
5.111111
false
true
false
false
thehung111/ViSearchSwiftSDK
Example/Example/Lib/SwiftHUEColorPicker.swift
3
9199
// // SwiftHUEColorPicker.swift // SwiftHUEColorPicker // // Created by Maxim Bilan on 5/6/15. // Copyright (c) 2015 Maxim Bilan. All rights reserved. // import UIKit public protocol SwiftHUEColorPickerDelegate : class { func valuePicked(_ color: UIColor, type: SwiftHUEColorPicker.PickerType) } open class SwiftHUEColorPicker: UIView { // MARK: - Type public enum PickerType: Int { case color case saturation case brightness case alpha } // MARK: - Direction public enum PickerDirection: Int { case horizontal case vertical } // MARK: - Constants let HUEMaxValue: CGFloat = 360 let PercentMaxValue: CGFloat = 100 // MARK: - Main public properties open weak var delegate: SwiftHUEColorPickerDelegate! open var type: PickerType = .color open var direction: PickerDirection = .horizontal open var currentColor: UIColor { get { return color } set(newCurrentColor) { color = newCurrentColor var hue: CGFloat = 0 var s: CGFloat = 0 var b: CGFloat = 0 var a: CGFloat = 0 if color.getHue(&hue, saturation: &s, brightness: &b, alpha: &a) { var needUpdate = false if hueValue != hue { needUpdate = true } hueValue = hue saturationValue = s brightnessValue = b alphaValue = a if needUpdate && hueValue > 0 && hueValue < 1 { update() setNeedsDisplay() } } } } // MARK: - Additional public properties open var labelFontColor: UIColor = UIColor.white open var labelBackgroundColor: UIColor = UIColor.black open var labelFont = UIFont(name: "Helvetica Neue", size: 12) open var cornerRadius: CGFloat = 10.0 // MARK: - Private properties fileprivate var color: UIColor = UIColor.clear fileprivate var currentSelectionY: CGFloat = 0.0 fileprivate var currentSelectionX: CGFloat = 0.0 fileprivate var hueImage: UIImage! fileprivate var hueValue: CGFloat = 0.0 fileprivate var saturationValue: CGFloat = 1.0 fileprivate var brightnessValue: CGFloat = 1.0 fileprivate var alphaValue: CGFloat = 1.0 // MARK: - Initialization required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.backgroundColor = UIColor.clear } override public init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor.clear } override open func layoutSubviews() { super.layoutSubviews() if !self.isHidden { update() } } // MARK: - Prerendering func generateHUEImage(_ size: CGSize) -> UIImage { let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) UIGraphicsBeginImageContextWithOptions(size, false, 0) UIBezierPath(roundedRect: rect, cornerRadius: cornerRadius).addClip() if direction == .horizontal { for x: Int in 0 ..< Int(size.width) { switch type { case .color: UIColor(hue: CGFloat(CGFloat(x) / size.width), saturation: 1.0, brightness: 1.0, alpha: 1.0).set() break case .saturation: UIColor(hue: hueValue, saturation: CGFloat(CGFloat(x) / size.width), brightness: 1.0, alpha: 1.0).set() break case .brightness: UIColor(hue: hueValue, saturation: 1.0, brightness: CGFloat(CGFloat(x) / size.width), alpha: 1.0).set() break case .alpha: UIColor(hue: hueValue, saturation: 1.0, brightness: 1.0, alpha: CGFloat(CGFloat(x) / size.width)).set() break } let temp = CGRect(x: CGFloat(x), y: 0, width: 1, height: size.height) UIRectFill(temp) } } else { for y: Int in 0 ..< Int(size.height) { switch type { case .color: UIColor(hue: CGFloat(CGFloat(y) / size.height), saturation: 1.0, brightness: 1.0, alpha: 1.0).set() break case .saturation: UIColor(hue: hueValue, saturation: CGFloat(CGFloat(y) / size.height), brightness: 1.0, alpha: 1.0).set() break case .brightness: UIColor(hue: hueValue, saturation: 1.0, brightness: CGFloat(CGFloat(y) / size.height), alpha: 1.0).set() break case .alpha: UIColor(hue: hueValue, saturation: 1.0, brightness: 1.0, alpha: CGFloat(CGFloat(y) / size.height)).set() break } let temp = CGRect(x: 0, y: CGFloat(y), width: size.width, height: 1) UIRectFill(temp) } } let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return image } // MARK: - Updating func update() { let offset = (direction == .horizontal ? self.frame.size.height : self.frame.size.width) let halfOffset = offset * 0.5 var size = self.frame.size if direction == .horizontal { size.width -= offset } else { size.height -= offset } var value: CGFloat = 0 switch type { case .color: value = hueValue break case .saturation: value = saturationValue break case .brightness: value = brightnessValue break case .alpha: value = alphaValue break } currentSelectionX = (value * size.width) + halfOffset currentSelectionY = (value * size.height) + halfOffset hueImage = generateHUEImage(size) } // MARK: - Drawing override open func draw(_ rect: CGRect) { super.draw(rect) let radius = (direction == .horizontal ? self.frame.size.height : self.frame.size.width) let halfRadius = radius * 0.5 var circleX = currentSelectionX - halfRadius var circleY = currentSelectionY - halfRadius if circleX >= rect.size.width - radius { circleX = rect.size.width - radius } else if circleX < 0 { circleX = 0 } if circleY >= rect.size.height - radius { circleY = rect.size.height - radius } else if circleY < 0 { circleY = 0 } let circleRect = (direction == .horizontal ? CGRect(x: circleX, y: 0, width: radius, height: radius) : CGRect(x: 0, y: circleY, width: radius, height: radius)) let circleColor = labelBackgroundColor var hueRect = rect if hueImage != nil { if direction == .horizontal { hueRect.size.width -= radius hueRect.origin.x += halfRadius } else { hueRect.size.height -= radius hueRect.origin.y += halfRadius } hueImage.draw(in: hueRect) } let context = UIGraphicsGetCurrentContext() circleColor.set() context!.addEllipse(in: circleRect) context!.setFillColor(circleColor.cgColor) context!.fillPath() context!.strokePath() let textParagraphStyle = NSMutableParagraphStyle() textParagraphStyle.alignment = .center let attributes: NSDictionary = [NSForegroundColorAttributeName: labelFontColor, NSParagraphStyleAttributeName: textParagraphStyle, NSFontAttributeName: labelFont!] var value: CGFloat = 0 switch type { case .color: value = hueValue break case .saturation: value = saturationValue break case .brightness: value = brightnessValue break case .alpha: value = alphaValue break } let textValue = Int(value * (type == .color ? HUEMaxValue : PercentMaxValue)) let text = String(textValue) as NSString var textRect = circleRect textRect.origin.y += (textRect.size.height - (labelFont?.lineHeight)!) * 0.5 text.draw(in: textRect, withAttributes: attributes as? [String : AnyObject]) } // MARK: - Touch events open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { let touch: AnyObject? = touches.first if let point = touch?.location(in: self) { handleTouch(point) } } open override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { let touch: AnyObject? = touches.first if let point = touch?.location(in: self) { handleTouch(point) } } open override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { let touch: AnyObject? = touches.first if let point = touch?.location(in: self) { handleTouch(point) } } open override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { } // MARK: - Touch handling func handleTouch(_ touchPoint: CGPoint) { currentSelectionX = touchPoint.x currentSelectionY = touchPoint.y let offset = (direction == .horizontal ? self.frame.size.height : self.frame.size.width) let halfOffset = offset * 0.5 if currentSelectionX < halfOffset { currentSelectionX = halfOffset } else if currentSelectionX >= self.frame.size.width - halfOffset { currentSelectionX = self.frame.size.width - halfOffset } if currentSelectionY < halfOffset { currentSelectionY = halfOffset } else if currentSelectionY >= self.frame.size.height - halfOffset { currentSelectionY = self.frame.size.height - halfOffset } let value = (direction == .horizontal ? CGFloat((currentSelectionX - halfOffset) / (self.frame.size.width - offset)) : CGFloat((currentSelectionY - halfOffset) / (self.frame.size.height - offset))) switch type { case .color: hueValue = value break case .saturation: saturationValue = value break case .brightness: brightnessValue = value break case .alpha: alphaValue = value break } color = UIColor(hue: hueValue, saturation: saturationValue, brightness: brightnessValue, alpha: alphaValue) if delegate != nil { delegate.valuePicked(color, type: type) } setNeedsDisplay() } }
mit
66bc17b409ccdbdd1c17e997a65e4be0
25.05949
161
0.674856
3.509729
false
false
false
false
tardieu/swift
test/Interpreter/SDK/objc_bridge.swift
17
1675
// Test Objective-C bridging for a non-Foundation type that is // otherwise unknown to the compiler. // RUN: rm -rf %t && mkdir -p %t // Build the Appliances module // RUN: %target-clang -fobjc-arc -I %S/../../Inputs/ObjCBridging %S/../../Inputs/ObjCBridging/Appliances.m -c -o %t/AppliancesObjC.o // RUN: %target-build-swift -emit-module -I %S/../../Inputs/ObjCBridging %S/../../Inputs/ObjCBridging/Appliances.swift -module-name Appliances -o %t // RUN: %target-build-swift -c -parse-as-library -I %S/../../Inputs/ObjCBridging %S/../../Inputs/ObjCBridging/Appliances.swift -module-name Appliances -o %t/AppliancesSwift.o // RUN: %target-build-swift -I %t -I %S/../../Inputs/ObjCBridging %s %t/AppliancesSwift.o %t/AppliancesObjC.o -o %t/a.out // RUN: %target-run %t/a.out | %FileCheck %s // REQUIRES: executable_test // REQUIRES: objc_interop import Foundation import Appliances let home = APPHouse() // CHECK: 50 print(home.fridge.temperature) // CHECK: 75 home.fridge.temperature += 25.0 print(home.fridge.temperature) var fridge: Refrigerator = home.fridge fridge.temperature += 25.0 // CHECK: 100 print(fridge) // CHECK: 75 print(home.fridge.temperature) home.fridge = fridge // CHECK: 100 print(home.fridge.temperature) // Check dynamic casting let obj: AnyObject = home.fridge as APPRefrigerator if let f2 = obj as? Refrigerator { // CHECK: Fridge has temperature 100 print("Fridge has temperature \(f2.temperature)") } // Check improper nullability auditing of `id` interfaces. `nil` should come // through as a nonnull `Any` without crashing. autoreleasepool { let broken = APPBroken() let thing = broken.thing } // CHECK: DONE print("DONE")
apache-2.0
a8221b32a24d2064cec58328144364e7
27.87931
174
0.711642
3.363454
false
false
false
false
LeoFangQ/CMSwiftUIKit
Source/CMUIKit/CMSubtitleButton.swift
1
1186
// // CMSubtitleButton.swift // YFStore // // Created by Fang on 2016/12/2. // Copyright © 2016年 yfdyf. All rights reserved. // import UIKit import SnapKit class CMSubtitleButton: UIButton { override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor.white addSubview(primaryLabel) addSubview(subtitleLabel) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() primaryLabel.snp.makeConstraints { (make) in make.top.left.right.equalToSuperview() make.height.equalTo(20) } subtitleLabel.snp.makeConstraints { (make) in make.top.equalTo(primaryLabel.snp.bottom) make.left.right.equalToSuperview() make.height.equalTo(20) } } lazy public var primaryLabel:UILabel = { let primaryTitle = UILabel() return primaryTitle }() lazy public var subtitleLabel:UILabel = { let primaryTitle = UILabel() return primaryTitle }() }
mit
82abc06c4f7315fffa5ab65a150c39e2
24.170213
59
0.613694
4.464151
false
false
false
false
almazrafi/Metatron
Tests/MetatronTests/ID3v1/ID3v1TagGenresTest.swift
1
17543
// // ID3v1TagGenresTest.swift // Metatron // // Copyright (c) 2016 Almaz Ibragimov // // 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 XCTest @testable import Metatron class ID3v1TagGenresTest: XCTestCase { // MARK: Instance Methods func test() { let textEncoding = ID3v1Latin1TextEncoding.regular let tag = ID3v1Tag() do { let value: [String] = [] tag.genres = value XCTAssert(tag.genres == []) XCTAssert(tag.genre == "") do { tag.version = ID3v1Version.v0 XCTAssert(tag.toData() == nil) } do { tag.version = ID3v1Version.v1 XCTAssert(tag.toData() == nil) } do { tag.version = ID3v1Version.vExt0 XCTAssert(tag.toData() == nil) } do { tag.version = ID3v1Version.vExt1 XCTAssert(tag.toData() == nil) } } do { let value = [""] tag.genres = value XCTAssert(tag.genres == []) XCTAssert(tag.genre == "") do { tag.version = ID3v1Version.v0 XCTAssert(tag.toData() == nil) } do { tag.version = ID3v1Version.v1 XCTAssert(tag.toData() == nil) } do { tag.version = ID3v1Version.vExt0 XCTAssert(tag.toData() == nil) } do { tag.version = ID3v1Version.vExt1 XCTAssert(tag.toData() == nil) } } do { let value = ["Abc 123"] tag.genres = value XCTAssert(tag.genres == [value[0]]) XCTAssert(tag.genre == value[0]) do { tag.version = ID3v1Version.v0 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v1Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genre == "") } do { tag.version = ID3v1Version.v1 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v1Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genre == "") } do { tag.version = ID3v1Version.vExt0 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v1Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genre == value[0].deencoded(with: textEncoding).prefix(30)) } do { tag.version = ID3v1Version.vExt1 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v1Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genre == value[0].deencoded(with: textEncoding).prefix(30)) } } do { let value = ["Абв 123"] tag.genres = value XCTAssert(tag.genres == [value[0]]) XCTAssert(tag.genre == value[0]) do { tag.version = ID3v1Version.v0 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v1Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genre == "") } do { tag.version = ID3v1Version.v1 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v1Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genre == "") } do { tag.version = ID3v1Version.vExt0 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v1Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genre == value[0].deencoded(with: textEncoding).prefix(30)) } do { tag.version = ID3v1Version.vExt1 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v1Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genre == value[0].deencoded(with: textEncoding).prefix(30)) } } do { let value = ["Abc 1", "Abc 2"] tag.genres = value XCTAssert(tag.genres == [value[0]]) XCTAssert(tag.genre == value[0]) do { tag.version = ID3v1Version.v0 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v1Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genre == "") } do { tag.version = ID3v1Version.v1 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v1Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genre == "") } do { tag.version = ID3v1Version.vExt0 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v1Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genre == value[0].deencoded(with: textEncoding).prefix(30)) } do { tag.version = ID3v1Version.vExt1 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v1Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genre == value[0].deencoded(with: textEncoding).prefix(30)) } } do { let value = ["", "Abc 2"] tag.genres = value XCTAssert(tag.genres == ["Abc 2"]) XCTAssert(tag.genre == "Abc 2") do { tag.version = ID3v1Version.v0 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v1Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genre == "") } do { tag.version = ID3v1Version.v1 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v1Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genre == "") } do { tag.version = ID3v1Version.vExt0 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v1Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genre == String("Abc 2").deencoded(with: textEncoding).prefix(30)) } do { tag.version = ID3v1Version.vExt1 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v1Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genre == String("Abc 2").deencoded(with: textEncoding).prefix(30)) } } do { let value = ["Abc 1", ""] tag.genres = value XCTAssert(tag.genres == ["Abc 1"]) XCTAssert(tag.genre == "Abc 1") do { tag.version = ID3v1Version.v0 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v1Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genre == "") } do { tag.version = ID3v1Version.v1 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v1Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genre == "") } do { tag.version = ID3v1Version.vExt0 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v1Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genre == String("Abc 1").deencoded(with: textEncoding).prefix(30)) } do { tag.version = ID3v1Version.vExt1 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v1Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genre == String("Abc 1").deencoded(with: textEncoding).prefix(30)) } } do { let value: [String] = ["", ""] tag.genres = value XCTAssert(tag.genres == []) XCTAssert(tag.genre == "") do { tag.version = ID3v1Version.v0 XCTAssert(tag.toData() == nil) } do { tag.version = ID3v1Version.v1 XCTAssert(tag.toData() == nil) } do { tag.version = ID3v1Version.vExt0 XCTAssert(tag.toData() == nil) } do { tag.version = ID3v1Version.vExt1 XCTAssert(tag.toData() == nil) } } do { let value = [Array<String>(repeating: "Abc", count: 123).joined(separator: "\n")] tag.genres = value XCTAssert(tag.genres == [value[0]]) XCTAssert(tag.genre == value[0]) do { tag.version = ID3v1Version.v0 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v1Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genre == "") } do { tag.version = ID3v1Version.v1 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v1Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genre == "") } do { tag.version = ID3v1Version.vExt0 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v1Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genre == value[0].deencoded(with: textEncoding).prefix(30)) } do { tag.version = ID3v1Version.vExt1 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v1Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genre == value[0].deencoded(with: textEncoding).prefix(30)) } } do { let value = Array<String>(repeating: "Abc", count: 123) tag.genres = value XCTAssert(tag.genres == [value[0]]) XCTAssert(tag.genre == value[0]) do { tag.version = ID3v1Version.v0 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v1Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genre == "") } do { tag.version = ID3v1Version.v1 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v1Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genre == "") } do { tag.version = ID3v1Version.vExt0 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v1Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genre == value[0].deencoded(with: textEncoding).prefix(30)) } do { tag.version = ID3v1Version.vExt1 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v1Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genre == value[0].deencoded(with: textEncoding).prefix(30)) } } do { let value = ["Classic Rock"] tag.genres = value XCTAssert(tag.genres == [value[0]]) XCTAssert(tag.genre == value[0]) do { tag.version = ID3v1Version.v0 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v1Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genre == value[0].deencoded(with: textEncoding).prefix(30)) } do { tag.version = ID3v1Version.v1 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v1Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genre == value[0].deencoded(with: textEncoding).prefix(30)) } do { tag.version = ID3v1Version.vExt0 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v1Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genre == value[0].deencoded(with: textEncoding).prefix(30)) } do { tag.version = ID3v1Version.vExt1 guard let data = tag.toData() else { return XCTFail() } guard let other = ID3v1Tag(fromData: data) else { return XCTFail() } XCTAssert(other.genre == value[0].deencoded(with: textEncoding).prefix(30)) } } do { tag.genre = "" XCTAssert(tag.genres == []) } do { tag.genre = "Abc 1, Abc 2" XCTAssert(tag.genres == ["Abc 1, Abc 2"]) } } }
mit
1ec8b6da746bcd443c3343a0f4d7f6d9
25.10119
98
0.432155
4.861419
false
false
false
false
lorentey/swift
stdlib/public/core/StringStorageBridge.swift
3
9473
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftShims #if _runtime(_ObjC) @_effects(readonly) private func _isNSString(_ str:AnyObject) -> UInt8 { return _swift_stdlib_isNSString(str) } internal let _cocoaASCIIEncoding:UInt = 1 /* NSASCIIStringEncoding */ internal let _cocoaUTF8Encoding:UInt = 4 /* NSUTF8StringEncoding */ // ObjC interfaces. extension _AbstractStringStorage { @inline(__always) @_effects(releasenone) internal func _getCharacters( _ buffer: UnsafeMutablePointer<UInt16>, _ aRange: _SwiftNSRange ) { _precondition(aRange.location >= 0 && aRange.length >= 0, "Range out of bounds") _precondition(aRange.location + aRange.length <= Int(count), "Range out of bounds") let range = Range( uncheckedBounds: (aRange.location, aRange.location+aRange.length)) let str = asString str._copyUTF16CodeUnits( into: UnsafeMutableBufferPointer(start: buffer, count: range.count), range: range) } @inline(__always) @_effects(releasenone) internal func _getCString( _ outputPtr: UnsafeMutablePointer<UInt8>, _ maxLength: Int, _ encoding: UInt ) -> Int8 { switch (encoding, isASCII) { case (_cocoaASCIIEncoding, true), (_cocoaUTF8Encoding, _): guard maxLength >= count + 1 else { return 0 } outputPtr.initialize(from: start, count: count) outputPtr[count] = 0 return 1 default: return _cocoaGetCStringTrampoline(self, outputPtr, maxLength, encoding) } } @inline(__always) @_effects(readonly) internal func _cString(encoding: UInt) -> UnsafePointer<UInt8>? { switch (encoding, isASCII) { case (_cocoaASCIIEncoding, true), (_cocoaUTF8Encoding, _): return start default: return _cocoaCStringUsingEncodingTrampoline(self, encoding) } } @_effects(readonly) internal func _nativeIsEqual<T:_AbstractStringStorage>( _ nativeOther: T ) -> Int8 { if count != nativeOther.count { return 0 } return (start == nativeOther.start || (memcmp(start, nativeOther.start, count) == 0)) ? 1 : 0 } @inline(__always) @_effects(readonly) internal func _isEqual(_ other: AnyObject?) -> Int8 { guard let other = other else { return 0 } if self === other { return 1 } // Handle the case where both strings were bridged from Swift. // We can't use String.== because it doesn't match NSString semantics. let knownOther = _KnownCocoaString(other) switch knownOther { case .storage: return _nativeIsEqual( _unsafeUncheckedDowncast(other, to: __StringStorage.self)) case .shared: return _nativeIsEqual( _unsafeUncheckedDowncast(other, to: __SharedStringStorage.self)) #if !(arch(i386) || arch(arm)) case .tagged: fallthrough #endif case .cocoa: // We're allowed to crash, but for compatibility reasons NSCFString allows // non-strings here. if _isNSString(other) != 1 { return 0 } // At this point we've proven that it is an NSString of some sort, but not // one of ours. defer { _fixLifetime(other) } let otherUTF16Length = _stdlib_binary_CFStringGetLength(other) // CFString will only give us ASCII bytes here, but that's fine. // We already handled non-ASCII UTF8 strings earlier since they're Swift. if let otherStart = _cocoaASCIIPointer(other) { //We know that otherUTF16Length is also its byte count at this point if count != otherUTF16Length { return 0 } return (start == otherStart || (memcmp(start, otherStart, count) == 0)) ? 1 : 0 } if UTF16Length != otherUTF16Length { return 0 } /* The abstract implementation of -isEqualToString: falls back to -compare: immediately, so when we run out of fast options to try, do the same. We can likely be more clever here if need be */ return _cocoaStringCompare(self, other) == 0 ? 1 : 0 } } } extension __StringStorage { @objc(length) final internal var UTF16Length: Int { @_effects(readonly) @inline(__always) get { return asString.utf16.count // UTF16View special-cases ASCII for us. } } @objc final internal var hash: UInt { @_effects(readonly) get { if isASCII { return _cocoaHashASCIIBytes(start, length: count) } return _cocoaHashString(self) } } @objc(characterAtIndex:) @_effects(readonly) final internal func character(at offset: Int) -> UInt16 { let str = asString return str.utf16[str._toUTF16Index(offset)] } @objc(getCharacters:range:) @_effects(releasenone) final internal func getCharacters( _ buffer: UnsafeMutablePointer<UInt16>, range aRange: _SwiftNSRange ) { _getCharacters(buffer, aRange) } @objc(_fastCStringContents:) @_effects(readonly) final internal func _fastCStringContents( _ requiresNulTermination: Int8 ) -> UnsafePointer<CChar>? { if isASCII { return start._asCChar } return nil } @objc(UTF8String) @_effects(readonly) final internal func _utf8String() -> UnsafePointer<UInt8>? { return start } @objc(cStringUsingEncoding:) @_effects(readonly) final internal func cString(encoding: UInt) -> UnsafePointer<UInt8>? { return _cString(encoding: encoding) } @objc(getCString:maxLength:encoding:) @_effects(releasenone) final internal func getCString( _ outputPtr: UnsafeMutablePointer<UInt8>, maxLength: Int, encoding: UInt ) -> Int8 { return _getCString(outputPtr, maxLength, encoding) } @objc final internal var fastestEncoding: UInt { @_effects(readonly) get { if isASCII { return _cocoaASCIIEncoding } return _cocoaUTF8Encoding } } @objc(isEqualToString:) @_effects(readonly) final internal func isEqualToString(to other: AnyObject?) -> Int8 { return _isEqual(other) } @objc(isEqual:) @_effects(readonly) final internal func isEqual(to other: AnyObject?) -> Int8 { return _isEqual(other) } @objc(copyWithZone:) final internal func copy(with zone: _SwiftNSZone?) -> AnyObject { // While __StringStorage instances aren't immutable in general, // mutations may only occur when instances are uniquely referenced. // Therefore, it is safe to return self here; any outstanding Objective-C // reference will make the instance non-unique. return self } } extension __SharedStringStorage { @objc(length) final internal var UTF16Length: Int { @_effects(readonly) get { return asString.utf16.count // UTF16View special-cases ASCII for us. } } @objc final internal var hash: UInt { @_effects(readonly) get { if isASCII { return _cocoaHashASCIIBytes(start, length: count) } return _cocoaHashString(self) } } @objc(characterAtIndex:) @_effects(readonly) final internal func character(at offset: Int) -> UInt16 { let str = asString return str.utf16[str._toUTF16Index(offset)] } @objc(getCharacters:range:) @_effects(releasenone) final internal func getCharacters( _ buffer: UnsafeMutablePointer<UInt16>, range aRange: _SwiftNSRange ) { _getCharacters(buffer, aRange) } @objc final internal var fastestEncoding: UInt { @_effects(readonly) get { if isASCII { return _cocoaASCIIEncoding } return _cocoaUTF8Encoding } } @objc(_fastCStringContents:) @_effects(readonly) final internal func _fastCStringContents( _ requiresNulTermination: Int8 ) -> UnsafePointer<CChar>? { if isASCII { return start._asCChar } return nil } @objc(UTF8String) @_effects(readonly) final internal func _utf8String() -> UnsafePointer<UInt8>? { return start } @objc(cStringUsingEncoding:) @_effects(readonly) final internal func cString(encoding: UInt) -> UnsafePointer<UInt8>? { return _cString(encoding: encoding) } @objc(getCString:maxLength:encoding:) @_effects(releasenone) final internal func getCString( _ outputPtr: UnsafeMutablePointer<UInt8>, maxLength: Int, encoding: UInt ) -> Int8 { return _getCString(outputPtr, maxLength, encoding) } @objc(isEqualToString:) @_effects(readonly) final internal func isEqualToString(to other: AnyObject?) -> Int8 { return _isEqual(other) } @objc(isEqual:) @_effects(readonly) final internal func isEqual(to other: AnyObject?) -> Int8 { return _isEqual(other) } @objc(copyWithZone:) final internal func copy(with zone: _SwiftNSZone?) -> AnyObject { // While __StringStorage instances aren't immutable in general, // mutations may only occur when instances are uniquely referenced. // Therefore, it is safe to return self here; any outstanding Objective-C // reference will make the instance non-unique. return self } } #endif // _runtime(_ObjC)
apache-2.0
df34cfa86db0bac684aa9ccf9aab5921
26.864706
80
0.653119
4.219599
false
false
false
false
rene-dohan/CS-IOS
Renetik/Renetik/Classes/Core/Extensions/UIKit/UICollectionView+CSExtension.swift
1
2000
// // Created by Rene on 2018-11-29. // import UIKit private let DEFAULT_CELL_ID = "emptyCellIdentifier" public extension UICollectionView { override open func construct() -> Self { super.construct() return background(.clear) } @discardableResult func construct(_ parent: UICollectionViewDelegate & UICollectionViewDataSource) -> Self { construct() delegates(parent) registerDefaultCell() reloadData() return self } @discardableResult func delegates(_ parent: UICollectionViewDelegate & UICollectionViewDataSource) -> Self { delegate = parent dataSource = parent return self } @discardableResult func register<CellType: UICollectionViewCell>(cell cellType: CellType.Type) -> Self { register(cellType, forCellWithReuseIdentifier: cellType.className()) return self } func dequeue<CellType: UICollectionViewCell>( cell cellType: CellType.Type, _ path: IndexPath, onCreate: ((CellType) -> Void)? = nil) -> CellType { var cell = dequeueReusableCell(withReuseIdentifier: cellType.className(), for: path) as! CellType if cell.contentView.isEmpty { // cell.contentView.matchParent() cell.construct() onCreate?(cell) } return cell } public func scrollToPage() { var currentCellOffset = contentOffset currentCellOffset.x += width / 2 var path = indexPathForItem(at: currentCellOffset) if path.isNil { currentCellOffset.x += 15 path = indexPathForItem(at: currentCellOffset) } if path != nil { logInfo("Scrolling to page \(path!)") scrollToItem(at: path!, at: .centeredHorizontally, animated: true) } } func registerDefaultCell() -> Self { register(UICollectionViewCell.self, forCellWithReuseIdentifier: DEFAULT_CELL_ID) return self } }
mit
e66ff637f004dd57ef9dd54c222e29a6
28.411765
113
0.6325
5.291005
false
false
false
false
diversario/bitfountain-ios-foundations
Swift/tuples.playground/Contents.swift
1
292
//: Playground - noun: a place where people can play import UIKit let toople = ("a", 3, false) toople.2 var poople = (cat: "Mr. Kitty", dog: "IDGAF") poople.cat poople.dog = "no" let shmoople = (doop: "foo", meep: "wat") var boople = ( ("one", 2), ("three", 4) ) boople.0.1
mit
1bfab207d4463b85d8031b5f070393c6
11.695652
52
0.585616
2.393443
false
false
false
false
pendowski/PopcornTimeIOS
Popcorn Time/UI/Table View Controllers/StreamToDevicesTableViewController.swift
1
5882
import UIKit import MediaPlayer import GoogleCast class StreamToDevicesTableViewController: UITableViewController, GCKDeviceScannerListener, ConnectDevicesProtocol { var airPlayDevices = [MPAVRouteProtocol]() var googleCastDevices = [GCKDevice]() var airPlayManager: AirPlayManager! var googleCastManager: GoogleCastManager! var onlyShowCastDevices: Bool = false var castMetadata: PCTCastMetaData? override func viewDidLoad() { if !onlyShowCastDevices { airPlayManager = AirPlayManager() airPlayManager.delegate = self } googleCastManager = GoogleCastManager() googleCastManager.delegate = self } @IBAction func mirroringChanged(sender: UISwitch) { let selectedRoute = airPlayDevices[tableView.indexPathForCell(sender.superview?.superview as! AirPlayTableViewCell)!.row] airPlayManager.mirrorChanged(sender, selectedRoute: selectedRoute) } func updateTableView(dataSource newDataSource: [AnyObject], updateType: TableViewUpdates, indexPaths: [NSIndexPath]?) { self.tableView.beginUpdates() if let dataSource = newDataSource as? [GCKDevice] { googleCastDevices = dataSource } else { airPlayDevices = newDataSource as! [MPAVRouteProtocol] } switch updateType { case .Insert: self.tableView.insertRowsAtIndexPaths(indexPaths!, withRowAnimation: .Middle) fallthrough case .Reload: if let visibleIndexPaths = self.tableView.indexPathsForVisibleRows { self.tableView.reloadRowsAtIndexPaths(visibleIndexPaths, withRowAnimation: .None) } case .Delete: self.tableView.deleteRowsAtIndexPaths(indexPaths!, withRowAnimation: .Middle) } self.tableView.endUpdates() } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { if airPlayDevices.isEmpty && googleCastDevices.isEmpty { let label = UILabel(frame: CGRectMake(0,0,100,100)) label.text = "No devices available" label.textColor = UIColor.lightGrayColor() label.numberOfLines = 0 label.textAlignment = .Center label.sizeToFit() tableView.backgroundView = label tableView.separatorStyle = .None } else { tableView.backgroundView = nil tableView.separatorStyle = .SingleLine } return 2 } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { switch section { case 0: return airPlayDevices.isEmpty ? nil : "AirPlay" case 1: return googleCastDevices.isEmpty ? nil : "Google Cast" default: return nil } } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return section == 0 ? airPlayDevices.count : googleCastDevices.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! AirPlayTableViewCell if indexPath.section == 0 { cell.picked = airPlayDevices[indexPath.row].isPicked!() if let mirroringRoute = airPlayDevices[indexPath.row].wirelessDisplayRoute?() where mirroringRoute.isPicked!() { cell.picked = true cell.mirrorSwitch?.setOn(true, animated: true) } else { cell.mirrorSwitch?.setOn(false, animated: false) } cell.titleLabel?.text = airPlayDevices[indexPath.row].routeName!() cell.airImageView?.image = airPlayManager.airPlayItemImage(indexPath.row) } else { cell.titleLabel?.text = googleCastDevices[indexPath.row].friendlyName cell.airImageView?.image = UIImage(named: "CastOff") if let session = GCKCastContext.sharedInstance().sessionManager.currentSession { cell.picked = googleCastDevices[indexPath.row] == session.device } else { cell.picked = false } } return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if indexPath.section == 0 { airPlayManager.didSelectRoute(airPlayDevices[indexPath.row]) } else { googleCastManager.didSelectRoute(googleCastDevices[indexPath.row], castMetadata: castMetadata) } } override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if section == 0 && airPlayDevices.isEmpty { return CGFloat.min } else if section == 1 && googleCastDevices.isEmpty { return CGFloat.min } return 18 } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if indexPath.section == 0 { if let _ = airPlayDevices[indexPath.row].wirelessDisplayRoute?() where airPlayDevices[indexPath.row].isPicked!() || airPlayDevices[indexPath.row].wirelessDisplayRoute!().isPicked!() { return 88 } } return 44 } func didConnectToDevice(deviceIsChromecast chromecast: Bool) { if chromecast && presentingViewController is PCTPlayerViewController { NSNotificationCenter.defaultCenter().postNotification(NSNotification(name: presentCastPlayerNotification, object: nil)) } else { dismissViewControllerAnimated(true, completion: nil) } } }
gpl-3.0
2a789658d8ecd08e2295b65e50f3e2d4
39.287671
195
0.649609
5.228444
false
false
false
false
gregomni/swift
test/IDE/complete_property_delegate_attribute.swift
2
2429
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=AFTER_PAREN | %FileCheck %s -check-prefix=AFTER_PAREN // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ARG_MyEnum_NODOT | %FileCheck %s -check-prefix=ARG_MyEnum_NODOT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ARG_MyEnum_DOT | %FileCheck %s -check-prefix=ARG_MyEnum_DOT // RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=ARG_MyEnum_NOBINDING | %FileCheck %s -check-prefix=ARG_MyEnum_NOBINDING enum MyEnum { case east, west } @propertyWrapper struct MyStruct { var wrappedValue: MyEnum init(wrappedValue: MyEnum) {} init(arg1: MyEnum, arg2: Int) {} } var globalInt: Int = 1 var globalMyEnum: MyEnum = .east struct TestStruct { @MyStruct(#^AFTER_PAREN^# var test1 // AFTER_PAREN: Begin completions, 2 items // AFTER_PAREN-DAG: Decl[Constructor]/CurrNominal/Flair[ArgLabels]: ['(']{#wrappedValue: MyEnum#}[')'][#MyStruct#]; name=wrappedValue: // AFTER_PAREN-DAG: Decl[Constructor]/CurrNominal/Flair[ArgLabels]: ['(']{#arg1: MyEnum#}, {#arg2: Int#}[')'][#MyStruct#]; name=arg1:arg2: // AFTER_PAREN: End completions @MyStruct(arg1: #^ARG_MyEnum_NODOT^# var test2 // ARG_MyEnum_NODOT: Begin completions // ARG_MyEnum_NODOT-DAG: Decl[Struct]/CurrModule: TestStruct[#TestStruct#]; name=TestStruct // ARG_MyEnum_NODOT-DAG: Decl[GlobalVar]/CurrModule/TypeRelation[Convertible]: globalMyEnum[#MyEnum#]; name=globalMyEnum // ARG_MyEnum_NODOT: End completions @MyStruct(arg1: .#^ARG_MyEnum_DOT^# var test3 // ARG_MyEnum_DOT: Begin completions, 3 items // ARG_MyEnum_DOT-DAG: Decl[EnumElement]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Convertible]: east[#MyEnum#]; name=east // ARG_MyEnum_DOT-DAG: Decl[EnumElement]/CurrNominal/Flair[ExprSpecific]/TypeRelation[Convertible]: west[#MyEnum#]; name=west // ARG_MyEnum_DOT-DAG: Decl[InstanceMethod]/CurrNominal/TypeRelation[Invalid]: hash({#(self): MyEnum#})[#(into: inout Hasher) -> Void#]; // ARG_MyEnum_DOT: End completions @MyStruct(arg1: MyEnum.#^ARG_MyEnum_NOBINDING^#) // ARG_MyEnum_NOBINDING: Begin completions // ARG_MyEnum_NOBINDING-DAG: Decl[EnumElement]/CurrNominal: east[#MyEnum#]; // ARG_MyEnum_NOBINDING-DAG: Decl[EnumElement]/CurrNominal: west[#MyEnum#]; // ARG_MyEnum_NOBINDING: End completions }
apache-2.0
d17a3185fa8ac65d6384954a7d3062c0
49.604167
162
0.728283
3.525399
false
true
false
false
azadibogolubov/InterestDestroyer
iOS Version/Interest Destroyer/Charts/Classes/Charts/PieRadarChartViewBase.swift
16
27248
// // PieRadarChartViewBase.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics import UIKit /// Base class of PieChartView and RadarChartView. public class PieRadarChartViewBase: ChartViewBase { /// holds the normalized version of the current rotation angle of the chart private var _rotationAngle = CGFloat(270.0) /// holds the raw version of the current rotation angle of the chart private var _rawRotationAngle = CGFloat(270.0) /// flag that indicates if rotation is enabled or not public var rotationEnabled = true private var _rotationWithTwoFingers = false private var _tapGestureRecognizer: UITapGestureRecognizer! private var _rotationGestureRecognizer: UIRotationGestureRecognizer! public override init(frame: CGRect) { super.init(frame: frame) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } deinit { stopDeceleration() } internal override func initialize() { super.initialize() _tapGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("tapGestureRecognized:")) _rotationGestureRecognizer = UIRotationGestureRecognizer(target: self, action: Selector("rotationGestureRecognized:")) self.addGestureRecognizer(_tapGestureRecognizer) self.addGestureRecognizer(_rotationGestureRecognizer) _rotationGestureRecognizer.enabled = rotationWithTwoFingers } internal override func calcMinMax() { _deltaX = CGFloat(_data.xVals.count - 1) } public override func notifyDataSetChanged() { if (_dataNotSet) { return } calcMinMax() if (_legend !== nil) { _legendRenderer.computeLegend(_data) } calculateOffsets() setNeedsDisplay() } internal override func calculateOffsets() { var legendLeft = CGFloat(0.0) var legendRight = CGFloat(0.0) var legendBottom = CGFloat(0.0) var legendTop = CGFloat(0.0) if (_legend != nil && _legend.enabled) { var fullLegendWidth = min(_legend.neededWidth, _viewPortHandler.chartWidth * _legend.maxSizePercent) fullLegendWidth += _legend.formSize + _legend.formToTextSpace if (_legend.position == .RightOfChartCenter) { // this is the space between the legend and the chart let spacing = CGFloat(13.0) legendRight = fullLegendWidth + spacing } else if (_legend.position == .RightOfChart) { // this is the space between the legend and the chart let spacing = CGFloat(8.0) let legendWidth = fullLegendWidth + spacing let legendHeight = _legend.neededHeight + _legend.textHeightMax let c = self.midPoint let bottomRight = CGPoint(x: self.bounds.width - legendWidth + 15.0, y: legendHeight + 15) let distLegend = distanceToCenter(x: bottomRight.x, y: bottomRight.y) let reference = getPosition(center: c, dist: self.radius, angle: angleForPoint(x: bottomRight.x, y: bottomRight.y)) let distReference = distanceToCenter(x: reference.x, y: reference.y) let minOffset = CGFloat(5.0) if (distLegend < distReference) { let diff = distReference - distLegend legendRight = minOffset + diff } if (bottomRight.y >= c.y && self.bounds.height - legendWidth > self.bounds.width) { legendRight = legendWidth } } else if (_legend.position == .LeftOfChartCenter) { // this is the space between the legend and the chart let spacing = CGFloat(13.0) legendLeft = fullLegendWidth + spacing } else if (_legend.position == .LeftOfChart) { // this is the space between the legend and the chart let spacing = CGFloat(8.0) let legendWidth = fullLegendWidth + spacing let legendHeight = _legend.neededHeight + _legend.textHeightMax let c = self.midPoint let bottomLeft = CGPoint(x: legendWidth - 15.0, y: legendHeight + 15) let distLegend = distanceToCenter(x: bottomLeft.x, y: bottomLeft.y) let reference = getPosition(center: c, dist: self.radius, angle: angleForPoint(x: bottomLeft.x, y: bottomLeft.y)) let distReference = distanceToCenter(x: reference.x, y: reference.y) let min = CGFloat(5.0) if (distLegend < distReference) { let diff = distReference - distLegend legendLeft = min + diff } if (bottomLeft.y >= c.y && self.bounds.height - legendWidth > self.bounds.width) { legendLeft = legendWidth } } else if (_legend.position == .BelowChartLeft || _legend.position == .BelowChartRight || _legend.position == .BelowChartCenter) { let yOffset = self.requiredBottomOffset; // It's possible that we do not need this offset anymore as it is available through the extraOffsets legendBottom = min(_legend.neededHeight + yOffset, _viewPortHandler.chartHeight * _legend.maxSizePercent) } legendLeft += self.requiredBaseOffset legendRight += self.requiredBaseOffset legendTop += self.requiredBaseOffset } legendTop += self.extraTopOffset legendRight += self.extraRightOffset legendBottom += self.extraBottomOffset legendLeft += self.extraLeftOffset var minOffset = CGFloat(10.0) if (self.isKindOfClass(RadarChartView)) { let x = (self as! RadarChartView).xAxis if x.isEnabled && x.drawLabelsEnabled { minOffset = max(10.0, x.labelWidth) } } let offsetLeft = max(minOffset, legendLeft) let offsetTop = max(minOffset, legendTop) let offsetRight = max(minOffset, legendRight) let offsetBottom = max(minOffset, max(self.requiredBaseOffset, legendBottom)) _viewPortHandler.restrainViewPort(offsetLeft: offsetLeft, offsetTop: offsetTop, offsetRight: offsetRight, offsetBottom: offsetBottom) } /// - returns: the angle relative to the chart center for the given point on the chart in degrees. /// The angle is always between 0 and 360°, 0° is NORTH, 90° is EAST, ... public func angleForPoint(x x: CGFloat, y: CGFloat) -> CGFloat { let c = centerOffsets let tx = Double(x - c.x) let ty = Double(y - c.y) let length = sqrt(tx * tx + ty * ty) let r = acos(ty / length) var angle = r * ChartUtils.Math.RAD2DEG if (x > c.x) { angle = 360.0 - angle } // add 90° because chart starts EAST angle = angle + 90.0 // neutralize overflow if (angle > 360.0) { angle = angle - 360.0 } return CGFloat(angle) } /// Calculates the position around a center point, depending on the distance /// from the center, and the angle of the position around the center. internal func getPosition(center center: CGPoint, dist: CGFloat, angle: CGFloat) -> CGPoint { return CGPoint(x: center.x + dist * cos(angle * ChartUtils.Math.FDEG2RAD), y: center.y + dist * sin(angle * ChartUtils.Math.FDEG2RAD)) } /// - returns: the distance of a certain point on the chart to the center of the chart. public func distanceToCenter(x x: CGFloat, y: CGFloat) -> CGFloat { let c = self.centerOffsets var dist = CGFloat(0.0) var xDist = CGFloat(0.0) var yDist = CGFloat(0.0) if (x > c.x) { xDist = x - c.x } else { xDist = c.x - x } if (y > c.y) { yDist = y - c.y } else { yDist = c.y - y } // pythagoras dist = sqrt(pow(xDist, 2.0) + pow(yDist, 2.0)) return dist } /// - returns: the xIndex for the given angle around the center of the chart. /// -1 if not found / outofbounds. public func indexForAngle(angle: CGFloat) -> Int { fatalError("indexForAngle() cannot be called on PieRadarChartViewBase") } /// current rotation angle of the pie chart /// /// **default**: 270 --> top (NORTH) /// - returns: will always return a normalized value, which will be between 0.0 < 360.0 public var rotationAngle: CGFloat { get { return _rotationAngle } set { _rawRotationAngle = newValue _rotationAngle = ChartUtils.normalizedAngleFromAngle(newValue) setNeedsDisplay() } } /// gets the raw version of the current rotation angle of the pie chart the returned value could be any value, negative or positive, outside of the 360 degrees. /// this is used when working with rotation direction, mainly by gestures and animations. public var rawRotationAngle: CGFloat { return _rawRotationAngle } /// - returns: the diameter of the pie- or radar-chart public var diameter: CGFloat { let content = _viewPortHandler.contentRect return min(content.width, content.height) } /// - returns: the radius of the chart in pixels. public var radius: CGFloat { fatalError("radius cannot be called on PieRadarChartViewBase") } /// - returns: the required bottom offset for the chart. internal var requiredBottomOffset: CGFloat { fatalError("requiredBottomOffset cannot be called on PieRadarChartViewBase") } /// - returns: the base offset needed for the chart without calculating the /// legend size. internal var requiredBaseOffset: CGFloat { fatalError("requiredBaseOffset cannot be called on PieRadarChartViewBase") } public override var chartXMax: Double { return 0.0 } public override var chartXMin: Double { getSelectionDetailsAtIndex(1); return 0.0 } /// The SelectionDetail objects give information about the value at the selected index and the DataSet it belongs to. /// - returns: an array of SelectionDetail objects for the given x-index. public func getSelectionDetailsAtIndex(xIndex: Int) -> [ChartSelectionDetail] { var vals = [ChartSelectionDetail]() for (var i = 0; i < _data.dataSetCount; i++) { let dataSet = _data.getDataSetByIndex(i) if (dataSet === nil || !dataSet.isHighlightEnabled) { continue } // extract all y-values from all DataSets at the given x-index let yVal = dataSet!.yValForXIndex(xIndex) if (yVal.isNaN) { continue } vals.append(ChartSelectionDetail(value: yVal, dataSetIndex: i, dataSet: dataSet!)) } return vals } public var isRotationEnabled: Bool { return rotationEnabled; } /// flag that indicates if rotation is done with two fingers or one. /// when the chart is inside a scrollview, you need a two-finger rotation because a one-finger rotation eats up all touch events. /// /// **default**: false public var rotationWithTwoFingers: Bool { get { return _rotationWithTwoFingers } set { _rotationWithTwoFingers = newValue _rotationGestureRecognizer.enabled = _rotationWithTwoFingers } } /// flag that indicates if rotation is done with two fingers or one. /// when the chart is inside a scrollview, you need a two-finger rotation because a one-finger rotation eats up all touch events. /// /// **default**: false public var isRotationWithTwoFingers: Bool { return _rotationWithTwoFingers } // MARK: - Animation private var _spinAnimator: ChartAnimator! /// Applys a spin animation to the Chart. public func spin(duration duration: NSTimeInterval, fromAngle: CGFloat, toAngle: CGFloat, easing: ChartEasingFunctionBlock?) { if (_spinAnimator != nil) { _spinAnimator.stop() } _spinAnimator = ChartAnimator() _spinAnimator.updateBlock = { self.rotationAngle = (toAngle - fromAngle) * self._spinAnimator.phaseX + fromAngle } _spinAnimator.stopBlock = { self._spinAnimator = nil; } _spinAnimator.animate(xAxisDuration: duration, easing: easing) } public func spin(duration duration: NSTimeInterval, fromAngle: CGFloat, toAngle: CGFloat, easingOption: ChartEasingOption) { spin(duration: duration, fromAngle: fromAngle, toAngle: toAngle, easing: easingFunctionFromOption(easingOption)) } public func spin(duration duration: NSTimeInterval, fromAngle: CGFloat, toAngle: CGFloat) { spin(duration: duration, fromAngle: fromAngle, toAngle: toAngle, easing: nil) } public func stopSpinAnimation() { if (_spinAnimator != nil) { _spinAnimator.stop() } } // MARK: - Gestures private var _touchStartPoint: CGPoint! private var _isRotating = false private var _defaultTouchEventsWereEnabled = false private var _startAngle = CGFloat(0.0) private struct AngularVelocitySample { var time: NSTimeInterval var angle: CGFloat } private var _velocitySamples = [AngularVelocitySample]() private var _decelerationLastTime: NSTimeInterval = 0.0 private var _decelerationDisplayLink: CADisplayLink! private var _decelerationAngularVelocity: CGFloat = 0.0 public override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { // if rotation by touch is enabled if (rotationEnabled) { stopDeceleration() if (!rotationWithTwoFingers) { let touch = touches.first as UITouch! let touchLocation = touch.locationInView(self) self.resetVelocity() if (rotationEnabled) { self.sampleVelocity(touchLocation: touchLocation) } self.setGestureStartAngle(x: touchLocation.x, y: touchLocation.y) _touchStartPoint = touchLocation } } if (!_isRotating) { super.touchesBegan(touches, withEvent: event) } } public override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { if (rotationEnabled && !rotationWithTwoFingers) { let touch = touches.first as UITouch! let touchLocation = touch.locationInView(self) if (isDragDecelerationEnabled) { sampleVelocity(touchLocation: touchLocation) } if (!_isRotating && distance(eventX: touchLocation.x, startX: _touchStartPoint.x, eventY: touchLocation.y, startY: _touchStartPoint.y) > CGFloat(8.0)) { _isRotating = true } else { self.updateGestureRotation(x: touchLocation.x, y: touchLocation.y) setNeedsDisplay() } } if (!_isRotating) { super.touchesMoved(touches, withEvent: event) } } public override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { if (!_isRotating) { super.touchesEnded(touches, withEvent: event) } if (rotationEnabled && !rotationWithTwoFingers) { let touch = touches.first as UITouch! let touchLocation = touch.locationInView(self) if (isDragDecelerationEnabled) { stopDeceleration() sampleVelocity(touchLocation: touchLocation) _decelerationAngularVelocity = calculateVelocity() if (_decelerationAngularVelocity != 0.0) { _decelerationLastTime = CACurrentMediaTime() _decelerationDisplayLink = CADisplayLink(target: self, selector: Selector("decelerationLoop")) _decelerationDisplayLink.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes) } } } if (_isRotating) { _isRotating = false } } public override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) { super.touchesCancelled(touches, withEvent: event) if (_isRotating) { _isRotating = false } } private func resetVelocity() { _velocitySamples.removeAll(keepCapacity: false) } private func sampleVelocity(touchLocation touchLocation: CGPoint) { let currentTime = CACurrentMediaTime() _velocitySamples.append(AngularVelocitySample(time: currentTime, angle: angleForPoint(x: touchLocation.x, y: touchLocation.y))) // Remove samples older than our sample time - 1 seconds for (var i = 0, count = _velocitySamples.count; i < count - 2; i++) { if (currentTime - _velocitySamples[i].time > 1.0) { _velocitySamples.removeAtIndex(0) i-- count-- } else { break } } } private func calculateVelocity() -> CGFloat { if (_velocitySamples.isEmpty) { return 0.0 } var firstSample = _velocitySamples[0] var lastSample = _velocitySamples[_velocitySamples.count - 1] // Look for a sample that's closest to the latest sample, but not the same, so we can deduce the direction var beforeLastSample = firstSample for (var i = _velocitySamples.count - 1; i >= 0; i--) { beforeLastSample = _velocitySamples[i] if (beforeLastSample.angle != lastSample.angle) { break } } // Calculate the sampling time var timeDelta = lastSample.time - firstSample.time if (timeDelta == 0.0) { timeDelta = 0.1 } // Calculate clockwise/ccw by choosing two values that should be closest to each other, // so if the angles are two far from each other we know they are inverted "for sure" var clockwise = lastSample.angle >= beforeLastSample.angle if (abs(lastSample.angle - beforeLastSample.angle) > 270.0) { clockwise = !clockwise } // Now if the "gesture" is over a too big of an angle - then we know the angles are inverted, and we need to move them closer to each other from both sides of the 360.0 wrapping point if (lastSample.angle - firstSample.angle > 180.0) { firstSample.angle += 360.0 } else if (firstSample.angle - lastSample.angle > 180.0) { lastSample.angle += 360.0 } // The velocity var velocity = abs((lastSample.angle - firstSample.angle) / CGFloat(timeDelta)) // Direction? if (!clockwise) { velocity = -velocity } return velocity } /// sets the starting angle of the rotation, this is only used by the touch listener, x and y is the touch position private func setGestureStartAngle(x x: CGFloat, y: CGFloat) { _startAngle = angleForPoint(x: x, y: y) // take the current angle into consideration when starting a new drag _startAngle -= _rotationAngle } /// updates the view rotation depending on the given touch position, also takes the starting angle into consideration private func updateGestureRotation(x x: CGFloat, y: CGFloat) { self.rotationAngle = angleForPoint(x: x, y: y) - _startAngle } public func stopDeceleration() { if (_decelerationDisplayLink !== nil) { _decelerationDisplayLink.removeFromRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes) _decelerationDisplayLink = nil } } @objc private func decelerationLoop() { let currentTime = CACurrentMediaTime() _decelerationAngularVelocity *= self.dragDecelerationFrictionCoef let timeInterval = CGFloat(currentTime - _decelerationLastTime) self.rotationAngle += _decelerationAngularVelocity * timeInterval _decelerationLastTime = currentTime if(abs(_decelerationAngularVelocity) < 0.001) { stopDeceleration() } } /// - returns: the distance between two points private func distance(eventX eventX: CGFloat, startX: CGFloat, eventY: CGFloat, startY: CGFloat) -> CGFloat { let dx = eventX - startX let dy = eventY - startY return sqrt(dx * dx + dy * dy) } /// - returns: the distance between two points private func distance(from from: CGPoint, to: CGPoint) -> CGFloat { let dx = from.x - to.x let dy = from.y - to.y return sqrt(dx * dx + dy * dy) } /// reference to the last highlighted object private var _lastHighlight: ChartHighlight! @objc private func tapGestureRecognized(recognizer: UITapGestureRecognizer) { if (recognizer.state == UIGestureRecognizerState.Ended) { let location = recognizer.locationInView(self) let distance = distanceToCenter(x: location.x, y: location.y) // check if a slice was touched if (distance > self.radius) { // if no slice was touched, highlight nothing self.highlightValues(nil) _lastHighlight = nil _lastHighlight = nil } else { var angle = angleForPoint(x: location.x, y: location.y) if (self.isKindOfClass(PieChartView)) { angle /= _animator.phaseY } let index = indexForAngle(angle) // check if the index could be found if (index < 0) { self.highlightValues(nil) _lastHighlight = nil } else { let valsAtIndex = getSelectionDetailsAtIndex(index) var dataSetIndex = 0 // get the dataset that is closest to the selection (PieChart only has one DataSet) if (self.isKindOfClass(RadarChartView)) { dataSetIndex = ChartUtils.closestDataSetIndex(valsAtIndex, value: Double(distance / (self as! RadarChartView).factor), axis: nil) } if (dataSetIndex < 0) { self.highlightValues(nil) _lastHighlight = nil } else { let h = ChartHighlight(xIndex: index, dataSetIndex: dataSetIndex) if (_lastHighlight !== nil && h == _lastHighlight) { self.highlightValue(highlight: nil, callDelegate: true) _lastHighlight = nil } else { self.highlightValue(highlight: h, callDelegate: true) _lastHighlight = h } } } } } } @objc private func rotationGestureRecognized(recognizer: UIRotationGestureRecognizer) { if (recognizer.state == UIGestureRecognizerState.Began) { stopDeceleration() _startAngle = self.rawRotationAngle } if (recognizer.state == UIGestureRecognizerState.Began || recognizer.state == UIGestureRecognizerState.Changed) { let angle = ChartUtils.Math.FRAD2DEG * recognizer.rotation self.rotationAngle = _startAngle + angle setNeedsDisplay() } else if (recognizer.state == UIGestureRecognizerState.Ended) { let angle = ChartUtils.Math.FRAD2DEG * recognizer.rotation self.rotationAngle = _startAngle + angle setNeedsDisplay() if (isDragDecelerationEnabled) { stopDeceleration() _decelerationAngularVelocity = ChartUtils.Math.FRAD2DEG * recognizer.velocity if (_decelerationAngularVelocity != 0.0) { _decelerationLastTime = CACurrentMediaTime() _decelerationDisplayLink = CADisplayLink(target: self, selector: Selector("decelerationLoop")) _decelerationDisplayLink.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes) } } } } }
apache-2.0
914ef62d47c64af56e0123725e83d724
31.944377
191
0.555755
5.554332
false
false
false
false
StreamOneNL/AppleTV-Demo
AppleTV-Demo/ItemCell.swift
1
2527
// // ItemCell.swift // AppleTV-Demo // // Created by Nicky Gerritsen on 10-01-16. // Copyright © 2016 StreamOne. All rights reserved. // import UIKit class ItemCell: UICollectionViewCell { @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var dateLabel: UILabel! @IBOutlet weak var durationLabel: UILabel! var representedItem: Item? var normalLabelConstraint: NSLayoutConstraint! var focussedLabelConstraint: NSLayoutConstraint! // MARK: Initialization override func awakeFromNib() { super.awakeFromNib() dateLabel.alpha = 0.0 durationLabel.alpha = 0.0 self.focussedLabelConstraint = imageView.focusedFrameGuide.bottomAnchor.constraintEqualToAnchor(titleLabel.topAnchor, constant: -20) self.focussedLabelConstraint.active = false self.normalLabelConstraint = imageView.bottomAnchor.constraintEqualToAnchor(titleLabel.topAnchor, constant: -20) self.normalLabelConstraint.active = true } // MARK: UICollectionReusableView override func prepareForReuse() { super.prepareForReuse() // Reset the label's alpha value so it's initially hidden. dateLabel.alpha = 0.0 durationLabel.alpha = 0.0 self.focussedLabelConstraint.active = false self.normalLabelConstraint.active = true } // MARK: UIFocusEnvironment override func didUpdateFocusInContext(context: UIFocusUpdateContext, withAnimationCoordinator coordinator: UIFocusAnimationCoordinator) { /* Update the label's alpha value using the `UIFocusAnimationCoordinator`. This will ensure all animations run alongside each other when the focus changes. */ coordinator.addCoordinatedAnimations({ [unowned self] in if self.focused { self.dateLabel.alpha = 1.0 self.durationLabel.alpha = 1.0 self.titleLabel.textColor = UIColor.whiteColor() self.normalLabelConstraint.active = false self.focussedLabelConstraint.active = true } else { self.dateLabel.alpha = 0.0 self.durationLabel.alpha = 0.0 self.titleLabel.textColor = UIColor.blackColor() self.focussedLabelConstraint.active = false self.normalLabelConstraint.active = true } self.layoutIfNeeded() }, completion: nil) } }
mit
84ad26b890f9376e37f2426e2eb0b704
32.236842
141
0.662312
5.197531
false
false
false
false
benlangmuir/swift
test/DebugInfo/basic.swift
13
4912
// A (no longer) basic test for debug info. // -------------------------------------------------------------------- // Verify that we don't emit any debug info by default. // RUN: %target-swift-frontend %s -emit-ir -o - \ // RUN: | %FileCheck %s --check-prefix NDEBUG // NDEBUG: source_filename // NDEBUG-NOT: !dbg // NDEBUG-NOT: DICompileUnit // -------------------------------------------------------------------- // Verify that we don't emit any debug info with -gnone. // RUN: %target-swift-frontend %s -emit-ir -gnone -o - \ // RUN: | %FileCheck %s --check-prefix NDEBUG // -------------------------------------------------------------------- // Verify that we don't emit any type info with -gline-tables-only. // RUN: %target-swift-frontend %s -emit-ir -gline-tables-only -o - \ // RUN: | %FileCheck %s --check-prefix CHECK-LINETABLES // CHECK: !dbg // CHECK-LINETABLES-NOT: DI{{.*}}Variable // CHECK-LINETABLES-NOT: DW_TAG_structure_type // CHECK-LINETABLES-NOT: DIBasicType // -------------------------------------------------------------------- // Now check that we do generate line+scope info with -g. // RUN: %target-swift-frontend %/s -emit-ir -g -o - \ // RUN: | %FileCheck %s --check-prefixes CHECK,DWARF-CHECK // -------------------------------------------------------------------- // Currently -gdwarf-types should give the same results as -g. // RUN: %target-swift-frontend %/s -emit-ir -gdwarf-types -o - \ // RUN: | %FileCheck %s --check-prefixes CHECK,DWARF-CHECK // -------------------------------------------------------------------- // Verify that -g -debug-info-format=dwarf gives the same results as -g. // RUN: %target-swift-frontend %/s -emit-ir -g -debug-info-format=dwarf -o - \ // RUN: | %FileCheck %s --check-prefixes CHECK,DWARF-CHECK // -------------------------------------------------------------------- // RUN: %target-swift-frontend %/s -emit-ir -g -debug-info-format=codeview -o - \ // RUN: | %FileCheck %s --check-prefixes CHECK,CV-CHECK // -------------------------------------------------------------------- // // CHECK: foo // CHECK-DAG: ret{{.*}}, !dbg ![[RET:[0-9]+]] // CHECK-DAG: ![[FOO:[0-9]+]] = distinct !DISubprogram(name: "foo",{{.*}} line: [[@LINE+2]],{{.*}} type: ![[FOOTYPE:[0-9]+]] public func foo(_ a: Int64, _ b: Int64) -> Int64 { var a = a var b = b // CHECK-DAG: ![[ALOC:.*]] = !DILocation(line: [[@LINE-3]],{{.*}} scope: ![[FOO]]) // Check that a is the first and b is the second argument. // CHECK-DAG: store i64 %0, i64* [[AADDR:.*]], align // CHECK-DAG: store i64 %1, i64* [[BADDR:.*]], align // CHECK-DAG: [[AVAL:%.*]] = getelementptr inbounds {{.*}}, [[AMEM:.*]], i32 0, i32 0 // CHECK-DAG: [[BVAL:%.*]] = getelementptr inbounds {{.*}}, [[BMEM:.*]], i32 0, i32 0 // CHECK-DAG: call void @llvm.dbg.declare(metadata i64* [[AADDR]], metadata ![[AARG:.*]], metadata !DIExpression()), !dbg ![[ALOC]] // CHECK-DAG: call void @llvm.dbg.declare(metadata i64* [[BADDR]], metadata ![[BARG:.*]], metadata !DIExpression()) // CHECK-DAG: ![[AARG]] = !DILocalVariable(name: "a", arg: 1 // CHECK-DAG: ![[BARG]] = !DILocalVariable(name: "b", arg: 2 if b != 0 { // CHECK-DAG: !DILexicalBlock({{.*}} line: [[@LINE-1]] // Transparent inlined multiply: // CHECK-DAG: smul{{.*}}, !dbg ![[MUL:[0-9]+]] // CHECK-DAG: [[MUL]] = !DILocation(line: [[@LINE+1]], return a*b } else { // CHECK-DAG: ![[PARENT:[0-9]+]] = distinct !DILexicalBlock({{.*}} line: [[@LINE-1]] var c: Int64 = 42 // CHECK-DAG: ![[CONDITION:[0-9]+]] = distinct !DILexicalBlock(scope: ![[PARENT]], {{.*}}, line: [[@LINE+1]] if a == 0 { // CHECK-DAG: !DILexicalBlock(scope: ![[CONDITION]], {{.*}}, line: [[@LINE-1]] // What about a nested scope? return 0 } return c } } // CHECK-DAG: ![[MAINFILE:[0-9]+]] = !DIFile(filename: "{{.*}}DebugInfo/basic.swift", directory: "{{.*}}") // CHECK-DAG: !DICompileUnit(language: DW_LANG_Swift, file: ![[MAINFILE]],{{.*}} producer: "{{.*}}Swift version{{.*}},{{.*}} // CHECK-DAG: !DISubprogram(name: "main", {{.*}}file: ![[MAINFILE]], // Function type for foo. // CHECK-DAG: ![[FOOTYPE]] = !DISubroutineType(types: ![[PARAMTYPES:[0-9]+]]) // CHECK-DAG: ![[INT64:.*]] = !DICompositeType(tag: DW_TAG_structure_type, name: "Int64", {{.*}}, identifier: "$ss5Int64VD") // CHECK-DAG: ![[PARAMTYPES]] = !{![[INT64]], ![[INT64]], ![[INT64]]} // Import of the main module with the implicit name. // CHECK-DAG: !DIImportedEntity(tag: DW_TAG_imported_module, scope: ![[MAINFILE]], entity: ![[MAINMODULE:[0-9]+]], file: ![[MAINFILE]]) // CHECK-DAG: ![[MAINMODULE]] = !DIModule({{.*}}, name: "basic" // DWARF Version // DWARF-CHECK-DAG: i32 7, !"Dwarf Version", i32 4} // CV-CHECK-DAG: i32 2, !"CodeView", i32 1} // Debug Info Version // CHECK-DAG: i32 2, !"Debug Info Version", i32
apache-2.0
4b41a1112599e0530fb59b9909cff0f4
52.978022
136
0.520969
3.464034
false
false
false
false
MuYangZhe/Swift30Projects
Project 11 - Animations/Animations/AppDelegate.swift
1
4586
// // AppDelegate.swift // Animations // // Created by 牧易 on 17/7/23. // Copyright © 2017年 MuYi. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded 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. */ let container = NSPersistentContainer(name: "Animations") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() 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. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() 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 fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
mit
7de1767b2682173ad006dbde3c141763
48.236559
285
0.685302
5.840561
false
false
false
false
Vienta/kuafu
kuafu/kuafu/src/View/KFEventCell.swift
1
5036
// // KFEventCell.swift // kuafu // // Created by Vienta on 15/6/23. // Copyright (c) 2015年 www.vienta.me. All rights reserved. // import UIKit import MGSwipeTableCell class KFEventCell: MGSwipeTableCell{ @IBOutlet weak var lblMark: UILabel! @IBOutlet weak var lblTitle: UILabel! @IBOutlet weak var lblContent: UILabel! @IBOutlet weak var lblDueTime: UILabel! @IBOutlet weak var igvDue: UIImageView! override func awakeFromNib() { super.awakeFromNib() // Initialization code KFUtil.drawCircleView(self.lblMark, borderColor: KF_THEME_COLOR, borderWidth: 1.0) } func configData(eventDO: KFEventDO) { if eventDO.title != nil && eventDO.title.isEmpty == false { self.lblTitle.text = eventDO.title } else { self.lblTitle.text = "" } //TODO:2015年06月25日23:13:24 脑袋不清楚时候写的 后面需要优化 if eventDO.starttime == 0 && eventDO.endtime == 0 { self.lblDueTime.text = "" self.igvDue.image = nil } else if eventDO.starttime != 0 && eventDO.endtime == 0 { if eventDO.starttime.doubleValue > NSDate().timeIntervalSince1970 { self.igvDue.image = UIImage(named: "btn_datealert")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate) self.igvDue.tintColor = KF_THEME_COLOR } else { self.igvDue.image = UIImage(named: "btn_datealert")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate) self.igvDue.tintColor = UIColor.redColor() } var tmpDate: NSDate = KFUtil.dateFromTimeStamp(eventDO.starttime.doubleValue) as NSDate self.lblDueTime.text = self.todayString(tmpDate) } else if eventDO.starttime == 0 && eventDO.endtime != 0 { if eventDO.endtime.doubleValue > NSDate().timeIntervalSince1970 { self.igvDue.image = UIImage(named: "btn_dateto")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate) self.igvDue.tintColor = KF_THEME_COLOR } else { self.igvDue.image = UIImage(named: "btn_dateto")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate) self.igvDue.tintColor = UIColor.redColor() } var tmpDate: NSDate = KFUtil.dateFromTimeStamp(eventDO.endtime.doubleValue) as NSDate self.lblDueTime.text = self.todayString(tmpDate) } else if eventDO.starttime != 0 && eventDO.endtime != 0 { println(eventDO.starttime) if NSDate().timeIntervalSince1970 < eventDO.starttime.doubleValue { self.igvDue.image = UIImage(named: "btn_datealert")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate) self.igvDue.tintColor = KF_THEME_COLOR var tmpDate: NSDate = KFUtil.dateFromTimeStamp(eventDO.starttime.doubleValue) as NSDate self.lblDueTime.text = self.todayString(tmpDate) } else if NSDate().timeIntervalSince1970 > eventDO.starttime.doubleValue && NSDate().timeIntervalSince1970 < eventDO.endtime.doubleValue { self.igvDue.image = UIImage(named: "btn_dateto")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate) self.igvDue.tintColor = KF_THEME_COLOR var tmpDate: NSDate = KFUtil.dateFromTimeStamp(eventDO.endtime.doubleValue) self.lblDueTime.text = self.todayString(tmpDate) } else { self.igvDue.image = UIImage(named: "btn_dateto")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate) self.igvDue.tintColor = UIColor.redColor() var tmpDate: NSDate = KFUtil.dateFromTimeStamp(eventDO.endtime.doubleValue) self.lblDueTime.text = self.todayString(tmpDate) } } self.lblContent.text = eventDO.content var markString: String! if self.lblTitle.text?.isEmpty == false { markString = self.lblTitle.text } else { markString = self.lblContent.text } var subString: String = markString.substringToIndex(advance(markString.startIndex, 1)) self.lblMark.text = subString } func todayString(date: NSDate) -> String { var tmpDate: NSDate = date var isToday: Bool = NSCalendar.currentCalendar().isDateInToday(tmpDate) var dateString: String! if isToday == true { dateString = KFUtil.getTodayShortDate(tmpDate) } else { dateString = KFUtil.getShortDate(tmpDate) } return dateString } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
mit
beb40bbcfd1ea8b7e4acc0b68023dcc2
41.355932
150
0.621248
4.403524
false
false
false
false
frootloops/swift
stdlib/public/core/ObjCMirrors.swift
3
3599
//===--- ObjCMirrors.swift ------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftShims #if _runtime(_ObjC) @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) @_silgen_name("swift_ObjCMirror_count") internal func _getObjCCount(_: _MagicMirrorData) -> Int @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) @_silgen_name("swift_ObjCMirror_subscript") internal func _getObjCChild<T>(_: Int, _: _MagicMirrorData) -> (T, _Mirror) @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal func _getObjCSummary(_ data: _MagicMirrorData) -> String { let theDescription = _swift_stdlib_objcDebugDescription(data._loadValue(ofType: AnyObject.self)) as AnyObject return _cocoaStringToSwiftString_NonASCII(theDescription) } public // SPI(runtime) struct _ObjCMirror : _Mirror { @_versioned // FIXME(sil-serialize-all) internal let data: _MagicMirrorData @_inlineable // FIXME(sil-serialize-all) public var value: Any { return data.objcValue } @_inlineable // FIXME(sil-serialize-all) public var valueType: Any.Type { return data.objcValueType } @_inlineable // FIXME(sil-serialize-all) public var objectIdentifier: ObjectIdentifier? { return data._loadValue(ofType: ObjectIdentifier.self) } @_inlineable // FIXME(sil-serialize-all) public var count: Int { return _getObjCCount(data) } @_inlineable // FIXME(sil-serialize-all) public subscript(i: Int) -> (String, _Mirror) { return _getObjCChild(i, data) } @_inlineable // FIXME(sil-serialize-all) public var summary: String { return _getObjCSummary(data) } @_inlineable // FIXME(sil-serialize-all) public var quickLookObject: PlaygroundQuickLook? { let object = _swift_ClassMirror_quickLookObject(data) return _getClassPlaygroundQuickLook(object) } @_inlineable // FIXME(sil-serialize-all) public var disposition: _MirrorDisposition { return .objCObject } } public // SPI(runtime) struct _ObjCSuperMirror : _Mirror { @_versioned // FIXME(sil-serialize-all) internal let data: _MagicMirrorData @_inlineable // FIXME(sil-serialize-all) public var value: Any { return data.objcValue } @_inlineable // FIXME(sil-serialize-all) public var valueType: Any.Type { return data.objcValueType } // Suppress the value identifier for super mirrors. @_inlineable // FIXME(sil-serialize-all) public var objectIdentifier: ObjectIdentifier? { return nil } @_inlineable // FIXME(sil-serialize-all) public var count: Int { return _getObjCCount(data) } @_inlineable // FIXME(sil-serialize-all) public subscript(i: Int) -> (String, _Mirror) { return _getObjCChild(i, data) } @_inlineable // FIXME(sil-serialize-all) public var summary: String { return _getObjCSummary(data) } @_inlineable // FIXME(sil-serialize-all) public var quickLookObject: PlaygroundQuickLook? { let object = _swift_ClassMirror_quickLookObject(data) return _getClassPlaygroundQuickLook(object) } @_inlineable // FIXME(sil-serialize-all) public var disposition: _MirrorDisposition { return .objCObject } } #endif
apache-2.0
177413ee8b25389ad13d62d2144d092e
34.633663
111
0.695471
4.066667
false
false
false
false
CodeEagle/SSImageBrowser
Source/SSPhoto.swift
1
9613
// // SSPhoto.swift // Pods // // Created by LawLincoln on 15/7/10. // // import UIKit import Photos public final class SSPhoto: NSObject { public var aCaption: String? public var photoURL: URL? public var progressUpdateBlock: SSProgressUpdateBlock? public var aPlaceholderImage: UIImage? fileprivate var aUnderlyingImage: UIImage? fileprivate var loadingInProgress: Bool? public var photoPath: String? public var asset: PHAsset? public var targetSize: CGSize? fileprivate var requestId: PHImageRequestID? fileprivate var _task: URLSessionTask? convenience public init(image: UIImage) { self.init() aUnderlyingImage = image } convenience public init(filePath: String) { self.init() photoPath = filePath } convenience public init(url: URL) { self.init() photoURL = url } convenience public init(aAsset: PHAsset, aTargetSize: CGSize! = nil) { self.init() asset = aAsset targetSize = aTargetSize } override init() { super.init() NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "stopAllRequest"), object: nil, queue: OperationQueue.main) { [weak self](_) -> Void in self?.cancelRequest() } } deinit { cancelRequest() } func cancelRequest() { if let id = requestId { PHImageManager.default().cancelImageRequest(id) } } } // MARK: - NSURLSessionDelegate extension SSPhoto: URLSessionDownloadDelegate { public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { let downloadedImage = UIImage(data: try! Data(contentsOf: location)) aUnderlyingImage = downloadedImage DispatchQueue.main.async { self.imageLoadingComplete() } } public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { let progress = CGFloat(totalBytesWritten) / CGFloat(totalBytesExpectedToWrite) progressUpdateBlock?(progress) } } // MARK: - Class Method extension SSPhoto { public class func photoWithImage(_ image: UIImage) -> SSPhoto { return SSPhoto(image: image) } public class func photoWithFilePath(_ path: String) -> SSPhoto { return SSPhoto(filePath: path) } public class func photoWithURL(_ url: URL) -> SSPhoto { return SSPhoto(url: url) } public class func photosWithImages(_ imagesArray: [UIImage]) -> [SSPhoto] { var photos = [SSPhoto]() for image in imagesArray { photos.append(SSPhoto(image: image)) } return photos } public class func photosWithFilePaths(_ pathsArray: [String]) -> [SSPhoto] { var photos = [SSPhoto]() for path in pathsArray { photos.append(SSPhoto(filePath: path)) } return photos } public class func photosWithURLs(_ urlsArray: [URL]) -> [SSPhoto] { var photos = [SSPhoto]() for url in urlsArray { photos.append(SSPhoto(url: url)) } return photos } public class func photosWithAssets(_ assets: [PHAsset], targetSize: CGSize! = nil) -> [SSPhoto] { var photos = [SSPhoto]() for asset in assets { photos.append(SSPhoto(aAsset: asset, aTargetSize: targetSize)) } return photos } } // MARK: - SSPhotoProtocol public func == (lhs: SSPhoto, rhs: SSPhoto) -> Bool { return lhs.hashValue == rhs.hashValue } extension SSPhoto { public func underlyingImage() -> UIImage! { return aUnderlyingImage } fileprivate func createDownloadTask(_ url: URL) { _task?.cancel() let downloadRequest = URLRequest(url: url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 30) let session = Foundation.URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: OperationQueue.main) _task = session.downloadTask(with: downloadRequest) _task?.resume() } public func loadUnderlyingImageAndNotify() { loadingInProgress = true if aUnderlyingImage != nil { imageLoadingComplete() } else { if let _ = photoPath { DispatchQueue.global(qos: .default).async { self.loadImageFromFileAsync() } } else if let url = photoURL { DispatchQueue.global(qos: .userInitiated).async { self.createDownloadTask(url) } } else if let photo = asset { var size = CGSize(width: CGFloat(photo.pixelWidth), height: CGFloat(photo.pixelHeight)) if let asize = targetSize { size = asize } weak var wsekf: SSPhoto! = self let progressBlock: PHAssetImageProgressHandler = { (value, error, stop, info) -> Void in DispatchQueue.main.async(execute: { () -> Void in wsekf.progressUpdateBlock?(CGFloat(value)) }) } DispatchQueue.global(qos: .default).async { wsekf.requestId = photo.imageWithSize(size, progress: progressBlock, done: { (image) -> () in DispatchQueue.main.async(execute: { () -> Void in wsekf.aUnderlyingImage = image wsekf.imageLoadingComplete() }) }) } } } } public func unloadUnderlyingImage() { loadingInProgress = false if aUnderlyingImage != nil && (photoPath != nil || photoURL != nil) { aUnderlyingImage = nil } cancelRequest() } public func caption() -> String? { return aCaption } public func placeholderImage() -> UIImage? { return aPlaceholderImage } } // MARK: - Async Loading extension SSPhoto { func decodedImageWithImage(_ image: UIImage) -> UIImage? { if let _ = image.images { return image } let imageRef = image.cgImage let imageSize = CGSize(width: CGFloat((imageRef?.width)!), height: CGFloat((imageRef?.height)!)) let imageRect = (CGRect(x: 0, y: 0, width: imageSize.width, height: imageSize.height)) let colorSpace = CGColorSpaceCreateDeviceRGB() var bitmapInfo = imageRef?.bitmapInfo let infoMask = bitmapInfo?.intersection(CGBitmapInfo.alphaInfoMask) let alphaNone = CGBitmapInfo(rawValue: CGImageAlphaInfo.none.rawValue) let alphaNoneSkipFirst = CGBitmapInfo(rawValue: CGImageAlphaInfo.noneSkipFirst.rawValue) let alphaNoneSkipLast = CGBitmapInfo(rawValue: CGImageAlphaInfo.noneSkipLast.rawValue) let anyNonAlpha = infoMask == alphaNone || infoMask == alphaNoneSkipFirst || infoMask == alphaNoneSkipLast // CGBitmapContextCreate doesn't support kCGImageAlphaNone with RGB. if (infoMask == alphaNone && colorSpace.numberOfComponents > 1) { // Unset the old alpha info. let newBitmapInfoRaw = (bitmapInfo?.rawValue)! & ~CGBitmapInfo.alphaInfoMask.rawValue // Set noneSkipFirst. bitmapInfo = CGBitmapInfo(rawValue: (newBitmapInfoRaw | alphaNoneSkipFirst.rawValue)) } // Some PNGs tell us they have alpha but only 3 components. Odd. else if (!anyNonAlpha && colorSpace.numberOfComponents == 3) { // Unset the old alpha info. let newBitmapInfoRaw = (bitmapInfo?.rawValue)! & ~CGBitmapInfo.alphaInfoMask.rawValue // bitmapInfo &= ~CGBitmapInfo.AlphaInfoMask bitmapInfo = CGBitmapInfo(rawValue: newBitmapInfoRaw | CGImageAlphaInfo.premultipliedFirst.rawValue) } // It calculates the bytes-per-row based on the bitsPerComponent and width arguments. let context = CGContext(data: nil, width: Int(imageSize.width), height: Int(imageSize.height), bitsPerComponent: (imageRef?.bitsPerComponent)!, bytesPerRow: 0, space: colorSpace, bitmapInfo: (bitmapInfo?.rawValue)!) // If failed, return undecompressed image if context == nil { return image } context?.draw(imageRef!, in: imageRect) guard let decompressedImageRef = context?.makeImage() else { return nil } let decompressedImage = UIImage(cgImage: decompressedImageRef, scale: image.scale, orientation: image.imageOrientation) return decompressedImage } func loadImageFromFileAsync() { autoreleasepool { () -> () in if let path = photoPath, let img = UIImage(contentsOfFile: path) { aUnderlyingImage = img } else { if let image = aUnderlyingImage, let img = decodedImageWithImage(image) { aUnderlyingImage = img } } DispatchQueue.main.async(execute: { () -> Void in self.imageLoadingComplete() }) } } func imageLoadingComplete() { loadingInProgress = false NotificationCenter.default.post(name: Notification.Name.SSPhotoLoadingDidEnd, object: self) } } public extension PHAsset { public var identifier: String { return URL(string: self.localIdentifier)?.pathComponents[0] ?? "" } public func imageWithSize(_ size: CGSize, progress: PHAssetImageProgressHandler!, done: @escaping (UIImage!) -> ()) -> PHImageRequestID! { let cache = URLCache.shared let key = identifier + "_\(size.width)x\(size.height)" guard let url = URL(string: "https://\(key)") else { return nil } let request = URLRequest(url: url) if let resp = cache.cachedResponse(for: request), let img = UIImage(data: resp.data) { done(img) return nil } let manager = PHImageManager.default() let option = PHImageRequestOptions() option.isSynchronous = false option.isNetworkAccessAllowed = true option.normalizedCropRect = CGRect(origin: CGPoint.zero, size: size) option.resizeMode = .exact option.progressHandler = progress option.deliveryMode = .highQualityFormat option.version = .original return manager.requestImage(for: self, targetSize: size, contentMode: .aspectFit, options: option, resultHandler: { (result, info) -> Void in if let img = result { let urlresp = URLResponse(url: url, mimeType: nil, expectedContentLength: 0, textEncodingName: nil) if let data = UIImageJPEGRepresentation(img, 1) { let resp = CachedURLResponse(response: urlresp, data: data) cache.storeCachedResponse(resp, for: request) } } done(result) }) } }
mit
30baecaba7ddb636cb21b9ab31892028
29.61465
217
0.713929
3.869968
false
false
false
false
1457792186/JWOCLibertyDemoWithPHP
LibertyDemoWithPHP/NxhTest/Library/Charts/Charts/Renderers/Scatter/TriangleShapeRenderer.swift
1
2546
// // TriangleShapeRenderer.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import UIKit open class TriangleShapeRenderer : NSObject, IShapeRenderer { open func renderShape( context: CGContext, dataSet: IScatterChartDataSet, viewPortHandler: ViewPortHandler, point: CGPoint, color: NSUIColor) { let shapeSize = dataSet.scatterShapeSize let shapeHalf = shapeSize / 2.0 let shapeHoleSizeHalf = dataSet.scatterShapeHoleRadius let shapeHoleSize = shapeHoleSizeHalf * 2.0 let shapeHoleColor = dataSet.scatterShapeHoleColor let shapeStrokeSize = (shapeSize - shapeHoleSize) / 2.0 context.setFillColor(color.cgColor) // create a triangle path context.beginPath() context.move(to: CGPoint(x: point.x, y: point.y - shapeHalf)) context.addLine(to: CGPoint(x: point.x + shapeHalf, y: point.y + shapeHalf)) context.addLine(to: CGPoint(x: point.x - shapeHalf, y: point.y + shapeHalf)) if shapeHoleSize > 0.0 { context.addLine(to: CGPoint(x: point.x, y: point.y - shapeHalf)) context.move(to: CGPoint(x: point.x - shapeHalf + shapeStrokeSize, y: point.y + shapeHalf - shapeStrokeSize)) context.addLine(to: CGPoint(x: point.x + shapeHalf - shapeStrokeSize, y: point.y + shapeHalf - shapeStrokeSize)) context.addLine(to: CGPoint(x: point.x, y: point.y - shapeHalf + shapeStrokeSize)) context.addLine(to: CGPoint(x: point.x - shapeHalf + shapeStrokeSize, y: point.y + shapeHalf - shapeStrokeSize)) } context.closePath() context.fillPath() if shapeHoleSize > 0.0 && shapeHoleColor != nil { context.setFillColor(shapeHoleColor!.cgColor) // create a triangle path context.beginPath() context.move(to: CGPoint(x: point.x, y: point.y - shapeHalf + shapeStrokeSize)) context.addLine(to: CGPoint(x: point.x + shapeHalf - shapeStrokeSize, y: point.y + shapeHalf - shapeStrokeSize)) context.addLine(to: CGPoint(x: point.x - shapeHalf + shapeStrokeSize, y: point.y + shapeHalf - shapeStrokeSize)) context.closePath() context.fillPath() } } }
apache-2.0
2e173852e7ce4f36d269ed1b566b35f9
37.575758
124
0.620581
4.637523
false
false
false
false
Vostro162/VaporTelegram
Sources/App/Game+Extensions.swift
1
1282
// // Game+Extensions.swift // VaporTelegram // // Created by Marius Hartig on 11.05.17. // // import Foundation import Vapor // MARK: - JSON extension Game: JSONInitializable { public init(json: JSON) throws { guard let title = json["title"]?.string, let description = json["description"]?.string else { throw VaporTelegramError.parsing } if let entitiesJSON = json["text_entities"], let entities = try? MessageEntity.create(arrayJSON: entitiesJSON) { self.textEntities = entities } else { self.textEntities = [MessageEntity]() } if let photosJSON = json["photo"], let photos = try? PhotoSize.create(arrayJSON: photosJSON) { self.photos = photos } else { self.photos = [PhotoSize]() } if let text = json["text"]?.string { self.text = text } else { self.text = nil } if let animationJSON = json["animation"], let animation = try? Animation(json: animationJSON) { self.animation = animation } else { self.animation = nil } self.title = title self.description = description } }
mit
73fdc8eef1800a65830ec3b84fd0c061
26.276596
120
0.549142
4.514085
false
false
false
false
arvedviehweger/swift
test/SILOptimizer/access_enforcement_selection.swift
1
2333
// RUN: %target-swift-frontend -enforce-exclusivity=checked -Onone -emit-sil -parse-as-library %s -Xllvm -debug-only=access-enforcement-selection 2>&1 | %FileCheck %s // REQUIRES: asserts // This is a source-level test because it helps bring up the entire -Onone pipeline with the access markers. public func takesInout(_ i: inout Int) { i = 42 } // CHECK-LABEL: Access Enforcement Selection in _T028access_enforcement_selection10takesInoutySizF // CHECK: Static Access: %{{.*}} = begin_access [modify] [static] %{{.*}} : $*Int // Helper taking a basic, no-escape closure. func takeClosure(_: ()->Int) {} // Generate an alloc_stack that escapes into a closure. public func captureStack() -> Int { // Use a `var` so `x` isn't treated as a literal. var x = 3 takeClosure { return x } return x } // CHECK-LABEL: Access Enforcement Selection in _T028access_enforcement_selection12captureStackSiyF // Static access for `return x`. // CHECK: Static Access: %{{.*}} = begin_access [read] [static] %{{.*}} : $*Int // The access inside the closure is dynamic, until we have the logic necessary to // prove that no other closures are passed to `takeClosure` that may write to // `x`. // // CHECK-LABEL: Access Enforcement Selection in _T028access_enforcement_selection12captureStackSiyFSiycfU_ // CHECK: Dynamic Access: %{{.*}} = begin_access [read] [dynamic] %{{.*}} : $*Int // Generate a closure in which the @inout_aliasing argument // escapes to an @inout function `bar`. public func recaptureStack() -> Int { var x = 3 takeClosure { takesInout(&x); return x } return x } // CHECK-LABEL: Access Enforcement Selection in _T028access_enforcement_selection14recaptureStackSiyF // // Static access for `return x`. // CHECK: Static Access: %{{.*}} = begin_access [read] [static] %{{.*}} : $*Int // CHECK-LABEL: Access Enforcement Selection in _T028access_enforcement_selection14recaptureStackSiyFSiycfU_ // // The first [modify] access inside the closure must be dynamic. It enforces the // @inout argument. // CHECK: Dynamic Access: %{{.*}} = begin_access [modify] [dynamic] %{{.*}} : $*Int // // The second [read] access is only dynamic because the analysis isn't strong // enough to prove otherwise. Same as `captureStack` above. // // CHECK: Dynamic Access: %{{.*}} = begin_access [read] [dynamic] %{{.*}} : $*Int
apache-2.0
7c08100557a23a42584a373b8c01a347
41.418182
166
0.698671
3.750804
false
false
false
false
minhkiller/iBurn-iOS
iBurn/BRCMoreViewController.swift
2
5580
// // BRCMoreViewController.swift // iBurn // // Created by Christopher Ballinger on 8/13/15. // Copyright (c) 2015 Burning Man Earth. All rights reserved. // import UIKit import HockeySDK_Source import StoreKit enum CellTag: Int { case Art = 1, Camps = 2, Unlock = 3, Credits = 4, Feedback = 5, Share = 6, Rate = 7, DebugShowOnboarding = 8 } class BRCMoreViewController: UITableViewController, SKStoreProductViewControllerDelegate { // MARK: - View Lifecycle override func viewDidLoad() { super.viewDidLoad() self.title = "More" } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) tableView.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - UITableViewDelegate & DataSource override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = super.tableView(tableView, cellForRowAtIndexPath: indexPath) if let cellImage = cell.imageView?.image { cell.imageView!.image = cellImage.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate) } if cell.tag == CellTag.Unlock.rawValue { if BRCEmbargo.allowEmbargoedData() { cell.imageView!.image = UIImage(named: "BRCUnlockIcon")!.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate) cell.textLabel!.text = "Location Data Unlocked" cell.textLabel!.textColor = UIColor.lightGrayColor() cell.userInteractionEnabled = false } } return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) let cell = tableView.cellForRowAtIndexPath(indexPath)! if let cellTag = CellTag(rawValue: cell.tag) { switch cellTag { case .Art: pushArtView() case .Camps: pushCampsView() case .Unlock: showUnlockView() case .Credits: pushCreditsView() case .Feedback: showFeedbackView() case .Share: showShareSheet(cell) case .Rate: showRatingsView() case .DebugShowOnboarding: showOnboardingView() } } } func pushArtView() { let dbManager = BRCDatabaseManager.sharedInstance() let artVC = BRCFilteredTableViewController(viewClass: BRCArtObject.self, viewName: dbManager.artViewName, searchViewName: dbManager.searchArtView) artVC.title = "Art" artVC.hidesBottomBarWhenPushed = true navigationController!.pushViewController(artVC, animated: true) } func pushCampsView() { let dbManager = BRCDatabaseManager.sharedInstance() let campsVC = BRCFilteredTableViewController(viewClass: BRCCampObject.self, viewName: dbManager.campsViewName, searchViewName: dbManager.searchCampsView) campsVC.title = "Camps" campsVC.hidesBottomBarWhenPushed = true navigationController!.pushViewController(campsVC, animated: true) } func showUnlockView() { let unlockVC = BRCEmbargoPasscodeViewController() unlockVC.dismissAction = { unlockVC.dismissViewControllerAnimated(true, completion: nil) } presentViewController(unlockVC, animated: true, completion: nil) } func pushCreditsView() { let creditsVC = BRCCreditsViewController() creditsVC.title = "Credits" creditsVC.hidesBottomBarWhenPushed = true navigationController!.pushViewController(creditsVC, animated: true) } func showFeedbackView() { BITHockeyManager.sharedHockeyManager().feedbackManager.showFeedbackListView() } func showShareSheet(fromView: UIView) { let url = NSURL(string: "http://iburnapp.com")! let string = "Going to Burning Man? Check out @iBurnApp for offline maps, events and more!" let shareVC = UIActivityViewController(activityItems: [string, url], applicationActivities: nil) shareVC.popoverPresentationController?.sourceView = fromView; presentViewController(shareVC, animated: true, completion: nil) } func showRatingsView() { let storeVC = SKStoreProductViewController() storeVC.delegate = self storeVC.loadProductWithParameters([SKStoreProductParameterITunesItemIdentifier : 388169740], completionBlock: nil) presentViewController(storeVC, animated: true, completion: nil) } // MARK: - Debug func pushDebugView() { // TODO: make debug view } func showOnboardingView() { var onboardingVC: OnboardingViewController? = nil onboardingVC = BRCAppDelegate.onboardingViewControllerWithCompletion { () -> Void in onboardingVC!.dismissViewControllerAnimated(true, completion: nil) } presentViewController(onboardingVC!, animated: true, completion: nil) } // MARK: - SKStoreProductViewControllerDelegate func productViewControllerDidFinish(viewController: SKStoreProductViewController!) { viewController.dismissViewControllerAnimated(true, completion: nil) } }
mpl-2.0
dcd85b6d85c5f5281e89271e129721ba
33.875
161
0.656989
5.171455
false
false
false
false
juliangrosshauser/Dynamics
Dynamics/Source/ImageFlickController.swift
1
2524
// // ImageFlickController.swift // Dynamics // // Created by Julian Grosshauser on 10/10/15. // Copyright © 2015 Julian Grosshauser. All rights reserved. // import UIKit class ImageFlickController: UIViewController { //MARK: Properties private var dynamicAnimator: UIDynamicAnimator! private var itemBehavior: UIDynamicItemBehavior! private var collisionBehavior: UICollisionBehavior! private let image = UIImageView(image: UIImage(named: "ProfileImage.png")) private var offset = CGPoint.zero //MARK: UIViewController override func viewDidLoad() { super.viewDidLoad() dynamicAnimator = UIDynamicAnimator(referenceView: view) image.center = view.center image.userInteractionEnabled = true let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: "pan:") image.addGestureRecognizer(panGestureRecognizer) view.addSubview(image) itemBehavior = UIDynamicItemBehavior(items: [image]) itemBehavior.resistance = 0.5 dynamicAnimator.addBehavior(itemBehavior) collisionBehavior = UICollisionBehavior(items: [image]) collisionBehavior.translatesReferenceBoundsIntoBoundary = true dynamicAnimator.addBehavior(collisionBehavior) } //MARK: Gesture Recognizers @objc private func pan(pan: UIPanGestureRecognizer) { var location = pan.locationInView(view) switch pan.state { case .Began: let center = image.center offset.x = location.x - center.x offset.y = location.y - center.y case .Changed: let referenceBounds = view.bounds let referenceWidth = referenceBounds.width let referenceHeight = referenceBounds.height let itemBounds = image.bounds let itemHalfWidth = itemBounds.width / 2.0 let itemHalfHeight = itemBounds.height / 2.0 location.x -= offset.x location.y -= offset.y location.x = max(itemHalfWidth, location.x) location.x = min(referenceWidth - itemHalfWidth, location.x) location.y = max(itemHalfHeight, location.y) location.y = min(referenceHeight - itemHalfHeight, location.y) image.center = location case .Cancelled, .Ended: let velocity = pan.velocityInView(view) itemBehavior.addLinearVelocity(velocity, forItem: image) default: () } } }
mit
9a561993aaced34b87828ad8cdcfe5f9
29.768293
87
0.655172
5.076459
false
false
false
false
chayelheinsen/GamingStreams-tvOS-App
StreamCenter/StreamCenterService.swift
3
5066
// // StreamCenterService.swift // GamingStreamsTVApp // // Created by Brendan Kirchner on 10/15/15. // Copyright © 2015 Rivus Media Inc. All rights reserved. // import UIKit import Alamofire enum ServiceError: ErrorType { case URLError case JSONError case DataError case AuthError case NoAuthTokenError case OtherError(String) var errorDescription: String { get { switch self { case .URLError: return "There was an error with the request." case .JSONError: return "There was an error parsing the JSON." case .DataError: return "The response contained bad data" case .AuthError: return "The user is not authenticated." case .NoAuthTokenError: return "There was no auth token provided in the response data." case .OtherError(let message): return message } } } //only use this top log, do not present this to the user var developerSuggestion: String { get { switch self { case .URLError: return "Please make sure that the url is formatted correctly." case .JSONError, .DataError: return "Please check the request information and response." case .AuthError: return "Please make sure to authenticate with Twitch before attempting to load this data." case .NoAuthTokenError: return "Please check the server logs and response." case .OtherError: //change to case .OtherError(let message):if you want to be able to utilize an error message return "Sorry, there's no provided solution for this error." } } } } class StreamCenterService { static func authenticateTwitch(withCode code: String, andUUID UUID: String, completionHandler: (token: String?, error: ServiceError?) -> ()) { let urlString = "http://streamcenterapp.com/oauth/twitch/\(UUID)/\(code)" Alamofire.request(.GET, urlString) .responseJSON { response in if response.result.isSuccess { if let dictionary = response.result.value as? [String : AnyObject] { guard let token = dictionary["access_token"] as? String, date = dictionary["generated_date"] as? String else { Logger.Error("Could not retrieve desired information from response:\naccess_token\ngenerated_date") completionHandler(token: nil, error: .NoAuthTokenError) return } //NOTE: date is formatted: '2015-10-13 20:35:12' Mixpanel.tracker()?.trackEvents([Event.ServiceAuthenticationEvent("Twitch")]) Logger.Debug("User sucessfully retrieved Oauth token") completionHandler(token: token, error: nil) } else { Logger.Error("Could not parse response as JSON") completionHandler(token: nil, error: .JSONError) } } else { Logger.Error("Could not request Twitch Oauth service") completionHandler(token: nil, error: .URLError) return } } } static func getCustomURL(fromCode code: String, completionHandler: (url: String?, error: ServiceError?) -> ()) { let urlString = "http://streamcenterapp.com/customurl/\(code)" Alamofire.request(.GET, urlString) .responseJSON { response in //here's a test url // completionHandler(url: "http://qthttp.apple.com.edgesuite.net/1010qwoeiuryfg/sl.m3u8", error: nil) // return if response.result.isSuccess { if let dictionary = response.result.value as? [String : AnyObject] { if let urlString = dictionary["url"] as? String { Logger.Debug("Returned: \(urlString)") completionHandler(url: urlString, error: nil) return } if let errorMessage = dictionary["message"] as? String { Logger.Error("Custom url service returned an error:\n\(errorMessage)") completionHandler(url: nil, error: .OtherError(errorMessage)) return } } Logger.Error("Could not parse response as JSON") completionHandler(url: nil, error: .JSONError) } else { Logger.Error("Could not request the custom url service") completionHandler(url: nil, error: .URLError) } } } }
mit
5a62f318ef0f10062b22d14379fbfd69
40.516393
146
0.539783
5.388298
false
false
false
false
davidprochazka/HappyDay
HappyDayMobileApp/HappyDay/TeamViewController.swift
1
10022
// // MasterViewController.swift // HappyDay // // Created by David Prochazka on 09/03/16. // Copyright © 2016 David Prochazka. All rights reserved. // import UIKit import CoreData class TeamViewController: UITableViewController, NSFetchedResultsControllerDelegate { var managedObjectContext: NSManagedObjectContext? = nil var editedTeamIndexPath: NSIndexPath? = nil override func viewDidLoad() { super.viewDidLoad() // Edit button on the left side self.navigationItem.leftBarButtonItem = self.editButtonItem() // Height of the team line, shloud be calculated automatically self.tableView.rowHeight = 135 } override func viewWillAppear(animated: Bool) { self.clearsSelectionOnViewWillAppear = self.splitViewController!.collapsed super.viewWillAppear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Segues override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // If someone clicked on a team button if segue.identifier == "teamSelected" { // send our controller and MOC // It is not necessary to send MOC, can be instantiated separately in the seque. let personsViewController = segue.destinationViewController as! PersonsTableViewController personsViewController.teamViewControllerNC = self.navigationController // Send selected team if let indexPath = self.tableView.indexPathForSelectedRow { let selectedTeam = self.fetchedResultsController.objectAtIndexPath(indexPath) as! Team personsViewController.selectedTeam = selectedTeam } } else if segue.identifier == "editTeam" { let controller = (segue.destinationViewController as! UINavigationController).topViewController as! EditTeamViewController // Send selected team if let indexPath = self.editedTeamIndexPath { let selectedTeam = self.fetchedResultsController.objectAtIndexPath(indexPath) as! Team controller.selectedTeam = selectedTeam } } } // MARK: - EditTeamDelegate // Saving changes in a team func saveEditedTeamWith(name: String, andImage image: UIImage,atIndexPath indexPath:NSIndexPath){ let context = self.fetchedResultsController.managedObjectContext let team = self.fetchedResultsController.objectAtIndexPath(indexPath) as! Team team.name = name team.image = UIImagePNGRepresentation(image) // Save the context. do { try context.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. //print("Unresolved error \(error), \(error.userInfo)") abort() } } // MARK: - Table View override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return self.fetchedResultsController.sections?.count ?? 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let sectionInfo = self.fetchedResultsController.sections![section] return sectionInfo.numberOfObjects } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("TeamCell", forIndexPath: indexPath) self.configureCell(cell, atIndexPath: indexPath) return cell } override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { let context = self.fetchedResultsController.managedObjectContext context.deleteObject(self.fetchedResultsController.objectAtIndexPath(indexPath) as! NSManagedObject) do { try context.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. //print("Unresolved error \(error), \(error.userInfo)") abort() } } } // Support method that loads data into a table cell func configureCell(cell: UITableViewCell, atIndexPath indexPath: NSIndexPath) { let teamCell = cell as! TeamTableViewCell let fetchedTeam = self.fetchedResultsController.objectAtIndexPath(indexPath) as! Team let imageData = fetchedTeam.image teamCell.teamImage.image = UIImage(data: imageData!) teamCell.nameLabel?.text = (fetchedTeam.name) } // MARK: - Fetched results controller var fetchedResultsController: NSFetchedResultsController { if _fetchedResultsController != nil { return _fetchedResultsController! } let fetchRequest = NSFetchRequest() // Load Teams from database let entity = NSEntityDescription.entityForName("Team", inManagedObjectContext: self.managedObjectContext!) fetchRequest.entity = entity // Set the batch size to a suitable number. fetchRequest.fetchBatchSize = 20 // Sort records by the name. let sortDescriptor = NSSortDescriptor(key: "name", ascending: false) fetchRequest.sortDescriptors = [sortDescriptor] // Edit the section name key path and cache name if appropriate. // nil for section name key path means "no sections". let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedObjectContext!, sectionNameKeyPath: nil, cacheName: "Master") aFetchedResultsController.delegate = self _fetchedResultsController = aFetchedResultsController do { try _fetchedResultsController!.performFetch() } 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. //print("Unresolved error \(error), \(error.userInfo)") abort() } return _fetchedResultsController! } var _fetchedResultsController: NSFetchedResultsController? = nil func controllerWillChangeContent(controller: NSFetchedResultsController) { self.tableView.beginUpdates() } func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) { switch type { case .Insert: self.tableView.insertSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade) case .Delete: self.tableView.deleteSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade) default: return } } func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) { switch type { case .Insert: tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade) case .Delete: tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade) case .Update: self.configureCell(tableView.cellForRowAtIndexPath(indexPath!)!, atIndexPath: indexPath!) case .Move: tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade) tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade) } } func controllerDidChangeContent(controller: NSFetchedResultsController) { self.tableView.endUpdates() } // MARK: - Custom edit menu override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]? { let deleteAction = UITableViewRowAction(style: UITableViewRowActionStyle.Destructive, title: "Delete" , handler: { (action:UITableViewRowAction!, indexPath:NSIndexPath!) -> Void in // smazu objekt jen z MOC, tabulka se aktualizuje automaticky self.tableView(self.tableView, commitEditingStyle: .Delete, forRowAtIndexPath: indexPath) }) let editAction = UITableViewRowAction(style: UITableViewRowActionStyle.Normal, title: "Edit" , handler: { (action:UITableViewRowAction!, indexPath:NSIndexPath!) -> Void in self.editedTeamIndexPath = indexPath self.performSegueWithIdentifier("editTeam", sender: nil) //let storyboard = UIStoryboard(name: "Main", bundle: nil) //let vc = storyboard.instantiateViewControllerWithIdentifier("editTeamView") as! UINavigationController //self.presentViewController(vc, animated: true, completion: nil) }) return [deleteAction,editAction] } }
gpl-3.0
384ee9dac490a88c936d7a7bed097423
45.393519
211
0.679872
6.036747
false
false
false
false
bluquar/emoji_keyboard
EmojiKeyboard/EmojiSelectKB/experiment.playground/section-1.swift
1
209
// Playground - noun: a place where people can play import UIKit var x = 1+2 let a = 0...2 let b = 0..<3 a == b var d : [Int: String] = [0: "hi"] print(d) var e : [Int: String] = [:] e[2] = "hey" e
gpl-2.0
3a01505a0ee43ca7bc6d061440ae0508
8.5
51
0.526316
2.348315
false
false
false
false
noppoMan/aws-sdk-swift
Sources/Soto/Services/SSOAdmin/SSOAdmin_API.swift
1
16912
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. @_exported import SotoCore /* Client object for interacting with AWS SSOAdmin service. */ public struct SSOAdmin: AWSService { // MARK: Member variables public let client: AWSClient public let config: AWSServiceConfig // MARK: Initialization /// Initialize the SSOAdmin client /// - parameters: /// - client: AWSClient used to process requests /// - region: Region of server you want to communicate with. This will override the partition parameter. /// - partition: AWS partition where service resides, standard (.aws), china (.awscn), government (.awsusgov). /// - endpoint: Custom endpoint URL to use instead of standard AWS servers /// - timeout: Timeout value for HTTP requests public init( client: AWSClient, region: SotoCore.Region? = nil, partition: AWSPartition = .aws, endpoint: String? = nil, timeout: TimeAmount? = nil, byteBufferAllocator: ByteBufferAllocator = ByteBufferAllocator(), options: AWSServiceConfig.Options = [] ) { self.client = client self.config = AWSServiceConfig( region: region, partition: region?.partition ?? partition, amzTarget: "SWBExternalService", service: "sso", serviceProtocol: .json(version: "1.1"), apiVersion: "2020-07-20", endpoint: endpoint, errorType: SSOAdminErrorType.self, timeout: timeout, byteBufferAllocator: byteBufferAllocator, options: options ) } // MARK: API Calls /// Attaches an IAM managed policy ARN to a permission set. If the permission set is already referenced by one or more account assignments, you will need to call ProvisionPermissionSet after this action to apply the corresponding IAM policy updates to all assigned accounts. public func attachManagedPolicyToPermissionSet(_ input: AttachManagedPolicyToPermissionSetRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<AttachManagedPolicyToPermissionSetResponse> { return self.client.execute(operation: "AttachManagedPolicyToPermissionSet", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Assigns access to a principal for a specified AWS account using a specified permission set. The term principal here refers to a user or group that is defined in AWS SSO. As part of a successful CreateAccountAssignment call, the specified permission set will automatically be provisioned to the account in the form of an IAM policy attached to the SSO-created IAM role. If the permission set is subsequently updated, the corresponding IAM policies attached to roles in your accounts will not be updated automatically. In this case, you will need to call ProvisionPermissionSet to make these updates. public func createAccountAssignment(_ input: CreateAccountAssignmentRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<CreateAccountAssignmentResponse> { return self.client.execute(operation: "CreateAccountAssignment", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Creates a permission set within a specified SSO instance. To grant users and groups access to AWS account resources, use CreateAccountAssignment . public func createPermissionSet(_ input: CreatePermissionSetRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<CreatePermissionSetResponse> { return self.client.execute(operation: "CreatePermissionSet", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Deletes a principal's access from a specified AWS account using a specified permission set. public func deleteAccountAssignment(_ input: DeleteAccountAssignmentRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DeleteAccountAssignmentResponse> { return self.client.execute(operation: "DeleteAccountAssignment", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Deletes the inline policy from a specified permission set. public func deleteInlinePolicyFromPermissionSet(_ input: DeleteInlinePolicyFromPermissionSetRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DeleteInlinePolicyFromPermissionSetResponse> { return self.client.execute(operation: "DeleteInlinePolicyFromPermissionSet", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Deletes the specified permission set. public func deletePermissionSet(_ input: DeletePermissionSetRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DeletePermissionSetResponse> { return self.client.execute(operation: "DeletePermissionSet", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Describes the status of the assignment creation request. public func describeAccountAssignmentCreationStatus(_ input: DescribeAccountAssignmentCreationStatusRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeAccountAssignmentCreationStatusResponse> { return self.client.execute(operation: "DescribeAccountAssignmentCreationStatus", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Describes the status of the assignment deletion request. public func describeAccountAssignmentDeletionStatus(_ input: DescribeAccountAssignmentDeletionStatusRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribeAccountAssignmentDeletionStatusResponse> { return self.client.execute(operation: "DescribeAccountAssignmentDeletionStatus", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Gets the details of the permission set. public func describePermissionSet(_ input: DescribePermissionSetRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribePermissionSetResponse> { return self.client.execute(operation: "DescribePermissionSet", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Describes the status for the given permission set provisioning request. public func describePermissionSetProvisioningStatus(_ input: DescribePermissionSetProvisioningStatusRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DescribePermissionSetProvisioningStatusResponse> { return self.client.execute(operation: "DescribePermissionSetProvisioningStatus", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Detaches the attached IAM managed policy ARN from the specified permission set. public func detachManagedPolicyFromPermissionSet(_ input: DetachManagedPolicyFromPermissionSetRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<DetachManagedPolicyFromPermissionSetResponse> { return self.client.execute(operation: "DetachManagedPolicyFromPermissionSet", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Obtains the inline policy assigned to the permission set. public func getInlinePolicyForPermissionSet(_ input: GetInlinePolicyForPermissionSetRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<GetInlinePolicyForPermissionSetResponse> { return self.client.execute(operation: "GetInlinePolicyForPermissionSet", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Lists the status of the AWS account assignment creation requests for a specified SSO instance. public func listAccountAssignmentCreationStatus(_ input: ListAccountAssignmentCreationStatusRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListAccountAssignmentCreationStatusResponse> { return self.client.execute(operation: "ListAccountAssignmentCreationStatus", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Lists the status of the AWS account assignment deletion requests for a specified SSO instance. public func listAccountAssignmentDeletionStatus(_ input: ListAccountAssignmentDeletionStatusRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListAccountAssignmentDeletionStatusResponse> { return self.client.execute(operation: "ListAccountAssignmentDeletionStatus", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Lists the assignee of the specified AWS account with the specified permission set. public func listAccountAssignments(_ input: ListAccountAssignmentsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListAccountAssignmentsResponse> { return self.client.execute(operation: "ListAccountAssignments", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Lists all the AWS accounts where the specified permission set is provisioned. public func listAccountsForProvisionedPermissionSet(_ input: ListAccountsForProvisionedPermissionSetRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListAccountsForProvisionedPermissionSetResponse> { return self.client.execute(operation: "ListAccountsForProvisionedPermissionSet", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Lists the SSO instances that the caller has access to. public func listInstances(_ input: ListInstancesRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListInstancesResponse> { return self.client.execute(operation: "ListInstances", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Lists the IAM managed policy that is attached to a specified permission set. public func listManagedPoliciesInPermissionSet(_ input: ListManagedPoliciesInPermissionSetRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListManagedPoliciesInPermissionSetResponse> { return self.client.execute(operation: "ListManagedPoliciesInPermissionSet", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Lists the status of the permission set provisioning requests for a specified SSO instance. public func listPermissionSetProvisioningStatus(_ input: ListPermissionSetProvisioningStatusRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListPermissionSetProvisioningStatusResponse> { return self.client.execute(operation: "ListPermissionSetProvisioningStatus", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Lists the PermissionSets in an SSO instance. public func listPermissionSets(_ input: ListPermissionSetsRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListPermissionSetsResponse> { return self.client.execute(operation: "ListPermissionSets", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Lists all the permission sets that are provisioned to a specified AWS account. public func listPermissionSetsProvisionedToAccount(_ input: ListPermissionSetsProvisionedToAccountRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListPermissionSetsProvisionedToAccountResponse> { return self.client.execute(operation: "ListPermissionSetsProvisionedToAccount", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Lists the tags that are attached to a specified resource. public func listTagsForResource(_ input: ListTagsForResourceRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ListTagsForResourceResponse> { return self.client.execute(operation: "ListTagsForResource", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// The process by which a specified permission set is provisioned to the specified target. public func provisionPermissionSet(_ input: ProvisionPermissionSetRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<ProvisionPermissionSetResponse> { return self.client.execute(operation: "ProvisionPermissionSet", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Attaches an IAM inline policy to a permission set. If the permission set is already referenced by one or more account assignments, you will need to call ProvisionPermissionSet after this action to apply the corresponding IAM policy updates to all assigned accounts. public func putInlinePolicyToPermissionSet(_ input: PutInlinePolicyToPermissionSetRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<PutInlinePolicyToPermissionSetResponse> { return self.client.execute(operation: "PutInlinePolicyToPermissionSet", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Associates a set of tags with a specified resource. public func tagResource(_ input: TagResourceRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<TagResourceResponse> { return self.client.execute(operation: "TagResource", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Disassociates a set of tags from a specified resource. public func untagResource(_ input: UntagResourceRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<UntagResourceResponse> { return self.client.execute(operation: "UntagResource", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } /// Updates an existing permission set. public func updatePermissionSet(_ input: UpdatePermissionSetRequest, logger: Logger = AWSClient.loggingDisabled, on eventLoop: EventLoop? = nil) -> EventLoopFuture<UpdatePermissionSetResponse> { return self.client.execute(operation: "UpdatePermissionSet", path: "/", httpMethod: .POST, serviceConfig: self.config, input: input, logger: logger, on: eventLoop) } } extension SSOAdmin { /// Initializer required by `AWSService.with(middlewares:timeout:byteBufferAllocator:options)`. You are not able to use this initializer directly as there are no public /// initializers for `AWSServiceConfig.Patch`. Please use `AWSService.with(middlewares:timeout:byteBufferAllocator:options)` instead. public init(from: SSOAdmin, patch: AWSServiceConfig.Patch) { self.client = from.client self.config = from.config.with(patch: patch) } }
apache-2.0
e21e5c05f07500cfd4a3dee3e5c40d30
80.307692
612
0.748995
4.909144
false
true
false
false
steelwheels/Coconut
CoconutData/Test/UnitTest/UTEscapeSequence.swift
1
4332
/** * @file UTEscapeSequence.swift * @brief Test function for CNEscapeSequence * @par Copyright * Copyright (C) 2019 Steel Wheels Project */ import CoconutData import Foundation public func testEscapeSequence(console cons: CNConsole) -> Bool { let res0 = dumpSequence(string: "Hello, World !!", console: cons) let res1 = dumpCode(code: CNEscapeCode.cursorUp(1), console: cons) let res2 = dumpCode(code: CNEscapeCode.cursorForward(3), console: cons) let res21 = dumpCode(code: CNEscapeCode.saveCursorPosition, console: cons) let res22 = dumpCode(code: CNEscapeCode.restoreCursorPosition, console: cons) let res3 = dumpCode(code: CNEscapeCode.cursorPosition(1, 2), console: cons) let res4 = dumpCode(code: CNEscapeCode.eraceEntireLine, console: cons) let res11 = dumpCode(code: CNEscapeCode.boldCharacter(true), console: cons) let res12 = dumpCode(code: CNEscapeCode.boldCharacter(false), console: cons) let res13 = dumpCode(code: CNEscapeCode.underlineCharacter(true), console: cons) let res14 = dumpCode(code: CNEscapeCode.underlineCharacter(false), console: cons) let res15 = dumpCode(code: CNEscapeCode.blinkCharacter(true), console: cons) let res16 = dumpCode(code: CNEscapeCode.blinkCharacter(false), console: cons) let res17 = dumpCode(code: CNEscapeCode.reverseCharacter(true), console: cons) let res18 = dumpCode(code: CNEscapeCode.reverseCharacter(false), console: cons) let res6 = dumpCode(code: CNEscapeCode.foregroundColor(.white), console: cons) let res19 = dumpCode(code: CNEscapeCode.defaultForegroundColor, console: cons) let res7 = dumpCode(code: CNEscapeCode.backgroundColor(.red), console: cons) let res20 = dumpCode(code: CNEscapeCode.defaultBackgroundColor, console: cons) let res8 = dumpCode(code: CNEscapeCode.resetCharacterAttribute, console: cons) let res9 = dumpCode(code: CNEscapeCode.requestScreenSize, console: cons) let res10 = dumpCode(code: CNEscapeCode.screenSize(80, 25), console: cons) let str0 = CNEscapeCode.cursorNextLine(1).encode() let str1 = CNEscapeCode.eraceEntireLine.encode() let str = "Hello, " + str0 + " and " + str1 + ". Bye." let res5 = dumpSequence(string: str, console: cons) let lsstr = "Applications\r" + "Desktop\r" + "Development\r" + "Documents\r" + "Downloads\r" + "Google ドライブ\r" + "Library\r" + "Movies\r" + "Music\r" + "Pictures\r" + "Project\r" + "Public\r" + "Script\r" + "Sequrity\r" + "Shared\r" + "Sites\r" + "build\r" + "iCloud Drive(アーカイブ)\r" + "local\r" + "tmp_dir\r" + "tools\r" + "アプリケーション\r" let res23 = dumpSequence(string: lsstr, console: cons) let result = res0 && res1 && res2 && res3 && res4 && res5 && res6 && res7 && res8 && res9 && res10 && res11 && res12 && res13 && res14 && res15 && res16 && res17 && res18 && res19 && res20 && res21 && res22 && res23 if result { cons.print(string: "testEscapeSequence .. OK\n") } else { cons.print(string: "testEscapeSequence .. NG\n") } //cons.error(string: "Color message\n") return result } private func dumpCode(code ecode: CNEscapeCode, console cons: CNConsole) -> Bool { cons.print(string: "* dumpCode\n") let result: Bool let str = ecode.encode() switch CNEscapeCode.decode(string: str) { case .ok(let codes): for code in codes { cons.print(string: code.description()) cons.print(string: "\n") } if codes.count == 1 { if ecode.compare(code: codes[0]) { cons.print(string: "Same code\n") } else { let desc = codes[0].description() cons.error(string: "[Error] Different code: \(desc)\n") } } else { cons.error(string: "[Error] Too many codes\n") } result = true case .error(let err): cons.error(string: "[Error] \(err.toString())\n") result = false } return result } private func dumpSequence(string src: String, console cons: CNConsole) -> Bool { cons.print(string: "* dumpSequence\n") let result: Bool switch CNEscapeCode.decode(string: src) { case .ok(let codes): for code in codes { cons.print(string: code.description()) cons.print(string: "\n") } result = true case .error(let err): cons.print(string: "[Error] " + err.toString() + "\n") result = false } return result }
lgpl-2.1
e8fd43adbe094502efb7c8dd08b0a7d8
33.304
102
0.677006
3.155261
false
false
false
false
PureSwift/Bluetooth
Sources/BluetoothHCI/LowEnergyEvent.swift
1
3965
// // LowEnergyEvent.swift // Bluetooth // // Created by Alsey Coleman Miller on 3/2/16. // Copyright © 2016 PureSwift. All rights reserved. // /// Bluetooth Low Energy HCI Events @frozen public enum LowEnergyEvent: UInt8, HCIEvent { /// LE Connection Complete case connectionComplete = 0x01 /// LE Advertising Report case advertisingReport = 0x02 /// LE Connection Update Complete case connectionUpdateComplete = 0x03 /// LE Read Remote Used Features Complete case readRemoteUsedFeaturesComplete = 0x04 /// LE Long Term Key Request case longTermKeyRequest = 0x05 /// LE Remote Connection Parameter Request Event case remoteConnectionParameterRequest = 0x06 /// LE Data Length Change Event case dataLengthChange = 0x07 /// LE Read Local P-256 Public Key Complete Event case readLocalP256PublicKeyComplete = 0x08 /// LE Generate DHKey Complete Event case generateDHKeyComplete = 0x09 /// LE Enhanced Connection Complete Event case enhancedConnectionComplete = 0x0A /// LE Directed Advertising Report Event case directedAdvertisingReport = 0x0B /// LE PHY Update Complete Event case phyUpdateComplete = 0x0C /// LE Extended Advertising Report Event case extendedAdvertisingReport = 0x0D /// LE Periodic Advertising Sync Established Event case periodicAdvertisingSyncEstablished = 0x0E /// LE Periodic Advertising Report Event case periodicAdvertisingReport = 0x0F /// LE Periodic Advertising Sync Lost Event case periodicAdvertisingSyncLost = 0x10 /// LE Scan Timeout Event case scanTimeout = 0x11 /// LE Advertising Set Terminated Event case advertisingSetTerminated = 0x12 /// LE Scan Request Received Event case scanRequestReceived = 0x13 /// LE Channel Selection Algorithm Event case channelSelectionAlgorithm = 0x14 } // MARK: - Name public extension LowEnergyEvent { var name: String { switch self { case .connectionComplete: return "LE Connection Complete" case .advertisingReport: return "LE Advertising Report" case .connectionUpdateComplete: return "LE Connection Update Complete" case .readRemoteUsedFeaturesComplete: return "LE Read Remote Used Features Complete" case .longTermKeyRequest: return "LE Long Term Key Request" case .remoteConnectionParameterRequest: return "LE Remote Connection Parameter Request Event" case .dataLengthChange: return "LE Data Length Change Event" case .readLocalP256PublicKeyComplete: return "LE Read Local P-256 Public Key Complete Event" case .generateDHKeyComplete: return "LE Generate DHKey Complete Event" case .enhancedConnectionComplete: return "LE Enhanced Connection Complete" case .directedAdvertisingReport: return "LE Directed Advertising Report Event" case .phyUpdateComplete: return "LE PHY Update Complete" case .extendedAdvertisingReport: return "LE Extended Advertising Report Event" case .periodicAdvertisingSyncEstablished: return "LE Periodic Advertising Sync Established Event" case .periodicAdvertisingReport: return "LE Periodic Advertising Report Event" case .periodicAdvertisingSyncLost: return "LE Periodic Advertising Sync Lost Event" case .scanTimeout: return "LE Scan Timeout Event" case .advertisingSetTerminated: return "LE Advertising Set Terminated Event" case .scanRequestReceived: return "LE Scan Request Received Event" case .channelSelectionAlgorithm: return "LE Channel Selection Algorithm Event" } } }
mit
29cd2997a53d6340bce72d8df51fc982
37.485437
105
0.672553
5.114839
false
false
false
false
ansinlee/meteorology
meteorology/ProfTopicViewController.swift
1
6014
// // ProfBBSViewController.swift // meteorology // // Created by sunsing on 6/19/15. // Copyright (c) 2015 LeeAnsin. All rights reserved. // import UIKit class ProfTopicViewController: UITableViewController { var currentDataSource:[Topic] = [] var currentPage = 0 override func viewDidLoad() { super.viewDidLoad() // 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() loadListData(false) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() if tableView.respondsToSelector("layoutMargins") { self.tableView.layoutMargins = UIEdgeInsetsZero } self.tableView.separatorInset = UIEdgeInsetsZero } // MARK: load data func loadListData(readmore:Bool) { dispatch_async(dispatch_get_global_queue(0, 0)) { self.isLoading = true if !readmore { self.currentDataSource = [] self.currentPage = 0 } var url = NSURL(string:GetUrl("/topic?offset=\(PediaListProvider.pageSize*self.currentPage)&limit=\(PediaListProvider.pageSize)&query=creatorid:\(GetCurrentUser().Id!)")) //获取JSON数据 var data = NSData(contentsOfURL: url!, options: NSDataReadingOptions.DataReadingUncached, error: nil) if data != nil { var json:AnyObject = NSJSONSerialization.JSONObjectWithData(data!,options:NSJSONReadingOptions.AllowFragments,error:nil)! //解析获取JSON字段值 var errcode:NSNumber = json.objectForKey("errcode") as! NSNumber //json结构字段名。 var errmsg:String? = json.objectForKey("errmsg") as? String var retdata:NSArray? = json.objectForKey("data") as? NSArray NSLog("errcode:\(errcode) errmsg:\(errmsg) data:\(retdata)") if errcode == 0 && retdata != nil { var list = retdata! var len = list.count-1 for i in 0...len { var subject = Topic(data: list[i]) self.currentDataSource.append(subject) } self.currentPage++ } } dispatch_async(dispatch_get_main_queue()) { self.tableView.reloadData() self.isLoading = false } } } // MARK: scrollview delagate var isLoading = false override func scrollViewDidScroll(scrollView: UIScrollView) { //println("77777777 \(scrollView.contentSize.height - scrollView.frame.size.height): \(currentPage*10) \(self.currentDataSource.count) \(isLoading)") if scrollView == tableView && scrollView.contentSize.height - scrollView.frame.size.height > 0 && currentPage*PediaListProvider.pageSize == self.currentDataSource.count && !isLoading { if scrollView.contentOffset.y > scrollView.contentSize.height - scrollView.frame.size.height + 44 { self.loadListData(true) } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete method implementation. // Return the number of rows in the section. return self.currentDataSource.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("topiccell", forIndexPath: indexPath) as! UITableViewCell let topic = currentDataSource[indexPath.row] if topic.Creator == nil || topic.Creator!.Icon == nil { (cell.viewWithTag(1) as! UIImageView).image = UIImage(named: "default_icon") } else { dispatch_async(dispatch_get_global_queue(0, 0)) { var data = NSData(contentsOfURL: NSURL(string: topic.Creator!.Icon!)!) dispatch_async(dispatch_get_main_queue()) { if data != nil { (cell.viewWithTag(1) as! UIImageView).image = UIImage(data: data!) } else { (cell.viewWithTag(1) as! UIImageView).image = UIImage(named: "default_icon") } } } } (cell.viewWithTag(2) as! UILabel).text = topic.Creator?.Nick ?? "匿名用户" (cell.viewWithTag(3) as! UILabel).text = topic.Time (cell.viewWithTag(4) as! UILabel).text = topic.Title (cell.viewWithTag(5) as! UILabel).text = topic.Abstract return cell } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 120 } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.destinationViewController is BBSNewDetailViewController { if let desVC = segue.destinationViewController as? BBSNewDetailViewController { if let indexPath = tableView.indexPathForCell(sender as! UITableViewCell) { desVC.topic = currentDataSource[indexPath.row] } } } } override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { if cell.respondsToSelector("layoutMargins") { cell.layoutMargins = UIEdgeInsetsZero } } }
apache-2.0
d32ff7419e3ba74e9023879b28c14f67
42.275362
192
0.61152
5.170563
false
false
false
false
tardieu/swift
test/decl/protocol/req/optionality.swift
27
4913
// RUN: %target-typecheck-verify-swift @objc class C1 { } @objc class C2 { } // ------------------------------------------------------------------------ // Parameters of IUO type. // ------------------------------------------------------------------------ @objc protocol ParameterIUO1 { @objc optional func f0(_ x: C1!) } @objc class ParameterIUO1a : ParameterIUO1 { func f0(_ x: C1!) { } // okay: exact match } @objc class ParameterIUO1b : ParameterIUO1 { func f0(_ x: C1) { } // okay: all is permitted with IUO requirements } @objc class ParameterIUO1c : ParameterIUO1 { func f0(_ x: C1?) { } // okay: all is permitted with IUO requirements } // ------------------------------------------------------------------------ // Parameters of optional type. // ------------------------------------------------------------------------ @objc protocol ParameterOpt1 { @objc optional func f0(_ x: C1?) // expected-note 2{{declared here}} } @objc class ParameterOpt1a : ParameterOpt1 { func f0(_ x: C1?) { } // okay: exact match } @objc class ParameterOpt1b : ParameterOpt1 { func f0(_ x: C1!) { } // expected-warning{{different optionality than expected}}{{18-19=?}} } @objc class ParameterOpt1c : ParameterOpt1 { func f0(_ x: C1) { } // expected-error{{different optionality than required}}{{18-18=?}} } // ------------------------------------------------------------------------ // Parameters of non-optional type. // ------------------------------------------------------------------------ @objc protocol ParameterNonOpt1 { @objc optional func f0(_ x: C1) // expected-note 2{{declared here}} } @objc class ParameterNonOpt1a : ParameterNonOpt1 { func f0(_ x: C1) { } // okay: exact match } @objc class ParameterNonOpt1b : ParameterNonOpt1 { func f0(_ x: C1!) { } // expected-warning{{parameter of 'f0' has different optionality than expected by protocol 'ParameterNonOpt1'}}{{18-19=}} } @objc class ParameterNonOpt1c : ParameterNonOpt1 { func f0(_ x: C1?) { } // expected-warning{{parameter of 'f0' has different optionality than expected by protocol 'ParameterNonOpt1'}}{{18-19=}} } // ------------------------------------------------------------------------ // Result of IUO type. // ------------------------------------------------------------------------ @objc protocol ResultIUO1 { @objc optional func f0() -> C1! } @objc class ResultIUO1a : ResultIUO1 { func f0() -> C1! { return nil } // okay: exact match } @objc class ResultIUO1b : ResultIUO1 { func f0() -> C1 { } // okay: all is permitted with IUO requirements } @objc class ResultIUO1c : ResultIUO1 { func f0() -> C1? { } // okay: all is permitted with IUO requirements } // ------------------------------------------------------------------------ // Result of optional type. // ------------------------------------------------------------------------ @objc protocol ResultOpt1 { @objc optional func f0() -> C1? // expected-note 2{{declared here}} } @objc class ResultOpt1a : ResultOpt1 { func f0() -> C1? { return nil } // okay: exact match } @objc class ResultOpt1b : ResultOpt1 { func f0() -> C1 { } // expected-warning{{different optionality}}{{18-18=?}} } @objc class ResultOpt1c : ResultOpt1 { func f0() -> C1! { } // expected-warning{{different optionality}}{{18-19=?}} } // ------------------------------------------------------------------------ // Result of non-optional type. // ------------------------------------------------------------------------ @objc protocol ResultNonOpt1 { @objc optional func f0() -> C1 // expected-note 2 {{declared here}} } @objc class ResultNonOpt1a : ResultNonOpt1 { func f0() -> C1 { } // okay: exact match } @objc class ResultNonOpt1b : ResultNonOpt1 { func f0() -> C1? { } // expected-error{{different optionality than required}}{{18-19=}} } @objc class ResultNonOpt1c : ResultNonOpt1 { func f0() -> C1! { } // expected-warning{{different optionality}}{{18-19=}} } // ------------------------------------------------------------------------ // Multiple parameter mismatches // ------------------------------------------------------------------------ @objc protocol MultiParamsOpt1 { @objc optional func f0(_ x: C1?, y: C1) // expected-note{{here}} } @objc class MultiParamsOpt1a : MultiParamsOpt1 { func f0(_ x: C1!, y: C1!) { } // expected-warning{{parameters of 'f0(_:y:)' have different optionality than expected}}{{18-19=?}}{{26-27=}} } // ------------------------------------------------------------------------ // Parameter and result type mismatches // ------------------------------------------------------------------------ @objc protocol ParamAndResult1 { @objc optional func f0(_ x: C1?) -> C1 // expected-note{{here}} } @objc class ParamAndResult1a : ParamAndResult1 { func f0(_ x: C1!) -> C1! { } // expected-warning{{result and parameters of 'f0' have different optionality than expected}}{{18-19=?}}{{26-27=}} }
apache-2.0
9af88f4fc7057845c2251fd5b68e903b
33.843972
145
0.505801
4.030353
false
false
false
false