repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
pietrocaselani/Trakt-Swift
refs/heads/master
Trakt/Models/Base/StandardMediaEntity.swift
unlicense
1
public class StandardMediaEntity: Codable, Hashable { public var title: String? public var overview: String? public var rating: Double? public var votes: Int? public var updatedAt: Date? public var translations: [String]? private enum CodingKeys: String, CodingKey { case title case overview case rating case votes case updatedAt = "updated_at" case translations = "available_translations" } public init(title: String?, overview: String?, rating: Double?, votes: Int?, updatedAt: Date?, translations: [String]?) { self.title = title self.overview = overview self.rating = rating self.votes = votes self.updatedAt = updatedAt self.translations = translations } public required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.title = try container.decodeIfPresent(String.self, forKey: .title) self.overview = try container.decodeIfPresent(String.self, forKey: .overview) self.rating = try container.decodeIfPresent(Double.self, forKey: .rating) self.votes = try container.decodeIfPresent(Int.self, forKey: .votes) self.translations = try container.decodeIfPresent([String].self, forKey: .translations) let updatedAt = try container.decodeIfPresent(String.self, forKey: .updatedAt) self.updatedAt = TraktDateTransformer.dateTimeTransformer.transformFromJSON(updatedAt) } public var hashValue: Int { var hash = 0 if let titleHash = title?.hashValue { hash = hash ^ titleHash } if let overviewHash = overview?.hashValue { hash = hash ^ overviewHash } if let ratingHash = rating?.hashValue { hash = hash ^ ratingHash } if let votesHash = votes?.hashValue { hash = hash ^ votesHash } if let updatedAtHash = updatedAt?.hashValue { hash = hash ^ updatedAtHash } translations?.forEach { hash = hash ^ $0.hashValue } return hash } public static func == (lhs: StandardMediaEntity, rhs: StandardMediaEntity) -> Bool { return lhs.hashValue == rhs.hashValue } }
449af8d9b4f7c365914d545cac5b900c
28.366197
123
0.704556
false
false
false
false
itanchao/TCRunloopView
refs/heads/master
Example/TCRunloopView/ViewController.swift
mit
1
// // ViewController.swift // TCRunloopView // // Created by itanchao on 05/03/2017. // Copyright (c) 2017 itanchao. All rights reserved. // import UIKit import TCRunloopView class ViewController: UIViewController,TCRunLoopViewDelegate,UITableViewDelegate { var runView : TCRunLoopView? override func viewDidLoad() { super.viewDidLoad() let runloopView = TCRunLoopView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 400)) runView = runloopView runloopView.delegate = self view.addSubview(runloopView) let urlArray = ["http://ww1.sinaimg.cn/mw1024/473df571jw1f2aq06o3ltj20qo0ur79o.jpg","http://ww3.sinaimg.cn/mw1024/473df571jw1f24p6b71lhj20m80m841x.jpg","http://ww2.sinaimg.cn/mw1024/473df571jw1f1p8u1kf0hj20q50yvn3z.jpg","http://ww3.sinaimg.cn/mw1024/473df571jw1f17waawibmj20rs15o1kx.jpg","http://ww2.sinaimg.cn/mw1024/473df571jw1f0s5nq609zg20ku0kutbg.gif"] runloopView.loopDataGroup = urlArray.map{ (url) in LoopData(image:url,des:url) } } /// MARK:RunLoopSwiftViewDelegate /// /// - parameter loopView: loopView /// - parameter index: 选择的index func runLoopViewDidClick(_ loopView: TCRunLoopView, didSelectRowAtIndex index: NSInteger) { print("选择了第"+index.description+"张") loopView.loopInterval = Double(index.description)! } func runLoopViewDidScroll(_ loopView: TCRunLoopView, didScrollRowAtIndex index: NSInteger) { print("现在是"+index.description+"张") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
a7a0300282e39b066d0628b294313caa
37.044444
364
0.696846
false
false
false
false
xwu/swift
refs/heads/master
test/Concurrency/Runtime/async_task_cancellation_while_running.swift
apache-2.0
1
// RUN: %target-run-simple-swift( -Xfrontend -disable-availability-checking %import-libdispatch -parse-as-library) | %FileCheck %s // REQUIRES: executable_test // REQUIRES: concurrency // REQUIRES: libdispatch // rdar://76038845 // REQUIRES: concurrency_runtime // UNSUPPORTED: back_deployment_runtime import Dispatch let seconds: UInt64 = 1_000_000_000 @available(SwiftStdlib 5.5, *) func test_detach_cancel_while_child_running() async { let task: Task<Bool, Error> = Task.detached { async let childCancelled: Bool = { () -> Bool in await Task.sleep(3 * seconds) return Task.isCancelled }() let childWasCancelled = await childCancelled print("child, cancelled: \(childWasCancelled)") // CHECK: child, cancelled: true let selfWasCancelled = Task.isCancelled print("self, cancelled: \(selfWasCancelled )") // CHECK: self, cancelled: true return selfWasCancelled } // sleep here, i.e. give the task a moment to start running await Task.sleep(2 * seconds) task.cancel() print("task.cancel()") let got = try! await task.get() print("was cancelled: \(got)") // CHECK: was cancelled: true } @available(SwiftStdlib 5.5, *) func test_cancel_while_withTaskCancellationHandler_inflight() async { let task: Task<Bool, Error> = Task.detached { await withTaskCancellationHandler { await Task.sleep(2 * seconds) print("operation-1") await Task.sleep(1 * seconds) print("operation-2") return Task.isCancelled } onCancel: { print("onCancel") } } await Task.sleep(1 * seconds) // CHECK: task.cancel() // CHECK: onCancel // CHECK: operation-1 // CHECK: operation-2 print("task.cancel()") task.cancel() let got = try! await task.get() print("was cancelled: \(got)") // CHECK: was cancelled: true } @available(SwiftStdlib 5.5, *) func test_cancel_while_withTaskCancellationHandler_onlyOnce() async { let task: Task<Bool, Error> = Task.detached { await withTaskCancellationHandler { await Task.sleep(2 * seconds) await Task.sleep(2 * seconds) await Task.sleep(2 * seconds) print("operation-done") return Task.isCancelled } onCancel: { print("onCancel") } } await Task.sleep(1 * seconds) // CHECK: task.cancel() // CHECK: onCancel // onCancel runs only once, even though we attempt to cancel the task many times // CHECK-NEXT: operation-done print("task.cancel()") task.cancel() task.cancel() task.cancel() let got = try! await task.get() print("was cancelled: \(got)") // CHECK: was cancelled: true } @available(SwiftStdlib 5.5, *) @main struct Main { static func main() async { await test_detach_cancel_while_child_running() await test_cancel_while_withTaskCancellationHandler_inflight() await test_cancel_while_withTaskCancellationHandler_onlyOnce() } }
754ba1216f1762e03273c8846a07aaa1
27.39604
130
0.67887
false
true
false
false
cafielo/iOS_BigNerdRanch_5th
refs/heads/master
Chap14_Homepwner_bronze_silver_gold/Homepwner/DetailViewController.swift
mit
1
// // DetailViewController.swift // Homepwner // // Created by Joonwon Lee on 8/6/16. // Copyright © 2016 Joonwon Lee. All rights reserved. // import UIKit class DetailViewController: UIViewController { @IBOutlet weak var nameField: UITextField! @IBOutlet weak var serialNumberField: UITextField! @IBOutlet weak var valueField: UITextField! @IBOutlet weak var dateLabel: UILabel! @IBOutlet var imageView: UIImageView! @IBOutlet weak var cameraOverlayView: UIView! var item: Item! { didSet { navigationItem.title = item.name } } var imageStore: ImageStore! let numberFormatter: NSNumberFormatter = { let formatter = NSNumberFormatter() formatter.numberStyle = .DecimalStyle formatter.minimumFractionDigits = 2 formatter.maximumFractionDigits = 2 return formatter }() let dateFormatter: NSDateFormatter = { let formatter = NSDateFormatter() formatter.dateStyle = .MediumStyle formatter.timeStyle = .NoStyle return formatter }() override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) nameField.text = item.name serialNumberField.text = item.serialNumber valueField.text = numberFormatter.stringFromNumber(item.valueInDollars) dateLabel.text = dateFormatter.stringFromDate(item.dateCreated) //load image let key = item.itemKey let imageToDisplay = imageStore.imageForKey(key) imageView.image = imageToDisplay } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) view.endEditing(true) item.name = nameField.text ?? "" item.serialNumber = serialNumberField.text if let valueText = valueField.text, value = numberFormatter.numberFromString(valueText) { item.valueInDollars = value.integerValue } else { item.valueInDollars = 0 } valueField.text = numberFormatter.stringFromNumber(item.valueInDollars) dateLabel.text = dateFormatter.stringFromDate(item.dateCreated) } } //IBAction extension DetailViewController { @IBAction func takePicture(sender: UIBarButtonItem) { let imagePicker = UIImagePickerController() if UIImagePickerController.isSourceTypeAvailable(.Camera) { imagePicker.sourceType = .Camera } else { imagePicker.sourceType = .PhotoLibrary } imagePicker.delegate = self imagePicker.allowsEditing = true //camera view area has always same ratio 3:4 cameraOverlayView.frame = CGRectMake(0, 44, self.view.bounds.width, self.view.bounds.width * 4/3) imagePicker.cameraOverlayView = cameraOverlayView presentViewController(imagePicker, animated: true, completion: nil) } @IBAction func deleteImage(sender: UIBarButtonItem) { //delete image let key = item.itemKey imageView.image = nil imageStore.deleteImageForKey(key) } @IBAction func backgroundTapped(sender: UITapGestureRecognizer) { view.endEditing(true) } } extension DetailViewController: UINavigationControllerDelegate { } extension DetailViewController: UIImagePickerControllerDelegate { func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { // get selected image from info Dictionary let image = info[UIImagePickerControllerEditedImage] as! UIImage imageStore.setImage(image, forKey: item.itemKey) imageView.image = image //gotta dismiss imagepicker dismissViewControllerAnimated(true, completion: nil) } } extension DetailViewController: UITextFieldDelegate { func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true } }
0f3b71a3e10888e867a2d503a6996d47
29.510949
123
0.661722
false
false
false
false
arslanbilal/cryptology-project
refs/heads/master
Cryptology Project/Cryptology Project/Classes/Models/Realm/RealmUser.swift
mit
1
// // User.swift // Cryptology Project // // Created by Bilal Arslan on 17/03/16. // Copyright © 2016 Bilal Arslan. All rights reserved. // import Foundation import RealmSwift class RealmUser: Object { dynamic var id = 0 dynamic var name = "" dynamic var lastname = "" dynamic var username = "" dynamic var passwordSalt = "" dynamic var passwordHash = "" dynamic var isLocked = false dynamic var wrongAttemptCount = 0 dynamic var attemptableDate = NSDate() override static func primaryKey() -> String? { return "id" } class var userId: Int { let realm = try! Realm() let users: NSArray = Array(realm.objects(RealmUser).sorted("id")) let last = users.lastObject if users.count > 0 { let id = last?.valueForKey("id") as? Int return id! + 1 } else { return 1 } } func changePassword(password: String) { let realm = try! Realm() let salt = FBEncryptorAES.generateKey() let newHash = FBEncryptorAES.generateSHA512((password + salt)) try! realm.write { self.passwordSalt = salt self.passwordHash = newHash } } func checkPassword(password: String) -> Bool { let inputPasswordHash = FBEncryptorAES.generateSHA512((password + self.passwordSalt)) if self.passwordHash == inputPasswordHash { return true } return false } }
1740583c422d2e145eb61e200a9bf328
23.777778
93
0.570788
false
false
false
false
devpunk/cartesian
refs/heads/master
cartesian/Model/Store/Purchases/MStoreItemNodeHexagon.swift
mit
1
import UIKit class MStoreItemNodeHexagon:MStoreItem { private let kStorePurchaseId:MStore.PurchaseId = "iturbide.cartesian.nodeHexagon" init() { let title:String = NSLocalizedString("MStoreItemNodeHexagon_title", comment:"") let descr:String = NSLocalizedString("MStoreItemNodeHexagon_descr", comment:"") let image:UIImage = #imageLiteral(resourceName: "assetNodeHexagon") super.init( purchaseId:kStorePurchaseId, title:title, descr:descr, image:image) } override func purchaseAction() { MSession.sharedInstance.settings?.purchaseNodeHexagon = true DManager.sharedInstance?.save() } override func validatePurchase() -> Bool { guard let purchased:Bool = MSession.sharedInstance.settings?.purchaseNodeHexagon else { return false } return purchased } }
ba2fa5c316866ee44676acf3f32aa173
24.897436
87
0.6
false
false
false
false
ScoutHarris/WordPress-iOS
refs/heads/develop
WordPress/Classes/ViewRelated/People/RoleViewController.swift
gpl-2.0
2
import Foundation import UIKit import WordPressShared /// Displays a Person Role Picker /// class RoleViewController: UITableViewController { /// List of available roles. /// var roles: [RemoteRole] = [] /// Currently Selected Role /// var selectedRole: String! /// Closure to be executed whenever the selected role changes. /// var onChange: ((String) -> Void)? /// Activity Spinner, to be animated during Backend Interaction /// fileprivate let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .gray) // MARK: - View Lifecyle Methods override func viewDidLoad() { super.viewDidLoad() title = NSLocalizedString("Role", comment: "User Roles Title") setupActivityIndicator() WPStyleGuide.configureColors(for: view, andTableView: tableView) } // MARK: - Private Helpers fileprivate func setupActivityIndicator() { activityIndicator.translatesAutoresizingMaskIntoConstraints = false view.addSubview(activityIndicator) view.pinSubviewAtCenter(activityIndicator) } // MARK: - UITableView Methods override func numberOfSections(in tableView: UITableView) -> Int { return numberOfSections } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return roles.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: reusableIdentifier, for: indexPath) let roleForCurrentRow = roleAtIndexPath(indexPath) cell.textLabel?.text = roleForCurrentRow.name cell.accessoryType = (roleForCurrentRow.slug == selectedRole) ? .checkmark : .none WPStyleGuide.configureTableViewCell(cell) return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectSelectedRowWithAnimationAfterDelay(true) let roleForSelectedRow = roleAtIndexPath(indexPath) guard selectedRole != roleForSelectedRow.slug else { return } // Refresh Interface selectedRole = roleForSelectedRow.slug tableView.reloadDataPreservingSelection() // Callback onChange?(roleForSelectedRow.slug) _ = navigationController?.popViewController(animated: true) } // MARK: - Private Methods fileprivate func roleAtIndexPath(_ indexPath: IndexPath) -> RemoteRole { return roles[indexPath.row] } // MARK: - Private Constants fileprivate let numberOfSections = 1 fileprivate let reusableIdentifier = "roleCell" }
d64d2ce310b2ee13bf6e06d425197d36
29.865169
109
0.693484
false
false
false
false
nsagora/validation-toolkit
refs/heads/main
Sources/Constraints/AnyConstraint.swift
mit
1
import Foundation /** A type-erased `Constraint`. ```swift enum Failure: Error { case notEven } let constraint = BlockConstraint<Int, Failure> { $0 % 2 == 0 } errorBuilder: { .notEven } let anyConstraint = AnyConstraint(constraint) anyConstraint.evaluate(with: 3) ``` */ public struct AnyConstraint<T, E: Error>: Constraint { public typealias InputType = T public typealias ErrorType = E private let evaluate: (InputType) -> Result<Void, Summary<E>> /** Creates a type-erased `Constraint` that wraps the given instance. */ public init<C: Constraint>(_ constraint: C) where C.InputType == T, C.ErrorType == E { self.evaluate = constraint.evaluate } /** Evaluates the input against the receiver. - parameter input: The input to be validated. - returns: `.success` if the input is valid,`.failure` containing the `Summary` of the failing `Constraint`s otherwise. */ public func evaluate(with input: T) -> Result<Void, Summary<E>> { return evaluate(input) } } extension Constraint { /** Wraps this constraint with a type eraser. ```swift enum Failure: Error { case notEven } let constraint = BlockConstraint<Int, Failure> { $0 % 2 == 0 } errorBuilder: { .notEven } var erasedConstraint = constraint.erase() erasedConstraint.evaluate(with: 5) ``` - Returns: An `AnyConstraint` wrapping this constraint. */ public func erase() -> AnyConstraint<InputType, ErrorType> { return AnyConstraint(self) } }
737b2f7f79e21781981a7f79d188b961
22.183099
124
0.619077
false
false
false
false
ladanv/EmailNotifier
refs/heads/master
EmailNotifier/EmailEntity.swift
mit
1
// // EmailEntity.swift // EmailNotifier // // Created by Vitaliy.Ladan on 10.12.14. // Copyright (c) 2014 Vitaliy.Ladan. All rights reserved. // class EmailEntity: NSObject { var sender: String! var date: NSDate! var subject: String! var uid: UInt64! override init() { } init(message: MCOIMAPMessage) { super.init() self.initWithMessage(message) } func initWithMessage(message: MCOIMAPMessage) { if let sender = message.header?.sender?.displayName { self.sender = sender } else if let sender = message.header?.from?.displayName { self.sender = sender } else { self.sender = "No sender" } if let subject = message.header?.subject { self.subject = subject } else { self.subject = "No subject" } date = message.header.date uid = UInt64(message.uid) } }
2188368bfced20ae4c405f5a6df3f29f
23.589744
66
0.5683
false
false
false
false
anzfactory/QiitaCollection
refs/heads/master
QiitaCollection/BaseTableView.swift
mit
1
// // BaseTableView.swift // QiitaCollection // // Created by ANZ on 2015/02/20. // Copyright (c) 2015年 anz. All rights reserved. // import UIKit class BaseTableView: UITableView { typealias RefreshAction = () -> Void var total: Int = 0 var items: [EntityProtocol] = [EntityProtocol]() var page: Int = 1 var refreshControl: UIRefreshControl? = nil var refreshAction: RefreshAction? = nil override func awakeFromNib() { super.awakeFromNib() let dummy: UIView = UIView(frame: CGRect.zeroRect) self.tableFooterView = dummy } func setupRefreshControl(action: RefreshAction) { self.refreshControl = UIRefreshControl() self.refreshControl!.attributedTitle = NSAttributedString(string: "引っ張って更新") self.refreshControl!.addTarget(self, action: "refresh", forControlEvents: UIControlEvents.ValueChanged) self.addSubview(self.refreshControl!) } func refresh() { if let refresh = self.refreshControl { refresh.endRefreshing() } if let action = self.refreshAction { action() } } func loadedItems<T:EntityProtocol>(total: Int, items: [T], isAppendable: ((T) -> Bool)?) { if total == 0 && self.page == 1 { Toast.show("結果0件でした...", style: JFMinimalNotificationStytle.StyleWarning) return } self.total = total if items.count == 0 { self.page = NSNotFound // オートページング止めるために return } else if (self.page == 1) { // リフレッシュ対象なのでリストクリア self.items.removeAll(keepCapacity: false) } for item: T in items { if (isAppendable == nil || isAppendable!(item)) { self.items.append(item) } } self.page++ self.reloadData() } func loadedItems<T:EntityProtocol>(items: [T]) { if items.count == 0 && self.page == 1 { Toast.show("結果0件でした...", style: JFMinimalNotificationStytle.StyleWarning) return } self.total = self.items.count + items.count if items.count == 0 { self.page = NSNotFound // オートページング止めるために return } else if (self.page == 1) { // リフレッシュ対象なのでリストクリア self.items.removeAll(keepCapacity: false) } for item: T in items { self.items.append(item) } self.page++ self.reloadData() } func clearItems() { if self.items.count == 0 { return } self.items.removeAll(keepCapacity: false) self.reloadData() } }
29446c4edc1063c799ff8e71dd2d23a0
25.064815
111
0.54103
false
false
false
false
Automattic/Automattic-Tracks-iOS
refs/heads/trunk
Sources/Encrypted Logs/ExponentialBackoffTimer.swift
gpl-2.0
1
import Foundation struct ExponentialBackoffTimer { /// The current amount of delay, in seconds private(set) var delay: Int /// The current exponent private var exponent: Int = 1 /// Keep a copy of the initial delay to allow reset private let initialDelay: Int = 0 /// The minimum allowed delay private let minimumDelay: Int /// The maximum allowed delay private let maximumDelay: Int /// Create a backoff timer with an optional initial duration. /// /// - Parameters: /// - minimumDelay: The smallest possible delay (specified in seconds). Must be greater than one. /// - maximumDelay: The largest possible delay (specified in seconds). Must be greater than one, and greater than the initial delay. /// The default is approximately one day. init(minimumDelay: Int = 2, maximumDelay: Int = 86_400) { precondition(minimumDelay > 1, "The initial delay must be greater than 1 – otherwise it will never increase") precondition(maximumDelay > minimumDelay, "The limit must be greater than the initial delay") precondition(maximumDelay < Int32.max / 2, "The limit must be less than Int32.max / 2 to avoid overflow") self.delay = initialDelay self.minimumDelay = minimumDelay self.maximumDelay = maximumDelay } /// Exponentially increase the delay (up to `maximumDelay`) mutating func increment() { delay = Int(pow(Double(minimumDelay), Double(exponent))) exponent += 1 if delay > maximumDelay { delay = maximumDelay } next = .now() + .seconds(delay) nextDate = Date(timeIntervalSinceNow: TimeInterval(delay)) } /// Reset the delay to zero mutating func reset() { delay = initialDelay self.next = .now() self.nextDate = Date() } /// A `DispatchTime` compatible with `DispatchQueue.asyncAfter` that represents the next time the timer should fire. private(set) internal var next: DispatchTime = .now() /// A `Date` representation of `next`. private(set) var nextDate: Date = Date() }
aa45399b49aa0d792f528bc927a0a790
34.766667
138
0.656104
false
false
false
false
pavankataria/SwiftDataTables
refs/heads/master
SwiftDataTables/Classes/Cells/MenuLengthHeader/MenuLengthHeaderViewModel.swift
mit
1
// // MenuLengthHeaderViewModel.swift // SwiftDataTables // // Created by Pavan Kataria on 03/03/2017. // Copyright © 2017 Pavan Kataria. All rights reserved. // import Foundation import UIKit class MenuLengthHeaderViewModel: NSObject { //MARK: - Events var searchTextFieldDidChangeEvent: ((String) -> Void)? = nil } extension MenuLengthHeaderViewModel: CollectionViewSupplementaryElementRepresentable { static func registerHeaderFooterViews(collectionView: UICollectionView) { let identifier = String(describing: MenuLengthHeader.self) let headerNib = UINib(nibName: identifier, bundle: nil) collectionView.register(headerNib, forCellWithReuseIdentifier: identifier) } func dequeueView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, for indexPath: IndexPath) -> UICollectionReusableView { let identifier = String(describing: MenuLengthHeader.self) guard let headerView = collectionView.dequeueReusableSupplementaryView( ofKind: kind, withReuseIdentifier: identifier, for: indexPath ) as? MenuLengthHeader else { return UICollectionReusableView() } headerView.configure(self) return headerView } } extension MenuLengthHeaderViewModel { @objc func textFieldDidChange(textField: UITextField){ guard let text = textField.text else { return } self.searchTextFieldDidChangeEvent?(text) } } extension MenuLengthHeaderViewModel: UISearchBarDelegate { }
852269f21b06572fb3366856d730b925
29.925926
158
0.68024
false
false
false
false
VirrageS/TDL
refs/heads/master
TDL/SlideNavigationController.swift
mit
1
import UIKit import QuartzCore let DEBUG: Bool = false let MENU_SLIDE_ANIMATION_DURATION: NSTimeInterval = 0.3 let MENU_QUICK_SLIDE_ANIMATION_DURATION: NSTimeInterval = 0.18 let MENU_SHADOW_RADIUS: CGFloat = 5 let MENU_SHADOW_OPACITY: Float = 1 let MENU_DEFAULT_SLIDE_OFFSET: CGFloat = 60.0 let MENU_FAST_VELOCITY_FOR_SWIPE_FOLLOW_DIRECTION = 1200 var singletonInstance: SlideNavigationController? var bar: UINavigationBar? @objc protocol SlideNavigationControllerDelegate { optional func shouldDisplayMenu() -> Bool } class SlideNavigationController: UINavigationController, UINavigationControllerDelegate, UIGestureRecognizerDelegate { enum PopType { case PopTypeAll case PopTypeRoot } var avoidSwitchingToSameClassViewController: Bool = false var _enableSwipeGesture: Bool? var enableShadow: Bool? let portraitSlideOffset: CGFloat = MENU_DEFAULT_SLIDE_OFFSET let landscapeSlideOffset: CGFloat = MENU_DEFAULT_SLIDE_OFFSET let panGestureSideOffset: CGFloat = MENU_DEFAULT_SLIDE_OFFSET var _delegate: SlideNavigationControllerDelegate? var menu: UIViewController? var lastRevealedMenu: UIViewController? var _tapRecognizer: UITapGestureRecognizer? var _panRecognizer: UIPanGestureRecognizer? var draggingPoint: CGPoint! = CGPoint(x: 0, y: 0) var leftBarButtonItem: UIBarButtonItem? var _menuRevealAnimator: SlideNavigationControllerAnimatorSlide? convenience init() { self.init(nibName: nil, bundle: nil) if DEBUG { println("init called") } if singletonInstance == nil { singletonInstance = self } // // if bar == nil { // bar = self.navigationBar // } // self.navigationBar.bounds.origin = CGPoint(x: -10, y: 0) avoidSwitchingToSameClassViewController = true setEnableSwipeGesture(true) setEnableShadow(true) delegate = self } func sharedInstance() -> SlideNavigationController { if singletonInstance == nil { println("\(singletonInstance) SlideNavigationController has not been initialized. Either place one in your storyboard or initialize one in code") } return singletonInstance! } // func initWithRootViewController(rootViewController: UIViewController) -> AnyObject! { // return self; // } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() // Update shadow size of enabled if (enableShadow != nil) { if enableShadow! { view.layer.shadowPath = UIBezierPath(rect: view.bounds).CGPath } } } override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) { super.willRotateToInterfaceOrientation(toInterfaceOrientation, duration: duration) enableTapGestureToCloseMenu(false) view.layer.shadowOpacity = 0 } override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) { super.didRotateFromInterfaceOrientation(fromInterfaceOrientation) updateMenuFrameAndTransformAccordingToOrientation() view.layer.shadowPath = UIBezierPath(rect: view.bounds).CGPath view.layer.shadowOpacity = MENU_SHADOW_OPACITY } func switchToViewController(viewController: UIViewController, slideOutAnimation: Bool, poptype: PopType, completion: (Bool) -> Void) { if DEBUG { println("switchToViewController step #1 called") } if avoidSwitchingToSameClassViewController && topViewController == viewController { closeMenuWithCompletion(completion) return } let switchAndCallCompletion = { (closeMenuBeforeCallingCompletion: Bool) -> () in if poptype == PopType.PopTypeAll { self.setViewControllers([viewController], animated: false) } else { // #TODO // self.popToRootViewControllerAnimated(false) self.pushViewController(viewController, animated: false) } if closeMenuBeforeCallingCompletion { self.closeMenuWithCompletion(completion) } } if DEBUG { println("switchToViewController step #2 called") } if isMenuOpen() { if slideOutAnimation { UIView.animateWithDuration(MENU_SLIDE_ANIMATION_DURATION, delay: 0, options: UIViewAnimationOptions.CurveEaseOut, animations: { () -> Void in var width: CGFloat = self.horizontalSize() var moveLocation: CGFloat = self.horizontalLocation() > 0 ? width : width*(-1) self.moveHorizontallyToLocation(moveLocation) }, completion: { (Bool) -> Void in switchAndCallCompletion(true) }) } else { switchAndCallCompletion(true) } } else { switchAndCallCompletion(false) } if DEBUG { println("switchToViewController step #3 called") } } func switchToViewController(viewController: UIViewController, completion: (Bool) -> Void) { switchToViewController(viewController, slideOutAnimation: true, poptype: PopType.PopTypeRoot, completion: completion) } func popToRootAndSwitchToViewController(viewController: UIViewController, slideOutAnimation: Bool, completion: (Bool) -> Void) { switchToViewController(viewController, slideOutAnimation: slideOutAnimation, poptype: PopType.PopTypeRoot, completion: completion) } func popToRootAndSwitchToViewController(viewController: UIViewController, completion: (Bool) -> Void) { switchToViewController(viewController, slideOutAnimation: true, poptype: PopType.PopTypeRoot, completion: completion) } func popAllAndSwitchToViewController(viewController: UIViewController, slideOutAnimation: Bool, completion: (Bool) -> Void) { switchToViewController(viewController, slideOutAnimation: slideOutAnimation, poptype: PopType.PopTypeAll, completion: completion) } func popAllAndSwitchToViewController(viewController: UIViewController, completion: (Bool) -> Void) { switchToViewController(viewController, slideOutAnimation: true, poptype: PopType.PopTypeAll, completion: completion) } func closeMenuWithCompletion(completion: (Bool) -> Void) { closeMenuWithDuration(MENU_SLIDE_ANIMATION_DURATION, completion: completion) } func openMenu(completion: (Bool) -> Void) { openMenu(MENU_SLIDE_ANIMATION_DURATION, completion: completion) } func isMenuOpen() -> Bool { return horizontalLocation() == 0 ? false : true; } func setEnableShadow(enable: Bool) { enableShadow = enable if enable { view.layer.shadowColor = UIColor.darkGrayColor().CGColor view.layer.shadowRadius = MENU_SHADOW_RADIUS view.layer.shadowOpacity = MENU_SHADOW_OPACITY view.layer.shadowPath = UIBezierPath(rect: view.bounds).CGPath view.layer.shouldRasterize = true; view.layer.rasterizationScale = UIScreen.mainScreen().scale } else { view.layer.shadowOpacity = 0; view.layer.shadowRadius = 0; } } override func popToRootViewControllerAnimated(animated: Bool) -> [AnyObject]? { if isMenuOpen() { closeMenuWithCompletion({ (Bool) -> Void in self.popToRootViewControllerAnimated(animated) return }) } else { return super.popToRootViewControllerAnimated(animated) } return nil; } override func pushViewController(viewController: UIViewController, animated: Bool) { if isMenuOpen() { closeMenuWithCompletion({ (Bool) -> Void in self.pushViewController(viewController, animated: animated) }) } else { super.pushViewController(viewController, animated: animated) } } override func popToViewController(viewController: UIViewController, animated: Bool) -> [AnyObject]? { if isMenuOpen() { closeMenuWithCompletion({ (Bool) -> Void in self.popToViewController(viewController, animated: animated) return }) } else { return popToViewController(viewController, animated: animated) } return nil } func updateMenuFrameAndTransformAccordingToOrientation() { let transform: CGAffineTransform = view.transform menu!.view.transform = transform menu!.view.frame = initialRectForMenu() } func enableTapGestureToCloseMenu(enable: Bool) { if enable { interactivePopGestureRecognizer.enabled = false topViewController.view.userInteractionEnabled = false view.addGestureRecognizer(tapRecognizer()) } else { interactivePopGestureRecognizer.enabled = true topViewController.view.userInteractionEnabled = true view.removeGestureRecognizer(tapRecognizer()) } } func toggleMenu(completion: (Bool) -> Void) { if DEBUG { println("toggleMenu called") } if isMenuOpen() { closeMenuWithCompletion(completion) } else { openMenu(completion) } } func barButtonItemForMenu() -> UIBarButtonItem { let selector: Selector = "leftMenuSelected:" var customButton: UIBarButtonItem? = leftBarButtonItem if customButton != nil { customButton!.action = selector customButton!.target = self return customButton! } else { let image: UIImage = UIImage(named: "menu-button")! return UIBarButtonItem(image: image, style: UIBarButtonItemStyle.Plain, target: self, action: selector) } } func shouldDisplayMenu(vc: UIViewController) -> Bool { if DEBUG { println("shouldDisplayMenu called") } if let check = _delegate?.shouldDisplayMenu!() { if DEBUG { print(check) } return check } return true } func openMenu(duration: NSTimeInterval, completion: (Bool) -> Void) { if DEBUG { println("openMenu called") } enableTapGestureToCloseMenu(true) prepareMenuForReveal() UIView.animateWithDuration(duration, delay: 0, options: UIViewAnimationOptions.CurveEaseOut, animations: { () -> Void in var rect: CGRect = self.view.frame var width: CGFloat = self.horizontalSize() rect.origin.x = width - self.slideOffset() self.moveHorizontallyToLocation(rect.origin.x) }, completion: completion ) } func closeMenuWithDuration(duration: NSTimeInterval, completion: (Bool) -> Void) { enableTapGestureToCloseMenu(false) UIView.animateWithDuration(duration, delay: 0, options: UIViewAnimationOptions.CurveEaseOut, animations: {() -> Void in var rect: CGRect = self.view.frame rect.origin.x = 0 self.moveHorizontallyToLocation(rect.origin.x) }, completion: completion ) } func moveHorizontallyToLocation(location: CGFloat) { var rect: CGRect = self.view.frame let orientation: UIDeviceOrientation = UIDevice.currentDevice().orientation if orientation.isLandscape { rect.origin.x = 0 rect.origin.y = location } else { rect.origin.x = location rect.origin.y = 0 } view.frame = rect updateMenuAnimation() } func updateMenuAnimation() { var progress: CGFloat = horizontalLocation() / (horizontalSize() - slideOffset()) _menuRevealAnimator?.animateMenu(progress) } func initialRectForMenu() -> CGRect { var rect: CGRect = view.frame rect.origin.x = 0 rect.origin.y = 0 return rect; } func prepareMenuForReveal() { if lastRevealedMenu != nil { if lastRevealedMenu == menu { return } } lastRevealedMenu = menu view.window?.insertSubview(menu!.view, atIndex: 0) // view.window?.insertSubview(bar!, atIndex: 1) // .navigationBar.topItem.title = "Hello" // navigationItem.title = "lol" updateMenuFrameAndTransformAccordingToOrientation() _menuRevealAnimator?.prepareMenuForAnimation() } func horizontalLocation() -> CGFloat { var rect: CGRect = view.frame let orientation: UIDeviceOrientation = UIDevice.currentDevice().orientation if orientation.isLandscape { return rect.origin.y } else { return rect.origin.x } } func horizontalSize() -> CGFloat { var rect: CGRect = view.frame let orientation: UIDeviceOrientation = UIDevice.currentDevice().orientation if orientation.isLandscape { return rect.size.height } else { return rect.size.width } } func navigationController(navigationController: UINavigationController, willShowViewController viewController: UIViewController, animated: Bool) { if DEBUG { println("navigationController called") } if shouldDisplayMenu(viewController) { viewController.navigationItem.leftBarButtonItem = barButtonItemForMenu() if DEBUG { println("leftButtonSet called") } } } func slideOffset() -> CGFloat { return UIDevice.currentDevice().orientation.isLandscape ? landscapeSlideOffset : portraitSlideOffset } func leftMenuSelected(sender: AnyObject) { if DEBUG { println("leftMenuSelected called") } if isMenuOpen() { if DEBUG { println("leftMenuSelected -> isMenuOpen -> true -> called") } closeMenuWithCompletion({ (Bool) -> Void in }) } else { if DEBUG { println("leftMenuSelected -> isMenuOpen -> false -> called") } openMenu({ (Bool) -> Void in }) } } func tapDetected(tapRecognizer: UITapGestureRecognizer) { closeMenuWithCompletion({ (Bool) -> Void in }) } func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool { if panGestureSideOffset == 0 { return true } var pointInView: CGPoint = touch.locationInView(view) return (pointInView.x <= panGestureSideOffset || pointInView.x >= horizontalSize() - panGestureSideOffset) } func panDetected(aPanRecognizer: UIPanGestureRecognizer) { var translation: CGPoint = aPanRecognizer.translationInView(aPanRecognizer.view!) var velocity: CGPoint = aPanRecognizer.velocityInView(aPanRecognizer.view) var movement: CGFloat = translation.x - draggingPoint.x if aPanRecognizer.state == UIGestureRecognizerState.Began { draggingPoint = translation } else if aPanRecognizer.state == UIGestureRecognizerState.Changed { var lastHorizontalLocation: CGFloat = 0 var newHorizontalLocation: CGFloat = horizontalLocation() lastHorizontalLocation = newHorizontalLocation newHorizontalLocation += movement if newHorizontalLocation >= CGFloat(minXForDragging()) && newHorizontalLocation <= CGFloat(maxXForDragging()) { moveHorizontallyToLocation(newHorizontalLocation) } draggingPoint = translation } else if aPanRecognizer.state == UIGestureRecognizerState.Ended { var currentX: CGFloat = horizontalLocation() var currentXOffset = (currentX > 0) ? currentX : currentX*(-1) var possitiveVelocity = (velocity.x > 0) ? velocity.x : velocity.x*(-1) if possitiveVelocity >= CGFloat(MENU_FAST_VELOCITY_FOR_SWIPE_FOLLOW_DIRECTION) { if currentX > 0 { closeMenuWithDuration(MENU_QUICK_SLIDE_ANIMATION_DURATION, completion: { (Bool) -> Void in }) } else { if shouldDisplayMenu(self.visibleViewController) { openMenu(MENU_QUICK_SLIDE_ANIMATION_DURATION , completion: { (Bool) -> Void in }) } } } else { if currentXOffset < (self.horizontalSize() - self.slideOffset())/2 { closeMenuWithCompletion({ (Bool) -> Void in }) } else { openMenu({ (Bool) -> Void in }) } } } } func minXForDragging() -> Int { return 0 } func maxXForDragging() -> Int { return Int(horizontalSize()) - Int(slideOffset()) } func tapRecognizer() -> UITapGestureRecognizer { if !(_tapRecognizer != nil) { _tapRecognizer = UITapGestureRecognizer(target: self, action: "tapDetected:") } return _tapRecognizer! } func panRecognizer() -> UIPanGestureRecognizer { if DEBUG { println("panRecognizer called") } if !(_panRecognizer != nil) { _panRecognizer = UIPanGestureRecognizer(target: self, action: "panDetected:") _panRecognizer!.delegate = self } return _panRecognizer! } func setEnableSwipeGesture(markEnableSwipeGesture: Bool) { _enableSwipeGesture = markEnableSwipeGesture if (_enableSwipeGesture != nil) { self.view.addGestureRecognizer(panRecognizer()) } else { self.view.removeGestureRecognizer(panRecognizer()) } } func setMenuRevealAnimator(menuRevealAnimator: SlideNavigationControllerAnimatorSlide) { menuRevealAnimator.setInstance(singletonInstance!) menuRevealAnimator.clear() _menuRevealAnimator = menuRevealAnimator } }
14f89b7cf18c681e83621d36038d3053
34.255597
157
0.615177
false
false
false
false
lojals/DoorsConcept
refs/heads/master
DoorConcept/Controllers/Doors/DoorsTableViewController.swift
mit
1
// // BuildingsTableViewController.swift // DoorConcept // // Created by Jorge Raul Ovalle Zuleta on 3/18/16. // Copyright © 2016 jorgeovalle. All rights reserved. // import UIKit import SESlideTableViewCell import DZNEmptyDataSet class DoorsTableViewController: UITableViewController { @IBOutlet weak var btnAdd: UIBarButtonItem! let doorInteractor = DoorsInteractor() var doors:[Door] = [Door]() var building:Building! override func viewDidLoad() { self.tableView.emptyDataSetDelegate = self self.tableView.emptyDataSetSource = self } override func viewWillAppear(animated: Bool) { loadDoors() } /** Check if the actual instance contains a building (Detail view), and then load the buildings */ func loadDoors(){ if building != nil{ doorInteractor.getDoorsByBuilding(building) { (data, error) -> Void in if error == nil{ self.doors = data as! [Door] self.tableView.reloadData() }else{ print(error) } } if building.owner == UserService.sharedInstance.currentUser{ btnAdd.enabled = true }else{ btnAdd.enabled = false } }else{ doorInteractor.getDoors({ (data, error) -> Void in if error == nil{ self.doors = data as! [Door] self.tableView.reloadData() }else{ print(error) } }) btnAdd.enabled = false } } /** redirect to AddDoorsViewController - parameter sender: event sender => UIButton */ @IBAction func AddDoor(sender: AnyObject) { let addDoorView = self.storyboard?.instantiateViewControllerWithIdentifier("AddDoorsViewController") as! AddDoorsViewController addDoorView.building = self.building self.navigationController?.pushViewController(addDoorView, animated: true) } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.doors.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("DoorCell", forIndexPath: indexPath) as! DoorsTableViewCell cell.delegate = self cell.tag = indexPath.row cell.configureCellWithDoor(doors[indexPath.row]) return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let doorDefault = DoorDetailViewController() doorDefault.door = doors[indexPath.row] self.navigationController?.showViewController(doorDefault, sender: self) } } // MARK: - SESlideTableViewCellDelegate // Handle the delete event (dragging left on the cells) extension DoorsTableViewController:SESlideTableViewCellDelegate{ func slideTableViewCell(cell: SESlideTableViewCell!, didTriggerRightButton buttonIndex: Int) { doorInteractor.deleteDoor(doors[cell.tag]) self.loadDoors() } } // MARK: - DZNEmptyDataSetSource,DZNEmptyDataSetDelegate // Style for empty state extension DoorsTableViewController:DZNEmptyDataSetSource,DZNEmptyDataSetDelegate{ func imageForEmptyDataSet(scrollView: UIScrollView!) -> UIImage! { return UIImage(named: "empty_doors") } func titleForEmptyDataSet(scrollView: UIScrollView!) -> NSAttributedString! { let str = "Oops!!" let infoStr = NSMutableAttributedString(string: str) infoStr.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(18, weight: 0.7), range: NSMakeRange(0, str.characters.count)) infoStr.addAttribute(NSForegroundColorAttributeName, value: UIColor.DCThemeColorMain(), range: NSMakeRange(0, str.characters.count)) return infoStr as NSAttributedString } func descriptionForEmptyDataSet(scrollView: UIScrollView!) -> NSAttributedString! { let str = "There’s no doors yet, add a new one\nclicking in the + button, only if you're the building's owner." let infoStr = NSMutableAttributedString(string: str) infoStr.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(14, weight: 0.1), range: NSMakeRange(0, str.characters.count)) infoStr.addAttribute(NSForegroundColorAttributeName, value: UIColor.DCThemeColorMain(), range: NSMakeRange(0, str.characters.count)) return infoStr as NSAttributedString } func backgroundColorForEmptyDataSet(scrollView: UIScrollView!) -> UIColor! { return UIColor.whiteColor() } func emptyDataSetShouldFadeIn(scrollView: UIScrollView!) -> Bool { return true } }
58e704d86c56e1f536732ef0848b0af0
36.007246
143
0.65942
false
false
false
false
PureSwift/LittleCMS
refs/heads/master
Sources/LittleCMS/ToneCurve.swift
mit
1
// // ToneCurve.swift // LittleCMS // // Created by Alsey Coleman Miller on 6/3/17. // // import CLCMS public final class ToneCurve { // MARK: - Properties internal let internalPointer: OpaquePointer // MARK: - Initialization deinit { // deallocate profile cmsFreeToneCurve(internalPointer) } internal init(_ internalPointer: OpaquePointer) { self.internalPointer = internalPointer } public init?(gamma: Double, context: Context? = nil) { guard let internalPointer = cmsBuildGamma(context?.internalPointer, gamma) else { return nil } self.internalPointer = internalPointer } // MARK: - Accessors public var isLinear: Bool { return cmsIsToneCurveLinear(internalPointer) != 0 } } // MARK: - Internal Protocols extension ToneCurve: DuplicableHandle { static var cmsDuplicate: cmsDuplicateFunction { return cmsDupToneCurve } }
fcf66b2cc8abb685ff6c5681ee810280
19.54
82
0.615385
false
false
false
false
CybercomPoland/CPLKeyboardManager
refs/heads/master
Example/Source/TableViewController.swift
mit
1
// // TableViewController.swift // CPLKeyboardManager // // Created by Michal Zietera on 17.03.2017. // Copyright © 2017 CocoaPods. All rights reserved. // import UIKit import CPLKeyboardManager private enum CellProperties: Int { case TextField = 0 case Label case TextView func getHeight() -> CGFloat { switch self { case .TextField, .Label: return 44 case .TextView: return 220 } } func reuseId() -> String { switch self { case .TextField: return "tableViewCellWithTextField" case .Label: return "tableViewCell" case .TextView: return "tableViewCellWithTextView" } } } class TableViewController: UIViewController, UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate, UITextViewDelegate { @IBOutlet weak var tableView: UITableView! var keyboardManager: CPLKeyboardManager? override func viewDidLoad() { super.viewDidLoad() keyboardManager = CPLKeyboardManager(tableView: tableView, inViewController: self) tableView.delegate = self // tableView.estimatedRowHeight = 44 tableView.rowHeight = UITableViewAutomaticDimension } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) keyboardManager?.start() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) keyboardManager?.stop() } func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { //tableView.rowHeight = UITableViewAutomaticDimension } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { // return UITableViewAutomaticDimension let modulo = indexPath.row % 3 return CellProperties(rawValue: modulo)?.getHeight() ?? 44.0 // if modulo == 0 { // return 44.0 // } else if modulo == 1 { // return 44.0 // } else if modulo == 2 { // return 200.0 // } // return 44.0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var reusableId: String let modulo = indexPath.row % 3 if modulo == 0 { reusableId = "tableViewCellWithTextField" } else if modulo == 1 { reusableId = "tableViewCell" } else { reusableId = "tableViewCellWithTextView" } let cell = tableView.dequeueReusableCell(withIdentifier: reusableId)! if modulo == 1 { cell.textLabel?.text = "Cell number \(indexPath.row) sdkjsak sajd kakdkaskd kaksdkaskdkak dkakdak kdakaks kakk dkaskdkasdk kk kaskdka kdkas kdakskask kas " } else { (cell as? TextViewTableViewCell)?.textView.delegate = self } return cell } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 22 } func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) { searchBar.showsCancelButton = true } func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { searchBar.resignFirstResponder() searchBar.showsCancelButton = false } func textViewDidChange(_ textView: UITextView) { let currentOffset = tableView.contentOffset UIView.setAnimationsEnabled(false) tableView.beginUpdates() tableView.endUpdates() UIView.setAnimationsEnabled(true) tableView.setContentOffset(currentOffset, animated: false) } }
d84aa6a81b5b476639b742b8abbb76cb
28.578125
167
0.642895
false
false
false
false
turingcorp/gattaca
refs/heads/master
gattaca/View/Home/VHomeActionsCell.swift
mit
1
import UIKit class VHomeActionsCell:UICollectionViewCell { private weak var background:UIImageView! private weak var icon:UIImageView! override init(frame:CGRect) { super.init(frame:frame) clipsToBounds = true backgroundColor = UIColor.clear let background:UIImageView = UIImageView() background.clipsToBounds = true background.contentMode = UIViewContentMode.center background.translatesAutoresizingMaskIntoConstraints = false background.isUserInteractionEnabled = false self.background = background let icon:UIImageView = UIImageView() icon.isUserInteractionEnabled = false icon.clipsToBounds = true icon.contentMode = UIViewContentMode.center icon.translatesAutoresizingMaskIntoConstraints = false self.icon = icon addSubview(background) addSubview(icon) NSLayoutConstraint.equals( view:background, toView:self) NSLayoutConstraint.equals( view:icon, toView:self) } required init?(coder:NSCoder) { return nil } override var isSelected:Bool { didSet { hover() } } override var isHighlighted:Bool { didSet { hover() } } //MARK: private func hover() { if isSelected || isHighlighted { background.image = #imageLiteral(resourceName: "assetGenericActionOn") icon.tintColor = UIColor.colourBackgroundDark } else { background.image = #imageLiteral(resourceName: "assetGenericActionOff") icon.tintColor = UIColor.white } } //MARK: internal func config(model:MHomeActionProtocol) { icon.image = model.icon.withRenderingMode( UIImageRenderingMode.alwaysTemplate) hover() } }
ac3fe2dd2912f55a7489b542cf1c5bbf
22.883721
83
0.581792
false
false
false
false
Antidote-for-Tox/Antidote
refs/heads/develop
Antidote/LoginCreateAccountController.swift
mit
2
// 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 UIKit protocol LoginCreateAccountControllerDelegate: class { func loginCreateAccountControllerCreate(_ controller: LoginCreateAccountController, name: String, profile: String) func loginCreateAccountControllerImport(_ controller: LoginCreateAccountController, profile: String) } class LoginCreateAccountController: LoginGenericCreateController { enum ControllerType { case createAccount case importProfile } weak var delegate: LoginCreateAccountControllerDelegate? fileprivate let type: ControllerType init(theme: Theme, type: ControllerType) { self.type = type super.init(theme: theme) } required convenience init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func configureViews() { firstTextField.title = String(localized: "create_account_username_title") firstTextField.placeholder = String(localized: "create_account_username_placeholder") firstTextField.maxTextUTF8Length = Int(kOCTToxMaxNameLength) secondTextField.title = String(localized: "create_account_profile_title") secondTextField.placeholder = String(localized: "create_account_profile_placeholder") secondTextField.hint = String(localized: "create_account_profile_hint") secondTextField.returnKeyType = .next bottomButton.setTitle(String(localized: "create_account_next_button"), for: UIControlState()) switch type { case .createAccount: titleLabel.text = String(localized: "create_profile") case .importProfile: titleLabel.text = String(localized: "import_profile") firstTextField.isHidden = true } } override func bottomButtonPressed() { let profile = secondTextField.text ?? "" guard !profile.isEmpty else { UIAlertController.showWithTitle(String(localized: "login_enter_username_and_profile"), message: nil, retryBlock: nil) return } guard !ProfileManager().allProfileNames.contains(profile) else { UIAlertController.showWithTitle(String(localized: "login_profile_already_exists"), message: nil, retryBlock: nil) return } switch type { case .createAccount: let name = firstTextField.text ?? "" guard !name.isEmpty else { UIAlertController.showWithTitle(String(localized: "login_enter_username_and_profile"), message: nil, retryBlock: nil) return } delegate?.loginCreateAccountControllerCreate(self, name: name, profile: profile) case .importProfile: delegate?.loginCreateAccountControllerImport(self, profile: profile) } } }
08b3b5b008f0947dfd701a44c047de2d
37.3
137
0.670366
false
false
false
false
Holmusk/HMRequestFramework-iOS
refs/heads/master
HMRequestFramework/database/coredata/model/HMCDTextSearchRequest.swift
apache-2.0
1
// // HMCDTextSearchRequest.swift // HMRequestFramework // // Created by Hai Pham on 25/10/17. // Copyright © 2017 Holmusk. All rights reserved. // import CoreData import SwiftUtilities /// This class provides the necessary parameters for a CoreData text search /// request. public struct HMCDTextSearchRequest { public enum Comparison { case beginsWith case contains fileprivate func comparison() -> String { switch self { case .beginsWith: return "BEGINSWITH" case .contains: return "CONTAINS" } } } public enum Modifier { case caseInsensitive case diacriticInsensitive fileprivate func modifier() -> String { switch self { case .caseInsensitive: return "c" case .diacriticInsensitive: return "d" } } } fileprivate var pKey: String? fileprivate var pValue: String? fileprivate var pComparison: Comparison? fileprivate var pModifiers: [Modifier] fileprivate init() { pModifiers = [] } } public extension HMCDTextSearchRequest { /// Get the predicate to perform a text search. /// /// - Returns: A NSPredicate instance. /// - Throws: Exception if arguments are not available. public func textSearchPredicate() throws -> NSPredicate { guard let key = self.pKey, let value = self.pValue, let comparison = self.pComparison else { throw Exception("Some arguments are nil") } let modifiers = self.pModifiers.map({$0.modifier()}) let modifierString = modifiers.isEmpty ? "" : "[\(modifiers.joined(separator: ""))]" let format = "%K \(comparison.comparison())\(modifierString) %@" return NSPredicate(format: format, key, value) } } extension HMCDTextSearchRequest: HMBuildableType { public static func builder() -> Builder { return Builder() } public final class Builder { fileprivate var request: Buildable fileprivate init() { request = Buildable() } /// Set the request key. /// /// - Parameter key: A String value. /// - Returns: The current Builder instance. @discardableResult public func with(key: String?) -> Self { request.pKey = key return self } /// Set the request value. /// /// - Parameter value: A String value. /// - Returns: The current Builder instance. @discardableResult public func with(value: String?) -> Self { request.pValue = value return self } /// Set the request comparison. /// /// - Parameter comparison: A Comparison instance. /// - Returns: The current Builder instance. @discardableResult public func with(comparison: Comparison?) -> Self { request.pComparison = comparison return self } /// Add request modifiers. /// /// - Parameter modifiers: A Sequence of request modifiers. /// - Returns: The current Builder instance. @discardableResult public func add<S>(modifiers: S) -> Self where S: Sequence, S.Element == Modifier { request.pModifiers.append(contentsOf: modifiers) return self } /// Set the request modifiers. /// /// - Parameter modifiers: A Sequence of Modifier. /// - Returns: The current Builder instance. @discardableResult public func with<S>(modifiers: S) -> Self where S: Sequence, S.Element == Modifier { request.pModifiers.removeAll() return self.add(modifiers: modifiers) } /// Add a request modifier. /// /// - Parameter modifier: A Modifier instance. /// - Returns: The current Builder instance. @discardableResult public func add(modifier: Modifier) -> Self { request.pModifiers.append(modifier) return self } } } extension HMCDTextSearchRequest.Builder: HMBuilderType { public typealias Buildable = HMCDTextSearchRequest @discardableResult public func with(buildable: Buildable?) -> Self { if let buildable = buildable { return self .with(key: buildable.pKey) .with(value: buildable.pValue) .with(comparison: buildable.pComparison) .with(modifiers: buildable.pModifiers) } else { return self } } public func build() -> Buildable { return request } }
311710631a4a94556e93c378aea291dd
27.709302
75
0.558526
false
false
false
false
wesj/firefox-ios-1
refs/heads/master
Client/Frontend/Browser/SearchEngines.swift
mpl-2.0
1
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared let DefaultSearchEngineName = "Yahoo" private let OrderedEngineNames = "search.orderedEngineNames" private let DisabledEngineNames = "search.disabledEngineNames" private let ShowSearchSuggestionsOptIn = "search.suggestions.showOptIn" private let ShowSearchSuggestions = "search.suggestions.show" /** * Manage a set of Open Search engines. * * The search engines are ordered. Individual search engines can be enabled and disabled. The * first search engine is distinguished and labeled the "default" search engine; it can never be * disabled. Search suggestions should always be sourced from the default search engine. * * Two additional bits of information are maintained: whether the user should be shown "opt-in to * search suggestions" UI, and whether search suggestions are enabled. * * Consumers will almost always use `defaultEngine` if they want a single search engine, and * `quickSearchEngines()` if they want a list of enabled quick search engines (possibly empty, * since the default engine is never included in the list of enabled quick search engines, and * it is possible to disable every non-default quick search engine). * * The search engines are backed by a write-through cache into a ProfilePrefs instance. This class * is not thread-safe -- you should only access it on a single thread (usually, the main thread)! */ class SearchEngines { let prefs: Prefs init(prefs: Prefs) { self.prefs = prefs // By default, show search suggestions opt-in and don't show search suggestions automatically. self.shouldShowSearchSuggestionsOptIn = prefs.boolForKey(ShowSearchSuggestionsOptIn) ?? true self.shouldShowSearchSuggestions = prefs.boolForKey(ShowSearchSuggestions) ?? false self.disabledEngineNames = getDisabledEngineNames() self.orderedEngines = getOrderedEngines() } var defaultEngine: OpenSearchEngine { get { return self.orderedEngines[0] } set(defaultEngine) { // The default engine is always enabled. self.enableEngine(defaultEngine) // The default engine is always first in the list. var orderedEngines = self.orderedEngines.filter({ engine in engine.shortName != defaultEngine.shortName }) orderedEngines.insert(defaultEngine, atIndex: 0) self.orderedEngines = orderedEngines } } func isEngineDefault(engine: OpenSearchEngine) -> Bool { return defaultEngine.shortName == engine.shortName } // The keys of this dictionary are used as a set. private var disabledEngineNames: [String: Bool]! { didSet { self.prefs.setObject(self.disabledEngineNames.keys.array, forKey: DisabledEngineNames) } } var orderedEngines: [OpenSearchEngine]! { didSet { self.prefs.setObject(self.orderedEngines.map({ (engine) in engine.shortName }), forKey: OrderedEngineNames) } } var quickSearchEngines: [OpenSearchEngine]! { get { return self.orderedEngines.filter({ (engine) in !self.isEngineDefault(engine) && self.isEngineEnabled(engine) }) } } var shouldShowSearchSuggestionsOptIn: Bool { didSet { self.prefs.setObject(shouldShowSearchSuggestionsOptIn, forKey: ShowSearchSuggestionsOptIn) } } var shouldShowSearchSuggestions: Bool { didSet { self.prefs.setObject(shouldShowSearchSuggestions, forKey: ShowSearchSuggestions) } } func isEngineEnabled(engine: OpenSearchEngine) -> Bool { return disabledEngineNames.indexForKey(engine.shortName) == nil } func enableEngine(engine: OpenSearchEngine) { disabledEngineNames.removeValueForKey(engine.shortName) } func disableEngine(engine: OpenSearchEngine) { if isEngineDefault(engine) { // Can't disable default engine. return } disabledEngineNames[engine.shortName] = true } private func getDisabledEngineNames() -> [String: Bool] { if let disabledEngineNames = self.prefs.stringArrayForKey(DisabledEngineNames) { var disabledEngineDict = [String: Bool]() for engineName in disabledEngineNames { disabledEngineDict[engineName] = true } return disabledEngineDict } else { return [String: Bool]() } } // Get all known search engines, with the default search engine first, but the others in no // particular order. class func getUnorderedEngines() -> [OpenSearchEngine] { var error: NSError? let path = NSBundle.mainBundle().resourcePath?.stringByAppendingPathComponent("Locales/en-US/searchplugins") if path == nil { println("Error: Could not find search engine directory") return [] } let directory = NSFileManager.defaultManager().contentsOfDirectoryAtPath(path!, error: &error) if error != nil { println("Could not fetch search engines") return [] } var engines = [OpenSearchEngine]() let parser = OpenSearchParser(pluginMode: true) for file in directory! { let fullPath = path!.stringByAppendingPathComponent(file as String) let engine = parser.parse(fullPath) engines.append(engine!) } return engines.sorted({ e, _ in e.shortName == DefaultSearchEngineName }) } // Get all known search engines, possibly as ordered by the user. private func getOrderedEngines() -> [OpenSearchEngine] { let unorderedEngines = SearchEngines.getUnorderedEngines() if let orderedEngineNames = prefs.stringArrayForKey(OrderedEngineNames) { var orderedEngines = [OpenSearchEngine]() for engineName in orderedEngineNames { for engine in unorderedEngines { if engine.shortName == engineName { orderedEngines.append(engine) } } } return orderedEngines } else { // We haven't persisted the engine order, so return whatever order we got from disk. return unorderedEngines } } }
7836292670d203894756bba56c9181e0
37.729412
119
0.663882
false
false
false
false
SomeSimpleSolutions/MemorizeItForever
refs/heads/Development
MemorizeItForeverCore/MemorizeItForeverCoreTests/Helper/Helper.swift
mit
1
// // Helper.swift // MemorizeItForeverCore // // Created by Hadi Zamani on 11/18/16. // Copyright © 2016 SomeSimpleSolutions. All rights reserved. // import Foundation var resultKey = 0 var setNumberKey = 1 var setNameKey = 2 var setIdKey = 3 var phraseKey = 4 var meaningKey = 5 var statusKey = 6 var orderKey = 7 var wordIdKey = 8 var columnKey = 9 var dateKey = 10 var wordIdInProgressKey = 11 var columnNoKey = 12 var wordKey = 13 var wordHistoryCountKey = 13 class Helper { static func methodSwizzling(_ cls: Swift.AnyClass!, origin: Selector!, swizzled: Selector!){ let originalMethod = class_getInstanceMethod(cls, origin) let swizzledMethod = class_getInstanceMethod(cls, swizzled) method_exchangeImplementations(originalMethod!, swizzledMethod!) } }
1120f19f5b699cbd3b33cd49df140f4e
22.764706
96
0.720297
false
false
false
false
Rahulclaritaz/rahul
refs/heads/master
ixprez/ixprez/Pulsator.swift
mit
1
// // Pulsator.swift // Pulsator // // Created by Shuichi Tsutsumi on 4/9/16. // Copyright © 2016 Shuichi Tsutsumi. All rights reserved. // // Objective-C version: https://github.com/shu223/PulsingHalo import UIKit import QuartzCore internal let kPulsatorAnimationKey = "pulsator" open class Pulsator: CAReplicatorLayer, CAAnimationDelegate { fileprivate let pulse = CALayer() fileprivate var animationGroup: CAAnimationGroup! fileprivate var alpha: CGFloat = 0.45 override open var backgroundColor: CGColor? { didSet { pulse.backgroundColor = backgroundColor guard let backgroundColor = backgroundColor else {return} let oldAlpha = alpha alpha = backgroundColor.alpha if alpha != oldAlpha { recreate() } } } override open var repeatCount: Float { didSet { if let animationGroup = animationGroup { animationGroup.repeatCount = repeatCount } } } // MARK: - Public Properties /// The number of pulse. open var numPulse: Int = 1 { didSet { if numPulse < 1 { numPulse = 1 } instanceCount = numPulse updateInstanceDelay() } } /// The radius of pulse. open var radius: CGFloat = 60 { didSet { updatePulse() } } /// The animation duration in seconds. open var animationDuration: TimeInterval = 3 { didSet { updateInstanceDelay() } } /// If this property is `true`, the instanse will be automatically removed /// from the superview, when it finishes the animation. open var autoRemove = false /// fromValue for radius /// It must be smaller than 1.0 open var fromValueForRadius: Float = 0.0 { didSet { if fromValueForRadius >= 1.0 { fromValueForRadius = 0.0 } recreate() } } /// The value of this property should be ranging from @c 0 to @c 1 (exclusive). open var keyTimeForHalfOpacity: Float = 0.2 { didSet { recreate() } } /// The animation interval in seconds. open var pulseInterval: TimeInterval = 0 /// A function describing a timing curve of the animation. open var timingFunction: CAMediaTimingFunction? = CAMediaTimingFunction(name: kCAMediaTimingFunctionDefault) { didSet { if let animationGroup = animationGroup { animationGroup.timingFunction = timingFunction } } } /// The value of this property showed a pulse is started open var isPulsating: Bool { guard let keys = pulse.animationKeys() else {return false} return keys.count > 0 } /// private properties for resuming fileprivate weak var prevSuperlayer: CALayer? fileprivate var prevLayerIndex: Int? // MARK: - Initializer override public init() { super.init() setupPulse() instanceDelay = 1 repeatCount = MAXFLOAT backgroundColor = UIColor( red: 0, green: 0.455, blue: 0.756, alpha: 0.45).cgColor NotificationCenter.default.addObserver(self, selector: #selector(save), name: NSNotification.Name.UIApplicationDidEnterBackground, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(resume), name: NSNotification.Name.UIApplicationWillEnterForeground, object: nil) } override public init(layer: Any) { super.init(layer: layer) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { NotificationCenter.default.removeObserver(self) } // MARK: - Private Methods fileprivate func setupPulse() { pulse.contentsScale = UIScreen.main.scale pulse.opacity = 0 addSublayer(pulse) updatePulse() } fileprivate func setupAnimationGroup() { let scaleAnimation = CABasicAnimation(keyPath: "transform.scale.xy") scaleAnimation.fromValue = fromValueForRadius scaleAnimation.toValue = 1.0 scaleAnimation.duration = animationDuration let opacityAnimation = CAKeyframeAnimation(keyPath: "opacity") opacityAnimation.duration = animationDuration opacityAnimation.values = [alpha, alpha * 0.5, 0.0] opacityAnimation.keyTimes = [0.0, NSNumber(value: keyTimeForHalfOpacity), 1.0] animationGroup = CAAnimationGroup() animationGroup.animations = [scaleAnimation, opacityAnimation] animationGroup.duration = animationDuration + pulseInterval animationGroup.repeatCount = repeatCount if let timingFunction = timingFunction { animationGroup.timingFunction = timingFunction } animationGroup.delegate = self } fileprivate func updatePulse() { let diameter: CGFloat = radius * 2 pulse.bounds = CGRect( origin: CGPoint.zero, size: CGSize(width: diameter, height: diameter)) pulse.cornerRadius = radius pulse.backgroundColor = backgroundColor } fileprivate func updateInstanceDelay() { guard numPulse >= 1 else { fatalError() } instanceDelay = (animationDuration + pulseInterval) / Double(numPulse) } fileprivate func recreate() { guard animationGroup != nil else { return } // Not need to be recreated. stop() let when = DispatchTime.now() + Double(Int64(0.2 * double_t(NSEC_PER_SEC))) / Double(NSEC_PER_SEC) DispatchQueue.main.asyncAfter(deadline: when) { () -> Void in self.start() } } // MARK: - Internal Methods internal func save() { prevSuperlayer = superlayer prevLayerIndex = prevSuperlayer?.sublayers?.index(where: {$0 === self}) } internal func resume() { if let prevSuperlayer = prevSuperlayer, let prevLayerIndex = prevLayerIndex { prevSuperlayer.insertSublayer(self, at: UInt32(prevLayerIndex)) } if pulse.superlayer == nil { addSublayer(pulse) } let isAnimating = pulse.animation(forKey: kPulsatorAnimationKey) != nil // if the animationGroup is not nil, it means the animation was not stopped if let animationGroup = animationGroup, !isAnimating { pulse.add(animationGroup, forKey: kPulsatorAnimationKey) } } // MARK: - Public Methods /// Start the animation. open func start() { setupPulse() setupAnimationGroup() pulse.add(animationGroup, forKey: kPulsatorAnimationKey) } /// Stop the animation. open func stop() { pulse.removeAllAnimations() animationGroup = nil } // MARK: - Delegate methods for CAAnimation public func animationDidStop(_ anim: CAAnimation, finished flag: Bool) { if let keys = pulse.animationKeys(), keys.count > 0 { pulse.removeAllAnimations() } pulse.removeFromSuperlayer() if autoRemove { removeFromSuperlayer() } } }
4c531fae588fd87a2bdb9147d0371428
29.928
114
0.584454
false
false
false
false
Zewo/HTTP
refs/heads/master
Modules/HTTP/Sources/HTTP/Middleware/ContentNegotiationMiddleware/ContentNegotiatonMiddleware.swift
mit
3
public enum ContentNegotiationMiddlewareError : Error { case noSuitableParser case noSuitableSerializer case writerBodyNotSupported } public struct ContentNegotiationMiddleware : Middleware { public enum Mode { case server case client } public enum SerializationMode { case buffer case stream } private let converters: [MediaTypeConverter] private let mediaTypes: [MediaType] private let mode: Mode private let serializationMode: SerializationMode public init(mediaTypes: [MediaTypeConverter], mode: Mode = .server, serializationMode: SerializationMode = .stream) { self.converters = mediaTypes self.mediaTypes = converters.map({$0.mediaType}) self.mode = mode self.serializationMode = serializationMode } public func respond(to request: Request, chainingTo chain: Responder) throws -> Response { switch mode { case .server: return try serverRespond(to: request, chainingTo: chain) case .client: return try clientRespond(to: request, chainingTo: chain) } } private func serverRespond(to request: Request, chainingTo chain: Responder) throws -> Response { var request = request if let contentType = request.contentType, !request.body.isEmpty { do { let content: Map switch request.body { case .buffer(let buffer): content = try parse(buffer: buffer, mediaType: contentType) case .reader(let stream): content = try parse(stream: stream, deadline: .never, mediaType: contentType) case .writer: // TODO: Deal with writer bodies throw ContentNegotiationMiddlewareError.writerBodyNotSupported } request.content = content } catch ContentNegotiationMiddlewareError.noSuitableParser { throw HTTPError.unsupportedMediaType } } var response = try chain.respond(to: request) if let content = response.content { let mediaTypes: [MediaType] if let contentType = response.contentType { mediaTypes = [contentType] } else { mediaTypes = request.accept.isEmpty ? self.mediaTypes : request.accept } response.content = nil switch serializationMode { case .buffer: let (mediaType, buffer) = try serializeToBuffer(from: content, mediaTypes: mediaTypes) response.contentType = mediaType // TODO: Maybe add `willSet` to `body` and configure the headers there response.transferEncoding = nil response.contentLength = buffer.count response.body = .buffer(buffer) case .stream: let (mediaType, writer) = try serializeToStream(from: content, deadline: .never, mediaTypes: mediaTypes) response.contentType = mediaType // TODO: Maybe add `willSet` to `body` and configure the headers there response.contentLength = nil response.transferEncoding = "chunked" response.body = .writer(writer) } } return response } private func clientRespond(to request: Request, chainingTo chain: Responder) throws -> Response { var request = request request.accept = mediaTypes if let content = request.content { let mediaTypes: [MediaType] if let contentType = request.contentType { mediaTypes = [contentType] } else { mediaTypes = self.mediaTypes } request.content = nil switch serializationMode { case .buffer: let (mediaType, buffer) = try serializeToBuffer(from: content, mediaTypes: mediaTypes) request.contentType = mediaType // TODO: Maybe add `willSet` to `body` and configure the headers there request.transferEncoding = nil request.contentLength = buffer.count request.body = .buffer(buffer) case .stream: let (mediaType, writer) = try serializeToStream(from: content, deadline: .never, mediaTypes: mediaTypes) request.contentType = mediaType // TODO: Maybe add `willSet` to `body` and configure the headers there request.contentLength = nil request.transferEncoding = "chunked" request.body = .writer(writer) } } var response = try chain.respond(to: request) if let contentType = response.contentType { let content: Map switch response.body { case .buffer(let buffer): content = try parse(buffer: buffer, mediaType: contentType) case .reader(let stream): content = try parse(stream: stream, deadline: .never, mediaType: contentType) case .writer: // TODO: Deal with writer bodies throw ContentNegotiationMiddlewareError.writerBodyNotSupported } response.content = content } return response } private func parserTypes(for mediaType: MediaType) -> [MapParser.Type] { var parsers: [MapParser.Type] = [] for converter in converters where converter.mediaType.matches(other: mediaType) { parsers.append(converter.parser) } return parsers } private func firstParserType(for mediaType: MediaType) throws -> MapParser.Type { guard let first = parserTypes(for: mediaType).first else { throw ContentNegotiationMiddlewareError.noSuitableParser } return first } private func serializerTypes(for mediaType: MediaType) -> [(MediaType, MapSerializer.Type)] { var serializers: [(MediaType, MapSerializer.Type)] = [] for converter in converters where converter.mediaType.matches(other: mediaType) { serializers.append(converter.mediaType, converter.serializer) } return serializers } private func firstSerializerType(for mediaType: MediaType) throws -> (MediaType, MapSerializer.Type) { guard let first = serializerTypes(for: mediaType).first else { throw ContentNegotiationMiddlewareError.noSuitableSerializer } return first } private func parse(stream: InputStream, deadline: Double, mediaType: MediaType) throws -> Map { let parserType = try firstParserType(for: mediaType) do { return try parserType.parse(stream, deadline: deadline) } catch { throw ContentNegotiationMiddlewareError.noSuitableParser } } private func parse(buffer: Buffer, mediaType: MediaType) throws -> Map { var lastError: Error? for parserType in parserTypes(for: mediaType) { do { return try parserType.parse(buffer) } catch { lastError = error continue } } if let lastError = lastError { throw lastError } else { throw ContentNegotiationMiddlewareError.noSuitableParser } } private func serializeToStream(from content: Map, deadline: Double, mediaTypes: [MediaType]) throws -> (MediaType, (OutputStream) throws -> Void) { for acceptedType in mediaTypes { for (mediaType, serializerType) in serializerTypes(for: acceptedType) { return (mediaType, { stream in try serializerType.serialize(content, stream: stream, deadline: deadline) }) } } throw ContentNegotiationMiddlewareError.noSuitableSerializer } private func serializeToBuffer(from content: Map, mediaTypes: [MediaType]) throws -> (MediaType, Buffer) { var lastError: Error? for acceptedType in mediaTypes { for (mediaType, serializerType) in serializerTypes(for: acceptedType) { do { let buffer = try serializerType.serialize(content) return (mediaType, buffer) } catch { lastError = error continue } } } if let lastError = lastError { throw lastError } else { throw ContentNegotiationMiddlewareError.noSuitableSerializer } } }
4c588643bb97276ed8920026a3124e62
34.487903
152
0.593001
false
false
false
false
ABTSoftware/SciChartiOSTutorial
refs/heads/master
v2.x/Examples/SciChartSwiftDemo/SciChartSwiftDemo/Views/CreateMultiseriesChart/StackedColumnChartView.swift
mit
1
//****************************************************************************** // SCICHART® Copyright SciChart Ltd. 2011-2018. All rights reserved. // // Web: http://www.scichart.com // Support: [email protected] // Sales: [email protected] // // StackedColumnChartView.swift is part of the SCICHART® Examples. Permission is hereby granted // to modify, create derivative works, distribute and publish any part of this source // code whether for commercial, private or personal use. // // The SCICHART® examples are distributed in the hope that they will be useful, but // without any warranty. It is provided "AS IS" without warranty of any kind, either // expressed or implied. //****************************************************************************** class StackedColumnChartView: SingleChartLayout { override func initExample() { let xAxis = SCINumericAxis() let yAxis = SCINumericAxis() let porkData = [10, 13, 7, 16, 4, 6, 20, 14, 16, 10, 24, 11] let vealData = [12, 17, 21, 15, 19, 18, 13, 21, 22, 20, 5, 10] let tomatoesData = [7, 30, 27, 24, 21, 15, 17, 26, 22, 28, 21, 22] let cucumberData = [16, 10, 9, 8, 22, 14, 12, 27, 25, 23, 17, 17] let pepperData = [7, 24, 21, 11, 19, 17, 14, 27, 26, 22, 28, 16] let ds1 = SCIXyDataSeries(xType: .double, yType: .double) ds1.seriesName = "Pork Series" let ds2 = SCIXyDataSeries(xType: .double, yType: .double) ds2.seriesName = "Veal Series" let ds3 = SCIXyDataSeries(xType: .double, yType: .double) ds3.seriesName = "Tomato Series" let ds4 = SCIXyDataSeries(xType: .double, yType: .double) ds4.seriesName = "Cucumber Series" let ds5 = SCIXyDataSeries(xType: .double, yType: .double) ds5.seriesName = "Pepper Series" let data = 1992 for i in 0..<porkData.count { let xValue = data + i; ds1.appendX(SCIGeneric(xValue), y: SCIGeneric(porkData[i])) ds2.appendX(SCIGeneric(xValue), y: SCIGeneric(vealData[i])) ds3.appendX(SCIGeneric(xValue), y: SCIGeneric(tomatoesData[i])) ds4.appendX(SCIGeneric(xValue), y: SCIGeneric(cucumberData[i])) ds5.appendX(SCIGeneric(xValue), y: SCIGeneric(pepperData[i])) } let verticalCollection1 = SCIVerticallyStackedColumnsCollection() verticalCollection1.add(getRenderableSeriesWith(dataSeries: ds1, fillColor: 0xff226fb7)) verticalCollection1.add(getRenderableSeriesWith(dataSeries: ds2, fillColor: 0xffff9a2e)) let verticalCollection2 = SCIVerticallyStackedColumnsCollection() verticalCollection2.add(getRenderableSeriesWith(dataSeries: ds3, fillColor: 0xffdc443f)) verticalCollection2.add(getRenderableSeriesWith(dataSeries: ds4, fillColor: 0xffaad34f)) verticalCollection2.add(getRenderableSeriesWith(dataSeries: ds5, fillColor: 0xff8562b4)) let columnCollection = SCIHorizontallyStackedColumnsCollection() columnCollection.add(verticalCollection1) columnCollection.add(verticalCollection2) let xDragModifier = SCIXAxisDragModifier() xDragModifier.clipModeX = .none let yDragModifier = SCIYAxisDragModifier() yDragModifier.dragMode = .pan SCIUpdateSuspender.usingWithSuspendable(surface) { self.surface.xAxes.add(xAxis) self.surface.yAxes.add(yAxis) self.surface.renderableSeries.add(columnCollection) self.surface.chartModifiers = SCIChartModifierCollection(childModifiers: [xDragModifier, yDragModifier, SCIPinchZoomModifier(), SCIZoomExtentsModifier(), SCIRolloverModifier()]) columnCollection.addAnimation(SCIWaveRenderableSeriesAnimation(duration: 3, curveAnimation: .easeOut)) } } fileprivate func getRenderableSeriesWith(dataSeries: SCIXyDataSeries, fillColor: uint) -> SCIStackedColumnRenderableSeries { let renderableSeries = SCIStackedColumnRenderableSeries() renderableSeries.dataSeries = dataSeries renderableSeries.fillBrushStyle = SCISolidBrushStyle(colorCode: fillColor) renderableSeries.strokeStyle = nil return renderableSeries } }
e94ab48e2fab57ee07f5f69173a3effc
48.62069
189
0.653695
false
false
false
false
tkester/swift-algorithm-club
refs/heads/master
Shunting Yard/ShuntingYard.playground/Contents.swift
mit
1
//: Playground - noun: a place where people can play // last checked with Xcode 9.0b4 #if swift(>=4.0) print("Hello, Swift 4!") #endif internal enum OperatorAssociativity { case leftAssociative case rightAssociative } public enum OperatorType: CustomStringConvertible { case add case subtract case divide case multiply case percent case exponent public var description: String { switch self { case .add: return "+" case .subtract: return "-" case .divide: return "/" case .multiply: return "*" case .percent: return "%" case .exponent: return "^" } } } public enum TokenType: CustomStringConvertible { case openBracket case closeBracket case Operator(OperatorToken) case operand(Double) public var description: String { switch self { case .openBracket: return "(" case .closeBracket: return ")" case .Operator(let operatorToken): return operatorToken.description case .operand(let value): return "\(value)" } } } public struct OperatorToken: CustomStringConvertible { let operatorType: OperatorType init(operatorType: OperatorType) { self.operatorType = operatorType } var precedence: Int { switch operatorType { case .add, .subtract: return 0 case .divide, .multiply, .percent: return 5 case .exponent: return 10 } } var associativity: OperatorAssociativity { switch operatorType { case .add, .subtract, .divide, .multiply, .percent: return .leftAssociative case .exponent: return .rightAssociative } } public var description: String { return operatorType.description } } func <= (left: OperatorToken, right: OperatorToken) -> Bool { return left.precedence <= right.precedence } func < (left: OperatorToken, right: OperatorToken) -> Bool { return left.precedence < right.precedence } public struct Token: CustomStringConvertible { let tokenType: TokenType init(tokenType: TokenType) { self.tokenType = tokenType } init(operand: Double) { tokenType = .operand(operand) } init(operatorType: OperatorType) { tokenType = .Operator(OperatorToken(operatorType: operatorType)) } var isOpenBracket: Bool { switch tokenType { case .openBracket: return true default: return false } } var isOperator: Bool { switch tokenType { case .Operator(_): return true default: return false } } var operatorToken: OperatorToken? { switch tokenType { case .Operator(let operatorToken): return operatorToken default: return nil } } public var description: String { return tokenType.description } } public class InfixExpressionBuilder { private var expression = [Token]() public func addOperator(_ operatorType: OperatorType) -> InfixExpressionBuilder { expression.append(Token(operatorType: operatorType)) return self } public func addOperand(_ operand: Double) -> InfixExpressionBuilder { expression.append(Token(operand: operand)) return self } public func addOpenBracket() -> InfixExpressionBuilder { expression.append(Token(tokenType: .openBracket)) return self } public func addCloseBracket() -> InfixExpressionBuilder { expression.append(Token(tokenType: .closeBracket)) return self } public func build() -> [Token] { // Maybe do some validation here return expression } } // This returns the result of the shunting yard algorithm public func reversePolishNotation(_ expression: [Token]) -> String { var tokenStack = Stack<Token>() var reversePolishNotation = [Token]() for token in expression { switch token.tokenType { case .operand(_): reversePolishNotation.append(token) case .openBracket: tokenStack.push(token) case .closeBracket: while tokenStack.count > 0, let tempToken = tokenStack.pop(), !tempToken.isOpenBracket { reversePolishNotation.append(tempToken) } case .Operator(let operatorToken): for tempToken in tokenStack.makeIterator() { if !tempToken.isOperator { break } if let tempOperatorToken = tempToken.operatorToken { if operatorToken.associativity == .leftAssociative && operatorToken <= tempOperatorToken || operatorToken.associativity == .rightAssociative && operatorToken < tempOperatorToken { reversePolishNotation.append(tokenStack.pop()!) } else { break } } } tokenStack.push(token) } } while tokenStack.count > 0 { reversePolishNotation.append(tokenStack.pop()!) } return reversePolishNotation.map({token in token.description}).joined(separator: " ") } // Simple demo let expr = InfixExpressionBuilder() .addOperand(3) .addOperator(.add) .addOperand(4) .addOperator(.multiply) .addOperand(2) .addOperator(.divide) .addOpenBracket() .addOperand(1) .addOperator(.subtract) .addOperand(5) .addCloseBracket() .addOperator(.exponent) .addOperand(2) .addOperator(.exponent) .addOperand(3) .build() print(expr.description) print(reversePolishNotation(expr))
71adca3027c2451d847bb24118e358ea
20.854772
102
0.670211
false
false
false
false
JGiola/swift
refs/heads/main
stdlib/public/SwiftOnoneSupport/SwiftOnoneSupport.swift
apache-2.0
14
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// // Pre-specialization of some popular generic classes and functions. //===----------------------------------------------------------------------===// import Swift // ============================================================================= // Definitions of proxy functions that mimic a generic function signature in the // standard library and are annotated with the standard library's // actual generic function name. The "prespecialize" annotation forces // the actual generic function to be specialized based on the argument // types passed to the proxy function. // ============================================================================= extension Collection { // _failEarlyRangeCheck(_: A.Index, bounds: Swift.Range<A.Index>) -> () @_semantics("prespecialize.$sSlsE20_failEarlyRangeCheck_6boundsy5IndexQz_SnyADGtF") func _prespecializeCollection(index: Index, range: Range<Index>) {} } extension Collection where Iterator == IndexingIterator<Self> { // makeIterator() -> Swift.IndexingIterator<A> @_semantics("prespecialize.$sSlss16IndexingIteratorVyxG0B0RtzrlE04makeB0ACyF") func _prespecializeIndexingIterator() {} } extension BidirectionalCollection { // reversed() -> ReversedCollection<A> @_semantics("prespecialize.$sSKsE8reverseds18ReversedCollectionVyxGyF") func _prespecializeBidirectionalCollection() {} } extension MutableCollection where Self: BidirectionalCollection { // _reverse(within: Swift.Range<A.Index>) -> () @_semantics("prespecialize.$sSMsSKRzrlE8_reverse6withinySny5IndexSlQzG_tF") mutating func _prespecializeMutableBirectionalCollection(range: Range<Index>) {} // _insertionSort(within: Swift.Range<A.Index>, // by: (A.Element, A.Element // ) throws -> Swift.Bool) throws -> () @_semantics("prespecialize.$sSMsSKRzrlE14_insertionSort6within2byySny5IndexSlQzG_Sb7ElementSTQz_AHtKXEtKF") mutating func _prespecializeMutableBirectionalCollection(range: Range<Index>, cmp: (Element, Element) throws -> Bool) {} // _insertionSort( // within: Swift.Range<A.Index>, // sortedEnd: A.Index, // by: (A.Element, A.Element) throws -> Swift.Bool // ) throws -> () @_semantics("prespecialize.$sSMsSKRzrlE14_insertionSort6within9sortedEnd2byySny5IndexSlQzG_AFSb7ElementSTQz_AItKXEtKF") mutating func _prespecializeMutableBirectionalCollection(range: Range<Index>, end: Index, cmp: (Element, Element) throws -> Bool) {} } // extension MutableCollection where Self: BidirectionalCollection extension MutableCollection where Self: RandomAccessCollection { // sort(by: (A.Element, A.Element) throws -> Swift.Bool) throws -> () @_semantics("prespecialize.$sSMsSkRzrlE4sort2byySb7ElementSTQz_ADtKXE_tKF") mutating func _prespecializeMutableRandomAccessCollection(cmp: (Element, Element) throws -> Bool) throws {} } extension RandomAccessCollection where Index : Strideable, Index.Stride == Int { // index(after: A.Index) -> A.Index @_semantics("prespecialize.$sSksSx5IndexRpzSnyABG7IndicesRtzSiAA_6StrideRTzrlE5index5afterA2B_tF") func _prespecializeRandomAccessCollection(after: Index) {} // indices.getter : Swift.Range<A.Index> @_semantics("prespecialize.$sSksSx5IndexRpzSnyABG7IndicesRtzSiAA_6StrideRTzrlE7indicesACvg") func _prespecializeRandomAccessCollection() {} } // _allocateUninitializedArray<A>(Builtin.Word) -> ([A], Builtin.RawPointer) @_semantics("prespecialize.$ss27_allocateUninitializedArrayySayxG_BptBwlF") func _prespecializeArray<T>(_ word: Builtin.Word) -> ([T], Builtin.RawPointer) { return ([], Builtin.inttoptr_Word(word)) } extension Array { // init() -> [A] @_semantics("prespecialize.$sS2ayxGycfC") // startIndex.getter : Swift.Int @_semantics("prespecialize.$sSa10startIndexSivg") // _getCapacity() -> Swift.Int @_semantics("prespecialize.$sSa12_getCapacitySiyF") // _makeMutableAndUnique() -> () @_semantics("prespecialize.$sSa21_makeMutableAndUniqueyyF") // _copyToContiguousArray() -> Swift.ContiguousArray<A> @_semantics("prespecialize.$sSa22_copyToContiguousArrays0cD0VyxGyF") // _hoistableIsNativeTypeChecked() -> Swift.Bool @_semantics("prespecialize.$sSa29_hoistableIsNativeTypeCheckedSbyF") // count.getter : Swift.Int @_semantics("prespecialize.$sSa5countSivg") // capacity.getter : Swift.Int @_semantics("prespecialize.$sSa8capacitySivg") // endIndex.getter : Swift.Int @_semantics("prespecialize.$sSa8endIndexSivg") // formIndex(before: inout Swift.Int) -> () @_semantics("prespecialize.$sSa9formIndex6beforeySiz_tF") func _prespecializeArray() {} // _makeUniqueAndReserveCapacityIfNotUnique() -> () @_semantics("prespecialize.$sSa034_makeUniqueAndReserveCapacityIfNotB0yyF") func _prespecializeMutableArray() {} // _checkSubscript(_: Swift.Int, wasNativeTypeChecked: Swift.Bool) -> Swift._DependenceToken @_semantics("prespecialize.$sSa15_checkSubscript_20wasNativeTypeCheckeds16_DependenceTokenVSi_SbtF") func _prespecializeArray(index: Int, flag: Bool) {} // _getElement(_: Swift.Int, wasNativeTypeChecked: Swift.Bool, matchingSubscriptCheck: Swift._DependenceToken) -> A @_semantics("prespecialize.$sSa11_getElement_20wasNativeTypeChecked22matchingSubscriptCheckxSi_Sbs16_DependenceTokenVtF") func _prespecializeArray(index: Int, flag: Bool, token: _DependenceToken) {} // init(arrayLiteral: A...) -> [A] @_semantics("prespecialize.$sSa12arrayLiteralSayxGxd_tcfC") func _prespecializeArray(arrayLiteral: Element...) {} // init(_unsafeUninitializedCapacity: Swift.Int, initializingWith: (inout Swift.UnsafeMutableBufferPointer<A>, inout Swift.Int) throws -> ()) throws -> [A] @_semantics("prespecialize.$sSa28_unsafeUninitializedCapacity16initializingWithSayxGSi_ySryxGz_SiztKXEtKcfC") func _prespecializeArray(capacity: Int, generator: (inout UnsafeMutableBufferPointer<Element>, inout Int) throws -> ()) {} // removeAll(keepingCapacity: Swift.Bool) -> () @_semantics("prespecialize.$sSa9removeAll15keepingCapacityySb_tF") // default argument 0 of Swift.Array.removeAll(keepingCapacity: Swift.Bool) -> () @_semantics("prespecialize.$sSa9removeAll15keepingCapacityySb_tFfA_") func _prespecializeArray(flag: Bool) {} // init(_uninitializedCount: Swift.Int) -> [A] @_semantics("prespecialize.$sSa19_uninitializedCountSayxGSi_tcfC") // _reserveCapacityAssumingUniqueBuffer(oldCount: Swift.Int) -> () @_semantics("prespecialize.$sSa36_reserveCapacityAssumingUniqueBuffer8oldCountySi_tF") // reserveCapacity(Swift.Int) -> () @_semantics("prespecialize.$sSa15reserveCapacityyySiF") // _copyToNewBuffer(oldCount: Swift.Int) -> () @_semantics("prespecialize.$sSa16_copyToNewBuffer8oldCountySi_tF") // _getCount() -> Swift.Int @_semantics("prespecialize.$sSa9_getCountSiyF") // formIndex(after: inout Swift.Int) -> () @_semantics("prespecialize.$sSa9formIndex5afterySiz_tF") // subscript.modify : (Swift.Int) -> A @_semantics("prespecialize.$sSayxSiciM") // subscript.getter : (Swift.Int) -> A @_semantics("prespecialize.$sSayxSicig") // subscript.read : (Swift.Int) -> A @_semantics("prespecialize.$sSayxSicir") func _prespecializeArray(index: Int) {} // _appendElementAssumeUniqueAndCapacity(_: Swift.Int, newElement: __owned A) -> () @_semantics("prespecialize.$sSa37_appendElementAssumeUniqueAndCapacity_03newB0ySi_xntF") func _prespecializeArray(index: Int, element: Element) {} // append(__owned A) -> () @_semantics("prespecialize.$sSa6appendyyxnF") // init(repeating: A, count: Swift.Int) -> [A] @_semantics("prespecialize.$sSa9repeating5countSayxGx_SitcfC") func _prespecializeArray(element: Element, index: Int) {} // replaceSubrange<A where A == A1.Element, A1: Swift.Collection>( // _: Swift.Range<Swift.Int>, with: __owned A1 // ) -> () @_semantics("prespecialize.$sSa15replaceSubrange_4withySnySiG_qd__nt7ElementQyd__RszSlRd__lF") func _prespecializeArray<C: Collection>(range: Range<C.Index>, collection: C) where Element == C.Element {} // _withUnsafeMutableBufferPointerIfSupported<A>( // (inout Swift.UnsafeMutableBufferPointer<A>) throws -> A1 // ) throws -> A1? @_semantics("prespecialize.$sSa42_withUnsafeMutableBufferPointerIfSupportedyqd__Sgqd__SryxGzKXEKlF") func _prespecializeArray<R>(with: (inout UnsafeMutableBufferPointer<Element>) throws -> R) {} } // extension Array extension _ContiguousArrayBuffer { // startIndex.getter : Swift.Int @_semantics("prespecialize.$ss22_ContiguousArrayBufferV10startIndexSivg") // firstElementAddress.getter : Swift.UnsafeMutablePointer<A> @_semantics("prespecialize.$ss22_ContiguousArrayBufferV19firstElementAddressSpyxGvg") // count.getter : Swift.Int @_semantics("prespecialize.$ss22_ContiguousArrayBufferV7_buffer19shiftedToStartIndexAByxGAE_SitcfC") // endIndex.getter : Swift.Int @_semantics("prespecialize.$ss22_ContiguousArrayBufferV8endIndexSivg") // init() -> Swift._ContiguousArrayBuffer<A> @_semantics("prespecialize.$ss22_ContiguousArrayBufferVAByxGycfC") func _prespecializeContiguousArrayBuffer() {} // _copyContents(subRange: Swift.Range<Swift.Int>, initializing: Swift.UnsafeMutablePointer<A>) -> Swift.UnsafeMutablePointer<A> @_semantics("prespecialize.$ss22_ContiguousArrayBufferV13_copyContents8subRange12initializingSpyxGSnySiG_AFtF") func _prespecializeContiguousArrayBuffer(range: Range<Int>, pointer: UnsafeMutablePointer<Element>) {} // _initStorageHeader(count: Swift.Int, capacity: Swift.Int) -> () @_semantics("prespecialize.$ss22_ContiguousArrayBufferV18_initStorageHeader5count8capacityySi_SitF") func _prespecializeContiguousArrayBuffer(count: Int, capacity: Int) {} @_semantics("prespecialize.$ss22_ContiguousArrayBufferV5countSivg") // init(_buffer: Swift._ContiguousArrayBuffer<A>, shiftedToStartIndex: Swift.Int) -> Swift._ContiguousArrayBuffer<A> func _prespecializeContiguousArrayBuffer(buffer: _ContiguousArrayBuffer<Element>, index: Int) {} } #if _runtime(_ObjC) extension _ArrayBuffer { // requestNativeBuffer() -> Swift._ContiguousArrayBuffer<A>? @_semantics("prespecialize.$ss12_ArrayBufferV013requestNativeB0s011_ContiguousaB0VyxGSgyF") // _nonNative.getter : Swift._CocoaArrayWrapper @_semantics("prespecialize.$ss12_ArrayBufferV10_nonNatives06_CocoaA7WrapperVvg") // startIndex.getter : Swift.Int @_semantics("prespecialize.$ss12_ArrayBufferV10startIndexSivg") // firstElementAddress.getter : Swift.UnsafeMutablePointer<A> @_semantics("prespecialize.$ss12_ArrayBufferV19firstElementAddressSpyxGvg") // isUniquelyReferenced() -> Swift.Bool @_semantics("prespecialize.$ss12_ArrayBufferV20isUniquelyReferencedSbyF") // count.setter : Swift.Int @_semantics("prespecialize.$ss12_ArrayBufferV5countSivs") // _native.getter : Swift._ContiguousArrayBuffer<A> @_semantics("prespecialize.$ss12_ArrayBufferV7_natives011_ContiguousaB0VyxGvg") // _isNative.getter : Swift.Bool @_semantics("prespecialize.$ss12_ArrayBufferV9_isNativeSbvg") // capacity.getter : Swift.Int @_semantics("prespecialize.$ss12_ArrayBufferV8capacitySivg") // endIndex.getter : Swift.Int @_semantics("prespecialize.$ss12_ArrayBufferV8endIndexSivg") func _prespecializeArrayBuffer() {} // requestUniqueMutableBackingBuffer(minimumCapacity: Swift.Int) -> Swift._ContiguousArrayBuffer<A>? @_semantics("prespecialize.$ss12_ArrayBufferV027requestUniqueMutableBackingB015minimumCapacitys011_ContiguousaB0VyxGSgSi_tF") // _getElementSlowPath(Swift.Int) -> Swift.AnyObject @_semantics("prespecialize.$ss12_ArrayBufferV19_getElementSlowPathyyXlSiF") // subscript.getter : (Swift.Int) -> A @_semantics("prespecialize.$ss12_ArrayBufferVyxSicig") // subscript.read : (Swift.Int) -> A @_semantics("prespecialize.$ss12_ArrayBufferVyxSicir") func _prespecializeArrayBuffer(index: Int) {} // _typeCheck(Swift.Range<Swift.Int>) -> () @_semantics("prespecialize.$ss12_ArrayBufferV10_typeCheckyySnySiGF") func _prespecializeArrayBuffer(range: Range<Int>) {} // _copyContents(subRange: Swift.Range<Swift.Int>, initializing: Swift.UnsafeMutablePointer<A>) -> Swift.UnsafeMutablePointer<A> @_semantics("prespecialize.$ss12_ArrayBufferV13_copyContents8subRange12initializingSpyxGSnySiG_AFtF") func _prespecializeArrayBuffer(range: Range<Int>, pointer: UnsafeMutablePointer<Element>) {} // _checkInoutAndNativeTypeCheckedBounds(_: Swift.Int, wasNativeTypeChecked: Swift.Bool) -> () @_semantics("prespecialize.$ss12_ArrayBufferV37_checkInoutAndNativeTypeCheckedBounds_03wasfgH0ySi_SbtF") func _prespecializeArrayBuffer(index: Int, flag: Bool) {} // init(_buffer: Swift._ContiguousArrayBuffer<A>, shiftedToStartIndex: Swift.Int) -> Swift._ArrayBuffer<A> @_semantics("prespecialize.$ss12_ArrayBufferV7_buffer19shiftedToStartIndexAByxGs011_ContiguousaB0VyxG_SitcfC") func _prespecializeArrayBuffer(buffer: _ContiguousArrayBuffer<Element>, index: Int) {} } #endif // ObjC extension Range { // contains(A) -> Swift.Bool @_semantics("prespecialize.$sSn8containsySbxF") func _prespecializeRange(bound: Bound) {} // init(uncheckedBounds: (lower: A, upper: A)) -> Swift.Range<A> @_semantics("prespecialize.$sSn15uncheckedBoundsSnyxGx5lower_x5uppert_tcfC") func _prespecializeRange(bounds: (lower: Bound, upper: Bound)) {} } extension Range where Bound: Strideable, Bound.Stride : SignedInteger { // startIndex.getter @_semantics("prespecialize.$sSnsSxRzSZ6StrideRpzrlE10startIndexxvg") // endIndex.getter @_semantics("prespecialize.$sSnsSxRzSZ6StrideRpzrlE8endIndexxvg") // index(after: A) -> A @_semantics("prespecialize.$sSnsSxRzSZ6StrideRpzrlE5index5afterxx_tF") // subscript.read @_semantics("prespecialize.$sSnsSxRzSZ6StrideRpzrlEyxxcir") func _prespecializeIntegerRange(bound: Bound) {} } extension ClosedRange { // init(uncheckedBounds: (lower: A, upper: A)) -> Swift.ClosedRange<A> @_semantics("prespecialize.$sSN15uncheckedBoundsSNyxGx5lower_x5uppert_tcfC") func _prespecializeClosedRange() {} } extension ClosedRange where Bound: Strideable, Bound.Stride : SignedInteger { // startIndex.getter @_semantics("prespecialize.$sSNsSxRzSZ6StrideRpzrlE10startIndexSNsSxRzSZABRQrlE0C0Oyx_Gvg") // endIndex.getter @_semantics("prespecialize.$sSNsSxRzSZ6StrideRpzrlE8endIndexSNsSxRzSZABRQrlE0C0Oyx_Gvg") // subscript.read @_semantics("prespecialize.$sSNsSxRzSZ6StrideRpzrlEyxSNsSxRzSZABRQrlE5IndexOyx_Gcir") func _prespecializeIntegerClosedRange() {} // index(after: ClosedRange<A>< where A: Swift.Strideable, A.Stride: Swift.SignedInteger>.Index) // -> ClosedRange<A>< where A: Swift.Strideable, A.Stride: Swift.SignedInteger>.Index @_semantics("prespecialize.$sSNsSxRzSZ6StrideRpzrlE5index5afterSNsSxRzSZABRQrlE5IndexOyx_GAG_tF") func _prespecializeIntegerClosedRange(range: Self) {} } // IndexingIterator.next() -> A.Element? @_semantics("prespecialize.$ss16IndexingIteratorV4next7ElementQzSgyF") func _prespecializeIndexingIterator<Elements>(_ x: IndexingIterator<Elements>) where Elements : Collection {} // ============================================================================= // Helpers that construct arguments of the necessary specialized types, // passing them to the above generic proxy functions. // ============================================================================= func prespecializeCollections<T>(_ element: T) { var umbp = UnsafeMutableBufferPointer<T>.allocate(capacity: 1) let cmp = { (_: T, _: T) in return false } umbp._prespecializeMutableBirectionalCollection(range: 0..<0) umbp._prespecializeMutableBirectionalCollection(range: 0..<0, cmp: cmp) umbp._prespecializeMutableBirectionalCollection(range: 0..<0, end: 0, cmp: cmp) try! umbp._prespecializeMutableRandomAccessCollection(cmp: cmp) let _: (Array<T>, Builtin.RawPointer) = _prespecializeArray(0._builtinWordValue) var array = Array<T>() array._prespecializeArray() array._prespecializeMutableArray() array._prespecializeArray(index: 0, flag: false) array._prespecializeArray(index: 0, flag: false, token: _DependenceToken()) array._prespecializeArray(arrayLiteral: element) array._prespecializeArray(capacity: 0) { (_: inout UnsafeMutableBufferPointer<T>, _: inout Int) in return } array._prespecializeArray(flag: false) array._prespecializeArray(index: 0) array._prespecializeArray(index: 0, element: element) array._prespecializeArray(element: element, index: 0) array._prespecializeArray(range: 0..<0, collection: EmptyCollection()) array._prespecializeArray(with: { (_: inout UnsafeMutableBufferPointer<T>) -> Optional<()> in return () }) array._prespecializeBidirectionalCollection() array._prespecializeRandomAccessCollection() try! array._prespecializeMutableRandomAccessCollection(cmp: cmp) let cab = _ContiguousArrayBuffer<T>() cab._prespecializeContiguousArrayBuffer() cab._prespecializeContiguousArrayBuffer(range: (0..<0), pointer: umbp.baseAddress!) cab._prespecializeContiguousArrayBuffer(count: 0, capacity: 0) cab._prespecializeContiguousArrayBuffer(buffer: cab, index: 0) #if _runtime(_ObjC) let ab = _ArrayBuffer<T>() ab._prespecializeArrayBuffer() ab._prespecializeArrayBuffer(index: 0) ab._prespecializeArrayBuffer(range: (0..<0)) ab._prespecializeArrayBuffer(range: (0..<0), pointer: umbp.baseAddress!) ab._prespecializeArrayBuffer(index: 0, flag: false) ab._prespecializeArrayBuffer(buffer: cab, index: 0) ab._prespecializeRandomAccessCollection(after: 0) ab._prespecializeRandomAccessCollection() ab._prespecializeCollection(index: 0, range: (0..<0)) #endif // ObjC var ca = ContiguousArray<T>() ca._prespecializeRandomAccessCollection() try! ca._prespecializeMutableRandomAccessCollection(cmp: cmp) let cb = _ContiguousArrayBuffer<T>() cb._prespecializeRandomAccessCollection() } func prespecializeRanges() { // Range<Int> (0..<0)._prespecializeCollection(index: 0, range: (0..<0)) (0..<0)._prespecializeRange(bound: 0) (0..<0)._prespecializeRange(bounds: (0, 0)) (0..<0)._prespecializeIntegerRange(bound: 0) (0..<0)._prespecializeIndexingIterator() _prespecializeIndexingIterator((0..<0).makeIterator()) // ClosedRange<Int> (0...0)._prespecializeClosedRange() (0...0)._prespecializeIntegerClosedRange() (0...0)._prespecializeIntegerClosedRange(range: (0...0)) (0...0)._prespecializeIndexingIterator() _prespecializeIndexingIterator((0...0).makeIterator()) } // ============================================================================= // Top-level function that statically calls all generic entry points // that require prespecialization. // ============================================================================= // Allow optimization here so that specialization occurs. func prespecializeAll() { prespecializeCollections(() as Any) prespecializeCollections("a" as Character) prespecializeCollections("a" as Unicode.Scalar) prespecializeCollections("a".utf8) prespecializeCollections("a".utf16) prespecializeCollections("a".unicodeScalars) prespecializeCollections("a" as String) prespecializeCollections(1.5 as Double) prespecializeCollections(1.5 as Float) prespecializeCollections(1 as Int) prespecializeCollections(1 as UInt) prespecializeCollections(1 as Int8) prespecializeCollections(1 as Int16) prespecializeCollections(1 as Int32) prespecializeCollections(1 as Int64) prespecializeCollections(1 as UInt8) prespecializeCollections(1 as UInt16) prespecializeCollections(1 as UInt32) prespecializeCollections(1 as UInt64) prespecializeRanges() } // Mark with optimize(none) to make sure its not get // rid of by dead function elimination. @_optimize(none) internal func _swift_forcePrespecializations() { prespecializeAll() }
9e583a0ccdaaec7bdd6a82f4d9907224
48.16545
157
0.736082
false
false
false
false
xoyip/AzureStorageApiClient
refs/heads/master
Pod/Classes/AzureStorage/Queue/Request/DeleteMessageRequest.swift
mit
1
// // DeleteMessageRequest.swift // AzureStorageApiClient // // Created by Hiromasa Ohno on 2015/08/06. // Copyright (c) 2015 Hiromasa Ohno. All rights reserved. // import Foundation import Regex public extension AzureQueue { public class DeleteMessageRequest: Request { public let method = "DELETE" let queue : String let messageId : String let popReceipt : String public typealias Response = Bool public init(queue : String, messageId: String, popReceipt : String) { self.queue = queue self.messageId = messageId self.popReceipt = popReceipt } public func path() -> String { var equalReplacedStr : String = popReceipt.replaceRegex("=", with: "%3D") return "/\(queue)/messages/\(messageId)?popreceipt=\(equalReplacedStr)" } public func body() -> NSData? { return nil } public func additionalHeaders() -> [String : String] { return ["Content-Length": "0"] } public func convertResponseObject(object: AnyObject?) -> Response? { return true } public func responseTypes() -> Set<String>? { return nil } } }
78317837b11abb11c478b8691dace3ec
26.625
85
0.558824
false
false
false
false
n41l/OMChartView
refs/heads/master
OMChartView/Classes/OMChartDefines.swift
mit
1
// // OMChartDefines.swift // Pods // // Created by HuangKun on 16/6/2. // // import UIKit public typealias ChartStatisticData = [CGFloat] public enum OMChartLayerLineCap: String { case Round = "round" case Butt = "butt" case Square = "square" } public typealias BezierParameters = (startPoint: CGPoint, cp1: CGPoint, cp2: CGPoint, endPoint: CGPoint)
c5cccdd0bbeea414730ecfd96f21f9b5
17.55
104
0.694595
false
false
false
false
aschwaighofer/swift
refs/heads/master
test/stdlib/Reflection_objc.swift
apache-2.0
3
// RUN: %empty-directory(%t) // // RUN: %target-clang %S/Inputs/Mirror/Mirror.mm -c -o %t/Mirror.mm.o -g // RUN: %target-build-swift -parse-stdlib %s -module-name Reflection -I %S/Inputs/Mirror/ -Xlinker %t/Mirror.mm.o -o %t/a.out // RUN: %target-codesign %t/a.out // RUN: %{python} %S/../Inputs/timeout.py 360 %target-run %t/a.out %S/Inputs/shuffle.jpg | %FileCheck %s // FIXME: timeout wrapper is necessary because the ASan test runs for hours // REQUIRES: executable_test // REQUIRES: objc_interop // // DO NOT add more tests to this file. Add them to test/1_stdlib/Runtime.swift. // import Swift import Foundation import simd #if os(macOS) import AppKit typealias OSImage = NSImage typealias OSColor = NSColor typealias OSBezierPath = NSBezierPath #endif #if os(iOS) || os(tvOS) || os(watchOS) import UIKit typealias OSImage = UIImage typealias OSColor = UIColor typealias OSBezierPath = UIBezierPath #endif // Check ObjC mirror implementation. // CHECK-LABEL: ObjC: print("ObjC:") // CHECK-NEXT: <NSObject: {{0x[0-9a-f]+}}> dump(NSObject()) // CHECK-LABEL: ObjC subclass: print("ObjC subclass:") // CHECK-NEXT: woozle wuzzle dump("woozle wuzzle" as NSString) // Test a mixed Swift-ObjC hierarchy. class NSGood : NSObject { let x: Int = 22 } class NSBetter : NSGood { let y: String = "333" } // CHECK-LABEL: Swift ObjC subclass: // CHECK-NEXT: <Reflection.NSBetter: {{0x[0-9a-f]+}}> #0 // CHECK-NEXT: super: Reflection.NSGood // CHECK-NEXT: super: NSObject print("Swift ObjC subclass:") dump(NSBetter()) // CHECK-LABEL: ObjC quick look objects: print("ObjC quick look objects:") // CHECK-LABEL: ObjC enums: print("ObjC enums:") // CHECK-NEXT: We cannot reflect NSComparisonResult yet print("We cannot reflect \(ComparisonResult.orderedAscending) yet") // Don't crash when introspecting framework types such as NSURL. // <rdar://problem/16592777> // CHECK-LABEL: NSURL: // CHECK-NEXT: file:///Volumes/ // CHECK-NEXT: - super: NSObject print("NSURL:") dump(NSURL(fileURLWithPath: "/Volumes", isDirectory: true)) // -- Check that quick look Cocoa objects get binned correctly to their // associated enum tag. // CHECK-NEXT: got the expected quick look text switch PlaygroundQuickLook(reflecting: "woozle wuzzle" as NSString) { case .text("woozle wuzzle"): print("got the expected quick look text") case let x: print("NSString: got something else: \(x)") } // CHECK-NEXT: foobar let somesubclassofnsstring = ("foo" + "bar") as NSString switch PlaygroundQuickLook(reflecting: somesubclassofnsstring) { case .text(let text): print(text) case let x: print("not the expected quicklook: \(x)") } // CHECK-NEXT: got the expected quick look attributed string let astr = NSAttributedString(string: "yizzle pizzle") switch PlaygroundQuickLook(reflecting: astr) { case .attributedString(let astr2 as NSAttributedString) where astr == astr2: print("got the expected quick look attributed string") case let x: print("NSAttributedString: got something else: \(x)") } // CHECK-NEXT: got the expected quick look int switch PlaygroundQuickLook(reflecting: Int.max as NSNumber) { case .int(+Int64(Int.max)): print("got the expected quick look int") case let x: print("NSNumber(Int.max): got something else: \(x)") } // CHECK-NEXT: got the expected quick look uint switch PlaygroundQuickLook(reflecting: NSNumber(value: UInt64.max)) { case .uInt(UInt64.max): print("got the expected quick look uint") case let x: print("NSNumber(Int64.max): got something else: \(x)") } // CHECK-NEXT: got the expected quick look double switch PlaygroundQuickLook(reflecting: 22.5 as NSNumber) { case .double(22.5): print("got the expected quick look double") case let x: print("NSNumber(22.5): got something else: \(x)") } // CHECK-NEXT: got the expected quick look float switch PlaygroundQuickLook(reflecting: Float32(1.25)) { case .float(1.25): print("got the expected quick look float") case let x: print("NSNumber(Float32(1.25)): got something else: \(x)") } // CHECK-NEXT: got the expected quick look image // CHECK-NEXT: got the expected quick look color // CHECK-NEXT: got the expected quick look bezier path let image = OSImage(contentsOfFile:CommandLine.arguments[1])! switch PlaygroundQuickLook(reflecting: image) { case .image(let image2 as OSImage) where image === image2: print("got the expected quick look image") case let x: print("OSImage: got something else: \(x)") } let color = OSColor.black switch PlaygroundQuickLook(reflecting: color) { case .color(let color2 as OSColor) where color === color2: print("got the expected quick look color") case let x: print("OSColor: got something else: \(x)") } let path = OSBezierPath() switch PlaygroundQuickLook(reflecting: path) { case .bezierPath(let path2 as OSBezierPath) where path === path2: print("got the expected quick look bezier path") case let x: print("OSBezierPath: got something else: \(x)") } // CHECK-LABEL: Reflecting NSArray: // CHECK-NEXT: [ 1 2 3 4 5 ] print("Reflecting NSArray:") let intNSArray : NSArray = [1 as NSNumber,2 as NSNumber,3 as NSNumber,4 as NSNumber,5 as NSNumber] let arrayMirror = Mirror(reflecting: intNSArray) var buffer = "[ " for i in arrayMirror.children { buffer += "\(i.1) " } buffer += "]" print(buffer) // CHECK-LABEL: Reflecting NSSet: // CHECK-NEXT: NSSet reflection working fine print("Reflecting NSSet:") let numset = NSSet(objects: 1,2,3,4) let numsetMirror = Mirror(reflecting: numset) var numsetNumbers = Set<Int>() for i in numsetMirror.children { if let number = i.1 as? Int { numsetNumbers.insert(number) } } if numsetNumbers == Set([1, 2, 3, 4]) { print("NSSet reflection working fine") } else { print("NSSet reflection broken: here are the numbers we got: \(numsetNumbers)") } // CHECK-NEXT: (3.0, 6.0) // CHECK-NEXT: x: 3.0 // CHECK-NEXT: y: 6.0 dump(CGPoint(x: 3,y: 6)) // CHECK-NEXT: (30.0, 60.0) // CHECK-NEXT: width: 30.0 // CHECK-NEXT: height: 60.0 dump(CGSize(width: 30, height: 60)) // CHECK-NEXT: (50.0, 60.0, 100.0, 150.0) // CHECK-NEXT: origin: (50.0, 60.0) // CHECK-NEXT: x: 50.0 // CHECK-NEXT: y: 60.0 // CHECK-NEXT: size: (100.0, 150.0) // CHECK-NEXT: width: 100.0 // CHECK-NEXT: height: 150.0 dump(CGRect(x: 50, y: 60, width: 100, height: 150)) // rdar://problem/18513769 -- Make sure that QuickLookObject lookup correctly // manages memory. @objc class CanaryBase { deinit { print("\(type(of: self)) overboard") } required init() { } } var CanaryHandle = false class IsDebugQLO : CanaryBase, CustomStringConvertible { @objc var description: String { return "I'm a QLO" } } class HasDebugQLO : CanaryBase { @objc var debugQuickLookObject: AnyObject { return IsDebugQLO() } } class HasNumberQLO : CanaryBase { @objc var debugQuickLookObject: AnyObject { let number = NSNumber(value: 97210) return number } } class HasAttributedQLO : CanaryBase { @objc var debugQuickLookObject: AnyObject { let str = NSAttributedString(string: "attributed string") objc_setAssociatedObject(str, &CanaryHandle, CanaryBase(), .OBJC_ASSOCIATION_RETAIN_NONATOMIC) return str } } class HasStringQLO : CanaryBase { @objc var debugQuickLookObject: AnyObject { let str = NSString(string: "plain string") objc_setAssociatedObject(str, &CanaryHandle, CanaryBase(), .OBJC_ASSOCIATION_RETAIN_NONATOMIC) return str } } func testQLO<T : CanaryBase>(_ type: T.Type) { autoreleasepool { _ = PlaygroundQuickLook(reflecting: type.init()) } } testQLO(IsDebugQLO.self) // CHECK-NEXT: IsDebugQLO overboard testQLO(HasDebugQLO.self) // CHECK-NEXT: HasDebugQLO overboard // CHECK-NEXT: IsDebugQLO overboard testQLO(HasNumberQLO.self) // CHECK-NEXT: HasNumberQLO overboard // TODO: tagged numbers are immortal, so we can't reliably check for // cleanup here testQLO(HasAttributedQLO.self) // CHECK-NEXT: HasAttributedQLO overboard // CHECK-NEXT: CanaryBase overboard testQLO(HasStringQLO.self) // CHECK-NEXT: HasStringQLO overboard // CHECK-NEXT: CanaryBase overboard let x = float4(0) print("float4 has \(Mirror(reflecting: x).children.count) children") // CHECK-NEXT: float4 has 1 children // CHECK-LABEL: and now our song is done print("and now our song is done")
80133f93ebbcb7068c6a35de6c2d80f7
27.101351
125
0.705458
false
false
false
false
liuchuo/Swift-practice
refs/heads/master
20150609-2.playground/Contents.swift
gpl-2.0
1
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" let specialCharTab1 = "Hello\tWorld." println("specialCharTab1:\(specialCharTab1)") let specialCharNewLine = "Hello\nWorld." println("specialCharNewLine:\(specialCharNewLine)") let specialCharReturn = "Hello\rWorld." println("specialCharReturn:\(specialCharReturn)") //在时间轴里面不会出现\n\r的输出格式但是在输出框里面会有体现 let 🌎 = "🐶🐺🐱🐭🐹🐰🐸🐯🐨🐻🐷🐦🐧🐼🐘🐑🐴🐒🐵🐗🐮🐽🐤🐥🐣🐔🐍🐢🐛🐝🐜🐞🐌🐃🐀🐏🐄🐋🐬🐳🐟🐠🐙🐅" println("诺亚方舟上的小动物数:\(count(🌎))") let 熊: String = "🐻" let 猫: String = "🐱" let 🐼 = 熊 + 猫 //用+只能用string型进行运算 let emptyString1 = "" let emptyString = String()
b04e849677c97160600b65156e53c887
20.344828
54
0.66559
false
false
false
false
KrishMunot/swift
refs/heads/master
test/Constraints/diagnostics.swift
apache-2.0
2
// RUN: %target-parse-verify-swift protocol P { associatedtype SomeType } protocol P2 { func wonka() } extension Int : P { typealias SomeType = Int } extension Double : P { typealias SomeType = Double } func f0(_ x: Int, _ y: Float) { } func f1(_: (Int, Float) -> Int) { } func f2(_: (_: (Int) -> Int)) -> Int {} func f3(_: (_: (Int) -> Float) -> Int) {} func f4(_ x: Int) -> Int { } func f5<T : P2>(_ : T) { } func f6<T : P, U : P where T.SomeType == U.SomeType>(_ t: T, _ u: U) {} var i : Int var d : Double // Check the various forms of diagnostics the type checker can emit. // Tuple size mismatch. f1( f4 // expected-error {{cannot convert value of type '(Int) -> Int' to expected argument type '(Int, Float) -> Int'}} ) // Tuple element unused. f0(i, i, i) // expected-error{{extra argument in call}} // Position mismatch f5(f4) // expected-error {{argument type '(Int) -> Int' does not conform to expected type 'P2'}} // Tuple element not convertible. f0(i, d // expected-error {{cannot convert value of type 'Double' to expected argument type 'Float'}} ) // Function result not a subtype. f1( f0 // expected-error {{cannot convert value of type '(Int, Float) -> ()' to expected argument type '(Int, Float) -> Int'}} ) f3( f2 // expected-error {{cannot convert value of type '(((Int) -> Int)) -> Int' to expected argument type '((Int) -> Float) -> Int'}} ) f4(i, d) // expected-error {{extra argument in call}} // Missing member. i.wobble() // expected-error{{value of type 'Int' has no member 'wobble'}} // Generic member does not conform. extension Int { func wibble<T: P2>(_ x: T, _ y: T) -> T { return x } func wubble<T>(_ x: Int -> T) -> T { return x(self) } } i.wibble(3, 4) // expected-error {{argument type 'Int' does not conform to expected type 'P2'}} // Generic member args correct, but return type doesn't match. struct A : P2 { func wonka() {} } let a = A() for j in i.wibble(a, a) { // expected-error {{type 'A' does not conform to protocol 'Sequence'}} } // Generic as part of function/tuple types func f6<T:P2>(_ g: Void -> T) -> (c: Int, i: T) { return (c: 0, i: g()) } func f7() -> (c: Int, v: A) { let g: Void -> A = { return A() } return f6(g) // expected-error {{cannot convert return expression of type '(c: Int, i: A)' to return type '(c: Int, v: A)'}} } func f8<T:P2>(_ n: T, _ f: (T) -> T) {} f8(3, f4) // expected-error {{in argument type '(Int) -> Int', 'Int' does not conform to expected type 'P2'}} typealias Tup = (Int, Double) func f9(_ x: Tup) -> Tup { return x } f8((1,2.0), f9) // expected-error {{in argument type '(Tup) -> Tup', 'Tup' (aka '(Int, Double)') does not conform to expected type 'P2'}} // <rdar://problem/19658691> QoI: Incorrect diagnostic for calling nonexistent members on literals 1.doesntExist(0) // expected-error {{value of type 'Int' has no member 'doesntExist'}} [1, 2, 3].doesntExist(0) // expected-error {{value of type '[Int]' has no member 'doesntExist'}} "awfawf".doesntExist(0) // expected-error {{value of type 'String' has no member 'doesntExist'}} // Does not conform to protocol. f5(i) // expected-error {{argument type 'Int' does not conform to expected type 'P2'}} // Make sure we don't leave open existentials when diagnosing. // <rdar://problem/20598568> func pancakes(_ p: P2) { f4(p.wonka) // expected-error{{cannot convert value of type '() -> ()' to expected argument type 'Int'}} f4(p.wonka()) // expected-error{{cannot convert value of type '()' to expected argument type 'Int'}} } protocol Shoes { static func select(_ subject: Shoes) -> Self } // Here the opaque value has type (metatype_type (archetype_type ... )) func f(_ x: Shoes, asType t: Shoes.Type) { return t.select(x) // expected-error{{unexpected non-void return value in void function}} } infix operator **** { associativity left precedence 200 } func ****(_: Int, _: String) { } i **** i // expected-error{{cannot convert value of type 'Int' to expected argument type 'String'}} infix operator ***~ { associativity left precedence 200 } func ***~(_: Int, _: String) { } i ***~ i // expected-error{{cannot convert value of type 'Int' to expected argument type 'String'}} @available(*, unavailable, message: "call the 'map()' method on the sequence") public func myMap<C : Collection, T>( _ source: C, _ transform: (C.Iterator.Element) -> T ) -> [T] { fatalError("unavailable function can't be called") } @available(*, unavailable, message: "call the 'map()' method on the optional value") public func myMap<T, U>(_ x: T?, @noescape _ f: (T)->U) -> U? { fatalError("unavailable function can't be called") } // <rdar://problem/20142523> // FIXME: poor diagnostic, to be fixed in 20142462. For now, we just want to // make sure that it doesn't crash. func rdar20142523() { myMap(0..<10, { x in // expected-error{{ambiguous reference to member '..<'}} () return x }) } // <rdar://problem/21080030> Bad diagnostic for invalid method call in boolean expression: (_, IntegerLiteralConvertible)' is not convertible to 'IntegerLiteralConvertible func rdar21080030() { var s = "Hello" if s.characters.count() == 0 {} // expected-error{{cannot call value of non-function type 'Distance'}} } // <rdar://problem/21248136> QoI: problem with return type inference mis-diagnosed as invalid arguments func r21248136<T>() -> T { preconditionFailure() } // expected-note 2 {{in call to function 'r21248136'}} r21248136() // expected-error {{generic parameter 'T' could not be inferred}} let _ = r21248136() // expected-error {{generic parameter 'T' could not be inferred}} // <rdar://problem/16375647> QoI: Uncallable funcs should be compile time errors func perform<T>() {} // expected-error {{generic parameter 'T' is not used in function signature}} // <rdar://problem/17080659> Error Message QOI - wrong return type in an overload func recArea(_ h: Int, w : Int) { return h * w // expected-error {{no '*' candidates produce the expected contextual result type '()'}} // expected-note @-1 {{overloads for '*' exist with these result types: UInt8, Int8, UInt16, Int16, UInt32, Int32, UInt64, Int64, UInt, Int, Float, Double}} } // <rdar://problem/17224804> QoI: Error In Ternary Condition is Wrong func r17224804(_ monthNumber : Int) { // expected-error @+2 {{binary operator '+' cannot be applied to operands of type 'String' and 'Int'}} // expected-note @+1 {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (String, String), (UnsafeMutablePointer<Pointee>, Int), (UnsafePointer<Pointee>, Int)}} let monthString = (monthNumber <= 9) ? ("0" + monthNumber) : String(monthNumber) } // <rdar://problem/17020197> QoI: Operand of postfix '!' should have optional type; type is 'Int?' func r17020197(_ x : Int?, y : Int) { if x! { } // expected-error {{type 'Int' does not conform to protocol 'Boolean'}} // <rdar://problem/12939553> QoI: diagnostic for using an integer in a condition is utterly terrible if y {} // expected-error {{type 'Int' does not conform to protocol 'Boolean'}} } // <rdar://problem/20714480> QoI: Boolean expr not treated as Bool type when function return type is different func validateSaveButton(_ text: String) { return (text.characters.count > 0) ? true : false // expected-error {{unexpected non-void return value in void function}} } // <rdar://problem/20201968> QoI: poor diagnostic when calling a class method via a metatype class r20201968C { func blah() { r20201968C.blah() // expected-error {{use of instance member 'blah' on type 'r20201968C'; did you mean to use a value of type 'r20201968C' instead?}} } } // <rdar://problem/21459429> QoI: Poor compilation error calling assert func r21459429(_ a : Int) { assert(a != nil, "ASSERT COMPILATION ERROR") // expected-error {{value of type 'Int' can never be nil, comparison isn't allowed}} } // <rdar://problem/21362748> [WWDC Lab] QoI: cannot subscript a value of type '[Int]?' with an index of type 'Int' struct StructWithOptionalArray { var array: [Int]? } func testStructWithOptionalArray(_ foo: StructWithOptionalArray) -> Int { return foo.array[0] // expected-error {{value of optional type '[Int]?' not unwrapped; did you mean to use '!' or '?'?}} {{19-19=!}} } // <rdar://problem/19774755> Incorrect diagnostic for unwrapping non-optional bridged types var invalidForceUnwrap = Int()! // expected-error {{cannot force unwrap value of non-optional type 'Int'}} {{31-32=}} // <rdar://problem/20905802> Swift using incorrect diagnostic sometimes on String().asdf String().asdf // expected-error {{value of type 'String' has no member 'asdf'}} // <rdar://problem/21553065> Spurious diagnostic: '_' can only appear in a pattern or on the left side of an assignment protocol r21553065Protocol {} class r21553065Class<T : AnyObject> {} _ = r21553065Class<r21553065Protocol>() // expected-error {{type 'r21553065Protocol' does not conform to protocol 'AnyObject'}} // Type variables not getting erased with nested closures struct Toe { let toenail: Nail // expected-error {{use of undeclared type 'Nail'}} func clip() { toenail.inspect { x in toenail.inspect { y in } } } } // <rdar://problem/21447318> dot'ing through a partially applied member produces poor diagnostic class r21447318 { var x = 42 func doThing() -> r21447318 { return self } } func test21447318(_ a : r21447318, b : () -> r21447318) { a.doThing.doThing() // expected-error {{method 'doThing' was used as a property; add () to call it}} {{12-12=()}} b.doThing() // expected-error {{function 'b' was used as a property; add () to call it}} {{4-4=()}} } // <rdar://problem/20409366> Diagnostics for init calls should print the class name class r20409366C { init(a : Int) {} init?(a : r20409366C) { let req = r20409366C(a: 42)? // expected-error {{cannot use optional chaining on non-optional value of type 'r20409366C'}} {{32-33=}} } } // <rdar://problem/18800223> QoI: wrong compiler error when swift ternary operator branches don't match func r18800223(_ i : Int) { // 20099385 _ = i == 0 ? "" : i // expected-error {{result values in '? :' expression have mismatching types 'String' and 'Int'}} // 19648528 _ = true ? [i] : i // expected-error {{result values in '? :' expression have mismatching types '[Int]' and 'Int'}} var buttonTextColor: String? _ = (buttonTextColor != nil) ? 42 : {$0}; // expected-error {{result values in '? :' expression have mismatching types 'Int' and '(_) -> _'}} } // <rdar://problem/21883806> Bogus "'_' can only appear in a pattern or on the left side of an assignment" is back _ = { $0 } // expected-error {{unable to infer closure return type in current context}} _ = 4() // expected-error {{cannot call value of non-function type 'Int'}} _ = 4(1) // expected-error {{cannot call value of non-function type 'Int'}} // <rdar://problem/21784170> Incongruous `unexpected trailing closure` error in `init` function which is cast and called without trailing closure. func rdar21784170() { let initial = (1.0 as Double, 2.0 as Double) (Array.init as (Double...) -> Array<Double>)(initial as (Double, Double)) // expected-error {{cannot convert value of type '(Double, Double)' to expected argument type 'Double'}} } // <rdar://problem/21829141> BOGUS: unexpected trailing closure func expect<T, U>(_: T) -> (U.Type) -> Int { return { a in 0 } } func expect<T, U>(_: T, _: Int = 1) -> (U.Type) -> String { return { a in "String" } } let expectType1 = expect(Optional(3))(Optional<Int>.self) let expectType1Check: Int = expectType1 // <rdar://problem/19804707> Swift Enum Scoping Oddity func rdar19804707() { enum Op { case BinaryOperator((Double, Double) -> Double) } var knownOps : Op knownOps = Op.BinaryOperator({$1 - $0}) knownOps = Op.BinaryOperator(){$1 - $0} knownOps = Op.BinaryOperator{$1 - $0} knownOps = .BinaryOperator({$1 - $0}) // FIXME: rdar://19804707 - These two statements should be accepted by the type checker. knownOps = .BinaryOperator(){$1 - $0} // expected-error {{reference to member 'BinaryOperator' cannot be resolved without a contextual type}} knownOps = .BinaryOperator{$1 - $0} // expected-error {{reference to member 'BinaryOperator' cannot be resolved without a contextual type}} } // <rdar://problem/20789423> Unclear diagnostic for multi-statement closure with no return type func r20789423() { class C { func f(_ value: Int) { } } let p: C print(p.f(p)()) // expected-error {{cannot convert value of type 'C' to expected argument type 'Int'}} let _f = { (v: Int) in // expected-error {{unable to infer closure return type in current context}} print("a") return "hi" } } func f7(_ a: Int) -> (b: Int) -> Int { return { b in a+b } } f7(1)(b: 1) f7(1.0)(2) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} f7(1)(1.0) // expected-error {{missing argument label 'b:' in call}} f7(1)(b: 1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} let f8 = f7(2) f8(b: 1) f8(10) // expected-error {{missing argument label 'b:' in call}} {{4-4=b: }} f8(1.0) // expected-error {{missing argument label 'b:' in call}} f8(b: 1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} class CurriedClass { func method1() {} func method2(_ a: Int) -> (b : Int) -> () { return { b in () } } func method3(_ a: Int, b : Int) {} } let c = CurriedClass() _ = c.method1 c.method1(1) // expected-error {{argument passed to call that takes no arguments}} _ = c.method2(1) _ = c.method2(1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} c.method2(1)(b: 2) c.method2(1)(c: 2) // expected-error {{incorrect argument label in call (have 'c:', expected 'b:')}} {{14-15=b}} c.method2(1)(c: 2.0) // expected-error {{incorrect argument label in call (have 'c:', expected 'b:')}} c.method2(1)(b: 2.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} c.method2(1.0)(b: 2) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} c.method2(1.0)(b: 2.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} CurriedClass.method1(c)() _ = CurriedClass.method1(c) CurriedClass.method1(c)(1) // expected-error {{argument passed to call that takes no arguments}} CurriedClass.method1(2.0)(1) // expected-error {{use of instance member 'method1' on type 'CurriedClass'; did you mean to use a value of type 'CurriedClass' instead?}} CurriedClass.method2(c)(32)(b: 1) _ = CurriedClass.method2(c) _ = CurriedClass.method2(c)(32) _ = CurriedClass.method2(1,2) // expected-error {{use of instance member 'method2' on type 'CurriedClass'; did you mean to use a value of type 'CurriedClass' instead?}} CurriedClass.method2(c)(1.0)(b: 1) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} CurriedClass.method2(c)(1)(b: 1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} CurriedClass.method2(c)(2)(c: 1.0) // expected-error {{incorrect argument label in call (have 'c:', expected 'b:')}} CurriedClass.method3(c)(32, b: 1) _ = CurriedClass.method3(c) _ = CurriedClass.method3(c)(1, 2) // expected-error {{missing argument label 'b:' in call}} {{32-32=b: }} _ = CurriedClass.method3(c)(1, b: 2)(32) // expected-error {{cannot call value of non-function type '()'}} _ = CurriedClass.method3(1, 2) // expected-error {{use of instance member 'method3' on type 'CurriedClass'; did you mean to use a value of type 'CurriedClass' instead?}} CurriedClass.method3(c)(1.0, b: 1) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} CurriedClass.method3(c)(1) // expected-error {{missing argument for parameter 'b' in call}} CurriedClass.method3(c)(c: 1.0) // expected-error {{missing argument for parameter 'b' in call}} extension CurriedClass { func f() { method3(1, b: 2) method3() // expected-error {{missing argument for parameter #1 in call}} method3(42) // expected-error {{missing argument for parameter 'b' in call}} method3(self) // expected-error {{missing argument for parameter 'b' in call}} } } extension CurriedClass { func m1(_ a : Int, b : Int) {} func m2(_ a : Int) {} } // <rdar://problem/23718816> QoI: "Extra argument" error when accidentally currying a method CurriedClass.m1(2, b: 42) // expected-error {{use of instance member 'm1' on type 'CurriedClass'; did you mean to use a value of type 'CurriedClass' instead?}} // <rdar://problem/22108559> QoI: Confusing error message when calling an instance method as a class method CurriedClass.m2(12) // expected-error {{use of instance member 'm2' on type 'CurriedClass'; did you mean to use a value of type 'CurriedClass' instead?}} // <rdar://problem/19870975> Incorrect diagnostic for failed member lookups within closures passed as arguments ("(_) -> _") func ident<T>(_ t: T) -> T {} var c = ident({1.DOESNT_EXIST}) // error: expected-error {{value of type 'Int' has no member 'DOESNT_EXIST'}} // <rdar://problem/20712541> QoI: Int/UInt mismatch produces useless error inside a block var afterMessageCount : Int? = nil func uintFunc() -> UInt {} func takeVoidVoidFn(_ a : () -> ()) {} takeVoidVoidFn { () -> Void in afterMessageCount = uintFunc() // expected-error {{cannot assign value of type 'UInt' to type 'Int?'}} } // <rdar://problem/19997471> Swift: Incorrect compile error when calling a function inside a closure func f19997471(_ x: String) {} func f19997471(_ x: Int) {} func someGeneric19997471<T>(_ x: T) { takeVoidVoidFn { f19997471(x) // expected-error {{cannot invoke 'f19997471' with an argument list of type '(T)'}} // expected-note @-1 {{overloads for 'f19997471' exist with these partially matching parameter lists: (String), (Int)}} } } // <rdar://problem/20371273> Type errors inside anonymous functions don't provide enough information func f20371273() { let x: [Int] = [1, 2, 3, 4] let y: UInt = 4 x.filter { $0 == y } // expected-error {{binary operator '==' cannot be applied to operands of type 'Int' and 'UInt'}} // expected-note @-1 {{overloads for '==' exist with these partially matching parameter lists: (UInt, UInt), (Int, Int)}} } // <rdar://problem/20921068> Swift fails to compile: [0].map() { _ in let r = (1,2).0; return r } // FIXME: Should complain about not having a return type annotation in the closure. [0].map { _ in let r = (1,2).0; return r } // expected-error @-1 {{expression type '[_]' is ambiguous without more context}} // <rdar://problem/21078316> Less than useful error message when using map on optional dictionary type func rdar21078316() { var foo : [String : String]? var bar : [(String, String)]? bar = foo.map { ($0, $1) } // expected-error {{contextual closure type '([String : String]) -> [(String, String)]' expects 1 argument, but 2 were used in closure body}} } // <rdar://problem/20978044> QoI: Poor diagnostic when using an incorrect tuple element in a closure var numbers = [1, 2, 3] zip(numbers, numbers).filter { $0.2 > 1 } // expected-error {{value of tuple type '(Int, Int)' has no member '2'}} // <rdar://problem/20868864> QoI: Cannot invoke 'function' with an argument list of type 'type' func foo20868864(_ callback: ([String]) -> ()) { } func rdar20868864(_ s: String) { var s = s foo20868864 { (strings: [String]) in s = strings // expected-error {{cannot assign value of type '[String]' to type 'String'}} } } // <rdar://problem/20491794> Error message does not tell me what the problem is enum Color { case Red case Unknown(description: String) static func rainbow() -> Color {} static func overload(a : Int) -> Color {} static func overload(b : Int) -> Color {} static func frob(_ a : Int, b : inout Int) -> Color {} } let _: (Int, Color) = [1,2].map({ ($0, .Unknown("")) }) // expected-error {{'map' produces '[T]', not the expected contextual result type '(Int, Color)'}} let _: [(Int, Color)] = [1,2].map({ ($0, .Unknown("")) })// expected-error {{missing argument label 'description:' in call}} {{51-51=description: }} let _: [Color] = [1,2].map { _ in .Unknown("") }// expected-error {{missing argument label 'description:' in call}} {{44-44=description: }} let _: Int -> (Int, Color) = { ($0, .Unknown("")) } // expected-error {{missing argument label 'description:' in call}} {{46-46=description: }} let _: Color = .Unknown("") // expected-error {{missing argument label 'description:' in call}} {{25-25=description: }} let _: Color = .Unknown // expected-error {{contextual member 'Unknown' expects argument of type '(description: String)'}} let _: Color = .Unknown(42) // expected-error {{cannot convert value of type 'Int' to expected argument type 'String'}} let _ : Color = .rainbow(42) // expected-error {{argument passed to call that takes no arguments}} let _ : (Int, Float) = (42.0, 12) // expected-error {{cannot convert value of type 'Double' to specified type 'Int'}} let _ : Color = .rainbow // expected-error {{contextual member 'rainbow' expects argument of type '()'}} let _: Color = .overload(a : 1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} let _: Color = .overload(1.0) // expected-error {{ambiguous reference to member 'overload'}} // expected-note @-1 {{overloads for 'overload' exist with these partially matching parameter lists: (a: Int), (b: Int)}} let _: Color = .overload(1) // expected-error {{ambiguous reference to member 'overload'}} // expected-note @-1 {{overloads for 'overload' exist with these partially matching parameter lists: (a: Int), (b: Int)}} let _: Color = .frob(1.0, &i) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} let _: Color = .frob(1, i) // expected-error {{passing value of type 'Int' to an inout parameter requires explicit '&'}} let _: Color = .frob(1, b: i) // expected-error {{passing value of type 'Int' to an inout parameter requires explicit '&'}} let _: Color = .frob(1, &d) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} let _: Color = .frob(1, b: &d) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}} var someColor : Color = .red // expected-error {{type 'Color' has no member 'red'}} someColor = .red // expected-error {{type 'Color' has no member 'red'}} func testTypeSugar(_ a : Int) { typealias Stride = Int let x = Stride(a) x+"foo" // expected-error {{binary operator '+' cannot be applied to operands of type 'Stride' (aka 'Int') and 'String'}} // expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (String, String), (Int, UnsafeMutablePointer<Pointee>), (Int, UnsafePointer<Pointee>)}} } // <rdar://problem/21974772> SegFault in FailureDiagnosis::visitInOutExpr func r21974772(_ y : Int) { let x = &(1.0 + y) // expected-error {{binary operator '+' cannot be applied to operands of type 'Double' and 'Int'}} //expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (Double, Double), (UnsafeMutablePointer<Pointee>, Int), (UnsafePointer<Pointee>, Int)}} } // <rdar://problem/22020088> QoI: missing member diagnostic on optional gives worse error message than existential/bound generic/etc protocol r22020088P {} func r22020088Foo<T>(_ t: T) {} func r22020088bar(_ p: r22020088P?) { r22020088Foo(p.fdafs) // expected-error {{value of type 'r22020088P?' has no member 'fdafs'}} } // <rdar://problem/22288575> QoI: poor diagnostic involving closure, bad parameter label, and mismatch return type func f(_ arguments: [String]) -> [ArraySlice<String>] { return arguments.split(maxSplits: 1, omittingEmptySubsequences: false, isSeparator: { $0 == "--" }) } struct AOpts : OptionSet { let rawValue : Int } class B { func function(_ x : Int8, a : AOpts) {} func f2(_ a : AOpts) {} static func f1(_ a : AOpts) {} } func test(_ a : B) { B.f1(nil) // expected-error {{nil is not compatible with expected argument type 'AOpts'}} a.function(42, a: nil) //expected-error {{nil is not compatible with expected argument type 'AOpts'}} a.function(42, nil) //expected-error {{missing argument label 'a:' in call}} a.f2(nil) // expected-error {{nil is not compatible with expected argument type 'AOpts'}} } // <rdar://problem/21684487> QoI: invalid operator use inside a closure reported as a problem with the closure typealias MyClosure = ([Int]) -> Bool func r21684487() { var closures = Array<MyClosure>() let testClosure = {(list: [Int]) -> Bool in return true} let closureIndex = closures.index{$0 === testClosure} // expected-error {{cannot convert value of type 'MyClosure' (aka 'Array<Int> -> Bool') to expected argument type 'AnyObject?'}} } // <rdar://problem/18397777> QoI: special case comparisons with nil func r18397777(_ d : r21447318?) { let c = r21447318() if c != nil { // expected-error {{value of type 'r21447318' can never be nil, comparison isn't allowed}} } if d { // expected-error {{optional type 'r21447318?' cannot be used as a boolean; test for '!= nil' instead}} {{6-6=(}} {{7-7= != nil)}} } if !d { // expected-error {{optional type 'r21447318?' cannot be used as a boolean; test for '== nil' instead}} {{6-7=}} {{7-7=(}} {{8-8= == nil)}} } if !Optional(c) { // expected-error {{optional type 'Optional<_>' cannot be used as a boolean; test for '== nil' instead}} {{6-7=}} {{7-7=(}} {{18-18= == nil)}} } } // <rdar://problem/22255907> QoI: bad diagnostic if spurious & in argument list func r22255907_1<T>(_ a : T, b : Int) {} func r22255907_2<T>(_ x : Int, a : T, b: Int) {} func reachabilityForInternetConnection() { var variable: Int = 42 r22255907_1(&variable, b: 2.1) // expected-error {{'&' used with non-inout argument of type 'Int'}} {{15-16=}} r22255907_2(1, a: &variable, b: 2.1)// expected-error {{'&' used with non-inout argument of type 'Int'}} {{21-22=}} } // <rdar://problem/21601687> QoI: Using "=" instead of "==" in if statement leads to incorrect error message if i = 6 { } // expected-error {{use of '=' in a boolean context, did you mean '=='?}} {{6-7===}} _ = (i = 6) ? 42 : 57 // expected-error {{use of '=' in a boolean context, did you mean '=='?}} {{8-9===}} // <rdar://problem/22263468> QoI: Not producing specific argument conversion diagnostic for tuple init func r22263468(_ a : String?) { typealias MyTuple = (Int, String) _ = MyTuple(42, a) // expected-error {{value of optional type 'String?' not unwrapped; did you mean to use '!' or '?'?}} {{20-20=!}} } // rdar://22470302 - Crash with parenthesized call result. class r22470302Class { func f() {} } func r22470302(_ c: r22470302Class) { print((c.f)(c)) // expected-error {{argument passed to call that takes no arguments}} } // <rdar://problem/21928143> QoI: Pointfree reference to generic initializer in generic context does not compile extension String { @available(*, unavailable, message: "calling this is unwise") func unavail<T : Sequence where T.Iterator.Element == String> // expected-note 2 {{'unavail' has been explicitly marked unavailable here}} (_ a : T) -> String {} } extension Array { func g() -> String { return "foo".unavail([""]) // expected-error {{'unavail' is unavailable: calling this is unwise}} } func h() -> String { return "foo".unavail([0]) // expected-error {{'unavail' is unavailable: calling this is unwise}} } } // <rdar://problem/22519983> QoI: Weird error when failing to infer archetype func safeAssign<T: RawRepresentable>(_ lhs: inout T) -> Bool {} // expected-note @-1 {{in call to function 'safeAssign'}} let a = safeAssign // expected-error {{generic parameter 'T' could not be inferred}} // <rdar://problem/21692808> QoI: Incorrect 'add ()' fixit with trailing closure struct Radar21692808<Element> { init(count: Int, value: Element) {} } func radar21692808() -> Radar21692808<Int> { return Radar21692808<Int>(count: 1) { // expected-error {{cannot invoke initializer for type 'Radar21692808<Int>' with an argument list of type '(count: Int, () -> Int)'}} // expected-note @-1 {{expected an argument list of type '(count: Int, value: Element)'}} return 1 } } // <rdar://problem/17557899> - This shouldn't suggest calling with (). func someOtherFunction() {} func someFunction() -> () { // Producing an error suggesting that this return someOtherFunction // expected-error {{unexpected non-void return value in void function}} } // <rdar://problem/23560128> QoI: trying to mutate an optional dictionary result produces bogus diagnostic func r23560128() { var a : (Int,Int)? a.0 = 42 // expected-error {{value of optional type '(Int, Int)?' not unwrapped; did you mean to use '!' or '?'?}} {{4-4=?}} } // <rdar://problem/21890157> QoI: wrong error message when accessing properties on optional structs without unwrapping struct ExampleStruct21890157 { var property = "property" } var example21890157: ExampleStruct21890157? example21890157.property = "confusing" // expected-error {{value of optional type 'ExampleStruct21890157?' not unwrapped; did you mean to use '!' or '?'?}} {{16-16=?}} struct UnaryOp {} _ = -UnaryOp() // expected-error {{unary operator '-' cannot be applied to an operand of type 'UnaryOp'}} // expected-note @-1 {{overloads for '-' exist with these partially matching parameter lists: (Float), (Double)}} // <rdar://problem/23433271> Swift compiler segfault in failure diagnosis func f23433271(_ x : UnsafePointer<Int>) {} func segfault23433271(_ a : UnsafeMutablePointer<Void>) { f23433271(a[0]) // expected-error {{cannot convert value of type 'Void' (aka '()') to expected argument type 'UnsafePointer<Int>'}} } // <rdar://problem/22058555> crash in cs diags in withCString func r22058555() { var firstChar: UInt8 = 0 "abc".withCString { chars in firstChar = chars[0] // expected-error {{cannot assign value of type 'Int8' to type 'UInt8'}} } } // <rdar://problem/23272739> Poor diagnostic due to contextual constraint func r23272739(_ contentType: String) { let actualAcceptableContentTypes: Set<String> = [] return actualAcceptableContentTypes.contains(contentType) // expected-error {{unexpected non-void return value in void function}} } // <rdar://problem/23641896> QoI: Strings in Swift cannot be indexed directly with integer offsets func r23641896() { var g = "Hello World" g.replaceSubrange(0...2, with: "ce") // expected-error {{String may not be indexed with 'Int', it has variable size elements}} // expected-note @-1 {{consider using an existing high level algorithm, str.startIndex.advanced(by: n), or a projection like str.utf8}} _ = g[12] // expected-error {{'subscript' is unavailable: cannot subscript String with an Int, see the documentation comment for discussion}} } // <rdar://problem/23718859> QoI: Incorrectly flattening ((Int,Int)) argument list to (Int,Int) when printing note func test17875634() { var match: [(Int, Int)] = [] var row = 1 var col = 2 match.append(row, col) // expected-error {{extra argument in call}} } // <https://github.com/apple/swift/pull/1205> Improved diagnostics for enums with associated values enum AssocTest { case one(Int) } if AssocTest.one(1) == AssocTest.one(1) {} // expected-error{{binary operator '==' cannot be applied to two 'AssocTest' operands}} // expected-note @-1 {{binary operator '==' cannot be synthesized for enums with associated values}} // <rdar://problem/24251022> Swift 2: Bad Diagnostic Message When Adding Different Integer Types func r24251022() { var a = 1 var b: UInt32 = 2 a += a + b // expected-error {{cannot convert value of type 'UInt32' to expected argument type 'Int'}} } func overloadSetResultType(_ a : Int, b : Int) -> Int { // https://twitter.com/_jlfischer/status/712337382175952896 return a == b && 1 == 2 // expected-error {{'&&' produces 'Bool', not the expected contextual result type 'Int'}} } // <rdar://problem/21523291> compiler error message for mutating immutable field is incorrect func r21523291(_ bytes : UnsafeMutablePointer<UInt8>) { let i = 42 // expected-note {{change 'let' to 'var' to make it mutable}} let r = bytes[i++] // expected-error {{cannot pass immutable value as inout argument: 'i' is a 'let' constant}} }
33144ad1bb73fddf14fa86f5d97cf607
41.813802
195
0.668988
false
false
false
false
christopherhelf/Swift-FFT-Example
refs/heads/master
ffttest/main.swift
cc0-1.0
1
// // main.swift // ffttest // // Created by Christopher Helf on 17.08.15. // Copyright (c) 2015-Present Christopher Helf. All rights reserved. // import Foundation import Accelerate var fft = FFT() let n = 512 // Should be power of two for the FFT let frequency1 = 4.0 let phase1 = 0.0 let amplitude1 = 8.0 let seconds = 2.0 let fps = Double(n)/seconds var sineWave = (0..<n).map { amplitude1 * sin(2.0 * .pi / fps * Double($0) * frequency1 + phase1) } fft.calculate(sineWave, fps: fps)
6a675559e4baadb84cf6b996af302535
18.307692
72
0.665339
false
false
false
false
aschwaighofer/swift
refs/heads/master
test/multifile/require-layout-generic-arg.swift
apache-2.0
1
// RUN: %target-swift-frontend -module-name test -emit-ir -verify -primary-file %s %S/Inputs/require-layout-generic-class.swift | %FileCheck --check-prefix=FILE1 %s // RUN: %target-swift-frontend -module-name test -emit-ir -verify %s -primary-file %S/Inputs/require-layout-generic-class.swift | %FileCheck --check-prefix=FILE2 %s // REQUIRES: CPU=x86_64 // The offset of the typemetadata in the class typemetadata must match. // FILE1-LABEL: define{{.*}} swiftcc void @"$s4test11requestTypeyyAA3SubCyxGlF"(%T4test3SubC* %0) // FILE1: [[T1:%.*]] = bitcast %T4test3SubC* %0 to %swift.type** // FILE1: [[TYPEMETADATA:%.*]] = load %swift.type*, %swift.type** [[T1]] // FILE1: [[T2:%.*]] = bitcast %swift.type* [[TYPEMETADATA]] to %swift.type** // FILE1: [[T_PTR:%.*]] = getelementptr inbounds %swift.type*, %swift.type** [[T2]], i64 16 // FILE1: [[T:%.*]] = load %swift.type*, %swift.type** [[T_PTR]] public func requestType<T>(_ c: Sub<T>) { print(T.self) } // FILE2-LABEL: define internal %swift.type* @"$s4test3SubCMi"(%swift.type_descriptor* %0, i8** %1, i8* %2) // FILE2: [[T_ADDR:%.*]] = bitcast i8** %1 to %swift.type** // FILE2: [[T:%.*]] = load %swift.type*, %swift.type** [[T_ADDR]] // FILE2: [[CLASSMETADATA:%.*]] = call %swift.type* @swift_allocateGenericClassMetadata
9c42fd1753e1502a12448d4a742079d7
57.863636
164
0.647876
false
true
false
false
k3zi/KZ
refs/heads/master
KZ/Source/KZTableViewController.swift
mit
1
// // KZTableViewController.swift // KZ // // Created by Kesi Maduka on 1/25/16. // Copyright © 2016 Storm Edge Apps LLC. All rights reserved. // import UIKit open class KZTableViewController: KZViewController { open var tableView: UITableView? = nil open var items = [Any]() open var createTable = true //MARK: Setup View public convenience init(createTable: Bool) { self.init() self.createTable = createTable } override open func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. if createTable { tableView = UITableView(frame: view.bounds, style: .grouped) tableView!.delegate = self tableView!.dataSource = self tableView?.separatorStyle = .none tableView?.showsVerticalScrollIndicator = false tableView?.sectionIndexBackgroundColor = RGB(224) tableView?.sectionIndexColor = RGB(103) view.addSubview(tableView!) } } override open func setupConstraints() { super.setupConstraints() if createTable { tableView!.autoPin(toTopLayoutGuideOf: self, withInset: 0.0) tableView!.autoPinEdge(toSuperviewEdge: .left) tableView!.autoPinEdge(toSuperviewEdge: .right) tableView!.autoPinEdge(toSuperviewEdge: .bottom) } } open override func tableViewCellData(_ tableView: UITableView, section: Int) -> [Any] { return items } } public struct TableSection { public var sectionName: String public var sectionObjects: [Any] public init(sectionName: String, sectionObjects: [Any]) { self.sectionName = sectionName self.sectionObjects = sectionObjects } }
918e13598958cb4fc48a9312d2956cdd
26.646154
91
0.639399
false
false
false
false
spark/photon-tinker-ios
refs/heads/master
Photon-Tinker/Mesh/Common/Gen3SetupStep.swift
apache-2.0
1
// // Created by Raimundas Sakalauskas on 2019-03-02. // Copyright (c) 2019 Particle. All rights reserved. // import Foundation import CoreBluetooth protocol Gen3SetupStepDelegate { func stepCompleted(_ sender: Gen3SetupStep) func rewindTo(_ sender: Gen3SetupStep, step: Gen3SetupStep.Type, runStep: Bool) -> Gen3SetupStep func fail(_ sender: Gen3SetupStep, withReason reason: Gen3SetupFlowError, severity: Gen3SetupErrorSeverity, nsError: Error?) } class Gen3SetupStep: NSObject { var context: Gen3SetupContext? func log(_ message: String) { ParticleLogger.logInfo("Gen3SetupFlow", format: message, withParameters: getVaList([])) } func run(context: Gen3SetupContext) { self.context = context self.start() } func stepCompleted() { guard let context = self.context else { return } context.stepDelegate.stepCompleted(self) self.context = nil } func reset() { //clear step flags } func start() { fatalError("not implemented!!!") } func retry() { self.start() } func rewindFrom() { self.context = nil } func rewindTo(context: Gen3SetupContext) { self.context = context self.reset() } func handleBluetoothErrorResult(_ result: ControlReplyErrorType) { guard let context = self.context, !context.canceled else { return } if (result == .TIMEOUT && !context.bluetoothReady) { self.fail(withReason: .BluetoothDisabled) } else if (result == .TIMEOUT) { self.fail(withReason: .BluetoothTimeout) } else if (result == .INVALID_STATE) { self.fail(withReason: .InvalidDeviceState, severity: .Fatal) } else { self.fail(withReason: .BluetoothError) } } func fail(withReason reason: Gen3SetupFlowError, severity: Gen3SetupErrorSeverity = .Error, nsError: Error? = nil) { guard let context = self.context else { return } context.stepDelegate.fail(self, withReason: reason, severity: severity, nsError: nsError) } func handleBluetoothConnectionManagerError(_ error: BluetoothConnectionManagerError) -> Bool { return false } func handleBluetoothConnectionManagerPeripheralDiscovered(_ peripheral: CBPeripheral) -> Bool { return false } func handleBluetoothConnectionManagerConnectionCreated(_ connection: Gen3SetupBluetoothConnection) -> Bool { return false } func handleBluetoothConnectionManagerConnectionBecameReady(_ connection: Gen3SetupBluetoothConnection) -> Bool { return false } func handleBluetoothConnectionManagerConnectionDropped(_ connection: Gen3SetupBluetoothConnection) -> Bool { return false } } extension Gen3SetupStep { static func removeRepeatedMeshNetworks(_ networks: [Gen3SetupNetworkInfo]) -> [Gen3SetupNetworkInfo] { var meshNetworkIds:Set<String> = [] var filtered:[Gen3SetupNetworkInfo] = [] for network in networks { if (!meshNetworkIds.contains(network.extPanID)) { meshNetworkIds.insert(network.extPanID) filtered.append(network) } } return filtered.sorted { networkInfo, networkInfo2 in return networkInfo.name.localizedCaseInsensitiveCompare(networkInfo2.name) == .orderedAscending } } static func removeRepeatedWifiNetworks(_ networks: [Gen3SetupNewWifiNetworkInfo]) -> [Gen3SetupNewWifiNetworkInfo] { var wifiNetworkIds:Set<String> = [] var filtered:[Gen3SetupNewWifiNetworkInfo] = [] for network in networks { if (!wifiNetworkIds.contains(network.ssid)) { wifiNetworkIds.insert(network.ssid) filtered.append(network) } } return filtered.sorted { networkInfo, networkInfo2 in return networkInfo.ssid.localizedCaseInsensitiveCompare(networkInfo2.ssid) == .orderedAscending } } static func GetMeshNetworkCells(meshNetworks: [Gen3SetupNetworkInfo], apiMeshNetworks: [ParticleNetwork]) -> [Gen3SetupNetworkCellInfo] { var networks = [String: Gen3SetupNetworkCellInfo]() for network in meshNetworks { networks[network.extPanID] = Gen3SetupNetworkCellInfo(name: network.name, extPanID: network.extPanID, userOwned: false, deviceCount: nil) } for apiNetwork in apiMeshNetworks { if let xpanId = apiNetwork.xpanId, var meshNetwork = networks[xpanId] { meshNetwork.userOwned = true meshNetwork.deviceCount = apiNetwork.deviceCount networks[xpanId] = meshNetwork } } return Array(networks.values) } static func validateNetworkPassword(_ password: String) -> Bool { return password.count >= 6 } static func validateNetworkName(_ networkName: String) -> Bool { //ensure proper length if (networkName.count == 0) || (networkName.count > 16) { return false } //ensure no illegal characters let regex = try! NSRegularExpression(pattern: "[^a-zA-Z0-9_\\-]+") let matches = regex.matches(in: networkName, options: [], range: NSRange(location: 0, length: networkName.count)) return matches.count == 0 } }
023b0151dece2c3cc28c5331739d1087
30.413793
149
0.645993
false
false
false
false
ceaseless-prayer/CeaselessIOS
refs/heads/master
Ceaseless/BWWalkthroughPageViewController.swift
mit
1
/* The MIT License (MIT) Copyright (c) 2015 Yari D'areglia @bitwaker 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 public enum WalkthroughAnimationType:String{ case Linear = "Linear" case Curve = "Curve" case Zoom = "Zoom" case InOut = "InOut" init(_ name:String){ if let tempSelf = WalkthroughAnimationType(rawValue: name){ self = tempSelf }else{ self = .Linear } } } open class BWWalkthroughPageViewController: UIViewController, BWWalkthroughPage { fileprivate var animation:WalkthroughAnimationType = .Linear fileprivate var subsWeights:[CGPoint] = Array() fileprivate var notAnimatableViews:[Int] = [] // Array of views' tags that should not be animated during the scroll/transition // MARK: Inspectable Properties // Edit these values using the Attribute inspector or modify directly the "User defined runtime attributes" in IB @IBInspectable var speed:CGPoint = CGPoint(x: 0.0, y: 0.0); // Note if you set this value via Attribute inspector it can only be an Integer (change it manually via User defined runtime attribute if you need a Float) @IBInspectable var speedVariance:CGPoint = CGPoint(x: 0.0, y: 0.0) // Note if you set this value via Attribute inspector it can only be an Integer (change it manually via User defined runtime attribute if you need a Float) @IBInspectable var animationType:String { set(value){ self.animation = WalkthroughAnimationType(rawValue: value)! } get{ return self.animation.rawValue } } @IBInspectable var animateAlpha:Bool = false @IBInspectable var staticTags:String { // A comma separated list of tags that you don't want to animate during the transition/scroll set(value){ self.notAnimatableViews = value.components(separatedBy: ",").map{Int($0)!} } get{ return notAnimatableViews.map{String($0)}.joined(separator: ",") } } // MARK: BWWalkthroughPage Implementation override open func viewDidLoad() { super.viewDidLoad() self.view.layer.masksToBounds = true subsWeights = Array() for v in view.subviews{ speed.x += speedVariance.x speed.y += speedVariance.y if !notAnimatableViews.contains(v.tag) { subsWeights.append(speed) } } } open func walkthroughDidScroll(_ position: CGFloat, offset: CGFloat) { for i in (0..<subsWeights.count){ // Perform Transition/Scale/Rotate animations switch animation{ case .Linear: animationLinear(i, offset) case .Zoom: animationZoom(i, offset) case .Curve: animationCurve(i, offset) case .InOut: animationInOut(i, offset) } // Animate alpha if(animateAlpha){ animationAlpha(i, offset) } } } // MARK: Animations (WIP) private func animationAlpha(_ index:Int, _ offset:CGFloat){ var offset = offset let cView = view.subviews[index] if(offset > 1.0){ offset = 1.0 + (1.0 - offset) } cView.alpha = (offset) } fileprivate func animationCurve(_ index:Int, _ offset:CGFloat){ var transform = CATransform3DIdentity let x:CGFloat = (1.0 - offset) * 10 transform = CATransform3DTranslate(transform, (pow(x,3) - (x * 25)) * subsWeights[index].x, (pow(x,3) - (x * 20)) * subsWeights[index].y, 0 ) applyTransform(index, transform: transform) } fileprivate func animationZoom(_ index:Int, _ offset:CGFloat){ var transform = CATransform3DIdentity var tmpOffset = offset if(tmpOffset > 1.0){ tmpOffset = 1.0 + (1.0 - tmpOffset) } let scale:CGFloat = (1.0 - tmpOffset) transform = CATransform3DScale(transform, 1 - scale , 1 - scale, 1.0) applyTransform(index, transform: transform) } fileprivate func animationLinear(_ index:Int, _ offset:CGFloat){ var transform = CATransform3DIdentity let mx:CGFloat = (1.0 - offset) * 100 transform = CATransform3DTranslate(transform, mx * subsWeights[index].x, mx * subsWeights[index].y, 0 ) applyTransform(index, transform: transform) } fileprivate func animationInOut(_ index:Int, _ offset:CGFloat){ var transform = CATransform3DIdentity //var x:CGFloat = (1.0 - offset) * 20 var tmpOffset = offset if(tmpOffset > 1.0){ tmpOffset = 1.0 + (1.0 - tmpOffset) } transform = CATransform3DTranslate(transform, (1.0 - tmpOffset) * subsWeights[index].x * 100, (1.0 - tmpOffset) * subsWeights[index].y * 100, 0) applyTransform(index, transform: transform) } fileprivate func applyTransform(_ index:Int, transform:CATransform3D){ let subview = view.subviews[index] if !notAnimatableViews.contains(subview.tag){ view.subviews[index].layer.transform = transform } } }
9a673553bce43acab4b57bf2df367f02
35.977011
230
0.623562
false
false
false
false
danthorpe/Money
refs/heads/development
Tests/NSDecimalNumberTests.swift
mit
1
// // Money, https://github.com/danthorpe/Money // Created by Dan Thorpe, @danthorpe // // The MIT License (MIT) // // Copyright (c) 2015 Daniel Thorpe // // 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 Money class NSDecimalNumberTests: XCTestCase { var a: NSDecimalNumber! var b: NSDecimalNumber! var behaviors: NSDecimalNumberBehaviors! override func setUp() { super.setUp() a = 10 b = 20 behaviors = DecimalNumberBehavior.Plain.decimalNumberBehaviors } override func tearDown() { a = nil b = nil behaviors = nil super.tearDown() } func test__zero_is_not_equal_to_one() { XCTAssertNotEqual(NSDecimalNumber.zero, NSDecimalNumber.one) } func test__zero_is_less_than_one() { XCTAssertTrue(NSDecimalNumber.zero < NSDecimalNumber.one) } func test__zero_is_greater_than_negative_one() { XCTAssertTrue(NSDecimalNumber.zero > NSDecimalNumber.one.negate(withBehavior: behaviors)) } func test__negative_one_is_negative() { XCTAssertTrue(NSDecimalNumber.one.negate(withBehavior: behaviors).isNegative) } func test__zero_is_not_negative() { XCTAssertFalse(NSDecimalNumber.zero.isNegative) XCTAssertFalse(NSDecimalNumber.one.isNegative) } func test__addition() { let result = a.adding(b, withBehavior: behaviors) XCTAssertEqual(result, 30) } func test__subtraction() { let result = a.subtracting(b, withBehavior: behaviors) XCTAssertEqual(result, -10) } func test__multiplication() { let result = a.multiplying(by: b, withBehavior: behaviors) XCTAssertEqual(result, 200) } func test__division() { let result = a.dividing(by: b, withBehavior: behaviors) XCTAssertEqual(result, 0.5) } func test__remainder() { let result = a.remainder(b, withBehavior: behaviors) XCTAssertEqual(result, 10) } func test__remainder_swift_documentation_examples() { // https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/BasicOperators.html#//apple_ref/doc/uid/TP40014097-CH6-ID63 a = 9; b = 4 XCTAssertEqual(a.remainder(b, withBehavior: behaviors), 1) a = -9; b = 4 XCTAssertEqual(a.remainder(b, withBehavior: behaviors), -1) a = 9; b = -4 XCTAssertEqual(a.remainder(b, withBehavior: behaviors), 1) a = 8; b = 2.5 XCTAssertEqual(a.remainder(b, withBehavior: behaviors), 0.5) } }
c5ff0ca71a3c98b0853d9cc2d343c185
31.864865
168
0.67955
false
true
false
false
amraboelela/swift
refs/heads/master
test/TypeDecoder/local_types.swift
apache-2.0
1
// RUN: %empty-directory(%t) // RUN: %target-build-swift -emit-executable %s -g -o %t/local_types -emit-module // RUN: sed -ne '/\/\/ *DEMANGLE: /s/\/\/ *DEMANGLE: *//p' < %s > %t/input // RUN: %lldb-moduleimport-test %t/local_types -type-from-mangled=%t/input | %FileCheck %s func blackHole(_: Any...) {} func foo() { struct Outer { struct Inner { } struct GenericInner<T> { } } do { let x1 = Outer() let x2 = Outer.Inner() let x3 = Outer.GenericInner<Int>() blackHole(x1, x2, x3) } do { let x1 = Outer.self let x2 = Outer.Inner.self let x3 = Outer.GenericInner<Int>.self blackHole(x1, x2, x3) } } // DEMANGLE: $s11local_types3fooyyF5OuterL_VD // CHECK: Outer // DEMANGLE: $s11local_types3fooyyF5OuterL_V5InnerVD // CHECK: Outer.Inner // DEMANGLE: $s11local_types3fooyyF5OuterL_V12GenericInnerVy_SiGD // CHECK: Outer.GenericInner<Int> // DEMANGLE: $s11local_types3fooyyF5OuterL_VmD // CHECK: Outer.Type // DEMANGLE: $s11local_types3fooyyF5OuterL_V5InnerVmD // CHECK: Outer.Inner.Type // DEMANGLE: $s11local_types3fooyyF5OuterL_V12GenericInnerVy_SiGmD // CHECK: Outer.GenericInner<Int>.Type
6dfb752895d3094566a0e533b58727eb
23.104167
90
0.667243
false
false
false
false
cdtschange/SwiftMKit
refs/heads/master
SwiftMKitDemo/SwiftMKitDemoTests/CachePoolTests.swift
mit
1
// // CachePoolTests.swift // SwiftMKitDemo // // Created by Mao on 6/16/16. // Copyright © 2016 cdts. All rights reserved. // import XCTest @testable import SwiftMKitDemo class CachePoolTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testClearCache() { let cachePool: CachePoolProtocol = CachePool() let isCleared = cachePool.clear() XCTAssertTrue(isCleared) XCTAssertEqual(cachePool.size, 0) } func testCacheModel() { let cachePool: CachePoolProtocol = CachePool() cachePool.clear() let fileName = "icon_user_head" let image = UIImage(named: fileName) XCTAssertNotNil(image) let sizeBeforeCache = cachePool.size let key = (cachePool.addCache(image!, name: fileName)) XCTAssertNotNil(key) sleep(1) let cachedImage = (cachePool.getCache(forKey: key)) as? UIImage XCTAssertNotNil(cachedImage) let sizeAfterCache = cachePool.size var all = cachePool.all() XCTAssertNotNil(all) XCTAssertEqual(all?.count ?? 0, 1) let model = all?.first XCTAssertEqual(model?.size ?? 0, sizeAfterCache-sizeBeforeCache) cachePool.clear() all = cachePool.all() XCTAssertNotNil(all) XCTAssertEqual(all?.count ?? 0, 0) } func testCacheImage() { let cachePool: CachePoolProtocol = CachePool() cachePool.clear() let fileName = "icon_user_head" let image = UIImage(named: fileName) XCTAssertNotNil(image) let sizeBeforeCache = cachePool.size let key = (cachePool.addCache(image!, name: fileName)) XCTAssertNotNil(key) sleep(1) let cachedImage = (cachePool.getCache(forKey: key)) as? UIImage XCTAssertNotNil(cachedImage) let sizeAfterCache = cachePool.size XCTAssertLessThan(sizeBeforeCache, sizeAfterCache) XCTAssertLessThanOrEqual(cachePool.size, cachePool.capacity) let isRemoved = cachePool.removeCache(forKey: key) XCTAssertTrue(isRemoved) let sizeAfterRemoved = cachePool.size XCTAssertEqual(sizeBeforeCache, sizeAfterRemoved) XCTAssertLessThanOrEqual(cachePool.size, cachePool.capacity) let object = (cachePool.getCache(forKey: key)) XCTAssertNil(object) cachePool.clear() } func testCacheNSData() { let cachePool: CachePoolProtocol = CachePool() cachePool.clear() let fileName = "icon_user_head" let data = UIImagePNGRepresentation(UIImage(named: fileName)!) XCTAssertNotNil(data) let sizeBeforeCache = cachePool.size let key = (cachePool.addCache(data!, name: fileName)) XCTAssertNotNil(key) sleep(1) let cachedData = (cachePool.getCache(forKey: key)) as? NSData XCTAssertNotNil(cachedData) let sizeAfterCache = cachePool.size XCTAssertLessThan(sizeBeforeCache, sizeAfterCache) XCTAssertLessThanOrEqual(cachePool.size, cachePool.capacity) let isRemoved = cachePool.removeCache(forKey: key) XCTAssertTrue(isRemoved) let sizeAfterRemoved = cachePool.size XCTAssertEqual(sizeBeforeCache, sizeAfterRemoved) XCTAssertLessThanOrEqual(cachePool.size, cachePool.capacity) let object = (cachePool.getCache(forKey: key)) XCTAssertNil(object) cachePool.clear() } func testCacheFile() { let cachePool: CachePoolProtocol = CachePool() cachePool.clear() let filePath = Bundle.main.path(forResource: "testhaha", ofType: "jpg") let fileName = " " XCTAssertNotNil(filePath) let fileUrl = URL(fileURLWithPath: filePath!) XCTAssertNotNil(fileUrl) let sizeBeforeCache = cachePool.size let key = (cachePool.addCache(fileUrl, name: fileName)) XCTAssertNotNil(key) sleep(1) let cachedFile = UIImage(data: (cachePool.getCache(forKey: key) as! Data)) XCTAssertNotNil(cachedFile) let sizeAfterCache = cachePool.size XCTAssertLessThan(sizeBeforeCache, sizeAfterCache) XCTAssertLessThanOrEqual(cachePool.size, cachePool.capacity) let isRemoved = cachePool.removeCache(forKey: key) XCTAssertTrue(isRemoved) let sizeAfterRemoved = cachePool.size XCTAssertEqual(sizeBeforeCache, sizeAfterRemoved) XCTAssertLessThanOrEqual(cachePool.size, cachePool.capacity) let object = (cachePool.getCache(forKey: key)) XCTAssertNil(object) cachePool.clear() } func testCacheSizeOnlyMatch1() { var cachePool: CachePoolProtocol = CachePool() cachePool.clear() let fileName = "icon_user_head" let image = UIImage(named: fileName) XCTAssertNotNil(image) let sizeBeforeCache = cachePool.size let key = (cachePool.addCache(image!, name: fileName)) XCTAssertNotNil(key) sleep(1) let sizeAfterCache = cachePool.size let sizeOfImage = sizeAfterCache - sizeBeforeCache cachePool.clear() cachePool.capacity = sizeOfImage * 1 let key1 = (cachePool.addCache(image!, name: fileName + "1")) XCTAssertNotNil(key1) sleep(1) var cachedImage1 = (cachePool.getCache(forKey: key1)) as? UIImage XCTAssertNotNil(cachedImage1) XCTAssertLessThanOrEqual(cachePool.size, cachePool.capacity) let key2 = (cachePool.addCache(image!, name: fileName + "2")) XCTAssertNotNil(key2) sleep(1) let cachedImage2 = (cachePool.getCache(forKey: key2)) as? UIImage XCTAssertNotNil(cachedImage2) XCTAssertLessThanOrEqual(cachePool.size, cachePool.capacity) cachedImage1 = (cachePool.getCache(forKey: key1)) as? UIImage XCTAssertNil(cachedImage1) cachePool.clear() } func testCacheSizeMatchManyObjects() { var cachePool: CachePoolProtocol = CachePool() cachePool.clear() let fileName = "icon_user_head" let cacheCount = 10 let image = UIImage(named: fileName) XCTAssertNotNil(image) let sizeBeforeCache = cachePool.size let key = (cachePool.addCache(image!, name: fileName)) XCTAssertNotNil(key) let sizeAfterCache = cachePool.size let sizeOfImage = sizeAfterCache - sizeBeforeCache cachePool.clear() cachePool.capacity = sizeOfImage * Int64(cacheCount) for i in 0..<cacheCount*2 { let key1 = (cachePool.addCache(image!, name: fileName + i.toString)) XCTAssertNotNil(key1) sleep(1) let cachedImage1 = (cachePool.getCache(forKey: key1)) as? UIImage XCTAssertNotNil(cachedImage1) XCTAssertLessThanOrEqual(cachePool.size, cachePool.capacity) } } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
40bfeb1d5f21bc934d18d2eb29b80467
35.454106
111
0.639412
false
true
false
false
JigarM/Swift-Tutorials
refs/heads/master
UICollectionView+Swift/ProfileController.swift
apache-2.0
3
// // ProfileController.swift // UICollectionView+Swift // // Created by Mobmaxime on 15/08/14. // Copyright (c) 2014 Jigar M. All rights reserved. // import UIKit import QuartzCore class ProfileController: UIViewController { @IBOutlet var BannerImage : UIImageView! @IBOutlet var ProfileImage : UIImageView! override func viewDidLoad() { super.viewDidLoad() //1. Circule profile picture //var layer : CALayer = self.ProfileImage?.layer self.ProfileImage.layer.cornerRadius = self.ProfileImage.frame.size.width / 2 self.ProfileImage.layer.borderWidth = 3.5 self.ProfileImage.layer.borderColor = UIColor.whiteColor().CGColor self.ProfileImage.clipsToBounds = true //2. Rectangle Profile shape /* var layer:CALayer = self.ProfileImage.layer! layer.shadowPath = UIBezierPath(rect: layer.bounds).CGPath layer.shouldRasterize = true; layer.rasterizationScale = UIScreen.mainScreen().scale layer.borderColor = UIColor.whiteColor().CGColor layer.borderWidth = 2.0 layer.shadowColor = UIColor.grayColor().CGColor layer.shadowOpacity = 0.4 layer.shadowOffset = CGSizeMake(1, 3) layer.shadowRadius = 1.5 self.ProfileImage.clipsToBounds = false */ // Do any additional setup after loading the view. } /* // #pragma mark - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue?, sender: AnyObject?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ }
03f24a2a91173ce5f4e64a7418a5020e
30.655172
106
0.655773
false
false
false
false
talyadev/EdmundsAPI-Swift
refs/heads/master
EdmundsAPITests/VehicleSpecs_SwiftTests.swift
mit
1
// // VehicleSpecs_SwiftTests.swift // EdmundsAPITests // // Created by Talia DeVault on 1/28/15. // Copyright (c) 2015 Frames Per Sound. All rights reserved. // import UIKit import XCTest import EdmundsAPI class VehicleSpecs_SwiftTests: XCTestCase { let manager = EdmundsAPIManager() override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } //MARK: SPEC: VEHICLE MAKE func testGetAllCarMakes() { let readyExpectation = self.expectationWithDescription("ready") manager.getAllCarMakes(state: EdmundsAPIManager.STATE.kNEW, year: "2014", view: EdmundsAPIManager.VIEW.kBASIC) { (dictionary: NSDictionary?, err: NSError?) -> Void in XCTAssertNotNil(dictionary, "dictionary is nil") readyExpectation.fulfill() } self.waitForExpectationsWithTimeout(5, handler: { (error: NSError!) -> Void in XCTAssertNil(error, "error") }) } func testGetAllCarMakes_OptionalValues() { let readyExpectation = self.expectationWithDescription("ready") manager.getAllCarMakes(state: nil, year: nil, view: nil) { (dictionary: NSDictionary?, err: NSError?) -> Void in XCTAssertNotNil(dictionary, "dictionary is nil") readyExpectation.fulfill() } self.waitForExpectationsWithTimeout(5, handler: { (error: NSError!) -> Void in XCTAssertNil(error, "error") }) } func testGetCarMakeDetailsByMakeNicename() { let readyExpectation = self.expectationWithDescription("ready") manager.getCarMakeDetailsByMakeNicename(makeNiceName: "Audi", state: EdmundsAPIManager.STATE.kNEW, year: "2014", view: EdmundsAPIManager.VIEW.kBASIC) { (dictionary: NSDictionary?, err: NSError?) -> Void in XCTAssertNotNil(dictionary, "dictionary is nil") readyExpectation.fulfill() } self.waitForExpectationsWithTimeout(5, handler: { (error: NSError!) -> Void in XCTAssertNil(error, "error") }) } func testGetCarMakeDetailsByMakeNicename_OptionalValues() { let readyExpectation = self.expectationWithDescription("ready") manager.getCarMakeDetailsByMakeNicename(makeNiceName: "Audi", state: nil, year: nil, view: nil) { (dictionary: NSDictionary?, err: NSError?) -> Void in XCTAssertNotNil(dictionary, "dictionary is nil") readyExpectation.fulfill() } self.waitForExpectationsWithTimeout(5, handler: { (error: NSError!) -> Void in XCTAssertNil(error, "error") }) } func testGetCarMakesCount() { let readyExpectation = self.expectationWithDescription("ready") manager.getCarMakesCount(state: EdmundsAPIManager.STATE.kNEW, year: "2014", view: EdmundsAPIManager.VIEW.kBASIC) { (dictionary: NSDictionary?, err: NSError?) -> Void in XCTAssertNotNil(dictionary, "dictionary is nil") readyExpectation.fulfill() } self.waitForExpectationsWithTimeout(5, handler: { (error: NSError!) -> Void in XCTAssertNil(error, "error") }) } func testGetCarMakesCount_OptionalValues() { let readyExpectation = self.expectationWithDescription("ready") manager.getCarMakesCount(state: nil, year: nil, view: nil) { (dictionary: NSDictionary?, err: NSError?) -> Void in XCTAssertNotNil(dictionary, "dictionary is nil") readyExpectation.fulfill() } self.waitForExpectationsWithTimeout(5, handler: { (error: NSError!) -> Void in XCTAssertNil(error, "error") }) } //MARK: SPEC: VEHICLE MODEL func testGetCarModelDetailsByCarMakeAndModelNicenames() { let readyExpectation = self.expectationWithDescription("ready") manager.getCarModelDetailsByCarMakeAndModelNicenames(makeNiceName: "honda", modelNiceName: "accord", state: EdmundsAPIManager.STATE.kNEW, year: "2014", view: EdmundsAPIManager.VIEW.kBASIC) { (dictionary: NSDictionary?, error: NSError?) -> Void in XCTAssertNotNil(dictionary, "dictionary is nil") readyExpectation.fulfill() } self.waitForExpectationsWithTimeout(5, handler: { (error: NSError!) -> Void in XCTAssertNil(error, "error") }) } func testGetCarModelDetailsByCarMakeAndModelNicenames_OptionalValues() { let readyExpectation = self.expectationWithDescription("ready") manager.getCarModelDetailsByCarMakeAndModelNicenames(makeNiceName: "honda", modelNiceName: "accord", state: nil, year: nil, view: nil) { (dictionary: NSDictionary?, error: NSError?) -> Void in XCTAssertNotNil(dictionary, "dictionary is nil") readyExpectation.fulfill() } self.waitForExpectationsWithTimeout(5, handler: { (error: NSError!) -> Void in XCTAssertNil(error, "error") }) } func testGetAllCarModelsByACarMakeNicename() { let readyExpectation = self.expectationWithDescription("ready") manager.getAllCarModelsByACarMakeNicename(makeNiceName: "bmw", state: EdmundsAPIManager.STATE.kNEW, year: "2013", category: EdmundsAPIManager.CATEGORY.kSEDAN, view: EdmundsAPIManager.VIEW.kBASIC) { (dictionary: NSDictionary?, error: NSError?) -> Void in XCTAssertNotNil(dictionary, "dictionary is nil") readyExpectation.fulfill() } self.waitForExpectationsWithTimeout(5, handler: { (error: NSError!) -> Void in XCTAssertNil(error, "error") }) } func testGetAllCarModelsByACarMakeNicename_OptionalValues() { let readyExpectation = self.expectationWithDescription("ready") manager.getAllCarModelsByACarMakeNicename(makeNiceName: "bmw", state: nil, year: nil, category: nil, view: nil) { (dictionary: NSDictionary?, error: NSError?) -> Void in XCTAssertNotNil(dictionary, "dictionary is nil") readyExpectation.fulfill() } self.waitForExpectationsWithTimeout(5, handler: { (error: NSError!) -> Void in XCTAssertNil(error, "error") }) } func testGetCarModelsCount() { let readyExpectation = self.expectationWithDescription("ready") manager.getCarModelsCount(makeNiceName: "honda", state: EdmundsAPIManager.STATE.kUSED, year: "2011", category: EdmundsAPIManager.CATEGORY.kCOUPE, view: EdmundsAPIManager.VIEW.kBASIC) { (dictionary: NSDictionary?, error: NSError?) -> Void in XCTAssertNotNil(dictionary, "dictionary is nil") readyExpectation.fulfill() } self.waitForExpectationsWithTimeout(5, handler: { (error: NSError!) -> Void in XCTAssertNil(error, "error") }) } func testGetCarModelsCount_OptionalValues() { let readyExpectation = self.expectationWithDescription("ready") manager.getCarModelsCount(makeNiceName: "honda", state: nil, year: nil, category: nil, view: nil) { (dictionary: NSDictionary?, error: NSError?) -> Void in XCTAssertNotNil(dictionary, "dictionary is nil") readyExpectation.fulfill() } self.waitForExpectationsWithTimeout(5, handler: { (error: NSError!) -> Void in XCTAssertNil(error, "error") }) } //MARK: SPEC: VEHICLE MODEL YEAR func testGetCarModelYearByCarMakeAndModelNicenames() { let readyExpectation = self.expectationWithDescription("ready") manager.getCarModelYearByCarMakeAndModelNicenames(makeNiceName: "honda", modelNiceName: "accord", state: EdmundsAPIManager.STATE.kNEW, category: EdmundsAPIManager.CATEGORY.kCOUPE, view: EdmundsAPIManager.VIEW.kFULL) { (dictionary: NSDictionary?, error: NSError?) -> Void in XCTAssertNotNil(dictionary, "dictionary is nil") readyExpectation.fulfill() } self.waitForExpectationsWithTimeout(5, handler: { (error: NSError!) -> Void in XCTAssertNil(error, "error") }) } func testGetCarModelYearByCarMakeAndModelNicenames_OptionalValues() { let readyExpectation = self.expectationWithDescription("ready") manager.getCarModelYearByCarMakeAndModelNicenames(makeNiceName: "honda", modelNiceName: "accord", state: nil, category: nil, view: nil) { (dictionary: NSDictionary?, error: NSError?) -> Void in XCTAssertNotNil(dictionary, "dictionary is nil") readyExpectation.fulfill() } self.waitForExpectationsWithTimeout(5, handler: { (error: NSError!) -> Void in XCTAssertNil(error, "error") }) } func testGetCarModelYearByCarMakeAndModelNicenamesAndTheCarYear() { let readyExpectation = self.expectationWithDescription("ready") manager.getCarModelYearByCarMakeAndModelNicenamesAndTheCarYear(makeNiceName: "honda", modelNiceName: "civic", year: "2013", category: EdmundsAPIManager.CATEGORY.kSEDAN, view: EdmundsAPIManager.VIEW.kFULL) { (dictionary: NSDictionary?, error: NSError?) -> Void in XCTAssertNotNil(dictionary, "dictionary is nil") readyExpectation.fulfill() } self.waitForExpectationsWithTimeout(5, handler: { (error: NSError!) -> Void in XCTAssertNil(error, "error") }) } func testGetCarModelYearByCarMakeAndModelNicenamesAndTheCarYear_OptionalValues() { let readyExpectation = self.expectationWithDescription("ready") manager.getCarModelYearByCarMakeAndModelNicenamesAndTheCarYear(makeNiceName: "honda", modelNiceName: "civic", year: "2013", category: nil, view: nil) { (dictionary: NSDictionary?, error: NSError?) -> Void in XCTAssertNotNil(dictionary, "dictionary is nil") readyExpectation.fulfill() } self.waitForExpectationsWithTimeout(5, handler: { (error: NSError!) -> Void in XCTAssertNil(error, "error") }) } func testGetCarModelYearsCountByVehicleMakeAndModelNicenames() { let readyExpectation = self.expectationWithDescription("ready") manager.getCarModelYearsCountByVehicleMakeAndModelNicenames(makeNiceName: "audi", modelNiceName: "a6", state: EdmundsAPIManager.STATE.kNEW, view: EdmundsAPIManager.VIEW.kFULL) { (dictionary: NSDictionary?, error: NSError?) -> Void in XCTAssertNotNil(dictionary, "dictionary is nil") readyExpectation.fulfill() } self.waitForExpectationsWithTimeout(5, handler: { (error: NSError!) -> Void in XCTAssertNil(error, "error") }) } func testGetCarModelYearsCountByVehicleMakeAndModelNicenames_OptionalValues() { let readyExpectation = self.expectationWithDescription("ready") manager.getCarModelYearsCountByVehicleMakeAndModelNicenames(makeNiceName: "audi", modelNiceName: "a6", state: nil, view: nil) { (dictionary: NSDictionary?, error: NSError?) -> Void in XCTAssertNotNil(dictionary, "dictionary is nil") readyExpectation.fulfill() } self.waitForExpectationsWithTimeout(5, handler: { (error: NSError!) -> Void in XCTAssertNil(error, "error") }) } //MARK: SPEC: VEHICLE STYLE func testGetStyleDetailsByID() { let readyExpectation = self.expectationWithDescription("ready") manager.getStyleDetailsByID(id: "200487199", view: EdmundsAPIManager.VIEW.kFULL) { (dictionary: NSDictionary?, error: NSError?) -> Void in XCTAssertNotNil(dictionary, "dictionary is nil") readyExpectation.fulfill() } self.waitForExpectationsWithTimeout(5, handler: { (error: NSError!) -> Void in XCTAssertNil(error, "error") }) } func testGetStyleDetailsByID_ViewNil() { let readyExpectation = self.expectationWithDescription("ready") manager.getStyleDetailsByID(id: "200487199", view: nil) { (dictionary: NSDictionary?, error: NSError?) -> Void in XCTAssertNotNil(dictionary, "dictionary is nil") readyExpectation.fulfill() } self.waitForExpectationsWithTimeout(5, handler: { (error: NSError!) -> Void in XCTAssertNil(error, "error") }) } func testGetStylesDetailsByVehicleMakeModelYear() { let readyExpectation = self.expectationWithDescription("ready") manager.getStylesDetailsByVehicleMakeModelYear(makeNiceName: "honda", modelNiceName: "pilot", year: "2010", state: EdmundsAPIManager.STATE.kUSED, category: EdmundsAPIManager.CATEGORY.kSEDAN, view: EdmundsAPIManager.VIEW.kFULL) { (dictionary: NSDictionary?, error: NSError?) -> Void in XCTAssertNotNil(dictionary, "dictionary is nil") readyExpectation.fulfill() } self.waitForExpectationsWithTimeout(5, handler: { (error: NSError!) -> Void in XCTAssertNil(error, "error") }) } func testGetStylesDetailsByVehicleMakeModelYear_OptionalValues() { let readyExpectation = self.expectationWithDescription("ready") manager.getStylesDetailsByVehicleMakeModelYear(makeNiceName: "honda", modelNiceName: "pilot", year: "2010", state: nil, category: nil, view: nil) { (dictionary: NSDictionary?, error: NSError?) -> Void in XCTAssertNotNil(dictionary, "dictionary is nil") readyExpectation.fulfill() } self.waitForExpectationsWithTimeout(5, handler: { (error: NSError!) -> Void in XCTAssertNil(error, "error") }) } func testGetStylesCountByVehicleMakeModelYear() { let readyExpectation = self.expectationWithDescription("ready") manager.getStylesCountByVehicleMakeModelYear(makeNiceName: "honda", modelNiceName: "pilot", year: "2010", state: EdmundsAPIManager.STATE.kUSED) { (dictionary: NSDictionary?, error: NSError?) -> Void in XCTAssertNotNil(dictionary, "dictionary is nil") readyExpectation.fulfill() } self.waitForExpectationsWithTimeout(5, handler: { (error: NSError!) -> Void in XCTAssertNil(error, "error") }) } func testGetStylesCountByVehicleMakeModelYear_StateNil() { let readyExpectation = self.expectationWithDescription("ready") manager.getStylesCountByVehicleMakeModelYear(makeNiceName: "honda", modelNiceName: "pilot", year: "2010", state: nil) { (dictionary: NSDictionary?, error: NSError?) -> Void in XCTAssertNotNil(dictionary, "dictionary is nil") readyExpectation.fulfill() } self.waitForExpectationsWithTimeout(5, handler: { (error: NSError!) -> Void in XCTAssertNil(error, "error") }) } func testGetStylesCountByVehicleMakeAndModel() { let readyExpectation = self.expectationWithDescription("ready") manager.getStylesCountByVehicleMakeAndModel(makeNiceName: "honda", modelNiceName: "pilot", state: EdmundsAPIManager.STATE.kUSED) { (dictionary: NSDictionary?, error: NSError?) -> Void in XCTAssertNotNil(dictionary, "dictionary is nil") readyExpectation.fulfill() } self.waitForExpectationsWithTimeout(5, handler: { (error: NSError!) -> Void in XCTAssertNil(error, "error") }) } func testGetStylesCountByVehicleMakeAndModel_StateNil() { let readyExpectation = self.expectationWithDescription("ready") manager.getStylesCountByVehicleMakeAndModel(makeNiceName: "honda", modelNiceName: "pilot", state: nil) { (dictionary: NSDictionary?, error: NSError?) -> Void in XCTAssertNotNil(dictionary, "dictionary is nil") readyExpectation.fulfill() } self.waitForExpectationsWithTimeout(5, handler: { (error: NSError!) -> Void in XCTAssertNil(error, "error") }) } func testGetStylesCountByVehicleMake() { let readyExpectation = self.expectationWithDescription("ready") manager.getStylesCountByVehicleMake(makeNiceName: "honda", state: EdmundsAPIManager.STATE.kUSED) { (dictionary: NSDictionary?, error: NSError?) -> Void in XCTAssertNotNil(dictionary, "dictionary is nil") readyExpectation.fulfill() } self.waitForExpectationsWithTimeout(5, handler: { (error: NSError!) -> Void in XCTAssertNil(error, "error") }) } func testGetStylesCountByVehicleMake_StateNil() { let readyExpectation = self.expectationWithDescription("ready") manager.getStylesCountByVehicleMake(makeNiceName: "honda", state: nil) { (dictionary: NSDictionary?, error: NSError?) -> Void in XCTAssertNotNil(dictionary, "dictionary is nil") readyExpectation.fulfill() } self.waitForExpectationsWithTimeout(5, handler: { (error: NSError!) -> Void in XCTAssertNil(error, "error") }) } func testGetStylesCount() { let readyExpectation = self.expectationWithDescription("ready") manager.getStylesCount(state: EdmundsAPIManager.STATE.kUSED) { (dictionary: NSDictionary?, error: NSError?) -> Void in XCTAssertNotNil(dictionary, "dictionary is nil") readyExpectation.fulfill() } self.waitForExpectationsWithTimeout(5, handler: { (error: NSError!) -> Void in XCTAssertNil(error, "error") }) } func testGetStylesDetailsByVehicleChromeID() { let readyExpectation = self.expectationWithDescription("ready") manager.getStylesDetailsByVehicleChromeID(chromeId: "11916", view: EdmundsAPIManager.VIEW.kFULL) { (dictionary: NSDictionary?, error: NSError?) -> Void in XCTAssertNotNil(dictionary, "dictionary is nil") readyExpectation.fulfill() } self.waitForExpectationsWithTimeout(5, handler: { (error: NSError!) -> Void in XCTAssertNil(error, "error") }) } //MARK: SPEC: VEHICLE COLORS AND OPTIONS func testGetListOfOptionsByStyleID() { let readyExpectation = self.expectationWithDescription("ready") manager.getListOfOptionsByStyleID(id: "200477465", category: EdmundsAPIManager.OPTIONS.kEXTERIOR) { (dictionary: NSDictionary?, error: NSError?) -> Void in XCTAssertNotNil(dictionary, "dictionary is nil") readyExpectation.fulfill() } self.waitForExpectationsWithTimeout(5, handler: { (error: NSError!) -> Void in XCTAssertNil(error, "error") }) } func testGetListOfOptionsByStyleID_CategoryNil() { let readyExpectation = self.expectationWithDescription("ready") manager.getListOfOptionsByStyleID(id: "200477465", category: nil) { (dictionary: NSDictionary?, error: NSError?) -> Void in XCTAssertNotNil(dictionary, "dictionary is nil") readyExpectation.fulfill() } self.waitForExpectationsWithTimeout(5, handler: { (error: NSError!) -> Void in XCTAssertNil(error, "error") }) } func testGetOptionsDetailsByID() { let readyExpectation = self.expectationWithDescription("ready") manager.getOptionsDetailsByID(id: "200477465") { (dictionary: NSDictionary?, error: NSError?) -> Void in XCTAssertNotNil(dictionary, "dictionary is nil") readyExpectation.fulfill() } self.waitForExpectationsWithTimeout(5, handler: { (error: NSError!) -> Void in XCTAssertNil(error, "error") }) } func testGetListOfColorsByStyleID() { let readyExpectation = self.expectationWithDescription("ready") manager.getListOfColorsByStyleID(id: "200477465", category: EdmundsAPIManager.OPTIONS.kEXTERIOR) { (dictionary: NSDictionary?, error: NSError?) -> Void in XCTAssertNotNil(dictionary, "dictionary is nil") readyExpectation.fulfill() } self.waitForExpectationsWithTimeout(5, handler: { (error: NSError!) -> Void in XCTAssertNil(error, "error") }) } func testGetListOfColorsByStyleID_CategoryNil() { let readyExpectation = self.expectationWithDescription("ready") manager.getListOfColorsByStyleID(id: "200477465", category: EdmundsAPIManager.OPTIONS.kEXTERIOR) { (dictionary: NSDictionary?, error: NSError?) -> Void in XCTAssertNotNil(dictionary, "dictionary is nil") readyExpectation.fulfill() } self.waitForExpectationsWithTimeout(5, handler: { (error: NSError!) -> Void in XCTAssertNil(error, "error") }) } func testGetColorsDetailsByID() { let readyExpectation = self.expectationWithDescription("ready") manager.getColorsDetailsByID(id: "200477486") { (dictionary: NSDictionary?, error: NSError?) -> Void in XCTAssertNotNil(dictionary, "dictionary is nil") readyExpectation.fulfill() } self.waitForExpectationsWithTimeout(5, handler: { (error: NSError!) -> Void in XCTAssertNil(error, "error") }) } func testGetListOfEnginesByStyleID() { let readyExpectation = self.expectationWithDescription("ready") manager.getListOfEnginesByStyleID(id: "200477465", availability: EdmundsAPIManager.AVAILABILITY.kSTANDARD) { (dictionary: NSDictionary?, error: NSError?) -> Void in XCTAssertNotNil(dictionary, "dictionary is nil") readyExpectation.fulfill() } self.waitForExpectationsWithTimeout(5, handler: { (error: NSError!) -> Void in XCTAssertNil(error, "error") }) } func testGetListOfEnginesByStyleID_AvailabilityNil() { let readyExpectation = self.expectationWithDescription("ready") manager.getListOfEnginesByStyleID(id: "200477465", availability: nil) { (dictionary: NSDictionary?, error: NSError?) -> Void in XCTAssertNotNil(dictionary, "dictionary is nil") readyExpectation.fulfill() } self.waitForExpectationsWithTimeout(5, handler: { (error: NSError!) -> Void in XCTAssertNil(error, "error") }) } func testGetEngineDetailsByID() { let readyExpectation = self.expectationWithDescription("ready") manager.getEngineDetailsByID(id: "200477467") { (dictionary: NSDictionary?, error: NSError?) -> Void in XCTAssertNotNil(dictionary, "dictionary is nil") readyExpectation.fulfill() } self.waitForExpectationsWithTimeout(5, handler: { (error: NSError!) -> Void in XCTAssertNil(error, "error") }) } func testGetListOfTransmissionsByStyleID() { let readyExpectation = self.expectationWithDescription("ready") manager.getListOfTransmissionsByStyleID(id: "200477465", availability: EdmundsAPIManager.AVAILABILITY.kSTANDARD) { (dictionary: NSDictionary?, error: NSError?) -> Void in XCTAssertNotNil(dictionary, "dictionary is nil") readyExpectation.fulfill() } self.waitForExpectationsWithTimeout(5, handler: { (error: NSError!) -> Void in XCTAssertNil(error, "error") }) } func testGetListOfTransmissionsByStyleID_AvailabilityNil() { let readyExpectation = self.expectationWithDescription("ready") manager.getListOfTransmissionsByStyleID(id: "200477465", availability: nil) { (dictionary: NSDictionary?, error: NSError?) -> Void in XCTAssertNotNil(dictionary, "dictionary is nil") readyExpectation.fulfill() } self.waitForExpectationsWithTimeout(5, handler: { (error: NSError!) -> Void in XCTAssertNil(error, "error") }) } func testGetTransmissionDetailsByID() { let readyExpectation = self.expectationWithDescription("ready") manager.getTransmissionDetailsByID(id: "200477468") { (dictionary: NSDictionary?, error: NSError?) -> Void in XCTAssertNotNil(dictionary, "dictionary is nil") readyExpectation.fulfill() } self.waitForExpectationsWithTimeout(5, handler: { (error: NSError!) -> Void in XCTAssertNil(error, "error") }) } //MARK: SPEC: VEHICLE EQUIPMENT func testGetEquipmentDetailsByStyleID() { let readyExpectation = self.expectationWithDescription("ready") manager.getEquipmentDetailsByStyleID(id: "200477465", availability: EdmundsAPIManager.AVAILABILITY.kSTANDARD, equipmentType: EdmundsAPIManager.EQUIPMENTTYPE.kOTHER, name: EdmundsAPIManager.EQUIPMENTNAME.k1STROWSEATS) { (dictionary: NSDictionary?, error: NSError?) -> Void in XCTAssertNotNil(dictionary, "dictionary is nil") readyExpectation.fulfill() } self.waitForExpectationsWithTimeout(5, handler: { (error: NSError!) -> Void in XCTAssertNil(error, "error") }) } func testGetEquipmentDetailsByStyleID_NameNil() { let readyExpectation = self.expectationWithDescription("ready") manager.getEquipmentDetailsByStyleID(id: "200477465", availability: EdmundsAPIManager.AVAILABILITY.kSTANDARD, equipmentType: EdmundsAPIManager.EQUIPMENTTYPE.kOTHER, name: nil) { (dictionary: NSDictionary?, error: NSError?) -> Void in XCTAssertNotNil(dictionary, "dictionary is nil") readyExpectation.fulfill() } self.waitForExpectationsWithTimeout(5, handler: { (error: NSError!) -> Void in XCTAssertNil(error, "error") }) } func testGetEquipmentDetailsByID_NameNil() { let readyExpectation = self.expectationWithDescription("ready") manager.getEquipmentDetailsByID(id: "200477520") { (dictionary: NSDictionary?, error: NSError?) -> Void in XCTAssertNotNil(dictionary, "dictionary is nil") readyExpectation.fulfill() } self.waitForExpectationsWithTimeout(5, handler: { (error: NSError!) -> Void in XCTAssertNil(error, "error") }) } //MARK: SPEC: VEHICLE SQUISHVINS func testGetVehicleDetailsBySquishVIN() { let readyExpectation = self.expectationWithDescription("ready") manager.getVehicleDetailsBySquishVIN(id: "1GTGG29W11") { (dictionary: NSDictionary?, error: NSError?) -> Void in XCTAssertNotNil(dictionary, "dictionary is nil") readyExpectation.fulfill() } self.waitForExpectationsWithTimeout(5, handler: { (error: NSError!) -> Void in XCTAssertNil(error, "error") }) } //MARK: SPEC: VEHICLE CONFIGURATION func testGetDefaultConfiguredVehicleByZipcodeAndStyleID() { let readyExpectation = self.expectationWithDescription("ready") manager.getDefaultConfiguredVehicleByZipcodeAndStyleID(zip: "90019", styleid: "200477465") { (dictionary: NSDictionary?, error: NSError?) -> Void in XCTAssertNotNil(dictionary, "dictionary is nil") readyExpectation.fulfill() } self.waitForExpectationsWithTimeout(5, handler: { (error: NSError!) -> Void in XCTAssertNil(error, "error") }) } func testGetConfiguredVehicleWithOptions() { let readyExpectation = self.expectationWithDescription("ready") manager.getConfiguredVehicleWithOptions(zip: "90019", styleid: "200477465", selected: "200477503") { (dictionary: NSDictionary?, error: NSError?) -> Void in XCTAssertNotNil(dictionary, "dictionary is nil") readyExpectation.fulfill() } self.waitForExpectationsWithTimeout(5, handler: { (error: NSError!) -> Void in XCTAssertNil(error, "error") }) } //MARK: SPEC: VIN DECODING func testGetBasicVehicleInformationByVIN() { let readyExpectation = self.expectationWithDescription("ready") manager.getBasicVehicleInformationByVIN(vin: "2G1FC3D33C9165616") { (dictionary: NSDictionary?, error: NSError?) -> Void in XCTAssertNotNil(dictionary, "dictionary is nil") readyExpectation.fulfill() } self.waitForExpectationsWithTimeout(5, handler: { (error: NSError!) -> Void in XCTAssertNil(error, "error") }) } func testGetFullVehicleDetailsByVIN() { let readyExpectation = self.expectationWithDescription("ready") manager.getBasicVehicleInformationByVIN(vin: "2G1FC3D33C9165616") { (dictionary: NSDictionary?, error: NSError?) -> Void in XCTAssertNotNil(dictionary, "dictionary is nil") readyExpectation.fulfill() } self.waitForExpectationsWithTimeout(5, handler: { (error: NSError!) -> Void in XCTAssertNil(error, "error") }) } }
44cbaf992cf4b9a2d1b90b755edf285b
48.511149
292
0.66505
false
true
false
false
sync/NearbyTrams
refs/heads/master
NearbyTramsKit/Source/RoutesProvider.swift
mit
1
// // Copyright (c) 2014 Dblechoc. All rights reserved. // import Foundation import NearbyTramsStorageKit import NearbyTramsNetworkKit public class RoutesProvider { let networkService: NetworkService let managedObjectContext: NSManagedObjectContext public init (networkService: NetworkService = NetworkService(), managedObjectContext: NSManagedObjectContext) { self.networkService = networkService self.managedObjectContext = managedObjectContext } public func getAllRoutesWithManagedObjectContext(managedObjectContext: NSManagedObjectContext, completionHandler: (([NSManagedObjectID]?, NSError?) -> Void)?) -> Void { let task = networkService.getAllRoutesWithCompletionHandler { routes, error -> Void in if error.hasValue { if let handler = completionHandler { dispatch_async(dispatch_get_main_queue()) { handler(nil, error) } } } else if routes.hasValue { let localContext = NSManagedObjectContext(concurrencyType: .ConfinementConcurrencyType) localContext.parentContext = managedObjectContext let result: (routes: [Route?], errors: [NSError?]) = Route.insertOrUpdateFromRestArray(routes!, inManagedObjectContext: localContext) localContext.save(nil) var objectIds: [NSManagedObjectID] = [] for potentialRoute in result.routes { if let route = potentialRoute { objectIds.append(route.objectID) } } if let handler = completionHandler { dispatch_async(dispatch_get_main_queue()) { handler(objectIds, nil) } } } else { if let handler = completionHandler { dispatch_async(dispatch_get_main_queue()) { // FIXME: build a decent error here let error = NSError() handler(nil, error) } } } } } }
385034b6607ed55f26726c78534971b0
33.222222
170
0.512175
false
false
false
false
Crowdmix/Buildasaur
refs/heads/master
BuildaKit/Persistence.swift
mit
4
// // Persistence.swift // Buildasaur // // Created by Honza Dvorsky on 07/03/2015. // Copyright (c) 2015 Honza Dvorsky. All rights reserved. // import Foundation import BuildaUtils public class Persistence { public class func loadJSONFromUrl(url: NSURL) throws -> AnyObject? { let data = try NSData(contentsOfURL: url, options: NSDataReadingOptions()) let json: AnyObject = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) return json } public class func saveJSONToUrl(json: AnyObject, url: NSURL) throws { let data = try NSJSONSerialization.dataWithJSONObject(json, options: NSJSONWritingOptions.PrettyPrinted) try data.writeToURL(url, options: NSDataWritingOptions.DataWritingAtomic) } public class func getFileInAppSupportWithName(name: String, isDirectory: Bool) -> NSURL { let root = self.buildaApplicationSupportFolderURL() let url = root.URLByAppendingPathComponent(name, isDirectory: isDirectory) if isDirectory { self.createFolderIfNotExists(url) } return url } public class func createFolderIfNotExists(url: NSURL) { let fm = NSFileManager.defaultManager() do { try fm.createDirectoryAtURL(url, withIntermediateDirectories: true, attributes: nil) } catch { fatalError("Failed to create a folder in Builda's Application Support folder \(url), error \(error)") } } public class func buildaApplicationSupportFolderURL() -> NSURL { let fm = NSFileManager.defaultManager() if let appSupport = fm.URLsForDirectory(NSSearchPathDirectory.ApplicationSupportDirectory, inDomains:NSSearchPathDomainMask.UserDomainMask).first { let buildaAppSupport = appSupport.URLByAppendingPathComponent("Buildasaur", isDirectory: true) //ensure it exists do { try fm.createDirectoryAtURL(buildaAppSupport, withIntermediateDirectories: true, attributes: nil) return buildaAppSupport } catch { Log.error("Failed to create Builda's Application Support folder, error \(error)") } } assertionFailure("Couldn't access Builda's persistence folder, aborting") return NSURL() } public class func iterateThroughFilesInFolder(folderUrl: NSURL, visit: (url: NSURL) -> ()) { let fm = NSFileManager.defaultManager() do { let contents = try fm.contentsOfDirectoryAtURL(folderUrl, includingPropertiesForKeys: nil, options: [.SkipsHiddenFiles, .SkipsSubdirectoryDescendants]) contents.forEach { visit(url: $0) } } catch { Log.error("Couldn't read folder \(folderUrl), error \(error)") } } }
0fb7f3dd4192a7b353b8deb62e60b3a3
36.481013
163
0.647754
false
false
false
false
lanserxt/teamwork-ios-sdk
refs/heads/master
TeamWorkClient/TeamWorkClient/Requests/TWApiClient+Categories.swift
mit
1
// // TWApiClient+Invoices.swift // TeamWorkClient // // Created by Anton Gubarenko on 02.02.17. // Copyright © 2017 Anton Gubarenko. All rights reserved. // import Foundation import Alamofire public enum TWCategory: String { case Message = "messageCategories" case File = "fileCategories" case Notebook = "notebookCategories" case Link = "linkCategories" case Project = "projectCategories" } extension TWApiClient{ func createCategory(projectId: String, category: Category, categoryType: TWCategory, _ responseBlock: @escaping (Bool, Int, Category?, Error?) -> Void){ let parameters: [String : Any] = ["category" : category.dictionaryRepresentation() as! [String : Any]] Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.createCategory.path, projectId, categoryType.rawValue), method: HTTPMethod.post, parameters: parameters, encoding: URLEncoding.default, headers: nil) .validate(statusCode: 200..<300) .validate(contentType: [kContentType]) .authenticate(user: kApiToken, password: kAuthPass) .responseJSON { response in switch response.result { case .success: if let result = response.result.value { let JSON = result as! NSDictionary if let responseContainer = ResponseContainer<Category>.init(rootObjectName: TWApiClientConstants.APIPath.createCategory.rootElement, dictionary: JSON){ if (responseContainer.status == TWApiStatusCode.OK){ responseBlock (true, 200, responseContainer.rootObject, nil) } else { responseBlock (false, 0, nil, TWApiClientErrors.ResponseStatusNotOK) } } else { responseBlock (false, 0, nil, TWApiClientErrors.ResponseValidationError) } } case .failure(let error): print(error) responseBlock(false, (response.response?.statusCode)!, nil, error) } } } func getSingleCategory(categoryId: String, categoryType: TWCategory, _ responseBlock: @escaping (Bool, Int, Category?, Error?) -> Void){ Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.getSingleCategory.path, categoryType.rawValue, categoryId), method: HTTPMethod.get, parameters: nil, encoding: URLEncoding.default, headers: nil) .validate(statusCode: 200..<300) .validate(contentType: [kContentType]) .authenticate(user: kApiToken, password: kAuthPass) .responseJSON { response in switch response.result { case .success: if let result = response.result.value { let JSON = result as! NSDictionary if let responseContainer = ResponseContainer<Category>.init(rootObjectName: TWApiClientConstants.APIPath.getSingleCategory.rootElement, dictionary: JSON){ if (responseContainer.status == TWApiStatusCode.OK){ responseBlock (true, 200, responseContainer.rootObject, nil) } else { responseBlock (false, 0, nil, TWApiClientErrors.ResponseStatusNotOK) } } else { responseBlock (false, 0, nil, TWApiClientErrors.ResponseValidationError) } } case .failure(let error): print(error) responseBlock(false, (response.response?.statusCode)!, nil, error) } } } func getAllCategoriesForProject(projectId: String, categoryType: TWCategory, _ responseBlock: @escaping (Bool, Int, [Category]?, Error?) -> Void){ Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.getAllCategoriesForProject.path, projectId, categoryType.rawValue), method: HTTPMethod.get, parameters: nil, encoding: URLEncoding.default, headers: nil) .validate(statusCode: 200..<300) .validate(contentType: [kContentType]) .authenticate(user: kApiToken, password: kAuthPass) .responseJSON { response in switch response.result { case .success: if let result = response.result.value { let JSON = result as! NSDictionary if let responseContainer = MultipleResponseContainer<Category>.init(rootObjectName: TWApiClientConstants.APIPath.getAllCategoriesForProject.rootElement, dictionary: JSON){ if (responseContainer.status == TWApiStatusCode.OK){ responseBlock (true, 200, responseContainer.rootObjects, nil) } else { responseBlock (false, 0, nil, TWApiClientErrors.ResponseStatusNotOK) } } else { responseBlock (false, 0, nil, TWApiClientErrors.ResponseValidationError) } } case .failure(let error): print(error) responseBlock(false, (response.response?.statusCode)!, nil, error) } } } func updateCategory(category: Category, categoryType: TWCategory, _ responseBlock: @escaping (Bool, Int, Error?) -> Void){ let parameters: [String : Any] = ["category" : category.dictionaryRepresentation() as! [String : Any]] Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.updateCategory.path, category.id!, categoryType.rawValue), method: HTTPMethod.put, parameters: parameters, encoding: URLEncoding.default, headers: nil) .validate(statusCode: 200..<300) .validate(contentType: [kContentType]) .authenticate(user: kApiToken, password: kAuthPass) .responseJSON { response in switch response.result { case .success: if let result = response.result.value { let JSON = result as! NSDictionary if let responseContainer = ResponseContainer<Category>.init(rootObjectName: TWApiClientConstants.APIPath.updateCategory.rootElement, dictionary: JSON){ if (responseContainer.status == TWApiStatusCode.OK){ responseBlock (true, 200, nil) } else { responseBlock (false, 0, TWApiClientErrors.ResponseStatusNotOK) } } else { responseBlock (false, 0, TWApiClientErrors.ResponseValidationError) } } case .failure(let error): print(error) responseBlock(false, (response.response?.statusCode)!, error) } } } func deleteCategory(category: Category, categoryType: TWCategory, _ responseBlock: @escaping (Bool, Int, Error?) -> Void){ Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.deleteCategory.path, category.id!, categoryType.rawValue), method: HTTPMethod.delete, parameters: nil, encoding: URLEncoding.default, headers: nil) .validate(statusCode: 200..<300) .validate(contentType: [kContentType]) .authenticate(user: kApiToken, password: kAuthPass) .responseJSON { response in switch response.result { case .success: if let result = response.result.value { let JSON = result as! NSDictionary if let responseContainer = ResponseContainer<Category>.init(rootObjectName: TWApiClientConstants.APIPath.deleteCategory.rootElement, dictionary: JSON){ if (responseContainer.status == TWApiStatusCode.OK){ responseBlock (true, 200, nil) } else { responseBlock (false, 0, TWApiClientErrors.ResponseStatusNotOK) } } else { responseBlock (false, 0, TWApiClientErrors.ResponseValidationError) } } case .failure(let error): print(error) responseBlock(false, (response.response?.statusCode)!, error) } } } }
0199c283703c75cfcfa17d5cbc1735da
51.805714
239
0.549399
false
false
false
false
AlwaysRightInstitute/SwiftySecurity
refs/heads/develop
SwiftySecurity/PKCS12.swift
mit
1
// // PKCS12.swift // TestSwiftyDocker // // Created by Helge Hess on 07/05/15. // Copyright (c) 2015 Helge Hess. All rights reserved. // import Foundation // https://developer.apple.com/library/mac/documentation/Security/Reference/certifkeytrustservices/index.html#//apple_ref/c/func/SecTrustGetTrustResult public struct PKCS12Item { let storage : NSDictionary init(_ storage: NSDictionary) { self.storage = storage } public var keyID : NSData? { // Typically a SHA-1 digest of the public key return storage.secValueForKey(kSecImportItemKeyID) } public var label : String? { return storage.secValueForKey(kSecImportItemLabel) } public var identity : SecIdentity? { return storage.secValueForKey(kSecImportItemIdentity) } public var trust : SecTrust? { return storage.secValueForKey(kSecImportItemTrust) } public var certificateChain : [ SecCertificate ]? { return storage.secValueForKey(kSecImportItemCertChain) } } extension PKCS12Item: CustomStringConvertible { public var description: String { var s = "<PKCS12Item:" if let v = keyID { s += " id=\(v)" } if let v = label { s += " '\(v)'" } if let v = identity { s += " \(v)" } if let v = trust { s += " \(v)" } if let v = certificateChain { s += " certs[" var isFirst = true for cert in v { if isFirst { isFirst = false } else { s += ", " } s += "\(cert)" } s += "]" } s += ">" return s } } // PKCS12 is just a wrapper of items public typealias PKCS12 = [ PKCS12Item ] public func ImportPKCS12(data: NSData, options: [ String : String ] = [:]) -> PKCS12? { var keyref : CFArray? let importStatus = SecPKCS12Import(data, options, &keyref); guard importStatus == noErr && keyref != nil else { print("PKCS#12 import failed: \(importStatus)") return nil } let items = keyref! as NSArray return items.map { PKCS12Item($0 as! NSDictionary) } } public func ImportPKCS12(path: String, password: String) -> PKCS12? { guard let data = NSData(contentsOfFile: path) else { return nil } let options = [ String(kSecImportExportPassphrase) : password ] return ImportPKCS12(data, options: options) } extension NSDictionary { func secValueForKey<T>(key: CFString) -> T? { let key = String(key) let v : AnyObject? = self[key] if let vv : AnyObject = v { return (vv as! T)} return nil } }
5ff0e98527cc4cc8bf3dad643d7685dc
23.45098
151
0.634723
false
false
false
false
sebastienh/SwiftFlux
refs/heads/master
SwiftFluxTests/ActionCreatorSpec.swift
mit
1
// // ActionCreatorSpec.swift // SwiftFlux // // Created by Kenichi Yonekawa on 8/11/15. // Copyright (c) 2015 mog2dev. All rights reserved. // import Quick import Nimble import Result import SwiftFlux class ActionCreatorSpec: QuickSpec { struct ActionCreatorTestModel { let name: String } struct ActionCreatorTestAction: Action { typealias Payload = ActionCreatorTestModel func invoke(dispatcher: Dispatcher) { dispatcher.dispatch(action: self, result: Result(value: ActionCreatorTestModel(name: "test"))) } } struct ActionCreatorDefaultErrorAction: Action { typealias Payload = ActionCreatorTestModel func invoke(dispatcher: Dispatcher) { dispatcher.dispatch(action: self, result: Result(error: NSError(domain: "TEST00000", code: -1, userInfo: [:]))) } } enum ActionError: Error { case UnexpectedError(NSError) } struct ActionCreatorErrorAction: Action { typealias Payload = ActionCreatorTestModel typealias Error = ActionError func invoke(dispatcher: Dispatcher) { // let error = ActionError.UnexpectedError( // NSError(domain: "TEST00000", code: -1, userInfo: [:]) // ) dispatcher.dispatch(action: self, result: Result(error: NSError(domain: "TEST00000", code: -1, userInfo: [:]))) } } override func spec() { describe("invoke", { () in var results = [String]() var fails = [String]() var callbacks = [String]() beforeEach({ () -> () in results = [] fails = [] callbacks = [] let id1 = ActionCreator.dispatcher.register(type: ActionCreatorTestAction.self) { (result) in switch result { case .success(let box): results.append("\(box.name)1") case .failure(_): fails.append("fail1") } } let id2 = ActionCreator.dispatcher.register(type: ActionCreatorErrorAction.self) { (result) in switch result { case .success(let box): results.append("\(box.name)2") case .failure(let error): fails.append("fail2 \(type(of: error))") } } let id3 = ActionCreator.dispatcher.register(type: ActionCreatorDefaultErrorAction.self) { (result) in switch result { case .success(let box): results.append("\(box.name)3") case .failure(let error): fails.append("fail3 \(type(of: error))") } } callbacks.append(id1) callbacks.append(id2) callbacks.append(id3) }) afterEach({ () -> () in for id in callbacks { ActionCreator.dispatcher.unregister(dispatchToken: id) } }) context("when action succeeded") { it("should dispatch to registered callback handlers") { let action = ActionCreatorTestAction() ActionCreator.invoke(action: action) expect(results.count).to(equal(1)) expect(fails.isEmpty).to(beTruthy()) expect(results).to(contain("test1")) } } context("when action failed with error type") { it("should dispatch to registered callback handlers") { let action = ActionCreatorErrorAction() ActionCreator.invoke(action: action) expect(fails.count).to(equal(1)) expect(results.isEmpty).to(beTruthy()) expect(fails).to(contain("fail2 NSError")) } } context("when action failed") { it("should dispatch to registered callback handlers") { let action = ActionCreatorDefaultErrorAction() ActionCreator.invoke(action: action) expect(fails.count).to(equal(1)) expect(results.isEmpty).to(beTruthy()) expect(fails).to(contain("fail3 NSError")) } } }) } }
bdc9d6f70411cd90024e0728e014d66a
35.210938
123
0.502913
false
true
false
false
Elm-Tree-Island/Shower
refs/heads/master
Carthage/Checkouts/ReactiveCocoa/ReactiveCocoaTests/AppKit/NSTableViewSpec.swift
gpl-3.0
7
import Quick import Nimble import ReactiveCocoa import ReactiveSwift import Result import AppKit final class NSTableViewSpec: QuickSpec { override func spec() { var tableView: TestTableView! beforeEach { tableView = TestTableView() } describe("reloadData") { var bindingSignal: Signal<(), NoError>! var bindingObserver: Signal<(), NoError>.Observer! var reloadDataCount = 0 beforeEach { let (signal, observer) = Signal<(), NoError>.pipe() (bindingSignal, bindingObserver) = (signal, observer) reloadDataCount = 0 tableView.reloadDataSignal.observeValues { reloadDataCount += 1 } } it("invokes reloadData whenever the bound signal sends a value") { tableView.reactive.reloadData <~ bindingSignal bindingObserver.send(value: ()) bindingObserver.send(value: ()) expect(reloadDataCount) == 2 } } } } private final class TestTableView: NSTableView { let reloadDataSignal: Signal<(), NoError> private let reloadDataObserver: Signal<(), NoError>.Observer override init(frame: CGRect) { (reloadDataSignal, reloadDataObserver) = Signal.pipe() super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { (reloadDataSignal, reloadDataObserver) = Signal.pipe() super.init(coder: aDecoder) } override func reloadData() { super.reloadData() reloadDataObserver.send(value: ()) } }
c403b87b8d0451550acd074b4f8d8c3c
21
69
0.710678
false
false
false
false
abertelrud/swift-package-manager
refs/heads/main
Sources/Commands/PackageTools/Learn.swift
apache-2.0
2
//===----------------------------------------------------------------------===// // // This source file is part of the Swift open source project // // Copyright (c) 2014-2022 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import ArgumentParser import CoreCommands import PackageGraph import PackageModel import TSCBasic extension SwiftPackageTool { struct Learn: SwiftCommand { @OptionGroup() var globalOptions: GlobalOptions static let configuration = CommandConfiguration(abstract: "Learn about Swift and this package") func files(fileSystem: FileSystem, in directory: AbsolutePath, fileExtension: String? = nil) throws -> [AbsolutePath] { guard fileSystem.isDirectory(directory) else { return [] } let files = try fileSystem.getDirectoryContents(directory) .map { try AbsolutePath(validating: $0, relativeTo: directory) } .filter { fileSystem.isFile($0) } guard let fileExtension = fileExtension else { return files } return files.filter { $0.extension == fileExtension } } func subdirectories(fileSystem: FileSystem, in directory: AbsolutePath) throws -> [AbsolutePath] { guard fileSystem.isDirectory(directory) else { return [] } return try fileSystem.getDirectoryContents(directory) .map { try AbsolutePath(validating: $0, relativeTo: directory) } .filter { fileSystem.isDirectory($0) } } func loadSnippetsAndSnippetGroups(fileSystem: FileSystem, from package: ResolvedPackage) throws -> [SnippetGroup] { let snippetsDirectory = package.path.appending(component: "Snippets") guard fileSystem.isDirectory(snippetsDirectory) else { return [] } let topLevelSnippets = try files(fileSystem: fileSystem, in: snippetsDirectory, fileExtension: "swift") .map { try Snippet(parsing: $0) } let topLevelSnippetGroup = SnippetGroup(name: "Getting Started", baseDirectory: snippetsDirectory, snippets: topLevelSnippets, explanation: "") let subdirectoryGroups = try subdirectories(fileSystem: fileSystem, in: snippetsDirectory) .map { subdirectory -> SnippetGroup in let snippets = try files(fileSystem: fileSystem, in: subdirectory, fileExtension: "swift") .map { try Snippet(parsing: $0) } let explanationFile = subdirectory.appending(component: "Explanation.md") let snippetGroupExplanation: String if fileSystem.isFile(explanationFile) { snippetGroupExplanation = try String(contentsOf: explanationFile.asURL) } else { snippetGroupExplanation = "" } return SnippetGroup(name: subdirectory.basename, baseDirectory: subdirectory, snippets: snippets, explanation: snippetGroupExplanation) } let snippetGroups = [topLevelSnippetGroup] + subdirectoryGroups.sorted { $0.baseDirectory.basename < $1.baseDirectory.basename } return snippetGroups.filter { !$0.snippets.isEmpty } } func run(_ swiftTool: SwiftTool) throws { let graph = try swiftTool.loadPackageGraph() let package = graph.rootPackages[0] print(package.products.map { $0.description }) let snippetGroups = try loadSnippetsAndSnippetGroups(fileSystem: swiftTool.fileSystem, from: package) var cardStack = CardStack(package: package, snippetGroups: snippetGroups, swiftTool: swiftTool) cardStack.run() } } }
aa0fff4992e102a43061e6801e741b04
41.228571
127
0.569012
false
false
false
false
sonsongithub/numsw
refs/heads/master
Tests/numswTests/NDArrayTests/NDArrayPerformanceTests.swift
mit
1
import Foundation import XCTest @testable import numsw class NDArrayPerformanceTests: XCTestCase { func testTransposePerformance() { let a = NDArray<Int>.zeros([10, 10, 10, 10]) measure { _ = a.transposed() } } func testSubscriptSubarrayPerformance() { let a = NDArray<Int>.zeros([1000, 1000]) measure { _ = a[0..<300, 100..<200] } } func testStackPerformance0() { let a = NDArray<Int>.zeros([1000, 1000]) measure { _ = NDArray.concatenate([a, a, a], along: 0) } } func testStackPerformance1() { let a = NDArray<Int>.zeros([1000, 1000]) measure { _ = NDArray.concatenate([a, a, a], along: 1) } } func testDividePerformance() { let a = NDArray<Double>.linspace(low: 1, high: 1e7, count: 100000) let b = NDArray<Double>.linspace(low: 10, high: 1e7, count: 100000) measure { _ = divide(a, b) } } #if os(iOS) || os(OSX) func testDivideAcceleratePerformance() { let a = NDArray<Double>.linspace(low: 1, high: 1e7, count: 100000) let b = NDArray<Double>.linspace(low: 10, high: 1e7, count: 100000) measure { _ = divideAccelerate(a, b) } } #endif func testSqrtPerformance() { let a = NDArray<Double>.linspace(low: -10 * .pi, high: 10 * .pi, count: 1000000) measure { _ = _sqrt(a) } } #if os(iOS) || os(OSX) func testSqrtAcceleratePerformance() { let a = NDArray<Double>.linspace(low: -10 * .pi, high: 10 * .pi, count: 1000000) measure { _ = _sqrtAccelerate(a) } } #endif func testSumPerformance0() { let a = NDArray<Double>.linspace(low: 0, high: 1e4, count: 100000) measure { _ = _sum(a) } } func testSumPerformance1() { let a = NDArray<Double>.linspace(low: 0, high: 1e4, count: 100000).reshaped([10, 10, 10, 10, 10]) measure { _ = _sum(a, along: 2) } } #if os(iOS) || os(OSX) func testSumAcceleratePerformance() { let a = NDArray<Double>.linspace(low: 0, high: 1e4, count: 100000) measure { _ = _sumAccelerate(a) } } func testSumAcceleratePerformance2() { let a = NDArray<Double>.linspace(low: 0, high: 1e4, count: 100000).reshaped([10, 10, 10, 10, 10]) measure { _ = _sumAccelerate(a, along: 2) } } #endif func testNormalPerformance() { measure { _ = NDArray<Double>.normal(mu: 0, sigma: 1, shape: [100, 100]) } } static var allTests: [(String, (NDArrayPerformanceTests) -> () throws -> Void)] { return [ ("testTransposePerformance", testTransposePerformance), ("testSubscriptSubarrayPerformance", testSubscriptSubarrayPerformance), ("testStackPerformance0", testStackPerformance0), ("testStackPerformance1", testStackPerformance1), ("testDividePerformance", testDividePerformance), ("testSqrtPerformance", testSqrtPerformance), ("testSumPerformance0", testSumPerformance0), ("testSumPerformance1", testSumPerformance1), ("testNormalPerformance", testNormalPerformance) ] } }
83d0579ebb4616a0b65c1c8adbe89628
28.491525
105
0.541379
false
true
false
false
banjun/SwiftBeaker
refs/heads/master
Sources/Generator.swift
mit
1
import Foundation import Stencil typealias SwiftCode = (local: String, global: String) protocol SwiftConvertible { associatedtype Context func swift(_ context: Context, public: Bool) throws -> SwiftCode } fileprivate extension String { func indented(by level: Int) -> String { return components(separatedBy: "\n").map {Array(repeating: " ", count: level).joined() + $0}.joined(separator: "\n") } } fileprivate extension String { func swiftKeywordsEscaped() -> String { let keywords = ["Error"] return keywords.contains(self) ? self + "_" : self } func swiftTypeMapped() -> String { let typeMap = ["string": "String", "number": "Int", "enum": "Int", "boolean": "Bool"] return typeMap[self] ?? self } func swiftIdentifierized() -> String { let cs = CharacterSet(charactersIn: " _/{?,}-") return components(separatedBy: cs).joined(separator: "_") } func docCommentPrefixed() -> String { return components(separatedBy: .newlines).map {"/// " + $0}.joined(separator: "\n") } } private let stencilExtension: Extension = { let ext = Extension() ext.registerFilter("escapeKeyword") { (value: Any?) in let keywords = ["var", "let", "where", "operator", "throws"] guard let s = value as? String, keywords.contains(s) else { return value } return "`" + s + "`" } return ext }() private let stencilEnvironment = Environment(extensions: [stencilExtension]) extension DataStructureElement.Content: SwiftConvertible { func swift(_ name: String? = nil, public: Bool) throws -> SwiftCode { let localDSTemplate = Template(templateString: """ {{ public }}struct {{ name }}: Codable { {% for v in vars %} {{ v.doc }} {{ public }}var {{ v.name|escapeKeyword }}: {{ v.type }}{% endfor %}{% if publicMemberwiseInit %} // public memberwise init{# default synthesized memberwise init is internal in Swift 3 #} public init({% for v in vars %}{{ v.name|escapeKeyword }}: {{ v.type }}{% ifnot forloop.last %}, {% endif %}{% endfor %}) { {% for v in vars %} self.{{ v.name|escapeKeyword }} = {{ v.name|escapeKeyword }} {% endfor %}}{% endif %} } """, environment: stencilEnvironment) guard let name = ((name ?? id).map {$0.swiftKeywordsEscaped()}) else { throw ConversionError.undefined } let vars: [[String: Any]] = try members .map {try $0.memberAvoidingSwiftRecursiveStruct(parentTypes: [name])} .map { m in let optional = !m.required return [ "name": m.swiftName, "type": m.swiftType, "optional": optional, "doc": m.swiftDoc]} let localName = name.components(separatedBy: ".").last ?? name return (local: try localDSTemplate.render(["public": `public` ? "public " : "", "publicMemberwiseInit": `public`, "name": localName.swiftIdentifierized(), "vars": vars]), global: "") } } extension TransitionElement: SwiftConvertible { func swift(_ resource: ResourceElement, public: Bool) throws -> SwiftCode { var globalExtensionCode = "" let request = transactions.first!.request! let requestTypeName = try swiftRequestTypeName(request: request, resource: resource) let href = resource.href(transition: self, request: request) let otherTransitions = resource.transitions func allResponses(method: String) -> [HTTPResponseElement] { otherTransitions .flatMap {t in t.transactions.map {(transition: t, transaction: $0)}} .filter {$0.transaction.request?.attributes.method.content.rawValue == method && resource.href(transition: $0.transition, request: $0.transaction.request!) == href} .flatMap {$0.transaction.responses} } let trTemplate = Template(templateString: """ {{ copy }} {{ public }}struct {{ name }}: {{ extensions|join:", " }} { {{ public }}let baseURL: URL {{ public }}var method: HTTPMethod {return {{ method }}} {% for v in pathVars %}{% if forloop.first %} {{ public }}let path = "" // see intercept(urlRequest:) static let pathTemplate: URITemplate = "{{ path }}" {{ public }}var pathVars: PathVars {{ public }}struct PathVars: URITemplateContextConvertible { {% endif %} {{ v.doc }} {{ public }}var {{ v.name|escapeKeyword }}: {{ v.type }}{% if forloop.last %}{% if publicMemberwiseInit %} // public memberwise init{# default synthesized memberwise init is internal in Swift 3 #} public init({% for v in pathVars %}{{ v.name|escapeKeyword }}: {{ v.type }}{% ifnot forloop.last %}, {% endif %}{% endfor %}) { {% for v in pathVars %} self.{{ v.name|escapeKeyword }} = {{ v.name|escapeKeyword }} {% endfor %}}{% endif %} }{% else %} {% endif %}{% empty %} {{ public }}var path: String {return "{{ path }}"}{% endfor %} {% if paramType %} {{ public }}let param: {{ paramType }} {{ public }}var bodyParameters: BodyParameters? {% if paramType == "String" %}{return TextBodyParameters(contentType: "{{ paramContentType }}", content: param)}{% else %}{ let encoder = JSONEncoder() encoder.dateEncodingStrategy = .iso8601 return try? JSONBodyParameters(JSONObject: JSONSerialization.jsonObject(with: encoder.encode(param))) } {% endif %}{% endif %}{% if structParam %}{{ structParam }}{% endif %} {{ public }}enum Responses { {% for r in responseCases %} case {{ r.case }}({{ r.type }}){% if r.innerType %} {{ r.innerType }}{% endif %} {% endfor %} } {% if headerVars %} {{ public }}var headerFields: [String: String] {return headerVars.context} {{ public }}var headerVars: HeaderVars {{ public }}struct HeaderVars: URITemplateContextConvertible { {% for v in headerVars %} {{ v.doc }} {{ public }}var {{ v.name }}: {{ v.type }} {% endfor %} enum CodingKeys: String, CodingKey { {% for v in headerVars %} case {{ v.name }} = "{{ v.key }}" {% endfor %} }{% if publicMemberwiseInit %} // public memberwise init{# default synthesized memberwise init is internal in Swift 3 #} public init({% for v in headerVars %}{{ v.name|escapeKeyword }}: {{ v.type }}{% ifnot forloop.last %}, {% endif %}{% endfor %}) { {% for v in headerVars %} self.{{ v.name|escapeKeyword }} = {{ v.name|escapeKeyword }} {% endfor %}}{% endif %} } {% endif %}{% if publicMemberwiseInit %} // public memberwise init{# default synthesized memberwise init is internal in Swift 3 #} public init(baseURL: URL{% if pathVars %}, pathVars: PathVars{% endif %}{% if paramType %}, param: {{ paramType }}{% endif %}{% if headerVars %}, headerVars: HeaderVars{% endif %}) { self.baseURL = baseURL{% if pathVars %}\n self.pathVars = pathVars{% endif %}{% if paramType %}\n self.param = param{% endif %}{% if headerVars %}\n self.headerVars = headerVars{% endif %} } {% endif %} {{ public }}func response(from object: Any, urlResponse: HTTPURLResponse) throws -> Responses { let contentType = contentMIMEType(in: urlResponse) switch (urlResponse.statusCode, contentType) { {% for r in responseCases %} case ({{ r.statusCode }}, {{ r.contentType }}): return .{{ r.case }}({{ r.decode }}) {% endfor %} default: throw ResponseError.undefined(urlResponse.statusCode, contentType) } } } """, environment: stencilEnvironment) let siblingResponses = allResponses(method: request.attributes.method.content.rawValue) let responseCases = try siblingResponses.map { r -> [String: Any] in let type: String let contentTypeEscaped = (r.attributes.headers?.contentType ?? "").replacingOccurrences(of: "/", with: "_") let innerType: (local: String, global: String)? switch r.dataStructure?.content { case .anonymous?: type = "Response\(r.attributes.statusCode)_\(contentTypeEscaped)" innerType = try r.dataStructure!.content.swift("\(requestTypeName).Responses.\(type)", public: `public`) _ = innerType.map {globalExtensionCode += $0.global} case let .ref(id: id)?: // external type (reference to type defined in Data Structures) type = id innerType = nil case nil: switch r.attributes.headers?.contentType { case "text/plain"?, "text/html"?: type = "String" innerType = nil default: type = "Void" innerType = nil } case .named?: throw ConversionError.unknownDataStructure case .array?: throw ConversionError.unknownDataStructure } var context: [String: String] = [ "statusCode": String(r.attributes.statusCode), "contentType": r.attributes.headers?.contentType.map {"\"\($0)\"?"} ?? "_", "case": "http\(r.attributes.statusCode)_\(contentTypeEscaped)", "type": type, "decode": { switch r.attributes.headers?.contentType { case nil, "application/json"?: return "try decodeJSON(from: object, urlResponse: urlResponse)" case "text/html"?, "text/plain"?: return "try string(from: object, urlResponse: urlResponse)" default: return "" } }()] if let innerType = innerType { context["innerType"] = innerType.local.indented(by: 8) } return context } var context: [String: Any] = [ "public": `public` ? "public " : "", "publicMemberwiseInit": `public`, "name": requestTypeName, "responseCases": responseCases, "method": "." + request.attributes.method.content.rawValue.lowercased(), "path": href ] if let hrefVariables = attributes?.hrefVariables { let pathVars: [[String: Any]] = hrefVariables.content.map { ["key": $0.name, "name": $0.swiftName, "type": $0.swiftType, "doc": $0.swiftDoc, "optional": !$0.required] } context["extensions"] = ["APIBlueprintRequest", "URITemplateRequest"] context["pathVars"] = pathVars } else { context["extensions"] = ["APIBlueprintRequest"] } if let headers = (request.attributes.headers.map {[String: String]($0.content)}), !headers.isEmpty { let headerVars = headers.filter {$0.key != "Content-Type"}.map { (k, v) in ["key": k, "name": k.lowercased().swiftIdentifierized(), "type": "String", "doc": v.docCommentPrefixed()] } context["headerVars"] = headerVars } switch request.dataStructure?.content { case let .anonymous(members)?: // inner type let ds = DataStructureElement.Content.anonymous(members: members) context["paramType"] = "Param" let s = try ds.swift("\(requestTypeName).Param", public: `public`) globalExtensionCode += s.global context["structParam"] = s.local.indented(by: 4) case let .ref(id: id)?: let ds = DataStructureElement.Content.ref(id: id) // external type (reference to type defined in Data Structures) context["paramType"] = ds.id case .named?: throw ConversionError.notSupported("named DataStructure definition in a request param") case .array?: throw ConversionError.notSupported("array DataStructure definition in a request param") case nil: if let requestContentType = request.attributes.headers?.contentType, requestContentType.hasPrefix("text/") { context["paramType"] = "String" context["paramContentType"] = requestContentType } } context["copy"] = copy?.content.docCommentPrefixed() return try (local: trTemplate.render(context), global: globalExtensionCode) } func swiftRequestTypeName(request: HTTPRequestElement, resource: ResourceElement) throws -> String { if let title = meta?.title?.content, let first = title.first { return (String(first).uppercased() + String(title.dropFirst())).swiftIdentifierized() } else { return (request.attributes.method.content.rawValue + "_" + resource.href(transition: self, request: request)).swiftIdentifierized() } } } extension MemberElement { var swiftName: String {return name.swiftIdentifierized()} var swiftType: String { let name: String switch content.value { case .string: name = "string".swiftTypeMapped().swiftKeywordsEscaped() case .number: name = "number".swiftTypeMapped().swiftKeywordsEscaped() case .array(let t): name = "[" + (t.map {$0.swiftTypeMapped().swiftKeywordsEscaped()} ?? "Any") + "]" case .id(let t): name = t.swiftTypeMapped().swiftKeywordsEscaped() // TODO: support indirect recursion case .indirect(let t): name = "Indirect<\(t)>" } return name + (required ? "" : "?") } var swiftDoc: String {return [meta?.description?.content, content.displayValue.map {" ex. " + $0}] .compactMap {$0} .joined(separator: " ") .docCommentPrefixed()} func memberAvoidingSwiftRecursiveStruct(parentTypes: [String]) throws -> MemberElement { let recursive = parentTypes.contains { if case .id($0) = content.value { return true } // currently support simple recursions return false } guard recursive else { return self } guard !required else { throw ConversionError.notSupported("recursive data structure with required param") } guard case let .id(exactType) = content.value else { throw ConversionError.notSupported("recursive data structure with compound param") } return MemberElement( element: element, meta: meta, attributes: Attributes(typeAttributes: attributes?.typeAttributes.map { ArrayElement<StringElement>(element: ArrayElement<StringElement>.elementName, content: $0.content.filter {$0.content != "required"})}), content: .init( key: content.key, value: .indirect(exactType))) } }
d0c458c6f419779dbf53fd46807690ab
45.458967
217
0.570821
false
false
false
false
ivlevAstef/DITranquillity
refs/heads/master
Sources/Core/Internal/Component.swift
mit
1
// // Component.swift // DITranquillity // // Created by Alexander Ivlev on 10/06/16. // Copyright © 2016 Alexander Ivlev. All rights reserved. // typealias Injection = (signature: MethodSignature, cycle: Bool) // Reference final class ComponentContainer { private var map = Dictionary<TypeKey, Set<Component>>() private var manyMap = Dictionary<ShortTypeKey, Set<Component>>() func insert(_ key: TypeKey, _ component: Component, otherOperation: (() -> Void)? = nil) { let shortKey = ShortTypeKey(by: key.type) mutex.sync { if nil == map[key]?.insert(component) { map[key] = [component] } if nil == manyMap[shortKey]?.insert(component) { manyMap[shortKey] = [component] } otherOperation?() } } subscript(_ key: TypeKey) -> Set<Component> { return mutex.sync { return map[key] ?? [] } } subscript(_ key: ShortTypeKey) -> Set<Component> { return mutex.sync { return manyMap[key] ?? [] } } var components: [Component] { let values = mutex.sync { map.values.flatMap { $0 } } let sortedValues = values.sorted(by: { $0.order < $1.order }) var result = sortedValues // remove dublicates - dublicates generated for `as(Type.self)` var index = 0 while index + 1 < result.count { if result[index].order == result[index + 1].order { result.remove(at: index) continue } index += 1 } return result } private let mutex = PThreadMutex(normal: ()) } private var componentsCount: Int = 0 private let componentsCountSynchronizer = makeFastLock() final class Component { typealias UniqueKey = DIComponentInfo init(componentInfo: DIComponentInfo, in framework: DIFramework.Type?, _ part: DIPart.Type?) { self.info = componentInfo self.framework = framework self.part = part componentsCountSynchronizer.lock() componentsCount += 1 self.order = componentsCount componentsCountSynchronizer.unlock() } let info: DIComponentInfo let framework: DIFramework.Type? let part: DIPart.Type? let order: Int var lifeTime = DILifeTime.default var priority: DIComponentPriority = .normal var alternativeTypes: [ComponentAlternativeType] = [] fileprivate(set) var initial: MethodSignature? fileprivate(set) var injections: [Injection] = [] var postInit: MethodSignature? } extension Component: Hashable { #if swift(>=5.0) func hash(into hasher: inout Hasher) { hasher.combine(info) } #else var hashValue: Int { return info.hashValue } #endif static func ==(lhs: Component, rhs: Component) -> Bool { return lhs.info == rhs.info } } extension Component { func set(initial signature: MethodSignature) { initial = signature } func append(injection signature: MethodSignature, cycle: Bool) { injections.append(Injection(signature: signature, cycle: cycle)) } } typealias Components = ContiguousArray<Component>
35f5f2baaf7cfe3d19c45f62bafd8897
23.57377
95
0.661107
false
false
false
false
qiscus/qiscus-sdk-ios
refs/heads/master
Qiscus/Qiscus/Model/DataModel/Public/QRoom+PublicAPI.swift
mit
1
// // QRoom+PublicAPI.swift // Qiscus // // Created by Ahmad Athaullah on 21/11/17. // Copyright © 2017 Ahmad Athaullah. All rights reserved. // import RealmSwift import SwiftyJSON public extension QRoom { // MARK: - Class method @objc public class func all() -> [QRoom]{ return QRoom.allRoom() } public class func unpinAll(){ QRoom.unpinAllRoom() } @objc public class func room(withId id:String) -> QRoom? { return QRoom.getRoom(withId: id) } public class func room(withUniqueId uniqueId:String) -> QRoom? { return QRoom.getRoom(withUniqueId:uniqueId) } @objc public class func room(withUser user:String) -> QRoom? { if Thread.isMainThread { return QRoom.getSingleRoom(withUser: user) }else{ return nil } } public class func room(fromJSON json:JSON)->QRoom{ return QRoom.addNewRoom(json:json) } public class func deleteRoom(room:QRoom){ QRoom.removeRoom(room: room) } // MARK: - Object method public func pin(){ self.pinRoom() } public func unpin(){ self.unpinRoom() } public func update(roomName:String? = nil, roomAvatarURL:String? = nil, roomOptions:String? = nil, onSuccess:@escaping ((_ room: QRoom)->Void),onError:@escaping ((_ error: String)->Void)){ self.updateRoom(roomName: roomName, roomAvatarURL: roomAvatarURL, roomOptions: roomOptions, onSuccess: onSuccess, onError: onError) } @objc public func publishStopTyping(){ if !self.isPublicChannel { self.publishStopTypingRoom() } } public func publishStartTyping(){ if !self.isPublicChannel { self.publishStartTypingRoom() } } public func subscribeRealtimeStatus(){ self.subscribeRoomChannel() } public func unsubscribeRealtimeStatus(){ self.unsubscribeRoomChannel() } public func sync(){ self.syncRoom() } public func loadMore(){ self.loadMoreComment() } public func updateCommentStatus(inComment comment:QComment, status:QCommentStatus){ self.updateStatus(inComment: comment, status: status) } public func publishCommentStatus(withStatus status:QCommentStatus){ self.publishStatus(withStatus: status) } public func downloadAvatar(){ self.downloadRoomAvatar() } public func loadAvatar(onSuccess: @escaping (UIImage)->Void, onError: @escaping (String)->Void){ self.loadRoomAvatar(onSuccess: onSuccess, onError: onError) } public func add(newComment comment:QComment){ self.addComment(newComment: comment) } public func loadData(limit:Int = 20, offset:String? = nil, onSuccess:@escaping (QRoom)->Void, onError:@escaping (String)->Void){ self.loadRoomData(limit: limit, offset: offset, onSuccess: onSuccess, onError: onError) } }
6a0cdce4b63f3f6d39d3965204a65675
31.722222
192
0.647538
false
false
false
false
zxwWei/SwfitZeng
refs/heads/master
XWWeibo接收数据/XWWeibo/Classes/Model(模型)/Main(主要)/Controller/XWcompassVc.swift
apache-2.0
1
// // XWcompassVc.swift // XWWeibo // // Created by apple on 15/10/26. // Copyright © 2015年 ZXW. All rights reserved. // // MARK: - 让所有的四个控制器继承自它,让它们没登陆的时候都实现如下业务逻辑 显示这个界面 import UIKit class XWcompassVc: UITableViewController{ // MARK: - when user has login ,we can in other vc var userLogin = XWUserAccount.userLogin() //var userLogin = false // var vistorView: XWCompassView? // 当加载view的时候 如果用另外的view代替原有的view,则不再往下执行 override func loadView() { // 当登陆成功的时候加载原先的view 不成功的时候加载 自定义的view userLogin ? super.loadView() : setupVistorView() } private func setupVistorView(){ // 为什么要用XWCompassView呢 // 转换成xwcompassView let vistorView = XWCompassView() view = vistorView // 根据控制器的不同显示不同的信息 if (self is XWHomeTableVC){ vistorView.rotation() // 监听进入后台和前台的通知 NSNotificationCenter.defaultCenter().addObserver(self, selector: "didEnterBackground", name: UIApplicationDidEnterBackgroundNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "didBecomeActive", name: UIApplicationDidBecomeActiveNotification, object: nil) } else if (self is XWMessageTableVC){ vistorView.setupVistorView("你妹", rotationViewName: "visitordiscover_image_message") } else if (self is XWDiscoverTableVC){ vistorView.setupVistorView("坑", rotationViewName: "visitordiscover_image_message") } else if (self is XWProfileTableVC){ vistorView.setupVistorView("坑爹", rotationViewName: "visitordiscover_image_profile") } // MARK: - 注册代理 vistorView.vistorDelegate = self // 添加左边和右边的导航条按钮 navigationItem.leftBarButtonItem = UIBarButtonItem(title: "注册", style: UIBarButtonItemStyle.Plain, target: self, action: "vistorWillRegegister") navigationItem.rightBarButtonItem = UIBarButtonItem(title: "登陆", style: UIBarButtonItemStyle.Plain, target: self, action: "vistorWillLogin") //vistorView.backgroundColor = UIColor.whiteColor() } // MARK: - 监听通知 func didEnterBackground(){ // 进入后台暂停旋转 (view as! XWCompassView).pauseAnimation() } func didBecomeActive(){ (view as! XWCompassView).resumeAnimation() } } // MARK: - 延伸 代理方法的实现 放在控制器外 extension XWcompassVc: XWCompassViewDelegate { func vistorWillRegegister() { print("vistorWillRegegister") } func vistorWillLogin() { //print("vistorWillLogin") let loginVc = XWOauthVC() // 记得添加导航条 presentViewController(UINavigationController(rootViewController: loginVc), animated: true, completion: nil) } }
ee7cd7f06def809ceb6556dffc9f27d6
30.228261
162
0.639053
false
false
false
false
KarlHarnois/Reduxable
refs/heads/master
ReduxableTests/ActionSpec.swift
mit
1
// // ActionSpec.swift // Reduxable // // Created by Karl Rivest Harnois on 2016-08-31. // Copyright © 2016 Karl Rivest Harnois. All rights reserved. // // import Quick // import Nimble // @testable import Reduxable // // class ActionSpec: QuickSpec { // override func spec() { // // var store: Store<AppState>! // var newState: AppState? // beforeEach { // let state = AppState() // store = Store(initialState: state) // newState = nil // store.dispatcher = { newState = $0 } // } // // describe("an action") { // // context("when its associatedtype is the same as the store generic type") { // var action: ActionType! // beforeEach { // action = IncrementCounter() // } // context("when dispatched to a store") { // beforeEach { // store.dispatch(action) // } // it("creates a new state") { // expect(newState).to(beTruthy()) // } // it("alters the state properties") { // expect(newState?.counter).to(equal(1)) // } // } // } // // context("when its associatedtype is different than the store generic type") { // var action: ActionType! // beforeEach { // action = AppendString(string: "hello") // } // context("when dispatched to a store") { // beforeEach { // store.dispatch(action) // } // it("creates a new state") { // expect(newState).to(beTruthy()) // } // it("creates a new state that is unchanged") { // expect(newState?.counter).to(be(0)) // } // } // } // } // } // }
316c4c657b366961de8c106084509c60
32.25
92
0.413534
false
false
false
false
noahemmet/WorldKit
refs/heads/master
WorldKit/Sources/Platform.swift
apache-2.0
1
// // Platform.swift // WorldKit // // Created by Noah Emmet on 4/16/16. // Copyright © 2016 Sticks. All rights reserved. // import Foundation // // Platform.swift // WorldKit // // Created by Noah Emmet on 4/9/16. // Copyright © 2016 Sticks. All rights reserved. // import Foundation #if os(iOS) import UIKit public typealias View = UIView public typealias Color = UIColor public typealias Rect = CGRect public typealias Image = UIImage #else import Cocoa public typealias View = NSView public typealias Color = NSColor public typealias Rect = NSRect public typealias Image = NSImage #endif
22fdad726f79ba52e4214e1de48acd85
17.606061
49
0.718241
false
false
false
false
WhisperSystems/Signal-iOS
refs/heads/master
Signal/src/ViewControllers/UsernameViewController.swift
gpl-3.0
1
// // Copyright (c) 2019 Open Whisper Systems. All rights reserved. // import Foundation @objc class UsernameViewController: OWSViewController { // MARK: - Dependencies var databaseStorage: SDSDatabaseStorage { return SSKEnvironment.shared.databaseStorage } // MARK: - private static let minimumUsernameLength = 4 private static let maximumUsernameLength: UInt = 26 private let usernameTextField = OWSTextField() private var hasPendingChanges: Bool { return pendingUsername != (OWSProfileManager.shared().localUsername() ?? "") } private var pendingUsername: String { return usernameTextField.text?.stripped.lowercased() ?? "" } private var errorLabel = UILabel() private var errorRow = UIView() private enum ValidationState { case valid case tooShort case invalidCharacters case inUse } private var validationState: ValidationState = .valid { didSet { updateValidationError() } } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = Theme.backgroundColor title = NSLocalizedString("USERNAME_TITLE", comment: "The title for the username view.") navigationItem.leftBarButtonItem = UIBarButtonItem(title: CommonStrings.cancelButton, style: .plain, target: self, action: #selector(didTapCancel)) let stackView = UIStackView() stackView.axis = .vertical stackView.spacing = 0 view.addSubview(stackView) stackView.autoPinWidthToSuperview() stackView.autoPinTopToSuperviewMargin(withInset: 35) let topLine = UIView() let bottomLine = UIView() for line in [topLine, bottomLine] { stackView.addArrangedSubview(line) line.backgroundColor = Theme.cellSeparatorColor line.autoSetDimension(.height, toSize: CGHairlineWidth()) } // Username let usernameRow = UIView() stackView.insertArrangedSubview(usernameRow, at: 1) usernameRow.layoutMargins = UIEdgeInsets(top: 10, leading: 18, bottom: 10, trailing: 18) let titleLabel = UILabel() titleLabel.text = NSLocalizedString("USERNAME_FIELD", comment: "Label for the username field in the username view.") titleLabel.textColor = Theme.primaryColor titleLabel.font = UIFont.ows_dynamicTypeBodyClamped.ows_mediumWeight() usernameRow.addSubview(titleLabel) titleLabel.autoPinLeadingToSuperviewMargin() titleLabel.autoPinHeightToSuperviewMargins() usernameTextField.font = .ows_dynamicTypeBodyClamped usernameTextField.textColor = Theme.primaryColor usernameTextField.autocorrectionType = .no usernameTextField.autocapitalizationType = .none usernameTextField.placeholder = NSLocalizedString("USERNAME_PLACEHOLDER", comment: "The placeholder for the username text entry in the username view.") usernameTextField.text = OWSProfileManager.shared().localUsername() usernameTextField.textAlignment = .right usernameTextField.delegate = self usernameTextField.returnKeyType = .done usernameTextField.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged) usernameTextField.becomeFirstResponder() usernameRow.addSubview(usernameTextField) usernameTextField.autoPinLeading(toTrailingEdgeOf: titleLabel, offset: 10) usernameTextField.autoPinTrailingToSuperviewMargin() usernameTextField.autoVCenterInSuperview() // Error stackView.addArrangedSubview(errorRow) errorRow.isHidden = true errorLabel.textColor = .ows_red errorLabel.textAlignment = .center errorLabel.numberOfLines = 0 errorLabel.lineBreakMode = .byWordWrapping errorLabel.font = .ows_dynamicTypeCaption1Clamped errorRow.addSubview(errorLabel) errorLabel.autoPinWidthToSuperview(withMargin: 18) errorLabel.autoPinHeightToSuperview(withMargin: 5) // Info let infoRow = UIView() stackView.addArrangedSubview(infoRow) let infoLabel = UILabel() infoLabel.textColor = Theme.secondaryColor infoLabel.text = NSLocalizedString("USERNAME_DESCRIPTION", comment: "An explanation of how usernames work on the username view.") infoLabel.font = .ows_dynamicTypeCaption1Clamped infoLabel.numberOfLines = 0 infoLabel.lineBreakMode = .byWordWrapping infoRow.addSubview(infoLabel) infoLabel.autoPinWidthToSuperview(withMargin: 18) infoLabel.autoPinHeightToSuperview(withMargin: 10) } func updateSaveButton() { guard hasPendingChanges else { navigationItem.rightBarButtonItem = nil return } navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .save, target: self, action: #selector(didTapSave)) } func updateValidationError() { switch validationState { case .valid: errorRow.isHidden = true case .tooShort: errorRow.isHidden = false errorLabel.text = NSLocalizedString("USERNAME_TOO_SHORT_ERROR", comment: "An error indicating that the supplied username is too short.") case .invalidCharacters: errorRow.isHidden = false errorLabel.text = NSLocalizedString("USERNAME_INVALID_CHARACTERS_ERROR", comment: "An error indicating that the supplied username contains disallowed characters.") case .inUse: errorRow.isHidden = false let unavailableErrorFormat = NSLocalizedString("USERNAME_UNAVAIALBE_ERROR_FORMAT", comment: "An error indicating that the supplied username is in use by another user. Embeds {{requested username}}.") errorLabel.text = String(format: unavailableErrorFormat, pendingUsername) } } func saveUsername() { // If we're trying to save, but we have nothing to save, just dismiss immediately. guard hasPendingChanges else { return usernameSavedOrCanceled() } guard usernameIsValid() else { return } var usernameToUse: String? = pendingUsername if usernameToUse?.isEmpty == true { usernameToUse = nil } ModalActivityIndicatorViewController.present(fromViewController: self, canCancel: false) { modalView in let usernameRequest: TSRequest if let usernameToUse = usernameToUse { usernameRequest = OWSRequestFactory.usernameSetRequest(usernameToUse) } else { usernameRequest = OWSRequestFactory.usernameDeleteRequest() } SSKEnvironment.shared.networkManager.makePromise(request: usernameRequest).done { _ in self.databaseStorage.write { transaction in OWSProfileManager.shared().updateLocalUsername(usernameToUse, transaction: transaction) } modalView.dismiss { self.usernameSavedOrCanceled() } }.catch { error in if case .taskError(let task, _)? = error as? NetworkManagerError, task.statusCode() == 409 { modalView.dismiss { self.validationState = .inUse } return } owsFailDebug("Unexpected username update error \(error)") modalView.dismiss { OWSAlerts.showErrorAlert(message: NSLocalizedString("USERNAME_VIEW_ERROR_UPDATE_FAILED", comment: "Error moessage shown when a username update fails.")) } } } } func usernameIsValid() -> Bool { // We allow empty usernames, as this is how you delete your username guard !pendingUsername.isEmpty else { return true } guard pendingUsername.count >= UsernameViewController.minimumUsernameLength else { validationState = .tooShort return false } // Usernames only allow a-z, 0-9, and underscore let validUsernameRegex = try! NSRegularExpression(pattern: "^[a-z0-9_]+$", options: []) guard validUsernameRegex.hasMatch(input: pendingUsername) else { validationState = .invalidCharacters return false } return true } func usernameSavedOrCanceled() { usernameTextField.resignFirstResponder() dismiss(animated: true, completion: nil) } // MARK: - @objc func didTapCancel() { guard hasPendingChanges else { return usernameSavedOrCanceled() } OWSAlerts.showPendingChangesAlert { [weak self] in self?.usernameSavedOrCanceled() } } @objc func didTapSave() { saveUsername() } @objc func textFieldDidChange() { // Clear validation errors when the user starts typing again. validationState = .valid updateSaveButton() } } // MARK: - extension UsernameViewController: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { usernameTextField.resignFirstResponder() return false } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { return TextFieldHelper.textField( textField, shouldChangeCharactersInRange: range, replacementString: string, byteLimit: UsernameViewController.maximumUsernameLength ) } }
b70b9f924bd9f11d6fbae9674d414439
36.088235
175
0.633624
false
false
false
false
stupidfive/SwiftDataStructuresAndAlgorithms
refs/heads/master
SwiftDataStructuresAndAlgorithms/SplayTree.swift
mit
1
// // SplayTree.swift // SwiftDataStructuresAndAlgorithms // // Created by George Wu on 9/25/15. // Copyright © 2015 George Wu. All rights reserved. // import Foundation public class SplayTree<KeyT: Comparable, ValueT>: BinarySearchTree<KeyT, ValueT> { override public func find(key: KeyT) -> ValueT? { guard let node = findNode(key) else { return nil } splay(node) return node.value } override public func insert(key: KeyT, value: ValueT) { let node = BSTNode(key: key, value: value) insertNodeReplacingDuplicate(node) splay(node) } override public func delete(key: KeyT) -> Bool { // TODO: ~ // case 1: node doesn't exist guard let node = findNode(key) else { return false } // case 2&3: node has zero or one child if node.leftChild == nil { transplant(node, withNode: node.rightChild) } else if node.rightChild == nil { transplant(node, withNode: node.leftChild) } // case 4: node has two children else { // find the left most child of the right subtree let replaceNode = node.rightChild!.leftMostChild() // replace node with replaceNode if (node !== replaceNode.parent) { // steps can be omitted if node is the direct parent of replaceNode transplant(replaceNode, withNode: replaceNode.rightChild) replaceNode.rightChild = node.rightChild! replaceNode.rightChild!.parent = replaceNode } transplant(node, withNode: replaceNode) replaceNode.leftChild = node.leftChild! replaceNode.leftChild!.parent = replaceNode } size-- return false } private func splay(node: BSTNode<KeyT, ValueT>) { while node !== root { let parent = node.parent! if parent === root { if node.key < parent.key { zigRight(node, parent: parent) } else { zigLeft(node, parent: parent) } continue } let grandParent = parent.parent! if node.key < parent.key && parent.key < grandParent.key { zigZigRight(node, parent: parent, grandParent: grandParent) } else if node.key > parent.key && parent.key > grandParent.key { zigZigLeft(node, parent: parent, grandParent: grandParent) } else if node.key < parent.key && parent.key > grandParent.key { zigZagLeft(node, parent: parent, grandParent: grandParent) } else if node.key > parent.key && parent.key < grandParent.key { zigZagRight(node, parent: parent, grandParent: grandParent) } continue } } private func zigLeft(node: BSTNode<KeyT, ValueT>, parent: BSTNode<KeyT, ValueT>) { root = node node.parent = nil parent.rightChild = node.leftChild parent.rightChild?.parent = parent node.leftChild = parent parent.parent = node } private func zigRight(node: BSTNode<KeyT, ValueT>, parent: BSTNode<KeyT, ValueT>) { root = node node.parent = nil parent.leftChild = node.rightChild parent.leftChild?.parent = parent node.rightChild = parent parent.parent = node } // perform before zig-zig or zig-zag private func linkUpGreatGrandParent(node: BSTNode<KeyT, ValueT>, parent: BSTNode<KeyT, ValueT>, grandParent: BSTNode<KeyT, ValueT>) { if grandParent === root { root = node node.parent = nil } else if let greatGrandParent = grandParent.parent { if node.key < greatGrandParent.key { greatGrandParent.leftChild = node } else { greatGrandParent.rightChild = node } node.parent = greatGrandParent } } private func zigZigLeft(node: BSTNode<KeyT, ValueT>, parent: BSTNode<KeyT, ValueT>, grandParent: BSTNode<KeyT, ValueT>) { linkUpGreatGrandParent(node, parent: parent, grandParent: grandParent) grandParent.rightChild = parent.leftChild grandParent.rightChild?.parent = grandParent parent.leftChild = grandParent grandParent.parent = parent parent.rightChild = node.leftChild parent.rightChild?.parent = parent node.leftChild = parent parent.parent = node } private func zigZigRight(node: BSTNode<KeyT, ValueT>, parent: BSTNode<KeyT, ValueT>, grandParent: BSTNode<KeyT, ValueT>) { linkUpGreatGrandParent(node, parent: parent, grandParent: grandParent) grandParent.leftChild = parent.rightChild grandParent.leftChild?.parent = grandParent parent.rightChild = grandParent grandParent.parent = parent parent.leftChild = node.rightChild parent.leftChild?.parent = parent node.rightChild = parent parent.parent = node } private func zigZagLeft(node: BSTNode<KeyT, ValueT>, parent: BSTNode<KeyT, ValueT>, grandParent: BSTNode<KeyT, ValueT>) { linkUpGreatGrandParent(node, parent: parent, grandParent: grandParent) parent.leftChild = node.rightChild parent.leftChild?.parent = parent node.rightChild = parent parent.parent = node grandParent.rightChild = node.leftChild grandParent.rightChild?.parent = grandParent node.leftChild = grandParent grandParent.parent = node } private func zigZagRight(node: BSTNode<KeyT, ValueT>, parent: BSTNode<KeyT, ValueT>, grandParent: BSTNode<KeyT, ValueT>) { linkUpGreatGrandParent(node, parent: parent, grandParent: grandParent) parent.rightChild = node.leftChild parent.rightChild?.parent = parent node.leftChild = parent parent.parent = node grandParent.leftChild = node.rightChild grandParent.leftChild?.parent = grandParent node.rightChild = grandParent grandParent.parent = node } public override init() { super.init() } }
c1b1348016176a0a15917b2d79b3a179
24.726415
134
0.69912
false
false
false
false
brentdax/swift
refs/heads/master
stdlib/public/core/Map.swift
apache-2.0
1
//===--- Map.swift - Lazily map over a Sequence ---------------*- 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 // //===----------------------------------------------------------------------===// /// A `Sequence` whose elements consist of those in a `Base` /// `Sequence` passed through a transform function returning `Element`. /// These elements are computed lazily, each time they're read, by /// calling the transform function on a base element. @_fixed_layout public struct LazyMapSequence<Base : Sequence, Element> { public typealias Elements = LazyMapSequence @usableFromInline internal var _base: Base @usableFromInline internal let _transform: (Base.Element) -> Element /// Creates an instance with elements `transform(x)` for each element /// `x` of base. @inlinable internal init(_base: Base, transform: @escaping (Base.Element) -> Element) { self._base = _base self._transform = transform } } extension LazyMapSequence { @_fixed_layout public struct Iterator { @usableFromInline internal var _base: Base.Iterator @usableFromInline internal let _transform: (Base.Element) -> Element @inlinable public var base: Base.Iterator { return _base } @inlinable internal init( _base: Base.Iterator, _transform: @escaping (Base.Element) -> Element ) { self._base = _base self._transform = _transform } } } extension LazyMapSequence.Iterator: IteratorProtocol, Sequence { /// Advances to the next element and returns it, or `nil` if no next element /// exists. /// /// Once `nil` has been returned, all subsequent calls return `nil`. /// /// - Precondition: `next()` has not been applied to a copy of `self` /// since the copy was made. @inlinable public mutating func next() -> Element? { return _base.next().map(_transform) } } extension LazyMapSequence: LazySequenceProtocol { /// Returns an iterator over the elements of this sequence. /// /// - Complexity: O(1). @inlinable public __consuming func makeIterator() -> Iterator { return Iterator(_base: _base.makeIterator(), _transform: _transform) } /// A value less than or equal to the number of elements in the sequence, /// calculated nondestructively. /// /// The default implementation returns 0. If you provide your own /// implementation, make sure to compute the value nondestructively. /// /// - Complexity: O(1), except if the sequence also conforms to `Collection`. /// In this case, see the documentation of `Collection.underestimatedCount`. @inlinable public var underestimatedCount: Int { return _base.underestimatedCount } } /// A `Collection` whose elements consist of those in a `Base` /// `Collection` passed through a transform function returning `Element`. /// These elements are computed lazily, each time they're read, by /// calling the transform function on a base element. @_fixed_layout public struct LazyMapCollection<Base: Collection, Element> { @usableFromInline internal var _base: Base @usableFromInline internal let _transform: (Base.Element) -> Element /// Create an instance with elements `transform(x)` for each element /// `x` of base. @inlinable internal init(_base: Base, transform: @escaping (Base.Element) -> Element) { self._base = _base self._transform = transform } } extension LazyMapCollection: Sequence { public typealias Iterator = LazyMapSequence<Base,Element>.Iterator /// Returns an iterator over the elements of this sequence. /// /// - Complexity: O(1). @inlinable public __consuming func makeIterator() -> Iterator { return Iterator(_base: _base.makeIterator(), _transform: _transform) } /// A value less than or equal to the number of elements in the sequence, /// calculated nondestructively. /// /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the length /// of the collection. @inlinable public var underestimatedCount: Int { return _base.underestimatedCount } } extension LazyMapCollection: LazyCollectionProtocol { public typealias Index = Base.Index public typealias Indices = Base.Indices public typealias SubSequence = LazyMapCollection<Base.SubSequence, Element> @inlinable public var startIndex: Base.Index { return _base.startIndex } @inlinable public var endIndex: Base.Index { return _base.endIndex } @inlinable public func index(after i: Index) -> Index { return _base.index(after: i) } @inlinable public func formIndex(after i: inout Index) { _base.formIndex(after: &i) } /// Accesses the element at `position`. /// /// - Precondition: `position` is a valid position in `self` and /// `position != endIndex`. @inlinable public subscript(position: Base.Index) -> Element { return _transform(_base[position]) } @inlinable public subscript(bounds: Range<Base.Index>) -> SubSequence { return SubSequence(_base: _base[bounds], transform: _transform) } @inlinable public var indices: Indices { return _base.indices } /// A Boolean value indicating whether the collection is empty. @inlinable public var isEmpty: Bool { return _base.isEmpty } /// The number of elements in the collection. /// /// To check whether the collection is empty, use its `isEmpty` property /// instead of comparing `count` to zero. Unless the collection guarantees /// random-access performance, calculating `count` can be an O(*n*) /// operation. /// /// - Complexity: O(1) if `Index` conforms to `RandomAccessIndex`; O(*n*) /// otherwise. @inlinable public var count: Int { return _base.count } @inlinable public var first: Element? { return _base.first.map(_transform) } @inlinable public func index(_ i: Index, offsetBy n: Int) -> Index { return _base.index(i, offsetBy: n) } @inlinable public func index( _ i: Index, offsetBy n: Int, limitedBy limit: Index ) -> Index? { return _base.index(i, offsetBy: n, limitedBy: limit) } @inlinable public func distance(from start: Index, to end: Index) -> Int { return _base.distance(from: start, to: end) } } extension LazyMapCollection : BidirectionalCollection where Base : BidirectionalCollection { /// A value less than or equal to the number of elements in the collection. /// /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*n*), where *n* is the length /// of the collection. @inlinable public func index(before i: Index) -> Index { return _base.index(before: i) } @inlinable public func formIndex(before i: inout Index) { _base.formIndex(before: &i) } @inlinable public var last: Element? { return _base.last.map(_transform) } } extension LazyMapCollection : RandomAccessCollection where Base : RandomAccessCollection { } //===--- Support for s.lazy -----------------------------------------------===// extension LazySequenceProtocol { /// Returns a `LazyMapSequence` over this `Sequence`. The elements of /// the result are computed lazily, each time they are read, by /// calling `transform` function on a base element. @inlinable public func map<U>( _ transform: @escaping (Elements.Element) -> U ) -> LazyMapSequence<Self.Elements, U> { return LazyMapSequence(_base: self.elements, transform: transform) } } extension LazyCollectionProtocol { /// Returns a `LazyMapCollection` over this `Collection`. The elements of /// the result are computed lazily, each time they are read, by /// calling `transform` function on a base element. @inlinable public func map<U>( _ transform: @escaping (Elements.Element) -> U ) -> LazyMapCollection<Self.Elements, U> { return LazyMapCollection(_base: self.elements, transform: transform) } } extension LazyMapSequence { @inlinable @available(swift, introduced: 5) public func map<ElementOfResult>( _ transform: @escaping (Element) -> ElementOfResult ) -> LazyMapSequence<Base, ElementOfResult> { return LazyMapSequence<Base, ElementOfResult>( _base: _base, transform: {transform(self._transform($0))}) } } extension LazyMapCollection { @inlinable @available(swift, introduced: 5) public func map<ElementOfResult>( _ transform: @escaping (Element) -> ElementOfResult ) -> LazyMapCollection<Base, ElementOfResult> { return LazyMapCollection<Base, ElementOfResult>( _base: _base, transform: {transform(self._transform($0))}) } }
3244042497099de76d283c9e5c74c6eb
30.58156
80
0.681451
false
false
false
false
BigxMac/firefox-ios
refs/heads/master
StorageTests/TestLogins.swift
mpl-2.0
18
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import XCTest import XCGLogger private let log = XCGLogger.defaultInstance() class TestSQLiteLogins: XCTestCase { var db: BrowserDB! var logins: SQLiteLogins! let login = Login.createWithHostname("hostname1", username: "username1", password: "password1") override func setUp() { super.setUp() let files = MockFiles() self.db = BrowserDB(filename: "testsqlitelogins.db", files: files) self.logins = SQLiteLogins(db: self.db) let expectation = self.expectationWithDescription("Remove all logins.") self.removeAllLogins().upon({ res in expectation.fulfill() }) waitForExpectationsWithTimeout(10.0, handler: nil) } func testAddLogin() { log.debug("Created \(self.login)") let expectation = self.expectationWithDescription("Add login") addLogin(login) >>> getLoginsFor(login.protectionSpace, expected: [login]) >>> done(expectation) waitForExpectationsWithTimeout(10.0, handler: nil) } func testGetOrder() { let expectation = self.expectationWithDescription("Add login") // Different GUID. let login2 = Login.createWithHostname("hostname1", username: "username2", password: "password2") addLogin(login) >>> { self.addLogin(login2) } >>> getLoginsFor(login.protectionSpace, expected: [login2, login]) >>> done(expectation) waitForExpectationsWithTimeout(10.0, handler: nil) } func testRemoveLogin() { let expectation = self.expectationWithDescription("Remove login") addLogin(login) >>> removeLogin(login) >>> getLoginsFor(login.protectionSpace, expected: []) >>> done(expectation) waitForExpectationsWithTimeout(10.0, handler: nil) } func testUpdateLogin() { let expectation = self.expectationWithDescription("Update login") let updated = Login.createWithHostname("hostname1", username: "username1", password: "password3") updated.guid = self.login.guid addLogin(login) >>> updateLogin(updated) >>> getLoginsFor(login.protectionSpace, expected: [updated]) >>> done(expectation) waitForExpectationsWithTimeout(10.0, handler: nil) } /* func testAddUseOfLogin() { let expectation = self.expectationWithDescription("Add visit") if var usageData = login as? LoginUsageData { usageData.timeCreated = NSDate.nowMicroseconds() } addLogin(login) >>> addUseDelayed(login, time: 1) >>> getLoginDetailsFor(login, expected: login as! LoginUsageData) >>> done(login.protectionSpace, expectation: expectation) waitForExpectationsWithTimeout(10.0, handler: nil) } */ func done(expectation: XCTestExpectation)() -> Success { return removeAllLogins() >>> getLoginsFor(login.protectionSpace, expected: []) >>> { expectation.fulfill() return succeed() } } // Note: These functions are all curried so that we pass arguments, but still chain them below func addLogin(login: LoginData) -> Success { log.debug("Add \(login)") return logins.addLogin(login) } func updateLogin(login: LoginData)() -> Success { log.debug("Update \(login)") return logins.updateLoginByGUID(login.guid, new: login, significant: true) } func addUseDelayed(login: Login, time: UInt32)() -> Success { sleep(time) login.timeLastUsed = NSDate.nowMicroseconds() let res = logins.addUseOfLoginByGUID(login.guid) sleep(time) return res } func getLoginsFor(protectionSpace: NSURLProtectionSpace, expected: [LoginData]) -> (() -> Success) { return { log.debug("Get logins for \(protectionSpace)") return self.logins.getLoginsForProtectionSpace(protectionSpace) >>== { results in XCTAssertEqual(expected.count, results.count) for (index, login) in enumerate(expected) { XCTAssertEqual(results[index]!.username!, login.username!) XCTAssertEqual(results[index]!.hostname, login.hostname) XCTAssertEqual(results[index]!.password, login.password) } return succeed() } } } /* func getLoginDetailsFor(login: LoginData, expected: LoginUsageData) -> (() -> Success) { return { log.debug("Get details for \(login)") let deferred = self.logins.getUsageDataForLogin(login) log.debug("Final result \(deferred)") return deferred >>== { l in log.debug("Got cursor") XCTAssertLessThan(expected.timePasswordChanged - l.timePasswordChanged, 10) XCTAssertLessThan(expected.timeLastUsed - l.timeLastUsed, 10) XCTAssertLessThan(expected.timeCreated - l.timeCreated, 10) return succeed() } } } */ func removeLogin(login: LoginData)() -> Success { log.debug("Remove \(login)") return logins.removeLoginByGUID(login.guid) } func removeAllLogins() -> Success { log.debug("Remove All") // Because we don't want to just mark them as deleted. return self.db.run("DELETE FROM \(TableLoginsMirror)") >>> { self.db.run("DELETE FROM \(TableLoginsLocal)") } } } class TestSyncableLogins: XCTestCase { var db: BrowserDB! var logins: SQLiteLogins! override func setUp() { super.setUp() let files = MockFiles() self.db = BrowserDB(filename: "testsyncablelogins.db", files: files) self.logins = SQLiteLogins(db: self.db) let expectation = self.expectationWithDescription("Remove all logins.") self.removeAllLogins().upon({ res in expectation.fulfill() }) waitForExpectationsWithTimeout(10.0, handler: nil) } func removeAllLogins() -> Success { log.debug("Remove All") // Because we don't want to just mark them as deleted. return self.db.run("DELETE FROM \(TableLoginsMirror)") >>> { self.db.run("DELETE FROM \(TableLoginsLocal)") } } func testDiffers() { let guid = "abcdabcdabcd" let host = "http://example.com" let user = "username" var loginA1 = Login(guid: guid, hostname: host, username: user, password: "password1") loginA1.formSubmitURL = "\(host)/form1/" loginA1.usernameField = "afield" var loginA2 = Login(guid: guid, hostname: host, username: user, password: "password1") loginA2.formSubmitURL = "\(host)/form1/" loginA2.usernameField = "somefield" var loginB = Login(guid: guid, hostname: host, username: user, password: "password2") loginB.formSubmitURL = "\(host)/form1/" var loginC = Login(guid: guid, hostname: host, username: user, password: "password") loginC.formSubmitURL = "\(host)/form2/" XCTAssert(loginA1.isSignificantlyDifferentFrom(loginB)) XCTAssert(loginA1.isSignificantlyDifferentFrom(loginC)) XCTAssert(loginA2.isSignificantlyDifferentFrom(loginB)) XCTAssert(loginA2.isSignificantlyDifferentFrom(loginC)) XCTAssert(!loginA1.isSignificantlyDifferentFrom(loginA2)) } func testLocalNewStaysNewAndIsRemoved() { let guidA = "abcdabcdabcd" var loginA1 = Login(guid: guidA, hostname: "http://example.com", username: "username", password: "password") loginA1.formSubmitURL = "http://example.com/form/" loginA1.timesUsed = 1 XCTAssertTrue((self.logins as BrowserLogins).addLogin(loginA1).value.isSuccess) let local1 = self.logins.getExistingLocalRecordByGUID(guidA).value.successValue! XCTAssertNotNil(local1) XCTAssertEqual(local1!.guid, guidA) XCTAssertEqual(local1!.syncStatus, SyncStatus.New) XCTAssertEqual(local1!.timesUsed, 1) XCTAssertTrue(self.logins.addUseOfLoginByGUID(guidA).value.isSuccess) // It's still new. let local2 = self.logins.getExistingLocalRecordByGUID(guidA).value.successValue! XCTAssertNotNil(local2) XCTAssertEqual(local2!.guid, guidA) XCTAssertEqual(local2!.syncStatus, SyncStatus.New) XCTAssertEqual(local2!.timesUsed, 2) // It's removed immediately, because it was never synced. XCTAssertTrue((self.logins as BrowserLogins).removeLoginByGUID(guidA).value.isSuccess) XCTAssertNil(self.logins.getExistingLocalRecordByGUID(guidA).value.successValue!) } func testApplyLogin() { let guidA = "abcdabcdabcd" var loginA1 = ServerLogin(guid: guidA, hostname: "http://example.com", username: "username", password: "password", modified: 1234) loginA1.formSubmitURL = "http://example.com/form/" loginA1.timesUsed = 3 XCTAssertTrue(self.logins.applyChangedLogin(loginA1).value.isSuccess) let local = self.logins.getExistingLocalRecordByGUID(guidA).value.successValue! let mirror = self.logins.getExistingMirrorRecordByGUID(guidA).value.successValue! XCTAssertTrue(nil == local) XCTAssertTrue(nil != mirror) XCTAssertEqual(mirror!.guid, guidA) XCTAssertFalse(mirror!.isOverridden) XCTAssertEqual(mirror!.serverModified, Timestamp(1234), "Timestamp matches.") XCTAssertEqual(mirror!.timesUsed, 3) XCTAssertTrue(nil == mirror!.httpRealm) XCTAssertTrue(nil == mirror!.passwordField) XCTAssertTrue(nil == mirror!.usernameField) XCTAssertEqual(mirror!.formSubmitURL!, "http://example.com/form/") XCTAssertEqual(mirror!.hostname, "http://example.com") XCTAssertEqual(mirror!.username!, "username") XCTAssertEqual(mirror!.password, "password") // Change it. var loginA2 = ServerLogin(guid: guidA, hostname: "http://example.com", username: "username", password: "newpassword", modified: 2234) loginA2.formSubmitURL = "http://example.com/form/" loginA2.timesUsed = 4 XCTAssertTrue(self.logins.applyChangedLogin(loginA2).value.isSuccess) let changed = self.logins.getExistingMirrorRecordByGUID(guidA).value.successValue! XCTAssertTrue(nil != changed) XCTAssertFalse(changed!.isOverridden) XCTAssertEqual(changed!.serverModified, Timestamp(2234), "Timestamp is new.") XCTAssertEqual(changed!.username!, "username") XCTAssertEqual(changed!.password, "newpassword") XCTAssertEqual(changed!.timesUsed, 4) // Change it locally. let preUse = NSDate.now() XCTAssertTrue(self.logins.addUseOfLoginByGUID(guidA).value.isSuccess) let localUsed = self.logins.getExistingLocalRecordByGUID(guidA).value.successValue! let mirrorUsed = self.logins.getExistingMirrorRecordByGUID(guidA).value.successValue! XCTAssertNotNil(localUsed) XCTAssertNotNil(mirrorUsed) XCTAssertEqual(mirrorUsed!.guid, guidA) XCTAssertEqual(localUsed!.guid, guidA) XCTAssertEqual(mirrorUsed!.password, "newpassword") XCTAssertEqual(localUsed!.password, "newpassword") XCTAssertTrue(mirrorUsed!.isOverridden) // It's now overridden. XCTAssertEqual(mirrorUsed!.serverModified, Timestamp(2234), "Timestamp is new.") XCTAssertTrue(localUsed!.localModified >= preUse) // Local record is modified. XCTAssertEqual(localUsed!.syncStatus, SyncStatus.Synced) // Uses aren't enough to warrant upload. // Uses are local until reconciled. XCTAssertEqual(localUsed!.timesUsed, 5) XCTAssertEqual(mirrorUsed!.timesUsed, 4) // Change the password and form URL locally. var newLocalPassword = Login(guid: guidA, hostname: "http://example.com", username: "username", password: "yupyup") newLocalPassword.formSubmitURL = "http://example.com/form2/" let preUpdate = NSDate.now() // Updates always bump our usages, too. XCTAssertTrue(self.logins.updateLoginByGUID(guidA, new: newLocalPassword, significant: true).value.isSuccess) let localAltered = self.logins.getExistingLocalRecordByGUID(guidA).value.successValue! let mirrorAltered = self.logins.getExistingMirrorRecordByGUID(guidA).value.successValue! XCTAssertFalse(mirrorAltered!.isSignificantlyDifferentFrom(mirrorUsed!)) // The mirror is unchanged. XCTAssertFalse(mirrorAltered!.isSignificantlyDifferentFrom(localUsed!)) XCTAssertTrue(mirrorAltered!.isOverridden) // It's still overridden. XCTAssertTrue(localAltered!.isSignificantlyDifferentFrom(localUsed!)) XCTAssertEqual(localAltered!.password, "yupyup") XCTAssertEqual(localAltered!.formSubmitURL!, "http://example.com/form2/") XCTAssertTrue(localAltered!.localModified >= preUpdate) XCTAssertEqual(localAltered!.syncStatus, SyncStatus.Changed) // Changes are enough to warrant upload. XCTAssertEqual(localAltered!.timesUsed, 6) XCTAssertEqual(mirrorAltered!.timesUsed, 4) } func testDeltas() { // Shared. let guidA = "abcdabcdabcd" var loginA1 = ServerLogin(guid: guidA, hostname: "http://example.com", username: "username", password: "password", modified: 1234) loginA1.timeCreated = 1200 loginA1.timeLastUsed = 1234 loginA1.timePasswordChanged = 1200 loginA1.formSubmitURL = "http://example.com/form/" loginA1.timesUsed = 3 let a1a1 = loginA1.deltas(from: loginA1) XCTAssertEqual(0, a1a1.nonCommutative.count) XCTAssertEqual(0, a1a1.nonConflicting.count) XCTAssertEqual(0, a1a1.commutative.count) var loginA2 = ServerLogin(guid: guidA, hostname: "http://example.com", username: "username", password: "password", modified: 1235) loginA2.timeCreated = 1200 loginA2.timeLastUsed = 1235 loginA2.timePasswordChanged = 1200 loginA2.timesUsed = 4 let a1a2 = loginA2.deltas(from: loginA1) XCTAssertEqual(2, a1a2.nonCommutative.count) XCTAssertEqual(0, a1a2.nonConflicting.count) XCTAssertEqual(1, a1a2.commutative.count) switch a1a2.commutative[0] { case let .TimesUsed(increment): XCTAssertEqual(increment, 1) break default: XCTFail("Unexpected commutative login field.") } switch a1a2.nonCommutative[0] { case let .FormSubmitURL(to): XCTAssertNil(to) break default: XCTFail("Unexpected non-commutative login field.") } switch a1a2.nonCommutative[1] { case let .TimeLastUsed(to): XCTAssertEqual(to, 1235) break default: XCTFail("Unexpected non-commutative login field.") } var loginA3 = ServerLogin(guid: guidA, hostname: "http://example.com", username: "username", password: "something else", modified: 1280) loginA3.timeCreated = 1200 loginA3.timeLastUsed = 1250 loginA3.timePasswordChanged = 1250 loginA3.formSubmitURL = "http://example.com/form/" loginA3.timesUsed = 5 let a1a3 = loginA3.deltas(from: loginA1) XCTAssertEqual(3, a1a3.nonCommutative.count) XCTAssertEqual(0, a1a3.nonConflicting.count) XCTAssertEqual(1, a1a3.commutative.count) switch a1a3.commutative[0] { case let .TimesUsed(increment): XCTAssertEqual(increment, 2) break default: XCTFail("Unexpected commutative login field.") } switch a1a3.nonCommutative[0] { case let .Password(to): XCTAssertEqual("something else", to) break default: XCTFail("Unexpected non-commutative login field.") } switch a1a3.nonCommutative[1] { case let .TimeLastUsed(to): XCTAssertEqual(to, 1250) break default: XCTFail("Unexpected non-commutative login field.") } switch a1a3.nonCommutative[2] { case let .TimePasswordChanged(to): XCTAssertEqual(to, 1250) break default: XCTFail("Unexpected non-commutative login field.") } // Now apply the deltas to the original record and check that they match! XCTAssertFalse(loginA1.applyDeltas(a1a2).isSignificantlyDifferentFrom(loginA2)) XCTAssertFalse(loginA1.applyDeltas(a1a3).isSignificantlyDifferentFrom(loginA3)) let merged = Login.mergeDeltas(a: (loginA2.serverModified, a1a2), b: (loginA3.serverModified, a1a3)) let mCCount = merged.commutative.count let a2CCount = a1a2.commutative.count let a3CCount = a1a3.commutative.count XCTAssertEqual(mCCount, a2CCount + a3CCount) let mNCount = merged.nonCommutative.count let a2NCount = a1a2.nonCommutative.count let a3NCount = a1a3.nonCommutative.count XCTAssertLessThanOrEqual(mNCount, a2NCount + a3NCount) XCTAssertGreaterThanOrEqual(mNCount, max(a2NCount, a3NCount)) let mFCount = merged.nonConflicting.count let a2FCount = a1a2.nonConflicting.count let a3FCount = a1a3.nonConflicting.count XCTAssertLessThanOrEqual(mFCount, a2FCount + a3FCount) XCTAssertGreaterThanOrEqual(mFCount, max(a2FCount, a3FCount)) switch merged.commutative[0] { case let .TimesUsed(increment): XCTAssertEqual(1, increment) } switch merged.commutative[1] { case let .TimesUsed(increment): XCTAssertEqual(2, increment) } switch merged.nonCommutative[0] { case let .Password(to): XCTAssertEqual("something else", to) break default: XCTFail("Unexpected non-commutative login field.") } switch merged.nonCommutative[1] { case let .FormSubmitURL(to): XCTAssertNil(to) break default: XCTFail("Unexpected non-commutative login field.") } switch merged.nonCommutative[2] { case let .TimeLastUsed(to): XCTAssertEqual(to, 1250) break default: XCTFail("Unexpected non-commutative login field.") } switch merged.nonCommutative[3] { case let .TimePasswordChanged(to): XCTAssertEqual(to, 1250) break default: XCTFail("Unexpected non-commutative login field.") } // Applying the merged deltas gives us the expected login. var expected = Login(guid: guidA, hostname: "http://example.com", username: "username", password: "something else") expected.timeCreated = 1200 expected.timeLastUsed = 1250 expected.timePasswordChanged = 1250 expected.formSubmitURL = nil expected.timesUsed = 6 let applied = loginA1.applyDeltas(merged) XCTAssertFalse(applied.isSignificantlyDifferentFrom(expected)) XCTAssertFalse(expected.isSignificantlyDifferentFrom(applied)) } }
c7f6db0474ecd5208f6c1791e1fd14c6
38.560241
144
0.646091
false
false
false
false
zvonler/PasswordElephant
refs/heads/master
external/github.com/CryptoSwift/Sources/CryptoSwift/BlockMode/CTR.swift
gpl-3.0
1
// // CryptoSwift // // Copyright (C) 2014-2017 Marcin Krzyżanowski <[email protected]> // This software is provided 'as-is', without any express or implied warranty. // // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: // // - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. // - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. // - This notice may not be removed or altered from any source or binary distribution. // // Counter (CTR) // public struct CTR: BlockMode { public enum Error: Swift.Error { /// Invalid IV case invalidInitializationVector } public let options: BlockModeOption = [.initializationVectorRequired, .useEncryptToDecrypt] private let iv: Array<UInt8> public init(iv: Array<UInt8>) { self.iv = iv } public func worker(blockSize: Int, cipherOperation: @escaping CipherOperationOnBlock) throws -> BlockModeWorker { if iv.count != blockSize { throw Error.invalidInitializationVector } return CTRModeWorker(blockSize: blockSize, iv: iv.slice, cipherOperation: cipherOperation) } } struct CTRModeWorker: RandomAccessBlockModeWorker { let cipherOperation: CipherOperationOnBlock let blockSize: Int let additionalBufferSize: Int = 0 private let iv: ArraySlice<UInt8> var counter: UInt = 0 init(blockSize: Int, iv: ArraySlice<UInt8>, cipherOperation: @escaping CipherOperationOnBlock) { self.blockSize = blockSize self.iv = iv self.cipherOperation = cipherOperation } mutating func encrypt(block plaintext: ArraySlice<UInt8>) -> Array<UInt8> { let nonce = buildNonce(iv, counter: UInt64(counter)) counter = counter + 1 guard let ciphertext = cipherOperation(nonce.slice) else { return Array(plaintext) } return xor(plaintext, ciphertext) } mutating func decrypt(block ciphertext: ArraySlice<UInt8>) -> Array<UInt8> { return encrypt(block: ciphertext) } } private func buildNonce(_ iv: ArraySlice<UInt8>, counter: UInt64) -> Array<UInt8> { let noncePartLen = iv.count / 2 let noncePrefix = iv[iv.startIndex..<iv.startIndex.advanced(by: noncePartLen)] let nonceSuffix = iv[iv.startIndex.advanced(by: noncePartLen)..<iv.startIndex.advanced(by: iv.count)] let c = UInt64(bytes: nonceSuffix) + counter return noncePrefix + c.bytes() }
565c43d04355464e851e0ecb17d36e55
37.065789
217
0.706533
false
false
false
false
Jnosh/swift
refs/heads/master
test/SILGen/unowned.swift
apache-2.0
3
// RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s func takeClosure(_ fn: () -> Int) {} class C { func f() -> Int { return 42 } } struct A { unowned var x: C } _ = A(x: C()) // CHECK-LABEL: sil hidden @_T07unowned1AV{{[_0-9a-zA-Z]*}}fC // CHECK: bb0([[X:%.*]] : $C, %1 : $@thin A.Type): // CHECK: [[X_UNOWNED:%.*]] = ref_to_unowned [[X]] : $C to $@sil_unowned C // CHECK: unowned_retain [[X_UNOWNED]] // CHECK: destroy_value [[X]] // CHECK: [[A:%.*]] = struct $A ([[X_UNOWNED]] : $@sil_unowned C) // CHECK: return [[A]] // CHECK: } protocol P {} struct X: P {} struct AddressOnly { unowned var x: C var p: P } _ = AddressOnly(x: C(), p: X()) // CHECK-LABEL: sil hidden @_T07unowned11AddressOnlyV{{[_0-9a-zA-Z]*}}fC // CHECK: bb0([[RET:%.*]] : $*AddressOnly, [[X:%.*]] : $C, {{.*}}): // CHECK: [[X_ADDR:%.*]] = struct_element_addr [[RET]] : $*AddressOnly, #AddressOnly.x // CHECK: [[X_UNOWNED:%.*]] = ref_to_unowned [[X]] : $C to $@sil_unowned C // CHECK: unowned_retain [[X_UNOWNED]] : $@sil_unowned C // CHECK: store [[X_UNOWNED]] to [init] [[X_ADDR]] // CHECK: destroy_value [[X]] // CHECK: } // CHECK-LABEL: sil hidden @_T07unowned5test0yAA1CC1c_tF : $@convention(thin) (@owned C) -> () { func test0(c c: C) { // CHECK: bb0([[ARG:%.*]] : $C): var a: A // CHECK: [[A1:%.*]] = alloc_box ${ var A }, var, name "a" // CHECK: [[MARKED_A1:%.*]] = mark_uninitialized [var] [[A1]] // CHECK: [[PBA:%.*]] = project_box [[MARKED_A1]] unowned var x = c // CHECK: [[X:%.*]] = alloc_box ${ var @sil_unowned C } // CHECK: [[PBX:%.*]] = project_box [[X]] // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]] // CHECK: [[T2:%.*]] = ref_to_unowned [[ARG_COPY]] : $C to $@sil_unowned C // CHECK: unowned_retain [[T2]] : $@sil_unowned C // CHECK: store [[T2]] to [init] [[PBX]] : $*@sil_unowned C // CHECK: destroy_value [[ARG_COPY]] // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] a.x = c // CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]] // CHECK: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]] // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PBA]] // CHECK: [[T1:%.*]] = struct_element_addr [[WRITE]] : $*A, #A.x // CHECK: [[T2:%.*]] = ref_to_unowned [[ARG_COPY]] : $C // CHECK: unowned_retain [[T2]] : $@sil_unowned C // CHECK: assign [[T2]] to [[T1]] : $*@sil_unowned C // CHECK: destroy_value [[ARG_COPY]] // CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]] a.x = x // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PBX]] // CHECK: [[T2:%.*]] = load [take] [[READ]] : $*@sil_unowned C // CHECK: strong_retain_unowned [[T2]] : $@sil_unowned C // CHECK: [[T3:%.*]] = unowned_to_ref [[T2]] : $@sil_unowned C to $C // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PBA]] // CHECK: [[XP:%.*]] = struct_element_addr [[WRITE]] : $*A, #A.x // CHECK: [[T4:%.*]] = ref_to_unowned [[T3]] : $C to $@sil_unowned C // CHECK: unowned_retain [[T4]] : $@sil_unowned C // CHECK: assign [[T4]] to [[XP]] : $*@sil_unowned C // CHECK: destroy_value [[T3]] : $C // CHECK: destroy_value [[X]] // CHECK: destroy_value [[MARKED_A1]] // CHECK: destroy_value [[ARG]] } // CHECK: } // end sil function '_T07unowned5test0yAA1CC1c_tF' // CHECK-LABEL: sil hidden @{{.*}}testunowned_local func testunowned_local() -> C { // CHECK: [[C:%.*]] = apply let c = C() // CHECK: [[UC:%.*]] = alloc_box ${ var @sil_unowned C }, let, name "uc" // CHECK: [[PB_UC:%.*]] = project_box [[UC]] // CHECK: [[BORROWED_C:%.*]] = begin_borrow [[C]] // CHECK: [[C_COPY:%.*]] = copy_value [[BORROWED_C]] // CHECK: [[tmp1:%.*]] = ref_to_unowned [[C_COPY]] : $C to $@sil_unowned C // CHECK: unowned_retain [[tmp1]] // CHECK: store [[tmp1]] to [init] [[PB_UC]] // CHECK: destroy_value [[C_COPY]] // CHECK: end_borrow [[BORROWED_C]] from [[C]] unowned let uc = c // CHECK: [[tmp2:%.*]] = load [take] [[PB_UC]] // CHECK: strong_retain_unowned [[tmp2]] // CHECK: [[tmp3:%.*]] = unowned_to_ref [[tmp2]] return uc // CHECK: destroy_value [[UC]] // CHECK: destroy_value [[C]] // CHECK: return [[tmp3]] } // <rdar://problem/16877510> capturing an unowned let crashes in silgen func test_unowned_let_capture(_ aC : C) { unowned let bC = aC takeClosure { bC.f() } } // CHECK-LABEL: sil private @_T07unowned05test_A12_let_captureyAA1CCFSiycfU_ : $@convention(thin) (@owned @sil_unowned C) -> Int { // CHECK: bb0([[ARG:%.*]] : $@sil_unowned C): // CHECK-NEXT: debug_value %0 : $@sil_unowned C, let, name "bC", argno 1 // CHECK-NEXT: strong_retain_unowned [[ARG]] : $@sil_unowned C // CHECK-NEXT: [[UNOWNED_ARG:%.*]] = unowned_to_ref [[ARG]] : $@sil_unowned C to $C // CHECK-NEXT: [[FUN:%.*]] = class_method [[UNOWNED_ARG]] : $C, #C.f!1 : (C) -> () -> Int, $@convention(method) (@guaranteed C) -> Int // CHECK-NEXT: [[RESULT:%.*]] = apply [[FUN]]([[UNOWNED_ARG]]) : $@convention(method) (@guaranteed C) -> Int // CHECK-NEXT: destroy_value [[UNOWNED_ARG]] // CHECK-NEXT: destroy_value [[ARG]] : $@sil_unowned C // CHECK-NEXT: return [[RESULT]] : $Int // <rdar://problem/16880044> unowned let properties don't work as struct and class members class TestUnownedMember { unowned let member : C init(inval: C) { self.member = inval } } // CHECK-LABEL: sil hidden @_T07unowned17TestUnownedMemberCAcA1CC5inval_tcfc : // CHECK: bb0([[ARG1:%.*]] : $C, [[SELF_PARAM:%.*]] : $TestUnownedMember): // CHECK: [[SELF:%.*]] = mark_uninitialized [rootself] [[SELF_PARAM]] : $TestUnownedMember // CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]] // CHECK: [[BORROWED_ARG1:%.*]] = begin_borrow [[ARG1]] // CHECK: [[ARG1_COPY:%.*]] = copy_value [[BORROWED_ARG1]] // CHECK: [[FIELDPTR:%.*]] = ref_element_addr [[BORROWED_SELF]] : $TestUnownedMember, #TestUnownedMember.member // CHECK: [[INVAL:%.*]] = ref_to_unowned [[ARG1_COPY]] : $C to $@sil_unowned C // CHECK: unowned_retain [[INVAL]] : $@sil_unowned C // CHECK: assign [[INVAL]] to [[FIELDPTR]] : $*@sil_unowned C // CHECK: destroy_value [[ARG1_COPY]] : $C // CHECK: end_borrow [[BORROWED_ARG1]] from [[ARG1]] // CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]] // CHECK: [[RET_SELF:%.*]] = copy_value [[SELF]] // CHECK: destroy_value [[SELF]] // CHECK: destroy_value [[ARG1]] // CHECK: return [[RET_SELF]] : $TestUnownedMember // CHECK: } // end sil function '_T07unowned17TestUnownedMemberCAcA1CC5inval_tcfc' // Just verify that lowering an unowned reference to a type parameter // doesn't explode. struct Unowned<T: AnyObject> { unowned var object: T } func takesUnownedStruct(_ z: Unowned<C>) {} // CHECK-LABEL: sil hidden @_T07unowned18takesUnownedStructyAA0C0VyAA1CCGF : $@convention(thin) (@owned Unowned<C>) -> ()
4f6a00fffd52992883510aeaba5e46e2
40.793939
136
0.569751
false
true
false
false
velvetroom/columbus
refs/heads/master
Source/Model/CreateSearch/MCreateSearch+Completer.swift
mit
1
import MapKit extension MCreateSearch { //MARK: private private func asyncSearchItem(item:MKLocalSearchCompletion) { let searchRequest:MKLocalSearchRequest = MKLocalSearchRequest(completion:item) let search:MKLocalSearch = MKLocalSearch(request:searchRequest) search.start { [weak self] (response:MKLocalSearchResponse?, error:Error?) in self?.searchItem( response:response, error:error) } } private func searchItem( response:MKLocalSearchResponse?, error:Error?) { guard error == nil, let mapItems:[MKMapItem] = response?.mapItems, let firstItem:MKMapItem = mapItems.first else { return } let coordinate:CLLocationCoordinate2D = firstItem.placemark.coordinate DispatchQueue.main.async { [weak self] in self?.itemFound(coordinate:coordinate) } } private func itemFound(coordinate:CLLocationCoordinate2D) { guard let controller:CCreateSearch = view?.controller as? CCreateSearch else { return } controller.itemFound(coordinate:coordinate) } //MARK: internal func complete(string:String) { guard string.isEmpty else { completer.queryFragment = string return } completer.cancel() updateItems(items:[]) } func searchItem(item:MKLocalSearchCompletion) { DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async { [weak self] in self?.asyncSearchItem(item:item) } } }
5b96d4ac04fd00fe5be5afea0baab184
21.546512
86
0.527076
false
false
false
false
lingostar/PilotPlant
refs/heads/master
PilotPlant/NavigationControllers.swift
agpl-3.0
1
// // NavigationControllers.swift // PilotPlant // // Created by Lingostar on 2016. 12. 15.. // // import Foundation import UIKit @IBDesignable public class TransparentNavigationController:UINavigationController { public override func viewDidLoad() { super.viewDidLoad() self.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default) self.navigationBar.shadowImage = UIImage() self.navigationBar.isTranslucent = true self.view.backgroundColor = UIColor.clear } } @IBDesignable open class CHTabBar : UITabBar { @IBInspectable open var badgeOffsetX:Float = 0.0 @IBInspectable open var badgeOffsetY:Float = 0.0 override open func layoutSubviews() { super.layoutSubviews() self.subviews.map({ $0.subviews.map({ badgeView in if NSStringFromClass(badgeView.classForCoder) == "_UIBadgeView" { badgeView.layer.transform = CATransform3DIdentity badgeView.layer.transform = CATransform3DMakeTranslation(CGFloat(badgeOffsetX), CGFloat(badgeOffsetY), 1.0) } }) }) } } extension Array { subscript (safe index: Int) -> Element? { return indices ~= index ? self[index] : nil } } public class HalfSizePresentationController : UIPresentationController { public override var frameOfPresentedViewInContainerView: CGRect { return CGRect(x: 0, y: containerView!.bounds.height-500, width: containerView!.bounds.width, height: 500) } } open class Link: UIStoryboardSegue { override open func perform() { print("Linked") } }
3606cfb66773116bea4aa794ff2d0189
25.28125
127
0.659334
false
false
false
false
ernieb4768/VelocityCBT
refs/heads/master
CBT Velocity/ActivitiesViewController.swift
apache-2.0
1
// // ActivitiesViewController.swift // CBT Velocity // // Created by Ryan Hoffman on 4/5/16. // Copyright © 2016 Ryan Hoffman. All rights reserved. // import UIKit class ActivitiesViewController: UITableViewController { var activities = Array<String>() let urlPath = "http://76.188.89.113/getAllActivities.php" @IBOutlet var uiTableView: UITableView! var TableData: Array<datastruct> = Array<datastruct>() enum ErrorHandler: ErrorType { case ErrorFetchingResults } struct datastruct { var imageURL: String? var description: String? var image: UIImage? = nil init(add: NSDictionary){ imageURL = add["IMAGE"] as? String description = add["DESCRIPTION"] as? String } } override func viewDidLoad() { super.viewDidLoad() uiTableView.dataSource = self uiTableView.delegate = self getActivitiesFromJson(urlPath) // 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() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // Retrieve the JSON array from the url. func getActivitiesFromJson(url: String){ let url: NSURL = NSURL(string: url)! let session = NSURLSession.sharedSession() let request = NSMutableURLRequest(URL: url) request.HTTPMethod = "GET" request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData let task = session.dataTaskWithRequest(request) {(let data, let response, let error) in guard let _: NSData = data, let _: NSURLResponse = response where error == nil else { print("error") return } dispatch_async(dispatch_get_main_queue(), { self.extractJson(data!) return }) } task.resume() } func extractJson(jsonData: NSData) { let json: AnyObject? do { json = try NSJSONSerialization.JSONObjectWithData(jsonData, options: []) } catch { json = nil return } if let list = json as? NSArray { for i in 0 ..< list.count{ if let dataBlock = list[i] as? NSDictionary { TableData.append(datastruct(add: dataBlock)) print(dataBlock) } } refreshTable() } } func refreshTable(){ dispatch_async(dispatch_get_main_queue(), { self.tableView.reloadData() return }) } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // return the number of sections return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // Return the number of rows in the TableView return TableData.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("ReusableCell", forIndexPath: indexPath) // Configure the cell. let data = TableData[indexPath.row] cell.textLabel?.text = data.description return cell } // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return false } // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source //tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, // and add a new row to the table view } } /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return false } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before // navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
cae41ef1a7f8c57b362baefca7fe08f9
30.956044
97
0.595083
false
false
false
false
mitchtreece/Bulletin
refs/heads/master
Bulletin/Classes/BulletinManager.swift
mit
1
// // BulletinManager.swift // Bulletin // // Created by Mitch Treece on 7/10/17. // Copyright © 2017 Mitch Treece. All rights reserved. // import UIKit import AVFoundation import SnapKit internal class BulletinManager { static let shared = BulletinManager() private(set) var bulletinWindow: BulletinWindow? private var bulletinViewController: BulletinViewController? private(set) var bulletinView: BulletinView? fileprivate var timer: Timer? private var soundPlayer: AVAudioPlayer? private init() { // Swizzle UIViewController's present() function // so we can properly handle bulletin window levels UIViewController.bulletin_swizzlePresent() } func present(_ bulletin: BulletinView, after delay: TimeInterval = 0) { DispatchQueue.main.asyncAfter(deadline: .now() + delay) { [weak self] in guard let _self = self else { return } if let _ = _self.bulletinView { // Already displaying a bulletin, // dismiss and call present again _self.dismissCurrentBulletin(completion: { _self.present(bulletin) }) } else { bulletin._delegate = self bulletin.soundEffectPlayer?.play() bulletin.tapticFeedback(for: bulletin.taptics.presentation) _self.timer?.invalidate() _self.bulletinView = bulletin _self.animateBulletinIn(bulletin) // Needs to be called after animateBulletinIn() so frame is set correctly bulletin.appearanceDelegate?.bulletinViewWillAppear?(bulletin) var duration: TimeInterval = 0 if case .limit(let time) = bulletin.duration { duration = time } if duration > 0 { _self.timer = Timer.scheduledTimer(timeInterval: duration, target: _self, selector: #selector(_self.bulletinTimerDidFire(_:)), userInfo: ["bulletin": bulletin], repeats: false) } } } } func dismissCurrentBulletin(withDuration duration: TimeInterval = 0.4, damping: CGFloat = 0.8, velocity: CGFloat = 0.3, completion: (()->())? = nil) { guard let cbv = bulletinView else { return } timer?.invalidate() timer = nil cbv.appearanceDelegate?.bulletinViewWillDisappear?(cbv) animateCurrentBulletinOut(withDuration: duration, damping: damping, velocity: velocity, completion: completion) } func dismiss(_ bulletin: BulletinView) { guard let cbv = bulletinView, cbv == bulletin else { return } dismissCurrentBulletin() } private func animateBulletinIn(_ bulletin: BulletinView) { bulletinWindow = BulletinWindow() bulletinWindow!.backgroundColor = UIColor.clear bulletinWindow!.windowLevel = UIWindow.Level(rawValue: bulletin.level.rawValue) bulletinWindow!.isHidden = false if let keyboardWindow = UIApplication.shared.currentKeyboardWindow, bulletin.level == .keyboard { keyboardWindow.addSubview(bulletinWindow!) } bulletinViewController = BulletinViewController() bulletinViewController!.bulletin = bulletin bulletinViewController!.previousStatusBarStyle = UIApplication.shared.currentStatusBarAppearance.style bulletinViewController!.isStatusBarHidden = UIApplication.shared.currentStatusBarAppearance.hidden bulletinWindow!.rootViewController = bulletinViewController bulletinViewController!.animateIn() } fileprivate func animateCurrentBulletinOut(withDuration duration: TimeInterval, damping: CGFloat, velocity: CGFloat, completion: (()->())?) { bulletinViewController?.animateOut(withDuration: duration, damping: damping, velocity: velocity, completion: { self.bulletinView?.removeFromSuperview() self.bulletinView = nil self.bulletinViewController?.view.removeFromSuperview() self.bulletinViewController = nil self.bulletinWindow?.removeFromSuperview() self.bulletinWindow?.isHidden = true self.bulletinWindow = nil completion?() }) } @objc fileprivate func bulletinTimerDidFire(_ timer: Timer) { guard let info = timer.userInfo as? [String: Any], let bulletin = info["bulletin"] as? BulletinView else { return } dismissCurrentBulletin() bulletin.appearanceDelegate?.bulletinViewWasAutomaticallyDismissed?(bulletin) } } extension BulletinManager: BulletinViewDelegate { func bulletinViewDidTap(_ bulletin: BulletinView) { guard let action = bulletin.action else { return } bulletin.tapticFeedback(for: bulletin.taptics.action) dismissCurrentBulletin { self.dismissCurrentBulletin() action() } } func bulletinViewDidBeginPanning(_ bulletin: BulletinView) { timer?.invalidate() } func bulletinViewDidEndPanning(_ bulletin: BulletinView, withTranslation translation: CGPoint, velocity: CGPoint) { let maxTranslation = (bulletin.style.edgeInsets.top + (bulletin.bounds.height / 2)) let maxVelocity: CGFloat = 500 let yTranslation = (bulletin.position == .top) ? -translation.y : translation.y let yVelocity = (bulletin.position == .top) ? -velocity.y : velocity.y // print("translation = (\(yTranslation) / \(maxTranslation)), velocity = (\(yVelocity) / \(maxVelocity))") if yTranslation >= maxTranslation || yVelocity >= maxVelocity { dismissCurrentBulletin(velocity: velocity.y) bulletin.appearanceDelegate?.bulletinViewWasInteractivelyDismissed?(bulletin) } else { let damping = (bulletin.presentationAnimation.springDamping > 0) ? 0.7 : 0 let velocity = (bulletin.presentationAnimation.springVelocity > 0) ? 0.4 : 0 if damping > 0 && velocity > 0 { // Presented with a spring, snap back with one UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.4, options: [.curveEaseOut], animations: { bulletin.transform = CGAffineTransform.identity }, completion: nil) } else { UIView.animate(withDuration: 0.25, delay: 0, options: [.curveEaseOut], animations: { bulletin.transform = CGAffineTransform.identity }, completion: nil) } if bulletin.style.isStretchingEnabled { bulletin.tapticFeedback(for: bulletin.taptics.snapping) } var duration: TimeInterval = 0 if case .limit(let time) = bulletin.duration { duration = time } if duration > 0 { timer = Timer.scheduledTimer(timeInterval: duration, target: self, selector: #selector(bulletinTimerDidFire(_:)), userInfo: ["bulletin": bulletin], repeats: false) } } } }
3c010da87416ee1f811128b03eb4ea7b
34.59375
196
0.574439
false
false
false
false
shahmishal/swift
refs/heads/master
test/stdlib/OSLogPrototypeExecTest.swift
apache-2.0
3
// RUN: %empty-directory(%t) // RUN: %target-build-swift %s -swift-version 5 -DPTR_SIZE_%target-ptrsize -o %t/OSLogPrototypeExecTest // RUN: %target-run %t/OSLogPrototypeExecTest // REQUIRES: executable_test // REQUIRES: OS=macosx || OS=ios || OS=tvos || OS=watchos // Run-time tests for testing the new OS log APIs that accept string // interpolations. The new APIs are still prototypes and must be used only in // tests. import OSLogPrototype import StdlibUnittest defer { runAllTests() } internal var OSLogTestSuite = TestSuite("OSLogTest") if #available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) { // Following tests check whether valid log calls execute without // compile-time and run-time errors. func logMessages(_ h: Logger) { // Test logging of simple messages. h.log("A message with no data") // Test logging at specific levels. h.log(level: .debug, "Minimum integer value: \(Int.min, format: .hex)") h.log(level: .info, "Maximum integer value: \(Int.max, format: .hex)") let privateID = 0x79abcdef h.log( level: .error, "Private Identifier: \(privateID, format: .hex, privacy: .private)") let addr = 0x7afebabe h.log( level: .fault, "Invalid address: 0x\(addr, format: .hex, privacy: .public)") // Test logging with multiple arguments. let filePermissions = 0o777 let pid = 122225 h.log( level: .error, """ Access prevented: process \(pid) initiated by \ user: \(privateID, privacy: .private) attempted resetting \ permissions to \(filePermissions, format: .octal) """) } OSLogTestSuite.test("log with default logger") { let h = Logger() logMessages(h) } OSLogTestSuite.test("log with custom logger") { let h = Logger(subsystem: "com.swift.test", category: "OSLogAPIPrototypeTest") logMessages(h) } OSLogTestSuite.test("escaping of percents") { let h = Logger() h.log("a = c % d") h.log("Process failed after 99% completion") h.log("Double percents: %%") } // A stress test that checks whether the log APIs handle messages with more // than 48 interpolated expressions. Interpolated expressions beyond this // limit must be ignored. OSLogTestSuite.test("messages with too many arguments") { let h = Logger() h.log( level: .error, """ \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \ \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \ \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \ \(1) \(1) \(1) \(1) \(1) \(48) \(49) """) // The number 49 should not appear in the logged message. } OSLogTestSuite.test("escape characters") { let h = Logger() h.log("\"Imagination is more important than knowledge\" - Einstein") h.log("\'Imagination is more important than knowledge\' - Einstein") h.log("Imagination is more important than knowledge \n - Einstein") h.log("Imagination is more important than knowledge - \\Einstein") h.log("The log message will be truncated here.\0 You won't see this") } OSLogTestSuite.test("unicode characters") { let h = Logger() h.log("dollar sign: \u{24}") h.log("black heart: \u{2665}") h.log("sparkling heart: \u{1F496}") } OSLogTestSuite.test("raw strings") { let h = Logger() let x = 10 h.log(#"There is no \(interpolated) value in this string"#) h.log(#"This is not escaped \n"#) h.log(##"'\b' is a printf escape character but not in Swift"##) h.log(##"The interpolated value is \##(x)"##) h.log(#"Sparkling heart should appear in the next line. \#n \#u{1F496}"#) } } // The following tests check the correctness of the format string and the // byte buffer constructed by the APIs from a string interpolation. // These tests do not perform logging and do not require the os_log ABIs to // be available. internal var InterpolationTestSuite = TestSuite("OSLogInterpolationTest") internal let intPrefix = Int.bitWidth == CLongLong.bitWidth ? "ll" : "" internal let bitsPerByte = 8 /// A struct that exposes methods for checking whether a given byte buffer /// conforms to the format expected by the os_log ABI. This struct acts as /// a specification of the byte buffer format. internal struct OSLogBufferChecker { internal let buffer: UnsafeBufferPointer<UInt8> internal init(_ byteBuffer: UnsafeBufferPointer<UInt8>) { buffer = byteBuffer } /// Bit mask for setting bits in the peamble. The bits denoted by the bit /// mask indicate whether there is an argument that is private, and whether /// there is an argument that is non-scalar: String, NSObject or Pointer. internal enum PreambleBitMask: UInt8 { case privateBitMask = 0x1 case nonScalarBitMask = 0x2 } /// Check the summary bytes of the byte buffer. /// - Parameters: /// - argumentCount: number of arguments expected to be in the buffer. /// - hasPrivate: true iff there exists a private argument /// - hasNonScalar: true iff there exists a non-scalar argument internal func checkSummaryBytes( argumentCount: UInt8, hasPrivate: Bool, hasNonScalar: Bool ) { let preamble = buffer[0] let privateBit = preamble & PreambleBitMask.privateBitMask.rawValue expectEqual(hasPrivate, privateBit != 0) let nonScalarBit = preamble & PreambleBitMask.nonScalarBitMask.rawValue expectEqual(hasNonScalar, nonScalarBit != 0) expectEqual(argumentCount, buffer[1]) } /// The possible values for the argument flag as defined by the os_log ABI. /// This occupies four least significant bits of the first byte of the /// argument header. Two least significant bits are used to indicate privacy /// and the other two bits are reserved. internal enum ArgumentFlag: UInt8 { case privateFlag = 0x1 case publicFlag = 0x2 } /// The possible values for the argument type as defined by the os_log ABI. /// This occupies four most significant bits of the first byte of the /// argument header. internal enum ArgumentType: UInt8 { case scalar = 0, count, string, pointer, object // TODO: include wide string and errno here if needed. } /// Check the encoding of an argument in the byte buffer starting from the /// `startIndex`. /// - precondition: `T` must be a type that is accepted by os_log ABI. private func checkArgument<T>( startIndex: Int, size: UInt8, flag: ArgumentFlag, type: ArgumentType, expectedData: T ) { let argumentHeader = buffer[startIndex] expectEqual((type.rawValue << 4) | flag.rawValue, argumentHeader) expectEqual(size, buffer[startIndex + 1]) // Check every byte of the payload. withUnsafeBytes(of: expectedData) { expectedBytes in for i in 0..<Int(size) { // Argument data starts after the two header bytes. expectEqual( expectedBytes[i], buffer[startIndex + 2 + i], "mismatch at byte number \(i) of the expected value \(expectedData)") } } } /// Check whether the bytes starting from `startIndex` contain the encoding /// for an Int. internal func checkInt( startIndex: Int, flag: ArgumentFlag, expectedInt: Int ) { checkArgument( startIndex: startIndex, size: UInt8(MemoryLayout<Int>.size), flag: flag, type: .scalar, expectedData: expectedInt) } /// Check the given assertions on the arguments stored in the byte buffer. /// - Parameters: /// - assertions: one assertion for each argument stored in the byte buffer. internal func checkArguments(_ assertions: [(Int) -> Void]) { var currentArgumentIndex = 2 for assertion in assertions { expectTrue(currentArgumentIndex < buffer.count) assertion(currentArgumentIndex) // Advance the index to the next argument by adding the size of the // current argument and the two bytes of headers. currentArgumentIndex += 2 + Int(buffer[currentArgumentIndex + 1]) } } /// Check a sequence of assertions on the arguments stored in the byte buffer. internal func checkArguments(_ assertions: (Int) -> Void ...) { checkArguments(assertions) } } InterpolationTestSuite.test("integer literal") { _checkFormatStringAndBuffer( "An integer literal \(10)", with: { (formatString, buffer) in expectEqual( "An integer literal %{public}\(intPrefix)d", formatString) let bufferChecker = OSLogBufferChecker(buffer) bufferChecker.checkSummaryBytes( argumentCount: 1, hasPrivate: false, hasNonScalar: false) bufferChecker.checkArguments({ bufferChecker.checkInt(startIndex: $0, flag: .publicFlag, expectedInt: 10) }) }) } InterpolationTestSuite.test("integer with formatting") { _checkFormatStringAndBuffer( "Minimum integer value: \(Int.min, format: .hex)", with: { (formatString, buffer) in expectEqual( "Minimum integer value: %{public}\(intPrefix)x", formatString) let bufferChecker = OSLogBufferChecker(buffer) bufferChecker.checkSummaryBytes( argumentCount: 1, hasPrivate: false, hasNonScalar: false) bufferChecker.checkArguments({ bufferChecker.checkInt( startIndex: $0, flag: .publicFlag, expectedInt: Int.min) }) }) } InterpolationTestSuite.test("integer with privacy and formatting") { let addr = 0x7afebabe _checkFormatStringAndBuffer( "Access to invalid address: \(addr, format: .hex, privacy: .private)", with: { (formatString, buffer) in expectEqual( "Access to invalid address: %{private}\(intPrefix)x", formatString) let bufferChecker = OSLogBufferChecker(buffer) bufferChecker.checkSummaryBytes( argumentCount: 1, hasPrivate: true, hasNonScalar: false) bufferChecker.checkArguments({ bufferChecker.checkInt( startIndex: $0, flag: .privateFlag, expectedInt: addr) }) }) } InterpolationTestSuite.test("integer with privacy and formatting") { let addr = 0x7afebabe _checkFormatStringAndBuffer( "Access to invalid address: \(addr, format: .hex, privacy: .private)", with: { (formatString, buffer) in expectEqual( "Access to invalid address: %{private}\(intPrefix)x", formatString) let bufferChecker = OSLogBufferChecker(buffer) bufferChecker.checkSummaryBytes( argumentCount: 1, hasPrivate: true, hasNonScalar: false) bufferChecker.checkArguments({ bufferChecker.checkInt( startIndex: $0, flag: .privateFlag, expectedInt: addr) }) }) } InterpolationTestSuite.test("test multiple arguments") { let filePerms = 0o777 let pid = 122225 let privateID = 0x79abcdef _checkFormatStringAndBuffer( """ Access prevented: process \(pid) initiated by \ user: \(privateID, privacy: .private) attempted resetting \ permissions to \(filePerms, format: .octal) """, with: { (formatString, buffer) in expectEqual( """ Access prevented: process %{public}\(intPrefix)d initiated by \ user: %{private}\(intPrefix)d attempted resetting permissions \ to %{public}\(intPrefix)o """, formatString) let bufferChecker = OSLogBufferChecker(buffer) bufferChecker.checkSummaryBytes( argumentCount: 3, hasPrivate: true, hasNonScalar: false) bufferChecker.checkArguments( { bufferChecker.checkInt( startIndex: $0, flag: .publicFlag, expectedInt: pid) }, { bufferChecker.checkInt( startIndex: $0, flag: .privateFlag, expectedInt: privateID) }, { bufferChecker.checkInt( startIndex: $0, flag: .publicFlag, expectedInt: filePerms) }) }) } InterpolationTestSuite.test("interpolation of too many arguments") { // The following string interpolation has 49 interpolated values. Only 48 // of these must be present in the generated format string and byte buffer. _checkFormatStringAndBuffer( """ \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \ \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \ \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \(1) \ \(1) \(1) \(1) \(1) \(1) \(1) \(1) """, with: { (formatString, buffer) in expectEqual( String( repeating: "%{public}\(intPrefix)d ", count: Int(maxOSLogArgumentCount)), formatString) let bufferChecker = OSLogBufferChecker(buffer) bufferChecker.checkSummaryBytes( argumentCount: maxOSLogArgumentCount, hasPrivate: false, hasNonScalar: false) bufferChecker.checkArguments( Array( repeating: { bufferChecker.checkInt( startIndex: $0, flag: .publicFlag, expectedInt: 1) }, count: Int(maxOSLogArgumentCount)) ) }) } InterpolationTestSuite.test("string interpolations with percents") { _checkFormatStringAndBuffer( "a = (c % d)%%", with: { (formatString, buffer) in expectEqual("a = (c %% d)%%%%", formatString) let bufferChecker = OSLogBufferChecker(buffer) bufferChecker.checkSummaryBytes( argumentCount: 0, hasPrivate: false, hasNonScalar: false) }) }
c8dfcedc3a9a97f82d491f454ed0c9b7
30.83683
103
0.638307
false
true
false
false
c1moore/deckstravaganza
refs/heads/master
Deckstravaganza/MasterViewController.swift
mit
1
// // MasterViewController.swift // Deckstravaganza // // Created by Stephen on 9/28/15. // Copyright © 2015 University of Florida. All rights reserved. // import UIKit protocol MenuSelectionDelegate: class { func menuSelected(newMenu: Menu) } class MasterViewController: UITableViewController { var delegate: MenuSelectionDelegate? var menus: [[Menu]] = [ [Menu(name: "Continue", description: "Continue Playing Last Game")], [ Menu(name: "New Game", description: "New Game", clickable: false), Menu(name: "\tSolitaire", description: "New Solitaire Game", level: 2, viewGameOptions: true, gameType: .Solitaire), Menu(name: "\tRummy", description: "New Rummy Game", level: 2, viewGameOptions: true, gameType: .Rummy) ] ]; 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() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return menus.count; } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let menuItems = menus[section].count; if(menus[section].first!.clickable) { return menuItems; } else { return menuItems - 1; } } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if(!menus[section].first!.clickable) { return menus[section].first!.name; } return nil; } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) // Configure the cell... if(!menus[indexPath.section].first!.clickable) { let menuItem = self.menus[indexPath.section][indexPath.row + 1]; cell.textLabel?.text = menuItem.name; return cell; } let menuItem = self.menus[indexPath.section][indexPath.row]; cell.textLabel?.text = menuItem.name; return cell } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let selectedMenu: Menu; if(self.menus[indexPath.section].first!.clickable) { selectedMenu = self.menus[indexPath.section][indexPath.row]; } else { selectedMenu = self.menus[indexPath.section][indexPath.row + 1]; } if let detailViewController = self.delegate as? DetailViewController { self.delegate?.menuSelected(selectedMenu); detailViewController.tearDownMenuUI(); detailViewController.setupMenuUI(); splitViewController?.showDetailViewController(detailViewController, sender: nil) } } /* // Override to support conditional editing of the table view. 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 to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
00c65164e3a31c363ea00f6196bb9cf1
34.119205
157
0.650952
false
false
false
false
Esri/arcgis-runtime-samples-ios
refs/heads/main
arcgis-ios-sdk-samples/Route and directions/Find service area interactive/FindServiceAreaInteractiveViewController.swift
apache-2.0
1
// // Copyright 2017 Esri. // // 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 ArcGIS class FindServiceAreaInteractiveViewController: UIViewController, AGSGeoViewTouchDelegate, ServiceAreaSettingsViewControllerDelegate, UIAdaptivePresentationControllerDelegate { @IBOutlet private var mapView: AGSMapView! @IBOutlet private var segmentedControl: UISegmentedControl! @IBOutlet private var serviceAreaBBI: UIBarButtonItem! private var facilitiesGraphicsOverlay = AGSGraphicsOverlay() private var barriersGraphicsOverlay = AGSGraphicsOverlay() private var serviceAreaGraphicsOverlay = AGSGraphicsOverlay() private var barrierGraphic: AGSGraphic! private var serviceAreaTask: AGSServiceAreaTask! private var serviceAreaParameters: AGSServiceAreaParameters! var firstTimeBreak: Int = 3 var secondTimeBreak: Int = 8 override func viewDidLoad() { super.viewDidLoad() // add the source code button item to the right of navigation bar (self.navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = ["FindServiceAreaInteractiveViewController", "ServiceAreaSettingsViewController"] // initialize map with basemap let map = AGSMap(basemapStyle: .arcGISTerrain) // center for initial viewpoint let center = AGSPoint(x: -13041154, y: 3858170, spatialReference: .webMercator()) // assign map to map view self.mapView.map = map self.mapView.setViewpoint(AGSViewpoint(center: center, scale: 1e5)) // assign touch delegate as self to know when use interacted with the map view // Will be adding facilities and barriers on interaction self.mapView.touchDelegate = self // initialize service area task self.serviceAreaTask = AGSServiceAreaTask(url: URL(string: "https://sampleserver6.arcgisonline.com/arcgis/rest/services/NetworkAnalysis/SanDiego/NAServer/ServiceArea")!) // get default parameters for the task self.getDefaultParameters() // facility picture marker symbol let facilitySymbol = AGSPictureMarkerSymbol(image: UIImage(named: "Facility")!) // offset symbol in Y to align image properly facilitySymbol.offsetY = 21 // assign renderer on facilities graphics overlay using the picture marker symbol self.facilitiesGraphicsOverlay.renderer = AGSSimpleRenderer(symbol: facilitySymbol) // barrier symbol let barrierSymbol = AGSSimpleFillSymbol(style: .diagonalCross, color: .red, outline: nil) // set symbol on barrier graphics overlay using renderer self.barriersGraphicsOverlay.renderer = AGSSimpleRenderer(symbol: barrierSymbol) // add graphicOverlays to the map. One for facilities, barriers and service areas self.mapView.graphicsOverlays.addObjects(from: [self.serviceAreaGraphicsOverlay, self.barriersGraphicsOverlay, self.facilitiesGraphicsOverlay]) } private func getDefaultParameters() { // get default parameters self.serviceAreaTask.defaultServiceAreaParameters { [weak self] (parameters: AGSServiceAreaParameters?, error: Error?) in guard error == nil else { self?.presentAlert(message: "Error getting default parameters:: \(error!.localizedDescription)") return } // keep a reference to the default parameters to be used later self?.serviceAreaParameters = parameters // enable service area bar button item self?.serviceAreaBBI.isEnabled = true } } private func serviceAreaSymbol(for index: Int) -> AGSSymbol { // fill symbol for service area var fillSymbol: AGSSimpleFillSymbol if index == 0 { let lineSymbol = AGSSimpleLineSymbol(style: .solid, color: UIColor(red: 0.4, green: 0.4, blue: 0, alpha: 0.3), width: 2) fillSymbol = AGSSimpleFillSymbol(style: .solid, color: UIColor(red: 0.8, green: 0.8, blue: 0, alpha: 0.3), outline: lineSymbol) } else { let lineSymbol = AGSSimpleLineSymbol(style: .solid, color: UIColor(red: 0, green: 0.4, blue: 0, alpha: 0.3), width: 2) fillSymbol = AGSSimpleFillSymbol(style: .solid, color: UIColor(red: 0, green: 0.8, blue: 0, alpha: 0.3), outline: lineSymbol) } return fillSymbol } // MARK: - Actions @IBAction private func serviceArea() { // remove previously added service areas serviceAreaGraphicsOverlay.graphics.removeAllObjects() let facilitiesGraphics = facilitiesGraphicsOverlay.graphics as! [AGSGraphic] // check if at least a single facility is added guard !facilitiesGraphics.isEmpty else { presentAlert(message: "At least one facility is required") return } // add facilities var facilities = [AGSServiceAreaFacility]() // for each graphic in facilities graphicsOverlay add a facility to the parameters for graphic in facilitiesGraphics { let point = graphic.geometry as! AGSPoint let facility = AGSServiceAreaFacility(point: point) facilities.append(facility) } self.serviceAreaParameters.setFacilities(facilities) // add barriers var barriers = [AGSPolygonBarrier]() // for each graphic in barrier graphicsOverlay add a barrier to the parameters for graphic in barriersGraphicsOverlay.graphics as! [AGSGraphic] { let polygon = graphic.geometry as! AGSPolygon let barrier = AGSPolygonBarrier(polygon: polygon) barriers.append(barrier) } serviceAreaParameters.setPolygonBarriers(barriers) // set time breaks serviceAreaParameters.defaultImpedanceCutoffs = [NSNumber(value: firstTimeBreak), NSNumber(value: secondTimeBreak)] serviceAreaParameters.geometryAtOverlap = .dissolve // show progress hud UIApplication.shared.showProgressHUD(message: "Loading") // solve for service area serviceAreaTask.solveServiceArea(with: serviceAreaParameters) { [weak self] (result: AGSServiceAreaResult?, error: Error?) in // dismiss progress hud UIApplication.shared.hideProgressHUD() guard let self = self else { return } if let error = error { self.presentAlert(message: "Error solving service area: \(error.localizedDescription)") } else { // add resulting polygons as graphics to the overlay // since we are using `geometryAtOVerlap` as `dissolve` and the cutoff values // are the same across facilities, we only need to draw the resultPolygons at // facility index 0. It will contain either merged or multipart polygons if let polygons = result?.resultPolygons(atFacilityIndex: 0) { for index in polygons.indices { let polygon = polygons[index] let fillSymbol = self.serviceAreaSymbol(for: index) let graphic = AGSGraphic(geometry: polygon.geometry, symbol: fillSymbol, attributes: nil) self.serviceAreaGraphicsOverlay.graphics.add(graphic) } } } } } @IBAction private func clearAction() { // remove all existing graphics in service area and facilities graphics overlays self.serviceAreaGraphicsOverlay.graphics.removeAllObjects() self.facilitiesGraphicsOverlay.graphics.removeAllObjects() self.barriersGraphicsOverlay.graphics.removeAllObjects() } // MARK: - AGSGeoViewTouchDelegate func geoView(_ geoView: AGSGeoView, didTapAtScreenPoint screenPoint: CGPoint, mapPoint: AGSPoint) { if segmentedControl.selectedSegmentIndex == 0 { // facilities selected let graphic = AGSGraphic(geometry: mapPoint, symbol: nil, attributes: nil) self.facilitiesGraphicsOverlay.graphics.add(graphic) } else { // barriers selected let bufferedGeometry = AGSGeometryEngine.bufferGeometry(mapPoint, byDistance: 500) let graphic = AGSGraphic(geometry: bufferedGeometry, symbol: nil, attributes: nil) self.barriersGraphicsOverlay.graphics.add(graphic) } } // MARK: - Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "ServiceAreaSettingsSegue" { let controller = segue.destination as! ServiceAreaSettingsViewController controller.presentationController?.delegate = self controller.preferredContentSize = CGSize(width: 300, height: 200) controller.delegate = self controller.firstTimeBreak = self.firstTimeBreak controller.secondTimeBreak = self.secondTimeBreak } } // MARK: - ServiceAreaSettingsViewControllerDelegate func serviceAreaSettingsViewController(_ serviceAreaSettingsViewController: ServiceAreaSettingsViewController, didUpdateFirstTimeBreak timeBreak: Int) { self.firstTimeBreak = timeBreak } func serviceAreaSettingsViewController(_ serviceAreaSettingsViewController: ServiceAreaSettingsViewController, didUpdateSecondTimeBreak timeBreak: Int) { self.secondTimeBreak = timeBreak } // MARK: - UIAdaptivePresentationControllerDelegate func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle { return .none } }
3dcf973a09d4eee29c8acebbc35ab5b4
44.577586
177
0.665406
false
false
false
false
bradhilton/HttpRequest
refs/heads/master
HttpRequest/HttpTask.swift
mit
1
// // HttpRequestDelegate.swift // HttpRequest // // Created by Bradley Hilton on 9/1/15. // Copyright © 2015 Skyvive. All rights reserved. // import Foundation import Convertible class HttpStandardTask<T : DataInitializable> : NSObject, NSURLSessionDataDelegate { let request: HttpRequest<T> let data = NSMutableData() let startDate = NSDate() var completedSendingData = false var completedRecievingData = false let queue: NSOperationQueue = { let queue = NSOperationQueue() queue.underlyingQueue = dispatch_queue_create(nil, nil) return queue }() var cachePolicy: NSURLRequestCachePolicy { return request.configuration.requestCachePolicy } var loggingEnabled: Bool { return request.loggingEnabled } var errorReportingEnabled: Bool { return true } var progressTrackingEnabled: Bool { return true } init(request: HttpRequest<T>) { self.request = request super.init() do { let urlRequest = try request.request(cachePolicy) if loggingEnabled { HttpLogging.logRequest(urlRequest) } NSURLSession(configuration: request.configuration, delegate: self, delegateQueue: queue).dataTaskWithRequest(urlRequest).resume() } catch where errorReportingEnabled { returnError(error) } catch {} } func URLSession(session: NSURLSession, task: NSURLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) { returnProgress(task) } func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) { completedSendingData = true returnProgress(dataTask) self.data.appendData(data) } func returnProgress(dataTask: NSURLSessionTask) { if progressTrackingEnabled { let sentProgress = progress(dataTask.countOfBytesSent, dataTask.countOfBytesExpectedToSend, completedSendingData) let recievedProgress = progress(dataTask.countOfBytesReceived, dataTask.countOfBytesExpectedToReceive, completedRecievingData) request.queue.addOperationWithBlock { self.request.progress?(sentProgress, recievedProgress) } } } func progress(count: Int64, _ expected: Int64, _ completed: Bool) -> Double { if expected > 0 { return Double(count)/Double(expected) } else { return completed ? 1 : 0 } } func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) { completedRecievingData = true returnProgress(task) do { returnResponse(try getHttpResponse(task, error: error)) } catch let error where errorReportingEnabled { returnError(error) } catch {} session.finishTasksAndInvalidate() } func getHttpResponse(task: NSURLSessionTask, error: NSError?) throws -> HttpResponse<T> { if let error = error { throw error } let responseTime = NSDate().timeIntervalSinceDate(startDate) guard let response = task.response as? NSHTTPURLResponse, let request = task.originalRequest else { throw HttpError.UnknownError } if loggingEnabled { HttpLogging.logResponse(response, request: request, responseTime: responseTime, data: data) } if !(200..<300).contains(response.statusCode) { throw HttpError.HttpError(response: response, data: data) } return HttpResponse(body: try T.initializeWithData(data, options: self.request.convertibleOptions), responseTime: responseTime, request: request, urlResponse: response) } func returnResponse(response: HttpResponse<T>) { request.queue.addOperationWithBlock { self.request.success?(response) self.request.completion?(response, nil) } } func returnError(error: ErrorType) { request.queue.addOperationWithBlock { self.request.failure?(error) self.request.completion?(nil, error) } } } class HttpCacheTask<T : DataInitializable> : HttpStandardTask<T> { override init(request: HttpRequest<T>) { super.init(request: request) } override var cachePolicy: NSURLRequestCachePolicy { return NSURLRequestCachePolicy.ReturnCacheDataDontLoad } override var loggingEnabled: Bool { return false } override var errorReportingEnabled: Bool { return request.success == nil && request.completion == nil } override var progressTrackingEnabled: Bool { return false } override func returnResponse(response: HttpResponse<T>) { request.queue.addOperationWithBlock { self.request.cache?(response) } } } class HttpNetworkTask<T : DataInitializable> : HttpStandardTask<T> { override init(request: HttpRequest<T>) { super.init(request: request) } override var cachePolicy: NSURLRequestCachePolicy { return NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData } }
0052a36f44a2456fa4671ac56ad89227
32.915584
176
0.666284
false
false
false
false
tiasn/TXLive
refs/heads/master
TXLive/TXLive/Classes/Main/View/PageTitleView.swift
mit
1
// // PageTitleView.swift // TXLive // // Created by LTX on 2016/12/11. // Copyright © 2016年 LTX. All rights reserved. // import UIKit //代理的协议 protocol pageTitleViewDelegate : class { func pageTitleView(titleView : PageTitleView, selectedIndex index : Int) } fileprivate let kScrollLineH : CGFloat = 2 fileprivate let kNormalColor : (CGFloat, CGFloat, CGFloat) = (85, 85,85) fileprivate let kSelectorColor : (CGFloat, CGFloat, CGFloat) = (255, 128, 0) class PageTitleView: UIView { //自定义属性:标题数组 fileprivate var titles : [String] fileprivate var currentIndex = 0; weak var delegate : pageTitleViewDelegate? // 懒加载属性 fileprivate lazy var titleLables : [UILabel] = [UILabel]() // 懒加载属性 fileprivate lazy var scrollView : UIScrollView = { let scrollView = UIScrollView() scrollView.showsHorizontalScrollIndicator = false scrollView.scrollsToTop = false scrollView.bounces = false return scrollView }() // 懒加载属性 fileprivate lazy var scrollLine : UIView = { let scrollLine = UIView() scrollLine.backgroundColor = UIColor.orange return scrollLine }() //自定义构造方法 init(frame: CGRect, titles : [String]) { self.titles = titles super.init(frame: frame) //设置UI界面 setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK:- 设置UI界面 extension PageTitleView{ fileprivate func setupUI() { // 添加ScrollView addSubview(scrollView) scrollView.frame = bounds //添加title Lable setupTitleLables() //添加TitleView底部滚动线 setupBottomLineAndScrollLine() } fileprivate func setupTitleLables() { //labe的值 let lableW : CGFloat = frame.width / CGFloat(titles.count) let lableH : CGFloat = frame.height - kScrollLineH let lableY : CGFloat = 0 for (index, title) in titles.enumerated() { // 创建lable let lable = UILabel() //设置lable属性 lable.text = title lable.tag = index lable.font = UIFont.systemFont(ofSize: 15) lable.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2) lable.textAlignment = .center //设置labe的Frame let labelX : CGFloat = lableW * CGFloat(index) lable.frame = CGRect(x: labelX, y: lableY, width: lableW, height: lableH) // 添加点击事件 lable.isUserInteractionEnabled = true let tapGes = UITapGestureRecognizer(target: self, action: #selector(self.titleLableClick(_ :))) lable.addGestureRecognizer(tapGes) //添加lable到ScrollView scrollView.addSubview(lable) //添加到数组 titleLables.append(lable) } } fileprivate func setupBottomLineAndScrollLine() { // 添加底线 let bottomLine = UIView() bottomLine.backgroundColor = UIColor.lightGray let lineH : CGFloat = 0.5 bottomLine.frame = CGRect(x: 0, y: frame.height - lineH, width: frame.width, height: lineH) addSubview(bottomLine) //添加scrollLine guard let firstLable = titleLables.first else { return } firstLable.textColor = UIColor(r: kSelectorColor.0, g: kSelectorColor.1, b: kSelectorColor.2) scrollView.addSubview(scrollLine) scrollLine.frame = CGRect(x: firstLable.frame.origin.x, y: frame.height - kScrollLineH, width: firstLable.frame.size.width, height: kScrollLineH) } } // MARK:- 监听事件 extension PageTitleView{ @objc fileprivate func titleLableClick(_ tapGes : UIGestureRecognizer){ //点击的lable guard let currentLable = tapGes.view as? UILabel else { return } if currentIndex == currentLable.tag { return } // 旧的lable let oldLable = titleLables[currentIndex] // 修改颜色 currentLable.textColor = UIColor(r: kSelectorColor.0, g: kSelectorColor.1, b: kSelectorColor.2) oldLable.textColor = UIColor(r: kNormalColor.0, g: kNormalColor.1, b: kNormalColor.2) let scrollLineX = CGFloat(currentLable.tag) * scrollLine.frame.width UIView .animate(withDuration: 0.25) { self.scrollLine.frame.origin.x = scrollLineX } //保存最新的lable下标 currentIndex = currentLable.tag //通知代理 delegate?.pageTitleView(titleView: self, selectedIndex: currentIndex) } } // MARK:- 对外暴露的方法 extension PageTitleView { func setTitleWithProgress(progress : CGFloat, sourceIndex : Int, targetIndex : Int) { //取出lable let sourceLable = titleLables[sourceIndex] let targetLable = titleLables[targetIndex] let moveTotal = targetLable.frame.origin.x - sourceLable.frame.origin.x let moveX = moveTotal * progress //指示线联动 scrollLine.frame.origin.x = sourceLable.frame.origin.x + moveX //颜色渐变 //取出渐变范围 let colorDelta = (kSelectorColor.0 - kNormalColor.0, kSelectorColor.1 - kNormalColor.1, kSelectorColor.2 - kNormalColor.2) //sourceLabel变色 sourceLable.textColor = UIColor(r: kSelectorColor.0 - colorDelta.0 * progress, g: kSelectorColor.1 - colorDelta.1 * progress, b: kSelectorColor.2 - colorDelta.2 * progress) //targetLable变色 targetLable.textColor = UIColor(r: kNormalColor.0 + colorDelta.0 * progress, g: kNormalColor.1 + colorDelta.1*progress, b: kNormalColor.2 + colorDelta.2*progress) //保存最新的index currentIndex = targetIndex } }
fd8925db8ec5017929cc35e4a80614f1
26.626126
180
0.587641
false
false
false
false
zmeyc/GRDB.swift
refs/heads/master
Tests/GRDBTests/Record+QueryInterfaceRequestTests.swift
mit
1
import XCTest #if USING_SQLCIPHER import GRDBCipher #elseif USING_CUSTOMSQLITE import GRDBCustomSQLite #else import GRDB #endif private class Reader : Record { var id: Int64? let name: String let age: Int? init(id: Int64?, name: String, age: Int?) { self.id = id self.name = name self.age = age super.init() } required init(row: Row){ self.id = row.value(named: "id") self.name = row.value(named: "name") self.age = row.value(named: "age") super.init(row: row) } override class var databaseTableName: String { return "readers" } override var persistentDictionary: [String: DatabaseValueConvertible?] { return ["id": id, "name": name, "age": age] } override func didInsert(with rowID: Int64, for column: String?) { id = rowID } } class RecordQueryInterfaceRequestTests: GRDBTestCase { override func setup(_ dbWriter: DatabaseWriter) throws { var migrator = DatabaseMigrator() migrator.registerMigration("createReaders") { db in try db.execute( "CREATE TABLE readers (" + "id INTEGER PRIMARY KEY, " + "name TEXT NOT NULL, " + "age INT" + ")") } try migrator.migrate(dbWriter) } // MARK: - Fetch Record func testFetch() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let arthur = Reader(id: nil, name: "Arthur", age: 42) try arthur.insert(db) let barbara = Reader(id: nil, name: "Barbara", age: 36) try barbara.insert(db) let request = Reader.all() do { let readers = try request.fetchAll(db) XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"readers\"") XCTAssertEqual(readers.count, 2) XCTAssertEqual(readers[0].id!, arthur.id!) XCTAssertEqual(readers[0].name, arthur.name) XCTAssertEqual(readers[0].age, arthur.age) XCTAssertEqual(readers[1].id!, barbara.id!) XCTAssertEqual(readers[1].name, barbara.name) XCTAssertEqual(readers[1].age, barbara.age) } do { let reader = try request.fetchOne(db)! XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"readers\"") XCTAssertEqual(reader.id!, arthur.id!) XCTAssertEqual(reader.name, arthur.name) XCTAssertEqual(reader.age, arthur.age) } do { let cursor = try request.fetchCursor(db) let names = cursor.map { $0.name } XCTAssertEqual(lastSQLQuery, "SELECT * FROM \"readers\"") XCTAssertEqual(try names.next()!, arthur.name) XCTAssertEqual(try names.next()!, barbara.name) XCTAssertTrue(try names.next() == nil) } } } }
4dbd81ef4209f187ef8d676d6169b640
30.356436
76
0.529839
false
false
false
false
Ramshandilya/Swift-Notes
refs/heads/master
Swift-Notes.playground/Pages/23. Generics.xcplaygroundpage/Contents.swift
mit
1
//: # Swift Foundation //: ---- //: ## Generics //: *Generic code* enables you to write flexible, reusable functions and types that can work with any type. //: ### The Problem /* The below example is commented as it doesn't work. http://stackoverflow.com/questions/31697093/cannot-pass-any-array-type-to-a-function-which-takes-any-as-parameter let names = ["Joffrey", "Cersei", "Mountain", "Hound"] let ranks = [1, 2, 3, 4, 5] let weights = [141.2, 166.0, 173.8, 220.3] //Let's create funcitons to print each element for the arrays func printNames(items: [String]){ for item in items { print(item) } } func printRanks(items: [Int]){ for item in items { print(item) } } func printWeights(items: [Double]){ for item in items { print(item) } } //: Clearly the there is code duplication. The body of the three functions are identical. We can get away by replacing the type with `Any` func printItems(items: [Any]){ for item in items { print(item) } } printItems(names) printItems(ranks) */ func swapIntegers(inout a: Int, inout _ b: Int){ let temp = a a = b b = temp } var foo = 10 var bar = 15 swapIntegers(&foo, &bar) foo bar // Let's create more such functions to swap Doubles, Strings etc. func swapStrings(inout a: String, inout _ b: String){ let temp = a a = b b = temp } func swapDoubles(inout a: Double, inout _ b: Double){ let temp = a a = b b = temp } //: Clearly the there is code duplication. The body of the three functions are identical. The only difference is the type of the parameters. func swapTwoItems(inout a: Any, inout _ b: Any) { let temporaryA = a a = b b = temporaryA } //: Using `Any` might seem to work but it'll fail when the parameters are of different types. var someInt = 3 var someString = "Foo" //swapTwoItems(&someInt, b: &someString) //: By using `Any` we've lost type safety. //: ### Enter Generics. //: Generic funcitons can work with any type. func swapTwoValues<T>(inout a: T, inout _ b: T) { let temp = a a = b b = temp } // Let's test. var string1 = "Valar" var string2 = "Morghulis" swapTwoValues(&string1, &string2) string1 string2 /*---------------------------------------*/ var integer1 = 123 var integer2 = 456 swapTwoValues(&integer1, &integer2) integer1 integer2 /*---------------------------------------*/ // And this is not possible. //swapTwoValues(&string1, &integer1) /*---------------------------------------*/ //: ## 😋👍 //: Instead of an actual type (`Int`, `String`, `Double`), we are using a *placeholder* type (called T, in this case). It says the type of `a` and `b` have to be of type `T`, whatever `T` represents. Also, we've put the `T` in angle brackets (`<T>`) after the function name so that swift doesn't look for an actual type called `T`. //: ### Type Parameters //: The placeholder type `T` is a example of a ***type parameter***. //: Generics allow us to write flexible functions that accept any type as a parameter. In fact, we can specify more than one generic type when defining functions. func someFunction<T, U>(a: T, _ b: U) -> (T, U) { return (a, b) } let stringIntTuple = someFunction("One", 1) let intDoubleTuple = someFunction(2, 3.14) //: Swift allows us to use any valid identfier as the type parameter name. But it is conventional to use single-character name `T`. //: ### Generic Types //: Swift also lets us define ***generic types***. Generic types are custom classes, enumerations and structs that work with any type, similar to how Swift collections like Array and Dictionary do. struct GenericStack<T> { var items = [T]() mutating func push(item: T) { items.append(item) } mutating func pop() { items.removeLast() } } var pizzaStack = GenericStack<String>() pizzaStack.push("Regular") pizzaStack.push("Cheeseburst") pizzaStack.push("Double Cheeseburst") pizzaStack.push("Large") pizzaStack.pop() pizzaStack.items /*: struct Dictionary<Key, Value> { //implementation } */ //: ### Extending Generic Type extension GenericStack { var top: T? { return items.isEmpty ? nil : items[items.count - 1] } } let top = pizzaStack.top //Optional String //: ### Type Contraints //Syntax /*: func someFuntion<T: SomeClass, U: SomeProtocol>(a: T, b: U) { //implementation } */ func findIndex<T: Equatable>(array: [T], _ valueToFind: T) -> Int? { for (index, value) in array.enumerate() { if value == valueToFind { return index } } return nil } //: The above function will take any type provided the type conforms to `Equatable` protocol. This is because the line `if value == valueToFind` may not work for all swift types. //: ### Associated Types //: Associated types gives a placeholder name to a type that is used as part of protocol. The actual type to use for that associated type is not specified until the protocol is adopted. protocol Printer { typealias ItemType func returnValue() -> ItemType } struct IntStruct: Printer { var value: Int func returnValue() -> Int { return value } } struct StringStruct: Printer { var value: String func returnValue() -> String { return value } } struct GenericStruct<T>: Printer { var value: T func returnValue() -> T { return value } } //: ### Where Clause //: Where clause can be used to define requirements for associated types. func someFunction<P1: Printer, P2: Printer where P1.ItemType == P2.ItemType, P1.ItemType: Equatable> (firstPrinter: P1, _ secondPrinter: P2) { firstPrinter.returnValue() secondPrinter.returnValue() } /*: * P1 must conform to `Printer` protocol. * P2 must conform to `Printer` protocol. * ItemType of P1 must be saem as the ItemType for P2 * The ItemType for P1 should be same as the ItemType for P2. * The ItemType for P1 must conform to Equatable protocol. */ /*: These requirements mean: * `firstPrinter` is a printer of type P1. * `secondPrinter` is a printer of type P2. * `firstPrinter` and `secondPrinter` contain the same type of items. * The items in `firstPrinter` can be checked with the equal operator (`==`). */ let intPrinter = IntStruct(value: 10) let genericIntPrinter = GenericStruct<Int>(value: 12) someFunction(intPrinter, genericIntPrinter) // Works perfectly let genericStringPrinter = GenericStruct<String>(value: "Hi") someFunction(genericIntPrinter, genericStringPrinter) //Doesn't work let stringPrinter = StringStruct(value: "World") someFunction(stringPrinter, genericStringPrinter) //Works perfectly //: ---- //: [Next](@next)
84cf6a5636d1ae9a111eabbd71aed4c9
22.935943
331
0.659084
false
false
false
false
AnRanScheme/magiGlobe
refs/heads/master
magi/magiGlobe/magiGlobe/Classes/Tool/Extension/Foundation/Bundle/Bundle+AppIcon.swift
mit
1
// // NSBundle+AppIcon.swift // swift-magic // // Created by 安然 on 17/2/15. // Copyright © 2017年 安然. All rights reserved. // import Foundation import UIKit public extension Bundle { /// 获取多个app icon名字数组 /// /// - Returns: 多个app icon名字的可选数组 public class func m_appIconsPath() -> [String]?{ if let infoDict = Bundle.main.infoDictionary,let bundleIcons = infoDict["CFBundleIcons"] as? [String : Any], let bundlePrimaryIcon = bundleIcons["CFBundlePrimaryIcon"] as? [String : Any], let bundleIconFiles = bundlePrimaryIcon["CFBundleIconFiles"] as? [String]{ return bundleIconFiles } return nil } /// 获取app 第一个 icon 图片 /// /// - Returns: app 第一个 icon 图片 public class func m_appIcon() -> UIImage?{ if let iconsPath = Bundle.m_appIconsPath() , iconsPath.count > 0 { return UIImage(named: iconsPath[0]) } return nil } }
101f3b2fac87512d68372d474d29fe72
26.794118
270
0.616931
false
false
false
false
overtake/TelegramSwift
refs/heads/master
Telegram-Mac/Auth_CodeEntryContol.swift
gpl-2.0
1
// // Auth_CodeEntryContol.swift // Telegram // // Created by Mike Renoir on 17.02.2022. // Copyright © 2022 Telegram. All rights reserved. // import Foundation import TGUIKit import KeyboardKey import AppKit final class Auth_CodeEntryContol : View { class Auth_CodeElement : Control { private var textView: TextView? = nil private var current: UInt16? = nil var prev:((Control, Bool)->Void)? var next:((Control, Bool)->Void)? var invoke:(()->Void)? var insertAll:(([Int])->Void)? var locked: Bool = false required init(frame frameRect: NSRect) { super.init(frame: frameRect) layer?.cornerRadius = 10 updateLocalizationAndTheme(theme: theme) self.set(handler: { control in control.window?.makeFirstResponder(control) }, for: .Click) } var value: String { if let current = current { return "\(current)" } else { return "" } } @objc func paste(_ id: Any) { let pasteboard = NSPasteboard.general guard let items = pasteboard.pasteboardItems else { return } for item in items { let string = item.string(forType: .string)?.components(separatedBy: CharacterSet.decimalDigits.inverted).joined() if let string = string, !string.isEmpty { let chars = Array(string).map { String($0) } self.insertAll?(chars.compactMap { Int($0) }) break } } } override func keyUp(with event: NSEvent) { super.keyUp(with: event) } override func keyDown(with event: NSEvent) { super.keyDown(with: event) guard !locked else { return } if let keyCode = KeyboardKey(rawValue: event.keyCode) { switch keyCode { case .Delete: self.inputKey(nil, animated: true) prev?(self, false) case .Tab: next?(self, true) case .LeftArrow: prev?(self, true) case .RightArrow: next?(self, true) case .Return: invoke?() default: self.inputKey(event.keyCode, animated: true) } } } private func updateTextView() { if let textView = textView, let current = self.current { let layout = TextViewLayout(.initialize(string: "\(current)", color: locked ? theme.colors.grayText : theme.colors.text, font: .code(24))) layout.measure(width: .greatestFiniteMagnitude) textView.update(layout) } } func inputKey(_ keyCode: UInt16?, animated: Bool) { if let keyCode = keyCode { if let number = KeyboardKey(rawValue: keyCode)?.number { if self.current != number { if let view = textView { performSubviewRemoval(view, animated: animated, duration: 0.2, scale: true) } let textView = TextView() self.textView = textView addSubview(textView) let layout = TextViewLayout(.initialize(string: "\(number)", color: theme.colors.text, font: .code(24))) layout.measure(width: .greatestFiniteMagnitude) textView.update(layout) textView.centerX(y: 7) textView.userInteractionEnabled = false textView.isSelectable = false textView.isEventLess = true if animated { textView.layer?.animateAlpha(from: 0, to: 1, duration: 0.2) textView.layer?.animatePosition(from: NSMakePoint(textView.frame.minX, textView.frame.minY + 5), to: textView.frame.origin) textView.layer?.animateScaleSpring(from: 0.1, to: 1, duration: 0.2) } } self.current = number self.next?(self, false) } else { self.shake(beep: true) } } else { if let view = textView { performSubviewRemoval(view, animated: animated, duration: 0.2, scale: true) } self.textView = nil self.current = nil } } override func layout() { super.layout() textView?.centerX(y: 7) } override func updateLocalizationAndTheme(theme: PresentationTheme) { super.updateLocalizationAndTheme(theme: theme) layer?.borderWidth = .borderSize background = theme.colors.grayBackground } var isFirstResponder: Bool { return window?.firstResponder == self } private func updateResponder(animated: Bool) { layer?.borderColor = isFirstResponder && !locked ? theme.colors.accent.cgColor : .clear if animated { layer?.animateBorder() } } override func resignFirstResponder() -> Bool { DispatchQueue.main.async { self.updateResponder(animated: true) } return true } override func becomeFirstResponder() -> Bool { DispatchQueue.main.async { self.updateResponder(animated: true) } return true } func set(locked: Bool, animated: Bool) { self.locked = locked updateResponder(animated: animated) updateTextView() } func clear() { inputKey(nil, animated: true) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } var takeNext:((String)->Void)? var takeError:(()->Void)? var locked: Bool = false required init(frame frameRect: NSRect) { super.init(frame: frameRect) } func moveToStart() { let subviews = self.subviews.compactMap { $0 as? Auth_CodeElement } for subview in subviews { subview.clear() } let subview = self.subviews.compactMap { $0 as? Auth_CodeElement }.first window?.makeFirstResponder(subview) } func set(locked: Bool, animated: Bool) { self.locked = locked let subviews = self.subviews.compactMap { $0 as? Auth_CodeElement } for subview in subviews { subview.set(locked: locked, animated: animated) } } func update(count: Int) -> NSSize { while subviews.count > count { subviews.removeLast() } while subviews.count < count { let element = Auth_CodeElement(frame: NSMakeRect(0, 0, 40, 40)) element.next = { [weak self] control, flip in self?.next(control, flip) } element.prev = { [weak self] control, flip in self?.prev(control, flip) } element.invoke = { [weak self] in self?.invoke() } element.insertAll = { [weak self] values in self?.insertAll(values) } subviews.append(element) } needsLayout = true return NSMakeSize(subviewsSize.width + (CGFloat(subviews.count - 1) * 8) + 20, 40) } private func insertAll(_ values: [Int]) { let subviews = self.subviews.compactMap { $0 as? Auth_CodeElement } if values.count == subviews.count { for (i, subview) in subviews.enumerated() { let value = values[i] if let keyboardKey = KeyboardKey.keyboardKey(value)?.rawValue { subview.inputKey(keyboardKey, animated: true) } } window?.makeFirstResponder(subviews.last) self.invoke() } } var value: String { let values = self.subviews.compactMap { $0 as? Auth_CodeElement } return values.reduce("", { current, value in return current + value.value }) } override func layout() { super.layout() var x: CGFloat = 10 for subview in subviews { subview.setFrameOrigin(NSMakePoint(x, 0)) x += subview.frame.width + 8 } } func firstResponder() -> NSResponder? { for subview in subviews { if window?.firstResponder == subview { return subview } } return subviews.first } func prev(_ current: Control, _ flip: Bool) { let subviews = self.subviews.compactMap { $0 as? Auth_CodeElement } if let index = subviews.firstIndex(where: { $0 == current }) { if index > 0 { let view = subviews[index - 1] window?.makeFirstResponder(view) } else if flip { let view = subviews[subviews.count - 1] window?.makeFirstResponder(view) } } } func next(_ current: Control, _ flip: Bool) { if !flip { takeError?() } let subviews = self.subviews.compactMap { $0 as? Auth_CodeElement } if let index = subviews.firstIndex(where: { $0 == current }) { if index < subviews.count - 1 { let view = subviews[index + 1] window?.makeFirstResponder(view) } else if flip { let view = subviews[0] window?.makeFirstResponder(view) } else if let index = subviews.firstIndex(where: { $0.value.isEmpty }) { let view = subviews[index] window?.makeFirstResponder(view) } if value.length == subviews.count, index == subviews.count - 1 { self.takeNext?(value) } } } func invoke() { guard !locked else { return } let subviews = self.subviews.compactMap { $0 as? Auth_CodeElement } if value.count == subviews.count { self.takeNext?(value) } else if let view = subviews.first(where: { $0.value.isEmpty }) { window?.makeFirstResponder(view) view.shake(beep: false) } } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
08f8ef686994392a5c1d8a9c50cd1cd9
33.02439
154
0.498656
false
false
false
false
ledwards/ios-twitter-redux
refs/heads/master
Twit/TwitterClient.swift
mit
1
// // TwitterClient.swift // Twit // // Created by Lee Edwards on 2/17/16. // Copyright © 2016 Lee Edwards. All rights reserved. // import UIKit import BDBOAuth1Manager let twitterConsumerKey = "ASDXfCo26uZTDqC9DK70U8G6B" let twitterConsumerSecret = "Ekfjc6Y9u5tnAkbqRvJnZGl6Rt6uNXo075lxI9C5n6rKpiAEbd" let twitterBaseURL = NSURL(string: "https://api.twitter.com") class TwitterClient: BDBOAuth1SessionManager { var loginCompletion: ((user: User?, error: NSError?) -> ())? class var sharedInstance: TwitterClient { struct Static { static let instance = TwitterClient(baseURL: twitterBaseURL, consumerKey: twitterConsumerKey, consumerSecret: twitterConsumerSecret) } return Static.instance } func homeTimelineWithCompletion(params: NSDictionary?, completion: (tweets: [Tweet]?, error: NSError?) -> ()) { GET("1.1/statuses/home_timeline.json", parameters: nil, progress: { (progress: NSProgress) -> Void in }, success: { (operation: NSURLSessionDataTask, response: AnyObject?) -> Void in let tweets = Tweet.tweetsWithArray((response as! [NSDictionary])) completion(tweets: tweets, error: nil) }, failure: { (operation: NSURLSessionDataTask?, error: NSError!) -> Void in print("error getting home timeline") completion(tweets: nil, error: error) }) } func mentionsTimelineWithCompletion(params: NSDictionary?, completion: (tweets: [Tweet]?, error: NSError?) -> ()) { GET("1.1/statuses/mentions_timeline.json", parameters: nil, progress: { (progress: NSProgress) -> Void in }, success: { (operation: NSURLSessionDataTask, response: AnyObject?) -> Void in let tweets = Tweet.tweetsWithArray((response as! [NSDictionary])) completion(tweets: tweets, error: nil) }, failure: { (operation: NSURLSessionDataTask?, error: NSError!) -> Void in print("error getting home timeline") completion(tweets: nil, error: error) }) } func loginWithCompletion(completion: (user: User?, error: NSError?) -> ()) { loginCompletion = completion TwitterClient.sharedInstance.requestSerializer.removeAccessToken() TwitterClient.sharedInstance.fetchRequestTokenWithPath("oauth/request_token", method: "GET", callbackURL: NSURL(string: "cptwitterdemo://oauth"), scope: nil, success: { (requestToken: BDBOAuth1Credential!) -> Void in print("success") let authURL = NSURL(string: "https://api.twitter.com/oauth/authorize?oauth_token=\(requestToken.token)") UIApplication.sharedApplication().openURL(authURL!) }, failure: { (error: NSError!) -> Void in print("fail") }) } func openURL(url: NSURL) { TwitterClient.sharedInstance.fetchAccessTokenWithPath("oauth/access_token", method: "POST", requestToken: BDBOAuth1Credential(queryString: url.query), success: { (requestToken: BDBOAuth1Credential!) -> Void in print("access token received") TwitterClient.sharedInstance.requestSerializer.saveAccessToken(requestToken) TwitterClient.sharedInstance.GET("1.1/account/verify_credentials.json", parameters: nil, progress: { (progress: NSProgress) -> Void in }, success: { (operation: NSURLSessionDataTask, response: AnyObject?) -> Void in let user = User(dictionary: response as! NSDictionary) User.currentUser = user print("user: \(User.currentUser!.name!)") self.loginCompletion?(user: user, error: nil) }, failure: { (operation: NSURLSessionDataTask?, error: NSError!) -> Void in print("error getting current user") self.loginCompletion?(user: nil, error: error) }) }, failure: { (error: NSError!) -> Void in print("failed to receive access token") } ) } func createTweetWithCompletion(params: NSDictionary, completion: (tweet: Tweet?, error: NSError?) -> ()) { POST("1.1/statuses/update.json", parameters: params, progress: { (progress: NSProgress) -> Void in }, success: { (operation: NSURLSessionDataTask, response: AnyObject?) -> Void in let tweet = Tweet(dictionary: response as! NSDictionary) completion(tweet: tweet, error: nil) }, failure: { (operation: NSURLSessionDataTask?, error: NSError!) -> Void in print("error getting home timeline") completion(tweet: nil, error: error) }) } func retweetWithCompletion(id: Int, completion: (tweet: Tweet?, error: NSError?) -> ()) { POST("1.1/statuses/retweet/\(id).json", parameters: nil, progress: { (progress: NSProgress) -> Void in }, success: { (operation: NSURLSessionDataTask, response: AnyObject?) -> Void in let tweet = Tweet(dictionary: response as! NSDictionary) completion(tweet: tweet, error: nil) }, failure: { (operation: NSURLSessionDataTask?, error: NSError!) -> Void in print("error getting home timeline") completion(tweet: nil, error: error) }) } func unretweetWithCompletion(id: Int, completion: (tweet: Tweet?, error: NSError?) -> ()) { POST("1.1/statuses/unretweet/\(id).json", parameters: nil, progress: { (progress: NSProgress) -> Void in }, success: { (operation: NSURLSessionDataTask, response: AnyObject?) -> Void in let tweet = Tweet(dictionary: response as! NSDictionary) completion(tweet: tweet, error: nil) }, failure: { (operation: NSURLSessionDataTask?, error: NSError!) -> Void in print("error getting home timeline") completion(tweet: nil, error: error) }) } func favoriteWithCompletion(id: Int?, completion: (tweet: Tweet?, error: NSError?) -> ()) { POST("1.1/favorites/create.json", parameters: NSDictionary(dictionary: ["id": id!]), progress: { (progress: NSProgress) -> Void in }, success: { (operation: NSURLSessionDataTask, response: AnyObject?) -> Void in let tweet = Tweet(dictionary: response as! NSDictionary) completion(tweet: tweet, error: nil) }, failure: { (operation: NSURLSessionDataTask?, error: NSError!) -> Void in print("error getting home timeline") completion(tweet: nil, error: error) }) } func unfavoriteWithCompletion(id: Int?, completion: (tweet: Tweet?, error: NSError?) -> ()) { POST("1.1/favorites/destroy.json", parameters: NSDictionary(dictionary: ["id": id!]), progress: { (progress: NSProgress) -> Void in }, success: { (operation: NSURLSessionDataTask, response: AnyObject?) -> Void in let tweet = Tweet(dictionary: response as! NSDictionary) completion(tweet: tweet, error: nil) }, failure: { (operation: NSURLSessionDataTask?, error: NSError!) -> Void in print("error getting home timeline") completion(tweet: nil, error: error) }) } }
556622964841a041811eb242f9c34e22
46.721212
165
0.577925
false
false
false
false
ygorshenin/omim
refs/heads/master
iphone/Maps/Bookmarks/Categories/BMCViewModel/BMCDefaultViewModel.swift
apache-2.0
1
final class BMCDefaultViewModel: NSObject { typealias BM = MWMBookmarksManager var view: BMCView! private enum Const { static let minCategoryNameLength: UInt = 0 static let maxCategoryNameLength: UInt = 60 } private var sections: [BMCSection] = [] private var permissions: [BMCPermission] = [] private var categories: [BMCCategory] = [] private var actions: [BMCAction] = [] private var notifications: [BMCNotification] = [] private(set) var isPendingPermission = false private var isAuthenticated = false private var filesPrepared = false; private var onPreparedToShareCategory: BMCViewModel.onPreparedToShareHandler? var minCategoryNameLength: UInt = Const.minCategoryNameLength var maxCategoryNameLength: UInt = Const.maxCategoryNameLength override init() { super.init() loadData() } private func setPermissions() { isAuthenticated = MWMAuthorizationViewModel.isAuthenticated() if !isAuthenticated { Statistics.logEvent(kStatBookmarksSyncProposalShown, withParameters: [kStatHasAuthorization: 0]) permissions = [.signup] } else if !BM.isCloudEnabled() { Statistics.logEvent(kStatBookmarksSyncProposalShown, withParameters: [kStatHasAuthorization: 1]) isPendingPermission = false permissions = [.backup] } else { isPendingPermission = false permissions = [.restore(BM.lastSynchronizationDate())] } } private func setCategories() { categories = BM.groupsIdList().map { categoryId -> BMCCategory in let title = BM.getCategoryName(categoryId)! let count = BM.getCategoryMarksCount(categoryId) + BM.getCategoryTracksCount(categoryId) let isVisible = BM.isCategoryVisible(categoryId) return BMCCategory(identifier: categoryId, title: title, count: count, isVisible: isVisible) } } private func setActions() { actions = [.create] } private func setNotifications() { notifications.append(.load) } private func loadData() { sections = [] sections.append(.permissions) setPermissions() if BM.areBookmarksLoaded() { sections.append(.categories) setCategories() sections.append(.actions) setActions() } else { sections.append(.notifications) setNotifications() } view?.update(sections: []) } } extension BMCDefaultViewModel: BMCViewModel { func numberOfSections() -> Int { return sections.count } func sectionType(section: Int) -> BMCSection { return sections[section] } func sectionIndex(section: BMCSection) -> Int { return sections.index(of: section)! } func numberOfRows(section: Int) -> Int { return numberOfRows(section: sectionType(section: section)) } func numberOfRows(section: BMCSection) -> Int { switch section { case .permissions: return permissions.count case .categories: return categories.count case .actions: return actions.count case .notifications: return notifications.count } } func item(indexPath: IndexPath) -> BMCModel { let (section, row) = (indexPath.section, indexPath.row) switch sectionType(section: section) { case .permissions: return permissions[row] case .categories: return categories[row] case .actions: return actions[row] case .notifications: return notifications[row] } } func areAllCategoriesHidden() -> Bool { var result = true; categories.forEach { if $0.isVisible { result = false } } return result } func updateAllCategoriesVisibility(isShowAll: Bool) { categories.forEach { $0.isVisible = isShowAll } BM.setUserCategoriesVisible(isShowAll) } func updateCategoryVisibility(category: BMCCategory) { category.isVisible = !category.isVisible BM.setCategory(category.identifier, isVisible: category.isVisible) } func addCategory(name: String) { guard let section = sections.index(of: .categories) else { assertionFailure() return } categories.append(BMCCategory(identifier: BM.createCategory(withName: name), title: name)) view.insert(at: [IndexPath(row: categories.count - 1, section: section)]) } func renameCategory(category: BMCCategory, name: String) { category.title = name BM.setCategory(category.identifier, name: name) } func deleteCategory(category: BMCCategory) { guard let row = categories.index(of: category), let section = sections.index(of: .categories) else { assertionFailure() return } categories.remove(at: row) BM.deleteCategory(category.identifier) view.delete(at: [IndexPath(row: row, section: section)]) } func checkCategory(name: String) -> Bool { return BM.checkCategoryName(name) } func shareCategory(category: BMCCategory, handler: @escaping onPreparedToShareHandler) { onPreparedToShareCategory = handler BM.shareCategory(category.identifier) } func finishShareCategory() { BM.finishShareCategory() onPreparedToShareCategory = nil } func pendingPermission(isPending: Bool) { isPendingPermission = isPending setPermissions() view.update(sections: [.permissions]) } func grant(permission: BMCPermission?) { if let permission = permission { switch permission { case .signup: assertionFailure() case .backup: Statistics.logEvent(kStatBookmarksSyncProposalApproved, withParameters: [ kStatNetwork: Statistics.connectionTypeString(), kStatHasAuthorization: isAuthenticated ? 1 : 0, ]) BM.setCloudEnabled(true) case .restore: assertionFailure("Not implemented") } } pendingPermission(isPending: false) } func convertAllKMLIfNeeded() { let count = BM.filesCountForConversion() if count > 0 { MWMAlertViewController.activeAlert().presentConvertBookmarksAlert(withCount: count) { MWMAlertViewController.activeAlert().presentSpinnerAlert(withTitle: L("converting"), cancel: nil) BM.convertAll() } } } func addToObserverList() { BM.add(self) } func removeFromObserverList() { BM.remove(self) } func setNotificationsEnabled(_ enabled: Bool) { BM.setNotificationsEnabled(enabled) } func areNotificationsEnabled() -> Bool { return BM.areNotificationsEnabled() } func requestRestoring() { BM.requestRestoring() } func applyRestoring() { BM.applyRestoring() } func cancelRestoring() { if filesPrepared { return } BM.cancelRestoring() } } extension BMCDefaultViewModel: MWMBookmarksObserver { func onRestoringStarted() { filesPrepared = false MWMAlertViewController.activeAlert().presentSpinnerAlert(withTitle: L("bookmarks_restore_process")) { [weak self] in self?.cancelRestoring() } } func onRestoringFilesPrepared() { filesPrepared = true } func onSynchronizationFinished(_ result: MWMSynchronizationResult) { MWMAlertViewController.activeAlert().closeAlert() { [weak self] in switch result { case .networkError: fallthrough case .authError: MWMAlertViewController.activeAlert().presentDefaultAlert(withTitle: L("error_server_title"), message: L("error_server_message"), rightButtonTitle: L("try_again"), leftButtonTitle: L("cancel")) { [weak self] in self?.requestRestoring() } case .diskError: MWMAlertViewController.activeAlert().presentInternalErrorAlert() case .userInterrupted: break case .success: guard let s = self else { return } s.setCategories() s.view.update(sections: [.categories]) } } } func onRestoringRequest(_ result: MWMRestoringRequestResult, deviceName name: String?, backupDate date: Date?) { MWMAlertViewController.activeAlert().closeAlert() { switch result { case .noInternet: MWMAlertViewController.activeAlert().presentNoConnectionAlert() case .backupExists: guard let date = date else { assertionFailure() return } let formatter = DateFormatter() formatter.dateStyle = .short formatter.timeStyle = .none let deviceName = name ?? "" let message = String(coreFormat: L("bookmarks_restore_message"), arguments: [formatter.string(from: date), deviceName]) let cancelAction = { [weak self] in self?.cancelRestoring() } as MWMVoidBlock MWMAlertViewController.activeAlert().presentRestoreBookmarkAlert(withMessage: message, rightButtonAction: { [weak self] in MWMAlertViewController.activeAlert().presentSpinnerAlert(withTitle: L("bookmarks_restore_process"), cancel: cancelAction) self?.applyRestoring() }, leftButtonAction: cancelAction) case .noBackup: MWMAlertViewController.activeAlert().presentDefaultAlert(withTitle: L("bookmarks_restore_empty_title"), message: L("bookmarks_restore_empty_message"), rightButtonTitle: L("ok"), leftButtonTitle: nil, rightButtonAction: nil) case .notEnoughDiskSpace: MWMAlertViewController.activeAlert().presentNotEnoughSpaceAlert() case .requestError: assertionFailure() } } } func onBookmarksLoadFinished() { loadData() convertAllKMLIfNeeded() } func onBookmarkDeleted(_: MWMMarkID) { loadData() } func onBookmarksCategoryFilePrepared(_ status: MWMBookmarksShareStatus) { switch status { case .success: onPreparedToShareCategory?(.success(BM.shareCategoryURL())) case .emptyCategory: onPreparedToShareCategory?(.error(title: L("bookmarks_error_title_share_empty"), text: L("bookmarks_error_message_share_empty"))) case .archiveError: fallthrough case .fileError: onPreparedToShareCategory?(.error(title: L("dialog_routing_system_error"), text: L("bookmarks_error_message_share_general"))) } } func onConversionFinish(_ success: Bool) { setCategories() view.update(sections: [.categories]) view.conversionFinished(success: success) } }
bd3ae6d9783fa9b1ad7e6a9832822d22
30.142857
135
0.640917
false
false
false
false
TabletopAssistant/DiceKit
refs/heads/master
DiceKit/AdditionExpression.swift
apache-2.0
1
// // AdditionExpression.swift // DiceKit // // Created by Brentley Jones on 7/19/15. // Copyright © 2015 Brentley Jones. All rights reserved. // import Foundation public struct AdditionExpression<LeftExpression: protocol<ExpressionType, Equatable>, RightExpression: protocol<ExpressionType, Equatable>>: Equatable { public let leftAddend: LeftExpression public let rightAddend: RightExpression public init(_ leftAddend: LeftExpression, _ rightAddend: RightExpression) { self.leftAddend = leftAddend self.rightAddend = rightAddend } } // MARK: - ExpressionType extension AdditionExpression: ExpressionType { public typealias Result = AdditionExpressionResult<LeftExpression.Result, RightExpression.Result> public func evaluate() -> Result { let leftResult = leftAddend.evaluate() let rightResult = rightAddend.evaluate() return Result(leftResult, rightResult) } public var probabilityMass: ExpressionProbabilityMass { return leftAddend.probabilityMass && rightAddend.probabilityMass } } // MARK: - CustomStringConvertible extension AdditionExpression: CustomStringConvertible { public var description: String { return "\(leftAddend) + \(rightAddend)" } } // MARK: - CustomDebugStringConvertible extension AdditionExpression: CustomDebugStringConvertible { public var debugDescription: String { return "\(String(reflecting: leftAddend)) + \(String(reflecting: rightAddend))" } } // MARK: - Equatable private func equate<L, R>(lhs: AdditionExpression<L, R>, _ rhs: AdditionExpression<L, R>) -> Bool { return lhs.leftAddend == rhs.leftAddend && lhs.rightAddend == rhs.rightAddend } // When the same types check for commutative public func == <E>(lhs: AdditionExpression<E, E>, rhs: AdditionExpression<E, E>) -> Bool { if equate(lhs, rhs) { return true } // Commutative return lhs.leftAddend == rhs.rightAddend && lhs.rightAddend == rhs.leftAddend } public func == <L, R>(lhs: AdditionExpression<L, R>, rhs: AdditionExpression<L, R>) -> Bool { return equate(lhs, rhs) } // MARK: - Operators public func + <L: protocol<ExpressionType, Equatable>, R: protocol<ExpressionType, Equatable>>(lhs: L, rhs: R) -> AdditionExpression<L, R> { return AdditionExpression(lhs, rhs) } public func + <R: protocol<ExpressionType, Equatable>>(lhs: ExpressionResultValue, rhs: R) -> AdditionExpression<Constant, R> { return AdditionExpression(Constant(lhs), rhs) } public func + <L: protocol<ExpressionType, Equatable>>(lhs: L, rhs: ExpressionResultValue) -> AdditionExpression<L, Constant> { return AdditionExpression(lhs, Constant(rhs)) }
9ffc0c7e8bfe7dde56659d7d65e6cb84
28.43617
152
0.698591
false
false
false
false
DumbDuck/VecodeKit
refs/heads/master
iOS_Mac/QuartzPictureExample/pictures/all_test.swift
mit
1
import CoreGraphics // MARK: g_picture_all_test public let g_picture_all_test = VKQuartzPicture(bounds: CGRect(x: 0, y: 0, width: 550, height: 400), drawer: draw_main) ///////////////////////// private func draw_gradient_0(_ ctx: CGContext) { let colors : [CGFloat] = [ 0, 0, 1, 1, 0, 0, 0, 1 ] let locations : [CGFloat] = [ 0, 1 ] let colorSpace = CGColorSpaceCreateDeviceRGB() let gradient = CGGradient(colorSpace: colorSpace, colorComponents: colors, locations: locations, count: 2)! let options : CGGradientDrawingOptions = [.drawsBeforeStartLocation, .drawsAfterEndLocation] ctx.drawRadialGradient(gradient, startCenter: CGPoint(x: 0, y: 0), startRadius: 0, endCenter: CGPoint(x: 0, y: 0), endRadius: 819.2, options: options); } private func def_path_0(_ ctx: CGContext) { ctx.move(to: CGPoint(x: 528.95, y: 193)) ctx.addLine(to: CGPoint(x: 528.95, y: 59)) ctx.addLine(to: CGPoint(x: 409.95, y: 59)) ctx.addLine(to: CGPoint(x: 409.95, y: 193)) ctx.addLine(to: CGPoint(x: 528.95, y: 193)) ctx.closePath() } private func draw_gradient_1(_ ctx: CGContext) { let colors : [CGFloat] = [ 1, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 1 ] let locations : [CGFloat] = [ 0, 0.164706, 0.364706, 0.498039, 0.666667, 0.831373, 1 ] let colorSpace = CGColorSpaceCreateDeviceRGB() let gradient = CGGradient(colorSpace: colorSpace, colorComponents: colors, locations: locations, count: 7)! let options : CGGradientDrawingOptions = [.drawsBeforeStartLocation, .drawsAfterEndLocation] ctx.drawLinearGradient(gradient, start: CGPoint(x: -819.2, y: 0), end: CGPoint(x: 819.2, y: 0), options: options) } private func def_path_1(_ ctx: CGContext) { ctx.move(to: CGPoint(x: 421.95, y: 245)) ctx.addLine(to: CGPoint(x: 421.95, y: 359.95)) ctx.addLine(to: CGPoint(x: 538.95, y: 359.95)) ctx.addLine(to: CGPoint(x: 538.95, y: 245)) ctx.addLine(to: CGPoint(x: 421.95, y: 245)) ctx.closePath() } private func def_path_2(_ ctx: CGContext) { ctx.move(to: CGPoint(x: 58.75, y: 160.95)) ctx.addLine(to: CGPoint(x: 14, y: 175.45)) ctx.addLine(to: CGPoint(x: 14, y: 222.5)) ctx.addLine(to: CGPoint(x: 58.75, y: 237)) ctx.addLine(to: CGPoint(x: 86.35, y: 199)) ctx.addLine(to: CGPoint(x: 58.75, y: 160.95)) ctx.closePath() } private func def_path_3(_ ctx: CGContext) { ctx.move(to: CGPoint(x: 528.95, y: 193)) ctx.addLine(to: CGPoint(x: 409.95, y: 193)) ctx.addLine(to: CGPoint(x: 409.95, y: 59)) ctx.addLine(to: CGPoint(x: 528.95, y: 59)) ctx.addLine(to: CGPoint(x: 528.95, y: 193)) } private func def_path_4(_ ctx: CGContext) { ctx.move(to: CGPoint(x: 421.95, y: 245)) ctx.addLine(to: CGPoint(x: 538.95, y: 245)) ctx.addLine(to: CGPoint(x: 538.95, y: 359.95)) ctx.addLine(to: CGPoint(x: 421.95, y: 359.95)) ctx.addLine(to: CGPoint(x: 421.95, y: 245)) } private typealias TKColorTransform = [CGFloat] private func TKColorApplyColorTransform(_ color: inout [CGFloat], _ index: Int, _ transform: TKColorTransform?) { if let transform = transform { assert(transform.count == 8); color[index + 0] = transform[0] * color[index + 0] + transform[4]; color[index + 1] = transform[1] * color[index + 1] + transform[5]; color[index + 2] = transform[2] * color[index + 2] + transform[6]; color[index + 3] = transform[3] * color[index + 3] + transform[7]; } } private func draw_gradient_2(_ ctx: CGContext, _ colorTrans: TKColorTransform?) { var colors : [CGFloat] = [ 1, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 1 ] TKColorApplyColorTransform(&colors, 0, colorTrans) TKColorApplyColorTransform(&colors, 4, colorTrans) TKColorApplyColorTransform(&colors, 8, colorTrans) TKColorApplyColorTransform(&colors, 12, colorTrans) TKColorApplyColorTransform(&colors, 16, colorTrans) TKColorApplyColorTransform(&colors, 20, colorTrans) TKColorApplyColorTransform(&colors, 24, colorTrans) let locations : [CGFloat] = [ 0, 0.164706, 0.364706, 0.498039, 0.666667, 0.831373, 1 ] let colorSpace = CGColorSpaceCreateDeviceRGB() let gradient = CGGradient(colorSpace: colorSpace, colorComponents: colors, locations: locations, count: 7)! let options : CGGradientDrawingOptions = [.drawsBeforeStartLocation, .drawsAfterEndLocation] ctx.drawLinearGradient(gradient, start: CGPoint(x: -819.2, y: 0), end: CGPoint(x: 819.2, y: 0), options: options) } private func def_path_5(_ ctx: CGContext) { ctx.move(to: CGPoint(x: 78.85, y: 0)) ctx.addLine(to: CGPoint(x: -1.52588e-06, y: 54)) ctx.addLine(to: CGPoint(x: 27.05, y: 145.7)) ctx.addLine(to: CGPoint(x: 122.6, y: 148.3)) ctx.addLine(to: CGPoint(x: 154.65, y: 58.25)) ctx.addLine(to: CGPoint(x: 78.85, y: 0)) ctx.closePath() } private func TKSetRGBStrokeColor(_ ctx: CGContext, _ r: CGFloat, _ g: CGFloat, _ b : CGFloat, _ a : CGFloat, _ transform: TKColorTransform?) { var color : [CGFloat] = [ r, g, b, a ]; TKColorApplyColorTransform(&color, 0, transform); ctx.setStrokeColor(red: color[0], green: color[1], blue: color[2], alpha: color[3]) } private func draw_shape_2(_ ctx: CGContext, _ colorTrans: TKColorTransform?) { ctx.saveGState() ctx.concatenate(CGAffineTransform(a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0)) def_path_5(ctx) ctx.clip(using: .evenOdd) ctx.concatenate(CGAffineTransform(a: 0.0943909, b: 0, c: 0, d: 0.0905151, tx: 77.3, ty: 74.15)) draw_gradient_2(ctx, colorTrans) ctx.restoreGState() ctx.saveGState() TKSetRGBStrokeColor(ctx, 0.2, 1, 0.4, 1, colorTrans) ctx.setLineWidth(1) ctx.setLineCap(.round) ctx.setLineJoin(.round) def_path_5(ctx) ctx.drawPath(using: .stroke) ctx.restoreGState() } private func draw_gradient_3(_ ctx: CGContext, _ colorTrans: TKColorTransform?) { var colors : [CGFloat] = [ 0, 1, 0, 1, 0, 0, 0, 1 ] TKColorApplyColorTransform(&colors, 0, colorTrans) TKColorApplyColorTransform(&colors, 4, colorTrans) let locations : [CGFloat] = [ 0, 1 ] let colorSpace = CGColorSpaceCreateDeviceRGB() let gradient = CGGradient(colorSpace: colorSpace, colorComponents: colors, locations: locations, count: 2)! let options : CGGradientDrawingOptions = [.drawsBeforeStartLocation, .drawsAfterEndLocation] ctx.drawRadialGradient(gradient, startCenter: CGPoint(x: 0, y: 0), startRadius: 0, endCenter: CGPoint(x: 0, y: 0), endRadius: 819.2, options: options); } private func def_path_6(_ ctx: CGContext) { ctx.move(to: CGPoint(x: 144, y: 76)) ctx.addQuadCurve(to: CGPoint(x: 122.9, y: 22.25), control: CGPoint(x: 144, y: 44.5)) ctx.addQuadCurve(to: CGPoint(x: 72, y: 0), control: CGPoint(x: 101.8, y: 0)) ctx.addQuadCurve(to: CGPoint(x: 21.1, y: 22.25), control: CGPoint(x: 42.2, y: 0)) ctx.addQuadCurve(to: CGPoint(x: 3.8147e-07, y: 76), control: CGPoint(x: 3.8147e-07, y: 44.5)) ctx.addQuadCurve(to: CGPoint(x: 21.1, y: 129.75), control: CGPoint(x: 3.8147e-07, y: 107.5)) ctx.addQuadCurve(to: CGPoint(x: 72, y: 152), control: CGPoint(x: 42.2, y: 152)) ctx.addQuadCurve(to: CGPoint(x: 122.9, y: 129.75), control: CGPoint(x: 101.8, y: 152)) ctx.addQuadCurve(to: CGPoint(x: 144, y: 76), control: CGPoint(x: 144, y: 107.5)) ctx.closePath() } private func draw_shape_4(_ ctx: CGContext, _ colorTrans: TKColorTransform?) { ctx.saveGState() ctx.concatenate(CGAffineTransform(a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0)) def_path_6(ctx) ctx.clip(using: .evenOdd) ctx.concatenate(CGAffineTransform(a: 0.0935059, b: 0, c: 0, d: 0.0935059, tx: 72, ty: 76)) draw_gradient_3(ctx, colorTrans) ctx.restoreGState() ctx.saveGState() TKSetRGBStrokeColor(ctx, 0.2, 1, 0.4, 1, colorTrans) ctx.setLineWidth(1) ctx.setLineCap(.round) ctx.setLineJoin(.round) def_path_6(ctx) ctx.drawPath(using: .stroke) ctx.restoreGState() } private func def_path_7(_ ctx: CGContext) { ctx.move(to: CGPoint(x: 306, y: -616)) ctx.addQuadCurve(to: CGPoint(x: 522, y: -368), control: CGPoint(x: 526.5, y: -620)) ctx.addQuadCurve(to: CGPoint(x: 306, y: -122), control: CGPoint(x: 527, y: -118)) ctx.addLine(to: CGPoint(x: 224, y: -122)) ctx.addLine(to: CGPoint(x: 224, y: -616)) ctx.addLine(to: CGPoint(x: 306, y: -616)) ctx.closePath() ctx.move(to: CGPoint(x: 318, y: 0)) ctx.addQuadCurve(to: CGPoint(x: 692, y: -368), control: CGPoint(x: 688.5, y: -1.5)) ctx.addQuadCurve(to: CGPoint(x: 318, y: -738), control: CGPoint(x: 688.5, y: -737.5)) ctx.addLine(to: CGPoint(x: 66, y: -738)) ctx.addLine(to: CGPoint(x: 66, y: 0)) ctx.addLine(to: CGPoint(x: 318, y: 0)) ctx.closePath() } private func def_path_8(_ ctx: CGContext) { ctx.move(to: CGPoint(x: 560, y: 0)) ctx.addLine(to: CGPoint(x: 554, y: -92)) ctx.addLine(to: CGPoint(x: 554, y: -514)) ctx.addLine(to: CGPoint(x: 400, y: -514)) ctx.addLine(to: CGPoint(x: 400, y: -204)) ctx.addQuadCurve(to: CGPoint(x: 308, y: -86), control: CGPoint(x: 392, y: -94)) ctx.addQuadCurve(to: CGPoint(x: 216, y: -204), control: CGPoint(x: 219, y: -85.5)) ctx.addLine(to: CGPoint(x: 216, y: -514)) ctx.addLine(to: CGPoint(x: 62, y: -514)) ctx.addLine(to: CGPoint(x: 62, y: -180)) ctx.addQuadCurve(to: CGPoint(x: 72, y: -98), control: CGPoint(x: 62.5, y: -137)) ctx.addQuadCurve(to: CGPoint(x: 242, y: 13), control: CGPoint(x: 105.5, y: -2)) ctx.addQuadCurve(to: CGPoint(x: 400, y: -62), control: CGPoint(x: 348, y: 13.5)) ctx.addLine(to: CGPoint(x: 406, y: 0)) ctx.addLine(to: CGPoint(x: 560, y: 0)) ctx.closePath() } private func def_path_9(_ ctx: CGContext) { ctx.move(to: CGPoint(x: 68, y: -514)) ctx.addLine(to: CGPoint(x: 68, y: 0)) ctx.addLine(to: CGPoint(x: 222, y: 0)) ctx.addLine(to: CGPoint(x: 222, y: -308)) ctx.addQuadCurve(to: CGPoint(x: 314, y: -426), control: CGPoint(x: 229, y: -418.5)) ctx.addQuadCurve(to: CGPoint(x: 406, y: -308), control: CGPoint(x: 403.5, y: -426.5)) ctx.addLine(to: CGPoint(x: 406, y: 0)) ctx.addLine(to: CGPoint(x: 560, y: 0)) ctx.addLine(to: CGPoint(x: 560, y: -308)) ctx.addQuadCurve(to: CGPoint(x: 652, y: -426), control: CGPoint(x: 567, y: -418.5)) ctx.addQuadCurve(to: CGPoint(x: 744, y: -308), control: CGPoint(x: 741.5, y: -426.5)) ctx.addLine(to: CGPoint(x: 744, y: 0)) ctx.addLine(to: CGPoint(x: 898, y: 0)) ctx.addLine(to: CGPoint(x: 898, y: -308)) ctx.addQuadCurve(to: CGPoint(x: 897.5, y: -350), control: CGPoint(x: 898, y: -329)) ctx.addQuadCurve(to: CGPoint(x: 895, y: -380.5), control: CGPoint(x: 896.5, y: -365)) ctx.addQuadCurve(to: CGPoint(x: 882, y: -432), control: CGPoint(x: 891.5, y: -409)) ctx.addQuadCurve(to: CGPoint(x: 718, y: -528), control: CGPoint(x: 838, y: -516)) ctx.addQuadCurve(to: CGPoint(x: 544, y: -432), control: CGPoint(x: 612, y: -531.5)) ctx.addQuadCurve(to: CGPoint(x: 380, y: -528), control: CGPoint(x: 500, y: -516)) ctx.addQuadCurve(to: CGPoint(x: 222, y: -452), control: CGPoint(x: 274.5, y: -528.5)) ctx.addLine(to: CGPoint(x: 220, y: -452)) ctx.addLine(to: CGPoint(x: 220, y: -514)) ctx.addLine(to: CGPoint(x: 68, y: -514)) ctx.closePath() } private func def_path_10(_ ctx: CGContext) { ctx.move(to: CGPoint(x: 314, y: -426)) ctx.addQuadCurve(to: CGPoint(x: 424, y: -256), control: CGPoint(x: 427, y: -427.5)) ctx.addQuadCurve(to: CGPoint(x: 314, y: -86), control: CGPoint(x: 427, y: -84.5)) ctx.addQuadCurve(to: CGPoint(x: 204, y: -256), control: CGPoint(x: 212.5, y: -92)) ctx.addQuadCurve(to: CGPoint(x: 314, y: -426), control: CGPoint(x: 212.5, y: -420)) ctx.closePath() ctx.move(to: CGPoint(x: 46, y: 0)) ctx.addLine(to: CGPoint(x: 198, y: 0)) ctx.addLine(to: CGPoint(x: 202, y: -72)) ctx.addLine(to: CGPoint(x: 204, y: -72)) ctx.addQuadCurve(to: CGPoint(x: 362, y: 13), control: CGPoint(x: 253, y: 12)) ctx.addQuadCurve(to: CGPoint(x: 520.5, y: -60), control: CGPoint(x: 465, y: 7)) ctx.addQuadCurve(to: CGPoint(x: 584, y: -256), control: CGPoint(x: 576, y: -127)) ctx.addQuadCurve(to: CGPoint(x: 344, y: -528), control: CGPoint(x: 566.5, y: -514.5)) ctx.addQuadCurve(to: CGPoint(x: 206, y: -454), control: CGPoint(x: 258, y: -524)) ctx.addLine(to: CGPoint(x: 204, y: -454)) ctx.addLine(to: CGPoint(x: 204, y: -738)) ctx.addLine(to: CGPoint(x: 50, y: -738)) ctx.addLine(to: CGPoint(x: 50, y: -102)) ctx.addLine(to: CGPoint(x: 46, y: 0)) ctx.closePath() } private func def_path_11(_ ctx: CGContext) { ctx.move(to: CGPoint(x: 262, y: -528)) ctx.addQuadCurve(to: CGPoint(x: 32, y: -256), control: CGPoint(x: 49.5, y: -514.5)) ctx.addQuadCurve(to: CGPoint(x: 98, y: -60.5), control: CGPoint(x: 40.5, y: -128)) ctx.addQuadCurve(to: CGPoint(x: 262, y: 13), control: CGPoint(x: 155.5, y: 6.5)) ctx.addQuadCurve(to: CGPoint(x: 490, y: -186), control: CGPoint(x: 478, y: 10.5)) ctx.addLine(to: CGPoint(x: 340, y: -186)) ctx.addQuadCurve(to: CGPoint(x: 262, y: -86), control: CGPoint(x: 333, y: -87.5)) ctx.addQuadCurve(to: CGPoint(x: 193.5, y: -245.5), control: CGPoint(x: 200, y: -84.5)) ctx.addQuadCurve(to: CGPoint(x: 192, y: -264), control: CGPoint(x: 193, y: -254.5)) ctx.addQuadCurve(to: CGPoint(x: 192.5, y: -273.5), control: CGPoint(x: 192, y: -269)) ctx.addQuadCurve(to: CGPoint(x: 260, y: -426), control: CGPoint(x: 198.5, y: -426)) ctx.addQuadCurve(to: CGPoint(x: 338, y: -332), control: CGPoint(x: 332, y: -425)) ctx.addLine(to: CGPoint(x: 490, y: -332)) ctx.addQuadCurve(to: CGPoint(x: 262, y: -528), control: CGPoint(x: 479.5, y: -518)) ctx.closePath() } private func def_path_12(_ ctx: CGContext) { ctx.move(to: CGPoint(x: 68, y: -738)) ctx.addLine(to: CGPoint(x: 68, y: 0)) ctx.addLine(to: CGPoint(x: 222, y: 0)) ctx.addLine(to: CGPoint(x: 222, y: -278)) ctx.addLine(to: CGPoint(x: 224, y: -280)) ctx.addLine(to: CGPoint(x: 378, y: 0)) ctx.addLine(to: CGPoint(x: 558, y: 0)) ctx.addLine(to: CGPoint(x: 368, y: -294)) ctx.addLine(to: CGPoint(x: 546, y: -520)) ctx.addLine(to: CGPoint(x: 374, y: -520)) ctx.addLine(to: CGPoint(x: 224, y: -304)) ctx.addLine(to: CGPoint(x: 222, y: -306)) ctx.addLine(to: CGPoint(x: 222, y: -738)) ctx.addLine(to: CGPoint(x: 68, y: -738)) ctx.closePath() } private func def_path_13(_ ctx: CGContext) { ctx.move(to: CGPoint(x: 456, y: 0)) ctx.addLine(to: CGPoint(x: 728, y: -738)) ctx.addLine(to: CGPoint(x: 572, y: -738)) ctx.addLine(to: CGPoint(x: 378, y: -156)) ctx.addLine(to: CGPoint(x: 376, y: -156)) ctx.addLine(to: CGPoint(x: 184, y: -738)) ctx.addLine(to: CGPoint(x: 10, y: -738)) ctx.addLine(to: CGPoint(x: 282, y: 0)) ctx.addLine(to: CGPoint(x: 456, y: 0)) ctx.closePath() } private func def_path_14(_ ctx: CGContext) { ctx.move(to: CGPoint(x: 538, y: -249)) ctx.addLine(to: CGPoint(x: 537, y: -273)) ctx.addLine(to: CGPoint(x: 534, y: -314)) ctx.addQuadCurve(to: CGPoint(x: 508, y: -406), control: CGPoint(x: 528, y: -363.5)) ctx.addQuadCurve(to: CGPoint(x: 288, y: -528), control: CGPoint(x: 449, y: -529)) ctx.addQuadCurve(to: CGPoint(x: 42, y: -256), control: CGPoint(x: 55, y: -515.5)) ctx.addQuadCurve(to: CGPoint(x: 288, y: 13), control: CGPoint(x: 39, y: 15.5)) ctx.addQuadCurve(to: CGPoint(x: 522, y: -152), control: CGPoint(x: 503, y: 12.5)) ctx.addLine(to: CGPoint(x: 384, y: -152)) ctx.addQuadCurve(to: CGPoint(x: 288, y: -86), control: CGPoint(x: 363, y: -83.5)) ctx.addQuadCurve(to: CGPoint(x: 200, y: -216), control: CGPoint(x: 195.5, y: -83)) ctx.addLine(to: CGPoint(x: 538, y: -216)) ctx.addLine(to: CGPoint(x: 538, y: -249)) ctx.closePath() ctx.move(to: CGPoint(x: 288, y: -426)) ctx.addQuadCurve(to: CGPoint(x: 378, y: -318), control: CGPoint(x: 380.5, y: -427)) ctx.addLine(to: CGPoint(x: 200, y: -318)) ctx.addQuadCurve(to: CGPoint(x: 288, y: -426), control: CGPoint(x: 202.5, y: -427)) ctx.closePath() } private func def_path_15(_ ctx: CGContext) { ctx.move(to: CGPoint(x: 312, y: -528)) ctx.addQuadCurve(to: CGPoint(x: 44, y: -256), control: CGPoint(x: 55.5, y: -517)) ctx.addQuadCurve(to: CGPoint(x: 312, y: 13), control: CGPoint(x: 55, y: 2.5)) ctx.addQuadCurve(to: CGPoint(x: 580, y: -256), control: CGPoint(x: 569, y: 2.5)) ctx.addQuadCurve(to: CGPoint(x: 312, y: -528), control: CGPoint(x: 568.5, y: -517)) ctx.closePath() ctx.move(to: CGPoint(x: 312, y: -426)) ctx.addQuadCurve(to: CGPoint(x: 422, y: -256), control: CGPoint(x: 424, y: -427)) ctx.addQuadCurve(to: CGPoint(x: 312, y: -86), control: CGPoint(x: 424, y: -85)) ctx.addQuadCurve(to: CGPoint(x: 202, y: -256), control: CGPoint(x: 200, y: -85)) ctx.addQuadCurve(to: CGPoint(x: 312, y: -426), control: CGPoint(x: 200, y: -427)) ctx.closePath() } private func def_path_16(_ ctx: CGContext) { ctx.move(to: CGPoint(x: 310, y: -426)) ctx.addQuadCurve(to: CGPoint(x: 420, y: -256), control: CGPoint(x: 411.5, y: -420)) ctx.addQuadCurve(to: CGPoint(x: 310, y: -86), control: CGPoint(x: 411.5, y: -92)) ctx.addQuadCurve(to: CGPoint(x: 198, y: -256), control: CGPoint(x: 194.5, y: -84.5)) ctx.addQuadCurve(to: CGPoint(x: 310, y: -426), control: CGPoint(x: 194.5, y: -427.5)) ctx.closePath() ctx.move(to: CGPoint(x: 418, y: -454)) ctx.addQuadCurve(to: CGPoint(x: 280, y: -528), control: CGPoint(x: 366, y: -524)) ctx.addQuadCurve(to: CGPoint(x: 40, y: -256), control: CGPoint(x: 56.5, y: -515.5)) ctx.addQuadCurve(to: CGPoint(x: 103, y: -60), control: CGPoint(x: 47.5, y: -127)) ctx.addQuadCurve(to: CGPoint(x: 262, y: 13), control: CGPoint(x: 158.5, y: 7)) ctx.addQuadCurve(to: CGPoint(x: 418, y: -72), control: CGPoint(x: 372, y: 12)) ctx.addLine(to: CGPoint(x: 420, y: -72)) ctx.addLine(to: CGPoint(x: 424, y: 0)) ctx.addLine(to: CGPoint(x: 578, y: 0)) ctx.addLine(to: CGPoint(x: 574, y: -102)) ctx.addLine(to: CGPoint(x: 574, y: -738)) ctx.addLine(to: CGPoint(x: 420, y: -738)) ctx.addLine(to: CGPoint(x: 420, y: -454)) ctx.addLine(to: CGPoint(x: 418, y: -454)) ctx.closePath() } private func draw_main(_ ctx: CGContext) { ctx.saveGState() ctx.concatenate(CGAffineTransform(a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0)) def_path_0(ctx) ctx.clip(using: .evenOdd) ctx.concatenate(CGAffineTransform(a: 0.109375, b: 0, c: 0, d: 0.109375, tx: 469.45, ty: 126)) draw_gradient_0(ctx) ctx.restoreGState() ctx.saveGState() ctx.concatenate(CGAffineTransform(a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0)) def_path_1(ctx) ctx.clip(using: .evenOdd) ctx.concatenate(CGAffineTransform(a: 0.0714111, b: 0, c: 0, d: 0.0701599, tx: 480.45, ty: 302.45)) draw_gradient_1(ctx) ctx.restoreGState() ctx.saveGState() ctx.setFillColor(red: 0.8, green: 0.2, blue: 0.6, alpha: 1) def_path_2(ctx) ctx.drawPath(using: .eoFill) ctx.restoreGState() ctx.saveGState() ctx.setStrokeColor(red: 0.2, green: 1, blue: 0.4, alpha: 1) ctx.setLineWidth(1) ctx.setLineCap(.round) ctx.setLineJoin(.round) def_path_3(ctx) ctx.drawPath(using: .stroke) ctx.restoreGState() ctx.saveGState() ctx.setStrokeColor(red: 0.2, green: 1, blue: 0.4, alpha: 1) ctx.setLineWidth(1) ctx.setLineCap(.round) ctx.setLineJoin(.round) def_path_4(ctx) ctx.drawPath(using: .stroke) ctx.restoreGState() ctx.saveGState() ctx.concatenate(CGAffineTransform(a: 1, b: 0, c: 0, d: 1, tx: 39.35, ty: 16.75)) draw_shape_2(ctx, nil) ctx.restoreGState() do { ctx.saveGState() ctx.concatenate(CGAffineTransform(a: 1, b: 0, c: 0, d: 1, tx: 217.65, ty: 16.75)) let colorTrans : TKColorTransform = [ 0.462745, 0.462745, 0.462745, 1.00392, 0, 0, 0, 0 ]; draw_shape_2(ctx, colorTrans) ctx.restoreGState() } ctx.saveGState() ctx.concatenate(CGAffineTransform(a: 1, b: 0, c: 0, d: 1, tx: 94.55, ty: 165.05)) draw_shape_4(ctx, nil) ctx.restoreGState() do { ctx.saveGState() ctx.concatenate(CGAffineTransform(a: 1, b: 0, c: 0, d: 1, tx: 238.55, ty: 181)) let colorTrans : TKColorTransform = [ 0.239216, 0.239216, 0.239216, 1.00392, 0.698039, 0.0588235, 0.760784, 0 ]; draw_shape_4(ctx, colorTrans) ctx.restoreGState() } ctx.saveGState() ctx.concatenate(CGAffineTransform(a: 0.0351562, b: 0, c: 0, d: 0.0351562, tx: 26.55, ty: 371.85)) ctx.setFillColor(red: 0.8, green: 0.2, blue: 0.6, alpha: 1) def_path_7(ctx) ctx.drawPath(using: .eoFill) ctx.restoreGState() ctx.saveGState() ctx.concatenate(CGAffineTransform(a: 0.0351562, b: 0, c: 0, d: 0.0351562, tx: 52.45, ty: 371.85)) ctx.setFillColor(red: 0.8, green: 0.2, blue: 0.6, alpha: 1) def_path_8(ctx) ctx.drawPath(using: .eoFill) ctx.restoreGState() ctx.saveGState() ctx.concatenate(CGAffineTransform(a: 0.0351562, b: 0, c: 0, d: 0.0351562, tx: 74.35, ty: 371.85)) ctx.setFillColor(red: 0.8, green: 0.2, blue: 0.6, alpha: 1) def_path_9(ctx) ctx.drawPath(using: .eoFill) ctx.restoreGState() ctx.saveGState() ctx.concatenate(CGAffineTransform(a: 0.0351562, b: 0, c: 0, d: 0.0351562, tx: 108.3, ty: 371.85)) ctx.setFillColor(red: 0.8, green: 0.2, blue: 0.6, alpha: 1) def_path_10(ctx) ctx.drawPath(using: .eoFill) ctx.restoreGState() ctx.saveGState() ctx.concatenate(CGAffineTransform(a: 0.0351562, b: 0, c: 0, d: 0.0351562, tx: 140.15, ty: 371.85)) ctx.setFillColor(red: 0.8, green: 0.8, blue: 0, alpha: 1) def_path_7(ctx) ctx.drawPath(using: .eoFill) ctx.restoreGState() ctx.saveGState() ctx.concatenate(CGAffineTransform(a: 0.0351562, b: 0, c: 0, d: 0.0351562, tx: 166.05, ty: 371.85)) ctx.setFillColor(red: 0.8, green: 0.8, blue: 0, alpha: 1) def_path_8(ctx) ctx.drawPath(using: .eoFill) ctx.restoreGState() ctx.saveGState() ctx.concatenate(CGAffineTransform(a: 0.0351562, b: 0, c: 0, d: 0.0351562, tx: 187.95, ty: 371.85)) ctx.setFillColor(red: 0.8, green: 0.8, blue: 0, alpha: 1) def_path_11(ctx) ctx.drawPath(using: .eoFill) ctx.restoreGState() ctx.saveGState() ctx.concatenate(CGAffineTransform(a: 0.0351562, b: 0, c: 0, d: 0.0351562, tx: 205.95, ty: 371.85)) ctx.setFillColor(red: 0.8, green: 0.8, blue: 0, alpha: 1) def_path_12(ctx) ctx.drawPath(using: .eoFill) ctx.restoreGState() ctx.saveGState() ctx.concatenate(CGAffineTransform(a: 0.0351562, b: 0, c: 0, d: 0.0351562, tx: 235.85, ty: 371.85)) ctx.setFillColor(red: 1, green: 0.2, blue: 0, alpha: 1) def_path_13(ctx) ctx.drawPath(using: .eoFill) ctx.restoreGState() ctx.saveGState() ctx.concatenate(CGAffineTransform(a: 0.0351562, b: 0, c: 0, d: 0.0351562, tx: 261.75, ty: 371.85)) ctx.setFillColor(red: 1, green: 0.2, blue: 0, alpha: 1) def_path_14(ctx) ctx.drawPath(using: .eoFill) ctx.restoreGState() ctx.saveGState() ctx.concatenate(CGAffineTransform(a: 0.0351562, b: 0, c: 0, d: 0.0351562, tx: 281.7, ty: 371.85)) ctx.setFillColor(red: 1, green: 0.2, blue: 0, alpha: 1) def_path_11(ctx) ctx.drawPath(using: .eoFill) ctx.restoreGState() ctx.saveGState() ctx.concatenate(CGAffineTransform(a: 0.0351562, b: 0, c: 0, d: 0.0351562, tx: 299.7, ty: 371.85)) ctx.setFillColor(red: 1, green: 0.2, blue: 0, alpha: 1) def_path_15(ctx) ctx.drawPath(using: .eoFill) ctx.restoreGState() ctx.saveGState() ctx.concatenate(CGAffineTransform(a: 0.0351562, b: 0, c: 0, d: 0.0351562, tx: 321.6, ty: 371.85)) ctx.setFillColor(red: 1, green: 0.2, blue: 0, alpha: 1) def_path_16(ctx) ctx.drawPath(using: .eoFill) ctx.restoreGState() ctx.saveGState() ctx.concatenate(CGAffineTransform(a: 0.0351562, b: 0, c: 0, d: 0.0351562, tx: 343.5, ty: 371.85)) ctx.setFillColor(red: 1, green: 0.2, blue: 0, alpha: 1) def_path_14(ctx) ctx.drawPath(using: .eoFill) ctx.restoreGState() }
83800632d0fba573f3b7ffc4a1178ffa
39.02439
155
0.617997
false
false
false
false
orta/Moya
refs/heads/master
Moya/ReactiveCocoa/Moya+ReactiveCocoa.swift
mit
1
import Foundation import ReactiveCocoa /// Subclass of MoyaProvider that returns RACSignal instances when requests are made. Much better than using completion closures. public class ReactiveCocoaMoyaProvider<T where T: MoyaTarget>: MoyaProvider<T> { /// Current requests that have not completed or errored yet. /// Note: Do not access this directly. It is public only for unit-testing purposes (sigh). public var inflightRequests = Dictionary<Endpoint<T>, RACSignal>() /// Initializes a reactive provider. override public init(endpointClosure: MoyaEndpointsClosure = MoyaProvider.DefaultEndpointMapping, endpointResolver: MoyaEndpointResolution = MoyaProvider.DefaultEnpointResolution, stubBehavior: MoyaStubbedBehavior = MoyaProvider.NoStubbingBehavior, networkActivityClosure: Moya.NetworkActivityClosure? = nil) { super.init(endpointClosure: endpointClosure, endpointResolver: endpointResolver, stubBehavior: stubBehavior, networkActivityClosure: networkActivityClosure) } /// Designated request-making method. public func request(token: T) -> RACSignal { let endpoint = self.endpoint(token) // weak self just for best practices – RACSignal will take care of any retain cycles anyway, // and we're connecting immediately (below), so self in the block will always be non-nil return RACSignal.`defer` { [weak self] () -> RACSignal! in if let weakSelf = self { objc_sync_enter(weakSelf) let inFlight = weakSelf.inflightRequests[endpoint] objc_sync_exit(weakSelf) if let existingSignal = inFlight { return existingSignal } } let signal = RACSignal.createSignal { (subscriber) -> RACDisposable! in let cancellableToken = self?.request(token) { data, statusCode, response, error in if let error = error { if let statusCode = statusCode { subscriber.sendError(NSError(domain: MoyaErrorDomain, code: statusCode, userInfo: [NSUnderlyingErrorKey: error as NSError])) } else { subscriber.sendError(error as NSError) } } else { if let data = data { subscriber.sendNext(MoyaResponse(statusCode: statusCode!, data: data, response: response)) } subscriber.sendCompleted() } } return RACDisposable { () -> Void in if let weakSelf = self { objc_sync_enter(weakSelf) weakSelf.inflightRequests[endpoint] = nil cancellableToken?.cancel() objc_sync_exit(weakSelf) } } }.publish().autoconnect() if let weakSelf = self { objc_sync_enter(weakSelf) weakSelf.inflightRequests[endpoint] = signal objc_sync_exit(weakSelf) } return signal } } }
f59b473b1d16776e7d726f08317cddf0
47.602941
314
0.57761
false
false
false
false
RobinChao/OpenAppleApps
refs/heads/master
OpenAppleApp/OpenAppleApp/OpenAPP.swift
mit
1
import UIKit import Foundation class OpenAPP { static func openiBooks() { self.openURL("itms-bookss://") } static func openiBooks(ISBN isbn: String) { self.openURL("itms-bookss://itunes.apple.com/book/isbn\(isbn)") } static func openiBooks(ibooksbookid bookid: String) { self.openURL("itms-bookss://itunes.apple.com/book/id\(bookid)") } static func openAppStore() { self.openURL("itms-apps://") } static func openAppStore(appid id: String) { self.openURL("itms-apps://itunes.apple.com/app/pages/id\(id)") } static func openPhotoLibary() { self.openURL("photos-redirect://") } static func openMap(query q: String) { self.openURL("http://maps.apple.com/?q=\(q)") } static func openMap(address address: String){ self.openURL("http://maps.apple.com/?address=\(address)") } static func openMap(location ll: String){ self.openURL("http://maps.apple.com/?ll=\(ll)") } static func openPhone(phone number: String) { self.openURL("tel:\(number)") } static func openSafari(URL url: String) { self.openURL(url) } static func openMail(mailto to: String, subject: String, body: String){ self.openURL("mailto:\(to)?subject=\(subject)&body=\(body)") } static func openSetting() { self.openURL(UIApplicationOpenSettingsURLString) } static func openSMS() { self.openURL("sms:") } static func openSMS(phone number: String) { self.openURL("sms:\(number)") } static func openFaceTime(){ self.openURL("facetime:") } static func openFaceTime(call call: String){ self.openURL("facetime://\(call)") } static func openFaceTimeAudio(){ self.openURL("facetime-audio:") } static func openFaceTimeAudio(call call: String){ self.openURL("facetime-audio://\(call)") } static func openURL(URLString: String) { if UIApplication.sharedApplication().canOpenURL(NSURL(string: URLString)!) { UIApplication.sharedApplication().openURL(NSURL(string: URLString)!) }else{ print("didn't open \(URLString)") } } }
3e118ac076a5e6d0a07e9ea92cf09196
24.736264
85
0.58522
false
false
false
false
yanif/circator
refs/heads/master
MetabolicCompass/Model/SampleDataAnalyzer.swift
apache-2.0
1
// // SampleDataAnalyzer.swift // MetabolicCompass // // Created by Sihao Lu on 10/24/15. // Copyright © 2015 Yanif Ahmad, Tom Woolf. All rights reserved. // import UIKit import MetabolicCompassKit import HealthKit import Charts import SwiftDate import MCCircadianQueries enum PlotSpec { case PlotPredicate(String, NSPredicate!) case PlotFasting } class SampleDataAnalyzer: NSObject { static let sampleFormatter = SampleFormatter() } /** We use this class to put data into the right format for all of the plots. The exact approach to how the data is input for the charts will depend on the charting library. But, the general need for this type of transformation (reading from the data stores and putting things into the right format) will be needed for any data that is analyzed by the user. - note: current format is set by our use of the Charts library */ class CorrelationDataAnalyzer: SampleDataAnalyzer { let labels: [String] let samples: [[MCSample]] let values: [[(NSDate, Double)]] let zipped: [(NSDate, Double, MCSample)] var dataSetConfigurators: [((LineChartDataSet) -> Void)?] = [] init?(labels: [String], samples: [[MCSample]]) { guard labels.count == 2 && samples.count == 2 else { self.labels = [] self.samples = [] self.values = [] self.zipped = [] super.init() return nil } self.labels = labels self.samples = samples self.values = [] self.zipped = [] super.init() } init?(labels: [String], values: [[(NSDate, Double)]]) { guard labels.count == 2 && values.count == 2 else { self.labels = [] self.samples = [] self.values = [] self.zipped = [] super.init() return nil } self.labels = labels self.samples = [] self.values = values self.zipped = [] super.init() } init?(labels: [String], zipped: [(NSDate, Double, MCSample)]) { guard labels.count == 2 else { self.labels = [] self.samples = [] self.values = [] self.zipped = [] super.init() return nil } self.labels = labels self.samples = [] self.values = [] self.zipped = zipped super.init() } var correlationChartData: LineChartData { if !samples.isEmpty { let firstParamEntries = samples[0].enumerate().map { (i, stats) -> ChartDataEntry in return ChartDataEntry(value: stats.numeralValue!, xIndex: i + 1) } let firstParamDataSet = LineChartDataSet(yVals: firstParamEntries, label: labels[0]) dataSetConfigurators[0]?(firstParamDataSet) let secondParamEntries = samples[1].enumerate().map { (i, stats) -> ChartDataEntry in return ChartDataEntry(value: stats.numeralValue!, xIndex: i + 1) } let secondParamDataSet = LineChartDataSet(yVals: secondParamEntries, label: labels[1]) dataSetConfigurators[1]?(secondParamDataSet) return LineChartData(xVals: Array(0...samples[0].count + 1), dataSets: [firstParamDataSet, secondParamDataSet]) } else if !values.isEmpty { let firstParamEntries = values[0].enumerate().map { (i, s) -> ChartDataEntry in return ChartDataEntry(value: s.1, xIndex: i + 1) } let firstParamDataSet = LineChartDataSet(yVals: firstParamEntries, label: labels[0]) dataSetConfigurators[0]?(firstParamDataSet) let secondParamEntries = values[1].enumerate().map { (i, s) -> ChartDataEntry in return ChartDataEntry(value: s.1, xIndex: i + 1) } let secondParamDataSet = LineChartDataSet(yVals: secondParamEntries, label: labels[1]) dataSetConfigurators[1]?(secondParamDataSet) return LineChartData(xVals: Array(0...values[0].count + 1), dataSets: [firstParamDataSet, secondParamDataSet]) } else { let firstParamEntries = zipped.enumerate().map { (i, s) -> ChartDataEntry in return ChartDataEntry(value: s.1, xIndex: i + 1) } let firstParamDataSet = LineChartDataSet(yVals: firstParamEntries, label: labels[0]) dataSetConfigurators[0]?(firstParamDataSet) let secondParamEntries = zipped.enumerate().map { (i, s) -> ChartDataEntry in return ChartDataEntry(value: s.2.numeralValue!, xIndex: i + 1) } let secondParamDataSet = LineChartDataSet(yVals: secondParamEntries, label: labels[1]) dataSetConfigurators[1]?(secondParamDataSet) return LineChartData(xVals: Array(0...zipped.count + 1), dataSets: [firstParamDataSet, secondParamDataSet]) } } } /** To prepare data for plots (1st button on left) - note: format set by Charts library; summary statistics are in BubbleChart */ class PlotDataAnalyzer: SampleDataAnalyzer { let sampleType: HKSampleType let samples: [MCSample] let values: [(NSDate, Double)] init(sampleType: HKSampleType, samples: [MCSample]) { self.sampleType = sampleType self.samples = samples self.values = [] super.init() } init(sampleType: HKSampleType, values: [(NSDate, Double)]) { self.sampleType = sampleType self.samples = [] self.values = values super.init() } enum DataGroupingMode { case ByInstance case ByDate } var dataGroupingMode: DataGroupingMode = .ByDate var dataSetConfigurator: ((LineChartDataSet) -> Void)? var dataSetConfiguratorBubbleChart: ((BubbleChartDataSet) -> Void)? var lineChartData: LineChartData { guard !(samples.isEmpty && values.isEmpty) else { return LineChartData(xVals: [""]) } if dataGroupingMode == .ByDate { var xVals: [String] = [] var entries: [ChartDataEntry] = [] if !samples.isEmpty { (xVals, entries) = lineFromSamples() } else { (xVals, entries) = lineFromValues() } let dataSet = LineChartDataSet(yVals: entries, label: "") dataSetConfigurator?(dataSet) return LineChartData(xVals: xVals, dataSet: dataSet) } else if !samples.isEmpty { let xVals: [String] = samples.map { (sample) -> String in return SampleFormatter.chartDateFormatter.stringFromDate(sample.startDate) } var index = 0 let entries: [ChartDataEntry] = samples.map { (sample) -> ChartDataEntry in index += 1 return ChartDataEntry(value: sample.numeralValue!, xIndex: index-1) } let dataSet = LineChartDataSet(yVals: entries, label: "") dataSetConfigurator?(dataSet) return LineChartData(xVals: xVals, dataSet: dataSet) } else { let xVals: [String] = values.map { return SampleFormatter.chartDateFormatter.stringFromDate($0.0) } var index = 0 let entries: [ChartDataEntry] = values.map { index += 1 return ChartDataEntry(value: $0.1, xIndex: index-1) } let dataSet = LineChartDataSet(yVals: entries, label: "") dataSetConfigurator?(dataSet) return LineChartData(xVals: xVals, dataSet: dataSet) } } /// for summary data -- in sets of 20% ordered from min to max -- var bubbleChartData: BubbleChartData { guard !(samples.isEmpty && values.isEmpty) else { return BubbleChartData(xVals: [""]) } if dataGroupingMode == .ByDate { var dataEntries: [BubbleChartDataEntry] = [] let summaryData: [Double] = !samples.isEmpty ? samples.map { return $0.numeralValue ?? 0.0 } : values.map { return $0.1 } let summaryDataSorted = summaryData.sort() guard !summaryData.isEmpty else { return BubbleChartData(xVals: [String](), dataSet: nil) } let xVals = ["Min", "1st", "2nd", "3rd", "4th", "Last 5th", "Max"] dataEntries.append(BubbleChartDataEntry(xIndex: 0, value: summaryDataSorted[0], size: CGFloat(summaryDataSorted[0]))) for partition in 1...5 { let prevFifth = summaryDataSorted.count / 5 * (partition - 1) let fifth = summaryDataSorted.count / 5 * partition let sum = summaryDataSorted[prevFifth..<fifth].reduce(0) { $0 + $1 } guard sum > 0 else { continue } let average = sum / Double(fifth - prevFifth) dataEntries.append(BubbleChartDataEntry(xIndex: partition, value: average, size: CGFloat(average))) } dataEntries.append(BubbleChartDataEntry(xIndex: 6, value: summaryDataSorted.last!, size: CGFloat(summaryDataSorted.last!))) let dataSet = BubbleChartDataSet(yVals: dataEntries) dataSetConfiguratorBubbleChart?(dataSet) return BubbleChartData(xVals: xVals, dataSet: dataSet) } else if !samples.isEmpty { let xVals : [String] = samples.map { (sample) -> String in return SampleFormatter.chartDateFormatter.stringFromDate(sample.startDate) } var index = 0 let summaryData : [ChartDataEntry] = samples.map { (sample) -> ChartDataEntry in index += 1 return ChartDataEntry(value: sample.numeralValue!, xIndex: index-1) } let dataSet = BubbleChartDataSet(yVals: summaryData) dataSetConfiguratorBubbleChart?(dataSet) return BubbleChartData(xVals: xVals, dataSet: dataSet) } else { let xVals : [String] = values.map { (sample) -> String in return SampleFormatter.chartDateFormatter.stringFromDate(sample.0) } var index = 0 let summaryData : [ChartDataEntry] = values.map { (sample) -> ChartDataEntry in index += 1 return ChartDataEntry(value: sample.1, xIndex: index-1) } let dataSet = BubbleChartDataSet(yVals: summaryData) dataSetConfiguratorBubbleChart?(dataSet) return BubbleChartData(xVals: xVals, dataSet: dataSet) } } var summaryData: Double { guard !(samples.isEmpty && values.isEmpty) else { return 0.0 } let summaryData : [Double] = !samples.isEmpty ? samples.map { return $0.numeralValue! } : values.map { return $0.1 } return summaryData.sort().first! } func enumerateDates(startDate: NSDate, endDate: NSDate) -> [NSDate] { let zeroDate = startDate.startOf(.Day, inRegion: Region()) - 1.days let finalDate = endDate.startOf(.Day, inRegion: Region()) + 1.days var currentDate = zeroDate var dates: [NSDate] = [] while currentDate <= finalDate { currentDate = currentDate + 1.days dates.append(currentDate) } return dates } func datesFromSamples() -> [NSDate] { let firstDate = samples.first!.startDate let lastDate = samples.last!.startDate return enumerateDates(firstDate, endDate: lastDate) } func datesFromValues() -> [NSDate] { let firstDate = values.first!.0 let lastDate = values.last!.0 return enumerateDates(firstDate, endDate: lastDate) } func lineFromSamples() -> ([String], [ChartDataEntry]) { let dates = datesFromSamples() let zeroDate = dates.first! let xVals: [String] = dates.map { (date) -> String in SampleFormatter.chartDateFormatter.stringFromDate(date) } let entries: [ChartDataEntry] = samples.map { (sample) -> ChartDataEntry in let dayDiff = zeroDate.difference(sample.startDate.startOf(.Day, inRegion: Region()), unitFlags: .Day) let val = sample.numeralValue ?? 0.0 return ChartDataEntry(value: val, xIndex: dayDiff!.day) } return (xVals, entries) } func lineFromValues() -> ([String], [ChartDataEntry]) { let dates = datesFromValues() let zeroDate = dates.first! let xVals: [String] = dates.map { (date) -> String in SampleFormatter.chartDateFormatter.stringFromDate(date) } let entries: [ChartDataEntry] = values.map { (sample) -> ChartDataEntry in let dayDiff = zeroDate.difference(sample.0.startOf(.Day, inRegion: Region()), unitFlags: .Day) return ChartDataEntry(value: sample.1, xIndex: dayDiff!.day) } return (xVals, entries) } }
ccd98d142a9014595dc976978f34de1e
38.129129
355
0.595318
false
false
false
false
JGiola/swift
refs/heads/main
test/IRGen/associated_type_witness.swift
apache-2.0
9
// RUN: %target-swift-frontend -primary-file %s -emit-ir > %t.ll // RUN: %FileCheck %s -check-prefix=GLOBAL < %t.ll // RUN: %FileCheck %s < %t.ll // RUN: %target-swift-frontend -primary-file %s -emit-ir -wmo -num-threads 1 > %t.ll.wmo // RUN: %FileCheck %s -check-prefix=GLOBAL < %t.ll.wmo // RUN: %FileCheck %s < %t.ll.wmo // REQUIRES: CPU=x86_64 protocol P {} protocol Q {} protocol Assocked { associatedtype Assoc : P, Q } struct Universal : P, Q {} // CHECK-LABEL: @"symbolic _____ 23associated_type_witness12OuterPrivate{{.*}}InnermostV" = linkonce_odr hidden constant // CHECK-SAME: @"$s23associated_type_witness12OuterPrivate{{.*}}5InnerE0V9InnermostVMn" private struct OuterPrivate { struct InnerPrivate: HasSimpleAssoc { struct Innermost { } typealias Assoc = Innermost } } // CHECK: [[ASSOC_TYPE_NAMES:@.*]] = private constant [29 x i8] c"OneAssoc TwoAssoc ThreeAssoc\00" // CHECK: @"$s23associated_type_witness18HasThreeAssocTypesMp" = // CHECK-SAME: [[ASSOC_TYPE_NAMES]] to i64 protocol HasThreeAssocTypes { associatedtype OneAssoc associatedtype TwoAssoc associatedtype ThreeAssoc } // Witness table for WithUniversal : Assocked. // GLOBAL-LABEL: @"$s23associated_type_witness13WithUniversalVAA8AssockedAAWP" = hidden global [4 x i8*] [ // GLOBAL-SAME: @"$s23associated_type_witness13WithUniversalVAA8AssockedAAMc" // GLOBAL-SAME: @"associated conformance 23associated_type_witness13WithUniversalVAA8AssockedAA5AssocAaDP_AA1P", // GLOBAL-SAME: @"associated conformance 23associated_type_witness13WithUniversalVAA8AssockedAA5AssocAaDP_AA1Q" // GLOBAL-SAME: @"symbolic{{.*}}23associated_type_witness9UniversalV" // GLOBAL-SAME: ] struct WithUniversal : Assocked { typealias Assoc = Universal } // Witness table for GenericWithUniversal : Assocked. // GLOBAL-LABEL: @"$s23associated_type_witness20GenericWithUniversalVyxGAA8AssockedAAWP" = hidden global [4 x i8*] [ // GLOBAL-SAME: @"$s23associated_type_witness20GenericWithUniversalVyxGAA8AssockedAAMc" // GLOBAL-SAME: @"associated conformance 23associated_type_witness20GenericWithUniversalVyxGAA8AssockedAA5AssocAaEP_AA1P" // GLOBAL-SAME: @"associated conformance 23associated_type_witness20GenericWithUniversalVyxGAA8AssockedAA5AssocAaEP_AA1Q" // GLOBAL-SAME: @"symbolic{{.*}}23associated_type_witness9UniversalV" // GLOBAL-SAME: ] struct GenericWithUniversal<T> : Assocked { typealias Assoc = Universal } // Witness table for Fulfilled : Assocked. // GLOBAL-LABEL: @"$s23associated_type_witness9FulfilledVyxGAA8AssockedAAWp" = internal global [4 x i8*] [ // GLOBAL-SAME: @"$s23associated_type_witness9FulfilledVyxGAA8AssockedAAMc" // GLOBAL-SAME: @"associated conformance 23associated_type_witness9FulfilledVyxGAA8AssockedAA5AssocAaEP_AA1P" // GLOBAL-SAME: @"associated conformance 23associated_type_witness9FulfilledVyxGAA8AssockedAA5AssocAaEP_AA1Q" // GLOBAL-SAME: @"symbolic x" // GLOBAL-SAME: ] struct Fulfilled<T : P & Q> : Assocked { typealias Assoc = T } // Associated type witness table access function for Fulfilled.Assoc : P. // CHECK-LABEL: define internal swiftcc i8** @"$s23associated_type_witness9FulfilledVyxGAA8AssockedAA5AssocAaEP_AA1PPWT"(%swift.type* %"Fulfilled<T>.Assoc", %swift.type* %"Fulfilled<T>", i8** %"Fulfilled<T>.Assocked") // CHECK: [[T0:%.*]] = bitcast %swift.type* %"Fulfilled<T>" to i8*** // CHECK-NEXT: [[T1:%.*]] = getelementptr inbounds i8**, i8*** [[T0]], i64 3 // CHECK-NEXT: [[T2:%.*]] = load i8**, i8*** [[T1]], align 8, !invariant.load // CHECK-NEXT: ret i8** [[T2]] // Associated type witness table access function for Fulfilled.Assoc : Q. // CHECK-LABEL: define internal swiftcc i8** @"$s23associated_type_witness9FulfilledVyxGAA8AssockedAA5AssocAaEP_AA1QPWT"(%swift.type* %"Fulfilled<T>.Assoc", %swift.type* %"Fulfilled<T>", i8** %"Fulfilled<T>.Assocked") // CHECK: [[T0:%.*]] = bitcast %swift.type* %"Fulfilled<T>" to i8*** // CHECK-NEXT: [[T1:%.*]] = getelementptr inbounds i8**, i8*** [[T0]], i64 4 // CHECK-NEXT: [[T2:%.*]] = load i8**, i8*** [[T1]], align 8, !invariant.load // CHECK-NEXT: ret i8** [[T2]] struct Pair<T, U> : P, Q {} // Generic witness table pattern for Computed : Assocked. // GLOBAL-LABEL: @"$s23associated_type_witness8ComputedVyxq_GAA8AssockedAAWp" = internal global [4 x i8*] [ // GLOBAL-SAME: @"$s23associated_type_witness8ComputedVyxq_GAA8AssockedAAMc" // GLOBAL-SAME: @"associated conformance 23associated_type_witness8ComputedVyxq_GAA8AssockedAA5AssocAaEP_AA1P" // GLOBAL-SAME: @"associated conformance 23associated_type_witness8ComputedVyxq_GAA8AssockedAA5AssocAaEP_AA1Q" // GLOBAL-SAME: @"symbolic{{.*}}23associated_type_witness4PairV{{.*}}" // GLOBAL-SAME: ] // Protocol conformance descriptor for Computed : Assocked. // GLOBAL-LABEL: @"$s23associated_type_witness8ComputedVyxq_GAA8AssockedAAMc" = hidden constant // GLOBAL-SAME: i16 4, // GLOBAL-SAME: i16 1, // No instantiator function // GLOBAL-SAME: i32 0, // GLOBAL-SAME: i32 trunc (i64 sub (i64 ptrtoint ([16 x i8*]* [[PRIVATE:@.*]] to i64), i64 ptrtoint // GLOBAL-SAME: } struct Computed<T, U> : Assocked { typealias Assoc = Pair<T, U> } // Instantiation function for GenericComputed : DerivedFromSimpleAssoc. // CHECK-LABEL: define internal void @"$s23associated_type_witness15GenericComputedVyxGAA22DerivedFromSimpleAssocAAWI"(i8** %0, %swift.type* %"GenericComputed<T>", i8** %1) // CHECK: [[T0:%.*]] = call i8** @swift_getWitnessTable({{.*}}@"$s23associated_type_witness15GenericComputedVyxGAA14HasSimpleAssocAAMc" // CHECK-NEXT: [[T1:%.*]] = bitcast i8** [[T0]] to i8* // CHECK-NEXT: [[T2:%.*]] = getelementptr inbounds i8*, i8** %0, i32 1 // CHECK-NEXT: store i8* [[T1]], i8** [[T2]], align 8 // CHECK-NEXT: ret void struct PBox<T: P> {} protocol HasSimpleAssoc { associatedtype Assoc } protocol DerivedFromSimpleAssoc : HasSimpleAssoc {} // Generic witness table pattern for GenericComputed : DerivedFromSimpleAssoc. // GLOBAL-LABEL: @"$s23associated_type_witness15GenericComputedVyxGAA22DerivedFromSimpleAssocAAWp" = internal constant [2 x i8*] // GLOBAL-SAME: @"$s23associated_type_witness15GenericComputedVyxGAA22DerivedFromSimpleAssocAAMc" // GLOBAL-SAME: i8* null // Protocol conformance descriptor for GenericComputed : DerivedFromSimpleAssoc. // GLOBAL-LABEL: @"$s23associated_type_witness15GenericComputedVyxGAA22DerivedFromSimpleAssocAAMc" = hidden constant // GLOBAL-SAME: i16 2, // GLOBAL-SAME: i16 1, // Relative reference to instantiator function // GLOBAL-SAME: i32 trunc (i64 sub (i64 ptrtoint (void (i8**, %swift.type*, i8**)* @"$s23associated_type_witness15GenericComputedVyxGAA22DerivedFromSimpleAssocAAWI" to i64), // Relative reference to private data struct GenericComputed<T: P> : DerivedFromSimpleAssoc { typealias Assoc = PBox<T> } protocol HasAssocked { associatedtype Contents : Assocked } struct FulfilledFromAssociatedType<T : HasAssocked> : HasSimpleAssoc { typealias Assoc = PBox<T.Contents.Assoc> } struct UsesVoid : HasSimpleAssoc { typealias Assoc = () } // SR-11642: Failure to canonicalize type in associated type witness. struct Validator<T> { let validatorFailureType: Any.Type } protocol ValidatorType { associatedtype Data associatedtype Failure func validator() -> Validator<Data> } extension ValidatorType { func validator() -> Validator<Data> { .init(validatorFailureType: Failure.self) } } // MARK: Failing example extension Validator where T == String { struct V: ValidatorType { typealias Data = T // or String struct Failure {} } } // GLOBAL-LABEL: @"symbolic _____ySS__G 23associated_type_witness9ValidatorVAASSRszlE1VV7FailureV"
8a9f1427e038005f139f8e8f37bbd92b
40.875676
218
0.723248
false
false
false
false
louisdh/panelkit
refs/heads/master
PanelKit/Controller/PanelViewController+Offscreen.swift
mit
1
// // PanelViewController+Offscreen.swift // PanelKit // // Created by Louis D'hauwe on 09/03/2017. // Copyright © 2017 Silver Fox. All rights reserved. // import UIKit extension PanelViewController { func prepareMoveOffScreen() { position = view?.center } func movePanelOffScreen() { guard let viewToMove = self.view else { return } guard let superView = viewToMove.superview else { return } let deltaToMoveOffscreen: CGFloat = viewToMove.frame.width + shadowRadius + max(0, -shadowOffset.width) var frame = viewToMove.frame if viewToMove.center.x < superView.frame.size.width/2.0 { frame.center = CGPoint(x: -deltaToMoveOffscreen, y: viewToMove.center.y) } else { frame.center = CGPoint(x: superView.frame.size.width + deltaToMoveOffscreen, y: viewToMove.center.y) } manager?.updateFrame(for: self, to: frame) } func completeMoveOffScreen() { positionInFullscreen = view?.center } // MARK: - Move on screen func prepareMoveOnScreen() { guard let position = position else { return } guard let positionInFullscreen = positionInFullscreen else { return } guard let viewToMove = self.view else { return } let x = position.x - (positionInFullscreen.x - viewToMove.center.x) let y = position.y - (positionInFullscreen.y - viewToMove.center.y) self.position = CGPoint(x: x, y: y) } func movePanelOnScreen() { guard let position = position else { return } guard let viewToMove = self.view else { return } var frame = viewToMove.frame frame.center = position manager?.updateFrame(for: self, to: frame) } func completeMoveOnScreen() { } }
794330fcf2182404807c67ba5b3e9e51
17.076087
105
0.693927
false
false
false
false
mhergon/MPMoviePlayerController-Subtitles
refs/heads/master
Subtitles.swift
apache-2.0
1
// // MPMoviePlayerController-Subtitles.swift // MPMoviePlayerController-Subtitles // // Created by mhergon on 15/11/15. // Copyright © 2015 mhergon. All rights reserved. // import ObjectiveC import MediaPlayer private struct AssociatedKeys { static var FontKey = "FontKey" static var ColorKey = "FontKey" static var ContainerKey = "ContainerKey" static var SubtitleKey = "SubtitleKey" static var SubtitleHeightKey = "SubtitleHeightKey" static var PayloadKey = "PayloadKey" static var TimerKey = "TimerKey" } public class Subtitles { // MARK: - Properties fileprivate var parsedPayload: NSDictionary? // MARK: - Public methods public init(file filePath: URL, encoding: String.Encoding = String.Encoding.utf8) { // Get string let string = try! String(contentsOf: filePath, encoding: encoding) // Parse string parsedPayload = Subtitles.parseSubRip(string) } public init(subtitles string: String) { // Parse string parsedPayload = Subtitles.parseSubRip(string) } /// Search subtitles at time /// /// - Parameter time: Time /// - Returns: String if exists public func searchSubtitles(at time: TimeInterval) -> String? { return Subtitles.searchSubtitles(parsedPayload, time) } // MARK: - Private methods /// Subtitle parser /// /// - Parameter payload: Input string /// - Returns: NSDictionary fileprivate static func parseSubRip(_ payload: String) -> NSDictionary? { do { // Prepare payload var payload = payload.replacingOccurrences(of: "\n\r\n", with: "\n\n") payload = payload.replacingOccurrences(of: "\n\n\n", with: "\n\n") payload = payload.replacingOccurrences(of: "\r\n", with: "\n") // Parsed dict let parsed = NSMutableDictionary() // Get groups let regexStr = "(\\d+)\\n([\\d:,.]+)\\s+-{2}\\>\\s+([\\d:,.]+)\\n([\\s\\S]*?(?=\\n{2,}|$))" let regex = try NSRegularExpression(pattern: regexStr, options: .caseInsensitive) let matches = regex.matches(in: payload, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, payload.characters.count)) for m in matches { let group = (payload as NSString).substring(with: m.range) // Get index var regex = try NSRegularExpression(pattern: "^[0-9]+", options: .caseInsensitive) var match = regex.matches(in: group, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, group.characters.count)) guard let i = match.first else { continue } let index = (group as NSString).substring(with: i.range) // Get "from" & "to" time regex = try NSRegularExpression(pattern: "\\d{1,2}:\\d{1,2}:\\d{1,2}[,.]\\d{1,3}", options: .caseInsensitive) match = regex.matches(in: group, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, group.characters.count)) guard match.count == 2 else { continue } guard let from = match.first, let to = match.last else { continue } var h: TimeInterval = 0.0, m: TimeInterval = 0.0, s: TimeInterval = 0.0, c: TimeInterval = 0.0 let fromStr = (group as NSString).substring(with: from.range) var scanner = Scanner(string: fromStr) scanner.scanDouble(&h) scanner.scanString(":", into: nil) scanner.scanDouble(&m) scanner.scanString(":", into: nil) scanner.scanDouble(&s) scanner.scanString(",", into: nil) scanner.scanDouble(&c) let fromTime = (h * 3600.0) + (m * 60.0) + s + (c / 1000.0) let toStr = (group as NSString).substring(with: to.range) scanner = Scanner(string: toStr) scanner.scanDouble(&h) scanner.scanString(":", into: nil) scanner.scanDouble(&m) scanner.scanString(":", into: nil) scanner.scanDouble(&s) scanner.scanString(",", into: nil) scanner.scanDouble(&c) let toTime = (h * 3600.0) + (m * 60.0) + s + (c / 1000.0) // Get text & check if empty let range = NSMakeRange(0, to.range.location + to.range.length + 1) guard (group as NSString).length - range.length > 0 else { continue } let text = (group as NSString).replacingCharacters(in: range, with: "") // Create final object let final = NSMutableDictionary() final["from"] = fromTime final["to"] = toTime final["text"] = text parsed[index] = final } return parsed } catch { return nil } } /// Search subtitle on time /// /// - Parameters: /// - payload: Inout payload /// - time: Time /// - Returns: String fileprivate static func searchSubtitles(_ payload: NSDictionary?, _ time: TimeInterval) -> String? { let predicate = NSPredicate(format: "(%f >= %K) AND (%f <= %K)", time, "from", time, "to") guard let values = payload?.allValues, let result = (values as NSArray).filtered(using: predicate).first as? NSDictionary else { return nil } guard let text = result.value(forKey: "text") as? String else { return nil } return text.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) } } public extension MPMoviePlayerController { //MARK:- Public properties var subtitleLabel: UILabel? { get { return objc_getAssociatedObject(self, &AssociatedKeys.SubtitleKey) as? UILabel } set (value) { objc_setAssociatedObject(self, &AssociatedKeys.SubtitleKey, value, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } //MARK:- Private properties fileprivate var subtitleContainer: UIView? { get { return objc_getAssociatedObject(self, &AssociatedKeys.ContainerKey) as? UIView } set (value) { objc_setAssociatedObject(self, &AssociatedKeys.ContainerKey, value, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } fileprivate var subtitleLabelHeightConstraint: NSLayoutConstraint? { get { return objc_getAssociatedObject(self, &AssociatedKeys.SubtitleHeightKey) as? NSLayoutConstraint } set (value) { objc_setAssociatedObject(self, &AssociatedKeys.SubtitleHeightKey, value, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } fileprivate var parsedPayload: NSDictionary? { get { return objc_getAssociatedObject(self, &AssociatedKeys.PayloadKey) as? NSDictionary } set (value) { objc_setAssociatedObject(self, &AssociatedKeys.PayloadKey, value, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } fileprivate var timer: Timer? { get { return objc_getAssociatedObject(self, &AssociatedKeys.TimerKey) as? Timer } set (value) { objc_setAssociatedObject(self, &AssociatedKeys.TimerKey, value, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } //MARK:- Public methods func addSubtitles() -> Self { // Get subtitle view getContainer() // Create label addSubtitleLabel() // Notifications registerNotifications() return self } func open(file filePath: URL, encoding: String.Encoding = String.Encoding.utf8) { let contents = try! String(contentsOf: filePath, encoding: encoding) show(subtitles: contents) } func show(subtitles string: String) { // Parse parsedPayload = Subtitles.parseSubRip(string) // Timer timer = Timer.schedule(repeatInterval: 0.5) { (timer) -> Void in self.searchSubtitles() } } //MARK:- Private methods fileprivate func getContainer() { for a in view.subviews { for b in a.subviews { for c in b.subviews { if c.tag == 1006 { subtitleContainer = c } } } } } fileprivate func addSubtitleLabel() { guard let _ = subtitleLabel else { // Label subtitleLabel = UILabel() subtitleLabel?.translatesAutoresizingMaskIntoConstraints = false subtitleLabel?.backgroundColor = UIColor.clear subtitleLabel?.textAlignment = .center subtitleLabel?.numberOfLines = 0 subtitleLabel?.font = UIFont.boldSystemFont(ofSize: UI_USER_INTERFACE_IDIOM() == .pad ? 40.0 : 22.0) subtitleLabel?.textColor = UIColor.white subtitleLabel?.numberOfLines = 0; subtitleLabel?.layer.shadowColor = UIColor.black.cgColor subtitleLabel?.layer.shadowOffset = CGSize(width: 1.0, height: 1.0); subtitleLabel?.layer.shadowOpacity = 0.9; subtitleLabel?.layer.shadowRadius = 1.0; subtitleLabel?.layer.shouldRasterize = true; subtitleLabel?.layer.rasterizationScale = UIScreen.main.scale subtitleLabel?.lineBreakMode = .byWordWrapping subtitleContainer?.addSubview(subtitleLabel!) // Position var constraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-(20)-[l]-(20)-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["l" : subtitleLabel!]) subtitleContainer?.addConstraints(constraints) constraints = NSLayoutConstraint.constraints(withVisualFormat: "V:[l]-(30)-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["l" : subtitleLabel!]) subtitleContainer?.addConstraints(constraints) subtitleLabelHeightConstraint = NSLayoutConstraint(item: subtitleLabel!, attribute: .height, relatedBy: .equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1.0, constant: 30.0) subtitleContainer?.addConstraint(subtitleLabelHeightConstraint!) return } } fileprivate func registerNotifications() { // Finished NotificationCenter.default.addObserver( forName: NSNotification.Name.MPMoviePlayerPlaybackDidFinish, object: self, queue: OperationQueue.main) { (notification) -> Void in self.subtitleLabel?.isHidden = true self.timer?.invalidate() } // Change NotificationCenter.default.addObserver( forName: NSNotification.Name.MPMoviePlayerPlaybackStateDidChange, object: self, queue: OperationQueue.main) { (notification) -> Void in switch self.playbackState { case .playing: // Start timer self.timer = Timer.schedule(repeatInterval: 0.5) { (timer) -> Void in self.searchSubtitles() } break default: // Stop timer self.timer?.invalidate() break } } } fileprivate func searchSubtitles() { if playbackState == .playing { guard let label = subtitleLabel else { return } // Search && show subtitles subtitleLabel?.text = Subtitles.searchSubtitles(parsedPayload, currentPlaybackTime) // Adjust size let baseSize = CGSize(width: label.bounds.width, height: CGFloat.greatestFiniteMagnitude) let rect = label.sizeThatFits(baseSize) subtitleLabelHeightConstraint?.constant = rect.height + 5.0 subtitleLabel?.layoutIfNeeded() } } } // Others public extension Timer { class func schedule(repeatInterval interval: TimeInterval, handler: ((Timer?) -> Void)!) -> Timer! { let fireDate = interval + CFAbsoluteTimeGetCurrent() let timer = CFRunLoopTimerCreateWithHandler(kCFAllocatorDefault, fireDate, interval, 0, 0, handler) CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, .commonModes) return timer } }
e5c86d77db5c59209ccaeec3e93017b6
36.785915
214
0.561577
false
false
false
false
apple/swift-nio-transport-services
refs/heads/main
Tests/NIOTransportServicesTests/NIOTSBootstrapTests.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2019-2021 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// #if canImport(Network) import Atomics import XCTest import Network import NIOCore import NIOEmbedded import NIOTransportServices import NIOConcurrencyHelpers import Foundation @available(OSX 10.14, iOS 12.0, tvOS 12.0, *) final class NIOTSBootstrapTests: XCTestCase { var groupBag: [NIOTSEventLoopGroup]? = nil // protected by `self.lock` let lock = NIOLock() override func setUp() { self.lock.withLock { XCTAssertNil(self.groupBag) self.groupBag = [] } } override func tearDown() { XCTAssertNoThrow(try self.lock.withLock { guard let groupBag = self.groupBag else { XCTFail() return } XCTAssertNoThrow(try groupBag.forEach { XCTAssertNoThrow(try $0.syncShutdownGracefully()) }) self.groupBag = nil }) } func freshEventLoop() -> EventLoop { let group: NIOTSEventLoopGroup = .init(loopCount: 1, defaultQoS: .default) self.lock.withLock { self.groupBag!.append(group) } return group.next() } func testBootstrapsTolerateFuturesFromDifferentEventLoopsReturnedInInitializers() throws { let childChannelDone = self.freshEventLoop().makePromise(of: Void.self) let serverChannelDone = self.freshEventLoop().makePromise(of: Void.self) let serverChannel = try assertNoThrowWithValue(NIOTSListenerBootstrap(group: self.freshEventLoop()) .childChannelInitializer { channel in channel.eventLoop.preconditionInEventLoop() defer { childChannelDone.succeed(()) } return self.freshEventLoop().makeSucceededFuture(()) } .serverChannelInitializer { channel in channel.eventLoop.preconditionInEventLoop() defer { serverChannelDone.succeed(()) } return self.freshEventLoop().makeSucceededFuture(()) } .bind(host: "127.0.0.1", port: 0) .wait()) defer { XCTAssertNoThrow(try serverChannel.close().wait()) } let client = try assertNoThrowWithValue(NIOTSConnectionBootstrap(group: self.freshEventLoop()) .channelInitializer { channel in channel.eventLoop.preconditionInEventLoop() return self.freshEventLoop().makeSucceededFuture(()) } .connect(to: serverChannel.localAddress!) .wait()) defer { XCTAssertNoThrow(try client.syncCloseAcceptingAlreadyClosed()) } XCTAssertNoThrow(try childChannelDone.futureResult.wait()) XCTAssertNoThrow(try serverChannelDone.futureResult.wait()) } func testUniveralBootstrapWorks() { final class TellMeIfConnectionIsTLSHandler: ChannelInboundHandler { typealias InboundIn = ByteBuffer typealias OutboundOut = ByteBuffer private let isTLS: EventLoopPromise<Bool> private var buffer: ByteBuffer? init(isTLS: EventLoopPromise<Bool>) { self.isTLS = isTLS } func channelRead(context: ChannelHandlerContext, data: NIOAny) { var buffer = self.unwrapInboundIn(data) if self.buffer == nil { self.buffer = buffer } else { self.buffer!.writeBuffer(&buffer) } switch self.buffer!.readBytes(length: 2) { case .some([0x16, 0x03]): // TLS ClientHello always starts with 0x16, 0x03 self.isTLS.succeed(true) context.channel.close(promise: nil) case .some(_): self.isTLS.succeed(false) context.channel.close(promise: nil) case .none: // not enough data () } } } let group = NIOTSEventLoopGroup() func makeServer(isTLS: EventLoopPromise<Bool>) throws -> Channel { let numberOfConnections = ManagedAtomic(0) return try NIOTSListenerBootstrap(group: group) .childChannelInitializer { channel in XCTAssertEqual(0, numberOfConnections.loadThenWrappingIncrement(ordering: .relaxed)) return channel.pipeline.addHandler(TellMeIfConnectionIsTLSHandler(isTLS: isTLS)) } .bind(host: "127.0.0.1", port: 0) .wait() } let isTLSConnection1 = group.next().makePromise(of: Bool.self) let isTLSConnection2 = group.next().makePromise(of: Bool.self) var maybeServer1: Channel? = nil var maybeServer2: Channel? = nil XCTAssertNoThrow(maybeServer1 = try makeServer(isTLS: isTLSConnection1)) XCTAssertNoThrow(maybeServer2 = try makeServer(isTLS: isTLSConnection2)) guard let server1 = maybeServer1, let server2 = maybeServer2 else { XCTFail("can't make servers") return } defer { XCTAssertNoThrow(try server1.close().wait()) XCTAssertNoThrow(try server2.close().wait()) } let tlsOptions = NWProtocolTLS.Options() let bootstrap = NIOClientTCPBootstrap(NIOTSConnectionBootstrap(group: group), tls: NIOTSClientTLSProvider(tlsOptions: tlsOptions)) let tlsBootstrap = NIOClientTCPBootstrap(NIOTSConnectionBootstrap(group: group), tls: NIOTSClientTLSProvider()) .enableTLS() var buffer = server1.allocator.buffer(capacity: 2) buffer.writeString("NO") var maybeClient1: Channel? = nil XCTAssertNoThrow(maybeClient1 = try bootstrap.connect(to: server1.localAddress!).wait()) guard let client1 = maybeClient1 else { XCTFail("can't connect to server1") return } XCTAssertNotNil(try client1.getMetadata(definition: NWProtocolTCP.definition).wait() as? NWProtocolTCP.Metadata) XCTAssertNoThrow(try client1.writeAndFlush(buffer).wait()) // The TLS connection won't actually succeed but it takes Network.framework a while to tell us, we don't // actually care because we're only interested in the first 2 bytes which we're waiting for below. tlsBootstrap.connect(to: server2.localAddress!).whenSuccess { channel in XCTFail("TLS connection succeeded but really shouldn't have: \(channel)") channel.writeAndFlush(buffer, promise: nil) } XCTAssertNoThrow(XCTAssertFalse(try isTLSConnection1.futureResult.wait())) XCTAssertNoThrow(XCTAssertTrue(try isTLSConnection2.futureResult.wait())) } func testNIOTSConnectionBootstrapValidatesWorkingELGsCorrectly() { let elg = NIOTSEventLoopGroup() defer { XCTAssertNoThrow(try elg.syncShutdownGracefully()) } let el = elg.next() XCTAssertNotNil(NIOTSConnectionBootstrap(validatingGroup: elg)) XCTAssertNotNil(NIOTSConnectionBootstrap(validatingGroup: el)) } func testNIOTSConnectionBootstrapRejectsNotWorkingELGsCorrectly() { let elg = EmbeddedEventLoop() defer { XCTAssertNoThrow(try elg.syncShutdownGracefully()) } let el = elg.next() XCTAssertNil(NIOTSConnectionBootstrap(validatingGroup: elg)) XCTAssertNil(NIOTSConnectionBootstrap(validatingGroup: el)) } func testNIOTSListenerBootstrapValidatesWorkingELGsCorrectly() { let elg = NIOTSEventLoopGroup() defer { XCTAssertNoThrow(try elg.syncShutdownGracefully()) } let el = elg.next() XCTAssertNotNil(NIOTSListenerBootstrap(validatingGroup: elg)) XCTAssertNotNil(NIOTSListenerBootstrap(validatingGroup: el)) XCTAssertNotNil(NIOTSListenerBootstrap(validatingGroup: elg, childGroup: elg)) XCTAssertNotNil(NIOTSListenerBootstrap(validatingGroup: el, childGroup: el)) } func testNIOTSListenerBootstrapRejectsNotWorkingELGsCorrectly() { let correctELG = NIOTSEventLoopGroup() defer { XCTAssertNoThrow(try correctELG.syncShutdownGracefully()) } let wrongELG = EmbeddedEventLoop() defer { XCTAssertNoThrow(try wrongELG.syncShutdownGracefully()) } let wrongEL = wrongELG.next() let correctEL = correctELG.next() // both wrong XCTAssertNil(NIOTSListenerBootstrap(validatingGroup: wrongELG)) XCTAssertNil(NIOTSListenerBootstrap(validatingGroup: wrongEL)) XCTAssertNil(NIOTSListenerBootstrap(validatingGroup: wrongELG, childGroup: wrongELG)) XCTAssertNil(NIOTSListenerBootstrap(validatingGroup: wrongEL, childGroup: wrongEL)) // group correct, child group wrong XCTAssertNil(NIOTSListenerBootstrap(validatingGroup: correctELG, childGroup: wrongELG)) XCTAssertNil(NIOTSListenerBootstrap(validatingGroup: correctEL, childGroup: wrongEL)) // group wrong, child group correct XCTAssertNil(NIOTSListenerBootstrap(validatingGroup: wrongELG, childGroup: correctELG)) XCTAssertNil(NIOTSListenerBootstrap(validatingGroup: wrongEL, childGroup: correctEL)) } func testEndpointReuseShortcutOption() throws { let group = NIOTSEventLoopGroup() let listenerChannel = try NIOTSListenerBootstrap(group: group) .bind(host: "127.0.0.1", port: 0) .wait() let bootstrap = NIOClientTCPBootstrap(NIOTSConnectionBootstrap(group: group), tls: NIOInsecureNoTLS()) .channelConvenienceOptions([.allowLocalEndpointReuse]) let client = try bootstrap.connect(to: listenerChannel.localAddress!).wait() let optionValue = try client.getOption(NIOTSChannelOptions.allowLocalEndpointReuse).wait() try client.close().wait() XCTAssertEqual(optionValue, true) } func testShorthandOptionsAreEquivalent() throws { func setAndGetOption<Option>(option: Option, _ applyOptions : (NIOClientTCPBootstrap) -> NIOClientTCPBootstrap) throws -> Option.Value where Option : ChannelOption { let group = NIOTSEventLoopGroup() let listenerChannel = try NIOTSListenerBootstrap(group: group) .bind(host: "127.0.0.1", port: 0) .wait() let bootstrap = applyOptions(NIOClientTCPBootstrap(NIOTSConnectionBootstrap(group: group), tls: NIOInsecureNoTLS())) let client = try bootstrap.connect(to: listenerChannel.localAddress!).wait() let optionRead = try client.getOption(option).wait() try client.close().wait() return optionRead } func checkOptionEquivalence<Option>(longOption: Option, setValue: Option.Value, shortOption: ChannelOptions.TCPConvenienceOption) throws where Option : ChannelOption, Option.Value : Equatable { let longSetValue = try setAndGetOption(option: longOption) { bs in bs.channelOption(longOption, value: setValue) } let shortSetValue = try setAndGetOption(option: longOption) { bs in bs.channelConvenienceOptions([shortOption]) } let unsetValue = try setAndGetOption(option: longOption) { $0 } XCTAssertEqual(longSetValue, shortSetValue) XCTAssertNotEqual(longSetValue, unsetValue) } try checkOptionEquivalence(longOption: NIOTSChannelOptions.allowLocalEndpointReuse, setValue: true, shortOption: .allowLocalEndpointReuse) try checkOptionEquivalence(longOption: ChannelOptions.allowRemoteHalfClosure, setValue: true, shortOption: .allowRemoteHalfClosure) try checkOptionEquivalence(longOption: ChannelOptions.autoRead, setValue: false, shortOption: .disableAutoRead) } func testBootstrapsErrorGracefullyOnOutOfBandPorts() throws { let invalidPortNumbers = [-1, 65536] let group = NIOTSEventLoopGroup() defer { try! group.syncShutdownGracefully() } let listenerBootstrap = NIOTSListenerBootstrap(group: group) let connectionBootstrap = NIOTSConnectionBootstrap(group: group) for invalidPort in invalidPortNumbers { var listenerChannel: Channel? var connectionChannel: Channel? XCTAssertThrowsError(listenerChannel = try listenerBootstrap.bind(host: "localhost", port: invalidPort).wait()) { error in XCTAssertNotNil(error as? NIOTSErrors.InvalidPort) } XCTAssertThrowsError(connectionChannel = try connectionBootstrap.connect(host: "localhost", port: invalidPort).wait()) { error in XCTAssertNotNil(error as? NIOTSErrors.InvalidPort) } try? listenerChannel?.close().wait() try? connectionChannel?.close().wait() } } } extension Channel { func syncCloseAcceptingAlreadyClosed() throws { do { try self.close().wait() } catch ChannelError.alreadyClosed { /* we're happy with this one */ } catch let e { throw e } } } #endif
a6103d99e953697d736265e961f242b0
39.968839
142
0.611326
false
false
false
false
jihun-kang/ios_a2big_sdk
refs/heads/master
A2bigSDK/LookMonumentData.swift
apache-2.0
1
// // LookMonument.swift // nextpage // // Created by a2big on 2016. 11. 12.. // Copyright © 2016년 a2big. All rights reserved. // //import SwiftyJSON public class LookMonumentData { public var monument_no: String! public var monument_name: String! public var media_no: String! public var character_no: String! public var monument_ment: String! public var imageArr:[JSON] required public init(json: JSON, baseUrl:String) { monument_no = json["monument_no"].stringValue monument_name = json["monument_name"].stringValue media_no = baseUrl+json["media_no"].stringValue.replacingOccurrences(of: "./", with: "") character_no = json["character_no"].stringValue monument_ment = json["monument_ment"].stringValue imageArr = json["image_list"].arrayValue ///name = json["image_list"].arrayObject } }
ad2f24a924f0a5494ffe3e272c11a17f
31.071429
96
0.652561
false
false
false
false
stowy/ReactiveTwitterSearch
refs/heads/master
ReactiveTwitterSearch/Service/TwitterSearchService.swift
mit
1
// // TwitterSearchService.swift // ReactiveTwitterSearch // // Created by Colin Eberhardt on 10/05/2015. // Copyright (c) 2015 Colin Eberhardt. All rights reserved. // import Foundation import Accounts import Social import ReactiveCocoa class TwitterSearchService { private let accountStore: ACAccountStore private let twitterAccountType: ACAccountType init() { accountStore = ACAccountStore() twitterAccountType = accountStore.accountTypeWithAccountTypeIdentifier(ACAccountTypeIdentifierTwitter) } func requestAccessToTwitterSignal() -> SignalProducer<Int, NSError> { return SignalProducer { sink, _ in self.accountStore.requestAccessToAccountsWithType(self.twitterAccountType, options: nil) { (granted, _) in if granted { sendCompleted(sink) } else { sendError(sink, TwitterInstantError.AccessDenied.toError()) } } } } func signalForSearchWithText(text: String) -> SignalProducer<TwitterResponse, NSError> { func requestforSearchText(text: String) -> SLRequest { let url = NSURL(string: "https://api.twitter.com/1.1/search/tweets.json") let params = [ "q" : text, "count": "100", "lang" : "en" ] return SLRequest(forServiceType: SLServiceTypeTwitter, requestMethod: .GET, URL: url, parameters: params) } return SignalProducer { sink, disposable in let request = requestforSearchText(text) let maybeTwitterAccount = self.getTwitterAccount() if let twitterAccount = maybeTwitterAccount { request.account = twitterAccount println("performing request") request.performRequestWithHandler { (data, response, _) -> Void in println("response received") if response != nil && response.statusCode == 200 { let timelineData = NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments, error: nil) as! NSDictionary sendNext(sink, TwitterResponse(tweetsDictionary: timelineData)) sendCompleted(sink) } else { sendError(sink, TwitterInstantError.InvalidResponse.toError()) } } } else { sendError(sink, TwitterInstantError.NoTwitterAccounts.toError()) } } } private func getTwitterAccount() -> ACAccount? { let twitterAccounts = self.accountStore.accountsWithAccountType(self.twitterAccountType) as! [ACAccount] if twitterAccounts.count == 0 { return nil } else { return twitterAccounts[0] } } }
6fd776c59f0c628595cecae0c0fcd238
29.752941
130
0.662586
false
false
false
false
wikimedia/apps-ios-wikipedia
refs/heads/twn
Wikipedia/Code/WMFTableOfContentsPresentationController.swift
mit
1
import UIKit // MARK: - Delegate @objc public protocol WMFTableOfContentsPresentationControllerTapDelegate { func tableOfContentsPresentationControllerDidTapBackground(_ controller: WMFTableOfContentsPresentationController) } open class WMFTableOfContentsPresentationController: UIPresentationController, Themeable { var theme = Theme.standard var displaySide = WMFTableOfContentsDisplaySide.left var displayMode = WMFTableOfContentsDisplayMode.modal // MARK: - init public required init(presentedViewController: UIViewController, presentingViewController: UIViewController?, tapDelegate: WMFTableOfContentsPresentationControllerTapDelegate) { self.tapDelegate = tapDelegate super.init(presentedViewController: presentedViewController, presenting: presentedViewController) } weak open var tapDelegate: WMFTableOfContentsPresentationControllerTapDelegate? open var minimumVisibleBackgroundWidth: CGFloat = 60.0 open var maximumTableOfContentsWidth: CGFloat = 300.0 open var statusBarEstimatedHeight: CGFloat { return max(UIApplication.shared.statusBarFrame.size.height, presentedView?.safeAreaInsets.top ?? 0) } // MARK: - Views lazy var statusBarBackground: UIView = { let view = UIView(frame: CGRect.zero) view.autoresizingMask = .flexibleWidth view.layer.shadowOpacity = 0.8 view.layer.shadowOffset = CGSize(width: 0, height: 5) view.clipsToBounds = false return view }() lazy var closeButton:UIButton = { let button = UIButton(frame: CGRect.zero) button.setImage(UIImage(named: "close"), for: .normal) button.addTarget(self, action: #selector(WMFTableOfContentsPresentationController.didTap(_:)), for: .touchUpInside) button.accessibilityHint = WMFLocalizedString("table-of-contents-close-accessibility-hint", value:"Close", comment:"Accessibility hint for closing table of contents\n{{Identical|Close}}") button.accessibilityLabel = WMFLocalizedString("table-of-contents-close-accessibility-label", value:"Close Table of contents", comment:"Accessibility label for closing table of contents") button.translatesAutoresizingMaskIntoConstraints = false return button }() var closeButtonTrailingConstraint: NSLayoutConstraint? var closeButtonLeadingConstraint: NSLayoutConstraint? var closeButtonTopConstraint: NSLayoutConstraint? var closeButtonBottomConstraint: NSLayoutConstraint? lazy var backgroundView :UIVisualEffectView = { let view = UIVisualEffectView(frame: CGRect.zero) view.autoresizingMask = .flexibleWidth view.effect = UIBlurEffect(style: .light) view.alpha = 0.0 let tap = UITapGestureRecognizer.init() tap.addTarget(self, action: #selector(WMFTableOfContentsPresentationController.didTap(_:))) view.addGestureRecognizer(tap) view.contentView.addSubview(self.statusBarBackground) let closeButtonDimension: CGFloat = 44 let widthConstraint = self.closeButton.widthAnchor.constraint(equalToConstant: closeButtonDimension) let heightConstraint = self.closeButton.heightAnchor.constraint(equalToConstant: closeButtonDimension) let leadingConstraint = view.contentView.layoutMarginsGuide.leadingAnchor.constraint(equalTo: self.closeButton.leadingAnchor, constant: 0) let trailingConstraint = view.contentView.layoutMarginsGuide.trailingAnchor.constraint(equalTo: self.closeButton.trailingAnchor, constant: 0) let topConstraint = view.contentView.layoutMarginsGuide.topAnchor.constraint(equalTo: self.closeButton.topAnchor, constant: 0) let bottomConstraint = view.contentView.layoutMarginsGuide.bottomAnchor.constraint(equalTo: self.closeButton.bottomAnchor, constant: 0) trailingConstraint.isActive = false bottomConstraint.isActive = false closeButtonLeadingConstraint = leadingConstraint closeButtonTrailingConstraint = trailingConstraint closeButtonTopConstraint = topConstraint closeButtonBottomConstraint = bottomConstraint self.closeButton.frame = CGRect(x: 0, y: 0, width: closeButtonDimension, height: closeButtonDimension) self.closeButton.addConstraints([widthConstraint, heightConstraint]) view.contentView.addSubview(self.closeButton) view.contentView.addConstraints([leadingConstraint, trailingConstraint, topConstraint, bottomConstraint]) return view }() func updateStatusBarBackgroundFrame() { self.statusBarBackground.frame = CGRect(x: self.backgroundView.bounds.minX, y: self.backgroundView.bounds.minY, width: self.backgroundView.bounds.width, height: self.frameOfPresentedViewInContainerView.origin.y) } func updateButtonConstraints() { switch self.displaySide { case .right: fallthrough case .left: closeButtonLeadingConstraint?.isActive = false closeButtonBottomConstraint?.isActive = false closeButtonTrailingConstraint?.isActive = true closeButtonTopConstraint?.isActive = true break case .center: fallthrough default: closeButtonTrailingConstraint?.isActive = false closeButtonTopConstraint?.isActive = false closeButtonLeadingConstraint?.isActive = true closeButtonBottomConstraint?.isActive = true } return () } @objc func didTap(_ tap: UITapGestureRecognizer) { self.tapDelegate?.tableOfContentsPresentationControllerDidTapBackground(self) } // MARK: - Accessibility func togglePresentingViewControllerAccessibility(_ accessible: Bool) { self.presentingViewController.view.accessibilityElementsHidden = !accessible } // MARK: - UIPresentationController override open func presentationTransitionWillBegin() { guard let containerView = self.containerView, let presentedView = self.presentedView else { return } // Add the dimming view and the presented view to the heirarchy self.backgroundView.frame = containerView.bounds updateStatusBarBackgroundFrame() containerView.addSubview(self.backgroundView) if(self.traitCollection.verticalSizeClass == .compact){ self.statusBarBackground.isHidden = true } updateButtonConstraints() containerView.addSubview(presentedView) // Hide the presenting view controller for accessibility self.togglePresentingViewControllerAccessibility(false) apply(theme: theme) // Fade in the dimming view alongside the transition if let transitionCoordinator = self.presentingViewController.transitionCoordinator { transitionCoordinator.animate(alongsideTransition: {(context: UIViewControllerTransitionCoordinatorContext!) -> Void in self.backgroundView.alpha = 1.0 }, completion:nil) } } override open func presentationTransitionDidEnd(_ completed: Bool) { if !completed { self.backgroundView.removeFromSuperview() } } override open func dismissalTransitionWillBegin() { if let transitionCoordinator = self.presentingViewController.transitionCoordinator { transitionCoordinator.animate(alongsideTransition: {(context: UIViewControllerTransitionCoordinatorContext!) -> Void in self.backgroundView.alpha = 0.0 }, completion:nil) } } override open func dismissalTransitionDidEnd(_ completed: Bool) { if completed { self.backgroundView.removeFromSuperview() self.togglePresentingViewControllerAccessibility(true) self.presentedView?.layer.cornerRadius = 0 self.presentedView?.layer.borderWidth = 0 self.presentedView?.layer.shadowOpacity = 0 self.presentedView?.clipsToBounds = true } } override open var frameOfPresentedViewInContainerView : CGRect { var frame = self.containerView!.bounds var bgWidth = self.minimumVisibleBackgroundWidth var tocWidth = frame.size.width - bgWidth if(tocWidth > self.maximumTableOfContentsWidth){ tocWidth = self.maximumTableOfContentsWidth bgWidth = frame.size.width - tocWidth } frame.origin.y = self.statusBarEstimatedHeight + 0.5 frame.size.height -= frame.origin.y switch displaySide { case .center: frame.origin.y += 10 frame.origin.x += 0.5*bgWidth frame.size.height -= 80 break case .right: frame.origin.x += bgWidth break default: break } frame.size.width = tocWidth return frame } override open func viewWillTransition(to size: CGSize, with transitionCoordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: transitionCoordinator) transitionCoordinator.animate(alongsideTransition: {(context: UIViewControllerTransitionCoordinatorContext!) -> Void in self.backgroundView.frame = self.containerView!.bounds let frame = self.frameOfPresentedViewInContainerView self.presentedView!.frame = frame self.updateStatusBarBackgroundFrame() self.updateButtonConstraints() }, completion:nil) } public func apply(theme: Theme) { self.theme = theme guard self.containerView != nil else { return } switch displaySide { case .center: self.presentedView?.layer.cornerRadius = 10 self.presentedView?.clipsToBounds = true self.presentedView?.layer.borderColor = theme.colors.border.cgColor self.presentedView?.layer.borderWidth = 1.0 self.closeButton.setImage(UIImage(named: "toc-close-blue"), for: .normal) self.closeButton.tintColor = theme.colors.link self.statusBarBackground.isHidden = true break default: //Add shadow to the presented view self.presentedView?.layer.shadowOpacity = 0.8 self.presentedView?.layer.shadowColor = theme.colors.shadow.cgColor self.presentedView?.layer.shadowOffset = CGSize(width: 3, height: 5) self.presentedView?.clipsToBounds = false self.closeButton.setImage(UIImage(named: "close"), for: .normal) self.statusBarBackground.isHidden = false } self.backgroundView.effect = UIBlurEffect(style: theme.blurEffectStyle) self.statusBarBackground.backgroundColor = theme.colors.paperBackground self.statusBarBackground.layer.shadowColor = theme.colors.shadow.cgColor self.closeButton.tintColor = theme.colors.primaryText } }
dcd22b6f91ffee6ce4e9377f47bf0cb5
41.067669
219
0.691332
false
false
false
false
r4phab/ECAB
refs/heads/iOS9
ECAB/SessionViewController.swift
mit
1
// // HistoryViewController.swift // ECAB // // Created by Boris Yurkevich on 18/01/2015. // Copyright (c) 2015 Oliver Braddick and Jan Atkinson. All rights reserved. // import UIKit class SessionViewController: UIViewController { @IBOutlet weak var buttonGraph: UIBarButtonItem! @IBOutlet weak var logDetails: UITextView! @IBOutlet weak var helpMessage: UILabel! override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) // Hide graph button //buttonGraph.tintColor = UIColor.clearColor() hideLogs() hideGraphButton() showHelp() } @IBAction func changeViewType(sender: UIBarButtonItem) { } func showLogs(text: String) { logDetails.text = text logDetails.hidden = false hideHelp() //showGraphButton() } func hideLogs() { logDetails.hidden = true hideGraphButton() } func showGraphButton(){ buttonGraph.enabled = true } func hideGraphButton(){ buttonGraph.enabled = false } func showHelp(){ helpMessage.hidden = false } func hideHelp(){ helpMessage.hidden = true } }
a919297e4b936d652cd92656a29471b1
20.590164
77
0.606682
false
false
false
false
cjbeauchamp/tvOSDashboard
refs/heads/master
Charts/Classes/Renderers/ScatterChartRenderer.swift
apache-2.0
6
// // ScatterChartRenderer.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 #if !os(OSX) import UIKit #endif public class ScatterChartRenderer: LineScatterCandleRadarChartRenderer { public weak var dataProvider: ScatterChartDataProvider? public init(dataProvider: ScatterChartDataProvider?, animator: ChartAnimator?, viewPortHandler: ChartViewPortHandler) { super.init(animator: animator, viewPortHandler: viewPortHandler) self.dataProvider = dataProvider } public override func drawData(context context: CGContext) { guard let scatterData = dataProvider?.scatterData else { return } for (var i = 0; i < scatterData.dataSetCount; i++) { guard let set = scatterData.getDataSetByIndex(i) else { continue } if set.isVisible { if !(set is IScatterChartDataSet) { fatalError("Datasets for ScatterChartRenderer must conform to IScatterChartDataSet") } drawDataSet(context: context, dataSet: set as! IScatterChartDataSet) } } } private var _lineSegments = [CGPoint](count: 2, repeatedValue: CGPoint()) public func drawDataSet(context context: CGContext, dataSet: IScatterChartDataSet) { guard let dataProvider = dataProvider, animator = animator else { return } let trans = dataProvider.getTransformer(dataSet.axisDependency) let phaseY = animator.phaseY let entryCount = dataSet.entryCount 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 let shapeStrokeSizeHalf = shapeStrokeSize / 2.0 var point = CGPoint() let valueToPixelMatrix = trans.valueToPixelMatrix let shape = dataSet.scatterShape CGContextSaveGState(context) for (var j = 0, count = Int(min(ceil(CGFloat(entryCount) * animator.phaseX), CGFloat(entryCount))); j < count; j++) { guard let e = dataSet.entryForIndex(j) else { continue } point.x = CGFloat(e.xIndex) point.y = CGFloat(e.value) * phaseY point = CGPointApplyAffineTransform(point, valueToPixelMatrix); if (!viewPortHandler.isInBoundsRight(point.x)) { break } if (!viewPortHandler.isInBoundsLeft(point.x) || !viewPortHandler.isInBoundsY(point.y)) { continue } if (shape == .Square) { if shapeHoleSize > 0.0 { CGContextSetStrokeColorWithColor(context, dataSet.colorAt(j).CGColor) CGContextSetLineWidth(context, shapeStrokeSize) var rect = CGRect() rect.origin.x = point.x - shapeHoleSizeHalf - shapeStrokeSizeHalf rect.origin.y = point.y - shapeHoleSizeHalf - shapeStrokeSizeHalf rect.size.width = shapeHoleSize + shapeStrokeSize rect.size.height = shapeHoleSize + shapeStrokeSize CGContextStrokeRect(context, rect) if let shapeHoleColor = shapeHoleColor { CGContextSetFillColorWithColor(context, shapeHoleColor.CGColor) rect.origin.x = point.x - shapeHoleSizeHalf rect.origin.y = point.y - shapeHoleSizeHalf rect.size.width = shapeHoleSize rect.size.height = shapeHoleSize CGContextFillRect(context, rect) } } else { CGContextSetFillColorWithColor(context, dataSet.colorAt(j).CGColor) var rect = CGRect() rect.origin.x = point.x - shapeHalf rect.origin.y = point.y - shapeHalf rect.size.width = shapeSize rect.size.height = shapeSize CGContextFillRect(context, rect) } } else if (shape == .Circle) { if shapeHoleSize > 0.0 { CGContextSetStrokeColorWithColor(context, dataSet.colorAt(j).CGColor) CGContextSetLineWidth(context, shapeStrokeSize) var rect = CGRect() rect.origin.x = point.x - shapeHoleSizeHalf - shapeStrokeSizeHalf rect.origin.y = point.y - shapeHoleSizeHalf - shapeStrokeSizeHalf rect.size.width = shapeHoleSize + shapeStrokeSize rect.size.height = shapeHoleSize + shapeStrokeSize CGContextStrokeEllipseInRect(context, rect) if let shapeHoleColor = shapeHoleColor { CGContextSetFillColorWithColor(context, shapeHoleColor.CGColor) rect.origin.x = point.x - shapeHoleSizeHalf rect.origin.y = point.y - shapeHoleSizeHalf rect.size.width = shapeHoleSize rect.size.height = shapeHoleSize CGContextFillEllipseInRect(context, rect) } } else { CGContextSetFillColorWithColor(context, dataSet.colorAt(j).CGColor) var rect = CGRect() rect.origin.x = point.x - shapeHalf rect.origin.y = point.y - shapeHalf rect.size.width = shapeSize rect.size.height = shapeSize CGContextFillEllipseInRect(context, rect) } } else if (shape == .Triangle) { CGContextSetFillColorWithColor(context, dataSet.colorAt(j).CGColor) // create a triangle path CGContextBeginPath(context) CGContextMoveToPoint(context, point.x, point.y - shapeHalf) CGContextAddLineToPoint(context, point.x + shapeHalf, point.y + shapeHalf) CGContextAddLineToPoint(context, point.x - shapeHalf, point.y + shapeHalf) if shapeHoleSize > 0.0 { CGContextAddLineToPoint(context, point.x, point.y - shapeHalf) CGContextMoveToPoint(context, point.x - shapeHalf + shapeStrokeSize, point.y + shapeHalf - shapeStrokeSize) CGContextAddLineToPoint(context, point.x + shapeHalf - shapeStrokeSize, point.y + shapeHalf - shapeStrokeSize) CGContextAddLineToPoint(context, point.x, point.y - shapeHalf + shapeStrokeSize) CGContextAddLineToPoint(context, point.x - shapeHalf + shapeStrokeSize, point.y + shapeHalf - shapeStrokeSize) } CGContextClosePath(context) CGContextFillPath(context) if shapeHoleSize > 0.0 && shapeHoleColor != nil { CGContextSetFillColorWithColor(context, shapeHoleColor!.CGColor) // create a triangle path CGContextBeginPath(context) CGContextMoveToPoint(context, point.x, point.y - shapeHalf + shapeStrokeSize) CGContextAddLineToPoint(context, point.x + shapeHalf - shapeStrokeSize, point.y + shapeHalf - shapeStrokeSize) CGContextAddLineToPoint(context, point.x - shapeHalf + shapeStrokeSize, point.y + shapeHalf - shapeStrokeSize) CGContextClosePath(context) CGContextFillPath(context) } } else if (shape == .Cross) { CGContextSetStrokeColorWithColor(context, dataSet.colorAt(j).CGColor) _lineSegments[0].x = point.x - shapeHalf _lineSegments[0].y = point.y _lineSegments[1].x = point.x + shapeHalf _lineSegments[1].y = point.y CGContextStrokeLineSegments(context, _lineSegments, 2) _lineSegments[0].x = point.x _lineSegments[0].y = point.y - shapeHalf _lineSegments[1].x = point.x _lineSegments[1].y = point.y + shapeHalf CGContextStrokeLineSegments(context, _lineSegments, 2) } else if (shape == .X) { CGContextSetStrokeColorWithColor(context, dataSet.colorAt(j).CGColor) _lineSegments[0].x = point.x - shapeHalf _lineSegments[0].y = point.y - shapeHalf _lineSegments[1].x = point.x + shapeHalf _lineSegments[1].y = point.y + shapeHalf CGContextStrokeLineSegments(context, _lineSegments, 2) _lineSegments[0].x = point.x + shapeHalf _lineSegments[0].y = point.y - shapeHalf _lineSegments[1].x = point.x - shapeHalf _lineSegments[1].y = point.y + shapeHalf CGContextStrokeLineSegments(context, _lineSegments, 2) } else if (shape == .Custom) { CGContextSetFillColorWithColor(context, dataSet.colorAt(j).CGColor) let customShape = dataSet.customScatterShape if customShape == nil { return } // transform the provided custom path CGContextSaveGState(context) CGContextTranslateCTM(context, point.x, point.y) CGContextBeginPath(context) CGContextAddPath(context, customShape) CGContextFillPath(context) CGContextRestoreGState(context) } } CGContextRestoreGState(context) } public override func drawValues(context context: CGContext) { guard let dataProvider = dataProvider, scatterData = dataProvider.scatterData, animator = animator else { return } // if values are drawn if (scatterData.yValCount < Int(ceil(CGFloat(dataProvider.maxVisibleValueCount) * viewPortHandler.scaleX))) { guard let dataSets = scatterData.dataSets as? [IScatterChartDataSet] else { return } let phaseX = animator.phaseX let phaseY = animator.phaseY var pt = CGPoint() for (var i = 0; i < scatterData.dataSetCount; i++) { let dataSet = dataSets[i] if !dataSet.isDrawValuesEnabled || dataSet.entryCount == 0 { continue } let valueFont = dataSet.valueFont guard let formatter = dataSet.valueFormatter else { continue } let trans = dataProvider.getTransformer(dataSet.axisDependency) let valueToPixelMatrix = trans.valueToPixelMatrix let entryCount = dataSet.entryCount let shapeSize = dataSet.scatterShapeSize let lineHeight = valueFont.lineHeight for (var j = 0, count = Int(ceil(CGFloat(entryCount) * phaseX)); j < count; j++) { guard let e = dataSet.entryForIndex(j) else { break } pt.x = CGFloat(e.xIndex) pt.y = CGFloat(e.value) * phaseY pt = CGPointApplyAffineTransform(pt, valueToPixelMatrix) if (!viewPortHandler.isInBoundsRight(pt.x)) { break } // make sure the lines don't do shitty things outside bounds if ((!viewPortHandler.isInBoundsLeft(pt.x) || !viewPortHandler.isInBoundsY(pt.y))) { continue } let text = formatter.stringFromNumber(e.value) ChartUtils.drawText( context: context, text: text!, point: CGPoint( x: pt.x, y: pt.y - shapeSize - lineHeight), align: .Center, attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: dataSet.valueTextColorAt(j)] ) } } } } public override func drawExtras(context context: CGContext) { } private var _highlightPointBuffer = CGPoint() public override func drawHighlighted(context context: CGContext, indices: [ChartHighlight]) { guard let dataProvider = dataProvider, scatterData = dataProvider.scatterData, animator = animator else { return } let chartXMax = dataProvider.chartXMax CGContextSaveGState(context) for (var i = 0; i < indices.count; i++) { guard let set = scatterData.getDataSetByIndex(indices[i].dataSetIndex) as? IScatterChartDataSet else { continue } if !set.isHighlightEnabled { continue } CGContextSetStrokeColorWithColor(context, set.highlightColor.CGColor) CGContextSetLineWidth(context, set.highlightLineWidth) if (set.highlightLineDashLengths != nil) { CGContextSetLineDash(context, set.highlightLineDashPhase, set.highlightLineDashLengths!, set.highlightLineDashLengths!.count) } else { CGContextSetLineDash(context, 0.0, nil, 0) } let xIndex = indices[i].xIndex; // get the x-position if (CGFloat(xIndex) > CGFloat(chartXMax) * animator.phaseX) { continue } let yVal = set.yValForXIndex(xIndex) if (yVal.isNaN) { continue } let y = CGFloat(yVal) * animator.phaseY; // get the y-position _highlightPointBuffer.x = CGFloat(xIndex) _highlightPointBuffer.y = y let trans = dataProvider.getTransformer(set.axisDependency) trans.pointValueToPixel(&_highlightPointBuffer) // draw the lines drawHighlightLines(context: context, point: _highlightPointBuffer, set: set) } CGContextRestoreGState(context) } }
65f9369dccaa8e28f20b76c74c8c5a0b
38.783251
141
0.518296
false
false
false
false
antonio081014/LeeCode-CodeBase
refs/heads/main
Swift/sqrtx.swift
mit
2
/** * https://leetcode.com/problems/sqrtx/ * * */ class Solution { func mySqrt(_ x: Int) -> Int { if x == 1 { return 1 } var left = 1 var right = x while left < right { let mid = left + (right - left) / 2 if mid * mid > x { right = mid } else { left = mid + 1 } } return left - 1 } }/** * https://leetcode.com/problems/sqrtx/ * * */ // Date: Thu Jul 9 11:59:43 PDT 2020 class Solution { func mySqrt(_ x: Int) -> Int { var left = 1 var right = x + 1 while left < right { let mid = left + (right - left) / 2 if mid * mid >= x { right = mid } else { left = mid + 1 } } return left * left == x ? left : left - 1 } } class Solution { func mySqrt(_ x: Int) -> Int { var left = 1 var right = x + 1 while left < right { let mid = left + (right - left) / 2 if mid * mid > x { right = mid } else { left = mid + 1 } } return left - 1 } }
9efde00f78aac5fdf668f17f2a669bb2
20.666667
49
0.381377
false
false
false
false
huonw/swift
refs/heads/master
validation-test/Sema/type_checker_perf/slow/rdar17170728.swift
apache-2.0
5
// RUN: %target-typecheck-verify-swift -solver-expression-time-threshold=1 // REQUIRES: tools-release,no_asserts let i: Int? = 1 let j: Int? let k: Int? = 2 let _ = [i, j, k].reduce(0 as Int?) { // expected-error@-1 {{reasonable time}} $0 != nil && $1 != nil ? $0! + $1! : ($0 != nil ? $0! : ($1 != nil ? $1! : nil)) }
9ce297624cedddd758dad15663453b4b
28.545455
82
0.553846
false
false
false
false
iOSWizards/AwesomeData
refs/heads/master
AwesomeData/Classes/Placeholder/AwesomeBackgroundPlaceholder.swift
mit
1
// // AwesomeBackgroundPlaceholder.swift // Pods // // Created by Evandro Harrison Hoffmann on 02/12/2016. // // import UIKit open class AwesomeBackgroundPlaceholder: UIImageView { } extension UIView { public func addPlaceholderImage(named name: String, backgroundColor: UIColor = .clear, contentMode: UIViewContentMode = .center){ removePlaceholderImage() let imageView = AwesomeBackgroundPlaceholder(image: UIImage(named: name)) imageView.backgroundColor = backgroundColor imageView.frame = self.frame imageView.translatesAutoresizingMaskIntoConstraints = false imageView.contentMode = contentMode imageView.layer.cornerRadius = self.layer.cornerRadius imageView.layer.masksToBounds = true self.superview?.insertSubview(imageView, belowSubview: self) if #available(iOS 9.0, *) { imageView.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true imageView.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true imageView.widthAnchor.constraint(equalTo: self.widthAnchor).isActive = true imageView.heightAnchor.constraint(equalTo: self.heightAnchor).isActive = true } } public func removePlaceholderImage(){ for subview in subviews{ if let subview = subview as? AwesomeBackgroundPlaceholder { subview.removeFromSuperview() } } } public func copyConstraints(toView: UIView){ guard let constraints = self.superview?.constraints else { return } for constraint in constraints { if constraint.firstItem as? NSObject == self { self.superview?.addConstraints([ NSLayoutConstraint(item: toView, attribute: constraint.firstAttribute, relatedBy: constraint.relation, toItem: constraint.secondItem, attribute: constraint.secondAttribute, multiplier: constraint.multiplier, constant: constraint.constant) ]) } else if constraint.secondItem as? NSObject == self { self.superview?.addConstraints([ NSLayoutConstraint(item: constraint.firstItem as Any, attribute: constraint.firstAttribute, relatedBy: constraint.relation, toItem: toView, attribute: constraint.secondAttribute, multiplier: constraint.multiplier, constant: constraint.constant) ]) } } } }
f511cb15a4bb8225afd48f849c3a9b25
38.631579
133
0.559097
false
false
false
false
nathantannar4/InputBarAccessoryView
refs/heads/master
Sources/Plugins/AttachmentManager/AttachmentManager.swift
mit
1
// // AttachmentManager.swift // InputBarAccessoryView // // Copyright © 2017-2020 Nathan Tannar. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // // Created by Nathan Tannar on 10/4/17. // import UIKit open class AttachmentManager: NSObject, InputPlugin { public enum Attachment { case image(UIImage) case url(URL) case data(Data) @available(*, deprecated, message: ".other(AnyObject) has been depricated as of 2.0.0") case other(AnyObject) } // MARK: - Properties [Public] /// A protocol that can recieve notifications from the `AttachmentManager` open weak var delegate: AttachmentManagerDelegate? /// A protocol to passes data to the `AttachmentManager` open weak var dataSource: AttachmentManagerDataSource? open lazy var attachmentView: AttachmentCollectionView = { [weak self] in let attachmentView = AttachmentCollectionView() attachmentView.dataSource = self attachmentView.delegate = self return attachmentView }() /// The attachments that the managers holds private(set) public var attachments = [Attachment]() { didSet { reloadData() } } /// A flag you can use to determine if you want the manager to be always visible open var isPersistent = false { didSet { attachmentView.reloadData() } } /// A flag to determine if the AddAttachmentCell is visible open var showAddAttachmentCell = true { didSet { attachmentView.reloadData() } } /// The color applied to the backgroundColor of the deleteButton in each `AttachmentCell` open var tintColor: UIColor { if #available(iOS 13, *) { return .link } else { return .systemBlue } } // MARK: - Initialization public override init() { super.init() } // MARK: - InputPlugin open func reloadData() { attachmentView.reloadData() delegate?.attachmentManager(self, didReloadTo: attachments) delegate?.attachmentManager(self, shouldBecomeVisible: attachments.count > 0 || isPersistent) } /// Invalidates the `AttachmentManagers` session by removing all attachments open func invalidate() { attachments = [] } /// Appends the object to the attachments /// /// - Parameter object: The object to append @discardableResult open func handleInput(of object: AnyObject) -> Bool { let attachment: Attachment if let image = object as? UIImage { attachment = .image(image) } else if let url = object as? URL { attachment = .url(url) } else if let data = object as? Data { attachment = .data(data) } else { return false } insertAttachment(attachment, at: attachments.count) return true } // MARK: - API [Public] /// Performs an animated insertion of an attachment at an index /// /// - Parameter index: The index to insert the attachment at open func insertAttachment(_ attachment: Attachment, at index: Int) { attachmentView.performBatchUpdates({ self.attachments.insert(attachment, at: index) self.attachmentView.insertItems(at: [IndexPath(row: index, section: 0)]) }, completion: { success in self.attachmentView.reloadData() self.delegate?.attachmentManager(self, didInsert: attachment, at: index) self.delegate?.attachmentManager(self, shouldBecomeVisible: self.attachments.count > 0 || self.isPersistent) }) } /// Performs an animated removal of an attachment at an index /// /// - Parameter index: The index to remove the attachment at open func removeAttachment(at index: Int) { let attachment = attachments[index] attachmentView.performBatchUpdates({ self.attachments.remove(at: index) self.attachmentView.deleteItems(at: [IndexPath(row: index, section: 0)]) }, completion: { success in self.attachmentView.reloadData() self.delegate?.attachmentManager(self, didRemove: attachment, at: index) self.delegate?.attachmentManager(self, shouldBecomeVisible: self.attachments.count > 0 || self.isPersistent) }) } } extension AttachmentManager: UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { // MARK: - UICollectionViewDelegate final public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if indexPath.row == attachments.count { delegate?.attachmentManager(self, didSelectAddAttachmentAt: indexPath.row) delegate?.attachmentManager(self, shouldBecomeVisible: attachments.count > 0 || isPersistent) } } // MARK: - UICollectionViewDataSource final public func numberOfItems(inSection section: Int) -> Int { return 1 } final public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return attachments.count + (showAddAttachmentCell ? 1 : 0) } final public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if indexPath.row == attachments.count && showAddAttachmentCell { return createAttachmentCell(in: collectionView, at: indexPath) } let attachment = attachments[indexPath.row] if let cell = dataSource?.attachmentManager(self, cellFor: attachment, at: indexPath.row) { return cell } else { // Only images are supported by default switch attachment { case .image(let image): guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ImageAttachmentCell.reuseIdentifier, for: indexPath) as? ImageAttachmentCell else { fatalError() } cell.attachment = attachment cell.indexPath = indexPath cell.manager = self cell.imageView.image = image cell.imageView.tintColor = tintColor cell.deleteButton.backgroundColor = tintColor return cell default: return collectionView.dequeueReusableCell(withReuseIdentifier: AttachmentCell.reuseIdentifier, for: indexPath) as! AttachmentCell } } } // MARK: - UICollectionViewDelegateFlowLayout final public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { if let customSize = self.dataSource?.attachmentManager(self, sizeFor: self.attachments[indexPath.row], at: indexPath.row){ return customSize } var height = attachmentView.intrinsicContentHeight if let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout { height -= (layout.sectionInset.bottom + layout.sectionInset.top + collectionView.contentInset.top + collectionView.contentInset.bottom) } return CGSize(width: height, height: height) } @objc open func createAttachmentCell(in collectionView: UICollectionView, at indexPath: IndexPath) -> AttachmentCell { guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: AttachmentCell.reuseIdentifier, for: indexPath) as? AttachmentCell else { fatalError() } cell.deleteButton.isHidden = true // Draw a plus let frame = CGRect(origin: CGPoint(x: cell.bounds.origin.x, y: cell.bounds.origin.y), size: CGSize(width: cell.bounds.width - cell.padding.left - cell.padding.right, height: cell.bounds.height - cell.padding.top - cell.padding.bottom)) let strokeWidth: CGFloat = 3 let length: CGFloat = frame.width / 2 let grayColor: UIColor if #available(iOS 13, *) { grayColor = .systemGray2 } else { grayColor = .lightGray } let vLayer = CAShapeLayer() vLayer.path = UIBezierPath(roundedRect: CGRect(x: frame.midX - (strokeWidth / 2), y: frame.midY - (length / 2), width: strokeWidth, height: length), cornerRadius: 5).cgPath vLayer.fillColor = grayColor.cgColor let hLayer = CAShapeLayer() hLayer.path = UIBezierPath(roundedRect: CGRect(x: frame.midX - (length / 2), y: frame.midY - (strokeWidth / 2), width: length, height: strokeWidth), cornerRadius: 5).cgPath hLayer.fillColor = grayColor.cgColor cell.containerView.layer.addSublayer(vLayer) cell.containerView.layer.addSublayer(hLayer) return cell } }
50441b9469d559aa83db4548f6bddbf9
40.776892
173
0.628552
false
false
false
false
kickstarter/ios-oss
refs/heads/main
Library/UILabel+SimpleHTML.swift
apache-2.0
1
import class UIKit.UILabel public extension UILabel { func setHTML(_ html: String) { // Capture a few properties of the label so that they can be restored after setting the attributed text. let textColor = self.textColor let textAlignment = self.textAlignment self.attributedText = html.simpleHtmlAttributedString(font: self.font) // restore properties self.textColor = textColor self.textAlignment = textAlignment } }
01502ebe71044129be3295bedc9cc2bb
29.266667
108
0.740088
false
false
false
false
Diego5529/quaddro-mm
refs/heads/master
AprendendoSwift/AprendendoSwift-parte7-funcoesclosures.playground/Contents.swift
apache-2.0
3
//: Quaddro - noun: a place where people can learn //Função que retorna a área do quadrado func quadrado(lado: Float)->Float{ return lado * lado } //Função que retorna a área do Cubo func cubo(lado: Float)->Float{ return lado * lado * lado } //Criando nossa função que recebe uma closure func media(ladoA: Float, ladoB: Float, forma: (Float -> Float))->Float{ return (forma(ladoA) + forma(ladoB)) / 2 } //Utilizando nossas funções. media(10, 20, cubo) media(2, 4, quadrado) media(2, 4, {(valor: Float)-> Float in return valor * valor }) media(2, 4, {$0 * $0}) media(2, 4){$0 * $0} //Criamos um array let numeros: [Int] = [10, 32, 1, 15, 40, 10329, 198, 947] //Filtramos apenas os valores pares dentro do array numerosPares var numerosPares = numeros.filter({(valor) in valor % 2 == 0}) numerosPares var somaImpar = numeros.filter({$0 % 2 != 0}) .reduce(0, combine: {$0 + $1}) somaImpar var novosPares = numeros.filter({$0 % 2 != 0}) .map({$0 + 1}) novosPares
29432570141a71a683035a380acb8441
18.109091
71
0.616556
false
false
false
false
yoshiki/LINEBotAPI
refs/heads/master
Sources/Client.swift
mit
1
import JSON import Curl public typealias Headers = [(String,String)] public enum ClientError: Error { case invalidURI, unknownError } public struct Client { var headers: Headers let curl = Curl() public init(headers: Headers) { self.headers = headers } public func get(uri: String) -> Data? { return curl.get(url: uri, headers: headers) } public func post(uri: String, json: JSON? = nil) -> Data? { if let json = json { return curl.post(url: uri, headers: headers, body: JSONSerializer().serialize(json: json)) } else { return curl.post(url: uri, headers: headers, body: "") } } }
1c8315c71bbad30ae75b02fb1f20fe85
22.689655
102
0.604076
false
false
false
false
guidomb/Portal
refs/heads/master
Example/Views/Examples/SpinnerScreen.swift
mit
1
// // SpinnerScreen.swift // PortalExample // // Created by Argentino Ducret on 9/5/17. // Copyright © 2017 Guido Marucci Blas. All rights reserved. // import Portal enum SpinnerScreen { typealias Action = Portal.Action<Route, Message> typealias View = Portal.View<Route, Message, Navigator> static func view() -> View { return View( navigator: .main, root: .stack(ExampleApplication.navigationBar(title: "Spinner")), component: container( children: [ createSpinner() ], style: styleSheet { $0.backgroundColor = .black }, layout: layout { $0.flex = flex() { $0.grow = .one } } ) ) } } // MARK: - Private Methods fileprivate extension SpinnerScreen { fileprivate static func createSpinner() -> Component<Action> { return spinner( style: spinnerStyleSheet { base, spinner in base.backgroundColor = .black spinner.color = .red }, layout: layout { $0.justifyContent = .center $0.alignment = alignment { $0.`self` = .center } } ) } }
2e9aec0be87f11cfaf71a42e4d76e667
24.169811
77
0.49925
false
false
false
false
Anish-kumar-dev/Starscream
refs/heads/master
examples/SimpleTest/SimpleTest/ViewController.swift
apache-2.0
6
// // ViewController.swift // SimpleTest // // Created by Dalton Cherry on 8/12/14. // Copyright (c) 2014 vluxe. All rights reserved. // import UIKit import Starscream class ViewController: UIViewController, WebSocketDelegate { var socket = WebSocket(url: NSURL(scheme: "ws", host: "localhost:8080", path: "/")!, protocols: ["chat", "superchat"]) override func viewDidLoad() { super.viewDidLoad() socket.delegate = self socket.connect() } // MARK: Websocket Delegate Methods. func websocketDidConnect(ws: WebSocket) { println("websocket is connected") } func websocketDidDisconnect(ws: WebSocket, error: NSError?) { if let e = error { println("websocket is disconnected: \(e.localizedDescription)") } else { println("websocket disconnected") } } func websocketDidReceiveMessage(ws: WebSocket, text: String) { println("Received text: \(text)") } func websocketDidReceiveData(ws: WebSocket, data: NSData) { println("Received data: \(data.length)") } // MARK: Write Text Action @IBAction func writeText(sender: UIBarButtonItem) { socket.writeString("hello there!") } // MARK: Disconnect Action @IBAction func disconnect(sender: UIBarButtonItem) { if socket.isConnected { sender.title = "Connect" socket.disconnect() } else { sender.title = "Disconnect" socket.connect() } } }
9341cca80323392d80a513f91c01b521
24.548387
122
0.59596
false
false
false
false
einsteinx2/iSub
refs/heads/master
Frameworks/fmdb/Swift extensions/FMDatabasePoolAdditionsVariadic.swift
gpl-3.0
1
// // FMDatabasePoolAdditionsVariadic.swift // iSub // // Created by Benjamin Baron on 1/14/17. // Copyright © 2017 Ben Baron. All rights reserved. // import Foundation extension FMDatabasePool { func stringForQuery(_ sql: String, _ values: Any...) -> String? { var value: String? self.inDatabase { db in value = db.stringForQuery(sql, values) } return value } func intOptionalForQuery(_ sql: String, _ values: Any...) -> Int? { var value: Int? self.inDatabase { db in value = db.intOptionalForQuery(sql, values) } return value } func intForQuery(_ sql: String, _ values: Any...) -> Int { return intOptionalForQuery(sql, values) ?? 0 } func int32OptionalForQuery(_ sql: String, _ values: Any...) -> Int32? { var value: Int32? self.inDatabase { db in value = db.int32OptionalForQuery(sql, values) } return value } func int32ForQuery(_ sql: String, _ values: Any...) -> Int32 { return int32OptionalForQuery(sql, values) ?? 0 } func int64OptionalForQuery(_ sql: String, _ values: Any...) -> Int64? { var value: Int64? self.inDatabase { db in value = db.int64OptionalForQuery(sql, values) } return value } func int64ForQuery(_ sql: String, _ values: Any...) -> Int64 { return int64OptionalForQuery(sql, values) ?? 0 } func boolOptionalForQuery(_ sql: String, _ values: Any...) -> Bool? { var value: Bool? self.inDatabase { db in value = db.boolOptionalForQuery(sql, values) } return value } func boolForQuery(_ sql: String, _ values: Any...) -> Bool { return boolOptionalForQuery(sql, values) ?? false } func doubleOptionalForQuery(_ sql: String, _ values: Any...) -> Double? { var value: Double? self.inDatabase { db in value = db.doubleOptionalForQuery(sql, values) } return value } func doubleForQuery(_ sql: String, _ values: Any...) -> Double { return doubleOptionalForQuery(sql, values) ?? 0.0 } func dateForQuery(_ sql: String, _ values: Any...) -> Date? { var value: Date? self.inDatabase { db in value = db.dateForQuery(sql, values) } return value } func dataForQuery(_ sql: String, _ values: Any...) -> Data? { var value: Data? self.inDatabase { db in value = db.dataForQuery(sql, values) } return value } }
7c628d1be1ca55d7b3dba1bc7b82f740
27.168421
77
0.555306
false
false
false
false