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
wikimedia/wikipedia-ios
refs/heads/main
Wikipedia/Code/ArticleTableOfContentsDisplayController.swift
mit
1
// Handles hide/display of article table of contents // Manages a stack view and the associated constraints protocol ArticleTableOfContentsDisplayControllerDelegate : TableOfContentsViewControllerDelegate { func tableOfContentsDisplayControllerDidRecreateTableOfContentsViewController() func getVisibleSection(with: @escaping (Int, String) -> Void) func stashOffsetPercentage() } class ArticleTableOfContentsDisplayController: Themeable { weak var delegate: ArticleTableOfContentsDisplayControllerDelegate? lazy var viewController: TableOfContentsViewController = { return recreateTableOfContentsViewController() }() var theme: Theme = .standard let articleView: WKWebView func apply(theme: Theme) { self.theme = theme separatorView.backgroundColor = theme.colors.baseBackground stackView.backgroundColor = theme.colors.paperBackground inlineContainerView.backgroundColor = theme.colors.midBackground viewController.apply(theme: theme) } func recreateTableOfContentsViewController() -> TableOfContentsViewController { let displaySide: TableOfContentsDisplaySide = stackView.semanticContentAttribute == .forceRightToLeft ? .right : .left return TableOfContentsViewController(delegate: delegate, theme: theme, displaySide: displaySide) } init (articleView: WKWebView, delegate: ArticleTableOfContentsDisplayControllerDelegate, theme: Theme) { self.delegate = delegate self.theme = theme self.articleView = articleView stackView.semanticContentAttribute = delegate.tableOfContentsSemanticContentAttribute stackView.addArrangedSubview(inlineContainerView) stackView.addArrangedSubview(separatorView) stackView.addArrangedSubview(articleView) NSLayoutConstraint.activate([separatorWidthConstraint]) } lazy var stackView: UIStackView = { let stackView = UIStackView(frame: CGRect(x: 0, y: 0, width: 1, height: 1)) stackView.axis = .horizontal stackView.distribution = .fill stackView.alignment = .fill return stackView }() lazy var separatorView: UIView = { let sv = UIView(frame: .zero) sv.isHidden = true return sv }() lazy var inlineContainerView: UIView = { let cv = UIView(frame: .zero) cv.isHidden = true return cv }() lazy var separatorWidthConstraint: NSLayoutConstraint = { return separatorView.widthAnchor.constraint(equalToConstant: 1) }() func show(animated: Bool) { switch viewController.displayMode { case .inline: showInline() case .modal: showModal(animated: animated) } } func hide(animated: Bool) { switch viewController.displayMode { case .inline: hideInline() case .modal: hideModal(animated: animated) } } func showModal(animated: Bool) { guard delegate?.presentedViewController == nil else { return } delegate?.getVisibleSection(with: { (sectionId, _) in self.viewController.isVisible = true self.selectAndScroll(to: sectionId, animated: false) self.delegate?.present(self.viewController, animated: animated) }) } func hideModal(animated: Bool) { viewController.isVisible = false delegate?.dismiss(animated: animated) } func showInline() { delegate?.stashOffsetPercentage() viewController.isVisible = true UserDefaults.standard.wmf_setTableOfContentsIsVisibleInline(true) inlineContainerView.isHidden = false separatorView.isHidden = false } func hideInline() { delegate?.stashOffsetPercentage() viewController.isVisible = false UserDefaults.standard.wmf_setTableOfContentsIsVisibleInline(false) inlineContainerView.isHidden = true separatorView.isHidden = true } func setup(with traitCollection:UITraitCollection) { update(with: traitCollection) guard viewController.displayMode == .inline, UserDefaults.standard.wmf_isTableOfContentsVisibleInline() else { return } showInline() } func update(with traitCollection: UITraitCollection) { let isCompact = traitCollection.horizontalSizeClass == .compact viewController.displayMode = isCompact ? .modal : .inline setupTableOfContentsViewController() } func setupTableOfContentsViewController() { switch viewController.displayMode { case .inline: guard viewController.parent != delegate else { return } let wasVisible = viewController.isVisible if wasVisible { hideModal(animated: false) } viewController = recreateTableOfContentsViewController() viewController.displayMode = .inline delegate?.addChild(viewController) inlineContainerView.wmf_addSubviewWithConstraintsToEdges(viewController.view) viewController.didMove(toParent: delegate) if wasVisible { showInline() } delegate?.tableOfContentsDisplayControllerDidRecreateTableOfContentsViewController() case .modal: guard viewController.parent == delegate else { return } let wasVisible = viewController.isVisible viewController.displayMode = .modal viewController.willMove(toParent: nil) viewController.view.removeFromSuperview() viewController.removeFromParent() viewController = recreateTableOfContentsViewController() if wasVisible { hideInline() showModal(animated: false) } delegate?.tableOfContentsDisplayControllerDidRecreateTableOfContentsViewController() } } func selectAndScroll(to sectionId: Int, animated: Bool) { guard let index = delegate?.tableOfContentsItems.firstIndex(where: { $0.id == sectionId }) else { return } viewController.selectItem(at: index) viewController.scrollToItem(at: index) } }
2a1bed9652545182588178cad9492d0e
35.050562
126
0.658719
false
false
false
false
GlebRadchenko/AdvertServer
refs/heads/master
Sources/App/Models/Advertisment.swift
mit
1
// // Advertisment.swift // AdvertServer // // Created by GlebRadchenko on 11/23/16. // // import Foundation import Vapor import Fluent final class Advertisment: Model { static let databaseName = "advertisments" var id: Node? var title: String var description: String var media: String? var parentId: Node? var exists: Bool = false init(title: String, description: String) { self.title = title self.description = description } init(node: Node, in context: Context) throws { id = try node.extract("id") title = try node.extract("title") description = try node.extract("description") media = try node.extract("media") parentId = try node.extract("parentId") } func makeNode(context: Context) throws -> Node { return try Node(node: [ "_id": id, "title": title, "description": description, "media": media, "parentId": parentId ]) } static func prepare(_ database: Database) throws { try database.create(self.databaseName) { advertisments in advertisments.id() advertisments.string("title") advertisments.string("description") advertisments.string("media", length: nil, optional: true) advertisments.id("parentId", optional: false) } } static func revert(_ database: Database) throws { try database.delete(self.databaseName) } } extension Advertisment { func beacon() throws -> Parent<Beacon> { return try parent(parentId) } }
c2db24577149ae2937f2eb7eb8c1f9d1
24.953125
70
0.59121
false
false
false
false
Bluthwort/Bluthwort
refs/heads/master
Sources/Classes/Style/UIScrollViewStyle.swift
mit
1
// // UIScrollViewStyle.swift // // Copyright (c) 2018 Bluthwort // // 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. // extension Bluthwort where Base: UIScrollView { @discardableResult public func delegate(_ delegate: UIScrollViewDelegate?) -> Bluthwort { // The delegate of the scroll-view object. base.delegate = delegate return self } @discardableResult public func contentSize(_ size: CGSize) -> Bluthwort { // The size of the content view. base.contentSize = size return self } @discardableResult public func contentOffset(_ offset: CGPoint, animated: Bool? = nil) -> Bluthwort { if let animated = animated { // Sets the offset from the content view’s origin that corresponds to the receiver’s // origin. base.setContentOffset(offset, animated: animated) } else { // The point at which the origin of the content view is offset from the origin of the // scroll view. base.contentOffset = offset } return self } @discardableResult public func contentInset(_ inset: UIEdgeInsets) -> Bluthwort { // The insets derived from the content insets and the safe area of the scroll view. base.contentInset = inset return self } @available(iOS 11.0, *) @discardableResult public func contentInsetAdjustmentBehavior(_ behavior: UIScrollViewContentInsetAdjustmentBehavior) -> Bluthwort { // The behavior for determining the adjusted content offsets. base.contentInsetAdjustmentBehavior = behavior return self } @discardableResult public func isScrollEnabled(_ flag: Bool) -> Bluthwort { // A Boolean value that determines whether scrolling is enabled. base.isScrollEnabled = flag return self } @discardableResult public func isDirectionalLockEnabled(_ flag: Bool) -> Bluthwort { // A Boolean value that determines whether scrolling is disabled in a particular direction. base.isDirectionalLockEnabled = flag return self } @discardableResult public func isPagingEnabled(_ flag: Bool) -> Bluthwort { // A Boolean value that determines whether paging is enabled for the scroll view. base.isPagingEnabled = flag return self } @discardableResult public func scrollsToTop(_ flag: Bool) -> Bluthwort { // A Boolean value that controls whether the scroll-to-top gesture is enabled. base.scrollsToTop = flag return self } @discardableResult public func bounces(_ flag: Bool) -> Bluthwort { // A Boolean value that controls whether the scroll view bounces past the edge of content // and back again. base.bounces = flag return self } @discardableResult public func alwaysBounceVertical(_ flag: Bool) -> Bluthwort { // A Boolean value that determines whether bouncing always occurs when vertical scrolling // reaches the end of the content. base.alwaysBounceVertical = flag return self } @discardableResult public func alwaysBounceHorizontal(_ flag: Bool) -> Bluthwort { // A Boolean value that determines whether bouncing always occurs when horizontal scrolling // reaches the end of the content view. base.alwaysBounceHorizontal = flag return self } @discardableResult public func decelerationRate(_ rate: CGFloat) -> Bluthwort { // A floating-point value that determines the rate of deceleration after the user lifts their finger. base.decelerationRate = rate return self } @discardableResult public func indicatorStyle(_ style: UIScrollViewIndicatorStyle) -> Bluthwort { // The style of the scroll indicators. base.indicatorStyle = style return self } @discardableResult public func scrollIndicatorInsets(_ insets: UIEdgeInsets) -> Bluthwort { // The distance the scroll indicators are inset from the edge of the scroll view. base.scrollIndicatorInsets = insets return self } @discardableResult public func showsHorizontalScrollIndicator(_ flag: Bool) -> Bluthwort { // A Boolean value that controls whether the horizontal scroll indicator is visible. base.showsHorizontalScrollIndicator = flag return self } @discardableResult public func showsVerticalScrollIndicator(_ flag: Bool) -> Bluthwort { // A Boolean value that controls whether the vertical scroll indicator is visible. base.showsVerticalScrollIndicator = flag return self } @available(iOS 10.0, *) @discardableResult public func refreshControl(_ refreshControl: UIRefreshControl?) -> Bluthwort { // The refresh control associated with the scroll view. base.refreshControl = refreshControl return self } @discardableResult public func canCancelContentTouches(_ flag: Bool) -> Bluthwort { // A Boolean value that controls whether touches in the content view always lead to tracking. base.canCancelContentTouches = flag return self } @discardableResult public func delaysContentTouches(_ flag: Bool) -> Bluthwort { // A Boolean value that determines whether the scroll view delays the handling of touch-down // gestures. base.delaysContentTouches = flag return self } @discardableResult public func zoomScale(_ scale: CGFloat) -> Bluthwort { // A floating-point value that specifies the current scale factor applied to the scroll // view's content. base.zoomScale = scale return self } @discardableResult public func maximumZoomScale(_ scale: CGFloat) -> Bluthwort { // A floating-point value that specifies the maximum scale factor that can be applied to the // scroll view's content. base.maximumZoomScale = scale return self } @discardableResult public func minimumZoomScale(_ scale: CGFloat) -> Bluthwort { // A floating-point value that specifies the current scale factor applied to the scroll // view's content. base.minimumZoomScale = scale return self } @discardableResult public func bouncesZoom(_ flag: Bool) -> Bluthwort { // A Boolean value that determines whether the scroll view animates the content scaling when // the scaling exceeds the maximum or minimum limits. base.bouncesZoom = flag return self } @discardableResult public func keyboardDismissMode(_ mode: UIScrollViewKeyboardDismissMode) -> Bluthwort { // The manner in which the keyboard is dismissed when a drag begins in the scroll view. base.keyboardDismissMode = mode return self } @discardableResult public func indexDisplayMode(_ mode: UIScrollViewIndexDisplayMode) -> Bluthwort { // The manner in which the index is shown while the user is scrolling. base.indexDisplayMode = mode return self } }
a0384b4d3979b508f435186a546e3e0e
35.619469
117
0.67883
false
false
false
false
auth0/native-mobile-samples
refs/heads/master
iOS/basic-sample-swift/SwiftSample/HomeViewController.swift
mit
1
// HomeViewController.swift // // Copyright (c) 2014 Auth0 (http://auth0.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit import JWTDecode import MBProgressHUD import Lock class HomeViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() let keychain = MyApplication.sharedInstance.keychain if let idToken = keychain.stringForKey("id_token"), let jwt = try? JWTDecode.decode(idToken) { if jwt.expired, let refreshToken = keychain.stringForKey("refresh_token") { MBProgressHUD.showHUDAddedTo(self.view, animated: true) let success = {(token:A0Token!) -> () in keychain.setString(token.idToken, forKey: "id_token") MBProgressHUD.hideHUDForView(self.view, animated: true) self.performSegueWithIdentifier("showProfile", sender: self) } let failure = {(error:NSError!) -> () in keychain.clearAll() MBProgressHUD.hideHUDForView(self.view, animated: true) } let client = MyApplication.sharedInstance.lock.apiClient() client.fetchNewIdTokenWithRefreshToken(refreshToken, parameters: nil, success: success, failure: failure) } else { self.performSegueWithIdentifier("showProfile", sender: self) } } } @IBAction func showSignIn(sender: AnyObject) { let lock = MyApplication.sharedInstance.lock let authController = lock.newLockViewController() authController.closable = true authController.onAuthenticationBlock = { (profile, token) -> () in switch (profile, token) { case (.Some(let profile), .Some(let token)): let keychain = MyApplication.sharedInstance.keychain keychain.setString(token.idToken, forKey: "id_token") if let refreshToken = token.refreshToken { keychain.setString(refreshToken, forKey: "refresh_token") } keychain.setData(NSKeyedArchiver.archivedDataWithRootObject(profile), forKey: "profile") self.dismissViewControllerAnimated(true, completion: nil) self.performSegueWithIdentifier("showProfile", sender: self) default: print("User signed up without logging in") } } self.presentViewController(authController, animated: true, completion: nil) } }
4bba0dd50ac71770c03362c9f96fdae4
46.263158
121
0.6598
false
false
false
false
SereivoanYong/Charts
refs/heads/master
Source/Charts/Data/Implementations/Standard/RadarDataSet.swift
apache-2.0
1
// // RadarDataSet.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import UIKit open class RadarDataSet: LineRadarDataSet, IRadarChartDataSet { fileprivate func initialize() { valueFont = .systemFont(ofSize: 13.0) } public required init() { super.init() initialize() } public required override init(values: [Entry], label: String?) { super.init(values: values, label: label) initialize() } // MARK: - Data functions and accessors // MARK: - Styling functions and accessors /// flag indicating whether highlight circle should be drawn or not /// **default**: false open var isDrawHighlightCircleEnabled: Bool = false open var highlightCircleFillColor: UIColor? = .white /// The stroke color for highlight circle. /// If `nil`, the color of the dataset is taken. open var highlightCircleStrokeColor: UIColor? open var highlightCircleStrokeAlpha: CGFloat = 0.3 open var highlightCircleInnerRadius: CGFloat = 3.0 open var highlightCircleOuterRadius: CGFloat = 4.0 open var highlightCircleStrokeWidth: CGFloat = 2.0 }
605c90e7ac31c879be0426dd602bf2ee
23.288462
69
0.698337
false
false
false
false
Alienson/Bc
refs/heads/master
source-code/Parketovanie/ParquetElko.swift
apache-2.0
1
// // ParquetElko.swift // Parketovanie // // Created by Adam Turna on 4.4.2016. // Copyright © 2016 Adam Turna. All rights reserved. // import Foundation import SpriteKit class ParquetElko: Parquet { init(parent: SKSpriteNode, position: CGPoint){ super.init(imageNamed: "6-elko", position: position) let abstractCell = Cell() let height = abstractCell.frame.height // self.arrayOfCells.append(Cell(position: CGPoint(x: self.frame.minX, y: self.frame.maxY-height), parent: parent)) // self.arrayOfCells.append(Cell(position: CGPoint(x: self.frame.minX, y: self.frame.maxY-height*2), parent: parent)) // self.arrayOfCells.append(Cell(position: CGPoint(x: self.frame.minX, y: self.frame.maxY-height*3), parent: parent)) // self.arrayOfCells.append(Cell(position: CGPoint(x: self.frame.minX+height, y: self.frame.maxY-height*3), parent: parent)) self.arrayOfCells.append(Cell(position: CGPoint(x: -height/2, y: height), parent: parent)) self.arrayOfCells.append(Cell(position: CGPoint(x: -height/2, y: 0), parent: parent)) self.arrayOfCells.append(Cell(position: CGPoint(x: -height/2, y: -height), parent: parent)) self.arrayOfCells.append(Cell(position: CGPoint(x: height/2, y: -height), parent: parent)) //let cell1 = Cell(row: 1, collumn: 1, isEmpty: true, parent: parent) for cell in self.arrayOfCells { //parent.addChild(cell) self.addChild(cell) cell.anchorPoint = CGPoint(x: 0.5, y: 0.5) cell.alpha = CGFloat(1) cell.barPosition = cell.position } super.alpha = CGFloat(0.5) //self.arrayOfCells = [[Cell(position: CGPoint(self.frame.),parent: parent), nil],[Cell(parent: parent), nil],[Cell(parent: parent), Cell(parent: parent)]] } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
03b36ffe869b701f4d77f6b8c422dd7e
43.044444
163
0.645129
false
false
false
false
031240302/DouYuZB
refs/heads/master
DYZB/DYZB/Main/View/PageContentView.swift
mit
1
// // PageContentView.swift // DYZB // // Created by kk on 2017/10/12. // Copyright © 2017年 kk. All rights reserved. // import UIKit protocol PageContentViewDelegate: class { func pageContentView(contentView: PageContentView, progress: CGFloat, sourceIndex: Int, targetInde: Int) } private let ContentCellId = "ContentCellId" class PageContentView: UIView { // MARK:- 定义属性 private var childVcs: [UIViewController] private weak var parentViewController: UIViewController? private var startOffsetX: CGFloat = 0 weak var delegate: PageContentViewDelegate? private var isForbidScrollDelegate: Bool = false // MARK:- 懒加载属性 private lazy var collectionView: UICollectionView = { [weak self] in // 1.创建layout let layout = UICollectionViewFlowLayout() layout.itemSize = (self?.bounds.size)! layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.scrollDirection = .horizontal // 2.创建UICollectionView let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout) collectionView.showsHorizontalScrollIndicator = false collectionView.isPagingEnabled = true collectionView.bounces = false collectionView.dataSource = self collectionView.delegate = self collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: ContentCellId) collectionView.backgroundColor = UIColor.gray return collectionView }() // MARK:- 自定义构造函数 init(frame: CGRect, childVcs: [UIViewController], parentViewController: UIViewController?) { self.childVcs = childVcs self.parentViewController = parentViewController super.init(frame: frame) // 设置UI setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK:- 设置UI界面 extension PageContentView { private func setupUI() { // 1.将所有的子控制器添加到父控制器 for childVc in childVcs { parentViewController?.addChildViewController(childVc) } // 2.添加UICollectionView,用于在Cell中存放控制器View collectionView.frame = bounds self.addSubview(collectionView) } } // MARK:- 遵守UICollectionViewDataSource extension PageContentView: UICollectionViewDataSource{ func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return childVcs.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { // 1.创建cell let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ContentCellId, for: indexPath) // 2.给cell设置内容 for view in cell.subviews { view.removeFromSuperview() } let childVc = childVcs[indexPath.item] childVc.view.frame = cell.contentView.bounds cell.addSubview(childVc.view) return cell } } // MARK:- 遵守UICollectionViewDelegate extension PageContentView: UICollectionViewDelegate { func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { isForbidScrollDelegate = false startOffsetX = scrollView.contentOffset.x } func scrollViewDidScroll(_ scrollView: UIScrollView) { // 0.判断是否是点击事件 if isForbidScrollDelegate { return } // 1.获取需要的数据 var progress: CGFloat = 0 var sourceIndex: Int = 0 var targetIndex: Int = 0 // 2.判断是左滑还是右滑 let currentOffsetX = scrollView.contentOffset.x let scrollViewW = scrollView.bounds.width if currentOffsetX > startOffsetX { // 左滑 progress = currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW) // 2.计算sourceIndex sourceIndex = Int(currentOffsetX / scrollViewW) // 3.计算targetIndex targetIndex = sourceIndex + 1 if targetIndex >= childVcs.count { targetIndex = childVcs.count - 1 } } else { // 右滑 // 1.计算progress(滑动比例) progress = 1 - (currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW)) // 2.计算targetIndex targetIndex = Int(currentOffsetX / scrollViewW) // 3.计算sourceIndex sourceIndex = targetIndex + 1 if sourceIndex >= childVcs.count { sourceIndex = childVcs.count - 1 } // 4.如果完全划过去 if currentOffsetX - startOffsetX == scrollViewW { progress = 1 targetIndex = sourceIndex } } // 3.将progress/sourceIndex/targetIndex传递给titleView delegate?.pageContentView(contentView: self, progress: progress, sourceIndex: sourceIndex, targetInde: targetIndex) } } // MARK:- 对外暴露的方法 extension PageContentView { func setCurrentIndex(currentIndex: Int) { // 1.记录需要禁止直行的代理方法 isForbidScrollDelegate = true // 2.滚动到正确的位置 let offsetX = CGFloat(currentIndex) * collectionView.frame.width collectionView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: false) } }
c30ed9a5fae8405eb0455e4904b7984a
31.359281
123
0.637121
false
false
false
false
testpress/ios-app
refs/heads/master
ios-app/Utils/VideoPlayerUtils.swift
mit
1
// // VideoPlayerUtils.swift // ios-app // // Created by Karthik raja on 12/6/19. // Copyright © 2019 Testpress. All rights reserved. // import Foundation enum PlaybackSpeed:String { case verySlow = "0.5x" case slow = "0.75x" case normal = "Normal" case fast = "1.25x" case veryFast = "1.5x" case double = "2x" var value: Float { switch self { case .verySlow: return 0.5 case .slow: return 0.75 case .normal: return 1.00 case .fast: return 1.25 case .veryFast: return 1.5 case .double: return 2.00 } } var label: String { switch self { case .normal: return "1x" default: return self.rawValue } } } extension PlaybackSpeed: CaseIterable {} enum PlayerStatus { case readyToPlay case playing case paused case finished } enum VideoDurationType { case remainingTime case totalTime func getDurationString (seconds : Double) -> String { if seconds.isNaN || seconds.isInfinite { return "00:00" } let hour = Int(seconds) / 3600 let minute = Int(seconds) / 60 % 60 let second = Int(seconds) % 60 let time = hour > 0 ? String(format: "%02i:%02i:%02i", hour, minute, second) :String(format: "%02i:%02i", minute, second) return time } func value(seconds:Double, total:Double) -> String { switch self { case .remainingTime: return "-\(getDurationString(seconds: total-seconds))" case .totalTime: return getDurationString(seconds: total) } } } struct VideoQuality { var resolution: String var bitrate: Int }
e40decc0eba39c194dd3a4d26a7fc1fe
20.27907
129
0.549727
false
false
false
false
Shivol/Swift-CS333
refs/heads/master
playgrounds/persistence/notes-core-data/notes-core-data/AppDelegate.swift
mit
2
// // AppDelegate.swift // notes-core-data // // Created by Илья Лошкарёв on 22.03.17. // Copyright © 2017 Илья Лошкарёв. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { let splitViewController = self.window!.rootViewController as! UISplitViewController splitViewController.delegate = self let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem return true } func applicationWillTerminate(_ application: UIApplication) { CoreDataContainer.saveContext() } // MARK: - Split view func splitViewController(_ splitViewController: UISplitViewController, collapseSecondary secondaryViewController:UIViewController, onto primaryViewController:UIViewController) -> Bool { guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false } guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false } if topAsDetailController.detailItem == nil { // Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded. return true } return false } }
6ad52905dc024e0ca20935f9648faec3
38.590909
189
0.752009
false
false
false
false
onevcat/CotEditor
refs/heads/develop
CotEditor/Sources/SyntaxManager.swift
apache-2.0
1
// // SyntaxManager.swift // // CotEditor // https://coteditor.com // // Created by nakamuxu on 2004-12-24. // // --------------------------------------------------------------------------- // // © 2004-2007 nakamuxu // © 2014-2022 1024jp // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Combine import Foundation import UniformTypeIdentifiers import Yams @objc protocol SyntaxHolder: AnyObject { func changeSyntaxStyle(_ sender: AnyObject?) func recolorAll(_ sender: Any?) } enum BundledStyleName { static let none: SyntaxManager.SettingName = "None".localized(comment: "syntax style name") static let xml: SyntaxManager.SettingName = "XML" static let markdown: SyntaxManager.SettingName = "Markdown" } // MARK: - final class SyntaxManager: SettingFileManaging { typealias Setting = SyntaxStyle typealias SettingName = String typealias StyleDictionary = [String: Any] // MARK: Public Properties static let shared = SyntaxManager() // MARK: Setting File Managing Properties let didUpdateSetting: PassthroughSubject<SettingChange, Never> = .init() static let directoryName: String = "Syntaxes" let fileType: UTType = .yaml @Published var settingNames: [SettingName] = [] let bundledSettingNames: [SettingName] @Atomic var cachedSettings: [SettingName: Setting] = [:] // MARK: Private Properties private let bundledMap: [SettingName: [String: [String]]] @Atomic private var mappingTables: [SyntaxKey: [String: [SettingName]]] = [.extensions: [:], .filenames: [:], .interpreters: [:]] // MARK: - // MARK: Lifecycle private init() { // load bundled style list let url = Bundle.main.url(forResource: "SyntaxMap", withExtension: "json")! let data = try! Data(contentsOf: url) let map = try! JSONDecoder().decode([SettingName: [String: [String]]].self, from: data) self.bundledMap = map self.bundledSettingNames = map.keys.sorted(options: [.localized, .caseInsensitive]) // sanitize user setting file extensions try? self.sanitizeUserSettings() // cache user styles self.checkUserSettings() } // MARK: Public Methods /// return style name corresponding to given variables func settingName(documentFileName fileName: String, content: String) -> SettingName { return self.settingName(documentFileName: fileName) ?? self.settingName(documentContent: content) ?? BundledStyleName.none } /// return style name corresponding to file name func settingName(documentFileName fileName: String) -> SettingName? { let mappingTables = self.mappingTables if let settingName = mappingTables[.filenames]?[fileName]?.first { return settingName } if let pathExtension = fileName.components(separatedBy: ".").last, let extentionTable = mappingTables[.extensions] { if let settingName = extentionTable[pathExtension]?.first { return settingName } // check case-insensitively let lowerPathExtension = pathExtension.lowercased() if let sttingName = extentionTable .first(where: { $0.key.lowercased() == lowerPathExtension })? .value.first { return sttingName } } return nil } /// return style name scanning shebang in document content func settingName(documentContent content: String) -> SettingName? { if let interpreter = content.scanInterpreterInShebang(), let settingName = self.mappingTables[.interpreters]?[interpreter]?.first { return settingName } // check XML declaration if content.hasPrefix("<?xml ") { return BundledStyleName.xml } return nil } /// style dictionary list corresponding to style name func settingDictionary(name: SettingName) -> StyleDictionary? { if name == BundledStyleName.none { return self.blankSettingDictionary } guard let url = self.urlForUsedSetting(name: name), let dictionary = try? self.loadSettingDictionary(at: url) else { return nil } return dictionary.cocoaBindable } /// return bundled version style dictionary or nil if not exists func bundledSettingDictionary(name: SettingName) -> StyleDictionary? { guard let url = self.urlForBundledSetting(name: name), let dictionary = try? self.loadSettingDictionary(at: url) else { return nil } return dictionary.cocoaBindable } /// save setting file func save(settingDictionary: StyleDictionary, name: SettingName, oldName: SettingName?) throws { // create directory to save in user domain if not yet exist try self.prepareUserSettingDirectory() // sort items let beginStringSort = NSSortDescriptor(key: SyntaxDefinitionKey.beginString.rawValue, ascending: true, selector: #selector(NSString.caseInsensitiveCompare)) for key in SyntaxType.allCases { (settingDictionary[key.rawValue] as? NSMutableArray)?.sort(using: [beginStringSort]) } let keyStringSort = NSSortDescriptor(key: SyntaxDefinitionKey.keyString.rawValue, ascending: true, selector: #selector(NSString.caseInsensitiveCompare)) for key in [SyntaxKey.outlineMenu, .completions] { (settingDictionary[key.rawValue] as? NSMutableArray)?.sort(using: [keyStringSort]) } // save let saveURL = self.preparedURLForUserSetting(name: name) // move old file to new place to overwrite when style name is also changed if let oldName = oldName, name != oldName { try self.renameSetting(name: oldName, to: name) } // just remove the current custom setting file in the user domain if new style is just the same as bundled one // so that application uses bundled one if self.isEqualToBundledSetting(settingDictionary, name: name) { if saveURL.isReachable { try FileManager.default.removeItem(at: saveURL) } } else { // save file to user domain let yamlString = try Yams.dump(object: settingDictionary.yamlEncodable, allowUnicode: true) try yamlString.write(to: saveURL, atomically: true, encoding: .utf8) } // invalidate current cache self.$cachedSettings.mutate { $0[name] = nil } if let oldName = oldName { self.$cachedSettings.mutate { $0[oldName] = nil } } // update internal cache let change: SettingChange = oldName.flatMap { .updated(from: $0, to: name) } ?? .added(name) self.updateSettingList(change: change) self.didUpdateSetting.send(change) } /// conflicted maps var mappingConflicts: [SyntaxKey: [String: [SettingName]]] { return self.mappingTables.mapValues { $0.filter { $0.value.count > 1 } } } /// empty style dictionary var blankSettingDictionary: StyleDictionary { return [ SyntaxKey.metadata.rawValue: NSMutableDictionary(), SyntaxKey.extensions.rawValue: NSMutableArray(), SyntaxKey.filenames.rawValue: NSMutableArray(), SyntaxKey.interpreters.rawValue: NSMutableArray(), SyntaxType.keywords.rawValue: NSMutableArray(), SyntaxType.commands.rawValue: NSMutableArray(), SyntaxType.types.rawValue: NSMutableArray(), SyntaxType.attributes.rawValue: NSMutableArray(), SyntaxType.variables.rawValue: NSMutableArray(), SyntaxType.values.rawValue: NSMutableArray(), SyntaxType.numbers.rawValue: NSMutableArray(), SyntaxType.strings.rawValue: NSMutableArray(), SyntaxType.characters.rawValue: NSMutableArray(), SyntaxType.comments.rawValue: NSMutableArray(), SyntaxKey.outlineMenu.rawValue: NSMutableArray(), SyntaxKey.completions.rawValue: NSMutableArray(), SyntaxKey.commentDelimiters.rawValue: NSMutableDictionary(), ] } // MARK: Setting File Managing /// return setting instance corresponding to the given setting name func setting(name: SettingName) -> Setting? { if name == BundledStyleName.none { return SyntaxStyle() } guard let setting: Setting = { if let setting = self.cachedSettings[name] { return setting } guard let url = self.urlForUsedSetting(name: name) else { return nil } let setting = try? self.loadSetting(at: url) self.$cachedSettings.mutate { $0[name] = setting } return setting }() else { return nil } // add to recent styles list let maximumRecentStyleCount = max(0, UserDefaults.standard[.maximumRecentStyleCount]) var recentStyleNames = UserDefaults.standard[.recentStyleNames] recentStyleNames.removeFirst(name) recentStyleNames.insert(name, at: 0) UserDefaults.standard[.recentStyleNames] = Array(recentStyleNames.prefix(maximumRecentStyleCount)) return setting } /// load setting from the file at given URL func loadSetting(at fileURL: URL) throws -> Setting { let dictionary = try self.loadSettingDictionary(at: fileURL) let name = self.settingName(from: fileURL) return SyntaxStyle(dictionary: dictionary, name: name) } /// load settings in the user domain func checkUserSettings() { // load mapping definitions from style files in user domain let mappingKeys = SyntaxKey.mappingKeys.map(\.rawValue) let userMap: [SettingName: [String: [String]]] = self.userSettingFileURLs.reduce(into: [:]) { (dict, url) in guard let style = try? self.loadSettingDictionary(at: url) else { return } let settingName = self.settingName(from: url) // create file mapping data dict[settingName] = style.filter { mappingKeys.contains($0.key) } .mapValues { $0 as? [[String: String]] ?? [] } .mapValues { $0.compactMap { $0[SyntaxDefinitionKey.keyString] } } } let map = self.bundledMap.merging(userMap) { (_, new) in new } // sort styles alphabetically self.settingNames = map.keys.sorted(options: [.localized, .caseInsensitive]) // remove styles not exist UserDefaults.standard[.recentStyleNames].removeAll { !self.settingNames.contains($0) } // update file mapping tables let settingNames = self.settingNames.filter { !self.bundledSettingNames.contains($0) } + self.bundledSettingNames // postpone bundled styles self.mappingTables = SyntaxKey.mappingKeys.reduce(into: [:]) { (tables, key) in tables[key] = settingNames.reduce(into: [String: [SettingName]]()) { (table, settingName) in guard let items = map[settingName]?[key.rawValue] else { return } for item in items { table[item, default: []].append(settingName) } } } } // MARK: Private Methods /// Standardize the file extensions of user setting files. /// /// - Note: The file extension for syntax definition files are changed from `.yaml` to `.yml` in CotEditor 4.2.0 released in 2022. private func sanitizeUserSettings() throws { let urls = self.userSettingFileURLs.filter { $0.pathExtension == "yaml" } guard !urls.isEmpty else { return } for url in urls { let newURL = url.deletingPathExtension().appendingPathExtension(for: .yaml) try FileManager.default.moveItem(at: url, to: newURL) } } /// Load StyleDictionary at file URL. /// /// - Parameter fileURL: URL to a setting file. /// - Throws: `CocoaError` private func loadSettingDictionary(at fileURL: URL) throws -> StyleDictionary { let string = try String(contentsOf: fileURL) let yaml = try Yams.load(yaml: string) guard let styleDictionary = yaml as? StyleDictionary else { throw CocoaError.error(.fileReadCorruptFile, url: fileURL) } return styleDictionary } /// return whether contents of given highlight definition is the same as bundled one private func isEqualToBundledSetting(_ style: StyleDictionary, name: SettingName) -> Bool { guard let bundledStyle = self.bundledSettingDictionary(name: name) else { return false } return style == bundledStyle } } private extension StringProtocol where Self.Index == String.Index { /// Extract interepreter from the shebang line. func scanInterpreterInShebang() -> String? { guard self.hasPrefix("#!") else { return nil } // get first line let firstLineRange = self.lineContentsRange(at: self.startIndex) let shebang = self[firstLineRange] .dropFirst("#!".count) .trimmingCharacters(in: .whitespacesAndNewlines) // find interpreter let components = shebang.components(separatedBy: " ") let interpreter = components.first?.components(separatedBy: "/").last // use first arg if the path targets env if interpreter == "env" { return components[safe: 1] } return interpreter } } // MARK: - Cocoa Bindings Support private extension SyntaxManager.StyleDictionary { /// Convert to NSObject-based collection for Cocoa-Bindings recursively. var cocoaBindable: Self { return self.mapValues(Self.convertToCocoaBindable) } /// Convert to YAML serialization comaptible colletion recursively. var yamlEncodable: Self { return self.mapValues(Self.convertToYAMLEncodable) } // MARK: Private Methods private static func convertToYAMLEncodable(_ item: Any) -> Any { switch item { case let dictionary as NSDictionary: return (dictionary as! Dictionary).mapValues(Self.convertToYAMLEncodable) case let array as NSArray: return (array as Array).map(Self.convertToYAMLEncodable) case let bool as Bool: return bool case let string as String: return string default: assertionFailure("\(type(of: item))") return item } } private static func convertToCocoaBindable(_ item: Any) -> Any { switch item { case let dictionary as Dictionary: return NSMutableDictionary(dictionary: dictionary.mapValues(convertToCocoaBindable)) case let array as [Any]: return NSMutableArray(array: array.map(convertToCocoaBindable)) case let date as Date: return ISO8601DateFormatter.string(from: date, timeZone: .current, formatOptions: [.withFullDate, .withDashSeparatorInDate]) default: return item } } } // MARK: - Equitability Support private extension SyntaxManager.StyleDictionary { static func == (lhs: Self, rhs: Self) -> Bool { return areEqual(lhs, rhs) } // MARK: Private Methods /// Check the equitability recursively. /// /// This comparison is designed and valid only for StyleDictionary. private static func areEqual(_ lhs: Any, _ rhs: Any) -> Bool { switch (lhs, rhs) { case let (lhs, rhs) as (Dictionary, Dictionary): guard lhs.count == rhs.count else { return false } return lhs.allSatisfy { (key, lhsValue) -> Bool in guard let rhsValue = rhs[key] else { return false } return areEqual(lhsValue, rhsValue) } case let (lhs, rhs) as ([Any], [Any]): guard lhs.count == rhs.count else { return false } // check elements equitability by ignoring the order var rhs = rhs for lhsValue in lhs { guard let rhsIndex = rhs.firstIndex(where: { areEqual(lhsValue, $0) }) else { return false } rhs.remove(at: rhsIndex) } return true default: return type(of: lhs) == type(of: rhs) && String(describing: lhs) == String(describing: rhs) } } }
5aa570520a4178b580f7ace327c91ceb
33.66855
149
0.589005
false
false
false
false
t4thswm/Course
refs/heads/master
Course/TimeSettingsViewController.swift
gpl-3.0
1
// // TimeSettingsViewController.swift // Course // // Created by Archie Yu on 2017/1/14. // Copyright © 2017年 Archie Yu. All rights reserved. // import UIKit class TimeSettingsViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() (self.view as! UITableView).separatorColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.3) } override func viewDidAppear(_ animated: Bool) { tableView.cellForRow(at: IndexPath(row: 0, section: 0))?.isUserInteractionEnabled = (sunday != 1) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func numberOfSections(in tableView: UITableView) -> Int { return 2 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch(section) { case 0: return 2 case 1: return 1 default: return 0 } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "TimeSettingsCell", for: indexPath) cell.backgroundColor = UIColor(white: 1, alpha: 0.1) cell.textLabel?.textColor = .white let selectedColor = UIColor(white: 1, alpha: 0.3) let selectedBackground = UIView() selectedBackground.backgroundColor = selectedColor cell.selectedBackgroundView = selectedBackground switch indexPath.section { case 0: switch indexPath.row { case 0: if saturday == 0 { cell.accessoryType = .none } else { cell.accessoryType = .checkmark } cell.textLabel?.text = "周六" case 1: if sunday == 0 { cell.accessoryType = .none } else { cell.accessoryType = .checkmark } cell.textLabel?.text = "周日" default: break } case 1: cell.accessoryType = .none cell.textLabel?.text = "总周数" default: break } return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // 取消选中 tableView.deselectRow(at: indexPath, animated: true) let userDefault = UserDefaults(suiteName: "group.studio.sloth.Course") // 跳转 switch indexPath.section { case 0: switch indexPath.row { case 0: if saturday == 1 { tableView.cellForRow(at: indexPath)?.accessoryType = .none saturday = 0 userDefault?.set(0, forKey: "Saturday") } else { tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark saturday = 1 userDefault?.set(1, forKey: "Saturday") } case 1: let saturdayCell = tableView.cellForRow(at: IndexPath(row: 0, section: 0)) if sunday == 1 { saturdayCell?.isUserInteractionEnabled = true tableView.cellForRow(at: indexPath)?.accessoryType = .none sunday = 0 userDefault?.set(0, forKey: "Sunday") } else { saturdayCell?.accessoryType = .checkmark saturdayCell?.isUserInteractionEnabled = false saturday = 1 userDefault?.set(1, forKey: "Saturday") tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark sunday = 1 userDefault?.set(1, forKey: "Sunday") } default: break } weekdayNum = 5 + saturday + sunday needReload = true case 2: break default: break } userDefault?.synchronize() } }
557935773928f7849c6683ef86539bf0
31.944882
109
0.52892
false
false
false
false
jasnig/ScrollPageView
refs/heads/master
ScrollPageView/SegmentStyle.swift
mit
1
// // SegmentStyle.swift // ScrollViewController // // Created by jasnig on 16/4/13. // Copyright © 2016年 ZeroJ. All rights reserved. // github: https://github.com/jasnig // 简书: http://www.jianshu.com/users/fb31a3d1ec30/latest_articles // // 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 struct SegmentStyle { /// 是否显示遮盖 public var showCover = false /// 是否显示下划线 public var showLine = false /// 是否缩放文字 public var scaleTitle = false /// 是否可以滚动标题 public var scrollTitle = true /// 是否颜色渐变 public var gradualChangeTitleColor = false /// 是否显示附加的按钮 public var showExtraButton = false public var extraBtnBackgroundImageName: String? /// 下面的滚动条的高度 默认2 public var scrollLineHeight: CGFloat = 2 /// 下面的滚动条的颜色 public var scrollLineColor = UIColor.brownColor() /// 遮盖的背景颜色 public var coverBackgroundColor = UIColor.lightGrayColor() /// 遮盖圆角 public var coverCornerRadius = 14.0 /// cover的高度 默认28 public var coverHeight: CGFloat = 28.0 /// 文字间的间隔 默认15 public var titleMargin: CGFloat = 15 /// 文字 字体 默认14.0 public var titleFont = UIFont.systemFontOfSize(14.0) /// 放大倍数 默认1.3 public var titleBigScale: CGFloat = 1.3 /// 默认倍数 不可修改 let titleOriginalScale: CGFloat = 1.0 /// 文字正常状态颜色 请使用RGB空间的颜色值!! 如果提供的不是RGB空间的颜色值就可能crash public var normalTitleColor = UIColor(red: 51.0/255.0, green: 53.0/255.0, blue: 75/255.0, alpha: 1.0) /// 文字选中状态颜色 请使用RGB空间的颜色值!! 如果提供的不是RGB空间的颜色值就可能crash public var selectedTitleColor = UIColor(red: 255.0/255.0, green: 0.0/255.0, blue: 121/255.0, alpha: 1.0) public init() { } }
f841b988823906f3637ef4e2779ac872
33.1375
108
0.700733
false
false
false
false
wangchong321/tucao
refs/heads/master
WCWeiBo/WCWeiBo/Classes/Model/Home/HomeRefresh.swift
mit
1
// // HomeRefresh.swift // WCWeiBo // // Created by 王充 on 15/5/21. // Copyright (c) 2015年 wangchong. All rights reserved. // import UIKit class HomeRefresh: UIRefreshControl { override init() { super.init() prepareView() } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } // 准备子视图 var refreshView : RefreshView? // 准备 UIRefreshControl private func prepareView(){ let rView = NSBundle.mainBundle().loadNibNamed("HomeRefresh", owner: nil, options: nil).last as! RefreshView addSubview(rView) rView.setTranslatesAutoresizingMaskIntoConstraints(false) /// 添加约束数组 var cons = [AnyObject]() cons += NSLayoutConstraint.constraintsWithVisualFormat("H:[rView(136)]", options: NSLayoutFormatOptions(0), metrics: nil, views: ["rView":rView]) cons += NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[rView(60)]", options: NSLayoutFormatOptions(0), metrics: nil, views: ["rView":rView]) cons.append( NSLayoutConstraint(item: rView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1.0, constant: 0)) self.addConstraints(cons) self.addObserver(self, forKeyPath: "frame", options: NSKeyValueObservingOptions.New, context: nil) self.refreshView = rView } deinit{ self.removeObserver(self, forKeyPath: "frame") } override func endRefreshing() { super.endRefreshing() // 停止动画 refreshView?.stopLoading() // isLoadingFlag = false } // 显示箭头标记 var shouTipFlag = false // 显示正在加载标记 var isLoadingFlag = false override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) { if self.frame.origin.y >= 0 { return } // 如果正在刷新 并且还没有转圈显示 if refreshing && !isLoadingFlag{ // 根据给的动画时长来结束动画 println("正在加载") self.refreshView?.startLoding() isLoadingFlag = true return } if self.frame.origin.y > -50 && shouTipFlag{ shouTipFlag = false refreshView?.rotateTipIcon(shouTipFlag) }else if self.frame.origin.y <= -50 && !shouTipFlag{ shouTipFlag = true refreshView?.rotateTipIcon(shouTipFlag) // 箭头转向上边 } } } class RefreshView: UIView { /// load视图(转圈图标) @IBOutlet weak var loadImgView: UIImageView! /// 箭头图标 @IBOutlet weak var tipIcon: UIImageView! /// 提示视图 @IBOutlet weak var tipView: UIView! /// 旋转箭头 private func rotateTipIcon(whatDirection : Bool){ var angel = CGFloat(M_PI) as CGFloat angel += whatDirection ? -0.01 : 0.01 UIView.animateWithDuration(0.5) { self.tipIcon.transform = CGAffineTransformRotate(self.tipIcon.transform, CGFloat(M_PI)) } } /// 开始加载 func startLoding(){ tipView.hidden = true let anim = CABasicAnimation(keyPath: "transform.rotation") anim.duration = 0.5 anim.repeatCount = MAXFLOAT anim.toValue = M_PI * 2 loadImgView.layer.addAnimation(anim, forKey: nil) } /// 结束加载 func stopLoading(){ loadImgView.layer.removeAllAnimations() tipView.hidden = false } }
c9ac48df77a49d235841e04a850d043a
28.991597
208
0.607343
false
false
false
false
richard92m/three.bar
refs/heads/master
ThreeBar/ThreeBar/GameScene.swift
gpl-3.0
1
// // GameScene.swift // ThreeBar // // Created by Marquez, Richard A on 12/13/14. // Copyright (c) 2014 Richard Marquez. All rights reserved. // import SpriteKit class GameScene: SKScene, SKPhysicsContactDelegate { var lives: Int = 0 let hero = Hero() let hive = Hive() var mobs = [Mob]() let door = Door() var locks = [Lock]() var score: Int = 0 let scoreLabel = SKLabelNode() let livesLabel = SKLabelNode() var startTime = NSDate() override func didMoveToView(view: SKView) { NSNotificationCenter.defaultCenter().addObserver(self, selector: "onMotionShake:", name:"MotionShake", object: nil) physicsWorld.contactDelegate = self physicsWorld.gravity = CGVectorMake(0, 0) addLivesLabel() addScoreLabel() addHero() addMoveControl() addHive() populateWithMobs() addDoor() populateWithLocks() } func addLivesLabel() { livesLabel.fontName = _magic.get("livesFont") as String livesLabel.name = "livesLabel" livesLabel.text = "" for var i = 0; i < lives; ++i { livesLabel.text = "\(livesLabel.text)_" } livesLabel.fontSize = _magic.get("livesSize") as CGFloat livesLabel.position = CGPoint(x: size.width - 100, y: 15) livesLabel.zPosition = CGFloat(ZIndex.HUD.rawValue) self.addChild(livesLabel) } func addScoreLabel() { var bgSize = CGSize() bgSize.width = _magic.get("scoreBgWidth") as CGFloat bgSize.height = _magic.get("scoreBgHeight") as CGFloat let bgColor = UIColor(hex: _magic.get("scoreBgColor") as String) let scoreBg = SKSpriteNode(color: bgColor, size: bgSize) scoreBg.position = CGPoint(x: CGRectGetMidX(self.frame), y: size.height - 10) scoreBg.zRotation = DEGREES_TO_RADIANS(_magic.get("scoreBgRotation") as CGFloat) scoreBg.zPosition = CGFloat(ZIndex.HUD.rawValue - 1) self.addChild(scoreBg) scoreLabel.fontName = _magic.get("scoreFont") as String scoreLabel.name = "scoreLabel" scoreLabel.text = String(score) scoreLabel.fontSize = _magic.get("scoreSize") as CGFloat scoreLabel.fontColor = UIColor(hex: _magic.get("scoreColor") as String) scoreLabel.position = CGPoint(x: CGRectGetMidX(self.frame), y: size.height - 50) scoreLabel.zPosition = CGFloat(ZIndex.HUD.rawValue) self.addChild(scoreLabel) } func changeScore(changeBy: Int) { score += changeBy scoreLabel.text = String(score) } func addHero() { hero.position = getRandomPosition() addChild(hero) } func killHero() { hero.killLaser() hero.removeFromParent() } func addHive() { hive.position = CGPoint(x: size.width / 2, y: size.height / 2) addChild(hive) } func populateWithMobs() { for i in 1...3 { spawnMob() } } func spawnMob(spawnPosition: CGPoint) { let mob = Mob(position: spawnPosition) mobs.append(mob) addChild(mob) } func spawnMob() { spawnMob(getValidMobPosition()) } func getValidMobPosition() -> CGPoint { var possiblePosition: CGPoint var valid = true var distance:CGFloat = 0 do { possiblePosition = getRandomPosition(fromPoint: hero.position, minDistance: _magic.get("mobMinDistance") as CGFloat) valid = true for mob in mobs { distance = (mob.position - possiblePosition).length() if (distance <= (_magic.get("mobMinDistance") as CGFloat)) { valid = false } } } while !valid return possiblePosition } func respawnMob(spawnPosition: CGPoint) { let beforeSpawnAction = SKAction.runBlock({ self.hive.color = UIColor.whiteColor() }) let spawnAction = SKAction.runBlock({ self.spawnMob(spawnPosition) }) let afterSpawnAction = SKAction.runBlock({ self.hive.color = UIColor.blackColor() }) let waitAction = SKAction.waitForDuration(NSTimeInterval(_magic.get("mobRespawnTime") as Float)) runAction(SKAction.sequence([ beforeSpawnAction, waitAction, spawnAction, afterSpawnAction ])) } func killMob(mob: Mob) { mob.removeFromParent() var i = 0 for inArray in mobs { if inArray == mob { mobs.removeAtIndex(i) changeScore(100) } ++i } } func addDoor() { door.position = CGPoint(x: size.width / 2, y: size.height) addChild(door) } func populateWithLocks() { for i in 1...2 { addLock() } } func addLock() { let lock = Lock(position: getValidLockPosition()) locks.append(lock) addChild(lock) } func getValidLockPosition() -> CGPoint { var possiblePosition: CGPoint var valid = true var distance:CGFloat = 0 do { possiblePosition = getPossibleLockPosition() valid = true for lock in locks { distance = (lock.position - possiblePosition).length() if (distance <= (_magic.get("lockMinDistance") as CGFloat)) { valid = false } } } while !valid return possiblePosition } func getPossibleLockPosition() -> CGPoint { let randomPosition = getRandomPosition() var possiblePosition = CGPoint() let random = arc4random_uniform(4) + 1 if random == 1 { // Place on top possiblePosition = CGPoint(x: randomPosition.x, y: size.height) } else if random == 2 { // Place on right possiblePosition = CGPoint(x: size.width, y: randomPosition.y) } else if random == 3 { // Place on bottom possiblePosition = CGPoint(x: randomPosition.x, y: 0) } else { // Place on left possiblePosition = CGPoint(x: 0, y: randomPosition.y) } if checkIfInCorner(possiblePosition) || checkIfNearDoor(possiblePosition) { possiblePosition = getPossibleLockPosition() } return possiblePosition } func checkIfInCorner(possiblePosition: CGPoint) -> Bool { var inCorner = false let lockSize = _magic.get("lockWidth") as CGFloat let leftSide = (possiblePosition.x < lockSize) && ((possiblePosition.y > (size.height - lockSize)) || (possiblePosition.y < lockSize)) let rightSide = (possiblePosition.x > size.width - lockSize) && ((possiblePosition.y > (size.height - lockSize)) || (possiblePosition.y < lockSize)) if leftSide || rightSide { inCorner = true } return inCorner } func checkIfNearDoor(possiblePosition: CGPoint) -> Bool { var nearDoor = false let distance = (door.position - possiblePosition).length() if (distance <= (_magic.get("doorMinDistance") as CGFloat)) { nearDoor = true } return nearDoor } func checkLocksAreOpen() -> Bool { for lock in locks { if !lock.open { return false } } return true } func addMoveControl() { let moveControl = SKSpriteNode(texture: SKTexture(imageNamed: _magic.get("controlImage") as String), color: UIColor.yellowColor(), size: CGSize(width: _magic.get("controlSize") as CGFloat, height: _magic.get("controlSize") as CGFloat)) moveControl.position = CGPoint(x: _magic.get("controlCenter") as CGFloat, y: _magic.get("controlCenter") as CGFloat) moveControl.zPosition = CGFloat(ZIndex.MoveControl.rawValue) addChild(moveControl) } func getControlRelativeDirection(touchLocation: CGPoint) -> CGPoint { let controlCenter = CGPoint(x: _magic.get("controlCenter") as CGFloat, y: _magic.get("controlCenter") as CGFloat) return getRelativeDirection(controlCenter, destination: touchLocation) } override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { for touch in touches { let location = touch.locationInNode(self) // Move if left side touched if location.x < size.width / 2 { hero.facing = getControlRelativeDirection(location) hero.startMoving() } else { // Shoot if right side touched hero.shoot(self) } } } override func touchesEnded(touches: NSSet, withEvent event: UIEvent) { for touch in touches { let location = touch.locationInNode(self) // Stop moving hero when control no longer held if location.x < size.width / 2 { hero.stopMoving() } } } override func touchesMoved(touches: NSSet, withEvent event: UIEvent) { for touch in touches { let location = touch.locationInNode(self) // Continuously move hero if touch is held on left side if location.x < size.width / 2 { hero.facing = getControlRelativeDirection(location) } } } // Teleport hero on shake func onMotionShake(notification: NSNotification) { hero.teleport(self) } func heroDidCollideWithMob(mob: Mob) { let explosion = Explosion(node: hero) killHero() addChild(explosion) let endAction = SKAction.runBlock({ explosion.removeFromParent() --self.lives self.endgame() }) explosion.runAction(SKAction.sequence([ explosion.getAnimation(), endAction ])) } func heroDidCollideWithDoor() { if door.open { endgame() } } func laserDidCollideWithHero() { hero.killLaser() } func laserDidCollideWithMob(laser: Laser, mob: Mob) { laser.comeBack(hero) let explosion = Explosion(node: mob) killMob(mob) addChild(explosion) let endExplosionAction = SKAction.runBlock({ explosion.removeFromParent() }) explosion.runAction(SKAction.sequence([ explosion.getAnimation(), endExplosionAction ])) respawnMob(hive.position) } func laserDidCollideWithWall(laser: Laser) { laser.comeBack(hero) } func laserDidCollideWithLock(laser: Laser, lock: Lock) { laser.comeBack(hero) lock.unlock() if checkLocksAreOpen() { door.unlock() } } func laserDidCollideWithDoor(laser: Laser, door: Door) { if !checkLocksAreOpen() { door.blink() } } func didBeginContact(contact: SKPhysicsContact) { // Put bodies in ascending PhysicsCategory order var firstBody: SKPhysicsBody var secondBody: SKPhysicsBody if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask { firstBody = contact.bodyA secondBody = contact.bodyB } else { firstBody = contact.bodyB secondBody = contact.bodyA } // First, ensure both nodes are valid switch (firstBody.node?, secondBody.node?) { case let (.Some(firstNode), .Some(secondNode)): switch firstBody.categoryBitMask { case PhysicsCategory.Hero: switch secondBody.categoryBitMask { case PhysicsCategory.Mob: heroDidCollideWithMob(secondNode as Mob) case PhysicsCategory.ReturnLaser: laserDidCollideWithHero() case PhysicsCategory.Door: heroDidCollideWithDoor() default: break } case PhysicsCategory.Mob: switch secondBody.categoryBitMask { case PhysicsCategory.Laser: laserDidCollideWithMob(secondNode as Laser, mob: firstNode as Mob) default: break } case PhysicsCategory.Wall: switch secondBody.categoryBitMask { case PhysicsCategory.Laser: laserDidCollideWithWall(secondNode as Laser) default: break } case PhysicsCategory.Laser: switch secondBody.categoryBitMask { case PhysicsCategory.Lock: laserDidCollideWithLock(firstNode as Laser, lock: secondNode as Lock) case PhysicsCategory.Door: laserDidCollideWithDoor(firstNode as Laser, door: secondNode as Door) default: break } default: break } default: break } } override func update(currentTime: CFTimeInterval) { for mob in mobs { mob.nextAction(self) } if hero.moving { hero.move() } if let heroLaser = hero.laser { switch heroLaser.physicsBody!.categoryBitMask { case PhysicsCategory.Laser: heroLaser.move() case PhysicsCategory.ReturnLaser: heroLaser.moveBack(hero) default: break } } } func endgame() { hero.kill() if lives >= 0 { if let scene = GameScene.unarchiveFromFile("GameScene") as? GameScene { if let skView = self.view { scene.score = score scene.lives = lives scene.startTime = startTime skView.ignoresSiblingOrder = true scene.scaleMode = .AspectFill skView.presentScene(scene) } } } else { if let scene = EndgameScene.unarchiveFromFile("EndgameScene") as? EndgameScene { if let skView = self.view { scene.score = score scene.startTime = startTime skView.ignoresSiblingOrder = true scene.scaleMode = .AspectFill skView.presentScene(scene) } } } } }
3b5d42ee83feac3c9e72243de1b313e5
28.977186
156
0.525051
false
false
false
false
proxpero/Endgame
refs/heads/master
Sources/Bitboard+Attacks.swift
mit
1
// // Bitboard+Attacks.swift // Endgame // // Created by Todd Olsen on 3/15/17. // // extension Bitboard { /// Returns the pawn pushes available for `color` in `self`. public func pawnPushes(for color: Color, empty: Bitboard) -> Bitboard { return (color.isWhite ? shifted(toward: .north) : shifted(toward: .south)) & empty } /// Returns moves available to `piece` in `self`. public func moves(for piece: Piece, obstacles: Bitboard = 0) -> Bitboard { var pawns: Bitboard = 0 if piece.kind.isPawn { pawns |= pawnPushes(for: piece.color, empty: ~obstacles) if Rank.pawnRank(for: piece.color).contains(bitboard: self) { pawns |= pawns.pawnPushes(for: piece.color, empty: ~obstacles) } } return pawns | attacks(for: piece, obstacles: obstacles) } /// Returns the attacks available to `piece` in `self`. public func attacks(for piece: Piece, obstacles: Bitboard = 0) -> Bitboard { let diagonalSquares: Bitboard = { let ne = self .filled(toward: .northeast, until: obstacles) .shifted(toward: .northeast) let nw = self .filled(toward: .northwest, until: obstacles) .shifted(toward: .northwest) let se = self .filled(toward: .southeast, until: obstacles) .shifted(toward: .southeast) let sw = self .filled(toward: .southwest, until: obstacles) .shifted(toward: .southwest) return ne | nw | se | sw }() let orthogonalSquares: Bitboard = { let n = self .filled(toward: .north, until: obstacles) .shifted(toward: .north) let s = self .filled(toward: .south, until: obstacles) .shifted(toward: .south) let e = self .filled(toward: .east, until: obstacles) .shifted(toward: .east) let w = self .filled(toward: .west, until: obstacles) .shifted(toward: .west) return n | s | e | w }() switch piece.kind { case .pawn: switch piece.color { case .white: return shifted(toward: .northeast) | shifted(toward: .northwest) case .black: return shifted(toward: .southeast) | shifted(toward: .southwest) } case .knight: return (((self << 17) | (self >> 15)) & ~File.a) | (((self << 10) | (self >> 06)) & ~(File.a | File.b)) | (((self << 15) | (self >> 17)) & ~File.h) | (((self << 06) | (self >> 10)) & ~(File.g | File.h)) case .bishop: return diagonalSquares case .rook: return orthogonalSquares case .queen: return diagonalSquares | orthogonalSquares case .king: let row = shifted(toward: .east) | shifted(toward: .west) let bitboard = self | row return row | bitboard.shifted(toward: .north) | bitboard.shifted(toward: .south) } } }
a5ff67b8c1adfb64c04cde68e0f0403b
32.252525
90
0.508809
false
false
false
false
cnbin/LayerPlayer
refs/heads/master
LayerPlayer/CAEmitterLayerViewController.swift
mit
3
// // CAEmitterLayerViewController.swift // LayerPlayer // // Created by Scott Gardner on 11/22/14. // Copyright (c) 2014 Scott Gardner. All rights reserved. // import UIKit class CAEmitterLayerViewController: UIViewController { @IBOutlet weak var viewForEmitterLayer: UIView! var emitterLayer = CAEmitterLayer() var emitterCell = CAEmitterCell() // MARK: - Quick reference func setUpEmitterLayer() { emitterLayer.frame = viewForEmitterLayer.bounds emitterLayer.seed = UInt32(NSDate().timeIntervalSince1970) emitterLayer.emitterPosition = CGPoint(x: CGRectGetMidX(viewForEmitterLayer.bounds) * 1.5, y: CGRectGetMidY(viewForEmitterLayer.bounds)) } func setUpEmitterCell() { emitterCell.enabled = true emitterCell.contents = UIImage(named: "smallStar")?.CGImage emitterCell.contentsRect = CGRect(origin: CGPointZero, size: CGSize(width: 1, height: 1)) emitterCell.color = UIColor(hue: 0.0, saturation: 0.0, brightness: 0.0, alpha: 1.0).CGColor emitterCell.redRange = 1.0 emitterCell.greenRange = 1.0 emitterCell.blueRange = 1.0 emitterCell.alphaRange = 0.0 emitterCell.redSpeed = 0.0 emitterCell.greenSpeed = 0.0 emitterCell.blueSpeed = 0.0 emitterCell.alphaSpeed = -0.5 emitterCell.scale = 1.0 emitterCell.scaleRange = 0.0 emitterCell.scaleSpeed = 0.1 let zeroDegreesInRadians = degreesToRadians(0.0) emitterCell.spin = degreesToRadians(130.0) emitterCell.spinRange = zeroDegreesInRadians emitterCell.emissionLatitude = zeroDegreesInRadians emitterCell.emissionLongitude = zeroDegreesInRadians emitterCell.emissionRange = degreesToRadians(360.0) emitterCell.lifetime = 1.0 emitterCell.lifetimeRange = 0.0 emitterCell.birthRate = 250.0 emitterCell.velocity = 50.0 emitterCell.velocityRange = 500.0 emitterCell.xAcceleration = -750.0 emitterCell.yAcceleration = 0.0 } // MARK: - View life cycle override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) setUpEmitterCell() resetEmitterCells() setUpEmitterLayer() viewForEmitterLayer.layer.addSublayer(emitterLayer) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let identifier = segue.identifier { switch identifier { case "DisplayEmitterControls": emitterLayer.renderMode = kCAEmitterLayerAdditive let controller = segue.destinationViewController as CAEmitterLayerControlsViewController controller.emitterLayerViewController = self default: break } } } // MARK: - Triggered actions override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { if let location = touches.anyObject()?.locationInView(viewForEmitterLayer) { emitterLayer.emitterPosition = location } } override func touchesMoved(touches: NSSet, withEvent event: UIEvent) { if let location = touches.anyObject()?.locationInView(viewForEmitterLayer) { emitterLayer.emitterPosition = location } } // MARK: - Helpers func resetEmitterCells() { emitterLayer.emitterCells = nil emitterLayer.emitterCells = [emitterCell] } }
fb60154eeb4f251746bb25d3017662eb
30.407767
140
0.718702
false
false
false
false
mukeshthawani/UXMPDFKit
refs/heads/master
Pod/Classes/Form/PDFFormPageView.swift
mit
1
// // PDFFormView.swift // Pods // // Created by Chris Anderson on 5/26/16. // // import UIKit struct PDFFormViewOptions { var type: String var rect: CGRect var flags: [PDFFormFlag]? var name: String = "" var exportValue: String = "" var options: [String]? } struct PDFFormFlag: Equatable { let rawValue: UInt static let ReadOnly = PDFFormFlag(rawValue:1 << 0) static let Required = PDFFormFlag(rawValue:1 << 1) static let NoExport = PDFFormFlag(rawValue:1 << 2) static let TextFieldMultiline = PDFFormFlag(rawValue:1 << 12) static let TextFieldPassword = PDFFormFlag(rawValue:1 << 13) static let ButtonNoToggleToOff = PDFFormFlag(rawValue:1 << 14) static let ButtonRadio = PDFFormFlag(rawValue:1 << 15) static let ButtonPushButton = PDFFormFlag(rawValue:1 << 16) static let ChoiceFieldIsCombo = PDFFormFlag(rawValue:1 << 17) static let ChoiceFieldEditable = PDFFormFlag(rawValue:1 << 18) static let ChoiceFieldSorted = PDFFormFlag(rawValue:1 << 19) } func ==(lhs: PDFFormFlag, rhs: PDFFormFlag) -> Bool { return lhs.rawValue == rhs.rawValue } open class PDFFormPage: NSObject { let page: Int var fields: [PDFFormFieldObject] = [] let zoomScale: CGFloat = 1.0 init(page: Int) { self.page = page } func showForm(_ contentView: PDFPageContentView) { let formView = PDFFormPageView( frame: contentView.contentView.cropBoxRect, boundingBox: contentView.containerView.frame, cropBox: contentView.contentView.cropBoxRect, fields: self.fields) formView.zoomScale = contentView.zoomScale if contentView.contentView.subviews.filter({ $0 is PDFFormPageView }).count <= 0 { contentView.contentView.addSubview(formView) } contentView.viewDidZoom = { scale in formView.updateWithZoom(scale) } } func createFormField(_ dict: PDFDictionary) { fields.append(PDFFormFieldObject(dict: dict)) } func renderInContext(_ context: CGContext, size: CGRect) { let formView = PDFFormPageView( frame: size, boundingBox: size, cropBox: size, fields: self.fields) formView.renderInContext(context) } } open class PDFFormPageView: UIView { var fields: [PDFFormFieldObject] var fieldViews: [PDFFormField] = [] var zoomScale: CGFloat = 1.0 let cropBox: CGRect let boundingBox: CGRect let baseFrame: CGRect init(frame: CGRect, boundingBox: CGRect, cropBox: CGRect, fields: [PDFFormFieldObject]) { self.baseFrame = frame self.cropBox = cropBox self.boundingBox = boundingBox self.fields = fields super.init(frame: frame) for field in fields { guard let fieldView = field.createFormField() else { continue } addSubview(fieldView) adjustFrame(fieldView) fieldViews.append(fieldView) } } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func updateWithZoom(_ zoomScale: CGFloat) { for field in fieldViews { field.updateForZoomScale(zoomScale) field.refresh() } } func adjustFrame(_ field: PDFFormField) { let factor: CGFloat = 1.0 let correctedFrame = CGRect( x: (field.baseFrame.origin.x - cropBox.origin.x) * factor, y: (cropBox.height - field.baseFrame.origin.y - field.baseFrame.height - cropBox.origin.y) * factor, width: field.baseFrame.width * factor, height: field.baseFrame.height * factor) field.frame = correctedFrame } func renderInContext(_ context: CGContext) { for field in fieldViews { field.renderInContext(context) } } }
9064e12e01625e851b5da88bac0d450a
30.107692
112
0.617458
false
false
false
false
enbaya/WebyclipSDK
refs/heads/master
WebyclipSDK/Classes/WebyclipPlayerCell.swift
mit
1
import youtube_ios_player_helper class WebyclipPlayerCell: UICollectionViewCell { // MARK: - IBOtlets @IBOutlet var mediaPlayer: YTPlayerView! @IBOutlet var mediaTitle: UILabel! @IBOutlet var mediaAuthor: UILabel! @IBOutlet var mediaProvider: UILabel! // MARK: - Private fileprivate var playerVars = [ "playsinline": 1, "showinfo": 0, "modestbranding": 1, "rel": 0, "fs": 0, "theme": "light", "color": "white" ] as [String : Any] fileprivate func updateUI() { self.mediaPlayer.isUserInteractionEnabled = false self.mediaPlayer.load(withVideoId: self.media.mediaId, playerVars: self.playerVars) self.mediaTitle.text = self.media.title self.mediaAuthor.text = self.media.author self.mediaProvider.text = formatProvider(self.media.provider) } fileprivate func formatProvider(_ provider: String) -> String { let prv: String switch(provider) { case "youtube": prv = "YouTube" break; default: prv = "Unknown provider" } return prv; } fileprivate func getMediaThumbnail(_ mediaId: String) -> UIImage { let url = URL(string: "https://img.youtube.com/vi/" + mediaId + "/mqdefault.jpg")! let data = try! Data(contentsOf: url) return UIImage(data: data)! } // MARK: - Public var media: WebyclipPlayerItem! { didSet { updateUI(); } } }
8b950ec857397d4e23cc3e4be622667c
27.375
91
0.571429
false
false
false
false
dnevera/IMProcessing
refs/heads/master
IMProcessing/Classes/Adjustments/IMPHSVFilter.swift
mit
1
// // IMPHSVFilter.swift // IMProcessing // // Created by denis svinarchuk on 22.12.15. // Copyright © 2015 Dehancer.photo. All rights reserved. // import Foundation import Metal import simd public extension IMProcessing{ public struct hsv { /// Ramps of HSV hextants in the HSV color wheel with overlaping levels public static let hueRamps:[float4] = [kIMP_Reds, kIMP_Yellows, kIMP_Greens, kIMP_Cyans, kIMP_Blues, kIMP_Magentas] /// Hextants aliases public static let reds = hueRamps[0] public static let yellows = hueRamps[1] public static let greens = hueRamps[2] public static let cyans = hueRamps[3] public static let blues = hueRamps[4] public static let magentas = hueRamps[5] /// Overlap factor public static var hueOverlapFactor:Float = 1.4 /// Hue range of the HSV color wheel private static let hueRange = Range<Int>(0..<360) } } public extension Float32{ // // Get HSV weight which uses to define how two close colors interfer between ech others // func overlapWeight(ramp ramp:float4, overlap:Float = IMProcessing.hsv.hueOverlapFactor) -> Float32 { var sigma = (ramp.z-ramp.y) var mu = (ramp.w+ramp.x)/2.0 if ramp.y>ramp.z { sigma = (IMProcessing.hsv.hueRange.endIndex.float-ramp.y+ramp.z) if (self >= 0.float) && (self <= IMProcessing.hsv.hueRange.endIndex.float/2.0) { mu = (IMProcessing.hsv.hueRange.endIndex.float-ramp.y-ramp.z) / 2.0 }else{ mu = (ramp.y+ramp.z) } } return self.gaussianPoint(fi: 1, mu: mu, sigma: sigma * overlap) } } public extension SequenceType where Generator.Element == Float32 { public func overlapWeightsDistribution(ramp ramp:float4, overlap:Float = IMProcessing.hsv.hueOverlapFactor) -> [Float32]{ var a = [Float32]() for i in self{ a.append(i.overlapWeight(ramp: ramp, overlap: overlap)) } return a } public func overlapWeightsDistribution(ramp ramp:float4, overlap:Float = IMProcessing.hsv.hueOverlapFactor) -> NSData { let f:[Float32] = overlapWeightsDistribution(ramp: ramp, overlap: overlap) as [Float32] return NSData(bytes: f, length: f.count) } } public func * (left:IMPHSVLevel,right:Float) -> IMPHSVLevel { return IMPHSVLevel(hue: left.hue * right, saturation: left.saturation * right, value: left.value * right) } public extension IMPHSVAdjustment{ public var reds: IMPHSVLevel{ get { return levels.0 } set{ levels.0 = newValue }} public var yellows: IMPHSVLevel{ get { return levels.1 } set{ levels.1 = newValue }} public var greens: IMPHSVLevel{ get { return levels.2 } set{ levels.2 = newValue }} public var cyans: IMPHSVLevel{ get { return levels.3 } set{ levels.3 = newValue }} public var blues: IMPHSVLevel{ get { return levels.4 } set{ levels.4 = newValue }} public var magentas:IMPHSVLevel{ get { return levels.5 } set{ levels.5 = newValue }} public subscript(index:Int) -> IMPHSVLevel { switch(index){ case 0: return levels.0 case 1: return levels.1 case 2: return levels.2 case 3: return levels.3 case 4: return levels.4 case 5: return levels.5 default: return master } } public mutating func hue(index index:Int, value newValue:Float){ switch(index){ case 0: levels.0.hue = newValue case 1: levels.1.hue = newValue case 2: levels.2.hue = newValue case 3: levels.3.hue = newValue case 4: levels.4.hue = newValue case 5: levels.5.hue = newValue default: master.hue = newValue } } public mutating func saturation(index index:Int, value newValue:Float){ switch(index){ case 0: levels.0.saturation = newValue case 1: levels.1.saturation = newValue case 2: levels.2.saturation = newValue case 3: levels.3.saturation = newValue case 4: levels.4.saturation = newValue case 5: levels.5.saturation = newValue default: master.saturation = newValue } } public mutating func value(index index:Int, value newValue:Float){ switch(index){ case 0: levels.0.value = newValue case 1: levels.1.value = newValue case 2: levels.2.value = newValue case 3: levels.3.value = newValue case 4: levels.4.value = newValue case 5: levels.5.value = newValue default: master.value = newValue } } } /// /// HSV adjustment filter /// public class IMPHSVFilter:IMPFilter,IMPAdjustmentProtocol{ /// Optimization level description /// /// - HIGH: default optimization uses when you need to accelerate hsv adjustment /// - NORMAL: hsv adjustments application without interpolation public enum optimizationLevel{ case HIGH case NORMAL } /// /// Default HSV adjustment /// public static let defaultAdjustment = IMPHSVAdjustment( master: IMPHSVFilter.level, levels: (IMPHSVFilter.level,IMPHSVFilter.level,IMPHSVFilter.level,IMPHSVFilter.level,IMPHSVFilter.level,IMPHSVFilter.level), blending: IMPBlending(mode: IMPBlendingMode.NORMAL, opacity: 1) ) /// HSV adjustment levels public var adjustment:IMPHSVAdjustment!{ didSet{ if self.optimization == .HIGH { adjustmentLut.blending = adjustment.blending updateBuffer(&adjustmentLutBuffer, context:context, adjustment:&adjustmentLut, size:sizeof(IMPAdjustment)) updateBuffer(&adjustmentBuffer, context:context_hsv3DLut, adjustment:&adjustment, size:sizeof(IMPHSVAdjustment)) applyHsv3DLut() } else { updateBuffer(&adjustmentBuffer, context:context, adjustment:&adjustment, size:sizeof(IMPHSVAdjustment)) } dirty = true } } /// /// Overlap colors in the HSV color wheel. Define the width of color overlaping. /// public var overlap:Float = IMProcessing.hsv.hueOverlapFactor { didSet{ hueWeights = IMPHSVFilter.defaultHueWeights(self.context, overlap: overlap) if self.optimization == .HIGH { applyHsv3DLut() } dirty = true } } /// Create HSV adjustment filter. /// /// - .HIGH optimization level uses to reduce HSV adjustment computation per pixel. /// only defult 64x64x64 LUT creates and then applies to final image. With this /// option an image modification can lead to the appearance of artifacts in the image. /// .HIGH level can use for live-view mode of image processing /// /// - .Normal uses for more precise HSV adjustments /// /// - parameter context: execution context /// - parameter optimization: optimization level /// public required init(context: IMPContext, optimization:optimizationLevel) { super.init(context: context) self.optimization = optimization if self.optimization == .HIGH { hsv3DlutTexture = hsv3DLut(self.rgbCubeSize) kernel_hsv3DLut = IMPFunction(context: self.context_hsv3DLut, name: "kernel_adjustHSV3DLut") kernel = IMPFunction(context: self.context, name: "kernel_adjustLutD3D") } else{ kernel = IMPFunction(context: self.context, name: "kernel_adjustHSV") } addFunction(kernel) defer{ adjustment = IMPHSVFilter.defaultAdjustment } //NSLog("\(self): \(self.optimization )") } /// Create HSV adjustment filter with default optimization level .NORMAL /// /// - parameter context: device execution context /// public convenience required init(context: IMPContext) { self.init(context: context, optimization:context.isLazy ? .HIGH : .NORMAL) } public override func configure(function: IMPFunction, command: MTLComputeCommandEncoder) { if kernel == function { if self.optimization == .HIGH { command.setTexture(hsv3DlutTexture, atIndex: 2) command.setBuffer(adjustmentLutBuffer, offset: 0, atIndex: 0) } else{ command.setTexture(hueWeights, atIndex: 2) command.setBuffer(adjustmentBuffer, offset: 0, atIndex: 0) } } } /// Create new hue color overlaping weights for the HSV color wheel /// /// - parameter context: device execution context /// /// - returns: new overlaping weights public static func defaultHueWeights(context:IMPContext, overlap:Float) -> MTLTexture { let width = IMProcessing.hsv.hueRange.endIndex let textureDescriptor = MTLTextureDescriptor() textureDescriptor.textureType = .Type1DArray; textureDescriptor.width = width; textureDescriptor.height = 1; textureDescriptor.depth = 1; textureDescriptor.pixelFormat = .R32Float; textureDescriptor.arrayLength = IMProcessing.hsv.hueRamps.count; textureDescriptor.mipmapLevelCount = 1; let region = MTLRegionMake2D(0, 0, width, 1); let hueWeights = context.device.newTextureWithDescriptor(textureDescriptor) let hues = Float.range(0..<width) for i in 0..<IMProcessing.hsv.hueRamps.count{ let ramp = IMProcessing.hsv.hueRamps[i] var data = hues.overlapWeightsDistribution(ramp: ramp, overlap: overlap) as [Float32] hueWeights.replaceRegion(region, mipmapLevel:0, slice:i, withBytes:&data, bytesPerRow:sizeof(Float32) * width, bytesPerImage:0) } return hueWeights; } public var adjustmentBuffer:MTLBuffer? public var kernel:IMPFunction! public var rgbCube:MTLTexture? { return hsv3DlutTexture } public var rgbCubeSize = 64 { didSet{ if self.optimization == .HIGH { adjustmentLut.blending = adjustment.blending updateBuffer(&adjustmentLutBuffer, context:context, adjustment:&adjustmentLut, size:sizeof(IMPAdjustment)) updateBuffer(&adjustmentBuffer, context:context_hsv3DLut, adjustment:&adjustment, size:sizeof(IMPHSVAdjustment)) applyHsv3DLut() dirty = true } } } internal static let level:IMPHSVLevel = IMPHSVLevel(hue: 0.0, saturation: 0, value: 0) internal lazy var hueWeights:MTLTexture = { return IMPHSVFilter.defaultHueWeights(self.context, overlap: IMProcessing.hsv.hueOverlapFactor) }() private var adjustmentLut = IMPAdjustment(blending: IMPBlending(mode: IMPBlendingMode.NORMAL, opacity: 1)) internal var adjustmentLutBuffer:MTLBuffer? private var optimization:optimizationLevel! // // Convert HSV transformation to 3D-rgb lut-cube // // private var kernel_hsv3DLut:IMPFunction! private lazy var context_hsv3DLut:IMPContext = {return self.context }() private func applyHsv3DLut(){ context_hsv3DLut.execute{ (commandBuffer) -> Void in let width = self.hsv3DlutTexture!.width let height = self.hsv3DlutTexture!.height let depth = self.hsv3DlutTexture!.depth let threadgroupCounts = MTLSizeMake(4, 4, 4) let threadgroups = MTLSizeMake(width/4, height/4, depth/4) let commandEncoder = commandBuffer.computeCommandEncoder() commandEncoder.setComputePipelineState(self.kernel_hsv3DLut.pipeline!) commandEncoder.setTexture(self.hsv3DlutTexture, atIndex:0) commandEncoder.setTexture(self.hueWeights, atIndex:1) commandEncoder.setBuffer(self.adjustmentBuffer, offset: 0, atIndex: 0) commandEncoder.dispatchThreadgroups(threadgroups, threadsPerThreadgroup:threadgroupCounts) commandEncoder.endEncoding() #if os(OSX) let blitEncoder = commandBuffer.blitCommandEncoder() blitEncoder.synchronizeResource(self.hsv3DlutTexture!) blitEncoder.endEncoding() #endif } } private var hsv3DlutTexture:MTLTexture? private func hsv3DLut(dimention:Int) -> MTLTexture { let textureDescriptor = MTLTextureDescriptor() textureDescriptor.textureType = .Type3D textureDescriptor.width = dimention textureDescriptor.height = dimention textureDescriptor.depth = dimention textureDescriptor.pixelFormat = .RGBA8Unorm textureDescriptor.arrayLength = 1; textureDescriptor.mipmapLevelCount = 1; let texture = context_hsv3DLut.device.newTextureWithDescriptor(textureDescriptor) return texture } }
08aece461483dffa233eb2a06c5a6283
33.855696
139
0.606741
false
false
false
false
jindulys/Leetcode_Solutions_Swift
refs/heads/master
Sources/LinkedList/86_PartitionList.swift
mit
1
// // 83_PartitionList.swift // LeetcodeSwift // // Created by yansong li on 2016-11-07. // Copyright © 2016 YANSONG LI. All rights reserved. // import Foundation /** Title:86 Partition List URL: https://leetcode.com/problems/partition-list/ Space: O(1) Time: O(N) */ class PartitionList_Solution { func partition(_ head: ListNode?, _ x: Int) -> ListNode? { let prevDummy = ListNode(0) var prev: ListNode? = prevDummy let postDummy = ListNode(0) var post: ListNode? = postDummy var checkingNode = head while let validCheckingNode = checkingNode { checkingNode = validCheckingNode.next if validCheckingNode.val < x { prev?.next = validCheckingNode prev = prev?.next } else { post?.next = validCheckingNode post = post?.next } } post?.next = nil prev?.next = postDummy.next return prevDummy.next } }
f713f61b220516b8587a693b00f85bb0
22.333333
60
0.640659
false
false
false
false
daxiangfei/RTSwiftUtils
refs/heads/master
RTSwiftUtils/Extension/NSAttributedStringExtension.swift
mit
1
// // NSAttributedStringExtension.swift // RongTeng // // Created by rongteng on 16/5/17. // Copyright © 2016年 Mike. All rights reserved. // import Foundation import UIKit extension NSAttributedString { ///二部分 色值和字体都不同 public class func attributedOfTwoPart(onePartTitle:String,onePartForegroundColor:UIColor,onePartFontSize:CGFloat,twoPartTitle:String,twoPartForegroundColor:UIColor,twoPartFontSize:CGFloat) -> NSAttributedString { let resultAtt = NSMutableAttributedString() let oneAttDic = [NSAttributedStringKey.foregroundColor:onePartForegroundColor,NSAttributedStringKey.font:UIFont.systemFont(ofSize: onePartFontSize)] let oneAtt = NSAttributedString(string: onePartTitle, attributes: oneAttDic) resultAtt.append(oneAtt) let twoAttDic = [NSAttributedStringKey.foregroundColor:twoPartForegroundColor,NSAttributedStringKey.font:UIFont.systemFont(ofSize: twoPartFontSize)] let twoAtt = NSAttributedString(string: twoPartTitle, attributes: twoAttDic) resultAtt.append(twoAtt) return resultAtt } ///二部分 色值相同 字体不同 public class func attributedOfTwoPartWithSameColor(foregroundColor:UIColor,onePartTitle:String,onePartFontSize:CGFloat,twoPartTitle:String,twoPartFontSize:CGFloat) -> NSAttributedString { let resultAtt = NSMutableAttributedString() let oneAttDic = [NSAttributedStringKey.foregroundColor:foregroundColor,NSAttributedStringKey.font:UIFont.systemFont(ofSize: onePartFontSize)] let oneAtt = NSAttributedString(string: onePartTitle, attributes: oneAttDic) resultAtt.append(oneAtt) let twoAttDic = [NSAttributedStringKey.foregroundColor:foregroundColor,NSAttributedStringKey.font:UIFont.systemFont(ofSize: twoPartFontSize)] let twoAtt = NSAttributedString(string: twoPartTitle, attributes: twoAttDic) resultAtt.append(twoAtt) return resultAtt } ///创建一个 有下划线的文字 public class func attributedOfUnderLine(title:String,titleColor:UIColor) -> NSAttributedString { let oneAttDic = [NSAttributedStringKey.underlineStyle:NSUnderlineStyle.styleSingle.rawValue, NSAttributedStringKey.underlineColor:titleColor, NSAttributedStringKey.foregroundColor:titleColor] as [NSAttributedStringKey : Any] let oneAtt = NSAttributedString(string: title, attributes: oneAttDic) return oneAtt } ///下划线和正常类型 public class func attributedForUnderLineAndNormal(oneTitle:String,oneTitleColor:UIColor,twoTitle:String,twoTitleColor:UIColor) -> NSAttributedString { let resultAtt = NSMutableAttributedString() let oneAttDic = [NSAttributedStringKey.underlineStyle:NSUnderlineStyle.styleSingle.rawValue, NSAttributedStringKey.underlineColor:oneTitleColor, NSAttributedStringKey.foregroundColor:oneTitleColor] as [NSAttributedStringKey : Any] let oneAtt = NSAttributedString(string: oneTitle, attributes: oneAttDic) resultAtt.append(oneAtt) let twoAttDic = [NSAttributedStringKey.foregroundColor:twoTitleColor] let twoAtt = NSAttributedString(string: twoTitle, attributes: twoAttDic) resultAtt.append(twoAtt) return resultAtt } }
6165063dd0d47c71158b22e0541dec9e
33.297872
214
0.766439
false
false
false
false
FrainL/FxJSON
refs/heads/master
FxJSONTests/ProtocolTests.swift
mit
1
// // SerializeTests.swift // SweeftyJSON // // Created by Frain on 8/27/16. // // The MIT License (MIT) // // Copyright (c) 2016 Frain // // 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 class ProtocolTests: XCTestCase { func testCodable() { struct A: JSONDecodable, JSONEncodable { let name: String let age: Int let gender: Gender // init(decode json: JSON) throws { // name = try json["name"]< // age = try json["age"]< // gender = try json["gender"]< // } enum Gender: Int, JSONCodable { case boy case girl } } let json = ["name": "name", "age": 10, "gender": 0] as JSON guard let a = A.init(json) else { XCTFail(); return } XCTAssertEqual(a.age, 10) XCTAssertEqual(a.name, "name") XCTAssertEqual(a.gender.rawValue, A.Gender.boy.rawValue) XCTAssertEqual(a.json, json) XCTAssertThrowsError(try A.init(decode: ["name": "", "age": "10"])) { (error) in guard case JSON.Error.typeMismatch = error else { XCTFail(); return } } } func testError() { } }
4a2e95e265b20f639ce070853585f68a
30.913043
84
0.655313
false
true
false
false
frootloops/swift
refs/heads/master
test/Constraints/closures.swift
apache-2.0
1
// RUN: %target-typecheck-verify-swift -swift-version 3 // RUN: %target-typecheck-verify-swift -swift-version 4 func myMap<T1, T2>(_ array: [T1], _ fn: (T1) -> T2) -> [T2] {} var intArray : [Int] _ = myMap(intArray, { String($0) }) _ = myMap(intArray, { x -> String in String(x) } ) // Closures with too few parameters. func foo(_ x: (Int, Int) -> Int) {} foo({$0}) // expected-error{{contextual closure type '(Int, Int) -> Int' expects 2 arguments, but 1 was used in closure body}} foo({ [intArray] in $0}) // expected-error{{contextual closure type '(Int, Int) -> Int' expects 2 arguments, but 1 was used in closure body}} struct X {} func mySort(_ array: [String], _ predicate: (String, String) -> Bool) -> [String] {} func mySort(_ array: [X], _ predicate: (X, X) -> Bool) -> [X] {} var strings : [String] _ = mySort(strings, { x, y in x < y }) // Closures with inout arguments. func f0<T, U>(_ t: T, _ f: (inout T) -> U) -> U { var t2 = t return f(&t2) } struct X2 { func g() -> Float { return 0 } } _ = f0(X2(), {$0.g()}) // Closures with inout arguments and '__shared' conversions. func inoutToSharedConversions() { func fooOW<T, U>(_ f : (__owned T) -> U) {} fooOW({ (x : Int) in return Int(5) }) // '__owned'-to-'__owned' allowed fooOW({ (x : __shared Int) in return Int(5) }) // '__shared'-to-'__owned' allowed fooOW({ (x : inout Int) in return Int(5) }) // expected-error {{cannot convert value of type '(inout Int) -> Int' to expected argument type '(_) -> _'}} func fooIO<T, U>(_ f : (inout T) -> U) {} fooIO({ (x : inout Int) in return Int(5) }) // 'inout'-to-'inout' allowed fooIO({ (x : __shared Int) in return Int(5) }) // expected-error {{cannot convert value of type '(__shared Int) -> Int' to expected argument type '(inout _) -> _'}} fooIO({ (x : Int) in return Int(5) }) // expected-error {{cannot convert value of type '(inout Int) -> Int' to expected argument type '(inout _) -> _'}} func fooSH<T, U>(_ f : (__shared T) -> U) {} fooSH({ (x : __shared Int) in return Int(5) }) // '__shared'-to-'__shared' allowed fooSH({ (x : inout Int) in return Int(5) }) // expected-error {{cannot convert value of type '(inout Int) -> Int' to expected argument type '(__shared _) -> _'}} fooSH({ (x : Int) in return Int(5) }) // '__owned'-to-'__shared' allowed } // Autoclosure func f1(f: @autoclosure () -> Int) { } func f2() -> Int { } f1(f: f2) // expected-error{{function produces expected type 'Int'; did you mean to call it with '()'?}}{{9-9=()}} f1(f: 5) // Ternary in closure var evenOrOdd : (Int) -> String = {$0 % 2 == 0 ? "even" : "odd"} // <rdar://problem/15367882> func foo() { not_declared({ $0 + 1 }) // expected-error{{use of unresolved identifier 'not_declared'}} } // <rdar://problem/15536725> struct X3<T> { init(_: (T) -> ()) {} } func testX3(_ x: Int) { var x = x _ = X3({ x = $0 }) _ = x } // <rdar://problem/13811882> func test13811882() { var _ : (Int) -> (Int, Int) = {($0, $0)} var x = 1 var _ : (Int) -> (Int, Int) = {($0, x)} x = 2 } // <rdar://problem/21544303> QoI: "Unexpected trailing closure" should have a fixit to insert a 'do' statement // <https://bugs.swift.org/browse/SR-3671> func r21544303() { var inSubcall = true { } // expected-error {{computed property must have accessors specified}} inSubcall = false // This is a problem, but isn't clear what was intended. var somethingElse = true { } // expected-error {{computed property must have accessors specified}} inSubcall = false var v2 : Bool = false v2 = inSubcall { // expected-error {{cannot call value of non-function type 'Bool'}} expected-note {{did you mean to use a 'do' statement?}} {{3-3=do }} } } // <https://bugs.swift.org/browse/SR-3671> func SR3671() { let n = 42 func consume(_ x: Int) {} { consume($0) }(42) ; ({ $0(42) } { consume($0) }) // expected-note {{callee is here}} { print(42) } // expected-warning {{braces here form a trailing closure separated from its callee by multiple newlines}} expected-note {{did you mean to use a 'do' statement?}} {{3-3=do }} expected-error {{cannot call value of non-function type '()'}} ; ({ $0(42) } { consume($0) }) // expected-note {{callee is here}} { print($0) } // expected-warning {{braces here form a trailing closure separated from its callee by multiple newlines}} expected-error {{cannot call value of non-function type '()'}} ; ({ $0(42) } { consume($0) }) // expected-note {{callee is here}} { [n] in print(42) } // expected-warning {{braces here form a trailing closure separated from its callee by multiple newlines}} expected-error {{cannot call value of non-function type '()'}} ; ({ $0(42) } { consume($0) }) // expected-note {{callee is here}} { consume($0) }(42) // expected-warning {{braces here form a trailing closure separated from its callee by multiple newlines}} expected-error {{cannot call value of non-function type '()'}} ; ({ $0(42) } { consume($0) }) // expected-note {{callee is here}} { (x: Int) in consume(x) }(42) // expected-warning {{braces here form a trailing closure separated from its callee by multiple newlines}} expected-error {{cannot call value of non-function type '()'}} ; // This is technically a valid call, so nothing goes wrong until (42) { $0(3) } { consume($0) }(42) // expected-error {{cannot call value of non-function type '()'}} ; ({ $0(42) }) { consume($0) }(42) // expected-error {{cannot call value of non-function type '()'}} ; { $0(3) } { [n] in consume($0) }(42) // expected-error {{cannot call value of non-function type '()'}} ; ({ $0(42) }) { [n] in consume($0) }(42) // expected-error {{cannot call value of non-function type '()'}} ; // Equivalent but more obviously unintended. { $0(3) } // expected-note {{callee is here}} { consume($0) }(42) // expected-error {{cannot call value of non-function type '()'}} // expected-warning@-1 {{braces here form a trailing closure separated from its callee by multiple newlines}} ({ $0(3) }) // expected-note {{callee is here}} { consume($0) }(42) // expected-error {{cannot call value of non-function type '()'}} // expected-warning@-1 {{braces here form a trailing closure separated from its callee by multiple newlines}} ; // Also a valid call (!!) { $0 { $0 } } { $0 { 1 } } // expected-error {{expression resolves to an unused function}} consume(111) } // <rdar://problem/22162441> Crash from failing to diagnose nonexistent method access inside closure func r22162441(_ lines: [String]) { _ = lines.map { line in line.fooBar() } // expected-error {{value of type 'String' has no member 'fooBar'}} _ = lines.map { $0.fooBar() } // expected-error {{value of type 'String' has no member 'fooBar'}} } func testMap() { let a = 42 [1,a].map { $0 + 1.0 } // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}} // expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists: }} } // <rdar://problem/22414757> "UnresolvedDot" "in wrong phase" assertion from verifier [].reduce { $0 + $1 } // expected-error {{cannot invoke 'reduce' with an argument list of type '((_, _) -> _)'}} // <rdar://problem/22333281> QoI: improve diagnostic when contextual type of closure disagrees with arguments var _: () -> Int = {0} // expected-error @+1 {{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}} {{24-24=_ in }} var _: (Int) -> Int = {0} // expected-error @+1 {{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}} {{24-24= _ in}} var _: (Int) -> Int = { 0 } // expected-error @+1 {{contextual type for closure argument list expects 2 arguments, which cannot be implicitly ignored}} {{29-29=_,_ in }} var _: (Int, Int) -> Int = {0} // expected-error @+1 {{contextual closure type '(Int, Int) -> Int' expects 2 arguments, but 3 were used in closure body}} var _: (Int,Int) -> Int = {$0+$1+$2} // expected-error @+1 {{contextual closure type '(Int, Int, Int) -> Int' expects 3 arguments, but 2 were used in closure body}} var _: (Int, Int, Int) -> Int = {$0+$1} // expected-error @+1 {{contextual closure type '(Int) -> Int' expects 1 argument, but 2 were used in closure body}} var _: (Int) -> Int = {a,b in 0} // expected-error @+1 {{contextual closure type '(Int) -> Int' expects 1 argument, but 3 were used in closure body}} var _: (Int) -> Int = {a,b,c in 0} // expected-error @+1 {{contextual closure type '(Int, Int, Int) -> Int' expects 3 arguments, but 2 were used in closure body}} var _: (Int, Int, Int) -> Int = {a, b in a+b} // <rdar://problem/15998821> Fail to infer types for closure that takes an inout argument func r15998821() { func take_closure(_ x : (inout Int) -> ()) { } func test1() { take_closure { (a : inout Int) in a = 42 } } func test2() { take_closure { a in a = 42 } } func withPtr(_ body: (inout Int) -> Int) {} func f() { withPtr { p in return p } } let g = { x in x = 3 } take_closure(g) } // <rdar://problem/22602657> better diagnostics for closures w/o "in" clause var _: (Int,Int) -> Int = {$0+$1+$2} // expected-error {{contextual closure type '(Int, Int) -> Int' expects 2 arguments, but 3 were used in closure body}} // Crash when re-typechecking bodies of non-single expression closures struct CC {} func callCC<U>(_ f: (CC) -> U) -> () {} func typeCheckMultiStmtClosureCrash() { callCC { // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{11-11= () -> Int in }} _ = $0 return 1 } } // SR-832 - both these should be ok func someFunc(_ foo: ((String) -> String)?, bar: @escaping (String) -> String) { let _: (String) -> String = foo != nil ? foo! : bar let _: (String) -> String = foo ?? bar } func verify_NotAC_to_AC_failure(_ arg: () -> ()) { func takesAC(_ arg: @autoclosure () -> ()) {} takesAC(arg) // expected-error {{function produces expected type '()'; did you mean to call it with '()'?}} } // SR-1069 - Error diagnostic refers to wrong argument class SR1069_W<T> { func append<Key: AnyObject>(value: T, forKey key: Key) where Key: Hashable {} } class SR1069_C<T> { let w: SR1069_W<(AnyObject, T) -> ()> = SR1069_W() } struct S<T> { let cs: [SR1069_C<T>] = [] func subscribe<Object: AnyObject>(object: Object?, method: (Object, T) -> ()) where Object: Hashable { let wrappedMethod = { (object: AnyObject, value: T) in } // expected-error @+1 {{value of optional type 'Object?' not unwrapped; did you mean to use '!' or '?'?}} cs.forEach { $0.w.append(value: wrappedMethod, forKey: object) } } } // Make sure we cannot infer an () argument from an empty parameter list. func acceptNothingToInt (_: () -> Int) {} func testAcceptNothingToInt(ac1: @autoclosure () -> Int) { acceptNothingToInt({ac1($0)}) // expected-error@-1{{contextual closure type '() -> Int' expects 0 arguments, but 1 was used in closure body}} } // <rdar://problem/23570873> QoI: Poor error calling map without being able to infer "U" (closure result inference) struct Thing { init?() {} } // This throws a compiler error let things = Thing().map { thing in // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{34-34=-> (Thing) }} // Commenting out this makes it compile _ = thing return thing } // <rdar://problem/21675896> QoI: [Closure return type inference] Swift cannot find members for the result of inlined lambdas with branches func r21675896(file : String) { let x: String = { // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{20-20= () -> String in }} if true { return "foo" } else { return file } }().pathExtension } // <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? 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/20921068> Swift fails to compile: [0].map() { _ in let r = (1,2).0; return r } [0].map { // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{5-5=-> Int }} _ in let r = (1,2).0 return r } // <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/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/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 complex closure return type; add explicit type to disambiguate}} {{23-23=-> String }} print("a") return "hi" } } // Make sure that behavior related to allowing trailing closures to match functions // with Any as a final parameter is the same after the changes made by SR-2505, namely: // that we continue to select function that does _not_ have Any as a final parameter in // presence of other possibilities. protocol SR_2505_Initable { init() } struct SR_2505_II : SR_2505_Initable {} protocol P_SR_2505 { associatedtype T: SR_2505_Initable } extension P_SR_2505 { func test(it o: (T) -> Bool) -> Bool { return o(T.self()) } } class C_SR_2505 : P_SR_2505 { typealias T = SR_2505_II func test(_ o: Any) -> Bool { return false } func call(_ c: C_SR_2505) -> Bool { // Note: no diagnostic about capturing 'self', because this is a // non-escaping closure -- that's how we know we have selected // test(it:) and not test(_) return c.test { o in test(o) } } } let _ = C_SR_2505().call(C_SR_2505()) // <rdar://problem/28909024> Returning incorrect result type from method invocation can result in nonsense diagnostic extension Collection { func r28909024(_ predicate: (Iterator.Element)->Bool) -> Index { return startIndex } } func fn_r28909024(n: Int) { return (0..<10).r28909024 { // expected-error {{unexpected non-void return value in void function}} _ in true } } // SR-2994: Unexpected ambiguous expression in closure with generics struct S_2994 { var dataOffset: Int } class C_2994<R> { init(arg: (R) -> Void) {} } func f_2994(arg: String) {} func g_2994(arg: Int) -> Double { return 2 } C_2994<S_2994>(arg: { (r: S_2994) in f_2994(arg: g_2994(arg: r.dataOffset)) }) // expected-error {{cannot convert value of type 'Double' to expected argument type 'String'}} let _ = { $0[$1] }(1, 1) // expected-error {{cannot subscript a value of incorrect or ambiguous type}} let _ = { $0 = ($0 = {}) } // expected-error {{assigning a variable to itself}} let _ = { $0 = $0 = 42 } // expected-error {{assigning a variable to itself}} // https://bugs.swift.org/browse/SR-403 // The () -> T => () -> () implicit conversion was kicking in anywhere // inside a closure result, not just at the top-level. let mismatchInClosureResultType : (String) -> ((Int) -> Void) = { (String) -> ((Int) -> Void) in return { } // expected-error@-1 {{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}} } // SR-3520: Generic function taking closure with inout parameter can result in a variety of compiler errors or EXC_BAD_ACCESS func sr3520_1<T>(_ g: (inout T) -> Int) {} sr3520_1 { $0 = 1 } // expected-error {{cannot convert value of type '()' to closure result type 'Int'}} // This test makes sure that having closure with inout argument doesn't crash with member lookup struct S_3520 { var number1: Int } func sr3520_set_via_closure<S, T>(_ closure: (inout S, T) -> ()) {} sr3520_set_via_closure({ $0.number1 = $1 }) // expected-error {{type of expression is ambiguous without more context}} // SR-3073: UnresolvedDotExpr in single expression closure struct SR3073Lense<Whole, Part> { let set: (inout Whole, Part) -> () } struct SR3073 { var number1: Int func lenses() { let _: SR3073Lense<SR3073, Int> = SR3073Lense( set: { $0.number1 = $1 } // ok ) } } // SR-3479: Segmentation fault and other error for closure with inout parameter func sr3497_unfold<A, B>(_ a0: A, next: (inout A) -> B) {} func sr3497() { let _ = sr3497_unfold((0, 0)) { s in 0 } // ok } // SR-3758: Swift 3.1 fails to compile 3.0 code involving closures and IUOs let _: ((Any?) -> Void) = { (arg: Any!) in } // This example was rejected in 3.0 as well, but accepting it is correct. let _: ((Int?) -> Void) = { (arg: Int!) in } // rdar://30429709 - We should not attempt an implicit conversion from // () -> T to () -> Optional<()>. func returnsArray() -> [Int] { return [] } returnsArray().flatMap { $0 }.flatMap { } // expected-warning@-1 {{expression of type 'Int' is unused}} // expected-warning@-2 {{result of call to 'flatMap' is unused}} // rdar://problem/30271695 _ = ["hi"].flatMap { $0.isEmpty ? nil : $0 } // rdar://problem/32432145 - compiler should emit fixit to remove "_ in" in closures if 0 parameters is expected func r32432145(_ a: () -> ()) {} r32432145 { _,_ in // expected-error@-1 {{contextual closure type '() -> ()' expects 0 arguments, but 2 were used in closure body}} {{13-19=}} print("answer is 42") } // rdar://problem/30106822 - Swift ignores type error in closure and presents a bogus error about the caller [1, 2].first { $0.foo = 3 } // expected-error@-1 {{value of type 'Int' has no member 'foo'}} // rdar://problem/32433193, SR-5030 - Higher-order function diagnostic mentions the wrong contextual type conversion problem protocol A_SR_5030 { associatedtype Value func map<U>(_ t : @escaping (Self.Value) -> U) -> B_SR_5030<U> } struct B_SR_5030<T> : A_SR_5030 { typealias Value = T func map<U>(_ t : @escaping (T) -> U) -> B_SR_5030<U> { fatalError() } } func sr5030_exFalso<T>() -> T { fatalError() } extension A_SR_5030 { func foo() -> B_SR_5030<Int> { let tt : B_SR_5030<Int> = sr5030_exFalso() return tt.map { x in (idx: x) } // expected-error@-1 {{cannot convert value of type '(idx: (Int))' to closure result type 'Int'}} } } // rdar://problem/33296619 let u = rdar33296619().element //expected-error {{use of unresolved identifier 'rdar33296619'}} [1].forEach { _ in _ = "\(u)" _ = 1 + "hi" // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'String'}} // expected-note@-1 {{overloads for '+' exist with these partially matching parameter lists}} } class SR5666 { var property: String? } func testSR5666(cs: [SR5666?]) -> [String?] { return cs.map({ c in let a = c.propertyWithTypo ?? "default" // expected-error@-1 {{value of type 'SR5666?' has no member 'propertyWithTypo'}} let b = "\(a)" return b }) } // Ensure that we still do the appropriate pointer conversion here. _ = "".withCString { UnsafeMutableRawPointer(mutating: $0) } // rdar://problem/34077439 - Crash when pre-checking bails out and // leaves us with unfolded SequenceExprs inside closure body. _ = { (offset) -> T in // expected-error {{use of undeclared type 'T'}} return offset ? 0 : 0 } struct SR5202<T> { func map<R>(fn: (T) -> R) {} } SR5202<()>().map{ return 0 } SR5202<()>().map{ _ in return 0 } SR5202<Void>().map{ return 0 } SR5202<Void>().map{ _ in return 0 } func sr3520_2<T>(_ item: T, _ update: (inout T) -> Void) { var x = item update(&x) } var sr3250_arg = 42 sr3520_2(sr3250_arg) { $0 += 3 } // ok // SR-1976/SR-3073: Inference of inout func sr1976<T>(_ closure: (inout T) -> Void) {} sr1976({ $0 += 2 }) // ok // rdar://problem/33429010 struct I_33429010 : IteratorProtocol { func next() -> Int? { fatalError() } } extension Sequence { public func rdar33429010<Result>(into initialResult: Result, _ nextPartialResult: (_ partialResult: inout Result, Iterator.Element) throws -> () ) rethrows -> Result { return initialResult } } extension Int { public mutating func rdar33429010_incr(_ inc: Int) { self += inc } } func rdar33429010_2() { let iter = I_33429010() var acc: Int = 0 // expected-warning {{}} let _: Int = AnySequence { iter }.rdar33429010(into: acc, { $0 + $1 }) // expected-warning@-1 {{result of operator '+' is unused}} let _: Int = AnySequence { iter }.rdar33429010(into: acc, { $0.rdar33429010_incr($1) }) } class P_33429010 { var name: String = "foo" } class C_33429010 : P_33429010 { } func rdar33429010_3() { let arr = [C_33429010()] let _ = arr.map({ ($0.name, $0 as P_33429010) }) // Ok } func rdar36054961() { func bar(dict: [String: (inout String, Range<String.Index>, String) -> Void]) {} bar(dict: ["abc": { str, range, _ in str.replaceSubrange(range, with: str[range].reversed()) }]) }
15ba242c98a50d66fc89d5bded674b46
34.039755
254
0.633749
false
false
false
false
burla69/PayDay
refs/heads/master
PayDay/QRScanningViewController.swift
mit
1
// // QRScanningViewController.swift // PayDay // // Created by Oleksandr Burla on 3/15/16. // Copyright © 2016 Oleksandr Burla. All rights reserved. // import UIKit import AVFoundation protocol QRScanningViewControllerDelegate { func qrCodeFromQRViewController(string: String) func goFromQRCode() } class QRScanningViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate { @IBOutlet weak var cameraView: UIView! var delegate: QRScanningViewControllerDelegate! var captureSession: AVCaptureSession? var videoPreviewLayer: AVCaptureVideoPreviewLayer? var qrCodeFrameView: UIView? var isFrontCamera = true override func viewDidLoad() { super.viewDidLoad() guard let captureDevice = (AVCaptureDevice.devices() .filter{ $0.hasMediaType(AVMediaTypeVideo) && $0.position == .Back}) .first as? AVCaptureDevice else { return } do { let input = try AVCaptureDeviceInput(device: captureDevice) captureSession = AVCaptureSession() captureSession?.addInput(input) let captureMetadataOutput = AVCaptureMetadataOutput() captureSession?.addOutput(captureMetadataOutput) captureMetadataOutput.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue()) captureMetadataOutput.metadataObjectTypes = [AVMetadataObjectTypeQRCode, AVMetadataObjectTypeCode93Code] videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession) videoPreviewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill videoPreviewLayer?.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 155) cameraView.layer.addSublayer(videoPreviewLayer!) captureSession?.startRunning() qrCodeFrameView = UIView() if let qrCodeFrameView = qrCodeFrameView { qrCodeFrameView.layer.borderColor = UIColor.greenColor().CGColor qrCodeFrameView.layer.borderWidth = 3 cameraView.addSubview(qrCodeFrameView) cameraView.bringSubviewToFront(qrCodeFrameView) } } catch { print(error) return } isFrontCamera = false } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) { if metadataObjects == nil || metadataObjects.count == 0 { qrCodeFrameView?.frame = CGRectZero print("QR Code is not detected") return } let metadataObj = metadataObjects[0] as! AVMetadataMachineReadableCodeObject let barCodeObject = videoPreviewLayer?.transformedMetadataObjectForMetadataObject(metadataObj) qrCodeFrameView?.frame = barCodeObject!.bounds var token: dispatch_once_t = 0 dispatch_once(&token) { if metadataObj.stringValue != nil { print("QR code\(metadataObj.stringValue)") self.delegate.qrCodeFromQRViewController(metadataObj.stringValue) } self.dismissViewControllerAnimated(true, completion: { self.delegate.goFromQRCode() }) } } @IBAction func useKeyPadPressed(sender: UIButton) { self.dismissViewControllerAnimated(true, completion: nil) } @IBAction func changeCamera(sender: AnyObject) { if isFrontCamera { guard let captureDevice = (AVCaptureDevice.devices() .filter{ $0.hasMediaType(AVMediaTypeVideo) && $0.position == .Back}) .first as? AVCaptureDevice else { return } do { let input = try AVCaptureDeviceInput(device: captureDevice) captureSession = AVCaptureSession() captureSession?.addInput(input) let captureMetadataOutput = AVCaptureMetadataOutput() captureSession?.addOutput(captureMetadataOutput) captureMetadataOutput.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue()) captureMetadataOutput.metadataObjectTypes = [AVMetadataObjectTypeQRCode, AVMetadataObjectTypeCode93Code] videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession) videoPreviewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill videoPreviewLayer?.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 155) cameraView.layer.addSublayer(videoPreviewLayer!) captureSession?.startRunning() qrCodeFrameView = UIView() if let qrCodeFrameView = qrCodeFrameView { qrCodeFrameView.layer.borderColor = UIColor.greenColor().CGColor qrCodeFrameView.layer.borderWidth = 3 cameraView.addSubview(qrCodeFrameView) cameraView.bringSubviewToFront(qrCodeFrameView) } } catch { print(error) return } isFrontCamera = false } else { guard let captureDevice = (AVCaptureDevice.devices() .filter{ $0.hasMediaType(AVMediaTypeVideo) && $0.position == .Front}) .first as? AVCaptureDevice else { return } do { let input = try AVCaptureDeviceInput(device: captureDevice) captureSession = AVCaptureSession() captureSession?.addInput(input) let captureMetadataOutput = AVCaptureMetadataOutput() captureSession?.addOutput(captureMetadataOutput) captureMetadataOutput.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue()) captureMetadataOutput.metadataObjectTypes = [AVMetadataObjectTypeQRCode, AVMetadataObjectTypeCode93Code] videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession) videoPreviewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill videoPreviewLayer?.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 155) cameraView.layer.addSublayer(videoPreviewLayer!) captureSession?.startRunning() qrCodeFrameView = UIView() if let qrCodeFrameView = qrCodeFrameView { qrCodeFrameView.layer.borderColor = UIColor.greenColor().CGColor qrCodeFrameView.layer.borderWidth = 3 cameraView.addSubview(qrCodeFrameView) cameraView.bringSubviewToFront(qrCodeFrameView) } } catch { print(error) return } isFrontCamera = true } } }
9c2e8e94b35040cce5a49c25ac115c60
35.33945
162
0.577001
false
false
false
false
cuappdev/eatery
refs/heads/master
Eatery/Onboarding/Controllers/OnboardingInfoViewController.swift
mit
1
// // OnboardingInfoViewController.swift // Eatery // // Created by Reade Plunkett on 11/15/19. // Copyright © 2019 CUAppDev. All rights reserved. // import Lottie import UIKit class OnboardingInfoViewController: OnboardingViewController { private let stackView = UIStackView() private let animationView = AnimationView() private let nextButton = UIButton() private let animation: String init(title: String, subtitle: String, animation: String) { self.animation = animation super.init(title: title, subtitle: subtitle) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() setUpStackView() setUpAnimationView() setUpButton() contentView.snp.makeConstraints { make in make.width.equalToSuperview() make.height.equalTo(stackView) } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) DispatchQueue.main.async { self.animationView.play() } } private func setUpStackView() { stackView.axis = .vertical stackView.distribution = .fill stackView.alignment = .center stackView.spacing = 40 contentView.addSubview(stackView) stackView.snp.makeConstraints { make in make.center.width.equalToSuperview() } } private func setUpAnimationView() { animationView.animation = Animation.named(animation) animationView.contentMode = .scaleAspectFit animationView.transform = CGAffineTransform(scaleX: 2, y: 2) stackView.addArrangedSubview(animationView) animationView.snp.makeConstraints { make in make.height.equalTo(128) } } private func setUpButton() { nextButton.layer.borderWidth = 2 nextButton.layer.borderColor = UIColor.white.cgColor nextButton.layer.cornerRadius = 30 nextButton.setTitle("NEXT", for: .normal) nextButton.titleLabel?.font = .systemFont(ofSize: 17, weight: .heavy) nextButton.titleLabel?.textColor = .white nextButton.addTarget(self, action: #selector(didTapNextButton), for: .touchUpInside) stackView.addArrangedSubview(nextButton) nextButton.snp.makeConstraints { make in make.width.equalTo(240) make.height.equalTo(60) } } @objc private func didTapNextButton(sender: UIButton) { delegate?.onboardingViewControllerDidTapNext(self) } }
1f0abc7480f15e73aff9d8333132360d
27.376344
92
0.654415
false
false
false
false
mleiv/MEGameTracker
refs/heads/master
MEGameTracker/Views/Common/Data Rows/Callouts/CalloutsNib.swift
mit
1
// // CalloutsNib.swift // MEGameTracker // // Created by Emily Ivie on 6/9/16. // Copyright © 2016 Emily Ivie. All rights reserved. // import UIKit @IBDesignable open class CalloutsNib: SimpleArrayDataRowNib { override open class func loadNib(heading: String? = nil, cellNibs: [String] = []) -> CalloutsNib? { let bundle = Bundle(for: CalloutsNib.self) if let view = bundle.loadNibNamed("CalloutsNib", owner: self, options: nil)?.first as? CalloutsNib { let bundle = Bundle(for: CalloutsNib.self) for nib in cellNibs { view.tableView?.register(UINib(nibName: nib, bundle: bundle), forCellReuseIdentifier: nib) } return view } return nil } }
59ee69a4a7b22dd5c45fafd8db8fe2a3
27.291667
103
0.698085
false
false
false
false
marchinram/SwiftChip-8
refs/heads/master
SwiftChip-8/SettingsManager.swift
mit
1
// // SettingsManager.swift // SwiftChip-8 // // Created by Brian Rojas on 8/24/17. // Copyright © 2017 Brian Rojas. All rights reserved. // import Foundation import GLKit class SettingsManager { public static let instance = SettingsManager() public static let yellowishPixelColor = #colorLiteral(red: 1, green: 0.768627451, blue: 0, alpha: 1) public static let orangeBackgroundColor = #colorLiteral(red: 0.6901960784, green: 0.2901960784, blue: 0, alpha: 1) private init() { let pixelRGBA: (Float, Float, Float, Float) = SettingsManager.yellowishPixelColor.separate() let bgRGBA: (Float, Float, Float, Float) = SettingsManager.orangeBackgroundColor.separate() UserDefaults.standard.register(defaults:[ "pixelColorR": pixelRGBA.0, "pixelColorG": pixelRGBA.1, "pixelColorB": pixelRGBA.2, "pixelColorA": pixelRGBA.3, "backgroundColorR": bgRGBA.0, "backgroundColorG": bgRGBA.1, "backgroundColorB": bgRGBA.2, "backgroundColorA": bgRGBA.3, "buzzerNote": Buzzer.Frequency.C4.rawValue, "buzzerVolume": 1.0 ]) } public var pixelColor: UIColor { get { let r = CGFloat(UserDefaults.standard.float(forKey: "pixelColorR")) let g = CGFloat(UserDefaults.standard.float(forKey: "pixelColorG")) let b = CGFloat(UserDefaults.standard.float(forKey: "pixelColorB")) let a = CGFloat(UserDefaults.standard.float(forKey: "pixelColorA")) return UIColor(red: r, green: g, blue: b, alpha: a) } set { let rgba: (CGFloat, CGFloat, CGFloat, CGFloat) = newValue.separate() UserDefaults.standard.set(rgba.0, forKey: "pixelColorR") UserDefaults.standard.set(rgba.1, forKey: "pixelColorG") UserDefaults.standard.set(rgba.2, forKey: "pixelColorB") UserDefaults.standard.set(rgba.3, forKey: "pixelColorA") } } public var backgroundColor: UIColor { get { let r = CGFloat(UserDefaults.standard.float(forKey: "backgroundColorR")) let g = CGFloat(UserDefaults.standard.float(forKey: "backgroundColorG")) let b = CGFloat(UserDefaults.standard.float(forKey: "backgroundColorB")) let a = CGFloat(UserDefaults.standard.float(forKey: "backgroundColorA")) return UIColor(red: r, green: g, blue: b, alpha: a) } set { let rgba: (CGFloat, CGFloat, CGFloat, CGFloat) = newValue.separate() UserDefaults.standard.set(rgba.0, forKey: "backgroundColorR") UserDefaults.standard.set(rgba.1, forKey: "backgroundColorG") UserDefaults.standard.set(rgba.2, forKey: "backgroundColorB") UserDefaults.standard.set(rgba.3, forKey: "backgroundColorA") } } public var buzzerNote: Buzzer.Frequency { get { let rawValue = UserDefaults.standard.float(forKey: "buzzerNote") return Buzzer.Frequency(rawValue: rawValue) ?? Buzzer.Frequency.C4 } set { UserDefaults.standard.set(newValue.rawValue, forKey: "buzzerNote") } } public var buzzerVolume: Float { get { return UserDefaults.standard.float(forKey: "buzzerVolume") } set { UserDefaults.standard.set(newValue, forKey: "buzzerVolume") } } } extension UIColor { var glkVector4: GLKVector4 { let rgba: (Float, Float, Float, Float) = separate() return GLKVector4Make(rgba.0, rgba.1, rgba.2, rgba.3) } var floatTuple: (Float, Float, Float, Float) { return separate() } fileprivate func separate<T: BinaryFloatingPoint>() -> (T, T, T, T) { var r: CGFloat = 0.0 var g: CGFloat = 0.0 var b: CGFloat = 0.0 var a: CGFloat = 0.0 getRed(&r, green: &g, blue: &b, alpha: &a) return (T(Float(r)), T(Float(g)), T(Float(b)), T(Float(a))) } }
f9b125172ac197fd7e8013b6be7f5b89
35.6875
118
0.602823
false
false
false
false
sbennett912/SwiftGL
refs/heads/master
SwiftGL/Shader.swift
mit
1
// // Shader.swift // SwiftGL // // Created by Scott Bennett on 2014-06-08. // Copyright (c) 2014 Scott Bennett. All rights reserved. // #if os(OSX) import Cocoa import OpenGL #else import Foundation import OpenGLES func glProgramUniform1i(_ program: GLuint, _ location: GLint, _ x: GLint) { return glProgramUniform1iEXT(program, location, x) } func glProgramUniform2i(_ program: GLuint, _ location: GLint, _ x: GLint, _ y: GLint) { return glProgramUniform2iEXT(program, location, x, y) } func glProgramUniform3i(_ program: GLuint, _ location: GLint, _ x: GLint, _ y: GLint, _ z: GLint) { return glProgramUniform3iEXT(program, location, x, y, z) } func glProgramUniform4i(_ program: GLuint, _ location: GLint, _ x: GLint, _ y: GLint, _ z: GLint, _ w: GLint) { return glProgramUniform4iEXT(program, location, x, y, z, w) } func glProgramUniform1iv(_ program: GLuint, _ location: GLint, _ count: GLsizei, _ value: UnsafePointer<GLint>) { return glProgramUniform1ivEXT(program, location, count, value) } func glProgramUniform2iv(_ program: GLuint, _ location: GLint, _ count: GLsizei, _ value: UnsafePointer<GLint>) { return glProgramUniform2ivEXT(program, location, count, value) } func glProgramUniform3iv(_ program: GLuint, _ location: GLint, _ count: GLsizei, _ value: UnsafePointer<GLint>) { return glProgramUniform3ivEXT(program, location, count, value) } func glProgramUniform4iv(_ program: GLuint, _ location: GLint, _ count: GLsizei, _ value: UnsafePointer<GLint>) { return glProgramUniform4ivEXT(program, location, count, value) } func glProgramUniform1f(_ program: GLuint, _ location: GLint, _ x: GLfloat) { return glProgramUniform1fEXT(program, location, x) } func glProgramUniform2f(_ program: GLuint, _ location: GLint, _ x: GLfloat, _ y: GLfloat) { return glProgramUniform2fEXT(program, location, x, y) } func glProgramUniform3f(_ program: GLuint, _ location: GLint, _ x: GLfloat, _ y: GLfloat, _ z: GLfloat) { return glProgramUniform3fEXT(program, location, x, y, z) } func glProgramUniform4f(_ program: GLuint, _ location: GLint, _ x: GLfloat, _ y: GLfloat, _ z: GLfloat, _ w: GLfloat) { return glProgramUniform4fEXT(program, location, x, y, z, w) } func glProgramUniform1fv(_ program: GLuint, _ location: GLint, _ count: GLsizei, _ value: UnsafePointer<GLfloat>) { return glProgramUniform1fvEXT(program, location, count, value) } func glProgramUniform2fv(_ program: GLuint, _ location: GLint, _ count: GLsizei, _ value: UnsafePointer<GLfloat>) { return glProgramUniform2fvEXT(program, location, count, value) } func glProgramUniform3fv(_ program: GLuint, _ location: GLint, _ count: GLsizei, _ value: UnsafePointer<GLfloat>) { return glProgramUniform3fvEXT(program, location, count, value) } func glProgramUniform4fv(_ program: GLuint, _ location: GLint, _ count: GLsizei, _ value: UnsafePointer<GLfloat>) { return glProgramUniform4fvEXT(program, location, count, value) } func glProgramUniformMatrix4fv(_ program: GLuint, _ location: GLint, _ count: GLsizei, _ transpose: GLboolean, _ value: UnsafePointer<GLfloat>) { return glProgramUniformMatrix4fvEXT(program, location, count, transpose, value) } #endif open class Shader { public typealias GLprogram = GLuint public typealias GLattrib = GLint public typealias GLuniform = GLint var id: GLprogram = 0 public init() { } public init(vertexSource: String, fragmentSource: String) { _ = compile(vertexSource, fragmentSource) } public init(vertexSource: String, fragmentSource: String, bindAttibutes: (GLprogram) -> ()) { _ = compile(vertexSource, fragmentSource, bindAttibutes) } public init(vertexFile: String, fragmentFile: String) { _ = load(vertexFile, fragmentFile) } public init(vertexFile: String, fragmentFile: String, bindAttibutes: (GLprogram) -> ()) { _ = load(vertexFile, fragmentFile, bindAttibutes) } deinit { glDeleteProgram(id) } /// @return true on success open func compile(_ vertexSource: String, _ fragmentSource: String) -> Bool { glDeleteProgram(id) id = glCreateProgram(); let vertexShader = Shader.compile(GL_VERTEX_SHADER, vertexSource) let fragmentShader = Shader.compile(GL_FRAGMENT_SHADER, fragmentSource) // Attach the shaders to our id glAttachShader(id, vertexShader) glAttachShader(id, fragmentShader) // Delete the shaders since they are now attached to the id, which will retain a reference to them glDeleteShader(vertexShader) glDeleteShader(fragmentShader) glLinkProgram(id) return Shader.verify(id) } /// @return true on success open func compile(_ vertexSource: String, _ fragmentSource: String, _ bindAttibutes: (GLprogram) -> ()) -> Bool { glDeleteProgram(id) id = glCreateProgram(); let vertexShader = Shader.compile(GL_VERTEX_SHADER, vertexSource) let fragmentShader = Shader.compile(GL_FRAGMENT_SHADER, fragmentSource) // Call the external function to bind all of the default shader attributes bindAttibutes(id) // Attach the shaders to our id glAttachShader(id, vertexShader) glAttachShader(id, fragmentShader) // Delete the shaders since they are now attached to the id, which will retain a reference to them glDeleteShader(vertexShader) glDeleteShader(fragmentShader) glLinkProgram(id) return Shader.verify(id) } /// @return true on success open func load(_ shader: String) -> Bool { if let vertexSource = try? String(contentsOfFile: shader + ".vsh", encoding: String.Encoding.ascii) { if let fragmentSource = try? String(contentsOfFile: shader + ".fsh", encoding: String.Encoding.ascii) { return self.compile(vertexSource, fragmentSource) } } return false } /// @return true on success open func load(_ vertexFile: String, _ fragmentFile: String) -> Bool { if let vertexSource = try? String(contentsOfFile: vertexFile, encoding: String.Encoding.ascii) { if let fragmentSource = try? String(contentsOfFile: fragmentFile, encoding: String.Encoding.ascii) { return self.compile(vertexSource, fragmentSource) } } return false } /// @return true on success open func load(_ vertexFile: String, _ fragmentFile: String, _ bindAttibutes: (GLprogram) -> ()) -> Bool { if let vertexSource = try? String(contentsOfFile: vertexFile, encoding: String.Encoding.ascii) { if let fragmentSource = try? String(contentsOfFile: fragmentFile, encoding: String.Encoding.ascii) { return self.compile(vertexSource, fragmentSource, bindAttibutes) } } return false } open func bind() { glUseProgram(id) } open func attribute(_ name: String) -> GLint { return glGetAttribLocation(id, UnsafePointer<CChar>(name.cString(using: String.Encoding.ascii)!)) } open func uniform(_ name: String) -> GLuniform { return glGetUniformLocation(id, UnsafePointer<CChar>(name.cString(using: String.Encoding.ascii)!)) } // Bind Uniforms using Uniform Location open func bind(_ uniform: GLuniform, _ x: Float) { glProgramUniform1f(id, uniform, x) } open func bind(_ uniform: GLuniform, _ x: Float, _ y: Float) { glProgramUniform2f(id, uniform, x, y) } open func bind(_ uniform: GLuniform, _ x: Float, _ y: Float, _ z: Float) { glProgramUniform3f(id, uniform, x, y, z) } open func bind(_ uniform: GLuniform, _ x: Float, _ y: Float, _ z: Float, _ w: Float) { glProgramUniform4f(id, uniform, x, y, z, w) } open func bind(_ uniform: GLuniform, _ v: inout Vec2) { glProgramUniform2fv(id, uniform, 1, v.ptr) } open func bind(_ uniform: GLuniform, _ v: inout Vec3) { glProgramUniform3fv(id, uniform, 1, v.ptr) } open func bind(_ uniform: GLuniform, _ v: inout Vec4) { glProgramUniform4fv(id, uniform, 1, v.ptr) } open func bind(_ uniform: GLuniform, _ m: inout Mat4, transpose: GLboolean = GL_FALSE) { glProgramUniformMatrix4fv(id, uniform, 1, transpose, m.ptr) } open func bind(_ uniform: GLuniform, _ texture: Texture, index: GLint = 0) { glProgramUniform1i(id, uniform, index) glActiveTexture(GL_TEXTURE0 + GLenum(index)) glBindTexture(GL_TEXTURE_2D, texture.id) } // Bind Uniforms using String open func bind(_ uniform: String, _ x: Float) { glProgramUniform1f(id, self.uniform(uniform), x) } open func bind(_ uniform: String, _ x: Float, _ y: Float) { glProgramUniform2f(id, self.uniform(uniform), x, y) } open func bind(_ uniform: String, _ x: Float, _ y: Float, _ z: Float) { glProgramUniform3f(id, self.uniform(uniform), x, y, z) } open func bind(_ uniform: String, _ x: Float, _ y: Float, _ z: Float, _ w: Float) { glProgramUniform4f(id, self.uniform(uniform), x, y, z, w) } open func bind(_ uniform: String, _ v: inout Vec2) { glProgramUniform2fv(id, self.uniform(uniform), 1, v.ptr) } open func bind(_ uniform: String, _ v: inout Vec3) { glProgramUniform3fv(id, self.uniform(uniform), 1, v.ptr) } open func bind(_ uniform: String, _ v: inout Vec4) { glProgramUniform4fv(id, self.uniform(uniform), 1, v.ptr) } open func bind(_ uniform: String, _ m: inout Mat4, transpose: GLboolean = GL_FALSE) { glProgramUniformMatrix4fv(id, self.uniform(uniform), 1, transpose, m.ptr) } open func bind(_ uniform: String, _ texture: Texture, index: GLint = 0) { glProgramUniform1i(id, self.uniform(uniform), index) glActiveTexture(GL_TEXTURE0 + GLenum(index)) glBindTexture(GL_TEXTURE_2D, texture.id) } fileprivate class func ptr <T> (_ ptr: UnsafePointer<T>) -> UnsafePointer<T> { return ptr } fileprivate class func compile(_ type: GLenum, _ source: String) -> GLprogram { if let csource: [GLchar] = source.cString(using: String.Encoding.ascii) { let cptr = ptr(csource) let shader = glCreateShader(type) glShaderSource(shader, 1, [cptr], nil) glCompileShader(shader) var logLength: GLint = 0 glGetShaderiv(shader, GLenum(GL_INFO_LOG_LENGTH), &logLength) if logLength > 0 { let log = malloc(Int(logLength)).assumingMemoryBound(to: CChar.self) glGetShaderInfoLog(shader, logLength, &logLength, log) print("Shader compile log: \(String(describing: log))") free(log) } var status: GLint = 0 glGetShaderiv(shader, GLenum(GL_COMPILE_STATUS), &status) if status == GLint(GL_FALSE) { print("Failed to compile shader: \(csource)") return 0 } return shader } return 0 } fileprivate class func verify(_ program: GLprogram) -> Bool { // #if DEBUG // Assert that the program was successfully linked var logLength: GLint = 0 glGetProgramiv(program, GLenum(GL_INFO_LOG_LENGTH), &logLength) if logLength > 0 { let log = malloc(Int(logLength)).assumingMemoryBound(to: CChar.self) glGetProgramInfoLog(program, logLength, &logLength, log) print("Program link log:\n\(String(describing: log))") free(log) } // #endif var status: GLint = 0 glGetProgramiv(program, GLenum(GL_LINK_STATUS), &status) if status == 0 { print("Failed to link shader program") return false } return true } }
27f1fb9ba770f334ed6920d26ce066f1
45.765873
185
0.656258
false
false
false
false
steelwheels/Canary
refs/heads/master
Source/CNEdge.swift
gpl-2.0
1
/** * @file CNEdge.swift * @brief Define CNEdge class * @par Copyright * Copyright (C) 2017 Steel Wheels Project */ import Foundation public typealias CNWeakEdgeReference = CNWeakReference<CNEdge> /* * Note: The owner of the edge is a CNGraph */ public class CNEdge: Equatable { private var mUniqueId: Int public var uniqueId: Int { get { return mUniqueId }} public weak var fromNode: CNNode? public weak var toNode: CNNode? public var didVisited: Bool public init(uniqueId uid: Int){ mUniqueId = uid fromNode = nil toNode = nil didVisited = false } } public func == (left : CNEdge, right : CNEdge) -> Bool { return left.uniqueId == right.uniqueId }
c6a7cc9250e3cb1a8255f24217587e1a
18.571429
62
0.70219
false
false
false
false
hsuanan/Mr-Ride-iOS
refs/heads/master
Mr-Ride/Model/StationDataManagement.swift
mit
1
// // StationDataManagement.swift // Mr-Ride // // Created by Hsin An Hsu on 7/11/16. // Copyright © 2016 AppWorks School HsinAn Hsu. All rights reserved. // import Foundation import Alamofire import CoreData import CoreLocation protocol JSONDataDelegation: class { func didReceiveDataFromServer() } struct StationModel{ var station: String = "" var district: String = "" var location: String = "" var availableBikesNumber: Int = 0 var availableDocks: Int = 0 var latitude: Double = 0.0 var longitude: Double = 0.0 } class StationDataManager { static let sharedDataManager = StationDataManager() var stationArray = [StationModel]() weak var delegate: JSONDataDelegation? func getBikeDataFromServer(){ dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED,0)){ Alamofire.request( .GET, "http://data.taipei/youbike") .validate() .responseJSON { response in guard let json = response.result.value as? [String: AnyObject] else{ print (response.response) return } self.stationArray.removeAll() self.readJSONObject(json) dispatch_async(dispatch_get_main_queue()) { [weak self] in self?.delegate?.didReceiveDataFromServer() } print (response.response) } } } func readJSONObject(json: [String: AnyObject]){ guard let data = json["retVal"] as? [String:AnyObject] else { print("readJSONObject error") return } for value in data.values { guard let station = value["snaen"] as? String, let district = value["sareaen"] as? String, let location = value["aren"] as? String, let availableBikesNumber = value["sbi"] as? String, let availableDocks = value["bemp"] as? String, let latitude = value["lat"] as? String, let longitude = value["lng"] as? String else { print ("transJSONtype error") continue } stationArray.append( StationModel( station: station, district: district, location: location, availableBikesNumber: Int(availableBikesNumber)!, availableDocks: Int(availableDocks)!, latitude: Double(latitude)!, longitude: Double(longitude)!)) } } }
ef97547da981388888f1818fd17ea5cf
28.356436
82
0.496964
false
false
false
false
SequencingDOTcom/oAuth2-Code-Example-.NET
refs/heads/master
swift/Pods/sequencing-oauth-api-swift/Pod/SQToken.swift
mit
4
// // SQToken.swift // Copyright © 2015-2016 Sequencing.com. All rights reserved // import Foundation public class SQToken: NSObject { public var accessToken = String() public var expirationDate = NSDate() public var tokenType = String() public var scope = String() public var refreshToken = String() }
fa1f72ab2351021a0b7106e135bbb463
21.3125
61
0.635854
false
false
false
false
chernyog/CYWeibo
refs/heads/master
CYWeibo/CYWeibo/CYWeibo/Classes/UI/Home/StatusCell.swift
mit
1
// // StatusCell.swift // CYWeibo // // Created by 陈勇 on 15/3/6. // Copyright (c) 2015年 zhssit. All rights reserved. // import UIKit class StatusCell: UITableViewCell { // MARK: - 控件列表 /// 头像 @IBOutlet weak var iconImageView: UIImageView! /// 姓名 @IBOutlet weak var nameLabel: UILabel! /// 会员图标 @IBOutlet weak var memberImageView: UIImageView! /// 认证图标 @IBOutlet weak var vipImageView: UIImageView! /// 微博发表时间 @IBOutlet weak var timeLabel: UILabel! /// 微博来源 @IBOutlet weak var sourceLabel: UILabel! /// 微博正文 @IBOutlet weak var contentLabel: UILabel! /// 微博配图 @IBOutlet weak var pictureView: UICollectionView! /// 配图视图的布局 @IBOutlet weak var pictureLayout: UICollectionViewFlowLayout! /// 配图视图的宽 @IBOutlet weak var pictureViewWidth: NSLayoutConstraint! /// 配图视图的高 @IBOutlet weak var pictureViewHeight: NSLayoutConstraint! /// 底部的工具条 @IBOutlet weak var bottomView: UIView! /// 转发微博文字 @IBOutlet weak var forwardContentLabel: UILabel! // MARK: - 成员变量 /// 微博模型 - 设置微博数据 var status: Status? { didSet{ self.nameLabel.text = status!.user!.name self.timeLabel.text = status!.created_at self.sourceLabel.text = status!.source?.getHrefText() // self.contentLabel.text = status!.text self.contentLabel.attributedText = status!.text?.emotionString() ?? NSAttributedString(string: status!.text ?? "") if let iconUrl = status?.user?.profile_image_url { NetworkManager.sharedManager.requestImage(iconUrl) { (result, error) -> () in if let image = result as? UIImage { self.iconImageView.image = image } } } // 计算微博配图的尺寸 let result = self.calcPictureViewSize(status!) self.pictureLayout.itemSize = result.itemSize self.pictureViewWidth.constant = result.viewSize.width self.pictureViewHeight.constant = result.viewSize.height // 强制刷新界面 self.pictureView.reloadData() // 设置转发微博文字 if status?.retweeted_status != nil { forwardContentLabel.text = status!.retweeted_status!.user!.name! + ":" + status!.retweeted_status!.text! } } } override func awakeFromNib() { super.awakeFromNib() self.contentLabel.preferredMaxLayoutWidth = UIScreen.mainScreen().bounds.width - 30 self.forwardContentLabel?.preferredMaxLayoutWidth = UIScreen.mainScreen().bounds.width - 30 } /// 计算微博配图的尺寸 /// /// :param: status 微博实体 /// /// :returns: (itemSize,viewSize) func calcPictureViewSize(status: Status) -> (itemSize: CGSize, viewSize: CGSize) { let defaultWH: CGFloat = 90 // 默认的图片大小 var itemSize = CGSize(width: defaultWH, height: defaultWH) // 默认PictureView大小 var viewSize = CGSizeZero // 计算微博配图的个数 var count = status.pictureUrls?.count ?? 0 // 图片间的间距 let margin: CGFloat = 10 if count == 0 { return (itemSize, viewSize) } if count == 1 { // 如果只有一张图,则按照默认的尺寸显示 let path = NetworkManager.sharedManager.fullImageCachePathByMD5(status.pictureUrls![0].thumbnail_pic!) if let image = UIImage(contentsOfFile: path) { return (image.size, image.size) } else { return (itemSize, viewSize) } } if count == 4 { viewSize = CGSize(width: defaultWH * 2, height: defaultWH * 2) return (itemSize, viewSize) } else { // 行下标 let row = (count - 1) / 3 viewSize = CGSize(width: defaultWH * 3 + margin * 2, height: defaultWH * (CGFloat(row) + 1) + margin * CGFloat(row)) } return (itemSize, viewSize) } /// 返回可重用标识符 class func cellIdentifier(status: Status) -> String { if status.retweeted_status != nil { // 转发微博 return "ForwardCell" } else { // 原创微博 return "HomeCell" } } func cellHeight(status: Status) -> CGFloat { // 设置微博数据 self.status = status // 强制刷新布局 layoutIfNeeded() // 返回cell的高度 return CGRectGetMaxY(self.bottomView.frame) } /// 选中图片的闭包回调 var photoDidSelected: ((status: Status, photoIndex: Int) -> ())? } extension StatusCell: UICollectionViewDataSource, UICollectionViewDelegate { func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { // 配图的数量 // println("配图的数量 count=\(status?.pictureUrls?.count)") return status?.pictureUrls?.count ?? 0 } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("PictureCell", forIndexPath: indexPath) as! PictureCell // 设置配图的图像路径 cell.urlString = status!.pictureUrls![indexPath.item].thumbnail_pic return cell } // 选中行事件 func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { if self.photoDidSelected != nil { self.photoDidSelected!(status: status!, photoIndex: indexPath.item) } } } /// 配图cell class PictureCell: UICollectionViewCell { @IBOutlet weak var imageView: UIImageView! /// 图像的 url 字符串 var urlString: String? { didSet { // 1. 图像缓存路径 let path = NetworkManager.sharedManager.fullImageCachePathByMD5(urlString!) // println("path=\(path)") // 2. 实例化图像 let image = UIImage(contentsOfFile: path) imageView.image = image } } }
2a84144f5b4f7bc33e9376d88d99ee62
28.519417
130
0.586581
false
false
false
false
RevenueCat/purchases-ios
refs/heads/main
Tests/UnitTests/Mocks/MockSystemInfo.swift
mit
1
// // MockSystemInfo.swift // PurchasesTests // // Created by Andrés Boedo on 7/20/20. // Copyright © 2020 Purchases. All rights reserved. // import Foundation @testable import RevenueCat // Note: this class is implicitly `@unchecked Sendable` through its parent // even though it's not actually thread safe. class MockSystemInfo: SystemInfo { var stubbedIsApplicationBackgrounded: Bool? var stubbedIsSandbox: Bool? convenience init(finishTransactions: Bool, storeKit2Setting: StoreKit2Setting = .default) { // swiftlint:disable:next force_try try! self.init(platformInfo: nil, finishTransactions: finishTransactions, storeKit2Setting: storeKit2Setting) } override func isApplicationBackgrounded(completion: @escaping (Bool) -> Void) { completion(stubbedIsApplicationBackgrounded ?? false) } var stubbedIsOperatingSystemAtLeastVersion: Bool? var stubbedCurrentOperatingSystemVersion: OperatingSystemVersion? override public func isOperatingSystemAtLeast(_ version: OperatingSystemVersion) -> Bool { if let stubbedIsOperatingSystemAtLeastVersion = self.stubbedIsOperatingSystemAtLeastVersion { return stubbedIsOperatingSystemAtLeastVersion } if let currentVersion = self.stubbedCurrentOperatingSystemVersion { return currentVersion >= version } return true } override var isSandbox: Bool { return self.stubbedIsSandbox ?? super.isSandbox } } extension OperatingSystemVersion: Comparable { public static func < (lhs: OperatingSystemVersion, rhs: OperatingSystemVersion) -> Bool { if lhs.majorVersion == rhs.majorVersion { if lhs.minorVersion == rhs.minorVersion { return lhs.patchVersion < rhs.patchVersion } else { return lhs.minorVersion < rhs.minorVersion } } else { return lhs.majorVersion < rhs.majorVersion } } public static func == (lhs: OperatingSystemVersion, rhs: OperatingSystemVersion) -> Bool { return ( lhs.majorVersion == rhs.majorVersion && lhs.minorVersion == rhs.minorVersion && lhs.patchVersion == rhs.patchVersion ) } }
da5c29d47ccc9901f1ca1f5a48f6036e
31.472222
101
0.665954
false
false
false
false
pkrawat1/TravelApp-ios
refs/heads/master
TravelApp/View/SearchTripCell.swift
mit
1
// // SearchTripCell.swift // TravelApp // // Created by Nitesh on 03/02/17. // Copyright © 2017 Pankaj Rawat. All rights reserved. // import UIKit class SearchTripCell: BaseCell { var trip: Trip? { didSet { print(trip!) userNameLabel.text = trip?.user?.name durationLabel.text = trip?.created_at?.relativeDate() tripNameLabel.text = trip?.name setupThumbnailImage() setupProfileImage() } } func setupThumbnailImage() { if let thumbnailImageUrl = trip?.thumbnail_image_url { thumbnailImageView.loadImageUsingUrlString(urlString: thumbnailImageUrl, width: Float(thumbnailImageView.frame.width)) } let tapGestureRecognizer = UITapGestureRecognizer(target:self, action:#selector(showTripDetail)) thumbnailImageView.isUserInteractionEnabled = true thumbnailImageView.addGestureRecognizer(tapGestureRecognizer) } func showTripDetail() { let tripDetailViewCtrl = TripDetailViewController() store.dispatch(SelectTrip(tripId: (trip?.id!)!)) SharedData.sharedInstance.homeController?.present(tripDetailViewCtrl, animated: true, completion: nil) } func setupProfileImage() { if let profileImageURL = trip?.user?.profile_pic?.url { userProfileImageView.loadImageUsingUrlString(urlString: profileImageURL, width: Float(userProfileImageView.frame.width)) } } let thumbnailImageView: CustomImageView = { let imageView = CustomImageView() imageView.contentMode = .scaleAspectFill imageView.translatesAutoresizingMaskIntoConstraints = false imageView.clipsToBounds = true imageView.image = UIImage(named: "") imageView.backgroundColor = UIColor.black imageView.alpha = 0.5 return imageView }() let userProfileImageView: CustomImageView = { let imageView = CustomImageView() imageView.image = UIImage(named: "") imageView.translatesAutoresizingMaskIntoConstraints = false imageView.contentMode = .scaleAspectFill imageView.clipsToBounds = true imageView.layer.cornerRadius = 22 imageView.layer.masksToBounds = true // imageView.backgroundColor = UIColor.blue return imageView }() let likeButton: UIButton = { let ub = UIButton(type: .system) ub.setImage(UIImage(named: "like"), for: .normal) ub.tintColor = UIColor.gray ub.translatesAutoresizingMaskIntoConstraints = false // ub.backgroundColor = UIColor.red return ub }() let userNameLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.text = "" label.numberOfLines = 1 label.font = label.font.withSize(14) label.textColor = UIColor.white // label.backgroundColor = UIColor.green return label }() let durationLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.text = "" label.numberOfLines = 1 label.textColor = UIColor.white // label.backgroundColor = UIColor.yellow label.font = label.font.withSize(10) return label }() let tripNameLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.text = "" label.font = label.font.withSize(25) label.numberOfLines = 2 label.textColor = UIColor.white label.textAlignment = .center // label.backgroundColor = UIColor.green return label }() override func setupViews() { addSubview(thumbnailImageView) addSubview(userProfileImageView) addSubview(userNameLabel) addSubview(durationLabel) addSubview(likeButton) addSubview(tripNameLabel) thumbnailImageView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true thumbnailImageView.widthAnchor.constraint(equalTo: self.widthAnchor).isActive = true thumbnailImageView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true userProfileImageView.bottomAnchor.constraint(equalTo: thumbnailImageView.bottomAnchor, constant: -10).isActive = true userProfileImageView.widthAnchor.constraint(equalToConstant: 44).isActive = true userProfileImageView.leftAnchor.constraint(equalTo: thumbnailImageView.leftAnchor, constant: 10).isActive = true userProfileImageView.heightAnchor.constraint(equalToConstant: 44).isActive = true userNameLabel.topAnchor.constraint(equalTo: userProfileImageView.topAnchor).isActive = true userNameLabel.leftAnchor.constraint(equalTo: userProfileImageView.rightAnchor, constant: 10).isActive = true userNameLabel.rightAnchor.constraint(equalTo: likeButton.leftAnchor, constant: -10).isActive = true userNameLabel.heightAnchor.constraint(equalToConstant: 20).isActive = true durationLabel.topAnchor.constraint(equalTo: userNameLabel.bottomAnchor, constant: 4).isActive = true durationLabel.leftAnchor.constraint(equalTo: userProfileImageView.rightAnchor, constant: 10).isActive = true durationLabel.rightAnchor.constraint(equalTo: likeButton.leftAnchor, constant: -10).isActive = true durationLabel.heightAnchor.constraint(equalToConstant: 20).isActive = true likeButton.bottomAnchor.constraint(equalTo: thumbnailImageView.bottomAnchor, constant: -10).isActive = true likeButton.widthAnchor.constraint(equalToConstant: 44).isActive = true likeButton.rightAnchor.constraint(equalTo: thumbnailImageView.rightAnchor, constant: -10).isActive = true likeButton.heightAnchor.constraint(equalToConstant: 44).isActive = true tripNameLabel.widthAnchor.constraint(equalTo: thumbnailImageView.widthAnchor, constant: -20).isActive = true tripNameLabel.centerYAnchor.constraint(equalTo: thumbnailImageView.centerYAnchor).isActive = true tripNameLabel.centerXAnchor.constraint(equalTo: thumbnailImageView.centerXAnchor).isActive = true tripNameLabel.heightAnchor.constraint(equalToConstant: 40).isActive = true } }
274b78d90a0bef12e0ed7a32655a9c48
40.056962
132
0.683675
false
false
false
false
russbishop/swift
refs/heads/master
stdlib/public/SDK/UIKit/UIKit_FoundationExtensions.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import Foundation @_exported import UIKit // UITableView extensions public extension IndexPath { /// Initialize for use with `UITableView` or `UICollectionView`. public init(row: Int, section: Int) { self.init(indexes: [section, row]) } /// The section of this index path, when used with `UITableView`. /// /// - precondition: The index path must have exactly two elements. public var section: Int { get { precondition(count == 2, "Invalid index path for use with UITableView. This index path must contain exactly two indices specifying the section and row.") return self[0] } set { precondition(count == 2, "Invalid index path for use with UITableView. This index path must contain exactly two indices specifying the section and row.") self[0] = newValue } } /// The row of this index path, when used with `UITableView`. /// /// - precondition: The index path must have exactly two elements. public var row: Int { get { precondition(count == 2, "Invalid index path for use with UITableView. This index path must contain exactly two indices specifying the section and row.") return self[1] } set { precondition(count == 2, "Invalid index path for use with UITableView. This index path must contain exactly two indices specifying the section and row.") self[1] = newValue } } } // UICollectionView extensions public extension IndexPath { /// Initialize for use with `UITableView` or `UICollectionView`. public init(item: Int, section: Int) { self.init(indexes: [section, item]) } /// The item of this index path, when used with `UICollectionView`. /// /// - precondition: The index path must have exactly two elements. public var item: Int { get { precondition(count == 2, "Invalid index path for use with UICollectionView. This index path must contain exactly two indices specifying the section and item.") return self[1] } set { precondition(count == 2, "Invalid index path for use with UICollectionView. This index path must contain exactly two indices specifying the section and item.") self[1] = newValue } }} public extension URLResourceValues { /// Returns a dictionary of UIImage objects keyed by size. @available(iOS 8.0, *) public var thumbnailDictionary : [URLThumbnailSizeKey : UIImage]? { return allValues[URLResourceKey.thumbnailDictionaryKey] as? [URLThumbnailSizeKey : UIImage] } }
13ce6d46e6a1ad784d191cad2c37beea
37.662651
171
0.622001
false
false
false
false
CodaFi/swift
refs/heads/main
validation-test/compiler_crashers_fixed/00093-swift-boundgenerictype-get.swift
apache-2.0
65
// 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 // RUN: not %target-swift-frontend %s -typecheck struct j<l : o> { k b: l } func a<l>() -> [j<l>] { return [] } f k) func f<l>() -> (l, l -> l) -> l { l j l.n = { } { l) { n } } protocol f { class func n() } class l: f{ class func n {} func a<i>() { b b { l j } } class a<f : b, l : b m f.l == l> { } protocol b { typealias l typealias k } struct j<n : b> : b { typealias l = n typealias k = a<j<n>, l> }
cce80d79b8d1930a8a55e98dc3fa42d0
18.380952
79
0.576167
false
false
false
false
dibaicongyouwangzi/QQMusic
refs/heads/master
QQMusic/QQMusic/Classes/QQDetail/Controller/QQLrcTVC.swift
mit
1
// // QQLrcTVC.swift // QQMusic // // Created by 迪拜葱油王子 on 2016/11/14. // Copyright © 2016年 迪拜葱油王子. All rights reserved. // import UIKit class QQLrcTVC: UITableViewController { // 提供给外界赋值的进度 var progress : CGFloat = 0{ didSet{ // 拿到当前正在播放的cell let indexPath = NSIndexPath(row: scrollRow, section: 0) let cell = tableView.cellForRow(at: indexPath as IndexPath) as? QQLrcCell // 给cell里面的label的进度赋值 cell?.progress = progress } } // 提供给外界的数值,代表需要滚动的行数 var scrollRow = -1{ didSet{ // 过滤值,降低滚动频率 // 如果两个值相等,代表滚动的是同一行,没有必要滚动很多次 if scrollRow == oldValue{ return } let indexPaths = tableView.indexPathsForVisibleRows tableView.reloadRows(at: indexPaths!, with: .fade) let indexPath = NSIndexPath(row: scrollRow, section: 0) tableView.scrollToRow(at: indexPath as IndexPath, at: UITableViewScrollPosition.middle, animated: true) } } var lrcMs : [QQLrcModel] = [QQLrcModel]() { didSet{ tableView.reloadData() } } override func viewDidLoad() { tableView.separatorStyle = .none tableView.allowsSelection = false } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() tableView.contentInset = UIEdgeInsetsMake(tableView.frame.size.height * 0.5, 0, tableView.frame.size.height * 0.5, 0) } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return lrcMs.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = QQLrcCell.cellWithTableView(tableView: tableView) // 取出歌词模型 let model = lrcMs[indexPath.row] if indexPath.row == scrollRow{ cell.progress = progress }else{ cell.progress = 0 } cell.lrcContent = model.lrcContent return cell } }
eaf67de57318b74fb4134f165155221e
24.632184
125
0.568161
false
false
false
false
frankcjw/CJWLib
refs/heads/master
UI/CJWBaseViewController.swift
mit
1
// // YGBaseViewController.swift // YuanGuangProject // // Created by Frank on 6/26/15. // Copyright (c) 2015 YG. All rights reserved. // import UIKit class CJWBaseViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() self.setBackTitle("") } } extension UIViewController { func pushViewController(viewController: UIViewController){ if self.navigationController != nil { viewController.hidesBottomBarWhenPushed = true self.navigationController?.pushViewController(viewController, animated: true) } } func popViewController(){ if self.navigationController != nil { self.navigationController?.popViewControllerAnimated(true) } } func setBackTitle(title:String){ let back = UIBarButtonItem() back.title = title self.navigationItem.backBarButtonItem = back } func setBackAction(action:Selector){ let back = UIBarButtonItem() // back.title = title back.action = action self.navigationItem.backBarButtonItem = back } }
b4c7e34636661a8256876a2d69b32d67
22.24
89
0.641997
false
false
false
false
collinhundley/MySQL
refs/heads/master
Sources/MySQL/PreparedStatement.swift
mit
1
// // PreparedStatement.swift // MySQL // // Created by Collin Hundley on 6/24/17. // import Foundation #if os(Linux) import CMySQLLinux #else import CMySQLMac #endif /// MySQL implementation for prepared statements. public class PreparedStatement { enum Error: Swift.Error, LocalizedError { case initialize(String) case execute(String) var errorDescription: String? { switch self { case .execute(let msg): return msg case .initialize(let msg): return msg } } } /// Reference to native MySQL statement. private(set) var statement: UnsafeMutablePointer<MYSQL_STMT>? private var binds = [MYSQL_BIND]() private var bindsCapacity = 0 private var bindPtr: UnsafeMutablePointer<MYSQL_BIND>? = nil /// Static date formatter for converting MySQL fetch results to Swift types. private static let dateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd HH:mm:ss" return formatter }() /// Initializes a prepared statement. /// /// - Parameters: /// - stmt: The statement to execute. /// - mysql: A reference to a MySQL connection. /// - Throws: `PreparedStatement.Error` if an error is encountered. init(_ stmt: String, mysql: UnsafeMutablePointer<MYSQL>?) throws { // Make sure database connection has already been established guard let mysql = mysql else { throw Error.initialize("MySQL not connected. Call connect() before execute().") } // Initialize MySQL statement guard let statement = mysql_stmt_init(mysql) else { throw Error.initialize(Connection.getError(from: mysql)) } // Prepare statement guard mysql_stmt_prepare(statement, stmt, UInt(stmt.utf8.count)) == 0 else { defer { mysql_stmt_close(statement) } throw Error.initialize(Connection.getError(from: statement)) } self.statement = statement } /// Ensure that statement and binds become deallocated. deinit { release() } /// Execute the statement, optionally with parameters. /// /// - Parameter parameters: An array of parameters to use for execution, if any. /// - Returns: The result of the execution. /// - Throws: `PreparedStatement.Error` if an error occurs. func execute(parameters: [Any?]? = nil) throws -> MySQL.Result { guard let statement = self.statement else { throw Error.execute("The prepared statement has already been released.") } if let parameters = parameters { if let bindPtr = bindPtr { guard bindsCapacity == parameters.count else { throw Error.execute("Each call to execute() must pass the same number of parameters.") } } else { // true only for the first time execute() is called for this PreparedStatement bindsCapacity = parameters.count bindPtr = UnsafeMutablePointer<MYSQL_BIND>.allocate(capacity: bindsCapacity) } do { try allocateBinds(parameters: parameters) } catch { // Catch error so we can close the statement before throwing self.statement = nil mysql_stmt_close(statement) throw error } } guard let resultMetadata = mysql_stmt_result_metadata(statement) else { // Non-query statement (insert, update, delete) guard mysql_stmt_execute(statement) == 0 else { guard let statement = self.statement else { throw Error.execute("Statement is nil after execution.") } let error = Connection.getError(from: statement) self.statement = nil mysql_stmt_close(statement) throw Error.execute(error) } // TODO: Potentially return number of affected rows here // let affectedRows = mysql_stmt_affected_rows(statement) as UInt64 return [[:]] } defer { mysql_free_result(resultMetadata) } let resultFetcher = try ResultFetcher(preparedStatement: self, resultMetadata: resultMetadata) return resultFetcher.rows() } /// Deallocate statement and binds. func release() { deallocateBinds() if let statement = self.statement { self.statement = nil mysql_stmt_close(statement) } } private func allocateBinds(parameters: [Any?]) throws { if binds.isEmpty { // first parameter set, create new bind and bind it to the parameter for (index, parameter) in parameters.enumerated() { var bind = MYSQL_BIND() setBind(&bind, parameter) binds.append(bind) bindPtr![index] = bind } } else { // bind was previously created, re-initialize value for (index, parameter) in parameters.enumerated() { var bind = binds[index] setBind(&bind, parameter) binds[index] = bind bindPtr![index] = bind } } guard mysql_stmt_bind_param(statement, bindPtr) == 0 else { throw Error.execute(Connection.getError(from: statement!)) // THis is guaranteed to be safe } } private func deallocateBinds() { guard let bindPtr = self.bindPtr else { return } self.bindPtr = nil for bind in binds { if bind.buffer != nil { bind.buffer.deallocate(bytes: Int(bind.buffer_length), alignedTo: 1) } if bind.length != nil { bind.length.deallocate(capacity: 1) } if bind.is_null != nil { bind.is_null.deallocate(capacity: 1) } } bindPtr.deallocate(capacity: bindsCapacity) binds.removeAll() } private func setBind(_ bind: inout MYSQL_BIND, _ parameter: Any?) { if bind.is_null == nil { bind.is_null = UnsafeMutablePointer<Int8>.allocate(capacity: 1) } guard let parameter = parameter else { bind.buffer_type = MYSQL_TYPE_NULL bind.is_null.initialize(to: 1) return } bind.buffer_type = getType(parameter: parameter) bind.is_null.initialize(to: 0) bind.is_unsigned = 0 switch parameter { case let string as String: initialize(string: string, &bind) case let date as Date: // Note: Here we assume this is DateTime type - does not handle Date or Time types let formattedDate = PreparedStatement.dateFormatter.string(from: date) initialize(string: formattedDate, &bind) case let byteArray as [UInt8]: let typedBuffer = allocate(type: UInt8.self, capacity: byteArray.count, bind: &bind) #if swift(>=3.1) let _ = UnsafeMutableBufferPointer(start: typedBuffer, count: byteArray.count).initialize(from: byteArray) #else typedBuffer.initialize(from: byteArray) #endif case let data as Data: let typedBuffer = allocate(type: UInt8.self, capacity: data.count, bind: &bind) data.copyBytes(to: typedBuffer, count: data.count) case let dateTime as MYSQL_TIME: initialize(dateTime, &bind) case let float as Float: initialize(float, &bind) case let double as Double: initialize(double, &bind) case let bool as Bool: initialize(bool, &bind) case let int as Int: initialize(int, &bind) case let int as Int8: initialize(int, &bind) case let int as Int16: initialize(int, &bind) case let int as Int32: initialize(int, &bind) case let int as Int64: initialize(int, &bind) case let uint as UInt: initialize(uint, &bind) bind.is_unsigned = 1 case let uint as UInt8: initialize(uint, &bind) bind.is_unsigned = 1 case let uint as UInt16: initialize(uint, &bind) bind.is_unsigned = 1 case let uint as UInt32: initialize(uint, &bind) bind.is_unsigned = 1 case let uint as UInt64: initialize(uint, &bind) bind.is_unsigned = 1 case let unicodeScalar as UnicodeScalar: initialize(unicodeScalar, &bind) bind.is_unsigned = 1 default: print("WARNING: Unhandled parameter \(parameter) (type: \(type(of: parameter))). Will attempt to convert it to a String") initialize(string: String(describing: parameter), &bind) } } private func allocate<T>(type: T.Type, capacity: Int, bind: inout MYSQL_BIND) -> UnsafeMutablePointer<T> { let length = UInt(capacity * MemoryLayout<T>.size) if bind.length == nil { bind.length = UnsafeMutablePointer<UInt>.allocate(capacity: 1) } bind.length.initialize(to: length) let typedBuffer: UnsafeMutablePointer<T> if let buffer = bind.buffer, bind.buffer_length >= length { typedBuffer = buffer.assumingMemoryBound(to: type) } else { if bind.buffer != nil { // deallocate existing smaller buffer bind.buffer.deallocate(bytes: Int(bind.buffer_length), alignedTo: 1) } typedBuffer = UnsafeMutablePointer<T>.allocate(capacity: capacity) bind.buffer = UnsafeMutableRawPointer(typedBuffer) bind.buffer_length = length } return typedBuffer } private func initialize<T>(_ parameter: T, _ bind: inout MYSQL_BIND) { let typedBuffer = allocate(type: type(of: parameter), capacity: 1, bind: &bind) typedBuffer.initialize(to: parameter) } private func initialize(string: String, _ bind: inout MYSQL_BIND) { let utf8 = string.utf8 let typedBuffer = allocate(type: UInt8.self, capacity: utf8.count, bind: &bind) #if swift(>=3.1) let _ = UnsafeMutableBufferPointer(start: typedBuffer, count: utf8.count).initialize(from: utf8) #else typedBuffer.initialize(from: utf8) #endif } private func getType(parameter: Any) -> enum_field_types { switch parameter { case is String, is Date: return MYSQL_TYPE_STRING case is Data, is [UInt8]: return MYSQL_TYPE_BLOB case is Int8, is UInt8, is Bool: return MYSQL_TYPE_TINY case is Int16, is UInt16: return MYSQL_TYPE_SHORT case is Int32, is UInt32, is UnicodeScalar: return MYSQL_TYPE_LONG case is Int, is UInt, is Int64, is UInt64: return MYSQL_TYPE_LONGLONG case is Float: return MYSQL_TYPE_FLOAT case is Double: return MYSQL_TYPE_DOUBLE case is MYSQL_TIME: return MYSQL_TYPE_DATETIME default: return MYSQL_TYPE_STRING } } }
2333ee2037e1e4166b4c9e92be497d09
33.420749
133
0.55777
false
false
false
false
crazypoo/PTools
refs/heads/master
PooToolsSource/Base/PTFloatingPanelFuction.swift
mit
1
// // PTFloatingPanelFuction.swift // PooTools_Example // // Created by jax on 2022/10/11. // Copyright © 2022 crazypoo. All rights reserved. // import UIKit import FloatingPanel public typealias FloatingBlock = () -> Void public class PTFloatingPanelFuction: NSObject { class open func floatPanel_VC(vc:PTBaseViewController,panGesDelegate:(UIViewController & UIGestureRecognizerDelegate)? = PTUtils.getCurrentVC() as! PTBaseViewController,floatingDismiss:FloatingBlock? = nil) { let fpc = FloatingPanelController() fpc.set(contentViewController: vc) fpc.contentMode = .fitToBounds fpc.contentInsetAdjustmentBehavior = .never fpc.isRemovalInteractionEnabled = true fpc.panGestureRecognizer.isEnabled = true fpc.panGestureRecognizer.delegateProxy = panGesDelegate fpc.surfaceView.backgroundColor = .randomColor let backDropDismiss = UITapGestureRecognizer.init { action in vc.dismiss(animated: true) if floatingDismiss != nil { floatingDismiss!() } } fpc.backdropView.addGestureRecognizer(backDropDismiss) // Create a new appearance. let appearance = SurfaceAppearance() // Define shadows let shadow = SurfaceAppearance.Shadow() shadow.color = UIColor.black shadow.offset = CGSize(width: 0, height: 16) shadow.radius = 16 shadow.spread = 8 appearance.shadows = [shadow] // Define corner radius and background color appearance.cornerRadius = 8.0 appearance.backgroundColor = .white // Set the new appearance fpc.surfaceView.appearance = appearance fpc.delegate = vc (PTUtils.getCurrentVC() as? PTBaseViewController)?.present(fpc, animated: true) { if floatingDismiss != nil { floatingDismiss!() } } } }
7d4d8343a733da6df699dedfe76a852f
31.622951
210
0.640201
false
false
false
false
bsmith11/ScoreReporter
refs/heads/master
ScoreReporterCore/ScoreReporterCore/Models/Standing.swift
mit
1
// // Standing.swift // ScoreReporter // // Created by Bradley Smith on 7/18/16. // Copyright © 2016 Brad Smith. All rights reserved. // import Foundation import CoreData public class Standing: NSManagedObject { } // MARK: - Public public extension Standing { static func fetchedStandingsFor(pool: Pool) -> NSFetchedResultsController<Standing> { let predicate = NSPredicate(format: "%K == %@", #keyPath(Standing.pool), pool) let sortDescriptors = [ NSSortDescriptor(key: #keyPath(Standing.sortOrder), ascending: true) ] return fetchedResultsController(predicate: predicate, sortDescriptors: sortDescriptors) } } // MARK: - Fetchable extension Standing: Fetchable { public static var primaryKey: String { return "" } } // MARK: - CoreDataImportable extension Standing: CoreDataImportable { public static func object(from dictionary: [String: Any], context: NSManagedObjectContext) -> Standing? { guard let standing = createObject(in: context) else { return nil } standing.wins = dictionary[APIConstants.Response.Keys.wins] as? NSNumber standing.losses = dictionary[APIConstants.Response.Keys.losses] as? NSNumber standing.sortOrder = dictionary[APIConstants.Response.Keys.sortOrder] as? NSNumber let teamName = dictionary <~ APIConstants.Response.Keys.teamName let seed = self.seed(from: teamName) standing.seed = seed as NSNumber let seedString = "(\(seed))" standing.teamName = teamName?.replacingOccurrences(of: seedString, with: "").trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) if !standing.hasPersistentChangedValues { context.refresh(standing, mergeChanges: false) } return standing } static func seed(from teamName: String?) -> Int { let pattern = "([0-9]+)" if let seed = teamName?.matching(regexPattern: pattern), !seed.isEmpty { return Int(seed) ?? 0 } else { return 0 } } }
0141d54ebf6b12bb4dfd9cad58085a04
27.337838
144
0.657129
false
false
false
false
roehrdor/diagnoseit-ios-mobile-agent
refs/heads/master
Constants.swift
mit
1
/* Copyright (c) 2017 Oliver Roehrdanz Copyright (c) 2017 Matteo Sassano Copyright (c) 2017 Christopher Voelker Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import Foundation import UIKit struct Constants { static let INVALID = "INVALID".data(using: .utf8) static var HOST : String = "" static let submitResultUrl : String = "/rest/mobile/newinvocation" static var spanServicetUrl : String = "" static let UNKNOWN : String = "unknown" static func getTimestamp() -> UInt64 { return UInt64(NSDate().timeIntervalSince1970 * 1000000.0) } static func decimalToHex(decimal: UInt64) -> String { return String(decimal, radix: 16) } static func alert(windowTitle : String, message : String, confirmButtonName : String) -> UIAlertController { let alert = UIAlertController(title: windowTitle, message: message, preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: confirmButtonName, style: UIAlertActionStyle.default, handler: nil)) return alert; } static func addLabel(text : String, x : CGFloat, y : CGFloat, width : CGFloat, height : CGFloat) -> UILabel { let label = UILabel(frame: CGRect(x: x, y: y, width: width, height: height)) label.text = text return label } }
40dca6c24f07c2084652ca19f9ba19a1
42.203704
121
0.727818
false
false
false
false
srxboys/RXSwiftExtention
refs/heads/master
Pods/SwifterSwift/Source/Extensions/IntExtensions.swift
mit
1
// // IntExtensions.swift // SwifterSwift // // Created by Omar Albeik on 8/6/16. // Copyright © 2016 Omar Albeik. All rights reserved. // #if os(macOS) import Cocoa #else import UIKit #endif // MARK: - Properties public extension Int { /// SwifterSwift: Absolute value of integer. public var abs: Int { return Swift.abs(self) } /// SwifterSwift: String with number and current locale currency. public var asLocaleCurrency: String { let formatter = NumberFormatter() formatter.numberStyle = .currency formatter.locale = Locale.current return formatter.string(from: self as NSNumber)! } /// SwifterSwift: Radian value of degree input. public var degreesToRadians: Double { return Double.pi * Double(self) / 180.0 } /// SwifterSwift: Array of digits of integer value. public var digits: [Int] { var digits: [Int] = [] for char in String(self).characters { if let int = Int(String(char)) { digits.append(int) } } return digits } /// SwifterSwift: Number of digits of integer value. public var digitsCount: Int { return String(self).characters.count } /// SwifterSwift: Check if integer is even. public var isEven: Bool { return (self % 2) == 0 } /// SwifterSwift: Check if integer is odd. public var isOdd: Bool { return (self % 2) != 0 } /// SwifterSwift: Check if integer is positive. public var isPositive: Bool { return self > 0 } /// SwifterSwift: Check if integer is negative. public var isNegative: Bool { return self < 0 } /// SwifterSwift: Double. public var double: Double { return Double(self) } /// SwifterSwift: Float. public var float: Float { return Float(self) } /// SwifterSwift: CGFloat. public var cgFloat: CGFloat { return CGFloat(self) } /// SwifterSwift: String. public var string: String { return String(self) } /// SwifterSwift: Degree value of radian input public var radiansToDegrees: Double { return Double(self) * 180 / Double.pi } /// SwifterSwift: Roman numeral string from integer (if applicable). public var romanNumeral: String? { // https://gist.github.com/kumo/a8e1cb1f4b7cff1548c7 guard self > 0 else { // there is no roman numerals for 0 or negative numbers return nil } let romanValues = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"] let arabicValues = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1] var romanValue = "" var startingValue = self for (index, romanChar) in romanValues.enumerated() { let arabicValue = arabicValues[index] let div = startingValue / arabicValue if (div > 0) { for _ in 0..<div { romanValue += romanChar } startingValue -= arabicValue * div } } return romanValue } /// SwifterSwift: String of format (XXh XXm) from seconds Int. public var timeString: String { guard self > 0 else { return "0 sec" } if self < 60 { return "\(self) sec" } if self < 3600 { return "\(self / 60) min" } let hours = self / 3600 let mins = (self % 3600) / 60 if hours != 0 && mins == 0 { return "\(hours)h" } return "\(hours)h \(mins)m" } /// SwifterSwift: String formatted for values over ±1000 (example: 1k, -2k, 100k, 1kk, -5kk..) public var kFormatted: String { var sign: String { return self >= 0 ? "" : "-" } let abs = self.abs if abs == 0 { return "0k" } else if abs >= 0 && abs < 1000 { return "0k" } else if abs >= 1000 && abs < 1000000 { return String(format: "\(sign)%ik", abs / 1000) } return String(format: "\(sign)%ikk", abs / 100000) } } // MARK: - Methods public extension Int { /// SwifterSwift: Greatest common divisor of integer value and n. /// /// - Parameter n: integer value to find gcd with. /// - Returns: greatest common divisor of self and n. public func gcd(of n: Int) -> Int { return n == 0 ? self : n.gcd(of: self % n) } /// SwifterSwift: Least common multiple of integer and n. /// /// - Parameter n: integer value to find lcm with. /// - Returns: least common multiple of self and n. public func lcm(of n: Int) -> Int { return (self * n).abs / gcd(of: n) } /// SwifterSwift: Random integer between two integer values. /// /// - Parameters: /// - min: minimum number to start random from. /// - max: maximum number random number end before. /// - Returns: random double between two double values. public static func random(between min: Int, and max: Int) -> Int { return random(inRange: min...max) } /// SwifterSwift: Random integer in a closed interval range. /// /// - Parameter range: closed interval range. public static func random(inRange range: ClosedRange<Int>) -> Int { let delta = UInt32(range.upperBound - range.lowerBound + 1) return range.lowerBound + Int(arc4random_uniform(delta)) } } // MARK: - Initializers public extension Int { /// SwifterSwift: Created a random integer between two integer values. /// /// - Parameters: /// - min: minimum number to start random from. /// - max: maximum number random number end before. public init(randomBetween min: Int, and max: Int) { self = Int.random(between: min, and: max) } /// SwifterSwift: Create a random integer in a closed interval range. /// /// - Parameter range: closed interval range. public init(randomInRange range: ClosedRange<Int>) { self = Int.random(inRange: range) } } // MARK: - Operators precedencegroup PowerPrecedence { higherThan: MultiplicationPrecedence } infix operator ** : PowerPrecedence /// SwifterSwift: Value of exponentiation. /// /// - Parameters: /// - lhs: base integer. /// - rhs: exponent integer. /// - Returns: exponentiation result (example: 2 ** 3 = 8). public func ** (lhs: Int, rhs: Int) -> Double { // http://nshipster.com/swift-operators/ return pow(Double(lhs), Double(rhs)) } prefix operator √ /// SwifterSwift: Square root of integer. /// /// - Parameter int: integer value to find square root for /// - Returns: square root of given integer. public prefix func √ (int: Int) -> Double { // http://nshipster.com/swift-operators/ return sqrt(Double(int)) } infix operator ± /// SwifterSwift: Tuple of plus-minus operation. /// /// - Parameters: /// - lhs: integer number /// - rhs: integer number /// - Returns: tuple of plus-minus operation (example: 2 ± 3 -> (5, -1)). public func ± (lhs: Int, rhs: Int) -> (Int, Int) { // http://nshipster.com/swift-operators/ return (lhs + rhs, lhs - rhs) } prefix operator ± /// SwifterSwift: Tuple of plus-minus operation. /// /// - Parameter int: integer number /// - Returns: tuple of plus-minus operation (example: ± 2 -> (2, -2)). public prefix func ± (int: Int) -> (Int, Int) { // http://nshipster.com/swift-operators/ return 0 ± int }
ad967050883412cdf56cebe914987ae3
24.130112
95
0.651036
false
false
false
false
IngmarStein/swift
refs/heads/master
test/stdlib/RuntimeObjC.swift
apache-2.0
4
// RUN: rm -rf %t && mkdir -p %t // // RUN: %target-clang %S/Inputs/Mirror/Mirror.mm -c -o %t/Mirror.mm.o -g // RUN: %target-build-swift -parse-stdlib -Xfrontend -disable-access-control -module-name a -I %S/Inputs/Mirror/ -Xlinker %t/Mirror.mm.o %s -o %t.out // RUN: %target-run %t.out // REQUIRES: executable_test // REQUIRES: objc_interop import Swift import StdlibUnittest import Foundation import CoreGraphics import SwiftShims import MirrorObjC var nsObjectCanaryCount = 0 @objc class NSObjectCanary : NSObject { override init() { nsObjectCanaryCount += 1 } deinit { nsObjectCanaryCount -= 1 } } struct NSObjectCanaryStruct { var ref = NSObjectCanary() } var swiftObjectCanaryCount = 0 class SwiftObjectCanary { init() { swiftObjectCanaryCount += 1 } deinit { swiftObjectCanaryCount -= 1 } } struct SwiftObjectCanaryStruct { var ref = SwiftObjectCanary() } @objc class ClassA { init(value: Int) { self.value = value } var value: Int } struct BridgedValueType : _ObjectiveCBridgeable { init(value: Int) { self.value = value } func _bridgeToObjectiveC() -> ClassA { return ClassA(value: value) } static func _forceBridgeFromObjectiveC( _ x: ClassA, result: inout BridgedValueType? ) { assert(x.value % 2 == 0, "not bridged to Objective-C") result = BridgedValueType(value: x.value) } static func _conditionallyBridgeFromObjectiveC( _ x: ClassA, result: inout BridgedValueType? ) -> Bool { if x.value % 2 == 0 { result = BridgedValueType(value: x.value) return true } result = nil return false } static func _unconditionallyBridgeFromObjectiveC(_ source: ClassA?) -> BridgedValueType { var result: BridgedValueType? _forceBridgeFromObjectiveC(source!, result: &result) return result! } var value: Int var canaryRef = SwiftObjectCanary() } struct BridgedLargeValueType : _ObjectiveCBridgeable { init(value: Int) { value0 = value value1 = value value2 = value value3 = value value4 = value value5 = value value6 = value value7 = value } func _bridgeToObjectiveC() -> ClassA { assert(value == value0) return ClassA(value: value0) } static func _forceBridgeFromObjectiveC( _ x: ClassA, result: inout BridgedLargeValueType? ) { assert(x.value % 2 == 0, "not bridged to Objective-C") result = BridgedLargeValueType(value: x.value) } static func _conditionallyBridgeFromObjectiveC( _ x: ClassA, result: inout BridgedLargeValueType? ) -> Bool { if x.value % 2 == 0 { result = BridgedLargeValueType(value: x.value) return true } result = nil return false } static func _unconditionallyBridgeFromObjectiveC(_ source: ClassA?) -> BridgedLargeValueType { var result: BridgedLargeValueType? _forceBridgeFromObjectiveC(source!, result: &result) return result! } var value: Int { let x = value0 assert(value0 == x && value1 == x && value2 == x && value3 == x && value4 == x && value5 == x && value6 == x && value7 == x) return x } var (value0, value1, value2, value3): (Int, Int, Int, Int) var (value4, value5, value6, value7): (Int, Int, Int, Int) var canaryRef = SwiftObjectCanary() } class BridgedVerbatimRefType { var value: Int = 42 var canaryRef = SwiftObjectCanary() } func withSwiftObjectCanary<T>( _ createValue: () -> T, _ check: (T) -> Void, file: String = #file, line: UInt = #line ) { let stackTrace = SourceLocStack(SourceLoc(file, line)) swiftObjectCanaryCount = 0 autoreleasepool { var valueWithCanary = createValue() expectEqual(1, swiftObjectCanaryCount, stackTrace: stackTrace) check(valueWithCanary) } expectEqual(0, swiftObjectCanaryCount, stackTrace: stackTrace) } var Runtime = TestSuite("Runtime") func _isClassOrObjCExistential_Opaque<T>(_ x: T.Type) -> Bool { return _isClassOrObjCExistential(_opaqueIdentity(x)) } Runtime.test("_isClassOrObjCExistential") { expectTrue(_isClassOrObjCExistential(NSObjectCanary.self)) expectTrue(_isClassOrObjCExistential_Opaque(NSObjectCanary.self)) expectFalse(_isClassOrObjCExistential(NSObjectCanaryStruct.self)) expectFalse(_isClassOrObjCExistential_Opaque(NSObjectCanaryStruct.self)) expectTrue(_isClassOrObjCExistential(SwiftObjectCanary.self)) expectTrue(_isClassOrObjCExistential_Opaque(SwiftObjectCanary.self)) expectFalse(_isClassOrObjCExistential(SwiftObjectCanaryStruct.self)) expectFalse(_isClassOrObjCExistential_Opaque(SwiftObjectCanaryStruct.self)) typealias SwiftClosure = () -> () expectFalse(_isClassOrObjCExistential(SwiftClosure.self)) expectFalse(_isClassOrObjCExistential_Opaque(SwiftClosure.self)) typealias ObjCClosure = @convention(block) () -> () expectTrue(_isClassOrObjCExistential(ObjCClosure.self)) expectTrue(_isClassOrObjCExistential_Opaque(ObjCClosure.self)) expectTrue(_isClassOrObjCExistential(CFArray.self)) expectTrue(_isClassOrObjCExistential_Opaque(CFArray.self)) expectTrue(_isClassOrObjCExistential(CFArray.self)) expectTrue(_isClassOrObjCExistential_Opaque(CFArray.self)) expectTrue(_isClassOrObjCExistential(AnyObject.self)) expectTrue(_isClassOrObjCExistential_Opaque(AnyObject.self)) // AnyClass == AnyObject.Type expectFalse(_isClassOrObjCExistential(AnyClass.self)) expectFalse(_isClassOrObjCExistential_Opaque(AnyClass.self)) expectFalse(_isClassOrObjCExistential(AnyObject.Protocol.self)) expectFalse(_isClassOrObjCExistential_Opaque(AnyObject.Protocol.self)) expectFalse(_isClassOrObjCExistential(NSObjectCanary.Type.self)) expectFalse(_isClassOrObjCExistential_Opaque(NSObjectCanary.Type.self)) } Runtime.test("_canBeClass") { expectEqual(1, _canBeClass(NSObjectCanary.self)) expectEqual(0, _canBeClass(NSObjectCanaryStruct.self)) typealias ObjCClosure = @convention(block) () -> () expectEqual(1, _canBeClass(ObjCClosure.self)) expectEqual(1, _canBeClass(CFArray.self)) } Runtime.test("bridgeToObjectiveC") { expectEqual(42, (_bridgeAnythingToObjectiveC(BridgedValueType(value: 42)) as! ClassA).value) expectEqual(42, (_bridgeAnythingToObjectiveC(BridgedLargeValueType(value: 42)) as! ClassA).value) var bridgedVerbatimRef = BridgedVerbatimRefType() expectTrue(_bridgeAnythingToObjectiveC(bridgedVerbatimRef) === bridgedVerbatimRef) } Runtime.test("bridgeToObjectiveC/NoLeak") { withSwiftObjectCanary( { BridgedValueType(value: 42) }, { expectEqual(42, (_bridgeAnythingToObjectiveC($0) as! ClassA).value) }) withSwiftObjectCanary( { BridgedLargeValueType(value: 42) }, { expectEqual(42, (_bridgeAnythingToObjectiveC($0) as! ClassA).value) }) withSwiftObjectCanary( { BridgedVerbatimRefType() }, { expectTrue(_bridgeAnythingToObjectiveC($0) === $0) }) } Runtime.test("forceBridgeFromObjectiveC") { // Bridge back using BridgedValueType. expectNil(_conditionallyBridgeFromObjectiveC( ClassA(value: 21), BridgedValueType.self)) expectEqual(42, _forceBridgeFromObjectiveC( ClassA(value: 42), BridgedValueType.self).value) expectEqual(42, _conditionallyBridgeFromObjectiveC( ClassA(value: 42), BridgedValueType.self)!.value) expectNil(_conditionallyBridgeFromObjectiveC( BridgedVerbatimRefType(), BridgedValueType.self)) // Bridge back using BridgedLargeValueType. expectNil(_conditionallyBridgeFromObjectiveC( ClassA(value: 21), BridgedLargeValueType.self)) expectEqual(42, _forceBridgeFromObjectiveC( ClassA(value: 42), BridgedLargeValueType.self).value) expectEqual(42, _conditionallyBridgeFromObjectiveC( ClassA(value: 42), BridgedLargeValueType.self)!.value) expectNil(_conditionallyBridgeFromObjectiveC( BridgedVerbatimRefType(), BridgedLargeValueType.self)) // Bridge back using BridgedVerbatimRefType. expectNil(_conditionallyBridgeFromObjectiveC( ClassA(value: 21), BridgedVerbatimRefType.self)) expectNil(_conditionallyBridgeFromObjectiveC( ClassA(value: 42), BridgedVerbatimRefType.self)) var bridgedVerbatimRef = BridgedVerbatimRefType() expectTrue(_forceBridgeFromObjectiveC( bridgedVerbatimRef, BridgedVerbatimRefType.self) === bridgedVerbatimRef) expectTrue(_conditionallyBridgeFromObjectiveC( bridgedVerbatimRef, BridgedVerbatimRefType.self)! === bridgedVerbatimRef) } Runtime.test("isBridgedToObjectiveC") { expectTrue(_isBridgedToObjectiveC(BridgedValueType)) expectTrue(_isBridgedToObjectiveC(BridgedVerbatimRefType)) } Runtime.test("isBridgedVerbatimToObjectiveC") { expectFalse(_isBridgedVerbatimToObjectiveC(BridgedValueType)) expectTrue(_isBridgedVerbatimToObjectiveC(BridgedVerbatimRefType)) } //===----------------------------------------------------------------------===// class SomeClass {} @objc class SomeObjCClass {} class SomeNSObjectSubclass : NSObject {} Runtime.test("typeName") { expectEqual("a.SomeObjCClass", _typeName(SomeObjCClass.self)) expectEqual("a.SomeNSObjectSubclass", _typeName(SomeNSObjectSubclass.self)) expectEqual("NSObject", _typeName(NSObject.self)) var a : Any = SomeObjCClass() expectEqual("a.SomeObjCClass", _typeName(type(of: a))) a = SomeNSObjectSubclass() expectEqual("a.SomeNSObjectSubclass", _typeName(type(of: a))) a = NSObject() expectEqual("NSObject", _typeName(type(of: a))) } class GenericClass<T> {} class MultiGenericClass<T, U> {} struct GenericStruct<T> {} enum GenericEnum<T> {} struct PlainStruct {} enum PlainEnum {} protocol ProtocolA {} protocol ProtocolB {} Runtime.test("Generic class ObjC runtime names") { expectEqual("_TtGC1a12GenericClassSi_", NSStringFromClass(GenericClass<Int>.self)) expectEqual("_TtGC1a12GenericClassVS_11PlainStruct_", NSStringFromClass(GenericClass<PlainStruct>.self)) expectEqual("_TtGC1a12GenericClassOS_9PlainEnum_", NSStringFromClass(GenericClass<PlainEnum>.self)) expectEqual("_TtGC1a12GenericClassTVS_11PlainStructOS_9PlainEnumS1___", NSStringFromClass(GenericClass<(PlainStruct, PlainEnum, PlainStruct)>.self)) expectEqual("_TtGC1a12GenericClassMVS_11PlainStruct_", NSStringFromClass(GenericClass<PlainStruct.Type>.self)) expectEqual("_TtGC1a12GenericClassFMVS_11PlainStructS1__", NSStringFromClass(GenericClass<(PlainStruct.Type) -> PlainStruct>.self)) expectEqual("_TtGC1a12GenericClassFzMVS_11PlainStructS1__", NSStringFromClass(GenericClass<(PlainStruct.Type) throws -> PlainStruct>.self)) expectEqual("_TtGC1a12GenericClassFTVS_11PlainStructROS_9PlainEnum_Si_", NSStringFromClass(GenericClass<(PlainStruct, inout PlainEnum) -> Int>.self)) expectEqual("_TtGC1a12GenericClassPS_9ProtocolA__", NSStringFromClass(GenericClass<ProtocolA>.self)) expectEqual("_TtGC1a12GenericClassPS_9ProtocolAS_9ProtocolB__", NSStringFromClass(GenericClass<ProtocolA & ProtocolB>.self)) expectEqual("_TtGC1a12GenericClassPMPS_9ProtocolAS_9ProtocolB__", NSStringFromClass(GenericClass<(ProtocolA & ProtocolB).Type>.self)) expectEqual("_TtGC1a12GenericClassMPS_9ProtocolAS_9ProtocolB__", NSStringFromClass(GenericClass<(ProtocolB & ProtocolA).Protocol>.self)) expectEqual("_TtGC1a12GenericClassCSo7CFArray_", NSStringFromClass(GenericClass<CFArray>.self)) expectEqual("_TtGC1a12GenericClassVSC7Decimal_", NSStringFromClass(GenericClass<Decimal>.self)) expectEqual("_TtGC1a12GenericClassCSo8NSObject_", NSStringFromClass(GenericClass<NSObject>.self)) expectEqual("_TtGC1a12GenericClassCSo8NSObject_", NSStringFromClass(GenericClass<NSObject>.self)) expectEqual("_TtGC1a12GenericClassPSo9NSCopying__", NSStringFromClass(GenericClass<NSCopying>.self)) expectEqual("_TtGC1a12GenericClassPSo9NSCopyingS_9ProtocolAS_9ProtocolB__", NSStringFromClass(GenericClass<ProtocolB & NSCopying & ProtocolA>.self)) expectEqual("_TtGC1a17MultiGenericClassGVS_13GenericStructSi_GOS_11GenericEnumGS2_Si___", NSStringFromClass(MultiGenericClass<GenericStruct<Int>, GenericEnum<GenericEnum<Int>>>.self)) } Runtime.test("typeByName") { // Make sure we don't crash if we have foreign classes in the // table -- those don't have NominalTypeDescriptors print(CFArray.self) expectTrue(_typeByName("a.SomeClass") == SomeClass.self) expectTrue(_typeByName("DoesNotExist") == nil) } Runtime.test("casting AnyObject to class metatypes") { do { var ao: AnyObject = SomeClass.self expectTrue(ao as? Any.Type == SomeClass.self) expectTrue(ao as? AnyClass == SomeClass.self) expectTrue(ao as? SomeClass.Type == SomeClass.self) } do { var ao : AnyObject = SomeNSObjectSubclass() expectTrue(ao as? Any.Type == nil) expectTrue(ao as? AnyClass == nil) ao = SomeNSObjectSubclass.self expectTrue(ao as? Any.Type == SomeNSObjectSubclass.self) expectTrue(ao as? AnyClass == SomeNSObjectSubclass.self) expectTrue(ao as? SomeNSObjectSubclass.Type == SomeNSObjectSubclass.self) } do { var a : Any = SomeNSObjectSubclass() expectTrue(a as? Any.Type == nil) expectTrue(a as? AnyClass == nil) } do { var nso: NSObject = SomeNSObjectSubclass() expectTrue(nso as? AnyClass == nil) nso = (SomeNSObjectSubclass.self as AnyObject) as! NSObject expectTrue(nso as? Any.Type == SomeNSObjectSubclass.self) expectTrue(nso as? AnyClass == SomeNSObjectSubclass.self) expectTrue(nso as? SomeNSObjectSubclass.Type == SomeNSObjectSubclass.self) } } var RuntimeFoundationWrappers = TestSuite("RuntimeFoundationWrappers") RuntimeFoundationWrappers.test("_stdlib_NSObject_isEqual/NoLeak") { nsObjectCanaryCount = 0 autoreleasepool { let a = NSObjectCanary() let b = NSObjectCanary() expectEqual(2, nsObjectCanaryCount) _stdlib_NSObject_isEqual(a, b) } expectEqual(0, nsObjectCanaryCount) } var nsStringCanaryCount = 0 @objc class NSStringCanary : NSString { override init() { nsStringCanaryCount += 1 super.init() } required init(coder: NSCoder) { fatalError("don't call this initializer") } deinit { nsStringCanaryCount -= 1 } @objc override var length: Int { return 0 } @objc override func character(at index: Int) -> unichar { fatalError("out-of-bounds access") } } RuntimeFoundationWrappers.test( "_stdlib_compareNSStringDeterministicUnicodeCollation/NoLeak" ) { nsStringCanaryCount = 0 autoreleasepool { let a = NSStringCanary() let b = NSStringCanary() expectEqual(2, nsStringCanaryCount) _stdlib_compareNSStringDeterministicUnicodeCollation(a, b) } expectEqual(0, nsStringCanaryCount) } RuntimeFoundationWrappers.test( "_stdlib_compareNSStringDeterministicUnicodeCollationPtr/NoLeak" ) { nsStringCanaryCount = 0 autoreleasepool { let a = NSStringCanary() let b = NSStringCanary() expectEqual(2, nsStringCanaryCount) let ptrA = unsafeBitCast(a, to: OpaquePointer.self) let ptrB = unsafeBitCast(b, to: OpaquePointer.self) _stdlib_compareNSStringDeterministicUnicodeCollationPointer(ptrA, ptrB) } expectEqual(0, nsStringCanaryCount) } RuntimeFoundationWrappers.test("_stdlib_NSStringHashValue/NoLeak") { nsStringCanaryCount = 0 autoreleasepool { let a = NSStringCanary() expectEqual(1, nsStringCanaryCount) _stdlib_NSStringHashValue(a, true) } expectEqual(0, nsStringCanaryCount) } RuntimeFoundationWrappers.test("_stdlib_NSStringHashValueNonASCII/NoLeak") { nsStringCanaryCount = 0 autoreleasepool { let a = NSStringCanary() expectEqual(1, nsStringCanaryCount) _stdlib_NSStringHashValue(a, false) } expectEqual(0, nsStringCanaryCount) } RuntimeFoundationWrappers.test("_stdlib_NSStringHashValuePointer/NoLeak") { nsStringCanaryCount = 0 autoreleasepool { let a = NSStringCanary() expectEqual(1, nsStringCanaryCount) let ptrA = unsafeBitCast(a, to: OpaquePointer.self) _stdlib_NSStringHashValuePointer(ptrA, true) } expectEqual(0, nsStringCanaryCount) } RuntimeFoundationWrappers.test("_stdlib_NSStringHashValuePointerNonASCII/NoLeak") { nsStringCanaryCount = 0 autoreleasepool { let a = NSStringCanary() expectEqual(1, nsStringCanaryCount) let ptrA = unsafeBitCast(a, to: OpaquePointer.self) _stdlib_NSStringHashValuePointer(ptrA, false) } expectEqual(0, nsStringCanaryCount) } RuntimeFoundationWrappers.test("_stdlib_NSStringHasPrefixNFDPointer/NoLeak") { nsStringCanaryCount = 0 autoreleasepool { let a = NSStringCanary() let b = NSStringCanary() expectEqual(2, nsStringCanaryCount) let ptrA = unsafeBitCast(a, to: OpaquePointer.self) let ptrB = unsafeBitCast(b, to: OpaquePointer.self) _stdlib_NSStringHasPrefixNFDPointer(ptrA, ptrB) } expectEqual(0, nsStringCanaryCount) } RuntimeFoundationWrappers.test("_stdlib_NSStringHasSuffixNFDPointer/NoLeak") { nsStringCanaryCount = 0 autoreleasepool { let a = NSStringCanary() let b = NSStringCanary() expectEqual(2, nsStringCanaryCount) let ptrA = unsafeBitCast(a, to: OpaquePointer.self) let ptrB = unsafeBitCast(b, to: OpaquePointer.self) _stdlib_NSStringHasSuffixNFDPointer(ptrA, ptrB) } expectEqual(0, nsStringCanaryCount) } RuntimeFoundationWrappers.test("_stdlib_NSStringHasPrefixNFD/NoLeak") { nsStringCanaryCount = 0 autoreleasepool { let a = NSStringCanary() let b = NSStringCanary() expectEqual(2, nsStringCanaryCount) _stdlib_NSStringHasPrefixNFD(a, b) } expectEqual(0, nsStringCanaryCount) } RuntimeFoundationWrappers.test("_stdlib_NSStringHasSuffixNFD/NoLeak") { nsStringCanaryCount = 0 autoreleasepool { let a = NSStringCanary() let b = NSStringCanary() expectEqual(2, nsStringCanaryCount) _stdlib_NSStringHasSuffixNFD(a, b) } expectEqual(0, nsStringCanaryCount) } RuntimeFoundationWrappers.test("_stdlib_NSStringLowercaseString/NoLeak") { nsStringCanaryCount = 0 autoreleasepool { let a = NSStringCanary() expectEqual(1, nsStringCanaryCount) _stdlib_NSStringLowercaseString(a) } expectEqual(0, nsStringCanaryCount) } RuntimeFoundationWrappers.test("_stdlib_NSStringUppercaseString/NoLeak") { nsStringCanaryCount = 0 autoreleasepool { let a = NSStringCanary() expectEqual(1, nsStringCanaryCount) _stdlib_NSStringUppercaseString(a) } expectEqual(0, nsStringCanaryCount) } RuntimeFoundationWrappers.test("_stdlib_CFStringCreateCopy/NoLeak") { nsStringCanaryCount = 0 autoreleasepool { let a = NSStringCanary() expectEqual(1, nsStringCanaryCount) _stdlib_binary_CFStringCreateCopy(a) } expectEqual(0, nsStringCanaryCount) } RuntimeFoundationWrappers.test("_stdlib_CFStringGetLength/NoLeak") { nsStringCanaryCount = 0 autoreleasepool { let a = NSStringCanary() expectEqual(1, nsStringCanaryCount) _stdlib_binary_CFStringGetLength(a) } expectEqual(0, nsStringCanaryCount) } RuntimeFoundationWrappers.test("_stdlib_CFStringGetCharactersPtr/NoLeak") { nsStringCanaryCount = 0 autoreleasepool { let a = NSStringCanary() expectEqual(1, nsStringCanaryCount) _stdlib_binary_CFStringGetCharactersPtr(a) } expectEqual(0, nsStringCanaryCount) } RuntimeFoundationWrappers.test("bridgedNSArray") { var c = [NSObject]() autoreleasepool { let a = [NSObject]() let b = a as NSArray c = b as! [NSObject] } c.append(NSObject()) // expect no crash. } var Reflection = TestSuite("Reflection") class SwiftFooMoreDerivedObjCClass : FooMoreDerivedObjCClass { let first: Int = 123 let second: String = "abc" } Reflection.test("Class/ObjectiveCBase/Default") { do { let value = SwiftFooMoreDerivedObjCClass() var output = "" dump(value, to: &output) let expected = "▿ This is FooObjCClass #0\n" + " - super: FooMoreDerivedObjCClass\n" + " - super: FooDerivedObjCClass\n" + " - super: FooObjCClass\n" + " - super: NSObject\n" + " - first: 123\n" + " - second: \"abc\"\n" expectEqual(expected, output) } } protocol SomeNativeProto {} @objc protocol SomeObjCProto {} extension SomeClass: SomeObjCProto {} Reflection.test("MetatypeMirror") { do { let concreteClassMetatype = SomeClass.self let expectedSomeClass = "- a.SomeClass #0\n" let objcProtocolMetatype: SomeObjCProto.Type = SomeClass.self var output = "" dump(objcProtocolMetatype, to: &output) expectEqual(expectedSomeClass, output) let objcProtocolConcreteMetatype = SomeObjCProto.self let expectedObjCProtocolConcrete = "- a.SomeObjCProto #0\n" output = "" dump(objcProtocolConcreteMetatype, to: &output) expectEqual(expectedObjCProtocolConcrete, output) let compositionConcreteMetatype = (SomeNativeProto & SomeObjCProto).self let expectedComposition = "- a.SomeNativeProto & a.SomeObjCProto #0\n" output = "" dump(compositionConcreteMetatype, to: &output) expectEqual(expectedComposition, output) let objcDefinedProtoType = NSObjectProtocol.self expectEqual(String(describing: objcDefinedProtoType), "NSObject") } } Reflection.test("CGPoint") { var output = "" dump(CGPoint(x: 1.25, y: 2.75), to: &output) let expected = "▿ (1.25, 2.75)\n" + " - x: 1.25\n" + " - y: 2.75\n" expectEqual(expected, output) } Reflection.test("CGSize") { var output = "" dump(CGSize(width: 1.25, height: 2.75), to: &output) let expected = "▿ (1.25, 2.75)\n" + " - width: 1.25\n" + " - height: 2.75\n" expectEqual(expected, output) } Reflection.test("CGRect") { var output = "" dump( CGRect( origin: CGPoint(x: 1.25, y: 2.25), size: CGSize(width: 10.25, height: 11.75)), to: &output) let expected = "▿ (1.25, 2.25, 10.25, 11.75)\n" + " ▿ origin: (1.25, 2.25)\n" + " - x: 1.25\n" + " - y: 2.25\n" + " ▿ size: (10.25, 11.75)\n" + " - width: 10.25\n" + " - height: 11.75\n" expectEqual(expected, output) } Reflection.test("Unmanaged/nil") { var output = "" var optionalURL: Unmanaged<CFURL>? dump(optionalURL, to: &output) let expected = "- nil\n" expectEqual(expected, output) } Reflection.test("Unmanaged/not-nil") { var output = "" var optionalURL: Unmanaged<CFURL>? = Unmanaged.passRetained(CFURLCreateWithString(nil, "http://llvm.org/" as CFString, nil)) dump(optionalURL, to: &output) let expected = "▿ Optional(Swift.Unmanaged<__ObjC.CFURL>(_value: http://llvm.org/))\n" + " ▿ some: Swift.Unmanaged<__ObjC.CFURL>\n" + " - _value: http://llvm.org/ #0\n" + " - super: NSObject\n" expectEqual(expected, output) optionalURL!.release() } Reflection.test("TupleMirror/NoLeak") { do { nsObjectCanaryCount = 0 autoreleasepool { var tuple = (1, NSObjectCanary()) expectEqual(1, nsObjectCanaryCount) var output = "" dump(tuple, to: &output) } expectEqual(0, nsObjectCanaryCount) } do { nsObjectCanaryCount = 0 autoreleasepool { var tuple = (1, NSObjectCanaryStruct()) expectEqual(1, nsObjectCanaryCount) var output = "" dump(tuple, to: &output) } expectEqual(0, nsObjectCanaryCount) } do { swiftObjectCanaryCount = 0 autoreleasepool { var tuple = (1, SwiftObjectCanary()) expectEqual(1, swiftObjectCanaryCount) var output = "" dump(tuple, to: &output) } expectEqual(0, swiftObjectCanaryCount) } do { swiftObjectCanaryCount = 0 autoreleasepool { var tuple = (1, SwiftObjectCanaryStruct()) expectEqual(1, swiftObjectCanaryCount) var output = "" dump(tuple, to: &output) } expectEqual(0, swiftObjectCanaryCount) } } class TestArtificialSubclass: NSObject { dynamic var foo = "foo" } var KVOHandle = 0 Reflection.test("Name of metatype of artificial subclass") { let obj = TestArtificialSubclass() // Trigger the creation of a KVO subclass for TestArtificialSubclass. obj.addObserver(obj, forKeyPath: "foo", options: [.new], context: &KVOHandle) obj.removeObserver(obj, forKeyPath: "foo") expectEqual("\(type(of: obj))", "TestArtificialSubclass") } @objc class StringConvertibleInDebugAndOtherwise : NSObject { override var description: String { return "description" } override var debugDescription: String { return "debugDescription" } } Reflection.test("NSObject is properly CustomDebugStringConvertible") { let object = StringConvertibleInDebugAndOtherwise() expectEqual(String(reflecting: object), object.debugDescription) } Reflection.test("NSRange QuickLook") { let rng = NSRange(location:Int.min, length:5) let ql = PlaygroundQuickLook(reflecting: rng) switch ql { case .range(let loc, let len): expectEqual(loc, Int64(Int.min)) expectEqual(len, 5) default: expectUnreachable("PlaygroundQuickLook for NSRange did not match Range") } } class SomeSubclass : SomeClass {} var ObjCConformsToProtocolTestSuite = TestSuite("ObjCConformsToProtocol") ObjCConformsToProtocolTestSuite.test("cast/instance") { expectTrue(SomeClass() is SomeObjCProto) expectTrue(SomeSubclass() is SomeObjCProto) } ObjCConformsToProtocolTestSuite.test("cast/metatype") { expectTrue(SomeClass.self is SomeObjCProto.Type) expectTrue(SomeSubclass.self is SomeObjCProto.Type) } runAllTests()
4e6dc5b1e89a1f7eee7fb3a3ac1e32d8
28.787879
149
0.715392
false
true
false
false
phimage/Alamofire-YamlSwift
refs/heads/master
Alamofire-YamlSwift/Alamofire+YamlSwift.swift
mit
1
// // Alamofire+YamlSwift.swift // Alamofire-YamlSwift /* The MIT License (MIT) Copyright (c) 2015 Eric Marchand (phimage) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import Foundation import YamlSwift import Alamofire extension Request { public static func YamlResponseSerializer() -> ResponseSerializer<Yaml, NSError> { return ResponseSerializer { request, response, data, error in guard error == nil else { return .Failure(error!) } guard let validData = data else { let failureReason = "Data could not be serialized. Input data was nil." let error = Error.errorWithCode(.DataSerializationFailed, failureReason: failureReason) return .Failure(error) } guard let string = String(data: validData, encoding: NSUTF8StringEncoding) else { let failureReason = "Data could not be deserialized. Input data was not convertible to String." let error = Error.errorWithCode(.DataSerializationFailed, failureReason: failureReason) return .Failure(error) } let result: YamlSwift.Result<Yaml> = Yaml.load(string) switch result { case .Error(let failureReason): let error = Error.errorWithCode(.DataSerializationFailed, failureReason: failureReason) return .Failure(error) case .Value: return .Success(result.value!) } } } public func responseYaml(completionHandler: Response<Yaml, NSError> -> Void) -> Self { return response(responseSerializer: Request.YamlResponseSerializer(), completionHandler: completionHandler) } }
8e6fe05241c6b9c140a382bf4ca93383
45.389831
115
0.695541
false
false
false
false
insidegui/WWDC
refs/heads/master
WWDC/ClipComposition.swift
bsd-2-clause
1
// // ClipComposition.swift // WWDC // // Created by Guilherme Rambo on 02/06/20. // Copyright © 2020 Guilherme Rambo. All rights reserved. // import Cocoa import AVFoundation import CoreMedia import CoreImage.CIFilterBuiltins final class ClipComposition: AVMutableComposition { private struct Constants { static let minBoxWidth: CGFloat = 325 static let maxBoxWidth: CGFloat = 600 static let boxPadding: CGFloat = 42 } let title: String let subtitle: String let video: AVAsset let includeBanner: Bool var videoComposition: AVMutableVideoComposition? init(video: AVAsset, title: String, subtitle: String, includeBanner: Bool) throws { self.video = video self.title = title self.subtitle = subtitle self.includeBanner = includeBanner super.init() guard let newVideoTrack = addMutableTrack(withMediaType: .video, preferredTrackID: kCMPersistentTrackID_Invalid) else { // Should this ever fail in real life? Who knows... preconditionFailure("Failed to add video track to composition") } if let videoTrack = video.tracks(withMediaType: .video).first { try newVideoTrack.insertTimeRange(CMTimeRange(start: .zero, duration: video.duration), of: videoTrack, at: .zero) } if let newAudioTrack = addMutableTrack(withMediaType: .audio, preferredTrackID: kCMPersistentTrackID_Invalid) { if let audioTrack = video.tracks(withMediaType: .audio).first { try newAudioTrack.insertTimeRange(CMTimeRange(start: .zero, duration: video.duration), of: audioTrack, at: .zero) } } configureCompositionIfNeeded(videoTrack: newVideoTrack) } private func configureCompositionIfNeeded(videoTrack: AVMutableCompositionTrack) { guard includeBanner else { return } let mainInstruction = AVMutableVideoCompositionInstruction() mainInstruction.timeRange = CMTimeRange(start: .zero, duration: video.duration) let videolayerInstruction = AVMutableVideoCompositionLayerInstruction(assetTrack: videoTrack) mainInstruction.layerInstructions = [videolayerInstruction] videoComposition = AVMutableVideoComposition(propertiesOf: video) videoComposition?.instructions = [mainInstruction] composeTemplate(with: videoTrack.naturalSize) } private func composeTemplate(with renderSize: CGSize) { guard let asset = CALayer.load(assetNamed: "ClipTemplate") else { fatalError("Missing ClipTemplate asset") } guard let assetContainer = asset.sublayer(named: "container", of: CALayer.self) else { fatalError("Missing container layer") } guard let box = assetContainer.sublayer(named: "box", of: CALayer.self) else { fatalError("Missing box layer") } guard let titleLayer = box.sublayer(named: "sessionTitle", of: CATextLayer.self) else { fatalError("Missing sessionTitle layer") } guard let subtitleLayer = box.sublayer(named: "eventName", of: CATextLayer.self) else { fatalError("Missing sessionTitle layer") } guard let videoLayer = assetContainer.sublayer(named: "video", of: CALayer.self) else { fatalError("Missing video layer") } if let iconLayer = box.sublayer(named: "appicon", of: CALayer.self) { iconLayer.contents = NSApp.applicationIconImage } // Add a NSVisualEffectView-like blur to the box. let blur = CIFilter.gaussianBlur() blur.radius = 22 let saturate = CIFilter.colorControls() saturate.setDefaults() saturate.saturation = 1.5 box.backgroundFilters = [saturate, blur] box.masksToBounds = true // Set text on layers. titleLayer.string = attributedTitle subtitleLayer.string = attributedSubtitle // Compute final box/title layer widths based on title. let titleSize = attributedTitle.size() if titleSize.width > titleLayer.bounds.width { var boxFrame = box.frame boxFrame.size.width = titleSize.width + Constants.boxPadding * 3 box.frame = boxFrame var titleFrame = titleLayer.frame titleFrame.size.width = titleSize.width titleLayer.frame = titleFrame } let container = CALayer() container.frame = CGRect(origin: .zero, size: renderSize) container.addSublayer(assetContainer) container.resizeLayer(assetContainer) assetContainer.isGeometryFlipped = true videoComposition?.animationTool = AVVideoCompositionCoreAnimationTool(postProcessingAsVideoLayer: videoLayer, in: container) box.sublayers?.compactMap({ $0 as? CATextLayer }).forEach { layer in layer.minificationFilter = .trilinear // Workaround rdar://32718905 layer.display() } } private lazy var attributedTitle: NSAttributedString = { NSAttributedString.create( with: title, font: .wwdcRoundedSystemFont(ofSize: 16, weight: .medium), color: .white ) }() private lazy var attributedSubtitle: NSAttributedString = { NSAttributedString.create( with: subtitle, font: .systemFont(ofSize: 13, weight: .medium), color: .white ) }() }
210f12be8983fc4dbfcad98f1f877500
34.11465
132
0.657537
false
false
false
false
EclipseSoundscapes/EclipseSoundscapes
refs/heads/master
Example/Pods/RxSwift/RxSwift/Observables/First.swift
apache-2.0
6
// // First.swift // RxSwift // // Created by Krunoslav Zaher on 7/31/17. // Copyright © 2017 Krunoslav Zaher. All rights reserved. // private final class FirstSink<Element, Observer: ObserverType> : Sink<Observer>, ObserverType where Observer.Element == Element? { typealias Parent = First<Element> func on(_ event: Event<Element>) { switch event { case .next(let value): self.forwardOn(.next(value)) self.forwardOn(.completed) self.dispose() case .error(let error): self.forwardOn(.error(error)) self.dispose() case .completed: self.forwardOn(.next(nil)) self.forwardOn(.completed) self.dispose() } } } final class First<Element>: Producer<Element?> { private let _source: Observable<Element> init(source: Observable<Element>) { self._source = source } override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element? { let sink = FirstSink(observer: observer, cancel: cancel) let subscription = self._source.subscribe(sink) return (sink: sink, subscription: subscription) } }
af9de643ccd13a393b508a11e1883450
30.463415
172
0.625581
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/Localization/Sources/Localization/LocalizationConstants+Account.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. // swiftlint:disable all import Foundation extension LocalizationConstants { public enum Account { public static let myWallet = NSLocalizedString( "Private Key Wallet", comment: "Used for naming non custodial wallets." ) public static let myInterestWallet = NSLocalizedString( "Rewards Account", comment: "Used for naming rewards accounts." ) public static let myTradingAccount = NSLocalizedString( "Trading Account", comment: "Used for naming trading accounts." ) public static let myExchangeAccount = NSLocalizedString( "Exchange Account", comment: "Used for naming exchange accounts." ) public static let lowFees = NSLocalizedString( "Low Fees", comment: "Low Fees" ) public static let faster = NSLocalizedString( "Faster", comment: "Faster" ) public static let legacyMyBitcoinWallet = NSLocalizedString( "My Bitcoin Wallet", comment: "My Bitcoin Wallet" ) public static let noFees = NSLocalizedString( "No Fees", comment: "No Fees" ) public static let wireFee = NSLocalizedString( "Wire Fee", comment: "Wire Fee" ) public static let minWithdraw = NSLocalizedString( "Min Withdraw", comment: "Min Withdraw" ) } public enum AccountGroup { public static let allWallets = NSLocalizedString( "All Wallets", comment: "All Wallets" ) public static let myWallets = NSLocalizedString( "%@ Wallets", comment: "Must contain %@. Used for naming account groups e.g. Ethereum Wallets" ) public static let myCustodialWallets = NSLocalizedString( "%@ Custodial Accounts", comment: "Must contain %@. Used for naming trading account groups e.g. Ethereum Custodial Wallets" ) } }
a4b4ca331e764049a4ba863fd7b98836
27.671053
110
0.577788
false
false
false
false
JGiola/swift-corelibs-foundation
refs/heads/master
Foundation/NSPredicate.swift
apache-2.0
13
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // // Predicates wrap some combination of expressions and operators and when evaluated return a BOOL. open class NSPredicate : NSObject, NSSecureCoding, NSCopying { private enum PredicateKind { case boolean(Bool) case block((Any?, [String : Any]?) -> Bool) case format(String) case metadataQuery(String) } private let kind: PredicateKind public static var supportsSecureCoding: Bool { return true } public required init?(coder aDecoder: NSCoder) { guard aDecoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } let encodedBool = aDecoder.decodeBool(forKey: "NS.boolean.value") self.kind = .boolean(encodedBool) super.init() } open func encode(with aCoder: NSCoder) { guard aCoder.allowsKeyedCoding else { preconditionFailure("Unkeyed coding is unsupported.") } //TODO: store kind key for .boolean, .format, .metadataQuery switch self.kind { case .boolean(let value): aCoder.encode(value, forKey: "NS.boolean.value") case .block: preconditionFailure("NSBlockPredicate cannot be encoded or decoded.") case .format: NSUnimplemented() case .metadataQuery: NSUnimplemented() } } open override func copy() -> Any { return copy(with: nil) } open func copy(with zone: NSZone? = nil) -> Any { switch self.kind { case .boolean(let value): return NSPredicate(value: value) case .block(let block): return NSPredicate(block: block) case .format: NSUnimplemented() case .metadataQuery: NSUnimplemented() } } open override func isEqual(_ object: Any?) -> Bool { guard let other = object as? NSPredicate else { return false } if other === self { return true } else { switch (other.kind, self.kind) { case (.boolean(let otherBool), .boolean(let selfBool)): return otherBool == selfBool case (.format, .format): NSUnimplemented() case (.metadataQuery, .metadataQuery): NSUnimplemented() default: // NSBlockPredicate returns false even for copy return false } } } // Parse predicateFormat and return an appropriate predicate public init(format predicateFormat: String, argumentArray arguments: [Any]?) { NSUnimplemented() } public init(format predicateFormat: String, arguments argList: CVaListPointer) { NSUnimplemented() } public init?(fromMetadataQueryString queryString: String) { NSUnimplemented() } public init(value: Bool) { kind = .boolean(value) super.init() } // return predicates that always evaluate to true/false public init(block: @escaping (Any?, [String : Any]?) -> Bool) { kind = .block(block) super.init() } open var predicateFormat: String { switch self.kind { case .boolean(let value): return value ? "TRUEPREDICATE" : "FALSEPREDICATE" case .block: // TODO: Bring NSBlockPredicate's predicateFormat to macOS's Foundation version // let address = unsafeBitCast(block, to: Int.self) // return String(format:"BLOCKPREDICATE(%2X)", address) return "BLOCKPREDICATE" case .format: NSUnimplemented() case .metadataQuery: NSUnimplemented() } } open func withSubstitutionVariables(_ variables: [String : Any]) -> Self { NSUnimplemented() } // substitute constant values for variables open func evaluate(with object: Any?) -> Bool { return evaluate(with: object, substitutionVariables: nil) } // evaluate a predicate against a single object open func evaluate(with object: Any?, substitutionVariables bindings: [String : Any]?) -> Bool { if bindings != nil { NSUnimplemented() } switch kind { case let .boolean(value): return value case let .block(block): return block(object, bindings) case .format: NSUnimplemented() case .metadataQuery: NSUnimplemented() } } // single pass evaluation substituting variables from the bindings dictionary for any variable expressions encountered open func allowEvaluation() { NSUnimplemented() } // Force a predicate which was securely decoded to allow evaluation } extension NSPredicate { public convenience init(format predicateFormat: String, _ args: CVarArg...) { NSUnimplemented() } } extension NSArray { open func filtered(using predicate: NSPredicate) -> [Any] { return allObjects.filter({ object in return predicate.evaluate(with: object) }) } } extension NSMutableArray { open func filter(using predicate: NSPredicate) { var indexesToRemove = IndexSet() for (index, object) in self.enumerated() { if !predicate.evaluate(with: object) { indexesToRemove.insert(index) } } self.removeObjects(at: indexesToRemove) } } extension NSSet { open func filtered(using predicate: NSPredicate) -> Set<AnyHashable> { let objs = allObjects.filter { (object) -> Bool in return predicate.evaluate(with: object) } return Set(objs.map { $0 as! AnyHashable }) } } extension NSMutableSet { open func filter(using predicate: NSPredicate) { for object in self { if !predicate.evaluate(with: object) { self.remove(object) } } } } extension NSOrderedSet { open func filtered(using predicate: NSPredicate) -> NSOrderedSet { return NSOrderedSet(array: self.allObjects.filter({ object in return predicate.evaluate(with: object) })) } } extension NSMutableOrderedSet { open func filter(using predicate: NSPredicate) { var indexesToRemove = IndexSet() for (index, object) in self.enumerated() { if !predicate.evaluate(with: object) { indexesToRemove.insert(index) } } self.removeObjects(at: indexesToRemove) } }
d39c94973b4d6dc355d28e9a34f530fc
31.153488
142
0.604947
false
false
false
false
alfredcc/SwiftPlayground
refs/heads/master
Functions/Functions.playground/Contents.swift
mit
1
//: Playground - noun: a place where people can play import UIKit func treble(i: Int) -> Int { return i * 3 } let nums = [1,2,3,4].map(treble) // closure expression let treble1 = { (i: Int) in return i * 3} let newNums = [1,2,3,4].map(treble1) let isEven = { $0%2 == 0} as Int8 -> Bool isEven(4) // IntegerLiteralConvertible //protocol IntegerLiteralConvertible { // typealias IntegerLiteralType // // init(IntegerLiteral value: Self.IntegerLiteralType) //} func isEven<T: IntegerType>(i: T) -> Bool { return i%2 == 0 } // 将一个generic funtion 赋值给一个变量必须指定 Type let int8isEven: Int8 -> Bool = isEven // Tips: 闭包是一种特殊的方法(匿名方法),闭包与方法主要的不同点是`闭包`能够捕获变量 // 一个粒子 // 利用 Objective-C 的 runtime let last = "lastName", first = "firstName" let people = [ [first: "Neil", last: "Chao"], [first: "Yu",last: "Yu"], [first: "Chao", last: "Race"] ] // //let lastDescriptor = NSSortDescriptor(key: last, ascending: true, selector: "localizedCaseInsensitiveCompare:") //let firstDescriptor = NSSortDescriptor(key: first, ascending: true, selector: "localizedCaseInsensitiveCompare:") // //let descriptor = [lastDescriptor, firstDescriptor] //let sortedArray = (people as NSArray).sortedArrayUsingDescriptors(descriptor) var strings = ["Hello", "hallo", "Hallo","hello"] strings.sortInPlace { return $0.localizedCaseInsensitiveCompare($1) == .OrderedAscending } let sortedArrays = people.sort { $0[last] < $1[last] } sortedArrays let sortedArray = people.sort { (lhs, rhs) -> Bool in return rhs[first].flatMap{ lhs[first]?.localizedCaseInsensitiveCompare($0) } == .OrderedAscending }
b3b1e492c31b5ad9d64b5294bd2ce18c
22.926471
115
0.687154
false
false
false
false
honghaoz/CrackingTheCodingInterview
refs/heads/master
Swift/LeetCode/Array/80_Remove Duplicates from Sorted Array II.swift
mit
1
// // 80. Remove Duplicates from Sorted Array II.swift // LeetCode // // Created by Honghao Zhang on 2016-10-20. // Copyright © 2016 Honghaoz. All rights reserved. // import Foundation //Follow up for "Remove Duplicates": //What if duplicates are allowed at most twice? // //For example, //Given sorted array nums = [1,1,1,2,2,3], // //Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3. It doesn't matter what you leave beyond the new length. class Num80_RemoveDuplicatesFromSortedArrayII: Solution { func removeDuplicates(_ nums: inout [Int]) -> Int { guard nums.count > 2 else { return nums.count } var lastIndex1: Int = 0 var lastIndex2: Int = 1 for i in 2 ..< nums.count { let num = nums[i] if num != nums[lastIndex2] || (num == nums[lastIndex2] && num != nums[lastIndex1]) { lastIndex1 += 1 lastIndex2 += 1 nums[lastIndex2] = num continue } } return lastIndex2 + 1 } func removeDuplicates2(_ nums: inout [Int]) -> Int { guard nums.count > 0 else { return 0 } if nums.count == 1 { return 1 } var last = 1 for i in 2..<nums.count { let n = nums[i] if n != nums[last] { last += 1 nums[last] = n } else if nums[last - 1] != nums[last] { last += 1 nums[last] = n } } return last + 1 } func test() { // [] -> [] var nums: [Int] = [] var expected: [Int] = [] assert(removeDuplicates(&nums) == expected.count) assert(checkEqual(nums1: nums, nums2: expected, firstCount: expected.count)) // [1] -> [1] nums = [1] expected = [1] assert(removeDuplicates(&nums) == expected.count) assert(checkEqual(nums1: nums, nums2: expected, firstCount: expected.count)) // [1, 1] -> [1, 1] nums = [1, 1] expected = [1, 1] assert(removeDuplicates(&nums) == expected.count) assert(checkEqual(nums1: nums, nums2: expected, firstCount: expected.count)) // [1, 2] -> [1, 2] nums = [1, 2] expected = [1, 2] assert(removeDuplicates(&nums) == expected.count) assert(checkEqual(nums1: nums, nums2: expected, firstCount: expected.count)) // [1, 1, 1] -> [1, 1] nums = [1, 1, 1] expected = [1, 1] assert(removeDuplicates(&nums) == expected.count) assert(checkEqual(nums1: nums, nums2: expected, firstCount: expected.count)) // [1, 1, 2] -> [1, 1, 2] nums = [1, 1, 2] expected = [1, 1, 2] assert(removeDuplicates(&nums) == expected.count) assert(checkEqual(nums1: nums, nums2: expected, firstCount: expected.count)) // [1, 2, 2] -> [1, 2, 2] nums = [1, 2, 2] expected = [1, 2, 2] assert(removeDuplicates(&nums) == expected.count) assert(checkEqual(nums1: nums, nums2: expected, firstCount: expected.count)) // [1, 1, 1, 1] -> [1, 1] nums = [1, 1, 1, 1] expected = [1, 1] assert(removeDuplicates(&nums) == expected.count) assert(checkEqual(nums1: nums, nums2: expected, firstCount: expected.count)) // [1, 1, 1, 2] -> [1, 1, 2] nums = [1, 1, 1, 2] expected = [1, 1, 2] assert(removeDuplicates(&nums) == expected.count) assert(checkEqual(nums1: nums, nums2: expected, firstCount: expected.count)) // [1, 1, 2, 2] -> [1, 1, 2, 2] nums = [1, 1, 2, 2] expected = [1, 1, 2, 2] assert(removeDuplicates(&nums) == expected.count) assert(checkEqual(nums1: nums, nums2: expected, firstCount: expected.count)) // [1, 2, 2, 2] -> [1, 2, 2] nums = [1, 2, 2, 2] expected = [1, 2, 2] assert(removeDuplicates(&nums) == expected.count) assert(checkEqual(nums1: nums, nums2: expected, firstCount: expected.count)) } func checkEqual(nums1: [Int], nums2: [Int], firstCount: Int) -> Bool { guard nums1.count >= firstCount && nums2.count >= firstCount else { return false } for i in 0..<firstCount { if nums1[i] != nums2[i] { return false } } return true } }
7cee29c610f4e85ea53c14aec6889cc0
28.166667
158
0.58559
false
false
false
false
Ivacker/swift
refs/heads/master
test/decl/enum/objc_enum_multi_file.swift
apache-2.0
20
// RUN: not %target-swift-frontend -module-name main %s -primary-file %S/Inputs/objc_enum_multi_file_helper.swift -parse -D NO_RAW_TYPE 2>&1 | FileCheck -check-prefix=NO_RAW_TYPE %s // RUN: not %target-swift-frontend -module-name main %s -primary-file %S/Inputs/objc_enum_multi_file_helper.swift -parse -D BAD_RAW_TYPE 2>&1 | FileCheck -check-prefix=BAD_RAW_TYPE %s // RUN: not %target-swift-frontend -module-name main %s -primary-file %S/Inputs/objc_enum_multi_file_helper.swift -parse -D NON_INT_RAW_TYPE 2>&1 | FileCheck -check-prefix=NON_INT_RAW_TYPE %s // RUN: not %target-swift-frontend -module-name main %s -primary-file %S/Inputs/objc_enum_multi_file_helper.swift -parse -D NO_CASES 2>&1 | FileCheck -check-prefix=NO_CASES %s // RUN: not %target-swift-frontend -module-name main %s -primary-file %S/Inputs/objc_enum_multi_file_helper.swift -parse -D DUPLICATE_CASES 2>&1 | FileCheck -check-prefix=DUPLICATE_CASES %s // Note that the *other* file is the primary file in this test! #if NO_RAW_TYPE // NO_RAW_TYPE: :[[@LINE+1]]:12: error: '@objc' enum must declare an integer raw type @objc enum TheEnum { case A } #elseif BAD_RAW_TYPE // BAD_RAW_TYPE: :[[@LINE+1]]:22: error: '@objc' enum raw type 'Array<Int>' is not an integer type @objc enum TheEnum : Array<Int> { case A } #elseif NON_INT_RAW_TYPE // NON_INT_RAW_TYPE: :[[@LINE+1]]:22: error: '@objc' enum raw type 'Float' is not an integer type @objc enum TheEnum : Float { case A = 0.0 } #elseif NO_CASES // NO_CASES: :[[@LINE+1]]:22: error: an enum with no cases cannot declare a raw type @objc enum TheEnum : Int32 { static var A: TheEnum! { return nil } } #elseif DUPLICATE_CASES @objc enum TheEnum : Int32 { case A case B = 0 // DUPLICATE_CASES: :[[@LINE-1]]:12: error: raw value for enum case is not unique // DUPLICATE_CASES: :[[@LINE-3]]:8: note: raw value previously used here // DUPLICATE_CASES: :[[@LINE-4]]:8: note: raw value implicitly auto-incremented from zero } #else enum TheEnum: Invalid { // should never be hit case A } #endif
157c1dc605c7cbd21a32866da6eaac83
43.23913
191
0.695823
false
false
false
false
yangchenghu/actor-platform
refs/heads/master
actor-apps/app-ios/ActorApp/View/UATableData.swift
mit
1
// // Copyright (c) 2014-2015 Actor LLC. <https://actor.im> // import Foundation class UABaseTableData : NSObject, UITableViewDataSource, UITableViewDelegate { static let ReuseCommonCell = "_CommonCell"; static let ReuseTextCell = "_TextCell"; static let ReuseTitledCell = "_TitledCell"; private var tableView: UITableView private var sections: [UASection] = [UASection]() var tableScrollClosure: ((tableView: UITableView) -> ())? init(tableView: UITableView) { self.tableView = tableView super.init() self.tableView.registerClass(CommonCell.self, forCellReuseIdentifier: UABaseTableData.ReuseCommonCell) self.tableView.registerClass(TextCell.self, forCellReuseIdentifier: UABaseTableData.ReuseTextCell) self.tableView.registerClass(TitledCell.self, forCellReuseIdentifier: UABaseTableData.ReuseTitledCell) self.tableView.dataSource = self self.tableView.delegate = self } func registerClass(cellClass: AnyClass, forCellReuseIdentifier identifier: String) { self.tableView.registerClass(cellClass, forCellReuseIdentifier: identifier) } func addSection(autoSeparator: Bool = false) -> UASection { let res = UASection(tableView: tableView, index: sections.count) res.autoSeparators = autoSeparator sections.append(res) return res } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return sections.count } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return sections[section].itemsCount() } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { return sections[indexPath.section].buildCell(tableView, cellForRowAtIndexPath: indexPath) } func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { let text = sections[section].headerText if text != nil { return localized(text!) } else { return text } } func tableView(tableView: UITableView, titleForFooterInSection section: Int) -> String? { let text = sections[section].footerText if text != nil { return localized(text!) } else { return text } } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return CGFloat(sections[indexPath.section].cellHeight(tableView, cellForRowAtIndexPath: indexPath)) } func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return false } func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { return false } func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle { return UITableViewCellEditingStyle.None } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let section = sections[indexPath.section] if (section.canSelect(tableView, cellForRowAtIndexPath: indexPath)) { if section.select(tableView, cellForRowAtIndexPath: indexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) } } else { tableView.deselectRowAtIndexPath(indexPath, animated: true) } } func tableView(tableView: UITableView, canPerformAction action: Selector, forRowAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) -> Bool { if action == "copy:" { let section = sections[indexPath.section] return section.canCopy(tableView, cellForRowAtIndexPath: indexPath) } return false } func tableView(tableView: UITableView, shouldShowMenuForRowAtIndexPath indexPath: NSIndexPath) -> Bool { let section = sections[indexPath.section] return section.canCopy(tableView, cellForRowAtIndexPath: indexPath) } func tableView(tableView: UITableView, performAction action: Selector, forRowAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) { if action == "copy:" { let section = sections[indexPath.section] if section.canCopy(tableView, cellForRowAtIndexPath: indexPath) { section.copy(tableView, cellForRowAtIndexPath: indexPath) } } } func scrollViewDidScroll(scrollView: UIScrollView) { if (tableView == scrollView) { self.tableScrollClosure?(tableView: tableView) } } } class UATableData : UABaseTableData { func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return CGFloat(sections[section].headerHeight) } func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return CGFloat(sections[section].footerHeight) } func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { if (sections[section].headerText == nil) { return UIView() } else { return nil } } func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { if (sections[section].footerText == nil) { return UIView() } else { return nil } } } class UAGrouppedTableData : UABaseTableData { func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { let header: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView header.textLabel!.textColor = MainAppTheme.list.sectionColor } func tableView(tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) { let header: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView header.textLabel!.textColor = MainAppTheme.list.hintColor } } class UASection { var headerHeight: Double = 0 var footerHeight: Double = 0 var headerText: String? = nil var footerText: String? = nil var index: Int var autoSeparatorTopOffset: Int = 0 var autoSeparatorBottomOffset: Int = 0 var autoSeparators: Bool = false var autoSeparatorsInset: CGFloat = 15.0 private var tableView: UITableView var regions: [UARegion] = [UARegion]() init(tableView: UITableView, index: Int) { self.tableView = tableView self.index = index } func setSeparatorsTopOffset(offset: Int) -> UASection { self.autoSeparatorTopOffset = offset return self } func setFooterText(footerText: String) -> UASection { self.footerText = footerText return self } func setHeaderText(headerText: String) -> UASection { self.headerText = headerText return self } func setFooterHeight(footerHeight: Double) -> UASection { self.footerHeight = footerHeight return self } func setHeaderHeight(headerHeight: Double) -> UASection { self.headerHeight = headerHeight return self } func addActionCell(title: String, actionClosure: (() -> Bool)) -> UACommonCellRegion { return addCommonCell() .setContent(title) .setAction(actionClosure) .setStyle(.Action) } func addDangerCell(title: String, actionClosure: (() -> Bool)) -> UACommonCellRegion { return addCommonCell() .setContent(title) .setAction(actionClosure) .setStyle(.Destructive) } func addNavigationCell(title: String, actionClosure: (() -> Bool)) -> UACommonCellRegion { return addCommonCell() .setContent(title) .setAction(actionClosure) .setStyle(.Navigation) } func addCommonCell(closure: (cell: CommonCell)->()) -> UACommonCellRegion { let res = UACommonCellRegion(section: self, closure: closure) regions.append(res) return res } func addCommonCell() -> UACommonCellRegion { let res = UACommonCellRegion(section: self) regions.append(res) return res } func addTextCell(title: String, text: String) -> UATextCellRegion { let res = UATextCellRegion(title: title, text: text, section: self) regions.append(res) return res } func addTitledCell(title: String, text: String) -> UATitledCellRegion { let res = UATitledCellRegion(title: title, text: text, section: self) regions.append(res) return res } func addCustomCell(closure: (tableView:UITableView, indexPath: NSIndexPath) -> UITableViewCell) -> UACustomCellRegion { let res = UACustomCellRegion(section: self, closure: closure) regions.append(res) return res } func addCustomCells(height: CGFloat,countClosure: () -> Int, closure: (tableView:UITableView, index: Int, indexPath: NSIndexPath) -> UITableViewCell) -> UACustomCellsRegion { let res = UACustomCellsRegion(height:height, countClosure: countClosure, closure: closure, section: self) regions.append(res) return res } func itemsCount() -> Int { var res = 0 for r in regions { res += r.itemsCount() } return res } private func getRegion(indexPath: NSIndexPath) -> RegionSearchResult { var prevLength = 0 for r in regions { if (prevLength <= indexPath.row && indexPath.row < prevLength + r.itemsCount()) { return RegionSearchResult(region: r, index: indexPath.row - prevLength) } prevLength += r.itemsCount() } fatalError("Inconsistent cell") } func buildCell(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let r = getRegion(indexPath) let res = r.region.buildCell(tableView, index: r.index, indexPath: indexPath) if autoSeparators { if let cell = res as? UATableViewCell { // Top separator // Showing only for top cell cell.topSeparatorLeftInset = 0 cell.topSeparatorVisible = indexPath.row == autoSeparatorTopOffset if indexPath.row >= autoSeparatorTopOffset { cell.bottomSeparatorVisible = true if indexPath.row == itemsCount() - 1 { cell.bottomSeparatorLeftInset = 0 } else { cell.bottomSeparatorLeftInset = autoSeparatorsInset } } else { // too high cell.bottomSeparatorVisible = false } } } return res } func cellHeight(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { let r = getRegion(indexPath) return r.region.cellHeight(r.index, width: tableView.bounds.width) } func canSelect(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> Bool { let r = getRegion(indexPath) return r.region.canSelect(r.index) } func select(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> Bool { let r = getRegion(indexPath) return r.region.select(r.index) } func canCopy(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> Bool { let r = getRegion(indexPath) return r.region.canCopy(r.index) } func copy(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) { let r = getRegion(indexPath) r.region.copy(r.index) } } class UARegion { private var section: UASection init(section: UASection) { self.section = section } func itemsCount() -> Int { fatalError("Not implemented") } func cellHeight(index: Int, width: CGFloat) -> CGFloat { fatalError("Not implemented") } func buildCell(tableView: UITableView, index: Int, indexPath: NSIndexPath) -> UITableViewCell { fatalError("Not implemented") } func canSelect(index: Int) -> Bool { return false } func select(index: Int) -> Bool { fatalError("Not implemented") } func canCopy(index: Int) -> Bool { return false } func copy(index: Int) { fatalError("Not implemented") } } class UASingleCellRegion : UARegion { private var copyData: String? private var height: CGFloat = 44.0 private var actionClosure: (() -> Bool)? private var longActionClosure: (() -> ())? func setAction(actionClosure: () -> Bool) -> UASingleCellRegion { self.actionClosure = actionClosure return self } func setCopy(copyData: String) -> UASingleCellRegion { self.copyData = copyData return self } override func itemsCount() -> Int { return 1 } func setHeight(height: CGFloat) -> UASingleCellRegion { self.height = height return self } override func canSelect(index: Int) -> Bool { return actionClosure != nil } override func select(index: Int) -> Bool { return actionClosure!() } override func cellHeight(index: Int, width: CGFloat) -> CGFloat { return height } override func canCopy(index: Int) -> Bool { return copyData != nil } override func copy(index: Int) { UIPasteboard.generalPasteboard().string = copyData } } class UACustomCellRegion : UASingleCellRegion { private var closure: (tableView:UITableView, indexPath: NSIndexPath) -> UITableViewCell init(section: UASection, closure: (tableView:UITableView, indexPath: NSIndexPath) -> UITableViewCell) { self.closure = closure super.init(section: section) } override func buildCell(tableView: UITableView, index: Int, indexPath: NSIndexPath) -> UITableViewCell { return closure(tableView: tableView, indexPath: indexPath) } } class UACustomCellsRegion : UARegion { private var canCopy = false private var height: CGFloat private var countClosure: () -> Int private var closure: (tableView:UITableView, index: Int, indexPath: NSIndexPath) -> UITableViewCell private var actionClosure: ((index: Int) -> Bool)? init(height: CGFloat, countClosure: () -> Int, closure: (tableView:UITableView, index: Int, indexPath: NSIndexPath) -> UITableViewCell, section: UASection) { self.height = height self.countClosure = countClosure self.closure = closure super.init(section: section) } func setAction(actionClosure: (index: Int) -> Bool) -> UACustomCellsRegion { self.actionClosure = actionClosure return self } func setCanCopy(canCopy: Bool) -> UACustomCellsRegion { self.canCopy = canCopy return self } override func itemsCount() -> Int { return countClosure() } override func cellHeight(index: Int, width: CGFloat) -> CGFloat { return height } override func canSelect(index: Int) -> Bool { return actionClosure != nil } override func select(index: Int) -> Bool { return actionClosure!(index: index) } override func buildCell(tableView: UITableView, index: Int, indexPath: NSIndexPath) -> UITableViewCell { return closure(tableView: tableView, index: index, indexPath: indexPath) } override func canCopy(index: Int) -> Bool { return canCopy } } class UATextCellRegion: UASingleCellRegion { private var text: String private var title: String private var enableNavigation: Bool = false private var isAction: Bool = false init(title: String, text: String, section: UASection) { self.text = text self.title = title super.init(section: section) } func setEnableNavigation(enableNavigation: Bool) -> UATextCellRegion{ self.enableNavigation = enableNavigation return self } func setContent(title: String, text: String) { self.text = text self.title = title } func setIsAction(isAction: Bool) { self.isAction = isAction } override func buildCell(tableView: UITableView, index: Int, indexPath: NSIndexPath) -> UITableViewCell { let res = tableView.dequeueReusableCellWithIdentifier(UABaseTableData.ReuseTextCell, forIndexPath: indexPath) as! TextCell res.setTitle(title, content: text) res.setAction(isAction) if enableNavigation { res.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator } else { res.accessoryType = UITableViewCellAccessoryType.None } return res } override func cellHeight(index: Int, width: CGFloat) -> CGFloat { return TextCell.measure(text, width: width, enableNavigation: enableNavigation) } } class UATitledCellRegion: UASingleCellRegion { private var title: String private var text: String init(title: String, text: String, section: UASection) { self.title = title self.text = text super.init(section: section) } override func buildCell(tableView: UITableView, index: Int, indexPath: NSIndexPath) -> UITableViewCell { let res = tableView.dequeueReusableCellWithIdentifier(UABaseTableData.ReuseTitledCell, forIndexPath: indexPath) as! TitledCell res.setTitle(title, content: text) return res } override func cellHeight(index: Int, width: CGFloat) -> CGFloat { return 55 } override func canCopy(index: Int) -> Bool { return true } override func copy(index: Int) { // Implemented in cell } } class UACommonCellRegion : UARegion { private var closure: ((cell: CommonCell) -> ())? private var actionClosure: (() -> Bool)? private var style: CommonCellStyle? = nil private var content: String? = nil private var leftInset: Double = 0.0 private var bottomSeparatorLeftInset: Double = 0.0 private var topSeparatorLeftInset: Double = 0.0 private var bottomSeparator: Bool = true private var topSeparator: Bool = true init(section: UASection, closure: (cell: CommonCell) -> ()) { self.closure = closure super.init(section: section) } override init(section: UASection) { super.init(section: section) } func setModificator(closure: (cell: CommonCell) -> ()) -> UACommonCellRegion { self.closure = closure return self } func setAction(actionClosure: (() -> Bool)) -> UACommonCellRegion { self.actionClosure = actionClosure return self } func setStyle(style: CommonCellStyle) -> UACommonCellRegion { self.style = style return self } func setContent(content: String) -> UACommonCellRegion { self.content = content return self } func setLeftInset(leftInset: Double) -> UACommonCellRegion { self.leftInset = leftInset return self } func showBottomSeparator(inset: Double) -> UACommonCellRegion { self.bottomSeparator = true self.bottomSeparatorLeftInset = inset return self } func hideBottomSeparator() -> UACommonCellRegion { self.bottomSeparator = false return self } func showTopSeparator(inset: Double) -> UACommonCellRegion { self.topSeparator = true self.topSeparatorLeftInset = inset return self } func hideTopSeparator() -> UACommonCellRegion { self.topSeparator = false return self } override func itemsCount() -> Int { return 1 } override func cellHeight(index: Int, width: CGFloat) -> CGFloat { return 44.0 } override func canSelect(index: Int) -> Bool { return actionClosure != nil } override func select(index: Int) -> Bool { return actionClosure!() } override func buildCell(tableView: UITableView, index: Int, indexPath: NSIndexPath) -> UITableViewCell { let res = tableView .dequeueReusableCellWithIdentifier( UABaseTableData.ReuseCommonCell, forIndexPath: indexPath) as! CommonCell res.selectionStyle = canSelect(index) ? UITableViewCellSelectionStyle.Blue : UITableViewCellSelectionStyle.None res.separatorInset = UIEdgeInsets(top: 0, left: CGFloat(leftInset), bottom: 0, right: 0) if (content != nil) { res.setContent(NSLocalizedString(content!, comment: "Cell Title")) } if (style != nil) { res.style = style! } res.bottomSeparatorVisible = bottomSeparator res.bottomSeparatorLeftInset = CGFloat(bottomSeparatorLeftInset) res.topSeparatorVisible = topSeparator res.topSeparatorLeftInset = CGFloat(topSeparatorLeftInset) closure?(cell: res) return res } } class RegionSearchResult { let region: UARegion let index: Int init(region: UARegion, index: Int) { self.region = region self.index = index } }
3bd0ff3a7e5a64cc039cc452c5f7cd3e
30.779539
178
0.631648
false
false
false
false
muccy/Ferrara
refs/heads/master
Source/Match.swift
mit
1
import Foundation /// How two objects match /// /// - none: No match /// - change: Partial match (same object has changed) /// - equal: Complete match public enum Match: String, CustomDebugStringConvertible { case none = "❌" case change = "🔄" case equal = "✅" public var debugDescription: String { return self.rawValue } } /// The way two objects are compared to spot no match, partial match or complete match public protocol Matchable { func match(with object: Any) -> Match } public extension Matchable where Self: Equatable { public func match(with object: Any) -> Match { if let object = object as? Self { return self == object ? .equal : .none } return .none } } public extension Equatable where Self: Matchable { public static func ==(lhs: Self, rhs: Self) -> Bool { return lhs.match(with: rhs) == .equal } }
5a62bd6d0c446bbfa84a638df9f4411d
24
86
0.624865
false
false
false
false
JGiola/swift
refs/heads/main
test/attr/require_explicit_availability.swift
apache-2.0
5
// Test the -require-explicit-availability flag // REQUIRES: OS=macosx // RUN: %swiftc_driver -typecheck -parse-as-library -target %target-cpu-apple-macosx10.10 -Xfrontend -verify -require-explicit-availability -require-explicit-availability-target "macOS 10.10" %s public struct S { // expected-warning {{public declarations should have an availability attribute when building with -require-explicit-availability}} public func method() { } } @available(macOS, unavailable) public struct UnavailableStruct { public func okMethod() { } } public func foo() { bar() } // expected-warning {{public declarations should have an availability attribute when building with -require-explicit-availability}} {{1-1=@available(macOS 10.10, *)\n}} @usableFromInline func bar() { } // expected-warning {{public declarations should have an availability attribute when building with -require-explicit-availability}} {{1-1=@available(macOS 10.10, *)\n}} @available(macOS 10.1, *) public func ok() { } @available(macOS, unavailable) public func unavailableOk() { } @available(macOS, deprecated: 10.10) public func missingIntro() { } // expected-warning {{public declarations should have an availability attribute when building with -require-explicit-availability}} {{1-1=@available(macOS 10.10, *)\n}} @available(iOS 9.0, *) public func missingTargetPlatform() { } // expected-warning {{public declarations should have an availability attribute when building with -require-explicit-availability}} {{1-1=@available(macOS 10.10, *)\n}} func privateFunc() { } @_alwaysEmitIntoClient public func alwaysEmitted() { } @available(macOS 10.1, *) struct SOk { public func okMethod() { } } precedencegroup MediumPrecedence {} infix operator + : MediumPrecedence public func +(lhs: S, rhs: S) -> S { } // expected-warning {{public declarations should have an availability attribute when building with -require-explicit-availability}} {{1-1=@available(macOS 10.10, *)\n}} public enum E { } // expected-warning {{public declarations should have an availability attribute when building with -require-explicit-availability}} {{1-1=@available(macOS 10.10, *)\n}} @available(macOS, unavailable) public enum UnavailableEnum { case caseOk } public class C { } // expected-warning {{public declarations should have an availability attribute when building with -require-explicit-availability}} {{1-1=@available(macOS 10.10, *)\n}} @available(macOS, unavailable) public class UnavailableClass { public func okMethod() { } } public protocol P { } // expected-warning {{public declarations should have an availability attribute when building with -require-explicit-availability}} {{1-1=@available(macOS 10.10, *)\n}} @available(macOS, unavailable) public protocol UnavailableProto { func requirementOk() } private protocol PrivateProto { } extension S { // expected-warning {{public declarations should have an availability attribute when building with -require-explicit-availability}} {{1-1=@available(macOS 10.10, *)\n}} public func warnForPublicMembers() { } // expected-warning {{public declarations should have an availability attribute when building with -require-explicit-availability}} {{3-3=@available(macOS 10.10, *)\n }} } @available(macOS 10.1, *) extension S { public func okWhenTheExtensionHasAttribute() { } } @available(macOS, unavailable) extension S { public func okWhenTheExtensionIsUnavailable() { } } extension S { internal func dontWarnWithoutPublicMembers() { } private func dontWarnWithoutPublicMembers1() { } } // An empty extension should be ok. extension S { } extension S : P { // expected-warning {{public declarations should have an availability attribute when building with -require-explicit-availability}} {{1-1=@available(macOS 10.10, *)\n}} } extension S : PrivateProto { } open class OpenClass { } // expected-warning {{public declarations should have an availability attribute when building with -require-explicit-availability}} {{1-1=@available(macOS 10.10, *)\n}} private class PrivateClass { } extension PrivateClass { } @available(macOS 10.1, *) public protocol PublicProtocol { } @available(macOS 10.1, *) extension S : PublicProtocol { } @_spi(SPIsAreOK) public func spiFunc() { } @_spi(SPIsAreOK) public struct spiStruct { public func spiMethod() {} } extension spiStruct { public func spiExtensionMethod() {} } public var publicVar = S() // expected-warning {{public declarations should have an availability attribute when building with -require-explicit-availability}} {{1-1=@available(macOS 10.10, *)\n}} @available(macOS 10.10, *) public var publicVarOk = S() @available(macOS, unavailable) public var unavailablePublicVarOk = S() public var (a, b) = (S(), S()) // expected-warning {{public declarations should have an availability attribute when building with -require-explicit-availability}} {{1-1=@available(macOS 10.10, *)\n}} @available(macOS 10.10, *) public var (c, d) = (S(), S()) public var _ = S() // expected-error {{global variable declaration does not bind any variables}} public var implicitGet: S { // expected-warning {{public declarations should have an availability attribute when building with -require-explicit-availability}} {{1-1=@available(macOS 10.10, *)\n}} return S() } @available(macOS 10.10, *) public var implicitGetOk: S { return S() } @available(macOS, unavailable) public var unavailableImplicitGetOk: S { return S() } public var computed: S { // expected-warning {{public declarations should have an availability attribute when building with -require-explicit-availability}} {{1-1=@available(macOS 10.10, *)\n}} get { return S() } set { } } public var computedHalf: S { // expected-warning {{public declarations should have an availability attribute when building with -require-explicit-availability}} {{1-1=@available(macOS 10.10, *)\n}} @available(macOS 10.10, *) get { return S() } set { } } // FIXME the following warning is not needed. public var computedOk: S { // expected-warning {{public declarations should have an availability attribute when building with -require-explicit-availability}} {{1-1=@available(macOS 10.10, *)\n}} @available(macOS 10.10, *) get { return S() } @available(macOS 10.10, *) set { } } @available(macOS 10.10, *) public var computedOk1: S { get { return S() } set { } } public class SomeClass { // expected-warning {{public declarations should have an availability attribute when building with -require-explicit-availability}} {{1-1=@available(macOS 10.10, *)\n}} public init () {} public subscript(index: String) -> Int { get { return 42; } set(newValue) { } } } extension SomeClass { // expected-warning {{public declarations should have an availability attribute when building with -require-explicit-availability}} {{1-1=@available(macOS 10.10, *)\n}} public convenience init(s : S) {} // expected-warning {{public declarations should have an availability attribute when building with -require-explicit-availability}} {{3-3=@available(macOS 10.10, *)\n }} @available(macOS 10.10, *) public convenience init(s : SomeClass) {} public subscript(index: Int) -> Int { // expected-warning {{public declarations should have an availability attribute when building with -require-explicit-availability}} {{3-3=@available(macOS 10.10, *)\n }} get { return 42; } set(newValue) { } } @available(macOS 10.10, *) public subscript(index: S) -> Int { get { return 42; } set(newValue) { } } } @available(iOS 13.0, macOS 10.15, watchOS 6.0, tvOS 13.0, macCatalyst 13.0, *) public struct StructWithImplicitMembers { } extension StructWithImplicitMembers: Hashable { } // expected-note @-1 {{add @available attribute to enclosing extension}} // expected-warning @-2 {{public declarations should have an availability attribute when building with -require-explicit-availability}} // expected-error @-3 {{'StructWithImplicitMembers' is only available in macOS 10.15 or newer}}
ae063bf538db633d8b6f454890fc481d
37.047619
211
0.72816
false
false
false
false
KimiMengjie/AudioDemo
refs/heads/master
QQ音乐/QQ音乐/Classes/QQList/Controller/QQLitsTableViewController.swift
mit
1
// // QQLitsTableViewController.swift // QQ音乐 // // Created by kimi on 16/10/7. // Copyright © 2016年 kimi. All rights reserved. // import UIKit class QQLitsTableViewController: UITableViewController { 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 numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 0 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 0 } /* override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> 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, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .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, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> 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 prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
2a0daed3562fef9f6debcb33c5a5b086
31.8
136
0.669769
false
false
false
false
nicolastinkl/swift
refs/heads/master
AdventureBuildingaSpriteKitgameusingSwift/Adventure/Adventure Shared/Sprites/HeroCharacter.swift
mit
1
/* Copyright (C) 2014 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: Defines the common class for hero characters */ import SpriteKit let kCharacterCollisionRadius: CGFloat = 40.0 let kHeroProjectileSpeed: CGFloat = 480.0 let kHeroProjectileLifetime: NSTimeInterval = 1.0 let kHeroProjectileFadeOutTime: NSTimeInterval = 0.6 class HeroCharacter: Character { var player: Player init(atPosition position: CGPoint, withTexture texture: SKTexture? = nil, player: Player) { self.player = player super.init(texture: texture, atPosition: position) zRotation = CGFloat(M_PI) zPosition = -0.25 name = "Hero" } override func configurePhysicsBody() { physicsBody = SKPhysicsBody(circleOfRadius: kCharacterCollisionRadius) physicsBody.categoryBitMask = ColliderType.Hero.toRaw() physicsBody.collisionBitMask = ColliderType.GoblinOrBoss.toRaw() | ColliderType.Hero.toRaw() | ColliderType.Wall.toRaw() | ColliderType.Cave.toRaw() physicsBody.contactTestBitMask = ColliderType.GoblinOrBoss.toRaw() } override func collidedWith(other: SKPhysicsBody) { if other.categoryBitMask & ColliderType.GoblinOrBoss.toRaw() == 0 { return } if let enemy = other.node as? Character { if !enemy.dying { applyDamage(5.0) requestedAnimation = .GetHit } } } override func animationDidComplete(animation: AnimationState) { super.animationDidComplete(animation) switch animation { case .Death: let actions = [SKAction.waitForDuration(4.0), SKAction.runBlock { self.characterScene.heroWasKilled(self) }, SKAction.removeFromParent()] runAction(SKAction.sequence(actions)) case .Attack: fireProjectile() default: () // Do nothing } } // PROJECTILES func fireProjectile() { let projectile = self.projectile()!.copy() as SKSpriteNode projectile.position = position projectile.zRotation = zRotation let emitter = projectileEmitter()!.copy() as SKEmitterNode emitter.targetNode = scene.childNodeWithName("world") projectile.addChild(emitter) characterScene.addNode(projectile, atWorldLayer: .Character) let rot = zRotation let x = -sin(rot) * kHeroProjectileSpeed * CGFloat(kHeroProjectileLifetime) let y = cos(rot) * kHeroProjectileSpeed * CGFloat(kHeroProjectileLifetime) projectile.runAction(SKAction.moveByX(x, y: y, duration: kHeroProjectileLifetime)) let waitAction = SKAction.waitForDuration(kHeroProjectileFadeOutTime) let fadeAction = SKAction.fadeOutWithDuration(kHeroProjectileLifetime - kHeroProjectileFadeOutTime) let removeAction = SKAction.removeFromParent() let sequence = [waitAction, fadeAction, removeAction] projectile.runAction(SKAction.sequence(sequence)) projectile.runAction(projectileSoundAction()) let data: NSMutableDictionary = ["kPlayer" : self.player] projectile.userData = data } func projectile() -> SKSpriteNode? { return nil } func projectileEmitter() -> SKEmitterNode? { return nil } func projectileSoundAction() -> SKAction { return sSharedProjectileSoundAction } class func loadSharedHeroAssets() { sSharedProjectileSoundAction = SKAction.playSoundFileNamed("magicmissile.caf", waitForCompletion: false) } } var sSharedProjectileSoundAction = SKAction() let kPlayer = "kPlayer"
d558ff9b2efe8f4927d1ecd095c838d1
31.711864
156
0.649741
false
false
false
false
prebid/prebid-mobile-ios
refs/heads/master
InternalTestApp/PrebidMobileDemoRendering/Model/TestCasesManager.swift
apache-2.0
1
/*   Copyright 2018-2021 Prebid.org, Inc.  Licensed under the Apache License, Version 2.0 (the "License");  you may not use this file except in compliance with the License.  You may obtain a copy of the License at  http://www.apache.org/licenses/LICENSE-2.0  Unless required by applicable law or agreed to in writing, software  distributed under the License is distributed on an "AS IS" BASIS,  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the License for the specific language governing permissions and  limitations under the License.  */ import Foundation import UIKit import GoogleMobileAds import PrebidMobileGAMEventHandlers import PrebidMobile let nativeStylesCreative = """ <html><body> <style type='text/css'>.sponsored-post { background-color: #fffdeb; font-family: sans-serif; } .content { overflow: hidden; } .thumbnail { width: 50px; height: 50px; float: left; margin: 0 20px 10px 0; background-size: cover; } h1 { font-size: 18px; margin: 0; } a { color: #0086b3; text-decoration: none; } p { font-size: 16px; color: #000; margin: 10px 0 10px 0; } .attribution { color: #000; font-size: 9px; font-weight: bold; display: inline-block; letter-spacing: 2px; background-color: #ffd724; border-radius: 2px; padding: 4px; }</style> <div class="sponsored-post"> <div class="thumbnail"> <img src="hb_native_icon" alt="hb_native_icon" width="50" height="50"></div> <div class="content"> <h1><p>hb_native_title</p></h1> <p>hb_native_body</p> <a target="_blank" href="hb_native_linkurl" class="pb-click">hb_native_cta</a> <div class="attribution">hb_native_brand</div> </div> <img src="hb_native_image" alt="hb_native_image" width="320" height="50"> </div> <script src="https://cdn.jsdelivr.net/npm/prebid-universal-creative@latest/dist/native-trk.js"></script> <script> let pbNativeTagData = {}; pbNativeTagData.pubUrl = "%%PATTERN:url%%"; pbNativeTagData.targetingMap = %%PATTERN:TARGETINGMAP%%; // if not DFP, use these params pbNativeTagData.adId = "%%PATTERN:hb_adid%%"; pbNativeTagData.cacheHost = "%%PATTERN:hb_cache_host%%"; pbNativeTagData.cachePath = "%%PATTERN:hb_cache_path%%"; pbNativeTagData.uuid = "%%PATTERN:hb_cache_id%%"; pbNativeTagData.env = "%%PATTERN:hb_env%%"; pbNativeTagData.hbPb = "%%PATTERN:hb_pb%%"; window.pbNativeTag.startTrackers(pbNativeTagData); </script> </body> </html> """; //NOTE: there is no pbNativeTagData.targetingMap = %%PATTERN:TARGETINGMAP%%; in this creative let nativeStylesCreativeKeys = """ <html><body> <style type='text/css'>.sponsored-post { background-color: #fffdeb; font-family: sans-serif; } .content { overflow: hidden; } .thumbnail { width: 50px; height: 50px; float: left; margin: 0 20px 10px 0; background-size: cover; } h1 { font-size: 18px; margin: 0; } a { color: #0086b3; text-decoration: none; } p { font-size: 16px; color: #000; margin: 10px 0 10px 0; } .attribution { color: #000; font-size: 9px; font-weight: bold; display: inline-block; letter-spacing: 2px; background-color: #ffd724; border-radius: 2px; padding: 4px; }</style> <div class="sponsored-post"> <div class="thumbnail"> <img src="hb_native_icon" alt="hb_native_icon" width="50" height="50"></div> <div class="content"> <h1><p>hb_native_title</p></h1> <p>hb_native_body</p> <a target="_blank" href="hb_native_linkurl" class="pb-click">hb_native_cta</a> <div class="attribution">hb_native_brand</div> </div> <img src="hb_native_image" alt="hb_native_image" width="320" height="50"> </div> <script src="https://cdn.jsdelivr.net/npm/prebid-universal-creative@latest/dist/native-trk.js"></script> <script> let pbNativeTagData = {}; pbNativeTagData.pubUrl = "%%PATTERN:url%%"; // if not DFP, use these params pbNativeTagData.adId = "%%PATTERN:hb_adid%%"; pbNativeTagData.cacheHost = "%%PATTERN:hb_cache_host%%"; pbNativeTagData.cachePath = "%%PATTERN:hb_cache_path%%"; pbNativeTagData.uuid = "%%PATTERN:hb_cache_id%%"; pbNativeTagData.env = "%%PATTERN:hb_env%%"; pbNativeTagData.hbPb = "%%PATTERN:hb_pb%%"; window.pbNativeTag.startTrackers(pbNativeTagData); </script> </body> </html> """; struct TestCaseManager { // {"configId": ["7e2c753a-2aad-49fb-b3b3-9b18018feb67": params1, "0e04335b-c39a-41f8-8f91-24ff13767dcc": params2]} private static var customORTBParams: [String: [String: [String: Any]]] = [:] // MARK: - Public Methods let testCases = TestCaseManager.prebidExamples mutating func parseCustomOpenRTB(openRTBString: String) { guard let data = openRTBString.data(using: .utf8) else { return } guard let jsonArray = try? JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions()) as? [Any] else { return } for param in jsonArray { guard let dictParam = param as? [String:Any], let openRtb = dictParam["openRtb"] as? [String: Any] else { continue } if let configId = dictParam["configId"] as? String { TestCaseManager.customORTBParams["configId", default: [:]][configId] = openRtb } } } /* EXTRA_OPEN_RTB "[ { "auid":"537454411","openRtb":{ "auid":"537454411", "age":23, "url":"https://url.com", "crr":"carrier", "ip":"127.0.0.1", "xid":"007", "gen":"MALE", "buyerid":"buyerid", "publisherName": "publisherName", "customdata":"customdata", "keywords":"keyword1,keyword2", "geo":{ "lat":1.0, "lon":2.0 }, "ext":{ "key1":"string", "key2":1, "object":{ "inner":"value" } } } } ]" */ static func updateUserData(_ openRtb: [String: Any]) { let targeting = Targeting.shared if let age = openRtb["age"] as? Int { targeting.yearOfBirth = age } if let value = openRtb["url"] as? String { targeting.storeURL = value } if let value = openRtb["gen"] as? String { targeting.userGender = TestCaseManager.strToGender(value) } if let value = openRtb["buyerid"] as? String { targeting.buyerUID = value } if let value = openRtb["xid"] as? String { targeting.userID = value } if let value = openRtb["publisherName"] as? String { targeting.publisherName = value } if let value = openRtb["keywords"] as? String { targeting.keywords = value } if let value = openRtb["customdata"] as? String { targeting.userCustomData = value } if let geo = openRtb["geo"] as? [String: Double] { if let lat = geo["lat"], let lon = geo["lon"] { targeting.setLatitude(lat, longitude: lon) } } if let dictExt = openRtb["ext"] as? [String : AnyHashable] { targeting.userExt = dictExt } } // MARK: - Private Methods // MARK: - --== PREBID ==-- private static let prebidExamples: [TestCase] = { return [ // MARK: ---- Banner (In-App) ---- TestCase(title: "Banner 320x50 (In-App)", tags: [.banner, .inapp, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let bannerController = PrebidBannerController(rootController: adapterVC) bannerController.adSizes = [CGSize(width: 320, height: 50)] bannerController.prebidConfigId = "imp-prebid-banner-320-50"; bannerController.storedAuctionResponse = "response-prebid-banner-320-50" adapterVC.setup(adapter: bannerController) setupCustomParams(for: bannerController.prebidConfigId) }), TestCase(title: "Banner Events 320x50 (In-App)", tags: [.banner, .inapp, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } Prebid.shared.prebidServerAccountId = "prebid-stored-request-enabled-events" let bannerController = PrebidBannerController(rootController: adapterVC) bannerController.adSizes = [CGSize(width: 320, height: 50)] bannerController.prebidConfigId = "imp-prebid-banner-320-50"; bannerController.storedAuctionResponse = "response-prebid-banner-320-50" adapterVC.setup(adapter: bannerController) setupCustomParams(for: bannerController.prebidConfigId) }), TestCase(title: "Banner 320x50 (In-App) [noBids]", tags: [.banner, .inapp, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let bannerController = PrebidBannerController(rootController: adapterVC) bannerController.adSizes = [CGSize(width: 320, height: 50)] bannerController.prebidConfigId = "imp-prebid-no-bids" bannerController.storedAuctionResponse = "response-prebid-no-bids" adapterVC.setup(adapter: bannerController) setupCustomParams(for: bannerController.prebidConfigId) }), TestCase(title: "Banner 320x50 (In-App) [Items]", tags: [.banner, .inapp, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let bannerController = PrebidBannerController(rootController: adapterVC) bannerController.prebidConfigId = "imp-prebid-banner-items" bannerController.storedAuctionResponse = "response-prebid-banner-items" bannerController.adSizes = [CGSize(width: 320, height: 50)] adapterVC.setup(adapter: bannerController) setupCustomParams(for: bannerController.prebidConfigId) }), TestCase(title: "Banner 320x50 (In-App) [New Tab]", tags: [.banner, .inapp, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let bannerController = PrebidBannerController(rootController: adapterVC) bannerController.prebidConfigId = "imp-prebid-banner-newtab" bannerController.storedAuctionResponse = "response-prebid-banner-newtab" bannerController.adSizes = [CGSize(width: 320, height: 50)] adapterVC.setup(adapter: bannerController) setupCustomParams(for: bannerController.prebidConfigId) }), TestCase(title: "Banner 320x50 (In-App) [Incorrect VAST]", tags: [.banner, .inapp, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let bannerController = PrebidBannerController(rootController: adapterVC) bannerController.prebidConfigId = "imp-prebid-banner-incorrect-vast" bannerController.storedAuctionResponse = "response-prebid-banner-incorrect-vast" bannerController.adSizes = [CGSize(width: 320, height: 50)] adapterVC.setup(adapter: bannerController) setupCustomParams(for: bannerController.prebidConfigId) }), TestCase(title: "Banner 320x50 (In-App) [DeepLink+]", tags: [.banner, .inapp, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let bannerController = PrebidBannerController(rootController: adapterVC) bannerController.prebidConfigId = "imp-prebid-banner-deeplink" bannerController.storedAuctionResponse = "response-prebid-banner-deeplink" bannerController.adSizes = [CGSize(width: 320, height: 50)] adapterVC.setup(adapter: bannerController) setupCustomParams(for: bannerController.prebidConfigId) }), TestCase(title: "Banner 320x50 (In-App) [Scrollable]", tags: [.banner, .inapp, .server], exampleVCStoryboardID: "ScrollableAdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let bannerController = PrebidBannerController(rootController: adapterVC) bannerController.prebidConfigId = "imp-prebid-banner-320-50" bannerController.storedAuctionResponse = "response-prebid-banner-320-50" bannerController.adSizes = [CGSize(width: 320, height: 50)] adapterVC.setup(adapter: bannerController) setupCustomParams(for: bannerController.prebidConfigId) }), TestCase(title: "Banner 300x250 (In-App)", tags: [.banner, .inapp, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let bannerController = PrebidBannerController(rootController: adapterVC) bannerController.prebidConfigId = "imp-prebid-banner-300-250" bannerController.storedAuctionResponse = "response-prebid-banner-300-250" bannerController.adSizes = [CGSize(width: 300, height: 250)] adapterVC.setup(adapter: bannerController) setupCustomParams(for: bannerController.prebidConfigId) }), TestCase(title: "Banner 728x90 (In-App)", tags: [.banner, .inapp, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let bannerController = PrebidBannerController(rootController: adapterVC) bannerController.prebidConfigId = "imp-prebid-banner-728-90" bannerController.storedAuctionResponse = "response-prebid-banner-728-90" bannerController.adSizes = [CGSize(width: 728, height: 90)] adapterVC.setup(adapter: bannerController) setupCustomParams(for: bannerController.prebidConfigId) }), TestCase(title: "Banner Multisize (In-App)", tags: [.banner, .inapp, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let bannerController = PrebidBannerController(rootController: adapterVC) bannerController.prebidConfigId = "imp-prebid-banner-multisize" bannerController.storedAuctionResponse = "response-prebid-banner-multisize" bannerController.adSizes = [CGSize(width: 320, height: 50), CGSize(width: 728, height: 90)] adapterVC.setup(adapter: bannerController) setupCustomParams(for: bannerController.prebidConfigId) }), TestCase(title: "Banner 320x50 (In-App) ATS", tags: [.banner, .inapp, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } Targeting.shared.eids = [ [ "source" : "liveramp.com", "uids" : [ [ "id": "XY1000bIVBVah9ium-sZ3ykhPiXQbEcUpn4GjCtxrrw2BRDGM" ] ] ] ] let bannerController = PrebidBannerController(rootController: adapterVC) bannerController.prebidConfigId = "imp-prebid-banner-320-50" bannerController.storedAuctionResponse = "response-prebid-banner-320-50" bannerController.adSizes = [CGSize(width: 320, height: 50)] adapterVC.setup(adapter: bannerController) setupCustomParams(for: bannerController.prebidConfigId) }), TestCase(title: "Banner 320x50 (In-App) [SKAdN]", tags: [.banner, .inapp, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let bannerController = PrebidBannerController(rootController: adapterVC) bannerController.prebidConfigId = "imp-prebid-banner-320-50-skadn" bannerController.storedAuctionResponse = "response-prebid-banner-320-50-skadn" bannerController.adSizes = [CGSize(width: 320, height: 50)] adapterVC.setup(adapter: bannerController) setupCustomParams(for: bannerController.prebidConfigId) }), TestCase(title: "Banner 320x50 (In-App) [SKAdN 2.2]", tags: [.banner, .inapp, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let bannerController = PrebidBannerController(rootController: adapterVC) bannerController.prebidConfigId = "imp-prebid-banner-320-50-skadn-v22" bannerController.adSizes = [CGSize(width: 320, height: 50)] bannerController.storedAuctionResponse = "response-prebid-banner-320-50-skadn-v22" adapterVC.setup(adapter: bannerController) setupCustomParams(for: bannerController.prebidConfigId) }), // MARK: ---- Banner (GAM) ---- TestCase(title: "Banner 320x50 (GAM) [OK, AppEvent]", tags: [.banner, .gam, .server, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let gamBannerController = PrebidGAMBannerController(rootController: adapterVC) gamBannerController.gamAdUnitId = "/21808260008/prebid_oxb_320x50_banner" gamBannerController.validAdSizes = [GADAdSizeBanner] gamBannerController.prebidConfigId = "imp-prebid-banner-320-50" gamBannerController.storedAuctionResponse = "response-prebid-banner-320-50" adapterVC.setup(adapter: gamBannerController) setupCustomParams(for: gamBannerController.prebidConfigId) }), TestCase(title: "Banner 320x50 Events (GAM) [OK, AppEvent]", tags: [.banner, .gam, .server, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } Prebid.shared.prebidServerAccountId = "prebid-stored-request-enabled-events" let gamBannerController = PrebidGAMBannerController(rootController: adapterVC) gamBannerController.gamAdUnitId = "/21808260008/prebid_oxb_320x50_banner" gamBannerController.validAdSizes = [GADAdSizeBanner] gamBannerController.prebidConfigId = "imp-prebid-banner-320-50" gamBannerController.storedAuctionResponse = "response-prebid-banner-320-50" adapterVC.setup(adapter: gamBannerController) setupCustomParams(for: gamBannerController.prebidConfigId) }), TestCase(title: "Banner 320x50 (GAM) [OK, GAM Ad]", tags: [.banner, .gam, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let gamBannerController = PrebidGAMBannerController(rootController: adapterVC) gamBannerController.prebidConfigId = "imp-prebid-banner-320-50" gamBannerController.storedAuctionResponse = "response-prebid-banner-320-50" gamBannerController.gamAdUnitId = "/21808260008/prebid_oxb_320x50_banner_static" gamBannerController.validAdSizes = [GADAdSizeBanner] adapterVC.setup(adapter: gamBannerController) setupCustomParams(for: gamBannerController.prebidConfigId) }), TestCase(title: "Banner 320x50 (GAM) [noBids, GAM Ad]", tags: [.banner, .gam, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let gamBannerController = PrebidGAMBannerController(rootController: adapterVC) gamBannerController.prebidConfigId = "imp-prebid-no-bids" gamBannerController.storedAuctionResponse = "response-prebid-no-bids" gamBannerController.gamAdUnitId = "/21808260008/prebid_oxb_320x50_banner_static" gamBannerController.validAdSizes = [GADAdSizeBanner] adapterVC.setup(adapter: gamBannerController) setupCustomParams(for: gamBannerController.prebidConfigId) }), TestCase(title: "Banner 320x50 (GAM) [OK, Random]", tags: [.banner, .gam, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let gamBannerController = PrebidGAMBannerController(rootController: adapterVC) gamBannerController.prebidConfigId = "imp-prebid-banner-320-50" gamBannerController.storedAuctionResponse = "response-prebid-banner-320-50" gamBannerController.gamAdUnitId = "/21808260008/prebid_oxb_320x50_banner_random" gamBannerController.validAdSizes = [GADAdSizeBanner] adapterVC.setup(adapter: gamBannerController) setupCustomParams(for: gamBannerController.prebidConfigId) }), TestCase(title: "Banner 320x50 (GAM) [Random, Respective]", tags: [.banner, .gam, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let gamBannerController = PrebidGAMBannerController(rootController: adapterVC) gamBannerController.prebidConfigId = "imp-prebid-banner-320-50" gamBannerController.storedAuctionResponse = "response-prebid-banner-320-50" gamBannerController.gamAdUnitId = "/21808260008/prebid_oxb_320x50_banner" gamBannerController.validAdSizes = [GADAdSizeBanner] adapterVC.setup(adapter: gamBannerController) setupCustomParams(for: gamBannerController.prebidConfigId) }), TestCase(title: "Banner 300x250 (GAM)", tags: [.banner, .gam, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let gamBannerController = PrebidGAMBannerController(rootController: adapterVC) gamBannerController.prebidConfigId = "imp-prebid-banner-300-250" gamBannerController.storedAuctionResponse = "response-prebid-banner-300-250" gamBannerController.gamAdUnitId = "/21808260008/prebid_oxb_300x250_banner" gamBannerController.validAdSizes = [GADAdSizeMediumRectangle] adapterVC.setup(adapter: gamBannerController) setupCustomParams(for: gamBannerController.prebidConfigId) }), TestCase(title: "Banner 728x90 (GAM)", tags: [.banner, .gam, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let gamBannerController = PrebidGAMBannerController(rootController: adapterVC) gamBannerController.prebidConfigId = "imp-prebid-banner-728-90" gamBannerController.storedAuctionResponse = "response-prebid-banner-728-90" gamBannerController.gamAdUnitId = "/21808260008/prebid_oxb_728x90_banner" gamBannerController.validAdSizes = [GADAdSizeLeaderboard] adapterVC.setup(adapter: gamBannerController) setupCustomParams(for: gamBannerController.prebidConfigId) }), TestCase(title: "Banner Multisize (GAM)", tags: [.banner, .gam, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let gamBannerController = PrebidGAMBannerController(rootController: adapterVC) gamBannerController.prebidConfigId = "imp-prebid-banner-multisize" gamBannerController.storedAuctionResponse = "response-prebid-banner-multisize" gamBannerController.gamAdUnitId = "/21808260008/prebid_oxb_multisize_banner" gamBannerController.validAdSizes = [GADAdSizeBanner, GADAdSizeLeaderboard] adapterVC.setup(adapter: gamBannerController) setupCustomParams(for: gamBannerController.prebidConfigId) }), TestCase(title: "Banner 320x50 (GAM) [Vanilla Prebid Order]", tags: [.banner, .gam, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let gamBannerController = PrebidGAMBannerController(rootController: adapterVC) gamBannerController.prebidConfigId = "imp-prebid-banner-320-50" gamBannerController.storedAuctionResponse = "response-prebid-banner-320-50" gamBannerController.gamAdUnitId = "/21808260008/prebid_android_300x250_banner" gamBannerController.validAdSizes = [GADAdSizeMediumRectangle] adapterVC.setup(adapter: gamBannerController) setupCustomParams(for: gamBannerController.prebidConfigId) }), // MARK: ---- Interstitial (In-App) ---- TestCase(title: "Display Interstitial 320x480 (In-App)", tags: [.interstitial, .inapp, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let interstitialController = PrebidInterstitialController(rootController: adapterVC) interstitialController.adFormats = [.display] interstitialController.prebidConfigId = "imp-prebid-display-interstitial-320-480" interstitialController.storedAuctionResponse="response-prebid-display-interstitial-320-480" adapterVC.setup(adapter: interstitialController) setupCustomParams(for: interstitialController.prebidConfigId) }), TestCase(title: "Display Interstitial 320x480 (In-App) [noBids]", tags: [.interstitial, .inapp, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let interstitialController = PrebidInterstitialController(rootController: adapterVC) interstitialController.adFormats = [.display] interstitialController.prebidConfigId = "imp-prebid-no-bids" interstitialController.storedAuctionResponse="response-prebid-no-bids" adapterVC.setup(adapter: interstitialController) setupCustomParams(for: interstitialController.prebidConfigId) }), TestCase(title: "Display Interstitial 320x480 (In-App) [Presentation]", tags: [.interstitial, .inapp, .server], exampleVCStoryboardID: "PrebidPresentationViewController", configurationClosure: { vc in guard let presentationVC = vc as? PrebidPresentationViewController else { return } presentationVC.adFormats = [.display] presentationVC.prebidConfigId = "imp-prebid-display-interstitial-320-480" presentationVC.storedAuctionResponse = "response-prebid-display-interstitial-320-480" setupCustomParams(for: presentationVC.prebidConfigId) }), TestCase(title: "Display Interstitial Multisize (In-App)", tags: [.interstitial, .inapp, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let interstitialController = PrebidInterstitialController(rootController: adapterVC) interstitialController.adFormats = [.display] interstitialController.prebidConfigId = "imp-prebid-display-interstitial-multisize" interstitialController.storedAuctionResponse = "response-prebid-display-interstitial-multisize" adapterVC.setup(adapter: interstitialController) setupCustomParams(for: interstitialController.prebidConfigId) }), TestCase(title: "Display Interstitial 320x480 (In-App) [SKAdN]", tags: [.interstitial, .inapp, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let interstitialController = PrebidInterstitialController(rootController: adapterVC) interstitialController.adFormats = [.display] interstitialController.prebidConfigId = "imp-prebid-display-interstitial-320-480-skadn" interstitialController.storedAuctionResponse = "response-prebid-display-interstitial-320-480-skadn" adapterVC.setup(adapter: interstitialController) setupCustomParams(for: interstitialController.prebidConfigId) }), TestCase(title: "Display Interstitial 320x480 (In-App) [SKAdN 2.2]", tags: [.interstitial, .inapp, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let interstitialController = PrebidInterstitialController(rootController: adapterVC) interstitialController.adFormats = [.display] interstitialController.prebidConfigId = "imp-prebid-display-interstitial-320-480-skadn" interstitialController.storedAuctionResponse = "response-prebid-display-interstitial-320-480-skadn-v22" adapterVC.setup(adapter: interstitialController) setupCustomParams(for: interstitialController.prebidConfigId) }), // MARK: ---- Multiformat Interstitial (In-App) TestCase(title: "MultiBid Video Interstitial 320x480 (In-App)", tags: [.interstitial, .video, .inapp, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let interstitialController = PrebidInterstitialController(rootController: adapterVC) interstitialController.prebidConfigId = "imp-prebid-interstitial-multiformat" interstitialController.storedAuctionResponse = "response-prebid-interstitial-multiformat" adapterVC.setup(adapter: interstitialController) setupCustomParams(for: interstitialController.prebidConfigId) }), TestCase(title: "Multiformat Interstitial 320x480 (In-App)", tags: [.interstitial, .video, .inapp, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let interstitialController = PrebidInterstitialController(rootController: adapterVC) let prebidStoredAuctionResponses = ["response-prebid-display-interstitial-320-480", "response-prebid-video-interstitial-320-480"] interstitialController.prebidConfigId = "imp-prebid-display-interstitial-320-480" interstitialController.storedAuctionResponse = prebidStoredAuctionResponses.randomElement() ?? prebidStoredAuctionResponses[0] adapterVC.setup(adapter: interstitialController) setupCustomParams(for: interstitialController.prebidConfigId) }), // MARK: ---- Interstitial (GAM) ---- TestCase(title: "Display Interstitial 320x480 (GAM) [OK, AppEvent]", tags: [.interstitial, .gam, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let gamInterstitialController = PrebidGAMInterstitialController(rootController: adapterVC) gamInterstitialController.adFormats = [.display] gamInterstitialController.gamAdUnitId = "/21808260008/prebid_oxb_html_interstitial" gamInterstitialController.prebidConfigId = "imp-prebid-display-interstitial-320-480" gamInterstitialController.storedAuctionResponse = "response-prebid-display-interstitial-320-480" adapterVC.setup(adapter: gamInterstitialController) setupCustomParams(for: gamInterstitialController.prebidConfigId) }), TestCase(title: "Display Interstitial 320x480 (GAM) [OK, Random]", tags: [.interstitial, .gam, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let gamInterstitialController = PrebidGAMInterstitialController(rootController: adapterVC) gamInterstitialController.adFormats = [.display] gamInterstitialController.prebidConfigId = "imp-prebid-display-interstitial-320-480" gamInterstitialController.storedAuctionResponse = "response-prebid-display-interstitial-320-480" gamInterstitialController.gamAdUnitId = "/21808260008/prebid_oxb_html_interstitial_random" adapterVC.setup(adapter: gamInterstitialController) setupCustomParams(for: gamInterstitialController.prebidConfigId) }), TestCase(title: "Display Interstitial 320x480 (GAM) [noBids, GAM Ad]", tags: [.interstitial, .gam, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let gamInterstitialController = PrebidGAMInterstitialController(rootController: adapterVC) gamInterstitialController.adFormats = [.display] gamInterstitialController.prebidConfigId = "imp-prebid-no-bids" gamInterstitialController.storedAuctionResponse = "response-prebid-no-bids" gamInterstitialController.gamAdUnitId = "/21808260008/prebid_oxb_320x480_html_interstitial_static" adapterVC.setup(adapter: gamInterstitialController) setupCustomParams(for: gamInterstitialController.prebidConfigId) }), TestCase(title: "Display Interstitial Multisize (GAM) [OK, AppEvent]", tags: [.interstitial, .gam, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let gamInterstitialController = PrebidGAMInterstitialController(rootController: adapterVC) gamInterstitialController.adFormats = [.display] gamInterstitialController.prebidConfigId = "imp-prebid-display-interstitial-multisize" gamInterstitialController.storedAuctionResponse = "response-prebid-display-interstitial-multisize" gamInterstitialController.gamAdUnitId = "/21808260008/prebid_oxb_html_interstitial" adapterVC.setup(adapter: gamInterstitialController) setupCustomParams(for: gamInterstitialController.prebidConfigId) }), TestCase(title: "Display Interstitial 320x480 (GAM) [Vanilla Prebid Order]", tags: [.interstitial, .gam, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let gamInterstitialController = PrebidGAMInterstitialController(rootController: adapterVC) gamInterstitialController.adFormats = [.display] gamInterstitialController.prebidConfigId = "imp-prebid-display-interstitial-320-480" gamInterstitialController.storedAuctionResponse = "response-prebid-display-interstitial-320-480" gamInterstitialController.gamAdUnitId = "/21808260008/prebid_html_interstitial" adapterVC.setup(adapter: gamInterstitialController) setupCustomParams(for: gamInterstitialController.prebidConfigId) }), // MARK: ---- Multiformat Interstitial (GAM) TestCase(title: "Multiformat Interstitial 320x480 (GAM)", tags: [.interstitial, .video, .gam, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let randomId = [0, 1].randomElement() ?? 0 let interstitialController = PrebidGAMInterstitialController(rootController: adapterVC) let gamAdUnitIds = ["/21808260008/prebid_html_interstitial", "/21808260008/prebid_oxb_interstitial_video"] let prebidStoredAuctionResponses = ["response-prebid-display-interstitial-320-480", "response-prebid-video-interstitial-320-480"] interstitialController.prebidConfigId = "imp-prebid-display-interstitial-320-480" interstitialController.storedAuctionResponse = prebidStoredAuctionResponses[randomId] interstitialController.gamAdUnitId = gamAdUnitIds[randomId] adapterVC.setup(adapter: interstitialController) setupCustomParams(for: interstitialController.prebidConfigId) }), // MARK: ---- Video Interstitial (In-App) ---- TestCase(title: "Video Interstitial 320x480 (In-App)", tags: [.video, .inapp, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let interstitialController = PrebidInterstitialController(rootController: adapterVC) interstitialController.prebidConfigId = "imp-prebid-video-interstitial-320-480" interstitialController.storedAuctionResponse = "response-prebid-video-interstitial-320-480" interstitialController.adFormats = [.video] adapterVC.setup(adapter: interstitialController) setupCustomParams(for: interstitialController.prebidConfigId) }), TestCase(title: "Video Interstitial With Ad Configuration API 320x480 (In-App)", tags: [.video, .inapp, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let interstitialController = PrebidInterstitialController(rootController: adapterVC) interstitialController.prebidConfigId = "imp-prebid-video-interstitial-320-480" interstitialController.storedAuctionResponse = "response-prebid-video-interstitial-320-480-with-ad-configuration" interstitialController.adFormats = [.video] // Custom video configuration interstitialController.maxDuration = 30 interstitialController.closeButtonArea = 0.15 interstitialController.closeButtonPosition = .topLeft interstitialController.skipDelay = 5 adapterVC.setup(adapter: interstitialController) setupCustomParams(for: interstitialController.prebidConfigId) }), TestCase(title: "Video Interstitial With Ad Configuration With End Card API 320x480 (In-App)", tags: [.video, .inapp, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let interstitialController = PrebidInterstitialController(rootController: adapterVC) interstitialController.prebidConfigId = "imp-prebid-video-interstitial-320-480-with-end-card" interstitialController.storedAuctionResponse = "response-prebid-video-interstitial-320-480-with-end-card" interstitialController.adFormats = [.video] // Custom video configuration interstitialController.maxDuration = 30 interstitialController.closeButtonArea = 0.15 interstitialController.closeButtonPosition = .topLeft interstitialController.skipButtonArea = 0.15 interstitialController.skipButtonPosition = .topRight interstitialController.skipDelay = 5 adapterVC.setup(adapter: interstitialController) setupCustomParams(for: interstitialController.prebidConfigId) }), TestCase(title: "Video Interstitial With Ad Configuration Server 320x480 (In-App)", tags: [.video, .inapp, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let interstitialController = PrebidInterstitialController(rootController: adapterVC) interstitialController.prebidConfigId = "imp-prebid-video-interstitial-320-480" interstitialController.storedAuctionResponse = "response-prebid-video-interstitial-320-480-with-ad-configuration" interstitialController.adFormats = [.video] adapterVC.setup(adapter: interstitialController) setupCustomParams(for: interstitialController.prebidConfigId) }), TestCase(title: "Video Interstitial With Ad Configuration With End Card Server 320x480 (In-App)", tags: [.video, .inapp, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let interstitialController = PrebidInterstitialController(rootController: adapterVC) interstitialController.prebidConfigId = "imp-prebid-video-interstitial-320-480-with-end-card" interstitialController.storedAuctionResponse = "response-prebid-video-interstitial-320-480-with-end-card-with-ad-configuration" interstitialController.adFormats = [.video] adapterVC.setup(adapter: interstitialController) setupCustomParams(for: interstitialController.prebidConfigId) }), TestCase(title: "Video Interstitial 320x480 (In-App) [noBids]", tags: [.video, .inapp, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let interstitialController = PrebidInterstitialController(rootController: adapterVC) interstitialController.prebidConfigId = "imp-prebid-no-bids" interstitialController.storedAuctionResponse = "response-prebid-no-bids" interstitialController.adFormats = [.video] adapterVC.setup(adapter: interstitialController) setupCustomParams(for: interstitialController.prebidConfigId) }), TestCase(title: "Video Interstitial 320x480 with End Card (In-App)", tags: [.video, .inapp, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let interstitialController = PrebidInterstitialController(rootController: adapterVC) interstitialController.prebidConfigId = "imp-prebid-video-interstitial-320-480-with-end-card" interstitialController.storedAuctionResponse = "response-prebid-video-interstitial-320-480-with-end-card" interstitialController.adFormats = [.video] adapterVC.setup(adapter: interstitialController) setupCustomParams(for: interstitialController.prebidConfigId) }), TestCase(title: "Video Interstitial Vertical (In-App)", tags: [.video, .inapp, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let interstitialController = PrebidInterstitialController(rootController: adapterVC) interstitialController.prebidConfigId = "imp-prebid-video-interstitial-vertical" interstitialController.storedAuctionResponse = "response-prebid-video-interstitial-vertical" interstitialController.adFormats = [.video] adapterVC.setup(adapter: interstitialController) setupCustomParams(for: interstitialController.prebidConfigId) }), TestCase(title: "Video Interstitial Vertical With End Card (In-App)", tags: [.video, .inapp, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let interstitialController = PrebidInterstitialController(rootController: adapterVC) interstitialController.prebidConfigId = "imp-prebid-video-interstitial-vertical" interstitialController.storedAuctionResponse = "response-prebid-video-interstitial-vertical-with-end-card" interstitialController.adFormats = [.video] adapterVC.setup(adapter: interstitialController) setupCustomParams(for: interstitialController.prebidConfigId) }), TestCase(title: "Video Interstitial Landscape With End Card (In-App)", tags: [.video, .inapp, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let interstitialController = PrebidInterstitialController(rootController: adapterVC) interstitialController.prebidConfigId = "imp-prebid-video-interstitial-vertical" interstitialController.storedAuctionResponse = "response-prebid-video-interstitial-landscape-with-end-card" interstitialController.adFormats = [.video] adapterVC.setup(adapter: interstitialController) setupCustomParams(for: interstitialController.prebidConfigId) }), TestCase(title: "Video Interstitial 320x480 DeepLink+ (In-App)", tags: [.video, .inapp, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let interstitialController = PrebidInterstitialController(rootController: adapterVC) interstitialController.prebidConfigId = "imp-prebid-video-interstitial-320-480-deeplink" interstitialController.storedAuctionResponse = "response-prebid-video-interstitial-320-480-deeplink" interstitialController.adFormats = [.video] adapterVC.setup(adapter: interstitialController) setupCustomParams(for: interstitialController.prebidConfigId) }), TestCase(title: "Video Interstitial 320x480 SkipOffset (In-App)", tags: [.video, .inapp, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let interstitialController = PrebidInterstitialController(rootController: adapterVC) interstitialController.prebidConfigId = "imp-prebid-video-interstitial-320-480-skip-offset" interstitialController.storedAuctionResponse = "response-prebid-video-interstitial-320-480-skip-offset" interstitialController.adFormats = [.video] adapterVC.setup(adapter: interstitialController) setupCustomParams(for: interstitialController.prebidConfigId) }), TestCase(title: "Video Interstitial 320x480 .mp4 (In-App)", tags: [.video, .inapp, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let interstitialController = PrebidInterstitialController(rootController: adapterVC) interstitialController.prebidConfigId = "imp-prebid-video-interstitial-mp4" interstitialController.storedAuctionResponse = "response-prebid-video-interstitial-mp4" interstitialController.adFormats = [.video] adapterVC.setup(adapter: interstitialController) setupCustomParams(for: interstitialController.prebidConfigId) }), TestCase(title: "Video Interstitial 320x480 .m4v (In-App)", tags: [.video, .inapp, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let interstitialController = PrebidInterstitialController(rootController: adapterVC) interstitialController.prebidConfigId = "imp-prebid-video-interstitial-m4v" interstitialController.storedAuctionResponse = "response-prebid-video-interstitial-m4v" interstitialController.adFormats = [.video] adapterVC.setup(adapter: interstitialController) setupCustomParams(for: interstitialController.prebidConfigId) }), TestCase(title: "Video Interstitial 320x480 .mov (In-App)", tags: [.video, .inapp, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let interstitialController = PrebidInterstitialController(rootController: adapterVC) interstitialController.prebidConfigId = "imp-prebid-video-interstitial-mov" interstitialController.storedAuctionResponse = "response-prebid-video-interstitial-mov" interstitialController.adFormats = [.video] adapterVC.setup(adapter: interstitialController) setupCustomParams(for: interstitialController.prebidConfigId) }), TestCase(title: "Video Interstitial 320x480 with MRAID End Card (In-App)", tags: [.video, .inapp, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let interstitialController = PrebidInterstitialController(rootController: adapterVC) interstitialController.prebidConfigId = "imp-prebid-video-interstitial-mraid-end-card" interstitialController.storedAuctionResponse = "response-prebid-video-interstitial-mraid-end-card" interstitialController.adFormats = [.video] adapterVC.setup(adapter: interstitialController) setupCustomParams(for: interstitialController.prebidConfigId) }), TestCase(title: "Video Interstitial 320x480 (In-App) [SKAdN]", tags: [.video, .inapp, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let interstitialController = PrebidInterstitialController(rootController: adapterVC) interstitialController.prebidConfigId = "imp-prebid-video-interstitial-320-480-skadn" interstitialController.storedAuctionResponse = "response-prebid-video-interstitial-320-480-skadn" interstitialController.adFormats = [.video] adapterVC.setup(adapter: interstitialController) setupCustomParams(for: interstitialController.prebidConfigId) }), TestCase(title: "Video Interstitial 320x480 (In-App) [SKAdN 2.2]", tags: [.video, .inapp, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let interstitialController = PrebidInterstitialController(rootController: adapterVC) interstitialController.prebidConfigId = "imp-prebid-video-interstitial-320-480-skadn" interstitialController.storedAuctionResponse = "response-prebid-video-interstitial-320-480-skadn-v22" interstitialController.adFormats = [.video] adapterVC.setup(adapter: interstitialController) setupCustomParams(for: interstitialController.prebidConfigId) }), // MARK: ---- Video Interstitial (GAM) ---- TestCase(title: "Video Interstitial 320x480 (GAM) [OK, AppEvent]", tags: [.video, .gam, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let gamInterstitialController = PrebidGAMInterstitialController(rootController: adapterVC) gamInterstitialController.prebidConfigId = "imp-prebid-video-interstitial-320-480" gamInterstitialController.storedAuctionResponse = "response-prebid-video-interstitial-320-480" gamInterstitialController.adFormats = [.video] gamInterstitialController.gamAdUnitId = "/21808260008/prebid_oxb_interstitial_video" adapterVC.setup(adapter: gamInterstitialController) setupCustomParams(for: gamInterstitialController.prebidConfigId) }), TestCase(title: "Video Interstitial 320x480 (GAM) [OK, Random]", tags: [.video, .gam, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let gamInterstitialController = PrebidGAMInterstitialController(rootController: adapterVC) gamInterstitialController.prebidConfigId = "imp-prebid-video-interstitial-320-480" gamInterstitialController.storedAuctionResponse = "response-prebid-video-interstitial-320-480" gamInterstitialController.adFormats = [.video] gamInterstitialController.gamAdUnitId = "/21808260008/prebid_oxb_320x480_interstitial_video_random" adapterVC.setup(adapter: gamInterstitialController) setupCustomParams(for: gamInterstitialController.prebidConfigId) }), TestCase(title: "Video Interstitial 320x480 (GAM) [noBids, GAM Ad]", tags: [.video, .gam, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let gamInterstitialController = PrebidGAMInterstitialController(rootController: adapterVC) gamInterstitialController.prebidConfigId = "imp-prebid-no-bids" gamInterstitialController.storedAuctionResponse = "response-prebid-no-bids" gamInterstitialController.adFormats = [.video] gamInterstitialController.gamAdUnitId = "/21808260008/prebid_oxb_320x480_interstitial_video_static" adapterVC.setup(adapter: gamInterstitialController) setupCustomParams(for: gamInterstitialController.prebidConfigId) }), TestCase(title: "Video Interstitial 320x480 With Ad Configuration API (GAM) [OK, AppEvent]", tags: [.video, .gam, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let gamInterstitialController = PrebidGAMInterstitialController(rootController: adapterVC) gamInterstitialController.prebidConfigId = "imp-prebid-video-interstitial-320-480" gamInterstitialController.storedAuctionResponse = "response-prebid-video-interstitial-320-480" gamInterstitialController.adFormats = [.video] gamInterstitialController.gamAdUnitId = "/21808260008/prebid_oxb_interstitial_video" // Custom video configuration gamInterstitialController.maxDuration = 30 gamInterstitialController.closeButtonArea = 0.15 gamInterstitialController.closeButtonPosition = .topLeft gamInterstitialController.skipDelay = 5 adapterVC.setup(adapter: gamInterstitialController) setupCustomParams(for: gamInterstitialController.prebidConfigId) }), TestCase(title: "Video Interstitial With Ad Configuration With End Card API 320x480 (GAM) [OK, AppEvent]", tags: [.video, .gam, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let gamInterstitialController = PrebidGAMInterstitialController(rootController: adapterVC) gamInterstitialController.prebidConfigId = "imp-prebid-video-interstitial-320-480-with-end-card" gamInterstitialController.storedAuctionResponse = "response-prebid-video-interstitial-320-480-with-end-card" gamInterstitialController.adFormats = [.video] gamInterstitialController.gamAdUnitId = "/21808260008/prebid_oxb_interstitial_video" // Custom video configuration gamInterstitialController.maxDuration = 30 gamInterstitialController.closeButtonArea = 0.15 gamInterstitialController.closeButtonPosition = .topLeft gamInterstitialController.skipButtonArea = 0.15 gamInterstitialController.skipButtonPosition = .topRight gamInterstitialController.skipDelay = 5 adapterVC.setup(adapter: gamInterstitialController) setupCustomParams(for: gamInterstitialController.prebidConfigId) }), TestCase(title: "Video Interstitial With Ad Configuration Server 320x480 (GAM) [OK, AppEvent]", tags: [.video, .gam, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let gamInterstitialController = PrebidGAMInterstitialController(rootController: adapterVC) gamInterstitialController.prebidConfigId = "imp-prebid-video-interstitial-320-480" gamInterstitialController.storedAuctionResponse = "response-prebid-video-interstitial-320-480-with-ad-configuration" gamInterstitialController.adFormats = [.video] gamInterstitialController.gamAdUnitId = "/21808260008/prebid_oxb_interstitial_video" adapterVC.setup(adapter: gamInterstitialController) setupCustomParams(for: gamInterstitialController.prebidConfigId) }), TestCase(title: "Video Interstitial With Ad Configuration With End Card Server 320x480 (GAM) [OK, AppEvent]", tags: [.video, .gam, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let gamInterstitialController = PrebidGAMInterstitialController(rootController: adapterVC) gamInterstitialController.prebidConfigId = "imp-prebid-video-interstitial-320-480-with-end-card" gamInterstitialController.storedAuctionResponse = "response-prebid-video-interstitial-320-480-with-end-card-with-ad-configuration" gamInterstitialController.adFormats = [.video] gamInterstitialController.gamAdUnitId = "/21808260008/prebid_oxb_interstitial_video" adapterVC.setup(adapter: gamInterstitialController) setupCustomParams(for: gamInterstitialController.prebidConfigId) }), TestCase(title: "Video Interstitial 320x480 (GAM) [Vanilla Prebid Order]", tags: [.video, .gam, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let gamInterstitialController = PrebidGAMInterstitialController(rootController: adapterVC) gamInterstitialController.prebidConfigId = "imp-prebid-video-interstitial-320-480" gamInterstitialController.storedAuctionResponse = "response-prebid-video-interstitial-320-480" gamInterstitialController.adFormats = [.video] gamInterstitialController.gamAdUnitId = "/21808260008/prebid_interstitial_video" adapterVC.setup(adapter: gamInterstitialController) setupCustomParams(for: gamInterstitialController.prebidConfigId) }), // MARK: ---- Video (In-App) ---- TestCase(title: "Video Outstream (In-App)", tags: [.video, .inapp, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let bannerController = PrebidBannerController(rootController: adapterVC) bannerController.prebidConfigId = "imp-prebid-video-outstream" bannerController.storedAuctionResponse = "response-prebid-video-outstream" bannerController.adSizes = [CGSize(width: 300, height: 250)] bannerController.adFormat = .video adapterVC.setup(adapter: bannerController) setupCustomParams(for: bannerController.prebidConfigId) }), TestCase(title: "Video Outstream (In-App) [noBids]", tags: [.video, .inapp, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let bannerController = PrebidBannerController(rootController: adapterVC) bannerController.prebidConfigId = "imp-prebid-no-bids" bannerController.storedAuctionResponse = "response-prebid-no-bids" bannerController.adSizes = [CGSize(width: 300, height: 250)] bannerController.adFormat = .video adapterVC.setup(adapter: bannerController) setupCustomParams(for: bannerController.prebidConfigId) }), TestCase(title: "Video Outstream with End Card (In-App)", tags: [.video, .inapp, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let bannerController = PrebidBannerController(rootController: adapterVC) bannerController.adSizes = [CGSize(width: 300, height: 250)] bannerController.adFormat = .video bannerController.prebidConfigId = "imp-prebid-video-outstream-with-end-card" bannerController.storedAuctionResponse = "response-prebid-video-outstream-with-end-card" adapterVC.setup(adapter: bannerController) setupCustomParams(for: bannerController.prebidConfigId) }), TestCase(title: "Video Outstream Feed (In-App)", tags: [.video, .inapp, .server], exampleVCStoryboardID: "PrebidFeedTableViewController", configurationClosure: { vc in guard let feedVC = vc as? PrebidFeedTableViewController, let tableView = feedVC.tableView else { return } feedVC.testCases = [ TestCaseManager.createDummyTableCell(for: tableView), TestCaseManager.createDummyTableCell(for: tableView), TestCaseManager.createDummyTableCell(for: tableView), TestCaseForTableCell(configurationClosureForTableCell: { [weak feedVC, weak tableView] cell in guard let videoViewCell = tableView?.dequeueReusableCell(withIdentifier: "FeedAdTableViewCell") as? FeedAdTableViewCell else { return } cell = videoViewCell guard videoViewCell.adView == nil else { return } var prebidConfigId = "imp-prebid-video-outstream" var storedAuctionResponse = "response-prebid-video-outstream" let adSize = CGSize(width: 300, height: 250) let adBannerView = BannerView(frame: CGRect(origin: .zero, size: adSize),configID: prebidConfigId,adSize: adSize) adBannerView.adFormat = .video adBannerView.videoParameters.placement = .InFeed adBannerView.delegate = feedVC adBannerView.accessibilityIdentifier = "PrebidBannerView" if let adUnitContext = AppConfiguration.shared.adUnitContext { for dataPair in adUnitContext { adBannerView.addContextData(dataPair.value, forKey: dataPair.key) } } setupCustomParams(for: prebidConfigId) adBannerView.setStoredAuctionResponse(storedAuction: storedAuctionResponse) adBannerView.loadAd() videoViewCell.bannerView.addSubview(adBannerView) videoViewCell.adView = adBannerView }), TestCaseManager.createDummyTableCell(for: tableView), TestCaseManager.createDummyTableCell(for: tableView), TestCaseManager.createDummyTableCell(for: tableView), ]; }), TestCase(title: "Video Outstream (In-App) [SKAdN]", tags: [.video, .inapp, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let bannerController = PrebidBannerController(rootController: adapterVC) bannerController.prebidConfigId = "imp-prebid-video-outstream-skadn" bannerController.storedAuctionResponse = "response-prebid-video-outstream-skadn" bannerController.adSizes = [CGSize(width: 300, height: 250)] bannerController.adFormat = .video adapterVC.setup(adapter: bannerController) setupCustomParams(for: bannerController.prebidConfigId) }), TestCase(title: "Video Outstream (In-App) [SKAdN 2.2]", tags: [.video, .inapp, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let bannerController = PrebidBannerController(rootController: adapterVC) bannerController.prebidConfigId = "imp-prebid-video-outstream-skadn" bannerController.storedAuctionResponse = "response-prebid-video-outstream-skadn-v22" bannerController.adSizes = [CGSize(width: 300, height: 250)] bannerController.adFormat = .video adapterVC.setup(adapter: bannerController) setupCustomParams(for: bannerController.prebidConfigId) }), // MARK: ---- Video (GAM) ---- TestCase(title: "Video Outstream (GAM) [OK, AppEvent]", tags: [.video, .gam, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let gamBannerController = PrebidGAMBannerController(rootController: adapterVC) gamBannerController.gamAdUnitId = "/21808260008/prebid_oxb_300x250_banner" gamBannerController.validAdSizes = [GADAdSizeMediumRectangle] gamBannerController.adFormat = .video gamBannerController.prebidConfigId = "imp-prebid-video-outstream" gamBannerController.storedAuctionResponse = "response-prebid-video-outstream" adapterVC.setup(adapter: gamBannerController) setupCustomParams(for: gamBannerController.prebidConfigId) }), TestCase(title: "Video Outstream with End Card (GAM) [OK, AppEvent]", tags: [.video, .gam, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let gamBannerController = PrebidGAMBannerController(rootController: adapterVC) gamBannerController.gamAdUnitId = "/21808260008/prebid_oxb_300x250_banner" gamBannerController.validAdSizes = [GADAdSizeMediumRectangle] gamBannerController.adFormat = .video gamBannerController.prebidConfigId = "imp-prebid-video-outstream-with-end-card" gamBannerController.storedAuctionResponse = "response-prebid-video-outstream-with-end-card" adapterVC.setup(adapter: gamBannerController) setupCustomParams(for: gamBannerController.prebidConfigId) }), TestCase(title: "Video Outstream (GAM) [OK, Random]", tags: [.video, .gam, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let gamBannerController = PrebidGAMBannerController(rootController: adapterVC) gamBannerController.prebidConfigId = "imp-prebid-video-outstream" gamBannerController.storedAuctionResponse = "response-prebid-video-outstream-with-end-card" gamBannerController.gamAdUnitId = "/21808260008/prebid_oxb_outstream_video_reandom" gamBannerController.validAdSizes = [GADAdSizeMediumRectangle] gamBannerController.adFormat = .video adapterVC.setup(adapter: gamBannerController) setupCustomParams(for: gamBannerController.prebidConfigId) }), TestCase(title: "Video Outstream (GAM) [noBids, GAM Ad]", tags: [.video, .gam, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let gamBannerController = PrebidGAMBannerController(rootController: adapterVC) gamBannerController.prebidConfigId = "imp-prebid-no-bids" gamBannerController.storedAuctionResponse = "response-prebid-no-bids" gamBannerController.gamAdUnitId = "/21808260008/prebid_oxb_outsream_video" gamBannerController.validAdSizes = [GADAdSizeMediumRectangle] gamBannerController.adFormat = .video adapterVC.setup(adapter: gamBannerController) setupCustomParams(for: gamBannerController.prebidConfigId) }), TestCase(title: "Video Outstream Feed (GAM)", tags: [.video, .gam, .server], exampleVCStoryboardID: "PrebidFeedTableViewController", configurationClosure: { vc in guard let feedVC = vc as? PrebidFeedTableViewController, let tableView = feedVC.tableView else { return } feedVC.testCases = [ TestCaseManager.createDummyTableCell(for: tableView), TestCaseManager.createDummyTableCell(for: tableView), TestCaseManager.createDummyTableCell(for: tableView), TestCaseForTableCell(configurationClosureForTableCell: { [weak feedVC, weak tableView] cell in guard let videoViewCell = tableView?.dequeueReusableCell(withIdentifier: "FeedAdTableViewCell") as? FeedAdTableViewCell else { return } cell = videoViewCell guard videoViewCell.adView == nil else { return } var prebidConfigId = "imp-prebid-video-outstream" var storedAuctionResponse = "response-prebid-video-outstream" let gamAdUnitId = "/21808260008/prebid_oxb_outstream_video_reandom" let validAdSize = GADAdSizeMediumRectangle let adSize = validAdSize.size let adEventHandler = GAMBannerEventHandler(adUnitID: gamAdUnitId, validGADAdSizes: [NSValueFromGADAdSize(validAdSize)]) let adBannerView = BannerView(configID: prebidConfigId,eventHandler: adEventHandler) adBannerView.adFormat = .video adBannerView.videoParameters.placement = .InFeed adBannerView.delegate = feedVC adBannerView.accessibilityIdentifier = "PrebidBannerView" if let adUnitContext = AppConfiguration.shared.adUnitContext { for dataPair in adUnitContext { adBannerView.addContextData(dataPair.value, forKey: dataPair.key) } } setupCustomParams(for: prebidConfigId) adBannerView.setStoredAuctionResponse(storedAuction: storedAuctionResponse) adBannerView.loadAd() videoViewCell.bannerView.addSubview(adBannerView) videoViewCell.adView = adBannerView }), TestCaseManager.createDummyTableCell(for: tableView), TestCaseManager.createDummyTableCell(for: tableView), TestCaseManager.createDummyTableCell(for: tableView), ]; }), // MARK: ---- Video Rewarded (In-App) ---- TestCase(title: "Video Rewarded 320x480 (In-App)", tags: [.video, .inapp, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let rewardedAdController = PrebidRewardedController(rootController: adapterVC) rewardedAdController.prebidConfigId = "imp-prebid-video-rewarded-320-480" rewardedAdController.storedAuctionResponse = "response-prebid-video-rewarded-320-480" adapterVC.setup(adapter: rewardedAdController) setupCustomParams(for: rewardedAdController.prebidConfigId) }), TestCase(title: "Video Rewarded 320x480 (In-App) [noBids]", tags: [.video, .inapp, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let rewardedAdController = PrebidRewardedController(rootController: adapterVC) rewardedAdController.prebidConfigId = "imp-prebid-no-bids" rewardedAdController.storedAuctionResponse = "response-prebid-no-bids" adapterVC.setup(adapter: rewardedAdController) setupCustomParams(for: rewardedAdController.prebidConfigId) }), TestCase(title: "Video Rewarded 320x480 without End Card (In-App)", tags: [.video, .inapp, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let rewardedAdController = PrebidRewardedController(rootController: adapterVC) rewardedAdController.prebidConfigId = "imp-prebid-video-rewarded-320-480-without-end-card" rewardedAdController.storedAuctionResponse = "response-prebid-video-rewarded-320-480-without-end-card" adapterVC.setup(adapter: rewardedAdController) setupCustomParams(for: rewardedAdController.prebidConfigId) }), TestCase(title: "Video Rewarded 480x320 (In-App)", tags: [.video, .inapp, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let rewardedAdController = PrebidRewardedController(rootController: adapterVC) rewardedAdController.prebidConfigId = "imp-prebid-video-rewarded-320-480" rewardedAdController.storedAuctionResponse = "response-prebid-video-rewarded-320-480" adapterVC.setup(adapter: rewardedAdController) setupCustomParams(for: rewardedAdController.prebidConfigId) }), TestCase(title: "Video Rewarded With Ad Configuration Server 320x480 (In-App)", tags: [.video, .inapp, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let rewardedAdController = PrebidRewardedController(rootController: adapterVC) rewardedAdController.prebidConfigId = "imp-prebid-video-rewarded-320-480" rewardedAdController.storedAuctionResponse = "response-prebid-video-rewarded-320-480-with-ad-configuration" adapterVC.setup(adapter: rewardedAdController) setupCustomParams(for: rewardedAdController.prebidConfigId) }), // MARK: ---- Video Rewarded (GAM) ---- TestCase(title: "Video Rewarded 320x480 (GAM) [OK, Metadata]", tags: [.video, .gam, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let gamRewardedAdController = PrebidGAMRewardedController(rootController: adapterVC) gamRewardedAdController.gamAdUnitId = "/21808260008/prebid_oxb_rewarded_video_test" gamRewardedAdController.prebidConfigId = "imp-prebid-video-rewarded-320-480" gamRewardedAdController.storedAuctionResponse = "response-prebid-video-rewarded-320-480" adapterVC.setup(adapter: gamRewardedAdController) setupCustomParams(for: gamRewardedAdController.prebidConfigId) }), TestCase(title: "Video Rewarded 320x480 With Ad Configuration Server (GAM) [OK, Metadata]", tags: [.video, .gam, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let gamRewardedAdController = PrebidGAMRewardedController(rootController: adapterVC) gamRewardedAdController.gamAdUnitId = "/21808260008/prebid_oxb_rewarded_video_test" gamRewardedAdController.prebidConfigId = "imp-prebid-video-rewarded-320-480" gamRewardedAdController.storedAuctionResponse = "response-prebid-video-rewarded-320-480-with-ad-configuration" adapterVC.setup(adapter: gamRewardedAdController) setupCustomParams(for: gamRewardedAdController.prebidConfigId) }), TestCase(title: "Video Rewarded 320x480 (GAM) [OK, Random]", tags: [.video, .gam, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let gamRewardedAdController = PrebidGAMRewardedController(rootController: adapterVC) gamRewardedAdController.prebidConfigId = "imp-prebid-video-rewarded-320-480" gamRewardedAdController.storedAuctionResponse = "response-prebid-video-rewarded-320-480" gamRewardedAdController.gamAdUnitId = "/21808260008/prebid_oxb_rewarded_video_random" adapterVC.setup(adapter: gamRewardedAdController) setupCustomParams(for: gamRewardedAdController.prebidConfigId) }), TestCase(title: "Video Rewarded 320x480 (GAM) [noBids, GAM Ad]", tags: [.video, .gam, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let gamRewardedAdController = PrebidGAMRewardedController(rootController: adapterVC) gamRewardedAdController.prebidConfigId = "imp-prebid-no-bids" gamRewardedAdController.storedAuctionResponse = "response-prebid-no-bids" gamRewardedAdController.gamAdUnitId = "/21808260008/prebid_oxb_rewarded_video_static" adapterVC.setup(adapter: gamRewardedAdController) setupCustomParams(for: gamRewardedAdController.prebidConfigId) }), TestCase(title: "Video Rewarded 320x480 without End Card (GAM) [OK, Metadata]", tags: [.video, .gam, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let gamRewardedAdController = PrebidGAMRewardedController(rootController: adapterVC) gamRewardedAdController.prebidConfigId = "imp-prebid-video-rewarded-320-480-without-end-card" gamRewardedAdController.storedAuctionResponse = "response-prebid-video-rewarded-320-480-without-end-card" gamRewardedAdController.gamAdUnitId = "/21808260008/prebid_oxb_rewarded_video_test" adapterVC.setup(adapter: gamRewardedAdController) setupCustomParams(for: gamRewardedAdController.prebidConfigId) }), // MARK: ---- MRAID (In-App) ---- TestCase(title: "MRAID 2.0: Expand - 1 Part (In-App)", tags: [.mraid, .inapp, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let bannerController = PrebidBannerController(rootController: adapterVC) bannerController.prebidConfigId = "imp-prebid-mraid-expand-1-part" bannerController.storedAuctionResponse = "response-prebid-mraid-expand-1-part" bannerController.adSizes = [CGSize(width: 320, height: 50)] adapterVC.setup(adapter: bannerController) setupCustomParams(for: bannerController.prebidConfigId) }), TestCase(title: "MRAID 2.0: Expand - 2 Part (In-App)", tags: [.mraid, .inapp, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let bannerController = PrebidBannerController(rootController: adapterVC) bannerController.prebidConfigId = "imp-prebid-mraid-expand-2-part" bannerController.storedAuctionResponse = "response-prebid-mraid-expand-2-part" bannerController.adSizes = [CGSize(width: 320, height: 50)] adapterVC.setup(adapter: bannerController) setupCustomParams(for: bannerController.prebidConfigId) }), TestCase(title: "MRAID 2.0: Resize (In-App)", tags: [.mraid, .inapp, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let bannerController = PrebidBannerController(rootController: adapterVC) bannerController.adSizes = [CGSize(width: 320, height: 50)] bannerController.prebidConfigId = "imp-prebid-mraid-resize" bannerController.storedAuctionResponse = "response-prebid-mraid-resize" adapterVC.setup(adapter: bannerController) setupCustomParams(for: bannerController.prebidConfigId) }), TestCase(title: "MRAID 2.0: Resize with Errors (In-App)", tags: [.mraid, .inapp, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let bannerController = PrebidBannerController(rootController: adapterVC) bannerController.prebidConfigId = "imp-prebid-mraid-resize-with-errors" bannerController.storedAuctionResponse = "response-prebid-mraid-resize-with-errors" bannerController.adSizes = [CGSize(width: 300, height: 250)] adapterVC.setup(adapter: bannerController) setupCustomParams(for: bannerController.prebidConfigId) }), TestCase(title: "MRAID 2.0: Fullscreen (In-App)", tags: [.mraid, .inapp, .server], exampleVCStoryboardID: "ScrollableAdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let bannerController = PrebidBannerController(rootController: adapterVC) bannerController.prebidConfigId = "imp-prebid-mraid-fullscreen" bannerController.storedAuctionResponse = "response-prebid-mraid-fullscreen" bannerController.adSizes = [CGSize(width: 320, height: 50)] adapterVC.setup(adapter: bannerController) setupCustomParams(for: bannerController.prebidConfigId) }), TestCase(title: "MRAID 2.0: Video Interstitial (In-App)", tags: [.mraid, .inapp, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let interstitialController = PrebidInterstitialController(rootController: adapterVC) interstitialController.prebidConfigId = "imp-prebid-mraid-video-interstitial" interstitialController.storedAuctionResponse = "response-prebid-mraid-video-interstitial" adapterVC.setup(adapter: interstitialController) setupCustomParams(for: interstitialController.prebidConfigId) }), TestCase(title: "MRAID 3.0: Viewability Compliance (In-App)", tags: [.mraid, .inapp, .server], exampleVCStoryboardID: "ScrollableAdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let bannerController = PrebidBannerController(rootController: adapterVC) bannerController.prebidConfigId = "imp-prebid-mraid-viewability-compliance" bannerController.storedAuctionResponse = "response-prebid-mraid-viewability-compliance" bannerController.adSizes = [CGSize(width: 300, height: 250)] adapterVC.setup(adapter: bannerController) setupCustomParams(for: bannerController.prebidConfigId) }), TestCase(title: "MRAID 3.0: Resize Negative Test (In-App)", tags: [.mraid, .inapp, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let bannerController = PrebidBannerController(rootController: adapterVC) bannerController.prebidConfigId = "imp-prebid-mraid-resize-negative-test" bannerController.storedAuctionResponse = "response-prebid-mraid-resize-negative-test" bannerController.adSizes = [CGSize(width: 300, height: 250)] adapterVC.setup(adapter: bannerController) setupCustomParams(for: bannerController.prebidConfigId) }), TestCase(title: "MRAID 3.0: Load And Events (In-App)", tags: [.mraid, .inapp, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let bannerController = PrebidBannerController(rootController: adapterVC) bannerController.prebidConfigId = "imp-prebid-mraid-load-and-events" bannerController.storedAuctionResponse = "response-prebid-mraid-load-and-events" bannerController.adSizes = [CGSize(width: 320, height: 50)] adapterVC.setup(adapter: bannerController) setupCustomParams(for: bannerController.prebidConfigId) }), TestCase(title: "MRAID OX: Test Properties 3.0 (In-App)", tags: [.mraid, .inapp, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let bannerController = PrebidBannerController(rootController: adapterVC) bannerController.prebidConfigId = "imp-prebid-mraid-test-properties-3" bannerController.storedAuctionResponse = "response-prebid-mraid-test-properties-3" bannerController.adSizes = [CGSize(width: 320, height: 50)] adapterVC.setup(adapter: bannerController) setupCustomParams(for: bannerController.prebidConfigId) }), TestCase(title: "MRAID OX: Test Methods 3.0 (In-App)", tags: [.mraid, .inapp, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let bannerController = PrebidBannerController(rootController: adapterVC) bannerController.prebidConfigId = "imp-prebid-mraid-test-methods-3" bannerController.storedAuctionResponse = "response-prebid-mraid-test-methods-3" bannerController.adSizes = [CGSize(width: 320, height: 50)] adapterVC.setup(adapter: bannerController) setupCustomParams(for: bannerController.prebidConfigId) }), TestCase(title: "MRAID OX: Resize (Expandable) (In-App)", tags: [.mraid, .inapp, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let bannerController = PrebidBannerController(rootController: adapterVC) bannerController.prebidConfigId = "imp-prebid-mraid-resize-expandable" bannerController.storedAuctionResponse = "response-prebid-mraid-resize-expandable" bannerController.adSizes = [CGSize(width: 300, height: 50)] adapterVC.setup(adapter: bannerController) setupCustomParams(for: bannerController.prebidConfigId) }), TestCase(title: "MRAID OX: Resize (With Scroll) (In-App)", tags: [.mraid, .inapp, .server], exampleVCStoryboardID: "ScrollableAdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let bannerController = PrebidBannerController(rootController: adapterVC) bannerController.prebidConfigId = "imp-prebid-mraid-resize" bannerController.storedAuctionResponse = "response-prebid-mraid-resize" bannerController.adSizes = [CGSize(width: 300, height: 50)] adapterVC.setup(adapter: bannerController) setupCustomParams(for: bannerController.prebidConfigId) }), // MARK: ---- MRAID (GAM) ---- TestCase(title: "MRAID 2.0: Expand - 1 Part (GAM)", tags: [.mraid, .gam, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let gamBannerController = PrebidGAMBannerController(rootController: adapterVC) gamBannerController.prebidConfigId = "imp-prebid-mraid-expand-1-part" gamBannerController.storedAuctionResponse = "response-prebid-mraid-expand-1-part" gamBannerController.gamAdUnitId = "/21808260008/prebid_oxb_320x50_banner" gamBannerController.validAdSizes = [GADAdSizeBanner] adapterVC.setup(adapter: gamBannerController) setupCustomParams(for: gamBannerController.prebidConfigId) }), TestCase(title: "MRAID 2.0: Resize (GAM)", tags: [.mraid, .gam, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let gamBannerController = PrebidGAMBannerController(rootController: adapterVC) gamBannerController.prebidConfigId = "imp-prebid-mraid-resize" gamBannerController.storedAuctionResponse = "response-prebid-mraid-resize" gamBannerController.gamAdUnitId = "/21808260008/prebid_oxb_320x50_banner" gamBannerController.validAdSizes = [GADAdSizeBanner] adapterVC.setup(adapter: gamBannerController) setupCustomParams(for: gamBannerController.prebidConfigId) }), TestCase(title: "MRAID 2.0: Video Interstitial (GAM)", tags: [.mraid, .gam, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let gamInterstitialController = PrebidGAMInterstitialController(rootController: adapterVC) gamInterstitialController.prebidConfigId = "imp-prebid-mraid-video-interstitial" gamInterstitialController.storedAuctionResponse = "response-prebid-mraid-video-interstitial" gamInterstitialController.gamAdUnitId = "/21808260008/prebid_oxb_html_interstitial" adapterVC.setup(adapter: gamInterstitialController) setupCustomParams(for: gamInterstitialController.prebidConfigId) }), // MARK: ---- Banner (AdMob) ---- TestCase(title: "Banner 320x50 (AdMob) [OK, OXB Adapter]", tags: [.banner, .admob, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let admobBannerController = PrebidAdMobBannerViewController(rootController: adapterVC) admobBannerController.adMobAdUnitId = "ca-app-pub-5922967660082475/9483570409" admobBannerController.adUnitSize = CGSize(width: 320, height: 50); admobBannerController.prebidConfigId = "imp-prebid-banner-320-50" admobBannerController.storedAuctionResponse = "response-prebid-banner-320-50" adapterVC.setup(adapter: admobBannerController) setupCustomParams(for: admobBannerController.prebidConfigId) }), TestCase(title: "Banner 320x50 Events (AdMob) [OK, OXB Adapter]", tags: [.banner, .admob, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } Prebid.shared.prebidServerAccountId = "prebid-stored-request-enabled-events" let admobBannerController = PrebidAdMobBannerViewController(rootController: adapterVC) admobBannerController.adMobAdUnitId = "ca-app-pub-5922967660082475/9483570409" admobBannerController.adUnitSize = CGSize(width: 320, height: 50); admobBannerController.prebidConfigId = "imp-prebid-banner-320-50" admobBannerController.storedAuctionResponse = "response-prebid-banner-320-50" adapterVC.setup(adapter: admobBannerController) setupCustomParams(for: admobBannerController.prebidConfigId) }), TestCase(title: "Banner 320x50 (AdMob) [OK, Random]", tags: [.banner, .admob, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let admobBannerController = PrebidAdMobBannerViewController(rootController: adapterVC) admobBannerController.prebidConfigId = "imp-prebid-banner-320-50" admobBannerController.storedAuctionResponse = "response-prebid-banner-320-50" admobBannerController.adMobAdUnitId = "ca-app-pub-5922967660082475/9483570409" admobBannerController.adUnitSize = CGSize(width: 320, height: 50); adapterVC.setup(adapter: admobBannerController) setupCustomParams(for: admobBannerController.prebidConfigId) }), TestCase(title: "Banner 320x50 (AdMob) [noBids, AdMob Ad]", tags: [.banner, .admob, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let admobBannerController = PrebidAdMobBannerViewController(rootController: adapterVC) admobBannerController.prebidConfigId = "imp-prebid-no-bids" admobBannerController.storedAuctionResponse = "response-prebid-no-bids" admobBannerController.adMobAdUnitId = "ca-app-pub-5922967660082475/9483570409" admobBannerController.adUnitSize = CGSize(width: 320, height: 50); adapterVC.setup(adapter: admobBannerController) setupCustomParams(for: admobBannerController.prebidConfigId) }), TestCase(title: "Banner 320x50 (AdMob) [Random, Respective]", tags: [.banner, .admob, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let admobBannerController = PrebidAdMobBannerViewController(rootController: adapterVC) admobBannerController.prebidConfigId = "imp-prebid-banner-320-50" admobBannerController.storedAuctionResponse = "response-prebid-banner-320-50" admobBannerController.adMobAdUnitId = "ca-app-pub-5922967660082475/9483570409" admobBannerController.adUnitSize = CGSize(width: 320, height: 50); adapterVC.setup(adapter: admobBannerController) setupCustomParams(for: admobBannerController.prebidConfigId) }), TestCase(title: "Banner 300x250 (AdMob)", tags: [.banner, .admob, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let admobBannerController = PrebidAdMobBannerViewController(rootController: adapterVC) admobBannerController.prebidConfigId = "imp-prebid-banner-300-250" admobBannerController.storedAuctionResponse = "response-prebid-banner-300-250" admobBannerController.adMobAdUnitId = "ca-app-pub-5922967660082475/9483570409" admobBannerController.adUnitSize = CGSize(width: 300, height: 250); adapterVC.setup(adapter: admobBannerController) setupCustomParams(for: admobBannerController.prebidConfigId) }), TestCase(title: "Banner Adaptive (AdMob)", tags: [.banner, .admob, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let admobBannerController = PrebidAdMobBannerViewController(rootController: adapterVC) admobBannerController.prebidConfigId = "imp-prebid-banner-multisize" admobBannerController.storedAuctionResponse = "response-prebid-banner-multisize" admobBannerController.adMobAdUnitId = "ca-app-pub-5922967660082475/9483570409" admobBannerController.adUnitSize = CGSize(width: 320, height: 50); admobBannerController.additionalAdSizes = [CGSize(width: 728, height: 90)] admobBannerController.gadAdSizeType = .adaptiveAnchored adapterVC.setup(adapter: admobBannerController) setupCustomParams(for: admobBannerController.prebidConfigId) }), // MARK: ---- Interstitial (AdMob) ---- TestCase(title: "Display Interstitial 320x480 (AdMob) [OK, OXB Adapter]", tags: [.interstitial, .admob, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let admobInterstitialController = PrebidAdMobInterstitialViewController(rootController: adapterVC) admobInterstitialController.adMobAdUnitId = "ca-app-pub-5922967660082475/3383099861" admobInterstitialController.adFormats = [.display] admobInterstitialController.prebidConfigId = "imp-prebid-display-interstitial-320-480" admobInterstitialController.storedAuctionResponse = "response-prebid-display-interstitial-320-480" adapterVC.setup(adapter: admobInterstitialController) setupCustomParams(for: admobInterstitialController.prebidConfigId) }), TestCase(title: "Display Interstitial 320x480 (AdMob) [noBids, AdMob Ad]", tags: [.interstitial, .admob, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let admobInterstitialController = PrebidAdMobInterstitialViewController(rootController: adapterVC) admobInterstitialController.adFormats = [.display] admobInterstitialController.prebidConfigId = "imp-prebid-no-bids" admobInterstitialController.storedAuctionResponse = "response-prebid-no-bids" admobInterstitialController.adMobAdUnitId = "ca-app-pub-5922967660082475/3383099861" adapterVC.setup(adapter: admobInterstitialController) setupCustomParams(for: admobInterstitialController.prebidConfigId) }), TestCase(title: "Display Interstitial 320x480 (AdMob) [OK, Random]", tags: [.interstitial, .admob, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let admobInterstitialController = PrebidAdMobInterstitialViewController(rootController: adapterVC) admobInterstitialController.adFormats = [.display] admobInterstitialController.prebidConfigId = "imp-prebid-display-interstitial-320-480" admobInterstitialController.storedAuctionResponse = "response-prebid-display-interstitial-320-480" admobInterstitialController.adMobAdUnitId = "ca-app-pub-5922967660082475/3383099861" adapterVC.setup(adapter: admobInterstitialController) setupCustomParams(for: admobInterstitialController.prebidConfigId) }), // MARK: ---- Video Interstitial (AdMob) ---- TestCase(title: "Video Interstitial 320x480 (AdMob) [OK, OXB Adapter]", tags: [.video, .admob, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let admobInterstitialController = PrebidAdMobInterstitialViewController(rootController: adapterVC) admobInterstitialController.prebidConfigId = "imp-prebid-video-interstitial-320-480" admobInterstitialController.storedAuctionResponse = "response-prebid-video-interstitial-320-480" admobInterstitialController.adFormats = [.video] admobInterstitialController.adMobAdUnitId = "ca-app-pub-5922967660082475/4527792002" adapterVC.setup(adapter: admobInterstitialController) setupCustomParams(for: admobInterstitialController.prebidConfigId) }), TestCase(title: "Video Interstitial With Ad Configuration 320x480 API (AdMob) [OK, OXB Adapter]", tags: [.video, .admob, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let admobInterstitialController = PrebidAdMobInterstitialViewController(rootController: adapterVC) admobInterstitialController.prebidConfigId = "imp-prebid-video-interstitial-320-480" admobInterstitialController.storedAuctionResponse = "response-prebid-video-interstitial-320-480" admobInterstitialController.adFormats = [.video] admobInterstitialController.adMobAdUnitId = "ca-app-pub-5922967660082475/4527792002" // Custom video configuration admobInterstitialController.maxDuration = 30 admobInterstitialController.closeButtonArea = 0.15 admobInterstitialController.closeButtonPosition = .topLeft admobInterstitialController.skipDelay = 5 adapterVC.setup(adapter: admobInterstitialController) setupCustomParams(for: admobInterstitialController.prebidConfigId) }), TestCase(title: "Video Interstitial With Ad Configuration With End Card 320x480 API (AdMob) [OK, OXB Adapter]", tags: [.video, .admob, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let admobInterstitialController = PrebidAdMobInterstitialViewController(rootController: adapterVC) admobInterstitialController.prebidConfigId = "imp-prebid-video-interstitial-320-480-with-end-card" admobInterstitialController.storedAuctionResponse = "response-prebid-video-interstitial-320-480-with-end-card" admobInterstitialController.adFormats = [.video] admobInterstitialController.adMobAdUnitId = "ca-app-pub-5922967660082475/4527792002" // Custom video configuration admobInterstitialController.maxDuration = 30 admobInterstitialController.closeButtonArea = 0.15 admobInterstitialController.closeButtonPosition = .topLeft admobInterstitialController.skipButtonArea = 0.15 admobInterstitialController.skipButtonPosition = .topRight admobInterstitialController.skipDelay = 5 adapterVC.setup(adapter: admobInterstitialController) setupCustomParams(for: admobInterstitialController.prebidConfigId) }), TestCase(title: "Video Interstitial With Ad Configuration 320x480 Server (AdMob) [OK, OXB Adapter]", tags: [.video, .admob, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let admobInterstitialController = PrebidAdMobInterstitialViewController(rootController: adapterVC) admobInterstitialController.prebidConfigId = "imp-prebid-video-interstitial-320-480" admobInterstitialController.storedAuctionResponse = "response-prebid-video-interstitial-320-480-with-ad-configuration" admobInterstitialController.adFormats = [.video] admobInterstitialController.adMobAdUnitId = "ca-app-pub-5922967660082475/4527792002" adapterVC.setup(adapter: admobInterstitialController) setupCustomParams(for: admobInterstitialController.prebidConfigId) }), TestCase(title: "Video Interstitial With Ad Configuration With End Card 320x480 Server (AdMob) [OK, OXB Adapter]", tags: [.video, .admob, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let admobInterstitialController = PrebidAdMobInterstitialViewController(rootController: adapterVC) admobInterstitialController.prebidConfigId = "imp-prebid-video-interstitial-320-480-with-end-card" admobInterstitialController.storedAuctionResponse = "response-prebid-video-interstitial-320-480-with-end-card-with-ad-configuration" admobInterstitialController.adFormats = [.video] admobInterstitialController.adMobAdUnitId = "ca-app-pub-5922967660082475/4527792002" adapterVC.setup(adapter: admobInterstitialController) setupCustomParams(for: admobInterstitialController.prebidConfigId) }), TestCase(title: "Video Interstitial 320x480 (AdMob) [OK, Random]", tags: [.video, .admob, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let admobInterstitialController = PrebidAdMobInterstitialViewController(rootController: adapterVC) admobInterstitialController.prebidConfigId = "imp-prebid-video-interstitial-320-480" admobInterstitialController.storedAuctionResponse = "response-prebid-video-interstitial-320-480" admobInterstitialController.adFormats = [.video] admobInterstitialController.adMobAdUnitId = "ca-app-pub-5922967660082475/4527792002" adapterVC.setup(adapter: admobInterstitialController) setupCustomParams(for: admobInterstitialController.prebidConfigId) }), TestCase(title: "Video Interstitial 320x480 (AdMob) [noBids, AdMob Ad]", tags: [.video, .admob, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let admobInterstitialController = PrebidAdMobInterstitialViewController(rootController: adapterVC) admobInterstitialController.prebidConfigId = "imp-prebid-no-bids" admobInterstitialController.storedAuctionResponse = "response-prebid-no-bids" admobInterstitialController.adFormats = [.video] admobInterstitialController.adMobAdUnitId = "ca-app-pub-5922967660082475/4527792002" adapterVC.setup(adapter: admobInterstitialController) setupCustomParams(for: admobInterstitialController.prebidConfigId) }), // MARK: ---- Multiformat Interstitial (AdMob) ---- TestCase(title: "Multiformat Interstitial 320x480 (AdMob)", tags: [.interstitial, .video, .admob, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let randomId = [0, 1].randomElement() ?? 0 let interstitialController = PrebidAdMobInterstitialViewController(rootController: adapterVC) let admobAdUnitIds = ["ca-app-pub-5922967660082475/3383099861", "ca-app-pub-5922967660082475/4527792002"] let prebidStoredAuctionResponses = ["response-prebid-display-interstitial-320-480", "response-prebid-video-interstitial-320-480"] interstitialController.prebidConfigId = "imp-prebid-display-interstitial-320-480" interstitialController.storedAuctionResponse = prebidStoredAuctionResponses[randomId] interstitialController.adMobAdUnitId = admobAdUnitIds[randomId] adapterVC.setup(adapter: interstitialController) setupCustomParams(for: interstitialController.prebidConfigId) }), // MARK: ---- Video Rewarded (AdMob) ---- TestCase(title: "Video Rewarded 320x480 (AdMob) [OK, OXB Adapter]", tags: [.video, .admob, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let admobRewardedAdController = PrebidAdMobRewardedViewController(rootController: adapterVC) admobRewardedAdController.adMobAdUnitId = "ca-app-pub-5922967660082475/7397370641" admobRewardedAdController.prebidConfigId = "imp-prebid-video-rewarded-320-480" admobRewardedAdController.storedAuctionResponse = "response-prebid-video-rewarded-320-480" adapterVC.setup(adapter: admobRewardedAdController) setupCustomParams(for: admobRewardedAdController.prebidConfigId) }), TestCase(title: "Video Rewarded With Ad Configuration 320x480 Server (AdMob) [OK, OXB Adapter]", tags: [.video, .admob, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let admobRewardedAdController = PrebidAdMobRewardedViewController(rootController: adapterVC) admobRewardedAdController.adMobAdUnitId = "ca-app-pub-5922967660082475/7397370641" admobRewardedAdController.prebidConfigId = "imp-prebid-video-rewarded-320-480" admobRewardedAdController.storedAuctionResponse = "response-prebid-video-rewarded-320-480-with-ad-configuration" adapterVC.setup(adapter: admobRewardedAdController) setupCustomParams(for: admobRewardedAdController.prebidConfigId) }), TestCase(title: "Video Rewarded 320x480 (AdMob) [noBids, AdMob Ad]", tags: [.video, .admob, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let admobRewardedAdController = PrebidAdMobRewardedViewController(rootController: adapterVC) admobRewardedAdController.prebidConfigId = "imp-prebid-no-bids" admobRewardedAdController.storedAuctionResponse = "response-prebid-no-bids" admobRewardedAdController.adMobAdUnitId = "ca-app-pub-5922967660082475/7397370641" adapterVC.setup(adapter: admobRewardedAdController) setupCustomParams(for: admobRewardedAdController.prebidConfigId) }), TestCase(title: "Video Rewarded 320x480 (AdMob) [OK, Random]", tags: [.video, .admob, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let admobRewardedAdController = PrebidAdMobRewardedViewController(rootController: adapterVC) admobRewardedAdController.prebidConfigId = "imp-prebid-video-rewarded-320-480" admobRewardedAdController.storedAuctionResponse = "response-prebid-video-rewarded-320-480" admobRewardedAdController.adMobAdUnitId = "ca-app-pub-5922967660082475/7397370641" adapterVC.setup(adapter: admobRewardedAdController) setupCustomParams(for: admobRewardedAdController.prebidConfigId) }), TestCase(title: "Video Rewarded 320x480 without End Card (AdMob) [OK, OXB Adapter]", tags: [.video, .admob, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let admobRewardedAdController = PrebidAdMobRewardedViewController(rootController: adapterVC) admobRewardedAdController.prebidConfigId = "imp-prebid-video-rewarded-320-480-without-end-card" admobRewardedAdController.storedAuctionResponse = "response-prebid-video-rewarded-320-480-without-end-card" admobRewardedAdController.adMobAdUnitId = "ca-app-pub-5922967660082475/7397370641" adapterVC.setup(adapter: admobRewardedAdController) setupCustomParams(for: admobRewardedAdController.prebidConfigId) }), // MARK: ---- Native (AdMob) ---- TestCase(title: "Native Ad (AdMob) [OK, OXB Adapter]", tags: [.native, .admob, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let nativeController = PrebidAdMobNativeViewController(rootController: adapterVC) nativeController.adMobAdUnitId = "ca-app-pub-5922967660082475/8634069303" nativeController.prebidConfigId = "imp-prebid-banner-native-styles" nativeController.storedAuctionResponse = "response-prebid-banner-native-styles" nativeController.nativeAssets = .defaultNativeRequestAssets nativeController.eventTrackers = .defaultNativeEventTrackers adapterVC.setup(adapter: nativeController) setupCustomParams(for: nativeController.prebidConfigId) }), TestCase(title: "Native Ad Events (AdMob) [OK, OXB Adapter]", tags: [.native, .admob, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } Prebid.shared.prebidServerAccountId = "prebid-stored-request-enabled-events" let nativeController = PrebidAdMobNativeViewController(rootController: adapterVC) nativeController.adMobAdUnitId = "ca-app-pub-5922967660082475/8634069303" nativeController.prebidConfigId = "imp-prebid-banner-native-styles" nativeController.storedAuctionResponse = "response-prebid-banner-native-styles" nativeController.nativeAssets = .defaultNativeRequestAssets nativeController.eventTrackers = .defaultNativeEventTrackers adapterVC.setup(adapter: nativeController) setupCustomParams(for: nativeController.prebidConfigId) }), TestCase(title: "Native Ad (AdMob) [noBids, GADNativeAd]", tags: [.native, .admob, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let nativeController = PrebidAdMobNativeViewController(rootController: adapterVC) nativeController.adMobAdUnitId = "ca-app-pub-5922967660082475/8634069303" nativeController.prebidConfigId = "imp-prebid-no-bids" nativeController.storedAuctionResponse = "imp-prebid-no-bids" nativeController.nativeAssets = .defaultNativeRequestAssets nativeController.eventTrackers = .defaultNativeEventTrackers adapterVC.setup(adapter: nativeController) setupCustomParams(for: nativeController.prebidConfigId) }), // MARK: ---- Native (In-App) ---- TestCase(title: "Native Ad (In-App)", tags: [.native, .inapp, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let nativeAdController = PrebidNativeAdController(rootController: adapterVC) nativeAdController.setupNativeAdView(NativeAdViewBox()) nativeAdController.prebidConfigId = "imp-prebid-banner-native-styles" nativeAdController.storedAuctionResponse = "response-prebid-banner-native-styles" nativeAdController.nativeAssets = .defaultNativeRequestAssets nativeAdController.eventTrackers = .defaultNativeEventTrackers adapterVC.setup(adapter: nativeAdController) setupCustomParams(for: nativeAdController.prebidConfigId) }), TestCase(title: "Native Ad Events (In-App)", tags: [.native, .inapp, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } Prebid.shared.prebidServerAccountId = "prebid-stored-request-enabled-events" let nativeAdController = PrebidNativeAdController(rootController: adapterVC) nativeAdController.setupNativeAdView(NativeAdViewBox()) nativeAdController.prebidConfigId = "imp-prebid-banner-native-styles" nativeAdController.storedAuctionResponse = "response-prebid-banner-native-styles" nativeAdController.nativeAssets = .defaultNativeRequestAssets nativeAdController.eventTrackers = .defaultNativeEventTrackers adapterVC.setup(adapter: nativeAdController) setupCustomParams(for: nativeAdController.prebidConfigId) }), TestCase(title: "Native Ad Links (In-App)", tags: [.native, .inapp, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let nativeAdController = PrebidNativeAdController(rootController: adapterVC) nativeAdController.setupNativeAdView(NativeAdViewBoxLinks()) nativeAdController.prebidConfigId = "imp-prebid-native-links" nativeAdController.storedAuctionResponse = "response-prebid-native-links" Prebid.shared.shouldAssignNativeAssetID = true let sponsored = NativeAssetData(type: .sponsored, required: true) let rating = NativeAssetData(type: .rating, required: true) let desc = NativeAssetData(type: .description, required: true) let cta = NativeAssetData(type: .ctatext, required: true) nativeAdController.nativeAssets = [sponsored, desc, rating, cta] nativeAdController.eventTrackers = .defaultNativeEventTrackers adapterVC.setup(adapter: nativeAdController) setupCustomParams(for: nativeAdController.prebidConfigId) }), TestCase(title: "Native Ad Feed (In-App)", tags: [.native, .inapp, .server], exampleVCStoryboardID: "PrebidFeedTableViewController", configurationClosure: { vc in guard let feedVC = vc as? PrebidFeedTableViewController else { return } let nativeAdFeedController = PrebidNativeAdFeedController(rootTableViewController: feedVC) nativeAdFeedController.prebidConfigId = "imp-prebid-banner-native-styles" nativeAdFeedController.storedAuctionResponse = "response-prebid-banner-native-styles" nativeAdFeedController.nativeAssets = .defaultNativeRequestAssets nativeAdFeedController.eventTrackers = .defaultNativeEventTrackers feedVC.adapter = nativeAdFeedController feedVC.loadAdClosure = nativeAdFeedController.allowLoadingAd nativeAdFeedController.createCells() setupCustomParams(for: nativeAdFeedController.prebidConfigId) }), // MARK: ---- Native (GAM, CustomTemplate) ---- TestCase(title: "Native Ad Custom Templates (GAM) [OK, NativeAd]", tags: [.native, .gam,.server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let gamNativeAdController = PrebidGAMNativeAdController(rootController: adapterVC) gamNativeAdController.prebidConfigId = "imp-prebid-banner-native-styles" gamNativeAdController.storedAuctionResponse = "response-prebid-banner-native-styles" gamNativeAdController.gamAdUnitId = "/21808260008/apollo_custom_template_native_ad_unit" gamNativeAdController.adTypes = [.customNative] gamNativeAdController.gamCustomTemplateIDs = ["11934135"] gamNativeAdController.nativeAssets = .defaultNativeRequestAssets gamNativeAdController.eventTrackers = .defaultNativeEventTrackers adapterVC.setup(adapter: gamNativeAdController) setupCustomParams(for: gamNativeAdController.prebidConfigId) }), TestCase(title: "Native Ad Custom Templates Events (GAM) [OK, NativeAd]", tags: [.native, .gam,.server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } Prebid.shared.prebidServerAccountId = "prebid-stored-request-enabled-events" let gamNativeAdController = PrebidGAMNativeAdController(rootController: adapterVC) gamNativeAdController.prebidConfigId = "imp-prebid-banner-native-styles" gamNativeAdController.storedAuctionResponse = "response-prebid-banner-native-styles" gamNativeAdController.gamAdUnitId = "/21808260008/apollo_custom_template_native_ad_unit" gamNativeAdController.adTypes = [.customNative] gamNativeAdController.gamCustomTemplateIDs = ["11934135"] gamNativeAdController.nativeAssets = .defaultNativeRequestAssets gamNativeAdController.eventTrackers = .defaultNativeEventTrackers adapterVC.setup(adapter: gamNativeAdController) setupCustomParams(for: gamNativeAdController.prebidConfigId) }), TestCase(title: "Native Ad (GAM) [OK, GADNativeCustomTemplateAd]", tags: [.native, .gam, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let gamNativeAdController = PrebidGAMNativeAdController(rootController: adapterVC) gamNativeAdController.prebidConfigId = "imp-prebid-banner-native-styles" gamNativeAdController.storedAuctionResponse = "response-prebid-banner-native-styles" gamNativeAdController.gamAdUnitId = "/21808260008/apollo_custom_template_native_ad_unit" gamNativeAdController.adTypes = [.customNative] gamNativeAdController.gamCustomTemplateIDs = ["11982639"] gamNativeAdController.nativeAssets = .defaultNativeRequestAssets gamNativeAdController.eventTrackers = .defaultNativeEventTrackers adapterVC.setup(adapter: gamNativeAdController) setupCustomParams(for: gamNativeAdController.prebidConfigId) }), TestCase(title: "Native Ad (GAM) [noBids, GADNativeCustomTemplateAd]", tags: [.native, .gam, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let gamNativeAdController = PrebidGAMNativeAdController(rootController: adapterVC) gamNativeAdController.prebidConfigId = "imp-prebid-native-video-with-end-card--dummy" gamNativeAdController.storedAuctionResponse = "response-prebid-video-with-end-card" gamNativeAdController.gamAdUnitId = "/21808260008/apollo_custom_template_native_ad_unit" gamNativeAdController.adTypes = [.customNative] gamNativeAdController.gamCustomTemplateIDs = ["11982639"] gamNativeAdController.nativeAssets = .defaultNativeRequestAssets gamNativeAdController.eventTrackers = .defaultNativeEventTrackers adapterVC.setup(adapter: gamNativeAdController) setupCustomParams(for: gamNativeAdController.prebidConfigId) }), TestCase(title: "Native Ad Feed (GAM) [OK, NativeAd]", tags: [.native, .gam, .server], exampleVCStoryboardID: "PrebidFeedTableViewController", configurationClosure: { vc in guard let feedVC = vc as? PrebidFeedTableViewController else { return } let gamNativeAdController = PrebidGAMNativeAdFeedController(rootTableViewController: feedVC) gamNativeAdController.prebidConfigId = "imp-prebid-banner-native-styles" gamNativeAdController.storedAuctionResponse = "response-prebid-banner-native-styles" gamNativeAdController.gamAdUnitId = "/21808260008/apollo_custom_template_native_ad_unit" gamNativeAdController.adTypes = [.customNative] gamNativeAdController.gamCustomTemplateIDs = ["11934135"] gamNativeAdController.nativeAssets = .defaultNativeRequestAssets gamNativeAdController.eventTrackers = .defaultNativeEventTrackers feedVC.adapter = gamNativeAdController feedVC.loadAdClosure = gamNativeAdController.allowLoadingAd gamNativeAdController.createCells() setupCustomParams(for: gamNativeAdController.prebidConfigId) }), // MARK: ---- Native (GAM, Unified) ---- TestCase(title: "Native Ad Unified Ad (GAM) [OK, NativeAd]", tags: [.native, .gam,.server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let gamNativeAdController = PrebidGAMNativeAdController(rootController: adapterVC) gamNativeAdController.prebidConfigId = "imp-prebid-banner-native-styles" gamNativeAdController.storedAuctionResponse = "response-prebid-banner-native-styles" gamNativeAdController.gamAdUnitId = "/21808260008/unified_native_ad_unit" gamNativeAdController.adTypes = [.native] gamNativeAdController.nativeAssets = .defaultNativeRequestAssets gamNativeAdController.eventTrackers = .defaultNativeEventTrackers adapterVC.setup(adapter: gamNativeAdController) setupCustomParams(for: gamNativeAdController.prebidConfigId) }), TestCase(title: "Native Ad (GAM) [OK, GADUnifiedNativeAd]", tags: [.native, .gam, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let gamNativeAdController = PrebidGAMNativeAdController(rootController: adapterVC) gamNativeAdController.prebidConfigId = "imp-prebid-banner-native-styles" gamNativeAdController.storedAuctionResponse = "response-prebid-banner-native-styles" gamNativeAdController.gamAdUnitId = "/21808260008/unified_native_ad_unit_static" gamNativeAdController.adTypes = [.native] gamNativeAdController.nativeAssets = .defaultNativeRequestAssets gamNativeAdController.eventTrackers = .defaultNativeEventTrackers adapterVC.setup(adapter: gamNativeAdController) setupCustomParams(for: gamNativeAdController.prebidConfigId) }), TestCase(title: "Native Ad (GAM) [noBids, GADUnifiedNativeAd]", tags: [.native, .gam, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let gamNativeAdController = PrebidGAMNativeAdController(rootController: adapterVC) gamNativeAdController.prebidConfigId = "imp-prebid-native-video-with-end-card--dummy" gamNativeAdController.storedAuctionResponse = "response-prebid-video-with-end-card" gamNativeAdController.gamAdUnitId = "/21808260008/unified_native_ad_unit_static" gamNativeAdController.adTypes = [.native] gamNativeAdController.nativeAssets = .defaultNativeRequestAssets gamNativeAdController.eventTrackers = .defaultNativeEventTrackers adapterVC.setup(adapter: gamNativeAdController) setupCustomParams(for: gamNativeAdController.prebidConfigId) }), // MARK: ---- Banner (MAX) ---- TestCase(title: "Banner 320x50 (MAX) [OK, OXB Adapter]", tags: [.banner, .max, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let maxBannerController = PrebidMAXBannerController(rootController: adapterVC) maxBannerController.maxAdUnitId = "5f111f4bcd0f58ca" maxBannerController.adUnitSize = CGSize(width: 320, height: 50); maxBannerController.prebidConfigId = "imp-prebid-banner-320-50" maxBannerController.storedAuctionResponse = "response-prebid-banner-320-50" adapterVC.setup(adapter: maxBannerController) setupCustomParams(for: maxBannerController.prebidConfigId) }), TestCase(title: "Banner 320x50 Events (MAX) [OK, OXB Adapter]", tags: [.banner, .max, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } Prebid.shared.prebidServerAccountId = "prebid-stored-request-enabled-events" let maxBannerController = PrebidMAXBannerController(rootController: adapterVC) maxBannerController.maxAdUnitId = "5f111f4bcd0f58ca" maxBannerController.adUnitSize = CGSize(width: 320, height: 50); maxBannerController.prebidConfigId = "imp-prebid-banner-320-50" maxBannerController.storedAuctionResponse = "response-prebid-banner-320-50" adapterVC.setup(adapter: maxBannerController) setupCustomParams(for: maxBannerController.prebidConfigId) }), TestCase(title: "Banner 320x50 (MAX) [noBids, MAX Ad]", tags: [.banner, .max, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let maxBannerController = PrebidMAXBannerController(rootController: adapterVC) maxBannerController.prebidConfigId = "imp-prebid-no-bids" maxBannerController.storedAuctionResponse = "response-prebid-no-bids" maxBannerController.maxAdUnitId = "5f111f4bcd0f58ca" maxBannerController.adUnitSize = CGSize(width: 320, height: 50); adapterVC.setup(adapter: maxBannerController) setupCustomParams(for: maxBannerController.prebidConfigId) }), TestCase(title: "Banner 320x50 (MAX) [OK, Random]", tags: [.banner, .max, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let maxBannerController = PrebidMAXBannerController(rootController: adapterVC) maxBannerController.prebidConfigId = "imp-prebid-banner-320-50" maxBannerController.storedAuctionResponse = "response-prebid-banner-320-50" maxBannerController.maxAdUnitId = "5f111f4bcd0f58ca" maxBannerController.adUnitSize = CGSize(width: 320, height: 50); adapterVC.setup(adapter: maxBannerController) setupCustomParams(for: maxBannerController.prebidConfigId) }), TestCase(title: "Banner 320x50 (MAX) [Random, Respective]", tags: [.banner, .max, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let maxBannerController = PrebidMAXBannerController(rootController: adapterVC) maxBannerController.prebidConfigId = "imp-prebid-banner-320-50" maxBannerController.storedAuctionResponse = "response-prebid-banner-320-50" maxBannerController.maxAdUnitId = "5f111f4bcd0f58ca" maxBannerController.adUnitSize = CGSize(width: 320, height: 50); adapterVC.setup(adapter: maxBannerController) setupCustomParams(for: maxBannerController.prebidConfigId) }), TestCase(title: "Banner 300x250 (MAX)", tags: [.banner, .max, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let maxBannerController = PrebidMAXBannerController(rootController: adapterVC) maxBannerController.prebidConfigId = "imp-prebid-banner-300-250" maxBannerController.storedAuctionResponse = "response-prebid-banner-300-250" maxBannerController.maxAdUnitId = "7715f9965a065152" maxBannerController.adUnitSize = CGSize(width: 300, height: 250); adapterVC.setup(adapter: maxBannerController) setupCustomParams(for: maxBannerController.prebidConfigId) }), TestCase(title: "Banner Adaptive (MAX)", tags: [.banner, .max, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let maxBannerController = PrebidMAXBannerController(rootController: adapterVC) maxBannerController.prebidConfigId = "imp-prebid-banner-multisize" maxBannerController.storedAuctionResponse = "response-prebid-banner-multisize" maxBannerController.maxAdUnitId = "5f111f4bcd0f58ca" maxBannerController.adUnitSize = CGSize(width: 320, height: 50); maxBannerController.additionalAdSizes = [CGSize(width: 728, height: 90)] maxBannerController.isAdaptive = true adapterVC.setup(adapter: maxBannerController) setupCustomParams(for: maxBannerController.prebidConfigId) }), // MARK: ---- Interstitial (MAX) ---- TestCase(title: "Display Interstitial 320x480 (MAX) [OK, OXB Adapter]", tags: [.interstitial, .max, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let maxInterstitialController = PrebidMAXInterstitialController(rootController: adapterVC) maxInterstitialController.adFormats = [.display] maxInterstitialController.maxAdUnitId = "78f9d445b8a1add7" maxInterstitialController.prebidConfigId = "imp-prebid-display-interstitial-320-480" maxInterstitialController.storedAuctionResponse = "response-prebid-display-interstitial-320-480" adapterVC.setup(adapter: maxInterstitialController) setupCustomParams(for: maxInterstitialController.prebidConfigId) }), TestCase(title: "Display Interstitial 320x480 (MAX) [noBids, MAX Ad]", tags: [.interstitial, .max, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let maxInterstitialController = PrebidMAXInterstitialController(rootController: adapterVC) maxInterstitialController.adFormats = [.display] maxInterstitialController.prebidConfigId = "imp-prebid-no-bids" maxInterstitialController.storedAuctionResponse = "response-prebid-no-bids" maxInterstitialController.maxAdUnitId = "78f9d445b8a1add7" adapterVC.setup(adapter: maxInterstitialController) setupCustomParams(for: maxInterstitialController.prebidConfigId) }), TestCase(title: "Display Interstitial 320x480 (MAX) [OK, Random]", tags: [.interstitial, .max, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let maxInterstitialController = PrebidMAXInterstitialController(rootController: adapterVC) maxInterstitialController.adFormats = [.display] maxInterstitialController.prebidConfigId = "imp-prebid-display-interstitial-320-480" maxInterstitialController.storedAuctionResponse = "response-prebid-display-interstitial-320-480" maxInterstitialController.maxAdUnitId = "78f9d445b8a1add7" adapterVC.setup(adapter: maxInterstitialController) setupCustomParams(for: maxInterstitialController.prebidConfigId) }), // MARK: ---- Video Interstitial (MAX) ---- TestCase(title: "Video Interstitial 320x480 (MAX) [OK, OXB Adapter]", tags: [.video, .max, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let maxInterstitialController = PrebidMAXInterstitialController(rootController: adapterVC) maxInterstitialController.prebidConfigId = "imp-prebid-video-interstitial-320-480" maxInterstitialController.storedAuctionResponse = "response-prebid-video-interstitial-320-480" maxInterstitialController.adFormats = [.video] maxInterstitialController.maxAdUnitId = "78f9d445b8a1add7" adapterVC.setup(adapter: maxInterstitialController) setupCustomParams(for: maxInterstitialController.prebidConfigId) }), TestCase(title: "Video Interstitial With Ad Configuration 320x480 API (MAX) [OK, OXB Adapter]", tags: [.video, .max, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let maxInterstitialController = PrebidMAXInterstitialController(rootController: adapterVC) maxInterstitialController.prebidConfigId = "imp-prebid-video-interstitial-320-480" maxInterstitialController.storedAuctionResponse = "response-prebid-video-interstitial-320-480" maxInterstitialController.adFormats = [.video] maxInterstitialController.maxAdUnitId = "78f9d445b8a1add7" // Custom video configuration maxInterstitialController.maxDuration = 30 maxInterstitialController.closeButtonArea = 0.15 maxInterstitialController.closeButtonPosition = .topLeft maxInterstitialController.skipDelay = 5 adapterVC.setup(adapter: maxInterstitialController) setupCustomParams(for: maxInterstitialController.prebidConfigId) }), TestCase(title: "Video Interstitial With Ad Configuration With End Card 320x480 API (MAX) [OK, OXB Adapter]", tags: [.video, .max, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let maxInterstitialController = PrebidMAXInterstitialController(rootController: adapterVC) maxInterstitialController.prebidConfigId = "imp-prebid-video-interstitial-320-480-with-end-card" maxInterstitialController.storedAuctionResponse = "response-prebid-video-interstitial-320-480-with-end-card" maxInterstitialController.adFormats = [.video] maxInterstitialController.maxAdUnitId = "78f9d445b8a1add7" // Custom video configuration maxInterstitialController.maxDuration = 30 maxInterstitialController.closeButtonArea = 0.15 maxInterstitialController.closeButtonPosition = .topLeft maxInterstitialController.skipButtonArea = 0.15 maxInterstitialController.skipButtonPosition = .topRight maxInterstitialController.skipDelay = 5 adapterVC.setup(adapter: maxInterstitialController) setupCustomParams(for: maxInterstitialController.prebidConfigId) }), TestCase(title: "Video Interstitial With Ad Configuration 320x480 Server (MAX) [OK, OXB Adapter]", tags: [.video, .max, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let maxInterstitialController = PrebidMAXInterstitialController(rootController: adapterVC) maxInterstitialController.prebidConfigId = "imp-prebid-video-interstitial-320-480" maxInterstitialController.storedAuctionResponse = "response-prebid-video-interstitial-320-480-with-ad-configuration" maxInterstitialController.adFormats = [.video] maxInterstitialController.maxAdUnitId = "78f9d445b8a1add7" adapterVC.setup(adapter: maxInterstitialController) setupCustomParams(for: maxInterstitialController.prebidConfigId) }), TestCase(title: "Video Interstitial With Ad Configuration With End Card 320x480 Server (MAX) [OK, OXB Adapter]", tags: [.video, .max, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let maxInterstitialController = PrebidMAXInterstitialController(rootController: adapterVC) maxInterstitialController.prebidConfigId = "imp-prebid-video-interstitial-320-480-with-end-card" maxInterstitialController.storedAuctionResponse = "response-prebid-video-interstitial-320-480-with-end-card-with-ad-configuration" maxInterstitialController.adFormats = [.video] maxInterstitialController.maxAdUnitId = "78f9d445b8a1add7" adapterVC.setup(adapter: maxInterstitialController) setupCustomParams(for: maxInterstitialController.prebidConfigId) }), TestCase(title: "Video Interstitial 320x480 (MAX) [OK, Random]", tags: [.video, .max, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let maxInterstitialController = PrebidMAXInterstitialController(rootController: adapterVC) maxInterstitialController.prebidConfigId = "imp-prebid-video-interstitial-320-480" maxInterstitialController.storedAuctionResponse = "response-prebid-video-interstitial-320-480" maxInterstitialController.adFormats = [.video] maxInterstitialController.maxAdUnitId = "78f9d445b8a1add7" adapterVC.setup(adapter: maxInterstitialController) setupCustomParams(for: maxInterstitialController.prebidConfigId) }), TestCase(title: "Video Interstitial 320x480 (MAX) [noBids, MAX Ad]", tags: [.video, .max, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let maxInterstitialController = PrebidMAXInterstitialController(rootController: adapterVC) maxInterstitialController.prebidConfigId = "imp-prebid-no-bids" maxInterstitialController.storedAuctionResponse = "response-prebid-no-bids" maxInterstitialController.adFormats = [.video] maxInterstitialController.maxAdUnitId = "78f9d445b8a1add7" adapterVC.setup(adapter: maxInterstitialController) setupCustomParams(for: maxInterstitialController.prebidConfigId) }), // MARK: ---- Multiformat Interstitial (MAX) ---- TestCase(title: "Multiformat Interstitial 320x480 (MAX)", tags: [.interstitial, .video, .max, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let randomId = [0, 1].randomElement() ?? 0 let interstitialController = PrebidMAXInterstitialController(rootController: adapterVC) let prebidStoredAuctionResponses = ["response-prebid-display-interstitial-320-480", "response-prebid-video-interstitial-320-480"] let prebidStoredImps = ["imp-prebid-display-interstitial-320-480", "imp-prebid-video-interstitial-320-480", ] interstitialController.prebidConfigId = prebidStoredImps[randomId] interstitialController.storedAuctionResponse = prebidStoredAuctionResponses[randomId] interstitialController.maxAdUnitId = "78f9d445b8a1add7" adapterVC.setup(adapter: interstitialController) setupCustomParams(for: interstitialController.prebidConfigId) }), // MARK: ---- Video Rewarded (MAX) ---- TestCase(title: "Video Rewarded 320x480 (MAX) [OK, OXB Adapter]", tags: [.video, .max, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let maxRewardedAdController = PrebidMAXRewardedController(rootController: adapterVC) maxRewardedAdController.maxAdUnitId = "8c68716a67d5a5af" maxRewardedAdController.prebidConfigId = "imp-prebid-video-rewarded-320-480" maxRewardedAdController.storedAuctionResponse = "response-prebid-video-rewarded-320-480" adapterVC.setup(adapter: maxRewardedAdController) setupCustomParams(for: maxRewardedAdController.prebidConfigId) }), TestCase(title: "Video Rewarded 320x480 With Ad Configuration Server (MAX) [OK, OXB Adapter]", tags: [.video, .max, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let maxRewardedAdController = PrebidMAXRewardedController(rootController: adapterVC) maxRewardedAdController.maxAdUnitId = "8c68716a67d5a5af" maxRewardedAdController.prebidConfigId = "imp-prebid-video-rewarded-320-480" maxRewardedAdController.storedAuctionResponse = "response-prebid-video-rewarded-320-480-with-ad-configuration" adapterVC.setup(adapter: maxRewardedAdController) setupCustomParams(for: maxRewardedAdController.prebidConfigId) }), TestCase(title: "Video Rewarded 320x480 (MAX) [noBids, MAX Ad]", tags: [.video, .max, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let maxRewardedAdController = PrebidMAXRewardedController(rootController: adapterVC) maxRewardedAdController.maxAdUnitId = "8c68716a67d5a5af" maxRewardedAdController.prebidConfigId = "imp-prebid-no-bids" maxRewardedAdController.storedAuctionResponse = "response-prebid-no-bids" adapterVC.setup(adapter: maxRewardedAdController) setupCustomParams(for: maxRewardedAdController.prebidConfigId) }), TestCase(title: "Video Rewarded 320x480 (MAX) [OK, Random]", tags: [.video, .max, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let maxRewardedAdController = PrebidMAXRewardedController(rootController: adapterVC) maxRewardedAdController.maxAdUnitId = "8c68716a67d5a5af" maxRewardedAdController.prebidConfigId = "imp-prebid-video-rewarded-320-480" maxRewardedAdController.storedAuctionResponse = "response-prebid-video-rewarded-320-480" adapterVC.setup(adapter: maxRewardedAdController) setupCustomParams(for: maxRewardedAdController.prebidConfigId) }), TestCase(title: "Video Rewarded 320x480 without End Card (MAX) [OK, OXB Adapter]", tags: [.video, .max, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let maxRewardedAdController = PrebidMAXRewardedController(rootController: adapterVC) maxRewardedAdController.maxAdUnitId = "8c68716a67d5a5af" maxRewardedAdController.prebidConfigId = "imp-prebid-video-rewarded-320-480-without-end-card" maxRewardedAdController.storedAuctionResponse = "response-prebid-video-rewarded-320-480-without-end-card" adapterVC.setup(adapter: maxRewardedAdController) setupCustomParams(for: maxRewardedAdController.prebidConfigId) }), // MARK: ---- Native (MAX) ---- TestCase(title: "Native Ad (MAX) [OK, OXB Adapter]", tags: [.native, .max, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let nativeController = PrebidMAXNativeController(rootController: adapterVC) nativeController.maxAdUnitId = "f4c3d8281ebf3c39" nativeController.prebidConfigId = "imp-prebid-banner-native-styles" nativeController.storedAuctionResponse = "response-prebid-banner-native-styles" nativeController.nativeAssets = .defaultNativeRequestAssets nativeController.eventTrackers = .defaultNativeEventTrackers adapterVC.setup(adapter: nativeController) setupCustomParams(for: nativeController.prebidConfigId) }), TestCase(title: "Native Ad Events (MAX) [OK, OXB Adapter]", tags: [.native, .max, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } Prebid.shared.prebidServerAccountId = "prebid-stored-request-enabled-events" let nativeController = PrebidMAXNativeController(rootController: adapterVC) nativeController.maxAdUnitId = "f4c3d8281ebf3c39" nativeController.prebidConfigId = "imp-prebid-banner-native-styles" nativeController.storedAuctionResponse = "response-prebid-banner-native-styles" nativeController.nativeAssets = .defaultNativeRequestAssets nativeController.eventTrackers = .defaultNativeEventTrackers adapterVC.setup(adapter: nativeController) setupCustomParams(for: nativeController.prebidConfigId) }), TestCase(title: "Native Ad (MAX) [noBids, MAX Ad]", tags: [.native, .max, .server], exampleVCStoryboardID: "AdapterViewController", configurationClosure: { vc in guard let adapterVC = vc as? AdapterViewController else { return } let nativeController = PrebidMAXNativeController(rootController: adapterVC) nativeController.maxAdUnitId = "f4c3d8281ebf3c39" nativeController.prebidConfigId = "imp-prebid-no-bids" nativeController.storedAuctionResponse = "imp-prebid-no-bids" nativeController.nativeAssets = .defaultNativeRequestAssets nativeController.eventTrackers = .defaultNativeEventTrackers adapterVC.setup(adapter: nativeController) setupCustomParams(for: nativeController.prebidConfigId) }), ] }() // MARK: - Helper Methods private static func setupCustomParams(for prebidConfigId: String) { if let customParams = TestCaseManager.customORTBParams["configId"]?[prebidConfigId] { TestCaseManager.updateUserData(customParams) } } static func createDummyTableCell(for tableView: UITableView) -> TestCaseForTableCell { return TestCaseForTableCell(configurationClosureForTableCell: { cell in cell = tableView.dequeueReusableCell(withIdentifier: "DummyTableViewCell") }); } // MALE, FEMALE, OTHER to PBMGender { private static func strToGender(_ gender: String) -> Gender { switch gender { case "MALE": return .male case "FEMALE": return .female case "OTHER": return .female default: return .unknown } } }
4d757dd17bb344fced716f3a238a7178
53.490638
391
0.578693
false
true
false
false
AnRanScheme/magiGlobe
refs/heads/master
magi/magiGlobe/magiGlobe/Classes/View/Home/View/ARALabel.swift
mit
1
// // ARALabel.swift // swift-magic // // Created by 安然 on 17/2/22. // Copyright © 2017年 安然. All rights reserved. // import UIKit import CoreText let kRegexHighlightViewTypeURL = "url" let kRegexHighlightViewTypeAccount = "account" let kRegexHighlightViewTypeTopic = "topic" let kRegexHighlightViewTypeEmoji = "emoji" let URLRegular = "(http|https)://(t.cn/|weibo.com/)+(([a-zA-Z0-9/])*)" let EmojiRegular = "(\\[\\w+\\])" //let AccountRegular = "@[\u4e00-\u9fa5a-zA-Z0-9_-]{2,30}" let TopicRegular = "#[^#]+#" class ARALabel: UIView { var text: String? var textColor: UIColor? var font: UIFont? var lineSpace: NSInteger? var textAlignment: NSTextAlignment? /* UIImageView *labelImageView; UIImageView *highlightImageView; BOOL highlighting; BOOL btnLoaded; BOOL emojiLoaded; NSRange currentRange; NSMutableDictionary *highlightColors; NSMutableDictionary *framesDict; NSInteger drawFlag; */ private var labelImageView: UIImageView? private var highlightImageView: UIImageView? private var highlighting: Bool? private var btnLoaded: Bool? private var emojiLoaded: Bool? private var currentRange: NSRange? private var highlightColors: NSMutableDictionary? private var framesDict: NSMutableDictionary? private var drawFlag: UInt32? override init(frame: CGRect) { super.init(frame: frame) drawFlag = arc4random() framesDict = NSMutableDictionary() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
caa14e5e8413ba98605029f547ab5111
21.881579
75
0.636573
false
false
false
false
hagmas/APNsKit
refs/heads/master
APNsKit/APNsRequest.swift
mit
1
import Foundation public struct APNsRequest { public struct Header { public enum Priority: String { case p5 = "5", p10 = "10" } public let id: String public let expiration: Date public let priority: Priority public let topic: String? public let collapseId: String? public init(id: String = UUID().uuidString, expiration: Date = Date(timeIntervalSince1970: 0), priority: Priority = .p10, topic: String? = nil, collapseId: String? = nil) { self.id = id self.expiration = expiration self.priority = .p10 self.topic = topic self.collapseId = collapseId } } public var port: APNsPort public var server: APNsServer public var deviceToken: String public var header: Header public var payload: APNsPayload public static let method = "POST" public init(port: APNsPort, server: APNsServer, deviceToken: String, header: Header = Header(), payload: APNsPayload) { self.port = port self.server = server self.deviceToken = deviceToken self.header = header self.payload = payload } public var url: URL? { let urlString = "https://" + server.rawValue + ":\(port.rawValue)" + "/3/device/" + deviceToken return URL(string: urlString) } public var urlRequest: URLRequest? { guard let url = url else { return nil } var request = URLRequest(url: url) request.setValue(for: header) request.httpMethod = APNsRequest.method request.httpBody = payload.data return request } } private extension URLRequest { mutating func setValue(for header: APNsRequest.Header) { self.addValue(header.id, forHTTPHeaderField: "apns-id") self.addValue("\(Int(header.expiration.timeIntervalSince1970))", forHTTPHeaderField: "apns-expiration") self.addValue(header.priority.rawValue, forHTTPHeaderField: "apns-priority") if let topic = header.topic { self.addValue(topic, forHTTPHeaderField: "apns-topic") } if let collapseId = header.collapseId { self.addValue(collapseId, forHTTPHeaderField: "apns-collapse-id") } } }
101117372169cede68a2fe9c2b85cc90
31.092105
123
0.585896
false
false
false
false
dymx101/Gamers
refs/heads/master
Gamers/Service/SliderBL.swift
apache-2.0
1
// // SliderBL.swift // Gamers // // Created by 虚空之翼 on 15/7/15. // Copyright (c) 2015年 Freedom. All rights reserved. // import Foundation import Alamofire import Bolts import SwiftyJSON class SliderBL: NSObject { // 单例模式 static let sharedSingleton = SliderBL() /** 获取首页顶部的轮播信息 :returns: 成功轮播列表,失败错误信息 */ func getHomeSlider() -> BFTask { var fetchTask = BFTask(result: nil) fetchTask = fetchTask.continueWithBlock({ (task) -> AnyObject! in return SliderDao.getHomeSlider() }) fetchTask = fetchTask.continueWithSuccessBlock({ (task) -> AnyObject! in if let sliders = task.result as? [Slider] { return BFTask(result: sliders) } if let response = task.result as? Response { return BFTask(result: response) } return task }) fetchTask = fetchTask.continueWithBlock({ (task) -> AnyObject! in return task }) return fetchTask } /** 获取频道的轮播信息 :param: channelId 频道ID :returns: 成功轮播列表,失败错误信息 */ func getChannelSlider(#channelId: String) -> BFTask { var fetchTask = BFTask(result: nil) fetchTask = fetchTask.continueWithBlock({ (task) -> AnyObject! in return SliderDao.getChannelSlider(channelId: channelId) }) fetchTask = fetchTask.continueWithSuccessBlock({ (task) -> AnyObject! in if let sliders = task.result as? [Slider] { return BFTask(result: sliders) } if let response = task.result as? Response { return BFTask(result: response) } return task }) fetchTask = fetchTask.continueWithBlock({ (task) -> AnyObject! in return task }) return fetchTask } }
5b46a7e5abfbda71f4a031f66944362f
24.1375
80
0.535323
false
false
false
false
xiaomudegithub/viossvc
refs/heads/master
viossvc/Scenes/User/AddServerController.swift
apache-2.0
1
// // AddServerController.swift // viossvc // // Created by 木柳 on 2016/12/1. // Copyright © 2016年 com.yundian. All rights reserved. // import UIKit import SVProgressHUD class AddServerController: UIViewController,UIPickerViewDelegate,UIPickerViewDataSource,UITextFieldDelegate { @IBOutlet weak var contentView: UIView! @IBOutlet weak var serviceNameText: UITextField! @IBOutlet weak var servicePriceText: UITextField! @IBOutlet weak var startTimeLabel: UILabel! @IBOutlet weak var endTimeLabel: UILabel! @IBOutlet weak var typeLabel: UILabel! @IBOutlet weak var picker: UIPickerView! @IBOutlet weak var pickerViewBottomConstraint: NSLayoutConstraint! @IBOutlet weak var contentToTopConstraint: NSLayoutConstraint! @IBOutlet weak var timeIconLabel: UILabel! enum PickType { case StartTime case EndTime case Type } var isTime: Bool = true var types = ["高端游", "商务游"] var pickType: PickType? var complete:CompleteBlock? var changeModel: UserServerModel?{ didSet{ if changeModel == nil { return } serviceNameText.text = changeModel?.service_name servicePriceText.text = "\(Double(changeModel!.service_price)/100)" startTimeLabel.text = timeStr((changeModel?.service_start)!) endTimeLabel.text = timeStr(changeModel!.service_end) typeLabel.text = changeModel!.change_type == 0 ? "高端游" : "商务游" } } //MARK: --LIFECYCLE override func viewDidLoad() { super.viewDidLoad() initUI() } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { super.touchesBegan(touches, withEvent: event) hideKeyboard() hiddlePick() } //MARK: --UI func initUI() { contentView.layer.cornerRadius = 8 contentView.layer.masksToBounds = true contentView.userInteractionEnabled = true picker.showsSelectionIndicator = false for i in 100...102{ let view = contentView.viewWithTag(i) view?.layer.cornerRadius = 4 view?.layer.masksToBounds = true } } @IBAction func choseStarTime(sender: AnyObject) { MobClick.event(AppConst.Event.server_start) pickType = .StartTime isTime = true showPickView() } @IBAction func choseEndTime(sender: AnyObject) { MobClick.event(AppConst.Event.server_end) pickType = .EndTime isTime = true showPickView() } @IBAction func choseType(sender: AnyObject) { MobClick.event(AppConst.Event.server_type) pickType = .Type isTime = false showPickView() } @IBAction func cancelBtnTapped(sender: AnyObject) { MobClick.event(AppConst.Event.server_cancelAdd) hiddlePick() dismissController() } @IBAction func SureBtnTapped(sender: AnyObject) { if checkServerTime([time(startTimeLabel.text!),time(endTimeLabel.text!)]) == false { return } if time(startTimeLabel.text!) > time(endTimeLabel.text!) { SVProgressHUD.showWainningMessage(WainningMessage: "服务结束时间应晚于服务开始时间", ForDuration: 1, completion: nil) return } if checkTextFieldEmpty([serviceNameText,servicePriceText]) { let model = UserServerModel() model.change_type = changeModel == nil ? 2 : 1 model.service_name = serviceNameText.text model.service_price = Int(Double(servicePriceText.text!)! * 100) model.service_type = typeLabel.text == "高端游" ? 0 : 1 model.service_start = time(startTimeLabel.text!) model.service_end = time(endTimeLabel.text!) if complete != nil { complete!(model) } hiddlePick() dismissController() } } func time(timeStr: String) -> Int { let timeNSStr = timeStr as NSString let hourStr = timeNSStr.substringToIndex(2) let minuStr = timeNSStr.substringFromIndex(3) let minus = Int(hourStr)! * 60 + Int(minuStr)! return minus } func timeStr(minus: Int) -> String { let hour = minus / 60 let leftMinus = minus % 60 let hourStr = hour > 9 ? "\(hour)":"0\(hour)" let minusStr = leftMinus > 9 ? "\(minus)":"0\(leftMinus)" return "\(hourStr):\(minusStr)" } func checkServerTime(times: [Int]) -> Bool { for time in times { if time < 8*60 || time > 21*60 { SVProgressHUD.showWainningMessage(WainningMessage: "请将服务时间设置介于早上8:00~晚上9:00之间", ForDuration: 1, completion: nil) return false } } return true } //MARK: --TextField func textFieldDidBeginEditing(textField: UITextField) { hiddlePick() if textField == servicePriceText { MobClick.event(AppConst.Event.server_price) } } //MARK: --Picker func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return isTime ? 2 : 1 } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return isTime ? (component == 0 ? 24 : 60) : types.count } func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { if isTime == false { return types[row] } let title = row > 9 ? "\(row)" : "0\(row)" return title } func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { if pickType == .Type { typeLabel.text = types[row] return } var rowStr = row > 9 ? "\(row)" : "0\(row)" if pickType == .StartTime { let hourStr = (self.startTimeLabel!.text! as NSString).substringToIndex(2) let minusStr = (self.startTimeLabel!.text! as NSString).substringFromIndex(3) startTimeLabel.text = component == 0 ? "\(rowStr):\(minusStr)" : "\(hourStr):\(rowStr)" return } if pickType == .EndTime { let hourStr = (self.endTimeLabel!.text! as NSString).substringToIndex(2) let minusStr = (self.endTimeLabel!.text! as NSString).substringFromIndex(3) if row == 0 && component == 0{ rowStr = "24" } endTimeLabel.text = component == 0 ? "\(rowStr):\(minusStr)" : "\(hourStr):\(rowStr)" return } } func showPickView() { view.endEditing(true) timeIconLabel.hidden = pickType == .Type pickerViewBottomConstraint.constant = 0 picker?.reloadAllComponents() contentToTopConstraint.constant = 20 } func hiddlePick() { pickerViewBottomConstraint.constant = -225 contentToTopConstraint.constant = 100 } }
52a97d98177d276ce526eef107d1373c
34.71
128
0.601372
false
false
false
false
miguelgutierrez/Curso-iOS-Swift-Programming-Netmind
refs/heads/master
newsApp 1.5/newsApp/ArticuloViewController.swift
mit
1
// // ArticuloViewController.swift // newsApp // // Created by Miguel Gutiérrez Moreno on 23/1/15. // Copyright (c) 2015 MGM. All rights reserved. // /* * v 1.2: tratamiento del artículo y muestra un View Controller (en Modal) * v 1.4: revisar Storyboard * v 1.5: permite guardar artículos en la tabla y seleccionar la fecha con DatePicker */ import UIKit struct FormatoFecha { static let formatoGeneral = "dd/MM/yyyy" } class ArticuloViewController: UIViewController, UITextFieldDelegate { struct MainStoryboard { struct SegueIdentifiers { static let muestraDetalleArticulo = "muestraDetalleArticulo" static let aFecha = "aFecha" } } // MARK: properties @IBOutlet weak var nombreEscritorTextField: UITextField! @IBOutlet weak var fechaArticuloTextField: UITextField! @IBOutlet weak var textoArticuloTextView: UITextView! weak var delegate : ArticulosTableViewController? var articulo : Articulo! // MARK: life cicle override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. if segue.identifier == MainStoryboard.SegueIdentifiers.muestraDetalleArticulo { let muestraDetalleArticuloController = segue.destinationViewController as! DetalleArticuloViewController muestraDetalleArticuloController.articulo = articulo } else if segue.identifier == MainStoryboard.SegueIdentifiers.aFecha { let fechaController = segue.destinationViewController as! FechaViewController fechaController.delegate = self } } // MARK: cerrar el teclado: el usuario pulsa en la view override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { super.touchesBegan(touches, withEvent: event) self.view.endEditing(true) } func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true } // MARK: eventos @IBAction func grabar(sender: UIButton) { if let nombre = nombreEscritorTextField.text{ articulo.nombre = nombre } if let texto = textoArticuloTextView.text{ articulo.texto = texto } let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = FormatoFecha.formatoGeneral if let fecha = fechaArticuloTextField.text { articulo.fecha = dateFormatter.dateFromString(fecha) } delegate?.cerrar(self) // self.navigationController?.popViewControllerAnimated(true) } // MARK: interface func actualizaFecha (fecha : NSDate) { let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = FormatoFecha.formatoGeneral fechaArticuloTextField.text = dateFormatter.stringFromDate(fecha) articulo.fecha = fecha } }
e51ba8b65be84cb6f8fb78f2ea34e7fb
31.934579
116
0.669977
false
false
false
false
LukaszLiberda/Swift-Design-Patterns
refs/heads/master
PatternProj/Creational/PrototypePattern.swift
gpl-2.0
1
// // PrototypePattern.swift // PatternProj // // Created by lukaszliberda on 06.07.2015. // Copyright (c) 2015 lukasz. All rights reserved. // import Foundation /* The prototype pattern is used to instantiate a new object by copying all of the properties of an existing object, creating an independent clone. This practise is particularly useful when the construction of a new object is inefficient. The prototype pattern is a creational design pattern in software development. It is used when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects. This pattern is used to: avoid subclasses of an object creator in the client application, like the abstract factory pattern does. avoid the inherent cost of creating a new object in the standard way (e.g., using the 'new' keyword) when it is prohibitively expensive for a given application. To implement the pattern, declare an abstract base class that specifies a pure virtual clone() method. Any class that needs a "polymorphic constructor" capability derives itself from the abstract base class, and implements the clone() operation. The client, instead of writing code that invokes the "new" operator on a hard-coded class name, calls the clone() method on the prototype, calls a factory method with a parameter designating the particular concrete derived class desired, or invokes the clone() method through some mechanism provided by another design pattern. The mitotic division of a cell — resulting in two identical cells — is an example of a prototype that plays an active role in copying itself and thus, demonstrates the Prototype pattern. When a cell splits, two cells of identical genotype result. In other words, the cell clones itself.[1] */ class ChungasRevengeDisplay { var name: String? let font: String init(font: String) { self.font = font } func clone() -> ChungasRevengeDisplay { return ChungasRevengeDisplay(font: self.font) } } /* usage */ class TestPrototype { func test() { let prototype = ChungasRevengeDisplay(font: "Project") let philippe = prototype.clone() philippe.name = "Philippe" let christoph = prototype.clone() christoph.name = "Christoph" let eduardo = prototype.clone() eduardo.name = "Eduardo" println() } func test2() { var pBin:BinPrototypesModule = BinPrototypesModule() pBin.addBinPrototype(Bin()) pBin.addBinPrototype(Bin()) pBin.addBinPrototype(TheOther()) var binObject: [BinPrototype] = [] var total: Int = 0 var sty: [String] = ["The other", "Bin", "The", "Bin", "The other", "Bin", "other", "Bin", "The other", "The other"] for i in 0...9 { if let binObj = pBin.findAndClone(sty[i]) { binObject.append(binObj) total++ } } for obj in binObject { println("obj \(obj)") if let bObj = obj as? BinCommand { println("\(bObj)--> ") bObj.binExecute() } } println() } } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// protocol BinPrototype { func clone() -> BinPrototype func name() -> String } protocol BinCommand { func binExecute() } class BinPrototypesModule { private var prototypes: [BinPrototype] = [] private var total: Int = 0 func addBinPrototype(obj: BinPrototype) { prototypes.append(obj) total++ } func findAndClone(name: String) -> BinPrototype? { for binProtot in prototypes { if binProtot.name() == name { return binProtot } } return nil } } class Bin: BinPrototype, BinCommand { func clone() -> BinPrototype { return Bin() } func name() -> String { return "Bin" } func binExecute() { println("Bin execute") } } class TheOther: BinPrototype, BinCommand { func clone() -> BinPrototype { return TheOther() } func name() -> String { return "The other" } func binExecute() { println("The other execute") } }
0edbd70c483e5751c5aa8b48bb7b1a59
24.959064
326
0.612976
false
false
false
false
mitchtreece/Spider
refs/heads/master
DYLive/Pods/Kingfisher/Sources/Views/AnimatedImageView.swift
mit
2
// // AnimatableImageView.swift // Kingfisher // // Created by bl4ckra1sond3tre on 4/22/16. // // The AnimatableImageView, AnimatedFrame and Animator is a modified version of // some classes from kaishin's Gifu project (https://github.com/kaishin/Gifu) // // The MIT License (MIT) // // Copyright (c) 2019 Reda Lemeden. // // 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. // // The name and characters used in the demo of this software are property of their // respective owners. #if !os(watchOS) #if canImport(UIKit) import UIKit import ImageIO /// Protocol of `AnimatedImageView`. public protocol AnimatedImageViewDelegate: AnyObject { /// Called after the animatedImageView has finished each animation loop. /// /// - Parameters: /// - imageView: The `AnimatedImageView` that is being animated. /// - count: The looped count. func animatedImageView(_ imageView: AnimatedImageView, didPlayAnimationLoops count: UInt) /// Called after the `AnimatedImageView` has reached the max repeat count. /// /// - Parameter imageView: The `AnimatedImageView` that is being animated. func animatedImageViewDidFinishAnimating(_ imageView: AnimatedImageView) } extension AnimatedImageViewDelegate { public func animatedImageView(_ imageView: AnimatedImageView, didPlayAnimationLoops count: UInt) {} public func animatedImageViewDidFinishAnimating(_ imageView: AnimatedImageView) {} } let KFRunLoopModeCommon = RunLoop.Mode.common /// Represents a subclass of `UIImageView` for displaying animated image. /// Different from showing animated image in a normal `UIImageView` (which load all frames at one time), /// `AnimatedImageView` only tries to load several frames (defined by `framePreloadCount`) to reduce memory usage. /// It provides a tradeoff between memory usage and CPU time. If you have a memory issue when using a normal image /// view to load GIF data, you could give this class a try. /// /// Kingfisher supports setting GIF animated data to either `UIImageView` and `AnimatedImageView` out of box. So /// it would be fairly easy to switch between them. open class AnimatedImageView: UIImageView { /// Proxy object for preventing a reference cycle between the `CADDisplayLink` and `AnimatedImageView`. class TargetProxy { private weak var target: AnimatedImageView? init(target: AnimatedImageView) { self.target = target } @objc func onScreenUpdate() { target?.updateFrameIfNeeded() } } /// Enumeration that specifies repeat count of GIF public enum RepeatCount: Equatable { case once case finite(count: UInt) case infinite public static func ==(lhs: RepeatCount, rhs: RepeatCount) -> Bool { switch (lhs, rhs) { case let (.finite(l), .finite(r)): return l == r case (.once, .once), (.infinite, .infinite): return true case (.once, .finite(let count)), (.finite(let count), .once): return count == 1 case (.once, _), (.infinite, _), (.finite, _): return false } } } // MARK: - Public property /// Whether automatically play the animation when the view become visible. Default is `true`. public var autoPlayAnimatedImage = true /// The count of the frames should be preloaded before shown. public var framePreloadCount = 10 /// Specifies whether the GIF frames should be pre-scaled to the image view's size or not. /// If the downloaded image is larger than the image view's size, it will help to reduce some memory use. /// Default is `true`. public var needsPrescaling = true /// Decode the GIF frames in background thread before using. It will decode frames data and do a off-screen /// rendering to extract pixel information in background. This can reduce the main thread CPU usage. public var backgroundDecode = true /// The animation timer's run loop mode. Default is `RunLoop.Mode.common`. /// Set this property to `RunLoop.Mode.default` will make the animation pause during UIScrollView scrolling. public var runLoopMode = KFRunLoopModeCommon { willSet { guard runLoopMode != newValue else { return } stopAnimating() displayLink.remove(from: .main, forMode: runLoopMode) displayLink.add(to: .main, forMode: newValue) startAnimating() } } /// The repeat count. The animated image will keep animate until it the loop count reaches this value. /// Setting this value to another one will reset current animation. /// /// Default is `.infinite`, which means the animation will last forever. public var repeatCount = RepeatCount.infinite { didSet { if oldValue != repeatCount { reset() setNeedsDisplay() layer.setNeedsDisplay() } } } /// Delegate of this `AnimatedImageView` object. See `AnimatedImageViewDelegate` protocol for more. public weak var delegate: AnimatedImageViewDelegate? /// The `Animator` instance that holds the frames of a specific image in memory. public private(set) var animator: Animator? // MARK: - Private property // Dispatch queue used for preloading images. private lazy var preloadQueue: DispatchQueue = { return DispatchQueue(label: "com.onevcat.Kingfisher.Animator.preloadQueue") }() // A flag to avoid invalidating the displayLink on deinit if it was never created, because displayLink is so lazy. private var isDisplayLinkInitialized: Bool = false // A display link that keeps calling the `updateFrame` method on every screen refresh. private lazy var displayLink: CADisplayLink = { isDisplayLinkInitialized = true let displayLink = CADisplayLink(target: TargetProxy(target: self), selector: #selector(TargetProxy.onScreenUpdate)) displayLink.add(to: .main, forMode: runLoopMode) displayLink.isPaused = true return displayLink }() // MARK: - Override override open var image: KFCrossPlatformImage? { didSet { if image != oldValue { reset() } setNeedsDisplay() layer.setNeedsDisplay() } } open override var isHighlighted: Bool { get { super.isHighlighted } set { // Highlighted image is unsupported for animated images. // See https://github.com/onevcat/Kingfisher/issues/1679 if displayLink.isPaused { super.isHighlighted = newValue } } } deinit { if isDisplayLinkInitialized { displayLink.invalidate() } } override open var isAnimating: Bool { if isDisplayLinkInitialized { return !displayLink.isPaused } else { return super.isAnimating } } /// Starts the animation. override open func startAnimating() { guard !isAnimating else { return } guard let animator = animator else { return } guard !animator.isReachMaxRepeatCount else { return } displayLink.isPaused = false } /// Stops the animation. override open func stopAnimating() { super.stopAnimating() if isDisplayLinkInitialized { displayLink.isPaused = true } } override open func display(_ layer: CALayer) { layer.contents = animator?.currentFrameImage?.cgImage ?? image?.cgImage } override open func didMoveToWindow() { super.didMoveToWindow() didMove() } override open func didMoveToSuperview() { super.didMoveToSuperview() didMove() } // This is for back compatibility that using regular `UIImageView` to show animated image. override func shouldPreloadAllAnimation() -> Bool { return false } // Reset the animator. private func reset() { animator = nil if let image = image, let imageSource = image.kf.imageSource { let targetSize = bounds.scaled(UIScreen.main.scale).size let animator = Animator( imageSource: imageSource, contentMode: contentMode, size: targetSize, imageSize: image.kf.size, imageScale: image.kf.scale, framePreloadCount: framePreloadCount, repeatCount: repeatCount, preloadQueue: preloadQueue) animator.delegate = self animator.needsPrescaling = needsPrescaling animator.backgroundDecode = backgroundDecode animator.prepareFramesAsynchronously() self.animator = animator } didMove() } private func didMove() { if autoPlayAnimatedImage && animator != nil { if let _ = superview, let _ = window { startAnimating() } else { stopAnimating() } } } /// Update the current frame with the displayLink duration. private func updateFrameIfNeeded() { guard let animator = animator else { return } guard !animator.isFinished else { stopAnimating() delegate?.animatedImageViewDidFinishAnimating(self) return } let duration: CFTimeInterval // CA based display link is opt-out from ProMotion by default. // So the duration and its FPS might not match. // See [#718](https://github.com/onevcat/Kingfisher/issues/718) // By setting CADisableMinimumFrameDuration to YES in Info.plist may // cause the preferredFramesPerSecond being 0 let preferredFramesPerSecond = displayLink.preferredFramesPerSecond if preferredFramesPerSecond == 0 { duration = displayLink.duration } else { // Some devices (like iPad Pro 10.5) will have a different FPS. duration = 1.0 / TimeInterval(preferredFramesPerSecond) } animator.shouldChangeFrame(with: duration) { [weak self] hasNewFrame in if hasNewFrame { self?.layer.setNeedsDisplay() } } } } protocol AnimatorDelegate: AnyObject { func animator(_ animator: AnimatedImageView.Animator, didPlayAnimationLoops count: UInt) } extension AnimatedImageView: AnimatorDelegate { func animator(_ animator: Animator, didPlayAnimationLoops count: UInt) { delegate?.animatedImageView(self, didPlayAnimationLoops: count) } } extension AnimatedImageView { // Represents a single frame in a GIF. struct AnimatedFrame { // The image to display for this frame. Its value is nil when the frame is removed from the buffer. let image: UIImage? // The duration that this frame should remain active. let duration: TimeInterval // A placeholder frame with no image assigned. // Used to replace frames that are no longer needed in the animation. var placeholderFrame: AnimatedFrame { return AnimatedFrame(image: nil, duration: duration) } // Whether this frame instance contains an image or not. var isPlaceholder: Bool { return image == nil } // Returns a new instance from an optional image. // // - parameter image: An optional `UIImage` instance to be assigned to the new frame. // - returns: An `AnimatedFrame` instance. func makeAnimatedFrame(image: UIImage?) -> AnimatedFrame { return AnimatedFrame(image: image, duration: duration) } } } extension AnimatedImageView { // MARK: - Animator /// An animator which used to drive the data behind `AnimatedImageView`. public class Animator { private let size: CGSize private let imageSize: CGSize private let imageScale: CGFloat /// The maximum count of image frames that needs preload. public let maxFrameCount: Int private let imageSource: CGImageSource private let maxRepeatCount: RepeatCount private let maxTimeStep: TimeInterval = 1.0 private let animatedFrames = SafeArray<AnimatedFrame>() private var frameCount = 0 private var timeSinceLastFrameChange: TimeInterval = 0.0 private var currentRepeatCount: UInt = 0 var isFinished: Bool = false var needsPrescaling = true var backgroundDecode = true weak var delegate: AnimatorDelegate? // Total duration of one animation loop var loopDuration: TimeInterval = 0 /// The image of the current frame. public var currentFrameImage: UIImage? { return frame(at: currentFrameIndex) } /// The duration of the current active frame duration. public var currentFrameDuration: TimeInterval { return duration(at: currentFrameIndex) } /// The index of the current animation frame. public internal(set) var currentFrameIndex = 0 { didSet { previousFrameIndex = oldValue } } var previousFrameIndex = 0 { didSet { preloadQueue.async { self.updatePreloadedFrames() } } } var isReachMaxRepeatCount: Bool { switch maxRepeatCount { case .once: return currentRepeatCount >= 1 case .finite(let maxCount): return currentRepeatCount >= maxCount case .infinite: return false } } /// Whether the current frame is the last frame or not in the animation sequence. public var isLastFrame: Bool { return currentFrameIndex == frameCount - 1 } var preloadingIsNeeded: Bool { return maxFrameCount < frameCount - 1 } var contentMode = UIView.ContentMode.scaleToFill private lazy var preloadQueue: DispatchQueue = { return DispatchQueue(label: "com.onevcat.Kingfisher.Animator.preloadQueue") }() /// Creates an animator with image source reference. /// /// - Parameters: /// - source: The reference of animated image. /// - mode: Content mode of the `AnimatedImageView`. /// - size: Size of the `AnimatedImageView`. /// - imageSize: Size of the `KingfisherWrapper`. /// - imageScale: Scale of the `KingfisherWrapper`. /// - count: Count of frames needed to be preloaded. /// - repeatCount: The repeat count should this animator uses. /// - preloadQueue: Dispatch queue used for preloading images. init(imageSource source: CGImageSource, contentMode mode: UIView.ContentMode, size: CGSize, imageSize: CGSize, imageScale: CGFloat, framePreloadCount count: Int, repeatCount: RepeatCount, preloadQueue: DispatchQueue) { self.imageSource = source self.contentMode = mode self.size = size self.imageSize = imageSize self.imageScale = imageScale self.maxFrameCount = count self.maxRepeatCount = repeatCount self.preloadQueue = preloadQueue GraphicsContext.begin(size: imageSize, scale: imageScale) } deinit { GraphicsContext.end() } /// Gets the image frame of a given index. /// - Parameter index: The index of desired image. /// - Returns: The decoded image at the frame. `nil` if the index is out of bound or the image is not yet loaded. public func frame(at index: Int) -> KFCrossPlatformImage? { return animatedFrames[index]?.image } public func duration(at index: Int) -> TimeInterval { return animatedFrames[index]?.duration ?? .infinity } func prepareFramesAsynchronously() { frameCount = Int(CGImageSourceGetCount(imageSource)) animatedFrames.reserveCapacity(frameCount) preloadQueue.async { [weak self] in self?.setupAnimatedFrames() } } func shouldChangeFrame(with duration: CFTimeInterval, handler: (Bool) -> Void) { incrementTimeSinceLastFrameChange(with: duration) if currentFrameDuration > timeSinceLastFrameChange { handler(false) } else { resetTimeSinceLastFrameChange() incrementCurrentFrameIndex() handler(true) } } private func setupAnimatedFrames() { resetAnimatedFrames() var duration: TimeInterval = 0 (0..<frameCount).forEach { index in let frameDuration = GIFAnimatedImage.getFrameDuration(from: imageSource, at: index) duration += min(frameDuration, maxTimeStep) animatedFrames.append(AnimatedFrame(image: nil, duration: frameDuration)) if index > maxFrameCount { return } animatedFrames[index] = animatedFrames[index]?.makeAnimatedFrame(image: loadFrame(at: index)) } self.loopDuration = duration } private func resetAnimatedFrames() { animatedFrames.removeAll() } private func loadFrame(at index: Int) -> UIImage? { let resize = needsPrescaling && size != .zero let options: [CFString: Any]? if resize { options = [ kCGImageSourceCreateThumbnailFromImageIfAbsent: true, kCGImageSourceCreateThumbnailWithTransform: true, kCGImageSourceShouldCacheImmediately: true, kCGImageSourceThumbnailMaxPixelSize: max(size.width, size.height) ] } else { options = nil } guard let cgImage = CGImageSourceCreateImageAtIndex(imageSource, index, options as CFDictionary?) else { return nil } let image = KFCrossPlatformImage(cgImage: cgImage) guard let context = GraphicsContext.current(size: imageSize, scale: imageScale, inverting: true, cgImage: cgImage) else { return image } return backgroundDecode ? image.kf.decoded(on: context) : image } private func updatePreloadedFrames() { guard preloadingIsNeeded else { return } animatedFrames[previousFrameIndex] = animatedFrames[previousFrameIndex]?.placeholderFrame preloadIndexes(start: currentFrameIndex).forEach { index in guard let currentAnimatedFrame = animatedFrames[index] else { return } if !currentAnimatedFrame.isPlaceholder { return } animatedFrames[index] = currentAnimatedFrame.makeAnimatedFrame(image: loadFrame(at: index)) } } private func incrementCurrentFrameIndex() { let wasLastFrame = isLastFrame currentFrameIndex = increment(frameIndex: currentFrameIndex) if isLastFrame { currentRepeatCount += 1 if isReachMaxRepeatCount { isFinished = true // Notify the delegate here because the animation is stopping. delegate?.animator(self, didPlayAnimationLoops: currentRepeatCount) } } else if wasLastFrame { // Notify the delegate that the loop completed delegate?.animator(self, didPlayAnimationLoops: currentRepeatCount) } } private func incrementTimeSinceLastFrameChange(with duration: TimeInterval) { timeSinceLastFrameChange += min(maxTimeStep, duration) } private func resetTimeSinceLastFrameChange() { timeSinceLastFrameChange -= currentFrameDuration } private func increment(frameIndex: Int, by value: Int = 1) -> Int { return (frameIndex + value) % frameCount } private func preloadIndexes(start index: Int) -> [Int] { let nextIndex = increment(frameIndex: index) let lastIndex = increment(frameIndex: index, by: maxFrameCount) if lastIndex >= nextIndex { return [Int](nextIndex...lastIndex) } else { return [Int](nextIndex..<frameCount) + [Int](0...lastIndex) } } } } class SafeArray<Element> { private var array: Array<Element> = [] private let lock = NSLock() subscript(index: Int) -> Element? { get { lock.lock() defer { lock.unlock() } return array.indices ~= index ? array[index] : nil } set { lock.lock() defer { lock.unlock() } if let newValue = newValue, array.indices ~= index { array[index] = newValue } } } var count : Int { lock.lock() defer { lock.unlock() } return array.count } func reserveCapacity(_ count: Int) { lock.lock() defer { lock.unlock() } array.reserveCapacity(count) } func append(_ element: Element) { lock.lock() defer { lock.unlock() } array += [element] } func removeAll() { lock.lock() defer { lock.unlock() } array = [] } } #endif #endif
d203088e5e7e2d186c66162781793a31
34.259484
133
0.610819
false
false
false
false
mikezone/EffectiveSwift
refs/heads/master
EffectiveSwift/Extension/Foundation/Data+SE.swift
gpl-3.0
1
// // Data+MKAdd.swift // SwiftExtension // // Created by Mike on 17/1/20. // Copyright © 2017年 Mike. All rights reserved. // import Foundation import CommonCrypto // MARK: - Hash public extension Data { public var md2String: String? { return String(data: self, encoding: .utf8)?.md2String } public var md4String: String? { return String(data: self, encoding: .utf8)?.md4String } public var md5String: String? { return String(data: self, encoding: .utf8)?.md5String } public var sha1String: String? { return String(data: self, encoding: .utf8)?.sha1String } public var sha224String: String? { return String(data: self, encoding: .utf8)?.sha224String } public var sha256String: String? { return String(data: self, encoding: .utf8)?.sha256String } public var sha384String: String? { return String(data: self, encoding: .utf8)?.sha384String } public var sha512String: String? { return String(data: self, encoding: .utf8)?.sha512String } public func hmacString(_ algorithm: CCHmacAlgorithm, _ key: String) -> String? { return String(data: self, encoding: .utf8)?.hmacString(algorithm, key) } public func hmacMD5String(_ key: String) -> String? { return hmacString(CCHmacAlgorithm(kCCHmacAlgMD5), key) } public func hmacSHA1String(_ key: String) -> String? { return hmacString(CCHmacAlgorithm(kCCHmacAlgSHA1), key) } public func hmacSHA224String(_ key: String) -> String? { return hmacString(CCHmacAlgorithm(kCCHmacAlgSHA224), key) } public func hmacSHA256String(_ key: String) -> String? { return hmacString(CCHmacAlgorithm(kCCHmacAlgSHA256), key) } public func hmacSHA384String(_ key: String) -> String? { return hmacString(CCHmacAlgorithm(kCCHmacAlgSHA384), key) } public func hmacSHA512String(_ key: String) -> String? { return hmacString(CCHmacAlgorithm(kCCHmacAlgSHA512), key) } public var crc32String: String? { guard let crc32Value = self.crc32Value else { return nil } return String(format: "%08x", crc32Value) } public var crc32Value: UInt? { return String(data: self, encoding: .utf8)?.crc32Value } } // MARK: - Encrypt and Decrypt public extension Data { public func aes256Encrypt(_ key: Data, _ iv: Data) -> Data? { if key.count != 16 && key.count != 24 && key.count != 32 { return nil } if iv.count != 16 && key.count != 0 { return nil } let bufferSize = self.count + kCCBlockSizeAES128 let buffer = UnsafeMutablePointer<CChar>.allocate(capacity: bufferSize) var encryptedSize: Int = 0; let cryptStatus = CCCrypt(CCOperation(kCCEncrypt), CCAlgorithm(kCCAlgorithmAES128), CCOptions(kCCOptionPKCS7Padding), String(data: key, encoding: .utf8)?.cString(using: .utf8), key.count, String(data: iv, encoding: .utf8)?.cString(using: .utf8), String(data: self, encoding: .utf8)?.cString(using: .utf8), self.count, buffer, bufferSize, &encryptedSize); if cryptStatus == CCCryptorStatus(kCCSuccess) { let result = Data(bytes: buffer, count: encryptedSize) free(buffer); return result; } else { free(buffer); return nil; } } public func aes256Decrypt(_ key: Data, _ iv: Data) -> Data? { if key.count != 16 && key.count != 24 && key.count != 32 { return nil } if iv.count != 16 && key.count != 0 { return nil } let bufferSize = self.count + kCCBlockSizeAES128 let buffer = UnsafeMutablePointer<CChar>.allocate(capacity: bufferSize) var encryptedSize: Int = 0; let cryptStatus = CCCrypt(CCOperation(kCCDecrypt), CCAlgorithm(kCCAlgorithmAES128), CCOptions(kCCOptionPKCS7Padding), String(data: key, encoding: .utf8)?.cString(using: .utf8), key.count, String(data: iv, encoding: .utf8)?.cString(using: .utf8), String(data: self, encoding: .utf8)?.cString(using: .utf8), self.count, buffer, bufferSize, &encryptedSize); if cryptStatus == CCCryptorStatus(kCCSuccess) { let result = Data(bytes: buffer, count: encryptedSize) free(buffer); return result; } else { free(buffer); return nil; } } }
49b612d6deb5244b373eac21dc357037
32.647436
93
0.532673
false
false
false
false
KhunLam/Swift_weibo
refs/heads/master
LKSwift_weibo/LKSwift_weibo/Classes/Library/Emoticon/UITextView+Emoticon.swift
apache-2.0
1
// // UITextView+Emoticon.swift // 表情键盘 // // Created by lamkhun on 15/11/8. // Copyright © 2015年 lamKhun. All rights reserved. // import UIKit /// 扩展 UITextView 分类 extension UITextView { /** 获取带表情图片的字符串 - returns: 带表情图片的字符串 */ func emoticonText() -> String { // 将所有遍历的文本拼接起来 var text = "" // enumerationRange: 遍历的范围 --0开始 文本长度 attributedText.enumerateAttributesInRange(NSRange(location: 0, length:attributedText.length), options: NSAttributedStringEnumerationOptions(rawValue: 0)) { (dict, range, _) -> Void in // print("dict\(dict)") ///---打印驱动 key -- “NSAttachment” // print("range\(range)") // 如果dict有 "NSAttachment" key 并且拿出来有值(NSTextAttachment) 表情图片, 没有就是普通的文本NSFont if let attachment = dict["NSAttachment"] as? LKTextAttachment { // 需要获取到表情图片对应的名称 // 需要一个属性记录下表情图片的名称,现有的类不能满足要求,创建一个类继承NSTextAttachment 的自定义类 text += attachment.name! }else { // 普通文本,截取 let str = (self.attributedText.string as NSString).substringWithRange(range) text += str } } // 遍历完后输出 return text } /** 添加表情到textView - parameter emoticon: 要添加的表情 */ func insertEmoticon(emoticon: LKEmoticon) { // 判断如果是删除按钮 if emoticon.removeEmoticon { // 删除文字或表情 deleteBackward() } // 添加emoji表情--系统自带 if let emoji = emoticon.emoji{ //插入文本 insertText(emoji) } // 添加图片表情 --判断是否 有表情 --用文本附件的形式 显示表情 if let pngPath = emoticon.pngPath { //一① 创建附件 -- let attachment = LKTextAttachment() //② 创建 image let image = UIImage(contentsOfFile: pngPath) //③ 将 image 添加到附件 attachment.image = image // 将表情图片的名称赋值 ---自定义属性 记录 attachment.name = emoticon.chs // 获取文本font的线高度 --文字高度 let height = font?.lineHeight ?? 10 // 设置附件大小 attachment.bounds = CGRect(x: 0, y: -(height * 0.25), width: height, height: height) //二① 创建属性文本 可变的 let attrString = NSMutableAttributedString(attributedString: NSAttributedString(attachment: attachment)) // 发现在表情图片后面在添加表情会很小.原因是前面的这个表请缺少font属性 // 给属性文本(附件) 添加 font属性 --附件 Range 0开始 长度1 attrString.addAttribute(NSFontAttributeName, value: font!, range: NSRange(location: 0, length: 1)) // 获取到已有的文本,将表情添加到已有的可变文本后面 let oldAttrString = NSMutableAttributedString(attributedString: attributedText) // 记录选中的范围 let oldSelectedRange = selectedRange // range: 替换的文本范围 oldAttrString.replaceCharactersInRange(oldSelectedRange, withAttributedString: attrString) //三① 赋值给textView的 attributedText 显示 attributedText = oldAttrString //② 设置输入光标位置,在表情后面 selectedRange = NSRange(location: oldSelectedRange.location + 1, length: 0) // 让表情图片 也能 发出 extViewDidChange 给条用者 知道 // 重新设置textView的attributedText没有触发textDidChanged // 主动调用代理的textViewDidChange delegate?.textViewDidChange?(self) // 主动发送 UITextViewTextDidChangeNotification NSNotificationCenter.defaultCenter().postNotificationName(UITextViewTextDidChangeNotification, object: self) } } }
a0fb7a6be8a6ad8e8494ec9846bc5d06
31.299145
191
0.550026
false
false
false
false
xdliu002/TongjiAppleClubDeviceManagement
refs/heads/master
TAC-DM/BookViewController.swift
mit
1
// // BookViewController.swift // TAC-DM // // Created by Harold Liu on 8/18/15. // Copyright (c) 2015 TAC. All rights reserved. // import UIKit class BookViewController:UITableViewController, DMDelegate { var dmModel: DatabaseModel! var bookList:[String]? = nil var bookNameArray:[String] = [] //MARK:- Custom Nav @IBOutlet weak var navView: UIView! @IBAction func back() { SVProgressHUD.dismiss() (tabBarController as! TabBarController).sidebar.showInViewController(self, animated: true) } // MARK:- Configure UI override func viewDidLoad() { super.viewDidLoad() configureNavBar() self.navigationController?.navigationBarHidden = true //self.navView.backgroundColor = UIColor(patternImage:UIImage(named: "book background")!) self.navView.backgroundColor = UIColor.clearColor() dmModel = DatabaseModel.getInstance() dmModel.delegate = self self.refreshControl = UIRefreshControl() self.refreshControl!.addTarget(self, action: Selector("refresh"), forControlEvents: .ValueChanged) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.navigationController?.navigationBarHidden = true updateUI() tableView.reloadData() SVProgressHUD.show() } func refresh() { SVProgressHUD.show() updateUI() print("data is refresh") tableView.reloadData() refreshControl?.endRefreshing() } //更新所有书籍 func updateUI() { bookList = nil bookNameArray = [] dmModel.getDeviceList("book") } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() // this api mush better than what i am use before remember it. self.tableView.backgroundView = UIImageView(image: UIImage(named: "book background")) } func configureNavBar() { self.navigationController?.navigationBar.barTintColor = UIColor(patternImage: UIImage(named: "book background")!) self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName : UIColor.whiteColor(),NSFontAttributeName:UIFont(name: "Hiragino Kaku Gothic ProN", size: 30)!] } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("TextCell", forIndexPath: indexPath) let row = indexPath.row if 0 == row % 2 { cell.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.65) cell.textLabel?.text = bookNameArray[row/2] cell.textLabel?.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.0) cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator } else { cell.backgroundColor = UIColor.clearColor() cell.textLabel?.text = "" } return cell } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if 0 == indexPath.row % 2 { return 75 } else { return 5 } } // MARK:- UITableViewDelegate Methods // TODO: should return count *2 Here attention override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return bookNameArray.count * 2 } @IBAction func backButton(sender: UIBarButtonItem) { // self.navigationController?.navigationBarHidden = true SVProgressHUD.dismiss() (tabBarController as! TabBarController).sidebar.showInViewController(self, animated: true) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) { let selectedIndex = self.tableView.indexPathForCell(sender as! UITableViewCell) if segue.identifier == "showDetial" { if let destinationVC = segue.destinationViewController as? BookDetail { let book = bookList![selectedIndex!.row/2].componentsSeparatedByString(",") destinationVC.borrowBookId = book[0] destinationVC.borrowBookName = book[1] destinationVC.borrowBookDescription = book[2] } } } func getRequiredInfo(Info: String) { //put book list in tableView print("图书列表:\(Info)") bookList = Info.componentsSeparatedByString("|") for book in bookList! { let bookName = book.componentsSeparatedByString(",") //check Info is empty if bookName.count > 1 { let tmpName = "\(bookName[0]),\(bookName[1])" bookNameArray.append(tmpName) } else { print("there is no book") tableView.reloadData() //tableView为空,给用户提示 SVProgressHUD.showErrorWithStatus("Sorry,there is no book for borrowing") return } } self.tableView.reloadData() SVProgressHUD.dismiss() } }
86bc52b89f67ed334b211350e23561f0
32.796178
140
0.62288
false
false
false
false
Derek316x/iOS8-day-by-day
refs/heads/master
34-corelocation-auth/WhereAmI/WhereAmI/ViewController.swift
apache-2.0
22
// // Copyright 2014 Scott Logic // // 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 MapKit import CoreLocation class ViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate { @IBOutlet weak var latValLabel: UILabel! @IBOutlet weak var longValLabel: UILabel! @IBOutlet weak var altValLabel: UILabel! @IBOutlet weak var accValLabel: UILabel! @IBOutlet weak var spdValLabel: UILabel! @IBOutlet weak var mapView: MKMapView! let locationManager = CLLocationManager() var historicalPoints = [CLLocationCoordinate2D]() var routeTrack = MKPolyline() override func viewDidLoad() { super.viewDidLoad() // Prepare the location manager locationManager.delegate = self locationManager.desiredAccuracy = 20 // Need to ask for the right permissions locationManager.requestWhenInUseAuthorization() locationManager.startUpdatingLocation() // Prepare the map view mapView.delegate = self } // MARK:- CLLocationManagerDelegate methods func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) { if let location = locations.first as? CLLocation { // Update the fields as expected: latValLabel.text = "\(location.coordinate.latitude)" longValLabel.text = "\(location.coordinate.longitude)" altValLabel.text = "\(location.altitude) m" accValLabel.text = "\(location.horizontalAccuracy) m" spdValLabel.text = "\(location.speed) ms⁻¹" // Re-center the map mapView.centerCoordinate = location.coordinate // And update the track on the map historicalPoints.append(location.coordinate) updateMapWithPoints(historicalPoints) } } // MARK:- MKMapViewDelegate methods func mapView(mapView: MKMapView!, rendererForOverlay overlay: MKOverlay!) -> MKOverlayRenderer! { if let overlay = overlay as? MKPolyline { let renderer = MKPolylineRenderer(polyline: overlay) renderer.lineWidth = 4.0 renderer.strokeColor = UIColor.blueColor().colorWithAlphaComponent(0.7) return renderer } return nil } // MARK:- Utility Methods private func updateMapWithPoints(points: [CLLocationCoordinate2D]) { let oldTrack = routeTrack // This has to be mutable, so we make a new reference var coordinates = points // Create the new route track routeTrack = MKPolyline(coordinates: &coordinates, count: points.count) // Switch them out mapView.addOverlay(routeTrack) mapView.removeOverlay(oldTrack) // Zoom the map mapView.visibleMapRect = mapView.mapRectThatFits(routeTrack.boundingMapRect, edgePadding: UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)) } }
75bdd7d37801b65d9771696495f744a4
32.408163
149
0.720831
false
false
false
false
DazzlingDevelopment/MathKit
refs/heads/master
MKProbability.swift
mit
1
// // MKProbability.swift // MathKit // // Created by Dazzling Development on 5/25/15. // Copyright (c) 2015 DAZ. All rights reserved. // import Foundation class MKProbability { var MathKitBasics = MKBasics() // Permutation Basic func permutation(totalObj: Double, objToHandle: Double) -> Double { var numerator = MathKitBasics.factorial(totalObj) var denominator = MathKitBasics.factorial(totalObj - objToHandle) var final: Double = Double(numerator) / Double(denominator) return final } // PermutationRepitition func permutationWithRepitition(totalObj: Double, similarObjects: [Double]) -> Double { var numerator = MathKitBasics.factorial(totalObj) var denominator: Double = 1 var iterator = 0 while iterator < similarObjects.count { denominator *= MathKitBasics.factorial(similarObjects[iterator]) iterator++ } var final = Double(numerator) / Double(denominator) return final } // PermutationCircular func permutationCircular(totalObj: Double) -> Double { var numerator = MathKitBasics.factorial(totalObj) var denominator = totalObj var final = Double(numerator) / Double(denominator) return final } // Combination Basic func combination(totalObj: Double, objToHandle: Double) -> Double { var numerator = MathKitBasics.factorial(totalObj) var denominator = ((MathKitBasics.factorial(totalObj - objToHandle)) * (MathKitBasics.factorial(objToHandle))) var final: Double = Double(numerator) / Double(denominator) return final } // Odds For func oddsFor(probSuccess: Double, probFailure: Double) -> Double { return probSuccess / probFailure } // Odds Against func oddsAgainst(probSuccess: Double, probFailure: Double) -> Double { return probFailure / probSuccess } }
b773d4b6c44e81e52b7dfba9e10b15d5
29.753846
118
0.648824
false
false
false
false
Coderian/SwiftedKML
refs/heads/master
SwiftedKML/Elements/HttpQuery.swift
mit
1
// // HttpQuery.swift // SwiftedKML // // Created by 佐々木 均 on 2016/02/02. // Copyright © 2016年 S-Parts. All rights reserved. // import Foundation /// KML HttpQuery /// /// [KML 2.2 shcema](http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd) /// /// <element name="httpQuery" type="string"/> public class HttpQuery:SPXMLElement,HasXMLElementValue,HasXMLElementSimpleValue { public static var elementName: String = "httpQuery" public override var parent:SPXMLElement! { didSet { // 複数回呼ばれたて同じものがある場合は追加しない if self.parent.childs.contains(self) == false { self.parent.childs.insert(self) switch parent { case let v as Link: v.value.httpQuery = self default: break } } } } public var value: String = "" public func makeRelation(contents:String, parent:SPXMLElement) -> SPXMLElement{ self.value = contents self.parent = parent return parent } }
ef67f99c286a8740ee3960edf9a3e379
27.777778
83
0.59749
false
false
false
false
uraimo/SwiftyGPIO
refs/heads/master
Sources/UART.swift
mit
1
/* SwiftyGPIO Copyright (c) 2016 Umberto Raimondi Licensed under the MIT license, as follows: Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.) */ #if os(Linux) import Glibc #else import Darwin.C #endif extension SwiftyGPIO { public static func UARTs(for board: SupportedBoard) -> [UARTInterface]? { switch board { case .CHIP: return [SysFSUART(["serial0","ttyAMA0"])!] case .RaspberryPiRev1, .RaspberryPiRev2, .RaspberryPiPlusZero, .RaspberryPi2: return [SysFSUART(["serial0","ttyAMA0"])!] case .RaspberryPi3, .RaspberryPi4, .RaspberryPiZero2: return [SysFSUART(["serial0","ttyS0"])!, SysFSUART(["serial1","ttyAMA0"])!] default: return nil } } } // MARK: UART public protocol UARTInterface { func configureInterface(speed: UARTSpeed, bitsPerChar: CharSize, stopBits: StopBits, parity: ParityType) func hasAvailableData() throws -> Bool func readString() -> String func readLine() -> String func readData() -> [CChar] func writeString(_ value: String) func writeData(_ values: [CChar]) } public enum ParityType { case None case Even case Odd public func configure(_ cfg: inout termios) { switch self { case .None: cfg.c_cflag &= ~UInt32(PARENB | PARODD) case .Even: cfg.c_cflag &= ~UInt32(PARENB | PARODD) cfg.c_cflag |= UInt32(PARENB) case .Odd: cfg.c_cflag |= UInt32(PARENB | PARODD) } } } public enum CharSize { case Eight case Seven case Six public func configure(_ cfg: inout termios) { cfg.c_cflag = (cfg.c_cflag & ~UInt32(CSIZE)) switch self { case .Eight: cfg.c_cflag |= UInt32(CS8) case .Seven: cfg.c_cflag |= UInt32(CS7) case .Six: cfg.c_cflag |= UInt32(CS6) } } } public enum StopBits { case One case Two public func configure(_ cfg: inout termios) { switch self { case .One: cfg.c_cflag &= ~UInt32(CSTOPB) case .Two: cfg.c_cflag |= UInt32(CSTOPB) } } } public enum UARTSpeed { case S2400 case S4800 case S9600 case S19200 case S38400 case S57600 case S115200 public func configure(_ cfg: inout termios) { switch self { case .S2400: cfsetispeed(&cfg, speed_t(B2400)) cfsetospeed(&cfg, speed_t(B2400)) case .S4800: cfsetispeed(&cfg, speed_t(B4800)) cfsetospeed(&cfg, speed_t(B4800)) case .S9600: cfsetispeed(&cfg, speed_t(B9600)) cfsetospeed(&cfg, speed_t(B9600)) case .S19200: cfsetispeed(&cfg, speed_t(B19200)) cfsetospeed(&cfg, speed_t(B19200)) case .S38400: cfsetispeed(&cfg, speed_t(B38400)) cfsetospeed(&cfg, speed_t(B38400)) case .S57600: cfsetispeed(&cfg, speed_t(B57600)) cfsetospeed(&cfg, speed_t(B57600)) case .S115200: cfsetispeed(&cfg, speed_t(B115200)) cfsetospeed(&cfg, speed_t(B115200)) } } } public enum IOCTLError: Error { case callExecutionFailed(detail: String) } /// UART via SysFS public final class SysFSUART: UARTInterface { var device: String var tty: termios var fd: Int32 public init?(_ uartIdList: [String]) { // try all items in list until one works for uartId in uartIdList { device = "/dev/"+uartId tty = termios() fd = open(device, O_RDWR | O_NOCTTY | O_SYNC) guard fd>0 else { if errno == ENOENT { // silently return nil if no such device continue } perror("Couldn't open UART device") continue } let ret = tcgetattr(fd, &tty) guard ret == 0 else { close(fd) perror("Couldn't get terminal attributes") continue } return } return nil } public convenience init?(_ uartId: String) { self.init([uartId]) } public func configureInterface(speed: UARTSpeed, bitsPerChar: CharSize, stopBits: StopBits, parity: ParityType) { speed.configure(&tty) bitsPerChar.configure(&tty) tty.c_iflag &= ~UInt32(IGNBRK) // disable break processing tty.c_lflag = 0 // no signaling chars, no echo, // no canonical processing -> read bytes as they come without waiting for LF tty.c_oflag = 0 // no remapping, no delays withUnsafeMutableBytes(of: &tty.c_cc) {$0[Int(VMIN)] = UInt8(1); return} withUnsafeMutableBytes(of: &tty.c_cc) {$0[Int(VTIME)] = UInt8(5); return} // 5 10th of second read timeout tty.c_iflag &= ~UInt32(IXON | IXOFF | IXANY) // Every kind of software flow control off tty.c_cflag &= ~UInt32(CRTSCTS) //No hw flow control tty.c_cflag |= UInt32(CLOCAL | CREAD) // Ignore modem controls, enable read parity.configure(&tty) stopBits.configure(&tty) applyConfiguration() } public func hasAvailableData() throws -> Bool { var bytesToRead = 0 let result = ioctl(fd, UInt(FIONREAD), &bytesToRead) guard result >= 0 else { throw IOCTLError.callExecutionFailed(detail: String(format: "%s", strerror(errno))) } return bytesToRead > 0 } public func readLine() -> String { var buf = [CChar](repeating:0, count: 4097) //4096 chars at max in canonical mode return buf.withUnsafeMutableBufferPointer { ptr -> String in let newLineChar = CChar(UInt8(ascii: "\n")) var pos = 0 repeat { let n = read(fd, ptr.baseAddress! + pos, MemoryLayout<CChar>.stride) if n<0 { perror("Error while reading from UART") abort() } pos += 1 } while (ptr[pos-1] != newLineChar) && (pos < ptr.count-1) ptr[pos] = 0 return String(cString: ptr.baseAddress!) } } public func readString() -> String { var buf = readData() buf.append(0) //Add terminator to convert cString correctly return String(cString: &buf) } public func readData() -> [CChar] { var buf = [CChar](repeating:0, count: 4096) //4096 chars at max in canonical mode let n = read(fd, &buf, buf.count * MemoryLayout<CChar>.stride) if n<0 { perror("Error while reading from UART") abort() } return Array(buf[0..<n]) } public func writeString(_ value: String) { let chars = Array(value.utf8CString) writeData(chars) } public func writeData(_ value: [CChar]) { var value = value _ = write(fd, &value, value.count) tcdrain(fd) } private func applyConfiguration() { if tcsetattr (fd, TCSANOW, &tty) != 0 { perror("Couldn't set terminal attributes") abort() } } deinit { close(fd) } } // MARK: - Darwin / Xcode Support #if os(OSX) || os(iOS) private let FIONREAD = 0x541B // Cannot be found on Darwin, only on Glibc. Added this to get it to compile with XCode. private var O_SYNC: CInt { fatalError("Linux only") } private var CRTSCTS: CInt { fatalError("Linux only") } // Shadowing some declarations from termios.h just to get it to compile with Xcode // As the rest, not atually intended to be run. public struct termios { var c_iflag: UInt32 = 0 var c_oflag: UInt32 = 0 var c_cflag: UInt32 = 0 var c_lflag: UInt32 = 0 var c_cc = [UInt32]() } func tcsetattr (_ fd: Int32, _ attr: Int32, _ tty: inout termios) -> Int { fatalError("Linux only") } func tcgetattr(_ fd: Int32, _ tty: inout termios) -> Int { fatalError("Linux only") } func cfsetispeed(_ tty: inout termios, _ speed: UInt) { fatalError("Linux only") } func cfsetospeed(_ tty: inout termios, _ speed: UInt) { fatalError("Linux only") } #endif
1f3e565303823294c1e358364e2a6774
29.810458
122
0.583157
false
false
false
false
CatchChat/Yep
refs/heads/master
Yep/Extensions/ASImageNode+Yep.swift
mit
1
// // ASImageNode+Yep.swift // Yep // // Created by NIX on 16/7/5. // Copyright © 2016年 Catch Inc. All rights reserved. // import YepKit import Navi import AsyncDisplayKit private var avatarKeyAssociatedObject: Void? extension ASImageNode { private var navi_avatarKey: String? { return objc_getAssociatedObject(self, &avatarKeyAssociatedObject) as? String } private func navi_setAvatarKey(avatarKey: String) { objc_setAssociatedObject(self, &avatarKeyAssociatedObject, avatarKey, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } func navi_setAvatar(avatar: Navi.Avatar, withFadeTransitionDuration fadeTransitionDuration: NSTimeInterval = 0) { navi_setAvatarKey(avatar.key) AvatarPod.wakeAvatar(avatar) { [weak self] finished, image, cacheType in guard let strongSelf = self, avatarKey = strongSelf.navi_avatarKey where avatarKey == avatar.key else { return } if finished && cacheType != .Memory { UIView.transitionWithView(strongSelf.view, duration: fadeTransitionDuration, options: .TransitionCrossDissolve, animations: { self?.image = image }, completion: nil) } else { self?.image = image } } } } private var messageKey: Void? extension ASImageNode { private var yep_messageImageKey: String? { return objc_getAssociatedObject(self, &messageKey) as? String } private func yep_setMessageImageKey(messageImageKey: String) { objc_setAssociatedObject(self, &messageKey, messageImageKey, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } func yep_setImageOfMessage(message: Message, withSize size: CGSize, tailDirection: MessageImageTailDirection, completion: (loadingProgress: Double, image: UIImage?) -> Void) { let imageKey = message.imageKey yep_setMessageImageKey(imageKey) ImageCache.sharedInstance.imageOfMessage(message, withSize: size, tailDirection: tailDirection, completion: { [weak self] progress, image in guard let strongSelf = self, _imageKey = strongSelf.yep_messageImageKey where _imageKey == imageKey else { return } completion(loadingProgress: progress, image: image) }) } }
e79e071efaefb164c78b4478363eaf4b
30.432432
179
0.670679
false
false
false
false
Bijiabo/F-Client-iOS
refs/heads/master
F/F/Controllers/ActionSelectTableViewController.swift
gpl-2.0
1
// // ActionSelectTableViewController.swift // CKM // // Created by huchunbo on 15/10/27. // Copyright © 2015年 TIDELAB. All rights reserved. // import UIKit class ActionSelectTableViewController: UITableViewController { let actions = [ [ "text": "New RecordType", "action": "NewRecord" ], [ "text": "Delete RecordType", "action": "DeleteRecord" ], [ "text": "Add Record", "action": "AddRecord" ], [ "text": "Edit Record", "action": "EditRecord" ], [ "text": "Delete Record", "action": "DeleteRecord" ], [ "text": "Query", "action": "Query" ] ] override func viewDidLoad() { super.viewDidLoad() self.clearsSelectionOnViewWillAppear = true // 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 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return actions.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) // Configure the cell... 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 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. } */ }
a7c50f1401c865585fecff32c398e604
29.440678
157
0.630568
false
false
false
false
ddki/my_study_project
refs/heads/master
language/swift/MyPlayground.playground/Contents.swift
mit
1
print("hello world!") // let - constant, var - variable var myVariable = 42 myVariable = 50 let myConstant = 42 // type let explicitDouble: Double = 70 // Values are never implicitly converted to another type. let label = "The width is " let width = 94 let widthLabel = label + String(width) // /() let apples = 3 let oranges = 5 let appleSummary = "I have \(apples) apples"; let fruitSummary = "I have \(apples + oranges) pieces of fruit"; // array var shoppingList = ["catfish", "water", "tulips", "blue paint"]; shoppingList[1] = "bottle of water"; print(shoppingList) // dictionary var occupations = [ "Malcolm": "Captain", "Keylee": "Mechanic", ] occupations["Jayne"] = "Public Relations" print(occupations) // empty let emptyArray = [String]() let emptyDictionary = [String: Float]() // shoppingList = []; occupations = [:]; // for if let individualScores = [75, 43, 103, 87, 12] var teamScore = 0 for score in individualScores { if score > 50 { teamScore += 3 } else { teamScore += 1 } } print(teamScore) // ? var optionalString: String? = "option" print(optionalString == nil) var optionalName: String? = nil var greeting = "Hello!" if let name = optionalName { greeting = "Hello, \(name)" } else { greeting = "just hello." } // ?? let nickName: String? = nil let fullName: String = "ddchen" let informalGreeting = "Hi \(nickName ?? fullName)" // switch case let vegetable = "red pepper" switch vegetable { case "celery": print("celery") case "cucumber", "watercress": print("cucumber, watercress") case let x where x.hasSuffix("pepper"): print("pepper \(x)?") default: print("Everything tastes good in soup.") } // for dictionary let interestingNumber = [ "Prime": [2, 3, 5, 7, 11, 13], "Fibonacci": [1, 1, 2, 3, 5, 8], "Square": [1, 4, 9, 16, 25] ] var largest = 0 var largestKind:String? = nil for (kind, numbers) in interestingNumber { for number in numbers { if number > largest { largest = number largestKind = kind } } } print(largest) print(largestKind) // while repeat-while var n = 2 while n < 100 { n = n * 2 } print(n) var m = 2 repeat { m = m * 2 } while m < 100 print(m) // ..< var firstForLoop = 0 let loopTimes:Int = 4 for i in 0 ..< loopTimes { firstForLoop += i } print(firstForLoop) var secondForLoop = 0 for var i=0;i < 4;i++ { secondForLoop += i } print(secondForLoop) // ... var thirdForLoop = 0 for i in 0...4 { thirdForLoop += i } print(thirdForLoop) // function func greet(name: String, day: String) -> String { return "Hello \(name), today is \(day)." } greet("Bob", day: "Tuesday") // tuples func calculateStatistics(scores: [Int]) -> (min: Int, max: Int, sum: Int) { var min = scores[0]; var max = scores[0]; var sum = 0; for score in scores { if score > max { max = score } else { min = score } sum += score } return (min, max, sum) } let statistics = calculateStatistics([5, 3, 100, 3, 9]) print(statistics.sum) print(statistics.2) func sumOf(numbers: Int...) -> Int { var sum = 0 for number in numbers { sum += number } return sum } sumOf() sumOf(42, 597, 12) // inner functions func returnFifteen() -> Int { var y = 10 func add() { y += 5 } add() return y } returnFifteen() // closure func makeIncrementer () -> ((Int) -> Int) { func addOne(number: Int) -> Int { return 1 + number } return addOne } var increment = makeIncrementer() increment(7) // func hasAnyMatches(list: [Int], condition: (Int) -> Bool) -> Bool { for item in list { if condition(item) { return true } } return false } func lessThanTen(number: Int) -> Bool { return number < 10 } var numbers = [20, 19, 7, 12] hasAnyMatches(numbers, condition: lessThanTen) // closure var clsr = [1, 2, 3, 4].map({ (number: Int) -> Int in if number % 2 == 1 { return 0 } return 1 }) print(clsr); var mapNum = [3, 4].map({ number in 3 * number }); print(mapNum) let sortedNumbers = [5, 6].sort {$0 > $1} print(sortedNumbers) // class class Shape { var numberOfSides = 0 func simpleDescription () -> String { return "A shape with \(numberOfSides) sides." } } var shape = Shape() shape.numberOfSides = 7 var shapeDesc = shape.simpleDescription() print(shapeDesc) class NamedShape { var numberOfSides: Int = 0 var name: String init(name: String) { self.name = name } func test () -> () { print("\(self.numberOfSides)") } } class Square: NamedShape { var sideLength: Double init(sideLength: Double, name: String) { self.sideLength = sideLength super.init(name:name) numberOfSides = 4 } override func test () -> () { print("\(self.sideLength)"); } } var square = Square(sideLength: 4.0, name: "square") square.test() class EquilateralTriangle: NamedShape { var sideLength: Double init(sideLength: Double, name: String) { self.sideLength = sideLength super.init(name: name); numberOfSides = 3 } var perimeter: Double { get { return 3.0 * sideLength } set { sideLength = newValue / 3.0 } } override func test() -> () { print("\(self.sideLength)") } } var triangle = EquilateralTriangle(sideLength: 3.1, name: "triangle") print(triangle.perimeter) triangle.perimeter = 9.9 print(triangle.sideLength) // willSet run before setting a new value // didSet run after setting a new value class TriangleAndSquare { var triangle: EquilateralTriangle { willSet { square.sideLength = newValue.sideLength } } var square: Square { willSet { triangle.sideLength = newValue.sideLength } } init(size: Double, name: String) { square = Square(sideLength: size, name:name) triangle = EquilateralTriangle(sideLength: size, name: name) } } var triangleAndSquare = TriangleAndSquare(size: 10, name: "another test shape") print(triangleAndSquare.square.sideLength) print(triangleAndSquare.triangle.sideLength) triangleAndSquare.square = Square(sideLength: 50, name: "larger square") print(triangleAndSquare.triangle.sideLength) // ? var optionalValue:Dictionary? = [ "good": [1, 2, 3, 5] ]; let okGetIt = (optionalValue?["good"]![2])! + 1 print(okGetIt) optionalValue = nil let okGetIt2 = optionalValue?["good"] print(optionalValue) // enum Rank: Int { case Ace = 100 case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten case Jack, Queen, King func simpleDescription() -> String { switch self { case .Ace: return "ace" case .Jack: return "jack" default: return String(self.rawValue) } } func compare (other: Rank) -> Bool { return self.rawValue > other.rawValue } } let ace = Rank.Ace let aceRawValue = ace.rawValue ace.simpleDescription() let queen = Rank.Queen let queenRawValue = queen.rawValue queen.compare(ace) if let convertedRank = Rank(rawValue: 3) { let threeDescription = convertedRank.simpleDescription() } enum Suit: String { case Spades, Hearts, Diamonds, Clubs func simpleDescription() -> String { switch self { case .Spades: return "spades" case .Hearts: return "hearts" case .Diamonds: return "diamonds" case .Clubs: return "clubs" } } } let hearts = Suit.Hearts print(hearts.rawValue) let heartsDescription = hearts.simpleDescription() // struct struct Card { var rank: Rank var suit: Suit func simpleDescription() -> String { return "The \(rank.simpleDescription()) of \(suit.simpleDescription())" } } let card = Card(rank:.Three, suit:.Hearts) card.simpleDescription() // enum ServerResponse { case Result(String, String) case Error(String) } let success = ServerResponse.Result("6:00 am", "8:09 pm") let failure = ServerResponse.Error("Out of cheese.") switch success { case let .Result(sunrise, sunset): print("Sunrise is at \(sunrise) and sunset is at \(sunset).") case let .Error(error): print("Failure... \(error)") } // protocol protocol ExampleProtocol { var simpleDescription: String { get } mutating func adjust() } class SimpleClass: ExampleProtocol { var simpleDescription: String = "A very simple class." var anotherProperty: Int = 78932 func adjust() { simpleDescription += " Now 100% adjusted." } } var simpleInst = SimpleClass() simpleInst.adjust() let aDesc = simpleInst.simpleDescription; struct SimpleStructure: ExampleProtocol { var simpleDescription: String = "A very simple structure." mutating func adjust() { simpleDescription += " Now 100% adjusted." } } var b = SimpleStructure() b.adjust() let bDesc = b.simpleDescription extension Int: ExampleProtocol { var simpleDescription: String { return "The number \(self)" } mutating func adjust() { self += 42 } } print(7.simpleDescription) let protocolValue: ExampleProtocol = simpleInst print(protocolValue.simpleDescription) // generic <> func repeatItem<Item>(item: Item, numberOfTimes: Int) -> [Item] { var result = [Item]() for _ in 0..<numberOfTimes { result.append(item) } return result } repeatItem("knock", numberOfTimes: 4) enum OptionalValue<Wrapped> { case None case some(Wrapped) } var possibleInteger: OptionalValue<Int> = .None possibleInteger = .some(100) func anyCommonElements <T: SequenceType, U: SequenceType where T.Generator.Element: Equatable, T.Generator.Element == U.Generator.Element> (lhs: T, _ rhs: U) -> Bool { for lhsItem in lhs { for rhsItem in rhs { if lhsItem == rhsItem { return true } } } return false } anyCommonElements([1, 2, 3], [3]) // import import UIKit let redSquare = UIView(frame: CGRect(x: 0, y: 0, width: 44, height: 44)) redSquare.backgroundColor = UIColor.redColor()
aa8a842c912ee1c67f1ea227e918623a
15.415797
160
0.548357
false
false
false
false
victor-pavlychko/SwiftyTasks
refs/heads/master
SwiftyTasks/Tasks/TaskProtocol.swift
mit
1
// // TaskProtocol.swift // SwiftyTasks // // Created by Victor Pavlychko on 9/15/16. // Copyright © 2016 address.wtf. All rights reserved. // import Foundation /// Abstract task public protocol AnyTask { /// List of backing operations var backingOperations: [Operation] { get } } /// Abstract task with result public protocol TaskProtocol: AnyTask { associatedtype ResultType /// Retrieves tast execution result or error /// /// - Throws: captured error if any /// - Returns: execution result func getResult() throws -> ResultType } extension Operation: AnyTask { /// List of backing operations which is equal to `[self]` in case of Operation public var backingOperations: [Operation] { return [self] } } public extension AnyTask { /// Starts execution of all backing operation and fires completion block when ready. /// Async operations will run concurrently in background, sync ones will execute one by one /// in current thread. /// /// - Parameter completionBlock: Completion block to be fired when everyhting is done public func start(_ completionBlock: @escaping () -> Void) { guard !backingOperations.isEmpty else { completionBlock() return } var counter: Int32 = Int32(backingOperations.count) let countdownBlock = { if (OSAtomicDecrement32Barrier(&counter) == 0) { completionBlock() } } for operation in backingOperations { operation.completionBlock = countdownBlock operation.start() } } } public extension TaskProtocol { /// Starts execution of all backing operation and fires completion block when ready. /// Async operations will run concurrently in background, sync ones will execute one by one /// in current thread. /// /// - Parameters: /// - completionBlock: Completion block to be fired when everyhting is done /// - resultBlock: Result block wrapping task outcome public func start(_ completionBlock: @escaping (_ resultBlock: () throws -> ResultType) -> Void) { start { completionBlock(self.getResult) } } }
a9e8bee83be68c583d3a3aeb3c54e471
27.935065
102
0.650808
false
false
false
false
sgr-ksmt/i18nSwift
refs/heads/master
Sources/Language.swift
mit
1
// // Language.swift // i18nSwift // // Created by Suguru Kishimoto on 3/28/17. // Copyright © 2017 Suguru Kishimoto. All rights reserved. // import Foundation extension i18n { public final class Language { public struct Constant { internal init() {} public static let currentLanguageKey = "i18n.current_language" fileprivate static let defaultLanguage = "en" fileprivate static let stringsFileSuffix = "lproj" fileprivate static let baseStringsFileName = "Base" fileprivate static let notificationKey = "i18n.current_language.didupdate" } static var dataStore: LanguageDataStore = DefaultLanguageDataStore() static var languageBundle: Bundle = .main static func localizableBundle(in bundle: Bundle, language: String) -> Bundle? { return localizableBundlePath(in: bundle, language: language).flatMap { Bundle(path: $0) } } private static func localizableBundlePath(in bundle: Bundle, language: String = current) -> String? { for l in [language, Constant.baseStringsFileName] { if let path = bundle.path(forResource: l, ofType: Constant.stringsFileSuffix) { return path } } return nil } // MARK: - Language public static func availableLanguages(includeBase: Bool = true) -> [String] { return languageBundle.localizations.filter { $0 != Constant.baseStringsFileName || includeBase } } public static var current: String { get { return dataStore.language(forKey: Constant.currentLanguageKey) ?? self.default } set { let language = availableLanguages().contains(newValue) ? newValue : Constant.defaultLanguage dataStore.set(language, forKey: Constant.currentLanguageKey) NotificationCenter.default.post(name: .CurrentLanguageDidUpdate, object: nil) } } public static func reset() { dataStore.reset(forKey: Constant.currentLanguageKey) NotificationCenter.default.post(name: .CurrentLanguageDidUpdate, object: nil) } public static var `default`: String { return languageBundle.preferredLocalizations.first! } public static func displayName(for language: String = current) -> String? { return NSLocale(localeIdentifier: current).displayName(forKey: .identifier, value: language) } } } public extension Notification.Name { public static let CurrentLanguageDidUpdate = Notification.Name(i18n.Language.Constant.notificationKey) }
c37d34ea1d35e75a86ad5f78bfc5994d
36.84
109
0.616279
false
false
false
false
natecook1000/WWDC
refs/heads/master
WWDC/SlidesDownloader.swift
bsd-2-clause
1
// // SlidesDownloader.swift // WWDC // // Created by Guilherme Rambo on 10/3/15. // Copyright © 2015 Guilherme Rambo. All rights reserved. // import Cocoa import Alamofire class SlidesDownloader { typealias ProgressHandler = (downloaded: Double, total: Double) -> Void typealias CompletionHandler = (success: Bool, data: NSData?) -> Void var session: Session init(session: Session) { self.session = session } func downloadSlides(completionHandler: CompletionHandler, progressHandler: ProgressHandler?) { guard session.slidesURL != "" else { return completionHandler(success: false, data: nil) } guard let slidesURL = NSURL(string: session.slidesURL) else { return completionHandler(success: false, data: nil) } Alamofire.download(Method.GET, slidesURL.absoluteString) { tempURL, response in if let data = NSData(contentsOfURL: tempURL) { mainQ { WWDCDatabase.sharedDatabase.doChanges { self.session.slidesPDFData = data } completionHandler(success: true, data: data) } } else { completionHandler(success: false, data: nil) } do { try NSFileManager.defaultManager().removeItemAtURL(tempURL) } catch { print("Error removing temporary PDF file") } return tempURL }.progress { _, totalBytesRead, totalBytesExpected in mainQ { progressHandler?(downloaded: Double(totalBytesRead), total: Double(totalBytesExpected)) } } } }
b66503e9738a0d6c1a7772d71d8c8501
32.897959
123
0.612048
false
false
false
false
syoung-smallwisdom/ResearchUXFactory-iOS
refs/heads/master
ResearchUXFactory/SBAPermissionsStep.swift
bsd-3-clause
1
// // SBAPermissionsStep.swift // ResearchUXFactory // // Copyright © 2016 Sage Bionetworks. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // 3. Neither the name of the copyright holder(s) nor the names of any contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. No license is granted to the trademarks of // the copyright holders even if such marks are included in this software. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // import ResearchKit open class SBAPermissionsSkipRule: ORKSkipStepNavigationRule { /** Manager for handling requesting permissions */ open var permissionsManager: SBAPermissionsManager { return SBAPermissionsManager.shared } /** Permission types to request for this step of the task. */ public let permissionTypes: [SBAPermissionObjectType] /** Whether or not the rule should be applied @param taskResult Ignored. @return `YES` if all permissions are granted */ open override func stepShouldSkip(with taskResult: ORKTaskResult) -> Bool { return self.permissionsManager.allPermissionsAuthorized(for: self.permissionTypes) } public required init(permissionTypes: [SBAPermissionObjectType]) { self.permissionTypes = permissionTypes super.init() } public required init(coder aDecoder: NSCoder) { self.permissionTypes = aDecoder.decodeObject(forKey: "permissionTypes") as! [SBAPermissionObjectType] super.init(coder: aDecoder) } open override func encode(with aCoder: NSCoder) { aCoder.encode(self.permissionTypes, forKey: "permissionTypes") super.encode(with: aCoder) } override open func copy(with zone: NSZone? = nil) -> Any { return type(of: self).init(permissionTypes: self.permissionTypes) } } open class SBAPermissionsStep: ORKTableStep, SBANavigationSkipRule { /** Manager for handling requesting permissions */ open var permissionsManager: SBAPermissionsManager { return SBAPermissionsManager.shared } /** Permission types to request for this step of the task. */ open var permissionTypes: [SBAPermissionObjectType] { get { return self.items as? [SBAPermissionObjectType] ?? [] } set { self.items = newValue } } @available(*, deprecated, message: "use `permissionTypes` instead") open var permissions: SBAPermissionsType { get { return permissionsManager.permissionsType(for: self.permissionTypes) } set { self.items = permissionsManager.typeObjectsFor(for: newValue) } } override public init(identifier: String) { super.init(identifier: identifier) commonInit() } public init(identifier: String, permissions: [SBAPermissionTypeIdentifier]) { super.init(identifier: identifier) self.items = self.permissionsManager.permissionsTypeFactory.permissionTypes(for: permissions) commonInit() } public convenience init?(inputItem: SBASurveyItem) { guard let survey = inputItem as? SBAFormStepSurveyItem else { return nil } self.init(identifier: inputItem.identifier) survey.mapStepValues(with: self) self.items = self.permissionsManager.permissionsTypeFactory.permissionTypes(for: survey.items) commonInit() } fileprivate func commonInit() { if self.title == nil { self.title = Localization.localizedString("SBA_PERMISSIONS_TITLE") } if self.items == nil { self.items = self.permissionsManager.defaultPermissionTypes } else if let healthKitPermission = self.permissionTypes.find({ $0.permissionType == .healthKit }) as? SBAHealthKitPermissionObjectType, (healthKitPermission.healthKitTypes == nil) || healthKitPermission.healthKitTypes!.count == 0, let replacement = permissionsManager.defaultPermissionTypes.find({ $0.permissionType == .healthKit }) as? SBAHealthKitPermissionObjectType { // If this is a healthkit step and the permission types are not defined, // then look in the default permission types for the default types to include. healthKitPermission.healthKitTypes = replacement.healthKitTypes } } required public init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override open func stepViewControllerClass() -> AnyClass { return SBAPermissionsStepViewController.classForCoder() } override open func isInstructionStep() -> Bool { return true } // MARK: SBANavigationSkipRule open func shouldSkipStep(with result: ORKTaskResult, and additionalTaskResults: [ORKTaskResult]?) -> Bool { return self.permissionsManager.allPermissionsAuthorized(for: self.permissionTypes) } // MARK: Cell overrides let cellIdentifier = "PermissionsCell" override open func reuseIdentifierForRow(at indexPath: IndexPath) -> String { return cellIdentifier } override open func registerCells(for tableView: UITableView) { tableView.register(SBAMultipleLineTableViewCell.classForCoder(), forCellReuseIdentifier: cellIdentifier) } override open func configureCell(_ cell: UITableViewCell, indexPath: IndexPath, tableView: UITableView) { guard let item = self.objectForRow(at: indexPath) as? SBAPermissionObjectType, let multipleLineCell = cell as? SBAMultipleLineTableViewCell else { return } multipleLineCell.titleLabel?.text = item.title multipleLineCell.subtitleLabel?.text = item.detail } } open class SBAPermissionsStepViewController: ORKTableStepViewController { var permissionsGranted: Bool = false override open var result: ORKStepResult? { guard let result = super.result else { return nil } // Add a result for whether or not the permissions were granted let grantedResult = ORKBooleanQuestionResult(identifier: result.identifier) grantedResult.booleanAnswer = NSNumber(value: permissionsGranted) result.results = [grantedResult] return result } override open func goForward() { guard let permissionsStep = self.step as? SBAPermissionsStep else { assertionFailure("Step is not of expected type") super.goForward() return } // Show a loading view to indicate that something is happening self.showLoadingView() let permissionsManager = permissionsStep.permissionsManager let permissions = permissionsStep.permissionTypes permissionsManager.requestPermissions(for: permissions, alertPresenter: self) { [weak self] (granted) in if granted || permissionsStep.isOptional { self?.permissionsGranted = granted self?.goNext() } else if let strongSelf = self, let strongDelegate = strongSelf.delegate { let error = NSError(domain: "SBAPermissionsStepDomain", code: 1, userInfo: nil) strongDelegate.stepViewControllerDidFail(strongSelf, withError: error) } } } override open func skipForward() { goNext() } fileprivate func goNext() { super.goForward() } open override var cancelButtonItem: UIBarButtonItem? { // Override the cancel button to *not* display. User must tap the "Continue" button. get { return nil } set {} } }
31a5e0dd50cd18d4c808f4910dd84c41
37.227848
152
0.681788
false
false
false
false
Kesoyuh/Codebrew2017
refs/heads/master
Codebrew2017/AppDelegate.swift
mit
1
// // AppDelegate.swift // Codebrew2017 // // Created by Changchang on 18/3/17. // Copyright © 2017 University of Melbourne. All rights reserved. // import UIKit import Firebase @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. // Initialize Firebase FIRApp.configure() //customize UINavigationBar appearance UINavigationBar.appearance().barStyle = UIBarStyle.default //UINavigationBar.appearance().barTintColor = UIColor.blackColor() //UIColor(red: 242.0/255.0, green: 116.0/255.0, blue: 119.0/255.0, alpha: 1.0) UINavigationBar.appearance().tintColor = UIColor(red: 0.0/255.0, green: 51.0/255.0, blue: 102.0/255.0, alpha: 1.0) if let barFont = UIFont(name: "Avenir-Light", size: 24.0) { UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName:UIColor(red: 0.0/255.0, green: 51.0/255.0, blue: 102.0/255.0, alpha: 1.0), NSFontAttributeName:barFont] } //customize UITabBar appearance UITabBar.appearance().tintColor = UIColor(red: 0.0/255.0, green: 51.0/255.0, blue: 102.0/255.0, alpha: 1.0) return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
f22744379ee998d1014494c411f35e6c
51.559322
285
0.726217
false
false
false
false
OatmealCode/Oatmeal
refs/heads/master
Carlos/FetcherValueTransformation.swift
mit
2
import Foundation import PiedPiper extension Fetcher { /** Applies a transformation to the fetcher The transformation works by changing the type of the value the fetcher returns when succeeding Use this transformation when you store a value type but want to mount the fetcher in a pipeline that works with other value types - parameter transformer: The transformation you want to apply - returns: A new fetcher result of the transformation of the original fetcher */ public func transformValues<A: OneWayTransformer where OutputType == A.TypeIn>(transformer: A) -> BasicFetcher<KeyType, A.TypeOut> { return BasicFetcher( getClosure: { key in return self.get(key).mutate(transformer) } ) } /** Applies a transformation to the fetcher The transformation works by changing the type of the value the fetcher returns when succeeding Use this transformation when you store a value type but want to mount the fetcher in a pipeline that works with other value types - parameter transformerClosure: The transformation closure you want to apply - returns: A new fetcher result of the transformation of the original fetcher */ @available(*, deprecated=0.7) public func transformValues<A>(transformerClosure: OutputType -> Future<A>) -> BasicFetcher<KeyType, A> { return self.transformValues(wrapClosureIntoOneWayTransformer(transformerClosure)) } } /** Applies a transformation to a fetch closure The transformation works by changing the type of the value the fetcher returns when succeeding Use this transformation when you store a value type but want to mount the fetcher in a pipeline that works with other value types - parameter fetchClosure: The fetcher closure you want to transform - parameter transformer: The transformation you want to apply - returns: A new fetcher result of the transformation of the original fetcher */ @available(*, deprecated=0.5) public func transformValues<A, B: OneWayTransformer>(fetchClosure: (key: A) -> Future<B.TypeIn>, transformer: B) -> BasicFetcher<A, B.TypeOut> { return transformValues(wrapClosureIntoFetcher(fetchClosure), transformer: transformer) } /** Applies a transformation to a fetcher The transformation works by changing the type of the value the fetcher returns when succeeding Use this transformation when you store a value type but want to mount the fetcher in a pipeline that works with other value types - parameter fetcher: The fetcher you want to transform - parameter transformer: The transformation you want to apply - returns: A new fetcher result of the transformation of the original fetcher */ @available(*, deprecated=0.5) public func transformValues<A: Fetcher, B: OneWayTransformer where A.OutputType == B.TypeIn>(fetcher: A, transformer: B) -> BasicFetcher<A.KeyType, B.TypeOut> { return fetcher.transformValues(transformer) } /** Applies a transformation to a fetch closure The transformation works by changing the type of the value the fetcher returns when succeeding Use this transformation when you store a value type but want to mount the fetcher in a pipeline that works with other value types - parameter fetchClosure: The fetcher closure you want to transform - parameter transformerClosure: The transformation closure you want to apply - returns: A new fetcher result of the transformation of the original fetcher */ @available(*, deprecated=0.5) public func transformValues<A, B, C>(fetchClosure: (key: A) -> Future<B>, transformerClosure: B -> Future<C>) -> BasicFetcher<A, C> { return transformValues(wrapClosureIntoFetcher(fetchClosure), transformer: wrapClosureIntoOneWayTransformer(transformerClosure)) } /** Applies a transformation to a fetcher The transformation works by changing the type of the value the fetcher returns when succeeding Use this transformation when you store a value type but want to mount the fetcher in a pipeline that works with other value types - parameter fetcher: The fetcher you want to transform - parameter transformerClosure: The transformation closure you want to apply - returns: A new fetcher result of the transformation of the original fetcher */ @available(*, deprecated=0.5) public func transformValues<A: Fetcher, B>(fetcher: A, transformerClosure: A.OutputType -> Future<B>) -> BasicFetcher<A.KeyType, B> { return fetcher.transformValues(transformerClosure) } /** Applies a transformation to a fetch closure The transformation works by changing the type of the value the fetcher returns when succeeding Use this transformation when you store a value type but want to mount the fetcher in a pipeline that works with other value types - parameter fetchClosure: The fetch closure you want to transform - parameter transformer: The transformation you want to apply - returns: A new fetcher result of the transformation of the original fetcher */ @available(*, deprecated=0.7) public func =>><A, B: OneWayTransformer>(fetchClosure: (key: A) -> Future<B.TypeIn>, transformer: B) -> BasicFetcher<A, B.TypeOut> { return wrapClosureIntoFetcher(fetchClosure).transformValues(transformer) } /** Applies a transformation to a fetcher The transformation works by changing the type of the value the fetcher returns when succeeding Use this transformation when you store a value type but want to mount the fetcher in a pipeline that works with other value types - parameter fetcher: The fetcher you want to transform - parameter transformer: The transformation you want to apply - returns: A new fetcher result of the transformation of the original fetcher */ public func =>><A: Fetcher, B: OneWayTransformer where A.OutputType == B.TypeIn>(fetcher: A, transformer: B) -> BasicFetcher<A.KeyType, B.TypeOut> { return fetcher.transformValues(transformer) } /** Applies a transformation to a fetch closure The transformation works by changing the type of the value the fetcher returns when succeeding Use this transformation when you store a value type but want to mount the fetcher in a pipeline that works with other value types - parameter fetchClosure: The fetch closure you want to transform - parameter transformerClosure: The transformation closure you want to apply - returns: A new fetcher result of the transformation of the original fetcher */ @available(*, deprecated=0.7) public func =>><A, B, C>(fetchClosure: (key: A) -> Future<B>, transformerClosure: B -> Future<C>) -> BasicFetcher<A, C> { return wrapClosureIntoFetcher(fetchClosure).transformValues(wrapClosureIntoOneWayTransformer(transformerClosure)) } /** Applies a transformation to a fetcher The transformation works by changing the type of the value the fetcher returns when succeeding Use this transformation when you store a value type but want to mount the fetcher in a pipeline that works with other value types - parameter fetcher: The fetcher you want to transform - parameter transformerClosure: The transformation closure you want to apply - returns: A new fetcher result of the transformation of the original fetcher */ @available(*, deprecated=0.7) public func =>><A: Fetcher, B>(fetcher: A, transformerClosure: A.OutputType -> Future<B>) -> BasicFetcher<A.KeyType, B> { return fetcher.transformValues(wrapClosureIntoOneWayTransformer(transformerClosure)) }
0e94e80a38bb0d1aa0ca7c1508b7dc43
46.477419
160
0.773716
false
false
false
false
mono0926/LicensePlist
refs/heads/main
Tests/LicensePlistTests/Entity/FileReader/SwiftPackageFileReaderTests.swift
mit
1
// // SwiftPackageFileReaderTests.swift // LicensePlistTests // // Created by yosshi4486 on 2021/04/06. // import XCTest @testable import LicensePlistCore class SwiftPackageFileReaderTests: XCTestCase { var fileURL: URL! var packageResolvedText: String { return #""" { "object": { "pins": [ { "package": "APIKit", "repositoryURL": "https://github.com/ishkawa/APIKit.git", "state": { "branch": null, "revision": "4e7f42d93afb787b0bc502171f9b5c12cf49d0ca", "version": "5.3.0" } }, { "package": "Flatten", "repositoryURL": "https://github.com/YusukeHosonuma/Flatten.git", "state": { "branch": null, "revision": "5286148aa255f57863e0d7e2b827ca6b91677051", "version": "0.1.0" } }, { "package": "HeliumLogger", "repositoryURL": "https://github.com/Kitura/HeliumLogger.git", "state": { "branch": null, "revision": "fc2a71597ae974da5282d751bcc11965964bccce", "version": "2.0.0" } }, { "package": "LoggerAPI", "repositoryURL": "https://github.com/Kitura/LoggerAPI.git", "state": { "branch": null, "revision": "4e6b45e850ffa275e8e26a24c6454fd709d5b6ac", "version": "2.0.0" } }, { "package": "SHList", "repositoryURL": "https://github.com/YusukeHosonuma/SHList.git", "state": { "branch": null, "revision": "6c61f5382dd07a64d76bc8b7fad8cec0d8a4ff7a", "version": "0.1.0" } }, { "package": "swift-argument-parser", "repositoryURL": "https://github.com/apple/swift-argument-parser.git", "state": { "branch": null, "revision": "9f39744e025c7d377987f30b03770805dcb0bcd1", "version": "1.1.4" } }, { "package": "HTMLEntities", "repositoryURL": "https://github.com/Kitura/swift-html-entities.git", "state": { "branch": null, "revision": "d8ca73197f59ce260c71bd6d7f6eb8bbdccf508b", "version": "4.0.1" } }, { "package": "swift-log", "repositoryURL": "https://github.com/apple/swift-log.git", "state": { "branch": null, "revision": "5d66f7ba25daf4f94100e7022febf3c75e37a6c7", "version": "1.4.2" } }, { "package": "SwiftParamTest", "repositoryURL": "https://github.com/YusukeHosonuma/SwiftParamTest", "state": { "branch": null, "revision": "f513e1dbbdd86e2ca2b672537f4bcb4417f94c27", "version": "2.2.1" } }, { "package": "Yaml", "repositoryURL": "https://github.com/behrang/YamlSwift.git", "state": { "branch": null, "revision": "287f5cab7da0d92eb947b5fd8151b203ae04a9a3", "version": "3.4.4" } } ] }, "version": 1 } """# } override func setUpWithError() throws { fileURL = URL(fileURLWithPath: "\(TestUtil.testProjectsPath)/SwiftPackageManagerTestProject/SwiftPackageManagerTestProject.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved") } override func tearDownWithError() throws { fileURL = nil } func testInvalidPath() throws { let invalidFilePath = fileURL.deletingLastPathComponent().appendingPathComponent("Podfile.lock") let reader = SwiftPackageFileReader(path: invalidFilePath) XCTAssertThrowsError(try reader.read()) } func testPackageSwift() throws { // Path for this package's Package.swift. let packageSwiftPath = TestUtil.sourceDir.appendingPathComponent("Package.swift").lp.fileURL let reader = SwiftPackageFileReader(path: packageSwiftPath) XCTAssertEqual( try reader.read()?.trimmingCharacters(in: .whitespacesAndNewlines), packageResolvedText.trimmingCharacters(in: .whitespacesAndNewlines) ) } func testPackageResolved() throws { // Path for this package's Package.resolved. let packageResolvedPath = TestUtil.sourceDir.appendingPathComponent("Package.resolved").lp.fileURL let reader = SwiftPackageFileReader(path: packageResolvedPath) XCTAssertEqual( try reader.read()?.trimmingCharacters(in: .whitespacesAndNewlines), packageResolvedText.trimmingCharacters(in: .whitespacesAndNewlines) ) } }
6030245b16d3d6814c41ea5cf7327df3
34.675497
200
0.501021
false
true
false
false
fangspeen/swift-linear-algebra
refs/heads/master
LinearAlgebra/main.swift
bsd-2-clause
1
// // main.swift // LinearAlgebra // // Created by Jean Blignaut on 2015/03/21. // Copyright (c) 2015 Jean Blignaut. All rights reserved. // import Foundation import Accelerate let a: Array<Double> = [1,2,3,4] let b: Array<Double> = [1,2,3] var A = la_object_t() var B = la_object_t() a.withUnsafeBufferPointer{ (buffer: UnsafeBufferPointer<Double>) -> Void in //should have been short hand for below but some how doesn't work in swift //A = la_vector_from_double_buffer(buffer.baseAddress, la_count_t(4), la_count_t(1), la_attribute_t(LA_DEFAULT_ATTRIBUTES)) A = la_matrix_from_double_buffer(buffer.baseAddress, la_count_t(a.count), la_count_t(1), la_count_t(1), la_hint_t(LA_NO_HINT), la_attribute_t(LA_DEFAULT_ATTRIBUTES)) } b.withUnsafeBufferPointer { (buffer: UnsafeBufferPointer<Double>) -> Void in //should have been short hand for below but some how doesn't work in swift //B = la_vector_from_double_buffer(buffer.baseAddress, la_count_t(4), la_count_t(1), la_attribute_t(LA_DEFAULT_ATTRIBUTES)) //I would have expected that the transpose would be required but seems oiptional B = //la_transpose( la_matrix_from_double_buffer(buffer.baseAddress, la_count_t(b.count), la_count_t(1), la_count_t(1), la_hint_t(LA_NO_HINT), la_attribute_t(LA_DEFAULT_ATTRIBUTES))//) } let res = la_solve(A,B) let mult = la_outer_product(A, B) var buf: Array<Double> = [0,0,0 ,0,0,0 ,0,0,0 ,0,0,0] buf.withUnsafeMutableBufferPointer { (inout buffer: UnsafeMutableBufferPointer<Double>) -> Void in la_matrix_to_double_buffer(buffer.baseAddress, la_count_t(3), mult) } //contents of a println(a) //contents of b println(b) //seems to be the dimensions of the vector in A print(A) //seems to be the dimensions of the vector in B print(B) //seems to be the dimensions of the resultant matrix print(mult) //result println(buf)
b363bdfd1c7bf21129b07f2ea69ef607
32.482759
172
0.678682
false
false
false
false
IcyButterfly/JSONFactory
refs/heads/master
JSONConverter/JSON/JSONAssembler.swift
mit
1
// // JSONAssembler.swift // JSONConverter // // Created by ET|冰琳 on 2017/3/2. // Copyright © 2017年 IB. All rights reserved. // import Foundation protocol JSONAssembler { static func assemble(jsonInfo: JSONInfo) -> String } extension JSONAssembler { static func assemble(jsonInfos: [JSONInfo]) -> String { let count = jsonInfos.count let last = jsonInfos[count - 1] var code = MappingAceAssembler.assemble(jsonInfo: last) for index in 0..<(count - 1) { code += "\n\n" let jsonInfo = jsonInfos[index] code += MappingAceAssembler.assemble(jsonInfo: jsonInfo) } return code } static func assemble(jsonInfos: [JSONInfo], to filePath: String) { let txt = assemble(jsonInfos: jsonInfos) do { try txt.write(toFile: filePath, atomically: true, encoding: String.Encoding.utf8) print("write to file suceed\n[Path]: \(filePath)") }catch (let e) { print("write to file failed\n[Path]: \(filePath)\n[Error]: \(e)") } } static func assemble(jsonInfos: [JSONInfo], toDocument: String){ let date = Date() let dateFormate = DateFormatter() dateFormate.dateFormat = "yyyy/M/d" let time = dateFormate.string(from: date) for item in jsonInfos { let title = "//\n" + "// \(item.name!).swift\n" + "//\n" + "// created by JSONConverter on \(time)" + "\n\n\n" let txt = title + assemble(jsonInfo: item) let filePath = toDocument + "/\(item.name!).swift" do { try txt.write(toFile: filePath, atomically: true, encoding: String.Encoding.utf8) print("write to file suceed\n[Path]: \(filePath)") }catch (let e) { print("write to file failed\n[Path]: \(filePath)\n[Error]: \(e)") } } } } struct MappingAceAssembler: JSONAssembler { static func assemble(jsonInfo: JSONInfo) -> String { let name = jsonInfo.name! var code = "public struct \(name): Mapping {\n" for property in jsonInfo.properties.sorted(by: { (a, b) -> Bool in a.name < b.name }) { let name = property.name let type = property.isRequired ? property.type : "\(property.type)?" let defaultValue: String if let defaultV = property.defaultValue { defaultValue = " = \(defaultV)" code = "public struct \(name): InitMapping {\n" } else { defaultValue = "" } let desc: String if let description = property.description { desc = "//\(description)" }else { desc = "" } code += " public var \(name): \(type)\(defaultValue)? \(desc)\n" } code += "}\n" return code } }
6350ba9994a8417b57af94d08d5e8ff0
26.429752
97
0.480265
false
false
false
false
fluidpixel/SwiftHN
refs/heads/master
SwiftHN/Cells/CommentsCell.swift
gpl-2.0
1
// // CommentsCell.swift // SwiftHN // // Created by Thomas Ricouard on 30/06/14. // Copyright (c) 2014 Thomas Ricouard. All rights reserved. // import UIKit import SwiftHNShared import HackerSwifter let CommentsCellId = "commentCellId" let CommentCellMarginConstant: CGFloat = 16.0 let CommentCellTopMargin: CGFloat = 5.0 let CommentCellFontSize: CGFloat = 13.0 let CommentCellUsernameHeight: CGFloat = 25.0 let CommentCellBottomMargin: CGFloat = 16.0 class CommentsCell: UITableViewCell { var comment: Comment! { didSet { var username = comment.username var date = " - " + comment.prettyTime! var usernameAttributed = NSAttributedString(string: username!, attributes: [NSFontAttributeName : UIFont.boldSystemFontOfSize(CommentCellFontSize), NSForegroundColorAttributeName: UIColor.HNColor()]) var dateAttribute = NSAttributedString(string: date, attributes: [NSFontAttributeName: UIFont.systemFontOfSize(CommentCellFontSize), NSForegroundColorAttributeName: UIColor.DateLighGrayColor()]) var fullAttributed = NSMutableAttributedString(attributedString: usernameAttributed) fullAttributed.appendAttributedString(dateAttribute) self.commentLabel.font = UIFont.systemFontOfSize(CommentCellFontSize) self.usernameLabel.attributedText = fullAttributed self.commentLabel.text = comment.text } } var indentation: CGFloat { didSet { self.commentLeftMarginConstraint.constant = indentation self.usernameLeftMarginConstrain.constant = indentation self.commentHeightConstrain.constant = self.contentView.frame.size.height - CommentCellUsernameHeight - CommentCellTopMargin - CommentCellMarginConstant + 5.0 self.contentView.setNeedsUpdateConstraints() } } @IBOutlet var usernameLabel: UILabel! = nil @IBOutlet var commentLabel: UITextView! = nil @IBOutlet var commentLeftMarginConstraint: NSLayoutConstraint! = nil @IBOutlet var commentHeightConstrain: NSLayoutConstraint! = nil @IBOutlet var usernameLeftMarginConstrain: NSLayoutConstraint! = nil required init?(coder aDecoder: NSCoder) { // required for Xcode6-Beta5 self.indentation = CommentCellMarginConstant super.init(coder: aDecoder) } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { self.indentation = CommentCellMarginConstant super.init(style: style, reuseIdentifier: reuseIdentifier) } override func awakeFromNib() { super.awakeFromNib() self.commentLabel.font = UIFont.systemFontOfSize(CommentCellFontSize) self.commentLabel.textColor = UIColor.CommentLightGrayColor() self.commentLabel.linkTextAttributes = [NSFontAttributeName: UIFont.systemFontOfSize(CommentCellFontSize), NSForegroundColorAttributeName: UIColor.ReadingListColor()] } override func layoutSubviews() { super.layoutSubviews() self.commentLabel.text = comment.text self.commentLabel.textContainer.lineFragmentPadding = 0 self.commentLabel.textContainerInset = UIEdgeInsetsZero self.commentLabel.contentInset = UIEdgeInsetsZero self.commentLabel.frame.size.width = self.contentView.bounds.width - (self.commentLeftMarginConstraint.constant * 2) - (CommentCellMarginConstant * CGFloat(self.comment.depth)) self.indentation = CommentCellMarginConstant + (CommentCellMarginConstant * CGFloat(self.comment.depth)) } class func heightForText(text: String, bounds: CGRect, level: Int) -> CGFloat { var size = text.boundingRectWithSize(CGSizeMake(CGRectGetWidth(bounds) - (CommentCellMarginConstant * 2) - (CommentCellMarginConstant * CGFloat(level)), CGFloat.max), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName: UIFont.systemFontOfSize(CommentCellFontSize)], context: nil) return CommentCellMarginConstant + CommentCellUsernameHeight + CommentCellTopMargin + size.height + CommentCellBottomMargin } }
2a4dbd4499082b36ec0b4b31cedd027b
42.828283
184
0.704079
false
false
false
false
Brightify/DataMapper
refs/heads/master
Tests/TestUtils/TestData.swift
mit
1
// // TestData.swift // DataMapper // // Created by Filip Dolnik on 01.01.17. // Copyright © 2017 Brightify. All rights reserved. // import DataMapper import Nimble struct TestData { static let deserializableStruct = DeserializableStruct(number: 1, text: "a", points: [2], children: []) static let mappableStruct = MappableStruct(number: 1, text: "a", points: [2], children: []) static let mappableClass = MappableClass(number: 1, text: "a", points: [2], children: []) static let serializableStruct = SerializableStruct(number: 1, text: "a", points: [2], children: []) static let type = SupportedType.dictionary(["number": .int(1), "text": .string("a"), "points": .array([.double(2)]), "children": .array([])]) static let invalidType = SupportedType.dictionary(["number": .int(1)]) // Returned elements == Floor[ x! * e ] static func generate(x: Int) -> PerformanceStruct { var object = PerformanceStruct(number: 0, text: "0", points: [], children: [], dictionary: ["A": false, "B": true]) for i in 1...x { object = PerformanceStruct(number: i, text: "\(i)", points: (1...i).map { Double($0) }, children: (1...i).map { _ in object }, dictionary: ["A": false, "B": true]) } return object } struct PerformanceStruct: Mappable, Codable { private(set) var number: Int? private(set) var text: String = "" private(set) var points: [Double] = [] private(set) var children: [PerformanceStruct] = [] let dictionary: [String: Bool] init(number: Int?, text: String, points: [Double], children: [PerformanceStruct], dictionary: [String: Bool]) { self.number = number self.text = text self.points = points self.children = children self.dictionary = dictionary } init(_ data: DeserializableData) throws { dictionary = try data["dictionary"].get() try mapping(data) } func serialize(to data: inout SerializableData) { data["dictionary"].set(dictionary) mapping(&data) } mutating func mapping(_ data: inout MappableData) throws { data["number"].map(&number) try data["text"].map(&text) data["points"].map(&points, or: []) data["children"].map(&children, or: []) } } struct DeserializableStruct: Deserializable { let number: Int? let text: String let points: [Double] let children: [MappableStruct] init(number: Int?, text: String, points: [Double], children: [MappableStruct]) { self.number = number self.text = text self.points = points self.children = children } init(_ data: DeserializableData) throws { number = data["number"].get() text = try data["text"].get() points = data["points"].get(or: []) children = data["children"].get(or: []) } } struct MappableStruct: Mappable { private(set) var number: Int? private(set) var text: String = "" private(set) var points: [Double] = [] private(set) var children: [MappableStruct] = [] init(number: Int?, text: String, points: [Double], children: [MappableStruct]) { self.number = number self.text = text self.points = points self.children = children } init(_ data: DeserializableData) throws { try mapping(data) } mutating func mapping(_ data: inout MappableData) throws { data["number"].map(&number) try data["text"].map(&text) data["points"].map(&points, or: []) data["children"].map(&children, or: []) } } class MappableClass: Mappable { let number: Int? private(set) var text: String = "" private(set) var points: [Double] = [] private(set) var children: [MappableStruct] = [] init(number: Int?, text: String, points: [Double], children: [MappableStruct]) { self.number = number self.text = text self.points = points self.children = children } required init(_ data: DeserializableData) throws { number = data["number"].get() try mapping(data) } func serialize(to data: inout SerializableData) { mapping(&data) data["number"].set(number) } func mapping(_ data: inout MappableData) throws { try data["text"].map(&text) data["points"].map(&points, or: []) data["children"].map(&children, or: []) } } struct SerializableStruct: Serializable { let number: Int? let text: String let points: [Double] let children: [MappableStruct] init(number: Int?, text: String, points: [Double], children: [MappableStruct]) { self.number = number self.text = text self.points = points self.children = children } func serialize(to data: inout SerializableData) { data["number"].set(number) data["text"].set(text) data["points"].set(points) data["children"].set(children) } } struct Map { static let validType = SupportedType.dictionary([ "value": .int(1), "array": .array([.int(1), .int(2)]), "dictionary": .dictionary(["a": .int(1), "b": .int(2)]), "optionalArray": .array([.int(1), .null]), "optionalDictionary": .dictionary(["a": .int(1), "b": .null]), ]) static let invalidType = SupportedType.dictionary([ "value": .double(1), "array": .array([.double(1), .int(2)]), "dictionary": .dictionary(["a": .double(1), "b": .int(2)]), "optionalArray": .double(1), "optionalDictionary": .null ]) static let nullType = SupportedType.dictionary([ "value": .null, "array": .null, "dictionary": .null, "optionalArray": .null, "optionalDictionary": .null, ]) static let pathType = SupportedType.dictionary(["a": .dictionary(["b": .int(1)])]) static func assertValidType(_ value: Int?, _ array: [Int]?, _ dictionary: [String: Int]?, _ optionalArray: [Int?]?, _ optionalDictionary: [String: Int?]?, file: FileString = #file, line: UInt = #line) { expect(value, file: file, line: line) == 1 expect(array, file: file, line: line) == [1, 2] expect(dictionary, file: file, line: line) == ["a": 1, "b": 2] expect(areEqual(optionalArray, [1, nil]), file: file, line: line).to(beTrue()) expect(areEqual(optionalDictionary, ["a": 1, "b": nil]), file: file, line: line).to(beTrue()) } static func assertValidTypeUsingTransformation(_ value: Int?, _ array: [Int]?, _ dictionary: [String: Int]?, _ optionalArray: [Int?]?, _ optionalDictionary: [String: Int?]?, file: FileString = #file, line: UInt = #line) { expect(value, file: file, line: line) == 2 expect(array, file: file, line: line) == [2, 4] expect(dictionary, file: file, line: line) == ["a": 2, "b": 4] expect(areEqual(optionalArray, [2, nil]), file: file, line: line).to(beTrue()) expect(areEqual(optionalDictionary, ["a": 2, "b": nil]), file: file, line: line).to(beTrue()) } static func assertInvalidTypeOr(_ value: Int?, _ array: [Int]?, _ dictionary: [String: Int]?, _ optionalArray: [Int?]?, _ optionalDictionary: [String: Int?]?, file: FileString = #file, line: UInt = #line) { expect(value, file: file, line: line) == 0 expect(array, file: file, line: line) == [0] expect(dictionary, file: file, line: line) == ["a": 0] expect(areEqual(optionalArray, [0]), file: file, line: line).to(beTrue()) expect(areEqual(optionalDictionary, ["a": 0]), file: file, line: line).to(beTrue()) } static func assertInvalidType(_ value: Int?, _ array: [Int]?, _ dictionary: [String: Int]?, _ optionalArray: [Int?]?, _ optionalDictionary: [String: Int?]?, file: FileString = #file, line: UInt = #line) { expect(value, file: file, line: line).to(beNil()) expect(array, file: file, line: line).to(beNil()) expect(dictionary, file: file, line: line).to(beNil()) expect(optionalArray, file: file, line: line).to(beNil()) expect(optionalDictionary, file: file, line: line).to(beNil()) } } struct StaticPolymorph { class A: Polymorphic { class var polymorphicKey: String { return "K" } class var polymorphicInfo: PolymorphicInfo { return createPolymorphicInfo().with(subtype: B.self) } } class B: A { override class var polymorphicInfo: PolymorphicInfo { // D is intentionally registered here. return createPolymorphicInfo().with(subtypes: C.self, D.self) } } class C: B { override class var polymorphicKey: String { return "C" } } class D: C { override class var polymorphicInfo: PolymorphicInfo { return createPolymorphicInfo(name: "D2") } } // Intentionally not registered. class E: D { } class X { } } struct PolymorphicTypes { static let a = A(id: 1) static let b = B(id: 2, name: "name") static let c = C(id: 3, number: 0) static let aType = SupportedType.dictionary(["id": .int(1), "type": .string("A")]) static let bType = SupportedType.dictionary(["id": .int(2), "name": .string("name"), "type": .string("B")]) static let cType = SupportedType.dictionary(["id": .int(3), "number": .int(0), "type": .string("C")]) static let aTypeWithoutPolymorphicData = SupportedType.dictionary(["id": .int(1)]) static let bTypeWithoutPolymorphicData = SupportedType.dictionary(["id": .int(2), "name": .string("name")]) static let cTypeWithoutPolymorphicData = SupportedType.dictionary(["id": .int(3), "number": .int(0)]) class A: PolymorphicMappable { static var polymorphicKey = "type" static var polymorphicInfo: PolymorphicInfo { return createPolymorphicInfo().with(subtypes: B.self, C.self) } let id: Int init(id: Int) { self.id = id } required init(_ data: DeserializableData) throws { id = try data["id"].get() try mapping(data) } func serialize(to data: inout SerializableData) { data["id"].set(id) mapping(&data) } func mapping(_ data: inout MappableData) throws { } } class B: A { var name: String? init(id: Int, name: String?) { super.init(id: id) self.name = name } required init(_ data: DeserializableData) throws { try super.init(data) } override func mapping(_ data: inout MappableData) throws { try super.mapping(&data) data["name"].map(&name) } } class C: A { var number: Int? init(id: Int, number: Int?) { super.init(id: id) self.number = number } required init(_ data: DeserializableData) throws { try super.init(data) } override func mapping(_ data: inout MappableData) throws { try super.mapping(&data) data["number"].map(&number) } } } struct CustomIntTransformation: Transformation { typealias Object = Int func transform(from value: SupportedType) -> Int? { return value.int.map { $0 * 2 } ?? nil } func transform(object: Int?) -> SupportedType { return object.map { .int($0 / 2) } ?? .null } } } extension TestData.PerformanceStruct: Equatable { } func ==(lhs: TestData.PerformanceStruct, rhs: TestData.PerformanceStruct) -> Bool { return lhs.number == rhs.number && lhs.text == rhs.text && lhs.points == rhs.points && lhs.children == rhs.children && lhs.dictionary == rhs.dictionary } extension TestData.DeserializableStruct: Equatable { } func ==(lhs: TestData.DeserializableStruct, rhs: TestData.DeserializableStruct) -> Bool { return lhs.number == rhs.number && lhs.text == rhs.text && lhs.points == rhs.points && lhs.children == rhs.children } extension TestData.MappableStruct: Equatable { } func ==(lhs: TestData.MappableStruct, rhs: TestData.MappableStruct) -> Bool { return lhs.number == rhs.number && lhs.text == rhs.text && lhs.points == rhs.points && lhs.children == rhs.children } extension TestData.MappableClass: Equatable { } func ==(lhs: TestData.MappableClass, rhs: TestData.MappableClass) -> Bool { return lhs.number == rhs.number && lhs.text == rhs.text && lhs.points == rhs.points && lhs.children == rhs.children } extension TestData.SerializableStruct: Equatable { } func ==(lhs: TestData.SerializableStruct, rhs: TestData.SerializableStruct) -> Bool { return lhs.number == rhs.number && lhs.text == rhs.text && lhs.points == rhs.points && lhs.children == rhs.children } func areEqual(_ lhs: [Int?]?, _ rhs: [Int?]?) -> Bool { if let lhs = lhs, let rhs = rhs { if lhs.count == rhs.count { for i in lhs.indices { if lhs[i] != rhs[i] { return false } } return true } } return lhs == nil && rhs == nil } func areEqual(_ lhs: [String: Int?]?, _ rhs: [String: Int?]?) -> Bool { if let lhs = lhs, let rhs = rhs { if lhs.count == rhs.count { for i in lhs.keys { if let lValue = lhs[i], let rValue = rhs[i], lValue == rValue { continue } else { return false } } return true } } return lhs == nil && rhs == nil }
d72f718979429f4133a356f31d7ca1e3
34.43018
155
0.508105
false
false
false
false
dreamsxin/swift
refs/heads/master
benchmark/single-source/SortStrings.swift
apache-2.0
4
//===--- SortStrings.swift ------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // Sort an array of strings using an explicit sort predicate. var stringBenchmarkWords: [String] = [ "woodshed", "lakism", "gastroperiodynia", "afetal", "ramsch", "Nickieben", "undutifulness", "birdglue", "ungentlemanize", "menacingly", "heterophile", "leoparde", "Casearia", "decorticate", "neognathic", "mentionable", "tetraphenol", "pseudonymal", "dislegitimate", "Discoidea", "intitule", "ionium", "Lotuko", "timbering", "nonliquidating", "oarialgia", "Saccobranchus", "reconnoiter", "criminative", "disintegratory", "executer", "Cylindrosporium", "complimentation", "Ixiama", "Araceae", "silaginoid", "derencephalus", "Lamiidae", "marrowlike", "ninepin", "dynastid", "lampfly", "feint", "trihemimer", "semibarbarous", "heresy", "tritanope", "indifferentist", "confound", "hyperbolaeon", "planirostral", "philosophunculist", "existence", "fretless", "Leptandra", "Amiranha", "handgravure", "gnash", "unbelievability", "orthotropic", "Susumu", "teleutospore", "sleazy", "shapeliness", "hepatotomy", "exclusivism", "stifler", "cunning", "isocyanuric", "pseudepigraphy", "carpetbagger", "respectiveness", "Jussi", "vasotomy", "proctotomy", "ovatotriangular", "aesthetic", "schizogamy", "disengagement", "foray", "haplocaulescent", "noncoherent", "astrocyte", "unreverberated", "presenile", "lanson", "enkraal", "contemplative", "Syun", "sartage", "unforgot", "wyde", "homeotransplant", "implicational", "forerunnership", "calcaneum", "stomatodeum", "pharmacopedia", "preconcessive", "trypanosomatic", "intracollegiate", "rampacious", "secundipara", "isomeric", "treehair", "pulmonal", "uvate", "dugway", "glucofrangulin", "unglory", "Amandus", "icterogenetic", "quadrireme", "Lagostomus", "brakeroot", "anthracemia", "fluted", "protoelastose", "thro", "pined", "Saxicolinae", "holidaymaking", "strigil", "uncurbed", "starling", "redeemeress", "Liliaceae", "imparsonee", "obtusish", "brushed", "mesally", "probosciformed", "Bourbonesque", "histological", "caroba", "digestion", "Vindemiatrix", "triactinal", "tattling", "arthrobacterium", "unended", "suspectfulness", "movelessness", "chartist", "Corynebacterium", "tercer", "oversaturation", "Congoleum", "antiskeptical", "sacral", "equiradiate", "whiskerage", "panidiomorphic", "unplanned", "anilopyrine", "Queres", "tartronyl", "Ing", "notehead", "finestiller", "weekender", "kittenhood", "competitrix", "premillenarian", "convergescence", "microcoleoptera", "slirt", "asteatosis", "Gruidae", "metastome", "ambuscader", "untugged", "uneducated", "redistill", "rushlight", "freakish", "dosology", "papyrine", "iconologist", "Bidpai", "prophethood", "pneumotropic", "chloroformize", "intemperance", "spongiform", "superindignant", "divider", "starlit", "merchantish", "indexless", "unidentifiably", "coumarone", "nomism", "diaphanous", "salve", "option", "anallantoic", "paint", "thiofurfuran", "baddeleyite", "Donne", "heterogenicity", "decess", "eschynite", "mamma", "unmonarchical", "Archiplata", "widdifow", "apathic", "overline", "chaetophoraceous", "creaky", "trichosporange", "uninterlined", "cometwise", "hermeneut", "unbedraggled", "tagged", "Sminthurus", "somniloquacious", "aphasiac", "Inoperculata", "photoactivity", "mobship", "unblightedly", "lievrite", "Khoja", "Falerian", "milfoil", "protectingly", "householder", "cathedra", "calmingly", "tordrillite", "rearhorse", "Leonard", "maracock", "youngish", "kammererite", "metanephric", "Sageretia", "diplococcoid", "accelerative", "choreal", "metalogical", "recombination", "unimprison", "invocation", "syndetic", "toadback", "vaned", "cupholder", "metropolitanship", "paramandelic", "dermolysis", "Sheriyat", "rhabdus", "seducee", "encrinoid", "unsuppliable", "cololite", "timesaver", "preambulate", "sampling", "roaster", "springald", "densher", "protraditional", "naturalesque", "Hydrodamalis", "cytogenic", "shortly", "cryptogrammatical", "squat", "genual", "backspier", "solubleness", "macroanalytical", "overcovetousness", "Natalie", "cuprobismutite", "phratriac", "Montanize", "hymnologist", "karyomiton", "podger", "unofficiousness", "antisplasher", "supraclavicular", "calidity", "disembellish", "antepredicament", "recurvirostral", "pulmonifer", "coccidial", "botonee", "protoglobulose", "isonym", "myeloid", "premiership", "unmonopolize", "unsesquipedalian", "unfelicitously", "theftbote", "undauntable", "lob", "praenomen", "underriver", "gorfly", "pluckage", "radiovision", "tyrantship", "fraught", "doppelkummel", "rowan", "allosyndetic", "kinesiology", "psychopath", "arrent", "amusively", "preincorporation", "Montargis", "pentacron", "neomedievalism", "sima", "lichenicolous", "Ecclesiastes", "woofed", "cardinalist", "sandaracin", "gymnasial", "lithoglyptics", "centimeter", "quadrupedous", "phraseology", "tumuli", "ankylotomy", "myrtol", "cohibitive", "lepospondylous", "silvendy", "inequipotential", "entangle", "raveling", "Zeugobranchiata", "devastating", "grainage", "amphisbaenian", "blady", "cirrose", "proclericalism", "governmentalist", "carcinomorphic", "nurtureship", "clancular", "unsteamed", "discernibly", "pleurogenic", "impalpability", "Azotobacterieae", "sarcoplasmic", "alternant", "fitly", "acrorrheuma", "shrapnel", "pastorize", "gulflike", "foreglow", "unrelated", "cirriped", "cerviconasal", "sexuale", "pussyfooter", "gadolinic", "duplicature", "codelinquency", "trypanolysis", "pathophobia", "incapsulation", "nonaerating", "feldspar", "diaphonic", "epiglottic", "depopulator", "wisecracker", "gravitational", "kuba", "lactesce", "Toxotes", "periomphalic", "singstress", "fannier", "counterformula", "Acemetae", "repugnatorial", "collimator", "Acinetina", "unpeace", "drum", "tetramorphic", "descendentalism", "cementer", "supraloral", "intercostal", "Nipponize", "negotiator", "vacationless", "synthol", "fissureless", "resoap", "pachycarpous", "reinspiration", "misappropriation", "disdiazo", "unheatable", "streng", "Detroiter", "infandous", "loganiaceous", "desugar", "Matronalia", "myxocystoma", "Gandhiism", "kiddier", "relodge", "counterreprisal", "recentralize", "foliously", "reprinter", "gender", "edaciousness", "chondriomite", "concordant", "stockrider", "pedary", "shikra", "blameworthiness", "vaccina", "Thamnophilinae", "wrongwise", "unsuperannuated", "convalescency", "intransmutable", "dropcloth", "Ceriomyces", "ponderal", "unstentorian", "mem", "deceleration", "ethionic", "untopped", "wetback", "bebar", "undecaying", "shoreside", "energize", "presacral", "undismay", "agricolite", "cowheart", "hemibathybian", "postexilian", "Phacidiaceae", "offing", "redesignation", "skeptically", "physicianless", "bronchopathy", "marabuto", "proprietory", "unobtruded", "funmaker", "plateresque", "preadventure", "beseeching", "cowpath", "pachycephalia", "arthresthesia", "supari", "lengthily", "Nepa", "liberation", "nigrify", "belfry", "entoolitic", "bazoo", "pentachromic", "distinguishable", "slideable", "galvanoscope", "remanage", "cetene", "bocardo", "consummation", "boycottism", "perplexity", "astay", "Gaetuli", "periplastic", "consolidator", "sluggarding", "coracoscapular", "anangioid", "oxygenizer", "Hunanese", "seminary", "periplast", "Corylus", "unoriginativeness", "persecutee", "tweaker", "silliness", "Dabitis", "facetiousness", "thymy", "nonimperial", "mesoblastema", "turbiniform", "churchway", "cooing", "frithbot", "concomitantly", "stalwartize", "clingfish", "hardmouthed", "parallelepipedonal", "coracoacromial", "factuality", "curtilage", "arachnoidean", "semiaridity", "phytobacteriology", "premastery", "hyperpurist", "mobed", "opportunistic", "acclimature", "outdistance", "sophister", "condonement", "oxygenerator", "acetonic", "emanatory", "periphlebitis", "nonsociety", "spectroradiometric", "superaverage", "cleanness", "posteroventral", "unadvised", "unmistakedly", "pimgenet", "auresca", "overimitate", "dipnoan", "chromoxylograph", "triakistetrahedron", "Suessiones", "uncopiable", "oligomenorrhea", "fribbling", "worriable", "flot", "ornithotrophy", "phytoteratology", "setup", "lanneret", "unbraceleted", "gudemother", "Spica", "unconsolatory", "recorruption", "premenstrual", "subretinal", "millennialist", "subjectibility", "rewardproof", "counterflight", "pilomotor", "carpetbaggery", "macrodiagonal", "slim", "indiscernible", "cuckoo", "moted", "controllingly", "gynecopathy", "porrectus", "wanworth", "lutfisk", "semiprivate", "philadelphy", "abdominothoracic", "coxcomb", "dambrod", "Metanemertini", "balminess", "homotypy", "waremaker", "absurdity", "gimcrack", "asquat", "suitable", "perimorphous", "kitchenwards", "pielum", "salloo", "paleontologic", "Olson", "Tellinidae", "ferryman", "peptonoid", "Bopyridae", "fallacy", "ictuate", "aguinaldo", "rhyodacite", "Ligydidae", "galvanometric", "acquisitor", "muscology", "hemikaryon", "ethnobotanic", "postganglionic", "rudimentarily", "replenish", "phyllorhine", "popgunnery", "summar", "quodlibetary", "xanthochromia", "autosymbolically", "preloreal", "extent", "strawberry", "immortalness", "colicwort", "frisca", "electiveness", "heartbroken", "affrightingly", "reconfiscation", "jacchus", "imponderably", "semantics", "beennut", "paleometeorological", "becost", "timberwright", "resuppose", "syncategorematical", "cytolymph", "steinbok", "explantation", "hyperelliptic", "antescript", "blowdown", "antinomical", "caravanserai", "unweariedly", "isonymic", "keratoplasty", "vipery", "parepigastric", "endolymphatic", "Londonese", "necrotomy", "angelship", "Schizogregarinida", "steeplebush", "sparaxis", "connectedness", "tolerance", "impingent", "agglutinin", "reviver", "hieroglyphical", "dialogize", "coestate", "declamatory", "ventilation", "tauromachy", "cotransubstantiate", "pome", "underseas", "triquadrantal", "preconfinemnt", "electroindustrial", "selachostomous", "nongolfer", "mesalike", "hamartiology", "ganglioblast", "unsuccessive", "yallow", "bacchanalianly", "platydactyl", "Bucephala", "ultraurgent", "penalist", "catamenial", "lynnhaven", "unrelevant", "lunkhead", "metropolitan", "hydro", "outsoar", "vernant", "interlanguage", "catarrhal", "Ionicize", "keelless", "myomantic", "booker", "Xanthomonas", "unimpeded", "overfeminize", "speronaro", "diaconia", "overholiness", "liquefacient", "Spartium", "haggly", "albumose", "nonnecessary", "sulcalization", "decapitate", "cellated", "unguirostral", "trichiurid", "loveproof", "amakebe", "screet", "arsenoferratin", "unfrizz", "undiscoverable", "procollectivistic", "tractile", "Winona", "dermostosis", "eliminant", "scomberoid", "tensile", "typesetting", "xylic", "dermatopathology", "cycloplegic", "revocable", "fissate", "afterplay", "screwship", "microerg", "bentonite", "stagecoaching", "beglerbeglic", "overcharitably", "Plotinism", "Veddoid", "disequalize", "cytoproct", "trophophore", "antidote", "allerion", "famous", "convey", "postotic", "rapillo", "cilectomy", "penkeeper", "patronym", "bravely", "ureteropyelitis", "Hildebrandine", "missileproof", "Conularia", "deadening", "Conrad", "pseudochylous", "typologically", "strummer", "luxuriousness", "resublimation", "glossiness", "hydrocauline", "anaglyph", "personifiable", "seniority", "formulator", "datiscaceous", "hydracrylate", "Tyranni", "Crawthumper", "overprove", "masher", "dissonance", "Serpentinian", "malachite", "interestless", "stchi", "ogum", "polyspermic", "archegoniate", "precogitation", "Alkaphrah", "craggily", "delightfulness", "bioplast", "diplocaulescent", "neverland", "interspheral", "chlorhydric", "forsakenly", "scandium", "detubation", "telega", "Valeriana", "centraxonial", "anabolite", "neger", "miscellanea", "whalebacker", "stylidiaceous", "unpropelled", "Kennedya", "Jacksonite", "ghoulish", "Dendrocalamus", "paynimhood", "rappist", "unluffed", "falling", "Lyctus", "uncrown", "warmly", "pneumatism", "Morisonian", "notate", "isoagglutinin", "Pelidnota", "previsit", "contradistinctly", "utter", "porometer", "gie", "germanization", "betwixt", "prenephritic", "underpier", "Eleutheria", "ruthenious", "convertor", "antisepsin", "winterage", "tetramethylammonium", "Rockaway", "Penaea", "prelatehood", "brisket", "unwishful", "Minahassa", "Briareus", "semiaxis", "disintegrant", "peastick", "iatromechanical", "fastus", "thymectomy", "ladyless", "unpreened", "overflutter", "sicker", "apsidally", "thiazine", "guideway", "pausation", "tellinoid", "abrogative", "foraminulate", "omphalos", "Monorhina", "polymyarian", "unhelpful", "newslessness", "oryctognosy", "octoradial", "doxology", "arrhythmy", "gugal", "mesityl", "hexaplaric", "Cabirian", "hordeiform", "eddyroot", "internarial", "deservingness", "jawbation", "orographically", "semiprecious", "seasick", "thermically", "grew", "tamability", "egotistically", "fip", "preabsorbent", "leptochroa", "ethnobotany", "podolite", "egoistic", "semitropical", "cero", "spinelessness", "onshore", "omlah", "tintinnabulist", "machila", "entomotomy", "nubile", "nonscholastic", "burnt", "Alea", "befume", "doctorless", "Napoleonic", "scenting", "apokreos", "cresylene", "paramide", "rattery", "disinterested", "idiopathetic", "negatory", "fervid", "quintato", "untricked", "Metrosideros", "mescaline", "midverse", "Musophagidae", "fictionary", "branchiostegous", "yoker", "residuum", "culmigenous", "fleam", "suffragism", "Anacreon", "sarcodous", "parodistic", "writmaking", "conversationism", "retroposed", "tornillo", "presuspect", "didymous", "Saumur", "spicing", "drawbridge", "cantor", "incumbrancer", "heterospory", "Turkeydom", "anteprandial", "neighbourship", "thatchless", "drepanoid", "lusher", "paling", "ecthlipsis", "heredosyphilitic", "although", "garetta", "temporarily", "Monotropa", "proglottic", "calyptro", "persiflage", "degradable", "paraspecific", "undecorative", "Pholas", "myelon", "resteal", "quadrantly", "scrimped", "airer", "deviless", "caliciform", "Sefekhet", "shastaite", "togate", "macrostructure", "bipyramid", "wey", "didynamy", "knacker", "swage", "supermanism", "epitheton", "overpresumptuous" ] @inline(never) func benchSortStrings(_ words: [String]) { // Notice that we _copy_ the array of words before we sort it. // Pass an explicit '<' predicate to benchmark reabstraction thunks. var tempwords = words tempwords.sort(isOrderedBefore: <) } public func run_SortStrings(_ N: Int) { for _ in 1...5*N { benchSortStrings(stringBenchmarkWords) } } var stringBenchmarkWordsUnicode: [String] = [ "❄️woodshed", "❄️lakism", "❄️gastroperiodynia", "❄️afetal", "❄️ramsch", "❄️Nickieben", "❄️undutifulness", "❄️birdglue", "❄️ungentlemanize", "❄️menacingly", "❄️heterophile", "❄️leoparde", "❄️Casearia", "❄️decorticate", "❄️neognathic", "❄️mentionable", "❄️tetraphenol", "❄️pseudonymal", "❄️dislegitimate", "❄️Discoidea", "❄️intitule", "❄️ionium", "❄️Lotuko", "❄️timbering", "❄️nonliquidating", "❄️oarialgia", "❄️Saccobranchus", "❄️reconnoiter", "❄️criminative", "❄️disintegratory", "❄️executer", "❄️Cylindrosporium", "❄️complimentation", "❄️Ixiama", "❄️Araceae", "❄️silaginoid", "❄️derencephalus", "❄️Lamiidae", "❄️marrowlike", "❄️ninepin", "❄️dynastid", "❄️lampfly", "❄️feint", "❄️trihemimer", "❄️semibarbarous", "❄️heresy", "❄️tritanope", "❄️indifferentist", "❄️confound", "❄️hyperbolaeon", "❄️planirostral", "❄️philosophunculist", "❄️existence", "❄️fretless", "❄️Leptandra", "❄️Amiranha", "❄️handgravure", "❄️gnash", "❄️unbelievability", "❄️orthotropic", "❄️Susumu", "❄️teleutospore", "❄️sleazy", "❄️shapeliness", "❄️hepatotomy", "❄️exclusivism", "❄️stifler", "❄️cunning", "❄️isocyanuric", "❄️pseudepigraphy", "❄️carpetbagger", "❄️respectiveness", "❄️Jussi", "❄️vasotomy", "❄️proctotomy", "❄️ovatotriangular", "❄️aesthetic", "❄️schizogamy", "❄️disengagement", "❄️foray", "❄️haplocaulescent", "❄️noncoherent", "❄️astrocyte", "❄️unreverberated", "❄️presenile", "❄️lanson", "❄️enkraal", "❄️contemplative", "❄️Syun", "❄️sartage", "❄️unforgot", "❄️wyde", "❄️homeotransplant", "❄️implicational", "❄️forerunnership", "❄️calcaneum", "❄️stomatodeum", "❄️pharmacopedia", "❄️preconcessive", "❄️trypanosomatic", "❄️intracollegiate", "❄️rampacious", "❄️secundipara", "❄️isomeric", "❄️treehair", "❄️pulmonal", "❄️uvate", "❄️dugway", "❄️glucofrangulin", "❄️unglory", "❄️Amandus", "❄️icterogenetic", "❄️quadrireme", "❄️Lagostomus", "❄️brakeroot", "❄️anthracemia", "❄️fluted", "❄️protoelastose", "❄️thro", "❄️pined", "❄️Saxicolinae", "❄️holidaymaking", "❄️strigil", "❄️uncurbed", "❄️starling", "❄️redeemeress", "❄️Liliaceae", "❄️imparsonee", "❄️obtusish", "❄️brushed", "❄️mesally", "❄️probosciformed", "❄️Bourbonesque", "❄️histological", "❄️caroba", "❄️digestion", "❄️Vindemiatrix", "❄️triactinal", "❄️tattling", "❄️arthrobacterium", "❄️unended", "❄️suspectfulness", "❄️movelessness", "❄️chartist", "❄️Corynebacterium", "❄️tercer", "❄️oversaturation", "❄️Congoleum", "❄️antiskeptical", "❄️sacral", "❄️equiradiate", "❄️whiskerage", "❄️panidiomorphic", "❄️unplanned", "❄️anilopyrine", "❄️Queres", "❄️tartronyl", "❄️Ing", "❄️notehead", "❄️finestiller", "❄️weekender", "❄️kittenhood", "❄️competitrix", "❄️premillenarian", "❄️convergescence", "❄️microcoleoptera", "❄️slirt", "❄️asteatosis", "❄️Gruidae", "❄️metastome", "❄️ambuscader", "❄️untugged", "❄️uneducated", "❄️redistill", "❄️rushlight", "❄️freakish", "❄️dosology", "❄️papyrine", "❄️iconologist", "❄️Bidpai", "❄️prophethood", "❄️pneumotropic", "❄️chloroformize", "❄️intemperance", "❄️spongiform", "❄️superindignant", "❄️divider", "❄️starlit", "❄️merchantish", "❄️indexless", "❄️unidentifiably", "❄️coumarone", "❄️nomism", "❄️diaphanous", "❄️salve", "❄️option", "❄️anallantoic", "❄️paint", "❄️thiofurfuran", "❄️baddeleyite", "❄️Donne", "❄️heterogenicity", "❄️decess", "❄️eschynite", "❄️mamma", "❄️unmonarchical", "❄️Archiplata", "❄️widdifow", "❄️apathic", "❄️overline", "❄️chaetophoraceous", "❄️creaky", "❄️trichosporange", "❄️uninterlined", "❄️cometwise", "❄️hermeneut", "❄️unbedraggled", "❄️tagged", "❄️Sminthurus", "❄️somniloquacious", "❄️aphasiac", "❄️Inoperculata", "❄️photoactivity", "❄️mobship", "❄️unblightedly", "❄️lievrite", "❄️Khoja", "❄️Falerian", "❄️milfoil", "❄️protectingly", "❄️householder", "❄️cathedra", "❄️calmingly", "❄️tordrillite", "❄️rearhorse", "❄️Leonard", "❄️maracock", "❄️youngish", "❄️kammererite", "❄️metanephric", "❄️Sageretia", "❄️diplococcoid", "❄️accelerative", "❄️choreal", "❄️metalogical", "❄️recombination", "❄️unimprison", "❄️invocation", "❄️syndetic", "❄️toadback", "❄️vaned", "❄️cupholder", "❄️metropolitanship", "❄️paramandelic", "❄️dermolysis", "❄️Sheriyat", "❄️rhabdus", "❄️seducee", "❄️encrinoid", "❄️unsuppliable", "❄️cololite", "❄️timesaver", "❄️preambulate", "❄️sampling", "❄️roaster", "❄️springald", "❄️densher", "❄️protraditional", "❄️naturalesque", "❄️Hydrodamalis", "❄️cytogenic", "❄️shortly", "❄️cryptogrammatical", "❄️squat", "❄️genual", "❄️backspier", "❄️solubleness", "❄️macroanalytical", "❄️overcovetousness", "❄️Natalie", "❄️cuprobismutite", "❄️phratriac", "❄️Montanize", "❄️hymnologist", "❄️karyomiton", "❄️podger", "❄️unofficiousness", "❄️antisplasher", "❄️supraclavicular", "❄️calidity", "❄️disembellish", "❄️antepredicament", "❄️recurvirostral", "❄️pulmonifer", "❄️coccidial", "❄️botonee", "❄️protoglobulose", "❄️isonym", "❄️myeloid", "❄️premiership", "❄️unmonopolize", "❄️unsesquipedalian", "❄️unfelicitously", "❄️theftbote", "❄️undauntable", "❄️lob", "❄️praenomen", "❄️underriver", "❄️gorfly", "❄️pluckage", "❄️radiovision", "❄️tyrantship", "❄️fraught", "❄️doppelkummel", "❄️rowan", "❄️allosyndetic", "❄️kinesiology", "❄️psychopath", "❄️arrent", "❄️amusively", "❄️preincorporation", "❄️Montargis", "❄️pentacron", "❄️neomedievalism", "❄️sima", "❄️lichenicolous", "❄️Ecclesiastes", "❄️woofed", "❄️cardinalist", "❄️sandaracin", "❄️gymnasial", "❄️lithoglyptics", "❄️centimeter", "❄️quadrupedous", "❄️phraseology", "❄️tumuli", "❄️ankylotomy", "❄️myrtol", "❄️cohibitive", "❄️lepospondylous", "❄️silvendy", "❄️inequipotential", "❄️entangle", "❄️raveling", "❄️Zeugobranchiata", "❄️devastating", "❄️grainage", "❄️amphisbaenian", "❄️blady", "❄️cirrose", "❄️proclericalism", "❄️governmentalist", "❄️carcinomorphic", "❄️nurtureship", "❄️clancular", "❄️unsteamed", "❄️discernibly", "❄️pleurogenic", "❄️impalpability", "❄️Azotobacterieae", "❄️sarcoplasmic", "❄️alternant", "❄️fitly", "❄️acrorrheuma", "❄️shrapnel", "❄️pastorize", "❄️gulflike", "❄️foreglow", "❄️unrelated", "❄️cirriped", "❄️cerviconasal", "❄️sexuale", "❄️pussyfooter", "❄️gadolinic", "❄️duplicature", "❄️codelinquency", "❄️trypanolysis", "❄️pathophobia", "❄️incapsulation", "❄️nonaerating", "❄️feldspar", "❄️diaphonic", "❄️epiglottic", "❄️depopulator", "❄️wisecracker", "❄️gravitational", "❄️kuba", "❄️lactesce", "❄️Toxotes", "❄️periomphalic", "❄️singstress", "❄️fannier", "❄️counterformula", "❄️Acemetae", "❄️repugnatorial", "❄️collimator", "❄️Acinetina", "❄️unpeace", "❄️drum", "❄️tetramorphic", "❄️descendentalism", "❄️cementer", "❄️supraloral", "❄️intercostal", "❄️Nipponize", "❄️negotiator", "❄️vacationless", "❄️synthol", "❄️fissureless", "❄️resoap", "❄️pachycarpous", "❄️reinspiration", "❄️misappropriation", "❄️disdiazo", "❄️unheatable", "❄️streng", "❄️Detroiter", "❄️infandous", "❄️loganiaceous", "❄️desugar", "❄️Matronalia", "❄️myxocystoma", "❄️Gandhiism", "❄️kiddier", "❄️relodge", "❄️counterreprisal", "❄️recentralize", "❄️foliously", "❄️reprinter", "❄️gender", "❄️edaciousness", "❄️chondriomite", "❄️concordant", "❄️stockrider", "❄️pedary", "❄️shikra", "❄️blameworthiness", "❄️vaccina", "❄️Thamnophilinae", "❄️wrongwise", "❄️unsuperannuated", "❄️convalescency", "❄️intransmutable", "❄️dropcloth", "❄️Ceriomyces", "❄️ponderal", "❄️unstentorian", "❄️mem", "❄️deceleration", "❄️ethionic", "❄️untopped", "❄️wetback", "❄️bebar", "❄️undecaying", "❄️shoreside", "❄️energize", "❄️presacral", "❄️undismay", "❄️agricolite", "❄️cowheart", "❄️hemibathybian", "❄️postexilian", "❄️Phacidiaceae", "❄️offing", "❄️redesignation", "❄️skeptically", "❄️physicianless", "❄️bronchopathy", "❄️marabuto", "❄️proprietory", "❄️unobtruded", "❄️funmaker", "❄️plateresque", "❄️preadventure", "❄️beseeching", "❄️cowpath", "❄️pachycephalia", "❄️arthresthesia", "❄️supari", "❄️lengthily", "❄️Nepa", "❄️liberation", "❄️nigrify", "❄️belfry", "❄️entoolitic", "❄️bazoo", "❄️pentachromic", "❄️distinguishable", "❄️slideable", "❄️galvanoscope", "❄️remanage", "❄️cetene", "❄️bocardo", "❄️consummation", "❄️boycottism", "❄️perplexity", "❄️astay", "❄️Gaetuli", "❄️periplastic", "❄️consolidator", "❄️sluggarding", "❄️coracoscapular", "❄️anangioid", "❄️oxygenizer", "❄️Hunanese", "❄️seminary", "❄️periplast", "❄️Corylus", "❄️unoriginativeness", "❄️persecutee", "❄️tweaker", "❄️silliness", "❄️Dabitis", "❄️facetiousness", "❄️thymy", "❄️nonimperial", "❄️mesoblastema", "❄️turbiniform", "❄️churchway", "❄️cooing", "❄️frithbot", "❄️concomitantly", "❄️stalwartize", "❄️clingfish", "❄️hardmouthed", "❄️parallelepipedonal", "❄️coracoacromial", "❄️factuality", "❄️curtilage", "❄️arachnoidean", "❄️semiaridity", "❄️phytobacteriology", "❄️premastery", "❄️hyperpurist", "❄️mobed", "❄️opportunistic", "❄️acclimature", "❄️outdistance", "❄️sophister", "❄️condonement", "❄️oxygenerator", "❄️acetonic", "❄️emanatory", "❄️periphlebitis", "❄️nonsociety", "❄️spectroradiometric", "❄️superaverage", "❄️cleanness", "❄️posteroventral", "❄️unadvised", "❄️unmistakedly", "❄️pimgenet", "❄️auresca", "❄️overimitate", "❄️dipnoan", "❄️chromoxylograph", "❄️triakistetrahedron", "❄️Suessiones", "❄️uncopiable", "❄️oligomenorrhea", "❄️fribbling", "❄️worriable", "❄️flot", "❄️ornithotrophy", "❄️phytoteratology", "❄️setup", "❄️lanneret", "❄️unbraceleted", "❄️gudemother", "❄️Spica", "❄️unconsolatory", "❄️recorruption", "❄️premenstrual", "❄️subretinal", "❄️millennialist", "❄️subjectibility", "❄️rewardproof", "❄️counterflight", "❄️pilomotor", "❄️carpetbaggery", "❄️macrodiagonal", "❄️slim", "❄️indiscernible", "❄️cuckoo", "❄️moted", "❄️controllingly", "❄️gynecopathy", "❄️porrectus", "❄️wanworth", "❄️lutfisk", "❄️semiprivate", "❄️philadelphy", "❄️abdominothoracic", "❄️coxcomb", "❄️dambrod", "❄️Metanemertini", "❄️balminess", "❄️homotypy", "❄️waremaker", "❄️absurdity", "❄️gimcrack", "❄️asquat", "❄️suitable", "❄️perimorphous", "❄️kitchenwards", "❄️pielum", "❄️salloo", "❄️paleontologic", "❄️Olson", "❄️Tellinidae", "❄️ferryman", "❄️peptonoid", "❄️Bopyridae", "❄️fallacy", "❄️ictuate", "❄️aguinaldo", "❄️rhyodacite", "❄️Ligydidae", "❄️galvanometric", "❄️acquisitor", "❄️muscology", "❄️hemikaryon", "❄️ethnobotanic", "❄️postganglionic", "❄️rudimentarily", "❄️replenish", "❄️phyllorhine", "❄️popgunnery", "❄️summar", "❄️quodlibetary", "❄️xanthochromia", "❄️autosymbolically", "❄️preloreal", "❄️extent", "❄️strawberry", "❄️immortalness", "❄️colicwort", "❄️frisca", "❄️electiveness", "❄️heartbroken", "❄️affrightingly", "❄️reconfiscation", "❄️jacchus", "❄️imponderably", "❄️semantics", "❄️beennut", "❄️paleometeorological", "❄️becost", "❄️timberwright", "❄️resuppose", "❄️syncategorematical", "❄️cytolymph", "❄️steinbok", "❄️explantation", "❄️hyperelliptic", "❄️antescript", "❄️blowdown", "❄️antinomical", "❄️caravanserai", "❄️unweariedly", "❄️isonymic", "❄️keratoplasty", "❄️vipery", "❄️parepigastric", "❄️endolymphatic", "❄️Londonese", "❄️necrotomy", "❄️angelship", "❄️Schizogregarinida", "❄️steeplebush", "❄️sparaxis", "❄️connectedness", "❄️tolerance", "❄️impingent", "❄️agglutinin", "❄️reviver", "❄️hieroglyphical", "❄️dialogize", "❄️coestate", "❄️declamatory", "❄️ventilation", "❄️tauromachy", "❄️cotransubstantiate", "❄️pome", "❄️underseas", "❄️triquadrantal", "❄️preconfinemnt", "❄️electroindustrial", "❄️selachostomous", "❄️nongolfer", "❄️mesalike", "❄️hamartiology", "❄️ganglioblast", "❄️unsuccessive", "❄️yallow", "❄️bacchanalianly", "❄️platydactyl", "❄️Bucephala", "❄️ultraurgent", "❄️penalist", "❄️catamenial", "❄️lynnhaven", "❄️unrelevant", "❄️lunkhead", "❄️metropolitan", "❄️hydro", "❄️outsoar", "❄️vernant", "❄️interlanguage", "❄️catarrhal", "❄️Ionicize", "❄️keelless", "❄️myomantic", "❄️booker", "❄️Xanthomonas", "❄️unimpeded", "❄️overfeminize", "❄️speronaro", "❄️diaconia", "❄️overholiness", "❄️liquefacient", "❄️Spartium", "❄️haggly", "❄️albumose", "❄️nonnecessary", "❄️sulcalization", "❄️decapitate", "❄️cellated", "❄️unguirostral", "❄️trichiurid", "❄️loveproof", "❄️amakebe", "❄️screet", "❄️arsenoferratin", "❄️unfrizz", "❄️undiscoverable", "❄️procollectivistic", "❄️tractile", "❄️Winona", "❄️dermostosis", "❄️eliminant", "❄️scomberoid", "❄️tensile", "❄️typesetting", "❄️xylic", "❄️dermatopathology", "❄️cycloplegic", "❄️revocable", "❄️fissate", "❄️afterplay", "❄️screwship", "❄️microerg", "❄️bentonite", "❄️stagecoaching", "❄️beglerbeglic", "❄️overcharitably", "❄️Plotinism", "❄️Veddoid", "❄️disequalize", "❄️cytoproct", "❄️trophophore", "❄️antidote", "❄️allerion", "❄️famous", "❄️convey", "❄️postotic", "❄️rapillo", "❄️cilectomy", "❄️penkeeper", "❄️patronym", "❄️bravely", "❄️ureteropyelitis", "❄️Hildebrandine", "❄️missileproof", "❄️Conularia", "❄️deadening", "❄️Conrad", "❄️pseudochylous", "❄️typologically", "❄️strummer", "❄️luxuriousness", "❄️resublimation", "❄️glossiness", "❄️hydrocauline", "❄️anaglyph", "❄️personifiable", "❄️seniority", "❄️formulator", "❄️datiscaceous", "❄️hydracrylate", "❄️Tyranni", "❄️Crawthumper", "❄️overprove", "❄️masher", "❄️dissonance", "❄️Serpentinian", "❄️malachite", "❄️interestless", "❄️stchi", "❄️ogum", "❄️polyspermic", "❄️archegoniate", "❄️precogitation", "❄️Alkaphrah", "❄️craggily", "❄️delightfulness", "❄️bioplast", "❄️diplocaulescent", "❄️neverland", "❄️interspheral", "❄️chlorhydric", "❄️forsakenly", "❄️scandium", "❄️detubation", "❄️telega", "❄️Valeriana", "❄️centraxonial", "❄️anabolite", "❄️neger", "❄️miscellanea", "❄️whalebacker", "❄️stylidiaceous", "❄️unpropelled", "❄️Kennedya", "❄️Jacksonite", "❄️ghoulish", "❄️Dendrocalamus", "❄️paynimhood", "❄️rappist", "❄️unluffed", "❄️falling", "❄️Lyctus", "❄️uncrown", "❄️warmly", "❄️pneumatism", "❄️Morisonian", "❄️notate", "❄️isoagglutinin", "❄️Pelidnota", "❄️previsit", "❄️contradistinctly", "❄️utter", "❄️porometer", "❄️gie", "❄️germanization", "❄️betwixt", "❄️prenephritic", "❄️underpier", "❄️Eleutheria", "❄️ruthenious", "❄️convertor", "❄️antisepsin", "❄️winterage", "❄️tetramethylammonium", "❄️Rockaway", "❄️Penaea", "❄️prelatehood", "❄️brisket", "❄️unwishful", "❄️Minahassa", "❄️Briareus", "❄️semiaxis", "❄️disintegrant", "❄️peastick", "❄️iatromechanical", "❄️fastus", "❄️thymectomy", "❄️ladyless", "❄️unpreened", "❄️overflutter", "❄️sicker", "❄️apsidally", "❄️thiazine", "❄️guideway", "❄️pausation", "❄️tellinoid", "❄️abrogative", "❄️foraminulate", "❄️omphalos", "❄️Monorhina", "❄️polymyarian", "❄️unhelpful", "❄️newslessness", "❄️oryctognosy", "❄️octoradial", "❄️doxology", "❄️arrhythmy", "❄️gugal", "❄️mesityl", "❄️hexaplaric", "❄️Cabirian", "❄️hordeiform", "❄️eddyroot", "❄️internarial", "❄️deservingness", "❄️jawbation", "❄️orographically", "❄️semiprecious", "❄️seasick", "❄️thermically", "❄️grew", "❄️tamability", "❄️egotistically", "❄️fip", "❄️preabsorbent", "❄️leptochroa", "❄️ethnobotany", "❄️podolite", "❄️egoistic", "❄️semitropical", "❄️cero", "❄️spinelessness", "❄️onshore", "❄️omlah", "❄️tintinnabulist", "❄️machila", "❄️entomotomy", "❄️nubile", "❄️nonscholastic", "❄️burnt", "❄️Alea", "❄️befume", "❄️doctorless", "❄️Napoleonic", "❄️scenting", "❄️apokreos", "❄️cresylene", "❄️paramide", "❄️rattery", "❄️disinterested", "❄️idiopathetic", "❄️negatory", "❄️fervid", "❄️quintato", "❄️untricked", "❄️Metrosideros", "❄️mescaline", "❄️midverse", "❄️Musophagidae", "❄️fictionary", "❄️branchiostegous", "❄️yoker", "❄️residuum", "❄️culmigenous", "❄️fleam", "❄️suffragism", "❄️Anacreon", "❄️sarcodous", "❄️parodistic", "❄️writmaking", "❄️conversationism", "❄️retroposed", "❄️tornillo", "❄️presuspect", "❄️didymous", "❄️Saumur", "❄️spicing", "❄️drawbridge", "❄️cantor", "❄️incumbrancer", "❄️heterospory", "❄️Turkeydom", "❄️anteprandial", "❄️neighbourship", "❄️thatchless", "❄️drepanoid", "❄️lusher", "❄️paling", "❄️ecthlipsis", "❄️heredosyphilitic", "❄️although", "❄️garetta", "❄️temporarily", "❄️Monotropa", "❄️proglottic", "❄️calyptro", "❄️persiflage", "❄️degradable", "❄️paraspecific", "❄️undecorative", "❄️Pholas", "❄️myelon", "❄️resteal", "❄️quadrantly", "❄️scrimped", "❄️airer", "❄️deviless", "❄️caliciform", "❄️Sefekhet", "❄️shastaite", "❄️togate", "❄️macrostructure", "❄️bipyramid", "❄️wey", "❄️didynamy", "❄️knacker", "❄️swage", "❄️supermanism", "❄️epitheton", "❄️overpresumptuous" ] public func run_SortStringsUnicode(_ N: Int) { for _ in 1...5*N { benchSortStrings(stringBenchmarkWordsUnicode) } }
cfa15d494cb5b84894f3ded8b5b91526
16.043137
80
0.584906
false
false
false
false
lyimin/EyepetizerApp
refs/heads/master
EyepetizerApp/EyepetizerApp/Views/VideoDetailView/EYEVideoDetailView.swift
mit
1
// // EYEVideoDetailView.swift // EyepetizerApp // // Created by 梁亦明 on 16/3/23. // Copyright © 2016年 xiaoming. All rights reserved. // import UIKit protocol EYEVideoDetailViewDelegate { // 点击播放按钮 func playImageViewDidClick() // 点击返回按钮 func backBtnDidClick() } class EYEVideoDetailView: UIView { //MARK: --------------------------- Life Cycle -------------------------- override init(frame: CGRect) { super.init(frame: frame) self.clipsToBounds = true self.addSubview(albumImageView) self.addSubview(blurImageView) self.addSubview(blurView) self.addSubview(backBtn) self.addSubview(playImageView) self.addSubview(videoTitleLabel) self.addSubview(lineView) self.addSubview(classifyLabel) self.addSubview(describeLabel) self.addSubview(bottomToolView) // 添加底部item let itemSize: CGFloat = 80 for i in 0..<bottomImgArray.count { let btn = BottomItemBtn(frame: CGRect(x: UIConstant.UI_MARGIN_15+CGFloat(i)*itemSize, y: 0, width: itemSize, height: bottomToolView.height), title: "0", image: bottomImgArray[i]!) itemArray.append(btn) bottomToolView.addSubview(btn) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } var model : ItemModel! { didSet { // self.albumImageView.yy_setImageWithURL(NSURL(string: model.feed), placeholder: UIImage.colorImage(UIColor.lightGrayColor(), size: albumImageView.size)) // self.albumImageView.yy_setImageWithURL(NSURL(string: model.feed), options: .ProgressiveBlur) self.blurImageView.yy_setImageWithURL(NSURL(string:model.feed), placeholder: UIImage(named: "7e42a62065ef37cfa233009fb364fd1e_0_0")) videoTitleLabel.animationString = model.title self.classifyLabel.text = model.subTitle // 显示底部数据 self.itemArray.first?.setTitle("\(model.collectionCount)", forState: .Normal) self.itemArray[1].setTitle("\(model.shareCount)", forState: .Normal) self.itemArray[2].setTitle("\(model.replyCount)", forState: .Normal) self.itemArray.last?.setTitle("缓存", forState: .Normal) // 计算宽度 self.describeLabel.text = model.description let size = self.describeLabel.boundingRectWithSize(describeLabel.size) self.describeLabel.frame = CGRectMake(describeLabel.x, describeLabel.y, size.width, size.height) } } //MARK: --------------------------- Event response -------------------------- /** 点击播放按钮 */ @objc private func playImageViewDidClick() { delegate.playImageViewDidClick() } /** 点击返回按钮 */ @objc private func backBtnDidClick() { delegate.backBtnDidClick() } //MARK: --------------------------- Getter or Setter -------------------------- // 代理 var delegate: EYEVideoDetailViewDelegate! // 图片 lazy var albumImageView : UIImageView = { // 图片大小 1242 x 777 // 6 621*388.5 // 5 621*388.5 let photoW : CGFloat = 1222.0 let photoH : CGFloat = 777.0 let albumImageViewH = self.height*0.6 let albumImageViewW = photoW*albumImageViewH/photoH let albumImageViewX = (albumImageViewW-self.width)*0.5 // let imageViewH = self.width*photoH / UIConstant.IPHONE6_WIDTH var albumImageView = UIImageView(frame: CGRect(x: -albumImageViewX, y: 0, width: albumImageViewW, height: albumImageViewH)) albumImageView.clipsToBounds = true albumImageView.contentMode = .ScaleAspectFill albumImageView.userInteractionEnabled = true return albumImageView }() // 模糊背景 lazy var blurImageView : UIImageView = { var blurImageView = UIImageView(frame: CGRect(x: 0, y: self.albumImageView.height, width: self.width, height: self.height-self.albumImageView.height)) return blurImageView }() lazy var blurView : UIVisualEffectView = { let blurEffect : UIBlurEffect = UIBlurEffect(style: .Light) var blurView = UIVisualEffectView(effect: blurEffect) blurView.frame = self.blurImageView.frame return blurView }() // 返回按钮 lazy var backBtn : UIButton = { var backBtn = UIButton(frame: CGRect(x: UIConstant.UI_MARGIN_10, y: UIConstant.UI_MARGIN_20, width: 40, height: 40)) backBtn.setImage(UIImage(named: "play_back_full"), forState: .Normal) backBtn.addTarget(self, action: #selector(EYEVideoDetailView.backBtnDidClick), forControlEvents: .TouchUpInside) return backBtn }() // 播放按钮 lazy var playImageView : UIImageView = { var playImageView = UIImageView(image: UIImage(named: "ic_action_play")) playImageView.frame = CGRect(x: 0, y: 0, width: 60, height: 60) playImageView.center = self.albumImageView.center playImageView.contentMode = .ScaleAspectFit playImageView.viewAddTarget(self, action: #selector(EYEVideoDetailView.playImageViewDidClick)) return playImageView }() // 标题 lazy var videoTitleLabel : EYEShapeView = { let rect = CGRect(x: UIConstant.UI_MARGIN_10, y: CGRectGetMaxY(self.albumImageView.frame)+UIConstant.UI_MARGIN_10, width: self.width-2*UIConstant.UI_MARGIN_10, height: 20) let font = UIFont.customFont_FZLTZCHJW(fontSize: UIConstant.UI_FONT_16) var videoTitleLabel = EYEShapeView(frame: rect) videoTitleLabel.font = font videoTitleLabel.fontSize = UIConstant.UI_FONT_16 return videoTitleLabel }() // 分割线 private lazy var lineView : UIView = { var lineView = UIView(frame: CGRect(x: UIConstant.UI_MARGIN_10, y: CGRectGetMaxY(self.videoTitleLabel.frame)+UIConstant.UI_MARGIN_10, width: self.width-2*UIConstant.UI_MARGIN_10, height: 0.5)) lineView.backgroundColor = UIColor.whiteColor() return lineView }() // 分类/时间 lazy var classifyLabel : UILabel = { var classifyLabel = UILabel(frame: CGRect(x: UIConstant.UI_MARGIN_10, y: CGRectGetMaxY(self.lineView.frame)+UIConstant.UI_MARGIN_10, width: self.width-2*UIConstant.UI_MARGIN_10, height: 20)) classifyLabel.textColor = UIColor.whiteColor() classifyLabel.font = UIFont.customFont_FZLTXIHJW(fontSize: UIConstant.UI_FONT_13) return classifyLabel }() // 描述 lazy var describeLabel : UILabel = { var describeLabel = UILabel(frame: CGRect(x: UIConstant.UI_MARGIN_10, y: CGRectGetMaxY(self.classifyLabel.frame)+UIConstant.UI_MARGIN_10, width: self.width-2*UIConstant.UI_MARGIN_10, height: 200)) describeLabel.numberOfLines = 0 describeLabel.textColor = UIColor.whiteColor() describeLabel.font = UIFont.customFont_FZLTXIHJW(fontSize: UIConstant.UI_FONT_13) return describeLabel }() // 底部 喜欢 分享 评论 缓存 lazy var bottomToolView : UIView = { var bottomToolView = UIView(frame: CGRect(x: 0, y: self.height-50, width: self.width, height: 30)) bottomToolView.backgroundColor = UIColor.clearColor() return bottomToolView }() private var itemArray: [BottomItemBtn] = [BottomItemBtn]() // 底部图片数组 private var bottomImgArray = [UIImage(named: "ic_action_favorites_without_padding"), UIImage(named: "ic_action_share_without_padding"), UIImage(named: "ic_action_reply_nopadding"), UIImage(named: "action_download_cut")] /// 底部item private class BottomItemBtn : UIButton { // 标题 private var title: String! // 图片 private var image: UIImage! override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor.clearColor() self.titleLabel?.font = UIFont.customFont_FZLTXIHJW() self.setTitleColor(UIColor.whiteColor(), forState: .Normal) } convenience init(frame: CGRect, title: String, image: UIImage) { self.init(frame: frame) self.title = title self.image = image self.setImage(image, forState: .Normal) self.setTitle(title, forState: .Normal) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } /** 文字的frame */ private override func titleRectForContentRect(contentRect: CGRect) -> CGRect { return CGRect(x: self.height-8, y: 0, width: self.width-self.height+8, height: self.height) } /** 图片的frame */ private override func imageRectForContentRect(contentRect: CGRect) -> CGRect { return CGRect(x: 0, y: 8, width: self.height-16, height: self.height-16) } } }
625a0e3fe855545fb9307e09a0e2adad
39.728507
223
0.63093
false
false
false
false
Lickability/PinpointKit
refs/heads/master
Examples/Pippin/Pods/PinpointKit/PinpointKit/PinpointKit/Sources/Core/BasicLogViewController.swift
mit
2
// // BasicLogViewController.swift // PinpointKit // // Created by Brian Capps on 2/5/16. // Copyright © 2016 Lickability. All rights reserved. // import UIKit /// The default view controller for the text log. open class BasicLogViewController: UIViewController, LogViewer { // MARK: - InterfaceCustomizable open var interfaceCustomization: InterfaceCustomization? { didSet { title = interfaceCustomization?.interfaceText.logCollectorTitle textView.font = interfaceCustomization?.appearance.logFont } } // MARK: - BasicLogViewController private let textView: UITextView = { let textView = UITextView() textView.translatesAutoresizingMaskIntoConstraints = false textView.isEditable = false textView.dataDetectorTypes = UIDataDetectorTypes() return textView }() // MARK: - UIViewController override open func viewDidLoad() { super.viewDidLoad() func setUpTextView() { view.addSubview(textView) textView.centerXAnchor.constraint(equalTo: view.centerXAnchor, constant: 0).isActive = true textView.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: 0).isActive = true textView.widthAnchor.constraint(equalTo: view.widthAnchor, constant: 0).isActive = true textView.heightAnchor.constraint(equalTo: view.heightAnchor, constant: 0).isActive = true } setUpTextView() } open override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) textView.scrollRangeToVisible(NSRange(location: (textView.text as NSString).length, length: 0)) } // MARK: - LogViewer open func viewLog(in collector: LogCollector, from viewController: UIViewController) { let logText = collector.retrieveLogs().joined(separator: "\n") textView.text = logText viewController.show(self, sender: viewController) } }
3fed6ea5d7e61b29dc439c94cc7be4bf
30.923077
103
0.655904
false
false
false
false
ello/ello-ios
refs/heads/master
Sources/Networking/UserService.swift
mit
1
//// /// UserService.swift // import Moya import SwiftyJSON import PromiseKit struct UserService { func join( email: String, username: String, password: String, invitationCode: String? = nil ) -> Promise<User> { return ElloProvider.shared.request( .join( email: email, username: username, password: password, invitationCode: invitationCode ) ) .then { data, _ -> Promise<User> in guard let user = data as? User else { throw NSError.uncastableModel() } let promise: Promise<User> = CredentialsAuthService().authenticate( email: email, password: password ) .map { _ -> User in return user } return promise } } func requestPasswordReset(email: String) -> Promise<()> { return ElloProvider.shared.request(.requestPasswordReset(email: email)) .asVoid() } func resetPassword(password: String, authToken: String) -> Promise<User> { return ElloProvider.shared.request(.resetPassword(password: password, authToken: authToken)) .map { user, _ -> User in guard let user = user as? User else { throw NSError.uncastableModel() } return user } } func loadUser(_ endpoint: ElloAPI) -> Promise<User> { return ElloProvider.shared.request(endpoint) .map { data, responseConfig -> User in guard let user = data as? User else { throw NSError.uncastableModel() } Preloader().preloadImages([user]) return user } } func loadUserPosts(_ userId: String) -> Promise<([Post], ResponseConfig)> { return ElloProvider.shared.request(.userStreamPosts(userId: userId)) .map { data, responseConfig -> ([Post], ResponseConfig) in let posts: [Post]? if data as? String == "" { posts = [] } else if let foundPosts = data as? [Post] { posts = foundPosts } else { posts = nil } if let posts = posts { Preloader().preloadImages(posts) return (posts, responseConfig) } else { throw NSError.uncastableModel() } } } }
d701576b235c2cece8ea6d7e51b09bf7
29.318681
100
0.470823
false
true
false
false
zhenghao58/On-the-road
refs/heads/master
OnTheRoadB/LocationPickerViewController.swift
mit
1
// // ViewController.swift // OnTheRoadB // // Created by Cunqi.X on 14/10/24. // Copyright (c) 2014年 CS9033. All rights reserved. // import UIKit import MapKit class LocationPickerViewController: UITableViewController, CLLocationManagerDelegate { var locationDelegate: LocationInformationDelegate! var locationManager:CLLocationManager! var sections = ["Restaurants","Parks","Museums","Hotels","Attractions"] var locationCategories = [ "Restaurants":[], "Parks":[], "Museums":[], "Hotels":[], "Attractions":[] ] override func viewDidLoad() { super.viewDidLoad() if CLLocationManager.locationServicesEnabled() == false { println("Can't get location") } self.locationManager = CLLocationManager(); self.locationManager.requestWhenInUseAuthorization() self.locationManager.delegate = self self.locationManager.desiredAccuracy = kCLLocationAccuracyBest self.locationManager.startUpdatingLocation() } func locationManager(manager:CLLocationManager, didUpdateLocations locations:[AnyObject]) { let location = locations.last as CLLocation let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude) let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01)) var requests = [String:MKLocalSearchRequest]() var searches = [String:MKLocalSearch]() for (category, closestPlaces)in self.locationCategories{ requests[category] = MKLocalSearchRequest() requests[category]!.region = region requests[category]!.naturalLanguageQuery = category searches[category] = MKLocalSearch(request: requests[category]) searches[category]!.startWithCompletionHandler { (response, error) in self.locationCategories[category] = response.mapItems as [MKMapItem] } } self.tableView.reloadData() } override func numberOfSectionsInTableView(tableView:UITableView) -> Int { return self.locationCategories.count } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { var category = self.locationCategories[self.sections[section]] as [MKMapItem] return category.count } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return self.sections[section] } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let row = indexPath.row let cell = self.tableView.dequeueReusableCellWithIdentifier("location", forIndexPath: indexPath) as UITableViewCell let category = self.sections[indexPath.section] let rows = self.locationCategories[category] as [MKMapItem] cell.textLabel!.text = rows[row].name let partOfAddress = rows[row].placemark.addressDictionary["FormattedAddressLines"] as? NSArray cell.detailTextLabel!.text = mergeToAddress(partOfAddress!) return cell } private func mergeToAddress(partOfAddress: NSArray)-> String { let result = NSMutableString() for element in partOfAddress { result.appendString(element as String) } return result.description } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let row = indexPath.row let category = self.sections[indexPath.section] let rows = self.locationCategories[category] as [MKMapItem] let placemark = rows[row].placemark as MKPlacemark var location = [String: AnyObject]() location["name"] = placemark.name location["address"] = placemark.addressDictionary["FormattedAddressLines"] location["location"] = placemark.location locationDelegate.setCurrentLocation(location) self.navigationController?.popViewControllerAnimated(true) } }
86e8b79b6fdd50d99e5c87fa25b0f354
34.353448
125
0.701536
false
false
false
false
suzuki-0000/SKPhotoBrowser
refs/heads/master
SKPhotoBrowser/SKPaginationView.swift
mit
1
// // SKPaginationView.swift // SKPhotoBrowser // // Created by keishi_suzuki on 2017/12/20. // Copyright © 2017年 suzuki_keishi. All rights reserved. // import UIKit class SKPaginationView: UIView { var counterLabel: UILabel? var prevButton: UIButton? var nextButton: UIButton? private var margin: CGFloat = 100 private var extraMargin: CGFloat = SKMesurement.isPhoneX ? 40 : 0 fileprivate weak var browser: SKPhotoBrowser? required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(frame: CGRect) { super.init(frame: frame) } convenience init(frame: CGRect, browser: SKPhotoBrowser?) { self.init(frame: frame) self.frame = CGRect(x: 0, y: frame.height - margin - extraMargin, width: frame.width, height: 100) self.browser = browser setupApperance() setupCounterLabel() setupPrevButton() setupNextButton() update(browser?.currentPageIndex ?? 0) } override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { if let view = super.hitTest(point, with: event) { if let counterLabel = counterLabel, counterLabel.frame.contains(point) { return view } else if let prevButton = prevButton, prevButton.frame.contains(point) { return view } else if let nextButton = nextButton, nextButton.frame.contains(point) { return view } return nil } return nil } func updateFrame(frame: CGRect) { self.frame = CGRect(x: 0, y: frame.height - margin, width: frame.width, height: 100) } func update(_ currentPageIndex: Int) { guard let browser = browser else { return } if browser.photos.count > 1 { counterLabel?.text = "\(currentPageIndex + 1) / \(browser.photos.count)" } else { counterLabel?.text = nil } guard let prevButton = prevButton, let nextButton = nextButton else { return } prevButton.isEnabled = (currentPageIndex > 0) nextButton.isEnabled = (currentPageIndex < browser.photos.count - 1) } func setControlsHidden(hidden: Bool) { let alpha: CGFloat = hidden ? 0.0 : 1.0 UIView.animate(withDuration: 0.35, animations: { () -> Void in self.alpha = alpha }, completion: nil) } } private extension SKPaginationView { func setupApperance() { backgroundColor = .clear clipsToBounds = true } func setupCounterLabel() { guard SKPhotoBrowserOptions.displayCounterLabel else { return } let label = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 50)) label.center = CGPoint(x: frame.width / 2, y: frame.height / 2) label.textAlignment = .center label.backgroundColor = .clear label.shadowColor = SKToolbarOptions.textShadowColor label.shadowOffset = CGSize(width: 0.0, height: 1.0) label.font = SKToolbarOptions.font label.textColor = SKToolbarOptions.textColor label.translatesAutoresizingMaskIntoConstraints = true label.autoresizingMask = [.flexibleBottomMargin, .flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin] addSubview(label) counterLabel = label } func setupPrevButton() { guard SKPhotoBrowserOptions.displayBackAndForwardButton else { return } guard browser?.photos.count ?? 0 > 1 else { return } let button = SKPrevButton(frame: frame) button.center = CGPoint(x: frame.width / 2 - 100, y: frame.height / 2) button.addTarget(browser, action: #selector(SKPhotoBrowser.gotoPreviousPage), for: .touchUpInside) addSubview(button) prevButton = button } func setupNextButton() { guard SKPhotoBrowserOptions.displayBackAndForwardButton else { return } guard browser?.photos.count ?? 0 > 1 else { return } let button = SKNextButton(frame: frame) button.center = CGPoint(x: frame.width / 2 + 100, y: frame.height / 2) button.addTarget(browser, action: #selector(SKPhotoBrowser.gotoNextPage), for: .touchUpInside) addSubview(button) nextButton = button } } class SKPaginationButton: UIButton { let insets: UIEdgeInsets = UIEdgeInsets(top: 13.25, left: 17.25, bottom: 13.25, right: 17.25) func setup(_ imageName: String) { backgroundColor = .clear imageEdgeInsets = insets translatesAutoresizingMaskIntoConstraints = true autoresizingMask = [.flexibleBottomMargin, .flexibleLeftMargin, .flexibleRightMargin, .flexibleTopMargin] contentMode = .center setImage(UIImage.bundledImage(named: imageName), for: .normal) } } class SKPrevButton: SKPaginationButton { let imageName = "btn_common_back_wh" required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(frame: CGRect) { super.init(frame: CGRect(x: 0, y: 0, width: 44, height: 44)) setup(imageName) } } class SKNextButton: SKPaginationButton { let imageName = "btn_common_forward_wh" required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(frame: CGRect) { super.init(frame: CGRect(x: 0, y: 0, width: 44, height: 44)) setup(imageName) } }
d47a80d2bcd3071d4d754500c06fd147
32.947059
106
0.605094
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/CryptoAssets/Sources/EthereumKit/Services/Activity/EthereumActivityItemEventDetails.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import MoneyKit import PlatformKit public struct EthereumActivityItemEventDetails: Equatable { public struct Confirmation: Equatable { public let needConfirmation: Bool public let confirmations: Int public let requiredConfirmations: Int public let factor: Float public let status: EthereumTransactionState } public let amount: CryptoValue public let confirmation: Confirmation public let createdAt: Date public let data: String? public let fee: CryptoValue public let from: EthereumAddress public let identifier: String public let to: EthereumAddress init(transaction: EthereumHistoricalTransaction) { amount = transaction.amount createdAt = transaction.createdAt data = transaction.data fee = transaction.fee ?? .zero(currency: .ethereum) from = transaction.fromAddress identifier = transaction.transactionHash to = transaction.toAddress confirmation = Confirmation( needConfirmation: transaction.state == .pending, confirmations: transaction.confirmations, requiredConfirmations: EthereumHistoricalTransaction.requiredConfirmations, factor: Float(transaction.confirmations) / Float(EthereumHistoricalTransaction.requiredConfirmations), status: transaction.state ) } }
08044ca8e99fb187c463d3ce2b29e2fe
34.560976
114
0.707819
false
false
false
false
huangboju/Moots
refs/heads/master
Examples/Lumia/Lumia/Component/Parade/Sources/ParadeExtensions/UIScrollView+Parade.swift
mit
1
// // UIScrollView+PDAnimation.swift // PDAnimator-Demo // // Created by Anton Doudarev on 4/2/18. // Copyright © 2018 ELEPHANT. All rights reserved. // import Foundation import UIKit /// This swizzles methods on a specific class. /// Note: Don't got get the call the swizzled method /// to ensure the original selector gets called /// /// - Parameters: /// - cls: slass to swizzle methods in /// - originalSelector: the original method /// - swizzledSelector: the swizzled method func swizzleSelector(_ cls: AnyClass!, originalSelector : Selector, swizzledSelector : Selector) { let originalMethod = class_getInstanceMethod(cls, originalSelector) let swizzledMethod = class_getInstanceMethod(cls, swizzledSelector) method_exchangeImplementations(originalMethod!, swizzledMethod!); } // MARK: - UIScrollViewv - ContentOffset Swizzle extension UIScrollView { /// Call this method to initialize the contentOffset highjacking final public class func initializeParade() { swizzleSelector(self, originalSelector: #selector(UIScrollView.setContentOffset(_:animated:)), swizzledSelector: #selector(UIScrollView.swizzledSetContentOffset(_:animated:))) swizzleSelector(self, originalSelector: #selector(getter : UIScrollView.contentOffset), swizzledSelector: #selector(getter : UIScrollView.swizzledContentOffset)) swizzleSelector(self, originalSelector: #selector(setter: UIScrollView.contentOffset), swizzledSelector: #selector(UIScrollView.swizzledSetContentOffset(_:))) } /// The swizzled contentOffset property @objc public var swizzledContentOffset: CGPoint { get { return self.swizzledContentOffset // not recursive, false warning } } /// The swizzed ContentOffset method (2 input parameters) @objc public func swizzledSetContentOffset(_ contentOffset : CGPoint, animated: Bool) { swizzledSetContentOffset(contentOffset, animated: animated) updateViews() } /// The swizzed ContentOffset method (1 input setter) @objc public func swizzledSetContentOffset(_ contentOffset: CGPoint) { swizzledSetContentOffset(contentOffset) // not recursive updateViews() } } extension UIScrollView { /// This is called by the swizzled method func updateViews() { var views : [UIView] = [UIView]() if let collectionSelf = self as? UICollectionView { views = collectionSelf.visibleCells } else if let collectionSelf = self as? UITableView { views = collectionSelf.visibleCells } else { views = subviews } for view in views { guard let animatableObject = view as? PDAnimatableType else { continue } var progressAnimator : PDAnimator? = view.cachedProgressAnimator if progressAnimator == nil { view.cachedProgressAnimator = animatableObject.configuredAnimator() progressAnimator = view.cachedProgressAnimator! } let relativeCenter = self.convert(view.center, to: UIScreen.main.coordinateSpace) switch progressAnimator!.animationDirection { case .vertical: if let progress = verticalProgress(at: relativeCenter, to : self.bounds.height) { progressAnimator!.interpolateViewAnimation(forProgress: progress) } case .horizontal: if let progress = horizontalProgress(at: relativeCenter, to : self.bounds.width) { progressAnimator!.interpolateViewAnimation(forProgress: progress) } } } } } let centerThreshHold : CGFloat = 0.0005 extension UIScrollView { internal func verticalProgress(at relativeCenter : CGPoint, to viewportHeight: CGFloat) -> PDScrollProgressType? { let relativePercent : CGFloat = relativeProgress(at: relativeCenter.y, to: viewportHeight)! if relativePercent < -centerThreshHold { return .verticalAboveCenter(progress : (1.0 + relativePercent)) } else if relativePercent > centerThreshHold { return .verticalBelowCenter(progress : (1.0 - relativePercent)) } return .verticalCenter } internal func horizontalProgress(at relativeCenter : CGPoint, to viewportWidth: CGFloat) -> PDScrollProgressType? { let relativePercent : CGFloat = relativeProgress(at: relativeCenter.x, to: viewportWidth)! if relativePercent < -centerThreshHold { return .horizontalLeftCenter(progress : (1.0 + relativePercent)) } else if relativePercent > centerThreshHold { return .horizontalRightCenter(progress : (1.0 - relativePercent)) } return .horizontalCenter } internal func relativeProgress(at progressValue : CGFloat, to relativeValue: CGFloat) -> CGFloat? { let relativePercent = (progressValue - (relativeValue / 2.0)) / relativeValue if relativePercent == 0.0 { return 0.0 } if relativePercent <= -1.0 { return -1.0 } if relativePercent >= 1.0 { return 1.0 } return relativePercent } }
92b3766ba8a7ad86f4fe6831c464a483
32.568182
104
0.595802
false
false
false
false
grpc/grpc-swift
refs/heads/main
Sources/protoc-gen-grpc-swift/Generator-Client+AsyncAwait.swift
apache-2.0
1
/* * Copyright 2021, gRPC Authors All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import SwiftProtobuf import SwiftProtobufPluginLibrary // MARK: - Client protocol extension Generator { internal func printAsyncServiceClientProtocol() { let comments = self.service.protoSourceComments() if !comments.isEmpty { // Source comments already have the leading '///' self.println(comments, newline: false) } self.printAvailabilityForAsyncAwait() self.println("\(self.access) protocol \(self.asyncClientProtocolName): GRPCClient {") self.withIndentation { self.println("static var serviceDescriptor: GRPCServiceDescriptor { get }") self.println("var interceptors: \(self.clientInterceptorProtocolName)? { get }") for method in service.methods { self.println() self.method = method let rpcType = streamingType(self.method) let callType = Types.call(for: rpcType) let arguments: [String] switch rpcType { case .unary, .serverStreaming: arguments = [ "_ request: \(self.methodInputName)", "callOptions: \(Types.clientCallOptions)?", ] case .clientStreaming, .bidirectionalStreaming: arguments = [ "callOptions: \(Types.clientCallOptions)?", ] } self.printFunction( name: self.methodMakeFunctionCallName, arguments: arguments, returnType: "\(callType)<\(self.methodInputName), \(self.methodOutputName)>", bodyBuilder: nil ) } } self.println("}") // protocol } } // MARK: - Client protocol default implementation: Calls extension Generator { internal func printAsyncClientProtocolExtension() { self.printAvailabilityForAsyncAwait() self.withIndentation("extension \(self.asyncClientProtocolName)", braces: .curly) { // Service descriptor. self.withIndentation( "\(self.access) static var serviceDescriptor: GRPCServiceDescriptor", braces: .curly ) { self.println("return \(self.serviceClientMetadata).serviceDescriptor") } self.println() // Interceptor factory. self.withIndentation( "\(self.access) var interceptors: \(self.clientInterceptorProtocolName)?", braces: .curly ) { self.println("return nil") } // 'Unsafe' calls. for method in self.service.methods { self.println() self.method = method let rpcType = streamingType(self.method) let callType = Types.call(for: rpcType) let callTypeWithoutPrefix = Types.call(for: rpcType, withGRPCPrefix: false) switch rpcType { case .unary, .serverStreaming: self.printFunction( name: self.methodMakeFunctionCallName, arguments: [ "_ request: \(self.methodInputName)", "callOptions: \(Types.clientCallOptions)? = nil", ], returnType: "\(callType)<\(self.methodInputName), \(self.methodOutputName)>", access: self.access ) { self.withIndentation("return self.make\(callTypeWithoutPrefix)", braces: .round) { self.println("path: \(self.methodPathUsingClientMetadata),") self.println("request: request,") self.println("callOptions: callOptions ?? self.defaultCallOptions,") self.println( "interceptors: self.interceptors?.\(self.methodInterceptorFactoryName)() ?? []" ) } } case .clientStreaming, .bidirectionalStreaming: self.printFunction( name: self.methodMakeFunctionCallName, arguments: ["callOptions: \(Types.clientCallOptions)? = nil"], returnType: "\(callType)<\(self.methodInputName), \(self.methodOutputName)>", access: self.access ) { self.withIndentation("return self.make\(callTypeWithoutPrefix)", braces: .round) { self.println("path: \(self.methodPathUsingClientMetadata),") self.println("callOptions: callOptions ?? self.defaultCallOptions,") self.println( "interceptors: self.interceptors?.\(self.methodInterceptorFactoryName)() ?? []" ) } } } } } } } // MARK: - Client protocol extension: "Simple, but safe" call wrappers. extension Generator { internal func printAsyncClientProtocolSafeWrappersExtension() { self.printAvailabilityForAsyncAwait() self.withIndentation("extension \(self.asyncClientProtocolName)", braces: .curly) { for (i, method) in self.service.methods.enumerated() { self.method = method let rpcType = streamingType(self.method) let callTypeWithoutPrefix = Types.call(for: rpcType, withGRPCPrefix: false) let streamsResponses = [.serverStreaming, .bidirectionalStreaming].contains(rpcType) let streamsRequests = [.clientStreaming, .bidirectionalStreaming].contains(rpcType) // (protocol, requires sendable) let sequenceProtocols: [(String, Bool)?] = streamsRequests ? [("Sequence", false), ("AsyncSequence", true)] : [nil] for (j, sequenceProtocol) in sequenceProtocols.enumerated() { // Print a new line if this is not the first function in the extension. if i > 0 || j > 0 { self.println() } let functionName = streamsRequests ? "\(self.methodFunctionName)<RequestStream>" : self.methodFunctionName let requestParamName = streamsRequests ? "requests" : "request" let requestParamType = streamsRequests ? "RequestStream" : self.methodInputName let returnType = streamsResponses ? Types.responseStream(of: self.methodOutputName) : self.methodOutputName let maybeWhereClause = sequenceProtocol.map { protocolName, mustBeSendable -> String in let constraints = [ "RequestStream: \(protocolName)" + (mustBeSendable ? " & Sendable" : ""), "RequestStream.Element == \(self.methodInputName)", ] return "where " + constraints.joined(separator: ", ") } self.printFunction( name: functionName, arguments: [ "_ \(requestParamName): \(requestParamType)", "callOptions: \(Types.clientCallOptions)? = nil", ], returnType: returnType, access: self.access, async: !streamsResponses, throws: !streamsResponses, genericWhereClause: maybeWhereClause ) { self.withIndentation( "return\(!streamsResponses ? " try await" : "") self.perform\(callTypeWithoutPrefix)", braces: .round ) { self.println("path: \(self.methodPathUsingClientMetadata),") self.println("\(requestParamName): \(requestParamName),") self.println("callOptions: callOptions ?? self.defaultCallOptions,") self.println( "interceptors: self.interceptors?.\(self.methodInterceptorFactoryName)() ?? []" ) } } } } } } } // MARK: - Client protocol implementation extension Generator { internal func printAsyncServiceClientImplementation() { self.printAvailabilityForAsyncAwait() self.withIndentation( "\(self.access) struct \(self.asyncClientStructName): \(self.asyncClientProtocolName)", braces: .curly ) { self.println("\(self.access) var channel: GRPCChannel") self.println("\(self.access) var defaultCallOptions: CallOptions") self.println("\(self.access) var interceptors: \(self.clientInterceptorProtocolName)?") self.println() self.println("\(self.access) init(") self.withIndentation { self.println("channel: GRPCChannel,") self.println("defaultCallOptions: CallOptions = CallOptions(),") self.println("interceptors: \(self.clientInterceptorProtocolName)? = nil") } self.println(") {") self.withIndentation { self.println("self.channel = channel") self.println("self.defaultCallOptions = defaultCallOptions") self.println("self.interceptors = interceptors") } self.println("}") } } }
d960790c41730ec2a3345dcb7d07af96
36.160494
100
0.620155
false
false
false
false
BenEmdon/swift-algorithm-club
refs/heads/master
Binary Search Tree/Solution 1/BinarySearchTree.playground/Sources/BinarySearchTree.swift
mit
1
/* A binary search tree. Each node stores a value and two children. The left child contains a smaller value; the right a larger (or equal) value. This tree allows duplicate elements. This tree does not automatically balance itself. To make sure it is balanced, you should insert new values in randomized order, not in sorted order. */ public class BinarySearchTree<T: Comparable> { fileprivate(set) public var value: T fileprivate(set) public var parent: BinarySearchTree? fileprivate(set) public var left: BinarySearchTree? fileprivate(set) public var right: BinarySearchTree? public init(value: T) { self.value = value } public convenience init(array: [T]) { precondition(array.count > 0) self.init(value: array.first!) for v in array.dropFirst() { insert(value: v, parent: self) } } public var isRoot: Bool { return parent == nil } public var isLeaf: Bool { return left == nil && right == nil } public var isLeftChild: Bool { return parent?.left === self } public var isRightChild: Bool { return parent?.right === self } public var hasLeftChild: Bool { return left != nil } public var hasRightChild: Bool { return right != nil } public var hasAnyChild: Bool { return hasLeftChild || hasRightChild } public var hasBothChildren: Bool { return hasLeftChild && hasRightChild } /* How many nodes are in this subtree. Performance: O(n). */ public var count: Int { return (left?.count ?? 0) + 1 + (right?.count ?? 0) } } // MARK: - Adding items extension BinarySearchTree { /* Inserts a new element into the tree. You should only insert elements at the root, to make to sure this remains a valid binary tree! Performance: runs in O(h) time, where h is the height of the tree. */ public func insert(value: T) { insert(value: value, parent: self) } fileprivate func insert(value: T, parent: BinarySearchTree) { if value < self.value { if let left = left { left.insert(value: value, parent: left) } else { left = BinarySearchTree(value: value) left?.parent = parent } } else { if let right = right { right.insert(value: value, parent: right) } else { right = BinarySearchTree(value: value) right?.parent = parent } } } } // MARK: - Deleting items extension BinarySearchTree { /* Deletes a node from the tree. Returns the node that has replaced this removed one (or nil if this was a leaf node). That is primarily useful for when you delete the root node, in which case the tree gets a new root. Performance: runs in O(h) time, where h is the height of the tree. */ @discardableResult public func remove() -> BinarySearchTree? { let replacement: BinarySearchTree? if let left = left { if let right = right { replacement = removeNodeWithTwoChildren(left, right) } else { // This node only has a left child. The left child replaces the node. replacement = left } } else if let right = right { // This node only has a right child. The right child replaces the node. replacement = right } else { // This node has no children. We just disconnect it from its parent. replacement = nil } reconnectParentTo(node: replacement) // The current node is no longer part of the tree, so clean it up. parent = nil left = nil right = nil return replacement } private func removeNodeWithTwoChildren(_ left: BinarySearchTree, _ right: BinarySearchTree) -> BinarySearchTree { // This node has two children. It must be replaced by the smallest // child that is larger than this node's value, which is the leftmost // descendent of the right child. let successor = right.minimum() // If this in-order successor has a right child of its own (it cannot // have a left child by definition), then that must take its place. successor.remove() // Connect our left child with the new node. successor.left = left left.parent = successor // Connect our right child with the new node. If the right child does // not have any left children of its own, then the in-order successor // *is* the right child. if right !== successor { successor.right = right right.parent = successor } else { successor.right = nil } // And finally, connect the successor node to our parent. return successor } private func reconnectParentTo(node: BinarySearchTree?) { if let parent = parent { if isLeftChild { parent.left = node } else { parent.right = node } } node?.parent = parent } } // MARK: - Searching extension BinarySearchTree { /* Finds the "highest" node with the specified value. Performance: runs in O(h) time, where h is the height of the tree. */ public func search(value: T) -> BinarySearchTree? { var node: BinarySearchTree? = self while case let n? = node { if value < n.value { node = n.left } else if value > n.value { node = n.right } else { return node } } return nil } /* // Recursive version of search public func search(value: T) -> BinarySearchTree? { if value < self.value { return left?.search(value) } else if value > self.value { return right?.search(value) } else { return self // found it! } } */ public func contains(value: T) -> Bool { return search(value: value) != nil } /* Returns the leftmost descendent. O(h) time. */ public func minimum() -> BinarySearchTree { var node = self while case let next? = node.left { node = next } return node } /* Returns the rightmost descendent. O(h) time. */ public func maximum() -> BinarySearchTree { var node = self while case let next? = node.right { node = next } return node } /* Calculates the depth of this node, i.e. the distance to the root. Takes O(h) time. */ public func depth() -> Int { var node = self var edges = 0 while case let parent? = node.parent { node = parent edges += 1 } return edges } /* Calculates the height of this node, i.e. the distance to the lowest leaf. Since this looks at all children of this node, performance is O(n). */ public func height() -> Int { if isLeaf { return 0 } else { return 1 + max(left?.height() ?? 0, right?.height() ?? 0) } } /* Finds the node whose value precedes our value in sorted order. */ public func predecessor() -> BinarySearchTree<T>? { if let left = left { return left.maximum() } else { var node = self while case let parent? = node.parent { if parent.value < value { return parent } node = parent } return nil } } /* Finds the node whose value succeeds our value in sorted order. */ public func successor() -> BinarySearchTree<T>? { if let right = right { return right.minimum() } else { var node = self while case let parent? = node.parent { if parent.value > value { return parent } node = parent } return nil } } } // MARK: - Traversal extension BinarySearchTree { public func traverseInOrder(process: (T) -> Void) { left?.traverseInOrder(process: process) process(value) right?.traverseInOrder(process: process) } public func traversePreOrder(process: (T) -> Void) { process(value) left?.traversePreOrder(process: process) right?.traversePreOrder(process: process) } public func traversePostOrder(process: (T) -> Void) { left?.traversePostOrder(process: process) right?.traversePostOrder(process: process) process(value) } /* Performs an in-order traversal and collects the results in an array. */ public func map(formula: (T) -> T) -> [T] { var a = [T]() if let left = left { a += left.map(formula: formula) } a.append(formula(value)) if let right = right { a += right.map(formula: formula) } return a } } /* Is this binary tree a valid binary search tree? */ extension BinarySearchTree { public func isBST(minValue: T, maxValue: T) -> Bool { if value < minValue || value > maxValue { return false } let leftBST = left?.isBST(minValue: minValue, maxValue: value) ?? true let rightBST = right?.isBST(minValue: value, maxValue: maxValue) ?? true return leftBST && rightBST } } // MARK: - Debugging extension BinarySearchTree: CustomStringConvertible { public var description: String { var s = "" if let left = left { s += "(\(left.description)) <- " } s += "\(value)" if let right = right { s += " -> (\(right.description))" } return s } } extension BinarySearchTree: CustomDebugStringConvertible { public var debugDescription: String { var s = "value: \(value)" if let parent = parent { s += ", parent: \(parent.value)" } if let left = left { s += ", left = [" + left.debugDescription + "]" } if let right = right { s += ", right = [" + right.debugDescription + "]" } return s } public func toArray() -> [T] { return map { $0 } } }
5d81a55d492e139b5c4d68923470849f
24.034483
115
0.622801
false
false
false
false
CodaFi/swift
refs/heads/main
stdlib/public/core/CString.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 // //===----------------------------------------------------------------------===// // String interop with C //===----------------------------------------------------------------------===// import SwiftShims extension String { /// Creates a new string by copying the null-terminated UTF-8 data referenced /// by the given pointer. /// /// If `cString` contains ill-formed UTF-8 code unit sequences, this /// initializer replaces them with the Unicode replacement character /// (`"\u{FFFD}"`). /// /// The following example calls this initializer with pointers to the /// contents of two different `CChar` arrays---the first with well-formed /// UTF-8 code unit sequences and the second with an ill-formed sequence at /// the end. /// /// let validUTF8: [CChar] = [67, 97, 102, -61, -87, 0] /// validUTF8.withUnsafeBufferPointer { ptr in /// let s = String(cString: ptr.baseAddress!) /// print(s) /// } /// // Prints "Café" /// /// let invalidUTF8: [CChar] = [67, 97, 102, -61, 0] /// invalidUTF8.withUnsafeBufferPointer { ptr in /// let s = String(cString: ptr.baseAddress!) /// print(s) /// } /// // Prints "Caf�" /// /// - Parameter cString: A pointer to a null-terminated UTF-8 code sequence. public init(cString: UnsafePointer<CChar>) { let len = UTF8._nullCodeUnitOffset(in: cString) self = String._fromUTF8Repairing( UnsafeBufferPointer(start: cString._asUInt8, count: len)).0 } /// Creates a new string by copying the null-terminated UTF-8 data referenced /// by the given pointer. /// /// This is identical to `init(cString: UnsafePointer<CChar>)` but operates on /// an unsigned sequence of bytes. public init(cString: UnsafePointer<UInt8>) { let len = UTF8._nullCodeUnitOffset(in: cString) self = String._fromUTF8Repairing( UnsafeBufferPointer(start: cString, count: len)).0 } /// Creates a new string by copying and validating the null-terminated UTF-8 /// data referenced by the given pointer. /// /// This initializer does not try to repair ill-formed UTF-8 code unit /// sequences. If any are found, the result of the initializer is `nil`. /// /// The following example calls this initializer with pointers to the /// contents of two different `CChar` arrays---the first with well-formed /// UTF-8 code unit sequences and the second with an ill-formed sequence at /// the end. /// /// let validUTF8: [CChar] = [67, 97, 102, -61, -87, 0] /// validUTF8.withUnsafeBufferPointer { ptr in /// let s = String(validatingUTF8: ptr.baseAddress!) /// print(s) /// } /// // Prints "Optional("Café")" /// /// let invalidUTF8: [CChar] = [67, 97, 102, -61, 0] /// invalidUTF8.withUnsafeBufferPointer { ptr in /// let s = String(validatingUTF8: ptr.baseAddress!) /// print(s) /// } /// // Prints "nil" /// /// - Parameter cString: A pointer to a null-terminated UTF-8 code sequence. public init?(validatingUTF8 cString: UnsafePointer<CChar>) { let len = UTF8._nullCodeUnitOffset(in: cString) guard let str = String._tryFromUTF8( UnsafeBufferPointer(start: cString._asUInt8, count: len)) else { return nil } self = str } /// Creates a new string by copying the null-terminated data referenced by /// the given pointer using the specified encoding. /// /// When you pass `true` as `isRepairing`, this method replaces ill-formed /// sequences with the Unicode replacement character (`"\u{FFFD}"`); /// otherwise, an ill-formed sequence causes this method to stop decoding /// and return `nil`. /// /// The following example calls this method with pointers to the contents of /// two different `CChar` arrays---the first with well-formed UTF-8 code /// unit sequences and the second with an ill-formed sequence at the end. /// /// let validUTF8: [UInt8] = [67, 97, 102, 195, 169, 0] /// validUTF8.withUnsafeBufferPointer { ptr in /// let s = String.decodeCString(ptr.baseAddress, /// as: UTF8.self, /// repairingInvalidCodeUnits: true) /// print(s) /// } /// // Prints "Optional((result: "Café", repairsMade: false))" /// /// let invalidUTF8: [UInt8] = [67, 97, 102, 195, 0] /// invalidUTF8.withUnsafeBufferPointer { ptr in /// let s = String.decodeCString(ptr.baseAddress, /// as: UTF8.self, /// repairingInvalidCodeUnits: true) /// print(s) /// } /// // Prints "Optional((result: "Caf�", repairsMade: true))" /// /// - Parameters: /// - cString: A pointer to a null-terminated code sequence encoded in /// `encoding`. /// - encoding: The Unicode encoding of the data referenced by `cString`. /// - isRepairing: Pass `true` to create a new string, even when the data /// referenced by `cString` contains ill-formed sequences. Ill-formed /// sequences are replaced with the Unicode replacement character /// (`"\u{FFFD}"`). Pass `false` to interrupt the creation of the new /// string if an ill-formed sequence is detected. /// - Returns: A tuple with the new string and a Boolean value that indicates /// whether any repairs were made. If `isRepairing` is `false` and an /// ill-formed sequence is detected, this method returns `nil`. @_specialize(where Encoding == Unicode.UTF8) @_specialize(where Encoding == Unicode.UTF16) @inlinable // Fold away specializations public static func decodeCString<Encoding: _UnicodeEncoding>( _ cString: UnsafePointer<Encoding.CodeUnit>?, as encoding: Encoding.Type, repairingInvalidCodeUnits isRepairing: Bool = true ) -> (result: String, repairsMade: Bool)? { guard let cPtr = cString else { return nil } if _fastPath(encoding == Unicode.UTF8.self) { let ptr = UnsafeRawPointer(cPtr).assumingMemoryBound(to: UInt8.self) let len = UTF8._nullCodeUnitOffset(in: ptr) let codeUnits = UnsafeBufferPointer(start: ptr, count: len) if isRepairing { return String._fromUTF8Repairing(codeUnits) } else { guard let str = String._tryFromUTF8(codeUnits) else { return nil } return (str, false) } } var end = cPtr while end.pointee != 0 { end += 1 } let len = end - cPtr let codeUnits = UnsafeBufferPointer(start: cPtr, count: len) return String._fromCodeUnits( codeUnits, encoding: encoding, repair: isRepairing) } /// Creates a string from the null-terminated sequence of bytes at the given /// pointer. /// /// - Parameters: /// - nullTerminatedCodeUnits: A pointer to a sequence of contiguous code /// units in the encoding specified in `sourceEncoding`, ending just /// before the first zero code unit. /// - sourceEncoding: The encoding in which the code units should be /// interpreted. @_specialize(where Encoding == Unicode.UTF8) @_specialize(where Encoding == Unicode.UTF16) @inlinable // Fold away specializations public init<Encoding: Unicode.Encoding>( decodingCString ptr: UnsafePointer<Encoding.CodeUnit>, as sourceEncoding: Encoding.Type ) { self = String.decodeCString(ptr, as: sourceEncoding)!.0 } } extension UnsafePointer where Pointee == UInt8 { @inlinable internal var _asCChar: UnsafePointer<CChar> { @inline(__always) get { return UnsafeRawPointer(self).assumingMemoryBound(to: CChar.self) } } } extension UnsafePointer where Pointee == CChar { @inlinable internal var _asUInt8: UnsafePointer<UInt8> { @inline(__always) get { return UnsafeRawPointer(self).assumingMemoryBound(to: UInt8.self) } } }
0724c9a28f98e179b30406edd13041e4
39.678049
80
0.624895
false
false
false
false
arvedviehweger/swift
refs/heads/master
test/SILGen/keypaths.swift
apache-2.0
1
// RUN: %target-swift-frontend -enable-experimental-keypaths -emit-silgen %s | %FileCheck %s // REQUIRES: PTRSIZE=64 struct S<T> { var x: T let y: String var z: C<T> var computed: C<T> { fatalError() } var observed: C<T> { didSet { fatalError() } } var reabstracted: () -> () } class C<T> { final var x: T final let y: String final var z: S<T> var nonfinal: S<T> var computed: S<T> { fatalError() } var observed: S<T> { didSet { fatalError() } } final var reabstracted: () -> () init() { fatalError() } } protocol P { var x: Int { get } var y: String { get set } } // CHECK-LABEL: sil hidden @{{.*}}storedProperties func storedProperties<T>(_: T) { // CHECK: keypath $WritableKeyPath<S<T>, T>, <τ_0_0> (root $S<τ_0_0>; stored_property #S.x : $τ_0_0) <T> _ = #keyPath2(S<T>, .x) // CHECK: keypath $KeyPath<S<T>, String>, <τ_0_0> (root $S<τ_0_0>; stored_property #S.y : $String) <T> _ = #keyPath2(S<T>, .y) // CHECK: keypath $ReferenceWritableKeyPath<S<T>, T>, <τ_0_0> (root $S<τ_0_0>; stored_property #S.z : $C<τ_0_0>; stored_property #C.x : $τ_0_0) <T> _ = #keyPath2(S<T>, .z.x) // CHECK: keypath $ReferenceWritableKeyPath<C<T>, T>, <τ_0_0> (root $C<τ_0_0>; stored_property #C.x : $τ_0_0) <T> _ = #keyPath2(C<T>, .x) // CHECK: keypath $KeyPath<C<T>, String>, <τ_0_0> (root $C<τ_0_0>; stored_property #C.y : $String) <T> _ = #keyPath2(C<T>, .y) // CHECK: keypath $ReferenceWritableKeyPath<C<T>, T>, <τ_0_0> (root $C<τ_0_0>; stored_property #C.z : $S<τ_0_0>; stored_property #S.x : $τ_0_0) <T> _ = #keyPath2(C<T>, .z.x) // CHECK: keypath $KeyPath<C<T>, String>, <τ_0_0> (root $C<τ_0_0>; stored_property #C.z : $S<τ_0_0>; stored_property #S.z : $C<τ_0_0>; stored_property #C.y : $String) <T> _ = #keyPath2(C<T>, .z.z.y) } // CHECK-LABEL: sil hidden @{{.*}}computedProperties func computedProperties<T: P>(_: T) { // CHECK: keypath $ReferenceWritableKeyPath<C<T>, S<T>>, <τ_0_0 where τ_0_0 : P> ( // CHECK-SAME: root $C<τ_0_0>; // CHECK-SAME: settable_property $S<τ_0_0>, // CHECK-SAME: id #C.nonfinal!getter.1 : <T> (C<T>) -> () -> S<T>, // CHECK-SAME: getter @_T08keypaths1CC8nonfinalAA1SVyxGvTK : $@convention(thin) <τ_0_0> (@in C<τ_0_0>, @thick C<τ_0_0>.Type) -> @out S<τ_0_0>, // CHECK-SAME: setter @_T08keypaths1CC8nonfinalAA1SVyxGvTk : $@convention(thin) <τ_0_0> (@in S<τ_0_0>, @in C<τ_0_0>, @thick C<τ_0_0>.Type) -> () // CHECK-SAME: ) <T> _ = #keyPath2(C<T>, .nonfinal) // CHECK: keypath $KeyPath<C<T>, S<T>>, <τ_0_0 where τ_0_0 : P> ( // CHECK-SAME: root $C<τ_0_0>; // CHECK-SAME: gettable_property $S<τ_0_0>, // CHECK-SAME: id #C.computed!getter.1 : <T> (C<T>) -> () -> S<T>, // CHECK-SAME: getter @_T08keypaths1CC8computedAA1SVyxGvTK : $@convention(thin) <τ_0_0> (@in C<τ_0_0>, @thick C<τ_0_0>.Type) -> @out S<τ_0_0> // CHECK-SAME: ) <T> _ = #keyPath2(C<T>, .computed) // CHECK: keypath $ReferenceWritableKeyPath<C<T>, S<T>>, <τ_0_0 where τ_0_0 : P> ( // CHECK-SAME: root $C<τ_0_0>; // CHECK-SAME: settable_property $S<τ_0_0>, // CHECK-SAME: id #C.observed!getter.1 : <T> (C<T>) -> () -> S<T>, // CHECK-SAME: getter @_T08keypaths1CC8observedAA1SVyxGvTK : $@convention(thin) <τ_0_0> (@in C<τ_0_0>, @thick C<τ_0_0>.Type) -> @out S<τ_0_0>, // CHECK-SAME: setter @_T08keypaths1CC8observedAA1SVyxGvTk : $@convention(thin) <τ_0_0> (@in S<τ_0_0>, @in C<τ_0_0>, @thick C<τ_0_0>.Type) -> () // CHECK-SAME: ) <T> _ = #keyPath2(C<T>, .observed) _ = #keyPath2(C<T>, .nonfinal.x) _ = #keyPath2(C<T>, .computed.x) _ = #keyPath2(C<T>, .observed.x) _ = #keyPath2(C<T>, .z.computed) _ = #keyPath2(C<T>, .z.observed) _ = #keyPath2(C<T>, .observed.x) // CHECK: keypath $ReferenceWritableKeyPath<C<T>, () -> ()>, <τ_0_0 where τ_0_0 : P> ( // CHECK-SAME: root $C<τ_0_0>; // CHECK-SAME: settable_property $() -> (), // CHECK-SAME: id ##C.reabstracted, // CHECK-SAME: getter @_T08keypaths1CC12reabstractedyycvTK : $@convention(thin) <τ_0_0> (@in C<τ_0_0>, @thick C<τ_0_0>.Type) -> @out @callee_owned (@in ()) -> @out (), // CHECK-SAME: setter @_T08keypaths1CC12reabstractedyycvTk : $@convention(thin) <τ_0_0> (@in @callee_owned (@in ()) -> @out (), @in C<τ_0_0>, @thick C<τ_0_0>.Type) -> () // CHECK-SAME: ) <T> _ = #keyPath2(C<T>, .reabstracted) // CHECK: keypath $KeyPath<S<T>, C<T>>, <τ_0_0 where τ_0_0 : P> ( // CHECK-SAME: root $S<τ_0_0>; gettable_property $C<τ_0_0>, // CHECK-SAME: id @_T08keypaths1SV8computedAA1CCyxGfg : $@convention(method) <τ_0_0> (@in_guaranteed S<τ_0_0>) -> @owned C<τ_0_0>, // CHECK-SAME: getter @_T08keypaths1SV8computedAA1CCyxGvTK : $@convention(thin) <τ_0_0> (@in S<τ_0_0>, @thick S<τ_0_0>.Type) -> @out C<τ_0_0> // CHECK-SAME: ) <T> _ = #keyPath2(S<T>, .computed) // CHECK: keypath $WritableKeyPath<S<T>, C<T>>, <τ_0_0 where τ_0_0 : P> ( // CHECK-SAME: root $S<τ_0_0>; // CHECK-SAME: settable_property $C<τ_0_0>, // CHECK-SAME: id @_T08keypaths1SV8observedAA1CCyxGfg : $@convention(method) <τ_0_0> (@in_guaranteed S<τ_0_0>) -> @owned C<τ_0_0>, // CHECK-SAME: getter @_T08keypaths1SV8observedAA1CCyxGvTK : $@convention(thin) <τ_0_0> (@in S<τ_0_0>, @thick S<τ_0_0>.Type) -> @out C<τ_0_0>, // CHECK-SAME: setter @_T08keypaths1SV8observedAA1CCyxGvTk : $@convention(thin) <τ_0_0> (@in C<τ_0_0>, @inout S<τ_0_0>, @thick S<τ_0_0>.Type) -> () // CHECK-SAME: ) <T> _ = #keyPath2(S<T>, .observed) _ = #keyPath2(S<T>, .z.nonfinal) _ = #keyPath2(S<T>, .z.computed) _ = #keyPath2(S<T>, .z.observed) _ = #keyPath2(S<T>, .computed.x) _ = #keyPath2(S<T>, .computed.y) // CHECK: keypath $WritableKeyPath<S<T>, () -> ()>, <τ_0_0 where τ_0_0 : P> ( // CHECK-SAME: root $S<τ_0_0>; // CHECK-SAME: settable_property $() -> (), // CHECK-SAME: id ##S.reabstracted, // CHECK-SAME: getter @_T08keypaths1SV12reabstractedyycvTK : $@convention(thin) <τ_0_0> (@in S<τ_0_0>, @thick S<τ_0_0>.Type) -> @out @callee_owned (@in ()) -> @out (), // CHECK-SAME: setter @_T08keypaths1SV12reabstractedyycvTk : $@convention(thin) <τ_0_0> (@in @callee_owned (@in ()) -> @out (), @inout S<τ_0_0>, @thick S<τ_0_0>.Type) -> () // CHECK-SAME: ) <T> _ = #keyPath2(S<T>, .reabstracted) // CHECK: keypath $KeyPath<T, Int>, <τ_0_0 where τ_0_0 : P> ( // CHECK-SAME: root $τ_0_0; // CHECK-SAME: gettable_property $Int, // CHECK-SAME: id #P.x!getter.1 : <Self where Self : P> (Self) -> () -> Int, // CHECK-SAME: getter @_T08keypaths1PP1xSivTK : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@in τ_0_0) -> @out Int // CHECK-SAME: ) <T> _ = #keyPath2(T, .x) // CHECK: keypath $WritableKeyPath<T, String>, <τ_0_0 where τ_0_0 : P> ( // CHECK-SAME: root $τ_0_0; // CHECK-SAME: settable_property $String, // CHECK-SAME: id #P.y!getter.1 : <Self where Self : P> (Self) -> () -> String, // CHECK-SAME: getter @_T08keypaths1PP1ySSvTK : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@in τ_0_0) -> @out String, // CHECK-SAME: setter @_T08keypaths1PP1ySSvTk : $@convention(thin) <τ_0_0 where τ_0_0 : P> (@in String, @inout τ_0_0) -> () // CHECK-SAME: ) <T> _ = #keyPath2(T, .y) }
3a898a86ad4caf7b2fef664eaa03fa6f
50.948905
177
0.578334
false
false
false
false
Rag0n/QuNotes
refs/heads/master
Carthage/Checkouts/yoga/YogaKit/YogaKitSample/YogaKitSample/ExamplesViewController.swift
bsd-3-clause
3
/** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the license found in the * LICENSE-examples file in the root directory of this source tree. */ import UIKit import IGListKit private final class ExampleModel { let title: String let controllerClass: UIViewController.Type init(title: String, controllerClass: UIViewController.Type) { self.title = title self.controllerClass = controllerClass } } extension ExampleModel: IGListDiffable { fileprivate func diffIdentifier() -> NSObjectProtocol { return title as NSString } fileprivate func isEqual(toDiffableObject object: IGListDiffable?) -> Bool { guard let otherObj = object as? ExampleModel else { return false } return (title == otherObj.title) && (controllerClass == otherObj.controllerClass) } } final class ExamplesViewController: UIViewController, IGListAdapterDataSource, IGListSingleSectionControllerDelegate { private lazy var adapter: IGListAdapter = { return IGListAdapter(updater: IGListAdapterUpdater(), viewController: self, workingRangeSize: 0) }() private let collectionView = IGListCollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout()) // Update this to array to create more examples. private let models: [ExampleModel] = [ExampleModel(title: "Basic Layout", controllerClass: BasicViewController.self), ExampleModel(title: "Exclude Views in Layout", controllerClass: LayoutInclusionViewController.self)] //MARK: UIViewController override func viewDidLoad() { super.viewDidLoad() title = "Examples" view.addSubview(collectionView) adapter.collectionView = collectionView adapter.dataSource = self } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() collectionView.frame = view.bounds } //MARK: IGListAdapterDataSource func objects(for listAdapter: IGListAdapter) -> [IGListDiffable] { return models as [IGListDiffable] } func listAdapter(_ listAdapter: IGListAdapter, sectionControllerFor object: Any) -> IGListSectionController { let sizeBlock: IGListSingleSectionCellSizeBlock = { (model, context) in return CGSize(width: (context?.containerSize.width)!, height: 75.0) } let configureBlock: IGListSingleSectionCellConfigureBlock = { (model, cell) in guard let m = model as? ExampleModel, let c = cell as? SingleLabelCollectionCell else { return } c.label.text = m.title } let sectionController = IGListSingleSectionController(cellClass: SingleLabelCollectionCell.self, configureBlock: configureBlock, sizeBlock: sizeBlock) sectionController.selectionDelegate = self return sectionController } func emptyView(for listAdapter: IGListAdapter) -> UIView? { return nil } //MARK: IGListSingleSectionControllerDelegate func didSelect(_ sectionController: IGListSingleSectionController) { let section = adapter.section(for: sectionController) let model = models[section] let controller = model.controllerClass.init() controller.title = model.title self.navigationController?.pushViewController(controller, animated: true) } }
aa07243633f5d06da1420004378341bc
34.79
142
0.67449
false
false
false
false
mohssenfathi/MTLImage
refs/heads/master
Example-iOS/Example-iOS/ViewControllers/Settings/SettingsViewController.swift
mit
1
// // SettingsViewController.swift // MTLImage // // Created by Mohssen Fathi on 3/31/16. // Copyright © 2016 CocoaPods. All rights reserved. // import UIKit import MTLImage class SettingsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, SettingsCellDelegate, PickerCellDelegate, ToggleCellDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var emptyLabel: UILabel! var filter: Filter! var touchProperty: Property? var mainViewController: MainViewController! override func viewDidLoad() { super.viewDidLoad() navigationItem.title = filter.title tableView.estimatedRowHeight = 80 mainViewController = self.navigationController?.parent as! MainViewController for property: Property in filter.properties { if property.propertyType == .point { touchProperty = property break; } } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) tableView.isHidden = (filter.properties.count == 0) emptyLabel.isHidden = (filter.properties.count != 0) } func handleTouchAtLocation(_ location: CGPoint) { if filter is Smudge { return } // Temp if touchProperty != nil { let viewSize = mainViewController.mtlView.frame.size let point = CGPoint(x: location.x / viewSize.width, y: location.y / viewSize.height) filter.setValue(NSValue(cgPoint: point), forKey: touchProperty!.key) } } func handlePan(_ sender: UIPanGestureRecognizer) { let translation = sender.translation(in: sender.view) let location = sender.location(in: sender.view) // let velocity = sender.velocityInView(sender.view) if let smudgeFilter = filter as? Smudge { smudgeFilter.location = location smudgeFilter.direction = translation // smudgeFilter.force = Float(max(velocity.x, velocity.y)) } } // MARK: - UITableView // MARK: DataSource func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return filter.properties.count + 1 } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if indexPath.row == filter.properties.count { return 80.0 } if cellIdentifier(filter.properties[indexPath.row].propertyType) == "pickerCell" { return 200.0 } return 80.0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var identifier: String! if indexPath.row == filter.properties.count { identifier = "resetCell" } else { identifier = cellIdentifier(filter.properties[indexPath.row].propertyType) } let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath) return cell } func cellIdentifier(_ propertyType: Property.PropertyType) -> String { if propertyType == .selection { return "pickerCell" } else if propertyType == .image { return "imageCell" } else if propertyType == .bool { return "toggleCell" } return "settingsCell" } func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { if cell.reuseIdentifier == "settingsCell" { let settingsCell: SettingsCell = cell as! SettingsCell let property: Property = filter.properties[indexPath.row] settingsCell.delegate = self settingsCell.titleLabel.text = property.title if property.propertyType == .value { let value = filter.value(forKey: property.key!) as! Float settingsCell.spectrum = false settingsCell.valueLabel.text = String(format: "%.2f", value) settingsCell.slider.value = value } else if property.propertyType == .color { settingsCell.spectrum = true settingsCell.valueLabel.text = "-" } else if property.propertyType == .point { settingsCell.message = "Touch preview image to adjust." } } else if cell.reuseIdentifier == "toggleCell" { let toggleCell: ToggleCell = cell as! ToggleCell toggleCell.titleLabel.text = filter.properties[indexPath.row].title toggleCell.delegate = self if let key = filter.properties[indexPath.row].key { if let isOn = filter.value(forKey: key) as? Bool { toggleCell.toggleSwitch.isOn = isOn } } } else if cell.reuseIdentifier == "pickerCell" { let pickerCell: PickerCell = cell as! PickerCell pickerCell.titleLabel.text = filter.properties[indexPath.row].title pickerCell.selectionItems = filter.properties[indexPath.row].selectionItems! pickerCell.delegate = self } } // MARK: Delegate func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let cell = tableView.cellForRow(at: indexPath) if cell?.reuseIdentifier == "resetCell" { filter.reset() } else if cell?.reuseIdentifier == "imageCell" { let navigationController = parent as! UINavigationController // let mainViewController = navigationController?.parentViewController as? MainViewController let imagePicker = UIImagePickerController() imagePicker.delegate = self navigationController.present(imagePicker, animated: true, completion: nil) } } // MARK: SettingsCell Delegate func settingsCellSliderValueChanged(_ sender: SettingsCell, value: Float) { let indexPath = tableView.indexPath(for: sender) let property: Property = filter.properties[(indexPath?.row)!] if property.propertyType == .value { sender.valueLabel.text = String(format: "%.2f", value) filter.setValue(value, forKey: property.key) } else if property.propertyType == .color { sender.valueLabel.text = "-" filter.setValue(sender.currentColor(), forKey: property.key) } } // MARK: PickerCell Delegate func pickerCellDidSelectItem(_ sender: PickerCell, index: Int) { let indexPath = tableView.indexPath(for: sender) let property: Property = filter.properties[(indexPath?.row)!] filter.setValue(index, forKey: property.key) } // MARK: ToggleCell Delegate func toggleValueChanged(sender: ToggleCell, isOn: Bool) { let indexPath = tableView.indexPath(for: sender) let property: Property = filter.properties[(indexPath?.row)!] filter.setValue(isOn, forKey: property.key) } // MARK: ImagePickerController Delegate func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { for property in filter.properties { if property.propertyType == .image { if let image: UIImage = info[UIImagePickerControllerOriginalImage] as? UIImage { filter.setValue(image, forKey: property.key) dismiss(animated: true, completion: nil) return } } } dismiss(animated: true, completion: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } /* // 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. } */ }
1361e50d31c5b1dfc376dca4d608a50d
35.516949
127
0.613367
false
false
false
false