repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
mamaz/gym-timer
GymTimer/AppDelegate.swift
1
2869
// // AppDelegate.swift // GymTimer // // Created by Hisma Mulya S on 11/10/16. // Copyright © 2016 mamaz. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? lazy var flowController = GTFlowController() lazy var setupViewModel = GTSetupViewModel() func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { self.window = { let window = UIWindow(frame: UIScreen.main.bounds) let setupViewController = GTSetupViewController(flowController: self.flowController, viewModel: self.setupViewModel) let navigationController = UINavigationController(rootViewController: setupViewController) self.flowController.configureSetupViewController(setupViewController: setupViewController, navigationController: navigationController) window.rootViewController = navigationController window.makeKeyAndVisible() return window }() 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:. } // privates }
mit
f3099dd4cd018ec5116f205a5ea62c0f
46.016393
285
0.73152
5.92562
false
false
false
false
ancode-cn/Meizhi
Meizhi/Classes/business/day/DayListTableViewController.swift
1
10290
// // DayListTableViewController.swift // Meizhi // // Created by snowleft on 15/9/24. // Copyright © 2015年 ancode. All rights reserved. // import UIKit class DayListTableViewController: UITableViewController { private var categoryInfo:CategoryInfo = CategoryInfo(title: "每日一弹", url: Constant.URL_DAY_LIST) private static let PAGE_SIZE = "20" private var page = 0 private var list:[DataItem]? private var estimatedCell:DayListCell? private var refreshType:RefreshType = RefreshType.PULL_DOWN private var contentInset:UIEdgeInsets? func setUIEdgeInsets(contentInset:UIEdgeInsets?){ self.contentInset = contentInset } override func viewDidLoad() { super.viewDidLoad() title = categoryInfo.title print("DayListTableViewController=====>\(title)") estimatedCell = instanceEstimatedCell() initTableView() initMJRefresh() } private func initTableView(){ // 去除cell分割线 //tableView.separatorStyle = UITableViewCellSeparatorStyle.None tableView.dataSource = self tableView.delegate = self // 设置tableView显示区域 if contentInset != nil{ tableView.contentInset = contentInset! }else{ tableView.contentInset = UIEdgeInsetsMake(0, 0, Constant.FOOTER_HEIGHT, 0) } // 隐藏多余的分割线 tableView.tableFooterView = UIView() // 注册xib let nib = UINib(nibName: "DayListCell", bundle: nil) self.tableView.registerNib(nib, forCellReuseIdentifier: "DayListCell") } // MARK: - Table view data source override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return list?.count ?? 0 } // cell绑定数据 override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("DayListCell", forIndexPath: indexPath) as! DayListCell configureCell(cell, indexPath: indexPath, isCalculateHeight: false) return cell } private func configureCell(cell:DayListCell,indexPath:NSIndexPath, isCalculateHeight:Bool){ if (indexPath.row % 2 == 0) { cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator; } else { cell.accessoryType = UITableViewCellAccessoryType.Checkmark; } let data = list?[indexPath.row] cell.bindData(data, indexPath: indexPath, isCalculateHeight: isCalculateHeight) } // 计算cell高度dde override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { // 自动计算方式 let height = tableView.fd_heightForCellWithIdentifier("DayListCell", cacheByIndexPath: indexPath) { (cell) -> Void in self.configureCell(cell as! DayListCell, indexPath: indexPath, isCalculateHeight: true) } print("height=============\(height)") return height // 手动计算方式 // let height = estimatedCellHeight(indexPath) // return height } // 估算cell高度 override func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 317.5 } // 处理cell line左边界不全问题 override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { // ios7.0+处理方式 cell.separatorInset = UIEdgeInsetsZero // ios8.0+需附加配置 if #available(iOS 8.0, *) { cell.preservesSuperviewLayoutMargins = false cell.layoutMargins = UIEdgeInsetsZero } else { // Fallback on earlier versions } } } // MARK: - TableViewCell处理器 extension DayListTableViewController:TableViewCellHandler{ // 实例化用于计算的TableViewCell func instanceEstimatedCell<DayListCell>() -> DayListCell?{ let cell:DayListCell = NSBundle.mainBundle().loadNibNamed("DayListCell", owner: nil, options: nil).last as! DayListCell // 不要使用以下方式,可能会造成内存泄露. // let cell = tableView.dequeueReusableCellWithIdentifier("DayListCell") as! DayListCell return cell } // 计算cell高度 func estimatedCellHeight(indexPath: NSIndexPath) -> CGFloat{ var height:CGFloat? if let categoryItem = list?[indexPath.row]{ height = categoryItem.cellHeight if height != nil{ return height ?? 0 } estimatedCell?.bindData(categoryItem, indexPath: indexPath, isCalculateHeight: true) height = estimatedCell!.contentView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height // height = CGRectGetMaxY(estimatedCell!.lb_who.frame) + 1 categoryItem.cellHeight = height print(height) } return height ?? 0 } } // MARK: - 下拉刷新 extension DayListTableViewController{ private func initMJRefresh(){ weak var weakSelf:DayListTableViewController? = self tableView.header = MJRefreshNormalHeader(refreshingBlock: { () -> Void in weakSelf?.refreshType = RefreshType.PULL_DOWN weakSelf?.page = 1 weakSelf?.loadData() }) let footer:MJRefreshAutoNormalFooter = MJRefreshAutoNormalFooter(refreshingBlock: { () -> Void in weakSelf?.refreshType = RefreshType.LOAD_MORE weakSelf?.loadData() }) footer.automaticallyRefresh = true tableView.footer = footer tableView.header.beginRefreshing() } // 停止刷新 private func endRefreshing(){ if refreshType == RefreshType.PULL_DOWN{ tableView.header.endRefreshing() }else{ tableView.footer.endRefreshing() } } } // MARK: - 数据处理 extension DayListTableViewController{ // 从网络/本地加载数据 private func loadData(){ let requestUrl:String = categoryInfo.url + DayListTableViewController.PAGE_SIZE + "/" + String(page) let url:String? = requestUrl.stringByAddingPercentEncodingWithAllowedCharacters(.URLQueryAllowedCharacterSet()) print(url) if url == nil{ endRefreshing() return } // 网络监测 AFNetworkReachabilityManager.sharedManager().startMonitoring() AFNetworkReachabilityManager.sharedManager().setReachabilityStatusChangeBlock { (status: AFNetworkReachabilityStatus) -> Void in print("network status=====>\(status)") } // 网络请求 weak var weakSelf = self // 弱引用self指针 let manager = AFHTTPRequestOperationManager() //使用这个将得到的是NSData manager.responseSerializer = AFHTTPResponseSerializer() //使用这个将得到的是JSON // manager.responseSerializer = AFJSONResponseSerializer() manager.GET(url, parameters: nil, success: { (operation:AFHTTPRequestOperation?, responseObject:AnyObject?) -> Void in print("responseObject type=====>\(responseObject?.classForCoder)") if responseObject != nil && responseObject is NSData{ weakSelf?.handleResponse(operation?.response, data: responseObject as? NSData) }else{ weakSelf?.endRefreshing() } }) { (operation:AFHTTPRequestOperation!, error:NSError!) -> Void in weakSelf?.endRefreshing() } } /** 处理服务器接口响应 - parameter response: NSHTTPURLResponse - parameter data: 源数据 */ private func handleResponse(response:NSHTTPURLResponse?, data:NSData?){ if response?.statusCode == 200 && data != nil{ if let list:[DataItem] = parseJson(data!){ if refreshType == RefreshType.PULL_DOWN{ self.list = list }else{ if self.list == nil{ self.list = [DataItem]() } self.list? += list } print("tableView.reloadData=====>\(list.count)") tableView.reloadData() page += 1 }else{ // no data. if refreshType == RefreshType.LOAD_MORE{ tableView.footer.noticeNoMoreData() } } } endRefreshing() } /** 解析json数据 - parameter data: 源数据 - returns: [CategoryItem] */ private func parseJson(data:NSData) -> [DataItem]?{ var list:[DataItem]? = nil do { let json = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) let error = json["error"] as? Bool if error != nil && error == false{ if let results = json["results"] as? Array<AnyObject>{ list = [DataItem]() for(var i=0; i < results.count; i++){ if let dic = results[i] as? NSDictionary{ let item = DataItem(fromDictionary: dic) // test item.desc = "这是一条测试描述" if i > 0{ item.desc! += list![i - 1].desc item.desc! += "abcdefghijklmnopqrstuvwxyz" } if i % 2 == 0{ item.url = nil } list?.append(item) } } } } } catch { print("parse json error!") } return list } }
mit
858fb747bdb6e2a655ec7468bc2f306c
33.716783
136
0.582335
5.372835
false
false
false
false
rene-dohan/CS-IOS
Renetik/Renetik/Classes/Core/Extensions/UIKit/UIBarButtonItem+CSExtension.swift
1
2157
// // Created by Rene Dohan on 12/18/19. // import BlocksKit import Renetik public extension UIBarButtonItem { class var flexSpaceItem: UIBarButtonItem { UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) } class var fixedSpaceItem: UIBarButtonItem { UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil) } class func space(_ width: CGFloat = 15) -> UIBarButtonItem { fixedSpaceItem.width(width) } convenience init(image: UIImage, onClick: ArgFunc<UIBarButtonItem>? = nil) { self.init() if let action = onClick { bk_init(with: image, style: UIBarButtonItem.Style.plain, handler: { _ in action(self) }) } else { self.init(image: image, style: UIBarButtonItem.Style.plain, target: nil, action: nil) } } convenience init(image: UIImage, onClick: Func? = nil) { self.init(image: image, onClick: { _ in onClick?() }) } convenience init(view: UIView, onClick: ArgFunc<UIBarButtonItem>? = nil) { self.init(customView: view) if let action = onClick { view.onClick { action(self) } } } convenience init(view: UIView, onClick: @escaping Func) { self.init(customView: view) view.onClick { onClick() } } convenience init(item: UIBarButtonItem.SystemItem, onClick: ((_ sender: UIBarButtonItem) -> Void)? = nil) { self.init() if let action = onClick { bk_init(with: item, handler: { action($0 as! UIBarButtonItem) }) } else { self.init(barButtonSystemItem: item, target: nil, action: nil) } } convenience init(title: String, onClick: ((_ sender: UIBarButtonItem) -> Void)? = nil) { self.init() if let action = onClick { bk_init(withTitle: title, style: UIBarButtonItem.Style.plain, handler: { action($0 as! UIBarButtonItem) }) } else { self.init(title: title, style: UIBarButtonItem.Style.plain, target: nil, action: nil) } } func width(_ value: CGFloat) -> Self { invoke { width = value } } }
mit
8babb5802c6389cecafd33242bba03ac
33.253968
111
0.616134
4.212891
false
false
false
false
salemoh/GoldenQuraniOS
GoldenQuranSwift/Pods/GRDB.swift/GRDB/Migrations/Migration.swift
2
3612
/// An internal struct that defines a migration. struct Migration { let identifier: String let disabledForeignKeyChecks: Bool let migrate: (Database) throws -> Void #if USING_CUSTOMSQLITE || USING_SQLCIPHER init(identifier: String, disabledForeignKeyChecks: Bool = false, migrate: @escaping (Database) throws -> Void) { self.identifier = identifier self.disabledForeignKeyChecks = disabledForeignKeyChecks self.migrate = migrate } #else init(identifier: String, migrate: @escaping (Database) throws -> Void) { self.identifier = identifier self.disabledForeignKeyChecks = false self.migrate = migrate } @available(iOS 8.2, OSX 10.10, *) // PRAGMA foreign_key_check was introduced in SQLite 3.7.16 http://www.sqlite.org/changes.html#version_3_7_16 // It is available from iOS 8.2 and OS X 10.10 https://github.com/yapstudios/YapDatabase/wiki/SQLite-version-(bundled-with-OS) init(identifier: String, disabledForeignKeyChecks: Bool, migrate: @escaping (Database) throws -> Void) { self.identifier = identifier self.disabledForeignKeyChecks = disabledForeignKeyChecks self.migrate = migrate } #endif func run(_ db: Database) throws { if try disabledForeignKeyChecks && (Bool.fetchOne(db, "PRAGMA foreign_keys") ?? false) { try runWithDisabledForeignKeys(db) } else { try runWithoutDisabledForeignKeys(db) } } private func runWithoutDisabledForeignKeys(_ db: Database) throws { try db.inTransaction(.immediate) { try migrate(db) try insertAppliedIdentifier(db) return .commit } } private func runWithDisabledForeignKeys(_ db: Database) throws { // Support for database alterations described at // https://www.sqlite.org/lang_altertable.html#otheralter // // > 1. If foreign key constraints are enabled, disable them using // > PRAGMA foreign_keys=OFF. try db.execute("PRAGMA foreign_keys = OFF") // > 2. Start a transaction. try db.inTransaction(.immediate) { try migrate(db) try insertAppliedIdentifier(db) // > 10. If foreign key constraints were originally enabled then run PRAGMA // > foreign_key_check to verify that the schema change did not break any foreign key // > constraints. if try Row.fetchOne(db, "PRAGMA foreign_key_check") != nil { // https://www.sqlite.org/pragma.html#pragma_foreign_key_check // // PRAGMA foreign_key_check does not return an error, // but the list of violated foreign key constraints. // // Let's turn any violation into an SQLITE_CONSTRAINT // error, and rollback the transaction. throw DatabaseError(resultCode: .SQLITE_CONSTRAINT, message: "FOREIGN KEY constraint failed") } // > 11. Commit the transaction started in step 2. return .commit } // > 12. If foreign keys constraints were originally enabled, reenable them now. try db.execute("PRAGMA foreign_keys = ON") } private func insertAppliedIdentifier(_ db: Database) throws { try db.execute("INSERT INTO grdb_migrations (identifier) VALUES (?)", arguments: [identifier]) } }
mit
3bb3b0c413ffa4d2cdde50de35612a30
41.494118
134
0.607143
4.758893
false
false
false
false
jkereako/MassStateKeno
Sources/Models/DrawingModel.swift
1
656
// // DrawingModel.swift // MassLotteryKeno // // Created by Jeff Kereakoglow on 5/18/19. // Copyright © 2019 Alexis Digital. All rights reserved. // import Foundation struct DrawingModel { let id: Int let drawDate: Date let numbers: [Int] let bonus: Int init(contract: DrawingContract, dateFormatter: DateFormatter) { dateFormatter.dateFormat = "mm/dd/yyyy" id = Int(contract.id) ?? 0 drawDate = dateFormatter.date(from: contract.drawDate) ?? Date() numbers = contract.winningNumbers.split(separator: "-").map { Int(String($0)) ?? 0 } bonus = Int(contract.bonusMultiplier) ?? 0 } }
mit
fc5d19f7a030c12ca46354666f56e5a8
25.2
92
0.648855
3.830409
false
false
false
false
avito-tech/Paparazzo
Paparazzo/Core/VIPER/PhotoLibraryV2/Presenter/PhotoLibraryV2Presenter.swift
1
21150
import Foundation final class PhotoLibraryV2Presenter: PhotoLibraryV2Module { // MARK: - Dependencies private let interactor: PhotoLibraryV2Interactor private let router: PhotoLibraryV2Router private let overridenTheme: PaparazzoUITheme private let isNewFlowPrototype: Bool weak var mediaPickerModule: MediaPickerModule? weak var view: PhotoLibraryV2ViewInput? { didSet { view?.onViewDidLoad = { [weak self] in self?.onViewDidLoad?() self?.setUpView() } } } // MARK: - Config private let shouldAllowFinishingWithNoPhotos: Bool // MARK: - State private var shouldScrollToTopOnFullReload = true private var continueButtonPlacement: MediaPickerContinueButtonPlacement? private var continueButtonTitle: String? // MARK: - Init init( interactor: PhotoLibraryV2Interactor, router: PhotoLibraryV2Router, overridenTheme: PaparazzoUITheme, isNewFlowPrototype: Bool) { self.interactor = interactor self.router = router self.overridenTheme = overridenTheme self.isNewFlowPrototype = isNewFlowPrototype self.shouldAllowFinishingWithNoPhotos = !interactor.selectedItems.isEmpty if isNewFlowPrototype { interactor.observeSelectedItemsChange { [weak self] in self?.adjustSelectedPhotosBar() } } } // MARK: - PhotoLibraryV2Module var onItemsAdd: (([MediaPickerItem], _ startIndex: Int) -> ())? var onItemUpdate: ((MediaPickerItem, _ index: Int?) -> ())? var onItemAutocorrect: ((MediaPickerItem, _ isAutocorrected: Bool, _ index: Int?) -> ())? var onItemMove: ((_ sourceIndex: Int, _ destinationIndex: Int) -> ())? var onItemRemove: ((MediaPickerItem, _ index: Int?) -> ())? var onCropFinish: (() -> ())? var onCropCancel: (() -> ())? var onContinueButtonTap: (() -> ())? var onViewDidLoad: (() -> ())? var onCancel: (() -> ())? var onFinish: (([MediaPickerItem]) -> ())? var onNewCameraShow: (() -> ())? func setContinueButtonTitle(_ title: String) { continueButtonTitle = title updateContinueButtonTitle() } func setContinueButtonEnabled(_ enabled: Bool) { mediaPickerModule?.setContinueButtonEnabled(enabled) } func setContinueButtonVisible(_ visible: Bool) { mediaPickerModule?.setContinueButtonVisible(visible) } func setContinueButtonStyle(_ style: MediaPickerContinueButtonStyle) { mediaPickerModule?.setContinueButtonStyle(style) view?.setContinueButtonStyle(style) } func setContinueButtonPlacement(_ placement: MediaPickerContinueButtonPlacement) { continueButtonPlacement = placement view?.setContinueButtonPlacement(placement) } public func setCameraTitle(_ title: String) { mediaPickerModule?.setCameraTitle(title) } public func setCameraSubtitle(_ subtitle: String) { mediaPickerModule?.setCameraSubtitle(subtitle) } public func setCameraHint(data: CameraHintData) { mediaPickerModule?.setCameraHint(data: data) } public func setAccessDeniedTitle(_ title: String) { mediaPickerModule?.setAccessDeniedTitle(title) } public func setAccessDeniedMessage(_ message: String) { mediaPickerModule?.setAccessDeniedMessage(message) } public func setAccessDeniedButtonTitle(_ title: String) { mediaPickerModule?.setAccessDeniedButtonTitle(title) } func setCropMode(_ cropMode: MediaPickerCropMode) { mediaPickerModule?.setCropMode(cropMode) } func setThumbnailsAlwaysVisible(_ alwaysVisible: Bool) { mediaPickerModule?.setThumbnailsAlwaysVisible(alwaysVisible) } func removeItem(_ item: MediaPickerItem) { mediaPickerModule?.removeItem(item) } func focusOnModule() { router.focusOnCurrentModule() } func dismissModule() { router.dismissCurrentModule() } func finish() { mediaPickerModule?.finish() } // MARK: - Private private func setUpView() { updateContinueButtonTitle() view?.setTitleVisible(false) view?.setPlaceholderState(.hidden) view?.setAccessDeniedTitle(localized("To pick photo from library")) view?.setAccessDeniedMessage(localized("Allow %@ to access your photo library", appName())) view?.setAccessDeniedButtonTitle(localized("Allow access to photo library")) view?.setDoneButtonTitle(localized("Done")) view?.setPlaceholderText(localized("Select at least one photo")) view?.setProgressVisible(true) view?.setContinueButtonVisible(!isNewFlowPrototype) if isNewFlowPrototype { view?.onViewWillAppear = { [weak self] in DispatchQueue.main.async { self?.adjustSelectedPhotosBar() self?.view?.reloadSelectedItems() } } } interactor.observeAuthorizationStatus { [weak self] accessGranted in self?.view?.setAccessDeniedViewVisible(!accessGranted) if !accessGranted { self?.view?.setProgressVisible(false) } } interactor.observeAlbums { [weak self] albums in guard let strongSelf = self else { return } // We're showing only non-empty albums let albums = albums.filter { $0.numberOfItems > 0 } self?.view?.setAlbums(albums.map(strongSelf.albumCellData)) if let currentAlbum = strongSelf.interactor.currentAlbum, albums.contains(currentAlbum) { self?.adjustView(for: currentAlbum) // title might have been changed } else if let album = albums.first { self?.selectAlbum(album) } else { self?.view?.setTitleVisible(false) self?.view?.setPlaceholderState(.visible(title: localized("No photos"))) self?.view?.setProgressVisible(false) } } interactor.observeCurrentAlbumEvents { [weak self] event, selectionState in guard let strongSelf = self else { return } var needToShowPlaceholder: Bool switch event { case .fullReload(let items): needToShowPlaceholder = items.isEmpty self?.view?.setItems( items.map(strongSelf.cellData), scrollToTop: strongSelf.shouldScrollToTopOnFullReload, completion: { self?.shouldScrollToTopOnFullReload = false self?.adjustViewForSelectionState(selectionState) self?.view?.setProgressVisible(false) } ) case .incrementalChanges(let changes): needToShowPlaceholder = changes.itemsAfterChanges.isEmpty self?.view?.applyChanges(strongSelf.viewChanges(from: changes), completion: { self?.adjustViewForSelectionState(selectionState) }) } self?.view?.setPlaceholderState( needToShowPlaceholder ? .visible(title: localized("Album is empty")) : .hidden ) } view?.onContinueButtonTap = { [weak self] in guard let strongSelf = self else { return } let selectedItems = strongSelf.interactor.selectedItems guard selectedItems.isEmpty == false else { strongSelf.onFinish?([]) return } let startIndex = 0 self?.onItemsAdd?( selectedItems, startIndex ) guard !strongSelf.isNewFlowPrototype else { strongSelf.onFinish?(selectedItems) return } let data = strongSelf.interactor.mediaPickerData.bySettingMediaPickerItems(selectedItems) self?.router.showMediaPicker( data: data, overridenTheme: strongSelf.overridenTheme, isNewFlowPrototype: strongSelf.isNewFlowPrototype, configure: { [weak self] module in self?.configureMediaPicker(module) } ) } view?.onCloseButtonTap = { [weak self] in self?.onCancel?() } view?.onAccessDeniedButtonTap = { if let url = URL(string: UIApplication.openSettingsURLString) { UIApplication.shared.openURL(url) } } view?.onLastPhotoThumbnailTap = { [weak self] in self?.showMediaPickerInNewFlow() } view?.onTitleTap = { [weak self] in self?.view?.toggleAlbumsList() } view?.onDimViewTap = { [weak self] in self?.view?.hideAlbumsList() } interactor.observeDeviceOrientation { [weak self] orientation in self?.cameraViewData { [weak self] viewData in self?.view?.setCameraViewData(viewData) } } } private func showMediaPickerInNewFlow() { let data = interactor.mediaPickerData .bySettingMediaPickerItems(interactor.selectedItems) .bySelectingLastItem() router.showMediaPicker( data: data, overridenTheme: overridenTheme, isNewFlowPrototype: true, configure: { [weak self] module in self?.configureMediaPicker(module) module.onFinish = { _ in self?.router.focusOnCurrentModule() } } ) } private func updateContinueButtonTitle() { let title = interactor.selectedItems.isEmpty ? localized("Continue") : localized("Select") view?.setContinueButtonTitle(continueButtonTitle ?? title) } private func appName() -> String { return Bundle.main.infoDictionary?[kCFBundleNameKey as String] as? String ?? "" } private func adjustViewForSelectionState(_ state: PhotoLibraryItemSelectionState) { view?.setDimsUnselectedItems(!state.canSelectMoreItems) view?.setCanSelectMoreItems(state.canSelectMoreItems) switch state.preSelectionAction { case .none: break case .deselectAll: view?.deselectAllItems() } } private func albumCellData(for album: PhotoLibraryAlbum) -> PhotoLibraryAlbumCellData { return PhotoLibraryAlbumCellData( identifier: album.identifier, title: album.title ?? localized("Unnamed album"), coverImage: album.coverImage, onSelect: { [weak self] in self?.selectAlbum(album) self?.view?.hideAlbumsList() } ) } private func selectAlbum(_ album: PhotoLibraryAlbum) { shouldScrollToTopOnFullReload = true interactor.setCurrentAlbum(album) adjustView(for: album) } private func adjustView(for album: PhotoLibraryAlbum) { view?.setTitle(album.title ?? localized("Unnamed album")) view?.setTitleVisible(true) view?.selectAlbum(withId: album.identifier) } private func cellData(_ item: PhotoLibraryItem) -> PhotoLibraryItemCellData { let mediaPickerItem = MediaPickerItem(item) let getSelectionIndex = { [weak self] in self?.interactor.selectedItems.firstIndex(of: mediaPickerItem).flatMap { $0 + 1 } } var cellData = PhotoLibraryItemCellData( image: item.image, getSelectionIndex: isNewFlowPrototype ? getSelectionIndex : nil ) cellData.selected = interactor.isSelected(mediaPickerItem) cellData.onSelectionPrepare = { [weak self] in if let selectionState = self?.interactor.prepareSelection() { self?.adjustViewForSelectionState(selectionState) } } cellData.onSelect = { [weak self] in if let selectionState = self?.interactor.selectItem(mediaPickerItem) { self?.adjustViewForSelectionState(selectionState) } if self?.isNewFlowPrototype == false { self?.view?.setHeaderVisible(false) } self?.updateContinueButtonTitle() } cellData.onDeselect = { [weak self] in self?.handleItemDeselect(mediaPickerItem) } return cellData } private func handleItemDeselect(_ item: MediaPickerItem) { let selectionState = interactor.deselectItem(item) adjustViewForSelectionState(selectionState) if isNewFlowPrototype { view?.reloadSelectedItems() } else { view?.setHeaderVisible(interactor.selectedItems.isEmpty) } updateContinueButtonTitle() } private func cameraViewData(completion: @escaping (_ viewData: PhotoLibraryCameraViewData?) -> ()) { interactor.getOutputParameters { [shouldAllowFinishingWithNoPhotos] parameters in let viewData = PhotoLibraryCameraViewData( parameters: parameters, onTap: { [weak self] in guard let strongSelf = self else { return } if strongSelf.isNewFlowPrototype { self?.onNewCameraShow?() self?.router.showNewCamera( selectedImagesStorage: strongSelf.interactor.selectedPhotosStorage, mediaPickerData: strongSelf.interactor.mediaPickerData, shouldAllowFinishingWithNoPhotos: shouldAllowFinishingWithNoPhotos, configure: { [weak self] newCameraModule in newCameraModule.configureMediaPicker = { mediaPickerModule in self?.configureMediaPicker(mediaPickerModule) mediaPickerModule.onFinish = { [weak newCameraModule] _ in newCameraModule?.focusOnModule() } } newCameraModule.onFinish = { module, result in switch result { case .finished: self?.view?.onContinueButtonTap?() case .cancelled: self?.router.focusOnCurrentModule() } } } ) } else { self?.router.showMediaPicker( data: strongSelf.interactor.mediaPickerData.byDisablingLibrary(), overridenTheme: strongSelf.overridenTheme, isNewFlowPrototype: strongSelf.isNewFlowPrototype, configure: { [weak self] module in self?.configureMediaPicker(module) } ) } } ) completion(viewData) } } private func configureMediaPicker(_ module: MediaPickerModule) { mediaPickerModule = module if let continueButtonPlacement = continueButtonPlacement { module.setContinueButtonPlacement(continueButtonPlacement) } if let continueButtonTitle = continueButtonTitle { module.setContinueButtonTitle(continueButtonTitle) } module.onItemsAdd = onItemsAdd module.onItemUpdate = onItemUpdate module.onItemAutocorrect = { [weak self] item, isAutocorrected, index in if let index = index { self?.interactor.replaceSelectedItem(at: index, with: item) } self?.onItemAutocorrect?(item, isAutocorrected, index) } module.onItemMove = { [weak self] sourceIndex, destinationIndex in self?.interactor.moveSelectedItem(at: sourceIndex, to: destinationIndex) self?.onItemMove?(sourceIndex, destinationIndex) } module.onItemRemove = { [weak self] mediaPickerItem, index in if self?.view?.deselectItem(with: mediaPickerItem.image) == false { // Кейс, когда удаляется "виртуальная" фотка (серверная, которой нет в галерее) self?.handleItemDeselect(mediaPickerItem) } if let originalItem = mediaPickerItem.originalItem { // Кейс, когда удаляется фотка, на которую наложен фильтр // (вьюха не знает про связь измененной фотки с оригинальной) self?.view?.deselectItem(with: originalItem.image) } self?.onItemRemove?(mediaPickerItem, index) } module.onCropFinish = onCropFinish module.onCropCancel = onCropCancel module.onContinueButtonTap = onContinueButtonTap module.onFinish = onFinish module.onCancel = { [weak module] in module?.dismissModule() } } private func viewChanges(from changes: PhotoLibraryChanges) -> PhotoLibraryViewChanges { return PhotoLibraryViewChanges( removedIndexes: changes.removedIndexes, insertedItems: changes.insertedItems.map { (index: $0, cellData: cellData($1)) }, updatedItems: changes.updatedItems.map { (index: $0, cellData: cellData($1)) }, movedIndexes: changes.movedIndexes ) } func adjustSelectedPhotosBar() { let images = interactor.selectedItems view?.setSelectedPhotosBarState(images.isEmpty ? (shouldAllowFinishingWithNoPhotos ? .placeholder : .hidden) : .visible(SelectedPhotosBarData( lastPhoto: images.last?.image, penultimatePhoto: images.count > 1 ? images[images.count - 2].image : nil, countString: "\(images.count) фото" )) ) } } extension MediaPickerData { func bySettingMediaPickerItems(_ mediaPickerItems: [MediaPickerItem]) -> MediaPickerData { return MediaPickerData( items: mediaPickerItems, autocorrectionFilters: autocorrectionFilters, selectedItem: mediaPickerItems.first ?? selectedItem, maxItemsCount: maxItemsCount, cropEnabled: cropEnabled, autocorrectEnabled: autocorrectEnabled, hapticFeedbackEnabled: hapticFeedbackEnabled, cropCanvasSize: cropCanvasSize, initialActiveCameraType: initialActiveCameraType, cameraEnabled: false, photoLibraryEnabled: false ) } func bySelectingLastItem() -> MediaPickerData { return MediaPickerData( items: items, autocorrectionFilters: autocorrectionFilters, selectedItem: items.last, maxItemsCount: maxItemsCount, cropEnabled: cropEnabled, autocorrectEnabled: autocorrectEnabled, hapticFeedbackEnabled: hapticFeedbackEnabled, cropCanvasSize: cropCanvasSize, initialActiveCameraType: initialActiveCameraType, cameraEnabled: cameraEnabled, photoLibraryEnabled: photoLibraryEnabled ) } func byDisablingLibrary() -> MediaPickerData { return MediaPickerData( items: items, autocorrectionFilters: autocorrectionFilters, selectedItem: selectedItem, maxItemsCount: maxItemsCount, cropEnabled: cropEnabled, autocorrectEnabled: autocorrectEnabled, hapticFeedbackEnabled: hapticFeedbackEnabled, cropCanvasSize: cropCanvasSize, initialActiveCameraType: initialActiveCameraType, cameraEnabled: cameraEnabled, photoLibraryEnabled: false ) } }
mit
cfa3b6a4f356a31107ca77caaff25867
35.957746
104
0.57741
5.72301
false
false
false
false
ipraba/Bean
Example/Bean/ViewController.swift
1
4868
// // ViewController.swift // Bean // // Created by Prabaharan on 12/17/2015. // Copyright (c) 2015 Prabaharan. All rights reserved. // import UIKit import Bean class ViewController: UICollectionViewController { let queue = NSOperationQueue() var photos = [FlickrObject]() var currentPage = 1 override func viewDidLoad() { super.viewDidLoad() self.title = "#Mindvalley" self.navigationController?.navigationBar.barTintColor = Colors.PumpkinColor fetchImages() // Do any additional setup after loading the view, typically from a nib. } func fetchImages(){ fetchImagesForText("Mindvalley", page: currentPage) { (results, error) -> Void in print(results) if error == nil && results != nil { self.photos.appendContentsOf(results!) dispatch_async(dispatch_get_main_queue(), { () -> Void in self.collectionView?.reloadData() }) } else{ self.showAlert("Error in Fetching data from Flickr") } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //Collection view delegates override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return photos.count } override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! ImagesCell let photo = photos[indexPath.row] let flickrURl = photo.flickrImageURL() cell.imgFlicker.image = nil //The reason for not using the Bean ImageView extension is //When scrolling very fast in a collectionView or Tableview the image requests sent will start updating the imageview for all reusable cell. This will lead to a flickering effect in cells. //Solution extracted from this post http://stackoverflow.com/questions/16663618/async-image-loading-from-url-inside-a-uitableview-cell-image-changes-to-wrong Bean.download(flickrURl).getImage { (url, image, error) -> Void in if let currentCell = collectionView.cellForItemAtIndexPath(indexPath) as? ImagesCell{ currentCell.imgFlicker.image = image } } if indexPath.row == photos.count-1 { //Last Cell //Fetch next set of images currentPage++ fetchImages() } return cell } override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView { if kind == UICollectionElementKindSectionFooter { let header = collectionView.dequeueReusableSupplementaryViewOfKind(UICollectionElementKindSectionFooter, withReuseIdentifier: "Footer", forIndexPath: indexPath) return header; } return UICollectionReusableView() } func fetchImagesForText(text: String, page: Int, completion : (results: [FlickrObject]?, error : NSError?) -> Void) { let escapedTerm = text.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())! //Flickr API search string should be escaped let URLString = "https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=\(FlickrConstants.apiKey)&text=\(escapedTerm)&per_page=20&page=\(page)&format=json&nojsoncallback=1" let request = NSURLRequest(URL: NSURL(string: URLString)!) NSURLConnection.sendAsynchronousRequest(request, queue: queue) {response, data, error in if error == nil { do { let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! NSDictionary var photos = [FlickrObject]() //Converting into models for photo in json["photos"]!["photo"] as! [[String: AnyObject]] { photos.append(FlickrObject(dict: photo)) } completion(results: photos, error: nil) } catch let jsonError as NSError { completion(results: nil,error: jsonError) } return } completion(results: nil,error: error) } } }
mit
51a002abefd4a875e0ca6f2c4652fe78
39.231405
199
0.633525
5.531818
false
false
false
false
VoIPGRID/vialer-ios
Vialer/Calling/SIP/Controllers/SetupCallTransferDialPadViewController.swift
1
6386
// // SetupCallTransferViewController.swift // Copyright © 2016 VoIPGRID. All rights reserved. // private var myContext = 0 class SetupCallTransferDialPadViewController: SetupCallTransfer, SegueHandler { var currentCallPhoneNumberLabelText: String? var number: String { set { numberToDialLabel?.text = newValue updateUI() } get { return numberToDialLabel.text! } } // MARK: - Outlets @IBOutlet weak var firstCallNumberLabel: UILabel! @IBOutlet weak var firstCallStatusLabel: UILabel! @IBOutlet weak var deleteButton: UIButton! @IBOutlet weak var callButton: UIButton! @IBOutlet weak var numberToDialLabel: UILabel! { didSet { numberToDialLabel.text = "" } } override func updateUI() { firstCallNumberLabel?.text = firstCallPhoneNumberLabelText callButton?.isEnabled = number != "" deleteButton?.isEnabled = number != "" toggleDeleteButton() guard let call = firstCall else { return } if call.callState == .disconnected { firstCallStatusLabel?.text = NSLocalizedString("Disconnected", comment: "Disconnected phone state") } else { firstCallStatusLabel?.text = NSLocalizedString("On hold", comment: "On hold") } } } // MARK: - Lifecycle extension SetupCallTransferDialPadViewController { override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // This fixes the transparent-line-on-navigation-bar bug self.navigationController?.navigationBar.barTintColor = UIColor(red: 0.968627, green: 0.968627, blue: 0.968627, alpha: 1) firstCall?.addObserver(self, forKeyPath: "callState", options: .new, context: &myContext) firstCall?.addObserver(self, forKeyPath: "mediaState", options: .new, context: &myContext) callObserversSet = true VialerGAITracker.trackScreenForController(name: controllerName) updateUI() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) if callObserversSet { firstCall?.removeObserver(self, forKeyPath: "callState") firstCall?.removeObserver(self, forKeyPath: "mediaState") callObserversSet = false } } } // MARK: - Actions extension SetupCallTransferDialPadViewController { @IBAction func backButtonPressed(_ sender: AnyObject) { guard let call = currentCall else { DispatchQueue.main.async { self.performSegue(segueIdentifier: .unwindToFirstCall) } return } callManager.end(call) { error in if error != nil { VialerLogError("Could not hangup call: \(String(describing: error))") } else { DispatchQueue.main.async { self.performSegue(segueIdentifier: .unwindToFirstCall) } } } } @IBAction func deleteButtonPressed(_ sender: UIButton) { number = String(number.dropLast()) } @IBAction func deleteButtonLongPress(_ sender: UILongPressGestureRecognizer) { if sender.state == .began { number = "" } } @IBAction func keypadButtonPressed(_ sender: NumberPadButton) { number = number + sender.number } @IBAction func callButtonPressed(_ sender: UIButton) { callButton.isEnabled = false guard let number = numberToDialLabel.text, number != "" else { callButton.isEnabled = true return } let cleanedPhoneNumber = PhoneNumberUtils.cleanPhoneNumber(number) ?? "" currentCallPhoneNumberLabelText = cleanedPhoneNumber callManager.startCall(toNumber: cleanedPhoneNumber, for: firstCall!.account!) { call, error in DispatchQueue.main.async { [weak self] in self?.currentCall = call self?.performSegue(segueIdentifier: .secondCallActive) } } } @IBAction func zeroButtonLongPress(_ sender: UILongPressGestureRecognizer) { if sender.state == .began { number = number + "+" } } } // MARK: - Helper functions extension SetupCallTransferDialPadViewController { private func toggleDeleteButton () { UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseIn, animations: { self.deleteButton?.alpha = self.number.count == 0 ? 0.0 : 1.0 }, completion:nil) } } // MARK: - Segues extension SetupCallTransferDialPadViewController { override func prepare(for segue: UIStoryboardSegue, sender: Any?) { switch segueIdentifier(segue: segue) { case .secondCallActive: // The second call is active and is a subtype of SIPCallingVC, so cast the destination to it. let secondCallVC = segue.destination as! SecondCallViewController secondCallVC.activeCall = currentCall secondCallVC.firstCall = firstCall secondCallVC.phoneNumberLabelText = currentCallPhoneNumberLabelText secondCallVC.firstCallPhoneNumberLabelText = firstCallPhoneNumberLabelText case .unwindToFirstCall: let callVC = segue.destination as! SIPCallingViewController if let call = currentCall, call.callState != .null && call.callState != .disconnected { callVC.activeCall = call } else if let call = firstCall, call.callState != .null && call.callState != .disconnected { callVC.activeCall = call } } } } // MARK: - KVO extension SetupCallTransferDialPadViewController { override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if context == &myContext { DispatchQueue.main.async { [weak self] in self?.updateUI() if let call = self?.firstCall, call.callState == .disconnected { self?.performSegue(segueIdentifier: .unwindToFirstCall) } } } else { super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context) } } }
gpl-3.0
48cc5699bc6892713d085933d5fc2c7e
35.278409
151
0.628974
4.96115
false
false
false
false
sunsunai/coffee-app
RestaurantMap/ListPlaceVC.swift
1
2388
// // ListPlaceVCV.swift // RestaurantMap // // Created by Vinh The on 4/6/17. // Copyright © 2017 Vinh The. All rights reserved. // import UIKit let appDelegate = UIApplication.shared.delegate as! AppDelegate class ListPlaceVC: UIViewController, DataControllableProtocol { public var cellNibName: String = "ListPlaceCell" public var data: [District] = [District]() public var dataViewable: DataViewableProtocol{ return tableView } var places = [Place]() @IBOutlet weak var gribView: UIView! @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() tableView.delegate = self appDelegate.mapVC.delegate = self // Do any additional setup after loading the view. setupInterface() gribView.layer.cornerRadius = 5.0 tableView.contentInset = UIEdgeInsetsMake(0, 0, 20, 0) } } extension ListPlaceVC: MapVCProtocol{ func placesResult(places: [Place]) { self.places = places tableView.reloadData() } } extension ListPlaceVC: UITableViewDataSource{ func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return places.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView[indexPath] as! ListPlaceCell cell.configureCell(place: places[indexPath.row]) return cell } } extension ListPlaceVC: UITableViewDelegate{ func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 85.0 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let detailPlace = storyboard?.instantiateViewController(withIdentifier: "DetailVC") as! DetailVC detailPlace.place = places[indexPath.row] present(detailPlace, animated: true, completion: nil) } } extension ListPlaceVC: PulleyDrawerViewControllerDelegate{ public func supportedDrawerPositions() -> [PulleyPosition] { return PulleyPosition.all } public func partialRevealDrawerHeight() -> CGFloat { return view.bounds.height / 2.5 } func collapsedDrawerHeight() -> CGFloat { return 20.0 } func drawerPositionDidChange(drawer: PulleyViewController) { if drawer.drawerPosition == .open { print("open pully") tableView.isScrollEnabled = true } } }
mit
dd4e7066eca625a2b385a26ea2106a83
25.522222
100
0.714705
4.436803
false
false
false
false
kdawgwilk/vapor
Sources/Vapor/Validation/Convenience/Compare.swift
2
1563
/** Validate a comparable - greaterThan: validate input is > associated value - greaterThanOrEqual: validate input is >= associated value - lessThan: validate input is < associated value - lessThanOrEqual: validate input is <= associated value - equals: validate input == associated value - containedIn: validate low <= input && input <= high */ public enum Compare<ComparableType where ComparableType: Comparable, ComparableType: Validatable>: Validator { public typealias InputType = ComparableType case greaterThan(ComparableType) case greaterThanOrEqual(ComparableType) case lessThan(ComparableType) case lessThanOrEqual(ComparableType) case equals(ComparableType) case containedIn(low: ComparableType, high: ComparableType) /** Validate that a string passes associated compare evaluation - parameter value: input string to validate - throws: an error if validation fails */ public func validate(input value: InputType) throws { switch self { case .greaterThan(let c) where value > c: break case .greaterThanOrEqual(let c) where value >= c: break case .lessThan(let c) where value < c: break case .lessThanOrEqual(let c) where value <= c: break case .equals(let e) where value == e: break case .containedIn(low: let l, high: let h) where l <= value && value <= h: break default: throw error(with: value) } } }
mit
11e5edbb81659e850f81c22010f21154
32.978261
110
0.650672
5.025723
false
false
false
false
capnslipp/IntN
Sources/Int2/Int2+_ObjectiveCBridgeable.swift
1
1510
// Vuckt // @author: Slipp Douglas Thompson // @license: Public Domain per The Unlicense. See accompanying LICENSE file or <http://unlicense.org/>. #if _runtime(_ObjC) fileprivate let Int2InNSValueObjCType = NSValue(int2: Int2()).objCType extension Int2: _ObjectiveCBridgeable { public func _bridgeToObjectiveC() -> NSValue { return { NSValue(int2: $0) }(self) } public static func _forceBridgeFromObjectiveC(_ source: NSValue, result: inout Int2?) { precondition(strcmp(source.objCType, { _ in Int2InNSValueObjCType }(Int2.self)) == 0, "NSValue does not contain the right type to bridge to Int2") result = { $0.int2Value }(source) } public static func _conditionallyBridgeFromObjectiveC(_ source: NSValue, result: inout Int2?) -> Bool { if strcmp(source.objCType, { _ in Int2InNSValueObjCType }(Int2.self)) != 0 { result = nil return false } result = { $0.int2Value }(source) return true } public static func _unconditionallyBridgeFromObjectiveC(_ source: NSValue?) -> Int2 { let unwrappedSource = source! precondition(strcmp(unwrappedSource.objCType, { _ in Int2InNSValueObjCType }(Int2.self)) == 0, "NSValue does not contain the right type to bridge to Int2") return { $0.int2Value }(unwrappedSource) } } #endif // _runtime(_ObjC)
unlicense
06b10e62e90439cfcb6addd7a9dc5db8
32.555556
104
0.607947
4.33908
false
false
false
false
kstaring/swift
stdlib/public/core/Unmanaged.swift
4
8033
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 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 // //===----------------------------------------------------------------------===// /// A type for propagating an unmanaged object reference. /// /// When you use this type, you become partially responsible for /// keeping the object alive. @_fixed_layout public struct Unmanaged<Instance : AnyObject> { internal unowned(unsafe) var _value: Instance @_versioned @_transparent internal init(_private: Instance) { _value = _private } /// Unsafely turns an opaque C pointer into an unmanaged class reference. /// /// This operation does not change reference counts. /// /// let str: CFString = Unmanaged.fromOpaque(ptr).takeUnretainedValue() /// /// - Parameter value: An opaque C pointer. /// - Returns: An unmanaged class reference to `value`. @_transparent public static func fromOpaque(_ value: UnsafeRawPointer) -> Unmanaged { return Unmanaged(_private: unsafeBitCast(value, to: Instance.self)) } /// Unsafely converts an unmanaged class reference to a pointer. /// /// This operation does not change reference counts. /// /// let str0: CFString = "boxcar" /// let bits = Unmanaged.passUnretained(str0) /// let ptr = bits.toOpaque() /// /// - Returns: An opaque pointer to the value of this unmanaged reference. @_transparent public func toOpaque() -> UnsafeMutableRawPointer { return unsafeBitCast(_value, to: UnsafeMutableRawPointer.self) } /// Creates an unmanaged reference with an unbalanced retain. /// /// The instance passed as `value` will leak if nothing eventually balances /// the retain. /// /// This is useful when passing an object to an API which Swift does not know /// the ownership rules for, but you know that the API expects you to pass /// the object at +1. /// /// - Parameter value: A class instance. /// - Returns: An unmanaged reference to the object passed as `value`. @_transparent public static func passRetained(_ value: Instance) -> Unmanaged { return Unmanaged(_private: value).retain() } /// Creates an unmanaged reference without performing an unbalanced /// retain. /// /// This is useful when passing a reference to an API which Swift /// does not know the ownership rules for, but you know that the /// API expects you to pass the object at +0. /// /// CFArraySetValueAtIndex(.passUnretained(array), i, /// .passUnretained(object)) /// /// - Parameter value: A class instance. /// - Returns: An unmanaged reference to the object passed as `value`. @_transparent public static func passUnretained(_ value: Instance) -> Unmanaged { return Unmanaged(_private: value) } /// Gets the value of this unmanaged reference as a managed /// reference without consuming an unbalanced retain of it. /// /// This is useful when a function returns an unmanaged reference /// and you know that you're not responsible for releasing the result. /// /// - Returns: The object referenced by this `Unmanaged` instance. public func takeUnretainedValue() -> Instance { return _value } /// Gets the value of this unmanaged reference as a managed /// reference and consumes an unbalanced retain of it. /// /// This is useful when a function returns an unmanaged reference /// and you know that you're responsible for releasing the result. /// /// - Returns: The object referenced by this `Unmanaged` instance. public func takeRetainedValue() -> Instance { let result = _value release() return result } /// Gets the value of the unmanaged referenced as a managed reference without /// consuming an unbalanced retain of it and passes it to the closure. Asserts /// that there is some other reference ('the owning reference') to the /// instance referenced by the unmanaged reference that guarantees the /// lifetime of the instance for the duration of the /// '_withUnsafeGuaranteedRef' call. /// /// NOTE: You are responsible for ensuring this by making the owning /// reference's lifetime fixed for the duration of the /// '_withUnsafeGuaranteedRef' call. /// /// Violation of this will incur undefined behavior. /// /// A lifetime of a reference 'the instance' is fixed over a point in the /// programm if: /// /// * There exists a global variable that references 'the instance'. /// /// import Foundation /// var globalReference = Instance() /// func aFunction() { /// point() /// } /// /// Or if: /// /// * There is another managed reference to 'the instance' whose life time is /// fixed over the point in the program by means of 'withExtendedLifetime' /// dynamically closing over this point. /// /// var owningReference = Instance() /// ... /// withExtendedLifetime(owningReference) { /// point($0) /// } /// /// Or if: /// /// * There is a class, or struct instance ('owner') whose lifetime is fixed /// at the point and which has a stored property that references /// 'the instance' for the duration of the fixed lifetime of the 'owner'. /// /// class Owned { /// } /// /// class Owner { /// final var owned: Owned /// /// func foo() { /// withExtendedLifetime(self) { /// doSomething(...) /// } // Assuming: No stores to owned occur for the dynamic lifetime of /// // the withExtendedLifetime invocation. /// } /// /// func doSomething() { /// // both 'self' and 'owned''s lifetime is fixed over this point. /// point(self, owned) /// } /// } /// /// The last rule applies transitively through a chain of stored references /// and nested structs. /// /// Examples: /// /// var owningReference = Instance() /// ... /// withExtendedLifetime(owningReference) { /// let u = Unmanaged.passUnretained(owningReference) /// for i in 0 ..< 100 { /// u._withUnsafeGuaranteedRef { /// $0.doSomething() /// } /// } /// } /// /// class Owner { /// final var owned: Owned /// /// func foo() { /// withExtendedLifetime(self) { /// doSomething(Unmanaged.passUnretained(owned)) /// } /// } /// /// func doSomething(_ u : Unmanaged<Owned>) { /// u._withUnsafeGuaranteedRef { /// $0.doSomething() /// } /// } /// } public func _withUnsafeGuaranteedRef<Result>( _ body: (Instance) throws -> Result ) rethrows -> Result { let (guaranteedInstance, token) = Builtin.unsafeGuaranteed(_value) let result = try body(guaranteedInstance) Builtin.unsafeGuaranteedEnd(token) return result } /// Performs an unbalanced retain of the object. @_transparent public func retain() -> Unmanaged { Builtin.retain(_value) return self } /// Performs an unbalanced release of the object. @_transparent public func release() { Builtin.release(_value) } #if _runtime(_ObjC) /// Performs an unbalanced autorelease of the object. @_transparent public func autorelease() -> Unmanaged { Builtin.autorelease(_value) return self } #endif } extension Unmanaged { @available(*, unavailable, message:"use 'fromOpaque(_: UnsafeRawPointer)' instead") public static func fromOpaque(_ value: OpaquePointer) -> Unmanaged { Builtin.unreachable() } @available(*, unavailable, message:"use 'toOpaque() -> UnsafeRawPointer' instead") public func toOpaque() -> OpaquePointer { Builtin.unreachable() } }
apache-2.0
74480a978667946851eeac782e5c63be
31.787755
80
0.632516
4.619321
false
false
false
false
kstaring/swift
test/Prototypes/Result.swift
4
3502
//===--- Result.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 // //===----------------------------------------------------------------------===// // RUN: %target-run-stdlib-swift // REQUIRES: executable_test public enum Result<Value> { case Success(Value) case Error(Error) init(success x: Value) { self = .Success(x) } init(error: Error) { self = .Error(error) } func map<U>(_ transform: (Value) -> U) -> Result<U> { switch self { case .Success(let x): return .Success(transform(x)) case .Error(let e): return .Error(e) } } func flatMap<U>(_ transform: (Value) -> Result<U>) -> Result<U> { switch self { case .Success(let x): return transform(x) case .Error(let e): return .Error(e) } } func get() throws -> Value { switch self { case .Success(let x): return x case .Error(let e): throw e } } var success: Value? { switch self { case .Success(let x): return x case .Error: return nil } } var error: Error? { switch self { case .Success: return nil case .Error(let x): return x } } } public func ?? <T> ( result: Result<T>, defaultValue: @autoclosure () -> T ) -> T { switch result { case .Success(let x): return x case .Error: return defaultValue() } } // We aren't actually proposing this overload; we think there should // be a compiler warning that catches the promotion that you probably // don't want. public func ?? <T> ( result: Result<T>?, defaultValue: @autoclosure () -> T ) -> T { fatalError("We should warn about Result<T> being promoted to Result<T>?") } /// Translate the execution of a throwing closure into a Result func catchResult<Success>( invoking body: () throws -> Success ) -> Result<Success> { do { return try .Success(body()) } catch { return .Error(error) } } // A couple of error types enum Nasty : Error { case Bad, Awful, Terrible } enum Icky : Error { case Sad, Bad, Poor } // Some Results to work with let three = Result(success: 3) let four = Result(success: 4) let nasty = Result<Int>(error: Nasty.Bad) let icky = Result<String>(error: Icky.Sad) print(three) print(nasty) print(icky) print(three ?? 4) print(nasty ?? 4) print(three.map { String($0) }) print(nasty.map { String($0) }) print(three.flatMap { .Success(String($0)) }) print(nasty.flatMap { .Success(String($0)) }) print(three.flatMap { _ in icky }) print(nasty.flatMap { _ in icky }) try print(three.get()) do { try print(nasty.get()) } catch { print(error) } func mayFail(_ fail: Bool) throws -> Int { if fail { throw Icky.Poor } return 0 } print(catchResult { try mayFail(true) }) print(catchResult { try mayFail(false) }) print(catchResult { _ in 1 }.flatMap { _ in Result(success: 4) }.flatMap { _ in Result<String>(error: Icky.Poor) }) print(catchResult { _ in 1 }.map { _ in three }.flatMap {$0} ) let results = [three, nasty, four] print(results.flatMap { $0.success }) print(results.flatMap { $0.error }) print(results.contains { $0.success != nil }) // Mistaken usage; causes Result<T> to be promoted to Result<T>? // print(three ?? nasty)
apache-2.0
c2bd690bc8bcd8fc74ca37d1221d527e
22.346667
115
0.619646
3.347992
false
false
false
false
kdbertel/Swiftground
closures.swift
2
653
import UIKit func genericAdder(add: Int) -> ((Int) -> (Int)) { return { x in return x + add } } let addOne: (Int)->(Int) = genericAdder(1) addOne(2) addOne(4) let addTen = genericAdder(10) addTen(14) func genericTimes(times: Int, repeater: ((Int)->(Int))) -> ((Int) -> (Int)) { return { x in var sum: Int = x for i in 0..times { sum = repeater(sum) } return sum } } let fourTimesAddOne = genericTimes(4, addOne) fourTimesAddOne(7) let sixTimesAddTen = genericTimes(6, addTen) sixTimesAddTen(20) let threeSquares = genericTimes(3) { x in return x * x } threeSquares(2)
unlicense
4bd66566f71089ed3b2fc8b69d29b484
15.769231
77
0.591118
2.995413
false
false
false
false
pfremm/watchOS-2-Sampler
watchOS2Sampler/AppDelegate.swift
1
3936
// // AppDelegate.swift // watchOS2Sampler // // Created by Shuichi Tsutsumi on 2015/06/10. // Copyright © 2015年 Shuichi Tsutsumi. All rights reserved. // import UIKit import WatchConnectivity import HealthKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, WCSessionDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { let settings = UIUserNotificationSettings( forTypes: [.Badge, .Sound, .Alert], categories: nil) UIApplication.sharedApplication().registerUserNotificationSettings(settings) if (WCSession.isSupported()) { let session = WCSession.defaultSession() session.delegate = self // conforms to WCSessionDelegate session.activateSession() } return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } func applicationShouldRequestHealthAuthorization(application: UIApplication) { let healthStore = HKHealthStore() guard HKHealthStore.isHealthDataAvailable() else { return } let dataTypes = Set([HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate)!]) healthStore.requestAuthorizationToShareTypes(nil, readTypes: dataTypes, completion: { (result, error) -> Void in }) } // ========================================================================= // MARK: - WCSessionDelegate func sessionWatchStateDidChange(session: WCSession) { print(__FUNCTION__) print(session) print("reachable:\(session.reachable)") } func session(session: WCSession, didReceiveMessage message: [String : AnyObject], replyHandler: ([String : AnyObject]) -> Void) { print(__FUNCTION__) guard message["request"] as? String == "fireLocalNotification" else {return} let localNotification = UILocalNotification() localNotification.alertBody = "Message Received!" localNotification.fireDate = NSDate() localNotification.soundName = UILocalNotificationDefaultSoundName; UIApplication.sharedApplication().scheduleLocalNotification(localNotification) } }
mit
2dd4ade70e73c8c4a558b07e998e2643
43.191011
285
0.702771
6.041475
false
false
false
false
Yalantis/GuillotineMenu
GuillotineMenuExample/GuillotineMenuExample/ViewController.swift
1
3279
// // ViewController.swift // GuillotineMenu // // Created by Maksym Lazebnyi on 3/24/15. // Copyright (c) 2015 Yalantis. All rights reserved. // import UIKit class ViewController: UIViewController { fileprivate let cellHeight: CGFloat = 210 fileprivate let cellSpacing: CGFloat = 20 fileprivate lazy var presentationAnimator = GuillotineTransitionAnimation() @IBOutlet fileprivate var barButton: UIButton! override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) print("VC: viewWillAppear") } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) print("VC: viewDidAppear") } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) print("VC: viewWillDisappear") } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) print("VC: viewDidDisappear") } override func viewDidLoad() { super.viewDidLoad() let navBar = self.navigationController?.navigationBar navBar?.barTintColor = UIColor( red: 65.0 / 255.0, green: 62.0 / 255.0, blue: 79.0 / 255.0, alpha: 1 ) navBar?.titleTextAttributes = [.foregroundColor: UIColor.white] } @IBAction func showMenuAction(_ sender: UIButton) { let menuViewController = storyboard!.instantiateViewController(withIdentifier: "MenuViewController") menuViewController.modalPresentationStyle = .custom menuViewController.transitioningDelegate = self presentationAnimator.animationDelegate = menuViewController as? GuillotineAnimationDelegate presentationAnimator.supportView = navigationController!.navigationBar presentationAnimator.presentButton = sender present(menuViewController, animated: true, completion: nil) } } extension ViewController: UICollectionViewDataSource, UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 5 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ContentCell", for: indexPath) return cell } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize { return CGSize(width: collectionView.bounds.width - cellSpacing, height: cellHeight) } } extension ViewController: UIViewControllerTransitioningDelegate { func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { presentationAnimator.mode = .presentation return presentationAnimator } func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { presentationAnimator.mode = .dismissal return presentationAnimator } }
mit
77a30daf7891edebcbbc4279f02579bd
33.882979
170
0.707838
6.016514
false
false
false
false
mrchenhao/Swift-every-day
KeyFrameDemo/KeyFrameDemo/headerView.swift
1
2458
// // headerView.swift // KeyFrameDemo // // Created by ChenHao on 8/1/15. // Copyright (c) 2015 HarriesChen. All rights reserved. // import UIKit class headerView: UIView { var fly:UIView override init(frame: CGRect) { fly = UIView(frame: CGRectMake(40, 150, 20, 20)) super.init(frame: frame) self.backgroundColor = UIColor.yellowColor() layout() } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func layout() { var circle = UIView(frame: CGRectMake(30, 140, 40, 40)) circle.backgroundColor = UIColor.redColor() circle.layer.cornerRadius = 20 self.addSubview(circle) fly.backgroundColor = UIColor.greenColor() fly.layer.cornerRadius = 10 self.addSubview(fly) } func start() { let zoomInScaleTransform = CGAffineTransformMakeScale(0.2, 0.2) UIView.animateKeyframesWithDuration(2, delay: 0, options: nil, animations: { () -> Void in UIView.addKeyframeWithRelativeStartTime(0, relativeDuration: 0.2, animations: { self.fly.center.x += self.frame.width self.fly.center.y += -180 self.fly.transform = zoomInScaleTransform }) UIView.addKeyframeWithRelativeStartTime(0.3, relativeDuration: 0.01, animations: { self.fly.alpha = 1 self.fly.transform = zoomInScaleTransform }) UIView.addKeyframeWithRelativeStartTime(0.3, relativeDuration: 0.5, animations: { self.fly.transform = CGAffineTransformIdentity self.fly.center.x -= (self.frame.width + 33) self.fly.center.y += 180 }) UIView.addKeyframeWithRelativeStartTime(0.9, relativeDuration: 0.01, animations: { self.fly.alpha = 1 }) UIView.addKeyframeWithRelativeStartTime(0.91, relativeDuration: 0.09, animations: { self.fly.center.x += 33 }) }) { (_) -> Void in } } /* // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { // Drawing code } */ }
mit
686ddd0dc22a78e47f8e6dd4aa155875
29.725
98
0.570789
4.791423
false
false
false
false
huonw/swift
stdlib/public/SDK/Network/NWParameters.swift
1
16355
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2018 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// An NWParameters object contains the parameters necessary to create /// a network connection or listener. NWParameters include any preferences for /// network paths (such as required, prohibited, and preferred networks, and local /// endpoint requirements); preferences for data transfer and quality of service; /// and the protocols to be used for a connection along with any protocol-specific /// options. @available(macOS 10.14, iOS 12.0, watchOS 5.0, tvOS 12.0, *) public final class NWParameters : CustomDebugStringConvertible { public var debugDescription: String { return String("\(self.nw)") } internal let nw : nw_parameters_t /// Creates a parameters object that is configured for TLS and TCP. The caller can use /// the default configuration for TLS and TCP, or set specific options for each protocol, /// or disable TLS. /// /// - Parameter tls: TLS options or nil for no TLS /// - Parameter tcp: TCP options. Defaults to NWProtocolTCP.Options() with no options overridden. /// - Returns: NWParameters object that can be used for creating a connection or listener public convenience init(tls: NWProtocolTLS.Options?, tcp: NWProtocolTCP.Options = NWProtocolTCP.Options()) { self.init() let protocolStack = self.defaultProtocolStack protocolStack.transportProtocol = tcp if let tls = tls { protocolStack.applicationProtocols = [tls] } else { protocolStack.applicationProtocols = [] } } /// Creates a parameters object that is configured for DTLS and UDP. The caller can use /// the default configuration for DTLS and UDP, or set specific options for each protocol, /// or disable TLS. /// /// - Parameter dtls: DTLS options or nil for no DTLS /// - Parameter udp: UDP options. Defaults to NWProtocolUDP.Options() with no options overridden. /// - Returns: NWParameters object that can be used for create a connection or listener public convenience init(dtls: NWProtocolTLS.Options?, udp: NWProtocolUDP.Options = NWProtocolUDP.Options()) { self.init() let protocolStack = self.defaultProtocolStack protocolStack.transportProtocol = udp if let dtls = dtls { protocolStack.applicationProtocols = [dtls] } else { protocolStack.applicationProtocols = [] } } /// Creates a generic NWParameters object. Note that in order to use parameters /// with a NWConnection or a NetworkListener, the parameters must have protocols /// added into the defaultProtocolStack. Clients using standard protocol /// configurations should use init(tls:tcp:) or init(dtls:udp:). public init() { self.nw = nw_parameters_create() } private init(nw: nw_parameters_t) { self.nw = nw } /// Default set of parameters for TLS over TCP /// This is equivalent to calling init(tls:NWProtocolTLS.Options(), tcp:NWProtocolTCP.Options()) public class var tls: NWParameters { return NWParameters(tls:NWProtocolTLS.Options()) } /// Default set of parameters for DTLS over UDP /// This is equivalent to calling init(dtls:NWProtocolTLS.Options(), udp:NWProtocolUDP.Options()) public class var dtls: NWParameters { return NWParameters(dtls:NWProtocolTLS.Options()) } /// Default set of parameters for TCP /// This is equivalent to calling init(tls:nil, tcp:NWProtocolTCP.Options()) public class var tcp: NWParameters { return NWParameters(tls:nil) } /// Default set of parameters for UDP /// This is equivalent to calling init(dtls:nil, udp:NWProtocolUDP.Options()) public class var udp: NWParameters { return NWParameters(dtls:nil) } /// Require a connection to use a specific interface, or fail if not available public var requiredInterface: NWInterface? { set { if let interface = newValue { nw_parameters_require_interface(self.nw, interface.nw) } else { nw_parameters_require_interface(self.nw, nil) } } get { if let interface = nw_parameters_copy_required_interface(self.nw) { return NWInterface(interface) } else { return nil } } } /// Require a connection to use a specific interface type, or fail if not available public var requiredInterfaceType: NWInterface.InterfaceType { set { nw_parameters_set_required_interface_type(self.nw, newValue.nw) } get { return NWInterface.InterfaceType(nw_parameters_get_required_interface_type(self.nw)) } } /// Define one or more interfaces that a connection will not be allowed to use public var prohibitedInterfaces: [NWInterface]? { set { nw_parameters_clear_prohibited_interfaces(self.nw) if let prohibitedInterfaces = newValue { for prohibitedInterface in prohibitedInterfaces { nw_parameters_prohibit_interface(self.nw, prohibitedInterface.nw) } } } get { var interfaces = [NWInterface]() nw_parameters_iterate_prohibited_interfaces(self.nw) { (interface) in interfaces.append(NWInterface(interface)) return true } return interfaces } } /// Define one or more interface types that a connection will not be allowed to use public var prohibitedInterfaceTypes: [NWInterface.InterfaceType]? { set { nw_parameters_clear_prohibited_interface_types(self.nw) if let prohibitedInterfaceTypes = newValue { for prohibitedInterfaceType in prohibitedInterfaceTypes { nw_parameters_prohibit_interface_type(self.nw, prohibitedInterfaceType.nw) } } } get { var interfaceTypes = [NWInterface.InterfaceType]() nw_parameters_iterate_prohibited_interface_types(self.nw) { (interfaceType) in interfaceTypes.append(NWInterface.InterfaceType(interfaceType)) return true } return interfaceTypes } } /// Disallow connection from using interfaces considered expensive public var prohibitExpensivePaths: Bool { set { nw_parameters_set_prohibit_expensive(self.nw, newValue) } get { return nw_parameters_get_prohibit_expensive(self.nw) } } /// If true, a direct connection will be attempted first even if proxies are configured. If the direct connection /// fails, connecting through the proxies will still be attempted. public var preferNoProxies: Bool { set { nw_parameters_set_prefer_no_proxy(self.nw, newValue) } get { return nw_parameters_get_prefer_no_proxy(self.nw) } } /// Force a specific local address to be used. This value is nil by /// default, in which case the system selects the most appropriate /// local address and selects a local port. public var requiredLocalEndpoint: NWEndpoint? { set { if let endpoint = newValue { nw_parameters_set_local_endpoint(self.nw, endpoint.nw) } else { nw_parameters_set_local_endpoint(self.nw, nil) } } get { if let endpoint = nw_parameters_copy_local_endpoint(self.nw) { return NWEndpoint(endpoint) } else { return nil } } } /// Allow multiple connections to use the same local address and port /// (SO_REUSEADDR and SO_REUSEPORT). public var allowLocalEndpointReuse: Bool { set { nw_parameters_set_reuse_local_address(self.nw, newValue) } get { return nw_parameters_get_reuse_local_address(self.nw) } } /// Cause an NWListener to only advertise services on the local link, /// and only accept connections from the local link. public var acceptLocalOnly: Bool { set { nw_parameters_set_local_only(self.nw, newValue) } get { return nw_parameters_get_local_only(self.nw) } } /// The ServiceClass represents the network queuing priority to use /// for traffic generated by a NWConnection. public enum ServiceClass { /// Default priority traffic case bestEffort /// Bulk traffic, or traffic that can be de-prioritized behind foreground traffic case background /// Interactive video traffic case interactiveVideo /// Interactive voice traffic case interactiveVoice /// Responsive data case responsiveData /// Signaling case signaling internal var nw: nw_service_class_t { switch self { case .bestEffort: return Network.nw_service_class_best_effort case .background: return Network.nw_service_class_background case .interactiveVideo: return Network.nw_service_class_interactive_video case .interactiveVoice: return Network.nw_service_class_interactive_voice case .responsiveData: return Network.nw_service_class_responsive_data case .signaling: return Network.nw_service_class_signaling } } internal init(_ nw: nw_service_class_t) { switch nw { case Network.nw_service_class_best_effort: self = .bestEffort case Network.nw_service_class_background: self = .background case Network.nw_service_class_interactive_video: self = .interactiveVideo case Network.nw_service_class_interactive_voice: self = .interactiveVoice case Network.nw_service_class_responsive_data: self = .responsiveData case Network.nw_service_class_signaling: self = .signaling default: self = .bestEffort } } } public var serviceClass: NWParameters.ServiceClass { set { nw_parameters_set_service_class(self.nw, newValue.nw) } get { return NWParameters.ServiceClass(nw_parameters_get_service_class(self.nw)) } } /// Multipath services represent the modes of multipath usage that are /// allowed for connections. public enum MultipathServiceType { /// No multipath transport will be attempted case disabled /// Only use the expensive interface when the when the primary one is not available case handover /// Use the expensive interface more aggressively to reduce latency case interactive /// Use all available interfaces to provide the highest throughput and lowest latency case aggregate internal var nw: nw_multipath_service_t { switch self { case .disabled: return Network.nw_multipath_service_disabled case .handover: return Network.nw_multipath_service_handover case .interactive: return Network.nw_multipath_service_interactive case .aggregate: return Network.nw_multipath_service_aggregate } } internal init(_ nw: nw_multipath_service_t) { switch nw { case Network.nw_multipath_service_disabled: self = .disabled case Network.nw_multipath_service_handover: self = .handover case Network.nw_multipath_service_interactive: self = .interactive case Network.nw_multipath_service_aggregate: self = .aggregate default: self = .disabled } } } public var multipathServiceType: NWParameters.MultipathServiceType { set { nw_parameters_set_multipath_service(self.nw, newValue.nw) } get { return NWParameters.MultipathServiceType(nw_parameters_get_multipath_service(self.nw)) } } /// Use fast open for an outbound NWConnection, which may be done at any /// protocol level. Use of fast open requires that the caller send /// idempotent data on the connection before the connection may move /// into ready state. As a side effect, this may implicitly enable /// fast open for protocols in the stack, even if they did not have /// fast open expliclty enabled on them (such as the option to enable /// TCP Fast Open). public var allowFastOpen: Bool { set { nw_parameters_set_fast_open_enabled(self.nw, newValue) } get { return nw_parameters_get_fast_open_enabled(self.nw) } } /// Allow or prohibit the use of expired DNS answers during connection establishment. /// If allowed, a DNS answer that was previously returned may be re-used for new /// connections even after the answers are considered expired. A query for fresh answers /// will be sent in parallel, and the fresh answers will be used as alternate addresses /// in case the expired answers do not result in successful connections. /// By default, this value is .systemDefault, which allows the system to determine /// if it is appropriate to use expired answers. public enum ExpiredDNSBehavior { /// Let the system determine whether or not to allow expired DNS answers case systemDefault /// Explicitly allow the use of expired DNS answers case allow /// Explicitly prohibit the use of expired DNS answers case prohibit internal var nw: nw_parameters_expired_dns_behavior_t { switch self { case .systemDefault: return Network.nw_parameters_expired_dns_behavior_default case .allow: return Network.nw_parameters_expired_dns_behavior_allow case .prohibit: return Network.nw_parameters_expired_dns_behavior_prohibit } } internal init(_ nw: nw_parameters_expired_dns_behavior_t) { switch nw { case Network.nw_parameters_expired_dns_behavior_default: self = .systemDefault case Network.nw_parameters_expired_dns_behavior_allow: self = .allow case Network.nw_parameters_expired_dns_behavior_prohibit: self = .prohibit default: self = .systemDefault } } } public var expiredDNSBehavior: NWParameters.ExpiredDNSBehavior { set { nw_parameters_set_expired_dns_behavior(self.nw, newValue.nw) } get { return NWParameters.ExpiredDNSBehavior(nw_parameters_get_expired_dns_behavior(self.nw)) } } /// A ProtocolStack contains a list of protocols to use for a connection. /// The members of the protocol stack are NWProtocolOptions objects, each /// defining which protocol to use within the stack along with any protocol-specific /// options. Each stack includes an array of application-level protocols, a single /// transport-level protocol, and an optional internet-level protocol. If the internet- /// level protocol is not specified, any available and applicable IP address family /// may be used. public class ProtocolStack { public var applicationProtocols: [NWProtocolOptions] { set { nw_protocol_stack_clear_application_protocols(self.nw) for applicationProtocol in newValue.reversed() { nw_protocol_stack_prepend_application_protocol(self.nw, applicationProtocol.nw) } } get { var applicationProtocols = [NWProtocolOptions]() nw_protocol_stack_iterate_application_protocols(self.nw) { (protocolOptions) in let applicationDefinition = nw_protocol_options_copy_definition(protocolOptions) if (nw_protocol_definition_is_equal(applicationDefinition, NWProtocolTLS.definition.nw)) { applicationProtocols.append(NWProtocolTLS.Options(protocolOptions)) } } return applicationProtocols } } public var transportProtocol: NWProtocolOptions? { set { if let transport = newValue { nw_protocol_stack_set_transport_protocol(self.nw, transport.nw) } } get { if let transport = nw_protocol_stack_copy_transport_protocol(nw) { let transportDefinition = nw_protocol_options_copy_definition(transport) if (nw_protocol_definition_is_equal(transportDefinition, NWProtocolTCP.definition.nw)) { return NWProtocolTCP.Options(transport) } else if (nw_protocol_definition_is_equal(transportDefinition, NWProtocolUDP.definition.nw)) { return NWProtocolUDP.Options(transport) } } return nil } } public var internetProtocol: NWProtocolOptions? { set { // Not currently allowed return } get { if let ip = nw_protocol_stack_copy_internet_protocol(nw) { if (nw_protocol_definition_is_equal(nw_protocol_options_copy_definition(ip), NWProtocolIP.definition.nw)) { return NWProtocolIP.Options(ip) } } return nil } } internal let nw: nw_protocol_stack_t internal init(_ nw: nw_protocol_stack_t) { self.nw = nw } } /// Every NWParameters has a default protocol stack, although it may start out empty. public var defaultProtocolStack: NWParameters.ProtocolStack { get { return NWParameters.ProtocolStack(nw_parameters_copy_default_protocol_stack(self.nw)) } } /// Perform a deep copy of parameters public func copy() -> NWParameters { return NWParameters(nw: nw_parameters_copy(self.nw)) } }
apache-2.0
f985975a31397d4cbc7ccb69fae79456
32.861284
114
0.718924
3.731462
false
false
false
false
PureSwift/Bluetooth
Sources/BluetoothGATT/ATTReadByTypeRequest.swift
1
2742
// // ATTReadByTypeRequest.swift // Bluetooth // // Created by Alsey Coleman Miller on 6/13/18. // Copyright © 2018 PureSwift. All rights reserved. // import Foundation /// Read By Type Request /// /// The *Read By Type Request* is used to obtain the values of attributes where the /// attribute type is known but the handle is not known. @frozen public struct ATTReadByTypeRequest: ATTProtocolDataUnit, Equatable { public static var attributeOpcode: ATTOpcode { return .readByTypeRequest } /// First requested handle number public var startHandle: UInt16 /// Last requested handle number public var endHandle: UInt16 /// 2 or 16 octet UUID public var attributeType: BluetoothUUID public init(startHandle: UInt16, endHandle: UInt16, attributeType: BluetoothUUID) { assert(attributeType.length != .bit32, "32-bit UUID not supported") self.startHandle = startHandle self.endHandle = endHandle self.attributeType = attributeType } } public extension ATTReadByTypeRequest { init?(data: Data) { guard let length = Length(rawValue: data.count), type(of: self).validateOpcode(data) else { return nil } self.startHandle = UInt16(littleEndian: UInt16(bytes: (data[1], data[2]))) self.endHandle = UInt16(littleEndian: UInt16(bytes: (data[3], data[4]))) switch length { case .uuid16: let value = UInt16(littleEndian: UInt16(bytes: (data[5], data[6]))) self.attributeType = .bit16(value) case .uuid128: self.attributeType = BluetoothUUID(littleEndian: BluetoothUUID(data: data.suffixNoCopy(from: 5))!) } } var data: Data { return Data(self) } } // MARK: - DataConvertible extension ATTReadByTypeRequest: DataConvertible { var dataLength: Int { return length.rawValue } static func += <T: DataContainer> (data: inout T, value: ATTReadByTypeRequest) { data += attributeOpcode.rawValue data += value.startHandle.littleEndian data += value.endHandle.littleEndian data += value.attributeType.littleEndian } } // MARK: - Supporting Types internal extension ATTReadByTypeRequest { enum Length: Int { case uuid16 = 7 case uuid128 = 21 } private var length: Length { switch attributeType { case .bit16: return .uuid16 case .bit128: return .uuid128 case .bit32: fatalError() // FIXME: Do not allow 32-bit UUID for Blueooth LE } } }
mit
8e18cf5604e38a9682067fc374f72c39
25.61165
110
0.612185
4.464169
false
false
false
false
kang77649119/DouYuDemo
DouYuDemo/DouYuDemo/Classes/Home/ViewModel/RecommendViewModel.swift
1
3821
// // RecommendViewModel.swift // DouYuDemo // // Created by 也许、 on 16/10/11. // Copyright © 2016年 K. All rights reserved. // import UIKit class RecommendViewModel: BaseAnchorViewModel { // 推荐 lazy var bigAnchorGroup:AnchorGroup = AnchorGroup() // 颜值 lazy var prettyAnchorGroup:AnchorGroup = AnchorGroup() // 轮播 lazy var carouselModels = [CarouselModel]() } extension RecommendViewModel { // http://capi.douyucdn.cn/api/v1/getbigDataRoom?limit=4&offset=0&time=1476170483.97425 // http://capi.douyucdn.cn/api/v1/getVerticalRoom?limit=4&offset=0&time=1476170483.97425 // http://capi.douyucdn.cn/api/v1/getHotCate?limit=4&offset=0&time=1476170483.97425 // 请求数据 func loadData(finishedCallBack:@escaping ()->()) { let group = DispatchGroup() let parameters = ["limit" : "4", "offset" : "0", "time" : NSDate.getCurrentTime()] // 推荐 group.enter() NetWorkTools.request(type: .GET, url: "http://capi.douyucdn.cn/api/v1/getbigDataRoom", parameters: parameters as [String : AnyObject]?) { (response) in guard let json = response else { return } self.bigAnchorGroup.tag_name = "推荐" self.bigAnchorGroup.icon_url = "home_header_hot" let datas:[[String : AnyObject]] = json["data"] as! [[String : AnyObject]] for obj in datas { self.bigAnchorGroup.anchors.append(Anchor(dict: obj)) } group.leave() } // 颜值 group.enter() NetWorkTools.request(type: .GET, url: "http://capi.douyucdn.cn/api/v1/getVerticalRoom", parameters: parameters as [String : AnyObject]?) { (response) in guard let json = response else { return } self.prettyAnchorGroup.tag_name = "颜值" self.prettyAnchorGroup.icon_url = "home_header_phone" let datas:[[String : AnyObject]] = json["data"] as! [[String : AnyObject]] for obj in datas { self.prettyAnchorGroup.anchors.append(Anchor(dict: obj)) } group.leave() } // 其他 group.enter() NetWorkTools.request(type: .GET, url: "http://capi.douyucdn.cn/api/v1/getHotCate", parameters: parameters as [String : AnyObject]?) { (response) in guard let json = response else { return } let datas:[[String : AnyObject]] = json["data"] as! [[String : AnyObject]] for obj in datas { let group = AnchorGroup(dict: obj) self.anchorGroups.append(group) } group.leave() } group.notify(queue: DispatchQueue.main) { self.anchorGroups.insert(self.prettyAnchorGroup, at: 0) self.anchorGroups.insert(self.bigAnchorGroup, at: 0) finishedCallBack() } } // 请求轮播数据 func loadCarouselData(finishedCallBack : @escaping ()->()) { let parameters = ["version" : "2.300"] NetWorkTools.request(type: .GET, url: "http://www.douyutv.com/api/v1/slide/6", parameters: parameters as [String : AnyObject]?) { (response) in guard let json = response else { return } guard let array = json["data"] as? [[String : AnyObject]] else { return } for obj in array { self.carouselModels.append(CarouselModel(dict: obj)) } finishedCallBack() } } }
mit
0f3a067ec28c1cf5d09de2fd52374ee2
30.596639
160
0.54016
4.423529
false
false
false
false
daniel-beard/DBSudoku
DBSudoku/GameViewController.swift
1
846
// // GameViewController.swift // DBSudoku // // Created by Daniel Beard on 8/1/15. // Copyright (c) 2015 DanielBeard. All rights reserved. // import UIKit import SpriteKit class GameViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() if let scene = GameScene(fileNamed:"GameScene") { // Configure the view. let skView = self.view as! SKView skView.showsFPS = true skView.showsNodeCount = true /* Sprite Kit applies additional optimizations to improve rendering performance */ skView.ignoresSiblingOrder = true /* Set the scale mode to scale to fit the window */ scene.scaleMode = .aspectFill skView.presentScene(scene) } } }
mit
b3e4a827834eac6237294e28768298eb
25.4375
94
0.594563
5.158537
false
false
false
false
abertelrud/swift-package-manager
Sources/PackageModel/BuildFlags.swift
2
1160
/* This source file is part of the Swift.org open source project Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ /// Build-tool independent flags. public struct BuildFlags: Equatable, Encodable { /// Flags to pass to the C compiler. public var cCompilerFlags: [String] /// Flags to pass to the C++ compiler. public var cxxCompilerFlags: [String] /// Flags to pass to the Swift compiler. public var swiftCompilerFlags: [String] /// Flags to pass to the linker. public var linkerFlags: [String] public init( cCompilerFlags: [String]? = nil, cxxCompilerFlags: [String]? = nil, swiftCompilerFlags: [String]? = nil, linkerFlags: [String]? = nil ) { self.cCompilerFlags = cCompilerFlags ?? [] self.cxxCompilerFlags = cxxCompilerFlags ?? [] self.swiftCompilerFlags = swiftCompilerFlags ?? [] self.linkerFlags = linkerFlags ?? [] } }
apache-2.0
fb04f692a641df8bbce8a283fd4aabf6
30.351351
67
0.671552
4.444444
false
false
false
false
abertelrud/swift-package-manager
Sources/Basics/Sandbox.swift
2
6391
//===----------------------------------------------------------------------===// // // This source file is part of the Swift open source project // // Copyright (c) 2021-2022 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import Foundation import TSCBasic import enum TSCUtility.Platform public enum Sandbox { /// Applies a sandbox invocation to the given command line (if the platform supports it), /// and returns the modified command line. On platforms that don't support sandboxing, the /// command line is returned unmodified. /// /// - Parameters: /// - command: The command line to sandbox (including executable as first argument) /// - strictness: The basic strictness level of the standbox. /// - writableDirectories: Paths under which writing should be allowed, even if they would otherwise be read-only based on the strictness or paths in `readOnlyDirectories`. /// - readOnlyDirectories: Paths under which writing should be denied, even if they would have otherwise been allowed by the rules implied by the strictness level. public static func apply( command: [String], strictness: Strictness = .default, writableDirectories: [AbsolutePath] = [], readOnlyDirectories: [AbsolutePath] = [] ) throws -> [String] { #if os(macOS) let profile = try macOSSandboxProfile(strictness: strictness, writableDirectories: writableDirectories, readOnlyDirectories: readOnlyDirectories) return ["/usr/bin/sandbox-exec", "-p", profile] + command #else // rdar://40235432, rdar://75636874 tracks implementing sandboxes for other platforms. return command #endif } /// Basic strictness level of a sandbox applied to a command line. public enum Strictness: Equatable { /// Blocks network access and all file system modifications. case `default` /// More lenient restrictions than the default, for compatibility with SwiftPM manifests using a tools version older than 5.3. case manifest_pre_53 // backwards compatibility for manifests /// Like `default`, but also makes temporary-files directories (such as `/tmp`) on the platform writable. case writableTemporaryDirectory } } // MARK: - macOS #if os(macOS) fileprivate func macOSSandboxProfile( strictness: Sandbox.Strictness, writableDirectories: [AbsolutePath], readOnlyDirectories: [AbsolutePath] ) throws -> String { var contents = "(version 1)\n" // Deny everything by default. contents += "(deny default)\n" // Import the system sandbox profile. contents += "(import \"system.sb\")\n" // Allow reading all files; ideally we'd only allow the package directory and any dependencies, // but all kinds of system locations need to be accessible. contents += "(allow file-read*)\n" // This is needed to launch any processes. contents += "(allow process*)\n" // The following accesses are only needed when interpreting the manifest (versus running a compiled version). if strictness == .manifest_pre_53 { // This is required by the Swift compiler. contents += "(allow sysctl*)\n" } // Allow writing only to certain directories. var writableDirectoriesExpression: [String] = [] // The following accesses are only needed when interpreting the manifest (versus running a compiled version). if strictness == .manifest_pre_53 { writableDirectoriesExpression += Platform.threadSafeDarwinCacheDirectories.get().map { ##"(regex #"^\##($0.pathString)/org\.llvm\.clang.*")"## } } // Optionally allow writing to temporary directories (a lot of use of Foundation requires this). else if strictness == .writableTemporaryDirectory { // Add `subpath` expressions for the regular and the Foundation temporary directories. for tmpDir in ["/tmp", NSTemporaryDirectory()] { writableDirectoriesExpression += try ["(subpath \(resolveSymlinks(AbsolutePath(validating: tmpDir)).quotedAsSubpathForSandboxProfile))"] } } // Emit rules for paths under which writing is allowed. Some of these expressions may be regular expressions and others literal subpaths. if writableDirectoriesExpression.count > 0 { contents += "(allow file-write*\n" for expression in writableDirectoriesExpression { contents += " \(expression)\n" } contents += ")\n" } // Emit rules for paths under which writing should be disallowed, even if they would be covered by a previous rule to allow writing to them. A classic case is a package which is located under the temporary directory, which should be read-only even though the temporary directory as a whole is writable. if readOnlyDirectories.count > 0 { contents += "(deny file-write*\n" for path in readOnlyDirectories { contents += " (subpath \(try resolveSymlinks(path).quotedAsSubpathForSandboxProfile))\n" } contents += ")\n" } // Emit rules for paths under which writing is allowed, even if they are descendants directories that are otherwise read-only. if writableDirectories.count > 0 { contents += "(allow file-write*\n" for path in writableDirectories { contents += " (subpath \(try resolveSymlinks(path).quotedAsSubpathForSandboxProfile))\n" } contents += ")\n" } return contents } fileprivate extension AbsolutePath { /// Private computed property that returns a version of the path as a string quoted for use as a subpath in a .sb sandbox profile. var quotedAsSubpathForSandboxProfile: String { return "\"" + self.pathString .replacingOccurrences(of: "\\", with: "\\\\") .replacingOccurrences(of: "\"", with: "\\\"") + "\"" } } extension TSCUtility.Platform { fileprivate static let threadSafeDarwinCacheDirectories = ThreadSafeArrayStore<AbsolutePath>((try? Self.darwinCacheDirectories()) ?? []) } #endif
apache-2.0
f39f84ca292cefcfdda9a020f979467b
43.381944
306
0.666875
4.904835
false
false
false
false
Kawoou/FlexibleImage
Sources/Filter/InvertFilter.swift
1
1476
// // InvertFilter.swift // FlexibleImage // // Created by Kawoou on 2017. 5. 12.. // Copyright © 2017년 test. All rights reserved. // #if !os(watchOS) import Metal #endif internal class InvertFilter: ImageFilter { // MARK: - Property internal override var metalName: String { get { return "InvertFilter" } } // MARK: - Internal #if !os(watchOS) @available(OSX 10.11, iOS 8, tvOS 9, *) internal override func processMetal(_ device: ImageMetalDevice, _ commandBuffer: MTLCommandBuffer, _ commandEncoder: MTLComputeCommandEncoder) -> Bool { return super.processMetal(device, commandBuffer, commandEncoder) } #endif override func processNone(_ device: ImageNoneDevice) -> Bool { let memoryPool = device.memoryPool! let width = Int(device.drawRect!.width) let height = Int(device.drawRect!.height) var index = 0 for _ in 0..<height { for _ in 0..<width { let r = memoryPool[index + 0] let g = memoryPool[index + 1] let b = memoryPool[index + 2] memoryPool[index + 0] = 255 - r memoryPool[index + 1] = 255 - g memoryPool[index + 2] = 255 - b index += 4 } } return super.processNone(device) } }
mit
3c7b429cc533806ad4f26242364afd87
25.303571
160
0.528174
4.383929
false
false
false
false
uasys/swift
test/SILGen/instrprof_basic.swift
6
2270
// RUN: %target-swift-frontend -parse-as-library -enable-sil-ownership -emit-silgen -profile-generate %s | %FileCheck %s // CHECK: sil hidden @[[F_EMPTY:.*empty.*]] : // CHECK: %[[NAME:.*]] = string_literal utf8 "{{.*}}instrprof_basic.swift:[[F_EMPTY]]" // CHECK: %[[HASH:.*]] = integer_literal $Builtin.Int64, // CHECK: %[[NCOUNTS:.*]] = integer_literal $Builtin.Int32, 1 // CHECK: %[[INDEX:.*]] = integer_literal $Builtin.Int32, 0 // CHECK: builtin "int_instrprof_increment"(%[[NAME]] : {{.*}}, %[[HASH]] : {{.*}}, %[[NCOUNTS]] : {{.*}}, %[[INDEX]] : {{.*}}) func empty() { // CHECK-NOT: builtin "int_instrprof_increment" } // CHECK: sil hidden @[[F_BASIC:.*basic.*]] : // CHECK: %[[NAME:.*]] = string_literal utf8 "{{.*}}instrprof_basic.swift:[[F_BASIC]]" // CHECK: %[[HASH:.*]] = integer_literal $Builtin.Int64, // CHECK: %[[NCOUNTS:.*]] = integer_literal $Builtin.Int32, 6 // CHECK: %[[INDEX:.*]] = integer_literal $Builtin.Int32, 0 // CHECK: builtin "int_instrprof_increment"(%[[NAME]] : {{.*}}, %[[HASH]] : {{.*}}, %[[NCOUNTS]] : {{.*}}, %[[INDEX]] : {{.*}}) func basic(a : Int32) { // CHECK: builtin "int_instrprof_increment" if a == 0 { } // CHECK: builtin "int_instrprof_increment" if a != 0 { } else { } // CHECK: builtin "int_instrprof_increment" while a == 0 { } // CHECK: builtin "int_instrprof_increment" for i in 0 ..< a { } // CHECK: builtin "int_instrprof_increment" for i in 1...a { } // CHECK-NOT: builtin "int_instrprof_increment" } // CHECK: sil hidden @[[F_THROWING_NOP:.*throwing_nop.*]] : func throwing_nop() throws {} // CHECK: sil hidden @[[F_EXCEPTIONS:.*exceptions.*]] : // CHECK: %[[NAME:.*]] = string_literal utf8 "{{.*}}instrprof_basic.swift:[[F_EXCEPTIONS]]" // CHECK: %[[HASH:.*]] = integer_literal $Builtin.Int64, // CHECK: %[[NCOUNTS:.*]] = integer_literal $Builtin.Int32, 3 // CHECK: %[[INDEX:.*]] = integer_literal $Builtin.Int32, 0 // CHECK: builtin "int_instrprof_increment"(%[[NAME]] : {{.*}}, %[[HASH]] : {{.*}}, %[[NCOUNTS]] : {{.*}}, %[[INDEX]] : {{.*}}) func exceptions() { do { try throwing_nop() // CHECK: builtin "int_instrprof_increment" } catch { // CHECK: builtin "int_instrprof_increment" return } // CHECK-NOT: builtin "int_instrprof_increment" }
apache-2.0
032a82faaa8c0070bf30023521138a0d
35.031746
127
0.582379
3.252149
false
false
false
false
Limon-O-O/Lego
Frameworks/EggKit/EggKit/Protocols/SegueHandlerType.swift
1
1097
// // SegueHandlerType.swift // EggKit // // Created by Limon on 20/02/2017. // Copyright © 2017 Limon.F. All rights reserved. // import UIKit public protocol SegueHandlerType { associatedtype SegueIdentifier: RawRepresentable } public extension SegueHandlerType where Self: UIViewController, SegueIdentifier.RawValue == String { public func performSegue(withIdentifier identifier: SegueIdentifier, sender: Any?) { if let navigationController = navigationController { guard navigationController.topViewController == self else { return } } DispatchQueue.main.async { self.performSegue(withIdentifier: identifier.rawValue, sender: sender) } } public func segueIdentifier(for segue: UIStoryboardSegue) -> SegueIdentifier { guard let identifier = segue.identifier, let segueIdentifier = SegueIdentifier(rawValue: identifier) else { fatalError("INVALID SEGUE IDENTIFIER \(segue.identifier)") } return segueIdentifier } }
mit
cae232113a9d660cf4e62c77f5a7f6b4
27.102564
100
0.667883
5.563452
false
false
false
false
qblu/CoverFlowCollectionView
CoverFlowCollectionView/CoverFlowLayout.swift
1
3586
// // CoverFlowLayout.swift // CoverFlowCollectionView // // Created by Rusty Zarse on 8/11/15. // Copyright (c) 2015 com.levous. All rights reserved. // import Foundation public class CoverFlowLayout : UICollectionViewFlowLayout { let zoomFactor: CGFloat = 0.75 let focusedItemContainerWidthRatio: CGFloat = 0.75 override public func prepareLayout() { self.minimumInteritemSpacing = 20.0 self.minimumLineSpacing = 20.0 self.scrollDirection = UICollectionViewScrollDirection.Horizontal let size = self.collectionView!.frame.size let itemWidth = size.width * focusedItemContainerWidthRatio self.itemSize = CGSizeMake(itemWidth, itemWidth * 0.75) self.sectionInset = UIEdgeInsetsMake(size.height * 0.15, size.height * 0.1, size.height * 0.15, size.height * 0.1) } override public func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool { return true } override public func layoutAttributesForElementsInRect(rect: CGRect) -> [AnyObject]? { var elementsAttributesInRect = super.layoutAttributesForElementsInRect(rect)! var visibleRect:CGRect = CGRectZero visibleRect.origin = self.collectionView!.contentOffset visibleRect.size = self.collectionView!.bounds.size let collectionViewHalfFrame = self.collectionView!.frame.size.width / 2.0 for index in 0..<elementsAttributesInRect.count { var layoutAttributes = elementsAttributesInRect[index] as! UICollectionViewLayoutAttributes if (CGRectIntersectsRect(layoutAttributes.frame, rect)) { let distanceFromCenter = CGRectGetMidX(visibleRect) - layoutAttributes.center.x let normalizedDistance = distanceFromCenter / collectionViewHalfFrame if (abs(distanceFromCenter) < collectionViewHalfFrame) { let zoom = 1.0 + zoomFactor * (1.0 - abs(normalizedDistance)) var rotationTransform = CATransform3DIdentity rotationTransform = CATransform3DMakeRotation(CGFloat(normalizedDistance * CGFloat(M_PI_2) * 0.8), 0.0, 1.0, 0.0) let zoomTransform = CATransform3DMakeScale(zoom, zoom, 1.0) layoutAttributes.transform3D = CATransform3DConcat(zoomTransform, rotationTransform) layoutAttributes.zIndex = Int(abs(normalizedDistance) * 10.0) var alpha = (1 - abs(normalizedDistance)) + 0.1 if (alpha > 1.0) { alpha = 1.0 } layoutAttributes.alpha = alpha } else { layoutAttributes.alpha = 0.0 } } } return elementsAttributesInRect } override public func targetContentOffsetForProposedContentOffset(proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint { var newOffset = proposedContentOffset if (newOffset.x > self.collectionView!.contentOffset.x) { newOffset.x = self.collectionView!.contentOffset.x + self.collectionView!.bounds.size.width / 2 } else if (newOffset.x < self.collectionView!.contentOffset.x) { newOffset.x = self.collectionView!.contentOffset.x - self.collectionView!.bounds.size.width / 2 } var offsetAdjustment: CGFloat = CGFloat(MAXFLOAT) let horizontalCenter = newOffset.x + self.collectionView!.bounds.size.width / 2 let targetRect = CGRectMake(newOffset.x, 0, self.collectionView!.bounds.size.width, self.collectionView!.bounds.size.height) let attributes = super.layoutAttributesForElementsInRect(targetRect)! for a in attributes { let itemHorizontalCenter = a.center.x if (abs(itemHorizontalCenter - horizontalCenter) < abs(offsetAdjustment)) { offsetAdjustment = itemHorizontalCenter - horizontalCenter } } return CGPointMake(newOffset.x + offsetAdjustment, newOffset.y); } }
mit
e7626f3f0f1d70ad7ec75c4393fd77e0
37.569892
151
0.755159
4.223793
false
false
false
false
nathawes/swift
test/Parse/dollar_identifier.swift
5
2815
// RUN: %target-typecheck-verify-swift -swift-version 4 // SR-1661: Dollar was accidentally allowed as an identifier in Swift 3. // SE-0144: Reject this behavior in the future. func dollarVar() { var $ : Int = 42 // expected-error {{'$' is not an identifier; use backticks to escape it}} {{7-8=`$`}} $ += 1 // expected-error {{'$' is not an identifier; use backticks to escape it}} {{3-4=`$`}} print($) // expected-error {{'$' is not an identifier; use backticks to escape it}} {{9-10=`$`}} } func dollarLet() { let $ = 42 // expected-error {{'$' is not an identifier; use backticks to escape it}} {{7-8=`$`}} print($) // expected-error {{'$' is not an identifier; use backticks to escape it}} {{9-10=`$`}} } func dollarClass() { class $ {} // expected-error {{'$' is not an identifier; use backticks to escape it}} {{9-10=`$`}} } func dollarEnum() { enum $ {} // expected-error {{'$' is not an identifier; use backticks to escape it}} {{8-9=`$`}} } func dollarStruct() { struct $ {} // expected-error {{'$' is not an identifier; use backticks to escape it}} {{10-11=`$`}} } func dollarFunc() { func $($ dollarParam: Int) {} // expected-error@-1 {{'$' is not an identifier; use backticks to escape it}} {{8-9=`$`}} // expected-error@-2 {{'$' is not an identifier; use backticks to escape it}} {{10-11=`$`}} $($: 24) // expected-error@-1 {{'$' is not an identifier; use backticks to escape it}} {{3-4=`$`}} // expected-error@-2 {{'$' is not an identifier; use backticks to escape it}} {{5-6=`$`}} } func escapedDollarVar() { var `$` : Int = 42 // no error `$` += 1 print(`$`) } func escapedDollarLet() { let `$` = 42 // no error print(`$`) } func escapedDollarClass() { class `$` {} // no error } func escapedDollarEnum() { enum `$` {} // no error } func escapedDollarStruct() { struct `$` {} // no error } func escapedDollarFunc() { func `$`(`$`: Int) {} // no error `$`(`$`: 25) // no error } func escapedDollarAnd() { // FIXME: Bad diagnostics. `$0` = 1 // expected-error {{expected expression}} `$$` = 2 `$abc` = 3 } func $declareWithDollar() { // expected-error{{cannot declare entity named '$declareWithDollar'}} var $foo = 17 // expected-error{{cannot declare entity named '$foo'}} // expected-warning@-1 {{initialization of variable '$foo' was never used; consider replacing with assignment to '_' or removing it}} func $bar() { } // expected-error{{cannot declare entity named '$bar'}} func wibble( $a: Int, // expected-error{{cannot declare entity named '$a'}} $b c: Int) { } // expected-error{{cannot declare entity named '$b'}} } // SR-13232 @propertyWrapper struct Wrapper { var wrappedValue: Int var projectedValue: String { String(wrappedValue) } } struct S { @Wrapper var café = 42 } let _ = S().$café // Okay
apache-2.0
9d7b2e41f4a3f7c1579aa4e8079aaa8c
32.094118
135
0.615357
3.653247
false
false
false
false
mxcl/swift-package-manager
Sources/Commands/SwiftPackageResolveTool.swift
1
2180
/* This source file is part of the Swift.org open source project Copyright 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 Swift project authors */ import PackageGraph import SourceControl private class ResolverToolDelegate: DependencyResolverDelegate { typealias Identifier = RepositoryPackageContainer.Identifier func added(container identifier: Identifier) { print("note: considering repository: \(identifier.url)") } } extension SwiftPackageTool { func executeResolve(_ opts: PackageToolOptions) throws { // Load the root manifest. let manifest = try loadRootManifest(opts) // Create the checkout manager. let repositoriesPath = opts.path.build.appending(component: "repositories") let checkoutManager = CheckoutManager(path: repositoriesPath, provider: GitRepositoryProvider()) // Create the container provider interface. let provider = RepositoryPackageContainerProvider( checkoutManager: checkoutManager, manifestLoader: manifestLoader) // Create the resolver. let delegate = ResolverToolDelegate() let resolver = DependencyResolver(provider, delegate) // Resolve the dependencies using the manifest constraints. let constraints = manifest.package.dependencies.map{ RepositoryPackageConstraint(container: RepositorySpecifier(url: $0.url), versionRequirement: .range($0.versionRange)) } let result = try resolver.resolve(constraints: constraints) print("Resolved dependencies for: \(manifest.name)") for (container, version) in result { // FIXME: It would be nice to show the reference path, should we get // that back or do we need to re-derive it? // FIXME: It would be nice to show information on the resulting // constraints, e.g., how much latitude do we have on particular // dependencies. print(" \(container.url): \(version)") } } }
apache-2.0
5251824f7a691e16033723648051d5e3
38.636364
131
0.699541
5.202864
false
false
false
false
cohena100/Shimi
Carthage/Checkouts/SwiftyBeaver/Tests/SwiftyBeaverTests/AES256CBCTests.swift
1
4692
// // AES256CBCTests.swift // AES256CBCTests // // Created by Sebastian Kreutzberger on 2/9/16. // Copyright © 2016 SwiftyBeaver. All rights reserved. // import XCTest @testable import SwiftyBeaver class AES256CBCTests: XCTestCase { override func setUp() { super.setUp() } override func tearDown() { super.tearDown() } func testEncryptDecryptStringCycle() { // encrypt. password must be 32 chars long let str = AES256CBC.randomText(32) let password = AES256CBC.randomText(32) let encrypted = AES256CBC.encryptString(str, password: password) XCTAssertNotNil(encrypted) //print("str: \(str)") //print("password: \(password)") //printn("encrypted secret (IV is at first 16 chars): \(encrypted)") if let encrypted = encrypted { XCTAssertGreaterThan(encrypted.characters.count, 16) // decrypt let decrypted = AES256CBC.decryptString(encrypted, password: password) //print("decrypted str: \(decrypted)") XCTAssertNotNil(decrypted) XCTAssertEqual(decrypted, str) } } func testEncryptString() { // str length can vary due to padding, password must be 32 chars long var str = "" var password = "" var encrypted = AES256CBC.encryptString(str, password: password) XCTAssertNil(encrypted) // str must be longer than 0 characters str = "" password = AES256CBC.randomText(32) encrypted = AES256CBC.encryptString(str, password: password) XCTAssertNil(encrypted) // password must be exactly 32 chars long str = AES256CBC.randomText(20) password = AES256CBC.randomText(31) encrypted = AES256CBC.encryptString(str, password: password) XCTAssertNil(encrypted) password = AES256CBC.randomText(33) encrypted = AES256CBC.encryptString(str, password: password) XCTAssertNil(encrypted) // that works, even with str length of 3 due to padding str = "x" password = AES256CBC.randomText(32) encrypted = AES256CBC.encryptString(str, password: password) XCTAssertNotNil(encrypted) //NSLog("str: \(str)") //NSLog("password: \(password)") //NSLog("encrypted: \(encrypted)") if let encrypted = encrypted { XCTAssertGreaterThan(encrypted.characters.count, 16) // decrypt let decrypted = AES256CBC.decryptString(encrypted, password: password) XCTAssertNotNil(decrypted) XCTAssertEqual(decrypted, str) } } func testDecryptString() { // the encrypted string must be at least 17 chars long because the first // 16 chars are the IV. password must be 32 chars long var str = "" var password = "" var decrypted = AES256CBC.decryptString(str, password: password) XCTAssertNil(decrypted) // str must be at least 17 chars long str = AES256CBC.randomText(16) password = AES256CBC.randomText(32) decrypted = AES256CBC.decryptString(str, password: password) XCTAssertNil(decrypted) str = AES256CBC.randomText(17) // password must be exactly 32 chars long password = AES256CBC.randomText(31) decrypted = AES256CBC.decryptString(str, password: password) XCTAssertNil(decrypted) password = AES256CBC.randomText(33) decrypted = AES256CBC.decryptString(str, password: password) XCTAssertNil(decrypted) } func testRandomText() { let length = 6 let text = AES256CBC.randomText(length) let text2 = AES256CBC.randomText(length) XCTAssertEqual(text.characters.count, length) XCTAssertEqual(text2.characters.count, length) XCTAssertNotEqual(text, text2) XCTAssertNil(text.range(of: " ")) XCTAssertNil(text2.range(of: " ")) } func testGeneratePassword() { let pw = AES256CBC.generatePassword() let pw2 = AES256CBC.generatePassword() XCTAssertEqual(pw.characters.count, 32) XCTAssertEqual(pw2.characters.count, 32) XCTAssertNotEqual(pw, pw2) XCTAssertNil(pw.range(of: " ")) XCTAssertNil(pw2.range(of: " ")) } // MARK: Linux allTests static let allTests = [ ("testEncryptDecryptStringCycle", testEncryptDecryptStringCycle), ("testEncryptString", testEncryptString), ("testDecryptString", testDecryptString), ("testRandomText", testRandomText), ("testGeneratePassword", testGeneratePassword) ] }
mit
012ed3b5df08c98cdacd796feffd9a35
32.992754
82
0.634833
4.558795
false
true
false
false
ihorrapalyuk/SimpleJSONParser
SimpleJSONParser/Classes/NSObject+JSON.swift
3
2343
// // NSObject+JSON.swift // MovieMakerApp // // Created by Ihor Rapalyuk on 7/21/16. // Copyright © 2016 My. All rights reserved. // import Foundation extension NSObject { public class func fromJson(jsonInfo: NSDictionary) -> Self { let object = self.init() (object as NSObject).updateWithDictionary(jsonInfo) return object } public class func fromAnyObject(object: AnyObject) -> Self { let objectCurrent = self.init() (objectCurrent as NSObject).updateWithAnyObject(object) return objectCurrent } public func updateWithAnyObject(object: AnyObject?) { if let jsonResult = object as? Dictionary<String, AnyObject> { self.updateWithDictionary(jsonResult) } } public func updateWithDictionary(jsonDictionary: NSDictionary) -> Self { for prop in self.propertyNames() { do { var object = jsonDictionary.objectForKey(prop.name) if let objectDict = object as? Dictionary<String, AnyObject>, classType = NSClassFromString(prop.classString) as? NSObject.Type { let embedObject = classType.init() embedObject.updateWithAnyObject(objectDict) self.setValue(embedObject, forKey: prop.name) } else { try self.validateValue(&object, forKey: prop.name) self.setValue(object, forKey: prop.name) } } catch { print("Failed to save \(prop.name)") } } return self } private func propertyNames() -> [(name: String, classString: String)] { var propertiesResult: [(name: String, classString: String)] = [] var count: UInt32 = 0 let properties = class_copyPropertyList(classForCoder, &count) for i in 0 ..< Int(count) { let property = properties[i] if let name = String.fromCString(property_getName(property)) { let classString = PropertyUtil.getPropertyType(property) propertiesResult.append((name: name, classString: classString)) } } free(properties) return propertiesResult } }
mit
761e73647b893a0961a48991e93e1e5e
32.457143
87
0.575576
4.972399
false
false
false
false
ymkjp/NewsPlayer
NewsPlayer/AppDelegate.swift
1
6382
// // AppDelegate.swift // NewsPlayer // // Created by YAMAMOTOKenta on 9/11/15. // Copyright (c) 2015 ymkjp. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.xn--nyqr7s4vc72p.NewsPlayer" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("NewsPlayer", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("NewsPlayer.sqlite") var error: NSError? = nil var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch var error1 as NSError { error = error1 coordinator = nil // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } catch { fatalError() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext? = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator if coordinator == nil { return nil } var managedObjectContext = NSManagedObjectContext() managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if let moc = self.managedObjectContext { var error: NSError? = nil if moc.hasChanges { do { try moc.save() } catch let error1 as NSError { error = error1 // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } } } } }
mit
178c3c002f3b9b2a9a27732f5b1102b6
51.743802
290
0.698527
5.759928
false
false
false
false
tlax/GaussSquad
GaussSquad/Metal/General/MetalProjection.swift
1
1364
import UIKit import MetalKit class MetalProjection:MetalBufferableProtocol { class func projectionMatrix(device:MTLDevice) -> MTLBuffer { let size:CGSize = UIScreen.main.bounds.size let width:CGFloat = size.width let height:CGFloat = size.height let projection:MetalProjection = MetalProjection( width:width, height:height) let metalBuffer:MTLBuffer = device.generateBuffer( bufferable:projection) return metalBuffer } class func projectionMatrix( device:MTLDevice, width:CGFloat, height:CGFloat) -> MTLBuffer { let projection:MetalProjection = MetalProjection( width:width, height:height) let metalBuffer:MTLBuffer = device.generateBuffer( bufferable:projection) return metalBuffer } private let ratioX:Float private let ratioY:Float private init(width:CGFloat, height:CGFloat) { let scale:Float = Float(UIScreen.main.scale) ratioX = Float(width) / scale ratioY = Float(height) / scale } //MARK: bufferableProtocol func buffer() -> [Float] { let bufferArray:[Float] = [ ratioX, ratioY ] return bufferArray } }
mit
1642c5181fdb89d9358049c5fb04d2b3
23.8
62
0.591642
4.871429
false
false
false
false
yaslab/ZeroFormatter.swift
Sources/ObjectExtractor.swift
1
1683
// // ObjectExtractor.swift // ZeroFormatter // // Created by Yasuhiro Hatta on 2016/11/24. // Copyright © 2016 yaslab. All rights reserved. // import Foundation public class ObjectExtractor { private let bytes: NSData private let offset: Int public let byteSize: Int public let isNil: Bool public init(_ bytes: NSData, _ offset: Int) { self.bytes = bytes self.offset = offset var tmp = 0 let byteSize: Int = BinaryUtility.deserialize(bytes, offset, &tmp) self.byteSize = byteSize self.isNil = (byteSize < 0) } // ----- public func extract<T: Serializable>(index: Int) -> T { var tmp = 0 let indexOffset: Int = BinaryUtility.deserialize(bytes, offset + 4 + 4 + (4 * index), &tmp) return T.deserialize(bytes, Int(indexOffset), &tmp) } public func extract<T: Serializable>(index: Int) -> T? { var tmp = 0 let indexOffset: Int = BinaryUtility.deserialize(bytes, offset + 4 + 4 + (4 * index), &tmp) return T.deserialize(bytes, Int(indexOffset), &tmp) } public func extract<T: Serializable>(index: Int) -> Array<T>? { var tmp = 0 let indexOffset: Int = BinaryUtility.deserialize(bytes, offset + 4 + 4 + (4 * index), &tmp) var byteSize = 0 let length: Int = BinaryUtility.deserialize(bytes, indexOffset, &byteSize) if length < 0 { return nil } var array = Array<T>() for _ in 0 ..< length { array.append(T.deserialize(bytes, indexOffset + byteSize, &byteSize)) } return array } }
mit
c770288d2746fc447af6c63b194ac5a3
27.508475
99
0.577883
4.072639
false
false
false
false
qoncept/TensorSwift
Sources/TensorSwift/Tensor.swift
1
7922
#if os(iOS) || os(OSX) import Accelerate #endif public struct Tensor { public typealias Element = Float public let shape: Shape public fileprivate(set) var elements: [Element] public init(shape: Shape, elements: [Element]) { let volume = shape.volume() precondition(elements.count >= volume, "`elements.count` must be greater than or equal to `shape.volume`: elements.count = \(elements.count), shape.volume = \(shape.volume())") self.shape = shape self.elements = (elements.count == volume) ? elements : Array(elements[0..<volume]) } } extension Tensor { // Additional Initializers public init(shape: Shape, element: Element = 0.0) { self.init(shape: shape, elements: [Element](repeating: element, count: shape.volume())) } } extension Tensor { public mutating func reshape(_ shape: Shape) { self = reshaped(shape) } public func reshaped(_ shape: Shape) -> Tensor { return Tensor(shape: shape, elements: elements) } } extension Tensor { // like CollentionType internal func index(_ indices: [Int]) -> Int { assert(indices.count == shape.dimensions.count, "`indices.count` must be \(shape.dimensions.count): \(indices.count)") return zip(shape.dimensions, indices).reduce(0) { assert(0 <= $1.1 && $1.1 < $1.0.value, "Illegal index: indices = \(indices), shape = \(shape)") return $0 * $1.0.value + $1.1 } } public subscript(indices: Int...) -> Element { get { return elements[index(indices)] } set { elements[index(indices)] = newValue } } public func volume() -> Int { return shape.volume() } } extension Tensor: Sequence { public func makeIterator() -> IndexingIterator<[Element]> { return elements.makeIterator() } } extension Tensor: Equatable {} public func ==(lhs: Tensor, rhs: Tensor) -> Bool { return lhs.shape == rhs.shape && lhs.elements == rhs.elements } internal func commutativeBinaryOperation(_ lhs: Tensor, _ rhs: Tensor, operation: (Float, Float) -> Float) -> Tensor { let lSize = lhs.shape.dimensions.count let rSize = rhs.shape.dimensions.count if lSize == rSize { precondition(lhs.shape == rhs.shape, "Incompatible shapes of tensors: lhs.shape = \(lhs.shape), rhs.shape = \(rhs.shape)") return Tensor(shape: lhs.shape, elements: zipMap(lhs.elements, rhs.elements, operation: operation)) } let a: Tensor let b: Tensor if lSize < rSize { a = rhs b = lhs } else { a = lhs b = rhs } assert(hasSuffix(array: a.shape.dimensions, suffix: b.shape.dimensions), "Incompatible shapes of tensors: lhs.shape = \(lhs.shape), rhs.shape = \(rhs.shape)") return Tensor(shape: a.shape, elements: zipMapRepeat(a.elements, b.elements, operation: operation)) } internal func noncommutativeBinaryOperation(_ lhs: Tensor, _ rhs: Tensor, operation: (Float, Float) -> Float) -> Tensor { let lSize = lhs.shape.dimensions.count let rSize = rhs.shape.dimensions.count if lSize == rSize { precondition(lhs.shape == rhs.shape, "Incompatible shapes of tensors: lhs.shape = \(lhs.shape), rhs.shape = \(rhs.shape)") return Tensor(shape: lhs.shape, elements: zipMap(lhs.elements, rhs.elements, operation: operation)) } else if lSize < rSize { precondition(hasSuffix(array: rhs.shape.dimensions, suffix: lhs.shape.dimensions), "Incompatible shapes of tensors: lhs.shape = \(lhs.shape), rhs.shape = \(rhs.shape)") return Tensor(shape: rhs.shape, elements: zipMapRepeat(rhs.elements, lhs.elements, operation: { operation($1, $0) })) } else { precondition(hasSuffix(array: lhs.shape.dimensions, suffix: rhs.shape.dimensions), "Incompatible shapes of tensors: lhs.shape = \(lhs.shape), rhs.shape = \(rhs.shape)") return Tensor(shape: lhs.shape, elements: zipMapRepeat(lhs.elements, rhs.elements, operation: operation)) } } public func +(lhs: Tensor, rhs: Tensor) -> Tensor { return commutativeBinaryOperation(lhs, rhs, operation: +) } public func -(lhs: Tensor, rhs: Tensor) -> Tensor { return noncommutativeBinaryOperation(lhs, rhs, operation: -) } public func *(lhs: Tensor, rhs: Tensor) -> Tensor { return commutativeBinaryOperation(lhs, rhs, operation: *) } public func /(lhs: Tensor, rhs: Tensor) -> Tensor { return noncommutativeBinaryOperation(lhs, rhs, operation: /) } public func *(lhs: Tensor, rhs: Float) -> Tensor { return Tensor(shape: lhs.shape, elements: lhs.elements.map { $0 * rhs }) } public func *(lhs: Float, rhs: Tensor) -> Tensor { return Tensor(shape: rhs.shape, elements: rhs.elements.map { lhs * $0 }) } public func /(lhs: Tensor, rhs: Float) -> Tensor { return Tensor(shape: lhs.shape, elements: lhs.elements.map { $0 / rhs }) } public func /(lhs: Float, rhs: Tensor) -> Tensor { return Tensor(shape: rhs.shape, elements: rhs.elements.map { lhs / $0 }) } extension Tensor { // Matrix public func matmul(_ tensor: Tensor) -> Tensor { precondition(shape.dimensions.count == 2, "This tensor is not a matrix: shape = \(shape)") precondition(tensor.shape.dimensions.count == 2, "The given tensor is not a matrix: shape = \(tensor.shape)") precondition(tensor.shape.dimensions[0] == shape.dimensions[1], "Incompatible shapes of matrices: self.shape = \(shape), tensor.shape = \(tensor.shape)") #if os(iOS) || os(OSX) let result = Tensor(shape: [shape.dimensions[0], tensor.shape.dimensions[1]]) let n = Int32(tensor.shape.dimensions[1].value) let k = Int32(shape.dimensions[1].value) cblas_sgemm( CblasRowMajor, // Order CblasNoTrans, // TransA CblasNoTrans, // TransB Int32(shape.dimensions[0].value), // M n, // N k, // K 1.0, // alpha elements, // A k, // lda tensor.elements, // B n, // ldb 1.0, // beta UnsafeMutablePointer<Float>(mutating: result.elements), // C n // ldc ) return result #else let n = shape.dimensions[1].value let numRows = shape.dimensions[0] let numCols = tensor.shape.dimensions[1] let leftHead = UnsafeMutablePointer<Float>(self.elements) let rightHead = UnsafeMutablePointer<Float>(tensor.elements) let elements = [Float](count: (numCols * numRows).value, repeatedValue: 0.0) for r in 0..<numRows.value { for i in 0..<n { var pointer = UnsafeMutablePointer<Float>(elements) + r * numCols.value let left = leftHead[r * n + i] var rightPointer = rightHead + i * numCols.value for _ in 0..<numCols.value { pointer.memory += left * rightPointer.memory pointer += 1 rightPointer += 1 } } } return Tensor(shape: [numRows, numCols], elements: elements) #endif } }
mit
929d37d78899eb8c5d8521dfcb273478
39.418367
184
0.558571
4.291441
false
false
false
false
swiftsanyue/TestKitchen
TestKitchen/TestKitchen/classes/ingredient(食材)/material(食材)/view/IngreMateriaView.swift
1
2247
// // IngreMateriaView.swift // TestKitchen // // Created by ZL on 16/11/1. // Copyright © 2016年 zl. All rights reserved. // import UIKit class IngreMateriaView: UIView { //点击事件 var jumpClosure: IngreJumpClosure? //表格 private var tbView:UITableView? //显示表格 var model : IngreMaterial? { didSet{ //刷新表格 if model != nil { tbView?.reloadData() } } } override init(frame: CGRect) { super.init(frame: frame) //创建表格 tbView = UITableView(frame: CGRectZero, style: .Plain) tbView?.delegate = self tbView?.dataSource = self addSubview(tbView!) //约束 tbView?.snp_makeConstraints(closure: { (make) in make.edges.equalTo(self) }) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension IngreMateriaView:UITableViewDelegate,UITableViewDataSource{ func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { var row = 0 if model?.data?.data?.count > 0 { row = (model?.data?.data?.count)! } return row } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { let tmpmodel = model?.data?.data![indexPath.row] return IngreMaterialCell.heightForCellWithModel(tmpmodel!) } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cellId = "IngreMaterialCellId" var cell = tableView.dequeueReusableCellWithIdentifier(cellId) as? IngreMaterialCell if nil == cell { cell = IngreMaterialCell(style: .Default, reuseIdentifier: cellId) } //显示数据 cell?.cellModel = model?.data?.data![indexPath.row] //点击事件 cell?.jumpClosure = jumpClosure //取消cell的点击 cell?.selectionStyle = .None return cell! } }
mit
25afdc0b51a372ca98aba908c3d6f22a
22.673913
109
0.572544
4.829268
false
false
false
false
mleiv/MEGameTracker
MEGameTracker/Views/Common/Data Rows/Availability/AvailabilityType.swift
1
1980
// // AvailabilityRowType.swift // MEGameTracker // // Created by Emily Ivie on 5/27/16. // Copyright © 2016 urdnot. All rights reserved. // import UIKit public struct AvailabilityRowType: TextDataRowType { public typealias RowType = TextDataRow var view: RowType? { return row } public var row: TextDataRow? public var identifier: String = "\(UUID().uuidString)" public var controller: Available? public var text: String? { return UIWindow.isInterfaceBuilder ? "Unavailable in Game 1" : controller?.availabilityMessage } let defaultPaddingTop: CGFloat = 0.0 let defaultPaddingSides: CGFloat = 15.0 var didSetup = false public var linkOriginController: UIViewController? { return controller as? UIViewController } var viewController: UIViewController? { return controller as? UIViewController } public init() {} public init(controller: Available, view: TextDataRow?) { self.controller = controller self.row = view } public mutating func setupView() { setupView(type: RowType.self) } public mutating func setup(view: UIView?) { guard let view = view as? RowType else { return } if UIWindow.isInterfaceBuilder || !didSetup { didSetup = true view.backgroundColor = UIColor(named: "availabilityBackground") view.textView?.tintColor = UIColor(named: "availabilityLink")! view.textView?.textRenderingFont = UIFont.preferredFont(forTextStyle: .callout) view.textView?.textRenderingTextColor = UIColor(named: "availabilityLabel")! view.textView?.markup() view.textView?.textAlignment = .center } view.textView?.text = text } } // Helper function inserted by Swift 4.2 migrator. fileprivate func convertToOptionalNSAttributedStringKeyDictionary(_ input: [String: Any]?) -> [NSAttributedString.Key: Any]? { guard let input = input else { return nil } return Dictionary(uniqueKeysWithValues: input.map { key, value in (NSAttributedString.Key(rawValue: key), value)}) }
mit
e8d6cdfd732b23db742ad4808042b041
31.983333
126
0.728146
4.265086
false
false
false
false
Mikelulu/BaiSiBuDeQiJie
LKBS/LKBS/Classes/Tools/LKTimeManager.swift
1
2208
// // LKTimeManager.swift // LKBS // // Created by mac on 2017/7/29. // Copyright © 2017年 LK. All rights reserved. // import UIKit struct LKTimeManager { /// 传入时间戳 返回发表的时间(..小时前,...天前) /// /// - Parameter timeString: 要计算的时间字符串 /// - Returns: <#return value description#> public static func getPublishTimeString(_ timeString: String?) -> String { guard (timeString != nil) else { return "" } /// 现将时间转成date格式 let dateFormatter: DateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" dateFormatter.locale = Locale.init(identifier: "zh_CN") dateFormatter.timeZone = TimeZone.current let date: Date = dateFormatter.date(from: timeString!)! /// 得到的时间戳是负数 因为是现在之前的时间 var timeInterval: TimeInterval = date.timeIntervalSinceNow timeInterval = -timeInterval var resultString = "" if timeInterval < 60 { resultString = "刚刚" }else if (timeInterval / 60) < 60 { let string: String = String.init(format: "%d", Int(timeInterval / 60)) resultString = "\(string)分钟前" }else if (timeInterval / 60 / 60) < 24 { let string: String = String.init(format: "%d", Int(timeInterval / 60 / 60)) resultString = "\(string)小时前" }else if (timeInterval / 60 / 60 / 24) < 30 { let string: String = String.init(format: "%d", Int(timeInterval / 60 / 60 / 24)) resultString = "\(string)天前" }else if (timeInterval / 60 / 60 / 24 / 30) < 12 { let string: String = String.init(format: "%df", Int(timeInterval / 60 / 60 / 24 / 30)) resultString = "\(string)月前" }else { let string: String = String.init(format: "%d", Int(timeInterval / 60 / 60 / 24 / 30 / 12)) resultString = "\(string)年前" } return resultString } }
mit
a414befbd62d2b21cd1419c6b9d13f0d
31.265625
102
0.536077
4.293139
false
false
false
false
Xinext/RemainderCalc
src/RemainderCalc/HistoryTableViewController.swift
1
2742
// // HistoryTableViewController.swift // RemainderCalc // import UIKit class HistoryTableViewController: UITableViewController { // MARK: - IBOutlet @IBOutlet var outletTableView: UITableView! @IBOutlet weak var outletBackButton: UIBarButtonItem! @IBOutlet weak var outletClearButton: UIBarButtonItem! var dataList: Array<D_History>? = nil // MARK: - UITableViewController Override override func viewDidLoad() { super.viewDidLoad() // ローカライズ設定 self.navigationItem.title = NSLocalizedString("STR_HISTORY_VIEW_TITLE", comment: "History") outletBackButton.title = NSLocalizedString("STR_HISTORY_BACK_BUTTON", comment: "< Back") outletClearButton.title = NSLocalizedString("STR_HISTORY_CLEAR_BUTTON", comment: "Clear") // 表示データの取得 dataList = ModelMgr.Load_D_History() } 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 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return ModelMgr.GetCount_D_History() } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.subtitle, reuseIdentifier: "ResultCell") cell.textLabel?.text = (dataList?[indexPath.row].m_i_expression)! + "=" + (dataList?[indexPath.row].m_i_answer)! return cell } // MARK: - Action method /** [Action] Sender:BackButton Event:TouchDown */ @IBAction func Action_BackButton_TouchDown(_ sender: UIBarButtonItem) { // Back the main view. _ = self.navigationController?.popViewController(animated: true) } /** [Action] Sender:ClearButton Event:TouchDown */ @IBAction func Action_ClearButton_TouchDown(_ sender: UIBarButtonItem) { XIDialog.DispConfirmationMsg(pvc: self, msg: NSLocalizedString("STR_HISTORY_CLEAR_CHECK_TEXT", comment: "Delete?"), handler: {() -> Void in ModelMgr.DeleteDataWithOffset(offset: 0) self.tableView.reloadData()}) } }
mit
dbbac80ae98ced7c9bcafedf9eb96525
32.875
120
0.630258
5.122873
false
false
false
false
dinhnhat0401/swift_design_partern
BlueLibrarySwift/HorizontalScroller.swift
1
5071
// // HorizontalScroller.swift // BlueLibrarySwift // // Created by Đinh Văn Nhật on 2014/12/29. // Copyright (c) 2014年 Dinh Van Nhat. All rights reserved. // import UIKit @objc protocol HorizontalScrollerDelegate { func numberOfViewsForHorizontalScroller(scroller: HorizontalScroller) -> Int func horizontalScrollerViewAtIndex(scroller: HorizontalScroller, index:Int) -> UIView func horizontalScrollerClickedViewAtIndex(scroller: HorizontalScroller, index:Int) optional func initialViewIndex(scroller: HorizontalScroller) -> Int } class HorizontalScroller: UIView { weak var delegate: HorizontalScrollerDelegate? private let VIEW_PADDING = 10 private let VIEW_DIMENSIONS = 100 private let VIEWS_OFFSET = 100 private var scroller : UIScrollView! var viewArray = [UIView]() override init(frame: CGRect) { super.init(frame: frame) initializeScrollView() } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initializeScrollView() } func initializeScrollView() { scroller = UIScrollView() addSubview(scroller) scroller.setTranslatesAutoresizingMaskIntoConstraints(false) self.addConstraint(NSLayoutConstraint(item: scroller, attribute: .Leading, relatedBy: .Equal, toItem: self, attribute: .Leading, multiplier: 1.0, constant: 0.0)) self.addConstraint(NSLayoutConstraint(item: scroller, attribute: .Trailing, relatedBy: .Equal, toItem: self, attribute: .Trailing, multiplier: 1.0, constant: 0.0)) self.addConstraint(NSLayoutConstraint(item: scroller, attribute: .Top, relatedBy: .Equal, toItem: self, attribute: .Top, multiplier: 1.0, constant: 0.0)) self.addConstraint(NSLayoutConstraint(item: scroller, attribute: .Bottom, relatedBy: .Equal, toItem: self, attribute: .Bottom, multiplier: 1.0, constant: 0.0)) let tapRecognizer = UITapGestureRecognizer(target: self, action: Selector("scrollerTapped:")) scroller.addGestureRecognizer(tapRecognizer) } func scrollerTapped(gesture: UITapGestureRecognizer) { let location = gesture.locationInView(gesture.view) if let delegate = self.delegate { for index in 0..<delegate.numberOfViewsForHorizontalScroller(self) { let view = scroller.subviews[index] as UIView if CGRectContainsPoint(view.frame, location) { delegate.horizontalScrollerClickedViewAtIndex(self, index: index) scroller.setContentOffset(CGPointMake(view.frame.origin.x - self.frame.size.width/2 + view.frame.size.width/2, 0), animated: true) break } } } } func viewAtIndex(index :Int) -> UIView { return viewArray[index] } func reload() { if let delegate = self.delegate { viewArray = [] let views: NSArray = scroller.subviews views.enumerateObjectsUsingBlock({ (object: AnyObject!, idx: Int, stop: UnsafeMutablePointer<ObjCBool>) -> Void in object.removeFromSuperview() }) var xValue = VIEWS_OFFSET for index in 0..<delegate.numberOfViewsForHorizontalScroller(self) { xValue += VIEW_PADDING let view = delegate.horizontalScrollerViewAtIndex(self, index: index) view.frame = CGRectMake(CGFloat(xValue), CGFloat(VIEW_PADDING), CGFloat(VIEW_DIMENSIONS), CGFloat(VIEW_DIMENSIONS)) scroller.addSubview(view) xValue += VIEW_DIMENSIONS + VIEW_PADDING viewArray.append(view) } scroller.contentSize = CGSizeMake(CGFloat(xValue + VIEWS_OFFSET), frame.size.height) if let initialView = delegate.initialViewIndex?(self) { scroller.setContentOffset(CGPointMake(CGFloat(initialView)*CGFloat((VIEW_DIMENSIONS + (2 * VIEW_PADDING))), 0), animated: true ) } } } override func didMoveToSuperview() { reload() } func centerCurrentView() { var xFinal = scroller.contentOffset.x + CGFloat((VIEWS_OFFSET/2) + VIEW_PADDING) let viewIndex = xFinal / CGFloat(VIEW_DIMENSIONS + 2 * VIEW_PADDING) xFinal = viewIndex * CGFloat(VIEW_DIMENSIONS + 2 * VIEW_PADDING) scroller.setContentOffset(CGPointMake(xFinal, 0), animated: true) if let delegate = self.delegate { delegate.horizontalScrollerClickedViewAtIndex(self, index: Int(viewIndex)) } } } extension HorizontalScroller: UIScrollViewDelegate { func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) { if !decelerate { centerCurrentView() } } func scrollViewDidEndDecelerating(scrollView: UIScrollView) { centerCurrentView() } }
mit
07d4255b574b9535774d5a31605ca469
37.961538
171
0.641856
5.019822
false
false
false
false
google/android-auto-companion-ios
Sources/AndroidAutoConnectedDeviceManager/AssociationMessageHelper.swift
1
3914
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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. @_implementationOnly import AndroidAutoCoreBluetoothProtocols import AndroidAutoLogger @_implementationOnly import AndroidAutoMessageStream @_implementationOnly import AndroidAutoSecureChannel import CoreBluetooth import Foundation /// Helper for handling `AssociationManager` message exchange allowing support for different /// versions of the association message exchange. protocol AssociationMessageHelper { static var log: Logger { get } /// Start the message exchange. func start() /// Handle the association message exchange between the device and the car. /// /// - Parameters /// - message: The message to process. /// - params: Contextual info such as operation type and recipient. func handleMessage(_ message: Data, params: MessageStreamParams) /// Invoked when a message that is requested to have been sent has succeeded. func messageDidSendSuccessfully() /// The encryption handshake requires verification using either the full verification data to be /// verified through a separate out of band channel or the visual pairing code. /// /// - Parameter verificationToken: Token with data to verify. func onRequiresPairingVerification(_ verificationToken: SecurityVerificationToken) /// The helper is being notified that the pairing code has been displayed. func onPairingCodeDisplayed() /// The helper is being notified that encryption has been established. func onEncryptionEstablished() } // MARK: - Common Methods extension AssociationMessageHelper { static var handshakeMessageParams: MessageStreamParams { MessageStreamParams(recipient: Config.defaultRecipientUUID, operationType: .encryptionHandshake) } /// Extract the Car ID from the message. /// /// - Returns: The car Id extracted from the message. /// - Throws: An error if the message does not meet the required form for a valid car Id. func extractCarId(fromMessage message: Data) throws -> String { let carId = try CBUUID(carId: message).uuidString Self.log("Received id from car: \(carId)") return carId } /// Returns `true` if the given message is a confirmation that the pairing code has been /// accepted. /// /// - Parameter message: The message to check /// - Returns: `true` if the pairing code has been confirmed. func isPairingCodeConfirmation(_ message: Data) -> Bool { let valueStr = String(data: message, encoding: .utf8) guard valueStr == AssociationManager.pairingCodeConfirmationValue else { Self.log.error( """ Received wrong confirmation for pairing code. Expected \ <\(AssociationManager.pairingCodeConfirmationValue)>, \ but received <\(valueStr ?? "nil")> """ ) return false } return true } /// Concatenate the device id with the authentication key and send it securely to the car. /// /// - Parameter keyData Data for the authentication key to send. func sendDeviceIdPlusAuthenticationKey(keyData: Data, on messageStream: MessageStream) { let deviceId = DeviceIdManager.deviceId var payload = deviceId.data payload.append(keyData) try? messageStream.writeEncryptedMessage( payload, params: Self.handshakeMessageParams ) Self.log("Sending device id: <\(deviceId.uuidString)> plus authentication key.") } }
apache-2.0
7a263fb66c14a5d5ed07208d0a56b46a
36.634615
100
0.734287
4.738499
false
false
false
false
MukeshKumarS/Swift
stdlib/public/Glibc/Glibc.swift
1
5777
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 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 // //===----------------------------------------------------------------------===// @_exported import SwiftGlibc // Clang module //===----------------------------------------------------------------------===// // sys/errno.h //===----------------------------------------------------------------------===// public var errno: Int32 { get { return __errno_location().memory } set(val) { return __errno_location().memory = val } } //===----------------------------------------------------------------------===// // fcntl.h //===----------------------------------------------------------------------===// @warn_unused_result @_silgen_name("_swift_Glibc_open") func _swift_Glibc_open(path: UnsafePointer<CChar>, _ oflag: CInt, _ mode: mode_t ) -> CInt @warn_unused_result @_silgen_name("_swift_Glibc_openat") func _swift_Glibc_openat( fd: CInt, _ path: UnsafePointer<CChar>, _ oflag: CInt, _ mode: mode_t ) -> CInt @warn_unused_result public func open( path: UnsafePointer<CChar>, _ oflag: CInt ) -> CInt { return _swift_Glibc_open(path, oflag, 0) } @warn_unused_result public func open( path: UnsafePointer<CChar>, _ oflag: CInt, _ mode: mode_t ) -> CInt { return _swift_Glibc_open(path, oflag, mode) } @warn_unused_result public func openat( fd: CInt, _ path: UnsafePointer<CChar>, _ oflag: CInt ) -> CInt { return _swift_Glibc_openat(fd, path, oflag, 0) } @warn_unused_result public func openat( fd: CInt, _ path: UnsafePointer<CChar>, _ oflag: CInt, _ mode: mode_t ) -> CInt { return _swift_Glibc_openat(fd, path, oflag, mode) } @warn_unused_result @_silgen_name("_swift_Glibc_fcntl") internal func _swift_Glibc_fcntl( fd: CInt, _ cmd: CInt, _ value: CInt ) -> CInt @warn_unused_result @_silgen_name("_swift_Glibc_fcntlPtr") internal func _swift_Glibc_fcntlPtr( fd: CInt, _ cmd: CInt, _ ptr: UnsafeMutablePointer<Void> ) -> CInt @warn_unused_result public func fcntl( fd: CInt, _ cmd: CInt ) -> CInt { return _swift_Glibc_fcntl(fd, cmd, 0) } @warn_unused_result public func fcntl( fd: CInt, _ cmd: CInt, _ value: CInt ) -> CInt { return _swift_Glibc_fcntl(fd, cmd, value) } @warn_unused_result public func fcntl( fd: CInt, _ cmd: CInt, _ ptr: UnsafeMutablePointer<Void> ) -> CInt { return _swift_Glibc_fcntlPtr(fd, cmd, ptr) } public var S_IFMT: mode_t { return mode_t(0o170000) } public var S_IFIFO: mode_t { return mode_t(0o010000) } public var S_IFCHR: mode_t { return mode_t(0o020000) } public var S_IFDIR: mode_t { return mode_t(0o040000) } public var S_IFBLK: mode_t { return mode_t(0o060000) } public var S_IFREG: mode_t { return mode_t(0o100000) } public var S_IFLNK: mode_t { return mode_t(0o120000) } public var S_IFSOCK: mode_t { return mode_t(0o140000) } public var S_IRWXU: mode_t { return mode_t(0o000700) } public var S_IRUSR: mode_t { return mode_t(0o000400) } public var S_IWUSR: mode_t { return mode_t(0o000200) } public var S_IXUSR: mode_t { return mode_t(0o000100) } public var S_IRWXG: mode_t { return mode_t(0o000070) } public var S_IRGRP: mode_t { return mode_t(0o000040) } public var S_IWGRP: mode_t { return mode_t(0o000020) } public var S_IXGRP: mode_t { return mode_t(0o000010) } public var S_IRWXO: mode_t { return mode_t(0o000007) } public var S_IROTH: mode_t { return mode_t(0o000004) } public var S_IWOTH: mode_t { return mode_t(0o000002) } public var S_IXOTH: mode_t { return mode_t(0o000001) } public var S_ISUID: mode_t { return mode_t(0o004000) } public var S_ISGID: mode_t { return mode_t(0o002000) } public var S_ISVTX: mode_t { return mode_t(0o001000) } //===----------------------------------------------------------------------===// // signal.h //===----------------------------------------------------------------------===// #if os(Linux) public var SIG_DFL: __sighandler_t? { return nil } public var SIG_IGN: __sighandler_t { return unsafeBitCast(1, __sighandler_t.self) } public var SIG_ERR: __sighandler_t { return unsafeBitCast(-1, __sighandler_t.self) } public var SIG_HOLD: __sighandler_t { return unsafeBitCast(2, __sighandler_t.self) } #endif //===----------------------------------------------------------------------===// // semaphore.h //===----------------------------------------------------------------------===// /// The value returned by `sem_open()` in the case of failure. public var SEM_FAILED: UnsafeMutablePointer<sem_t> { // The value is ABI. Value verified to be correct on Glibc. return UnsafeMutablePointer<sem_t>(bitPattern: 0) } @warn_unused_result @_silgen_name("_swift_Glibc_sem_open2") internal func _swift_Glibc_sem_open2( name: UnsafePointer<CChar>, _ oflag: CInt ) -> UnsafeMutablePointer<sem_t> @warn_unused_result @_silgen_name("_swift_Glibc_sem_open4") internal func _swift_Glibc_sem_open4( name: UnsafePointer<CChar>, _ oflag: CInt, _ mode: mode_t, _ value: CUnsignedInt ) -> UnsafeMutablePointer<sem_t> @warn_unused_result public func sem_open( name: UnsafePointer<CChar>, _ oflag: CInt ) -> UnsafeMutablePointer<sem_t> { return _swift_Glibc_sem_open2(name, oflag) } @warn_unused_result public func sem_open( name: UnsafePointer<CChar>, _ oflag: CInt, _ mode: mode_t, _ value: CUnsignedInt ) -> UnsafeMutablePointer<sem_t> { return _swift_Glibc_sem_open4(name, oflag, mode, value) }
apache-2.0
41edef975bcafade8d59d3fa39ec4184
26.122066
80
0.588021
3.280522
false
false
false
false
mitsuyoshi-yamazaki/SwarmChemistry
SwarmChemistryTests/ParametersTests.swift
1
2130
// // ParameterTests.swift // SwarmChemistry // // Created by mitsuyoshi.yamazaki on 2017/08/09. // Copyright © 2017 Mitsuyoshi Yamazaki. All rights reserved. // @testable import SwarmChemistry import XCTest final class ParametersTests: XCTestCase { func test_init() { let values = [ 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0 ] guard let parameters = Parameters(values) else { XCTAssert(false, "Parameter initialization failed") return } XCTAssert(parameters.neighborhoodRadius == 1.0) XCTAssert(parameters.normalSpeed == 2.0) XCTAssert(parameters.maxSpeed == 3.0) XCTAssert(parameters.cohesiveForce == 4.0) XCTAssert(parameters.aligningForce == 5.0) XCTAssert(parameters.separatingForce == 6.0) XCTAssert(parameters.probabilityOfRandomSteering == 7.0) XCTAssert(parameters.tendencyOfPacekeeping == 8.0) XCTAssert(parameters.maxVelocity == 9.0) } func test_all() { let values = [ 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0 ] guard let parameters = Parameters(values) else { XCTAssert(false, "Parameter initialization failed") return } XCTAssert(parameters.all == values) } func test_equality() { let values = [ 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0 ] let anotherValues = [ 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 ] XCTAssert(Parameters(values)! == Parameters(values)!) // swiftlint:disable:this force_unwrapping XCTAssert(Parameters(values)! != Parameters(anotherValues)!) // swiftlint:disable:this force_unwrapping } func test_zero() { let parameters = Parameters.zero XCTAssert(parameters.neighborhoodRadius == 0.0) XCTAssert(parameters.normalSpeed == 0.0) XCTAssert(parameters.maxSpeed == 0.0) XCTAssert(parameters.cohesiveForce == 0.0) XCTAssert(parameters.aligningForce == 0.0) XCTAssert(parameters.separatingForce == 0.0) XCTAssert(parameters.probabilityOfRandomSteering == 0.0) XCTAssert(parameters.tendencyOfPacekeeping == 0.0) XCTAssert(parameters.maxVelocity == 0.0) } func test_random() { XCTAssert(Parameters.random != Parameters.random) } }
mit
918d671d0e34fcdb80b06c736128ba97
31.257576
107
0.679192
3.439418
false
true
false
false
wireapp/wire-ios-sync-engine
Tests/Source/Integration/EventProcessingPerformanceTests.swift
1
4467
// // Wire // Copyright (C) 2017 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation /// These tests are measuring the performance of processing events of /// in different scenarios. /// /// NOTE that we are not receiving encrypted events since we are not /// interested in measuring decryption performance here. class EventProcessingPerformanceTests: IntegrationTest { override func setUp() { super.setUp() createSelfUserAndConversation() createTeamAndConversations() } var users: [MockUser]! var conversations: [MockConversation]! func testTextEventProcessingPerformance_InLargeGroups() { // given createUsersAndConversations(userCount: 100, conversationCount: 10) XCTAssertTrue(login()) simulateApplicationDidEnterBackground() mockTransportSession.performRemoteChanges { (_) in self.conversations.forEach { (conversation) in conversation.insertRandomTextMessages(count: 100, from: self.users) } } // then measure { simulateApplicationWillEnterForeground() XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.5)) } } func testTextEventProcessingPerformance_inSmallGroups() { // given createUsersAndConversations(userCount: 5, conversationCount: 10) XCTAssertTrue(login()) simulateApplicationDidEnterBackground() mockTransportSession.performRemoteChanges { (_) in self.conversations.forEach { (conversation) in conversation.insertRandomTextMessages(count: 100, from: self.users) } } // then measure { simulateApplicationWillEnterForeground() XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.5)) } } func testKnockEventProcessingPerformance() { // given createUsersAndConversations(userCount: 5, conversationCount: 10) XCTAssertTrue(login()) simulateApplicationDidEnterBackground() mockTransportSession.performRemoteChanges { (_) in self.conversations.forEach { (conversation) in conversation.insertRandomKnocks(count: 100, from: self.users) } } // then measure { simulateApplicationWillEnterForeground() XCTAssertTrue(waitForAllGroupsToBeEmpty(withTimeout: 0.5)) } } // MARK: Helpers func createUsersAndConversations(userCount: Int, conversationCount: Int) { mockTransportSession.performRemoteChanges { (session) in self.users = (1...userCount).map({ session.insertUser(withName: "User \($0)") }) let usersIncludingSelfUser = self.users + [self.selfUser!] self.conversations = (1...conversationCount).map({ let conversation = session.insertTeamConversation(to: self.team, with: usersIncludingSelfUser, creator: self.selfUser) conversation.changeName(by: self.selfUser, name: "Team conversation \($0)") return conversation }) } } } extension MockConversation { func insertRandomKnocks(count: Int, from users: [MockUser]) { (1...count).forEach { (_) in let knock = try! GenericMessage(content: Knock.with { $0.hotKnock = false }).serializedData() insertClientMessage(from: users.randomElement()!, data: knock) } } func insertRandomTextMessages(count: Int, from users: [MockUser]) { (1...count).forEach { (counter) in let text = try! GenericMessage(content: Text(content: "Random message \(counter)")).serializedData() insertClientMessage(from: users.randomElement()!, data: text) } } }
gpl-3.0
56784d1667326d7cadb0a952aa31a745
33.099237
134
0.654578
5.070375
false
false
false
false
ZackKingS/Tasks
task/Classes/Others/AppDelegate.swift
1
8622
// // AppDelegate.swift // task // // Created by 柏超曾 on 2017/9/15. // Copyright © 2017年 柏超曾. All rights reserved. // import UIKit import Alamofire import SwiftyJSON import AdSupport @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate ,JPUSHRegisterDelegate {// var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. networkStatusManage() window = UIWindow(frame: UIScreen.main.bounds) // 得到当前应用的版本号 let infoDictionary = Bundle.main.infoDictionary let currentAppVersion = infoDictionary!["CFBundleShortVersionString"] as! String // 取出之前保存的版本号 let userDefaults = UserDefaults.standard let appVersion = userDefaults.string(forKey: "appVersion") let storyboard = UIStoryboard.init(name: "ZBNewFeatureController", bundle: nil) let nav = ZBNavVC.init(rootViewController: TasksViewController()) self.window?.rootViewController = QQDRrawerViewController.drawerWithViewController(_leftViewcontroller: ZBLeftViewController.init(),_mainViewController: nav,DrawerMaxWithd: kMaxLeftOffset) self.window?.makeKeyAndVisible() // if appVersion == nil || appVersion != currentAppVersion { // // userDefaults.setValue(currentAppVersion, forKey: "appVersion") // let guideViewController = storyboard.instantiateInitialViewController() // self.window?.rootViewController = guideViewController // self.window?.makeKeyAndVisible() // // }else{ // // let nav = ZBNavVC.init(rootViewController: TasksViewController()) // self.window?.rootViewController = QQDRrawerViewController.drawerWithViewController(_leftViewcontroller: ZBLeftViewController.init(),_mainViewController: nav,DrawerMaxWithd: kMaxLeftOffset) // self.window?.makeKeyAndVisible() // } // 检测用户是不是第一次启动 config() // NetworkTool.errorMessage(error: "2333333") //1. 任务详情的url是写死的 //2. 跳转更新的url是写死的 //3. 推送 // let entity = JPUSHRegisterEntity(); // entity.types = Int(JPAuthorizationOptions.alert.rawValue) | Int(JPAuthorizationOptions.sound.rawValue) | Int(JPAuthorizationOptions.badge.rawValue); // JPUSHService.register(forRemoteNotificationConfig: entity, delegate: self); // // 注册极光推送 // JPUSHService.setup(withOption: launchOptions, appKey: "845b93e08c7fa192df019c07", channel:"Publish channel" , apsForProduction: false); // // 获取推送消息 // let remote = launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] as? Dictionary<String,Any>; // // 如果remote不为空,就代表应用在未打开的时候收到了推送消息 // if remote != nil { // // 收到推送消息实现的方法 //// self.perform(#selector(receivePush), with: remote, afterDelay: 1.0); // } return true } @available(iOS 10.0, *) func jpushNotificationCenter(_ center: UNUserNotificationCenter!, willPresent notification: UNNotification!, withCompletionHandler completionHandler: ((Int) -> Void)!) { print(">JPUSHRegisterDelegate jpushNotificationCenter willPresent") } @available(iOS 10.0, *) func jpushNotificationCenter(_ center: UNUserNotificationCenter!, didReceive response: UNNotificationResponse!, withCompletionHandler completionHandler: (() -> Void)!) { print(">JPUSHRegisterDelegate jpushNotificationCenter didReceive") } // func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { // // // JPUSHService.handleRemoteNotification(userInfo) //// let alert: String = userInfo["aps"]!["alert"] //// var badge: Int = userInfo["aps"]!["badge"] //// badge -= 1 //// JPUSHService.setBadge(badge) //// UIApplication.shared.applicationIconBadgeNumber = 0 //// /** //// * iOS的应用程序分为3种状态 //// * 1、前台运行的状态UIApplicationStateActive; //// * 2、后台运行的状态UIApplicationStateInactive; //// * 3、app关闭状态UIApplicationStateBackground。 //// */ //// // 应用在前台 或者后台开启状态下,不跳转页面,让用户选择。 //// if (application.applicationState == UIApplicationState.active) || (application.applicationState == UIApplicationState.background){ //// UIAlertView(title: "推送消息", message: "\(alert)", delegate: nil, cancelButtonTitle: "确定").show() //// }else{ //// //杀死状态下,直接跳转到跳转页面 //// } //// // badge清零 //// application.applicationIconBadgeNumber = 0 //// JPUSHService.resetBadge() //// completionHandler(UIBackgroundFetchResult.newData) // // // } func config(){ let nowDate = NSDate(timeIntervalSinceNow: 0) // 时间戳的值 let timeStamp:CLong = CLong(nowDate.timeIntervalSince1970) print(timeStamp) print(UserDefaults.standard.bool(forKey: "LGFirstLaunch")) if !UserDefaults.standard.bool(forKey: "LGFirstLaunch") { UserDefaults.standard.set(false, forKey: ZBLOGIN_KEY) UserDefaults.standard.set(true, forKey: "LGFirstLaunch") UserDefaults.standard.synchronize() } } func networkStatusManage(){ let manager = NetworkReachabilityManager(host: "https://www.baidu.com") manager!.listener = { status in switch status { case .notReachable: print("notReachable") UserDefaults.standard.set("a_notReachable_network", forKey: "network") case .unknown: print("unknown") UserDefaults.standard.set("b_unknown_network", forKey: "network") case .reachable(.ethernetOrWiFi): print("ethernetOrWiFi") UserDefaults.standard.set("c_ethernetOrWiFi_network", forKey: "network") case .reachable(.wwan): print("wwan") UserDefaults.standard.set("d_wwan_network", forKey: "network") } } manager!.startListening() } 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:. } }
apache-2.0
39f4943119874ebfb603d5aba3ab65b4
39.141463
285
0.654393
5.017683
false
false
false
false
macc704/iKF
iKF/KFPostRefIconView.swift
1
891
// // KFPostRefIconView.swift // iKF // // Created by Yoshiaki Matsuzawa on 2014-06-09. // Copyright (c) 2014 Yoshiaki Matsuzawa. All rights reserved. // import UIKit class KFPostRefIconView: UIView { var beenRead = false; let icon:UIImageView!; let iconx:UIImageView!; required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(frame: CGRect) { icon = UIImageView(image: UIImage(named: "note.png")); icon.frame = frame; iconx = UIImageView(image: UIImage(named: "notex.png")); iconx.frame = frame; super.init(frame: frame); update(); } func update(){ icon.removeFromSuperview(); iconx.removeFromSuperview(); if(beenRead){ self.addSubview(icon); }else{ self.addSubview(iconx); } } }
gpl-2.0
4b791897e0256b4a809d42ceebec87de
21.846154
64
0.583614
3.907895
false
false
false
false
Meniny/Oops
Oops/Extensions.swift
1
11608
// // MXExtensions.swift // Oops // // Created by Meniny on 16/04/16. // Copyright © 2016 Meniny. All rights reserved. // import Foundation import UIKit public extension Oops { // Pop Up Styles public enum PopUpStyle: String { case success = "Success" case error = "Error" case notice = "Notice" case warning = "Warning" case info = "Info" case editor = "Editor" case loading = "Loading" case question = "Question" public var defaultUIntColor: UInt { switch self { case .success: return 0x22B573 case .error: return 0xC1272D case .notice: return 0x727375 case .warning: return 0xFFD110 case .info: return 0x2866BF case .editor: return 0xA429FF case .loading: return 0x3C3C46//0xD62DA5 case .question: return 0x727375 } } public var defaultUIColor: UIColor { return UIColorFromRGB(defaultUIntColor) } public var defaultButtonTextColor: UIColor { switch self { case .warning: return UIColor.black default: return UIColor.white } } public var icon: UIImage? { switch self { case .success: return Oops.IconPainting.imageOfCheckmark case .error: return Oops.IconPainting.imageOfCross case .notice: return Oops.IconPainting.imageOfNotice case .warning: return Oops.IconPainting.imageOfWarning case .info: return Oops.IconPainting.imageOfInfo case .editor: return Oops.IconPainting.imageOfEditor case .loading: return nil case .question: return Oops.IconPainting.imageOfQuestion } } } // Animation Styles public enum AnimationStyle { case none, topToBottom, bottomToTop, leftToRight, rightToLeft } // Action Types public enum ActionType { case none, selector, closure } public enum ButtonLayout { case horizontal, vertical } public typealias DismissClosure = (Swift.Void) -> Swift.Void public class Configuration { public class func defaultConfiguration() -> Oops.Configuration { return Oops.Configuration() } public var defaultShadowOpacity: CGFloat// = 0.7 public var circleTopPosition: CGFloat// = 0 public var circleBackgroundTopPosition: CGFloat// = 6 public var circleHeight: CGFloat// = 56 public var circleIconHeight: CGFloat// = 20 public var titleTop: CGFloat// = 30 public var titleHeight: CGFloat// = 25 public var windowWidth: CGFloat// = 240 public var windowHeight: CGFloat// = 178 public var textHeight: CGFloat// = 90 public var textFieldHeight: CGFloat// = 55 public var textViewdHeight: CGFloat// = 80 public var buttonHeight: CGFloat// = 40 public var titleFont: UIFont// = UIFont.systemFont(ofSize: 20) public var titleMinimumScaleFactor: CGFloat// = 1 public var textFont: UIFont// = UIFont.systemFont(ofSize: 14) public var buttonFont: UIFont// = UIFont.boldSystemFont(ofSize: 14) public var showCloseButton: Bool// = true public var showCircularIcon: Bool// = true /// Set this false to 'Disable' Auto hideView when Oops.Button is tapped public var shouldAutoDismiss: Bool// = true public var contentViewCornerRadius: CGFloat// = 5 public var fieldCornerRadius: CGFloat// = 3 public var buttonCornerRadius: CGFloat// = 3 /// Actions public var hideWhenBackgroundViewIsTapped: Bool// = false public var circleBackgroundColor: UIColor// = UIColor.white public var contentViewColor: UIColor// = UIColorFromRGB(kUIntWhite) public var contentViewBorderColor: UIColor// = UIColorFromRGB(0xCCCCCC) public var titleColor: UIColor// = UIColorFromRGB(0x4D4D4D) public var dynamicAnimatorActive: Bool// = false public var disableTapGesture: Bool// = false public var buttonsLayout: Oops.ButtonLayout// = .vertical public var optionalButtonColor: UIColor? public var optionalButtonTitleColor: UIColor? public var normalButtonColor: UIColor? public var normalButtonTitleColor: UIColor? public init(defaultShadowOpacity: CGFloat = 0.7, circleTopPosition: CGFloat = 0, circleBackgroundTopPosition: CGFloat = 6, circleHeight: CGFloat = 56, circleIconHeight: CGFloat = 20, titleTop: CGFloat = 30, titleHeight: CGFloat = 25, windowWidth: CGFloat = 240, windowHeight: CGFloat = 178, textHeight: CGFloat = 90, textFieldHeight: CGFloat = 40, textViewdHeight: CGFloat = 80, buttonHeight: CGFloat = 40, titleFont: UIFont = UIFont.systemFont(ofSize: 20), titleMinimumScaleFactor: CGFloat = 1, textFont: UIFont = UIFont.systemFont(ofSize: 14), buttonFont: UIFont = UIFont.boldSystemFont(ofSize: 14), showCloseButton: Bool = true, showCircularIcon: Bool = true, shouldAutoDismiss: Bool = true, contentViewCornerRadius: CGFloat = 5, fieldCornerRadius: CGFloat = 3, buttonCornerRadius: CGFloat = 3, hideWhenBackgroundViewIsTapped: Bool = false, circleBackgroundColor: UIColor = UIColor.white, contentViewColor: UIColor = UIColorFromRGB(kUIntWhite), contentViewBorderColor: UIColor = UIColorFromRGB(0xCCCCCC), titleColor: UIColor = UIColorFromRGB(0x4D4D4D), optionalButtonColor: UIColor? = nil,//UIColor(red:0.45, green:0.45, blue:0.46, alpha:1.00), optionalButtonTitleColor: UIColor? = nil,//UIColor.white, normalButtonColor: UIColor? = nil,//UIColor(red:0.24, green:0.24, blue:0.27, alpha:1.00), normalButtonTitleColor: UIColor? = nil,//UIColor.white, dynamicAnimatorActive: Bool = false, disableTapGesture: Bool = false, buttonsLayout: Oops.ButtonLayout = .vertical) { self.defaultShadowOpacity = defaultShadowOpacity self.circleTopPosition = circleTopPosition self.circleBackgroundTopPosition = circleBackgroundTopPosition self.circleHeight = circleHeight self.circleIconHeight = circleIconHeight self.titleTop = titleTop self.titleHeight = titleHeight self.windowWidth = windowWidth self.windowHeight = windowHeight self.textHeight = textHeight self.textFieldHeight = textFieldHeight self.textViewdHeight = textViewdHeight self.buttonHeight = buttonHeight self.circleBackgroundColor = circleBackgroundColor self.contentViewColor = contentViewColor self.contentViewBorderColor = contentViewBorderColor self.titleColor = titleColor self.titleFont = titleFont self.titleMinimumScaleFactor = titleMinimumScaleFactor self.textFont = textFont self.buttonFont = buttonFont self.disableTapGesture = disableTapGesture self.showCloseButton = showCloseButton self.showCircularIcon = showCircularIcon self.shouldAutoDismiss = shouldAutoDismiss self.contentViewCornerRadius = contentViewCornerRadius self.fieldCornerRadius = fieldCornerRadius self.buttonCornerRadius = buttonCornerRadius self.hideWhenBackgroundViewIsTapped = hideWhenBackgroundViewIsTapped self.dynamicAnimatorActive = dynamicAnimatorActive self.buttonsLayout = buttonsLayout self.normalButtonColor = normalButtonColor self.normalButtonTitleColor = normalButtonTitleColor self.optionalButtonColor = optionalButtonColor self.optionalButtonTitleColor = optionalButtonTitleColor } public func set(windowHeight height: CGFloat) { windowHeight = height } public func set(textHeight height: CGFloat) { textHeight = height } } public struct TimeoutConfiguration { public typealias ActionClosure = () -> Swift.Void public var value: TimeInterval public let action: Oops.TimeoutConfiguration.ActionClosure mutating func increaseValue(by: Double) { self.value = value + by } public init(timeoutValue: TimeInterval, timeoutAction: @escaping Oops.TimeoutConfiguration.ActionClosure) { self.value = timeoutValue self.action = timeoutAction } } } public let kUIntWhite: UInt = 0xFFFFFF public let kUIntBlack: UInt = 0x000000 public let kCircleHeightBackground: CGFloat = 62 public let kUniqueTag: Int = Int(arc4random() % UInt32(Int32.max)) public let kUniqueAccessibilityIdentifier: String = "Oops" // Helper function to convert from RGB to UIColor public func UIColorFromRGB(_ rgbValue: UInt) -> UIColor { return UIColor( red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255, green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255, blue: CGFloat(rgbValue & 0x0000FF) / 255, alpha: CGFloat(1.0) ) } extension Int { func toUIColor() -> UIColor { return UIColor( red: CGFloat((self & 0xFF0000) >> 16) / 255, green: CGFloat((self & 0x00FF00) >> 8) / 255, blue: CGFloat(self & 0x0000FF) / 255, alpha: CGFloat(1.0) ) } func toCGColor() -> CGColor { return self.toUIColor().cgColor } } extension UInt { func toUIColor() -> UIColor { return UIColor( red: CGFloat((self & 0xFF0000) >> 16) / 255, green: CGFloat((self & 0x00FF00) >> 8) / 255, blue: CGFloat(self & 0x0000FF) / 255, alpha: CGFloat(1.0) ) } func toCGColor() -> CGColor { return self.toUIColor().cgColor } } extension String { func heightWithConstrainedWidth(_ width: CGFloat, font: UIFont) -> CGFloat { let constraintRect = CGSize(width: width, height: CGFloat.greatestFiniteMagnitude) let boundingBox = self.boundingRect(with: constraintRect, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil) return boundingBox.height } }
mit
861a2796b036c2a4117cac8d8cc5994f
36.201923
176
0.583355
5.324312
false
false
false
false
SunChJ/functional-swift
Fundational-Swift/FilterDemo/FilterDefine.swift
1
2705
// // FilterDefine.swift // FilterDemo // // Created by 孙超杰 on 2017/3/2. // Copyright © 2017年 Chaojie Sun. All rights reserved. // import UIKit // 定义Filter类型为一个函数 typealias Filter = (CIImage) -> CIImage // 构建滤镜 //func myFilter(/*parameters*/) -> Filter // 模糊滤镜 func blur(radius: Double) -> Filter { return { image in let parameters = [ kCIInputRadiusKey: radius, kCIInputImageKey: image ] as [String : Any] guard let filter = CIFilter(name: "CIGaussianBlur", withInputParameters: parameters) else {fatalError()} guard let outputImage = filter.outputImage else {fatalError()} return outputImage } } // 颜色叠层(固定颜色+定义合成滤镜) // 生产固定颜色的滤镜 func colorGenerator(color: UIColor) -> Filter { return { _ in let c = CIColor(color: color) let parameters = [kCIInputColorKey: c] guard let filter = CIFilter(name: "CIConstantColorGenerator", withInputParameters: parameters) else {fatalError()} guard let outputImage = filter.outputImage else {fatalError()} return outputImage } } // 定义合成滤镜 func compositeSourceOver(overlay: CIImage) -> Filter { return { image in let parameters = [ kCIInputBackgroundImageKey: image, kCIInputImageKey: overlay ] guard let filter = CIFilter(name: "CISourceOverCompositing", withInputParameters: parameters) else {fatalError()} guard let outputImage = filter.outputImage else {fatalError()} let cropRect = image.extent return outputImage.cropping(to: cropRect) } } // 最后的合成 func colorOverlay(color: UIColor) -> Filter { return { image in let overlay = colorGenerator(color: color)(image) return compositeSourceOver(overlay: overlay)(image) } } // 定义一个用于组合滤镜的函数 func composeFilter(filter1: @escaping Filter, _ filter2: @escaping Filter) -> Filter { return { image in filter2(filter1(image))} } // 自定义运算符 // 为了让代码更具有可读性, 我们可以再进一步, 为组合滤镜引入运算符 // 诚然, 随意自定义运算符并不一定对提升代码可读性有帮助。不过,在图像处理库中, 滤镜的组合式一个反复背讨论的问题, 所以引入运算符极有意义 precedencegroup FilterCopositivePrecedence { associativity: left higherThan: MultiplicationPrecedence } infix operator >>>: FilterCopositivePrecedence func >>>(filter1: @escaping Filter, filter2: @escaping Filter) -> Filter { return {image in filter2(filter1(image))} }
mit
5df951867359a39714a61a26265c0858
27.756098
122
0.677693
3.840391
false
false
false
false
Mclarenyang/medicine_aid
medicine aid/changeInfoViewController.swift
1
14149
// // changeInfoViewController.swift // medicine aid // // Created by nexuslink mac 2 on 2017/7/9. // Copyright © 2017年 NMID. All rights reserved. // import UIKit import RealmSwift import Alamofire import SwiftyJSON class changeInfoViewController: UIViewController, UITextFieldDelegate { // 屏幕信息 let screenWidth = UIScreen.main.bounds.width let screenHeight = UIScreen.main.bounds.height //设置状态码(确定修改的是哪个信息) var key = 0 var infoTextfield = UITextField() // var checkBtn1 = UIButton() var checkBtn2 = UIButton() //密码修改窗口 var oldPassword = UITextField() var newPassword1 = UITextField() var newPassword2 = UITextField() let defaults = UserDefaults.standard override func viewDidLoad() { super.viewDidLoad() //标题 changeNaviagtionBar() //首先加载背景 let bgView = UIView(frame:UIScreen.main.bounds) bgView.backgroundColor = UIColor(red:226/255,green:226/255,blue:226/255 ,alpha: 1) self.view.addSubview(bgView) // switch key { case 0,1,3,4: labelChange() case 2: chooseChange() case 5: passwordChange() default: print("error") } // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //使用一条状态条修改的方法 func labelChange() { //定义底层白条 let whiteView = UIView(frame:CGRect(x:0,y:70,width:screenWidth,height:40)) whiteView.backgroundColor = UIColor.white self.view.addSubview(whiteView) infoTextfield = UITextField(frame:CGRect(x:10,y:0,width:screenWidth-10,height:40)) infoTextfield.clearButtonMode = UITextFieldViewMode.whileEditing whiteView.addSubview(infoTextfield) infoTextfield.delegate = self let UserID = defaults.value(forKey: "UserID")! let realm = try! Realm() let User = realm.objects(UserText.self).filter("UserID = '\(UserID)'")[0] //依然使用状态码识别 switch key { case 0: infoTextfield.text = User.UserNickname case 1: infoTextfield.text = User.UserName case 3: infoTextfield.text = User.UserAge case 4: infoTextfield.text = User.UserPhoneNum default: print("error") } } //修改信息 return func textFieldShouldReturn(_ textField: UITextField) -> Bool { let UserID = defaults.value(forKey: "UserID")! let realm = try! Realm() let User = realm.objects(UserText.self).filter("UserID = '\(UserID)'")[0] realm.beginWrite() switch key { case 0: User.UserNickname = infoTextfield.text synchronizationInfoInNet(newNickname: infoTextfield.text!) case 1: User.UserName = infoTextfield.text case 3: User.UserAge = infoTextfield.text case 4: User.UserPhoneNum = infoTextfield.text case 5: print("修改密码") synchronizationPassword() default: print("error") } try! realm.commitWrite() textField.resignFirstResponder() _ = self.navigationController?.popViewController(animated: true) return true } //密码修改 func passwordChange(){ ///定义两行选择 //定义底层白条 let whiteView1 = UIView(frame:CGRect(x:0,y:70,width:screenWidth,height:40)) let whiteView2 = UIView(frame:CGRect(x:0,y:112,width:screenWidth,height:40)) let whiteView3 = UIView(frame:CGRect(x:0,y:154,width:screenWidth,height:40)) whiteView1.backgroundColor = UIColor.white whiteView2.backgroundColor = UIColor.white whiteView3.backgroundColor = UIColor.white self.view.addSubview(whiteView1) self.view.addSubview(whiteView2) self.view.addSubview(whiteView3) //密码窗口 oldPassword = UITextField(frame:CGRect(x:10,y:0,width:screenWidth-10,height:40)) newPassword1 = UITextField(frame:CGRect(x:10,y:0,width:screenWidth-10,height:40)) newPassword2 = UITextField(frame:CGRect(x:10,y:0,width:screenWidth-10,height:40)) oldPassword.clearButtonMode = UITextFieldViewMode.whileEditing newPassword1.clearButtonMode = UITextFieldViewMode.whileEditing newPassword2.clearButtonMode = UITextFieldViewMode.whileEditing oldPassword.delegate = self newPassword1.delegate = self newPassword2.delegate = self oldPassword.isSecureTextEntry = true newPassword1.isSecureTextEntry = true newPassword2.isSecureTextEntry = true oldPassword.keyboardType = .namePhonePad newPassword1.keyboardType = .namePhonePad newPassword2.keyboardType = .namePhonePad oldPassword.placeholder = "请输入旧密码" newPassword1.placeholder = "请输入新密码" newPassword2.placeholder = "再次输入新密码" whiteView1.addSubview(oldPassword) whiteView2.addSubview(newPassword1) whiteView3.addSubview(newPassword2) // 导出按钮 let doneBtn = UIButton(frame:CGRect(x:80,y:screenHeight*5/7+90,width:screenWidth-165,height:55)) doneBtn.setBackgroundImage(UIImage(named:"register_done_bt"), for: UIControlState.normal) doneBtn.addTarget(self, action: #selector(synchronizationPassword) , for: UIControlEvents.touchUpInside) self.view.addSubview(doneBtn) } //使用选择修改性别 func chooseChange() { ///定义两行选择 //定义底层白条 let whiteView1 = UIView(frame:CGRect(x:0,y:70,width:screenWidth,height:40)) let whiteView2 = UIView(frame:CGRect(x:0,y:112,width:screenWidth,height:40)) whiteView1.backgroundColor = UIColor.white whiteView2.backgroundColor = UIColor.white let gesture1 = UITapGestureRecognizer() gesture1.addTarget(self, action: #selector(tapMale)) let gesture2 = UITapGestureRecognizer() gesture2.addTarget(self, action: #selector(tapFemale)) whiteView1.isUserInteractionEnabled = true whiteView2.isUserInteractionEnabled = true whiteView1.addGestureRecognizer(gesture1) whiteView2.addGestureRecognizer(gesture2) self.view.addSubview(whiteView1) self.view.addSubview(whiteView2) //label let maleLabel = UILabel(frame:CGRect(x:10,y:0,width:screenWidth-10,height:40)) let femaleLabel = UILabel(frame:CGRect(x:10,y:0,width:screenWidth-10,height:40)) maleLabel.text = "男" femaleLabel.text = "女" whiteView1.addSubview(maleLabel) whiteView2.addSubview(femaleLabel) //button checkBtn1 = UIButton(frame:CGRect(x:screenWidth-30,y:10,width:20,height:20)) checkBtn2 = UIButton(frame:CGRect(x:screenWidth-30,y:10,width:20,height:20)) checkBtn1.setBackgroundImage(UIImage(named:"checkBtn"), for: .normal) checkBtn2.setBackgroundImage(UIImage(named:"checkBtn"), for: .normal) whiteView1.addSubview(checkBtn1) whiteView2.addSubview(checkBtn2) getSex() } //修改navigation title func changeNaviagtionBar() { switch key { case 0: self.navigationItem.title = "昵称" case 1: self.navigationItem.title = "姓名" case 2: self.navigationItem.title = "性别" case 3: self.navigationItem.title = "年龄" case 4: self.navigationItem.title = "电话" case 5: self.navigationItem.title = "密码修改" default: self.navigationItem.title = "error" } } //性别确认方法 func getSex() { let UserID = defaults.value(forKey: "UserID")! let realm = try! Realm() let User = realm.objects(UserText.self).filter("UserID = '\(UserID)'")[0] if User.UserSex == "男"{ checkBtn2.isHidden = true }else{ checkBtn1.isHidden = true } } func tapMale() { let UserID = defaults.value(forKey: "UserID")! let realm = try! Realm() let User = realm.objects(UserText.self).filter("UserID = '\(UserID)'")[0] if User.UserSex == "男"{ }else{ realm.beginWrite() User.UserSex = "男" try! realm.commitWrite() checkBtn1.isHidden = false checkBtn2.isHidden = true } _ = self.navigationController?.popViewController(animated: true) } func tapFemale() { let UserID = defaults.value(forKey: "UserID")! let realm = try! Realm() let User = realm.objects(UserText.self).filter("UserID = '\(UserID)'")[0] if User.UserSex == "女"{ }else{ realm.beginWrite() User.UserSex = "女" try! realm.commitWrite() checkBtn1.isHidden = true checkBtn2.isHidden = false } _ = self.navigationController?.popViewController(animated: true) } //网路接口_信息修改同步(nickname) func synchronizationInfoInNet(newNickname: String) { //用户Id let UserID = String(describing: defaults.value(forKey: "UserID")!) let url = AESEncoding.myURL + "igds/app/user/updateNickname" let parameters : Parameters = [ "idString": UserID, "newNickname": AESEncoding.Endcode_AES_ECB(strToEncode: newNickname, typeCode: .nickName) ] Alamofire.request(url, method: .post, parameters: parameters).responseJSON{ classValue in if let value = classValue.result.value{ let json = JSON(value) let code = json["code"] print("修改昵称code:\(code)") } } } //网路接口_信息修改同步(password) func synchronizationPassword() { //用户Id let UserID = String(describing: defaults.value(forKey: "UserID")!) //密码 let oldP = oldPassword.text let newP1 = newPassword1.text let newP2 = newPassword2.text if newP1 == newP2 { let url = AESEncoding.myURL + "igds/app/user/updatePassword" let parameters : Parameters = [ "idString": UserID, "oldPassword": AESEncoding.Endcode_AES_ECB(strToEncode: oldP!, typeCode: .passWord), "newPassword": AESEncoding.Endcode_AES_ECB(strToEncode: newP1!, typeCode: .passWord) ] Alamofire.request(url, method: .post, parameters: parameters).responseJSON{ classValue in if let value = classValue.result.value{ let json = JSON(value) let code = json["code"] print("修改密码code:\(code)") if code == 422 { let alert = UIAlertController(title: "错误提示", message: "旧密码错误", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "好", style: .cancel, handler: { _ in self.dismiss(animated: true, completion: nil) })) self.present(alert, animated: true, completion: nil) }else if code == 201 { let alert = UIAlertController(title: "提示", message: "修改成功", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "好", style: .cancel, handler: { _ in self.dismiss(animated: true, completion: nil) _ = self.navigationController?.popViewController(animated: true) })) self.present(alert, animated: true, completion: nil) } } } }else{ let alert = UIAlertController(title: "错误提示", message: "新密码不一致", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "好", style: .cancel, handler: { _ in self.dismiss(animated: true, completion: nil) self.newPassword1.text = "" self.newPassword2.text = "" })) self.present(alert, animated: true, completion: nil) } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
apache-2.0
4034eda900b5ab4b165caeebe01ff50b
31.536817
112
0.555702
4.772822
false
false
false
false
naithar/Kitura
Tests/KituraTests/TestStaticFileServer.swift
1
11188
/** * Copyright IBM Corporation 2016 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import XCTest import Foundation import SwiftyJSON @testable import Kitura @testable import KituraNet #if os(Linux) import Glibc #else import Darwin #endif class TestStaticFileServer: KituraTest { static var allTests: [(String, (TestStaticFileServer) -> () throws -> Void)] { return [ ("testFileServer", testFileServer), ("testGetWithWhiteSpaces", testGetWithWhiteSpaces), ("testGetWithSpecialCharacters", testGetWithSpecialCharacters), ("testGetWithSpecialCharactersEncoded", testGetWithSpecialCharactersEncoded), ("testGetKituraResource", testGetKituraResource), ("testGetMissingKituraResource", testGetMissingKituraResource), ("testAbsolutePathFunction", testAbsolutePathFunction) ] } let router = TestStaticFileServer.setupRouter() func testFileServer() { performServerTest(router, asyncTasks: { expectation in self.performRequest("get", path:"/qwer", callback: {response in XCTAssertNotNil(response, "ERROR!!! ClientRequest response object was nil") XCTAssertEqual(response?.statusCode, HTTPStatusCode.OK, "HTTP Status code was \(String(describing: response?.statusCode))") do { let body = try response?.readString() XCTAssertEqual(body, "<!DOCTYPE html><html><body><b>Index</b></body></html>\n") } catch { XCTFail("No response body") } XCTAssertEqual(response?.headers["x-custom-header"]?.first, "Kitura") XCTAssertNotNil(response?.headers["Last-Modified"]) XCTAssertNotNil(response?.headers["Etag"]) XCTAssertEqual(response?.headers["Cache-Control"]?.first, "max-age=2") expectation.fulfill() }) }, { expectation in self.performRequest("get", path:"/qwer/index.html", callback: {response in XCTAssertNotNil(response, "ERROR!!! ClientRequest response object was nil") XCTAssertEqual(response?.statusCode, HTTPStatusCode.OK, "HTTP Status code was \(String(describing: response?.statusCode))") do { let body = try response?.readString() XCTAssertEqual(body, "<!DOCTYPE html><html><body><b>Index</b></body></html>\n") } catch { XCTFail("No response body") } expectation.fulfill() }) }, { expectation in self.performRequest("get", path:"/qwer/index", callback: {response in XCTAssertNotNil(response, "ERROR!!! ClientRequest response object was nil") XCTAssertEqual(response?.statusCode, HTTPStatusCode.OK, "HTTP Status code was \(String(describing: response?.statusCode))") do { let body = try response?.readString() XCTAssertEqual(body, "<!DOCTYPE html><html><body><b>Index</b></body></html>\n") } catch { XCTFail("No response body") } expectation.fulfill() }) }, { expectation in self.performRequest("get", path:"/zxcv/index.html", callback: {response in XCTAssertNotNil(response, "ERROR!!! ClientRequest response object was nil") XCTAssertEqual(response?.statusCode, HTTPStatusCode.OK, "HTTP Status code was \(String(describing: response?.statusCode))") do { let body = try response?.readString() XCTAssertEqual(body, "<!DOCTYPE html><html><body><b>Index</b></body></html>\n") } catch { XCTFail("No response body") } XCTAssertNil(response?.headers["x-custom-header"]) XCTAssertNil(response?.headers["Last-Modified"]) XCTAssertNil(response?.headers["Etag"]) XCTAssertEqual(response?.headers["Cache-Control"]?.first, "max-age=0") expectation.fulfill() }) }, { expectation in self.performRequest("get", path:"/zxcv", callback: {response in XCTAssertNotNil(response, "ERROR!!! ClientRequest response object was nil") XCTAssertEqual(response?.statusCode, HTTPStatusCode.notFound, "HTTP Status code was \(String(describing: response?.statusCode))") expectation.fulfill() }) }, { expectation in self.performRequest("get", path:"/zxcv/index", callback: {response in XCTAssertNotNil(response, "ERROR!!! ClientRequest response object was nil") XCTAssertEqual(response?.statusCode, HTTPStatusCode.notFound, "HTTP Status code was \(String(describing: response?.statusCode))") expectation.fulfill() }) }, { expectation in self.performRequest("get", path:"/asdf", callback: {response in XCTAssertNotNil(response, "ERROR!!! ClientRequest response object was nil") XCTAssertEqual(response?.statusCode, HTTPStatusCode.notFound, "HTTP Status code was \(String(describing: response?.statusCode))") expectation.fulfill() }) }, { expectation in self.performRequest("put", path:"/asdf", callback: {response in XCTAssertNotNil(response, "ERROR!!! ClientRequest response object was nil") XCTAssertEqual(response?.statusCode, HTTPStatusCode.notFound, "HTTP Status code was \(String(describing:response?.statusCode))") expectation.fulfill() }) }, { expectation in self.performRequest("get", path:"/asdf/", callback: {response in XCTAssertNotNil(response, "ERROR!!! ClientRequest response object was nil") XCTAssertEqual(response?.statusCode, HTTPStatusCode.OK, "HTTP Status code was \(String(describing: response?.statusCode))") do { let body = try response?.readString() XCTAssertEqual(body, "<!DOCTYPE html><html><body><b>Index</b></body></html>\n") } catch { XCTFail("No response body") } XCTAssertNil(response?.headers["x-custom-header"]) XCTAssertNotNil(response?.headers["Last-Modified"]) XCTAssertNotNil(response?.headers["Etag"]) XCTAssertEqual(response?.headers["Cache-Control"]?.first, "max-age=0") expectation.fulfill() }) }) } static func setupRouter() -> Router { let router = Router() var cacheOptions = StaticFileServer.CacheOptions(maxAgeCacheControlHeader: 2) var options = StaticFileServer.Options(possibleExtensions: ["exe", "html"], cacheOptions: cacheOptions) router.all("/qwer", middleware: StaticFileServer(path: "./Tests/KituraTests/TestStaticFileServer/", options:options, customResponseHeadersSetter: HeaderSetter())) cacheOptions = StaticFileServer.CacheOptions(addLastModifiedHeader: false, generateETag: false) options = StaticFileServer.Options(serveIndexForDirectory: false, cacheOptions: cacheOptions) router.all("/zxcv", middleware: StaticFileServer(path: "./Tests/KituraTests/TestStaticFileServer/", options:options)) options = StaticFileServer.Options(redirect: false) let directoryURL = URL(fileURLWithPath: #file + "/../TestStaticFileServer").standardizedFileURL router.all("/asdf", middleware: StaticFileServer(path: directoryURL.path, options:options)) return router } class HeaderSetter: ResponseHeadersSetter { func setCustomResponseHeaders(response: RouterResponse, filePath: String, fileAttributes: [FileAttributeKey : Any]) { response.headers["x-custom-header"] = "Kitura" } } private typealias BodyChecker = (String) -> Void private func runGetResponseTest(path: String, expectedResponseText: String? = nil, expectedStatusCode: HTTPStatusCode = HTTPStatusCode.OK, bodyChecker: BodyChecker? = nil) { performServerTest(router) { expectation in self.performRequest("get", path: path, callback: { response in guard let response = response else { XCTFail("ClientRequest response object was nil") expectation.fulfill() return } XCTAssertEqual(response.statusCode, expectedStatusCode, "No success status code returned") if let optionalBody = try? response.readString(), let body = optionalBody { if let expectedResponseText = expectedResponseText { XCTAssertEqual(body, expectedResponseText, "mismatch in body") } bodyChecker?(body) } else { XCTFail("No response body") } expectation.fulfill() }) } } func testGetWithWhiteSpaces() { runGetResponseTest(path: "/qwer/index%20with%20whitespace.html", expectedResponseText: "<!DOCTYPE html><html><body><b>Index with whitespace</b></body></html>\n") } func testGetWithSpecialCharacters() { runGetResponseTest(path: "/qwer/index+@,.html", expectedResponseText: "<!DOCTYPE html><html><body><b>Index with plus at comma</b></body></html>\n") } func testGetWithSpecialCharactersEncoded() { runGetResponseTest(path: "/qwer/index%2B%40%2C.html", expectedResponseText: "<!DOCTYPE html><html><body><b>Index with plus at comma</b></body></html>\n") } func testGetKituraResource() { runGetResponseTest(path: "/@@Kitura-router@@/") } func testGetMissingKituraResource() { runGetResponseTest(path: "/@@Kitura-router@@/missing.file", expectedStatusCode: HTTPStatusCode.notFound) } func testAbsolutePathFunction() { XCTAssertEqual(StaticFileServer.ResourcePathHandler.getAbsolutePath(for: "/"), "/", "Absolute path did not resolve to system root") } }
apache-2.0
3e3a2c5226230e965ac81d2eb6b4b08a
49.854545
170
0.598141
5.32255
false
true
false
false
trill-lang/LLVMSwift
Sources/LLVM/Constant.swift
1
62015
#if SWIFT_PACKAGE import cllvm #endif /// An `IRConstant` is an entity whose value doees not change during the /// runtime of a program. This includes global variables and functions, whose /// addresses are constant, and constant expressions. public protocol IRConstant: IRValue {} extension IRConstant { /// Perform a GEP (Get Element Pointer) with this value as the base. /// /// - parameter indices: A list of indices that indicate which of the elements /// of the aggregate object are indexed. /// /// - returns: A value representing the address of a subelement of the given /// aggregate data structure value. public func constGEP(indices: [IRConstant]) -> IRConstant { var idxs = indices.map { $0.asLLVM() as Optional } return idxs.withUnsafeMutableBufferPointer { buf in return Constant<Struct>(llvm: LLVMConstGEP(asLLVM(), buf.baseAddress, UInt32(buf.count))) } } /// Build a constant bitcast to convert the given value to a value of the /// given type by just copying the bit pattern. /// /// - parameter type: The destination type. /// /// - returns: A constant value representing the result of bitcasting this /// constant value to fit the given type. public func bitCast(to type: IRType) -> IRConstant { return Constant<Struct>(llvm: LLVMConstBitCast(asLLVM(), type.asLLVM())) } } /// A protocol to which the phantom types for a constant's representation conform. public protocol ConstantRepresentation {} /// A protocol to which the phantom types for all numerical constants conform. public protocol NumericalConstantRepresentation: ConstantRepresentation {} /// A protocol to which the phantom types for integral constants conform. public protocol IntegralConstantRepresentation: NumericalConstantRepresentation {} /// Represents unsigned integral types and operations. public enum Unsigned: IntegralConstantRepresentation {} /// Represents signed integral types and operations. public enum Signed: IntegralConstantRepresentation {} /// Represents floating types and operations. public enum Floating: NumericalConstantRepresentation {} /// Represents struct types and operations. public enum Struct: ConstantRepresentation {} /// Represents vector types and operations. public enum Vector: ConstantRepresentation {} /// A `Constant` represents a value initialized to a constant. Constant values /// may be manipulated with standard Swift arithmetic operations and used with /// standard IR Builder instructions like any other operand. The difference /// being any instructions acting solely on constants and any arithmetic /// performed on constants is evaluated at compile-time only. /// /// `Constant`s keep track of the values they represent at the type level to /// disallow mixed-type arithmetic. Use the `cast` family of operations to /// safely convert constants to other representations. public struct Constant<Repr: ConstantRepresentation>: IRConstant { internal let llvm: LLVMValueRef internal init(llvm: LLVMValueRef!) { self.llvm = llvm } /// Retrieves the underlying LLVM constant object. public func asLLVM() -> LLVMValueRef { return llvm } } // MARK: Casting extension Constant where Repr: IntegralConstantRepresentation { /// Creates a constant cast to a given integral type. /// /// - parameter type: The type to cast towards. /// /// - returns: A const value representing this value cast to the given /// integral type. public func cast(to type: IntType) -> Constant<Signed> { return Constant<Signed>(llvm: LLVMConstIntCast(llvm, type.asLLVM(), /*signed:*/ true.llvm)) } /// Creates a constant cast to a given integral type. /// /// - parameter type: The type to cast towards. /// /// - returns: A const value representing this value cast to the given /// integral type. public func cast(to type: IntType) -> Constant<Unsigned> { return Constant<Unsigned>(llvm: LLVMConstIntCast(llvm, type.asLLVM(), /*signed:*/ false.llvm)) } } extension Constant where Repr == Unsigned { /// Creates a constant cast to a given floating type. /// /// - parameter type: The type to cast towards. /// /// - returns: A const value representing this value cast to the given /// floating type. public func cast(to type: FloatType) -> Constant<Floating> { return Constant<Floating>(llvm: LLVMConstUIToFP(llvm, type.asLLVM())) } } extension Constant where Repr == Signed { /// Creates a constant cast to a given integral type. /// /// - parameter type: The type to cast towards. /// /// - returns: A const value representing this value cast to the given /// integral type. public func cast(to type: IntType) -> Constant<Signed> { return Constant<Signed>(llvm: LLVMConstIntCast(llvm, type.asLLVM(), /*signed:*/ true.llvm)) } /// Creates a constant cast to a given integral type. /// /// - parameter type: The type to cast towards. /// /// - returns: A const value representing this value cast to the given /// integral type. public func cast(to type: IntType) -> Constant<Unsigned> { return Constant<Unsigned>(llvm: LLVMConstIntCast(llvm, type.asLLVM(), /*signed:*/ false.llvm)) } /// Creates a constant cast to a given floating type. /// /// - parameter type: The type to cast towards. /// /// - returns: A const value representing this value cast to the given /// floating type. public func cast(to type: FloatType) -> Constant<Floating> { let val = self.asLLVM() return Constant<Floating>(llvm: LLVMConstSIToFP(val, type.asLLVM())) } } extension Constant where Repr == Floating { /// Creates a constant cast to a given integral type. /// /// - parameter type: The type to cast towards. /// /// - returns: A const value representing this value cast to the given /// integral type. public func cast(to type: IntType) -> Constant<Signed> { return Constant<Signed>(llvm: LLVMConstFPToSI(llvm, type.asLLVM())) } /// Creates a constant cast to a given integral type. /// /// - parameter type: The type to cast towards. /// /// - returns: A const value representing this value cast to the given /// integral type. public func cast(to type: IntType) -> Constant<Unsigned> { return Constant<Unsigned>(llvm: LLVMConstFPToUI(llvm, type.asLLVM())) } /// Creates a constant cast to a given floating type. /// /// - parameter type: The type to cast towards. /// /// - returns: A const value representing this value cast to the given /// floating type. public func cast(to type: FloatType) -> Constant<Floating> { let val = self.asLLVM() return Constant<Floating>(llvm: LLVMConstFPCast(val, type.asLLVM())) } } // NOTE: These are here to improve the error message should a user attempt to cast a const struct extension Constant where Repr == Struct { @available(*, unavailable, message: "You cannot cast an aggregate type. See the LLVM Reference manual's section on `bitcast`") public func cast<T: IntegralConstantRepresentation>(to type: IntType) -> Constant<T> { fatalError() } @available(*, unavailable, message: "You cannot cast an aggregate type. See the LLVM Reference manual's section on `bitcast`") public func cast(to type: FloatType) -> Constant<Floating> { fatalError() } } // MARK: Truncation extension Constant where Repr == Signed { /// Creates a constant truncated to a given integral type. /// /// - parameter type: The type to truncate towards. /// /// - returns: A const value representing this value truncated to the given /// integral type's bitwidth. public func truncate(to type: IntType) -> Constant<Signed> { return Constant<Signed>(llvm: LLVMConstTrunc(llvm, type.asLLVM())) } } extension Constant where Repr == Unsigned { /// Creates a constant truncated to a given integral type. /// /// - parameter type: The type to truncate towards. /// /// - returns: A const value representing this value truncated to the given /// integral type's bitwidth. public func truncate(to type: IntType) -> Constant<Unsigned> { return Constant<Unsigned>(llvm: LLVMConstTrunc(llvm, type.asLLVM())) } } extension Constant where Repr == Floating { /// Creates a constant truncated to a given floating type. /// /// - parameter type: The type to truncate towards. /// /// - returns: A const value representing this value truncated to the given /// floating type's bitwidth. public func truncate(to type: FloatType) -> Constant<Floating> { return Constant<Floating>(llvm: LLVMConstFPTrunc(llvm, type.asLLVM())) } /// Creates a constant extended to a given floating type. /// /// - parameter type: The type to extend towards. /// /// - returns: A const value representing this value extended to the given /// floating type's bitwidth. public func extend(to type: FloatType) -> Constant<Floating> { return Constant<Floating>(llvm: LLVMConstFPExt(llvm, type.asLLVM())) } } // MARK: Arithmetic Operations // MARK: Negation extension Constant { /// Creates a constant negate operation to negate a value. /// /// - parameter lhs: The operand to negate. /// - parameter overflowBehavior: Should overflow occur, specifies the /// behavior of the resulting constant value. /// /// - returns: A constant value representing the negation of the given constant. public static func negate(_ lhs: Constant<Signed>, overflowBehavior: OverflowBehavior = .default) -> Constant<Signed> { let lhsVal = lhs.asLLVM() switch overflowBehavior { case .noSignedWrap: return Constant<Signed>(llvm: LLVMConstNSWNeg(lhsVal)) case .noUnsignedWrap: return Constant<Signed>(llvm: LLVMConstNUWNeg(lhsVal)) case .default: return Constant<Signed>(llvm: LLVMConstNeg(lhsVal)) } } /// Creates a constant negate operation to negate a value. /// /// - parameter lhs: The operand to negate. /// /// - returns: A constant value representing the negation of the given constant. public static func negate(_ lhs: Constant<Floating>) -> Constant<Floating> { return Constant<Floating>(llvm: LLVMConstFNeg(lhs.llvm)) } } extension Constant where Repr == Signed { /// Creates a constant negate operation to negate a value. /// /// - returns: A constant value representing the negation of the given constant. public func negate() -> Constant { return Constant.negate(self) } } extension Constant where Repr == Floating { /// Creates a constant negate operation to negate a value. /// /// - returns: A constant value representing the negation of the given constant. public func negate() -> Constant { return Constant.negate(self) } } // MARK: Addition extension Constant { /// Creates a constant add operation to add two homogenous constants together. /// /// - parameter lhs: The first summand value (the augend). /// - parameter rhs: The second summand value (the addend). /// - parameter overflowBehavior: Should overflow occur, specifies the /// behavior of the resulting constant value. /// /// - returns: A constant value representing the sum of the two operands. public static func add(_ lhs: Constant<Unsigned>, _ rhs: Constant<Unsigned>, overflowBehavior: OverflowBehavior = .default) -> Constant<Unsigned> { switch overflowBehavior { case .noSignedWrap: return Constant<Unsigned>(llvm: LLVMConstNSWAdd(lhs.llvm, rhs.llvm)) case .noUnsignedWrap: return Constant<Unsigned>(llvm: LLVMConstNUWAdd(lhs.llvm, rhs.llvm)) case .default: return Constant<Unsigned>(llvm: LLVMConstAdd(lhs.llvm, rhs.llvm)) } } /// Creates a constant add operation to add two homogenous constants together. /// /// - parameter lhs: The first summand value (the augend). /// - parameter rhs: The second summand value (the addend). /// - parameter overflowBehavior: Should overflow occur, specifies the /// behavior of the resulting constant value. /// /// - returns: A constant value representing the sum of the two operands. public static func add(_ lhs: Constant<Signed>, _ rhs: Constant<Signed>, overflowBehavior: OverflowBehavior = .default) -> Constant<Signed> { switch overflowBehavior { case .noSignedWrap: return Constant<Signed>(llvm: LLVMConstNSWAdd(lhs.llvm, rhs.llvm)) case .noUnsignedWrap: return Constant<Signed>(llvm: LLVMConstNUWAdd(lhs.llvm, rhs.llvm)) case .default: return Constant<Signed>(llvm: LLVMConstAdd(lhs.llvm, rhs.llvm)) } } /// Creates a constant add operation to add two homogenous constants together. /// /// - parameter lhs: The first summand value (the augend). /// - parameter rhs: The second summand value (the addend). /// /// - returns: A constant value representing the sum of the two operands. public static func add(_ lhs: Constant<Floating>, _ rhs: Constant<Floating>) -> Constant<Floating> { return Constant<Floating>(llvm: LLVMConstFAdd(lhs.llvm, rhs.llvm)) } } extension Constant where Repr == Signed { /// Creates a constant add operation to add two homogenous constants together. /// /// - parameter rhs: The second summand value (the addend). /// - parameter overflowBehavior: Should overflow occur, specifies the /// behavior of the resulting constant value. /// /// - returns: A constant value representing the sum of the two operands. public func adding(_ rhs: Constant, overflowBehavior: OverflowBehavior = .default) -> Constant { return Constant.add(self, rhs, overflowBehavior: overflowBehavior) } } extension Constant where Repr == Unsigned { /// Creates a constant add operation to add two homogenous constants together. /// /// - parameter rhs: The second summand value (the addend). /// - parameter overflowBehavior: Should overflow occur, specifies the /// behavior of the resulting constant value. /// /// - returns: A constant value representing the sum of the two operands. public func adding(_ rhs: Constant, overflowBehavior: OverflowBehavior = .default) -> Constant { return Constant.add(self, rhs, overflowBehavior: overflowBehavior) } } extension Constant where Repr == Floating { /// Creates a constant add operation to add two homogenous constants together. /// /// - parameter rhs: The second summand value (the addend). /// /// - returns: A constant value representing the sum of the two operands. public func adding(_ rhs: Constant) -> Constant { return Constant.add(self, rhs) } } // MARK: Subtraction extension Constant { /// Creates a constant sub operation to subtract two homogenous constants. /// /// - parameter lhs: The first value (the minuend). /// - parameter rhs: The second value (the subtrahend). /// - parameter overflowBehavior: Should overflow occur, specifies the /// behavior of the resulting constant value. /// /// - returns: A constant value representing the difference of the two operands. public static func subtract(_ lhs: Constant<Unsigned>, _ rhs: Constant<Unsigned>, overflowBehavior: OverflowBehavior = .default) -> Constant<Unsigned> { switch overflowBehavior { case .noSignedWrap: return Constant<Unsigned>(llvm: LLVMConstNSWSub(lhs.llvm, rhs.llvm)) case .noUnsignedWrap: return Constant<Unsigned>(llvm: LLVMConstNUWSub(lhs.llvm, rhs.llvm)) case .default: return Constant<Unsigned>(llvm: LLVMConstSub(lhs.llvm, rhs.llvm)) } } /// Creates a constant sub operation to subtract two homogenous constants. /// /// - parameter lhs: The first value (the minuend). /// - parameter rhs: The second value (the subtrahend). /// - parameter overflowBehavior: Should overflow occur, specifies the /// behavior of the resulting constant value. /// /// - returns: A constant value representing the difference of the two operands. public static func subtract(_ lhs: Constant<Signed>, _ rhs: Constant<Signed>, overflowBehavior: OverflowBehavior = .default) -> Constant<Signed> { switch overflowBehavior { case .noSignedWrap: return Constant<Signed>(llvm: LLVMConstNSWSub(lhs.llvm, rhs.llvm)) case .noUnsignedWrap: return Constant<Signed>(llvm: LLVMConstNUWSub(lhs.llvm, rhs.llvm)) case .default: return Constant<Signed>(llvm: LLVMConstSub(lhs.llvm, rhs.llvm)) } } /// Creates a constant sub operation to subtract two homogenous constants. /// /// - parameter lhs: The first value (the minuend). /// - parameter rhs: The second value (the subtrahend). /// /// - returns: A constant value representing the difference of the two operands. public static func subtract(_ lhs: Constant<Floating>, _ rhs: Constant<Floating>) -> Constant<Floating> { return Constant<Floating>(llvm: LLVMConstFSub(lhs.llvm, rhs.llvm)) } } extension Constant where Repr == Unsigned { /// Creates a constant sub operation to subtract two homogenous constants. /// /// - parameter rhs: The second value (the subtrahend). /// - parameter overflowBehavior: Should overflow occur, specifies the /// behavior of the resulting constant value. /// /// - returns: A constant value representing the difference of the two operands. public func subtracting(_ rhs: Constant, overflowBehavior: OverflowBehavior = .default) -> Constant { return Constant.subtract(self, rhs, overflowBehavior: overflowBehavior) } } extension Constant where Repr == Signed { /// Creates a constant sub operation to subtract two homogenous constants. /// /// - parameter rhs: The second value (the subtrahend). /// - parameter overflowBehavior: Should overflow occur, specifies the /// behavior of the resulting constant value. /// /// - returns: A constant value representing the difference of the two operands. public func subtracting(_ rhs: Constant, overflowBehavior: OverflowBehavior = .default) -> Constant { return Constant.subtract(self, rhs, overflowBehavior: overflowBehavior) } } extension Constant where Repr == Floating { /// Creates a constant sub operation to subtract two homogenous constants. /// /// - parameter rhs: The second value (the subtrahend). /// /// - returns: A constant value representing the difference of the two operands. public func subtracting(_ rhs: Constant) -> Constant { return Constant.subtract(self, rhs) } } // MARK: Multiplication extension Constant { /// Creates a constant multiply operation with the given values as operands. /// /// - parameter lhs: The first factor value (the multiplier). /// - parameter rhs: The second factor value (the multiplicand). /// - parameter overflowBehavior: Should overflow occur, specifies the /// behavior of the resulting constant value. /// /// - returns: A constant value representing the product of the two operands. public static func multiply(_ lhs: Constant<Unsigned>, _ rhs: Constant<Unsigned>, overflowBehavior: OverflowBehavior = .default) -> Constant<Unsigned> { switch overflowBehavior { case .noSignedWrap: return Constant<Unsigned>(llvm: LLVMConstNSWMul(lhs.llvm, rhs.llvm)) case .noUnsignedWrap: return Constant<Unsigned>(llvm: LLVMConstNUWMul(lhs.llvm, rhs.llvm)) case .default: return Constant<Unsigned>(llvm: LLVMConstMul(lhs.llvm, rhs.llvm)) } } /// Creates a constant multiply operation with the given values as operands. /// /// - parameter lhs: The first factor value (the multiplier). /// - parameter rhs: The second factor value (the multiplicand). /// - parameter overflowBehavior: Should overflow occur, specifies the /// behavior of the resulting constant value. /// /// - returns: A constant value representing the product of the two operands. public static func multiply(_ lhs: Constant<Signed>, _ rhs: Constant<Signed>, overflowBehavior: OverflowBehavior = .default) -> Constant<Signed> { switch overflowBehavior { case .noSignedWrap: return Constant<Signed>(llvm: LLVMConstNSWMul(lhs.llvm, rhs.llvm)) case .noUnsignedWrap: return Constant<Signed>(llvm: LLVMConstNUWMul(lhs.llvm, rhs.llvm)) case .default: return Constant<Signed>(llvm: LLVMConstMul(lhs.llvm, rhs.llvm)) } } /// Creates a constant multiply operation with the given values as operands. /// /// - parameter lhs: The first factor value (the multiplier). /// - parameter rhs: The second factor value (the multiplicand). /// /// - returns: A constant value representing the product of the two operands. public static func multiply(_ lhs: Constant<Floating>, _ rhs: Constant<Floating>) -> Constant<Floating> { return Constant<Floating>(llvm: LLVMConstFMul(lhs.llvm, rhs.llvm)) } } extension Constant where Repr == Unsigned { /// Creates a constant multiply operation with the given values as operands. /// /// - parameter rhs: The second factor value (the multiplicand). /// - parameter overflowBehavior: Should overflow occur, specifies the /// behavior of the resulting constant value. /// /// - returns: A constant value representing the product of the two operands. public func multiplying(_ rhs: Constant, overflowBehavior: OverflowBehavior = .default) -> Constant { return Constant.multiply(self, rhs, overflowBehavior: overflowBehavior) } } extension Constant where Repr == Signed { /// Creates a constant multiply operation with the given values as operands. /// /// - parameter rhs: The second factor value (the multiplicand). /// - parameter overflowBehavior: Should overflow occur, specifies the /// behavior of the resulting constant value. /// /// - returns: A constant value representing the product of the two operands. public func multiplying(_ rhs: Constant, overflowBehavior: OverflowBehavior = .default) -> Constant { return Constant.multiply(self, rhs, overflowBehavior: overflowBehavior) } } extension Constant where Repr == Floating { /// Creates a constant multiply operation with the given values as operands. /// /// - parameter lhs: The first factor value (the multiplier). /// - parameter rhs: The second factor value (the multiplicand). /// /// - returns: A constant value representing the product of the two operands. public func multiplying(_ rhs: Constant) -> Constant { return Constant.multiply(self, rhs) } } // MARK: Divide extension Constant { /// A constant divide operation that provides the remainder after divison of /// the first value by the second value. /// /// - parameter lhs: The first value (the dividend). /// - parameter rhs: The second value (the divisor). /// /// - returns: A constant value representing the quotient of the first and /// second operands. public static func divide(_ lhs: Constant<Unsigned>, _ rhs: Constant<Unsigned>) -> Constant<Unsigned> { return Constant<Unsigned>(llvm: LLVMConstUDiv(lhs.llvm, rhs.llvm)) } /// A constant divide operation that provides the remainder after divison of /// the first value by the second value. /// /// - parameter lhs: The first value (the dividend). /// - parameter rhs: The second value (the divisor). /// /// - returns: A constant value representing the quotient of the first and /// second operands. public static func divide(_ lhs: Constant<Signed>, _ rhs: Constant<Signed>) -> Constant<Signed> { return Constant<Signed>(llvm: LLVMConstSDiv(lhs.llvm, rhs.llvm)) } /// A constant divide operation that provides the remainder after divison of /// the first value by the second value. /// /// - parameter lhs: The first value (the dividend). /// - parameter rhs: The second value (the divisor). /// /// - returns: A constant value representing the quotient of the first and /// second operands. public static func divide(_ lhs: Constant<Floating>, _ rhs: Constant<Floating>) -> Constant<Floating> { return Constant<Floating>(llvm: LLVMConstFDiv(lhs.llvm, rhs.llvm)) } } extension Constant where Repr == Unsigned { /// A constant divide operation that provides the remainder after divison of /// the first value by the second value. /// /// - parameter rhs: The second value (the divisor). /// /// - returns: A constant value representing the quotient of the first and /// second operands. public func dividing(by rhs: Constant) -> Constant { return Constant.divide(self, rhs) } } extension Constant where Repr == Signed { /// A constant divide operation that provides the remainder after divison of /// the first value by the second value. /// /// - parameter rhs: The second value (the divisor). /// /// - returns: A constant value representing the quotient of the first and /// second operands. public func dividing(by rhs: Constant) -> Constant { return Constant.divide(self, rhs) } } extension Constant where Repr == Floating { /// A constant divide operation that provides the remainder after divison of /// the first value by the second value. /// /// - parameter rhs: The second value (the divisor). /// /// - returns: A constant value representing the quotient of the first and /// second operands. public func dividing(by rhs: Constant) -> Constant { return Constant.divide(self, rhs) } } // MARK: Remainder extension Constant { /// A constant remainder operation that provides the remainder after divison /// of the first value by the second value. /// /// - parameter lhs: The first value (the dividend). /// - parameter rhs: The second value (the divisor). /// /// - returns: A constant value representing the remainder of division of the /// first operand by the second operand. public static func remainder(_ lhs: Constant<Unsigned>, _ rhs: Constant<Unsigned>) -> Constant<Unsigned> { return Constant<Unsigned>(llvm: LLVMConstURem(lhs.llvm, rhs.llvm)) } /// A constant remainder operation that provides the remainder after divison /// of the first value by the second value. /// /// - parameter lhs: The first value (the dividend). /// - parameter rhs: The second value (the divisor). /// /// - returns: A constant value representing the remainder of division of the /// first operand by the second operand. public static func remainder(_ lhs: Constant<Signed>, _ rhs: Constant<Signed>) -> Constant<Signed> { return Constant<Signed>(llvm: LLVMConstSRem(lhs.llvm, rhs.llvm)) } /// A constant remainder operation that provides the remainder after divison /// of the first value by the second value. /// /// - parameter lhs: The first value (the dividend). /// - parameter rhs: The second value (the divisor). /// /// - returns: A constant value representing the remainder of division of the /// first operand by the second operand. public static func remainder(_ lhs: Constant<Floating>, _ rhs: Constant<Floating>) -> Constant<Floating> { return Constant<Floating>(llvm: LLVMConstFRem(lhs.llvm, rhs.llvm)) } } extension Constant where Repr == Unsigned { /// A constant remainder operation that provides the remainder after divison /// of the first value by the second value. /// /// - parameter rhs: The second value (the divisor). /// /// - returns: A constant value representing the remainder of division of the /// first operand by the second operand. public func remainder(_ rhs: Constant) -> Constant { return Constant.remainder(self, rhs) } } extension Constant where Repr == Signed { /// A constant remainder operation that provides the remainder after divison /// of the first value by the second value. /// /// - parameter rhs: The second value (the divisor). /// /// - returns: A constant value representing the remainder of division of the /// first operand by the second operand. public func remainder(_ rhs: Constant) -> Constant { return Constant.remainder(self, rhs) } } extension Constant where Repr == Floating { /// A constant remainder operation that provides the remainder after divison /// of the first value by the second value. /// /// - parameter rhs: The second value (the divisor). /// /// - returns: A constant value representing the remainder of division of the /// first operand by the second operand. public func remainder(_ rhs: Constant) -> Constant { return Constant.remainder(self, rhs) } } // MARK: Comparison Operations extension Constant where Repr: IntegralConstantRepresentation { /// A constant equality comparison between two values. /// /// - parameter lhs: The first value to compare. /// - parameter rhs: The second value to compare. /// /// - returns: A constant integral value (i1) representing the result of the /// comparision of the given operands. public static func equals(_ lhs: Constant, _ rhs: Constant) -> Constant<Signed> { return Constant<Signed>(llvm: LLVMConstICmp(IntPredicate.equal.llvm, lhs.llvm, rhs.llvm)) } } extension Constant where Repr == Signed { /// A constant less-than comparison between two values. /// /// - parameter lhs: The first value to compare. /// - parameter rhs: The second value to compare. /// /// - returns: A constant integral value (i1) representing the result of the /// comparision of the given operands. public static func lessThan(_ lhs: Constant, _ rhs: Constant) -> Constant<Signed> { return Constant<Signed>(llvm: LLVMConstICmp(IntPredicate.unsignedLessThan.llvm, lhs.llvm, rhs.llvm)) } /// A constant greater-than comparison between two values. /// /// - parameter lhs: The first value to compare. /// - parameter rhs: The second value to compare. /// /// - returns: A constant integral value (i1) representing the result of the /// comparision of the given operands. public static func greaterThan(_ lhs: Constant, _ rhs: Constant) -> Constant<Signed> { return Constant<Signed>(llvm: LLVMConstICmp(IntPredicate.signedGreaterThan.llvm, lhs.llvm, rhs.llvm)) } /// A constant less-than-or-equal comparison between two values. /// /// - parameter lhs: The first value to compare. /// - parameter rhs: The second value to compare. /// /// - returns: A constant integral value (i1) representing the result of the /// comparision of the given operands. public static func lessThanOrEqual(_ lhs: Constant, _ rhs: Constant) -> Constant<Signed> { return Constant<Signed>(llvm: LLVMConstICmp(IntPredicate.signedLessThanOrEqual.llvm, lhs.llvm, rhs.llvm)) } /// A constant greater-than-or-equal comparison between two values. /// /// - parameter lhs: The first value to compare. /// - parameter rhs: The second value to compare. /// /// - returns: A constant integral value (i1) representing the result of the /// comparision of the given operands. public static func greaterThanOrEqual(_ lhs: Constant, _ rhs: Constant) -> Constant<Signed> { return Constant<Signed>(llvm: LLVMConstICmp(IntPredicate.signedGreaterThanOrEqual.llvm, lhs.llvm, rhs.llvm)) } } extension Constant where Repr == Unsigned { /// A constant less-than comparison between two values. /// /// - parameter lhs: The first value to compare. /// - parameter rhs: The second value to compare. /// /// - returns: A constant integral value (i1) representing the result of the /// comparision of the given operands. public static func lessThan(_ lhs: Constant, _ rhs: Constant) -> Constant<Signed> { return Constant<Signed>(llvm: LLVMConstICmp(IntPredicate.unsignedLessThan.llvm, lhs.llvm, rhs.llvm)) } /// A constant greater-than comparison between two values. /// /// - parameter lhs: The first value to compare. /// - parameter rhs: The second value to compare. /// /// - returns: A constant integral value (i1) representing the result of the /// comparision of the given operands. public static func greaterThan(_ lhs: Constant, _ rhs: Constant) -> Constant<Signed> { return Constant<Signed>(llvm: LLVMConstICmp(IntPredicate.unsignedGreaterThan.llvm, lhs.llvm, rhs.llvm)) } /// A constant less-than-or-equal comparison between two values. /// /// - parameter lhs: The first value to compare. /// - parameter rhs: The second value to compare. /// /// - returns: A constant integral value (i1) representing the result of the /// comparision of the given operands. public static func lessThanOrEqual(_ lhs: Constant, _ rhs: Constant) -> Constant<Signed> { return Constant<Signed>(llvm: LLVMConstICmp(IntPredicate.unsignedLessThanOrEqual.llvm, lhs.llvm, rhs.llvm)) } /// A constant greater-than-or-equal comparison between two values. /// /// - parameter lhs: The first value to compare. /// - parameter rhs: The second value to compare. /// /// - returns: A constant integral value (i1) representing the result of the /// comparision of the given operands. public static func greaterThanOrEqual(_ lhs: Constant, _ rhs: Constant) -> Constant<Signed> { return Constant<Signed>(llvm: LLVMConstICmp(IntPredicate.unsignedGreaterThanOrEqual.llvm, lhs.llvm, rhs.llvm)) } } extension Constant where Repr == Floating { /// A constant equality comparison between two values. /// /// - parameter lhs: The first value to compare. /// - parameter rhs: The second value to compare. /// /// - returns: A constant integral value (i1) representing the result of the /// comparision of the given operands. public static func equals(_ lhs: Constant, _ rhs: Constant) -> Constant<Signed> { return Constant<Signed>(llvm: LLVMConstFCmp(RealPredicate.orderedEqual.llvm, lhs.llvm, rhs.llvm)) } /// A constant less-than comparison between two values. /// /// - parameter lhs: The first value to compare. /// - parameter rhs: The second value to compare. /// /// - returns: A constant integral value (i1) representing the result of the /// comparision of the given operands. public static func lessThan(_ lhs: Constant, _ rhs: Constant) -> Constant<Signed> { return Constant<Signed>(llvm: LLVMConstFCmp(RealPredicate.orderedLessThan.llvm, lhs.llvm, rhs.llvm)) } /// A constant greater-than comparison between two values. /// /// - parameter lhs: The first value to compare. /// - parameter rhs: The second value to compare. /// /// - returns: A constant integral value (i1) representing the result of the /// comparision of the given operands. public static func greaterThan(_ lhs: Constant, _ rhs: Constant) -> Constant<Signed> { return Constant<Signed>(llvm: LLVMConstFCmp(RealPredicate.orderedGreaterThan.llvm, lhs.llvm, rhs.llvm)) } /// A constant less-than-or-equal comparison between two values. /// /// - parameter lhs: The first value to compare. /// - parameter rhs: The second value to compare. /// /// - returns: A constant integral value (i1) representing the result of the /// comparision of the given operands. public static func lessThanOrEqual(_ lhs: Constant, _ rhs: Constant) -> Constant<Signed> { return Constant<Signed>(llvm: LLVMConstFCmp(RealPredicate.orderedLessThanOrEqual.llvm, lhs.llvm, rhs.llvm)) } /// A constant greater-than-or-equal comparison between two values. /// /// - parameter lhs: The first value to compare. /// - parameter rhs: The second value to compare. /// /// - returns: A constant integral value (i1) representing the result of the /// comparision of the given operands. public static func greaterThanOrEqual(_ lhs: Constant, _ rhs: Constant) -> Constant<Signed> { return Constant<Signed>(llvm: LLVMConstFCmp(RealPredicate.orderedGreaterThanOrEqual.llvm, lhs.llvm, rhs.llvm)) } } // MARK: Logical Operations extension Constant { /// A constant bitwise logical not with the given integral value as an operand. /// /// - parameter val: The value to negate. /// /// - returns: A constant value representing the logical negation of the given /// operand. public static func not<T: IntegralConstantRepresentation>(_ lhs: Constant<T>) -> Constant<T> { return Constant<T>(llvm: LLVMConstNot(lhs.llvm)) } /// A constant bitwise logical AND with the given values as operands. /// /// - parameter lhs: The first operand. /// - parameter rhs: The second operand. /// - parameter name: The name for the newly inserted instruction. /// /// - returns: A constant value representing the logical OR of the values of /// the two given operands. public static func and<T: IntegralConstantRepresentation>(_ lhs: Constant<T>, _ rhs: Constant<T>) -> Constant<T> { return Constant<T>(llvm: LLVMConstAnd(lhs.llvm, rhs.llvm)) } /// A constant bitwise logical OR with the given values as operands. /// /// - parameter lhs: The first operand. /// - parameter rhs: The second operand. /// - parameter name: The name for the newly inserted instruction. /// /// - returns: A constant value representing the logical OR of the values of /// the two given operands. public static func or<T: IntegralConstantRepresentation>(_ lhs: Constant<T>, _ rhs: Constant<T>) -> Constant<T> { return Constant<T>(llvm: LLVMConstOr(lhs.llvm, rhs.llvm)) } /// A constant bitwise logical exclusive OR with the given values as operands. /// /// - parameter lhs: The first operand. /// - parameter rhs: The second operand. /// /// - returns: A constant value representing the exclusive OR of the values of /// the two given operands. public static func xor<T: IntegralConstantRepresentation>(_ lhs: Constant<T>, _ rhs: Constant<T>) -> Constant<T> { return Constant<T>(llvm: LLVMConstXor(lhs.llvm, rhs.llvm)) } // MARK: Bitshifting Operations /// A constant left-shift of the first value by the second amount. /// /// - parameter lhs: The first operand. /// - parameter rhs: The second operand. /// /// - returns: A constant value representing the value of the first operand /// shifted left by the number of bits specified in the second operand. public static func leftShift<T: IntegralConstantRepresentation>(_ lhs: Constant<T>, _ rhs: Constant<T>) -> Constant<T> { return Constant<T>(llvm: LLVMConstShl(lhs.llvm, rhs.llvm)) } /// A constant right-shift of the first value by the second amount. /// /// - parameter lhs: The first operand. /// - parameter rhs: The second operand. /// - parameter arithmetic: Should the shift be arithmetic or logical (defaults to true) /// /// - returns: A constant value representing the value of the first operand /// shifted left by the number of bits specified in the second operand. public static func rightShift<T: IntegralConstantRepresentation>(_ lhs: Constant<T>, _ rhs: Constant<T>, arithmetic: Bool = true) -> Constant<T> { return Constant<T>(llvm: arithmetic ? LLVMConstAShr(lhs.llvm, rhs.llvm) : LLVMConstLShr(lhs.llvm, rhs.llvm)) } // MARK: Conditional Operations /// A constant select using the given condition to select among two values. /// /// - parameter cond: The condition to evaluate. It must have type `i1` or /// be a vector of `i1`. /// - parameter then: The value to select if the given condition is true. /// - parameter else: The value to select if the given condition is false. /// /// - returns: A constant value representing the constant value selected for /// by the condition. public static func select<T: IntegralConstantRepresentation, U>(_ cond: Constant<T>, then: Constant<U>, else: Constant<U>) -> Constant<U> { assert((cond.type as! IntType).width == 1) return Constant<U>(llvm: LLVMConstSelect(cond.llvm, then.llvm, `else`.llvm)) } } // MARK: Constant Pointer To Integer extension Constant where Repr: IntegralConstantRepresentation { /// Creates a constant pointer-to-integer operation to convert the given constant /// global pointer value to the given integer type. /// /// - parameter val: The pointer value. /// - parameter intType: The destination integer type. /// /// - returns: An constant value representing the constant value of the given /// pointer converted to the given integer type. public static func pointerToInt(_ val: IRConstant, _ intType: IntType) -> Constant { precondition(val.isConstant, "May only convert global constant pointers to integers") return Constant<Repr>(llvm: LLVMConstPtrToInt(val.asLLVM(), intType.asLLVM())) } } // MARK: Struct Operations extension Constant where Repr == Struct { /// Creates a constant operation retrieving the element at the index. /// /// - parameter indices: A list of indices that indicate which of the elements /// of the aggregate object are indexed. /// /// - returns: The value in the struct at the provided index. public func getElement(indices: [Int]) -> IRConstant { var indices = indices.map({ UInt32($0) }) return indices.withUnsafeMutableBufferPointer { buf in return Constant<Struct>(llvm: LLVMConstExtractValue(asLLVM(), buf.baseAddress, UInt32(buf.count))) } } /// Build a constant `GEP` (Get Element Pointer) instruction with a resultant /// value that is undefined if the address is outside the actual underlying /// allocated object and not the address one-past-the-end. /// /// The `GEP` instruction is often the source of confusion. LLVM [provides a /// document](http://llvm.org/docs/GetElementPtr.html) to answer questions /// around its semantics and correct usage. /// /// - parameter indices: A list of indices that indicate which of the elements /// of the aggregate object are indexed. /// /// - returns: A value representing the address of a subelement of the given /// aggregate data structure value. public func getElementPointer(indices: [IRConstant]) -> IRConstant { var indices = indices.map({ $0.asLLVM() as LLVMValueRef? }) return indices.withUnsafeMutableBufferPointer { buf in return Constant<Struct>(llvm: LLVMConstGEP(asLLVM(), buf.baseAddress, UInt32(buf.count))) } } /// Build a GEP (Get Element Pointer) instruction. /// /// The `GEP` instruction is often the source of confusion. LLVM [provides a /// document](http://llvm.org/docs/GetElementPtr.html) to answer questions /// around its semantics and correct usage. /// /// - parameter indices: A list of indices that indicate which of the elements /// of the aggregate object are indexed. /// /// - returns: A value representing the address of a subelement of the given /// aggregate data structure value. public func inBoundsGetElementPointer(indices: [IRConstant]) -> IRConstant { var indices = indices.map({ $0.asLLVM() as LLVMValueRef? }) return indices.withUnsafeMutableBufferPointer { buf in return Constant<Struct>(llvm: LLVMConstInBoundsGEP(asLLVM(), buf.baseAddress, UInt32(buf.count))) } } } // MARK: Vector Operations extension Constant where Repr == Vector { /// Builds a constant operation to construct a permutation of elements /// from the two given input vectors, returning a vector with the same element /// type as the inputs and length that is the same as the shuffle mask. /// /// - parameter vector1: The first constant vector to shuffle. /// - parameter vector2: The second constant vector to shuffle. /// - parameter mask: A constant vector of `i32` values that acts as a mask /// for the shuffled vectors. /// /// - returns: A value representing a constant vector with the same element /// type as the inputs and length that is the same as the shuffle mask. public static func buildShuffleVector(_ vector1: Constant, and vector2: Constant, mask: Constant) -> Constant { guard let maskTy = mask.type as? VectorType, maskTy.elementType is IntType else { fatalError("Vector shuffle mask's elements must be 32-bit integers") } return Constant(llvm: LLVMConstShuffleVector(vector1.asLLVM(), vector2.asLLVM(), mask.asLLVM())) } } // MARK: Swift Operators extension Constant where Repr == Floating { /// Creates a constant add operation to add two homogenous constants together. /// /// - parameter lhs: The first summand value (the augend). /// - parameter rhs: The second summand value (the addend). /// /// - returns: A constant value representing the sum of the two operands. public static func +(lhs: Constant, rhs: Constant) -> Constant { return lhs.adding(rhs) } /// Creates a constant sub operation to subtract two homogenous constants. /// /// - parameter lhs: The first value (the minuend). /// - parameter rhs: The second value (the subtrahend). /// /// - returns: A constant value representing the difference of the two operands. public static func -(lhs: Constant, rhs: Constant) -> Constant { return lhs.subtracting(rhs) } /// Creates a constant multiply operation with the given values as operands. /// /// - parameter lhs: The first factor value (the multiplier). /// - parameter rhs: The second factor value (the multiplicand). /// /// - returns: A constant value representing the product of the two operands. public static func *(lhs: Constant, rhs: Constant) -> Constant { return lhs.multiplying(rhs) } /// A constant divide operation that provides the remainder after divison of /// the first value by the second value. /// /// - parameter lhs: The first value (the dividend). /// - parameter rhs: The second value (the divisor). /// /// - returns: A constant value representing the quotient of the first and /// second operands. public static func /(lhs: Constant, rhs: Constant) -> Constant { return lhs.dividing(by: rhs) } /// A constant remainder operation that provides the remainder after divison /// of the first value by the second value. /// /// - parameter lhs: The first value (the dividend). /// - parameter rhs: The second value (the divisor). /// /// - returns: A constant value representing the remainder of division of the /// first operand by the second operand. public static func %(lhs: Constant, rhs: Constant) -> Constant { return lhs.remainder(rhs) } /// A constant equality comparison between two values. /// /// - parameter lhs: The first value to compare. /// - parameter rhs: The second value to compare. /// /// - returns: A constant integral value (i1) representing the result of the /// comparision of the given operands. public static func ==(lhs: Constant, rhs: Constant) -> Constant<Signed> { return Constant.equals(lhs, rhs) } /// A constant less-than comparison between two values. /// /// - parameter lhs: The first value to compare. /// - parameter rhs: The second value to compare. /// /// - returns: A constant integral value (i1) representing the result of the /// comparision of the given operands. public static func <(lhs: Constant, rhs: Constant) -> Constant<Signed> { return Constant.lessThan(lhs, rhs) } /// A constant greater-than comparison between two values. /// /// - parameter lhs: The first value to compare. /// - parameter rhs: The second value to compare. /// /// - returns: A constant integral value (i1) representing the result of the /// comparision of the given operands. public static func >(lhs: Constant, rhs: Constant) -> Constant<Signed> { return Constant.greaterThan(lhs, rhs) } /// A constant less-than-or-equal comparison between two values. /// /// - parameter lhs: The first value to compare. /// - parameter rhs: The second value to compare. /// /// - returns: A constant integral value (i1) representing the result of the /// comparision of the given operands. public static func <=(lhs: Constant, rhs: Constant) -> Constant<Signed> { return Constant.lessThanOrEqual(lhs, rhs) } /// A constant greater-than-or-equal comparison between two values. /// /// - parameter lhs: The first value to compare. /// - parameter rhs: The second value to compare. /// /// - returns: A constant integral value (i1) representing the result of the /// comparision of the given operands. public static func >=(lhs: Constant, rhs: Constant) -> Constant<Signed> { return Constant.greaterThanOrEqual(lhs, rhs) } } extension Constant where Repr == Signed { /// Creates a constant add operation to add two homogenous constants together. /// /// - parameter lhs: The first summand value (the augend). /// - parameter rhs: The second summand value (the addend). /// /// - returns: A constant value representing the sum of the two operands. public static func +(lhs: Constant, rhs: Constant) -> Constant { return lhs.adding(rhs) } /// Creates a constant sub operation to subtract two homogenous constants. /// /// - parameter lhs: The first value (the minuend). /// - parameter rhs: The second value (the subtrahend). /// /// - returns: A constant value representing the difference of the two operands. public static func -(lhs: Constant, rhs: Constant) -> Constant { return lhs.subtracting(rhs) } /// Creates a constant multiply operation with the given values as operands. /// /// - parameter lhs: The first factor value (the multiplier). /// - parameter rhs: The second factor value (the multiplicand). /// /// - returns: A constant value representing the product of the two operands. public static func *(lhs: Constant, rhs: Constant) -> Constant { return lhs.multiplying(rhs) } /// A constant divide operation that provides the remainder after divison of /// the first value by the second value. /// /// - parameter lhs: The first value (the dividend). /// - parameter rhs: The second value (the divisor). /// /// - returns: A constant value representing the quotient of the first and /// second operands. public static func /(lhs: Constant, rhs: Constant) -> Constant { return lhs.dividing(by: rhs) } /// A constant remainder operation that provides the remainder after divison /// of the first value by the second value. /// /// - parameter lhs: The first value (the dividend). /// - parameter rhs: The second value (the divisor). /// /// - returns: A constant value representing the remainder of division of the /// first operand by the second operand. public static func %(lhs: Constant, rhs: Constant) -> Constant { return lhs.remainder(rhs) } /// A constant equality comparison between two values. /// /// - parameter lhs: The first value to compare. /// - parameter rhs: The second value to compare. /// /// - returns: A constant integral value (i1) representing the result of the /// comparision of the given operands. public static func ==(lhs: Constant, rhs: Constant) -> Constant { return Constant.equals(lhs, rhs) } /// A constant less-than comparison between two values. /// /// - parameter lhs: The first value to compare. /// - parameter rhs: The second value to compare. /// /// - returns: A constant integral value (i1) representing the result of the /// comparision of the given operands. public static func <(lhs: Constant, rhs: Constant) -> Constant { return Constant.lessThan(lhs, rhs) } /// A constant greater-than comparison between two values. /// /// - parameter lhs: The first value to compare. /// - parameter rhs: The second value to compare. /// /// - returns: A constant integral value (i1) representing the result of the /// comparision of the given operands. public static func >(lhs: Constant, rhs: Constant) -> Constant { return Constant.greaterThan(lhs, rhs) } /// A constant less-than-or-equal comparison between two values. /// /// - parameter lhs: The first value to compare. /// - parameter rhs: The second value to compare. /// /// - returns: A constant integral value (i1) representing the result of the /// comparision of the given operands. public static func <=(lhs: Constant, rhs: Constant) -> Constant { return Constant.lessThanOrEqual(lhs, rhs) } /// A constant greater-than-or-equal comparison between two values. /// /// - parameter lhs: The first value to compare. /// - parameter rhs: The second value to compare. /// /// - returns: A constant integral value (i1) representing the result of the /// comparision of the given operands. public static func >=(lhs: Constant, rhs: Constant) -> Constant { return Constant.greaterThanOrEqual(lhs, rhs) } /// A constant bitwise logical OR with the given values as operands. /// /// - parameter lhs: The first operand. /// - parameter rhs: The second operand. /// /// - returns: A constant value representing the logical OR of the values of /// the two given operands. public static func |(lhs: Constant, rhs: Constant) -> Constant { return Constant.or(lhs, rhs) } /// A constant bitwise logical AND with the given values as operands. /// /// - parameter lhs: The first operand. /// - parameter rhs: The second operand. /// /// - returns: A constant value representing the logical OR of the values of /// the two given operands. public static func &(lhs: Constant, rhs: Constant) -> Constant { return Constant.and(lhs, rhs) } /// A constant left-shift of the first value by the second amount. /// /// - parameter lhs: The first operand. /// - parameter rhs: The second operand. /// /// - returns: A constant value representing the value of the first operand /// shifted left by the number of bits specified in the second operand. public static func <<(lhs: Constant, rhs: Constant) -> Constant { return Constant.leftShift(lhs, rhs) } /// A constant right-shift of the first value by the second amount. /// /// - parameter lhs: The first operand. /// - parameter rhs: The second operand. /// /// - returns: A constant value representing the value of the first operand /// shifted left by the number of bits specified in the second operand. public static func >>(lhs: Constant, rhs: Constant) -> Constant { return Constant.rightShift(lhs, rhs) } } extension Constant where Repr == Unsigned { /// Creates a constant add operation to add two homogenous constants together. /// /// - parameter lhs: The first summand value (the augend). /// - parameter rhs: The second summand value (the addend). /// /// - returns: A constant value representing the sum of the two operands. public static func +(lhs: Constant, rhs: Constant) -> Constant { return lhs.adding(rhs) } /// Creates a constant sub operation to subtract two homogenous constants. /// /// - parameter lhs: The first value (the minuend). /// - parameter rhs: The second value (the subtrahend). /// /// - returns: A constant value representing the difference of the two operands. public static func -(lhs: Constant, rhs: Constant) -> Constant { return lhs.subtracting(rhs) } /// Creates a constant multiply operation with the given values as operands. /// /// - parameter lhs: The first factor value (the multiplier). /// - parameter rhs: The second factor value (the multiplicand). /// /// - returns: A constant value representing the product of the two operands. public static func *(lhs: Constant, rhs: Constant) -> Constant { return lhs.multiplying(rhs) } /// A constant divide operation that provides the remainder after divison of /// the first value by the second value. /// /// - parameter lhs: The first value (the dividend). /// - parameter rhs: The second value (the divisor). /// /// - returns: A constant value representing the quotient of the first and /// second operands. public static func /(lhs: Constant, rhs: Constant) -> Constant { return lhs.dividing(by: rhs) } /// A constant remainder operation that provides the remainder after divison /// of the first value by the second value. /// /// - parameter lhs: The first value (the dividend). /// - parameter rhs: The second value (the divisor). /// /// - returns: A constant value representing the remainder of division of the /// first operand by the second operand. public static func %(lhs: Constant, rhs: Constant) -> Constant { return lhs.remainder(rhs) } /// A constant equality comparison between two values. /// /// - parameter lhs: The first value to compare. /// - parameter rhs: The second value to compare. /// /// - returns: A constant integral value (i1) representing the result of the /// comparision of the given operands. public static func ==(lhs: Constant, rhs: Constant) -> Constant<Signed> { return Constant.equals(lhs, rhs) } /// A constant less-than comparison between two values. /// /// - parameter lhs: The first value to compare. /// - parameter rhs: The second value to compare. /// /// - returns: A constant integral value (i1) representing the result of the /// comparision of the given operands. public static func <(lhs: Constant, rhs: Constant) -> Constant<Signed> { return Constant.lessThan(lhs, rhs) } /// A constant greater-than comparison between two values. /// /// - parameter lhs: The first value to compare. /// - parameter rhs: The second value to compare. /// /// - returns: A constant integral value (i1) representing the result of the /// comparision of the given operands. public static func >(lhs: Constant, rhs: Constant) -> Constant<Signed> { return Constant.greaterThan(lhs, rhs) } /// A constant less-than-or-equal comparison between two values. /// /// - parameter lhs: The first value to compare. /// - parameter rhs: The second value to compare. /// /// - returns: A constant integral value (i1) representing the result of the /// comparision of the given operands. public static func <=(lhs: Constant, rhs: Constant) -> Constant<Signed> { return Constant.lessThanOrEqual(lhs, rhs) } /// A constant greater-than-or-equal comparison between two values. /// /// - parameter lhs: The first value to compare. /// - parameter rhs: The second value to compare. /// /// - returns: A constant integral value (i1) representing the result of the /// comparision of the given operands. public static func >=(lhs: Constant, rhs: Constant) -> Constant<Signed> { return Constant.greaterThanOrEqual(lhs, rhs) } /// A constant bitwise logical OR with the given values as operands. /// /// - parameter lhs: The first operand. /// - parameter rhs: The second operand. /// /// - returns: A constant value representing the logical OR of the values of /// the two given operands. public static func |(lhs: Constant, rhs: Constant) -> Constant { return Constant.or(lhs, rhs) } /// A constant bitwise logical AND with the given values as operands. /// /// - parameter lhs: The first operand. /// - parameter rhs: The second operand. /// /// - returns: A constant value representing the logical OR of the values of /// the two given operands. public static func &(lhs: Constant, rhs: Constant) -> Constant { return Constant.and(lhs, rhs) } /// A constant left-shift of the first value by the second amount. /// /// - parameter lhs: The first operand. /// - parameter rhs: The second operand. /// /// - returns: A constant value representing the value of the first operand /// shifted left by the number of bits specified in the second operand. public static func <<(lhs: Constant, rhs: Constant) -> Constant { return Constant.leftShift(lhs, rhs) } /// A constant right-shift of the first value by the second amount. /// /// - parameter lhs: The first operand. /// - parameter rhs: The second operand. /// /// - returns: A constant value representing the value of the first operand /// shifted left by the number of bits specified in the second operand. public static func >>(lhs: Constant, rhs: Constant) -> Constant { return Constant.rightShift(lhs, rhs) } } extension Constant where Repr: IntegralConstantRepresentation { /// A constant bitwise logical not with the given integral value as an operand. /// /// - parameter val: The value to negate. /// /// - returns: A constant value representing the logical negation of the given /// operand. public static prefix func !(_ lhs: Constant) -> Constant { return Constant(llvm: LLVMConstNot(lhs.llvm)) } } // MARK: Undef extension Constant where Repr: IntegralConstantRepresentation { /// Returns the special LLVM `undef` value for this type. /// /// The `undef` value can be used anywhere a constant is expected, and /// indicates that the user of the value may receive an unspecified /// bit-pattern. public static func undef(_ ty: IntType) -> Constant { return Constant<Repr>(llvm: ty.undef().asLLVM()) } } extension Constant where Repr == Floating { /// Returns the special LLVM `undef` value for this type. /// /// The `undef` value can be used anywhere a constant is expected, and /// indicates that the user of the value may receive an unspecified /// bit-pattern. public static func undef(_ ty: FloatType) -> Constant { return Constant(llvm: ty.undef().asLLVM()) } } extension Constant where Repr == Struct { /// Returns the special LLVM `undef` value for this type. /// /// The `undef` value can be used anywhere a constant is expected, and /// indicates that the user of the value may receive an unspecified /// bit-pattern. public static func undef(_ ty: StructType) -> Constant { return Constant(llvm: ty.undef().asLLVM()) } } extension Constant where Repr == Vector { /// Returns the special LLVM `undef` value for this type. /// /// The `undef` value can be used anywhere a constant is expected, and /// indicates that the user of the value may receive an unspecified /// bit-pattern. public static func undef(_ ty: VectorType) -> Constant { return Constant(llvm: ty.undef().asLLVM()) } }
mit
6be321e9fd82669077aebe7ad6dde557
37.880878
154
0.695058
4.291102
false
false
false
false
noahemmet/Grid
Sources/PlaygroundUtilities.swift
1
2580
//// //// PlaygroundExtensions.swift //// Grid //// //// Created by Noah Emmet on 4/23/16. //// Copyright © 2016 Sticks. All rights reserved. //// // //import Foundation // //public typealias ColorAtIndex = Int -> UIColor // ///// A clumsy visualizer for getting around some Playground limitations. //public class GridVisualizer<Element: Hashable>: NSObject { // public let grid: Grid<Element> // public let collectionView: UICollectionView // private let dataSource: DataSource // // public init(grid: Grid<Element>, colorAtIndexPath: ColorAtIndex) { // let layout = UICollectionViewFlowLayout() // layout.itemSize = CGSize(width: 10, height: 10) // layout.minimumLineSpacing = 0 // layout.minimumInteritemSpacing = 0 // let frame = CGRect(x: 0, y: 0, width: CGFloat(grid.rows) * layout.itemSize.width, height: CGFloat(grid.columns) * layout.itemSize.height) // self.collectionView = UICollectionView(frame: frame, collectionViewLayout: layout) // self.collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: String(UICollectionViewCell)) // self.grid = grid // self.dataSource = DataSource(rows: grid.rows, columns: grid.columns, colorAtIndexPath: colorAtIndexPath) // self.collectionView.dataSource = self.dataSource // } //} // //private class DataSource: NSObject, UICollectionViewDataSource { // let rows: Int // let columns: Int // let colorAtIndexPath: ColorAtIndex // // init(rows: Int, columns: Int, colorAtIndexPath: ColorAtIndex) { // self.rows = rows // self.columns = columns // self.colorAtIndexPath = colorAtIndexPath // } // // @objc func numberOfSections(in collectionView: UICollectionView) -> Int { // return 1 // } // // @objc private func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { // return rows * columns // } // // @objc private func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: NSIndexPath) -> UICollectionViewCell { // let cell = collectionView.dequeueReusableCell(withReuseIdentifier: String(UICollectionViewCell), for: indexPath) // cell.backgroundColor = colorAtIndexPath(indexPath.row) // return cell // } //} // //extension Grid where Element: CustomPlaygroundQuickLookable { // public func customPlaygroundQuickLook() -> PlaygroundQuickLook { // let f = elements.first!.customPlaygroundQuickLook // return f // } //} // //extension GridVisualizer: CustomPlaygroundQuickLookable { // public func customPlaygroundQuickLook() -> PlaygroundQuickLook { // return PlaygroundQuickLook.View(collectionView) // } //}
apache-2.0
c8373354f785a0a137e913aa6ba773a9
35.842857
141
0.739434
4.04232
false
false
false
false
arvindhsukumar/PredicateEditor
Example/Pods/SeedStackViewController/StackViewController/AutoScrollView.swift
1
5331
// // AutoScrollView.swift // Seed // // Created by Indragie Karunaratne on 2016-03-10. // Copyright © 2016 Seed Platform, Inc. All rights reserved. // import UIKit /// A scroll view that automatically scrolls to a subview of its `contentView` /// when the keyboard is shown. This replicates the behaviour implemented by /// `UITableView`. public class AutoScrollView: UIScrollView { private struct Constants { static let DefaultAnimationDuration: NSTimeInterval = 0.25 static let DefaultAnimationCurve = UIViewAnimationCurve.EaseInOut static let ScrollAnimationID = "AutoscrollAnimation" } /// The content view to display inside the container view. Views can also /// be added directly to this view without using the `contentView` property, /// but it simply makes it more convenient for the common case where your /// content fills the bounds of the scroll view. public var contentView: UIView? { willSet { contentView?.removeFromSuperview() } didSet { if let contentView = contentView { addSubview(contentView) updateContentViewConstraints() } } } private var contentViewConstraints: [NSLayoutConstraint]? override public var contentInset: UIEdgeInsets { didSet { updateContentViewConstraints() } } private func updateContentViewConstraints() { if let constraints = contentViewConstraints { NSLayoutConstraint.deactivateConstraints(constraints) } if let contentView = contentView { contentViewConstraints = contentView.activateSuperviewHuggingConstraints(insets: contentInset) } else { contentViewConstraints = nil } } private func commonInit() { let nc = NSNotificationCenter.defaultCenter() nc.addObserver(self, selector: #selector(AutoScrollView.keyboardWillShow(_:)), name: UIKeyboardWillShowNotification, object: nil) nc.addObserver(self, selector: #selector(AutoScrollView.keyboardWillHide(_:)), name: UIKeyboardWillHideNotification, object: nil) } public override init(frame: CGRect) { super.init(frame: frame) commonInit() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } // MARK: Notifications // Implementation based on code from Apple documentation // https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html @objc private func keyboardWillShow(notification: NSNotification) { let keyboardFrameValue = notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue guard var keyboardFrame = keyboardFrameValue?.CGRectValue() else { return } keyboardFrame = convertRect(keyboardFrame, fromView: nil) let bottomInset: CGFloat let keyboardIntersectionRect = bounds.intersect(keyboardFrame) if !keyboardIntersectionRect.isNull { bottomInset = keyboardIntersectionRect.height let contentInset = UIEdgeInsets(top: 0, left: 0, bottom: bottomInset, right: 0) super.contentInset = contentInset scrollIndicatorInsets = contentInset } else { bottomInset = 0.0 } guard let firstResponder = firstResponder else { return } let firstResponderFrame = firstResponder.convertRect(firstResponder.bounds, toView: self) var contentBounds = CGRect(origin: contentOffset, size: bounds.size) contentBounds.size.height -= bottomInset if !contentBounds.contains(firstResponderFrame.origin) { let duration = notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? NSTimeInterval ?? Constants.DefaultAnimationDuration let curve = notification.userInfo?[UIKeyboardAnimationCurveUserInfoKey] as? UIViewAnimationCurve ?? Constants.DefaultAnimationCurve // Dropping down to the old style UIView animation API because the new API // does not support setting the curve directly. The other option is to take // `curve` and shift it left by 16 bits to turn it into a `UIViewAnimationOptions`, // but that seems uglier than just doing this. UIView.beginAnimations(Constants.ScrollAnimationID, context: nil) UIView.setAnimationCurve(curve) UIView.setAnimationDuration(duration) scrollRectToVisible(firstResponderFrame, animated: false) UIView.commitAnimations() } } @objc private func keyboardWillHide(notification: NSNotification) { super.contentInset = UIEdgeInsetsZero scrollIndicatorInsets = UIEdgeInsetsZero } } private extension UIView { var firstResponder: UIView? { if isFirstResponder() { return self } for subview in subviews { if let responder = subview.firstResponder { return responder } } return nil } }
mit
c4e89abfb847851208f7771674fd6721
38.776119
150
0.669794
5.818777
false
false
false
false
johnno1962c/swift-corelibs-foundation
Foundation/NSKeyedArchiver.swift
7
38362
// 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 CoreFoundation /// Archives created using the class method `archivedData(withRootObject:)` use this key /// for the root object in the hierarchy of encoded objects. The `NSKeyedUnarchiver` class method /// `unarchiveObject(with:)` looks for this root key as well. public let NSKeyedArchiveRootObjectKey: String = "root" internal let NSKeyedArchiveNullObjectReference = _NSKeyedArchiverUID(value: 0) internal let NSKeyedArchiveNullObjectReferenceName: String = "$null" internal let NSKeyedArchivePlistVersion = 100000 internal let NSKeyedArchiverSystemVersion : UInt32 = 2000 internal func escapeArchiverKey(_ key: String) -> String { if key.hasPrefix("$") { return "$" + key } else { return key } } internal let NSPropertyListClasses : [AnyClass] = [ NSArray.self, NSDictionary.self, NSString.self, NSData.self, NSDate.self, NSNumber.self ] /// `NSKeyedArchiver`, a concrete subclass of `NSCoder`, provides a way to encode objects /// (and scalar values) into an architecture-independent format that can be stored in a file. /// When you archive a set of objects, the class information and instance variables for each object /// are written to the archive. `NSKeyedArchiver`’s companion class, `NSKeyedUnarchiver`, /// decodes the data in an archive and creates a set of objects equivalent to the original set. /// /// A keyed archive differs from a non-keyed archive in that all the objects and values /// encoded into the archive are given names, or keys. When decoding a non-keyed archive, /// values have to be decoded in the same order in which they were encoded. /// When decoding a keyed archive, because values are requested by name, values can be decoded /// out of sequence or not at all. Keyed archives, therefore, provide better support /// for forward and backward compatibility. /// /// The keys given to encoded values must be unique only within the scope of the current /// object being encoded. A keyed archive is hierarchical, so the keys used by object A /// to encode its instance variables do not conflict with the keys used by object B, /// even if A and B are instances of the same class. Within a single object, /// however, the keys used by a subclass can conflict with keys used in its superclasses. /// /// An `NSKeyedArchiver` object can write the archive data to a file or to a /// mutable-data object (an instance of `NSMutableData`) that you provide. open class NSKeyedArchiver : NSCoder { struct ArchiverFlags : OptionSet { let rawValue : UInt init(rawValue : UInt) { self.rawValue = rawValue } static let none = ArchiverFlags(rawValue: 0) static let finishedEncoding = ArchiverFlags(rawValue : 1) static let requiresSecureCoding = ArchiverFlags(rawValue: 2) } private class EncodingContext { // the object container that is being encoded var dict = Dictionary<String, Any>() // the index used for non-keyed objects (encodeObject: vs encodeObject:forKey:) var genericKey : UInt = 0 } private static var _classNameMap = Dictionary<String, String>() private static var _classNameMapLock = NSLock() private var _stream : AnyObject private var _flags = ArchiverFlags(rawValue: 0) private var _containers : Array<EncodingContext> = [EncodingContext()] private var _objects : Array<Any> = [NSKeyedArchiveNullObjectReferenceName] private var _objRefMap : Dictionary<AnyHashable, UInt32> = [:] private var _replacementMap : Dictionary<AnyHashable, Any> = [:] private var _classNameMap : Dictionary<String, String> = [:] private var _classes : Dictionary<String, _NSKeyedArchiverUID> = [:] private var _cache : Array<_NSKeyedArchiverUID> = [] /// The archiver’s delegate. open weak var delegate: NSKeyedArchiverDelegate? /// The format in which the receiver encodes its data. /// /// The available formats are `xml` and `binary`. open var outputFormat = PropertyListSerialization.PropertyListFormat.binary { willSet { if outputFormat != PropertyListSerialization.PropertyListFormat.xml && outputFormat != PropertyListSerialization.PropertyListFormat.binary { NSUnimplemented() } } } /// Returns an `NSData` object containing the encoded form of the object graph /// whose root object is given. /// /// - Parameter rootObject: The root of the object graph to archive. /// - Returns: An `NSData` object containing the encoded form of the object graph /// whose root object is rootObject. The format of the archive is /// `NSPropertyListBinaryFormat_v1_0`. open class func archivedData(withRootObject rootObject: Any) -> Data { let data = NSMutableData() let keyedArchiver = NSKeyedArchiver(forWritingWith: data) keyedArchiver.encode(rootObject, forKey: NSKeyedArchiveRootObjectKey) keyedArchiver.finishEncoding() return data._swiftObject } /// Archives an object graph rooted at a given object by encoding it into a data object /// then atomically writes the resulting data object to a file at a given path, /// and returns a Boolean value that indicates whether the operation was successful. /// /// - Parameters: /// - rootObject: The root of the object graph to archive. /// - path: The path of the file in which to write the archive. /// - Returns: `true` if the operation was successful, otherwise `false`. open class func archiveRootObject(_ rootObject: Any, toFile path: String) -> Bool { var fd : Int32 = -1 var auxFilePath : String var finishedEncoding : Bool = false do { (fd, auxFilePath) = try _NSCreateTemporaryFile(path) } catch _ { return false } defer { do { if finishedEncoding { try _NSCleanupTemporaryFile(auxFilePath, path) } else { try FileManager.default.removeItem(atPath: auxFilePath) } } catch _ { } } let writeStream = _CFWriteStreamCreateFromFileDescriptor(kCFAllocatorSystemDefault, fd)! if !CFWriteStreamOpen(writeStream) { return false } defer { CFWriteStreamClose(writeStream) } let keyedArchiver = NSKeyedArchiver(output: writeStream) keyedArchiver.encode(rootObject, forKey: NSKeyedArchiveRootObjectKey) keyedArchiver.finishEncoding() finishedEncoding = keyedArchiver._flags.contains(ArchiverFlags.finishedEncoding) return finishedEncoding } public override convenience init() { self.init(forWritingWith: NSMutableData()) } private init(output: AnyObject) { self._stream = output super.init() } /// Returns the archiver, initialized for encoding an archive into a given a mutable-data object. /// /// When you finish encoding data, you must invoke `finishEncoding()` at which point data /// is filled. The format of the archive is `NSPropertyListBinaryFormat_v1_0`. /// /// - Parameter data: The mutable-data object into which the archive is written. public convenience init(forWritingWith data: NSMutableData) { self.init(output: data) } private func _writeXMLData(_ plist : NSDictionary) -> Bool { var success = false if let data = self._stream as? NSMutableData { let xml : CFData? xml = _CFPropertyListCreateXMLDataWithExtras(kCFAllocatorSystemDefault, plist) if let unwrappedXml = xml { data.append(unwrappedXml._swiftObject) success = true } } else { success = CFPropertyListWrite(plist, self._stream as! CFWriteStream, kCFPropertyListXMLFormat_v1_0, 0, nil) > 0 } return success } private func _writeBinaryData(_ plist : NSDictionary) -> Bool { return __CFBinaryPlistWriteToStream(plist, self._stream) > 0 } /// Returns the encoded data for the archiver. /// /// If encoding has not yet finished, invoking this property calls `finishEncoding()` /// and returns the data. If you initialized the keyed archiver with a specific /// mutable data instance, then that data is returned by the property after /// `finishEncoding()` is called. open var encodedData: Data { if !_flags.contains(.finishedEncoding) { finishEncoding() } return (_stream as! NSData)._swiftObject } /// Instructs the archiver to construct the final data stream. /// /// No more values can be encoded after this method is called. You must call this method when finished. open func finishEncoding() { if _flags.contains(ArchiverFlags.finishedEncoding) { return } var plist = Dictionary<String, Any>() var success : Bool plist["$archiver"] = NSStringFromClass(type(of: self)) plist["$version"] = NSKeyedArchivePlistVersion plist["$objects"] = self._objects plist["$top"] = self._containers[0].dict if let unwrappedDelegate = self.delegate { unwrappedDelegate.archiverWillFinish(self) } let nsPlist = plist._bridgeToObjectiveC() if self.outputFormat == PropertyListSerialization.PropertyListFormat.xml { success = _writeXMLData(nsPlist) } else { success = _writeBinaryData(nsPlist) } if let unwrappedDelegate = self.delegate { unwrappedDelegate.archiverDidFinish(self) } if success { let _ = self._flags.insert(ArchiverFlags.finishedEncoding) } } /// Adds a class translation mapping to `NSKeyedArchiver` whereby instances of a given /// class are encoded with a given class name instead of their real class names. /// /// When encoding, the class’s translation mapping is used only if no translation /// is found first in an instance’s separate translation map. /// /// - Parameters: /// - codedName: The name of the class that `NSKeyedArchiver` uses in place of `cls`. /// - cls: The class for which to set up a translation mapping. open class func setClassName(_ codedName: String?, for cls: AnyClass) { let clsName = String(describing: type(of: cls)) _classNameMapLock.synchronized { _classNameMap[clsName] = codedName } } /// Adds a class translation mapping to `NSKeyedArchiver` whereby instances of a given /// class are encoded with a given class name instead of their real class names. /// /// When encoding, the receiver’s translation map overrides any translation /// that may also be present in the class’s map. /// /// - Parameters: /// - codedName: The name of the class that the archiver uses in place of `cls`. /// - cls: The class for which to set up a translation mapping. open func setClassName(_ codedName: String?, for cls: AnyClass) { let clsName = String(describing: type(of: cls)) _classNameMap[clsName] = codedName } open override var systemVersion: UInt32 { return NSKeyedArchiverSystemVersion } open override var allowsKeyedCoding: Bool { return true } private func _validateStillEncoding() -> Bool { if self._flags.contains(ArchiverFlags.finishedEncoding) { fatalError("Encoder already finished") } return true } private class func _supportsSecureCoding(_ objv : Any?) -> Bool { var supportsSecureCoding : Bool = false if let secureCodable = objv as? NSSecureCoding { supportsSecureCoding = type(of: secureCodable).supportsSecureCoding } return supportsSecureCoding } private func _validateObjectSupportsSecureCoding(_ objv : Any?) { if let objv = objv, self.requiresSecureCoding && !NSKeyedArchiver._supportsSecureCoding(objv) { fatalError("Secure coding required when encoding \(objv)") } } private func _createObjectRefCached(_ uid : UInt32) -> _NSKeyedArchiverUID { if uid == 0 { return NSKeyedArchiveNullObjectReference } else if Int(uid) <= self._cache.count { return self._cache[Int(uid) - 1] } else { let objectRef = _NSKeyedArchiverUID(value: uid) self._cache.insert(objectRef, at: Int(uid) - 1) return objectRef } } /** Return a new object identifier, freshly allocated if need be. A placeholder null object is associated with the reference. */ private func _referenceObject(_ objv: Any?, conditional: Bool = false) -> _NSKeyedArchiverUID? { var uid : UInt32? if objv == nil { return NSKeyedArchiveNullObjectReference } let value = _SwiftValue.store(objv)! uid = self._objRefMap[value] if uid == nil { if conditional { return nil // object has not been unconditionally encoded } uid = UInt32(self._objects.count) self._objRefMap[value] = uid self._objects.insert(NSKeyedArchiveNullObjectReferenceName, at: Int(uid!)) } return _createObjectRefCached(uid!) } /** Returns true if the object has already been encoded. */ private func _haveVisited(_ objv: Any?) -> Bool { if objv == nil { return true // always have a null reference } else { return self._objRefMap[_SwiftValue.store(objv!)] != nil } } /** Get or create an object reference, and associate the object. */ private func _addObject(_ objv: Any?) -> _NSKeyedArchiverUID? { let haveVisited = _haveVisited(objv) let objectRef = _referenceObject(objv) if !haveVisited { _setObject(objv!, forReference: objectRef!) } return objectRef } private func _pushEncodingContext(_ encodingContext: EncodingContext) { self._containers.append(encodingContext) } private func _popEncodingContext() { self._containers.removeLast() } private var _currentEncodingContext : EncodingContext { return self._containers.last! } /** Associate an encoded object or reference with a key in the current encoding context */ private func _setObjectInCurrentEncodingContext(_ object : Any?, forKey key: String? = nil, escape: Bool = true) { let encodingContext = self._containers.last! var encodingKey : String if key != nil { if escape { encodingKey = escapeArchiverKey(key!) } else { encodingKey = key! } } else { encodingKey = _nextGenericKey() } if encodingContext.dict[encodingKey] != nil { NSLog("*** NSKeyedArchiver warning: replacing existing value for key '\(encodingKey)'; probable duplication of encoding keys in class hierarchy") } encodingContext.dict[encodingKey] = object } /** The generic key is used for objects that are encoded without a key. It is a per-encoding context monotonically increasing integer prefixed with "$". */ private func _nextGenericKey() -> String { let key = "$" + String(_currentEncodingContext.genericKey) _currentEncodingContext.genericKey += 1 return key } /** Update replacement object mapping */ private func replaceObject(_ object: Any, withObject replacement: Any?) { if let unwrappedDelegate = self.delegate { unwrappedDelegate.archiver(self, willReplace: object, with: replacement) } self._replacementMap[_SwiftValue.store(object)] = replacement } /** Returns true if the type cannot be encoded directly (i.e. is a container type) */ private func _isContainer(_ objv: Any?) -> Bool { // Note that we check for class equality rather than membership, because // their mutable subclasses are as object references guard let obj = objv else { return false } if obj is String { return false } guard let nsObject = obj as? NSObject else { return true } return !(nsObject.classForCoder === NSString.self || nsObject.classForCoder === NSNumber.self || nsObject.classForCoder === NSData.self) } /** Associates an object with an existing reference */ private func _setObject(_ objv: Any, forReference reference : _NSKeyedArchiverUID) { let index = Int(reference.value) self._objects[index] = objv } /** Returns a dictionary describing class metadata for a class */ private func _classDictionary(_ clsv: AnyClass) -> Dictionary<String, Any> { func _classNameForClass(_ clsv: AnyClass) -> String? { var className : String? className = classNameForClass(clsv) if className == nil { className = NSKeyedArchiver.classNameForClass(clsv) } return className } var classDict : [String:Any] = [:] let className = NSStringFromClass(clsv) let mappedClassName = _classNameForClass(clsv) if mappedClassName != nil && mappedClassName != className { // If we have a mapped class name, OS X only encodes the mapped name classDict["$classname"] = mappedClassName } else { var classChain : [String] = [] var classIter : AnyClass? = clsv classDict["$classname"] = className repeat { classChain.append(NSStringFromClass(classIter!)) classIter = _getSuperclass(classIter!) } while classIter != nil classDict["$classes"] = classChain if let ns = clsv as? NSObject.Type { let classHints = ns.classFallbacksForKeyedArchiver() if !classHints.isEmpty { classDict["$classhints"] = classHints } } } return classDict } /** Return an object reference for a class Because _classDictionary() returns a dictionary by value, and every time we bridge to NSDictionary we get a new object (the hash code is different), we maintain a private mapping between class name and object reference to avoid redundantly encoding class metadata */ private func _classReference(_ clsv: AnyClass) -> _NSKeyedArchiverUID? { let className = NSStringFromClass(clsv) var classRef = self._classes[className] // keyed by actual class name if classRef == nil { let classDict = _classDictionary(clsv) classRef = _addObject(classDict._bridgeToObjectiveC()) if let unwrappedClassRef = classRef { self._classes[className] = unwrappedClassRef } } return classRef } /** Return the object replacing another object (if any) */ private func _replacementObject(_ object: Any?) -> Any? { var objectToEncode : Any? = nil // object to encode after substitution // nil cannot be mapped if object == nil { return nil } // check replacement cache if let hashable = object as? AnyHashable { objectToEncode = self._replacementMap[hashable] if objectToEncode != nil { return objectToEncode } } // object replaced by NSObject.replacementObject(for:) // if it is replaced with nil, it cannot be further replaced if let ns = objectToEncode as? NSObject { objectToEncode = ns.replacementObject(for: self) if objectToEncode == nil { replaceObject(object!, withObject: nil) return nil } } if objectToEncode == nil { objectToEncode = object } // object replaced by delegate. If the delegate returns nil, nil is encoded if let unwrappedDelegate = self.delegate { objectToEncode = unwrappedDelegate.archiver(self, willEncode: objectToEncode!) replaceObject(object!, withObject: objectToEncode) } return objectToEncode } /** Internal function to encode an object. Returns the object reference. */ private func _encodeObject(_ objv: Any?, conditional: Bool = false) -> NSObject? { var object : Any? = nil // object to encode after substitution var objectRef : _NSKeyedArchiverUID? // encoded object reference let haveVisited : Bool let _ = _validateStillEncoding() haveVisited = _haveVisited(objv) object = _replacementObject(objv) // bridge value types if let bridgedObject = object as? _ObjectBridgeable { object = bridgedObject._bridgeToAnyObject() } objectRef = _referenceObject(object, conditional: conditional) guard let unwrappedObjectRef = objectRef else { // we can return nil if the object is being conditionally encoded return nil } _validateObjectSupportsSecureCoding(object) if !haveVisited { var encodedObject : Any if _isContainer(object) { guard let codable = object as? NSCoding else { fatalError("Object \(String(describing: object)) does not conform to NSCoding") } let innerEncodingContext = EncodingContext() _pushEncodingContext(innerEncodingContext) codable.encode(with: self) let ns = object as? NSObject let cls : AnyClass = ns?.classForKeyedArchiver ?? type(of: object!) as! AnyClass _setObjectInCurrentEncodingContext(_classReference(cls), forKey: "$class", escape: false) _popEncodingContext() encodedObject = innerEncodingContext.dict } else { encodedObject = object! } _setObject(encodedObject, forReference: unwrappedObjectRef) } if let unwrappedDelegate = self.delegate { unwrappedDelegate.archiver(self, didEncode: object) } return unwrappedObjectRef } /** Encode an object and associate it with a key in the current encoding context. */ private func _encodeObject(_ objv: Any?, forKey key: String?, conditional: Bool = false) { if let objectRef = _encodeObject(objv, conditional: conditional) { _setObjectInCurrentEncodingContext(objectRef, forKey: key, escape: key != nil) } } open override func encode(_ object: Any?) { _encodeObject(object, forKey: nil) } open override func encodeConditionalObject(_ object: Any?) { _encodeObject(object, forKey: nil, conditional: true) } /// Encodes a given object and associates it with a given key. /// /// - Parameters: /// - objv: The value to encode. /// - key: The key with which to associate `objv`. open override func encode(_ objv: Any?, forKey key: String) { _encodeObject(objv, forKey: key, conditional: false) } /// Encodes a reference to a given object and associates it with a given key /// only if it has been unconditionally encoded elsewhere in the archive with `encode(_:forKey:)`. /// /// - Parameters: /// - objv: The object to encode. /// - key: The key with which to associate the encoded value. open override func encodeConditionalObject(_ objv: Any?, forKey key: String) { _encodeObject(objv, forKey: key, conditional: true) } open override func encodePropertyList(_ aPropertyList: Any) { if !NSPropertyListClasses.contains(where: { $0 == type(of: aPropertyList) }) { fatalError("Cannot encode non-property list type \(type(of: aPropertyList)) as property list") } encode(aPropertyList) } open func encodePropertyList(_ aPropertyList: Any, forKey key: String) { if !NSPropertyListClasses.contains(where: { $0 == type(of: aPropertyList) }) { fatalError("Cannot encode non-property list type \(type(of: aPropertyList)) as property list") } encode(aPropertyList, forKey: key) } open func _encodePropertyList(_ aPropertyList: Any, forKey key: String? = nil) { let _ = _validateStillEncoding() _setObjectInCurrentEncodingContext(aPropertyList, forKey: key) } internal func _encodeValue<T: NSObject>(_ objv: T, forKey key: String? = nil) where T: NSCoding { _encodePropertyList(objv, forKey: key) } private func _encodeValueOfObjCType(_ type: _NSSimpleObjCType, at addr: UnsafeRawPointer) { switch type { case .ID: let objectp = addr.assumingMemoryBound(to: Any.self) encode(objectp.pointee) case .Class: let classp = addr.assumingMemoryBound(to: AnyClass.self) encode(NSStringFromClass(classp.pointee)._bridgeToObjectiveC()) case .Char: let charp = addr.assumingMemoryBound(to: CChar.self) _encodeValue(NSNumber(value: charp.pointee)) case .UChar: let ucharp = addr.assumingMemoryBound(to: UInt8.self) _encodeValue(NSNumber(value: ucharp.pointee)) case .Int, .Long: let intp = addr.assumingMemoryBound(to: Int32.self) _encodeValue(NSNumber(value: intp.pointee)) case .UInt, .ULong: let uintp = addr.assumingMemoryBound(to: UInt32.self) _encodeValue(NSNumber(value: uintp.pointee)) case .LongLong: let longlongp = addr.assumingMemoryBound(to: Int64.self) _encodeValue(NSNumber(value: longlongp.pointee)) case .ULongLong: let ulonglongp = addr.assumingMemoryBound(to: UInt64.self) _encodeValue(NSNumber(value: ulonglongp.pointee)) case .Float: let floatp = addr.assumingMemoryBound(to: Float.self) _encodeValue(NSNumber(value: floatp.pointee)) case .Double: let doublep = addr.assumingMemoryBound(to: Double.self) _encodeValue(NSNumber(value: doublep.pointee)) case .Bool: let boolp = addr.assumingMemoryBound(to: Bool.self) _encodeValue(NSNumber(value: boolp.pointee)) case .CharPtr: let charpp = addr.assumingMemoryBound(to: UnsafePointer<Int8>.self) encode(NSString(utf8String: charpp.pointee)) default: fatalError("NSKeyedArchiver.encodeValueOfObjCType: unknown type encoding ('\(type.rawValue)')") } } open override func encodeValue(ofObjCType typep: UnsafePointer<Int8>, at addr: UnsafeRawPointer) { guard let type = _NSSimpleObjCType(UInt8(typep.pointee)) else { let spec = String(typep.pointee) fatalError("NSKeyedArchiver.encodeValueOfObjCType: unsupported type encoding spec '\(spec)'") } if type == .StructBegin { fatalError("NSKeyedArchiver.encodeValueOfObjCType: this archiver cannot encode structs") } else if type == .ArrayBegin { let scanner = Scanner(string: String(cString: typep)) scanner.scanLocation = 1 // advance past ObJCType var count : Int = 0 guard scanner.scanInt(&count) && count > 0 else { fatalError("NSKeyedArchiver.encodeValueOfObjCType: array count is missing or zero") } guard let elementType = _NSSimpleObjCType(scanner.scanUpToString(String(_NSSimpleObjCType.ArrayEnd))) else { fatalError("NSKeyedArchiver.encodeValueOfObjCType: array type is missing") } encode(_NSKeyedCoderOldStyleArray(objCType: elementType, count: count, at: addr)) } else { return _encodeValueOfObjCType(type, at: addr) } } /// Encodes a given Boolean value and associates it with a given key. /// /// - Parameters: /// - boolv: The value to encode. /// - key: The key with which to associate `boolv`. open override func encode(_ boolv: Bool, forKey key: String) { _encodeValue(NSNumber(value: boolv), forKey: key) } /// Encodes a given 32-bit integer value and associates it with a given key. /// /// - Parameters: /// - intv: The value to encode. /// - key: The key with which to associate `intv`. open override func encode(_ intv: Int32, forKey key: String) { _encodeValue(NSNumber(value: intv), forKey: key) } /// Encodes a given 64-bit integer value and associates it with a given key. /// /// - Parameters: /// - intv: The value to encode. /// - key: The key with which to associate `intv`. open override func encode(_ intv: Int64, forKey key: String) { _encodeValue(NSNumber(value: intv), forKey: key) } /// Encodes a given float value and associates it with a given key. /// /// - Parameters: /// - realv: The value to encode. /// - key: The key with which to associate `realv`. open override func encode(_ realv: Float, forKey key: String) { _encodeValue(NSNumber(value: realv), forKey: key) } /// Encodes a given double value and associates it with a given key. /// /// - Parameters: /// - realv: The value to encode. /// - key: The key with which to associate `realv`. open override func encode(_ realv: Double, forKey key: String) { _encodeValue(NSNumber(value: realv), forKey: key) } /// Encodes a given integer value and associates it with a given key. /// /// - Parameters: /// - intv: The value to encode. /// - key: The key with which to associate `intv`. open override func encode(_ intv: Int, forKey key: String) { _encodeValue(NSNumber(value: intv), forKey: key) } open override func encode(_ data: Data) { // this encodes as a reference to an NSData object rather than encoding inline encode(data._nsObject) } /// Encodes a given number of bytes from a given C array of bytes and associates /// them with the a given key. /// /// - Parameters: /// - bytesp: A C array of bytes to encode. /// - lenv: The number of bytes from `bytesp` to encode. /// - key: The key with which to associate the encoded value. open override func encodeBytes(_ bytesp: UnsafePointer<UInt8>?, length lenv: Int, forKey key: String) { // this encodes the data inline let data = NSData(bytes: bytesp, length: lenv) _encodeValue(data, forKey: key) } /** Helper API for NSArray and NSDictionary that encodes an array of objects, creating references as it goes */ internal func _encodeArrayOfObjects(_ objects : NSArray, forKey key : String) { var objectRefs = [NSObject]() objectRefs.reserveCapacity(objects.count) for object in objects { let objectRef = _encodeObject(_SwiftValue.store(object))! objectRefs.append(objectRef) } _encodeValue(objectRefs._bridgeToObjectiveC(), forKey: key) } /// Indicates whether the archiver requires all archived classes to conform to `NSSecureCoding`. /// /// If you set the receiver to require secure coding, it will cause a fatal error /// if you attempt to archive a class which does not conform to `NSSecureCoding`. open override var requiresSecureCoding: Bool { get { return _flags.contains(ArchiverFlags.requiresSecureCoding) } set { if newValue { let _ = _flags.insert(ArchiverFlags.requiresSecureCoding) } else { _flags.remove(ArchiverFlags.requiresSecureCoding) } } } /// Returns the class name with which `NSKeyedArchiver` encodes instances of a given class. /// /// - Parameter cls: The class for which to determine the translation mapping. /// - Returns: The class name with which `NSKeyedArchiver` encodes instances of `cls`. /// Returns `nil` if `NSKeyedArchiver` does not have a translation mapping for `cls`. open class func classNameForClass(_ cls: AnyClass) -> String? { let clsName = String(reflecting: cls) var mappedClass : String? _classNameMapLock.synchronized { mappedClass = _classNameMap[clsName] } return mappedClass } /// Returns the class name with which the archiver encodes instances of a given class. /// /// - Parameter cls: The class for which to determine the translation mapping. /// - Returns: The class name with which the receiver encodes instances of cls. /// Returns `nil` if the archiver does not have a translation /// mapping for `cls`. The class’s separate translation map is not searched. open func classNameForClass(_ cls: AnyClass) -> String? { let clsName = String(reflecting: cls) return _classNameMap[clsName] } } extension NSKeyedArchiverDelegate { func archiver(_ archiver: NSKeyedArchiver, willEncode object: Any) -> Any? { // Returning the same object is the same as doing nothing return object } func archiver(_ archiver: NSKeyedArchiver, didEncode object: Any?) { } func archiver(_ archiver: NSKeyedArchiver, willReplace object: Any?, with newObject: Any?) { } func archiverWillFinish(_ archiver: NSKeyedArchiver) { } func archiverDidFinish(_ archiver: NSKeyedArchiver) { } } /// The `NSKeyedArchiverDelegate` protocol defines the optional methods implemented /// by delegates of `NSKeyedArchiver` objects. public protocol NSKeyedArchiverDelegate : class { /// Informs the delegate that `object` is about to be encoded. /// /// This method is called after the original object may have replaced itself /// with `replacementObject(for:)`. /// /// This method is called whether or not the object is being encoded conditionally. /// /// This method is not called for an object once a replacement mapping has been set up /// for that object (either explicitly, or because the object has previously been encoded). /// This method is also not called when `nil` is about to be encoded. /// /// - Parameters: /// - archiver: The archiver that invoked the method. /// - object: The object that is about to be encoded. /// - Returns: Either object or a different object to be encoded in its stead. /// The delegate can also modify the coder state. If the delegate /// returns `nil`, `nil` is encoded. func archiver(_ archiver: NSKeyedArchiver, willEncode object: Any) -> Any? /// Informs the delegate that a given object has been encoded. /// /// The delegate might restore some state it had modified previously, /// or use this opportunity to keep track of the objects that are encoded. /// /// This method is not called for conditional objects until they are actually encoded (if ever). /// /// - Parameters: /// - archiver: The archiver that invoked the method. /// - object: The object that has been encoded. func archiver(_ archiver: NSKeyedArchiver, didEncode object: Any?) /// Informs the delegate that one given object is being substituted for another given object. /// /// This method is called even when the delegate itself is doing, or has done, /// the substitution. The delegate may use this method if it is keeping track /// of the encoded or decoded objects. /// /// - Parameters: /// - archiver: The archiver that invoked the method. /// - object: The object being replaced in the archive. /// - newObject: The object replacing `object` in the archive. func archiver(_ archiver: NSKeyedArchiver, willReplace object: Any?, withObject newObject: Any?) /// Notifies the delegate that encoding is about to finish. /// /// - Parameter archiver: The archiver that invoked the method. func archiverWillFinish(_ archiver: NSKeyedArchiver) /// Notifies the delegate that encoding has finished. /// /// - Parameter archiver: The archiver that invoked the method. func archiverDidFinish(_ archiver: NSKeyedArchiver) }
apache-2.0
6c130aa999cdb951dacad30d09fa289b
37.971545
157
0.619276
4.906346
false
false
false
false
dcoufal/DECResizeFontToFitRect
Pod/Classes/ResizeFontToFitRect.swift
1
3564
// // Copyright (c) David Coufal 2015 // davidcoufal.com // Released for general use under an MIT license: http://opensource.org/licenses/MIT // import UIKit /** This function takes a font and returns a new font (if required) that can be used to fit the given String into the given CGRect. Only the pointSize of the font is modified. @param font: The font to start with. @param toRect: The CGRect to fit the string into using the font @param forString: The string to be fitted. @param withMaxFontSize: The maximum pointSize to be used. @param withMinFontSize: The minimum pointSize to be used. @param withFontSizeIncrement: The amount to increment the font pointSize by during calculations. Smaller values give a more accurate result, but take longer to calculate. @param andStringDrawingOptions: The `NSStringDrawingOptions` to be used in the call to String.boundingRect to calculate fits. @return A new UIFont (if needed, if no calculations can be performed the same font is returned) that will fit the String to the CGRect */ public func resize( font: UIFont, toRect rect: CGRect, forString text: String?, withMaxFontSize maxFontSizeIn: CGFloat, withMinFontSize minFontSize: CGFloat, withFontSizeIncrement fontSizeIncrement: CGFloat = 1.0, andStringDrawingOptions stringDrawingOptions: NSStringDrawingOptions = .usesLineFragmentOrigin ) -> UIFont { guard maxFontSizeIn > minFontSize else { assertionFailure("maxFontSize should be larger than minFontSize") return font } guard let text = text else { return font } var maxFontSize = maxFontSizeIn let words = text.components(separatedBy: CharacterSet.whitespacesAndNewlines) // calculate max font size based on each word for word in words { maxFontSize = getMaxFontSize(forWord: word, forWidth: rect.width, usingFont: font, withMaxFontSize: maxFontSize, withMinFontSize: minFontSize, withFontSizeIncrement: fontSizeIncrement) } // calculate what the font size should be based on entire phrase var tempfont = font.withSize(maxFontSize) var currentFontSize = maxFontSize while (currentFontSize > minFontSize) { tempfont = font.withSize(currentFontSize) let constraintSize = CGSize(width: rect.size.width, height: CGFloat.greatestFiniteMagnitude) let labelSize = text.boundingRect( with: constraintSize, options: stringDrawingOptions, attributes: [ .font : tempfont ], context: nil) if (labelSize.height <= rect.height) { break } currentFontSize -= fontSizeIncrement } return tempfont; } internal func getMaxFontSize( forWord word: String, forWidth width: CGFloat, usingFont font: UIFont, withMaxFontSize maxFontSize: CGFloat, withMinFontSize minFontSize: CGFloat, withFontSizeIncrement fontSizeIncrement: CGFloat) -> CGFloat { var currentFontSize: CGFloat = maxFontSize while (currentFontSize > minFontSize) { let tempfont = font.withSize(currentFontSize) let labelSize = word.size(withAttributes: [.font: tempfont]) if (labelSize.width < width) { return currentFontSize } currentFontSize -= fontSizeIncrement } return minFontSize }
mit
47af36a5214cf7d3f6ed901bb1ac8527
35.742268
171
0.669753
4.998597
false
false
false
false
Marquis103/VirtualTourist
VirtualTourist/PhotoViewController.swift
1
11626
// // PhotoViewController.swift // VirtualTourist // // Created by Marquis Dennis on 2/22/16. // Copyright © 2016 Marquis Dennis. All rights reserved. // import UIKit import MapKit import CoreData class PhotoViewController: UIViewController { var pin:Pin? var photoURLs:[String:NSDate]? @IBOutlet weak var newCollection: UIButton! @IBOutlet weak var photoCollectionView: UICollectionView! @IBOutlet weak var mapView: MKMapView! @IBOutlet weak var noPhotosLabel: UILabel! private var selectedPhotos:[NSIndexPath]? private var isFetchingData = false private var photosFilePath: String { return NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first! } override func viewDidLoad() { super.viewDidLoad() mapView.userInteractionEnabled = false photoCollectionView.backgroundColor = UIColor.whiteColor() photoCollectionView.delegate = self photoCollectionView.dataSource = self photoCollectionView.allowsMultipleSelection = true //set region if let pin = self.pin { let latitude = pin.latitude as! CLLocationDegrees let longitude = pin.longitude as! CLLocationDegrees let center = CLLocationCoordinate2D(latitude: latitude, longitude: longitude) let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05)) mapView.setRegion(region, animated: true) //drop annotation at pin let marker = MKPointAnnotation() marker.coordinate = center mapView.addAnnotation(marker) } loadfetchedResultsController() //array for selected items -- used to alleviate reusable cells being selected selectedPhotos = [NSIndexPath]() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) noPhotosLabel.hidden = true if pin?.photos?.count <= 0 { newCollection.enabled = false getPhotos() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func willAnimateRotationToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) { //set region if let pin = pin { let latitude = pin.latitude as! CLLocationDegrees let longitude = pin.longitude as! CLLocationDegrees let center = CLLocationCoordinate2D(latitude: latitude, longitude: longitude) let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05)) mapView.setRegion(region, animated: true) } } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() let width = CGRectGetWidth(view.frame) / 3 let layout = photoCollectionView.collectionViewLayout as! UICollectionViewFlowLayout layout.itemSize = CGSize(width: width - 1, height: width - 1) } //MARK: - Shared Context lazy var sharedContext: NSManagedObjectContext = { CoreDataStack.sharedInstance.managedObjectContext }() //MARK: NSFetchedResultsController lazy var fetchedResultsController : NSFetchedResultsController = { //create the fetch request let fetchRequest = NSFetchRequest(entityName: "Photo") //add a sort descriptor, enforces a sort order on the results fetchRequest.sortDescriptors = [NSSortDescriptor(key: "dateTaken", ascending: false)] //add a predicate to only get photos for the specified pin if let latitude = self.pin?.latitude, let longitude = self.pin?.longitude { let predicate = NSPredicate(format: "(pin.latitude == %@) AND (pin.longitude == %@)", latitude, longitude) fetchRequest.predicate = predicate } //create fetched results controller let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.sharedContext, sectionNameKeyPath: nil, cacheName: nil) return fetchedResultsController }() func loadfetchedResultsController() { fetchedResultsController.delegate = self //get results from the fetchedResultsController do { try self.fetchedResultsController.performFetch() } catch { let fetchError = error as NSError print("\(fetchError), \(fetchError.userInfo)") self.alertUI(withTitle: "Failed Query", message: "Failed to load photos") } } //MARK: Functions @IBAction func photoAction(sender: UIButton) { if selectedPhotos?.count > 0 { photoCollectionView.performBatchUpdates({ () -> Void in for indexPath in (self.selectedPhotos?.sort({ $0.item > $1.item}))! { self.removePhotosFromPin(indexPath) } }, completion: { (completed) -> Void in performUIUpdatesOnMain({ () -> Void in self.photoCollectionView.deleteItemsAtIndexPaths(self.selectedPhotos!) self.selectedPhotos?.removeAll() self.newCollection.setTitle("New Collection", forState: .Normal) }) }) } else { newCollection.enabled = false photoCollectionView.performBatchUpdates({ () -> Void in if let pin = self.pin, let _ = pin.photos { self.isFetchingData = true for photo in self.fetchedResultsController.fetchedObjects as! [Photo] { self.sharedContext.deleteObject(photo) } CoreDataStack.sharedInstance.saveMainContext() } }, completion: { (completed) -> Void in self.isFetchingData = false self.getPhotos() }) } } func removePhotosFromPin(indexPath:NSIndexPath) { handleManagedObjectContextOperations { () -> Void in let photo = self.fetchedResultsController.objectAtIndexPath(indexPath) as! Photo self.sharedContext.deleteObject(photo) CoreDataStack.sharedInstance.saveMainContext() } } func alertUI(withTitle title:String, message:String) { let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert) let action = UIAlertAction(title: "OK", style: .Default, handler: nil) alert.addAction(action) presentViewController(alert, animated: true, completion: nil) } //MARK: - Get Photos from Flickr func getPhotos(fromCache cache:Bool = false) { FlickrClient.sharedClient.getPhotosByLocation(using: pin!) { (result, error) -> Void in guard error == nil else { self.alertUI(withTitle: "Failed Query", message: "Could not retrieve images for this pin location") return } if let photos = result { if let photosDict = photos["photos"] as? [String:AnyObject] { if let photosDesc = photosDict["photo"] as? [[String:AnyObject]] { self.photoURLs = [String:NSDate]() let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss" for (_, photoItem) in photosDesc.enumerate() { if let photoURL = photoItem["url_m"] as? String, let dateTaken = photoItem["datetaken"] as? String { //photo urls of images to be downloaded self.photoURLs![photoURL] = dateFormatter.dateFromString(dateTaken) } } if self.photoURLs!.keys.count > 0 { handleManagedObjectContextOperations({ () -> Void in for urlString in self.photoURLs!.keys { if let photoFileName = urlString.componentsSeparatedByString("/").last { let photo = Photo(context: self.sharedContext) photo.imageUrl = urlString photo.dateTaken = self.photoURLs![urlString]! photo.pin = self.pin! photo.imageLocation = photoFileName CoreDataStack.sharedInstance.saveMainContext() } } //performUIUpdatesOnMain({ () -> Void in self.photoCollectionView.hidden = false self.newCollection.enabled = true }) } else { performUIUpdatesOnMain({ () -> Void in self.photoCollectionView.hidden = true self.newCollection.enabled = true self.noPhotosLabel.hidden = false }) } } } } } } } extension PhotoViewController : UICollectionViewDelegate { func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool { return true } func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { if let cell = collectionView.cellForItemAtIndexPath(indexPath) as? PhotoViewCell { cell.selected = true selectedPhotos?.append(indexPath) newCollection.setTitle("Remove Selected Pictures", forState: .Normal) configure(cell, forRowAtIndexPath: indexPath) } } func collectionView(collectionView: UICollectionView, didDeselectItemAtIndexPath indexPath: NSIndexPath) { if let cell = collectionView.cellForItemAtIndexPath(indexPath) as? PhotoViewCell { cell.selected = false if let indexToRemove = selectedPhotos?.indexOf(indexPath) { selectedPhotos?.removeAtIndex(indexToRemove) } if selectedPhotos?.count == 0 { newCollection.setTitle("New Collection", forState: .Normal) } configure(cell, forRowAtIndexPath: indexPath) } } } extension PhotoViewController : UICollectionViewDataSource { func configure(cell: PhotoViewCell, forRowAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { if let indexSet = selectedPhotos { if indexSet.contains(indexPath) { if cell.photoCellImageView.alpha == 1.0 { performUIUpdatesOnMain({ () -> Void in cell.photoCellImageView.alpha = 0.5 }) } } else { performUIUpdatesOnMain({ () -> Void in cell.photoCellImageView.alpha = 1.0 }) } } return cell } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if let sectionInfo = fetchedResultsController.sections { return sectionInfo[section].numberOfObjects } else { return 0 } } func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("photoCell", forIndexPath: indexPath) as! PhotoViewCell let photo = fetchedResultsController.objectAtIndexPath(indexPath) as! Photo let imageLocation = photo.imageLocation! if NSFileManager.defaultManager().fileExistsAtPath(NSURL(string: self.photosFilePath)!.URLByAppendingPathComponent(imageLocation).path!) { cell.photoCellImageView.image = UIImage(contentsOfFile: NSURL(string: self.photosFilePath)!.URLByAppendingPathComponent(imageLocation).path!) cell.loadingView.hidden = true } else { //if the file does not exist download it from the Internet and save it if let imageURL = NSURL(string: photo.imageUrl) { performDownloadsAndUpdateInBackground({ () -> Void in if let imageData = NSData(contentsOfURL: imageURL) { //save file imageData.writeToFile(NSURL(string: self.photosFilePath)!.URLByAppendingPathComponent(imageURL.lastPathComponent!).path!, atomically: true) performUIUpdatesOnMain({ () -> Void in cell.photoCellImageView.image = UIImage(data: imageData) cell.loadingView.hidden = true }) } }) } } return configure(cell, forRowAtIndexPath: indexPath) } } extension PhotoViewController : NSFetchedResultsControllerDelegate { func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) { switch type { case .Delete: if isFetchingData { photoCollectionView.reloadData() } break case .Insert: photoCollectionView.reloadData() break default: return } } }
mit
5ad61aee4416e9e730aadbd15506702d
32.025568
208
0.719914
4.502324
false
false
false
false
AnirudhDas/AniruddhaDas.github.io
CricketNews/CricketNews/Animations/GSImageViewerController.swift
1
13803
// // GSImageViewerController.swift // CricketNews // // Created by Anirudh Das on 7/5/18. // Copyright © 2018 Aniruddha Das. All rights reserved. // import UIKit public struct GSImageInfo { public enum ImageMode : Int { case aspectFit = 1 case aspectFill = 2 } public let image : UIImage public let imageMode : ImageMode public var imageHD : URL? public var contentMode : UIViewContentMode { return UIViewContentMode(rawValue: imageMode.rawValue)! } public init(image: UIImage, imageMode: ImageMode) { self.image = image self.imageMode = imageMode } public init(image: UIImage, imageMode: ImageMode, imageHD: URL?) { self.init(image: image, imageMode: imageMode) self.imageHD = imageHD } func calculateRect(_ size: CGSize) -> CGRect { let widthRatio = size.width / image.size.width let heightRatio = size.height / image.size.height switch imageMode { case .aspectFit: return CGRect(origin: CGPoint.zero, size: size) case .aspectFill: return CGRect( x : 0, y : 0, width : image.size.width * max(widthRatio, heightRatio), height : image.size.height * max(widthRatio, heightRatio) ) } } func calculateMaximumZoomScale(_ size: CGSize) -> CGFloat { return max(2, max( image.size.width / size.width, image.size.height / size.height )) } } open class GSTransitionInfo { open var duration: TimeInterval = 0.35 open var canSwipe: Bool = true public init(fromView: UIView) { self.fromView = fromView } weak var fromView : UIView? fileprivate var convertedRect : CGRect? } open class GSImageViewerController: UIViewController { open let imageInfo : GSImageInfo open var transitionInfo : GSTransitionInfo? fileprivate let imageView = UIImageView() fileprivate let scrollView = UIScrollView() fileprivate lazy var session: URLSession = { let configuration = URLSessionConfiguration.ephemeral return URLSession(configuration: configuration, delegate: nil, delegateQueue: OperationQueue.main) }() // MARK: Initialization public init(imageInfo: GSImageInfo) { self.imageInfo = imageInfo super.init(nibName: nil, bundle: nil) } public convenience init(imageInfo: GSImageInfo, transitionInfo: GSTransitionInfo) { self.init(imageInfo: imageInfo) self.transitionInfo = transitionInfo if let fromView = transitionInfo.fromView, let referenceView = fromView.superview { self.transitioningDelegate = self self.modalPresentationStyle = .custom transitionInfo.convertedRect = referenceView.convert(fromView.frame, to: nil) } } public convenience init(image: UIImage, imageMode: UIViewContentMode, imageHD: URL?, fromView: UIView?) { let imageInfo = GSImageInfo(image: image, imageMode: GSImageInfo.ImageMode(rawValue: imageMode.rawValue)!, imageHD: imageHD) if let fromView = fromView { self.init(imageInfo: imageInfo, transitionInfo: GSTransitionInfo(fromView: fromView)) } else { self.init(imageInfo: imageInfo) } } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: Override override open func viewDidLoad() { super.viewDidLoad() setupView() setupScrollView() setupImageView() setupGesture() setupImageHD() edgesForExtendedLayout = UIRectEdge() scrollView.contentInsetAdjustmentBehavior = .automatic //automaticallyAdjustsScrollViewInsets = false } override open func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() imageView.frame = imageInfo.calculateRect(view.bounds.size) scrollView.frame = view.bounds scrollView.contentSize = imageView.bounds.size scrollView.maximumZoomScale = imageInfo.calculateMaximumZoomScale(scrollView.bounds.size) } // MARK: Setups fileprivate func setupView() { view.backgroundColor = UIColor.black } fileprivate func setupScrollView() { scrollView.delegate = self scrollView.minimumZoomScale = 1.0 scrollView.showsHorizontalScrollIndicator = false scrollView.showsVerticalScrollIndicator = false view.addSubview(scrollView) } fileprivate func setupImageView() { imageView.image = imageInfo.image imageView.contentMode = .scaleAspectFit scrollView.addSubview(imageView) } fileprivate func setupGesture() { let single = UITapGestureRecognizer(target: self, action: #selector(singleTap)) let double = UITapGestureRecognizer(target: self, action: #selector(doubleTap(_:))) double.numberOfTapsRequired = 2 single.require(toFail: double) scrollView.addGestureRecognizer(single) scrollView.addGestureRecognizer(double) if transitionInfo?.canSwipe == true { let pan = UIPanGestureRecognizer(target: self, action: #selector(pan(_:))) pan.delegate = self scrollView.addGestureRecognizer(pan) } } fileprivate func setupImageHD() { guard let imageHD = imageInfo.imageHD else { return } let request = URLRequest(url: imageHD, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 15) let task = session.dataTask(with: request, completionHandler: { (data, response, error) -> Void in guard let data = data else { return } guard let image = UIImage(data: data) else { return } self.imageView.image = image self.view.layoutIfNeeded() }) task.resume() } // MARK: Gesture @objc fileprivate func singleTap() { if navigationController == nil || (presentingViewController != nil && navigationController!.viewControllers.count <= 1) { dismiss(animated: true, completion: nil) } } @objc fileprivate func doubleTap(_ gesture: UITapGestureRecognizer) { let point = gesture.location(in: scrollView) if scrollView.zoomScale == 1.0 { scrollView.zoom(to: CGRect(x: point.x-40, y: point.y-40, width: 80, height: 80), animated: true) } else { scrollView.setZoomScale(1.0, animated: true) } } fileprivate var panViewOrigin : CGPoint? fileprivate var panViewAlpha : CGFloat = 1 @objc fileprivate func pan(_ gesture: UIPanGestureRecognizer) { func getProgress() -> CGFloat { let origin = panViewOrigin! let changeX = abs(scrollView.center.x - origin.x) let changeY = abs(scrollView.center.y - origin.y) let progressX = changeX / view.bounds.width let progressY = changeY / view.bounds.height return max(progressX, progressY) } func getChanged() -> CGPoint { let origin = scrollView.center let change = gesture.translation(in: view) return CGPoint(x: origin.x + change.x, y: origin.y + change.y) } func getVelocity() -> CGFloat { let vel = gesture.velocity(in: scrollView) return sqrt(vel.x*vel.x + vel.y*vel.y) } switch gesture.state { case .began: panViewOrigin = scrollView.center case .changed: scrollView.center = getChanged() panViewAlpha = 1 - getProgress() view.backgroundColor = UIColor(white: 0.0, alpha: panViewAlpha) gesture.setTranslation(CGPoint.zero, in: nil) case .ended: if getProgress() > 0.25 || getVelocity() > 1000 { dismiss(animated: true, completion: nil) } else { fallthrough } default: UIView.animate(withDuration: 0.3, animations: { self.scrollView.center = self.panViewOrigin! self.view.backgroundColor = UIColor(white: 0.0, alpha: 1.0) }, completion: { _ in self.panViewOrigin = nil self.panViewAlpha = 1.0 } ) } } } extension GSImageViewerController: UIScrollViewDelegate { public func viewForZooming(in scrollView: UIScrollView) -> UIView? { return imageView } public func scrollViewDidZoom(_ scrollView: UIScrollView) { imageView.frame = imageInfo.calculateRect(scrollView.contentSize) } } extension GSImageViewerController: UIViewControllerTransitioningDelegate { public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { return GSImageViewerTransition(imageInfo: imageInfo, transitionInfo: transitionInfo!, transitionMode: .present) } public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { return GSImageViewerTransition(imageInfo: imageInfo, transitionInfo: transitionInfo!, transitionMode: .dismiss) } } class GSImageViewerTransition: NSObject, UIViewControllerAnimatedTransitioning { let imageInfo : GSImageInfo let transitionInfo : GSTransitionInfo var transitionMode : TransitionMode enum TransitionMode { case present case dismiss } init(imageInfo: GSImageInfo, transitionInfo: GSTransitionInfo, transitionMode: TransitionMode) { self.imageInfo = imageInfo self.transitionInfo = transitionInfo self.transitionMode = transitionMode super.init() } func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return transitionInfo.duration } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { let containerView = transitionContext.containerView let tempMask = UIView() tempMask.backgroundColor = UIColor.black let tempImage = UIImageView(image: imageInfo.image) tempImage.layer.cornerRadius = transitionInfo.fromView!.layer.cornerRadius tempImage.layer.masksToBounds = true tempImage.contentMode = imageInfo.contentMode containerView.addSubview(tempMask) containerView.addSubview(tempImage) if transitionMode == .present { transitionInfo.fromView!.alpha = 0 let imageViewer = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) as! GSImageViewerController imageViewer.view.layoutIfNeeded() tempMask.alpha = 0 tempMask.frame = imageViewer.view.bounds tempImage.frame = transitionInfo.convertedRect! UIView.animate(withDuration: transitionInfo.duration, animations: { tempMask.alpha = 1 tempImage.frame = imageViewer.imageView.frame }, completion: { _ in tempMask.removeFromSuperview() tempImage.removeFromSuperview() containerView.addSubview(imageViewer.view) transitionContext.completeTransition(true) } ) } if transitionMode == .dismiss { let imageViewer = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from) as! GSImageViewerController imageViewer.view.removeFromSuperview() tempMask.alpha = imageViewer.panViewAlpha tempMask.frame = imageViewer.view.bounds tempImage.frame = imageViewer.scrollView.frame UIView.animate(withDuration: transitionInfo.duration, animations: { tempMask.alpha = 0 tempImage.frame = self.transitionInfo.convertedRect! }, completion: { _ in tempMask.removeFromSuperview() imageViewer.view.removeFromSuperview() self.transitionInfo.fromView!.alpha = 1 transitionContext.completeTransition(true) } ) } } } extension GSImageViewerController: UIGestureRecognizerDelegate { public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { if let pan = gestureRecognizer as? UIPanGestureRecognizer { if scrollView.zoomScale != 1.0 { return false } if imageInfo.imageMode == .aspectFill && (scrollView.contentOffset.x > 0 || pan.translation(in: view).x <= 0) { return false } } return true } }
apache-2.0
b785476457e7482079871ec9c712b496
32.911548
177
0.603318
5.481334
false
false
false
false
luckymore0520/leetcode
First Missing Positive.playground/Contents.swift
1
1073
//: Playground - noun: a place where people can play import UIKit //Given an unsorted integer array, find the first missing positive integer. // //For example, //Given [1,2,0] return 3, //and [3,4,-1,1] return 2. // //Your algorithm should run in O(n) time and uses constant space. //这题要求 O(n),而且对空间有要求 //遍历数组,把对应数字交换到对应的位置 class Solution { func firstMissingPositive(_ nums: [Int]) -> Int { if (nums.isEmpty) { return 1 } var nums = nums var i = 0 while i < nums.count { if (nums[i] != i+1 && nums[i] <= nums.count && nums[i] > 0 && nums[i] != nums[nums[i]-1]) { (nums[i],nums[nums[i]-1]) = (nums[nums[i]-1], nums[i]) } else { i += 1 } } for i in 0...nums.count-1 { if nums[i] != i+1 { return i+1 } } return nums.count + 1 } } let solution = Solution() solution.firstMissingPositive([3,4,-1,1])
mit
7d244bcdf196628fc418e6528ced30fa
22
103
0.503462
3.282468
false
false
false
false
grahamearley/YoungChefs
Source/Young Chefs/Young Chefs/WebResources/JavaSwift.swift
1
553
// // JavaSwift.swift // Young Chefs // // Julia Bindler // Graham Earley // Charlie Imhoff // import Foundation ///Constants related to the JavaSwift port and system class JavaSwiftConstants { static let commandKey = "command" } ///A enum for the easy parsing of commands sent from js using the JavaSwift port enum JSCommand : NSString { case NextScreen = "nextButton" case PreviousScreen = "backButton" case ContentReadyNotification = "contentIsReady" case BindResponseKey = "bindResponseKey" case ResetExperiment = "resetButton" }
mit
93f1b50f59b888d157b78c7857e9a1e9
20.307692
80
0.743219
3.736486
false
false
false
false
cliqz-oss/browser-ios
Client/Cliqz/Foundation/Environment/SettingsPrefs.swift
1
8343
// // SettingsPrefs.swift // Client // // Created by Sahakyan on 9/1/16. // Copyright © 2016 Mozilla. All rights reserved. // import Foundation class SettingsPrefs { static let AdBlockerPrefKey = "blockAds" static let FairBlockingPrefKey = "fairBlocking" static let BlockExplicitContentPrefKey = "blockContent" static let HumanWebPrefKey = "humanweb.toggle" static let ShowAntitrackingHintKey = "showAntitrackingHint" static let ShowCliqzSearchHintKey = "showCliqzSearchHint" static let ShowVideoDownloaderHintKey = "ShowVideoDownloaderHint" static let blockPopupsPrefKey = "blockPopups" static let countryPrefKey = "UserCountry" static let querySuggestionPrefKey = "QuerySuggestion" static let LimitMobileDataUsagePrefKey = "LimitMobileDataUsage" static let AutoForgetTabPrefKey = "AutoForgetTab" static let LogTelemetryPrefKey = "showTelemetry" static let ShowTopSitesPrefKey = "showFreshTabTopSites" static let ShowNewsPrefKey = "showFreshTabNews" static let SendCrashReports = "sendCrashReports" static let SendTelemetry = "sendTelemetry" static let SearchBackendOptions = ["DE", "US", "FR", "GB", "ES", "IT", "PL"] var profile: Profile? open static var shared = SettingsPrefs() func getAdBlockerPref() -> Bool { let defaultValue = false if let blockAdsPref = self.getBoolPref(SettingsPrefs.AdBlockerPrefKey) { return blockAdsPref } return defaultValue } func getFairBlockingPref() -> Bool { let defaultValue = true if let FairBlockingPref = self.getBoolPref(SettingsPrefs.FairBlockingPrefKey) { return FairBlockingPref } return defaultValue } func updateAdBlockerPref(_ newValue: Bool) { self.updatePref(SettingsPrefs.AdBlockerPrefKey, value: newValue as AnyObject) AdblockingModule.sharedInstance.setAdblockEnabled(newValue) } func updateFairBlockingPref(_ newValue: Bool) { self.updatePref(SettingsPrefs.FairBlockingPrefKey, value: newValue as AnyObject) } func getBlockExplicitContentPref() -> Bool { let defaultValue = true if let blockExplicitContentPref = self.getBoolPref(SettingsPrefs.BlockExplicitContentPrefKey) { return blockExplicitContentPref } return defaultValue } func getHumanWebPref() -> Bool { let defaultValue = true if let humanWebPref = self.getBoolPref(SettingsPrefs.HumanWebPrefKey) { return humanWebPref } return defaultValue } func updateHumanWebPref(_ newValue: Bool) { self.updatePref(SettingsPrefs.HumanWebPrefKey, value: newValue as AnyObject) } func updateShowAntitrackingHintPref(_ newValue: Bool) { self.updatePref(SettingsPrefs.ShowAntitrackingHintKey, value: newValue as AnyObject) } func updateShowCliqzSearchHintPref(_ newValue: Bool) { self.updatePref(SettingsPrefs.ShowCliqzSearchHintKey, value: newValue as AnyObject) } func updateShowVideoDownloaderHintPref(_ newValue: Bool) { self.updatePref(SettingsPrefs.ShowVideoDownloaderHintKey, value: newValue as AnyObject) } func getShowCliqzSearchHintPref() -> Bool { let defaultValue = true if let showCliqSearchPref = self.getBoolPref(SettingsPrefs.ShowCliqzSearchHintKey) { return showCliqSearchPref } return defaultValue } func getShowAntitrackingHintPref() -> Bool { let defaultValue = true if let showAntitrackingHintPref = self.getBoolPref(SettingsPrefs.ShowAntitrackingHintKey) { return showAntitrackingHintPref } return defaultValue } func getShowVideoDownloaderHintPref() -> Bool { let defaultValue = true if let showVideoDownloaderPref = self.getBoolPref(SettingsPrefs.ShowVideoDownloaderHintKey) { return showVideoDownloaderPref } return defaultValue } func getBlockPopupsPref() -> Bool { let defaultValue = true if let blockPopupsPref = self.getBoolPref(SettingsPrefs.blockPopupsPrefKey) { return blockPopupsPref } return defaultValue } func updateBlockPopupsPref(_ newValue: Bool) { self.updatePref(SettingsPrefs.blockPopupsPrefKey, value: newValue as AnyObject) } func getRegionPref() -> String? { return self.getStringPref(SettingsPrefs.countryPrefKey) } func getUserRegionPref() -> String { if let reg = self.getRegionPref() { return reg } return self.getDefaultRegion() } func getDefaultRegion() -> String { if let regioncode = Locale.current.regionCode { switch regioncode { case "DE", "AT", "CH": // Germany, Austria, Switzerland return "DE" case "FR": return "FR" default: return "US" } } return "US" } func updateRegionPref(_ newValue: String) { self.updatePref(SettingsPrefs.countryPrefKey, value: newValue as AnyObject) } func updateQuerySuggestionPref(_ newValue: Bool) { self.updatePref(SettingsPrefs.querySuggestionPrefKey, value: newValue as AnyObject) } func getQuerySuggestionPref() -> Bool { let defaultValue = true if let querySuggestionPref = self.getBoolPref(SettingsPrefs.querySuggestionPrefKey) { return querySuggestionPref } return defaultValue } func getLimitMobileDataUsagePref() -> Bool { let defaultValue = true if let LimitMobileDataUsagePref = SettingsPrefs.shared.getBoolPref(SettingsPrefs.LimitMobileDataUsagePrefKey) { return LimitMobileDataUsagePref } return defaultValue } func updateLimitMobileDataUsagePref(_ newValue: Bool) { self.updatePref(SettingsPrefs.LimitMobileDataUsagePrefKey, value: newValue as AnyObject) } func getAutoForgetTabPref() -> Bool { let defaultValue = true if let AutoForgetTabPref = self.getBoolPref(SettingsPrefs.AutoForgetTabPrefKey) { return AutoForgetTabPref } return defaultValue } func updateAutoForgetTabPref(_ newValue: Bool) { self.updatePref(SettingsPrefs.AutoForgetTabPrefKey, value: newValue as AnyObject) if newValue == true { BloomFilterManager.sharedInstance.turnOn() } else { BloomFilterManager.sharedInstance.turnOff() } } func getLogTelemetryPref() -> Bool { return self.getBoolPref(SettingsPrefs.LogTelemetryPrefKey) ?? false } func getShowTopSitesPref() -> Bool { return self.getBoolPref(SettingsPrefs.ShowTopSitesPrefKey) ?? true } func getShowNewsPref() -> Bool { return self.getBoolPref(SettingsPrefs.ShowNewsPrefKey) ?? true } func getSendCrashReportsPref() -> Bool { // Need to get "settings.sendCrashReports" this way so that Sentry can be initialized before getting the Profile. let defaultValue = true if let sendCrashReportsPref = LocalDataStore.objectForKey(SettingsPrefs.SendCrashReports) as? Bool { return sendCrashReportsPref } return defaultValue } func updateSendCrashReportsPref(_ newValue: Bool) { LocalDataStore.setObject(newValue, forKey: SettingsPrefs.SendCrashReports) } func getSendTelemetryPref() -> Bool { // Need to get "settings.sendCrashReports" this way so that Sentry can be initialized before getting the Profile. let defaultValue = true if let sendTelemetryPref = LocalDataStore.objectForKey(SettingsPrefs.SendTelemetry) as? Bool { return sendTelemetryPref } return defaultValue } func updateSendTelemetryPref(_ newValue: Bool) { LocalDataStore.setObject(newValue, forKey: SettingsPrefs.SendTelemetry) } // MARK: - Private helper metods fileprivate func getBoolPref(_ forKey: String) -> Bool? { if let p = self.profile { return p.prefs.boolForKey(forKey) } return nil } fileprivate func updatePref(_ forKey: String, value: AnyObject) { if let p = self.profile { p.prefs.setObject(value, forKey: forKey) } } fileprivate func getStringPref(_ forKey: String) -> String? { if let p = self.profile { return p.prefs.stringForKey(forKey) } return nil } }
mpl-2.0
a290425aa6b799c1e8ba3cd50f341a7b
30.718631
121
0.693239
4.404435
false
false
false
false
banxi1988/Staff
Pods/BXForm/Pod/Classes/Buttons/ButtonFactory.swift
1
1755
// // ButtonFactory.swift // Pods // // Created by Haizhen Lee on 15/12/23. // // import Foundation import UIKit import BXiOSUtils extension UIButton{ func setupAsRedButton(){ setBackgroundImage(UIImage.bx_image(FormColors.redColor), forState: .Normal) setBackgroundImage(FormButtons.lightGrayImage, forState: .Disabled) setTitleColor(UIColor.whiteColor(), forState: .Normal) setTitleColor(UIColor.whiteColor(), forState: .Disabled) } func setupAsAccentButton(){ setBackgroundImage(FormButtons.accentImage, forState: .Normal) setBackgroundImage(FormButtons.lightGrayImage, forState: .Disabled) setTitleColor(UIColor.whiteColor(), forState: .Normal) setTitleColor(UIColor.whiteColor(), forState: .Disabled) } func setupAsPrimaryActionButton(){ setBackgroundImage(FormButtons.primaryImage, forState: .Normal) setBackgroundImage(FormButtons.lightGrayImage, forState: .Disabled) setTitleColor(UIColor.whiteColor(), forState: .Normal) setTitleColor(UIColor.whiteColor(), forState: .Disabled) } } struct FormButtons{ static func backgroundImage(color:UIColor) -> UIImage{ let cornerRadius = FormMetrics.cornerRadius let size = CGSize(width: 64, height: 64) let image = UIImage.bx_roundImage(color, size: size, cornerRadius: cornerRadius) let buttonImage = image.resizableImageWithCapInsets(UIEdgeInsets(top: cornerRadius, left: cornerRadius, bottom: cornerRadius, right: cornerRadius)) return buttonImage } static let accentImage = FormButtons.backgroundImage(FormColors.accentColor) static let primaryImage = FormButtons.backgroundImage(FormColors.accentColor) static let lightGrayImage = FormButtons.backgroundImage(FormColors.lightGrayColor) }
mit
1e46effb33e86790c8978ee33e803f89
32.769231
151
0.764672
4.558442
false
false
false
false
taketo1024/SwiftyAlgebra
Sources/SwmCore/Numbers/IntegerQuotient.swift
1
1311
// // IntegerQuotient.swift // SwiftyMath // // Created by Taketo Sano on 2018/04/01. // Copyright © 2018年 Taketo Sano. All rights reserved. // public typealias 𝐙₂ = IntegerQuotientRing<_2> // add more if necessary public struct IntegerIdeal<n: FixedSizeType>: EuclideanIdeal { public typealias Super = 𝐙 public static var generator: 𝐙 { n.intValue } } extension IntegerIdeal: MaximalIdeal where n: PrimeSizeType {} public struct IntegerQuotientRing<n: FixedSizeType>: EuclideanQuotientRing, FiniteSet, Randomable, Hashable, ExpressibleByIntegerLiteral { public typealias Base = 𝐙 public typealias Mod = IntegerIdeal<n> public let representative: 𝐙 public init(_ a: 𝐙) { self.representative = Self.reduce(a) } public static func reduce(_ a: Int) -> Int { (a >= 0) ? a % mod : (a % mod + mod) } public static var allElements: [Self] { (0 ..< mod).map{ .init($0) } } public static var countElements: Int { mod } public static var symbol: String { "𝐙\(Format.sub(mod))" } public static func random() -> Self { .init(.random(in: 0 ..< n.intValue)) } } extension IntegerQuotientRing: EuclideanRing, Field where n: PrimeSizeType {}
cc0-1.0
9bbc40c2d6e6438819a963f04190b68f
24.196078
138
0.638911
3.768328
false
false
false
false
macemmi/HBCI4Swift
HBCI4Swift/HBCI4Swift/Source/Sepa/HBCISepaGenerator.swift
1
3510
// // HBCISepaGenerator.swift // HBCISepaGenerator // // Created by Frank Emminghaus on 21.02.15. // Copyright (c) 2015 Frank Emminghaus. All rights reserved. // import Foundation enum SepaOrderType: String { case Credit = "001", Debit = "008" } class HBCISepaGenerator { let document:XMLDocument; let root:XMLElement; let numberFormatter = NumberFormatter(); let format:HBCISepaFormat; var schemaLocationAttrNode:XMLNode! init(format:HBCISepaFormat) { // set format self.format = format; // create document self.root = XMLElement(name: "Document"); self.document = XMLDocument(rootElement: self.root); self.document.version = "1.0"; self.document.characterEncoding = "UTF-8"; // set namespace self.setNamespace(); // init formatters initFormatters(); } var sepaFormat:HBCISepaFormat { get { return format; } } fileprivate func initFormatters() { numberFormatter.decimalSeparator = "."; numberFormatter.alwaysShowsDecimalSeparator = true; numberFormatter.minimumFractionDigits = 2; numberFormatter.maximumFractionDigits = 2; numberFormatter.generatesDecimalNumbers = true; } func numberToString(_ number:NSDecimalNumber) ->String? { return numberFormatter.string(from: number); } func defaultMessageId() ->String { let formatter = DateFormatter(); formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSS"; return formatter.string(from: Date()); } func setNamespace() { var namespace = XMLNode(kind: XMLNode.Kind.namespace); namespace.stringValue = format.urn; namespace.name = ""; root.addNamespace(namespace); namespace = XMLNode(kind: XMLNode.Kind.namespace); namespace.stringValue = "http://www.w3.org/2001/XMLSchema-instance"; namespace.name = "xsi"; root.addNamespace(namespace); schemaLocationAttrNode = XMLNode(kind: XMLNode.Kind.attribute); schemaLocationAttrNode.name = "xsi:schemaLocation" schemaLocationAttrNode.stringValue = format.schemaLocation; root.addAttribute(schemaLocationAttrNode); } func validate() ->Bool { // set local schema validation path let oldLocation = schemaLocationAttrNode.stringValue; schemaLocationAttrNode.stringValue = self.format.validationSchemaLocation; do { try document.validate(); } catch let error as NSError { logInfo("SEPA document error: " + error.description); logInfo("Schema validation location: " + (schemaLocationAttrNode.stringValue ?? "<none>")); logInfo("Schema validation location old: " + (oldLocation ?? "none")); schemaLocationAttrNode.stringValue = oldLocation; return false; } schemaLocationAttrNode.stringValue = oldLocation; return true; } func sepaISODateString() ->String { let formatter = DateFormatter(); formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssXXX"; return formatter.string(from: Date()); } func sepaDateString(_ date:Date) ->String { let formatter = DateFormatter(); formatter.dateFormat = "yyyy-MM-dd"; return formatter.string(from: date); } }
gpl-2.0
8746c957839074170316cfec6120a7da
29.789474
103
0.621083
4.736842
false
false
false
false
opalorange/OpalImagePicker
OpalImagePicker/Source/OpalImagePickerRootViewController.swift
1
22584
// // OpalImagePickerRootViewController.swift // OpalImagePicker // // Created by Kristos Katsanevas on 1/16/17. // Copyright © 2017 Opal Orange LLC. All rights reserved. // import UIKit import Photos /// Image Picker Root View Controller contains the logic for selecting images. The images are displayed in a `UICollectionView`, and multiple images can be selected. open class OpalImagePickerRootViewController: UIViewController { /// Delegate for Image Picker. Notifies when images are selected (done is tapped) or when the Image Picker is cancelled. open weak var delegate: OpalImagePickerControllerDelegate? /// Configuration to change Localized Strings open var configuration: OpalImagePickerConfiguration? { didSet { configuration?.updateStrings = configurationChanged if let configuration = self.configuration { configurationChanged(configuration) } } } /// `UICollectionView` for displaying photo library images open weak var collectionView: UICollectionView? /// `UICollectionView` for displaying external images open weak var externalCollectionView: UICollectionView? /// `UIToolbar` to switch between Photo Library and External Images. open lazy var toolbar: UIToolbar = { let toolbar = UIToolbar() toolbar.translatesAutoresizingMaskIntoConstraints = false return toolbar }() /// `UISegmentedControl` to switch between Photo Library and External Images. open lazy var tabSegmentedControl: UISegmentedControl = { let tabSegmentedControl = UISegmentedControl(items: [NSLocalizedString("Library", comment: "Library"), NSLocalizedString("External", comment: "External")]) tabSegmentedControl.addTarget(self, action: #selector(segmentTapped(_:)), for: .valueChanged) tabSegmentedControl.selectedSegmentIndex = 0 return tabSegmentedControl }() /// Custom Tint Color for overlay of selected images. open var selectionTintColor: UIColor? { didSet { collectionView?.reloadData() } } /// Custom Tint Color for selection image (checkmark). open var selectionImageTintColor: UIColor? { didSet { collectionView?.reloadData() } } /// Custom selection image (checkmark). open var selectionImage: UIImage? { didSet { collectionView?.reloadData() } } /// Allowed Media Types that can be fetched. See `PHAssetMediaType` open var allowedMediaTypes: Set<PHAssetMediaType>? { didSet { updateFetchOptionPredicate() } } /// Allowed MediaSubtype that can be fetched. Can be applied as `OptionSet`. See `PHAssetMediaSubtype` open var allowedMediaSubtypes: PHAssetMediaSubtype? { didSet { updateFetchOptionPredicate() } } /// Maximum photo selections allowed in picker (zero or fewer means unlimited). open var maximumSelectionsAllowed: Int = -1 /// Page size for paging through the Photo Assets in the Photo Library. Defaults to 100. Must override to change this value. Only works in iOS 9.0+ public let pageSize = 100 var photoAssets: PHFetchResult<PHAsset> = PHFetchResult() weak var doneButton: UIBarButtonItem? weak var cancelButton: UIBarButtonItem? internal var collectionViewLayout: OpalImagePickerCollectionViewLayout? { return collectionView?.collectionViewLayout as? OpalImagePickerCollectionViewLayout } internal lazy var fetchOptions: PHFetchOptions = { let fetchOptions = PHFetchOptions() fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)] return fetchOptions }() @available(iOS 9.0, *) internal var fetchLimit: Int { get { return fetchOptions.fetchLimit } set { fetchOptions.fetchLimit = newValue } } internal var shouldShowTabs: Bool { guard let imagePicker = navigationController as? OpalImagePickerController else { return false } return delegate?.imagePickerNumberOfExternalItems?(imagePicker) != nil } private var isCompleted = false private var photosCompleted = 0 private var savedImages: [UIImage] = [] private var showExternalImages = false private var selectedIndexPaths: [IndexPath] = [] private var externalSelectedIndexPaths: [IndexPath] = [] private lazy var cache: NSCache<NSIndexPath, NSData> = { let cache = NSCache<NSIndexPath, NSData>() cache.totalCostLimit = 128000000 //128 MB cache.countLimit = 100 // 100 images return cache }() private weak var rightExternalCollectionViewConstraint: NSLayoutConstraint? /// Initializer public required init() { super.init(nibName: nil, bundle: nil) } /// Initializer (Do not use this View Controller in Interface Builder) public required init?(coder aDecoder: NSCoder) { fatalError("Cannot init \(String(describing: OpalImagePickerRootViewController.self)) from Interface Builder") } private func setup() { guard let view = view else { return } fetchPhotos() let collectionView = UICollectionView(frame: view.frame, collectionViewLayout: OpalImagePickerCollectionViewLayout()) setup(collectionView: collectionView) view.addSubview(collectionView) self.collectionView = collectionView var constraints: [NSLayoutConstraint] = [] if shouldShowTabs { setupTabs() let externalCollectionView = UICollectionView(frame: view.frame, collectionViewLayout: OpalImagePickerCollectionViewLayout()) setup(collectionView: externalCollectionView) view.addSubview(externalCollectionView) self.externalCollectionView = externalCollectionView constraints += [externalCollectionView.constraintEqualTo(with: collectionView, attribute: .top)] constraints += [externalCollectionView.constraintEqualTo(with: collectionView, attribute: .bottom)] constraints += [externalCollectionView.constraintEqualTo(with: collectionView, receiverAttribute: .left, otherAttribute: .right)] constraints += [collectionView.constraintEqualTo(with: view, attribute: .width)] constraints += [externalCollectionView.constraintEqualTo(with: view, attribute: .width)] constraints += [toolbar.constraintEqualTo(with: collectionView, receiverAttribute: .bottom, otherAttribute: .top)] } else { constraints += [view.constraintEqualTo(with: collectionView, attribute: .top)] constraints += [view.constraintEqualTo(with: collectionView, attribute: .right)] } //Lower priority to override left constraint for animations let leftCollectionViewConstraint = view.constraintEqualTo(with: collectionView, attribute: .left) leftCollectionViewConstraint.priority = UILayoutPriority(rawValue: 999) constraints += [leftCollectionViewConstraint] constraints += [view.constraintEqualTo(with: collectionView, attribute: .bottom)] NSLayoutConstraint.activate(constraints) view.layoutIfNeeded() } private func setup(collectionView: UICollectionView) { collectionView.translatesAutoresizingMaskIntoConstraints = false collectionView.allowsMultipleSelection = true if #available(iOS 13.0, *) { collectionView.backgroundColor = .systemBackground } else { collectionView.backgroundColor = .white } collectionView.dataSource = self collectionView.delegate = self collectionView.register(ImagePickerCollectionViewCell.self, forCellWithReuseIdentifier: ImagePickerCollectionViewCell.reuseId) } private func setupTabs() { guard let view = view else { return } edgesForExtendedLayout = UIRectEdge() navigationController?.navigationBar.isTranslucent = false toolbar.isTranslucent = false view.addSubview(toolbar) let flexItem1 = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) let flexItem2 = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) let barButtonItem = UIBarButtonItem(customView: tabSegmentedControl) toolbar.setItems([flexItem1, barButtonItem, flexItem2], animated: false) if let imagePicker = navigationController as? OpalImagePickerController, let title = delegate?.imagePickerTitleForExternalItems?(imagePicker) { tabSegmentedControl.setTitle(title, forSegmentAt: 1) } NSLayoutConstraint.activate([ toolbar.constraintEqualTo(with: topLayoutGuide, receiverAttribute: .top, otherAttribute: .bottom), toolbar.constraintEqualTo(with: view, attribute: .left), toolbar.constraintEqualTo(with: view, attribute: .right) ]) } private func fetchPhotos() { requestPhotoAccessIfNeeded(PHPhotoLibrary.authorizationStatus()) if #available(iOS 9.0, *) { fetchOptions.fetchLimit = pageSize } photoAssets = PHAsset.fetchAssets(with: fetchOptions) collectionView?.reloadData() } private func updateFetchOptionPredicate() { var predicates: [NSPredicate] = [] if let allowedMediaTypes = self.allowedMediaTypes { let mediaTypesPredicates = allowedMediaTypes.map { NSPredicate(format: "mediaType = %d", $0.rawValue) } let allowedMediaTypesPredicate = NSCompoundPredicate(orPredicateWithSubpredicates: mediaTypesPredicates) predicates += [allowedMediaTypesPredicate] } if let allowedMediaSubtypes = self.allowedMediaSubtypes { let mediaSubtypes = NSPredicate(format: "(mediaSubtype & %d) == 0", allowedMediaSubtypes.rawValue) predicates += [mediaSubtypes] } if predicates.count > 0 { let predicate = NSCompoundPredicate(andPredicateWithSubpredicates: predicates) fetchOptions.predicate = predicate } else { fetchOptions.predicate = nil } fetchPhotos() } /// Load View open override func loadView() { view = UIView() } open override func viewDidLoad() { super.viewDidLoad() setup() navigationItem.title = configuration?.navigationTitle ?? NSLocalizedString("Photos", comment: "") let cancelButtonTitle = configuration?.cancelButtonTitle ?? NSLocalizedString("Cancel", comment: "") let cancelButton = UIBarButtonItem(title: cancelButtonTitle, style: .plain, target: self, action: #selector(cancelTapped)) navigationItem.leftBarButtonItem = cancelButton self.cancelButton = cancelButton let doneButtonTitle = configuration?.doneButtonTitle ?? NSLocalizedString("Done", comment: "") let doneButton = UIBarButtonItem(title: doneButtonTitle, style: .done, target: self, action: #selector(doneTapped)) navigationItem.rightBarButtonItem = doneButton self.doneButton = doneButton } open override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) isCompleted = false } @objc func cancelTapped() { dismiss(animated: true) { [weak self] in guard let imagePicker = self?.navigationController as? OpalImagePickerController else { return } self?.delegate?.imagePickerDidCancel?(imagePicker) } } @objc func doneTapped() { guard let imagePicker = navigationController as? OpalImagePickerController, !isCompleted else { return } let indexPathsForSelectedItems = selectedIndexPaths let externalIndexPaths = externalSelectedIndexPaths guard indexPathsForSelectedItems.count + externalIndexPaths.count > 0 else { cancelTapped() return } var photoAssets: [PHAsset] = [] for indexPath in indexPathsForSelectedItems { guard indexPath.item < self.photoAssets.count else { continue } photoAssets += [self.photoAssets.object(at: indexPath.item)] } delegate?.imagePicker?(imagePicker, didFinishPickingAssets: photoAssets) var selectedURLs: [URL] = [] for indexPath in externalIndexPaths { guard let url = delegate?.imagePicker?(imagePicker, imageURLforExternalItemAtIndex: indexPath.item) else { continue } selectedURLs += [url] } delegate?.imagePicker?(imagePicker, didFinishPickingExternalURLs: selectedURLs) } private func set(image: UIImage?, indexPath: IndexPath, isExternal: Bool) { update(isSelected: image != nil, isExternal: isExternal, for: indexPath) } private func update(isSelected: Bool, isExternal: Bool, for indexPath: IndexPath) { if isSelected && isExternal { externalSelectedIndexPaths += [indexPath] } else if !isSelected && isExternal { externalSelectedIndexPaths = externalSelectedIndexPaths.filter { $0 != indexPath } } else if isSelected && !isExternal { selectedIndexPaths += [indexPath] } else { selectedIndexPaths = selectedIndexPaths.filter { $0 != indexPath } } } @available(iOS 9.0, *) private func fetchNextPageIfNeeded(indexPath: IndexPath) { guard indexPath.item == fetchLimit-1 else { return } let oldFetchLimit = fetchLimit fetchLimit += pageSize photoAssets = PHAsset.fetchAssets(with: fetchOptions) var indexPaths: [IndexPath] = [] for item in oldFetchLimit..<photoAssets.count { indexPaths += [IndexPath(item: item, section: 0)] } collectionView?.insertItems(at: indexPaths) } private func requestPhotoAccessIfNeeded(_ status: PHAuthorizationStatus) { guard status == .notDetermined else { return } PHPhotoLibrary.requestAuthorization { [weak self] (_) in DispatchQueue.main.async { [weak self] in self?.photoAssets = PHAsset.fetchAssets(with: self?.fetchOptions) self?.collectionView?.reloadData() } } } @objc private func segmentTapped(_ sender: UISegmentedControl) { guard let view = view else { return } showExternalImages = sender.selectedSegmentIndex == 1 //Instantiate right constraint if needed if rightExternalCollectionViewConstraint == nil { let rightConstraint = externalCollectionView?.constraintEqualTo(with: view, attribute: .right) rightExternalCollectionViewConstraint = rightConstraint } rightExternalCollectionViewConstraint?.isActive = showExternalImages UIView.animate(withDuration: 0.2, animations: { [weak self] in sender.isUserInteractionEnabled = false self?.view.layoutIfNeeded() }, completion: { _ in sender.isUserInteractionEnabled = true }) } private func configurationChanged(_ configuration: OpalImagePickerConfiguration) { if let navigationTitle = configuration.navigationTitle { navigationItem.title = navigationTitle } if let librarySegmentTitle = configuration.librarySegmentTitle { tabSegmentedControl.setTitle(librarySegmentTitle, forSegmentAt: 0) } } } // MARK: - Collection View Delegate extension OpalImagePickerRootViewController: UICollectionViewDelegate { /// Collection View did select item at `IndexPath` /// /// - Parameters: /// - collectionView: the `UICollectionView` /// - indexPath: the `IndexPath` public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { guard let cell = collectionView.cellForItem(at: indexPath) as? ImagePickerCollectionViewCell, let image = cell.imageView.image else { return } set(image: image, indexPath: indexPath, isExternal: collectionView == self.externalCollectionView) } /// Collection View did de-select item at `IndexPath` /// /// - Parameters: /// - collectionView: the `UICollectionView` /// - indexPath: the `IndexPath` public func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) { set(image: nil, indexPath: indexPath, isExternal: collectionView == self.externalCollectionView) } public func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool { guard let cell = collectionView.cellForItem(at: indexPath) as? ImagePickerCollectionViewCell, cell.imageView.image != nil else { return false } guard maximumSelectionsAllowed > 0 else { return true } let collectionViewItems = self.collectionView?.indexPathsForSelectedItems?.count ?? 0 let externalCollectionViewItems = self.externalCollectionView?.indexPathsForSelectedItems?.count ?? 0 if maximumSelectionsAllowed <= collectionViewItems + externalCollectionViewItems { //We exceeded maximum allowed, so alert user. Don't allow selection let message = configuration?.maximumSelectionsAllowedMessage ?? NSLocalizedString("You cannot select more than \(maximumSelectionsAllowed) images. Please deselect another image before trying to select again.", comment: "You cannot select more than (x) images. Please deselect another image before trying to select again. (OpalImagePicker)") let alert = UIAlertController(title: "", message: message, preferredStyle: .alert) let okayString = configuration?.okayString ?? NSLocalizedString("OK", comment: "OK") let action = UIAlertAction(title: okayString, style: .cancel, handler: nil) alert.addAction(action) present(alert, animated: true, completion: nil) return false } return true } } // MARK: - Collection View Data Source extension OpalImagePickerRootViewController: UICollectionViewDataSource { /// Returns Collection View Cell for item at `IndexPath` /// /// - Parameters: /// - collectionView: the `UICollectionView` /// - indexPath: the `IndexPath` /// - Returns: Returns the `UICollectionViewCell` public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if collectionView == self.collectionView { return photoAssetCollectionView(collectionView, cellForItemAt: indexPath) } else { return externalCollectionView(collectionView, cellForItemAt: indexPath) } } private func photoAssetCollectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { if #available(iOS 9.0, *) { fetchNextPageIfNeeded(indexPath: indexPath) } guard let layoutAttributes = collectionView.collectionViewLayout.layoutAttributesForItem(at: indexPath), let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ImagePickerCollectionViewCell.reuseId, for: indexPath) as? ImagePickerCollectionViewCell else { return UICollectionViewCell() } let photoAsset = photoAssets.object(at: indexPath.item) cell.indexPath = indexPath cell.photoAsset = photoAsset cell.size = layoutAttributes.frame.size if let selectionTintColor = self.selectionTintColor { cell.selectionTintColor = selectionTintColor } if let selectionImageTintColor = self.selectionImageTintColor { cell.selectionImageTintColor = selectionImageTintColor } if let selectionImage = self.selectionImage { cell.selectionImage = selectionImage } return cell } private func externalCollectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard let imagePicker = navigationController as? OpalImagePickerController, let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ImagePickerCollectionViewCell.reuseId, for: indexPath) as? ImagePickerCollectionViewCell else { return UICollectionViewCell() } if let url = delegate?.imagePicker?(imagePicker, imageURLforExternalItemAtIndex: indexPath.item) { cell.cache = cache cell.url = url cell.indexPath = indexPath } else { assertionFailure("You need to implement `imagePicker(_:imageURLForExternalItemAtIndex:)` in your delegate.") } if let selectionTintColor = self.selectionTintColor { cell.selectionTintColor = selectionTintColor } if let selectionImageTintColor = self.selectionImageTintColor { cell.selectionImageTintColor = selectionImageTintColor } if let selectionImage = self.selectionImage { cell.selectionImage = selectionImage } return cell } /// Returns the number of items in a given section /// /// - Parameters: /// - collectionView: the `UICollectionView` /// - section: the given section of the `UICollectionView` /// - Returns: Returns an `Int` for the number of rows. public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if collectionView == self.collectionView { return photoAssets.count } else if let imagePicker = navigationController as? OpalImagePickerController, let numberOfItems = delegate?.imagePickerNumberOfExternalItems?(imagePicker) { return numberOfItems } else { assertionFailure("You need to implement `imagePickerNumberOfExternalItems(_:)` in your delegate.") return 0 } } }
mit
46ddc476512f024745dc2496f4520d48
42.765504
352
0.671169
5.873342
false
false
false
false
thierrybucco/Eureka
Source/Rows/ActionSheetRow.swift
7
3923
// ActionSheetRow.swift // Eureka ( https://github.com/xmartlabs/Eureka ) // // Copyright (c) 2016 Xmartlabs SRL ( http://xmartlabs.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 Foundation open class AlertSelectorCell<T: Equatable> : Cell<T>, CellType { required public init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } open override func update() { super.update() accessoryType = .none editingAccessoryType = accessoryType selectionStyle = row.isDisabled ? .none : .default } open override func didSelect() { super.didSelect() row.deselect() } } public class _ActionSheetRow<Cell: CellType>: OptionsRow<Cell>, PresenterRowType where Cell: BaseCell { public var onPresentCallback: ((FormViewController, SelectorAlertController<Cell.Value>) -> Void)? lazy public var presentationMode: PresentationMode<SelectorAlertController<Cell.Value>>? = { return .presentModally(controllerProvider: ControllerProvider.callback { [weak self] in let vc = SelectorAlertController<Cell.Value>(title: self?.selectorTitle, message: nil, preferredStyle: .actionSheet) if let popView = vc.popoverPresentationController { guard let cell = self?.cell, let tableView = cell.formViewController()?.tableView else { fatalError() } popView.sourceView = tableView popView.sourceRect = tableView.convert(cell.detailTextLabel?.frame ?? cell.textLabel?.frame ?? cell.contentView.frame, from: cell) } vc.row = self return vc }, onDismiss: { [weak self] in $0.dismiss(animated: true) self?.cell?.formViewController()?.tableView?.reloadData() }) }() public required init(tag: String?) { super.init(tag: tag) } public override func customDidSelect() { super.customDidSelect() if let presentationMode = presentationMode, !isDisabled { if let controller = presentationMode.makeController() { controller.row = self onPresentCallback?(cell.formViewController()!, controller) presentationMode.present(controller, row: self, presentingController: cell.formViewController()!) } else { presentationMode.present(nil, row: self, presentingController: cell.formViewController()!) } } } } /// An options row where the user can select an option from an ActionSheet public final class ActionSheetRow<T: Equatable>: _ActionSheetRow<AlertSelectorCell<T>>, RowType { required public init(tag: String?) { super.init(tag: tag) } }
mit
9ecdd6e8e04deb4c391331ed5604b86b
41.182796
146
0.683915
4.953283
false
false
false
false
tuannme/Up
Up+/Pods/NVActivityIndicatorView/NVActivityIndicatorView/Animations/NVActivityIndicatorAnimationBallClipRotateMultiple.swift
2
4156
// // NVActivityIndicatorAnimationBallClipRotateMultiple.swift // NVActivityIndicatorViewDemo // // The MIT License (MIT) // Copyright (c) 2016 Vinh Nguyen // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import UIKit class NVActivityIndicatorAnimationBallClipRotateMultiple: NVActivityIndicatorAnimationDelegate { func setUpAnimation(in layer: CALayer, size: CGSize, color: UIColor) { let bigCircleSize: CGFloat = size.width let smallCircleSize: CGFloat = size.width / 2 let longDuration: CFTimeInterval = 1 let timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) circleOf(shape: .ringTwoHalfHorizontal, duration: longDuration, timingFunction: timingFunction, layer: layer, size: bigCircleSize, color: color, reverse: false) circleOf(shape: .ringTwoHalfVertical, duration: longDuration, timingFunction: timingFunction, layer: layer, size: smallCircleSize, color: color, reverse: true) } func createAnimationIn(duration: CFTimeInterval, timingFunction: CAMediaTimingFunction, reverse: Bool) -> CAAnimation { // Scale animation let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale") scaleAnimation.keyTimes = [0, 0.5, 1] scaleAnimation.timingFunctions = [timingFunction, timingFunction] scaleAnimation.values = [1, 0.6, 1] scaleAnimation.duration = duration // Rotate animation let rotateAnimation = CAKeyframeAnimation(keyPath:"transform.rotation.z") rotateAnimation.keyTimes = scaleAnimation.keyTimes rotateAnimation.timingFunctions = [timingFunction, timingFunction] if (!reverse) { rotateAnimation.values = [0, M_PI, 2 * M_PI] } else { rotateAnimation.values = [0, -M_PI, -2 * M_PI] } rotateAnimation.duration = duration // Animation let animation = CAAnimationGroup() animation.animations = [scaleAnimation, rotateAnimation] animation.duration = duration animation.repeatCount = HUGE animation.isRemovedOnCompletion = false return animation } func circleOf(shape: NVActivityIndicatorShape, duration: CFTimeInterval, timingFunction: CAMediaTimingFunction, layer: CALayer, size: CGFloat, color: UIColor, reverse: Bool) { let circle = shape.layerWith(size: CGSize(width: size, height: size), color: color) let frame = CGRect(x: (layer.bounds.size.width - size) / 2, y: (layer.bounds.size.height - size) / 2, width: size, height: size) let animation = createAnimationIn(duration: duration, timingFunction: timingFunction, reverse: reverse) circle.frame = frame circle.add(animation, forKey: "animation") layer.addSublayer(circle) } }
mit
b1194220723209991eaf28b63a5ffec2
42.291667
179
0.664822
5.240858
false
false
false
false
colemancda/MySQLSwift
Sources/MySQL/Row.swift
3
1133
// // Row.swift // MySQL // // Created by Alsey Coleman Miller on 12/4/15. // Copyright © 2015 ColemanCDA. All rights reserved. // import SwiftFoundation import CMySQL public extension MySQL { public struct Row { // MARK: - Properties public let values: [Data] // MARK: - Initialization /// Extracts values from pointer. internal init(internalPointer: MYSQL_ROW, fieldCount: Int, fieldLengths: [UInt]) { assert(fieldCount == fieldLengths.count) let lastFieldIndex = fieldCount - 1 var values = [Data]() for i in 0...lastFieldIndex { let fieldValuePointer = internalPointer[i] let length = fieldLengths[i] let data = Data.fromBytePointer(fieldValuePointer, length: Int(length)) values.append(data) } // set values self.values = values } } }
mit
02a4c331fc7f85d5ca309a58ec13ab94
23.106383
90
0.483216
5.339623
false
false
false
false
auth0/Lock.iOS-OSX
LockTests/Interactors/DatabasePasswordInteractorSpec.swift
1
5836
// DatabasePasswordInteractorSpec.swift // // Copyright (c) 2016 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 Quick import Nimble import OHHTTPStubs import Auth0 @testable import Lock class DatabasePasswordInteractorSpec: QuickSpec { override func spec() { let authentication = Auth0.authentication(clientId: clientId, domain: domain) afterEach { Auth0Stubs.cleanAll() Auth0Stubs.failUnknown() } describe("init") { let database = DatabasePasswordInteractor(connections: OfflineConnections(), authentication: authentication, user: User(), dispatcher: ObserverStore()) it("should build with authentication") { expect(database).toNot(beNil()) } it("should have authentication object") { expect(database.authentication.clientId) == "CLIENT_ID" expect(database.authentication.url.host) == "samples.auth0.com" } } var user: User! var connections: OfflineConnections! var forgot: DatabasePasswordInteractor! var dispatcher: Dispatcher! beforeEach { dispatcher = ObserverStore() connections = OfflineConnections() connections.database(name: connection, requiresUsername: true) user = User() forgot = DatabasePasswordInteractor(connections: connections, authentication: authentication, user: user, dispatcher: dispatcher) } describe("updateEmail") { it("should update email") { expect{ try forgot.updateEmail(email) }.toNot(throwError()) expect(forgot.email) == email } it("should trim email") { expect{ try forgot.updateEmail(" \(email) ") }.toNot(throwError()) expect(forgot.email) == email } describe("email validation") { it("should always store value") { let _ = try? forgot.updateEmail("not an email") expect(forgot.email) == "not an email" } it("should raise error if email is invalid") { expect{ try forgot.updateEmail("not an email") }.to(throwError(InputValidationError.notAnEmailAddress)) } it("should raise error if email is empty") { expect{ try forgot.updateEmail("") }.to(throwError(InputValidationError.mustNotBeEmpty)) } it("should raise error if email is only spaces") { expect{ try forgot.updateEmail(" ") }.to(throwError(InputValidationError.mustNotBeEmpty)) } it("should raise error if email is nil") { expect{ try forgot.updateEmail(nil) }.to(throwError(InputValidationError.mustNotBeEmpty)) } } } describe("request email") { it("should fail if no db connection is found") { forgot = DatabasePasswordInteractor(connections: OfflineConnections(), authentication: authentication, user: user, dispatcher: dispatcher) try! forgot.updateEmail(email) waitUntil(timeout: 2) { done in forgot.requestEmail { error in expect(error) == .noDatabaseConnection done() } } } it("should yield no error on success") { stub(condition: databaseForgotPassword(email: email, connection: connection)) { _ in return Auth0Stubs.forgotEmailSent() } try! forgot.updateEmail(email) waitUntil(timeout: 2) { done in forgot.requestEmail { error in expect(error).to(beNil()) done() } } } it("should yield error on failure") { stub(condition: databaseForgotPassword(email: email, connection: connection)) { _ in return Auth0Stubs.failure() } try! forgot.updateEmail(email) waitUntil(timeout: 2) { done in forgot.requestEmail { error in expect(error) == .emailNotSent done() } } } it("should yield error when input is not valid") { waitUntil(timeout: 2) { done in forgot.requestEmail { error in expect(error) == .nonValidInput done() } } } } } }
mit
2e3e058f4b6ba1c53aa1a65a7d7bac1a
37.906667
163
0.574366
5.238779
false
false
false
false
Sajjon/SwiftIntro
Pods/Swinject/Sources/ResolutionPool.swift
1
1395
// // ResolutionPool.swift // Swinject // // Created by Yoichi Tagaya on 7/28/15. // Copyright (c) 2015 Swinject Contributors. All rights reserved. // import Foundation internal struct ResolutionPool { fileprivate static let maxDepth = 200 fileprivate var pool = [ServiceKey: Any]() fileprivate var depth: Int = 0 fileprivate var pendingCompletions: [()->()] = [] internal subscript(key: ServiceKey) -> Any? { get { return pool[key] } set { pool[key] = newValue } } internal mutating func incrementDepth() { guard depth < ResolutionPool.maxDepth else { fatalError("Infinite recursive call for circular dependency has been detected. " + "To avoid the infinite call, 'initCompleted' handler should be used to inject circular dependency.") } depth += 1 } internal mutating func decrementDepth() { assert(depth > 0, "The depth cannot be negative.") if depth == 1 { while let pendingCompletion = pendingCompletions.popLast() { pendingCompletion() // Must be invoked decrementing depth counter. } pool = [:] } depth -= 1 } internal mutating func appendPendingCompletion(_ completion: @escaping ()->()) { pendingCompletions.append(completion) } }
gpl-3.0
50194275c506a05c1fc85e5642157823
29.326087
123
0.605018
4.964413
false
false
false
false
touchopia/HackingWithSwift
project5/Project5/ViewController.swift
1
3273
// // ViewController.swift // Project5 // // Created by TwoStraws on 14/08/2016. // Copyright © 2016 Paul Hudson. All rights reserved. // import GameplayKit import UIKit class ViewController: UITableViewController { var allWords = [String]() var usedWords = [String]() override func viewDidLoad() { super.viewDidLoad() navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(promptForAnswer)) if let startWordsPath = Bundle.main.path(forResource: "start", ofType: "txt") { if let startWords = try? String(contentsOfFile: startWordsPath) { allWords = startWords.components(separatedBy: "\n") } } else { allWords = ["silkworm"] } startGame() } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return usedWords.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Word", for: indexPath) cell.textLabel?.text = usedWords[indexPath.row] return cell } func startGame() { allWords = GKRandomSource.sharedRandom().arrayByShufflingObjects(in: allWords) as! [String] title = allWords[0] usedWords.removeAll(keepingCapacity: true) tableView.reloadData() } func promptForAnswer() { let ac = UIAlertController(title: "Enter answer", message: nil, preferredStyle: .alert) ac.addTextField() let submitAction = UIAlertAction(title: "Submit", style: .default) { [unowned self, ac] action in let answer = ac.textFields![0] self.submit(answer: answer.text!) } ac.addAction(submitAction) present(ac, animated: true) } func isPossible(word: String) -> Bool { var tempWord = title!.lowercased() for letter in word.characters { if let pos = tempWord.range(of: String(letter)) { tempWord.remove(at: pos.lowerBound) } else { return false } } return true } func isOriginal(word: String) -> Bool { return !usedWords.contains(word) } func isReal(word: String) -> Bool { let checker = UITextChecker() let range = NSMakeRange(0, word.utf16.count) let misspelledRange = checker.rangeOfMisspelledWord(in: word, range: range, startingAt: 0, wrap: false, language: "en") return misspelledRange.location == NSNotFound } func submit(answer: String) { let lowerAnswer = answer.lowercased() let errorTitle: String let errorMessage: String if isPossible(word: lowerAnswer) { if isOriginal(word: lowerAnswer) { if isReal(word: lowerAnswer) { usedWords.insert(answer, at: 0) let indexPath = IndexPath(row: 0, section: 0) tableView.insertRows(at: [indexPath], with: .automatic) return } else { errorTitle = "Word not recognised" errorMessage = "You can't just make them up, you know!" } } else { errorTitle = "Word used already" errorMessage = "Be more original!" } } else { errorTitle = "Word not possible" errorMessage = "You can't spell that word from '\(title!.lowercased())'!" } let ac = UIAlertController(title: errorTitle, message: errorMessage, preferredStyle: .alert) ac.addAction(UIAlertAction(title: "OK", style: .default)) present(ac, animated: true) } }
unlicense
7424885529145a75ccc488a794cf6e26
25.819672
130
0.701406
3.611479
false
false
false
false
StevenMasini/Maskarade
Pod/Classes/Views/MaskView.swift
1
669
// // MaskView.swift // Pods // // Created by Steven Masini on 15/05/16. // // import UIKit @IBDesignable class MaskView: UIView { @IBInspectable var image: UIImage? = nil override func drawRect(rect: CGRect) { super.drawRect(rect) if let image = self.image { let maskLayer = CALayer() maskLayer.contents = image.CGImage maskLayer.frame = CGRect(origin: CGPointZero, size: rect.size) self.layer.mask = maskLayer self.layer.masksToBounds = true self.layer.backgroundColor = UIColor.blackColor().CGColor } } }
mit
1489ef306fb842709d3ee59441753114
23.777778
78
0.565022
4.344156
false
false
false
false
swizzlr/Moya
Source/Moya.swift
2
10096
import Foundation import Alamofire /// General-purpose class to store some enums and class funcs. public class Moya { /// Closure to be executed when a request has completed. public typealias Completion = (data: NSData?, statusCode: Int?, response: NSURLResponse?, error: ErrorType?) -> () /// Represents an HTTP method. public enum Method { case GET, POST, PUT, DELETE, OPTIONS, HEAD, PATCH, TRACE, CONNECT func method() -> Alamofire.Method { switch self { case .GET: return .GET case .POST: return .POST case .PUT: return .PUT case .DELETE: return .DELETE case .HEAD: return .HEAD case .OPTIONS: return .OPTIONS case PATCH: return .PATCH case TRACE: return .TRACE case .CONNECT: return .CONNECT } } } /// Choice of parameter encoding. public enum ParameterEncoding { case URL case JSON case PropertyList(NSPropertyListFormat, NSPropertyListWriteOptions) case Custom((URLRequestConvertible, [String: AnyObject]?) -> (NSMutableURLRequest, NSError?)) func parameterEncoding() -> Alamofire.ParameterEncoding { switch self { case .URL: return .URL case .JSON: return .JSON case .PropertyList(let format, let options): return .PropertyList(format, options) case .Custom(let closure): return .Custom(closure) } } } public enum StubBehavior { case Never case Immediate case Delayed(seconds: NSTimeInterval) } } /// Protocol to define the base URL, path, method, parameters and sample data for a target. public protocol MoyaTarget { var baseURL: NSURL { get } var path: String { get } var method: Moya.Method { get } var parameters: [String: AnyObject]? { get } var sampleData: NSData { get } } /// Protocol to define the opaque type returned from a request public protocol Cancellable { func cancel() } /// Request provider class. Requests should be made through this class only. public class MoyaProvider<Target: MoyaTarget> { /// Closure that defines the endpoints for the provider. public typealias EndpointClosure = Target -> Endpoint<Target> /// Closure that resolves an Endpoint into an NSURLRequest. public typealias RequestClosure = (Endpoint<Target>, NSURLRequest -> Void) -> Void /// Closure that decides if/how a request should be stubbed. public typealias StubClosure = Target -> Moya.StubBehavior public let endpointClosure: EndpointClosure public let requestClosure: RequestClosure public let stubClosure: StubClosure public let manager: Manager /// A list of plugins /// e.g. for logging, network activity indicator or credentials public let plugins: [Plugin<Target>] /// Initializes a provider. public init(endpointClosure: EndpointClosure = MoyaProvider.DefaultEndpointMapping, requestClosure: RequestClosure = MoyaProvider.DefaultRequestMapping, stubClosure: StubClosure = MoyaProvider.NeverStub, manager: Manager = Alamofire.Manager.sharedInstance, plugins: [Plugin<Target>] = []) { self.endpointClosure = endpointClosure self.requestClosure = requestClosure self.stubClosure = stubClosure self.manager = manager self.plugins = plugins } /// Returns an Endpoint based on the token, method, and parameters by invoking the endpointsClosure. public func endpoint(token: Target) -> Endpoint<Target> { return endpointClosure(token) } /// Designated request-making method. Returns a Cancellable token to cancel the request later. public func request(target: Target, completion: Moya.Completion) -> Cancellable { let endpoint = self.endpoint(target) let stubBehavior = self.stubClosure(target) var cancellableToken = CancellableWrapper() let performNetworking = { (request: NSURLRequest) in if cancellableToken.isCancelled { return } switch stubBehavior { case .Never: cancellableToken.innerCancellable = self.sendRequest(target, request: request, completion: completion) default: cancellableToken.innerCancellable = self.stubRequest(target, request: request, completion: completion, endpoint: endpoint, stubBehavior: stubBehavior) } } requestClosure(endpoint, performNetworking) return cancellableToken } } /// Mark: Defaults public extension MoyaProvider { // These functions are default mappings to endpoings and requests. public final class func DefaultEndpointMapping(target: Target) -> Endpoint<Target> { let url = target.baseURL.URLByAppendingPathComponent(target.path).absoluteString return Endpoint(URL: url, sampleResponseClosure: {.NetworkResponse(200, target.sampleData)}, method: target.method, parameters: target.parameters) } public final class func DefaultRequestMapping(endpoint: Endpoint<Target>, closure: NSURLRequest -> Void) { return closure(endpoint.urlRequest) } } /// Mark: Stubbing public extension MoyaProvider { // Swift won't let us put the StubBehavior enum inside the provider class, so we'll // at least add some class functions to allow easy access to common stubbing closures. public final class func NeverStub(_: Target) -> Moya.StubBehavior { return .Never } public final class func ImmediatelyStub(_: Target) -> Moya.StubBehavior { return .Immediate } public final class func DelayedStub(seconds: NSTimeInterval)(_: Target) -> Moya.StubBehavior { return .Delayed(seconds: seconds) } } private extension MoyaProvider { func sendRequest(target: Target, request: NSURLRequest, completion: Moya.Completion) -> CancellableToken { let request = manager.request(request) let plugins = self.plugins // Give plugins the chance to alter the outgoing request plugins.forEach { $0.willSendRequest(request, provider: self, target: target) } // Perform the actual request let alamoRequest = request.response { (_, response: NSHTTPURLResponse?, data: NSData?, error: NSError?) -> () in let statusCode = response?.statusCode // Inform all plugins about the response plugins.forEach { $0.didReceiveResponse(data, statusCode: statusCode, response: response, error: error, provider: self, target: target) } completion(data: data, statusCode: statusCode, response: response, error: error) } return CancellableToken(request: alamoRequest) } func stubRequest(target: Target, request: NSURLRequest, completion: Moya.Completion, endpoint: Endpoint<Target>, stubBehavior: Moya.StubBehavior) -> CancellableToken { var canceled = false let cancellableToken = CancellableToken { canceled = true } let request = manager.request(request) let plugins = self.plugins plugins.forEach { $0.willSendRequest(request, provider: self, target: target) } let stub: () -> () = { if (canceled) { let error = NSError(domain: NSURLErrorDomain, code: NSURLErrorCancelled, userInfo: nil) plugins.forEach { $0.didReceiveResponse(nil, statusCode: nil, response: nil, error: error, provider: self, target: target) } completion(data: nil, statusCode: nil, response: nil, error: error) return } switch endpoint.sampleResponseClosure() { case .NetworkResponse(let statusCode, let data): plugins.forEach { $0.didReceiveResponse(data, statusCode: statusCode, response: nil, error: nil, provider: self, target: target) } completion(data: data, statusCode: statusCode, response: nil, error: nil) case .NetworkError(let error): plugins.forEach { $0.didReceiveResponse(nil, statusCode: nil, response: nil, error: error, provider: self, target: target) } completion(data: nil, statusCode: nil, response: nil, error: error) } } switch stubBehavior { case .Immediate: stub() case .Delayed(let delay): let killTimeOffset = Int64(CDouble(delay) * CDouble(NSEC_PER_SEC)) let killTime = dispatch_time(DISPATCH_TIME_NOW, killTimeOffset) dispatch_after(killTime, dispatch_get_main_queue()) { stub() } case .Never: fatalError("Method called to stub request when stubbing is disabled.") } return cancellableToken } } /// Private token that can be used to cancel requests private struct CancellableToken: Cancellable , CustomDebugStringConvertible{ let cancelAction: () -> Void let request : Request? func cancel() { cancelAction() } init(action: () -> Void){ self.cancelAction = action self.request = nil } init(request : Request){ self.request = request self.cancelAction = { request.cancel() } } var debugDescription: String { guard let request = self.request else { return "Empty Request" } return request.debugDescription } } private struct CancellableWrapper: Cancellable { var innerCancellable: CancellableToken? = nil private var isCancelled = false func cancel() { innerCancellable?.cancel() } } /// Make the Alamofire Request type conform to our type, to prevent leaking Alamofire to plugins. extension Request: MoyaRequest { }
mit
3c133af96ad52d327c8aa0351f942a76
34.424561
171
0.638966
5.228379
false
false
false
false
iOSDevLog/InkChat
InkChat/InkChat/Login/Model/User.swift
1
9777
// // User.swift // InkChat // // Created by iOS Dev Log on 2017/5/28. // Copyright © 2017年 iOSDevLog. All rights reserved. // import UIKit import FirebaseAuth import FirebaseDatabase import FirebaseStorage import PKHUD class User: NSObject { var id: String? var name: String? var email: String? var city: String? var profileImageUrl: String? var type: String? var profileImage: UIImage? init(dictionary: [String: AnyObject]) { self.id = dictionary["id"] as? String self.type = dictionary["type"] as? String self.name = dictionary["name"] as? String self.email = dictionary["email"] as? String self.city = dictionary["city"] as? String self.profileImageUrl = dictionary["profileImageUrl"] as? String } //MARK: Inits init(id: String, name: String, email: String, city: String,profileImageUrl: String, profileImage: UIImage, type: String) { self.name = name self.email = email self.id = id self.city = city self.type = type self.profileImageUrl = profileImageUrl self.profileImage = profileImage } class func signUpUser(username: String, email: String, password: String, city: String, image: UIImage, type: String = "artist", completion: @escaping (Bool) -> Swift.Void) { let existUser = ad.users.contains { (user) -> Bool in user.name == username } guard existUser == false else { HUD.flash(.labeledProgress(title: "Error", subtitle: "username exist, try another"), delay: 2.0) completion(false) return } Auth.auth().createUser(withEmail: email, password: password, completion: { (user, error) in if error != nil { print(error!) HUD.flash(.labeledProgress(title: "Error", subtitle: error?.localizedDescription), delay: 2.0) completion(false) return } guard let uid = user?.uid else { completion(false) return } //successfully authenticated user let imageName = UUID().uuidString let storageRef = Storage.storage().reference().child("profile_images").child("\(imageName).jpg") if let uploadData = UIImageJPEGRepresentation(image, 0.1) { storageRef.putData(uploadData, metadata: nil, completion: { (metadata, error) in if error != nil { print(error!) HUD.flash(.labeledProgress(title: "Error", subtitle: error?.localizedDescription), delay: 2.0) return } if let profileImageUrl = metadata?.downloadURL()?.absoluteString { let values = ["name": username, "email": email, "profileImageUrl": profileImageUrl, "city": city, "type": type] let ref = Database.database().reference() let usersReference = ref.child("users").child(uid).child("credentials") usersReference.updateChildValues(values, withCompletionBlock: { (err, ref) in if err != nil { print(err!) HUD.flash(.labeledProgress(title: "Error", subtitle: err?.localizedDescription), delay: 2.0) return } ad.user = User(dictionary: values as [String : AnyObject]) UserDefaults.standard.set(values, forKey: "userInformation") UserDefaults.standard.synchronize() completion(true) }) } }) } }) } class func loginUser(userName: String, password: String, completion: @escaping (Bool) -> Swift.Void) { if let fileUser = ad.users.filter({ (user) -> Bool in user.name == userName }).first { let email = fileUser.email Auth.auth().signIn(withEmail: email!, password: password, completion: { (userInfo, error) in if error == nil { self.info(forUserID: (userInfo?.uid)!, completion: { (user) in ad.user = user }) completion(true) } else { HUD.flash(.labeledProgress(title: "Error", subtitle: error?.localizedDescription), delay: 2.0) completion(false) } }) } else { HUD.flash(.labeledProgress(title: "Error", subtitle: "user is not exist"), delay: 2.0) completion(false) } } class func loginUser(email: String, password: String, completion: @escaping (Bool) -> Swift.Void) { Auth.auth().signIn(withEmail: email, password: password, completion: { (userInfo, error) in if error == nil { let userId = userInfo?.uid if let id = Auth.auth().currentUser?.uid { self.info(forUserID: id, completion: { (user) in ad.user = user }) } completion(true) } else { completion(false) } }) } class func logOutUser(completion: @escaping (Bool) -> Swift.Void) { do { try Auth.auth().signOut() UserDefaults.standard.removeObject(forKey: "userInformation") completion(true) } catch _ { completion(false) } } class func info(forUserID: String, completion: @escaping (User) -> Swift.Void) { if let partainerUser = ad.users.first(where: { (user) -> Bool in user.id == forUserID }) { completion(partainerUser) return } Database.database().reference().child("users").child(forUserID).child("credentials").observeSingleEvent(of: .value, with: { (snapshot) in if let data = snapshot.value as? [String: String] { let name = data["name"]! let email = data["email"]! let type = data["type"]! let city = data["city"]! let profileImageUrl = data["profileImageUrl"]! let link = URL.init(string: profileImageUrl) URLSession.shared.dataTask(with: link!, completionHandler: { (data, response, error) in if error == nil { let profileImage = UIImage(data: data!) let user = User(id: forUserID, name: name, email: email, city: city, profileImageUrl: profileImageUrl, profileImage: profileImage!, type: type) completion(user) } }).resume() } }) } class func downloadAllUsers(completion: @escaping (User) -> Swift.Void) { Database.database().reference().child("users").observe(.childAdded, with: { (snapshot) in let id = snapshot.key let data = snapshot.value as! [String: Any] let credentials = data["credentials"] as! [String: String] let name = credentials["name"]! let email = credentials["email"]! let city = credentials["city"]! let type = credentials["type"]! let profileImageUrl = credentials["profileImageUrl"]! let link = URL.init(string: profileImageUrl) URLSession.shared.dataTask(with: link!, completionHandler: { (data, response, error) in if error == nil { let profileImage = UIImage(data: data!) let user = User(id: id, name: name, email: email, city: city, profileImageUrl: profileImageUrl, profileImage: profileImage!, type: type) completion(user) } }).resume() }) } class func downloadAllUsers(exceptID: String, completion: @escaping (User) -> Swift.Void) { Database.database().reference().child("users").observe(.childAdded, with: { (snapshot) in let id = snapshot.key let data = snapshot.value as! [String: Any] let credentials = data["credentials"] as! [String: String] if id != exceptID { let name = credentials["name"]! let email = credentials["email"]! let type = credentials["type"]! let city = credentials["city"]! let profileImageUrl = credentials["profileImageUrl"]! let link = URL.init(string: profileImageUrl) URLSession.shared.dataTask(with: link!, completionHandler: { (data, response, error) in if error == nil { let profileImage = UIImage(data: data!) let user = User(id: id, name: name, email: email, city: city, profileImageUrl: profileImageUrl, profileImage: profileImage!, type: type) completion(user) } }).resume() } }) } class func checkUserVerification(completion: @escaping (Bool) -> Swift.Void) { Auth.auth().currentUser?.reload(completion: { (_) in let status = (Auth.auth().currentUser?.isEmailVerified)! completion(status) }) } }
apache-2.0
44f3bfcdf299d007aca24b8248d96292
41.12931
177
0.520667
5.080042
false
false
false
false
asbhat/stanford-ios10-apps
Calculator/Calculator/AxesDrawer.swift
1
7916
// // AxesDrawer.swift // Calculator // // Created by CS193p Instructor. // Copyright © 2015-17 Stanford University. // All rights reserved. // import UIKit struct AxesDrawer { var color: UIColor var contentScaleFactor: CGFloat // set this from UIView's contentScaleFactor to position axes with maximum accuracy var minimumPointsPerHashmark: CGFloat = 40 // public even though init doesn't accommodate setting it (it's rare to want to change it) init(color: UIColor = UIColor.blue, contentScaleFactor: CGFloat = 1) { self.color = color self.contentScaleFactor = contentScaleFactor } // this method is the heart of the AxesDrawer // it draws in the current graphic context's coordinate system // therefore origin and bounds must be in the current graphics context's coordinate system // pointsPerUnit is essentially the "scale" of the axes // e.g. if you wanted there to be 100 points along an axis between -1 and 1, // you'd set pointsPerUnit to 50 func drawAxes(in rect: CGRect, origin: CGPoint, pointsPerUnit: CGFloat) { UIGraphicsGetCurrentContext()?.saveGState() color.set() let path = UIBezierPath() path.move(to: CGPoint(x: rect.minX, y: origin.y).aligned(usingScaleFactor: contentScaleFactor)!) path.addLine(to: CGPoint(x: rect.maxX, y: origin.y).aligned(usingScaleFactor: contentScaleFactor)!) path.move(to: CGPoint(x: origin.x, y: rect.minY).aligned(usingScaleFactor: contentScaleFactor)!) path.addLine(to: CGPoint(x: origin.x, y: rect.maxY).aligned(usingScaleFactor: contentScaleFactor)!) path.stroke() drawHashmarks(in: rect, origin: origin, pointsPerUnit: abs(pointsPerUnit)) UIGraphicsGetCurrentContext()?.restoreGState() } // the rest of this class is private private struct Constants { static let hashmarkSize: CGFloat = 6 } private let formatter = NumberFormatter() // formatter for the hashmark labels private func drawHashmarks(in rect: CGRect, origin: CGPoint, pointsPerUnit: CGFloat) { if ((origin.x >= rect.minX) && (origin.x <= rect.maxX)) || ((origin.y >= rect.minY) && (origin.y <= rect.maxY)) { // figure out how many units each hashmark must represent // to respect both pointsPerUnit and minimumPointsPerHashmark var unitsPerHashmark = minimumPointsPerHashmark / pointsPerUnit if unitsPerHashmark < 1 { unitsPerHashmark = pow(10, ceil(log10(unitsPerHashmark))) } else { unitsPerHashmark = floor(unitsPerHashmark) } let pointsPerHashmark = pointsPerUnit * unitsPerHashmark // figure out which is the closest set of hashmarks (radiating out from the origin) that are in rect var startingHashmarkRadius: CGFloat = 1 if !rect.contains(origin) { let leftx = max(origin.x - rect.maxX, 0) let rightx = max(rect.minX - origin.x, 0) let downy = max(origin.y - rect.minY, 0) let upy = max(rect.maxY - origin.y, 0) startingHashmarkRadius = min(min(leftx, rightx), min(downy, upy)) / pointsPerHashmark + 1 } // pick a reasonable number of fraction digits formatter.maximumFractionDigits = Int(-log10(Double(unitsPerHashmark))) formatter.minimumIntegerDigits = 1 // now create a bounding box inside whose edges those four hashmarks lie let bboxSize = pointsPerHashmark * startingHashmarkRadius * 2 var bbox = CGRect(center: origin, size: CGSize(width: bboxSize, height: bboxSize)) // radiate the bbox out until the hashmarks are further out than the rect while !bbox.contains(rect) { let label = formatter.string(from: (origin.x-bbox.minX)/pointsPerUnit)! if let leftHashmarkPoint = CGPoint(x: bbox.minX, y: origin.y).aligned(inside: rect, usingScaleFactor: contentScaleFactor) { drawHashmark(at: leftHashmarkPoint, label: .top("-\(label)")) } if let rightHashmarkPoint = CGPoint(x: bbox.maxX, y: origin.y).aligned(inside: rect, usingScaleFactor: contentScaleFactor) { drawHashmark(at: rightHashmarkPoint, label: .top(label)) } if let topHashmarkPoint = CGPoint(x: origin.x, y: bbox.minY).aligned(inside: rect, usingScaleFactor: contentScaleFactor) { drawHashmark(at: topHashmarkPoint, label: .left(label)) } if let bottomHashmarkPoint = CGPoint(x: origin.x, y: bbox.maxY).aligned(inside: rect, usingScaleFactor: contentScaleFactor) { drawHashmark(at: bottomHashmarkPoint, label: .left("-\(label)")) } bbox = bbox.insetBy(dx: -pointsPerHashmark, dy: -pointsPerHashmark) } } } private func drawHashmark(at location: CGPoint, label: AnchoredText) { var dx: CGFloat = 0, dy: CGFloat = 0 switch label { case .left: dx = Constants.hashmarkSize / 2 case .right: dx = Constants.hashmarkSize / 2 case .top: dy = Constants.hashmarkSize / 2 case .bottom: dy = Constants.hashmarkSize / 2 } let path = UIBezierPath() path.move(to: CGPoint(x: location.x-dx, y: location.y-dy)) path.addLine(to: CGPoint(x: location.x+dx, y: location.y+dy)) path.stroke() label.draw(at: location, usingColor: color) } private enum AnchoredText { case left(String) case right(String) case top(String) case bottom(String) static let verticalOffset: CGFloat = 3 static let horizontalOffset: CGFloat = 6 func draw(at location: CGPoint, usingColor color: UIColor) { let attributes = [ NSAttributedStringKey.font : UIFont.preferredFont(forTextStyle: .footnote), NSAttributedStringKey.foregroundColor : color ] var textRect = CGRect(center: location, size: text.size(withAttributes: attributes)) switch self { case .top: textRect.origin.y += textRect.size.height / 2 + AnchoredText.verticalOffset case .left: textRect.origin.x += textRect.size.width / 2 + AnchoredText.horizontalOffset case .bottom: textRect.origin.y -= textRect.size.height / 2 + AnchoredText.verticalOffset case .right: textRect.origin.x -= textRect.size.width / 2 + AnchoredText.horizontalOffset } text.draw(in: textRect, withAttributes: attributes) } var text: String { switch self { case .left(let text): return text case .right(let text): return text case .top(let text): return text case .bottom(let text): return text } } } } private extension CGPoint { func aligned(inside bounds: CGRect? = nil, usingScaleFactor scaleFactor: CGFloat = 1.0) -> CGPoint? { func align(_ coordinate: CGFloat) -> CGFloat { return round(coordinate * scaleFactor) / scaleFactor } let point = CGPoint(x: align(x), y: align(y)) if let permissibleBounds = bounds, !permissibleBounds.contains(point) { return nil } return point } } private extension NumberFormatter { func string(from point: CGFloat) -> String? { return string(from: NSNumber(value: Double(point))) } } private extension CGRect { init(center: CGPoint, size: CGSize) { self.init(x: center.x-size.width/2, y: center.y-size.height/2, width: size.width, height: size.height) } }
apache-2.0
81fcdcc483a316d773452a26846ead9c
41.326203
141
0.621352
4.591067
false
false
false
false
shorlander/firefox-ios
Storage/Bookmarks/BookmarksModel.swift
1
12979
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Deferred import Foundation import Shared private let log = Logger.syncLogger /** * The kinda-immutable base interface for bookmarks and folders. */ open class BookmarkNode { open var id: Int? open let guid: GUID open let title: String open let isEditable: Bool open var favicon: Favicon? init(guid: GUID, title: String, isEditable: Bool=false) { self.guid = guid self.title = title self.isEditable = isEditable } open var canDelete: Bool { return self.isEditable } } open class BookmarkSeparator: BookmarkNode { init(guid: GUID) { super.init(guid: guid, title: "—") } } /** * An immutable item representing a bookmark. * * To modify this, issue changes against the backing store and get an updated model. */ open class BookmarkItem: BookmarkNode { open let url: String! public init(guid: String, title: String, url: String, isEditable: Bool=false) { self.url = url super.init(guid: guid, title: title, isEditable: isEditable) } } /** * A folder is an immutable abstraction over a named * thing that can return its child nodes by index. */ open class BookmarkFolder: BookmarkNode { open var count: Int { return 0 } open subscript(index: Int) -> BookmarkNode? { return nil } open func itemIsEditableAtIndex(_ index: Int) -> Bool { return self[index]?.canDelete ?? false } override open var canDelete: Bool { return false } open func removeItemWithGUID(_ guid: GUID) -> BookmarkFolder? { return nil } } /** * A model is a snapshot of the bookmarks store, suitable for backing a table view. * * Navigation through the folder hierarchy produces a sequence of models. * * Changes to the backing store implicitly invalidates a subset of models. * * 'Refresh' means requesting a new model from the store. */ open class BookmarksModel: BookmarksModelFactorySource { fileprivate let factory: BookmarksModelFactory open let modelFactory: Deferred<Maybe<BookmarksModelFactory>> open let current: BookmarkFolder public init(modelFactory: BookmarksModelFactory, root: BookmarkFolder) { self.factory = modelFactory self.modelFactory = deferMaybe(modelFactory) self.current = root } /** * Produce a new model rooted at the appropriate folder. Fails if the folder doesn't exist. */ open func selectFolder(_ folder: BookmarkFolder) -> Deferred<Maybe<BookmarksModel>> { return self.factory.modelForFolder(folder) } /** * Produce a new model rooted at the appropriate folder. Fails if the folder doesn't exist. */ open func selectFolder(_ guid: String) -> Deferred<Maybe<BookmarksModel>> { return self.factory.modelForFolder(guid) } /** * Produce a new model rooted at the base of the hierarchy. Should never fail. */ open func selectRoot() -> Deferred<Maybe<BookmarksModel>> { return self.factory.modelForRoot() } /** * Produce a new model with a memory-backed root with the given GUID removed from the current folder */ open func removeGUIDFromCurrent(_ guid: GUID) -> BookmarksModel { if let removedRoot = self.current.removeItemWithGUID(guid) { return BookmarksModel(modelFactory: self.factory, root: removedRoot) } log.warning("BookmarksModel.removeGUIDFromCurrent did not remove anything. Check to make sure you're not using the abstract BookmarkFolder class.") return self } /** * Produce a new model rooted at the same place as this model. Can fail if * the folder has been deleted from the backing store. */ open func reloadData() -> Deferred<Maybe<BookmarksModel>> { return self.factory.modelForFolder(current) } open var canDelete: Bool { return false } } public protocol BookmarksModelFactorySource { var modelFactory: Deferred<Maybe<BookmarksModelFactory>> { get } } public protocol BookmarksModelFactory { func modelForFolder(_ folder: BookmarkFolder) -> Deferred<Maybe<BookmarksModel>> func modelForFolder(_ guid: GUID) -> Deferred<Maybe<BookmarksModel>> func modelForFolder(_ guid: GUID, title: String) -> Deferred<Maybe<BookmarksModel>> func modelForRoot() -> Deferred<Maybe<BookmarksModel>> // Whenever async construction is necessary, we fall into a pattern of needing // a placeholder that behaves correctly for the period between kickoff and set. var nullModel: BookmarksModel { get } func isBookmarked(_ url: String) -> Deferred<Maybe<Bool>> func removeByGUID(_ guid: GUID) -> Success @discardableResult func removeByURL(_ url: String) -> Success } /* * A folder that contains an array of children. */ open class MemoryBookmarkFolder: BookmarkFolder, Sequence { let children: [BookmarkNode] public init(guid: GUID, title: String, children: [BookmarkNode]) { self.children = children super.init(guid: guid, title: title) } public struct BookmarkNodeGenerator: IteratorProtocol { public typealias Element = BookmarkNode let children: [BookmarkNode] var index: Int = 0 init(children: [BookmarkNode]) { self.children = children } public mutating func next() -> BookmarkNode? { if index < children.count { defer { index += 1 } return children[index] } return nil } } override open var favicon: Favicon? { get { if let path = Bundle.main.path(forResource: "bookmarkFolder", ofType: "png") { let url = URL(fileURLWithPath: path) return Favicon(url: url.absoluteString, date: Date(), type: IconType.local) } return nil } set { } } override open var count: Int { return children.count } override open subscript(index: Int) -> BookmarkNode { get { return children[index] } } override open func itemIsEditableAtIndex(_ index: Int) -> Bool { return true } override open func removeItemWithGUID(_ guid: GUID) -> BookmarkFolder? { let without = children.filter { $0.guid != guid } return MemoryBookmarkFolder(guid: self.guid, title: self.title, children: without) } open func makeIterator() -> BookmarkNodeGenerator { return BookmarkNodeGenerator(children: self.children) } /** * Return a new immutable folder that's just like this one, * but also contains the new items. */ func append(_ items: [BookmarkNode]) -> MemoryBookmarkFolder { if items.isEmpty { return self } return MemoryBookmarkFolder(guid: self.guid, title: self.title, children: self.children + items) } } open class MemoryBookmarksSink: ShareToDestination { var queue: [BookmarkNode] = [] public init() { } open func shareItem(_ item: ShareItem) -> Success { let title = item.title == nil ? "Untitled" : item.title! func exists(_ e: BookmarkNode) -> Bool { if let bookmark = e as? BookmarkItem { return bookmark.url == item.url } return false } // Don't create duplicates. if !queue.contains(where: exists) { queue.append(BookmarkItem(guid: Bytes.generateGUID(), title: title, url: item.url)) } return succeed() } } private extension SuggestedSite { func asBookmark() -> BookmarkNode { let b = BookmarkItem(guid: self.guid ?? Bytes.generateGUID(), title: self.title, url: self.url) b.favicon = self.icon return b } } open class PrependedBookmarkFolder: BookmarkFolder { fileprivate let main: BookmarkFolder fileprivate let prepend: BookmarkNode init(main: BookmarkFolder, prepend: BookmarkNode) { self.main = main self.prepend = prepend super.init(guid: main.guid, title: main.guid) } override open var count: Int { return self.main.count + 1 } override open subscript(index: Int) -> BookmarkNode? { if index == 0 { return self.prepend } return self.main[index - 1] } override open func itemIsEditableAtIndex(_ index: Int) -> Bool { return index > 0 && self.main.itemIsEditableAtIndex(index - 1) } override open func removeItemWithGUID(_ guid: GUID) -> BookmarkFolder? { guard let removedFolder = main.removeItemWithGUID(guid) else { log.warning("Failed to remove child item from prepended folder. Check that main folder overrides removeItemWithGUID.") return nil } return PrependedBookmarkFolder(main: removedFolder, prepend: prepend) } } open class ConcatenatedBookmarkFolder: BookmarkFolder { fileprivate let main: BookmarkFolder fileprivate let append: BookmarkFolder init(main: BookmarkFolder, append: BookmarkFolder) { self.main = main self.append = append super.init(guid: main.guid, title: main.title) } override open var count: Int { return main.count + append.count } override open subscript(index: Int) -> BookmarkNode? { return index < main.count ? main[index] : append[index - main.count] } override open func itemIsEditableAtIndex(_ index: Int) -> Bool { return index < main.count ? main.itemIsEditableAtIndex(index) : append.itemIsEditableAtIndex(index - main.count) } override open func removeItemWithGUID(_ guid: GUID) -> BookmarkFolder? { let newMain = main.removeItemWithGUID(guid) ?? main let newAppend = append.removeItemWithGUID(guid) ?? append return ConcatenatedBookmarkFolder(main: newMain, append: newAppend) } } /** * A trivial offline model factory that represents a simple hierarchy. */ open class MockMemoryBookmarksStore: BookmarksModelFactory, ShareToDestination { let mobile: MemoryBookmarkFolder let root: MemoryBookmarkFolder var unsorted: MemoryBookmarkFolder let sink: MemoryBookmarksSink public init() { let res = [BookmarkItem]() mobile = MemoryBookmarkFolder(guid: BookmarkRoots.MobileFolderGUID, title: "Mobile Bookmarks", children: res) unsorted = MemoryBookmarkFolder(guid: BookmarkRoots.UnfiledFolderGUID, title: "Unsorted Bookmarks", children: []) sink = MemoryBookmarksSink() root = MemoryBookmarkFolder(guid: BookmarkRoots.RootGUID, title: "Root", children: [mobile, unsorted]) } open func modelForFolder(_ folder: BookmarkFolder) -> Deferred<Maybe<BookmarksModel>> { return self.modelForFolder(folder.guid, title: folder.title) } open func modelForFolder(_ guid: GUID) -> Deferred<Maybe<BookmarksModel>> { return self.modelForFolder(guid, title: "") } open func modelForFolder(_ guid: GUID, title: String) -> Deferred<Maybe<BookmarksModel>> { var m: BookmarkFolder switch guid { case BookmarkRoots.MobileFolderGUID: // Transparently merges in any queued items. m = self.mobile.append(self.sink.queue) break case BookmarkRoots.RootGUID: m = self.root break case BookmarkRoots.UnfiledFolderGUID: m = self.unsorted break default: return deferMaybe(DatabaseError(description: "No such folder \(guid).")) } return deferMaybe(BookmarksModel(modelFactory: self, root: m)) } open func modelForRoot() -> Deferred<Maybe<BookmarksModel>> { return deferMaybe(BookmarksModel(modelFactory: self, root: self.root)) } /** * This class could return the full data immediately. We don't, because real DB-backed code won't. */ open var nullModel: BookmarksModel { let f = MemoryBookmarkFolder(guid: BookmarkRoots.RootGUID, title: "Root", children: []) return BookmarksModel(modelFactory: self, root: f) } open func shareItem(_ item: ShareItem) -> Success { return self.sink.shareItem(item) } open func isBookmarked(_ url: String) -> Deferred<Maybe<Bool>> { return deferMaybe(DatabaseError(description: "Not implemented")) } open func removeByGUID(_ guid: GUID) -> Success { return deferMaybe(DatabaseError(description: "Not implemented")) } open func removeByURL(_ url: String) -> Success { return deferMaybe(DatabaseError(description: "Not implemented")) } open func clearBookmarks() -> Success { return succeed() } }
mpl-2.0
2df67bfa2e61cf24e4addef6b423530c
30.806373
155
0.653541
4.585512
false
false
false
false
asnow003/SwiftAppCommon
SwiftAppCommonDemo/SwiftAppCommonDemo/UIImageView+Extensions.swift
2
2231
// // UIImageView+Extensions.swift // // Created by Allen Snow on 6/8/17. // Copyright © 2017 Waggle Bum. All rights reserved. // import UIKit import Foundation extension UIImageView { open override func awakeFromNib() { super.awakeFromNib() self.setTintedImage() } public func setTintedImage(_ color: UIColor? = nil) { if let image = self.image { self.image = image.withRenderingMode(UIImageRenderingMode.alwaysTemplate) } self.tintColor = color == nil ? self.tintColor : color } public func setTintedImage(_ named: String, color: UIColor) { guard named.characters.count > 0 else { return } // check if image exists in the project assets guard let image = UIImage(named: named) else { return } self.tintColor = color self.image = image.withRenderingMode(UIImageRenderingMode.alwaysTemplate) } public func setParallaxEffect(_ shiftValue: Int = 10) { guard shiftValue > 0 else { return } // Set vertical effect let verticalMotionEffect = UIInterpolatingMotionEffect(keyPath: "center.y", type: .tiltAlongVerticalAxis) verticalMotionEffect.minimumRelativeValue = -1 * shiftValue verticalMotionEffect.maximumRelativeValue = shiftValue // Set horizontal effect let horizontalMotionEffect = UIInterpolatingMotionEffect(keyPath: "center.x", type: .tiltAlongHorizontalAxis) horizontalMotionEffect.minimumRelativeValue = -1 * shiftValue horizontalMotionEffect.maximumRelativeValue = shiftValue // Create group to combine both let group = UIMotionEffectGroup() group.motionEffects = [horizontalMotionEffect, verticalMotionEffect] // Make sure the image clips to bounds for the overhand if any self.clipsToBounds = true // Add both effects to your view self.addMotionEffect(group) } }
mit
cf584882dd08074fe27ff1deafe9257b
30.857143
96
0.593274
5.659898
false
false
false
false
xuanyi0627/jetstream-ios
JetstreamTests/ScopePauseTests.swift
1
5180
// // ScopePauseTests.swift // Jetstream // // Copyright (c) 2014 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit import XCTest class ScopePauseTest: XCTestCase { var root = TestModel() var scope = Scope(name: "Testing") var client = Client(transportAdapterFactory: { TestTransportAdapter() }) var firstMessage: ScopeStateMessage! let uuid = NSUUID() override func setUp() { root = TestModel() scope = Scope(name: "Testing") root.setScopeAndMakeRootModel(scope) XCTAssertEqual(scope.modelObjects.count, 1, "Correct number of objects in scope to start with") client = Client(transportAdapterFactory: { TestTransportAdapter() }) var msg = SessionCreateReplyMessage(index: 1, sessionToken: "jeah", error: nil) client.receivedMessage(msg) client.session!.scopeAttach(scope, scopeIndex: 0) let childUUID = NSUUID() var json: [String: AnyObject] = [ "type": "ScopeState", "index": 1, "scopeIndex": 0, "rootUUID": uuid.UUIDString, "fragments": [ [ "type": "change", "uuid": uuid.UUIDString, "clsName": "TestModel", "properties": [ "string": "set correctly", "integer": 10, "childModel": childUUID.UUIDString ] ], [ "type": "add", "uuid": childUUID.UUIDString, "properties": ["string": "ok"], "clsName": "TestModel" ] ] ] firstMessage = NetworkMessage.unserializeDictionary(json) as! ScopeStateMessage client.receivedMessage(firstMessage) } override func tearDown() { super.tearDown() } func testPause() { var json: [String: AnyObject] = [ "type": "ScopeSync", "index": 2, "scopeIndex": 0, "fragments": [ [ "type": "change", "uuid": uuid.UUIDString, "clsName": "TestModel", "properties": ["string": "changed"], ] ] ] root.scope?.pauseIncomingMessages() client.receivedMessage(NetworkMessage.unserializeDictionary(json)!) XCTAssertEqual(root.string!, "set correctly", "Property not yet changed") root.scope?.resumeIncomingMessages() XCTAssertEqual(root.string!, "changed", "Property changed") } func testMultiMessagePause() { root.scope?.pauseIncomingMessages() var json: [String: AnyObject] = [ "type": "ScopeSync", "index": 2, "scopeIndex": 0, "fragments": [ [ "type": "change", "uuid": uuid.UUIDString, "clsName": "TestModel", "properties": ["string": "changed"], ] ] ] client.receivedMessage(NetworkMessage.unserializeDictionary(json)!) json = [ "type": "ScopeSync", "index": 3, "scopeIndex": 0, "fragments": [ [ "type": "change", "uuid": uuid.UUIDString, "clsName": "TestModel", "properties": ["integer": 20], ] ] ] client.receivedMessage(NetworkMessage.unserializeDictionary(json)!) XCTAssertEqual(root.string!, "set correctly", "Property not yet changed") XCTAssertEqual(root.integer, 10, "Property not yet changed") root.scope?.resumeIncomingMessages() XCTAssertEqual(root.string!, "changed", "Property changed") XCTAssertEqual(root.integer, 20, "Property changed") } }
mit
c911be0b96a86de393d49dd3fc252d0d
34.724138
103
0.547104
4.933333
false
true
false
false
ggu/OSXPassGen
OSXPassGen/Password.swift
1
843
// // Password.swift // OSXPassGen // // Created by Gabriel Uribe on 12/11/15. // import Foundation struct Password { static let lowerBound = 33 // alphanumeric ASCII bounds static let upperBound = 126 static func generate(length: Int, toExclude: String) -> String { var charactersToExlude: [UnicodeScalar] = [] for char in toExclude.unicodeScalars { charactersToExlude.append(char) } var password = "" for _ in 0..<length { var passwordCharacter: UnicodeScalar repeat { let passwordCharacterInt = Utility.getRandomNumber(lowerBound, max: upperBound) passwordCharacter = UnicodeScalar(passwordCharacterInt) } while charactersToExlude.contains(passwordCharacter) password.append(passwordCharacter) } return password } }
mit
85796c955580737933a08e27a57b4915
22.416667
87
0.667853
4.556757
false
false
false
false
salmojunior/TMDb
TMDb/TMDb/Source/View/Movie/MovieDetailsView.swift
1
4620
// // MovieDetailsView.swift // TMDb // // Created by SalmoJunior on 13/05/17. // Copyright © 2017 Salmo Junior. All rights reserved. // import UIKit import Cosmos import Kingfisher class MovieDetailsView: UIView { // MARK: - Constants private let kRatingNormalize = 2.0 private let kPlaceholderImageName = "logo" private let kNavigationHeight: CGFloat = 64 private let kStartElementPosition: CGFloat = 100 private let kEndElementPosition: CGFloat = 0 private let kAnimationDuration = 0.3 // MARK: - Outlets @IBOutlet private weak var titleLabel: UILabel! @IBOutlet private weak var posterImageView: UIImageView! @IBOutlet private weak var genresLabel: UILabel! @IBOutlet private weak var ratingView: CosmosView! @IBOutlet private weak var overviewLabel: UILabel! @IBOutlet private weak var releaseDateLabel: UILabel! @IBOutlet private weak var backdropImageView: UIImageView! @IBOutlet private weak var containerView: UIView! @IBOutlet private weak var posterTopConstraint: NSLayoutConstraint! @IBOutlet private weak var genresStackViewTopConstraint: NSLayoutConstraint! // MARK: - Public Functions /// Fill screen in with movie details /// /// - Parameter movie: Movie object func fulfill(movie: Movie) { // Update Labels titleLabel.text = movie.title overviewLabel.text = movie.overview releaseDateLabel.text = "\(LocalizableStrings.release.localize()): \(movie.release)" ratingView.rating = movie.voteAverage / kRatingNormalize genresLabel.text = movie.genres?.reduce("", { (text, genre) -> String in return "\(text)\n\(genre.name)" }) // Update image views elements let placeholder = UIImage(named: kPlaceholderImageName) guard let posterURL = movie.posterPath else { posterImageView.image = placeholder return } guard let backdropURL = movie.backdropPath else { backdropImageView.image = placeholder return } let posterResource = ImageResource(downloadURL: posterURL, cacheKey: posterURL.description) let backdropResource = ImageResource(downloadURL: backdropURL, cacheKey: backdropURL.description) posterImageView.kf.setImage(with: posterResource, placeholder: placeholder, options: nil, progressBlock: nil, completionHandler: nil) backdropImageView.kf.setImage(with: backdropResource, placeholder: placeholder, options: nil, progressBlock: nil, completionHandler: nil) // Accessibility titleLabel.accessibilityLabel = "\(LocalizableStrings.title.localize()): \(movie.title)" overviewLabel.accessibilityLabel = "\(LocalizableStrings.overview.localize()): \(movie.overview)" if let genres = genresLabel.text { genresLabel.accessibilityLabel = "\(LocalizableStrings.genres.localize()): \(genres)" } // Force right elements position before present view layoutIfNeeded() } func posterImageViewFrame() -> CGRect { // Calculate final Poster frame before load view for custom transition let xPosition = posterImageView.frame.origin.x let yPosition = titleLabel.frame.origin.y + titleLabel.frame.size.height + posterTopConstraint.constant + kNavigationHeight let posterWidth = posterImageView.frame.size.width let posterHeight = posterImageView.frame.size.height let posterFrame = CGRect(x: xPosition, y: yPosition, width: posterWidth, height: posterHeight) return posterFrame } func initialViewElementsStatus() { posterImageView.alpha = 0 genresLabel.alpha = 0 ratingView.alpha = 0 overviewLabel.alpha = 0 releaseDateLabel.alpha = 0 backdropImageView.alpha = 0 genresStackViewTopConstraint.constant = kStartElementPosition } func presentingViewElementsStatus() { posterImageView.alpha = 1 self.genresStackViewTopConstraint.constant = self.kEndElementPosition UIView.animate(withDuration: kAnimationDuration, delay: 0, options: .curveEaseOut, animations: { self.genresLabel.alpha = 1 self.ratingView.alpha = 1 self.overviewLabel.alpha = 1 self.releaseDateLabel.alpha = 1 self.backdropImageView.alpha = 1 self.layoutIfNeeded() }, completion: nil) } }
mit
a64ce799f22da93eadf739927396547a
38.144068
145
0.667244
5.184063
false
false
false
false
Virpik/T
src/UI/[T][Style]/[T][StyleSupport]/UI Impl/[UITextField][TStyleSupportTextField].swift
1
2653
// // [UITextField][TStyleSupportTextField].swift // T // // Created by Virpik on 16/03/2018. // import Foundation import UIKit extension NSAttributedString { fileprivate func value<T>(by attribute: NSAttributedString.Key) -> T? { let attributes = self.attributes(at: 0, effectiveRange: nil) return attributes[NSAttributedString.Key.foregroundColor] as? T } fileprivate func set(value: Any, by attribute: NSAttributedString.Key) -> NSAttributedString { let mAttrStr = NSMutableAttributedString(attributedString: self) let range = NSRange(location: 0, length: self.string.count) mAttrStr.addAttributes([attribute: value], range: range) return mAttrStr } } extension UITextField: TStyleSupportTextField { private typealias AtrStrKey = NSAttributedString.Key public var aLabel: TStyleSupportLabel { return self } public var aView: TStyleSupportView { return self } public var aPlaceholder: TStyleSupportLabel { let impl = TStyleSupportLabelImpl(getTextColor: { () -> UIColor in let color: UIColor = self.attributedPlaceholder?.value(by: .foregroundColor as AtrStrKey) ?? .black return color }, setTextColor: { (color) in let attrStr = self.attributedPlaceholder ?? NSAttributedString(string: "") self.attributedPlaceholder = attrStr.set(value: color, by: .foregroundColor) }, getTextFont: { () -> UIFont in let defaultFont = UIFont.systemFont(ofSize: 14) let font: UIFont = self.attributedPlaceholder?.value(by: .font as AtrStrKey) ?? defaultFont return font }, setTextFont: { (font) in let attrStr = self.attributedPlaceholder ?? NSAttributedString(string: "") self.attributedPlaceholder = attrStr.set(value: font, by: .font) }, getTextAlignment: { () -> NSTextAlignment in let aligment: NSParagraphStyle? = self.attributedPlaceholder?.value(by: .paragraphStyle as AtrStrKey) return aligment?.alignment ?? .left }) { (textAligment) in let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.alignment = textAligment let attrStr = self.attributedPlaceholder ?? NSAttributedString(string: "") self.attributedPlaceholder = attrStr.set(value: paragraphStyle, by: .paragraphStyle) } return impl } }
mit
0ef96c269c0bc00cd0a5d21bb376cdc7
32.582278
113
0.61666
5.212181
false
false
false
false
bourvill/HydraKit
HydraKit/Classes/Hydra+Post.swift
1
1506
// // Hydra+Post.swift // HydraKit // // Created by maxime marinel on 26/06/2017. // import Foundation extension Hydra { /** Post resource - Parameter hydraObject: an object Type conform to protocol HydraObject - Parameter parameters: dictonary needed to create resource - Parameter completion: Result from task */ public func post<T: HydraObject>(_ hydraObject: T.Type, parameters: [String:Any] = [:], completion: @escaping (Result<T>) -> Void) { let url = URL(string: endpoint + hydraObject.hydraPoint()) var request: URLRequest = URLRequest(url: url!) request.httpMethod = URLRequest.HttpMethod.POST.rawValue do { request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: []) } catch { //@todo error } urlSession.dataTask(with: request) { data, _, error in guard error == nil else { completion(Result.failure(error!)) return } guard let data = data else { print("Data is empty") return } do { if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String:Any] { completion(Result.success(Results<T>(hydraObject, json: json))) } } catch let errorjson { completion(Result.failure(errorjson)) } }.resume() } }
mit
b2cdd3511291c44f8f9f8889a86d55b3
31.042553
136
0.563745
4.549849
false
false
false
false
RylynnLai/V2EX--practise
V2EX/Nodes/RLNodeBtn.swift
1
1017
// // RLNodeBtn.swift // V2EX // // Created by ucs on 16/1/13. // Copyright © 2016年 ucs. All rights reserved. // import UIKit class RLNodeBtn: UIButton { var nodeModel:RLNode? var isZoomAnimating:Bool override init(frame: CGRect) { isZoomAnimating = false super.init(frame: frame) setTitleColor(UIColor.darkGrayColor(), forState:.Normal) self.titleLabel?.adjustsFontSizeToFitWidth = true self.titleLabel?.minimumScaleFactor = 0.5 self.titleLabel?.numberOfLines = 2 self.titleLabel?.textAlignment = .Center self.layer.cornerRadius = 12 self.layer.masksToBounds = true self.layer.anchorPoint = CGPointMake(0.5, 0.5) self.imageView?.contentMode = .ScaleAspectFit setBackgroundImage(UIImage.init(named: "nodeIcon\(arc4random_uniform(8) + 1)"), forState: .Normal) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
76bd9a55bbc8a48220d6df2d8cd7392e
26.432432
106
0.650888
4.155738
false
false
false
false
finngaida/wwdc
2016/Finn Gaida/ImageWidget.swift
1
2036
// // ImageWidget.swift // Finn Gaida // // Created by Finn Gaida on 27.04.16. // Copyright © 2016 Finn Gaida. All rights reserved. // import UIKit import JTSImageViewController class ImageWidget: UIView { var parent: UIViewController? var images: [String] = [] init(frame: CGRect, images: [String], parent: UIViewController) { super.init(frame: frame) self.images = images self.parent = parent self.layer.masksToBounds = true self.layer.cornerRadius = frame.height / 10 self.layer.borderColor = UIColor.grayColor().CGColor self.layer.borderWidth = 2 self.backgroundColor = UIColor(white: 0.8, alpha: 0.2) let width = frame.height * 0.8 for (i, img) in images.enumerate() { let btn = UIButton(frame: CGRectMake(frame.height * 0.1 + (frame.height * 0.1 + width) * CGFloat(i), frame.height * 0.1, width, width)) btn.layer.masksToBounds = true btn.layer.cornerRadius = frame.height / 10 btn.tag = i btn.setImage(UIImage(named: img), forState: .Normal) btn.addTarget(self, action: #selector(ImageWidget.show(_:)), forControlEvents: .TouchUpInside) self.addSubview(btn) } } func show(sender: UIButton) { let imageInfo = JTSImageInfo() imageInfo.image = UIImage(named: self.images[sender.tag]) imageInfo.referenceRect = self.frame imageInfo.referenceView = self.superview // Setup view controller let imageViewer = JTSImageViewController(imageInfo: imageInfo, mode: JTSImageViewControllerMode.Image, backgroundStyle: JTSImageViewControllerBackgroundOptions.Scaled) // Present the view controller. imageViewer.showFromViewController(parent, transition:JTSImageViewControllerTransition.FromOriginalPosition) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
gpl-2.0
387514ebf84489b861cb715355634605
34.701754
175
0.643243
4.414317
false
false
false
false
wcochran/solitaire-iOS
Solitaire/AppDelegate.swift
1
3004
// // AppDelegate.swift // Solitaire // // Created by Wayne Cochran on 4/3/16. // Copyright © 2016 Wayne Cochran. All rights reserved. // import UIKit func sandboxArchivePath() -> String { let dir : NSString = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first! as NSString let path = dir.appendingPathComponent("solitaire.plist") return path } @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var solitaire : Solitaire! func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. let archiveName = sandboxArchivePath() if FileManager.default.fileExists(atPath: archiveName) { let dict = NSDictionary(contentsOfFile: archiveName) as! [String : AnyObject] solitaire = Solitaire(dictionary: dict) } else { solitaire = Solitaire() solitaire.freshGame() } return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. let archiveName = sandboxArchivePath() let dict : NSDictionary = solitaire.toDictionary() as NSDictionary dict.write(toFile: archiveName, atomically: true) } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
40be9134ae65635dab71acd4eb1dfec0
43.820896
285
0.724276
5.352941
false
false
false
false
YuantongL/Cross-Train
ICrossCommander/GameViewController.swift
1
2791
// // GameViewController.swift // ICrossCommander // // Created by Lyt on 9/8/14. // Copyright (c) 2014 Lyt. All rights reserved. // //This class is the view controller of all scenes, init all secenes and store them in the bank import UIKit import SpriteKit extension SKNode { class func unarchiveFromFile(file : NSString) -> SKNode? { if let path = NSBundle.mainBundle().pathForResource(file as String, ofType: "sks") { var sceneData = NSData(contentsOfFile: path, options: .DataReadingMappedIfSafe, error: nil) var archiver = NSKeyedUnarchiver(forReadingWithData: sceneData!) archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene") let scene = archiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey) as! GameScene archiver.finishDecoding() return scene } else { return nil } } } class GameViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() if let scene = GameScene.unarchiveFromFile("GameScene") as? GameScene { // Configure the view. Bank.storeScene(Mainplay.init(size: CGSizeMake(scene.frame.width, scene.frame.height)), x: 2) Bank.storeScene(gallary.init(size: CGSizeMake(scene.frame.width, scene.frame.height)), x: 3) Bank.storeScene(metric.init(size: CGSizeMake(scene.frame.width, scene.frame.height)), x: 4) Bank.storeScene(leaderboard.init(size: CGSizeMake(scene.frame.width, scene.frame.height)), x: 5) Bank.storeScene(missionselect.init(size: CGSizeMake(scene.frame.width, scene.frame.height)), x: 6) let skView = self.view as! SKView skView.showsFPS = true skView.showsNodeCount = true /* Sprite Kit applies additional optimizations to improve rendering performance */ skView.ignoresSiblingOrder = true /* Set the scale mode to scale to fit the window */ scene.scaleMode = .AspectFill skView.presentScene(scene) } } override func shouldAutorotate() -> Bool { return true } override func supportedInterfaceOrientations() -> Int { if UIDevice.currentDevice().userInterfaceIdiom == .Phone { return Int(UIInterfaceOrientationMask.AllButUpsideDown.rawValue) } else { return Int(UIInterfaceOrientationMask.All.rawValue) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Release any cached data, images, etc that aren't in use. } override func prefersStatusBarHidden() -> Bool { return true } }
mit
e70a801ebb4b80d63e9a551b8299f079
35.723684
110
0.639197
4.957371
false
false
false
false
Rostmen/TimelineController
RZTimelineCollection/RZAvatar.swift
1
3120
// // RZAvatarImageDataSource.swift // RZTimelineCollection // // Created by Rostyslav Kobizsky on 12/23/14. // Copyright (c) 2014 Rozdoum. All rights reserved. // import UIKit import ObjectiveC @objc protocol RZAvatarImageDataSource { /** * @return The avatar image for a regular display state. * * @discussion You may return `nil` from this method while the image is being downloaded. */ var avatarImage: UIImage? { get } /** * @return The avatar image for a highlighted display state. * * @discussion You may return `nil` from this method if this does not apply. */ var avatarHighlightedImage: UIImage? { get } /** * @return A placeholder avatar image to be displayed if avatarImage is not yet available, or `nil`. * For example, if avatarImage needs to be downloaded, this placeholder image * will be used until avatarImage is not `nil`. * * @discussion If you do not need support for a placeholder image, that is, your images * are stored locally on the device, then you may simply return the same value as avatarImage here. * * @warning You must not return `nil` from this method. */ var avatarPlaceholderImage: UIImage { get } } class RZAvatarImage: NSObject, RZAvatarImageDataSource, NSCopying { /** * @return The avatar image for a regular display state. * * @discussion You may return `nil` from this method while the image is being downloaded. */ var avatarImage: UIImage? /** * @return The avatar image for a highlighted display state. * * @discussion You may return `nil` from this method if this does not apply. */ var avatarHighlightedImage: UIImage? /** * @return A placeholder avatar image to be displayed if avatarImage is not yet available, or `nil`. * For example, if avatarImage needs to be downloaded, this placeholder image * will be used until avatarImage is not `nil`. * * @discussion If you do not need support for a placeholder image, that is, your images * are stored locally on the device, then you may simply return the same value as avatarImage here. * * @warning You must not return `nil` from this method. */ var avatarPlaceholderImage: UIImage init(image: UIImage?, highlightImage: UIImage?, placeholderImage: UIImage) { avatarImage = image avatarHighlightedImage = highlightImage avatarPlaceholderImage = placeholderImage } convenience init(image: UIImage) { self.init(image: image, highlightImage: image, placeholderImage: image) } convenience init(placeholder: UIImage) { self.init(image: nil, highlightImage: nil, placeholderImage: placeholder) } // MARK: NSCopying func copyWithZone(zone: NSZone) -> AnyObject { let copy = RZAvatarImage.allocWithZone(zone) copy.avatarImage = avatarImage copy.avatarHighlightedImage = avatarHighlightedImage copy.avatarPlaceholderImage = avatarPlaceholderImage return copy } }
apache-2.0
ee803c6d9cc370c310751b91f33f557d
33.677778
104
0.676923
4.635958
false
false
false
false
khanirteza/fusion
Fusion/Fusion/CoreDataStack.swift
2
2604
// // CoreDataStack.swift // Fusion // // Created by Mohammad Irteza Khan on 7/30/17. // Copyright © 2017 Mohammad Irteza Khan. All rights reserved. // import Foundation import CoreData class CoreDataStack{ static let sharedCoreDataStack = CoreDataStack() private init(){ } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "FusionDatabase") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
apache-2.0
e3af8326353187618d8646b3cf12c8c1
40.31746
199
0.62159
5.746137
false
false
false
false
justwudi/WDStarRatingView
WDStarRatingView.swift
1
12173
// WDStarRatingView.swift // // Copyright (c) 2015 Wu Di, Sudeep Agarwal and Hugo Sousa // // 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 @objc public protocol WDStarRatingDelegate { optional func starRatingView(starRatingView: WDStarRatingView, didDrawStarsWithValue value: CGFloat) optional func starRatingView(starRatingView: WDStarRatingView, didUpdateToValue value: CGFloat) optional func starRatingView(starRatingView: WDStarRatingView, didStartTracking tracking: Bool) optional func starRatingView(starRatingView: WDStarRatingView, didStopTracking tracking: Bool) } @IBDesignable public class WDStarRatingView: UIControl { private var _minimumValue: Int! private var _maximumValue: Int! private var _value: CGFloat! private var _spacing: CGFloat! private var _previousValue: CGFloat? private var _arrayOfFrames: [CGRect]! private var _allowsHalfStars = true // MARK: Initialization override public init(frame: CGRect) { super.init(frame: frame) _customInit() } required public init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) _customInit() } private func _customInit() { self.backgroundColor = UIColor.clearColor() self.exclusiveTouch = true _minimumValue = 1 _maximumValue = 5 _value = 0 _spacing = 5 _arrayOfFrames = [] } // MARK: Properties public var delegate: WDStarRatingDelegate? @IBInspectable public var allowsHalfStars: Bool { get { return _allowsHalfStars } set { _allowsHalfStars = newValue } } @IBInspectable public var minimumValue: Int { get { return max(_minimumValue, 0) } set { if _minimumValue != newValue { _minimumValue = newValue self.setNeedsDisplay() } } } @IBInspectable public var maximumValue: Int { get { return max(_minimumValue, _maximumValue) } set { if _maximumValue != newValue { _maximumValue = newValue self.setNeedsDisplay() self.invalidateIntrinsicContentSize() } } } @IBInspectable public var value: CGFloat { get { return min(max(_value, CGFloat(_minimumValue)), CGFloat(_maximumValue)) } set { if _value != newValue { _value = newValue self.sendActionsForControlEvents(.ValueChanged) self.setNeedsDisplay() } } } @IBInspectable public var spacing: CGFloat { get { return _spacing } set { _spacing = max(newValue, 0) self.setNeedsDisplay() } } // MARK: Drawing private func _drawStarWithFrame(frame: CGRect, tintColor: UIColor, highlighted: Bool) { var starShapePath = UIBezierPath() starShapePath.moveToPoint(CGPointMake(CGRectGetMinX(frame) + 0.62723 * CGRectGetWidth(frame), CGRectGetMinY(frame) + 0.37309 * CGRectGetHeight(frame))) starShapePath.addLineToPoint(CGPointMake(CGRectGetMinX(frame) + 0.50000 * CGRectGetWidth(frame), CGRectGetMinY(frame) + 0.02500 * CGRectGetHeight(frame))) starShapePath.addLineToPoint(CGPointMake(CGRectGetMinX(frame) + 0.37292 * CGRectGetWidth(frame), CGRectGetMinY(frame) + 0.37309 * CGRectGetHeight(frame))) starShapePath.addLineToPoint(CGPointMake(CGRectGetMinX(frame) + 0.02500 * CGRectGetWidth(frame), CGRectGetMinY(frame) + 0.39112 * CGRectGetHeight(frame))) starShapePath.addLineToPoint(CGPointMake(CGRectGetMinX(frame) + 0.30504 * CGRectGetWidth(frame), CGRectGetMinY(frame) + 0.62908 * CGRectGetHeight(frame))) starShapePath.addLineToPoint(CGPointMake(CGRectGetMinX(frame) + 0.20642 * CGRectGetWidth(frame), CGRectGetMinY(frame) + 0.97500 * CGRectGetHeight(frame))) starShapePath.addLineToPoint(CGPointMake(CGRectGetMinX(frame) + 0.50000 * CGRectGetWidth(frame), CGRectGetMinY(frame) + 0.78265 * CGRectGetHeight(frame))) starShapePath.addLineToPoint(CGPointMake(CGRectGetMinX(frame) + 0.79358 * CGRectGetWidth(frame), CGRectGetMinY(frame) + 0.97500 * CGRectGetHeight(frame))) starShapePath.addLineToPoint(CGPointMake(CGRectGetMinX(frame) + 0.69501 * CGRectGetWidth(frame), CGRectGetMinY(frame) + 0.62908 * CGRectGetHeight(frame))) starShapePath.addLineToPoint(CGPointMake(CGRectGetMinX(frame) + 0.97500 * CGRectGetWidth(frame), CGRectGetMinY(frame) + 0.39112 * CGRectGetHeight(frame))) starShapePath.addLineToPoint(CGPointMake(CGRectGetMinX(frame) + 0.62723 * CGRectGetWidth(frame), CGRectGetMinY(frame) + 0.37309 * CGRectGetHeight(frame))) starShapePath.closePath() starShapePath.miterLimit = 4; if highlighted { tintColor.setFill() starShapePath.fill() } tintColor.setStroke() starShapePath.lineWidth = 1 starShapePath.stroke() } private func _drawHalfStarWithFrame(frame: CGRect, tintColor: UIColor, highlighted: Bool) { var starShapePath = UIBezierPath() starShapePath.moveToPoint(CGPointMake(CGRectGetMinX(frame) + 0.50000 * CGRectGetWidth(frame), CGRectGetMinY(frame) + 0.02500 * CGRectGetHeight(frame))) starShapePath.addLineToPoint(CGPointMake(CGRectGetMinX(frame) + 0.37292 * CGRectGetWidth(frame), CGRectGetMinY(frame) + 0.37309 * CGRectGetHeight(frame))) starShapePath.addLineToPoint(CGPointMake(CGRectGetMinX(frame) + 0.02500 * CGRectGetWidth(frame), CGRectGetMinY(frame) + 0.39112 * CGRectGetHeight(frame))) starShapePath.addLineToPoint(CGPointMake(CGRectGetMinX(frame) + 0.30504 * CGRectGetWidth(frame), CGRectGetMinY(frame) + 0.62908 * CGRectGetHeight(frame))) starShapePath.addLineToPoint(CGPointMake(CGRectGetMinX(frame) + 0.20642 * CGRectGetWidth(frame), CGRectGetMinY(frame) + 0.97500 * CGRectGetHeight(frame))) starShapePath.addLineToPoint(CGPointMake(CGRectGetMinX(frame) + 0.50000 * CGRectGetWidth(frame), CGRectGetMinY(frame) + 0.78265 * CGRectGetHeight(frame))) starShapePath.addLineToPoint(CGPointMake(CGRectGetMinX(frame) + 0.50000 * CGRectGetWidth(frame), CGRectGetMinY(frame) + 0.02500 * CGRectGetHeight(frame))) starShapePath.closePath() starShapePath.miterLimit = 4; if highlighted { tintColor.setFill() starShapePath.fill() } tintColor.setStroke() starShapePath.lineWidth = 1; starShapePath.stroke() } public override func drawRect(rect: CGRect) { var context = UIGraphicsGetCurrentContext() CGContextSetFillColorWithColor(context, self.backgroundColor!.CGColor) CGContextFillRect(context, rect); let availableWidth = rect.size.width - (_spacing * CGFloat(_maximumValue + 1)) let cellWidth = (availableWidth / CGFloat(_maximumValue)) let starSide = (cellWidth <= rect.size.height) ? cellWidth : rect.size.height for index in 0..<_maximumValue { let idx = CGFloat(index) let center = CGPointMake( cellWidth * idx + cellWidth / 2 + _spacing * (idx + 1), rect.size.height / 2 ) let frame = CGRectMake(center.x - starSide / 2, center.y - starSide / 2, starSide, starSide) let highlighted = idx + 1 <= ceil(_value) let halfStar = highlighted ? (idx + 1 > _value) : false if halfStar && _allowsHalfStars { self._drawStarWithFrame(frame, tintColor: self.tintColor, highlighted: false) self._drawHalfStarWithFrame(frame, tintColor: self.tintColor, highlighted: highlighted) } else { self._drawStarWithFrame(frame, tintColor: self.tintColor, highlighted: highlighted) } self._arrayOfFrames.append(frame) } self.delegate?.starRatingView?(self, didDrawStarsWithValue: _value) } public override func setNeedsLayout() { super.setNeedsLayout() self.setNeedsDisplay() } public func starForValue(value: CGFloat) -> CGRect? { if value > 0 && value <= CGFloat(maximumValue) { return self._arrayOfFrames[Int(value + 0.5) - 1] } else if value == 0 { return self._arrayOfFrames.first } else { return nil } } // MARK: Touches public override func beginTrackingWithTouch(touch: UITouch, withEvent event: UIEvent) -> Bool { super.beginTrackingWithTouch(touch, withEvent: event) if !self.isFirstResponder() { self.becomeFirstResponder() } _previousValue = _value self._handleTouch(touch) self.delegate?.starRatingView?(self, didStartTracking: true) return true } public override func continueTrackingWithTouch(touch: UITouch, withEvent event: UIEvent) -> Bool { super.continueTrackingWithTouch(touch, withEvent: event) self._handleTouch(touch) return true } public override func endTrackingWithTouch(touch: UITouch, withEvent event: UIEvent) { super.endTrackingWithTouch(touch, withEvent: event) if self.isFirstResponder() { self.resignFirstResponder() } self._handleTouch(touch) if _value != _previousValue { self.sendActionsForControlEvents(.ValueChanged) } self.delegate?.starRatingView?(self, didStopTracking: true) } public override func cancelTrackingWithEvent(event: UIEvent?) { super.cancelTrackingWithEvent(event) if self.isFirstResponder() { self.resignFirstResponder() } } public override func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool { return !self.userInteractionEnabled } private func _handleTouch(touch: UITouch) { let cellWidth = self.bounds.size.width / CGFloat(_maximumValue) let location = touch.locationInView(self) let value = location.x / cellWidth if _allowsHalfStars && value + 0.5 < ceil(value) { _value = floor(value) + 0.5 } else { _value = ceil(value) } self.setNeedsDisplay() self.delegate?.starRatingView?(self, didUpdateToValue: _value) } // MARK: First Responder public override func canBecomeFirstResponder() -> Bool { return true } // MARK: Intrinsic Content Size public override func intrinsicContentSize() -> CGSize { let height: CGFloat = 44 return CGSizeMake( CGFloat(_maximumValue) * height + CGFloat(_maximumValue + 1) * _spacing, height ) } }
mit
bdfcb3a4efc7e12b5f7f9d8bf4fc20c5
36.458462
104
0.646595
4.958452
false
false
false
false
daxiangfei/RTSwiftUtils
RTSwiftUtils/Extension/ColorExtension.swift
1
1913
// // ColorExtension.swift // XiaoZhuGeJinFu // // Created by rongteng on 16/6/21. // Copyright © 2016年 rongteng. All rights reserved. // import UIKit public extension UIColor { /// 直接填入rbg的值 public class func rgbValue(red:CGFloat, green:CGFloat, blue:CGFloat, alpha:CGFloat = 1.0) -> UIColor { return UIColor(red: red/255, green: green/255, blue: blue/255, alpha: alpha) } /// rbg各自的值是相同的 public class func rgbValue(sameValue:CGFloat,alpha:CGFloat = 1.0) -> UIColor { return UIColor(red: sameValue/255, green: sameValue/255, blue: sameValue/255, alpha: alpha) } /// color with hex public convenience init(hexValue: UInt, alpha: CGFloat = 1) { self.init( red: CGFloat((hexValue & 0xFF0000) >> 16) / 255.0, green: CGFloat((hexValue & 0x00FF00) >> 8) / 255.0, blue: CGFloat(hexValue & 0x0000FF) / 255.0, alpha: alpha ) } /// 传入16进制的字符串值 如 "FF45BD" public convenience init(hexStr: String,alpha: CGFloat = 1) { var rValue:UInt64 = 0 var gValue:UInt64 = 0 var bValue:UInt64 = 0 if hexStr.count == 6 { let cString = hexStr.trimmingCharacters(in: .whitespacesAndNewlines).uppercased() let oneindex = cString.index(cString.startIndex, offsetBy: 2) let fourindex = cString.index(oneindex, offsetBy: 2) let sixindex = cString.index(fourindex, offsetBy: 2) let r = cString[cString.startIndex ..< oneindex] let g = cString[oneindex ..< fourindex] let b = cString[fourindex ..< sixindex] Scanner(string: String(r)).scanHexInt64(&rValue) Scanner(string: String(g)).scanHexInt64(&gValue) Scanner(string: String(b)).scanHexInt64(&bValue) } self.init(red: CGFloat(rValue)/255, green: CGFloat(gValue)/255, blue: CGFloat(bValue)/255, alpha: alpha ) } }
mit
0a2b50fb0b652022608b2119efd9ccb7
26.382353
104
0.641246
3.493433
false
false
false
false
shahmishal/swift
test/Constraints/dictionary_literal.swift
1
5717
// RUN: %target-typecheck-verify-swift final class DictStringInt : ExpressibleByDictionaryLiteral { typealias Key = String typealias Value = Int init(dictionaryLiteral elements: (String, Int)...) { } } final class MyDictionary<K, V> : ExpressibleByDictionaryLiteral { typealias Key = K typealias Value = V init(dictionaryLiteral elements: (K, V)...) { } } func useDictStringInt(_ d: DictStringInt) {} func useDict<K, V>(_ d: MyDictionary<K,V>) {} // Concrete dictionary literals. useDictStringInt(["Hello" : 1]) useDictStringInt(["Hello" : 1, "World" : 2]) useDictStringInt(["Hello" : 1, "World" : 2.5]) // expected-error@-1 {{cannot convert value of type 'Double' to expected dictionary value type 'DictStringInt.Value' (aka 'Int')}} useDictStringInt([4.5 : 2]) // expected-error@-1 {{cannot convert value of type 'Double' to expected dictionary key type 'DictStringInt.Key' (aka 'String')}} useDictStringInt([nil : 2]) // expected-error@-1 {{'nil' is not compatible with expected dictionary key type 'String'}} useDictStringInt([7 : 1, "World" : 2]) // expected-error@-1 {{cannot convert value of type 'Int' to expected dictionary key type 'DictStringInt.Key' (aka 'String')}} useDictStringInt(["Hello" : nil]) // expected-error@-1 {{'nil' is not compatible with expected dictionary value type 'Int'}} typealias FuncBoolToInt = (Bool) -> Int let dict1: MyDictionary<String, FuncBoolToInt> = ["Hello": nil] // expected-error@-1 {{'nil' is not compatible with expected dictionary value type '(Bool) -> Int'}} // Generic dictionary literals. useDict(["Hello" : 1]) useDict(["Hello" : 1, "World" : 2]) useDict(["Hello" : 1.5, "World" : 2]) useDict([1 : 1.5, 3 : 2.5]) // Fall back to Swift.Dictionary<K, V> if no context is otherwise available. var a = ["Hello" : 1, "World" : 2] var a2 : Dictionary<String, Int> = a var a3 = ["Hello" : 1] var b = [1 : 2, 1.5 : 2.5] var b2 : Dictionary<Double, Double> = b var b3 = [1 : 2.5] // <rdar://problem/22584076> QoI: Using array literal init with dictionary produces bogus error // expected-note @+1 {{did you mean to use a dictionary literal instead?}} var _: MyDictionary<String, (Int) -> Int>? = [ // expected-error {{dictionary of type 'MyDictionary<String, (Int) -> Int>' cannot be initialized with array literal}} "closure_1" as String, {(Int) -> Int in 0}, "closure_2", {(Int) -> Int in 0}] var _: MyDictionary<String, Int>? = ["foo", 1] // expected-error {{dictionary of type 'MyDictionary<String, Int>' cannot be initialized with array literal}} // expected-note @-1 {{did you mean to use a dictionary literal instead?}} {{43-44=:}} var _: MyDictionary<String, Int>? = ["foo", 1, "bar", 42] // expected-error {{dictionary of type 'MyDictionary<String, Int>' cannot be initialized with array literal}} // expected-note @-1 {{did you mean to use a dictionary literal instead?}} {{43-44=:}} {{53-54=:}} var _: MyDictionary<String, Int>? = ["foo", 1.0, 2] // expected-error {{cannot convert value of type '[Double]' to specified type 'MyDictionary<String, Int>?'}} // expected-error@-1 {{cannot convert value of type 'String' to expected element type 'Double'}} var _: MyDictionary<String, Int>? = ["foo" : 1.0] // expected-error {{cannot convert value of type 'Double' to expected dictionary value type 'Int'}} // <rdar://problem/24058895> QoI: Should handle [] in dictionary contexts better var _: [Int: Int] = [] // expected-error {{use [:] to get an empty dictionary literal}} {{22-22=:}} class A { } class B : A { } class C : A { } func testDefaultExistentials() { let _ = ["a" : 1, "b" : 2.5, "c" : "hello"] // expected-error@-1{{heterogeneous collection literal could only be inferred to '[String : Any]'; add explicit type annotation if this is intentional}}{{46-46= as [String : Any]}} let _: [String : Any] = ["a" : 1, "b" : 2.5, "c" : "hello"] let _ = ["a" : 1, "b" : nil, "c" : "hello"] // expected-error@-1{{heterogeneous collection literal could only be inferred to '[String : Any?]'; add explicit type annotation if this is intentional}}{{46-46= as [String : Any?]}} let _: [String : Any?] = ["a" : 1, "b" : nil, "c" : "hello"] let d2 = [:] // expected-error@-1{{empty collection literal requires an explicit type}} let _: Int = d2 // expected-error{{value of type '[AnyHashable : Any]'}} let _ = ["a": 1, "b": ["a", 2, 3.14159], "c": ["a": 2, "b": 3.5]] // expected-error@-3{{heterogeneous collection literal could only be inferred to '[String : Any]'; add explicit type annotation if this is intentional}} let d3 = ["b" : B(), "c" : C()] let _: Int = d3 // expected-error{{value of type '[String : A]'}} let _ = ["a" : B(), 17 : "seventeen", 3.14159 : "Pi"] // expected-error@-1{{heterogeneous collection literal could only be inferred to '[AnyHashable : Any]'}} let _ = ["a" : "hello", 17 : "string"] // expected-error@-1{{heterogeneous collection literal could only be inferred to '[AnyHashable : String]'}} } // SR-4952, rdar://problem/32330004 - Assertion failure during swift::ASTVisitor<::FailureDiagnosis,...>::visit func rdar32330004_1() -> [String: Any] { return ["a""one": 1, "two": 2, "three": 3] // expected-note {{did you mean to use a dictionary literal instead?}} // expected-error@-1 {{expected ',' separator}} // expected-error@-2 {{dictionary of type '[String : Any]' cannot be used with array literal}} } func rdar32330004_2() -> [String: Any] { return ["a", 0, "one", 1, "two", 2, "three", 3] // expected-error@-1 {{dictionary of type '[String : Any]' cannot be used with array literal}} // expected-note@-2 {{did you mean to use a dictionary literal instead?}} {{14-15=:}} {{24-25=:}} {{34-35=:}} {{46-47=:}} }
apache-2.0
da0f4e7599ca3eec30e79320b997aa1e
45.860656
184
0.650516
3.47116
false
false
false
false
sahara108/Utility
FileProvider/Network/FileProviderNetwork.swift
1
4292
// // FileProviderNetwork.swift // cacom.info // // Created by Nguyen Tuan on 3/15/17. // Copyright © 2017 Cacom.info. All rights reserved. // public enum FileProviderNetworkError: CustomNSError { /// The domain of the error. public static var errorDomain: String { get { return "FileProviderNetworkManagementDomain" } } case uploadFail } public protocol FileProviderNetwork { typealias FTPProgressReport = (Float) -> () typealias FTPFinalResport = (String?, FileProviderNetworkError?) -> () @discardableResult func startUploadFile(filePath: URL, toURL: URL, given objectName: String, progress: FTPProgressReport?, completion: FTPFinalResport?) -> UploadTask @discardableResult func startUpload(data: Data, toURL: URL, given objectName: String, progress: FTPProgressReport?, completion: FTPFinalResport?) -> UploadTask @discardableResult func downloadFile(fromURL: URL, destinationPath: URL?, progress: FTPProgressReport?, completion: FTPFinalResport?) -> DownloadTask func wipe() } public class FileProviderNetworkImpl: FileProviderNetwork { private var uploadQueue = OperationQueue() private var downloadQueue = OperationQueue() init() { uploadQueue.maxConcurrentOperationCount = 2 downloadQueue.maxConcurrentOperationCount = 2 } /// Upload a local file to a given url. It will creates a background session for the uploading. By default, the request will uses PUT method. /// /// - Parameters: /// - filePath: the location of the file /// - toURL: destination URL where we want to upload the file /// - objectName: an unique value can be used for identifiying the request and will be sent back on completion /// - progress: report about uploading progress /// - completion: end of uploading progress. See `FTPFinalResport` @discardableResult public func startUploadFile(filePath: URL, toURL: URL, given objectName: String, progress: FTPProgressReport?, completion: FTPFinalResport?) -> UploadTask { let task = UploadTask(fileURL: filePath, toURL: toURL, progress: progress, completion: completion) task.postedValue = objectName uploadQueue.addOperation(task) return task } /// Upload file data to a given url. It will creates a background session for the uploading. By default, the request will uses PUT method. /// /// - Parameters: /// - data: data to be uploaded /// - toURL: destination URL where we want to upload the file /// - objectName: an unique value can be used for identifiying the request and will be sent back on completion /// - progress: report about uploading progress /// - completion: end of uploading progress. See `FTPFinalResport` @discardableResult public func startUpload(data: Data, toURL: URL, given objectName: String, progress: FTPProgressReport?, completion: FTPFinalResport?) -> UploadTask { let task = UploadTask(fileData: data, toURL: toURL, progress: progress, completion: completion) task.postedValue = objectName uploadQueue.addOperation(task) return task } /// Download file from a given url. It will creates a background session for the downloading. Please note it will creates many diiferential sessions even if you try to download a single from many times /// /// - Parameters: /// - fromURL: given url /// - destinationPath: expected location for downloaded file. This path is expected to be returned in completion but it can returns a different path if there is an error while moving the file around /// - progress: report about downloading progress /// - completion: end of downloading progress. @discardableResult public func downloadFile(fromURL: URL, destinationPath: URL?, progress: FTPProgressReport?, completion: FTPFinalResport?) -> DownloadTask { let task = DownloadTask(downloadURL: fromURL, destinationPath: destinationPath, progress: progress, completion: completion) downloadQueue.addOperation(task) return task } public func wipe() { uploadQueue.cancelAllOperations() downloadQueue.cancelAllOperations() } }
mit
cd09bffaa15cede10e24b0a96c97cbba
43.697917
205
0.7024
4.837655
false
false
false
false
practicalswift/swift
stdlib/public/core/Dump.swift
10
7454
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// /// Dumps the given object's contents using its mirror to the specified output /// stream. /// /// - Parameters: /// - value: The value to output to the `target` stream. /// - target: The stream to use for writing the contents of `value`. /// - name: A label to use when writing the contents of `value`. When `nil` /// is passed, the label is omitted. The default is `nil`. /// - indent: The number of spaces to use as an indent for each line of the /// output. The default is `0`. /// - maxDepth: The maximum depth to descend when writing the contents of a /// value that has nested components. The default is `Int.max`. /// - maxItems: The maximum number of elements for which to write the full /// contents. The default is `Int.max`. /// - Returns: The instance passed as `value`. @discardableResult @_semantics("optimize.sil.specialize.generic.never") public func dump<T, TargetStream : TextOutputStream>( _ value: T, to target: inout TargetStream, name: String? = nil, indent: Int = 0, maxDepth: Int = .max, maxItems: Int = .max ) -> T { var maxItemCounter = maxItems var visitedItems = [ObjectIdentifier : Int]() target._lock() defer { target._unlock() } _dump_unlocked( value, to: &target, name: name, indent: indent, maxDepth: maxDepth, maxItemCounter: &maxItemCounter, visitedItems: &visitedItems) return value } /// Dumps the given object's contents using its mirror to standard output. /// /// - Parameters: /// - value: The value to output to the `target` stream. /// - name: A label to use when writing the contents of `value`. When `nil` /// is passed, the label is omitted. The default is `nil`. /// - indent: The number of spaces to use as an indent for each line of the /// output. The default is `0`. /// - maxDepth: The maximum depth to descend when writing the contents of a /// value that has nested components. The default is `Int.max`. /// - maxItems: The maximum number of elements for which to write the full /// contents. The default is `Int.max`. /// - Returns: The instance passed as `value`. @discardableResult @_semantics("optimize.sil.specialize.generic.never") public func dump<T>( _ value: T, name: String? = nil, indent: Int = 0, maxDepth: Int = .max, maxItems: Int = .max ) -> T { var stdoutStream = _Stdout() return dump( value, to: &stdoutStream, name: name, indent: indent, maxDepth: maxDepth, maxItems: maxItems) } /// Dump an object's contents. User code should use dump(). @_semantics("optimize.sil.specialize.generic.never") internal func _dump_unlocked<TargetStream : TextOutputStream>( _ value: Any, to target: inout TargetStream, name: String?, indent: Int, maxDepth: Int, maxItemCounter: inout Int, visitedItems: inout [ObjectIdentifier : Int] ) { guard maxItemCounter > 0 else { return } maxItemCounter -= 1 for _ in 0..<indent { target.write(" ") } let mirror = Mirror(reflecting: value) let count = mirror.children.count let bullet = count == 0 ? "-" : maxDepth <= 0 ? "▹" : "▿" target.write(bullet) target.write(" ") if let name = name { target.write(name) target.write(": ") } // This takes the place of the old mirror API's 'summary' property _dumpPrint_unlocked(value, mirror, &target) let id: ObjectIdentifier? if type(of: value) is AnyObject.Type { // Object is a class (but not an ObjC-bridged struct) id = ObjectIdentifier(_unsafeDowncastToAnyObject(fromAny: value)) } else if let metatypeInstance = value as? Any.Type { // Object is a metatype id = ObjectIdentifier(metatypeInstance) } else { id = nil } if let theId = id { if let previous = visitedItems[theId] { target.write(" #") _print_unlocked(previous, &target) target.write("\n") return } let identifier = visitedItems.count visitedItems[theId] = identifier target.write(" #") _print_unlocked(identifier, &target) } target.write("\n") guard maxDepth > 0 else { return } if let superclassMirror = mirror.superclassMirror { _dumpSuperclass_unlocked( mirror: superclassMirror, to: &target, indent: indent + 2, maxDepth: maxDepth - 1, maxItemCounter: &maxItemCounter, visitedItems: &visitedItems) } var currentIndex = mirror.children.startIndex for i in 0..<count { if maxItemCounter <= 0 { for _ in 0..<(indent+4) { _print_unlocked(" ", &target) } let remainder = count - i target.write("(") _print_unlocked(remainder, &target) if i > 0 { target.write(" more") } if remainder == 1 { target.write(" child)\n") } else { target.write(" children)\n") } return } let (name, child) = mirror.children[currentIndex] mirror.children.formIndex(after: &currentIndex) _dump_unlocked( child, to: &target, name: name, indent: indent + 2, maxDepth: maxDepth - 1, maxItemCounter: &maxItemCounter, visitedItems: &visitedItems) } } /// Dump information about an object's superclass, given a mirror reflecting /// that superclass. @_semantics("optimize.sil.specialize.generic.never") internal func _dumpSuperclass_unlocked<TargetStream : TextOutputStream>( mirror: Mirror, to target: inout TargetStream, indent: Int, maxDepth: Int, maxItemCounter: inout Int, visitedItems: inout [ObjectIdentifier : Int] ) { guard maxItemCounter > 0 else { return } maxItemCounter -= 1 for _ in 0..<indent { target.write(" ") } let count = mirror.children.count let bullet = count == 0 ? "-" : maxDepth <= 0 ? "▹" : "▿" target.write(bullet) target.write(" super: ") _debugPrint_unlocked(mirror.subjectType, &target) target.write("\n") guard maxDepth > 0 else { return } if let superclassMirror = mirror.superclassMirror { _dumpSuperclass_unlocked( mirror: superclassMirror, to: &target, indent: indent + 2, maxDepth: maxDepth - 1, maxItemCounter: &maxItemCounter, visitedItems: &visitedItems) } var currentIndex = mirror.children.startIndex for i in 0..<count { if maxItemCounter <= 0 { for _ in 0..<(indent+4) { target.write(" ") } let remainder = count - i target.write("(") _print_unlocked(remainder, &target) if i > 0 { target.write(" more") } if remainder == 1 { target.write(" child)\n") } else { target.write(" children)\n") } return } let (name, child) = mirror.children[currentIndex] mirror.children.formIndex(after: &currentIndex) _dump_unlocked( child, to: &target, name: name, indent: indent + 2, maxDepth: maxDepth - 1, maxItemCounter: &maxItemCounter, visitedItems: &visitedItems) } }
apache-2.0
54877aa1b4f96ba0054fee0a5b7424a7
28.903614
80
0.628525
4.084476
false
false
false
false
justinmakaila/JSONMapping
JSONMapping/NSManagedObject+JSONMapping.swift
1
15948
import CoreData import RemoteMapping extension NSManagedObject: JSONRepresentable, JSONValidator, JSONParser { open func isValid(json: JSONObject) -> Bool { return true } open func parseJSON(json: JSONObject, propertyDescription: NSPropertyDescription) -> Any? { return json[propertyDescription.remotePropertyName] } /// Merges `self` with `json` if the JSONObject is valid or /// if the `force` flag is set. /// /// - Parameters: /// - json: The `JSONObject` to sync with. /// - dateFormatter: A `JSONDateFormatter` to be used for serialzing Dates from JSON. If none is provided, /// no dates will be processed from the JSON. /// - parent: The parent of the object. Used for inverse relationships. /// - force: Force merge of `json` open func merge(withJSON json: JSONObject, dateFormatter: JSONDateFormatter? = nil, parent: NSManagedObject? = nil, force: Bool = false) { if isValid(json: json) || force { willSyncWithJSON(json: json) sync(scalarValuesWithJSON: json, dateFormatter: dateFormatter) sync(relationshipsWithJSON: json, dateFormatter: dateFormatter, parent: parent) didSyncWithJSON(success: true) } else { didSyncWithJSON(success: false) } } /// Serializes a `NSManagedObject` to a JSONObject, using the remote properties. /// /// - Parameters: /// - parent: The parent of the object. /// - relationshipType: Flag indicating what type of relationships to use. /// - excludeKeys: The names of properties to be removed. Should be the name of the property in your data model, /// not the remote property name. /// public func toJSON(relationshipType: RelationshipType = .embedded, excludeKeys: Set<String> = [], includeNilValues: Bool = true, dateFormatter: JSONDateFormatter? = nil, parent: NSManagedObject? = nil) -> JSONObject { return jsonObjectForProperties( entity.remoteProperties, dateFormatter: dateFormatter, parent: parent, relationshipType: relationshipType, excludeKeys: excludeKeys, includeNilValues: includeNilValues ) } /// Serializes a `NSManagedObject` to a JSONObject representing only the changed properties, as specified by the /// RemoteMapping implementation /// /// - Parameters: /// - parent: The parent of the object. /// - relationshipType: Flag indicating what type of relationships to use. /// - excludeKeys: The names of properties to be removed. Should be the name of the property in your data model, /// not the remote property name. /// public func toChangedJSON(relationshipType: RelationshipType = .embedded, excludeKeys: Set<String> = [], includeNilValues: Bool = true, dateFormatter: JSONDateFormatter? = nil, parent: NSManagedObject? = nil) -> JSONObject { let changedPropertyKeys: Set<String> = Set(self.changedValues().keys) let remoteProperties = entity.remoteProperties .filter { changedPropertyKeys.contains($0.name) } return jsonObjectForProperties( remoteProperties, dateFormatter: dateFormatter, parent: parent, relationshipType: relationshipType, excludeKeys: excludeKeys, includeNilValues: includeNilValues ) } /// Hook for when syncing with JSON will start open func willSyncWithJSON(json: JSONObject) { } /// Hook for when finished syncing with JSON open func didSyncWithJSON(success: Bool) { } } private extension NSManagedObject { /// Syncs the scalar values in the JSON to `self` func sync(scalarValuesWithJSON json: JSONObject, dateFormatter: JSONDateFormatter? = nil) { entity.remoteAttributes .forEach { attribute in if let jsonValue = parseJSON(json: json, propertyDescription: attribute) { let attributeValue = attribute.value( fromJSONValue: jsonValue, dateFormatter: dateFormatter ) if let attributeValue = attributeValue { setValue(attributeValue, forKey: attribute.name) } else if attribute.isOptional { setValue(attributeValue, forKey: attribute.name) } } } } func sync(relationshipsWithJSON json: JSONObject, dateFormatter: JSONDateFormatter? = nil, parent: NSManagedObject? = nil) { entity.remoteRelationships .forEach { relationship in if let jsonValue = parseJSON(json: json, propertyDescription: relationship) { if relationship.isToMany { if let collection = jsonValue as? [JSONObject] { sync( toManyRelationship: relationship, withJSON: collection, dateFormatter: dateFormatter, parent: parent ) } else if let primaryKeyCollection = jsonValue as? [String] { /// TODO: Find and insert objects via primary key } else if relationship.isOptional { setValue(nil, forKey: relationship.name) } } else { if let object = jsonValue as? JSONObject { sync( toOneRelationship: relationship, withJSON: object, dateFormatter: dateFormatter ) } else if let primaryKey = jsonValue as? String { /// TODO Find and insert an object via primary key } else if relationship.isOptional { setValue(nil, forKey: relationship.name) } } } } } func sync(toOneRelationship relationship: NSRelationshipDescription, withJSON json: JSONObject, dateFormatter: JSONDateFormatter? = nil) { guard let managedObjectContext = managedObjectContext, let destinationEntity = relationship.destinationEntity, let destinationEntityName = destinationEntity.name, !json.isEmpty else { return } if let remotePrimaryKey = json[destinationEntity.remotePrimaryKeyName] as? String { setValue( managedObjectContext.upsert(json: json, inEntity: destinationEntity, withPrimaryKey: remotePrimaryKey, dateFormatter: dateFormatter), forKey: relationship.name ) } else { guard let object = value(forKey: relationship.name) as? NSManagedObject else { let object = NSEntityDescription.insertNewObject(forEntityName: destinationEntityName, into: managedObjectContext) _ = object.merge(withJSON: json, dateFormatter: dateFormatter) return setValue(object, forKey: relationship.name) } _ = object.merge(withJSON: json, dateFormatter: dateFormatter) } } func sync(toManyRelationship relationship: NSRelationshipDescription, withJSON json: [JSONObject], dateFormatter: JSONDateFormatter? = nil, parent: NSManagedObject? = nil) { guard let managedObjectContext = managedObjectContext, let destinationEntity = relationship.destinationEntity, let destinationEntityName = destinationEntity.name else { return } let inverseIsToMany = relationship.inverseRelationship?.isToMany ?? false if json.count > 0 { var destinationEntityPredicate: NSPredicate? = nil if inverseIsToMany && relationship.isToMany { } else if let inverseEntityName = relationship.inverseRelationship?.name { destinationEntityPredicate = NSPredicate(format: "%K = %@", inverseEntityName, self) } let changes = managedObjectContext.update( entityNamed: destinationEntityName, withJSON: json, dateFormatter: dateFormatter, parent: self, predicate: destinationEntityPredicate ) setValue(Set(changes), forKey: relationship.name) } else if let parent = parent, parent.entity.name == destinationEntityName, inverseIsToMany { if relationship.isOrdered { let relatedObjects = mutableOrderedSetValue(forKey: relationship.name) if !relatedObjects.contains(parent) { relatedObjects.add(parent) setValue(relatedObjects, forKey: relationship.name) } } else { let relatedObjects = mutableSetValue(forKey: relationship.name) if !relatedObjects.contains(parent) { relatedObjects.add(parent) setValue(relatedObjects, forKey: relationship.name) } } } } } private extension NSManagedObject { /// Returns a JSON object. /// /// - Parameters: /// - properties: The properties to use for serialization. /// - parent: The parent of the object. /// - relationshipType: Flag indicating what type of relationships to use. /// - excludeKeys: The names of properties to be removed. Should be the name of the property in your data model, not the remote property name. /// func jsonObjectForProperties(_ properties: [NSPropertyDescription], dateFormatter: JSONDateFormatter? = nil, parent: NSManagedObject? = nil, relationshipType: RelationshipType = .embedded, excludeKeys: Set<String> = [], includeNilValues: Bool = true) -> JSONObject { var jsonObject = JSONObject() properties .filter { !excludeKeys.contains($0.remotePropertyName) } .forEach { propertyDescription in let remoteRelationshipName = propertyDescription.remotePropertyName if let attributeDescription = propertyDescription as? NSAttributeDescription { jsonObject[remoteRelationshipName] = json( valueForAttribute: attributeDescription, dateFormatter: dateFormatter, includeNilValues: includeNilValues ) } else if let relationshipDescription = propertyDescription as? NSRelationshipDescription, relationshipType != .none { /// A valid relationship is one which does not go back up the relationship heirarchy... /// TODO: This condition could be much clearer let isValidRelationship = !(parent != nil && (parent?.entity == relationshipDescription.destinationEntity) && !relationshipDescription.isToMany) if isValidRelationship { jsonObject[remoteRelationshipName] = json( valueForRelationship: relationshipDescription, relationshipType: relationshipType, dateFormatter: dateFormatter, includeNilValues: includeNilValues ) } } } return jsonObject } /// Transforms an object to JSON, using the supplied `relationshipType`. func json(attributesForObject object: NSManagedObject, dateFormatter: JSONDateFormatter?, parent: NSManagedObject?, relationshipType: RelationshipType, includeNilValues: Bool = true) -> Any { switch relationshipType { case .embedded: return object.toJSON( relationshipType: relationshipType, includeNilValues: includeNilValues, dateFormatter: dateFormatter, parent: parent ) case .reference: return object.primaryKey ?? NSNull() case let .custom(map): return map(object) default: return NSNull() } } /// Returns the JSON value of `attributeDescription` if it's `attributeType` is not a "Transformable" attribute. func json(valueForAttribute attribute: NSAttributeDescription, dateFormatter: JSONDateFormatter? = nil, includeNilValues: Bool = false) -> Any? { var attributeValue: Any? if attribute.attributeType != .transformableAttributeType { attributeValue = value(forKey: attribute.name) if let date = attributeValue as? Date { return dateFormatter?.string(from: date) } else if let data = attributeValue as? Data { return NSKeyedUnarchiver.unarchiveObject(with: data) } } if attributeValue == nil && includeNilValues { attributeValue = NSNull() } return attributeValue } /// Returns the JSON value of `relationship` if it's `attributeType` func json(valueForRelationship relationship: NSRelationshipDescription, relationshipType: RelationshipType, dateFormatter: JSONDateFormatter? = nil, includeNilValues: Bool = false) -> Any? { let relationshipMappingType = relationship.relationshipMapping ?? relationshipType /// If there are relationships at `localRelationshipName` if let relationshipValue = value(forKey: relationship.name) { /// If the relationship is to a single object... if let destinationObject = relationshipValue as? NSManagedObject { return json( attributesForObject: destinationObject, dateFormatter: dateFormatter, parent: self, relationshipType: relationshipMappingType, includeNilValues: includeNilValues ) /// If the relationship is to a set of objects... } else if let relationshipSet = relationshipValue as? Set<NSManagedObject> { return relationshipSet.map { object in return json( attributesForObject: object, dateFormatter: dateFormatter, parent: self, relationshipType: relationshipMappingType, includeNilValues: includeNilValues ) } /// If the relationship is to an ordered set of objects... } else if let relationshipSet = (relationshipValue as? NSOrderedSet)?.set as? Set<NSManagedObject> { return relationshipSet.map { object in return json( attributesForObject: object, dateFormatter: dateFormatter, parent: self, relationshipType: relationshipMappingType, includeNilValues: includeNilValues ) } } } return includeNilValues ? NSNull() : nil } }
mit
b48cdb0041be120e68c3a3f0832093f1
45.768328
270
0.576561
6.043198
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/BlockchainComponentLibrary/Sources/BlockchainComponentLibrary/3 - Compositions/Sheets/BottomSheet.swift
1
7616
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Extensions import SwiftUI extension View { /// Display a bottom sheet over the current content /// - Parameters: /// - item: An optional binding which determines what content should be shown /// - content: The contents of the sheet /// - Returns: ZStack containing `self` overlayed with the bottom sheet view @ViewBuilder public func bottomSheet<Item, Content>( item: Binding<Item?>, @ViewBuilder content: (Item) -> Content ) -> some View where Content: View { bottomSheet( isPresented: Binding( get: { item.transaction(item.transaction).wrappedValue != nil }, set: { newValue in if !newValue { item.transaction(item.transaction).wrappedValue = nil } } ), content: { if let item = item.transaction(item.transaction).wrappedValue { content(item) } } ) } /// Display a bottom sheet over the current content /// - Parameters: /// - isPresented: A binding which determines when the content should be shown /// - content: The contents of the sheet /// - Returns: ZStack containing `self` overlayed with the bottom sheet view public func bottomSheet<Content: View>( isPresented: Binding<Bool>, @ViewBuilder content: () -> Content ) -> some View { modifier(BottomSheetModifier(isPresented: isPresented, sheetContent: content())) } } /// A small sheet used to present content from a drawer. /// The content presented will be dismissed via the user swiping down, using the handle, /// tapping the handle or by tapping the faded area behind the presented sheet. /// /// # Figma /// [Sheet](https://www.figma.com/file/nlSbdUyIxB64qgypxJkm74/03---iOS-%7C-Shared?node-id=209%3A10112) struct BottomSheetView<Content: View>: View { let cornerRadius: CGFloat = 24 var content: Content var body: some View { VStack { Capsule() .fill(Color.semantic.dark) .frame(width: 32.pt, height: 4.pt) .foregroundColor(.semantic.muted) content } .padding(.top, Spacing.padding1) .padding(.bottom, Spacing.padding3) .frame(maxWidth: .infinity) .background( BottomSheetBackgroundShape() .foregroundColor(.semantic.background) ) .clipShape( BottomSheetBackgroundShape() ) .offset(y: Spacing.baseline) } } extension BottomSheetView { init(@ViewBuilder content: () -> Content) { self.content = content() } } struct BottomSheetModifier<SheetContent: View>: ViewModifier { @Binding var isPresented: Bool @GestureState( resetTransaction: Transaction(animation: .interactiveSpring()) ) var translation: CGSize = .zero let sheetContent: SheetContent @State private var inserted = false private func yTranslation(in proxy: GeometryProxy) -> CGFloat { if isPresented { return inserted ? proxy.size.height : max(translation.height, -Spacing.baseline) } else { return proxy.size.height } } func body(content: Content) -> some View { content.overlay( Group { GeometryReader { proxy in ZStack(alignment: .bottom) { if isPresented { Color.palette.overlay600 .onAppear { inserted = true } .onDisappear { inserted = false } .onTapGesture { isPresented = false } .transition(.opacity) .ignoresSafeArea() BottomSheetView(content: sheetContent) .zIndex(1) .onChange(of: inserted) { newValue in guard newValue else { return } DispatchQueue.main.async { withAnimation(.spring()) { inserted = false } } } .transition(.move(edge: .bottom)) .offset(y: yTranslation(in: proxy)) } } .ignoresSafeArea() .highPriorityGesture( DragGesture() .updating($translation) { value, state, _ in state = value.translation } .onEnded { value in let endLocation = value.predictedEndLocation let frame = proxy.frame(in: .global) if endLocation.y > frame.maxY - 60 { isPresented = false } } ) } } ) } } struct BottomSheetBackgroundShape: Shape { var cornerRadius: CGFloat = 32 var style: RoundedCornerStyle = .continuous func path(in rect: CGRect) -> Path { #if canImport(UIKit) let path = UIBezierPath( roundedRect: rect, byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize( width: cornerRadius, height: cornerRadius ) ) return Path(path.cgPath) #else return RoundedRectangle( cornerRadius: cornerRadius, style: style ) .path(in: rect) #endif } } // swiftlint:disable type_name struct BottomSheetView_PreviewContentView: View { @State var isPresented = false var body: some View { PrimaryButton(title: "Tap me") { withAnimation(.spring()) { isPresented = true } } .buttonStyle(.plain) .frame(maxWidth: .infinity, maxHeight: .infinity) .bottomSheet( isPresented: $isPresented.animation(.spring()) ) { VStack(spacing: 0) { ForEach(1...5, id: \.self) { i in PrimaryRow( title: "Title", subtitle: "Description", leading: { Icon.allIcons .randomElement()! .circle() .accentColor(.semantic.primary) .frame(maxHeight: 24.pt) }, action: {} ) if i != 5 { PrimaryDivider() } } } } } } struct BottomSheetView_Previews: PreviewProvider { static var previews: some View { Group { BottomSheetView_PreviewContentView() BottomSheetView_PreviewContentView(isPresented: true) BottomSheetView_PreviewContentView(isPresented: true) .previewDevice("iPhone SE (2nd generation)") .previewDisplayName("iPhone SE (2nd generation)") } } }
lgpl-3.0
3a7a999dc7ccfaa83d58228a01669714
32.844444
102
0.493368
5.518116
false
false
false
false
huonw/swift
test/DebugInfo/resilience.swift
1
3024
// RUN: %empty-directory(%t) // // Compile the external swift module. // RUN: %target-swift-frontend -g -emit-module -enable-resilience \ // RUN: -emit-module-path=%t/resilient_struct.swiftmodule \ // RUN: -module-name=resilient_struct %S/../Inputs/resilient_struct.swift // // RUN: %target-swift-frontend -g -I %t -emit-ir -enable-resilience %s -o - \ // RUN: | %FileCheck %s // // RUN: %target-swift-frontend -g -I %t -emit-ir -enable-resilience %s -o - \ // RUN: -enable-resilience-bypass | %FileCheck %s --check-prefix=CHECK-LLDB import resilient_struct let fixed = Point(x: 1, y: 2) let non_fixed = Size(w: 1, h: 2) let int = ResilientInt(i: 1) // CHECK: @"$S10resilience5fixed16resilient_struct5PointVvp" = // CHECK-SAME: !dbg ![[FIXED:[0-9]+]] // CHECK: @"$S10resilience9non_fixed16resilient_struct4SizeVvp" = // CHECK-SAME: !dbg ![[NON_FIXED:[0-9]+]] // CHECK: @"$S10resilience3int16resilient_struct12ResilientIntVvp" = // CHECK-SAME: !dbg ![[INT:[0-9]+]] // CHECK-LABEL: define{{.*}}main // CHECK-LABEL: define{{.*}} swiftcc void @"$S10resilience9takesSizeyy16resilient_struct0C0VF"(%swift.opaque* noalias nocapture) // CHECK-LLDB-LABEL: define{{.*}} swiftcc void @"$S10resilience9takesSizeyy16resilient_struct0C0VF"(%T16resilient_struct4SizeV* noalias nocapture dereferenceable({{8|16}})) public func takesSize(_ s: Size) {} // CHECK-LABEL: define{{.*}} swiftcc void @"$S10resilience1fyyF"() // CHECK-LLDB-LABEL: define{{.*}} swiftcc void @"$S10resilience1fyyF"() func f() { let s1 = Size(w: 1, h: 2) takesSize(s1) // CHECK: %[[ADDR:.*]] = alloca i8* // CHECK: call void @llvm.dbg.declare(metadata i8** %[[ADDR]], // CHECK-SAME: metadata ![[V1:[0-9]+]], // CHECK-SAME: metadata !DIExpression(DW_OP_deref)) // CHECK: %[[S1:.*]] = alloca i8, // CHECK: store i8* %[[S1]], i8** %[[ADDR]] // CHECK-LLDB: %[[ADDR:.*]] = alloca %T16resilient_struct4SizeV // CHECK-LLDB: call void @llvm.dbg.declare(metadata %T16resilient_struct4SizeV* %[[ADDR]], // CHECK-LLDB-SAME: metadata ![[V1:[0-9]+]], // CHECK-LLDB-SAME: metadata !DIExpression()) } f() // Note that these DW_OP_deref are not necessarily correct, but it's the best // approxmiation we have until LLDB can query the runtime for whether a relient // type's storage is inline or not. // CHECK: ![[FIXED]] = !DIGlobalVariableExpression( // CHECK-SAME: expr: !DIExpression()) // CHECK: ![[NON_FIXED]] = !DIGlobalVariableExpression( // CHECK-SAME: expr: !DIExpression(DW_OP_deref)) // CHECK: ![[TY:[0-9]+]] = !DICompositeType(tag: DW_TAG_structure_type, name: "Size", // CHECK: ![[INT]] = !DIGlobalVariableExpression( // CHECK-SAME: expr: !DIExpression(DW_OP_deref)) // CHECK: ![[V1]] = !DILocalVariable(name: "s1", {{.*}}type: ![[TY]]) // CHECK-LLDB: ![[TY:[0-9]+]] = !DICompositeType(tag: DW_TAG_structure_type, name: "Size", // CHECK-LLDB: ![[V1]] = !DILocalVariable(name: "s1", {{.*}}type: ![[TY]])
apache-2.0
603bb44f54c891d277dc3a1e3662e92c
44.818182
172
0.631944
3.234225
false
false
false
false
Automattic/Automattic-Tracks-iOS
Tests/Tests/Event Logging/LogFileTests.swift
1
1143
import XCTest #if SWIFT_PACKAGE @testable import AutomatticRemoteLogging @testable import AutomatticEncryptedLogs #else @testable import AutomatticTracks #endif class LogFileTests: XCTestCase { func testThatLogFileNameMatchesUUID() { let log = LogFile.containingRandomString() XCTAssertEqual(log.fileName, log.uuid) } func testParsingExistingFilenameUsesOnlyFilename() { let fileName = UUID().uuidString let contents = String.randomString(length: 255) let testFile = FileManager.default.createTempFile(named: fileName, containing: contents) let log = LogFile.fromExistingFile(at: testFile) XCTAssertEqual(log.fileName, fileName) XCTAssertEqual(log.uuid, fileName) } func testParsingExistingFilenameUsesOnlyFilenameIncludingExtension() { let contents = String.randomString(length: 255) let testFile = FileManager.default.createTempFile(named: "test.log", containing: contents) let log = LogFile.fromExistingFile(at: testFile) XCTAssertEqual(log.fileName, "test.log") XCTAssertEqual(log.uuid, "test.log") } }
gpl-2.0
5f556a503e0d77c5ea36f8f8990a788a
30.75
98
0.723535
4.684426
false
true
false
false
fellipecaetano/Democracy-iOS
Pods/RandomKit/Sources/RandomKit/Types/RandomGenerator/ChaCha.swift
1
6620
// // ChaCha.swift // RandomKit // // The MIT License (MIT) // // Copyright (c) 2015-2017 Nikolai Vazquez // // 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. // /// A generator that uses a [ChaCha20][1] algorithm. There is also a [Wikipedia section][2] describing this algorithm. /// /// This implementation is taken from that of [ChaCha][3] in the Rust `rand` crate. /// /// [1]: http://cr.yp.to/chacha.html /// [2]: https://en.wikipedia.org/wiki/Salsa20#ChaCha_variant /// [3]: https://doc.rust-lang.org/rand/rand/chacha/struct.ChaChaRng.html public struct ChaCha: RandomBytesGenerator, Seedable, SeedableFromSequence, SeedableFromRandomGenerator { /// The seed type. public typealias Seed = [UInt32] /// The seed sequence's element type. public typealias SeedSequenceElement = UInt32 private typealias _State = _Array16<UInt32> private static let _stateCount = 16 private static let _keyCount = 8 private static let _rounds = 20 private static var _empty: ChaCha { return ChaCha(_buffer: _zero16(), _state: _zero16(), _index: _stateCount) } /// A default global instance seeded with `DeviceRandom.default`. public static var `default` = seeded /// A default global instance that reseeds itself with `DeviceRandom.default`. public static var defaultReseeding = reseeding /// Returns an unseeded instance. public static var unseeded: ChaCha { var result = _empty result._reset() return result } private var _buffer: _State private var _state: _State private var _index: Int private var _bufferPointer: UnsafeMutablePointer<UInt32> { mutating get { return UnsafeMutablePointer(&_buffer.0) } } private var _statePointer: UnsafeMutablePointer<UInt32> { mutating get { return UnsafeMutablePointer(&_state.0) } } private init(_buffer: _State, _state: _State, _index: Int) { self._buffer = _buffer self._state = _state self._index = _index } /// Creates an instance from `seed`. public init<S: Sequence>(seed: S) where S.Iterator.Element == UInt32 { self = ._empty reseed(with: seed) } /// Creates an instance seeded with `randomGenerator`. public init<R: RandomGenerator>(seededWith randomGenerator: inout R) { var seed: _Array8<UInt32> = randomGenerator.randomUnsafeValue() self.init(seed: UnsafeBufferPointer(start: &seed.0, count: ChaCha._keyCount)) } private mutating func _reset() { _state.0 = 0x61707865 _state.1 = 0x3320646E _state.2 = 0x79622D32 _state.3 = 0x6B206574 let pointer = UnsafeMutablePointer(&_state.4) for i in 0 ..< 12 { pointer[i] = 0 } _index = ChaCha._stateCount } private mutating func _update() { let bufferPtr = _bufferPointer let statePtr = _statePointer _buffer = _state _index = 0 for _ in 0 ..< ChaCha._rounds / 2 { _doubleRound(bufferPtr) } for i in 0 ..< ChaCha._stateCount { bufferPtr[i] = bufferPtr[i] &+ statePtr[i] } for i in 12 ..< 16 { statePtr[i] = statePtr[i] &+ 1 guard statePtr[i] == 0 else { return } } } /// Sets the internal 128-bit counter. public mutating func setCounter(low: UInt64, high: UInt64) { #if swift(>=3.2) _state.12 = UInt32(extendingOrTruncating: low) _state.13 = UInt32(extendingOrTruncating: low &>> 32) _state.14 = UInt32(extendingOrTruncating: high) _state.15 = UInt32(extendingOrTruncating: high &>> 32) #else _state.12 = UInt32(truncatingBitPattern: low) _state.13 = UInt32(truncatingBitPattern: low >> 32) _state.14 = UInt32(truncatingBitPattern: high) _state.15 = UInt32(truncatingBitPattern: high >> 32) #endif _index = ChaCha._stateCount } /// Reseeds `self` with `seed`. public mutating func reseed<S: Sequence>(with seed: S) where S.Iterator.Element == UInt32 { _reset() let keyPointer = _statePointer for (i, s) in zip(4 ..< ChaCha._keyCount + 4, seed) { keyPointer[i] = s } } /// Returns random `Bytes`. public mutating func randomBytes() -> UInt32 { if _index == ChaCha._stateCount { _update() } defer { _index += 1 } return _bufferPointer[_index % ChaCha._stateCount] } } extension UInt32 { @inline(__always) fileprivate func _rotateLeft(_ n: UInt32) -> UInt32 { return (self << n) | (self >> (32 &- n)) } } @inline(__always) private func _quarterRound(_ a: inout UInt32, _ b: inout UInt32, _ c: inout UInt32, _ d: inout UInt32) { a = a &+ b; d ^= a; d = d._rotateLeft(16) c = c &+ d; b ^= c; b = b._rotateLeft(12) a = a &+ b; d ^= a; d = d._rotateLeft(8) c = c &+ d; b ^= c; b = b._rotateLeft(7) } @inline(__always) private func _doubleRound(_ x: UnsafeMutablePointer<UInt32>) { // Column round _quarterRound(&x[0], &x[4], &x[8], &x[12]) _quarterRound(&x[1], &x[5], &x[9], &x[13]) _quarterRound(&x[2], &x[6], &x[10], &x[14]) _quarterRound(&x[3], &x[7], &x[11], &x[15]) // Diagonal round _quarterRound(&x[0], &x[5], &x[10], &x[15]) _quarterRound(&x[1], &x[6], &x[11], &x[12]) _quarterRound(&x[2], &x[7], &x[8], &x[13]) _quarterRound(&x[3], &x[4], &x[9], &x[14]) }
mit
ab3793c613f770ca9ff99e8bb03fefc9
33.123711
118
0.613142
3.761364
false
false
false
false
pcperini/Thrust
Thrust/Source/HTTP.swift
1
12940
// // HTTP.swift // Thrust // // Created by Patrick Perini on 8/13/14. // Copyright (c) 2014 pcperini. All rights reserved. // import Foundation // MARK: - Extensions extension Dictionary { /// Returns a representation of the dictionary using percent escapes necessary to convert the key-value pairs into a legal URL string. var urlSerializedString: String { get { var serializedString: String = "" for (key, value) in self { let encodedKey = "\(key)".stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) let encodedValue = "\(value)".stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) if !serializedString.hasContent { serializedString = "\(encodedKey)=\(encodedValue)" } else { serializedString += "&\(encodedKey)=\(encodedValue)" } } return serializedString } } } class HTTP { // MARK: - Responses struct Response: DebugPrintable { // MARK: - Properties // MARK: Request Information /// The original request URL, with query parameters. var requestURL: NSURL /// The original request body. var requestBody: NSData // MARK: Response Information /// The response's HTTP status code. var status: Int? /// The response's binary data. var data: NSData? /// The response's data as a UTF8-string. var string: String? { return NSString(data: self.data!, encoding: NSUTF8StringEncoding) as String } /// The responses's data as a JSON container. var object: JSONContainer? { return self.string?.jsonObject } var debugDescription: String { return "\(self.requestURL) - \(self.status ?? 0)\n\t\(self.string ?? String())" } } // MARK: - Requests private struct Request { // MARK: Required Properties var url: NSURL var method: Method // MARK: Optional Properties var headers: [String: String]? var params: [String: String]? var payload: JSONContainer? var block: ((Response) -> Void)? // MARK: Request Operations func asyncRequest() { on (Queue.background) { let response: Response = self.syncRequest() on (Queue.main) { self.block?(response) } } } func syncRequest() -> Response { // Setup variables var urlString: String = self.url.absoluteString! let requestBody: NSData = self.payload?.jsonString?.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true) ?? NSData() // Add parameters if params != nil { urlString += "?\(params!.urlSerializedString)" } // Build request let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: NSURL(string: urlString)) urlRequest.HTTPMethod = method.toRaw() urlRequest.HTTPBody = requestBody // ... add headers urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") if headers != nil { for (key, value) in headers! { urlRequest.setValue(value, forHTTPHeaderField: key) } } // Build response var urlResponse: NSURLResponse? let responseBody: NSData? = NSURLConnection.sendSynchronousRequest(urlRequest, returningResponse: &urlResponse, error: nil) var response: Response = Response(requestURL: NSURL(string: urlString), requestBody: requestBody, status: nil, data: nil) if let httpURLResponse = urlResponse as? NSHTTPURLResponse { response.data = responseBody response.status = httpURLResponse.statusCode } return response } } struct RequestBatch { // MARK: Properties private var requests: [Request] = [] var requestCount: Int { return self.requests.count } // MARK: Mutators mutating func addGETRequest(url: NSURL, headers: [String: String]? = nil, params: [String: String]? = nil) { self.addRequest(url, method: Method.GET, headers: headers, params: params, payload: nil) } mutating func addPUTRequest(url: NSURL, headers: [String: String]? = nil, params: [String: String]? = nil, payload: JSONContainer?) { self.addRequest(url, method: Method.PUT, headers: headers, params: params, payload: payload) } mutating func addPOSTRequest(url: NSURL, headers: [String: String]? = nil, params: [String: String]? = nil, payload: JSONContainer?) { self.addRequest(url, method: Method.POST, headers: headers, params: params, payload: payload) } mutating func addDELETERequest(url: NSURL, headers: [String: String]? = nil, params: [String: String]? = nil) { self.addRequest(url, method: Method.DELETE, headers: headers, params: params, payload: nil) } private mutating func addRequest(url: NSURL, method: Method, headers: [String: String]? = nil, params: [String: String]? = nil, payload: JSONContainer?) { let request: Request = Request(url: url, method: method, headers: headers, params: params, payload: payload, block: nil) var requests: [Request] = self.requests requests.append(request) self.requests = requests } // MARK: Performers mutating func performRequests(block: ([Response]) -> Void) { let requestQueue: Queue = Queue(label: "Thrust.Swift.RequestBatch.performRequests") on (requestQueue) { var responses: [Response] = [] for request: Request in self.requests { let response: Response = request.syncRequest() responses.append(response) } self.requests = [] on (Queue.main) { block(responses) } } } } // MARK: - Methods private enum Method: String { case GET = "GET" case PUT = "PUT" case POST = "POST" case DELETE = "DELETE" } // MARK: - Requests /** Executes an HTTP GET request on the given URL. :param: url The URL to request. :param: headers HTTP headers. :param: params URL parameters, which become the request's query string. :param: block A reponse handler that takes a single HTTP.Response argument. */ class func get(url: NSURL, headers: [String: String]? = nil, params: [String: String]? = nil, block: ((Response) -> Void)?) { let request: Request = Request(url: url, method: Method.GET, headers: headers, params: params, payload: nil, block: block) request.asyncRequest() } /** Executes an HTTP GET request on the given URL. :param: url The URL to request. :param: headers HTTP headers. :param: params URL parameters, which become the request's query string. :returns: The HTTP.Response object representing the request's response. */ class func get(url: NSURL, headers: [String: String]? = nil, params: [String: String]? = nil) -> Response { let request: Request = Request(url: url, method: Method.GET, headers: headers, params: params, payload: nil, block: nil) return request.syncRequest() } /** Executes an HTTP PUT request on the given URL. :param: url The URL to request. :param: headers HTTP headers. :param: params URL parameters, which become the request's query string. :param: payload A JSON dictionary or array to be used as the JSON body of the request. :param: block A reponse handler that takes a single HTTP.Response argument. */ class func put(url: NSURL, headers: [String: String]? = nil, params: [String: String]? = nil, payload: JSONContainer?, block: ((Response) -> Void)?) { let request: Request = Request(url: url, method: Method.PUT, headers: headers, params: params, payload: payload, block: block) request.asyncRequest() } /** Executes an HTTP PUT request on the given URL. :param: url The URL to request. :param: headers HTTP headers. :param: params URL parameters, which become the request's query string. :param: payload A JSON dictionary or array to be used as the JSON body of the request. :returns: The HTTP.Response object representing the request's response. */ class func put(url: NSURL, headers: [String: String]? = nil, params: [String: String]? = nil, payload: JSONContainer?) -> Response { let request: Request = Request(url: url, method: Method.PUT, headers: headers, params: params, payload: payload, block: nil) return request.syncRequest() } /** Executes an HTTP POST request on the given URL. :param: url The URL to request. :param: headers HTTP headers. :param: params URL parameters, which become the request's query string. :param: payload A JSON dictionary or array to be used as the JSON body of the request. :param: block A reponse handler that takes a single HTTP.Response argument. */ class func post(url: NSURL, headers: [String: String]? = nil, params: [String: String]? = nil, payload: JSONContainer?, block: ((Response) -> Void)?) { let request: Request = Request(url: url, method: Method.POST, headers: headers, params: params, payload: payload, block: block) request.asyncRequest() } /** Executes an HTTP POST request on the given URL. :param: url The URL to request. :param: headers HTTP headers. :param: params URL parameters, which become the request's query string. :param: payload A JSON dictionary or array to be used as the JSON body of the request. :returns: The HTTP.Response object representing the request's response. */ class func post(url: NSURL, headers: [String: String]? = nil, params: [String: String]? = nil, payload: JSONContainer?) -> Response { let request: Request = Request(url: url, method: Method.POST, headers: headers, params: params, payload: payload, block: nil) return request.syncRequest() } /** Executes an HTTP DELETE request on the given URL. :param: url The URL to request. :param: headers HTTP headers. :param: params URL parameters, which become the request's query string. :param: block A reponse handler that takes a single HTTP.Response argument. */ class func delete(url: NSURL, headers: [String: String]? = nil, params: [String: String]? = nil, block: ((Response) -> Void)?) { let request: Request = Request(url: url, method: Method.GET, headers: headers, params: params, payload: nil, block: block) request.asyncRequest() } /** Executes an HTTP DELETE request on the given URL. :param: url The URL to request. :param: headers HTTP headers. :param: params URL parameters, which become the request's query string. :returns: The HTTP.Response object representing the request's response. */ class func delete(url: NSURL, headers: [String: String]? = nil, params: [String: String]? = nil) -> Response { let request: Request = Request(url: url, method: Method.GET, headers: headers, params: params, payload: nil, block: nil) return request.syncRequest() } }
mit
1113b649c32638d8ec7143e6a7fc1576
33.787634
162
0.558423
4.948375
false
false
false
false
TimurTarasenko/tispr-card-stack
TisprCardStack/TisprCardStack/TisprCardStackViewLayout.swift
1
16081
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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. */ // // TisprCardStackViewLayout.swift // // Created by Andrei Pitsko on 07/12/15. // Copyright (c) 2015 BuddyHopp Inc. All rights reserved. // import UIKit public class TisprCardStackViewLayout: UICollectionViewLayout, UIGestureRecognizerDelegate { // MARK: - Properties /// The index of the card that is currently on top of the stack. The index 0 represents the oldest card of the stack. var index: Int = 0 { didSet { //workaround for zIndex draggedCellPath = oldValue > index ? NSIndexPath(forItem: index, inSection: 0) : NSIndexPath(forItem: oldValue, inSection: 0) collectionView?.performBatchUpdates({ let x: Void = self.invalidateLayout() }, completion: nil) delegate?.cardDidChangeState(oldValue) } } var delegate: TisprCardStackViewControllerDelegate? /// The maximum number of cards displayed on the top stack. This value includes the currently visible card. @IBInspectable public var topStackMaximumSize: Int = 3 /// The maximum number of cards displayed on the bottom stack. @IBInspectable public var bottomStackMaximumSize: Int = 3 /// The visible height of the card of the bottom stack. @IBInspectable public var bottomStackCardHeight: CGFloat = 50 /// The size of a card in the stack layout. @IBInspectable var cardSize: CGSize = CGSizeMake(280, 380) // The inset or outset margins for the rectangle around the card. @IBInspectable public var cardInsets: UIEdgeInsets = UIEdgeInsetsZero /// A Boolean value indicating whether the pan and swipe gestures on cards are enabled. var gesturesEnabled: Bool = false { didSet { if (gesturesEnabled) { let recognizer = UIPanGestureRecognizer(target: self, action: Selector("handlePan:")) collectionView?.addGestureRecognizer(recognizer) panGestureRecognizer = recognizer panGestureRecognizer!.delegate = self swipeRecognizerDown = UISwipeGestureRecognizer(target: self, action: Selector("handleSwipe:")) swipeRecognizerDown!.direction = UISwipeGestureRecognizerDirection.Down swipeRecognizerDown!.delegate = self collectionView?.addGestureRecognizer(swipeRecognizerDown!) swipeRecognizerDown!.requireGestureRecognizerToFail(panGestureRecognizer!) swipeRecognizerUp = UISwipeGestureRecognizer(target: self, action: Selector("handleSwipe:")) swipeRecognizerUp!.direction = UISwipeGestureRecognizerDirection.Up swipeRecognizerUp!.delegate = self collectionView?.addGestureRecognizer(swipeRecognizerUp!) swipeRecognizerUp!.requireGestureRecognizerToFail(panGestureRecognizer!) } else { if let recognizer = panGestureRecognizer { collectionView?.removeGestureRecognizer(recognizer) } if let swipeDownRecog = swipeRecognizerDown { collectionView?.removeGestureRecognizer(swipeDownRecog) } if let swipeUpRecog = swipeRecognizerUp { collectionView?.removeGestureRecognizer(swipeUpRecog) } } } } // Index path of dragged cell private var draggedCellPath: NSIndexPath? // The initial center of the cell being dragged. private var initialCellCenter: CGPoint? // The rotation values of the bottom stack cards. private var bottomStackRotations = [Int: Double]() // Is the animation for new cards in progress? private var newCardAnimationInProgress: Bool = false /// Cards from bottom stack will be rotated with angle = coefficientOfRotation * hade. private let coefficientOfRotation: Double = 0.25 private let angleOfRotationForNewCardAnimation: CGFloat = 0.25 private let verticalOffsetBetweenCardsInTopStack = 10 private let centralCardYPosition = 70 private var panGestureRecognizer: UIPanGestureRecognizer? private var swipeRecognizerDown: UISwipeGestureRecognizer? private var swipeRecognizerUp: UISwipeGestureRecognizer? private let minimumXPanDistanceToSwipe: CGFloat = 100 private let minimumYPanDistanceToSwipe: CGFloat = 60 // MARK: - Getting the Collection View Information override public func collectionViewContentSize() -> CGSize { return collectionView!.frame.size } // MARK: - Providing Layout Attributes override public func initialLayoutAttributesForAppearingItemAtIndexPath(itemIndexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? { var result :UICollectionViewLayoutAttributes? if itemIndexPath.item == collectionView!.numberOfItemsInSection(0) - 1 && newCardAnimationInProgress { result = UICollectionViewLayoutAttributes(forCellWithIndexPath: itemIndexPath) let yPosition = collectionViewContentSize().height - cardSize.height //Random direction let directionFromRight = arc4random() % 2 == 0 let xPosition = directionFromRight ? collectionViewContentSize().width : -cardSize.width let cardFrame = CGRectMake(CGFloat(xPosition), yPosition, cardSize.width, cardSize.height) result!.frame = cardFrame result!.zIndex = 1000 - itemIndexPath.item result!.hidden = false result!.transform3D = CATransform3DMakeRotation(directionFromRight ?angleOfRotationForNewCardAnimation : -angleOfRotationForNewCardAnimation, 0, 0, 1) } return result } public override func layoutAttributesForElementsInRect(rect: CGRect) -> [AnyObject]? { let indexPaths = indexPathsForElementsInRect(rect) let layoutAttributes = indexPaths.map { self.layoutAttributesForItemAtIndexPath($0) } return layoutAttributes } public override func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes! { var result = UICollectionViewLayoutAttributes(forCellWithIndexPath: indexPath) if (indexPath.item >= index) { result = layoutAttributesForTopStackItemWithInitialAttributes(result) } else { result = layoutAttributesForBottomStackItemWithInitialAttributes(result) } //we have to hide invisible cards in top stask due perfomance issues due shadows result.hidden = (result.indexPath.item >= index + topStackMaximumSize) if indexPath.item == draggedCellPath?.item { //workaround for zIndex result.zIndex = 100000 } else { result.zIndex = (indexPath.item >= index) ? (1000 - indexPath.item) : (1000 + indexPath.item) } return result } // MARK: - Implementation private func indexPathsForElementsInRect(rect: CGRect) -> [NSIndexPath] { var result = [NSIndexPath]() let count = collectionView!.numberOfItemsInSection(0) let topStackCount = min(count - (index + 1), topStackMaximumSize - 1) let bottomStackCount = min(index, bottomStackMaximumSize) let start = index - bottomStackCount let end = (index + 1) + topStackCount for i in start..<end { result.append(NSIndexPath(forItem: i, inSection: 0)) } return result } private func layoutAttributesForTopStackItemWithInitialAttributes(attributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes { //we should not change position for card which will be hidden for good animation let minYPosition = centralCardYPosition - verticalOffsetBetweenCardsInTopStack*(topStackMaximumSize - 1) var yPosition = centralCardYPosition - verticalOffsetBetweenCardsInTopStack*(attributes.indexPath.row - index) yPosition = max(yPosition,minYPosition) //right position for new card if attributes.indexPath.item == collectionView!.numberOfItemsInSection(0) - 1 && newCardAnimationInProgress { //New card has to be displayed if there are no topStackMaximumSize cards in the top stack if attributes.indexPath.item >= index && attributes.indexPath.item < index + topStackMaximumSize { yPosition = centralCardYPosition - verticalOffsetBetweenCardsInTopStack*(attributes.indexPath.row - index) } else { attributes.hidden = true yPosition = centralCardYPosition } } let xPosition = (collectionView!.frame.size.width - cardSize.width)/2 let cardFrame = CGRectMake(xPosition, CGFloat(yPosition), cardSize.width, cardSize.height) attributes.frame = cardFrame return attributes } private func layoutAttributesForBottomStackItemWithInitialAttributes(attributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes { let yPosition = collectionView!.frame.size.height - bottomStackCardHeight let xPosition = (collectionView!.frame.size.width - cardSize.width)/2 let frame = CGRectMake(xPosition, CGFloat(yPosition), cardSize.width, cardSize.height) attributes.frame = frame if let angle = bottomStackRotations[attributes.indexPath.item] { attributes.transform3D = CATransform3DMakeRotation(CGFloat(angle), 0, 0, 1) } return attributes } // MARK: - Handling the Swipe and Pan Gesture internal func handleSwipe(sender: UISwipeGestureRecognizer) { switch sender.direction { case UISwipeGestureRecognizerDirection.Up: // Take the card at the current index // and process the swipe up only if it occurs below it // var temIndex = index // if temIndex >= collectionView!.numberOfItemsInSection(0) { // temIndex-- // } // let currentCard = collectionView!.cellForItemAtIndexPath(NSIndexPath(forItem: temIndex , inSection: 0))! // let point = sender.locationInView(collectionView) // if (point.y > CGRectGetMaxY(currentCard.frame) && index > 0) { index-- // } case UISwipeGestureRecognizerDirection.Down: if index + 1 < collectionView!.numberOfItemsInSection(0) { index++ } default: break } } internal func handlePan(sender: UIPanGestureRecognizer) { if (sender.state == .Began) { let initialPanPoint = sender.locationInView(collectionView) findDraggingCellByCoordinate(initialPanPoint) } else if (sender.state == .Changed) { let newCenter = sender.translationInView(collectionView!) updateCenterPositionOfDraggingCell(newCenter) } else { if let indexPath = draggedCellPath { finishedDragging(collectionView!.cellForItemAtIndexPath(indexPath)!) } } } //Define what card should we drag private func findDraggingCellByCoordinate(touchCoordinate: CGPoint) { if let indexPath = collectionView?.indexPathForItemAtPoint(touchCoordinate) { if indexPath.item >= index { //top stack draggedCellPath = NSIndexPath(forItem: index, inSection: 0) initialCellCenter = collectionView?.cellForItemAtIndexPath(draggedCellPath!)?.center } else { //bottomStack if (index > 0 ) { draggedCellPath = NSIndexPath(forItem: index - 1, inSection: 0) } initialCellCenter = collectionView?.cellForItemAtIndexPath(draggedCellPath!)?.center } //workaround for fix issue with zIndex let cell = collectionView!.cellForItemAtIndexPath(draggedCellPath!) collectionView?.bringSubviewToFront(cell!) } } //Change position of dragged card private func updateCenterPositionOfDraggingCell(touchCoordinate:CGPoint) { if let strongDraggedCellPath = draggedCellPath { if let cell = collectionView?.cellForItemAtIndexPath(strongDraggedCellPath) { let newCenterX = (initialCellCenter!.x + touchCoordinate.x) let newCenterY = (initialCellCenter!.y + touchCoordinate.y) cell.center = CGPoint(x: newCenterX, y:newCenterY) cell.transform = CGAffineTransformMakeRotation(CGFloat(storeAngleOfRotation())) } } } private func finishedDragging(cell: UICollectionViewCell) { let deltaX = abs(cell.center.x - initialCellCenter!.x) let deltaY = abs(cell.center.y - initialCellCenter!.y) let shouldSnapBack = (deltaX < minimumXPanDistanceToSwipe && deltaY < minimumYPanDistanceToSwipe) if shouldSnapBack { UIView.setAnimationsEnabled(false) collectionView!.reloadItemsAtIndexPaths([self.draggedCellPath!]) UIView.setAnimationsEnabled(true) } else { storeAngleOfRotation() if draggedCellPath?.item == index { index++ } else { index-- } initialCellCenter = CGPointZero draggedCellPath = nil } } //Compute and Store angle of rotation private func storeAngleOfRotation() -> Double { var result:Double = 0 if let strongDraggedCellPath = draggedCellPath { if let cell = collectionView?.cellForItemAtIndexPath(strongDraggedCellPath) { let centerYIncidence = collectionView!.frame.size.height + cardSize.height - bottomStackCardHeight let gamma:Double = Double((cell.center.x - collectionView!.bounds.size.width/2)/(centerYIncidence - cell.center.y)) result = atan(gamma) bottomStackRotations[strongDraggedCellPath.item] = atan(gamma)*coefficientOfRotation } } return result } // MARK: - appearance of new card func newCardDidAdd(newCardIndex:Int) { collectionView?.performBatchUpdates({ [weak self] _ in self?.newCardAnimationInProgress = true self?.collectionView?.insertItemsAtIndexPaths([NSIndexPath(forItem: newCardIndex, inSection: 0)]) }, completion: {[weak self] _ in let void: ()? = self?.newCardAnimationInProgress = false }) } //MARK: - UIGestureRecognizerDelegate public func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool { var result:Bool = true if let panGesture = gestureRecognizer as? UIPanGestureRecognizer { let velocity = panGesture.velocityInView(collectionView) result = abs(Int(velocity.y)) < 250 } return result } }
apache-2.0
8fc457326957135da88fd84b4c221eab
43.669444
162
0.65624
5.650387
false
false
false
false
XCEssentials/FunctionalState
Sources/Declare/Stateful.swift
2
6462
/* MIT License Copyright (c) 2016 Maxim Khatskevich ([email protected]) 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. */ /** Turns any class into [discrete system](https://en.wikipedia.org/wiki/Discrete_system). */ public protocol Stateful: class { var dispatcher: Dispatcher { get } } // MARK: - State constructors public extension Stateful { /** One of the designated functions to define a state. - Parameters: - stateId: Internal state identifier that helps to distinguish one state from another. It is supposed to be unique per stateful type. It's highly recommended to always let the function use default value, which is defined by the name of the enclosing function. This guarantees its uniqueness within `Subject` type and it's very convenient for debugging. - transition: Transition that will be used to apply `setBody` mutations. - onSetMutations: Closure that must be called to apply this state (to make it current when this state is NOT current yet, or current state is undefined yet). */ func setStateOnly( stateId: StateIdentifier = #function, via transition: Transition<Self>? = nil, _ onSetMutations: @escaping BasicClosure ) { let state = State<Self>( identifier: stateId, onSet: (onSetMutations, transition ?? DefaultTransitions.instant()), onUpdate: nil ) dispatcher.queue.enqueue(state.toSomeState(with: self)) dispatcher.processNext() } func setOrUpdateState( stateId: StateIdentifier = #function, via sameTransition: Transition<Self>? = nil, _ commonMutations: @escaping BasicClosure ) { let state = State<Self>( identifier: stateId, onSet: (commonMutations, sameTransition ?? DefaultTransitions.instant()), onUpdate: (commonMutations, sameTransition ?? DefaultTransitions.instant()) ) dispatcher.queue.enqueue(state.toSomeState(with: self)) dispatcher.processNext() } func setOrUpdateState( stateId: StateIdentifier = #function, setVia onSetTransition: Transition<Self>? = nil, updateVia onUpdateTransition: Transition<Self>? = nil, _ commonMutations: @escaping BasicClosure ) { let state = State<Self>( identifier: stateId, onSet: (commonMutations, onSetTransition ?? DefaultTransitions.instant()), onUpdate: (commonMutations, onUpdateTransition ?? DefaultTransitions.instant()) ) dispatcher.queue.enqueue(state.toSomeState(with: self)) dispatcher.processNext() } } //--- public extension Stateful { /** One of the designated functions to define a state. - Parameters: - stateId: Internal state identifier that helps to distinguish one state from another. It is supposed to be unique per stateful type. It's highly recommended to always let the function use default value, which is defined by the name of the enclosing function. This guarantees its uniqueness within `Subject` type and it's very convenient for debugging. - transition: Transition that will be used to apply `onSet` mutations. - onSet: Closure that must be called to apply this state (when this state is NOT current yet, or current state is undefined yet, to make it current). - Returns: An intermediate data structure that is used as syntax suger to define a state with both 'onSet' and 'onUpdate' mutations via chainable API. It will keep inside a state value made of all provided parameters (with empty 'onUpdate'). */ func setState( stateId: StateIdentifier = #function, via transition: Transition<Self>? = nil, _ onSetMutations: @escaping BasicClosure ) -> PendingState<Self> { return PendingState( host: self, stateId: stateId, onSetTransition: transition ?? DefaultTransitions.instant(), onSetMutations: onSetMutations ) } } //--- /** An intermediate data structure that is used as syntax suger to define a state with both 'onSet' and 'onUpdate' mutations via chainable API. */ public struct PendingState<Subject: Stateful> { fileprivate let host: Subject fileprivate let stateId: StateIdentifier fileprivate let onSetTransition: Transition<Subject> fileprivate let onSetMutations: BasicClosure } public extension PendingState { /** One of the designated functions to define a state. - Parameters: - onUpdateTransition: Transition that will be used to apply `onUpdate` mutations. - onUpdateMutations: Closure that must be called to apply this state when this state IS already current. This might be useful to update some parameters that the state captures from the outer scope when gets called/created, while entire state stays the same. */ func updateState( via onUpdateTransition: Transition<Subject>? = nil, _ onUpdateMutations: @escaping BasicClosure ) { let state = State<Subject>( identifier: stateId, onSet: (onSetMutations, onSetTransition), onUpdate: (onUpdateMutations, onUpdateTransition ?? DefaultTransitions.instant()) ) host.dispatcher.queue.enqueue(state.toSomeState(with: host)) host.dispatcher.processNext() } }
mit
8fef8695793b202e9ae8b0006f2fb690
33.741935
357
0.695605
4.776053
false
false
false
false