repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
nathantannar4/Parse-Dashboard-for-iOS-Pro
refs/heads/master
Parse Dashboard for iOS/ViewControllers/Misc/Info-About-Settings/AppInfoViewController.swift
mit
1
// // AppInfoViewController.swift // Parse Dashboard for iOS // // Created by Nathan Tannar on 3/4/17. // Copyright © 2017 Nathan Tannar. All rights reserved. // import UIKit import Social class AppInfoViewController: UITableViewController { // MARK: - View Life Cycle override func viewDidLoad() { super.viewDidLoad() title = Localizable.about.localized setupTableView() } // MARK: - Setup private func setupTableView() { tableView.backgroundColor = .groupTableViewBackground tableView.showsVerticalScrollIndicator = false tableView.estimatedRowHeight = 60 tableView.contentInset.bottom = 60 tableView.rowHeight = UITableViewAutomaticDimension tableView.separatorStyle = .none } // MARK: - UITableViewDatasource override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableViewAutomaticDimension } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 7 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell() cell.backgroundColor = .groupTableViewBackground cell.selectionStyle = .none cell.textLabel?.numberOfLines = 0 switch indexPath.row { case 0: let imageView = UIImageView(image: UIImage(named: "Dashboard")) imageView.contentMode = .scaleToFill cell.contentView.addSubview(imageView) imageView.fillSuperview() case 1: cell.textLabel?.text = "Parse Dashboard for iOS" cell.textLabel?.font = UIFont.boldSystemFont(ofSize: 24) let separatorView = UIView() separatorView.backgroundColor = .lightGray cell.contentView.addSubview(separatorView) separatorView.anchor(cell.contentView.bottomAnchor, left: cell.contentView.leftAnchor, right: cell.contentView.rightAnchor, heightConstant: 0.5) case 2: cell.textLabel?.text = Localizable.appDescription.localized cell.textLabel?.textColor = .darkGray cell.textLabel?.font = UIFont.preferredFont(forTextStyle: .body) case 3: cell.textLabel?.text = Localizable.dataSecurity.localized cell.textLabel?.font = UIFont.systemFont(ofSize: 18, weight: UIFont.Weight.medium) let separatorView = UIView() separatorView.backgroundColor = .lightGray cell.contentView.addSubview(separatorView) separatorView.anchor(cell.contentView.bottomAnchor, left: cell.contentView.leftAnchor, right: cell.contentView.rightAnchor, heightConstant: 0.5) case 4: cell.textLabel?.text = Localizable.dataSecurityInfo.localized cell.textLabel?.textColor = .darkGray cell.textLabel?.font = UIFont.preferredFont(forTextStyle: .body) case 5: cell.textLabel?.text = Localizable.openSource.localized cell.textLabel?.font = UIFont.systemFont(ofSize: 18, weight: UIFont.Weight.medium) let separatorView = UIView() separatorView.backgroundColor = .lightGray cell.contentView.addSubview(separatorView) separatorView.anchor(cell.contentView.bottomAnchor, left: cell.contentView.leftAnchor, right: cell.contentView.rightAnchor, heightConstant: 0.5) case 6: cell.textLabel?.text = Localizable.openSourceInfo.localized cell.textLabel?.textColor = .darkGray cell.textLabel?.font = UIFont.preferredFont(forTextStyle: .body) default: break } return cell } }
56707f43dbd508d816674ac0f0478489
38.6
156
0.656566
false
false
false
false
ngquerol/Diurna
refs/heads/master
App/Sources/View Controllers/SidebarViewController.swift
mit
1
// // SidebarViewController.swift // Diurna // // Created by Nicolas Gaulard-Querol on 19/03/2016. // Copyright © 2016 Nicolas Gaulard-Querol. All rights reserved. // import AppKit import HackerNewsAPI import OSLog class SidebarViewController: NSViewController { // MARK: Outlets @IBOutlet var topSpacingConstraint: NSLayoutConstraint! @IBOutlet var tableView: NSTableView! @IBOutlet var loginStatusView: UserLoginStatusView! { didSet { loginStatusView.user = webClient.authenticatedUser loginStatusView.delegate = self } } // MARK: Properties private lazy var notifyFirstCategoryChange: Void = { DispatchQueue.main.async(execute: notifyCategoryChange) }() private var userLoginViewController: UserLoginViewController? // MARK: View Lifecycle override func viewDidAppear() { super.viewDidAppear() _ = notifyFirstCategoryChange } // MARK: Functions func notifyCategoryChange() { guard 0..<StoryType.allCases.count ~= tableView.selectedRow else { return } NotificationCenter.default.post( name: .newCategorySelectedNotification, object: self, userInfo: ["selectedCategory": StoryType.allCases[tableView.selectedRow]] ) } } // MARK: - Notifications extension Notification.Name { static let newCategorySelectedNotification = Notification.Name( "NewCategorySelectedNotification") } // MARK: - NSUserInterfaceItemIdentifier extension NSUserInterfaceItemIdentifier { static let categoryCell = NSUserInterfaceItemIdentifier("CategoryCell") static let categoryRow = NSUserInterfaceItemIdentifier("CategoryRow") } // MARK: - NSTableView Data Source extension SidebarViewController: NSTableViewDataSource { func numberOfRows(in _: NSTableView) -> Int { return StoryType.allCases.count } func tableViewSelectionDidChange(_: Notification) { notifyCategoryChange() } } // MARK: - NSTableView Delegate extension SidebarViewController: NSTableViewDelegate { func tableView(_: NSTableView, heightOfRow _: Int) -> CGFloat { return 30.0 } func tableView(_ tableView: NSTableView, rowViewForRow _: Int) -> NSTableRowView? { return tableView .makeView(withIdentifier: .categoryRow, owner: self) as? NoEmphasisTableRowView } func tableView(_ tableView: NSTableView, viewFor _: NSTableColumn?, row: Int) -> NSView? { let cellView = tableView .makeView(withIdentifier: .categoryCell, owner: self) as? NSTableCellView let selectedCategory = StoryType.allCases[row] cellView?.objectValue = selectedCategory cellView?.textField?.stringValue = "\(selectedCategory.rawValue.capitalized) Stories" cellView?.imageView? .image = NSImage(named: "\(selectedCategory.rawValue.capitalized)IconTemplate") return cellView } } // MARK: - HNWebConsumer extension SidebarViewController: HNWebConsumer {} // MARK: - UserLoginActionDelegate extension SidebarViewController: UserLoginStatusViewDelegate { func userDidRequestLogin() { let userLoginViewController = UserLoginViewController( nibName: .userLoginViewController, bundle: nil ) userLoginViewController.delegate = self self.userLoginViewController = userLoginViewController self.presentAsSheet(userLoginViewController) } func userDidRequestLogout() { webClient.logout { [weak self] logoutResult in switch logoutResult { case .success: self?.loginStatusView.user = nil case .failure: NSAlert.showModal(withTitle: "Failed to log out") } } } } // MARK: - UserLoginViewControllerDelegate extension SidebarViewController: UserLoginViewControllerDelegate { func userDidLogin(with user: String) { userLoginViewController.map(dismiss) userLoginViewController = nil loginStatusView.user = user } func userDidCancelLogin() { userLoginViewController.map(dismiss) userLoginViewController = nil } }
fde8f214a7b3421a3e59255699ab144b
26.477419
94
0.682555
false
false
false
false
cliqz-oss/browser-ios
refs/heads/development
Client/Cliqz/Frontend/Browser/Dashboard/DashboardViewController.swift
mpl-2.0
2
// // DashboardViewController.swift // Client // // Created by Sahakyan on 8/12/16. // Copyright © 2016 Mozilla. All rights reserved. // import Foundation import QuartzCore protocol BrowsingDelegate: class { func didSelectURL(_ url: URL) func didSelectQuery(_ query: String) } enum DashBoardPanelType: Int { case TabsPanel = 0, HistoryPanel, FavoritesPanel, OffrzPanel } class DashboardViewController: UIViewController, BrowsingDelegate { var profile: Profile! let tabManager: TabManager var viewOpenTime : Double? var panelOpenTime : Double? var currentPanel : DashBoardPanelType = .TabsPanel fileprivate var panelSwitchControl = UISegmentedControl(items: []) fileprivate var panelSwitchContainerView: UIView! fileprivate var panelContainerView: UIView! fileprivate let dashboardThemeColor = UIConstants.CliqzThemeColor weak var delegate: BrowserNavigationDelegate! fileprivate lazy var historyViewController: HistoryViewController = { let historyViewController = HistoryViewController(profile: self.profile) historyViewController.delegate = self return historyViewController }() fileprivate lazy var favoritesViewController: FavoritesViewController = { let favoritesViewController = FavoritesViewController(profile: self.profile) favoritesViewController.delegate = self return favoritesViewController }() fileprivate lazy var tabsViewController: TabsViewController = { let tabsViewController = TabsViewController(tabManager: self.tabManager) return tabsViewController }() fileprivate lazy var offrzViewController: OffrzViewController = { let offrz = OffrzViewController(profile: self.profile) offrz.delegate = self return offrz }() init(profile: Profile, tabManager: TabManager) { self.tabManager = tabManager self.profile = profile super.init(nibName: nil, bundle: nil) } deinit { // Removed observers for Connect features NotificationCenter.default.removeObserver(self, name: ShowBrowserViewControllerNotification, object: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() panelSwitchContainerView = UIView() panelSwitchContainerView.backgroundColor = UIColor.white view.addSubview(panelSwitchContainerView) panelContainerView = UIView() view.addSubview(panelContainerView) self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "cliqzBack"), style: .plain, target: self, action: #selector(goBack)) self.navigationItem.title = NSLocalizedString("Overview", tableName: "Cliqz", comment: "Dashboard navigation bar title") self.navigationController?.navigationBar.tintColor = UIColor.black self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: NSLocalizedString("Settings", tableName: "Cliqz", comment: "Setting menu title"), style: .plain, target: self, action: #selector(openSettings)) self.navigationItem.rightBarButtonItem?.setTitleTextAttributes([NSFontAttributeName : UIFont.boldSystemFont(ofSize: 17)], for: UIControlState()) self.navigationItem.rightBarButtonItem?.tintColor = self.dashboardThemeColor view.backgroundColor = UIColor.white viewOpenTime = Date.getCurrentMillis() // Add observers for Connection features NotificationCenter.default.addObserver(self, selector: #selector(dismissView), name: ShowBrowserViewControllerNotification, object: nil) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) getApp().changeStatusBarStyle(.default, backgroundColor: self.view.backgroundColor!, isNormalMode: true) self.navigationController?.isNavigationBarHidden = false self.navigationController?.navigationBar.shadowImage = UIImage() self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default) adJustPanelSwitchControl() self.switchToCurrentPanel() } private func createPanelSwitchControl(numberOfSegments: Int) { guard panelSwitchControl.numberOfSegments != numberOfSegments else { return } let tabs = UIImage(named: "tabs") let history = UIImage(named: "history_quick_access") let fav = UIImage(named: "favorite_quick_access") let offrz = (self.profile.offrzDataSource?.hasUnseenOffrz() ?? false) ? UIImage(named: "offrz_active") : UIImage(named: "offrz_inactive") var items = [tabs, history, fav] if numberOfSegments == 4 { items.append(offrz) } if currentPanel.rawValue >= numberOfSegments { currentPanel = .TabsPanel } panelSwitchControl.removeFromSuperview() panelSwitchControl = UISegmentedControl(items: items) panelSwitchControl.tintColor = self.dashboardThemeColor panelSwitchControl.addTarget(self, action: #selector(switchPanel), for: .valueChanged) panelSwitchContainerView.addSubview(panelSwitchControl) panelSwitchControl.snp.makeConstraints { make in make.centerY.equalTo(panelSwitchContainerView) make.left.equalTo(panelSwitchContainerView).offset(10) make.right.equalTo(panelSwitchContainerView).offset(-10) make.height.equalTo(30) } } private func adJustPanelSwitchControl() { if (self.profile.offrzDataSource?.shouldShowOffrz() ?? false) { createPanelSwitchControl(numberOfSegments: 4) } else { createPanelSwitchControl(numberOfSegments: 3) } } override func viewWillDisappear(_ animated: Bool) { self.navigationController?.isNavigationBarHidden = true super.viewWillDisappear(animated) } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() self.setupConstraints() } override func didRotate(from fromInterfaceOrientation: UIInterfaceOrientation) { // setting the navigation bar origin to (0,0) to prevent shifting it when rotating from landscape to portrait orientation self.navigationController?.navigationBar.frame.origin = CGPoint(x: 0, y: 0) } // Called when send tab notification sent from Connect while dashboard is presented func dismissView() { self.navigationController?.popViewController(animated: false) } func didSelectURL(_ url: URL) { self.navigationController?.popViewController(animated: false) self.delegate?.navigateToURL(url) } func didSelectQuery(_ query: String) { CATransaction.begin() CATransaction.setCompletionBlock({ self.delegate?.navigateToQuery(query) }) self.navigationController?.popViewController(animated: false) CATransaction.commit() } func switchPanel(_ sender: UISegmentedControl) { if let panelType = DashBoardPanelType(rawValue: sender.selectedSegmentIndex) { currentPanel = panelType self.switchToCurrentPanel() } } private func switchToCurrentPanel() { self.panelSwitchControl.selectedSegmentIndex = currentPanel.rawValue var target = "UNDEFINED" self.hideCurrentPanelViewController() switch currentPanel { case .TabsPanel: self.showPanelViewController(self.tabsViewController) target = "openTabs" case .HistoryPanel: self.showPanelViewController(self.historyViewController) target = "history" case .FavoritesPanel: self.showPanelViewController(self.favoritesViewController) target = "favorites" case .OffrzPanel: self.panelSwitchControl.setImage(UIImage(named: "offrz_inactive"), forSegmentAt: 3) self.showPanelViewController(self.offrzViewController) target = "offrz" } logToolbarSignal("click", target: target, customData: nil) } fileprivate func setupConstraints() { panelSwitchContainerView.snp.makeConstraints { make in make.left.right.equalTo(self.view) make.top.equalTo(topLayoutGuide.snp.bottom) make.height.equalTo(65) } panelContainerView.snp.makeConstraints { make in make.top.equalTo(self.panelSwitchContainerView.snp.bottom) make.left.right.bottom.equalTo(self.view) } } fileprivate func showPanelViewController(_ viewController: UIViewController) { addChildViewController(viewController) self.panelContainerView.addSubview(viewController.view) viewController.view.snp.makeConstraints { make in make.top.left.right.bottom.equalTo(self.panelContainerView) } viewController.didMove(toParentViewController: self) logShowPanelSignal(viewController) panelOpenTime = Date.getCurrentMillis() } fileprivate func hideCurrentPanelViewController() { if let panel = childViewControllers.first { panel.willMove(toParentViewController: nil) panel.view.removeFromSuperview() panel.removeFromParentViewController() logHidePanelSignal(panel) } } @objc fileprivate func goBack() { self.navigationController?.popViewController(animated: false) if let openTime = viewOpenTime { let duration = Int(Date.getCurrentMillis() - openTime) logToolbarSignal("click", target: "back", customData: ["show_duration" :duration]) viewOpenTime = nil } } @objc fileprivate func openSettings() { let settingsTableViewController = AppSettingsTableViewController() settingsTableViewController.profile = profile settingsTableViewController.tabManager = tabManager settingsTableViewController.settingsDelegate = self let controller = SettingsNavigationController(rootViewController: settingsTableViewController) controller.popoverDelegate = self controller.modalPresentationStyle = UIModalPresentationStyle.formSheet present(controller, animated: true, completion: nil) logToolbarSignal("click", target: "settings", customData: nil) } } extension DashboardViewController: SettingsDelegate { func settingsOpenURLInNewTab(_ url: URL) { let tab = self.tabManager.addTab(URLRequest(url: url)) self.tabManager.selectTab(tab) self.navigationController?.popViewController(animated: false) } } extension DashboardViewController:PresentingModalViewControllerDelegate { func dismissPresentedModalViewController(_ modalViewController: UIViewController, animated: Bool) { self.dismiss(animated: animated, completion: nil) } } //MARK: - telemetry singals extension DashboardViewController { fileprivate func logToolbarSignal(_ action: String, target: String, customData: [String: Any]?) { TelemetryLogger.sharedInstance.logEvent(.Toolbar(action, target, "overview", nil, customData)) } fileprivate func logShowPanelSignal(_ panel: UIViewController) { let type = getPanelType(panel) TelemetryLogger.sharedInstance.logEvent(.DashBoard(type, "show", nil, nil)) panelOpenTime = nil } fileprivate func logHidePanelSignal(_ panel: UIViewController) { guard let openTime = panelOpenTime else { return } let duration = Int(Date.getCurrentMillis() - openTime) let customData = ["show_duration" : duration] let type = getPanelType(panel) TelemetryLogger.sharedInstance.logEvent(.DashBoard(type, "hide", nil, customData)) panelOpenTime = nil } private func getPanelType(_ panel: UIViewController) -> String { switch panel { case tabsViewController: return "open_tabs" case historyViewController: return "history" case favoritesViewController: return "favorites" default: return "UNDEFINED" } } }
cdc0d73d987370dea8c5f0b145023891
34.379104
210
0.721482
false
false
false
false
P0ed/FireTek
refs/heads/master
Source/IO/GamepadKit/EventsController.swift
mit
1
import Foundation import OpenEmuSystem class EventsController { lazy var deviceConfiguration = DeviceConfiguration(buttonsMapTable: [:], dPadMapTable: [:], keyboardMapTable: [:]) var leftJoystick = DSVector.zeroVector var rightJoystick = DSVector.zeroVector var leftTrigger = 0.0 var rightTrigger = 0.0 var hatDirection = DSHatDirection.null func handleEvent(_ event: OEHIDEvent) { switch event.type.rawValue { case OEHIDEventTypeAxis.rawValue: switch event.axis.rawValue { case OEHIDEventAxisX.rawValue: leftJoystick.dx = event.value.native case OEHIDEventAxisY.rawValue: leftJoystick.dy = -event.value.native case OEHIDEventAxisZ.rawValue: rightJoystick.dx = event.value.native case OEHIDEventAxisRz.rawValue: rightJoystick.dy = -event.value.native default: break } case OEHIDEventTypeTrigger.rawValue: switch event.axis.rawValue { case OEHIDEventAxisRx.rawValue: leftTrigger = event.value.native case OEHIDEventAxisRy.rawValue: rightTrigger = event.value.native default: break } case OEHIDEventTypeButton.rawValue: if let button = DSButton(rawValue: Int(event.buttonNumber)), let action = deviceConfiguration.buttonsMapTable[button] { action.performAction(event.state == OEHIDEventStateOn) } case OEHIDEventTypeHatSwitch.rawValue: if let hatDirection = DSHatDirection(rawValue: Int(event.hatDirection.rawValue)) { let buttons = changedStateDPadButtons(self.hatDirection, current: hatDirection) self.hatDirection = hatDirection func performActions(_ buttons: [DSHatDirection], pressed: Bool) { buttons.forEach { button in if let action = deviceConfiguration.dPadMapTable[button] { action.performAction(pressed) } } } performActions(buttons.up, pressed: false) performActions(buttons.down, pressed: true) } case OEHIDEventTypeKeyboard.rawValue: if let action = deviceConfiguration.keyboardMapTable[Int(event.keycode)] { action.performAction(event.state == OEHIDEventStateOn) } default: break } } func controlForEvent(_ event: OEHIDEvent) -> DSControl? { var control: DSControl? switch event.type.rawValue { case OEHIDEventTypeAxis.rawValue: if event.axis.rawValue == OEHIDEventAxisX.rawValue || event.axis.rawValue == OEHIDEventAxisY.rawValue { control = .stick(.left) } else if event.axis.rawValue == OEHIDEventAxisZ.rawValue || event.axis.rawValue == OEHIDEventAxisRz.rawValue { control = .stick(.right) } case OEHIDEventTypeTrigger.rawValue: if event.axis.rawValue == OEHIDEventAxisRx.rawValue { control = .trigger(.left) } else if event.axis.rawValue == OEHIDEventAxisRy.rawValue { control = .trigger(.right) } case OEHIDEventTypeButton.rawValue: if let button = DSButton(rawValue: Int(event.buttonNumber)) { control = .button(button) } case OEHIDEventTypeHatSwitch.rawValue: if let hatDirection = DSHatDirection(rawValue: Int(event.hatDirection.rawValue)) { control = .dPad(hatDirection) } default: break } return control } } func changedStateDPadButtons(_ previous: DSHatDirection, current: DSHatDirection) -> (up: [DSHatDirection], down: [DSHatDirection]) { var up: [DSHatDirection] = [] var down: [DSHatDirection] = [] for i in 0...3 { let bit = 1 << i let was = previous.rawValue & bit let now = current.rawValue & bit if was != now { if was != 0 { up.append(DSHatDirection(rawValue: bit)!) } else { down.append(DSHatDirection(rawValue: bit)!) } } } return (up, down) }
1fb04e83b0a52f1d1b1557b3723e738a
30.513274
133
0.724235
false
false
false
false
mrdepth/EVEUniverse
refs/heads/master
Legacy/Neocom/Neocom/NCDatabaseGroupsViewController.swift
lgpl-2.1
2
// // NCDatabaseGroupsViewController.swift // Neocom // // Created by Artem Shimanski on 08.12.16. // Copyright © 2016 Artem Shimanski. All rights reserved. // import UIKit import CoreData import EVEAPI import Futures class NCDatabaseGroupRow: NCFetchedResultsObjectNode<NCDBInvGroup> { required init(object: NCDBInvGroup) { super.init(object: object) cellIdentifier = Prototype.NCDefaultTableViewCell.compact.reuseIdentifier } override func configure(cell: UITableViewCell) { guard let cell = cell as? NCDefaultTableViewCell else {return} cell.titleLabel?.text = object.groupName cell.iconView?.image = object.icon?.image?.image ?? NCDBEveIcon.defaultGroup.image?.image cell.accessoryType = .disclosureIndicator } } class NCDatabaseGroupsViewController: NCTreeViewController, NCSearchableViewController { var category: NCDBInvCategory? override func viewDidLoad() { super.viewDidLoad() tableView.register([Prototype.NCHeaderTableViewCell.default, Prototype.NCDefaultTableViewCell.compact]) setupSearchController(searchResultsController: self.storyboard!.instantiateViewController(withIdentifier: "NCDatabaseTypesViewController")) title = category?.categoryName } override func didReceiveMemoryWarning() { if !isViewLoaded || view.window == nil { treeController?.content = nil } } override func content() -> Future<TreeNode?> { let request = NSFetchRequest<NCDBInvGroup>(entityName: "InvGroup") request.sortDescriptors = [NSSortDescriptor(key: "published", ascending: false), NSSortDescriptor(key: "groupName", ascending: true)] request.predicate = NSPredicate(format: "category == %@ AND types.@count > 0", category!) let results = NSFetchedResultsController(fetchRequest: request, managedObjectContext: NCDatabase.sharedDatabase!.viewContext, sectionNameKeyPath: "published", cacheName: nil) return .init(FetchedResultsNode(resultsController: results, sectionNode: NCDatabasePublishingSectionNode<NCDBInvGroup>.self, objectNode: NCDatabaseGroupRow.self)) } //MARK: - TreeControllerDelegate override func treeController(_ treeController: TreeController, didSelectCellWithNode node: TreeNode) { super.treeController(treeController, didSelectCellWithNode: node) guard let row = node as? NCDatabaseGroupRow else {return} Router.Database.Types(group: row.object).perform(source: self, sender: treeController.cell(for: node)) } //MARK: NCSearchableViewController var searchController: UISearchController? func updateSearchResults(for searchController: UISearchController) { let predicate: NSPredicate guard let controller = searchController.searchResultsController as? NCDatabaseTypesViewController else {return} if let text = searchController.searchBar.text, let category = category, text.count > 2 { predicate = NSPredicate(format: "group.category == %@ AND typeName CONTAINS[C] %@", category, text) } else { predicate = NSPredicate(value: false) } controller.predicate = predicate controller.reloadData() } }
031eecbc6b1273ef227b8ade6f42e482
36.158537
176
0.774532
false
false
false
false
siberianisaev/XcassetsCreator
refs/heads/master
XcassetsCreator/AppDelegate.swift
mit
1
// // AppDelegate.swift // XcassetsCreator // // Created by Andrey Isaev on 26.04.15. // Copyright (c) 2015 Andrey Isaev. All rights reserved. // import Cocoa import AppKit @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { @IBOutlet weak var window: NSWindow! @IBOutlet weak var progressIndicator: NSProgressIndicator! fileprivate var folderPath: String? fileprivate var assetsFolderPath: String { return (folderPath! as NSString).appendingPathComponent((folderPath! as NSString).lastPathComponent + ".xcassets") } func applicationDidFinishLaunching(_ aNotification: Notification) { // Insert code here to initialize your application } func applicationWillTerminate(_ aNotification: Notification) { // Insert code here to tear down your application } @IBAction func selectFolder(_ sender: AnyObject) { OpenPanel.open { [unowned self] (folders: [String]?) in if let folders = folders { for folderPath in folders { self.folderPath = folderPath do { var files = try FileManager.default.contentsOfDirectory(atPath: folderPath) files = files.filter() { let pathExtension = ($0 as NSString).pathExtension // Supported Image Formats https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIImage_Class/index.html for value in ["png", "jpg", "jpeg", "tiff", "tif", "gif", "bmp", "BMPf", "ico", "cur", "xbm"] { if pathExtension.caseInsensitiveCompare(value) == ComparisonResult.orderedSame { return true } } return false } self.createAssetCataloguesWithImages(files) } catch { print(error) } } } } } fileprivate func createAssetCataloguesWithImages(_ images: [String]) { if images.isEmpty { return } let assetsPath = assetsFolderPath let fm = FileManager.default if false == fm.fileExists(atPath: assetsPath) { do { try fm.createDirectory(atPath: assetsPath, withIntermediateDirectories: true, attributes: nil) } catch { print(error) return } } self.progressIndicator.startAnimation(nil) let sorted = images.sorted(by: { $0.localizedCaseInsensitiveCompare($1) == ComparisonResult.orderedDescending }) var assetsDict = [String: Asset]() for imageFileName in sorted { var name = (imageFileName as NSString).deletingPathExtension for value in ["-568h", "@2x", "@3x", "~ipad", "~iphone"] { name = name.stringByRemoveSubstring(value) } if name.isEmpty { continue } var asset = assetsDict[name] if asset == nil { asset = Asset(name: name) assetsDict[name] = asset } asset!.images.append(imageFileName) } for (_, value) in assetsDict { value.createAsset(assetsFolderPath) // Create asset folder & contents json for imageName in value.images { // Copy images to asset if let folderPath = folderPath, let path = value.path { let oldPath = (folderPath as NSString).appendingPathComponent(imageName) let newPath = (path as NSString).appendingPathComponent(imageName) do { try fm.copyItem(atPath: oldPath, toPath: newPath) } catch { print(error) } } } } NSWorkspace.shared.openFile(assetsFolderPath) self.progressIndicator.stopAnimation(nil) } }
55481218fb461588f777b8337fd8d8a1
34.708333
149
0.528821
false
false
false
false
laurentVeliscek/AudioKit
refs/heads/master
AudioKit/Common/Internals/CoreAudio/AKGetAUParams.swift
mit
2
// // AKGetAUParams.swift // AudioKit // // Created by Jeff Cooper, revision history on Github. // Copyright © 2016 AudioKit. All rights reserved. // import Foundation import AVFoundation /// Audio from the standard input public struct AKGetAUParams { private func getAUParams(inputAU: AudioUnit) -> ([AudioUnitParameterInfo]) { // Get number of parameters in this unit (size in bytes really): var size: UInt32 = 0 var propertyBool = DarwinBoolean(true) AudioUnitGetPropertyInfo( inputAU, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global, 0, &size, &propertyBool) let numParams = Int(size)/sizeof(AudioUnitParameterID) var parameterIDs = [AudioUnitParameterID](zeroes: Int(numParams)) AudioUnitGetProperty( inputAU, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global, 0, &parameterIDs, &size) var paramInfo = AudioUnitParameterInfo() var outParams = [AudioUnitParameterInfo]() var parameterInfoSize: UInt32 = UInt32(sizeof(AudioUnitParameterInfo)) for paramID in parameterIDs { AudioUnitGetProperty( inputAU, kAudioUnitProperty_ParameterInfo, kAudioUnitScope_Global, paramID, &paramInfo, &parameterInfoSize) outParams.append(paramInfo) print(paramID) print("Paramer name :\(paramInfo.cfNameString?.takeUnretainedValue()) | " + "Min:\(paramInfo.minValue) | " + "Max:\(paramInfo.maxValue) | " + "Default: \(paramInfo.defaultValue)") } return outParams } }
7fdf65630a468538533fd19374974601
31.803571
87
0.586282
false
false
false
false
niunaruto/DeDaoAppSwift
refs/heads/master
DeDaoSwift/DeDaoSwift/BaseClass/DDBaseTableViewModel.swift
mit
1
// // DDBaseTableViewModel.swift // DeDaoSwift // // Created by niuting on 2017/3/3. // Copyright © 2017年 niuNaruto. All rights reserved. // import UIKit import ObjectMapper public enum loadDataFinishedStatus : Int { case success case error } protocol viewModelDelegate : class { func loadDataFinished(_ vm : Any, _ status : loadDataFinishedStatus) } class DDBaseTableViewModel: DDBaseViewModel { /// 设置tableViewStyle 默认plain var tableViewStyle : UITableViewStyle? lazy var dataArray = Array<Any>() lazy var useRefreshControl = true lazy var useLoadMoreControl = true var cellClass : AnyClass? var headFootViewClass : AnyClass? var model : Any? weak var delegate : viewModelDelegate? override init() { super.init() if let style = tableViewStyle{ tableViewStyle = style }else{ tableViewStyle = UITableViewStyle.plain } initViewModel() } init(_ model : Any? = nil ,_ cellClass : AnyClass? = nil) { self.model = model self.cellClass = cellClass } } extension DDBaseTableViewModel { func initViewModel() { } } // MARK: - DDBaseTableViewModel,UITableViewDataSource extension DDBaseTableViewModel : UITableViewDataSource,UITableViewDelegate { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataArray.count; } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let vm = dataAtIndexPath(indexPath) let cell: DDBaseTableViewCell = tableView.cellForIndexPath(indexPath, cellClass: vm.cellClass)! cell.setCellsViewModel(vm.model) cell.delegate = self return cell } func dataAtIndexPath(_ indexPath : IndexPath) -> DDBaseTableViewModel { return DDBaseTableViewModel.init() } } extension DDBaseTableViewModel : DDBaseCellProtocol { func tableCell(cell: DDBaseTableViewCell, didTrigerEvent: DDCellEventType, params: Dictionary<String, Any>?) { } } // MARK: - 提供给控制器的刷新 方法 extension DDBaseTableViewModel { func refreshNewData() { refreshData({ (list) in dataArray.removeAll() if list.count > 0 { for i in 0...(list.count - 1) { /// 数据包装成model let vm = createViewModelWithModel(list[i]) dataArray.append(vm) } } delegate?.loadDataFinished(list, .success) }) { (errorMessege) in delegate?.loadDataFinished(errorMessege, .error) } } func loadMoreData() { refreshMoreData({ (list) in delegate?.loadDataFinished(list, .success) }) { (errorMessege) in delegate?.loadDataFinished(errorMessege, .error) } } } extension DDBaseTableViewModel { func createViewModelWithModel(_ model : Any? = nil ,_ cellClass : AnyClass? = nil) -> DDBaseTableViewModel{ return DDBaseTableViewModel.init(model, cellClass) } } // MARK: 子类需要重写的方法 获取网络数据 extension DDBaseTableViewModel { /// 刷新数据 /// /// - Parameters: /// - success: 请求成功的回调 /// - failure: 失败回调 func refreshData(_ array: (Array<Any>) -> (), _ error : ((String) -> ())) { } /// 请求更多数据 /// /// - Parameters: /// - success: 请求成功的回调 /// - failure: 失败回调 func refreshMoreData(_:(_ list : Array<Any>)->(),_:((_ erroeMessege:String)->())) { } }
8acd121b79a1e55b9cc2772af79af736
21.526316
114
0.57243
false
false
false
false
2345Team/Swifter-Tips
refs/heads/master
15.Any和AnyObject/Any和AnyObject/Any和AnyObject/ViewController.swift
mit
1
// // ViewController.swift // Any和AnyObject // // Created by wanglili on 16/9/7. // Copyright © 2016年 wanglili. All rights reserved. // import UIKit class ViewController: UIViewController { //假设原来的某个 API 返回的是一个 id,那么在 Swift 中现在就将被映射为 AnyObject? (因为 id 是可以指向 nil 的,所以在这里我们需要一个 Optional 的版本) func someMethod() -> AnyObject? { return "123" } override func viewDidLoad() { super.viewDidLoad() // 所有的 class 都隐式地实现了这个接口,这也是 AnyObject 只适用于 class 类型的原因 let anyObject: AnyObject? = self.someMethod() // as? 返回一个你试图想转成的类型的可选值 if let someInstance = anyObject as? String { // ... // 这里我们拿到了具体 SomeRealClass 的实例 someInstance.startIndex } /* struct 类型,并不能由 AnyObject 来表示,于是 Apple 提出了一个更为特殊的 Any,除了 class 以外,它还可以表示包括 struct 和 enum 在内的所有类型。 */ // 我们在这里声明了一个 Int 和一个 String,按理说它们都应该只能被 Any 代表,而不能被 AnyObject 代表的 // 因为我们显式地声明了需要 AnyObject,编译器认为我们需要的的是 Cocoa 类型而非原生类型,而帮我们进行了自动的转换 let swiftInt: Int = 1 let swiftString: String = "miao" var array: [AnyObject] = [] array.append(swiftInt) array.append(swiftString) print(array.first) print(array.last) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
7bde24493e9756cc4442c9534bd4dcfe
26.203704
105
0.605174
false
false
false
false
itsaboutcode/WordPress-iOS
refs/heads/develop
WordPress/WordPressThisWeekWidget/Tracks+ThisWeekWidget.swift
gpl-2.0
1
import Foundation /// This extension implements helper tracking methods, meant for Today Widget Usage. /// extension Tracks { // MARK: - Public Methods public func trackExtensionStatsLaunched(_ siteID: Int) { let properties = ["site_id": siteID] trackExtensionEvent(.statsLaunched, properties: properties as [String: AnyObject]?) } public func trackExtensionConfigureLaunched() { trackExtensionEvent(.configureLaunched) } public func trackDisplayModeChanged(properties: [String: Bool]) { trackExtensionEvent(.displayModeChanged, properties: properties as [String: AnyObject]) } // MARK: - Private Helpers fileprivate func trackExtensionEvent(_ event: ExtensionEvents, properties: [String: AnyObject]? = nil) { track(event.rawValue, properties: properties) } // MARK: - Private Enums fileprivate enum ExtensionEvents: String { case statsLaunched = "wpios_week_views_extension_stats_launched" case configureLaunched = "wpios_week_views_extension_configure_launched" case displayModeChanged = "wpios_week_views_extension_display_mode_changed" } }
75c200ac684f39c5e102582a2b98dfca
30.810811
108
0.702634
false
true
false
false
jgainfort/FRPlayer
refs/heads/master
FRPlayer/TimeUtil.swift
mit
1
// // TimeUtil.swift // FRPlayer // // Created by John Gainfort Jr on 4/3/17. // Copyright © 2017 John Gainfort Jr. All rights reserved. // import Foundation class TimeUtil { func formatSecondsToString(seconds: Double) -> String { let hr = addLeadingZero(floor(seconds / 3600)) let min = addLeadingZero(floor(seconds.truncatingRemainder(dividingBy: 3600)) / 60) let sec = addLeadingZero(floor(seconds.truncatingRemainder(dividingBy: 60))) return hr != "00" ? "\(hr):\(min):\(sec)" : "\(min):\(sec)" } private func addLeadingZero(_ num: Double) -> String { let formatter = NumberFormatter() formatter.minimumIntegerDigits = 2 return formatter.string(from: NSNumber(value: num)) ?? "00" } }
519c9c7b389571e430c5ef62fc278005
27.607143
91
0.619226
false
false
false
false
zpz1237/NirBillBoard
refs/heads/master
NirBillboard/ExploreAViewController.swift
mit
1
// // ExploreAViewController.swift // NirBillboard // // Created by Nirvana on 7/13/15. // Copyright © 2015 NSNirvana. All rights reserved. // import UIKit var exploreContentsArray = [CellContents]() var exploreContentsModel = CellContents() class ExploreAViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() exploreContentsModel.titleLabelText = "旅行" exploreContentsModel.detailTitleLabelText = "Yosemite国家公园" exploreContentsModel.timeDescribleText = "7月21日 - 8月2日" exploreContentsModel.chosenImageImage = UIImage(named: "exploreA")! exploreContentsArray.append(exploreContentsModel) exploreContentsModel.titleLabelText = "旅行" exploreContentsModel.detailTitleLabelText = "Yosemite国家公园" exploreContentsModel.timeDescribleText = "7月21日 - 8月2日" exploreContentsModel.chosenImageImage = UIImage(named: "exploreB")! exploreContentsArray.append(exploreContentsModel) exploreContentsModel.titleLabelText = "旅行" exploreContentsModel.detailTitleLabelText = "Yosemite国家公园" exploreContentsModel.timeDescribleText = "7月21日 - 8月2日" exploreContentsModel.chosenImageImage = UIImage(named: "exploreC")! exploreContentsArray.append(exploreContentsModel) exploreContentsModel.titleLabelText = "旅行" exploreContentsModel.detailTitleLabelText = "Yosemite国家公园" exploreContentsModel.timeDescribleText = "7月21日 - 8月2日" exploreContentsModel.chosenImageImage = UIImage(named: "exploreD")! exploreContentsArray.append(exploreContentsModel) } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 180 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("exploreCell")! as! ExploreATableViewCell cell.exploreTitleLabel.text = exploreContentsArray[indexPath.row].detailTitleLabelText cell.exploreTypeLabel.text = exploreContentsArray[indexPath.row].titleLabelText cell.exploreTimeLabel.text = exploreContentsArray[indexPath.row].timeDescribleText cell.exploreImageView.image = exploreContentsArray[indexPath.row].chosenImageImage return cell } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 4 } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
14b1df36c4f8607fefe2cf18ee30baea
37.238095
109
0.712329
false
false
false
false
QueryKit/TodoExample
refs/heads/master
Pods/QueryKit/QueryKit/Attribute.swift
bsd-2-clause
4
import Foundation /// An attribute, representing an attribute on a model public struct Attribute<AttributeType> : Equatable { public let key:String public init(_ key:String) { self.key = key } /// Builds a compound attribute with other key paths public init(attributes:[String]) { self.init(attributes.joinWithSeparator(".")) } /// Returns an expression for the attribute public var expression:NSExpression { return NSExpression(forKeyPath: key) } // MARK: Sorting /// Returns an ascending sort descriptor for the attribute public func ascending() -> NSSortDescriptor { return NSSortDescriptor(key: key, ascending: true) } /// Returns a descending sort descriptor for the attribute public func descending() -> NSSortDescriptor { return NSSortDescriptor(key: key, ascending: false) } func expressionForValue(value:AttributeType?) -> NSExpression { if let value = value { if let value = value as? NSObject { return NSExpression(forConstantValue: value as NSObject) } if sizeof(value.dynamicType) == sizeof(uintptr_t) { let value = unsafeBitCast(value, Optional<NSObject>.self) if let value = value { return NSExpression(forConstantValue: value) } } let value = unsafeBitCast(value, Optional<String>.self) if let value = value { return NSExpression(forConstantValue: value) } } return NSExpression(forConstantValue: NSNull()) } /// Builds a compound attribute by the current attribute with the given attribute public func attribute<T>(attribute:Attribute<T>) -> Attribute<T> { return Attribute<T>(attributes: [key, attribute.key]) } } /// Returns true if two attributes have the same name public func == <AttributeType>(lhs: Attribute<AttributeType>, rhs: Attribute<AttributeType>) -> Bool { return lhs.key == rhs.key } public func == <AttributeType>(left: Attribute<AttributeType>, right: AttributeType?) -> NSPredicate { return left.expression == left.expressionForValue(right) } public func != <AttributeType>(left: Attribute<AttributeType>, right: AttributeType?) -> NSPredicate { return left.expression != left.expressionForValue(right) } public func > <AttributeType>(left: Attribute<AttributeType>, right: AttributeType?) -> NSPredicate { return left.expression > left.expressionForValue(right) } public func >= <AttributeType>(left: Attribute<AttributeType>, right: AttributeType?) -> NSPredicate { return left.expression >= left.expressionForValue(right) } public func < <AttributeType>(left: Attribute<AttributeType>, right: AttributeType?) -> NSPredicate { return left.expression < left.expressionForValue(right) } public func <= <AttributeType>(left: Attribute<AttributeType>, right: AttributeType?) -> NSPredicate { return left.expression <= left.expressionForValue(right) } public func ~= <AttributeType>(left: Attribute<AttributeType>, right: AttributeType?) -> NSPredicate { return left.expression ~= left.expressionForValue(right) } public func << <AttributeType>(left: Attribute<AttributeType>, right: [AttributeType]) -> NSPredicate { let value = right.map { value in return value as! NSObject } return left.expression << NSExpression(forConstantValue: value) } public func << <AttributeType>(left: Attribute<AttributeType>, right: Range<AttributeType>) -> NSPredicate { let value = [right.startIndex as! NSObject, right.endIndex as! NSObject] as NSArray let rightExpression = NSExpression(forConstantValue: value) return NSComparisonPredicate(leftExpression: left.expression, rightExpression: rightExpression, modifier: NSComparisonPredicateModifier.DirectPredicateModifier, type: NSPredicateOperatorType.BetweenPredicateOperatorType, options: NSComparisonPredicateOptions(rawValue: 0)) } /// MARK: Bool Attributes prefix public func ! (left: Attribute<Bool>) -> NSPredicate { return left == false } public extension QuerySet { public func filter(attribute:Attribute<Bool>) -> QuerySet<ModelType> { return filter(attribute == true) } public func exclude(attribute:Attribute<Bool>) -> QuerySet<ModelType> { return filter(attribute == false) } } // MARK: Collections public func count(attribute:Attribute<NSSet>) -> Attribute<Int> { return Attribute<Int>(attributes: [attribute.key, "@count"]) } public func count(attribute:Attribute<NSOrderedSet>) -> Attribute<Int> { return Attribute<Int>(attributes: [attribute.key, "@count"]) }
0391fba9908e3795fb899610432928a4
33.381679
274
0.728464
false
false
false
false
Drusy/auvergne-webcams-ios
refs/heads/develop
Carthage/Checkouts/realm-cocoa/RealmSwift/List.swift
apache-2.0
6
//////////////////////////////////////////////////////////////////////////// // // Copyright 2014 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import Foundation import Realm import Realm.Private /// :nodoc: /// Internal class. Do not use directly. public class ListBase: RLMListBase { // Printable requires a description property defined in Swift (and not obj-c), // and it has to be defined as override, which can't be done in a // generic class. /// Returns a human-readable description of the objects contained in the List. @objc public override var description: String { return descriptionWithMaxDepth(RLMDescriptionMaxDepth) } @objc private func descriptionWithMaxDepth(_ depth: UInt) -> String { return RLMDescriptionWithMaxDepth("List", _rlmArray, depth) } /// Returns the number of objects in this List. public var count: Int { return Int(_rlmArray.count) } } /** `List` is the container type in Realm used to define to-many relationships. Like Swift's `Array`, `List` is a generic type that is parameterized on the type it stores. This can be either an `Object` subclass or one of the following types: `Bool`, `Int`, `Int8`, `Int16`, `Int32`, `Int64`, `Float`, `Double`, `String`, `Data`, and `Date` (and their optional versions) Unlike Swift's native collections, `List`s are reference types, and are only immutable if the Realm that manages them is opened as read-only. Lists can be filtered and sorted with the same predicates as `Results<Element>`. Properties of `List` type defined on `Object` subclasses must be declared as `let` and cannot be `dynamic`. */ public final class List<Element: RealmCollectionValue>: ListBase { // MARK: Properties /// The Realm which manages the list, or `nil` if the list is unmanaged. public var realm: Realm? { return _rlmArray.realm.map { Realm($0) } } /// Indicates if the list can no longer be accessed. public var isInvalidated: Bool { return _rlmArray.isInvalidated } // MARK: Initializers /// Creates a `List` that holds Realm model objects of type `Element`. public override init() { super.init(array: Element._rlmArray()) } internal init(rlmArray: RLMArray<AnyObject>) { super.init(array: rlmArray) } // MARK: Index Retrieval /** Returns the index of an object in the list, or `nil` if the object is not present. - parameter object: An object to find. */ public func index(of object: Element) -> Int? { return notFoundToNil(index: _rlmArray.index(of: dynamicBridgeCast(fromSwift: object) as AnyObject)) } /** Returns the index of the first object in the list matching the predicate, or `nil` if no objects match. - parameter predicate: The predicate with which to filter the objects. */ public func index(matching predicate: NSPredicate) -> Int? { return notFoundToNil(index: _rlmArray.indexOfObject(with: predicate)) } /** Returns the index of the first object in the list matching the predicate, or `nil` if no objects match. - parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments. */ public func index(matching predicateFormat: String, _ args: Any...) -> Int? { return index(matching: NSPredicate(format: predicateFormat, argumentArray: unwrapOptionals(in: args))) } // MARK: Object Retrieval /** Returns the object at the given index (get), or replaces the object at the given index (set). - warning: You can only set an object during a write transaction. - parameter index: The index of the object to retrieve or replace. */ public subscript(position: Int) -> Element { get { throwForNegativeIndex(position) return dynamicBridgeCast(fromObjectiveC: _rlmArray.object(at: UInt(position))) } set { throwForNegativeIndex(position) _rlmArray.replaceObject(at: UInt(position), with: dynamicBridgeCast(fromSwift: newValue) as AnyObject) } } /// Returns the first object in the list, or `nil` if the list is empty. public var first: Element? { return _rlmArray.firstObject().map(dynamicBridgeCast) } /// Returns the last object in the list, or `nil` if the list is empty. public var last: Element? { return _rlmArray.lastObject().map(dynamicBridgeCast) } // MARK: KVC /** Returns an `Array` containing the results of invoking `valueForKey(_:)` using `key` on each of the collection's objects. */ @nonobjc public func value(forKey key: String) -> [AnyObject] { return _rlmArray.value(forKeyPath: key)! as! [AnyObject] } /** Returns an `Array` containing the results of invoking `valueForKeyPath(_:)` using `keyPath` on each of the collection's objects. - parameter keyPath: The key path to the property whose values are desired. */ @nonobjc public func value(forKeyPath keyPath: String) -> [AnyObject] { return _rlmArray.value(forKeyPath: keyPath) as! [AnyObject] } /** Invokes `setValue(_:forKey:)` on each of the collection's objects using the specified `value` and `key`. - warning: This method can only be called during a write transaction. - parameter value: The object value. - parameter key: The name of the property whose value should be set on each object. */ public override func setValue(_ value: Any?, forKey key: String) { return _rlmArray.setValue(value, forKeyPath: key) } // MARK: Filtering /** Returns a `Results` containing all objects matching the given predicate in the list. - parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments. */ public func filter(_ predicateFormat: String, _ args: Any...) -> Results<Element> { return Results<Element>(_rlmArray.objects(with: NSPredicate(format: predicateFormat, argumentArray: unwrapOptionals(in: args)))) } /** Returns a `Results` containing all objects matching the given predicate in the list. - parameter predicate: The predicate with which to filter the objects. */ public func filter(_ predicate: NSPredicate) -> Results<Element> { return Results<Element>(_rlmArray.objects(with: predicate)) } // MARK: Sorting /** Returns a `Results` containing the objects in the list, but sorted. Objects are sorted based on the values of the given key path. For example, to sort a list of `Student`s from youngest to oldest based on their `age` property, you might call `students.sorted(byKeyPath: "age", ascending: true)`. - warning: Lists may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision floating point, integer, and string types. - parameter keyPath: The key path to sort by. - parameter ascending: The direction to sort in. */ public func sorted(byKeyPath keyPath: String, ascending: Bool = true) -> Results<Element> { return sorted(by: [SortDescriptor(keyPath: keyPath, ascending: ascending)]) } /** Returns a `Results` containing the objects in the list, but sorted. - warning: Lists may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision floating point, integer, and string types. - see: `sorted(byKeyPath:ascending:)` */ public func sorted<S: Sequence>(by sortDescriptors: S) -> Results<Element> where S.Iterator.Element == SortDescriptor { return Results<Element>(_rlmArray.sortedResults(using: sortDescriptors.map { $0.rlmSortDescriptorValue })) } // MARK: Aggregate Operations /** Returns the minimum (lowest) value of the given property among all the objects in the list, or `nil` if the list is empty. - warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified. - parameter property: The name of a property whose minimum value is desired. */ public func min<T: MinMaxType>(ofProperty property: String) -> T? { return _rlmArray.min(ofProperty: property).map(dynamicBridgeCast) } /** Returns the maximum (highest) value of the given property among all the objects in the list, or `nil` if the list is empty. - warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified. - parameter property: The name of a property whose maximum value is desired. */ public func max<T: MinMaxType>(ofProperty property: String) -> T? { return _rlmArray.max(ofProperty: property).map(dynamicBridgeCast) } /** Returns the sum of the values of a given property over all the objects in the list. - warning: Only a property whose type conforms to the `AddableType` protocol can be specified. - parameter property: The name of a property whose values should be summed. */ public func sum<T: AddableType>(ofProperty property: String) -> T { return dynamicBridgeCast(fromObjectiveC: _rlmArray.sum(ofProperty: property)) } /** Returns the average value of a given property over all the objects in the list, or `nil` if the list is empty. - warning: Only a property whose type conforms to the `AddableType` protocol can be specified. - parameter property: The name of a property whose average value should be calculated. */ public func average(ofProperty property: String) -> Double? { return _rlmArray.average(ofProperty: property).map(dynamicBridgeCast) } // MARK: Mutation /** Appends the given object to the end of the list. If the object is managed by a different Realm than the receiver, a copy is made and added to the Realm managing the receiver. - warning: This method may only be called during a write transaction. - parameter object: An object. */ public func append(_ object: Element) { _rlmArray.add(dynamicBridgeCast(fromSwift: object) as AnyObject) } /** Appends the objects in the given sequence to the end of the list. - warning: This method may only be called during a write transaction. */ public func append<S: Sequence>(objectsIn objects: S) where S.Iterator.Element == Element { for obj in objects { _rlmArray.add(dynamicBridgeCast(fromSwift: obj) as AnyObject) } } /** Inserts an object at the given index. - warning: This method may only be called during a write transaction. - warning: This method will throw an exception if called with an invalid index. - parameter object: An object. - parameter index: The index at which to insert the object. */ public func insert(_ object: Element, at index: Int) { throwForNegativeIndex(index) _rlmArray.insert(dynamicBridgeCast(fromSwift: object) as AnyObject, at: UInt(index)) } /** Removes an object at the given index. The object is not removed from the Realm that manages it. - warning: This method may only be called during a write transaction. - warning: This method will throw an exception if called with an invalid index. - parameter index: The index at which to remove the object. */ public func remove(at index: Int) { throwForNegativeIndex(index) _rlmArray.removeObject(at: UInt(index)) } /** Removes all objects from the list. The objects are not removed from the Realm that manages them. - warning: This method may only be called during a write transaction. */ public func removeAll() { _rlmArray.removeAllObjects() } /** Replaces an object at the given index with a new object. - warning: This method may only be called during a write transaction. - warning: This method will throw an exception if called with an invalid index. - parameter index: The index of the object to be replaced. - parameter object: An object. */ public func replace(index: Int, object: Element) { throwForNegativeIndex(index) _rlmArray.replaceObject(at: UInt(index), with: dynamicBridgeCast(fromSwift: object) as AnyObject) } /** Moves the object at the given source index to the given destination index. - warning: This method may only be called during a write transaction. - warning: This method will throw an exception if called with invalid indices. - parameter from: The index of the object to be moved. - parameter to: index to which the object at `from` should be moved. */ public func move(from: Int, to: Int) { throwForNegativeIndex(from) throwForNegativeIndex(to) _rlmArray.moveObject(at: UInt(from), to: UInt(to)) } /** Exchanges the objects in the list at given indices. - warning: This method may only be called during a write transaction. - warning: This method will throw an exception if called with invalid indices. - parameter index1: The index of the object which should replace the object at index `index2`. - parameter index2: The index of the object which should replace the object at index `index1`. */ public func swapAt(_ index1: Int, _ index2: Int) { throwForNegativeIndex(index1, parameterName: "index1") throwForNegativeIndex(index2, parameterName: "index2") _rlmArray.exchangeObject(at: UInt(index1), withObjectAt: UInt(index2)) } // MARK: Notifications /** Registers a block to be called each time the collection changes. The block will be asynchronously called with the initial results, and then called again after each write transaction which changes either any of the objects in the collection, or which objects are in the collection. The `change` parameter that is passed to the block reports, in the form of indices within the collection, which of the objects were added, removed, or modified during each write transaction. See the `RealmCollectionChange` documentation for more information on the change information supplied and an example of how to use it to update a `UITableView`. At the time when the block is called, the collection will be fully evaluated and up-to-date, and as long as you do not perform a write transaction on the same thread or explicitly call `realm.refresh()`, accessing it will never perform blocking work. Notifications are delivered via the standard run loop, and so can't be delivered while the run loop is blocked by other activity. When notifications can't be delivered instantly, multiple notifications may be coalesced into a single notification. This can include the notification with the initial collection. For example, the following code performs a write transaction immediately after adding the notification block, so there is no opportunity for the initial notification to be delivered first. As a result, the initial notification will reflect the state of the Realm after the write transaction. ```swift let results = realm.objects(Dog.self) print("dogs.count: \(dogs?.count)") // => 0 let token = dogs.observe { changes in switch changes { case .initial(let dogs): // Will print "dogs.count: 1" print("dogs.count: \(dogs.count)") break case .update: // Will not be hit in this example break case .error: break } } try! realm.write { let dog = Dog() dog.name = "Rex" person.dogs.append(dog) } // end of run loop execution context ``` You must retain the returned token for as long as you want updates to be sent to the block. To stop receiving updates, call `invalidate()` on the token. - warning: This method cannot be called during a write transaction, or when the containing Realm is read-only. - parameter block: The block to be called whenever a change occurs. - returns: A token which must be held for as long as you want updates to be delivered. */ public func observe(_ block: @escaping (RealmCollectionChange<List>) -> Void) -> NotificationToken { return _rlmArray.addNotificationBlock { _, change, error in block(RealmCollectionChange.fromObjc(value: self, change: change, error: error)) } } } extension List where Element: MinMaxType { /** Returns the minimum (lowest) value in the list, or `nil` if the list is empty. */ public func min() -> Element? { return _rlmArray.min(ofProperty: "self").map(dynamicBridgeCast) } /** Returns the maximum (highest) value in the list, or `nil` if the list is empty. */ public func max() -> Element? { return _rlmArray.max(ofProperty: "self").map(dynamicBridgeCast) } } extension List where Element: AddableType { /** Returns the sum of the values in the list. */ public func sum() -> Element { return sum(ofProperty: "self") } /** Returns the average of the values in the list, or `nil` if the list is empty. */ public func average() -> Double? { return average(ofProperty: "self") } } extension List: RealmCollection { /// The type of the objects stored within the list. public typealias ElementType = Element // MARK: Sequence Support /// Returns a `RLMIterator` that yields successive elements in the `List`. public func makeIterator() -> RLMIterator<Element> { return RLMIterator(collection: _rlmArray) } #if swift(>=4) /** Replace the given `subRange` of elements with `newElements`. - parameter subrange: The range of elements to be replaced. - parameter newElements: The new elements to be inserted into the List. */ public func replaceSubrange<C: Collection, R>(_ subrange: R, with newElements: C) where C.Iterator.Element == Element, R: RangeExpression, List<Element>.Index == R.Bound { let subrange = subrange.relative(to: self) for _ in subrange.lowerBound..<subrange.upperBound { remove(at: subrange.lowerBound) } for x in newElements.reversed() { insert(x, at: subrange.lowerBound) } } #else /** Replace the given `subRange` of elements with `newElements`. - parameter subrange: The range of elements to be replaced. - parameter newElements: The new elements to be inserted into the List. */ public func replaceSubrange<C: Collection>(_ subrange: Range<Int>, with newElements: C) where C.Iterator.Element == Element { for _ in subrange.lowerBound..<subrange.upperBound { remove(at: subrange.lowerBound) } for x in newElements.reversed() { insert(x, at: subrange.lowerBound) } } #endif /// The position of the first element in a non-empty collection. /// Identical to endIndex in an empty collection. public var startIndex: Int { return 0 } /// The collection's "past the end" position. /// endIndex is not a valid argument to subscript, and is always reachable from startIndex by /// zero or more applications of successor(). public var endIndex: Int { return count } public func index(after i: Int) -> Int { return i + 1 } public func index(before i: Int) -> Int { return i - 1 } /// :nodoc: public func _observe(_ block: @escaping (RealmCollectionChange<AnyRealmCollection<Element>>) -> Void) -> NotificationToken { let anyCollection = AnyRealmCollection(self) return _rlmArray.addNotificationBlock { _, change, error in block(RealmCollectionChange.fromObjc(value: anyCollection, change: change, error: error)) } } } #if swift(>=4.0) // MARK: - MutableCollection conformance, range replaceable collection emulation extension List: MutableCollection { #if swift(>=4.1) public typealias SubSequence = Slice<List> #else public typealias SubSequence = RandomAccessSlice<List> #endif /** Returns the objects at the given range (get), or replaces the objects at the given range with new objects (set). - warning: Objects may only be set during a write transaction. - parameter index: The index of the object to retrieve or replace. */ public subscript(bounds: Range<Int>) -> SubSequence { get { return SubSequence(base: self, bounds: bounds) } set { replaceSubrange(bounds.lowerBound..<bounds.upperBound, with: newValue) } } /** Removes the specified number of objects from the beginning of the list. The objects are not removed from the Realm that manages them. - warning: This method may only be called during a write transaction. */ public func removeFirst(_ number: Int = 1) { let count = Int(_rlmArray.count) guard number <= count else { throwRealmException("It is not possible to remove more objects (\(number)) from a list" + " than it already contains (\(count)).") return } for _ in 0..<number { _rlmArray.removeObject(at: 0) } } /** Removes the specified number of objects from the end of the list. The objects are not removed from the Realm that manages them. - warning: This method may only be called during a write transaction. */ public func removeLast(_ number: Int = 1) { let count = Int(_rlmArray.count) guard number <= count else { throwRealmException("It is not possible to remove more objects (\(number)) from a list" + " than it already contains (\(count)).") return } for _ in 0..<number { _rlmArray.removeLastObject() } } /** Inserts the items in the given collection into the list at the given position. - warning: This method may only be called during a write transaction. */ public func insert<C: Collection>(contentsOf newElements: C, at i: Int) where C.Iterator.Element == Element { var currentIndex = i for item in newElements { insert(item, at: currentIndex) currentIndex += 1 } } #if swift(>=4.1.50) /** Removes objects from the list at the given range. - warning: This method may only be called during a write transaction. */ public func removeSubrange<R>(_ boundsExpression: R) where R: RangeExpression, List<Element>.Index == R.Bound { let bounds = boundsExpression.relative(to: self) for _ in bounds { remove(at: bounds.lowerBound) } } #else /** Removes objects from the list at the given range. - warning: This method may only be called during a write transaction. */ public func removeSubrange(_ bounds: Range<Int>) { removeSubrange(bounds.lowerBound..<bounds.upperBound) } /// :nodoc: public func removeSubrange(_ bounds: ClosedRange<Int>) { removeSubrange(bounds.lowerBound...bounds.upperBound) } /// :nodoc: public func removeSubrange(_ bounds: CountableRange<Int>) { for _ in bounds { remove(at: bounds.lowerBound) } } /// :nodoc: public func removeSubrange(_ bounds: CountableClosedRange<Int>) { for _ in bounds { remove(at: bounds.lowerBound) } } /// :nodoc: public func removeSubrange(_ bounds: DefaultRandomAccessIndices<List>) { removeSubrange(bounds.startIndex..<bounds.endIndex) } /// :nodoc: public func replaceSubrange<C: Collection>(_ subrange: ClosedRange<Int>, with newElements: C) where C.Iterator.Element == Element { removeSubrange(subrange) insert(contentsOf: newElements, at: subrange.lowerBound) } /// :nodoc: public func replaceSubrange<C: Collection>(_ subrange: CountableRange<Int>, with newElements: C) where C.Iterator.Element == Element { removeSubrange(subrange) insert(contentsOf: newElements, at: subrange.lowerBound) } /// :nodoc: public func replaceSubrange<C: Collection>(_ subrange: CountableClosedRange<Int>, with newElements: C) where C.Iterator.Element == Element { removeSubrange(subrange) insert(contentsOf: newElements, at: subrange.lowerBound) } /// :nodoc: public func replaceSubrange<C: Collection>(_ subrange: DefaultRandomAccessIndices<List>, with newElements: C) where C.Iterator.Element == Element { removeSubrange(subrange) insert(contentsOf: newElements, at: subrange.startIndex) } #endif } #else // MARK: - RangeReplaceableCollection support extension List: RangeReplaceableCollection { /** Removes the last object in the list. The object is not removed from the Realm that manages it. - warning: This method may only be called during a write transaction. */ public func removeLast() { guard _rlmArray.count > 0 else { throwRealmException("It is not possible to remove an object from an empty list.") return } _rlmArray.removeLastObject() } } #endif // MARK: - Codable #if swift(>=4.1) extension List: Decodable where Element: Decodable { public convenience init(from decoder: Decoder) throws { self.init() var container = try decoder.unkeyedContainer() while !container.isAtEnd { append(try container.decode(Element.self)) } } } extension List: Encodable where Element: Encodable { public func encode(to encoder: Encoder) throws { var container = encoder.unkeyedContainer() for value in self { try container.encode(value) } } } #endif // MARK: - AssistedObjectiveCBridgeable extension List: AssistedObjectiveCBridgeable { internal static func bridging(from objectiveCValue: Any, with metadata: Any?) -> List { guard let objectiveCValue = objectiveCValue as? RLMArray<AnyObject> else { preconditionFailure() } return List(rlmArray: objectiveCValue) } internal var bridged: (objectiveCValue: Any, metadata: Any?) { return (objectiveCValue: _rlmArray, metadata: nil) } } // MARK: - Unavailable extension List { @available(*, unavailable, renamed: "remove(at:)") public func remove(objectAtIndex: Int) { fatalError() } }
010c591ee0450686b4a5955cd5b972d0
35.725699
128
0.658642
false
false
false
false
LiskUser1234/SwiftyLisk
refs/heads/master
Lisk/Signature/SignatureAPI.swift
mit
1
/* The MIT License Copyright (C) 2017 LiskUser1234 - Github: https://github.com/liskuser1234 Please vote LiskUser1234 for delegate to support this project. For donations: - Lisk: 6137947831033853925L - Bitcoin: 1NCTZwBJF7ZFpwPeQKiSgci9r2pQV3G7RG 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 class SignatureAPI { private static let moduleName = "signatures" /// Gets the fee to register a second signature. /// /// - Parameter callback: The function that will be called with information about the request /// /// For more information about the response see /// https://github.com/LiskArchive/lisk-wiki/wiki/Lisk-API-Reference#get-signature-fees open class func getFee(callback: @escaping Callback) { Api.request(module: moduleName, submodule: "fee", method: .get, callback: callback) } /// Adds a second signature /// /// - Parameters: /// - secret: The passphrase from which the address is derived /// - secondSecret: The second passphrase to add to the address derived from `secret` /// - publicKey: Optional: the expected public key associated with the account derived from `secret` /// - callback: The function that will be called with information about the request /// /// For more information about the response see /// https://github.com/LiskArchive/lisk-wiki/wiki/Lisk-API-Reference#add-second-signature open class func addSecondSignature(secret: String, secondSecret: String, publicKey: String?, isMultisig: Bool, callback: @escaping Callback) { var query = [ "secret": secret, "secondSecret": secondSecret ] if let publicKey = publicKey { if isMultisig { query["multisigAccountPublicKey"] = publicKey } else { query["publicKey"] = publicKey } } Api.request(module: moduleName, submodule: nil, method: .put, query: query, callback: callback) } }
d26dbea69922f6166d0eee2f27aefab8
38.458824
106
0.63864
false
false
false
false
mownier/Umalahokan
refs/heads/master
Umalahokan/Source/UI/Message Writer/MessageWriterView.swift
mit
1
// // MessageWriterView.swift // Umalahokan // // Created by Mounir Ybanez on 01/02/2017. // Copyright © 2017 Ner. All rights reserved. // import UIKit class MessageWriterView: UIView { var header: MessageWriterHeader! var tableView: UITableView! var isValidToReload: Bool = false var isInitiallyReloaded: Bool = false var sendView: SendView! override init(frame: CGRect) { super.init(frame: frame) initSetup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initSetup() } override func layoutSubviews() { var rect = CGRect.zero rect.size.width = frame.width rect.size.height = header.frame.height header.frame = rect rect.origin.y = rect.maxY rect.size.height = frame.height - rect.height - sendView.frame.height tableView.frame = rect if !sendView.layer.hasAnimation { rect.size.height = sendView.frame.height rect.origin.y = frame.height - rect.height rect.size.width = frame.width sendView.frame = rect } } private func initSetup() { backgroundColor = UIColor.white header = MessageWriterHeader() tableView = UITableView() tableView.tableFooterView = UIView() sendView = SendView() addSubview(header) addSubview(tableView) addSubview(sendView) } }
8245450f51be3f42d2ae02541bc893fd
23.677419
77
0.590196
false
false
false
false
cygy/swift-ovh
refs/heads/master
Examples/OVHAPIWrapper-Example-watchOS/OVHAPIWrapper-Example-watchOS/WatchSessionManager.swift
bsd-3-clause
2
// // WatchSessionManager.swift // // Copyright (c) 2016, OVH SAS. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of OVH SAS nor the // names of its contributors may be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY OVH SAS AND CONTRIBUTORS ``AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL OVH SAS AND CONTRIBUTORS BE LIABLE FOR ANY // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // import Foundation import WatchConnectivity import OVHAPIWrapper protocol WatchSessionManagerDelegate { func APICredentials() -> [String:AnyObject] func VPSList() -> [[String:AnyObject]] func glanceData() -> [String:AnyObject] func complicationData() -> [String:AnyObject] func loadNewVPSTask(_ VPSName: String, task: [String:AnyObject]) } final class WatchSessionManager: NSObject, WCSessionDelegate { // MARK: - Singleton static let sharedManager = WatchSessionManager() // MARK: - Properties var delegate: WatchSessionManagerDelegate? fileprivate let session: WCSession? fileprivate let queue: DispatchQueue = DispatchQueue(label: "com.ovh.OVHAPIWrapper-Example-watchOS.watchos", attributes: []) fileprivate var validSession: WCSession? { if let session = session, session.isPaired && session.isWatchAppInstalled { return session } return nil } fileprivate var APICredentials: [String:AnyObject]? { return delegate?.APICredentials() } fileprivate var VPSList: [[String:AnyObject]]? { return delegate?.VPSList() } fileprivate var glanceData: [String:AnyObject]? { return delegate?.glanceData() } fileprivate var complicationData: [String:AnyObject]? { return delegate?.complicationData() } // MARK: - Public methods /** Send to the watch the updated OVH API credentials. */ func updateAPICredentials() { if let credentials = APICredentials { queue.async { () -> Void in self.sendDataWithKey("credentials", andData: credentials as AnyObject) } } } /** Send to the watch the updated list of VPS. */ func updateVPSList() { if let list = VPSList { queue.async { () -> Void in self.sendDataWithKey("VPSlist", andData: list as AnyObject) } } } /** Send to the watch the updated state of a VPS. */ func updateVPS(_ VPS: [String:AnyObject], withOldRepresentation oldVPS: [String:AnyObject]) { if VPS["busy"] as? Bool == oldVPS["busy"] as? Bool && VPS["state"] as? String == oldVPS["state"] as? String && VPS["displayName"] as? String == oldVPS["displayName"] as? String { return } queue.async { () -> Void in self.sendDataWithKey("VPS", andData: VPS as AnyObject) } } /** Send to the watch the updated glance data. */ func updateGlance() { queue.async { () -> Void in if let session = self.validSession, let data = self.delegate?.glanceData() { do { try session.updateApplicationContext(data) print("Send application context: \(data)") } catch let error { print("Can not send glance data: \(error)") } } else { print("Watch OS glance is not available.") } } } /** Send to the watch the updated complication data. */ func updateComplication() { queue.async { () -> Void in if let session = self.validSession, session.isComplicationEnabled, let data = self.delegate?.complicationData() { session.transferCurrentComplicationUserInfo(data) print("Send complication data: \(data)") } else { print("Watch OS complication is not available.") } } } // MARK: - Private methods /** Send some data to the watch. */ fileprivate func sendDataWithKey(_ key: String, andData data: AnyObject) { if let session = validSession, session.isReachable { session.sendMessage([key : data], replyHandler: { response -> Void in print("Response received from watch application: \(response)") }, errorHandler: { error -> Void in print("Error send message to the watch: \(error)") }) print("Send message to watch: \(key) = \(data)") } else { print("Watch OS application is not available.") } } // MARK: - WCSessionDelegate methods func session(_ session: WCSession, didReceiveMessage message: [String : Any], replyHandler: @escaping ([String : Any]) -> Void) { print("Receive message from watch application: \(message)") var response = [String : AnyObject]() for (key, value) in message { switch key { case "init": // Get the API credentials and the VPS list. if let credentials = APICredentials, let list = VPSList { response = ["credentials": credentials as AnyObject, "VPSlist": list as AnyObject] } case "newTask": if let data = value as? [String:AnyObject] { let VPSName = data["vps"] as! String let task = data["task"] as! [String:AnyObject] delegate?.loadNewVPSTask(VPSName, task: task) } default: break } } replyHandler(response) } func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) { } func sessionDidBecomeInactive(_ session: WCSession) { } func sessionDidDeactivate(_ session: WCSession) { } // MARK: - Lifecycle override init() { if WCSession.isSupported() { session = WCSession.default() } else { session = nil } super.init() session?.delegate = self session?.activate() } }
5b9aa5c7609ccb272d4276277e6e84e9
32.343612
186
0.59638
false
false
false
false
CPRTeam/CCIP-iOS
refs/heads/master
Pods/SwiftDate/Sources/SwiftDate/TimePeriod/Groups/TimePeriodGroup.swift
gpl-3.0
4
// // SwiftDate // Parse, validate, manipulate, and display dates, time and timezones in Swift // // Created by Daniele Margutti // - Web: https://www.danielemargutti.com // - Twitter: https://twitter.com/danielemargutti // - Mail: [email protected] // // Copyright © 2019 Daniele Margutti. Licensed under MIT License. // import Foundation /// Time period groups are the final abstraction of date and time in DateTools. /// Here, time periods are gathered and organized into something useful. /// There are two main types of time period groups, `TimePeriodCollection` and `TimePeriodChain`. open class TimePeriodGroup: Sequence, Equatable { /// Array of periods that define the group. internal var periods: [TimePeriodProtocol] = [] /// The earliest beginning date of a `TimePeriod` in the group. /// `nil` if any `TimePeriod` in group has a nil beginning date (indefinite). public internal(set) var start: DateInRegion? /// The latest end date of a `TimePeriod` in the group. /// `nil` if any `TimePeriod` in group has a nil end date (indefinite). public internal(set) var end: DateInRegion? /// The total amount of time between the earliest and latest dates stored in the periods array. /// `nil` if any beginning or end date in any contained period is `nil`. public var duration: TimeInterval? { guard let start = start, let end = end else { return nil } return end.timeIntervalSince(start) } /// The number of periods in the periods array. public var count: Int { return periods.count } // MARK: - Equatable public static func == (lhs: TimePeriodGroup, rhs: TimePeriodGroup) -> Bool { return TimePeriodGroup.hasSameElements(array1: lhs.periods, rhs.periods) } // MARK: - Initializers public init(_ periods: [TimePeriodProtocol]? = nil) { self.periods = (periods ?? []) } // MARK: - Sequence Protocol public func makeIterator() -> IndexingIterator<[TimePeriodProtocol]> { return periods.makeIterator() } public func map<T>(_ transform: (TimePeriodProtocol) throws -> T) rethrows -> [T] { return try periods.map(transform) } public func filter(_ isIncluded: (TimePeriodProtocol) throws -> Bool) rethrows -> [TimePeriodProtocol] { return try periods.filter(isIncluded) } public func forEach(_ body: (TimePeriodProtocol) throws -> Void) rethrows { return try periods.forEach(body) } public func split(maxSplits: Int, omittingEmptySubsequences: Bool, whereSeparator isSeparator: (TimePeriodProtocol) throws -> Bool) rethrows -> [AnySequence<TimePeriodProtocol>] { return try periods.split(maxSplits: maxSplits, omittingEmptySubsequences: omittingEmptySubsequences, whereSeparator: isSeparator).map(AnySequence.init) } public subscript(index: Int) -> TimePeriodProtocol { get { return periods[index] } } internal func reduce<Result>(_ initialResult: Result, _ nextPartialResult: (Result, TimePeriodProtocol) throws -> Result) rethrows -> Result { return try periods.reduce(initialResult, nextPartialResult) } // MARK: - Internal Helper Functions internal static func hasSameElements(array1: [TimePeriodProtocol], _ array2: [TimePeriodProtocol]) -> Bool { guard array1.count == array2.count else { return false // No need to sorting if they already have different counts } let compArray1: [TimePeriodProtocol] = array1.sorted { (period1: TimePeriodProtocol, period2: TimePeriodProtocol) -> Bool in if period1.start == nil && period2.start == nil { return false } else if period1.start == nil { return true } else if period2.start == nil { return false } else { return period2.start! < period1.start! } } let compArray2: [TimePeriodProtocol] = array2.sorted { (period1: TimePeriodProtocol, period2: TimePeriodProtocol) -> Bool in if period1.start == nil && period2.start == nil { return false } else if period1.start == nil { return true } else if period2.start == nil { return false } else { return period2.start! < period1.start! } } for x in 0..<compArray1.count { if !compArray1[x].equals(compArray2[x]) { return false } } return true } }
117f09b281b781709785616346bc1c57
32.658537
180
0.713768
false
false
false
false
jjochen/JJFloatingActionButton
refs/heads/master
Sources/LayerProperties.swift
mit
1
// // LayerProperties.swift // // Copyright (c) 2017-Present Jochen Pfeiffer // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit public extension JJFloatingActionButton { /// The shadow color of the floating action button. /// Default is `UIColor.black`. /// @objc @IBInspectable dynamic var shadowColor: UIColor? { get { guard let cgColor = layer.shadowColor else { return nil } return UIColor(cgColor: cgColor) } set { layer.shadowColor = newValue?.cgColor } } /// The shadow offset of the floating action button. /// Default is `CGSize(width: 0, height: 1)`. /// @objc @IBInspectable dynamic var shadowOffset: CGSize { get { return layer.shadowOffset } set { layer.shadowOffset = newValue } } /// The shadow opacity of the floating action button. /// Default is `0.4`. /// @objc @IBInspectable dynamic var shadowOpacity: Float { get { return layer.shadowOpacity } set { layer.shadowOpacity = newValue } } /// The shadow radius of the floating action button. /// Default is `2`. /// @objc @IBInspectable dynamic var shadowRadius: CGFloat { get { return layer.shadowRadius } set { layer.shadowRadius = newValue } } } extension JJActionItem { /// The shadow color of the action item. /// Default is `UIColor.black`. /// @objc @IBInspectable dynamic var shadowColor: UIColor? { get { guard let cgColor = layer.shadowColor else { return nil } return UIColor(cgColor: cgColor) } set { layer.shadowColor = newValue?.cgColor } } /// The shadow offset of the action item. /// Default is `CGSize(width: 0, height: 1)`. /// @objc @IBInspectable dynamic var shadowOffset: CGSize { get { return layer.shadowOffset } set { layer.shadowOffset = newValue } } /// The shadow opacity of the action item. /// Default is `0.4`. /// @objc @IBInspectable dynamic var shadowOpacity: Float { get { return layer.shadowOpacity } set { layer.shadowOpacity = newValue } } /// The shadow radius of the action item. /// Default is `2`. /// @objc @IBInspectable dynamic var shadowRadius: CGFloat { get { return layer.shadowRadius } set { layer.shadowRadius = newValue } } }
5fcd98b953b68a7ff7fefb1b164ccbae
28
81
0.599105
false
false
false
false
nua-schroers/mvvm-frp
refs/heads/master
01_Common/CustomViews/MatchPileView.swift
mit
1
// // MatchPileView.swift // MatchGame // // Created by Dr. Wolfram Schroers on 5/17/16. // Copyright © 2016 Wolfram Schroers. All rights reserved. // import UIKit /// The match pile on the screen. class MatchPileView: UIView { /// Number of currently visible matches. fileprivate var visibleMatches: Int = 0 override init(frame: CGRect) { super.init(frame: frame) self.setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setup() } /// Configure this view (sets background color). fileprivate func setup() { self.backgroundColor = UIColor.clear } /// Set a fixed number of matches. Abort animations if needed. func setMatches(_ matchNumber: Int) { // Remove all currently visible/animating matches. let oldMatches = self.subviews for match in oldMatches { match.removeFromSuperview() } let matchesPerRow = 10 let rows = matchNumber / matchesPerRow let matchesInLastRow = matchNumber - (rows * matchesPerRow) // Draw all rows up to the last one. for row in 0..<rows { for column in 0..<matchesPerRow { let position = CGRect(x: CGFloat(10 + column * 30), y: CGFloat(0 + row * 80), width: 30, height: 80) let match = SingleMatchView(frame: position) self.addSubview(match) } } // Draw the final row. for column in 0..<matchesInLastRow { let position = CGRect(x: CGFloat(10 + column * 30), y: CGFloat(0 + rows * 80), width: 30, height: 80) let match = SingleMatchView(frame: position) self.addSubview(match) } // Aktuell sichtbare Zahl von Hölzern. self.visibleMatches = matchNumber } /// Remove a given number of matches with animation. func removeMatches(_ matchNumber: Int) { // All currently registered matches (including animated ones). let oldMatches = self.subviews // Actual number of matches to remove. let actualNumber = (matchNumber > self.visibleMatches) ? self.visibleMatches : matchNumber; let rotation = CGAffineTransform(rotationAngle: CGFloat(Double.pi / 2)) for i in 1...actualNumber { let lastIndex = self.visibleMatches - i let lastVisibleMatch = oldMatches[lastIndex] // Duration of rotation and fade transitions (in seconds, random). let rotateDuration = 1.0 + 0.1 * Double(arc4random_uniform(11)) let fadeDuration = 0.5 + 0.1 * Double(arc4random_uniform(16)) UIView.animate(withDuration: fadeDuration, animations: { () in lastVisibleMatch.alpha = 0.0 }, completion: { (_: Bool) in lastVisibleMatch.removeFromSuperview() }) UIView.animate(withDuration: rotateDuration, animations: { () in lastVisibleMatch.transform = rotation }) } // Finally, reduce the number of visible matches. self.visibleMatches = self.visibleMatches - matchNumber } }
3ec7c76b7677ccfec2be6d432dc39e6b
32.194175
99
0.566832
false
false
false
false
ChiliLabs/CHIPageControl
refs/heads/master
CHIPageControl/CHIPageControlPuya.swift
mit
1
// // CHIPageControlPuya.swift // CHIPageControl ( https://github.com/ChiliLabs/CHIPageControl ) // // Copyright (c) 2017 Chili ( http://chi.lv ) // // // 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 open class CHIPageControlPuya: CHIBasePageControl { fileprivate var diameter: CGFloat { return radius * 2 } fileprivate var elements = [CHILayer]() fileprivate var frames = [CGRect]() fileprivate var min: CGRect? fileprivate var max: CGRect? required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public override init(frame: CGRect) { super.init(frame: frame) } override func updateNumberOfPages(_ count: Int) { elements.forEach { $0.removeFromSuperlayer() } elements = [CHILayer]() elements = (0..<count).map {_ in let layer = CHILayer() self.layer.addSublayer(layer) return layer } setNeedsLayout() self.invalidateIntrinsicContentSize() } override open func layoutSubviews() { super.layoutSubviews() let floatCount = CGFloat(elements.count) let x = (self.bounds.size.width - self.diameter*floatCount - self.padding*(floatCount-1))*0.5 let y = (self.bounds.size.height - self.diameter)*0.5 var frame = CGRect(x: x, y: y, width: self.diameter, height: self.diameter) elements.enumerated().forEach() { index, layer in layer.backgroundColor = self.tintColor(position: index).withAlphaComponent(self.inactiveTransparency).cgColor if self.borderWidth > 0 { layer.borderWidth = self.borderWidth layer.borderColor = self.tintColor(position: index).cgColor } layer.cornerRadius = self.radius layer.frame = frame frame.origin.x += self.diameter + self.padding } if let active = elements.first { active.backgroundColor = (self.currentPageTintColor ?? self.tintColor)?.cgColor active.borderWidth = 0 } min = elements.first?.frame max = elements.last?.frame self.frames = elements.map { $0.frame } update(for: progress) } override func update(for progress: Double) { guard let min = self.min, let max = self.max, progress >= 0 && progress <= Double(numberOfPages - 1), numberOfPages > 1 else { return } let total = Double(numberOfPages - 1) let dist = max.origin.x - min.origin.x let percent = CGFloat(progress / total) let page = Int(progress) for (index, _) in self.frames.enumerated() { if page > index { self.elements[index+1].frame = self.frames[index] } else if page < index { self.elements[index].frame = self.frames[index] } } let offset = dist * percent guard let active = elements.first else { return } active.frame.origin.x = min.origin.x + offset active.borderWidth = 0 let index = page + 1 guard elements.indices.contains(index) else { return } let element = elements[index] guard frames.indices.contains(page), frames.indices.contains(page + 1) else { return } let prev = frames[page] let prevColor = tintColor(position: page) let current = frames[page + 1] let currentColor = tintColor(position: page + 1) let elementTotal: CGFloat = current.origin.x - prev.origin.x let elementProgress: CGFloat = current.origin.x - active.frame.origin.x let elementPercent = (elementTotal - elementProgress) / elementTotal element.backgroundColor = blend(color1: currentColor, color2: prevColor, progress: elementPercent).withAlphaComponent(self.inactiveTransparency).cgColor element.frame = prev element.frame.origin.x += elementProgress } override open var intrinsicContentSize: CGSize { return sizeThatFits(CGSize.zero) } override open func sizeThatFits(_ size: CGSize) -> CGSize { return CGSize(width: CGFloat(elements.count) * self.diameter + CGFloat(elements.count - 1) * self.padding, height: self.diameter) } override open func didTouch(gesture: UITapGestureRecognizer) { let point = gesture.location(ofTouch: 0, in: self) if var touchIndex = elements.enumerated().first(where: { $0.element.hitTest(point) != nil })?.offset { let intProgress = Int(progress) if intProgress > 0 { if touchIndex == 0 { touchIndex = intProgress } else if touchIndex <= intProgress { touchIndex -= 1 } } delegate?.didTouch(pager: self, index: touchIndex) } } }
824502704675fc2c18f189aa06195526
36.65
160
0.626826
false
false
false
false
noxytrux/Arpeggios
refs/heads/master
Arpeggios/ARPMainViewController.swift
mit
1
// // GameViewController.swift // Arpeggios // // Created by Marcin Pędzimąż on 15.10.2014. // Copyright (c) 2014 Marcin Pedzimaz. All rights reserved. // import UIKit import Metal import QuartzCore let maxFramesToBuffer = 3 struct sunStructure { var sunVector = Vector3() var sunColor = Vector3() } struct matrixStructure { var projMatrix = Matrix4x4() var viewMatrix = Matrix4x4() var normalMatrix = Matrix4x4() } class ARPMainViewController: UIViewController { internal var previousUpdateTime : CFTimeInterval = 0.0 internal var delta : CFTimeInterval = 0.0 let device = { MTLCreateSystemDefaultDevice() }() let metalLayer = { CAMetalLayer() }() var defaultLibrary: MTLLibrary! = nil //MARK: common var commandQueue: MTLCommandQueue! = nil var timer: CADisplayLink! = nil let inflightSemaphore = dispatch_semaphore_create(maxFramesToBuffer) var bufferIndex = 0 //MARK: matrices and sun info //vector for viewMatrix var eyeVec = Vector3(x: 0.0,y: 2.0,z: 3.0) var dirVec = Vector3(x: 0.0,y: -0.234083,z: -0.9) var upVec = Vector3(x: 0, y: 1, z: 0) var loadedModels = [ARPModel]() //sun info var sunPosition = Vector3(x: 5.316387,y: -2.408824,z: 0) var orangeColor = Vector3(x: 1.0, y: 0.5, z: 0.0) var yellowColor = Vector3(x: 1.0, y: 1.0, z: 0.8) //MARK: Render states var pipelineStates = [String : MTLRenderPipelineState]() //MARK: uniform data var sunBuffer: MTLBuffer! = nil var cameraMatrix: Matrix4x4 = Matrix4x4() var rotationAngle: Float32 = 0.0 var sunData = sunStructure() var matrixData = matrixStructure() var inverted = Matrix33() var rotMatrixX = Matrix33() var rotMatrixY = Matrix33() var rotMatrixZ = Matrix33() var baseStiencilState: MTLDepthStencilState! = nil override func prefersStatusBarHidden() -> Bool { return false } override func viewDidLoad() { super.viewDidLoad() metalLayer.device = device metalLayer.pixelFormat = .BGRA8Unorm metalLayer.framebufferOnly = true self.resize() view.layer.addSublayer(metalLayer) view.opaque = true view.backgroundColor = nil commandQueue = device.newCommandQueue() commandQueue.label = "main command queue" defaultLibrary = device.newDefaultLibrary() ARPSingletonFactory<ARPModelManager>.sharedInstance() ARPSingletonFactory<ARPTextureManager>.sharedInstance() //generate shaders and descriptors preparePipelineStates() //set matrix var aspect = Float32(view.frame.size.width/view.frame.size.height) matrixData.projMatrix = matrix44MakePerspective(degToRad(60), aspect, 0.01, 5000) //set unifor buffers sunBuffer = device.newBufferWithBytes(&sunData, length: sizeof(sunStructure), options: nil) //load models and scene loadModels() timer = CADisplayLink(target: self, selector: Selector("renderLoop")) timer.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSDefaultRunLoopMode) } func loadModels() { var palmModel = ARPSingletonFactory<ARPModelManager>.sharedInstance().loadModel("palmnew", device: device) if let palmModel = palmModel { palmModel.modelScale = 0.12 palmModel.modelMatrix.t = Vector3() palmModel.modelMatrix.M.rotY(Float32(M_PI + (M_PI_4 * 0.5))) palmModel.setCullModeForMesh(1, mode: .None) loadedModels.append(palmModel) } var boxModel = ARPSingletonFactory<ARPModelManager>.sharedInstance().loadModel("box", device: device) if let boxModel = boxModel { boxModel.modelScale = 0.25 boxModel.modelMatrix.t = Vector3(x: 2.5, y:0, z:0) loadedModels.append(boxModel) } var barrelModel = ARPSingletonFactory<ARPModelManager>.sharedInstance().loadModel("barrel", device: device) if let barrelModel = barrelModel { barrelModel.modelScale = 0.1 barrelModel.modelMatrix.t = Vector3(x: -4, y:0, z:0) loadedModels.append(barrelModel) } } func preparePipelineStates() { var desc = MTLDepthStencilDescriptor() desc.depthWriteEnabled = true; desc.depthCompareFunction = .LessEqual; baseStiencilState = device.newDepthStencilStateWithDescriptor(desc) //create all pipeline states for shaders var pipelineStateDescriptor = MTLRenderPipelineDescriptor() var pipelineError : NSError? var fragmentProgram: MTLFunction? var vertexProgram: MTLFunction? //BASIC SHADER fragmentProgram = defaultLibrary?.newFunctionWithName("basicRenderFragment") vertexProgram = defaultLibrary?.newFunctionWithName("basicRenderVertex") pipelineStateDescriptor.vertexFunction = vertexProgram pipelineStateDescriptor.fragmentFunction = fragmentProgram pipelineStateDescriptor.colorAttachments[0].pixelFormat = .BGRA8Unorm var basicState = device.newRenderPipelineStateWithDescriptor(pipelineStateDescriptor, error: &pipelineError) if (basicState == nil) { println("Failed to create pipeline state, error \(pipelineError)") } pipelineStates["basic"] = basicState } override func viewDidLayoutSubviews() { self.resize() } func resize() { view.contentScaleFactor = UIScreen.mainScreen().nativeScale metalLayer.frame = view.layer.frame var drawableSize = view.bounds.size drawableSize.width = drawableSize.width * CGFloat(view.contentScaleFactor) drawableSize.height = drawableSize.height * CGFloat(view.contentScaleFactor) metalLayer.drawableSize = drawableSize } deinit { timer.invalidate() } func renderLoop() { autoreleasepool { self.render() } } func render() { // use semaphore to encode 3 frames ahead dispatch_semaphore_wait(inflightSemaphore, DISPATCH_TIME_FOREVER) self.update() let commandBuffer = commandQueue.commandBuffer() commandBuffer.label = "Frame command buffer" let drawable = metalLayer.nextDrawable() //this one is generated on the fly as it render to our main FBO let renderPassDescriptor = MTLRenderPassDescriptor() renderPassDescriptor.colorAttachments[0].texture = drawable.texture renderPassDescriptor.colorAttachments[0].loadAction = .Clear renderPassDescriptor.colorAttachments[0].clearColor = MTLClearColor(red: 0.8, green: 0.8, blue: 0.8, alpha: 1.0) renderPassDescriptor.colorAttachments[0].storeAction = .Store let renderEncoder = commandBuffer.renderCommandEncoderWithDescriptor(renderPassDescriptor) renderEncoder?.label = "Regular pass encoder" renderEncoder?.setFrontFacingWinding(.CounterClockwise) renderEncoder?.setDepthStencilState(baseStiencilState) renderEncoder?.setVertexBuffer(sunBuffer, offset: 0, atIndex: 2) var cameraViewMatrix = Matrix34(initialize: false) cameraViewMatrix.setColumnMajor44(cameraMatrix) for model in loadedModels { //calcualte real model view matrix var modelViewMatrix = cameraViewMatrix * (model.modelMatrix * model.modelScale) var normalMatrix = Matrix33(other: modelViewMatrix.M) if modelViewMatrix.M.getInverse(&inverted) == true { normalMatrix.setTransposed(inverted) } //set updated buffer info modelViewMatrix.getColumnMajor44(&matrixData.viewMatrix) var normal4x4 = Matrix34(rot: normalMatrix, trans: Vector3(x: 0, y: 0, z: 0)) normal4x4.getColumnMajor44(&matrixData.normalMatrix) //cannot modify single value var matrices = UnsafeMutablePointer<matrixStructure>(model.matrixBuffer.contents()) matrices.memory = matrixData //memcpy(model.matrixBuffer.contents(), &matrixData, UInt(sizeof(matrixStructure))) renderEncoder?.setVertexBuffer(model.matrixBuffer, offset: 0, atIndex: 1) model.render(renderEncoder!, states: pipelineStates, shadowPass: false) } renderEncoder?.endEncoding() // use completion handler to signal the semaphore when this frame is completed allowing the encoding of the next frame to proceed // use cpature list to avoid any retain cycles if the command buffer gets retained anywhere besides this stack frame commandBuffer.addCompletedHandler{ [weak self] commandBuffer in if let strongSelf = self { dispatch_semaphore_signal(strongSelf.inflightSemaphore) } return } // bufferIndex matches the current semaphore controled frame index to ensure writing occurs at the correct region in the vertex buffer bufferIndex = (bufferIndex + 1) % maxFramesToBuffer; commandBuffer.presentDrawable(drawable) commandBuffer.commit() } func update() { delta = timer.timestamp - self.previousUpdateTime previousUpdateTime = timer.timestamp if delta > 0.3 { delta = 0.3 } //update lookAt matrix cameraMatrix = matrix44MakeLookAt(eyeVec, eyeVec+dirVec, upVec) //udpate sun position and color sunPosition.y += Float32(delta) * 0.5 sunPosition.x += Float32(delta) * 0.5 sunData.sunVector = Vector3(x: -cosf(sunPosition.x) * sinf(sunPosition.y), y: -cosf(sunPosition.y), z: -sinf(sunPosition.x) * sinf(sunPosition.y)) var sun_cosy = sunData.sunVector.y var factor = 0.25 + sun_cosy * 0.75 sunData.sunColor = ((orangeColor * (1.0 - factor)) + (yellowColor * factor)) memcpy(sunBuffer.contents(), &sunData, UInt(sizeof(sunStructure))) //update models rotation rotationAngle += Float32(delta) * 0.5 rotMatrixX.rotX(rotationAngle) rotMatrixY.rotY(rotationAngle) rotMatrixZ.rotZ(rotationAngle) for (index, model) in enumerate(loadedModels) { switch(index) { case 2 : var localRotation = Matrix33() localRotation.rotX(Float32(M_PI_2)) model.modelMatrix.M = localRotation * rotMatrixZ case 1 : model.modelMatrix.M = rotMatrixX * rotMatrixY * rotMatrixZ default: () } } } }
0d9f14a9c1c85961de14cd94a08425c0
31.915014
142
0.604235
false
false
false
false
tjhancocks/Pixel
refs/heads/master
PixelApp/PixelApp/Pixel Editor/PixelEditorLayer.swift
mit
1
// // PixelEditorLayer.swift // PixelApp // // Created by Tom Hancocks on 02/08/2014. // Copyright (c) 2014 Tom Hancocks. All rights reserved. // import Cocoa class PixelLayer { var name: String = "Untitled Layer" var size: CGSize = CGSizeZero { didSet { createNewDataBuffer() } } var layerRepresentation: NSImage? var opacity: CGFloat = 1.0 var visibility = true // Instantiate a layer to be a certain size init(size: CGSize) { self.size = size createNewDataBuffer() } // Create a new data buffer for the layer pixel data func createNewDataBuffer() { layerRepresentation = NSImage(size: size) } // The rectangle representation of the layer (AppKit variant) var rect: NSRect { return NSRect(x: 0, y: 0, width: size.width, height: size.height) } // Import data from an image at the specified URL and use it to fill in the pixel data for the layer. // This will crop the image to the size of the layer. func importPixelsFromImage(atURL url: NSURL) { var error: NSError? let imageData = NSData(contentsOfURL: url, options: NSDataReadingOptions.DataReadingMappedIfSafe, error: &error)! if let e = error? { println("\(e.localizedDescription)") return } if let layer = layerRepresentation? { let importImage = NSImage(data: imageData)! layer.lockFocus() // Keep track of the context's previous settings. We're going to be altering them temporarily so // that we can do a pixellated scale. if let graphicsContext = NSGraphicsContext.currentContext() { let wasAntialiasing = graphicsContext.shouldAntialias let previousImageInterpolation = graphicsContext.imageInterpolation graphicsContext.shouldAntialias = false graphicsContext.imageInterpolation = .None // Draw the new import image into the layer let importRect = NSRect(origin: CGPointZero, size: NSSizeToCGSize(importImage.size)) importImage.drawInRect(rect, fromRect: importRect, operation: .CompositeSourceOver, fraction: 1.0) // Restore previous settings graphicsContext.shouldAntialias = wasAntialiasing graphicsContext.imageInterpolation = previousImageInterpolation } layer.unlockFocus() } } // Update the specified pixel in the layer data and trigger a redraw of the layer // cached representation func setPixel(atPoint point: PixelPoint, toColor color: NSColor) { if let layer = layerRepresentation? { layer.lockFocus() color.setFill() NSBezierPath(rect: NSRect(x: point.x, y: point.y, width: 1, height: 1)).fill() layer.unlockFocus() } } // func drawCircle(atPoint point: PixelPoint, toColor color: NSColor, withRadius r: CGFloat, andSolid s: Bool) { if let layer = layerRepresentation? { layer.lockFocus() color.set() var rect = NSInsetRect(NSRect(x: point.x, y: point.y, width: 0, height: 0), -r, -r) if s { NSBezierPath(ovalInRect: rect).fill() } else { NSBezierPath(ovalInRect: rect).stroke() } layer.unlockFocus() } } // This will return NSColor.clearColor if there is no data for the pixel available. func pixelColor(atPoint point: PixelPoint) -> NSColor { if let layer = layerRepresentation? { // Grab a bitmap representation of the image and pull the color from it. let bitmap = NSBitmapImageRep(data: layer.TIFFRepresentation!)! return bitmap.colorAtX(point.x, y: point.y)! } return NSColor.clearColor() } }
4d0113c1d5de5aa9ae34322dcb71fa42
31.76378
114
0.584956
false
false
false
false
yeziahehe/Gank
refs/heads/master
Pods/LeanCloud/Sources/Storage/Value.swift
gpl-3.0
1
// // LCValue.swift // LeanCloud // // Created by Tang Tianyong on 2/27/16. // Copyright © 2016 LeanCloud. All rights reserved. // import Foundation /** Abstract data type. All LeanCloud data types must confirm this protocol. */ public protocol LCValue: NSObjectProtocol, NSCoding, NSCopying, LCValueConvertible { /** The JSON representation. */ var jsonValue: Any { get } /** The pretty description. */ var jsonString: String { get } /** The raw value of current value. For JSON-compatible objects, such as string, array, etc., raw value is the value of corresponding Swift built-in type. For some objects of other types, such as `LCObject`, `LCACL` etc., raw value is itself. */ var rawValue: LCValueConvertible { get } /* Shorthands for type conversion. */ var intValue: Int? { get } var uintValue: UInt? { get } var int8Value: Int8? { get } var uint8Value: UInt8? { get } var int16Value: Int16? { get } var uint16Value: UInt16? { get } var int32Value: Int32? { get } var uint32Value: UInt32? { get } var int64Value: Int64? { get } var uint64Value: UInt64? { get } var floatValue: Float? { get } var doubleValue: Double? { get } var boolValue: Bool? { get } var stringValue: String? { get } var arrayValue: [LCValueConvertible]? { get } var dictionaryValue: [String: LCValueConvertible]? { get } var dataValue: Data? { get } var dateValue: Date? { get } } extension LCValue { public var intValue: Int? { guard let number = rawValue as? Double else { return nil } return Int(number) } public var uintValue: UInt? { guard let number = rawValue as? Double else { return nil } return UInt(number) } public var int8Value: Int8? { guard let number = rawValue as? Double else { return nil } return Int8(number) } public var uint8Value: UInt8? { guard let number = rawValue as? Double else { return nil } return UInt8(number) } public var int16Value: Int16? { guard let number = rawValue as? Double else { return nil } return Int16(number) } public var uint16Value: UInt16? { guard let number = rawValue as? Double else { return nil } return UInt16(number) } public var int32Value: Int32? { guard let number = rawValue as? Double else { return nil } return Int32(number) } public var uint32Value: UInt32? { guard let number = rawValue as? Double else { return nil } return UInt32(number) } public var int64Value: Int64? { guard let number = rawValue as? Double else { return nil } return Int64(number) } public var uint64Value: UInt64? { guard let number = rawValue as? Double else { return nil } return UInt64(number) } public var floatValue: Float? { guard let number = rawValue as? Double else { return nil } return Float(number) } public var doubleValue: Double? { guard let number = rawValue as? Double else { return nil } return Double(number) } public var boolValue: Bool? { guard let number = rawValue as? Double else { return nil } return number != 0 } public var stringValue: String? { return rawValue as? String } public var arrayValue: [LCValueConvertible]? { return rawValue as? [LCValueConvertible] } public var dictionaryValue: [String: LCValueConvertible]? { return rawValue as? [String: LCValueConvertible] } public var dataValue: Data? { return rawValue as? Data } public var dateValue: Date? { return rawValue as? Date } } /** Extension of LCValue. By convention, all types that confirm `LCValue` must also confirm `LCValueExtension`. */ protocol LCValueExtension: LCValue { /** The LCON (LeanCloud Object Notation) representation. For JSON-compatible objects, such as string, array, etc., LCON value is the same as JSON value. However, some types might have different representations, or even have no LCON value. For example, when an object has not been saved, its LCON value is nil. */ var lconValue: Any? { get } /** Create an instance of current type. This method exists because some data types cannot be instantiated externally. - returns: An instance of current type. */ static func instance() throws -> LCValue // MARK: Enumeration /** Iterate children by a closure. - parameter body: The iterator closure. */ func forEachChild(_ body: (_ child: LCValue) throws -> Void) rethrows // MARK: Arithmetic /** Add an object. - parameter other: The object to be added, aka the addend. - returns: The sum of addition. */ func add(_ other: LCValue) throws -> LCValue /** Concatenate an object with unique option. - parameter other: The object to be concatenated. - parameter unique: Whether to concatenate with unique or not. If `unique` is true, for each element in `other`, if current object has already included the element, do nothing. Otherwise, the element will always be appended. - returns: The concatenation result. */ func concatenate(_ other: LCValue, unique: Bool) throws -> LCValue /** Calculate difference with other. - parameter other: The object to differ. - returns: The difference result. */ func differ(_ other: LCValue) throws -> LCValue /** Get formatted JSON string with indent. - parameter indentLevel: The indent level. - parameter numberOfSpacesForOneIndentLevel: The number of spaces for one indent level. - returns: The JSON string. */ func formattedJSONString(indentLevel: Int, numberOfSpacesForOneIndentLevel: Int) -> String } /** Convertible protocol for `LCValue`. */ public protocol LCValueConvertible { /** Get the `LCValue` value for current object. */ var lcValue: LCValue { get } } extension LCValueConvertible { public var intValue: Int? { return lcValue.intValue } public var uintValue: UInt? { return lcValue.uintValue } public var int8Value: Int8? { return lcValue.int8Value } public var uint8Value: UInt8? { return lcValue.uint8Value } public var int16Value: Int16? { return lcValue.int16Value } public var uint16Value: UInt16? { return lcValue.uint16Value } public var int32Value: Int32? { return lcValue.int32Value } public var uint32Value: UInt32? { return lcValue.uint32Value } public var int64Value: Int64? { return lcValue.int64Value } public var uint64Value: UInt64? { return lcValue.uint64Value } public var floatValue: Float? { return lcValue.floatValue } public var doubleValue: Double? { return lcValue.doubleValue } public var boolValue: Bool? { return lcValue.boolValue } public var stringValue: String? { return lcValue.stringValue } public var arrayValue: [LCValueConvertible]? { return lcValue.arrayValue } public var dictionaryValue: [String: LCValueConvertible]? { return lcValue.dictionaryValue } public var dataValue: Data? { return lcValue.dataValue } public var dateValue: Date? { return lcValue.dateValue } } /** Convertible protocol for `LCNull`. */ public protocol LCNullConvertible: LCValueConvertible { var lcNull: LCNull { get } } /** Convertible protocol for `LCNumber`. */ public protocol LCNumberConvertible: LCValueConvertible { var lcNumber: LCNumber { get } } /** Convertible protocol for `LCBool`. */ public protocol LCBoolConvertible: LCValueConvertible { var lcBool: LCBool { get } } /** Convertible protocol for `LCString`. */ public protocol LCStringConvertible: LCValueConvertible { var lcString: LCString { get } } /** Convertible protocol for `LCArray`. */ public protocol LCArrayConvertible: LCValueConvertible { var lcArray: LCArray { get } } /** Convertible protocol for `LCDictionary`. */ public protocol LCDictionaryConvertible: LCValueConvertible { var lcDictionary: LCDictionary { get } } /** Convertible protocol for `LCData`. */ public protocol LCDataConvertible: LCValueConvertible { var lcData: LCData { get } } /** Convertible protocol for `LCDate`. */ public protocol LCDateConvertible: LCValueConvertible { var lcDate: LCDate { get } } extension NSNull: LCNullConvertible { public var lcValue: LCValue { return lcNull } public var lcNull: LCNull { return LCNull() } } extension Int: LCNumberConvertible { public var lcValue: LCValue { return lcNumber } public var lcNumber: LCNumber { return LCNumber(Double(self)) } } extension UInt: LCNumberConvertible { public var lcValue: LCValue { return lcNumber } public var lcNumber: LCNumber { return LCNumber(Double(self)) } } extension Int8: LCNumberConvertible { public var lcValue: LCValue { return lcNumber } public var lcNumber: LCNumber { return LCNumber(Double(self)) } } extension UInt8: LCNumberConvertible { public var lcValue: LCValue { return lcNumber } public var lcNumber: LCNumber { return LCNumber(Double(self)) } } extension Int16: LCNumberConvertible { public var lcValue: LCValue { return lcNumber } public var lcNumber: LCNumber { return LCNumber(Double(self)) } } extension UInt16: LCNumberConvertible { public var lcValue: LCValue { return lcNumber } public var lcNumber: LCNumber { return LCNumber(Double(self)) } } extension Int32: LCNumberConvertible { public var lcValue: LCValue { return lcNumber } public var lcNumber: LCNumber { return LCNumber(Double(self)) } } extension UInt32: LCNumberConvertible { public var lcValue: LCValue { return lcNumber } public var lcNumber: LCNumber { return LCNumber(Double(self)) } } extension Int64: LCNumberConvertible { public var lcValue: LCValue { return lcNumber } public var lcNumber: LCNumber { return LCNumber(Double(self)) } } extension UInt64: LCNumberConvertible { public var lcValue: LCValue { return lcNumber } public var lcNumber: LCNumber { return LCNumber(Double(self)) } } extension Float: LCNumberConvertible { public var lcValue: LCValue { return lcNumber } public var lcNumber: LCNumber { return LCNumber(Double(self)) } } extension Double: LCNumberConvertible { public var lcValue: LCValue { return lcNumber } public var lcNumber: LCNumber { return LCNumber(Double(self)) } } extension Bool: LCBoolConvertible { public var lcValue: LCValue { return lcBool } public var lcBool: LCBool { return LCBool(self) } } extension NSNumber: LCNumberConvertible, LCBoolConvertible { public var lcValue: LCValue { if ObjectProfiler.shared.isBoolean(self) { return lcBool } return lcNumber } public var lcNumber: LCNumber { return LCNumber(doubleValue) } public var lcBool: LCBool { return LCBool(boolValue) } } extension String: LCStringConvertible { public var lcValue: LCValue { return lcString } public var lcString: LCString { return LCString(self) } } extension NSString: LCStringConvertible { public var lcValue: LCValue { return lcString } public var lcString: LCString { return LCString(String(self)) } } extension URL: LCStringConvertible { public var lcValue: LCValue { return lcString } public var lcString: LCString { return LCString(absoluteString) } } extension Array: LCValueConvertible, LCArrayConvertible where Element: LCValueConvertible { public var lcValue: LCValue { return lcArray } public var lcArray: LCArray { let value = map { element in element.lcValue } return LCArray(value) } } extension Dictionary: LCValueConvertible, LCDictionaryConvertible where Key == String, Value: LCValueConvertible { public var lcValue: LCValue { return lcDictionary } public var lcDictionary: LCDictionary { let value = mapValue { value in value.lcValue } return LCDictionary(value) } } extension Data: LCDataConvertible { public var lcValue: LCValue { return lcData } public var lcData: LCData { return LCData(self) } } extension NSData: LCDataConvertible { public var lcValue: LCValue { return lcData } public var lcData: LCData { return LCData(self as Data) } } extension Date: LCDateConvertible { public var lcValue: LCValue { return lcDate } public var lcDate: LCDate { return LCDate(self) } } extension NSDate: LCDateConvertible { public var lcValue: LCValue { return lcDate } public var lcDate: LCDate { return LCDate(self as Date) } } extension LCNull: LCValueConvertible, LCNullConvertible { public var lcValue: LCValue { return self } public var lcNull: LCNull { return self } } extension LCNumber: LCValueConvertible, LCNumberConvertible { public var lcValue: LCValue { return self } public var lcNumber: LCNumber { return self } } extension LCBool: LCValueConvertible, LCBoolConvertible { public var lcValue: LCValue { return self } public var lcBool: LCBool { return self } } extension LCString: LCValueConvertible, LCStringConvertible { public var lcValue: LCValue { return self } public var lcString: LCString { return self } } extension LCArray: LCValueConvertible, LCArrayConvertible { public var lcValue: LCValue { return self } public var lcArray: LCArray { return self } } extension LCDictionary: LCValueConvertible, LCDictionaryConvertible { public var lcValue: LCValue { return self } public var lcDictionary: LCDictionary { return self } } extension LCObject: LCValueConvertible { public var lcValue: LCValue { return self } } extension LCRelation: LCValueConvertible { public var lcValue: LCValue { return self } } extension LCGeoPoint: LCValueConvertible { public var lcValue: LCValue { return self } } extension LCData: LCValueConvertible, LCDataConvertible { public var lcValue: LCValue { return self } public var lcData: LCData { return self } } extension LCDate: LCValueConvertible, LCDateConvertible { public var lcValue: LCValue { return self } public var lcDate: LCDate { return self } } extension LCACL: LCValueConvertible { public var lcValue: LCValue { return self } }
61e8b4572ffd6b7c0cf8250432482605
20.651261
123
0.643185
false
false
false
false
Raizlabs/SketchyCode
refs/heads/master
SketchyCode/Transformation/Helpers.swift
mit
1
// // Helpers.swift // SketchyCode // // Created by Brian King on 10/13/17. // Copyright © 2017 Brian King. All rights reserved. // import Foundation extension MSRect { func asCGRect() -> String { return "CGRect(x: \(x), y: \(y), width: \(width), height: \(height))" } } struct ResizeOptions: OptionSet { var rawValue: Int static var none = ResizeOptions(rawValue: 0) static var flexibleLeftMargin = ResizeOptions(rawValue: 1 << 0) static var flexibleWidth = ResizeOptions(rawValue: 1 << 1) static var flexibleRightMargin = ResizeOptions(rawValue: 1 << 2) static var flexibleTopMargin = ResizeOptions(rawValue: 1 << 3) static var flexibleHeight = ResizeOptions(rawValue: 1 << 4) static var flexibleBottomMargin = ResizeOptions(rawValue: 1 << 5) };
4b66fe4ba65ebfc0333c1d63696a4158
31.230769
77
0.650358
false
false
false
false
freshOS/then
refs/heads/master
Tests/ThenTests/ChainTests.swift
mit
2
// // ChainTests.swift // then // // Created by Sacha Durand Saint Omer on 13/03/2017. // Copyright © 2017 s4cha. All rights reserved. // import XCTest import Then class ChainTests: XCTestCase { func testChainSyncPromise() { let exp = expectation(description: "") Promise<String>.resolve("Cool").chain { s in XCTAssertEqual(s, "Cool") exp.fulfill() }.then { _ in } waitForExpectations(timeout: 0.3, handler: nil) } func testChainASyncPromise() { let exp = expectation(description: "") fetchUserNameFromId(123).chain { s in XCTAssertEqual(s, "John Smith") exp.fulfill() }.then { _ in } waitForExpectations(timeout: 0.3, handler: nil) } func testChainNotCalledWhenSyncPromiseFails() { let exp = expectation(description: "") Promise<Int>.reject().chain { _ in XCTFail("testChainNotCalledWhenSyncPromiseFails failed") }.onError { _ in exp.fulfill() } waitForExpectations(timeout: 0.3, handler: nil) } func testChainNotCalledWhenAsyncPromiseFails() { let exp = expectation(description: "") failingFetchUserFollowStatusFromName("Tom").chain { _ in XCTFail("testChainNotCalledWhenAsyncPromiseFails failed") }.onError { _ in exp.fulfill() } waitForExpectations(timeout: 0.3, handler: nil) } func testChainKeepsProgress() { let progressExpectation = expectation(description: "thenExpectation") let thenExpectation = expectation(description: "thenExpectation") let chainExpectation = expectation(description: "chainExpectation") upload().chain { chainExpectation.fulfill() }.progress { p in XCTAssertEqual(p, 0.8) progressExpectation.fulfill() }.then { thenExpectation.fulfill() }.onError { _ in print("ERROR") } waitForExpectations(timeout: 0.5, handler: nil) } }
314d5babe04a30984d52539e09a6ed6f
29.867647
77
0.596951
false
true
false
false
danielinoa/TextFieldsTraversalController
refs/heads/master
Classes/TextFieldsTraversalAccessoryView.swift
mit
1
// // TextFieldsTraversalAccessoryView.swift // TextFieldsTraversalController // // Created by Daniel Inoa on 10/10/17. // Copyright © 2017 Daniel Inoa. All rights reserved. // import UIKit /// A toolbar intended to be used as an inputAccessoryView when traversing through a collection of textfields. /// This view contains 3 bar button items: a `previous`, a `next`, and a `done` bar button item. open class TextFieldsTraversalAccessoryView: UIToolbar { // MARK: - Orientation public var orientation: Orientation = .horizontal { didSet { switch orientation { case .horizontal: previousItem.image = image(forDirection: .left) nextItem.image = image(forDirection: .right) case .vertical: previousItem.image = image(forDirection: .up) nextItem.image = image(forDirection: .down) } } } public enum Orientation { case vertical case horizontal } // MARK: - Items let previousItem = UIBarButtonItem() let nextItem = UIBarButtonItem() let doneItem = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: nil) // MARK: - Lifecycle public override init(frame: CGRect) { super.init(frame: frame) configure() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) configure() } // MARK: - Configuration private func configure() { let flexible = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) let fixed = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil) fixed.width = 20 setItems([previousItem, fixed, nextItem, flexible, doneItem], animated: false) orientation = .horizontal } // MARK: - Image private func image(forDirection direction: Direction) -> UIImage { let upArrowImage = imageForUpArrow() let image = UIImage(cgImage: upArrowImage.cgImage!, scale: upArrowImage.scale, orientation: direction.imageOrientation) return image } private func imageForUpArrow() -> UIImage { let lineWidth: CGFloat = 1.5 let ratio: CGFloat = 5.0 / 9.0 let dimension: CGFloat = 20 let size = CGSize(width: dimension, height: dimension * ratio) let bounds = CGRect(origin: .zero, size: size).insetBy(dx: lineWidth / 2, dy: lineWidth / 2) let path = UIBezierPath() path.lineWidth = lineWidth path.lineCapStyle = .round path.move(to: CGPoint(x: bounds.minX, y: bounds.maxY)) path.addLine(to: CGPoint(x: bounds.midX, y: bounds.minY)) path.addLine(to: CGPoint(x: bounds.maxX, y: bounds.maxY)) UIGraphicsBeginImageContextWithOptions(size, false, 0) UIColor.black.setStroke() path.stroke() let image = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return image } // MARK: Direction private enum Direction { case left case right case up case down var imageOrientation: UIImage.Orientation { switch self { case .up: return .up case .down: return .down case .left: return .left case .right: return .right } } } }
071a169b480b47915a213152ed9bc42a
31.036697
127
0.610252
false
false
false
false
eno314/ApiRegisterIOS
refs/heads/develop
ApiRegister/EntryList/EntryListRequest.swift
mit
1
// // EntryListRequest.swift // ApiRegister // // Created by hiroto kitamur on 2014/11/01. // Copyright (c) 2014年 eno. All rights reserved. // import UIKit import Alamofire class EntryListRequest: NSObject { // リクエスト先のURL private let mRequestUrl: String // APIのパース結果を受け取った時のコールバック private let mOnReceiveEntryList: (Array<Entry> -> Void)? // エラー時のコールバック private let mOnRequestFaild: (() -> Void)? // Builder専用のコンストラクタ private init(builder: EntryListRequest.Builder) { mRequestUrl = builder.mRequestUrl mOnReceiveEntryList = builder.mOnReceiveEntryList mOnRequestFaild = builder.mOnRequestFaild } // リクエスト実行メソッド func execute() { Alamofire.request(.GET, mRequestUrl).responseJSON(onResponse) } // レスポンスを受け取った時のコールバック実装 private func onResponse(request: NSURLRequest, response: NSHTTPURLResponse?, json:AnyObject?, error: NSError?) { if error != nil { println(error) callOnRequestFaild() return } if json == nil { println("reponse json is null") callOnRequestFaild() return } let entryList: Array<Entry>? = EntryListParser().parse(json!) if entryList == nil { println("failed parse") callOnRequestFaild() } else { callOnReceiveEntryList(entryList!) } } private func callOnRequestFaild() { if mOnRequestFaild != nil { mOnRequestFaild!() } } private func callOnReceiveEntryList(entryList: Array<Entry>) { if mOnReceiveEntryList != nil { mOnReceiveEntryList!(entryList) } } class Builder: NSObject { // リクエスト先のURL private let mRequestUrl: String // APIのパース結果を受け取った時のコールバック private var mOnReceiveEntryList: ([Entry] -> Void)? // エラー時のコールバック private var mOnRequestFaild: (() -> Void)? init(url: String) { mRequestUrl = url } func setOnReceiveEntryList(onReceiveEntryList: [Entry] -> Void) -> Builder { mOnReceiveEntryList = onReceiveEntryList return self } func setOnRequestFaild(onRequestFailed: () -> Void) -> Builder { mOnRequestFaild = onRequestFailed return self } func build() -> EntryListRequest { return EntryListRequest(builder: self) } } }
e4c76e9d13655774b091517ee83854dc
25.09
116
0.570717
false
false
false
false
AnthonyMDev/Nimble
refs/heads/master
Tests/NimbleTests/Matchers/PostNotificationTest.swift
apache-2.0
2
import XCTest import Nimble import Foundation final class PostNotificationTest: XCTestCase { let notificationCenter = NotificationCenter() func testPassesWhenNoNotificationsArePosted() { expect { // no notifications here! return nil }.to(postNotifications(beEmpty(), fromNotificationCenter: notificationCenter)) } func testPassesWhenExpectedNotificationIsPosted() { let testNotification = Notification(name: Notification.Name("Foo"), object: nil) expect { self.notificationCenter.post(testNotification) }.to(postNotifications(equal([testNotification]), fromNotificationCenter: notificationCenter)) } func testPassesWhenAllExpectedNotificationsArePosted() { let foo = NSNumber(value: 1) let bar = NSNumber(value: 2) let n1 = Notification(name: Notification.Name("Foo"), object: foo) let n2 = Notification(name: Notification.Name("Bar"), object: bar) expect { self.notificationCenter.post(n1) self.notificationCenter.post(n2) return nil }.to(postNotifications(equal([n1, n2]), fromNotificationCenter: notificationCenter)) } func testFailsWhenNoNotificationsArePosted() { let testNotification = Notification(name: Notification.Name("Foo"), object: nil) failsWithErrorMessage("expected to equal <[\(testNotification)]>, got no notifications") { expect { // no notifications here! return nil }.to(postNotifications(equal([testNotification]), fromNotificationCenter: self.notificationCenter)) } } func testFailsWhenNotificationWithWrongNameIsPosted() { let n1 = Notification(name: Notification.Name("Foo"), object: nil) let n2 = Notification(name: Notification.Name(n1.name.rawValue + "a"), object: nil) failsWithErrorMessage("expected to equal <[\(n1)]>, got <[\(n2)]>") { expect { self.notificationCenter.post(n2) return nil }.to(postNotifications(equal([n1]), fromNotificationCenter: self.notificationCenter)) } } func testFailsWhenNotificationWithWrongObjectIsPosted() { let n1 = Notification(name: Notification.Name("Foo"), object: nil) let n2 = Notification(name: n1.name, object: NSObject()) failsWithErrorMessage("expected to equal <[\(n1)]>, got <[\(n2)]>") { expect { self.notificationCenter.post(n2) return nil }.to(postNotifications(equal([n1]), fromNotificationCenter: self.notificationCenter)) } } func testPassesWhenExpectedNotificationEventuallyIsPosted() { let testNotification = Notification(name: Notification.Name("Foo"), object: nil) expect { deferToMainQueue { self.notificationCenter.post(testNotification) } return nil }.toEventually(postNotifications(equal([testNotification]), fromNotificationCenter: notificationCenter)) } }
e7a2654c61e1c15010a3b9d4784e0e09
40.413333
112
0.648422
false
true
false
false
czechboy0/XcodeServerSDK
refs/heads/master
XcodeServerSDK/Server Entities/IntegrationIssue.swift
mit
1
// // Issue.swift // XcodeServerSDK // // Created by Mateusz Zając on 04.08.2015. // Copyright © 2015 Honza Dvorsky. All rights reserved. // import Foundation public class IntegrationIssue: XcodeServerEntity { public enum IssueType: String { case BuildServiceError = "buildServiceError" case BuildServiceWarning = "buildServiceWarning" case TriggerError = "triggerError" case Error = "error" case Warning = "warning" case TestFailure = "testFailure" case AnalyzerWarning = "analyzerWarning" } public enum IssueStatus: Int { case Fresh = 0 case Unresolved case Resolved case Silenced } /// Payload is holding whole Dictionary of the Issue public let payload: NSDictionary public let message: String? public let type: IssueType public let issueType: String public let commits: [Commit] public let integrationID: String public let age: Int public let status: IssueStatus // MARK: Initialization public required init(json: NSDictionary) throws { self.payload = json.copy() as? NSDictionary ?? NSDictionary() self.message = json.optionalStringForKey("message") self.type = try IssueType(rawValue: json.stringForKey("type"))! self.issueType = try json.stringForKey("issueType") self.commits = try json.arrayForKey("commits").map { try Commit(json: $0) } self.integrationID = try json.stringForKey("integrationID") self.age = try json.intForKey("age") self.status = IssueStatus(rawValue: try json.intForKey("status"))! try super.init(json: json) } }
099d7e828188fb4706a994dc8b127b33
29.732143
83
0.648256
false
false
false
false
magicmon/TWImageBrowser
refs/heads/master
TWImageBrowser/Classes/TWImageBrowser+ScrollView.swift
mit
1
// // TWImageBrowser+ScrollView.swift // TWImageBrowser // // Created by magicmon on 2016. 11. 3.. // Copyright © 2016 magicmon. All rights reserved. // // extension UIScrollView { var currentPage: Int { return Int((self.contentOffset.x + (0.5 * self.frame.size.width)) / self.frame.width) + 1 } var totalPage: Int { return Int(self.contentSize.width / self.frame.width) } } extension TWImageBrowser: UIScrollViewDelegate { public func scrollViewDidScroll(_ scrollView: UIScrollView) { self.pageControl.currentPage = self.currentPage - 1 self.delegate?.imageBrowserDidScroll(self) } public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { // Save last viewed page before scrolling lastPage = self.currentPage // Stops what was being scrolled NSObject.cancelPreviousPerformRequests(withTarget: self, selector:autoScrollFunctionName , object: nil) } public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { // Save list viewed page after scrolling lastPage = self.currentPage // stop scroll // Restart to auto scrolling if self.browserType == .banner && self.autoPlayTimeInterval > 0 { self.perform(autoScrollFunctionName, with: nil, afterDelay:self.autoPlayTimeInterval) } scrollViewDidEndScrollingAnimation(scrollView) } public func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) { switch self.browserType { case .normal: // Load image if it has not already been loaded. setupImage(from: self.scrollView.currentPage) // Initialize zoomScale when you go to another page. for index in 0...self.imageObjects.count - 1 { if index + 1 == self.scrollView.currentPage { continue } if let imageView = self.scrollView.subviews[index] as? TWImageView, imageView.imageView.image != nil && imageView.zoomScale > 1.0 { imageView.setZoomScale(imageView.minimumZoomScale, animated: false) } } case .banner: if self.scrollView.currentPage == 1 { self.scrollView.setContentOffset(CGPoint(x: self.scrollView.frame.width * CGFloat(self.totalPage), y: 0), animated: false) } else if self.scrollView.currentPage == self.imageObjects.count { self.scrollView.setContentOffset(CGPoint(x: self.scrollView.frame.width, y: 0), animated: false) } break } self.delegate?.imageBrowserDidEndScrollingAnimation(self) } }
268646129cecc48fd2273fa3db4dbc7a
35.736842
147
0.626074
false
false
false
false
2briancox/ioscreator
refs/heads/master
IOS8SwiftCoreImageTutorial/IOS8SwiftCoreImageTutorial/ViewController.swift
mit
40
// // ViewController.swift // IOS8SwiftCoreImageTutorial // // Created by Arthur Knopper on 01/04/15. // Copyright (c) 2015 Arthur Knopper. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet var imageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() let image = UIImage(named: "dog.jpg") let originalImage = CIImage(image: image) var filter = CIFilter(name: "CIPhotoEffectMono") filter.setDefaults() filter.setValue(originalImage, forKey: kCIInputImageKey) var outputImage = filter.outputImage var newImage = UIImage(CIImage: outputImage) imageView.image = newImage } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
bc1424ca86a92f693befa73d0a4b58e7
23.972222
64
0.655172
false
false
false
false
MxABC/swiftScan
refs/heads/master
swiftScan/ViewController.swift
mit
1
// // ViewController.swift // swiftScan // // Created by xialibing on 15/11/25. // Copyright © 2015年 xialibing. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIImagePickerControllerDelegate, UINavigationControllerDelegate, LBXScanViewControllerDelegate { var tableView: UITableView! var arrayItems: Array<Array<String>> = [ ["模拟qq扫码界面", "qqStyle"], ["模仿支付宝扫码区域", "ZhiFuBaoStyle"], ["模仿微信扫码区域", "weixinStyle"], ["无边框,内嵌4个角", "InnerStyle"], ["4个角在矩形框线上,网格动画", "OnStyle"], ["自定义颜色", "changeColor"], ["只识别框内", "recoCropRect"], ["改变尺寸", "changeSize"], ["条形码效果", "notSquare"], ["二维码/条形码生成", "myCode"], ["相册", "openLocalPhotoAlbum"] ] var isSupportContinuous = false; override func viewDidLoad() { super.viewDidLoad() tableView = UITableView(frame: CGRect(x: 0, y: 20, width: view.frame.width, height: view.frame.height)) self.title = "swift 扫一扫" tableView.delegate = self tableView.dataSource = self self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "reuseIdentifier") view.addSubview(tableView) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return arrayItems.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath as IndexPath) // Configure the cell... cell.textLabel?.text = arrayItems[indexPath.row].first return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { //objc_msgSend对应方法好像没有 if indexPath.row == 10 { openLocalPhotoAlbum() return } isSupportContinuous = false; switch indexPath.row { case 0: self.qqStyle() case 1: self.ZhiFuBaoStyle() case 2: self.weixinStyle() case 3: self.InnerStyle() case 4: self.OnStyle() case 5: self.changeColor() case 6: self.recoCropRect() case 7: self.changeSize() case 8: self.notSquare() case 9: self.myCode() case 10: self.openLocalPhotoAlbum() default: break } tableView.deselectRow(at: indexPath as IndexPath, animated: true) } // MARK: - ---模仿qq扫码界面--------- func qqStyle() { print("qqStyle") let vc = QQScanViewController() var style = LBXScanViewStyle() style.animationImage = UIImage(named: "CodeScan.bundle/qrcode_scan_light_green") vc.scanStyle = style self.navigationController?.pushViewController(vc, animated: true) } // MARK: - --模仿支付宝------ func ZhiFuBaoStyle() { //设置扫码区域参数 var style = LBXScanViewStyle() style.centerUpOffset = 60 style.xScanRetangleOffset = 30 if UIScreen.main.bounds.size.height <= 480 { //3.5inch 显示的扫码缩小 style.centerUpOffset = 40 style.xScanRetangleOffset = 20 } style.color_NotRecoginitonArea = UIColor(red: 0.4, green: 0.4, blue: 0.4, alpha: 0.4) style.photoframeAngleStyle = LBXScanViewPhotoframeAngleStyle.Inner style.photoframeLineW = 2.0 style.photoframeAngleW = 16 style.photoframeAngleH = 16 style.isNeedShowRetangle = false style.anmiationStyle = LBXScanViewAnimationStyle.NetGrid style.animationImage = UIImage(named: "CodeScan.bundle/qrcode_scan_full_net") let vc = LBXScanViewController() vc.scanStyle = style vc.isSupportContinuous = true; isSupportContinuous = true; vc.scanResultDelegate = self self.navigationController?.pushViewController(vc, animated: true) } func createImageWithColor(color: UIColor) -> UIImage { let rect=CGRect(x: 0.0, y: 0.0, width: 1.0, height: 1.0) UIGraphicsBeginImageContext(rect.size) let context = UIGraphicsGetCurrentContext() context!.setFillColor(color.cgColor) context!.fill(rect) let theImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return theImage! } // MARK: - ------条形码扫码界面 --------- func notSquare() { //设置扫码区域参数 //设置扫码区域参数 var style = LBXScanViewStyle() style.centerUpOffset = 44 style.photoframeAngleStyle = LBXScanViewPhotoframeAngleStyle.Inner style.photoframeLineW = 4 style.photoframeAngleW = 28 style.photoframeAngleH = 16 style.isNeedShowRetangle = false style.anmiationStyle = LBXScanViewAnimationStyle.LineStill style.animationImage = createImageWithColor(color: UIColor.red) //非正方形 //设置矩形宽高比 style.whRatio = 4.3/2.18 //离左边和右边距离 style.xScanRetangleOffset = 30 let vc = LBXScanViewController() vc.scanResultDelegate = self vc.scanStyle = style self.navigationController?.pushViewController(vc, animated: true) } // MARK: - ---无边框,内嵌4个角 ----- func InnerStyle() { //设置扫码区域参数 var style = LBXScanViewStyle() style.centerUpOffset = 44 style.photoframeAngleStyle = LBXScanViewPhotoframeAngleStyle.Inner style.photoframeLineW = 3 style.photoframeAngleW = 18 style.photoframeAngleH = 18 style.isNeedShowRetangle = false style.anmiationStyle = LBXScanViewAnimationStyle.LineMove //qq里面的线条图片 style.animationImage = UIImage(named: "CodeScan.bundle/qrcode_scan_light_green") let vc = LBXScanViewController() vc.scanStyle = style vc.scanResultDelegate = self self.navigationController?.pushViewController(vc, animated: true) } // MARK: - --无边框,内嵌4个角------ func weixinStyle() { //设置扫码区域参数 var style = LBXScanViewStyle() style.centerUpOffset = 44 style.photoframeAngleStyle = LBXScanViewPhotoframeAngleStyle.Inner style.photoframeLineW = 2 style.photoframeAngleW = 18 style.photoframeAngleH = 18 style.isNeedShowRetangle = false style.anmiationStyle = LBXScanViewAnimationStyle.LineMove style.colorAngle = UIColor(red: 0.0/255, green: 200.0/255.0, blue: 20.0/255.0, alpha: 1.0) style.animationImage = UIImage(named: "CodeScan.bundle/qrcode_Scan_weixin_Line") let vc = LBXScanViewController() vc.scanStyle = style vc.scanResultDelegate = self self.navigationController?.pushViewController(vc, animated: true) } // MARK: - ---框内区域识别 func recoCropRect() { //设置扫码区域参数 var style = LBXScanViewStyle() style.centerUpOffset = 44 style.photoframeAngleStyle = LBXScanViewPhotoframeAngleStyle.On style.photoframeLineW = 6 style.photoframeAngleW = 24 style.photoframeAngleH = 24 style.isNeedShowRetangle = true style.anmiationStyle = LBXScanViewAnimationStyle.NetGrid //矩形框离左边缘及右边缘的距离 style.xScanRetangleOffset = 80 //使用的支付宝里面网格图片 style.animationImage = UIImage(named: "CodeScan.bundle/qrcode_scan_part_net") let vc = LBXScanViewController() vc.scanStyle = style vc.isOpenInterestRect = true vc.scanResultDelegate = self //TODO:待设置框内识别 self.navigationController?.pushViewController(vc, animated: true) } // MARK: - ----4个角在矩形框线上,网格动画 func OnStyle() { //设置扫码区域参数 var style = LBXScanViewStyle() style.centerUpOffset = 44 style.photoframeAngleStyle = LBXScanViewPhotoframeAngleStyle.On style.photoframeLineW = 6 style.photoframeAngleW = 24 style.photoframeAngleH = 24 style.isNeedShowRetangle = true style.anmiationStyle = LBXScanViewAnimationStyle.NetGrid //使用的支付宝里面网格图片 style.animationImage = UIImage(named: "CodeScan.bundle/qrcode_scan_part_net") let vc = LBXScanViewController() vc.scanStyle = style vc.scanResultDelegate = self self.navigationController?.pushViewController(vc, animated: true) } // MARK: - ------自定义4个角及矩形框颜色 func changeColor() { //设置扫码区域参数 var style = LBXScanViewStyle() style.centerUpOffset = 44 style.photoframeAngleStyle = LBXScanViewPhotoframeAngleStyle.On style.photoframeLineW = 6 style.photoframeAngleW = 24 style.photoframeAngleH = 24 style.isNeedShowRetangle = true style.anmiationStyle = LBXScanViewAnimationStyle.LineMove //使用的支付宝里面网格图片 style.animationImage = UIImage(named: "CodeScan.bundle/qrcode_scan_light_green") //4个角的颜色 style.colorAngle = UIColor(red: 65.0/255.0, green: 174.0/255.0, blue: 57.0/255.0, alpha: 1.0) //矩形框颜色 style.colorRetangleLine = UIColor(red: 247.0/255.0, green: 202.0/255.0, blue: 15.0/255.0, alpha: 1.0) //非矩形框区域颜色 style.color_NotRecoginitonArea = UIColor(red: 247.0/255.0, green: 202.0/255.0, blue: 15.0/255.0, alpha: 0.2) let vc = LBXScanViewController() vc.scanStyle = style vc.readyString = "相机启动中..." vc.scanResultDelegate = self self.navigationController?.pushViewController(vc, animated: true) } // MARK: - -----改变扫码区域位置 func changeSize() { //设置扫码区域参数 var style = LBXScanViewStyle() //矩形框向上移动 style.centerUpOffset = 60 //矩形框离左边缘及右边缘的距离 style.xScanRetangleOffset = 100 style.photoframeAngleStyle = LBXScanViewPhotoframeAngleStyle.On style.photoframeLineW = 6 style.photoframeAngleW = 24 style.photoframeAngleH = 24 style.isNeedShowRetangle = true style.anmiationStyle = LBXScanViewAnimationStyle.LineMove //qq里面的线条图片 style.animationImage = UIImage(named: "CodeScan.bundle/qrcode_scan_light_green") let vc = LBXScanViewController() vc.scanStyle = style vc.scanResultDelegate = self self.navigationController?.pushViewController(vc, animated: true) } // MARK: - ------- 相册 func openLocalPhotoAlbum() { LBXPermissions.authorizePhotoWith { [weak self] (granted) in if granted { if let strongSelf = self { let picker = UIImagePickerController() picker.sourceType = UIImagePickerController.SourceType.photoLibrary picker.delegate = self; picker.allowsEditing = true strongSelf.present(picker, animated: true, completion: nil) } } else { LBXPermissions.jumpToSystemPrivacySetting() } } } // MARK: - ----相册选择图片识别二维码 (条形码没有找到系统方法) func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { picker.dismiss(animated: true, completion: nil) var image:UIImage? = info[UIImagePickerController.InfoKey.editedImage] as? UIImage if (image == nil ) { image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage } if(image == nil) { return } if(image != nil) { let arrayResult = LBXScanWrapper.recognizeQRImage(image: image!) if arrayResult.count > 0 { let result = arrayResult[0] showMsg(title: result.strBarCodeType, message: result.strScanned) return } } showMsg(title: "", message: "识别失败") } func showMsg(title:String?,message:String?) { let alertController = UIAlertController(title: title, message:message, preferredStyle: UIAlertController.Style.alert) let alertAction = UIAlertAction(title: "知道了", style: UIAlertAction.Style.default) { (alertAction) -> Void in } alertController.addAction(alertAction) present(alertController, animated: true, completion: nil) } func myCode() { let vc = MyCodeViewController() self.navigationController?.pushViewController(vc, animated: true) } func scanFinished(scanResult: LBXScanResult, error: String?) { NSLog("scanResult:\(scanResult)") if !isSupportContinuous { DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(400)) { let vc = ScanResultController() vc.codeResult = scanResult self.navigationController?.pushViewController(vc, animated: true) } } } }
4ef3c0e6c08439353efd4fee5911b451
29.678984
180
0.616606
false
false
false
false
jxxcarlson/exploring_swift
refs/heads/master
concentricCircles.playground/Sources/Circle.swift
mit
3
import UIKit public enum drawMode { case Fill case Stroke case Both } public class Circle{ public var center = Point() public var radius = 0.0 public var strokeColor = UIColor.blueColor() public var lineWidth = 2.0 public init() { } public init( center: Point, radius: Double) { self.center = center self.radius = radius } public func draw(frame: CGRect) { let ox = frame.size.width/2 let oy = frame.size.height/2 let context = UIGraphicsGetCurrentContext() self.strokeColor.set() CGContextSetLineWidth(context, CGFloat(self.lineWidth)) CGContextAddArc(context, CGFloat(self.center.x) + ox, CGFloat(self.center.y) + oy, CGFloat(self.radius), 0.0, CGFloat(M_PI * 2.0), 1) CGContextStrokePath(context) } }
cefea2528a93439646aabe33f1d0081a
18.078431
63
0.543679
false
false
false
false
MadArkitekt/Swift_Tutorials_And_Demos
refs/heads/master
DynamicDrop/DynamicDrop/ViewController.swift
gpl-2.0
1
// // ViewController.swift // DynamicDrop // // Created by Edward Salter on 8/17/14. // Copyright (c) 2014 Edward Salter. All rights reserved. // import UIKit import CoreGraphics import QuartzCore class ViewController: UIViewController, UICollisionBehaviorDelegate { var animator: UIDynamicAnimator! var gravity: UIGravityBehavior! var dynamicBehavior: UICollisionBehavior! var snapToTouch: UISnapBehavior! var square: UIView! var touch: UITouch! var firstContact = false override func viewDidLoad() { super.viewDidLoad() square = UIView(frame: CGRect(x: 100, y: 0, width: 100, height: 100)) square.backgroundColor = UIColor.greenColor() view.addSubview(self.square) let barrierFloor = UIView(frame: CGRectMake( 0, 560, 320, 20)) barrierFloor.backgroundColor = UIColor.blackColor() view.addSubview(barrierFloor) let bumperLeft = UIView(frame: CGRectMake(0, 300, 125, 25)) bumperLeft.backgroundColor = UIColor.orangeColor() view.addSubview(bumperLeft) let leftMidBumper = UIView(frame: CGRectMake(240, 385, 40, 40)) leftMidBumper.backgroundColor = UIColor.orangeColor() view.addSubview(leftMidBumper) let rightMidBumper = UIView(frame: CGRectMake(300, 205, 40, 40)) rightMidBumper.backgroundColor = UIColor.orangeColor() view.addSubview(rightMidBumper) animator = UIDynamicAnimator(referenceView: self.view) gravity = UIGravityBehavior(items: [self.square]) dynamicBehavior = UICollisionBehavior(items: [self.square]) dynamicBehavior.collisionDelegate = self dynamicBehavior.addBoundaryWithIdentifier("bumperLeft", forPath: UIBezierPath(rect: bumperLeft.frame)) dynamicBehavior.addBoundaryWithIdentifier("leftMidBumper", forPath: UIBezierPath(rect: leftMidBumper.frame)) dynamicBehavior.addBoundaryWithIdentifier("rightMidBumper", forPath: UIBezierPath(rect: rightMidBumper.frame)) dynamicBehavior.translatesReferenceBoundsIntoBoundary = true animator.addBehavior(dynamicBehavior) animator.addBehavior(gravity) var updateCount = 0 dynamicBehavior.action = { if (updateCount % 2 == 0) { let outline = UIView(frame: self.square.bounds) outline.transform = self.square.transform outline.center = self.square.center outline.alpha = 0.4 outline.backgroundColor = UIColor.clearColor() outline.layer.borderColor = self.square.layer.presentationLayer().backgroundColor outline.layer.borderWidth = 1.0 outline.layer.cornerRadius = 5 self.view.addSubview(outline) } ++updateCount } let objectBehavior = UIDynamicItemBehavior(items: [self.square]) objectBehavior.elasticity = 0.8 animator.addBehavior(objectBehavior) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func collisionBehavior(behavior: UICollisionBehavior!, beganContactForItem item: UIDynamicItem!, withBoundaryIdentifier identifier: NSCopying!, atPoint p: CGPoint) { println("We've been hit at \(identifier)") let collisionView = item as UIView collisionView.backgroundColor = UIColor.greenColor() UIView.animateWithDuration(0.3, animations: { () -> Void in collisionView.backgroundColor = UIColor.redColor() }) if (!firstContact) { firstContact = true let square = UIView(frame: CGRect(x: 30, y: 0, width: 100, height: 100)) square.backgroundColor = UIColor.greenColor() view.addSubview(square) dynamicBehavior.addItem(square) gravity.addItem(square) let attach = UIAttachmentBehavior(item: collisionView, attachedToItem:square) animator.addBehavior(attach) } } override func touchesBegan(touches: NSSet!, withEvent event: UIEvent!) { if ((snapToTouch) != nil) { animator.removeBehavior(snapToTouch) } touch = touches.anyObject() as UITouch snapToTouch = UISnapBehavior(item: square, snapToPoint: touch.locationInView(view)) animator.addBehavior(snapToTouch) self.view.setNeedsDisplay() } override func touchesEnded(touches: NSSet!, withEvent event: UIEvent!) { if (snapToTouch != nil) { animator.removeBehavior(snapToTouch) } gravity = UIGravityBehavior(items: [square, self.square]) animator.addBehavior(gravity) self.view.setNeedsDisplay() } }
be652e3c702ad730d01acaf6a0396d72
36.045802
169
0.650113
false
false
false
false
johntmcintosh/BarricadeKit
refs/heads/master
Examples/SwiftExample/SwiftExample/Tweaks.swift
mit
1
// // Tweaks.swift // SwiftExample // // Created by John McIntosh on 6/14/17. // Copyright © 2017 John T McIntosh. All rights reserved. // import Foundation import Tweaks public typealias TweakActionBlock = @convention(block) () -> Void @discardableResult public func tweakAction(categoryName: String, collectionName: String, tweakName: String, action: @escaping TweakActionBlock) -> FBTweak { let store = FBTweakStore.sharedInstance()! let category = store.makeCategory(name: categoryName) let collection = category.makeCollection(name: collectionName) let tweak = collection.makeTweak(categoryName: categoryName, tweakName: tweakName) tweak.defaultValue = unsafeBitCast(action, to: AnyObject.self) return tweak } extension FBTweakStore { public func makeCategory(name: String) -> FBTweakCategory { guard let category = tweakCategory(withName: name) else { let category = FBTweakCategory(name: name)! addTweakCategory(category) return category } return category } } extension FBTweakCategory { public func makeCollection(name: String) -> FBTweakCollection { guard let collection = tweakCollection(withName: name) else { let collection = FBTweakCollection(name: name)! addTweakCollection(collection) return collection } return collection } } extension FBTweakCollection { public func makeTweak(categoryName: String, tweakName: String) -> FBTweak { let identifier = FBTweak.makeIdentifier(categoryName: categoryName, collectionName: self.name, tweakName: tweakName) guard let tweak = tweak(withIdentifier: identifier) else { let tweak = FBTweak(identifier: identifier)! tweak.name = tweakName addTweak(tweak) return tweak } return tweak } } extension FBTweak { public static func makeIdentifier(categoryName: String, collectionName: String, tweakName: String) -> String { return "FBTweak:\(categoryName)-\(collectionName)-\(tweakName)" } }
75a9fd5436b7090a39d09d393acee049
27.666667
137
0.675814
false
false
false
false
rchatham/SwiftyAnimate
refs/heads/master
Sources/BlockTypes.swift
mit
1
// // BlockTypes.swift // SwiftyAnimate // // Created by Reid Chatham on 1/12/17. // Copyright © 2017 Reid Chatham. All rights reserved. // import Foundation /// Block containing standard animations to perform. public typealias AnimationBlock = (Void)->Void /// Block to be called from a `WaitBlock` that tells the animation to resume execution. It is safe to use with a timeout and can only be called once. public typealias ResumeBlock = (Void)->Void /// Block that contains code that an animation should be paused for. It gets passed a `ResumeBlock` that must be called to resume the animation. public typealias WaitBlock = (_ resume: @escaping ResumeBlock)->Void /// Block that gets called between animations. public typealias DoBlock = (Void)->Void class Block: NSObject { private struct Static { fileprivate static var instances: [Block] = [] } private var completion: (()->Void)? init(_ completion: @escaping ()->Void) { self.completion = completion super.init() Static.instances.append(self) } @objc func complete(_ sender: Any) { completion?() completion = nil Static.instances = Static.instances.filter { $0 !== self } } } class Wait: Block { init(timeout: TimeInterval? = nil, _ completion: @escaping ()->Void = {_ in}) { var timer: Timer? super.init() { completion() timer?.invalidate() } if let timeout = timeout { if #available(iOS 10.0, *) { timer = Timer.scheduledTimer(withTimeInterval: timeout, repeats: false) { [weak self] (timer) in self?.complete(timer) } } else { timer = Timer.scheduledTimer(timeInterval: timeout, target: self, selector: #selector(Wait.complete(_:)), userInfo: nil, repeats: false) } } } } class BasicAnimationBlock: Block { private var animationBlock: AnimationBlock? @discardableResult init(duration: TimeInterval, delay: TimeInterval, animationBlock: @escaping AnimationBlock, completion: ((Bool)->Void)? = nil) { self.animationBlock = animationBlock super.init { completion?(true) } // Animation if delay == 0.0 { animationBlock() } else { if #available(iOS 10.0, *) { Timer.scheduledTimer(withTimeInterval: delay, repeats: false, block: { [weak self] (timer) in self?.animationBlock(timer) }) } else { Timer.scheduledTimer(timeInterval: delay, target: self, selector: #selector(BasicAnimationBlock.animationBlock(_:)), userInfo: nil, repeats: false) } } // Completion if #available(iOS 10.0, *) { Timer.scheduledTimer(withTimeInterval: duration + delay, repeats: false, block: { [weak self] (timer) in self?.complete(timer) }) } else { Timer.scheduledTimer(timeInterval: duration + delay, target: self, selector: #selector(BasicAnimationBlock.complete(_:)), userInfo: nil, repeats: false) } } @objc func animationBlock(_ sender: Timer) { animationBlock?() animationBlock = nil } }
672c7851bc3e6b81c7709f8e2849dbf4
30.990566
164
0.590976
false
false
false
false
RocketChat/Rocket.Chat.iOS
refs/heads/develop
Rocket.Chat/Extensions/DifferenceKitExtension.swift
mit
1
// // DifferenceKitExtension.swift // Rocket.Chat // // Created by Samar Sunkaria on 8/22/18. // Copyright © 2018 Rocket.Chat. All rights reserved. // // swiftlint:disable cyclomatic_complexity import DifferenceKit extension UITableView { /// Applies multiple animated updates in stages using `StagedChangeset`. /// /// - Note: There are combination of changes that crash when applied simultaneously in `performBatchUpdates`. /// Assumes that `StagedChangeset` has a minimum staged changesets to avoid it. /// The data of the dataSource needs to be updated before `performBatchUpdates` in every stages. /// /// - Parameters: /// - stagedChangeset: A staged set of changes. /// - animation: An option to animate the updates. /// - updateRows: A closure used to update the contents of the cells in place of calling reloadRows. /// - interrupt: A closure that takes an changeset as its argument and returns `true` if the animated /// updates should be stopped and performed reloadData. Default is nil. /// - setData: A closure that takes the collection as a parameter. /// The collection should be set to dataSource of UITableView. func reload<C>( using stagedChangeset: StagedChangeset<C>, with animation: @autoclosure () -> UITableView.RowAnimation, updateRows: ([IndexPath]) -> Void, interrupt: ((Changeset<C>) -> Bool)? = nil, setData: (C) -> Void ) { if case .none = window, let data = stagedChangeset.last?.data { setData(data) return reloadData() } for changeset in stagedChangeset { if let interrupt = interrupt, interrupt(changeset), let data = stagedChangeset.last?.data { setData(data) return reloadData() } _performBatchUpdates { setData(changeset.data) if !changeset.sectionDeleted.isEmpty { deleteSections(IndexSet(changeset.sectionDeleted), with: animation()) } if !changeset.sectionInserted.isEmpty { insertSections(IndexSet(changeset.sectionInserted), with: animation()) } if !changeset.sectionUpdated.isEmpty { reloadSections(IndexSet(changeset.sectionUpdated), with: animation()) } for (source, target) in changeset.sectionMoved { moveSection(source, toSection: target) } if !changeset.elementDeleted.isEmpty { deleteRows(at: changeset.elementDeleted.map { IndexPath(row: $0.element, section: $0.section) }, with: animation()) } if !changeset.elementInserted.isEmpty { insertRows(at: changeset.elementInserted.map { IndexPath(row: $0.element, section: $0.section) }, with: animation()) } if !changeset.elementUpdated.isEmpty { updateRows(changeset.elementUpdated.map({ IndexPath(row: $0.element, section: $0.section) })) } for (source, target) in changeset.elementMoved { moveRow(at: IndexPath(row: source.element, section: source.section), to: IndexPath(row: target.element, section: target.section)) } } } } private func _performBatchUpdates(_ updates: () -> Void) { if #available(iOS 11.0, tvOS 11.0, *) { performBatchUpdates(updates) } else { beginUpdates() updates() endUpdates() } } }
1b0d0663764fac19fd22ee4abe2983b1
39.204301
149
0.586253
false
false
false
false
dvor/Antidote
refs/heads/master
Antidote/AddFriendController.swift
mit
1
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. import UIKit import SnapKit private struct Constants { static let TextViewTopOffset = 5.0 static let TextViewXOffset = 5.0 static let QrCodeBottomSpacerDeltaHeight = 70.0 static let SendAlertTextViewBottomOffset = -10.0 static let SendAlertTextViewXOffset = 5.0 static let SendAlertTextViewHeight = 70.0 } protocol AddFriendControllerDelegate: class { func addFriendControllerScanQRCode( _ controller: AddFriendController, validateCodeHandler: @escaping (String) -> Bool, didScanHander: @escaping (String) -> Void) func addFriendControllerDidFinish(_ controller: AddFriendController) } class AddFriendController: UIViewController { weak var delegate: AddFriendControllerDelegate? fileprivate let theme: Theme fileprivate weak var submanagerFriends: OCTSubmanagerFriends! fileprivate var textView: UITextView! fileprivate var orTopSpacer: UIView! fileprivate var qrCodeBottomSpacer: UIView! fileprivate var orLabel: UILabel! fileprivate var qrCodeButton: UIButton! fileprivate var cachedMessage: String? init(theme: Theme, submanagerFriends: OCTSubmanagerFriends) { self.theme = theme self.submanagerFriends = submanagerFriends super.init(nibName: nil, bundle: nil) addNavigationButtons() edgesForExtendedLayout = UIRectEdge() title = String(localized: "add_contact_title") } required convenience init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func loadView() { loadViewWithBackgroundColor(theme.colorForType(.NormalBackground)) createViews() installConstraints() updateSendButton() } } extension AddFriendController { func qrCodeButtonPressed() { func prepareString(_ string: String) -> String { var string = string string = string.uppercased().trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) if string.hasPrefix("TOX:") { return string.substring(from: string.characters.index(string.startIndex, offsetBy: 4)) } return string } delegate?.addFriendControllerScanQRCode(self, validateCodeHandler: { return isAddressString(prepareString($0)) }, didScanHander: { [unowned self] in self.textView.text = prepareString($0) self.updateSendButton() }) } func sendButtonPressed() { textView.resignFirstResponder() let messageView = UITextView() messageView.text = cachedMessage messageView.placeholder = String(localized: "add_contact_default_message_text") messageView.font = UIFont.systemFont(ofSize: 17.0) messageView.layer.cornerRadius = 5.0 messageView.layer.masksToBounds = true let alert = SDCAlertController( title: String(localized: "add_contact_default_message_title"), message: nil, preferredStyle: .alert)! alert.contentView.addSubview(messageView) messageView.snp.makeConstraints { $0.top.equalTo(alert.contentView) $0.bottom.equalTo(alert.contentView).offset(Constants.SendAlertTextViewBottomOffset); $0.leading.equalTo(alert.contentView).offset(Constants.SendAlertTextViewXOffset); $0.trailing.equalTo(alert.contentView).offset(-Constants.SendAlertTextViewXOffset); $0.height.equalTo(Constants.SendAlertTextViewHeight); } alert.addAction(SDCAlertAction(title: String(localized: "alert_cancel"), style: .default, handler: nil)) alert.addAction(SDCAlertAction(title: String(localized: "add_contact_send"), style: .recommended) { [unowned self] action in self.cachedMessage = messageView.text let message = messageView.text.isEmpty ? messageView.placeholder : messageView.text do { try self.submanagerFriends.sendFriendRequest(toAddress: self.textView.text, message: message) } catch let error as NSError { handleErrorWithType(.toxAddFriend, error: error) return } self.delegate?.addFriendControllerDidFinish(self) }) alert.present(completion: nil) } } extension AddFriendController: UITextViewDelegate { func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { if text == "\n" { textView.resignFirstResponder() return false } let resultText = (textView.text! as NSString).replacingCharacters(in: range, with: text) let maxLength = Int(kOCTToxAddressLength) if resultText.lengthOfBytes(using: String.Encoding.utf8) > maxLength { textView.text = resultText.substringToByteLength(maxLength, encoding: String.Encoding.utf8) return false } return true } func textViewDidChange(_ textView: UITextView) { updateSendButton() } } private extension AddFriendController { func addNavigationButtons() { navigationItem.rightBarButtonItem = UIBarButtonItem( title: String(localized: "add_contact_send"), style: .done, target: self, action: #selector(AddFriendController.sendButtonPressed)) } func createViews() { textView = UITextView() textView.placeholder = String(localized: "add_contact_tox_id_placeholder") textView.delegate = self textView.isScrollEnabled = false textView.font = UIFont.systemFont(ofSize: 17) textView.textColor = theme.colorForType(.NormalText) textView.backgroundColor = .clear textView.returnKeyType = .done textView.layer.cornerRadius = 5.0 textView.layer.borderWidth = 0.5 textView.layer.borderColor = theme.colorForType(.SeparatorsAndBorders).cgColor textView.layer.masksToBounds = true view.addSubview(textView) orTopSpacer = createSpacer() qrCodeBottomSpacer = createSpacer() orLabel = UILabel() orLabel.text = String(localized: "add_contact_or_label") orLabel.textColor = theme.colorForType(.NormalText) orLabel.backgroundColor = .clear view.addSubview(orLabel) qrCodeButton = UIButton(type: .system) qrCodeButton.setTitle(String(localized: "add_contact_use_qr"), for: UIControlState()) qrCodeButton.titleLabel!.font = UIFont.antidoteFontWithSize(16.0, weight: .bold) qrCodeButton.addTarget(self, action: #selector(AddFriendController.qrCodeButtonPressed), for: .touchUpInside) view.addSubview(qrCodeButton) } func createSpacer() -> UIView { let spacer = UIView() spacer.backgroundColor = .clear view.addSubview(spacer) return spacer } func installConstraints() { textView.snp.makeConstraints { $0.top.equalTo(view).offset(Constants.TextViewTopOffset) $0.leading.equalTo(view).offset(Constants.TextViewXOffset) $0.trailing.equalTo(view).offset(-Constants.TextViewXOffset) $0.bottom.equalTo(view.snp.centerY) } orTopSpacer.snp.makeConstraints { $0.top.equalTo(textView.snp.bottom) } orLabel.snp.makeConstraints { $0.top.equalTo(orTopSpacer.snp.bottom) $0.centerX.equalTo(view) } qrCodeButton.snp.makeConstraints { $0.top.equalTo(orLabel.snp.bottom) $0.centerX.equalTo(view) } qrCodeBottomSpacer.snp.makeConstraints { $0.top.equalTo(qrCodeButton.snp.bottom) $0.bottom.equalTo(view) $0.height.equalTo(orTopSpacer) } } func updateSendButton() { navigationItem.rightBarButtonItem!.isEnabled = isAddressString(textView.text) } }
57fa361ba075043ddc083c263f34c3ac
33.429167
132
0.659083
false
false
false
false
stephenelliott/SparkChamber
refs/heads/master
SparkKit/SparkKitTests/SparkButtonTests.swift
apache-2.0
1
/** * SparkButtonTests.swift * SparkKitTests * * Created by Steve Elliott on 10/05/2016. * Copyright (c) 2016 eBay Software Foundation. * * 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 SparkChamber @testable import SparkKit class SparkButtonTests: XCTestCase { func testSparkButtonTouchesEnded() { let button = TouchInsideSparkButtonMock() let expectation: XCTestExpectation = self.expectation(description: "A SparkButton's touch event action failed to execute.") let sparkEvent = SparkEvent(trigger: SparkTriggerType.didEndTouch, trace: "button touched") { _ in expectation.fulfill() } button.sparkEvents = [sparkEvent] let touch = UITouchMock() touch.view = button let fakeTouches: Set<UITouch> = [touch] button.touchesEnded(fakeTouches, with:nil) waitForExpectations(timeout: 3.0, handler: nil) } }
f0ff0d7f02efca7044ddd10464978f79
29.977778
125
0.736011
false
true
false
false
breadwallet/breadwallet-ios
refs/heads/master
breadwallet/src/Utilities/Base32.swift
mit
1
// // Base32.swift // breadwallet // // Bases32 Encoding provided by: // https://github.com/mattrubin/Bases // Commit: 6b780caed18179a598ba574ce12e75674d6f4f1f // // Copyright (c) 2015-2016 Matt Rubin and the Bases authors // // 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 typealias Byte = UInt8 typealias Quintet = UInt8 typealias EncodedChar = UInt8 func quintetsFromBytes(_ firstByte: Byte, _ secondByte: Byte, _ thirdByte: Byte, _ fourthByte: Byte, _ fifthByte: Byte) -> (Quintet, Quintet, Quintet, Quintet, Quintet, Quintet, Quintet, Quintet) { return ( firstQuintet(firstByte: firstByte), secondQuintet(firstByte: firstByte, secondByte: secondByte), thirdQuintet(secondByte: secondByte), fourthQuintet(secondByte: secondByte, thirdByte: thirdByte), fifthQuintet(thirdByte: thirdByte, fourthByte: fourthByte), sixthQuintet(fourthByte: fourthByte), seventhQuintet(fourthByte: fourthByte, fifthByte: fifthByte), eighthQuintet(fifthByte: fifthByte) ) } func quintetsFromBytes(_ firstByte: Byte, _ secondByte: Byte, _ thirdByte: Byte, _ fourthByte: Byte) -> (Quintet, Quintet, Quintet, Quintet, Quintet, Quintet, Quintet) { return ( firstQuintet(firstByte: firstByte), secondQuintet(firstByte: firstByte, secondByte: secondByte), thirdQuintet(secondByte: secondByte), fourthQuintet(secondByte: secondByte, thirdByte: thirdByte), fifthQuintet(thirdByte: thirdByte, fourthByte: fourthByte), sixthQuintet(fourthByte: fourthByte), seventhQuintet(fourthByte: fourthByte, fifthByte: 0) ) } func quintetsFromBytes(_ firstByte: Byte, _ secondByte: Byte, _ thirdByte: Byte) -> (Quintet, Quintet, Quintet, Quintet, Quintet) { return ( firstQuintet(firstByte: firstByte), secondQuintet(firstByte: firstByte, secondByte: secondByte), thirdQuintet(secondByte: secondByte), fourthQuintet(secondByte: secondByte, thirdByte: thirdByte), fifthQuintet(thirdByte: thirdByte, fourthByte: 0) ) } func quintetsFromBytes(_ firstByte: Byte, _ secondByte: Byte) -> (Quintet, Quintet, Quintet, Quintet) { return ( firstQuintet(firstByte: firstByte), secondQuintet(firstByte: firstByte, secondByte: secondByte), thirdQuintet(secondByte: secondByte), fourthQuintet(secondByte: secondByte, thirdByte: 0) ) } func quintetsFromBytes(_ firstByte: Byte) -> (Quintet, Quintet) { return ( firstQuintet(firstByte: firstByte), secondQuintet(firstByte: firstByte, secondByte: 0) ) } private func firstQuintet(firstByte: Byte) -> Quintet { return ((firstByte & 0b11111000) >> 3) } private func secondQuintet(firstByte: Byte, secondByte: Byte) -> Quintet { return ((firstByte & 0b00000111) << 2) | ((secondByte & 0b11000000) >> 6) } private func thirdQuintet(secondByte: Byte) -> Quintet { return ((secondByte & 0b00111110) >> 1) } private func fourthQuintet(secondByte: Byte, thirdByte: Byte) -> Quintet { return ((secondByte & 0b00000001) << 4) | ((thirdByte & 0b11110000) >> 4) } private func fifthQuintet(thirdByte: Byte, fourthByte: Byte) -> Quintet { return ((thirdByte & 0b00001111) << 1) | ((fourthByte & 0b10000000) >> 7) } private func sixthQuintet(fourthByte: Byte) -> Quintet { return ((fourthByte & 0b01111100) >> 2) } private func seventhQuintet(fourthByte: Byte, fifthByte: Byte) -> Quintet { return ((fourthByte & 0b00000011) << 3) | ((fifthByte & 0b11100000) >> 5) } private func eighthQuintet(fifthByte: Byte) -> Quintet { return (fifthByte & 0b00011111) } internal let paddingCharacter: EncodedChar = 61 private let encodingTable: [EncodedChar] = [65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 50, 51, 52, 53, 54, 55] internal func character(encoding quintet: Quintet) -> EncodedChar { return encodingTable[Int(quintet)] } internal typealias EncodedBlock = (EncodedChar, EncodedChar, EncodedChar, EncodedChar, EncodedChar, EncodedChar, EncodedChar, EncodedChar) internal func encodeBlock(bytes: UnsafePointer<Byte>, size: Int) -> EncodedBlock { switch size { case 1: return encodeBlock(bytes[0]) case 2: return encodeBlock(bytes[0], bytes[1]) case 3: return encodeBlock(bytes[0], bytes[1], bytes[2]) case 4: return encodeBlock(bytes[0], bytes[1], bytes[2], bytes[3]) case 5: return encodeBlock(bytes[0], bytes[1], bytes[2], bytes[3], bytes[4]) default: fatalError() } } private func encodeBlock(_ b0: Byte, _ b1: Byte, _ b2: Byte, _ b3: Byte, _ b4: Byte) -> EncodedBlock { let q = quintetsFromBytes(b0, b1, b2, b3, b4) let c0 = character(encoding: q.0) let c1 = character(encoding: q.1) let c2 = character(encoding: q.2) let c3 = character(encoding: q.3) let c4 = character(encoding: q.4) let c5 = character(encoding: q.5) let c6 = character(encoding: q.6) let c7 = character(encoding: q.7) return (c0, c1, c2, c3, c4, c5, c6, c7) } private func encodeBlock(_ b0: Byte, _ b1: Byte, _ b2: Byte, _ b3: Byte) -> EncodedBlock { let q = quintetsFromBytes(b0, b1, b2, b3) let c0 = character(encoding: q.0) let c1 = character(encoding: q.1) let c2 = character(encoding: q.2) let c3 = character(encoding: q.3) let c4 = character(encoding: q.4) let c5 = character(encoding: q.5) let c6 = character(encoding: q.6) let c7 = paddingCharacter return (c0, c1, c2, c3, c4, c5, c6, c7) } private func encodeBlock(_ b0: Byte, _ b1: Byte, _ b2: Byte) -> EncodedBlock { let q = quintetsFromBytes(b0, b1, b2) let c0 = character(encoding: q.0) let c1 = character(encoding: q.1) let c2 = character(encoding: q.2) let c3 = character(encoding: q.3) let c4 = character(encoding: q.4) let c5 = paddingCharacter let c6 = paddingCharacter let c7 = paddingCharacter return (c0, c1, c2, c3, c4, c5, c6, c7) } private func encodeBlock(_ b0: Byte, _ b1: Byte) -> EncodedBlock { let q = quintetsFromBytes(b0, b1) let c0 = character(encoding: q.0) let c1 = character(encoding: q.1) let c2 = character(encoding: q.2) let c3 = character(encoding: q.3) let c4 = paddingCharacter let c5 = paddingCharacter let c6 = paddingCharacter let c7 = paddingCharacter return (c0, c1, c2, c3, c4, c5, c6, c7) } private func encodeBlock(_ b0: Byte) -> EncodedBlock { let q = quintetsFromBytes(b0) let c0 = character(encoding: q.0) let c1 = character(encoding: q.1) let c2 = paddingCharacter let c3 = paddingCharacter let c4 = paddingCharacter let c5 = paddingCharacter let c6 = paddingCharacter let c7 = paddingCharacter return (c0, c1, c2, c3, c4, c5, c6, c7) } public enum Base32 { /// The size of a block before encoding, measured in bytes. private static let unencodedBlockSize = 5 /// The size of a block after encoding, measured in bytes. private static let encodedBlockSize = 8 public static func encode(_ data: Data) -> String { let unencodedByteCount = data.count let encodedByteCount = byteCount(encoding: unencodedByteCount) let encodedBytes = UnsafeMutablePointer<EncodedChar>.allocate(capacity: encodedByteCount) data.withUnsafeBytes { guard let unencodedBytes = $0.baseAddress?.assumingMemoryBound(to: Byte.self) else { return } var encodedWriteOffset = 0 for unencodedReadOffset in stride(from: 0, to: unencodedByteCount, by: unencodedBlockSize) { let nextBlockBytes = unencodedBytes + unencodedReadOffset let nextBlockSize = min(unencodedBlockSize, unencodedByteCount - unencodedReadOffset) let nextChars = encodeBlock(bytes: nextBlockBytes, size: nextBlockSize) encodedBytes[encodedWriteOffset + 0] = nextChars.0 encodedBytes[encodedWriteOffset + 1] = nextChars.1 encodedBytes[encodedWriteOffset + 2] = nextChars.2 encodedBytes[encodedWriteOffset + 3] = nextChars.3 encodedBytes[encodedWriteOffset + 4] = nextChars.4 encodedBytes[encodedWriteOffset + 5] = nextChars.5 encodedBytes[encodedWriteOffset + 6] = nextChars.6 encodedBytes[encodedWriteOffset + 7] = nextChars.7 encodedWriteOffset += encodedBlockSize } } // The Data instance takes ownership of the allocated bytes and will handle deallocation. let encodedData = Data(bytesNoCopy: encodedBytes, count: encodedByteCount, deallocator: .free) return String(data: encodedData, encoding: .ascii)! } private static func byteCount(encoding unencodedByteCount: Int) -> Int { let fullBlockCount = unencodedByteCount / unencodedBlockSize let remainingRawBytes = unencodedByteCount % unencodedBlockSize let blockCount = remainingRawBytes > 0 ? fullBlockCount + 1 : fullBlockCount return blockCount * encodedBlockSize } }
52650c53b2a8e7583064563d1e1775f3
38.639405
119
0.651411
false
false
false
false
xxxAIRINxxx/VHUD
refs/heads/master
Sources/ProgressView.swift
mit
1
// // ProgressView.swift // VHUD // // Created by xxxAIRINxxx on 2016/07/19. // Copyright © 2016 xxxAIRINxxx. All rights reserved. // // @see http://stackoverflow.com/questions/16192254/why-does-giving-addarcwithcenter-a-startangle-of-0-degrees-make-it-start-at-90-d import UIKit import QuartzCore final class ProgressView: UIView { private static let startAngle: Double = 90 private static let endAngle: Double = 270 var mode: Mode? var defaultColor: UIColor = .black var elapsedColor: UIColor = .lightGray var lineWidth: CGFloat = 30.0 { didSet { setNeedsDisplay() } } var loopLineWidth: Double = 25.0 { didSet { setNeedsDisplay() } } var radius: CGFloat { return (self.bounds.width * 0.5) - (self.lineWidth * 0.5) - self.outsideMargin } var outsideMargin: CGFloat = 10.0 { didSet { setNeedsDisplay() } } var percentComplete: Double = 0 { didSet { setNeedsDisplay() } } override public init(frame: CGRect) { super.init(frame: frame) self.setup() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setup() } private func setup() { self.backgroundColor = .clear } func finish() { self.mode = nil } private func convertAngle(percentComplete: Double) -> Double { return percentComplete * 360 - ProgressView.startAngle } private func drawPath(startAngle: Double, endAngle: Double, strokeColor: UIColor) { let s = CGFloat(startAngle * Double.pi / 180.0) let e = CGFloat(endAngle * Double.pi / 180.0) let center = CGPoint(x: self.bounds.width * 0.5, y: self.bounds.height * 0.5) let art = UIBezierPath(arcCenter: center, radius: self.radius, startAngle: s, endAngle: e, clockwise: true) art.lineWidth = self.lineWidth art.setLineDash([ CGFloat(Double.pi * Double(self.radius * 0.01 * 0.225)), CGFloat(Double.pi * Double(self.radius * 0.01 * 0.7545)) ], count: 2, phase: 0) strokeColor.setStroke() art.stroke() } private func draw(percentComplete: Double) { guard let m = self.mode else { return } if case Mode.loop = m { let current = self.convertAngle(percentComplete: percentComplete) let start = current - self.loopLineWidth self.drawPath(startAngle: -ProgressView.startAngle, endAngle: ProgressView.endAngle, strokeColor: self.defaultColor) self.drawPath(startAngle: start, endAngle: current, strokeColor: self.elapsedColor) } else { let start = -ProgressView.startAngle let current = self.convertAngle(percentComplete: percentComplete) if percentComplete >= 1.0 { self.drawPath(startAngle: start, endAngle: ProgressView.endAngle, strokeColor: self.elapsedColor) } else { self.drawPath(startAngle: -ProgressView.startAngle, endAngle: ProgressView.endAngle, strokeColor: self.defaultColor) self.drawPath(startAngle: start, endAngle: current, strokeColor: self.elapsedColor) } } } override public func draw(_ rect: CGRect) { super.draw(rect) self.draw(percentComplete: percentComplete) } }
08e068b85e13939e59bc5a5f5c9e20df
32.572816
142
0.615385
false
false
false
false
mojio/mojio-ios-sdk
refs/heads/master
MojioSDK/Models/TripPolyline.swift
mit
1
// // TripPolyline.swift // MojioSDK // // Created by Suresh Venkatraman on 11/15/16. // Copyright © 2016 Mojio. All rights reserved. // import UIKit import CoreLocation import ObjectMapper public class TripPolyline: Mappable { public dynamic var Id : String? = nil public dynamic var TripPolyline : String? = nil public dynamic var CreatedOn : String? = nil public dynamic var LastModified : String? = nil public dynamic var Deleted : Bool = false public required convenience init?(_ map: Map) { self.init() } public func mapping(map: Map) { Id <- map["Id"] TripPolyline <- map["Polyline"] CreatedOn <- map["CreatedOn"] LastModified <- map["LastModified"] Deleted <- map["Deleted"] } }
cb903888e5a09864b1d4e4174fa7a374
23.151515
51
0.627353
false
false
false
false
narner/AudioKit
refs/heads/master
AudioKit/Common/Nodes/Generators/Physical Models/Metal Bar/AKMetalBar.swift
mit
1
// // AKMetalBar.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright © 2017 Aurelius Prochazka. All rights reserved. // /// Metal Bar Physical Model /// open class AKMetalBar: AKNode, AKComponent { public typealias AKAudioUnitType = AKMetalBarAudioUnit /// Four letter unique description of the node public static let ComponentDescription = AudioComponentDescription(generator: "mbar") // MARK: - Properties private var internalAU: AKAudioUnitType? private var token: AUParameterObserverToken? fileprivate var leftBoundaryConditionParameter: AUParameter? fileprivate var rightBoundaryConditionParameter: AUParameter? fileprivate var decayDurationParameter: AUParameter? fileprivate var scanSpeedParameter: AUParameter? fileprivate var positionParameter: AUParameter? fileprivate var strikeVelocityParameter: AUParameter? fileprivate var strikeWidthParameter: AUParameter? /// Ramp Time represents the speed at which parameters are allowed to change @objc open dynamic var rampTime: Double = AKSettings.rampTime { willSet { internalAU?.rampTime = newValue } } /// Boundary condition at left end of bar. 1 = clamped, 2 = pivoting, 3 = free @objc open dynamic var leftBoundaryCondition: Double = 1 { willSet { if leftBoundaryCondition != newValue { if let existingToken = token { leftBoundaryConditionParameter?.setValue(Float(newValue), originator: existingToken) } } } } /// Boundary condition at right end of bar. 1 = clamped, 2 = pivoting, 3 = free @objc open dynamic var rightBoundaryCondition: Double = 1 { willSet { if rightBoundaryCondition != newValue { if let existingToken = token { rightBoundaryConditionParameter?.setValue(Float(newValue), originator: existingToken) } } } } /// 30db decay time (in seconds). @objc open dynamic var decayDuration: Double = 3 { willSet { if decayDuration != newValue { if let existingToken = token { decayDurationParameter?.setValue(Float(newValue), originator: existingToken) } } } } /// Speed of scanning the output location. @objc open dynamic var scanSpeed: Double = 0.25 { willSet { if scanSpeed != newValue { if let existingToken = token { scanSpeedParameter?.setValue(Float(newValue), originator: existingToken) } } } } /// Position along bar that strike occurs. @objc open dynamic var position: Double = 0.2 { willSet { if position != newValue { if let existingToken = token { positionParameter?.setValue(Float(newValue), originator: existingToken) } } } } /// Normalized strike velocity @objc open dynamic var strikeVelocity: Double = 500 { willSet { if strikeVelocity != newValue { if let existingToken = token { strikeVelocityParameter?.setValue(Float(newValue), originator: existingToken) } } } } /// Spatial width of strike. @objc open dynamic var strikeWidth: Double = 0.05 { willSet { if strikeWidth != newValue { if let existingToken = token { strikeWidthParameter?.setValue(Float(newValue), originator: existingToken) } } } } /// Tells whether the node is processing (ie. started, playing, or active) @objc open dynamic var isStarted: Bool { return internalAU?.isPlaying() ?? false } // MARK: - Initialization /// Initialize this Bar node /// /// - Parameters: /// - leftBoundaryCondition: Boundary condition at left end of bar. 1 = clamped, 2 = pivoting, 3 = free /// - rightBoundaryCondition: Boundary condition at right end of bar. 1 = clamped, 2 = pivoting, 3 = free /// - decayDuration: 30db decay time (in seconds). /// - scanSpeed: Speed of scanning the output location. /// - position: Position along bar that strike occurs. /// - strikeVelocity: Normalized strike velocity /// - strikeWidth: Spatial width of strike. /// - stiffness: Dimensionless stiffness parameter /// - highFrequencyDamping: High-frequency loss parameter. Keep this small /// @objc public init( leftBoundaryCondition: Double = 1, rightBoundaryCondition: Double = 1, decayDuration: Double = 3, scanSpeed: Double = 0.25, position: Double = 0.2, strikeVelocity: Double = 500, strikeWidth: Double = 0.05, stiffness: Double = 3, highFrequencyDamping: Double = 0.001) { self.leftBoundaryCondition = leftBoundaryCondition self.rightBoundaryCondition = rightBoundaryCondition self.decayDuration = decayDuration self.scanSpeed = scanSpeed self.position = position self.strikeVelocity = strikeVelocity self.strikeWidth = strikeWidth _Self.register() super.init() AVAudioUnit._instantiate(with: _Self.ComponentDescription) { [weak self] avAudioUnit in self?.avAudioNode = avAudioUnit self?.internalAU = avAudioUnit.auAudioUnit as? AKAudioUnitType } guard let tree = internalAU?.parameterTree else { AKLog("Parameter Tree Failed") return } leftBoundaryConditionParameter = tree["leftBoundaryCondition"] rightBoundaryConditionParameter = tree["rightBoundaryCondition"] decayDurationParameter = tree["decayDuration"] scanSpeedParameter = tree["scanSpeed"] positionParameter = tree["position"] strikeVelocityParameter = tree["strikeVelocity"] strikeWidthParameter = tree["strikeWidth"] token = tree.token(byAddingParameterObserver: { [weak self] _, _ in guard let _ = self else { AKLog("Unable to create strong reference to self") return } // Replace _ with strongSelf if needed DispatchQueue.main.async { // This node does not change its own values so we won't add any // value observing, but if you need to, this is where that goes. } }) internalAU?.leftBoundaryCondition = Float(leftBoundaryCondition) internalAU?.rightBoundaryCondition = Float(rightBoundaryCondition) internalAU?.decayDuration = Float(decayDuration) internalAU?.scanSpeed = Float(scanSpeed) internalAU?.position = Float(position) internalAU?.strikeVelocity = Float(strikeVelocity) internalAU?.strikeWidth = Float(strikeWidth) } // MARK: - Control /// Trigger the sound with an optional set of parameters /// open func trigger() { internalAU?.start() internalAU?.trigger() } /// Function to start, play, or activate the node, all do the same thing @objc open func start() { internalAU?.start() } /// Function to stop or bypass the node, both are equivalent @objc open func stop() { internalAU?.stop() } }
63268e4cbaff38ac2447d8538a40fdb7
34.54717
111
0.617038
false
false
false
false
RobotsAndPencils/SwiftCharts
refs/heads/master
Pods/SwiftCharts/SwiftCharts/Layers/ChartStackedBarsLayer.swift
apache-2.0
6
// // ChartStackedBarsLayer.swift // Examples // // Created by ischuetz on 15/05/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit public typealias ChartStackedBarItemModel = (quantity: Double, bgColor: UIColor) public class ChartStackedBarModel: ChartBarModel { let items: [ChartStackedBarItemModel] public init(constant: ChartAxisValue, start: ChartAxisValue, items: [ChartStackedBarItemModel]) { self.items = items let axisValue2Scalar = items.reduce(start.scalar) {sum, item in sum + item.quantity } let axisValue2 = start.copy(axisValue2Scalar) super.init(constant: constant, axisValue1: start, axisValue2: axisValue2) } lazy var totalQuantity: Double = { return self.items.reduce(0) {total, item in total + item.quantity } }() } class ChartStackedBarsViewGenerator<T: ChartStackedBarModel>: ChartBarsViewGenerator<T> { private typealias FrameBuilder = (barModel: ChartStackedBarModel, item: ChartStackedBarItemModel, currentTotalQuantity: Double) -> (frame: ChartPointViewBarStackedFrame, length: CGFloat) override init(horizontal: Bool, xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, chartInnerFrame: CGRect, barWidth barWidthMaybe: CGFloat?, barSpacing barSpacingMaybe: CGFloat?) { super.init(horizontal: horizontal, xAxis: xAxis, yAxis: yAxis, chartInnerFrame: chartInnerFrame, barWidth: barWidthMaybe, barSpacing: barSpacingMaybe) } override func generateView(barModel: T, constantScreenLoc constantScreenLocMaybe: CGFloat? = nil, bgColor: UIColor? = nil, animDuration: Float) -> ChartPointViewBar { let constantScreenLoc = constantScreenLocMaybe ?? self.constantScreenLoc(barModel) let frameBuilder: FrameBuilder = { switch self.direction { case .LeftToRight: return {barModel, item, currentTotalQuantity in let p0 = self.xAxis.screenLocForScalar(currentTotalQuantity) let p1 = self.xAxis.screenLocForScalar(currentTotalQuantity + item.quantity) let length = p1 - p0 let barLeftScreenLoc = self.xAxis.screenLocForScalar(length > 0 ? barModel.axisValue1.scalar : barModel.axisValue2.scalar) return (frame: ChartPointViewBarStackedFrame(rect: CGRectMake( p0 - barLeftScreenLoc, 0, length, self.barWidth), color: item.bgColor), length: length) } case .BottomToTop: return {barModel, item, currentTotalQuantity in let p0 = self.yAxis.screenLocForScalar(currentTotalQuantity) let p1 = self.yAxis.screenLocForScalar(currentTotalQuantity + item.quantity) let length = p1 - p0 let barTopScreenLoc = self.yAxis.screenLocForScalar(length > 0 ? barModel.axisValue1.scalar : barModel.axisValue2.scalar) return (frame: ChartPointViewBarStackedFrame(rect: CGRectMake( 0, p0 - barTopScreenLoc, self.barWidth, length), color: item.bgColor), length: length) } } }() let stackFrames = barModel.items.reduce((currentTotalQuantity: barModel.axisValue1.scalar, currentTotalLength: CGFloat(0), frames: Array<ChartPointViewBarStackedFrame>())) {tuple, item in let frameWithLength = frameBuilder(barModel: barModel, item: item, currentTotalQuantity: tuple.currentTotalQuantity) return (currentTotalQuantity: tuple.currentTotalQuantity + item.quantity, currentTotalLength: tuple.currentTotalLength + frameWithLength.length, frames: tuple.frames + [frameWithLength.frame]) } let viewPoints = self.viewPoints(barModel, constantScreenLoc: constantScreenLoc) return ChartPointViewBarStacked(p1: viewPoints.p1, p2: viewPoints.p2, width: self.barWidth, stackFrames: stackFrames.frames, animDuration: animDuration) } } public class ChartStackedBarsLayer: ChartCoordsSpaceLayer { private let barModels: [ChartStackedBarModel] private let horizontal: Bool private let barWidth: CGFloat? private let barSpacing: CGFloat? private let animDuration: Float public convenience init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, barModels: [ChartStackedBarModel], horizontal: Bool = false, barWidth: CGFloat, animDuration: Float) { self.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, barModels: barModels, horizontal: horizontal, barWidth: barWidth, barSpacing: nil, animDuration: animDuration) } public convenience init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, barModels: [ChartStackedBarModel], horizontal: Bool = false, barSpacing: CGFloat, animDuration: Float) { self.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, barModels: barModels, horizontal: horizontal, barWidth: nil, barSpacing: barSpacing, animDuration: animDuration) } private init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, barModels: [ChartStackedBarModel], horizontal: Bool = false, barWidth: CGFloat? = nil, barSpacing: CGFloat?, animDuration: Float) { self.barModels = barModels self.horizontal = horizontal self.barWidth = barWidth self.barSpacing = barSpacing self.animDuration = animDuration super.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame) } public override func chartInitialized(chart chart: Chart) { let barsGenerator = ChartStackedBarsViewGenerator(horizontal: self.horizontal, xAxis: self.xAxis, yAxis: self.yAxis, chartInnerFrame: self.innerFrame, barWidth: self.barWidth, barSpacing: self.barSpacing) for barModel in self.barModels { chart.addSubview(barsGenerator.generateView(barModel, animDuration: self.animDuration)) } } }
504a3cad71a37899c4cb009a3b327515
48.615385
214
0.651163
false
false
false
false
alexburtnik/ABSwiftExtensions
refs/heads/master
ABSwiftExtensions/Classes/UIKit/UIKit+Extensions.swift
mit
1
// // UIKit+Extensions.swift // s9fc // // Created by Alex Burtnik on 6/9/17. // Copyright © 2017 smartum.pro. All rights reserved. // import Foundation import UIKit //import Kingfisher //import MBProgressHUD //import OrderedSet //extension UIViewController { // func setupLeftBackButton() { // let index = navigationController?.viewControllers.index(of: self) // if index != 0 { // navigationItem.leftBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "icon_back"), target: self, action: #selector(backAction)) // } // } // // @objc private func backAction() { // _ = navigationController?.popViewController(animated: true) // } // // func setupLeftCloseButton() { // navigationItem.leftBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "icon_cross"), target: self, action: #selector(closePressed)) // } // // @objc private func closePressed() { // dismiss(animated: true, completion: nil) // } // // func showHUD(animated: Bool = true) { // let hud = MBProgressHUD.showAdded(to: view, animated: true) // hud.tintColor = Colors.green // } // // func hideHUD(animated: Bool = true) { // MBProgressHUD.hide(for: view, animated: true) // } // // // func setupPullToRefresh(tableView: UITableView, action: @escaping ((()->Void)?)->Void) { // let refreshHeader = RefreshHeaderAnimator.init(frame: CGRect.zero) // tableView.es_addPullToRefresh(animator: refreshHeader) { // action() { // tableView.es_stopPullToRefresh() // } // } // } // //} //extension UIImageView { // // func setImage(urlString: String?, placeholder: UIImage? = nil, animated: Bool = true) { // guard let urlString = urlString, let url = URL(string: urlString) else { // self.image = placeholder; return // } // var options: KingfisherOptionsInfo = [] // if animated { // options.append(.transition(.fade(0.2))) // } // self.kf.setImage(with: url, placeholder: placeholder, options: options) // } //} //extension UIScrollView { // func scrollToBottom(animated: Bool) { // let bottomOffset = CGPoint(x: 0, y: contentSize.height - bounds.size.height) // setContentOffset(bottomOffset, animated: animated) // } // // var bottomInset: CGFloat { // get { return contentInset.bottom } // set { // var contentInset = self.contentInset // contentInset.bottom = newValue // self.contentInset = contentInset // } // } //}
5d8168ce5b1c0da0b06f87192e71d851
27.56383
158
0.600745
false
false
false
false
GTMYang/GTMRefresh
refs/heads/master
GTMRefresh/GTMRefreshExtension.swift
mit
1
// // GTMRefreshExtension.swift // GTMRefresh // // Created by luoyang on 2016/12/7. // Copyright © 2016年 luoyang. All rights reserved. // import UIKit import ObjectiveC extension UIScrollView { internal var gtmHeader: GTMRefreshHeader? { get { return objc_getAssociatedObject(self, &GTMRefreshConstant.associatedObjectGtmHeader) as? GTMRefreshHeader } set { objc_setAssociatedObject(self, &GTMRefreshConstant.associatedObjectGtmHeader, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } internal var gtmFooter: GTMLoadMoreFooter? { get { return objc_getAssociatedObject(self, &GTMRefreshConstant.associatedObjectGtmFooter) as? GTMLoadMoreFooter } set { objc_setAssociatedObject(self, &GTMRefreshConstant.associatedObjectGtmFooter, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } /// 添加下拉刷新 /// /// - Parameters: /// - refreshHeader: 下拉刷新动效View必须继承GTMRefreshHeader并且要实现SubGTMRefreshHeaderProtocol,不传值的时候默认使用 DefaultGTMRefreshHeader /// - refreshBlock: 刷新数据Block @discardableResult final public func gtm_addRefreshHeaderView(refreshHeader: GTMRefreshHeader? = DefaultGTMRefreshHeader(), refreshBlock:@escaping () -> Void) -> UIScrollView { guard let newHeader = refreshHeader else { return self } guard newHeader is SubGTMRefreshHeaderProtocol else { fatalError("refreshHeader must implement SubGTMRefreshHeaderProtocol") } newHeader.frame = CGRect(x: 0, y: 0, width: self.mj_w, height: newHeader.headerProtocolImp!.contentHeight()) if let oldHeader = gtmHeader { oldHeader.removeFromSuperview() } newHeader.refreshBlock = refreshBlock self.insertSubview(newHeader, at: 0) self.gtmHeader = newHeader return self } /// 添加上拉加载 /// /// - Parameters: /// - loadMoreFooter: 上拉加载动效View必须继承GTMLoadMoreFooter,不传值的时候默认使用 DefaultGTMLoadMoreFooter /// - refreshBlock: 加载更多数据Block @discardableResult final public func gtm_addLoadMoreFooterView(loadMoreFooter: GTMLoadMoreFooter? = DefaultGTMLoadMoreFooter(), loadMoreBlock:@escaping () -> Void) -> UIScrollView { guard let newFooter = loadMoreFooter else { return self } guard loadMoreFooter is SubGTMLoadMoreFooterProtocol else { fatalError("loadMoreFooter must implement SubGTMLoadMoreFooterProtocol") } newFooter.frame = CGRect(x: 0, y: 0, width: self.mj_w, height: newFooter.subProtocol!.contentHeith()) if let oldFooter = gtmFooter { oldFooter.removeFromSuperview() } newFooter.loadMoreBlock = loadMoreBlock self.insertSubview(newFooter, at: 0) self.gtmFooter = newFooter return self } final public func triggerRefreshing(){ self.gtmHeader?.autoRefreshing() } final public func endRefreshing(isSuccess: Bool = true) { self.gtmHeader?.endRefresing(isSuccess: isSuccess) // 重置footer状态(防止footer还处在数据加载完成状态) self.gtmFooter?.state = .idle } final public func endLoadMore(isNoMoreData: Bool = false) { self.gtmFooter?.endLoadMore(isNoMoreData: isNoMoreData) } } extension UIScrollView { var mj_inset: UIEdgeInsets { get { if #available(iOS 11, *) { return self.adjustedContentInset } else { return self.contentInset } } } var mj_insetT: CGFloat { get { return mj_inset.top } set { var inset = self.contentInset inset.top = newValue if #available(iOS 11, *) { inset.top -= self.safeAreaInsets.top } self.contentInset = inset } } var mj_insetB: CGFloat { get { return mj_inset.bottom } set { var inset = self.contentInset inset.bottom = newValue if #available(iOS 11, *) { inset.bottom -= self.safeAreaInsets.bottom } self.contentInset = inset } } var mj_insetL: CGFloat { get { return mj_inset.left } set { var inset = self.contentInset inset.left = newValue if #available(iOS 11, *) { inset.left -= self.safeAreaInsets.left } self.contentInset = inset } } var mj_insetR: CGFloat { get { return mj_inset.right } set { var inset = self.contentInset inset.right = newValue if #available(iOS 11, *) { inset.right -= self.safeAreaInsets.right } self.contentInset = inset } } var mj_offsetX: CGFloat { get { return contentOffset.x } set { var offset = self.contentOffset offset.x = newValue self.contentOffset = offset } } var mj_offsetY: CGFloat { get { return contentOffset.y } set { var offset = self.contentOffset offset.y = newValue self.contentOffset = offset } } var mj_contentW: CGFloat { get { return contentSize.width } set { var size = self.contentSize size.width = newValue self.contentSize = size } } var mj_contentH: CGFloat { get { return contentSize.height } set { var size = self.contentSize size.height = newValue self.contentSize = size } } } extension UIView { var mj_x: CGFloat { get { return frame.origin.x } set { var frame = self.frame frame.origin.x = newValue self.frame = frame } } var mj_y: CGFloat { get { return frame.origin.y } set { var frame = self.frame frame.origin.y = newValue self.frame = frame } } var mj_w: CGFloat { get { return frame.size.width } set { var frame = self.frame frame.size.width = newValue self.frame = frame } } var mj_h: CGFloat { get { return frame.size.height } set { var frame = self.frame frame.size.height = newValue self.frame = frame } } var mj_size: CGSize { get { return frame.size } set { var frame = self.frame frame.size = newValue self.frame = frame } } var mj_origin: CGPoint { get { return frame.origin } set { var frame = self.frame frame.origin = newValue self.frame = frame } } var mj_center: CGPoint { get { return CGPoint(x: (frame.size.width-frame.origin.x)*0.5, y: (frame.size.height-frame.origin.y)*0.5) } set { var frame = self.frame frame.origin = CGPoint(x: newValue.x - frame.size.width*0.5, y: newValue.y - frame.size.height*0.5) self.frame = frame } } }
2ae0131e2c69e59b68f4c3a54c52ac9c
28.121094
166
0.562844
false
false
false
false
sschiau/swift-package-manager
refs/heads/master
Sources/Utility/ArgumentParser.swift
apache-2.0
1
/* 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 http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import Basic import Foundation import func POSIX.exit /// Errors which may be encountered when running argument parser. public enum ArgumentParserError: Swift.Error { /// An unknown option is encountered. case unknownOption(String) /// The value of an argument is invalid. case invalidValue(argument: String, error: ArgumentConversionError) /// Expected a value from the option. case expectedValue(option: String) /// An unexpected positional argument encountered. case unexpectedArgument(String) /// Expected these positional arguments but not found. case expectedArguments(ArgumentParser, [String]) } extension ArgumentParserError: CustomStringConvertible { public var description: String { switch self { case .unknownOption(let option): return "unknown option \(option); use --help to list available options" case .invalidValue(let argument, let error): return "\(error) for argument \(argument); use --help to print usage" case .expectedValue(let option): return "option \(option) requires a value; provide a value using '\(option) <value>' or '\(option)=<value>'" case .unexpectedArgument(let argument): return "unexpected argument \(argument); use --help to list available arguments" case .expectedArguments(_, let arguments): return "expected arguments: \(arguments.joined(separator: ", "))" } } } /// Conversion errors that can be returned from `ArgumentKind`'s failable /// initializer. public enum ArgumentConversionError: Swift.Error { /// The value is unknown. case unknown(value: String) /// The value could not be converted to the target type. case typeMismatch(value: String, expectedType: Any.Type) /// Custom reason for conversion failure. case custom(String) } extension ArgumentConversionError: CustomStringConvertible { public var description: String { switch self { case .unknown(let value): return "unknown value '\(value)'" case .typeMismatch(let value, let expectedType): return "'\(value)' is not convertible to \(expectedType)" case .custom(let reason): return reason } } } extension ArgumentConversionError: Equatable { public static func ==(lhs: ArgumentConversionError, rhs: ArgumentConversionError) -> Bool { switch (lhs, rhs) { case (.unknown(let lhsValue), .unknown(let rhsValue)): return lhsValue == rhsValue case (.unknown, _): return false case (.typeMismatch(let lhsValue, let lhsType), .typeMismatch(let rhsValue, let rhsType)): return lhsValue == rhsValue && lhsType == rhsType case (.typeMismatch, _): return false case (.custom(let lhsReason), .custom(let rhsReason)): return lhsReason == rhsReason case (.custom, _): return false } } } /// Different shells for which we can generate shell scripts. public enum Shell: String, StringEnumArgument { case bash case zsh public static var completion: ShellCompletion = .values([ (bash.rawValue, "generate completion script for Bourne-again shell"), (zsh.rawValue, "generate completion script for Z shell"), ]) } /// Various shell completions modes supplied by ArgumentKind. /// /// - none: Offers no completions at all; e.g. for string identifier /// - unspecified: No specific completions, will offer tool's completions /// - filename: Offers filename completions /// - function: Custom function for generating completions. Must be /// provided in the script's scope. /// - values: Offers completions from predefined list. A description /// can be provided which is shown in some shells, like zsh. public enum ShellCompletion { case none case unspecified case filename case function(String) case values([(value: String, description: String)]) } /// A protocol representing the possible types of arguments. /// /// Conforming to this protocol will qualify the type to act as /// positional and option arguments in the argument parser. public protocol ArgumentKind { /// Throwable convertion initializer. init(argument: String) throws /// Type of shell completion to provide for this argument. static var completion: ShellCompletion { get } } // MARK: - ArgumentKind conformance for common types extension String: ArgumentKind { public init(argument: String) throws { self = argument } public static let completion: ShellCompletion = .none } extension Int: ArgumentKind { public init(argument: String) throws { guard let int = Int(argument) else { throw ArgumentConversionError.typeMismatch(value: argument, expectedType: Int.self) } self = int } public static let completion: ShellCompletion = .none } extension Bool: ArgumentKind { public init(argument: String) throws { switch argument { case "true": self = true case "false": self = false default: throw ArgumentConversionError.unknown(value: argument) } } public static var completion: ShellCompletion = .unspecified } /// A protocol which implements ArgumentKind for string initializable enums. /// /// Conforming to this protocol will automatically make an enum with is /// String initializable conform to ArgumentKind. public protocol StringEnumArgument: ArgumentKind { init?(rawValue: String) } extension StringEnumArgument { public init(argument: String) throws { guard let value = Self.init(rawValue: argument) else { throw ArgumentConversionError.unknown(value: argument) } self = value } } /// An argument representing a path (file / directory). /// /// The path is resolved in the current working directory. public struct PathArgument: ArgumentKind { public let path: AbsolutePath public init(argument: String) throws { // FIXME: This should check for invalid paths. if let cwd = localFileSystem.currentWorkingDirectory { path = AbsolutePath(argument, relativeTo: cwd) } else { path = try AbsolutePath(validating: argument) } } public static var completion: ShellCompletion = .filename } /// An enum representing the strategy to parse argument values. public enum ArrayParsingStrategy { /// Will parse only the next argument and append all values together: `-Xcc -Lfoo -Xcc -Lbar`. case oneByOne /// Will parse all values up to the next option argument: `--files file1 file2 --verbosity 1`. case upToNextOption /// Will parse all remaining arguments, usually for executable commands: `swift run exe --option 1`. case remaining /// Function that parses the current arguments iterator based on the strategy /// and returns the parsed values. func parse(_ kind: ArgumentKind.Type, with parser: inout ArgumentParserProtocol) throws -> [ArgumentKind] { var values: [ArgumentKind] = [] switch self { case .oneByOne: guard let nextArgument = parser.next() else { throw ArgumentParserError.expectedValue(option: parser.currentArgument) } try values.append(kind.init(argument: nextArgument)) case .upToNextOption: /// Iterate over arguments until the end or an optional argument while let nextArgument = parser.peek(), isPositional(argument: nextArgument) { /// We need to call next to consume the argument. The peek above did not. _ = parser.next() try values.append(kind.init(argument: nextArgument)) } case .remaining: while let nextArgument = parser.next() { try values.append(kind.init(argument: nextArgument)) } } return values } } /// A protocol representing positional or options argument. protocol ArgumentProtocol: Hashable { // FIXME: This should be constrained to ArgumentKind but Array can't conform // to it: `extension of type 'Array' with constraints cannot have an // inheritance clause`. // /// The argument kind of this argument for eg String, Bool etc. associatedtype ArgumentKindTy /// Name of the argument which will be parsed by the parser. var name: String { get } /// Short name of the argument, this is usually used in options arguments /// for a short names for e.g: `--help` -> `-h`. var shortName: String? { get } /// The parsing strategy to adopt when parsing values. var strategy: ArrayParsingStrategy { get } /// Defines is the argument is optional var isOptional: Bool { get } /// The usage text associated with this argument. Used to generate complete help string. var usage: String? { get } /// The shell completions to offer as values for this argument. var completion: ShellCompletion { get } // FIXME: Because `ArgumentKindTy`` can't conform to `ArgumentKind`, this // function has to be provided a kind (which will be different from // ArgumentKindTy for arrays). Once the generics feature exists we can // improve this API. // /// Parses and returns the argument values from the parser. func parse(_ kind: ArgumentKind.Type, with parser: inout ArgumentParserProtocol) throws -> [ArgumentKind] } extension ArgumentProtocol { // MARK: - Conformance for Hashable public var hashValue: Int { return name.hashValue } public static func == (_ lhs: Self, _ rhs: Self) -> Bool { return lhs.name == rhs.name && lhs.usage == rhs.usage } } /// Returns true if the given argument does not starts with '-' i.e. it is /// a positional argument, otherwise it is an options argument. fileprivate func isPositional(argument: String) -> Bool { return !argument.hasPrefix("-") } /// A class representing option arguments. These are optional arguments which may /// or may not be provided in the command line. They are always prefixed by their /// name. For e.g. --verbosity true. public final class OptionArgument<Kind>: ArgumentProtocol { typealias ArgumentKindTy = Kind let name: String let shortName: String? // Option arguments are always optional. var isOptional: Bool { return true } let strategy: ArrayParsingStrategy let usage: String? let completion: ShellCompletion init(name: String, shortName: String?, strategy: ArrayParsingStrategy, usage: String?, completion: ShellCompletion) { precondition(!isPositional(argument: name)) self.name = name self.shortName = shortName self.strategy = strategy self.usage = usage self.completion = completion } func parse(_ kind: ArgumentKind.Type, with parser: inout ArgumentParserProtocol) throws -> [ArgumentKind] { do { return try _parse(kind, with: &parser) } catch let conversionError as ArgumentConversionError { throw ArgumentParserError.invalidValue(argument: name, error: conversionError) } } func _parse(_ kind: ArgumentKind.Type, with parser: inout ArgumentParserProtocol) throws -> [ArgumentKind] { // When we have an associated value, we ignore the strategy and only // parse that value. if let associatedArgument = parser.associatedArgumentValue { return try [kind.init(argument: associatedArgument)] } // As a special case, Bool options don't consume arguments. if kind == Bool.self && strategy == .oneByOne { return [true] } let values = try strategy.parse(kind, with: &parser) guard !values.isEmpty else { throw ArgumentParserError.expectedValue(option: name) } return values } } /// A class representing positional arguments. These arguments must be present /// and in the same order as they are added in the parser. public final class PositionalArgument<Kind>: ArgumentProtocol { typealias ArgumentKindTy = Kind let name: String // Postional arguments don't need short names. var shortName: String? { return nil } let strategy: ArrayParsingStrategy let isOptional: Bool let usage: String? let completion: ShellCompletion init(name: String, strategy: ArrayParsingStrategy, optional: Bool, usage: String?, completion: ShellCompletion) { precondition(isPositional(argument: name)) self.name = name self.strategy = strategy self.isOptional = optional self.usage = usage self.completion = completion } func parse(_ kind: ArgumentKind.Type, with parser: inout ArgumentParserProtocol) throws -> [ArgumentKind] { do { return try _parse(kind, with: &parser) } catch let conversionError as ArgumentConversionError { throw ArgumentParserError.invalidValue(argument: name, error: conversionError) } } func _parse(_ kind: ArgumentKind.Type, with parser: inout ArgumentParserProtocol) throws -> [ArgumentKind] { let value = try kind.init(argument: parser.currentArgument) var values = [value] switch strategy { case .oneByOne: // We shouldn't apply the strategy with `.oneByOne` because we // already have one, the parsed `parser.currentArgument`. break case .upToNextOption, .remaining: try values.append(contentsOf: strategy.parse(kind, with: &parser)) } return values } } /// A type-erased argument. /// /// Note: Only used for argument parsing purpose. final class AnyArgument: ArgumentProtocol, CustomStringConvertible { typealias ArgumentKindTy = Any let name: String let shortName: String? let strategy: ArrayParsingStrategy let isOptional: Bool let usage: String? let completion: ShellCompletion /// The argument kind this holds, used while initializing that argument. let kind: ArgumentKind.Type /// True if the argument kind is of array type. let isArray: Bool /// A type-erased wrapper around the argument's `parse` function. private let parseClosure: (ArgumentKind.Type, inout ArgumentParserProtocol) throws -> [ArgumentKind] init<T: ArgumentProtocol>(_ argument: T) { self.kind = T.ArgumentKindTy.self as! ArgumentKind.Type self.name = argument.name self.shortName = argument.shortName self.strategy = argument.strategy self.isOptional = argument.isOptional self.usage = argument.usage self.completion = argument.completion self.parseClosure = argument.parse(_:with:) isArray = false } /// Initializer for array arguments. init<T: ArgumentProtocol>(_ argument: T) where T.ArgumentKindTy: Sequence { self.kind = T.ArgumentKindTy.Element.self as! ArgumentKind.Type self.name = argument.name self.shortName = argument.shortName self.strategy = argument.strategy self.isOptional = argument.isOptional self.usage = argument.usage self.completion = argument.completion self.parseClosure = argument.parse(_:with:) isArray = true } var description: String { return "Argument(\(name))" } func parse(_ kind: ArgumentKind.Type, with parser: inout ArgumentParserProtocol) throws -> [ArgumentKind] { return try self.parseClosure(kind, &parser) } func parse(with parser: inout ArgumentParserProtocol) throws -> [ArgumentKind] { return try self.parseClosure(self.kind, &parser) } } // FIXME: We probably don't need this protocol anymore and should convert this to a class. // /// Argument parser protocol passed in initializers of ArgumentKind to manipulate /// parser as needed by the argument. public protocol ArgumentParserProtocol { /// The current argument being parsed. var currentArgument: String { get } /// The associated value in a `--foo=bar` style argument. var associatedArgumentValue: String? { get } /// Provides (consumes) and returns the next argument. Returns `nil` if there are not arguments left. mutating func next() -> String? /// Peek at the next argument without consuming it. func peek() -> String? } /// Argument parser struct responsible to parse the provided array of arguments /// and return the parsed result. public final class ArgumentParser { /// A class representing result of the parsed arguments. public class Result: CustomStringConvertible { /// Internal representation of arguments mapped to their values. private var results = [String: Any]() /// Result of the parent parent parser, if any. private var parentResult: Result? /// Reference to the parser this result belongs to. private let parser: ArgumentParser /// The subparser command chosen. fileprivate var subparser: String? /// Create a result with a parser and parent result. init(parser: ArgumentParser, parent: Result?) { self.parser = parser self.parentResult = parent } /// Adds a result. /// /// - Parameters: /// - values: The associated values of the argument. /// - argument: The argument for which this result is being added. /// - Note: /// While it may seem more fragile to use an array as input in the /// case of single-value arguments, this design choice allows major /// simplifications in the parsing code. fileprivate func add(_ values: [ArgumentKind], for argument: AnyArgument) throws { if argument.isArray { var array = results[argument.name] as? [ArgumentKind] ?? [] array.append(contentsOf: values) results[argument.name] = array } else { // We expect only one value for non-array arguments. guard let value = values.spm_only else { assertionFailure() return } results[argument.name] = value } } /// Get an option argument's value from the results. /// /// Since the options are optional, their result may or may not be present. public func get<T>(_ argument: OptionArgument<T>) -> T? { return (results[argument.name] as? T) ?? parentResult?.get(argument) } /// Array variant for option argument's get(_:). public func get<T>(_ argument: OptionArgument<[T]>) -> [T]? { return (results[argument.name] as? [T]) ?? parentResult?.get(argument) } /// Get a positional argument's value. public func get<T>(_ argument: PositionalArgument<T>) -> T? { return results[argument.name] as? T } /// Array variant for positional argument's get(_:). public func get<T>(_ argument: PositionalArgument<[T]>) -> [T]? { return results[argument.name] as? [T] } /// Get an argument's value using its name. /// - throws: An ArgumentParserError.invalidValue error if the parsed argument does not match the expected type. public func get<T>(_ name: String) throws -> T? { guard let value = results[name] else { // if we have a parent and this is an option argument, look in the parent result if let parentResult = parentResult, name.hasPrefix("-") { return try parentResult.get(name) } else { return nil } } guard let typedValue = value as? T else { throw ArgumentParserError.invalidValue(argument: name, error: .typeMismatch(value: String(describing: value), expectedType: T.self)) } return typedValue } /// Get the subparser which was chosen for the given parser. public func subparser(_ parser: ArgumentParser) -> String? { if parser === self.parser { return subparser } return parentResult?.subparser(parser) } public var description: String { var description = "ArgParseResult(\(results))" if let parent = parentResult { description += " -> " + parent.description } return description } } /// The mapping of subparsers to their subcommand. private(set) var subparsers: [String: ArgumentParser] = [:] /// List of arguments added to this parser. private(set) var optionArguments: [AnyArgument] = [] private(set) var positionalArguments: [AnyArgument] = [] // If provided, will be substituted instead of arg0 in usage text. let commandName: String? /// Usage string of this parser. let usage: String /// Overview text of this parser. let overview: String /// See more text of this parser. let seeAlso: String? /// If this parser is a subparser. private let isSubparser: Bool /// Boolean specifying if the parser can accept further positional /// arguments (false if it already has a positional argument with /// `isOptional` set to `true` or strategy set to `.remaining`). private var canAcceptPositionalArguments: Bool = true /// Create an argument parser. /// /// - Parameters: /// - commandName: If provided, this will be substitued in "usage" line of the generated usage text. /// Otherwise, first command line argument will be used. /// - usage: The "usage" line of the generated usage text. /// - overview: The "overview" line of the generated usage text. /// - seeAlso: The "see also" line of generated usage text. public init(commandName: String? = nil, usage: String, overview: String, seeAlso: String? = nil) { self.isSubparser = false self.commandName = commandName self.usage = usage self.overview = overview self.seeAlso = seeAlso } /// Create a subparser with its help text. private init(subparser overview: String) { self.isSubparser = true self.commandName = nil self.usage = "" self.overview = overview self.seeAlso = nil } /// Adds an option to the parser. public func add<T: ArgumentKind>( option: String, shortName: String? = nil, kind: T.Type, usage: String? = nil, completion: ShellCompletion? = nil ) -> OptionArgument<T> { assert(!optionArguments.contains(where: { $0.name == option }), "Can not define an option twice") let argument = OptionArgument<T>(name: option, shortName: shortName, strategy: .oneByOne, usage: usage, completion: completion ?? T.completion) optionArguments.append(AnyArgument(argument)) return argument } /// Adds an array argument type. public func add<T: ArgumentKind>( option: String, shortName: String? = nil, kind: [T].Type, strategy: ArrayParsingStrategy = .upToNextOption, usage: String? = nil, completion: ShellCompletion? = nil ) -> OptionArgument<[T]> { assert(!optionArguments.contains(where: { $0.name == option }), "Can not define an option twice") let argument = OptionArgument<[T]>(name: option, shortName: shortName, strategy: strategy, usage: usage, completion: completion ?? T.completion) optionArguments.append(AnyArgument(argument)) return argument } /// Adds an argument to the parser. /// /// Note: Only one positional argument is allowed if optional setting is enabled. public func add<T: ArgumentKind>( positional: String, kind: T.Type, optional: Bool = false, usage: String? = nil, completion: ShellCompletion? = nil ) -> PositionalArgument<T> { precondition(subparsers.isEmpty, "Positional arguments are not supported with subparsers") precondition(canAcceptPositionalArguments, "Can not accept more positional arguments") if optional { canAcceptPositionalArguments = false } let argument = PositionalArgument<T>(name: positional, strategy: .oneByOne, optional: optional, usage: usage, completion: completion ?? T.completion) positionalArguments.append(AnyArgument(argument)) return argument } /// Adds an argument to the parser. /// /// Note: Only one multiple-value positional argument is allowed. public func add<T: ArgumentKind>( positional: String, kind: [T].Type, optional: Bool = false, strategy: ArrayParsingStrategy = .upToNextOption, usage: String? = nil, completion: ShellCompletion? = nil ) -> PositionalArgument<[T]> { precondition(subparsers.isEmpty, "Positional arguments are not supported with subparsers") precondition(canAcceptPositionalArguments, "Can not accept more positional arguments") if optional || strategy == .remaining { canAcceptPositionalArguments = false } let argument = PositionalArgument<[T]>(name: positional, strategy: strategy, optional: optional, usage: usage, completion: completion ?? T.completion) positionalArguments.append(AnyArgument(argument)) return argument } /// Add a parser with a subcommand name and its corresponding overview. @discardableResult public func add(subparser command: String, overview: String) -> ArgumentParser { precondition(positionalArguments.isEmpty, "Subparsers are not supported with positional arguments") let parser = ArgumentParser(subparser: overview) subparsers[command] = parser return parser } // MARK: - Parsing /// A wrapper struct to pass to the ArgumentKind initializers. struct Parser: ArgumentParserProtocol { let currentArgument: String private(set) var associatedArgumentValue: String? /// The iterator used to iterate arguments. fileprivate var argumentsIterator: IndexingIterator<[String]> init(associatedArgumentValue: String?, argumentsIterator: IndexingIterator<[String]>, currentArgument: String) { self.associatedArgumentValue = associatedArgumentValue self.argumentsIterator = argumentsIterator self.currentArgument = currentArgument } mutating func next() -> String? { return argumentsIterator.next() } func peek() -> String? { var iteratorCopy = argumentsIterator let nextArgument = iteratorCopy.next() return nextArgument } } /// Parses the provided array and return the result. public func parse(_ arguments: [String] = []) throws -> Result { return try parse(arguments, parent: nil) } private func parse(_ arguments: [String] = [], parent: Result?) throws -> Result { let result = Result(parser: self, parent: parent) // Create options map to quickly look up the arguments. let optionsTuple = optionArguments.flatMap({ option -> [(String, AnyArgument)] in var result = [(option.name, option)] // Add the short names too, if we have them. if let shortName = option.shortName { result += [(shortName, option)] } return result }) let optionsMap = Dictionary(items: optionsTuple) // Create iterators. var positionalArgumentIterator = positionalArguments.makeIterator() var argumentsIterator = arguments.makeIterator() while let argumentString = argumentsIterator.next() { let argument: AnyArgument let parser: Parser // If argument is help then just print usage and exit. if argumentString == "-h" || argumentString == "-help" || argumentString == "--help" { printUsage(on: stdoutStream) exit(0) } else if isPositional(argument: argumentString) { /// If this parser has subparsers, we allow only one positional argument which is the subparser command. if !subparsers.isEmpty { // Make sure this argument has a subparser. guard let subparser = subparsers[argumentString] else { throw ArgumentParserError.expectedArguments(self, Array(subparsers.keys)) } // Save which subparser was chosen. result.subparser = argumentString // Parse reset of the arguments with the subparser. return try subparser.parse(Array(argumentsIterator), parent: result) } // Get the next positional argument we are expecting. guard let positionalArgument = positionalArgumentIterator.next() else { throw ArgumentParserError.unexpectedArgument(argumentString) } argument = positionalArgument parser = Parser( associatedArgumentValue: nil, argumentsIterator: argumentsIterator, currentArgument: argumentString) } else { let (argumentString, value) = argumentString.spm_split(around: "=") // Get the corresponding option for the option argument. guard let optionArgument = optionsMap[argumentString] else { throw ArgumentParserError.unknownOption(argumentString) } argument = optionArgument parser = Parser( associatedArgumentValue: value, argumentsIterator: argumentsIterator, currentArgument: argumentString) } // Update results. var parserProtocol = parser as ArgumentParserProtocol let values = try argument.parse(with: &parserProtocol) try result.add(values, for: argument) // Restore the argument iterator state. argumentsIterator = (parserProtocol as! Parser).argumentsIterator } // Report if there are any non-optional positional arguments left which were not present in the arguments. let leftOverArguments = Array(positionalArgumentIterator) if leftOverArguments.contains(where: { !$0.isOptional }) { throw ArgumentParserError.expectedArguments(self, leftOverArguments.map({ $0.name })) } return result } /// Prints usage text for this parser on the provided stream. public func printUsage(on stream: OutputByteStream) { /// Space settings. let maxWidthDefault = 24 let padding = 2 let maxWidth: Int // Determine the max width based on argument length or choose the // default width if max width is longer than the default width. if let maxArgument = (positionalArguments + optionArguments).map({ [$0.name, $0.shortName].compactMap({ $0 }).joined(separator: ", ").count }).max(), maxArgument < maxWidthDefault { maxWidth = maxArgument + padding + 1 } else { maxWidth = maxWidthDefault } /// Prints an argument on a stream if it has usage. func print(formatted argument: String, usage: String, on stream: OutputByteStream) { // Start with a new line and add some padding. stream <<< "\n" <<< Format.asRepeating(string: " ", count: padding) let count = argument.count // If the argument is longer than the max width, print the usage // on a new line. Otherwise, print the usage on the same line. if count >= maxWidth - padding { stream <<< argument <<< "\n" // Align full width because usage is to be printed on a new line. stream <<< Format.asRepeating(string: " ", count: maxWidth + padding) } else { stream <<< argument // Align to the remaining empty space on the line. stream <<< Format.asRepeating(string: " ", count: maxWidth - count) } stream <<< usage } stream <<< "OVERVIEW: " <<< overview // We only print command usage for top level parsers. if !isSubparser { stream <<< "\n\n" // Get the binary name from command line arguments. let defaultCommandName = CommandLine.arguments[0].components(separatedBy: "/").last! stream <<< "USAGE: " <<< (commandName ?? defaultCommandName) <<< " " <<< usage } if optionArguments.count > 0 { stream <<< "\n\n" stream <<< "OPTIONS:" for argument in optionArguments.lazy.sorted(by: { $0.name < $1.name }) { guard let usage = argument.usage else { continue } // Create name with its shortname, if available. let name = [argument.name, argument.shortName].compactMap({ $0 }).joined(separator: ", ") print(formatted: name, usage: usage, on: stream) } // Print help option, if this is a top level command. if !isSubparser { print(formatted: "--help", usage: "Display available options", on: stream) } } if subparsers.keys.count > 0 { stream <<< "\n\n" stream <<< "SUBCOMMANDS:" for (command, parser) in subparsers.sorted(by: { $0.key < $1.key }) { // Special case for hidden subcommands. guard !parser.overview.isEmpty else { continue } print(formatted: command, usage: parser.overview, on: stream) } } if positionalArguments.count > 0 { stream <<< "\n\n" stream <<< "POSITIONAL ARGUMENTS:" for argument in positionalArguments { guard let usage = argument.usage else { continue } print(formatted: argument.name, usage: usage, on: stream) } } if let seeAlso = seeAlso { stream <<< "\n\n" stream <<< "SEE ALSO: \(seeAlso)" } stream <<< "\n" stream.flush() } } /// A class to bind ArgumentParser's arguments to an option structure. public final class ArgumentBinder<Options> { /// The signature of body closure. private typealias BodyClosure = (inout Options, ArgumentParser.Result) throws -> Void /// This array holds the closures which should be executed to fill the options structure. private var bodies = [BodyClosure]() /// Create a binder. public init() { } /// Bind an option argument. public func bind<T>( option: OptionArgument<T>, to body: @escaping (inout Options, T) throws -> Void ) { addBody { guard let result = $1.get(option) else { return } try body(&$0, result) } } /// Bind an array option argument. public func bindArray<T>( option: OptionArgument<[T]>, to body: @escaping (inout Options, [T]) throws -> Void ) { addBody { guard let result = $1.get(option) else { return } try body(&$0, result) } } /// Bind a positional argument. public func bind<T>( positional: PositionalArgument<T>, to body: @escaping (inout Options, T) throws -> Void ) { addBody { // All the positional argument will always be present. guard let result = $1.get(positional) else { return } try body(&$0, result) } } /// Bind an array positional argument. public func bindArray<T>( positional: PositionalArgument<[T]>, to body: @escaping (inout Options, [T]) throws -> Void ) { addBody { // All the positional argument will always be present. guard let result = $1.get(positional) else { return } try body(&$0, result) } } /// Bind two positional arguments. public func bindPositional<T, U>( _ first: PositionalArgument<T>, _ second: PositionalArgument<U>, to body: @escaping (inout Options, T, U) throws -> Void ) { addBody { // All the positional arguments will always be present. guard let first = $1.get(first) else { return } guard let second = $1.get(second) else { return } try body(&$0, first, second) } } /// Bind three positional arguments. public func bindPositional<T, U, V>( _ first: PositionalArgument<T>, _ second: PositionalArgument<U>, _ third: PositionalArgument<V>, to body: @escaping (inout Options, T, U, V) throws -> Void ) { addBody { // All the positional arguments will always be present. guard let first = $1.get(first) else { return } guard let second = $1.get(second) else { return } guard let third = $1.get(third) else { return } try body(&$0, first, second, third) } } /// Bind two options. public func bind<T, U>( _ first: OptionArgument<T>, _ second: OptionArgument<U>, to body: @escaping (inout Options, T?, U?) throws -> Void ) { addBody { try body(&$0, $1.get(first), $1.get(second)) } } /// Bind three options. public func bind<T, U, V>( _ first: OptionArgument<T>, _ second: OptionArgument<U>, _ third: OptionArgument<V>, to body: @escaping (inout Options, T?, U?, V?) throws -> Void ) { addBody { try body(&$0, $1.get(first), $1.get(second), $1.get(third)) } } /// Bind two array options. public func bindArray<T, U>( _ first: OptionArgument<[T]>, _ second: OptionArgument<[U]>, to body: @escaping (inout Options, [T], [U]) throws -> Void ) { addBody { try body(&$0, $1.get(first) ?? [], $1.get(second) ?? []) } } /// Add three array option and call the final closure with their values. public func bindArray<T, U, V>( _ first: OptionArgument<[T]>, _ second: OptionArgument<[U]>, _ third: OptionArgument<[V]>, to body: @escaping (inout Options, [T], [U], [V]) throws -> Void ) { addBody { try body(&$0, $1.get(first) ?? [], $1.get(second) ?? [], $1.get(third) ?? []) } } /// Bind a subparser. public func bind( parser: ArgumentParser, to body: @escaping (inout Options, String) throws -> Void ) { addBody { guard let result = $1.subparser(parser) else { return } try body(&$0, result) } } /// Appends a closure to bodies array. private func addBody(_ body: @escaping BodyClosure) { bodies.append(body) } /// Fill the result into the options structure, /// throwing if one of the user-provided binder function throws. public func fill(parseResult result: ArgumentParser.Result, into options: inout Options) throws { try bodies.forEach { try $0(&options, result) } } /// Fill the result into the options structure. @available(*, deprecated, renamed: "fill(parseResult:into:)") public func fill(_ result: ArgumentParser.Result, into options: inout Options) { try! fill(parseResult: result, into: &options) } }
5d3fe3447df02ee364ef3592c9e32658
35.671493
158
0.621341
false
false
false
false
quickthyme/PUTcat
refs/heads/master
PUTcat/Presentation/Parser/ViewModel/ParserViewData.swift
apache-2.0
1
import UIKit struct ParserViewData { var section : [ParserViewDataSection] } struct ParserViewDataSection { var title : String var item : [ParserViewDataItem] } struct ParserViewDataItem { var refID : String = "" var cellID : String = "" var title : String? var detail : String? } extension ParserViewDataItem : ViewDataItem {} extension ParserViewData : Equatable {} func == (lhs: ParserViewData, rhs: ParserViewData) -> Bool { return (lhs.section == rhs.section) } extension ParserViewDataSection : Equatable {} func == (lhs: ParserViewDataSection, rhs: ParserViewDataSection) -> Bool { return (lhs.title == rhs.title && lhs.item == rhs.item) } extension ParserViewDataItem : Equatable {} func == (lhs: ParserViewDataItem, rhs: ParserViewDataItem) -> Bool { return (lhs.refID == rhs.refID && lhs.cellID == rhs.cellID && lhs.title == rhs.title && lhs.detail == rhs.detail) } protocol ParserViewDataItemConfigurable : class { func configure(headerViewDataItem item: ParserViewDataItem) } protocol ParserViewDataItemEditable : class { var textChanged : ((String) -> ())? { get set } var detailTextChanged : ((String) -> ())? { get set } var detailTextWillResize : (() -> ())? { get set } var detailTextDidResize : (() -> ())? { get set } }
0fca07859dbd3332f83279dd411cbee3
25.470588
74
0.659259
false
false
false
false
RyanHWillis/InfinityEngine
refs/heads/master
Example/InfinityEngine/AppDelegate.swift
mit
1
// // AppDelegate.swift // InfinityEngine // // Created by RyanHWillis on 04/30/2016. // Copyright (c) 2016 RyanHWillis. All rights reserved. // import UIKit import InfinityEngine @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { let loader = UIView() loader.backgroundColor = UIColor.red let params = InfinityParams(placeholderCount: 20, loadingView: loader) InfinityEngine.shared.setup(withParams: params) let startVC = HomeViewController() let nav = UINavigationController(rootViewController: startVC) self.window = UIWindow(frame: UIScreen.main.bounds) self.window?.rootViewController = nav self.window?.makeKeyAndVisible() 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 delay(_ delay:Double, closure:@escaping ()->()) { DispatchQueue.main.asyncAfter( deadline: DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: closure) }
c9503b830bd934624c1a1d6204d171f1
43.6875
285
0.727972
false
false
false
false
litoarias/SwiftTemplate
refs/heads/master
TemplateSwift3/Modules/Base/View/BaseViewController.swift
mit
1
// // BaseViewController.swift // TemplateSwift3 // // Created by Hipolito Arias on 13/07/2017. // Copyright © 2017 Hipolito Arias. All rights reserved. // import UIKit import MBProgressHUD import Localize_Swift class BaseViewController: UIViewController, BaseView { // MARK: Properties var progressHUD: MBProgressHUD? fileprivate var internalScrollView: UIScrollView? // MARK: Methods func showLoading() { let topmostViewController = findTopmostViewController() progressHUD = MBProgressHUD.showAdded(to: topmostViewController.view, animated: true) progressHUD?.mode = MBProgressHUDMode.indeterminate } func hideLoading() { self.progressHUD?.hide(animated: true) } func showMessage(_ message: String?, withTitle title: String?) { let errorMessage = message ?? "GENERIC_ERROR_MESSAGE".localized() let errorTitle = title ?? "ERROR".localized() let errorController = UIAlertController(title: errorTitle, message: errorMessage, preferredStyle: .alert) errorController.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil)) present(errorController, animated: true, completion: nil) } func showError(_ message: String?) { let errorMessage = message ?? "GENERIC_ERROR_MESSAGE".localized() let errorController = UIAlertController(title: "TITLE_ERROR".localized(), message: errorMessage, preferredStyle: .alert) errorController.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil)) present(errorController, animated: true, completion: nil) } func setupKeyboardNotifications(with scrollView: UIScrollView?) { internalScrollView = scrollView NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden), name: NSNotification.Name.UIKeyboardWillHide, object: nil) } // MARK: Keyboard Notifications func keyboardWillShow(notification: NSNotification) { guard let info = notification.userInfo, let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size else { return } let contentInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: keyboardSize.height + 15.0, right: 0.0) internalScrollView?.contentInset = contentInsets internalScrollView?.scrollIndicatorInsets = contentInsets var aRect = view.frame aRect.size.height -= keyboardSize.height guard let activeFieldPresent = findActiveTextField(view.subviews) else { return } if (!aRect.contains(activeFieldPresent.frame.origin)) { internalScrollView?.scrollRectToVisible(activeFieldPresent.frame, animated: true) } } func keyboardWillBeHidden(notification: NSNotification) { let contentInsets = UIEdgeInsets.zero internalScrollView?.contentInset = contentInsets internalScrollView?.scrollIndicatorInsets = contentInsets } }
c5f55c6793ef86cb76d5b5a7a12df9c8
40.076923
154
0.700062
false
false
false
false
Kiandr/CrackingCodingInterview
refs/heads/master
Swift/Ch 2. Linked Lists/Ch 2. Linked Lists.playground/Pages/2.8 Loop Detection.xcplaygroundpage/Contents.swift
mit
1
import Foundation /*: 2.8 Given a singly linked, circular list, return the node at the beginning of the loop. A circular list is a (corrupt) linked list in which a node's next pointer points to an earlier node in the list. Input: `a -> b -> c -> d -> e -> c` (The same c as before) \ Output: `c` */ extension MutableList { func nodeBeginningLoop() -> MutableList? { return nodeBeginningLoop(advanceBy: 1) } private func nodeBeginningLoop(advanceBy: Int) -> MutableList? { guard !isEmpty else { return nil } guard self !== node(at: advanceBy) else { return self } return tail?.nodeBeginningLoop(advanceBy: advanceBy + 1) } } let list = MutableList(arrayLiteral: "a", "b", "c", "d", "e") list.description let listToAppend = MutableList(arrayLiteral: "a", "b", "c", "d", "e") list.append(list: listToAppend) list.description assert(list.nodeBeginningLoop() == nil) let circularList = MutableList(arrayLiteral: "a", "b", "c", "d", "e") circularList.description assert(circularList.nodeBeginningLoop() == nil) let subList = circularList.tail?.tail circularList.append(list: subList!) assert(circularList.nodeBeginningLoop() === subList) // customizing MutableList's debugDescription prevents the playground from recursing infintely // when it prints a circular list extension MutableList: CustomDebugStringConvertible { public var debugDescription: String { guard let head = head else { return "nil" } let description = "\(head)" if let tailHead = tail?.head { return description + " -> \(tailHead) ..." } return description } }
2d854aa4599c5c48d37369ee0a95a90a
30.396226
94
0.670072
false
false
false
false
TimBroddin/meteor-ios
refs/heads/master
Examples/Todos/Todos/TodosViewController.swift
mit
4
// Copyright (c) 2014-2015 Martijn Walraven // // 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 CoreData import Meteor class TodosViewController: FetchedResultsTableViewController, UITextFieldDelegate { @IBOutlet weak var listLockStatusBarButtonItem: UIBarButtonItem! // MARK: - Model var listID: NSManagedObjectID? { didSet { assert(managedObjectContext != nil) if listID != nil { if listID != oldValue { list = (try? managedObjectContext!.existingObjectWithID(self.listID!)) as? List } } else { list = nil } } } private var listObserver: ManagedObjectObserver? private var list: List? { didSet { if list != oldValue { if list != nil { listObserver = ManagedObjectObserver(list!) { (changeType) -> Void in switch changeType { case .Deleted, .Invalidated: self.list = nil case .Updated, .Refreshed: self.listDidChange() default: break } } } else { listObserver = nil resetContent() } listDidChange() setNeedsLoadContent() } } } func listDidChange() { title = list?.name if isViewLoaded() { updateViewWithModel() } } // MARK: - View Lifecycle override func viewDidLoad() { super.viewDidLoad() addTaskContainerView.preservesSuperviewLayoutMargins = true } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) updateViewWithModel() } // MARK: - Content Loading override func loadContent() { if list == nil { return } super.loadContent() } override func configureSubscriptionLoader(subscriptionLoader: SubscriptionLoader) { if list != nil { subscriptionLoader.addSubscriptionWithName("todos", parameters: list!) } } override func createFetchedResultsController() -> NSFetchedResultsController? { if list == nil { return nil } let fetchRequest = NSFetchRequest(entityName: "Todo") fetchRequest.predicate = NSPredicate(format: "list == %@", self.list!) fetchRequest.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)] return NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: managedObjectContext, sectionNameKeyPath: nil, cacheName: nil) } // MARK: - Updating View func updateViewWithModel() { if list == nil { tableView.tableHeaderView = nil listLockStatusBarButtonItem.image = nil } else { tableView.tableHeaderView = addTaskContainerView if list!.user == nil { listLockStatusBarButtonItem.image = UIImage(named: "unlocked_icon") } else { listLockStatusBarButtonItem.image = UIImage(named: "locked_icon") } } } // MARK: - FetchedResultsTableViewDataSourceDelegate func dataSource(dataSource: FetchedResultsTableViewDataSource, configureCell cell: UITableViewCell, forObject object: NSManagedObject, atIndexPath indexPath: NSIndexPath) { if let todo = object as? Todo { cell.textLabel!.text = todo.text cell.accessoryType = todo.checked ? .Checkmark : .None } } func dataSource(dataSource: FetchedResultsTableViewDataSource, deleteObject object: NSManagedObject, atIndexPath indexPath: NSIndexPath) { if let todo = object as? Todo { managedObjectContext.deleteObject(todo) todo.list.incompleteCount-- saveManagedObjectContext() } } // MARK: - UITableViewDelegate override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? { if let todo = dataSource.objectAtIndexPath(indexPath) as? Todo { todo.checked = !todo.checked if (todo.checked) { todo.list.incompleteCount-- } else { todo.list.incompleteCount++ } saveManagedObjectContext() } return nil } // MARK: - UITextFieldDelegate @IBOutlet var addTaskContainerView: UIView! @IBOutlet weak var addTaskTextField: UITextField! func textFieldShouldReturn(textField: UITextField) -> Bool { guard let text = addTaskTextField.text where !text.isEmpty else { addTaskTextField.resignFirstResponder() return false } addTaskTextField.text = nil let todo = NSEntityDescription.insertNewObjectForEntityForName("Todo", inManagedObjectContext: managedObjectContext) as! Todo todo.creationDate = NSDate() todo.text = text todo.list = list list?.incompleteCount++ saveManagedObjectContext() return true } // MARK: - Making Lists Private @IBAction func listLockStatusButtonPressed() { if list != nil { let currentUser = self.currentUser if currentUser == nil { let alertController = UIAlertController(title: nil, message: "Please sign in to make private lists.", preferredStyle: .Alert) let okAction = UIAlertAction(title: "OK", style: .Default, handler: nil) alertController.addAction(okAction) presentViewController(alertController, animated: true, completion: nil) return } if list!.user == nil { list!.user = currentUser } else { list!.user = nil } saveManagedObjectContext() } } }
0f83475248cca5523b646611201c869d
29.269767
174
0.66933
false
false
false
false
MaartenBrijker/project
refs/heads/back
project/External/AudioKit-master/AudioKit/Common/Nodes/Generators/Oscillators/Square Wave/AKSquareWaveOscillator.swift
apache-2.0
1
// // AKSquareWaveOscillator.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright (c) 2016 Aurelius Prochazka. All rights reserved. // import AVFoundation /// This is a bandlimited square oscillator ported from the "square" function /// from the Faust programming language. /// /// - parameter frequency: In cycles per second, or Hz. /// - parameter amplitude: Output amplitude /// - parameter pulseWidth: Duty cycle width (range 0-1). /// - parameter detuningOffset: Frequency offset in Hz. /// - parameter detuningMultiplier: Frequency detuning multiplier /// public class AKSquareWaveOscillator: AKVoice { // MARK: - Properties internal var internalAU: AKSquareWaveOscillatorAudioUnit? internal var token: AUParameterObserverToken? private var frequencyParameter: AUParameter? private var amplitudeParameter: AUParameter? private var pulseWidthParameter: AUParameter? private var detuningOffsetParameter: AUParameter? private var detuningMultiplierParameter: AUParameter? /// Ramp Time represents the speed at which parameters are allowed to change public var rampTime: Double = AKSettings.rampTime { willSet(newValue) { if rampTime != newValue { internalAU?.rampTime = newValue internalAU?.setUpParameterRamp() } } } /// In cycles per second, or Hz. public var frequency: Double = 440 { willSet(newValue) { if frequency != newValue { if internalAU!.isSetUp() { frequencyParameter?.setValue(Float(newValue), originator: token!) } else { internalAU?.frequency = Float(newValue) } } } } /// Output Amplitude. public var amplitude: Double = 1 { willSet(newValue) { if amplitude != newValue { if internalAU!.isSetUp() { amplitudeParameter?.setValue(Float(newValue), originator: token!) } else { internalAU?.amplitude = Float(newValue) } } } } /// Frequency offset in Hz. public var detuningOffset: Double = 0 { willSet(newValue) { if detuningOffset != newValue { if internalAU!.isSetUp() { detuningOffsetParameter?.setValue(Float(newValue), originator: token!) } else { internalAU?.detuningOffset = Float(newValue) } } } } /// Frequency detuning multiplier public var detuningMultiplier: Double = 1 { willSet(newValue) { if detuningMultiplier != newValue { if internalAU!.isSetUp() { detuningMultiplierParameter?.setValue(Float(newValue), originator: token!) } else { internalAU?.detuningMultiplier = Float(newValue) } } } } /// Duty cycle width (range 0-1). public var pulseWidth: Double = 0.5 { willSet(newValue) { if pulseWidth != newValue { pulseWidthParameter?.setValue(Float(newValue), originator: token!) if internalAU!.isSetUp() { pulseWidthParameter?.setValue(Float(newValue), originator: token!) } else { internalAU?.pulseWidth = Float(newValue) } } } } /// Tells whether the node is processing (ie. started, playing, or active) override public var isStarted: Bool { return internalAU!.isPlaying() } // MARK: - Initialization /// Initialize the oscillator with defaults public convenience override init() { self.init(frequency: 440) } /// Initialize this oscillator node /// /// - parameter frequency: In cycles per second, or Hz. /// - parameter amplitude: Output amplitude /// - parameter pulseWidth: Duty cycle width (range 0-1). /// - parameter detuningOffset: Frequency offset in Hz. /// - parameter detuningMultiplier: Frequency detuning multiplier /// public init( frequency: Double, amplitude: Double = 1.0, pulseWidth: Double = 0.5, detuningOffset: Double = 0, detuningMultiplier: Double = 1) { self.frequency = frequency self.amplitude = amplitude self.pulseWidth = pulseWidth self.detuningOffset = detuningOffset self.detuningMultiplier = detuningMultiplier var description = AudioComponentDescription() description.componentType = kAudioUnitType_Generator description.componentSubType = 0x7371726f /*'sqro'*/ description.componentManufacturer = 0x41754b74 /*'AuKt'*/ description.componentFlags = 0 description.componentFlagsMask = 0 AUAudioUnit.registerSubclass( AKSquareWaveOscillatorAudioUnit.self, asComponentDescription: description, name: "Local AKSquareWaveOscillator", version: UInt32.max) super.init() AVAudioUnit.instantiateWithComponentDescription(description, options: []) { avAudioUnit, error in guard let avAudioUnitGenerator = avAudioUnit else { return } self.avAudioNode = avAudioUnitGenerator self.internalAU = avAudioUnitGenerator.AUAudioUnit as? AKSquareWaveOscillatorAudioUnit AudioKit.engine.attachNode(self.avAudioNode) } guard let tree = internalAU?.parameterTree else { return } frequencyParameter = tree.valueForKey("frequency") as? AUParameter amplitudeParameter = tree.valueForKey("amplitude") as? AUParameter pulseWidthParameter = tree.valueForKey("pulseWidth") as? AUParameter detuningOffsetParameter = tree.valueForKey("detuningOffset") as? AUParameter detuningMultiplierParameter = tree.valueForKey("detuningMultiplier") as? AUParameter token = tree.tokenByAddingParameterObserver { address, value in dispatch_async(dispatch_get_main_queue()) { if address == self.frequencyParameter!.address { self.frequency = Double(value) } else if address == self.amplitudeParameter!.address { self.amplitude = Double(value) } else if address == self.pulseWidthParameter!.address { self.pulseWidth = Double(value) } else if address == self.detuningOffsetParameter!.address { self.detuningOffset = Double(value) } else if address == self.detuningMultiplierParameter!.address { self.detuningMultiplier = Double(value) } } } internalAU?.frequency = Float(frequency) internalAU?.amplitude = Float(amplitude) internalAU?.pulseWidth = Float(pulseWidth) internalAU?.detuningOffset = Float(detuningOffset) internalAU?.detuningMultiplier = Float(detuningMultiplier) } /// Function create an identical new node for use in creating polyphonic instruments public override func duplicate() -> AKVoice { let copy = AKSquareWaveOscillator(frequency: self.frequency, amplitude: self.amplitude, pulseWidth: self.pulseWidth, detuningOffset: self.detuningOffset, detuningMultiplier: self.detuningMultiplier) return copy } /// Function to start, play, or activate the node, all do the same thing public override func start() { self.internalAU!.start() } /// Function to stop or bypass the node, both are equivalent public override func stop() { self.internalAU!.stop() } }
998b4052579575306dd6d8107e190a49
35.39726
206
0.610087
false
false
false
false
tensorflow/examples
refs/heads/master
lite/examples/object_detection/ios/ObjectDetection/Views/OverlayView.swift
apache-2.0
1
// Copyright 2019 The TensorFlow Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import UIKit /** This structure holds the display parameters for the overlay to be drawon on a detected object. */ struct ObjectOverlay { let name: String let borderRect: CGRect let nameStringSize: CGSize let color: UIColor let font: UIFont } /** This UIView draws overlay on a detected object. */ class OverlayView: UIView { var objectOverlays: [ObjectOverlay] = [] private let cornerRadius: CGFloat = 10.0 private let stringBgAlpha: CGFloat = 0.7 private let lineWidth: CGFloat = 3 private let stringFontColor = UIColor.white private let stringHorizontalSpacing: CGFloat = 13.0 private let stringVerticalSpacing: CGFloat = 7.0 override func draw(_ rect: CGRect) { // Drawing code for objectOverlay in objectOverlays { drawBorders(of: objectOverlay) drawBackground(of: objectOverlay) drawName(of: objectOverlay) } } /** This method draws the borders of the detected objects. */ func drawBorders(of objectOverlay: ObjectOverlay) { let path = UIBezierPath(rect: objectOverlay.borderRect) path.lineWidth = lineWidth objectOverlay.color.setStroke() path.stroke() } /** This method draws the background of the string. */ func drawBackground(of objectOverlay: ObjectOverlay) { let stringBgRect = CGRect(x: objectOverlay.borderRect.origin.x, y: objectOverlay.borderRect.origin.y , width: 2 * stringHorizontalSpacing + objectOverlay.nameStringSize.width, height: 2 * stringVerticalSpacing + objectOverlay.nameStringSize.height ) let stringBgPath = UIBezierPath(rect: stringBgRect) objectOverlay.color.withAlphaComponent(stringBgAlpha).setFill() stringBgPath.fill() } /** This method draws the name of object overlay. */ func drawName(of objectOverlay: ObjectOverlay) { // Draws the string. let stringRect = CGRect(x: objectOverlay.borderRect.origin.x + stringHorizontalSpacing, y: objectOverlay.borderRect.origin.y + stringVerticalSpacing, width: objectOverlay.nameStringSize.width, height: objectOverlay.nameStringSize.height) let attributedString = NSAttributedString(string: objectOverlay.name, attributes: [NSAttributedString.Key.foregroundColor : stringFontColor, NSAttributedString.Key.font : objectOverlay.font]) attributedString.draw(in: stringRect) } }
8676dd2fccb6028bdc63aa0b9216bc4e
31.733333
251
0.74372
false
false
false
false
SimonLYU/Swift-Transitioning
refs/heads/master
highGo2/LYUSmallImageCell.swift
mit
1
// // LYUSmallImageCell.swift // highGo2 // // Created by 吕旭明 on 16/8/4. // Copyright © 2016年 lyu. All rights reserved. // import UIKit import SDWebImage class LYUSmallImageCell: UICollectionViewCell { lazy var imageView : UIImageView = { let imageView = UIImageView() imageView.contentMode = .ScaleAspectFill imageView.frame = self.bounds imageView.clipsToBounds = true self.addSubview(imageView) return imageView }() var item : LYUItem?{ didSet{ guard let url = NSURL(string: item!.q_pic_url) else { return } self.imageView.sd_setImageWithURL(url, placeholderImage: UIImage(named: "empty_picture")) } } override init(frame: CGRect) { super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
949d013bc5a085a0a91ed4dc3205b006
23
101
0.596875
false
false
false
false
Chovans/refresher
refs/heads/master
PullToRefreshDemo/BeatAnimator.swift
mit
7
// // BeatAnimator.swift // // Copyright (c) 2014 Josip Cavar // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Foundation import Refresher import QuartzCore class BeatAnimator: UIView, PullToRefreshViewDelegate { private let layerLoader = CAShapeLayer() private let layerSeparator = CAShapeLayer() override init(frame: CGRect) { super.init(frame: frame) layerLoader.lineWidth = 4 layerLoader.strokeColor = UIColor(red: 0.13, green: 0.79, blue: 0.31, alpha: 1).CGColor layerLoader.strokeEnd = 0 layerSeparator.lineWidth = 1 layerSeparator.strokeColor = UIColor(red: 0.7, green: 0.7, blue: 0.7, alpha: 1).CGColor } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func pullToRefresh(view: PullToRefreshView, progressDidChange progress: CGFloat) { layerLoader.strokeEnd = progress } func pullToRefresh(view: PullToRefreshView, stateDidChange state: PullToRefreshViewState) { } func pullToRefreshAnimationDidEnd(view: PullToRefreshView) { layerLoader.removeAllAnimations() } func pullToRefreshAnimationDidStart(view: PullToRefreshView) { let pathAnimationEnd = CABasicAnimation(keyPath: "strokeEnd") pathAnimationEnd.duration = 0.5 pathAnimationEnd.repeatCount = 100 pathAnimationEnd.autoreverses = true pathAnimationEnd.fromValue = 1 pathAnimationEnd.toValue = 0.8 layerLoader.addAnimation(pathAnimationEnd, forKey: "strokeEndAnimation") let pathAnimationStart = CABasicAnimation(keyPath: "strokeStart") pathAnimationStart.duration = 0.5 pathAnimationStart.repeatCount = 100 pathAnimationStart.autoreverses = true pathAnimationStart.fromValue = 0 pathAnimationStart.toValue = 0.2 layerLoader.addAnimation(pathAnimationStart, forKey: "strokeStartAnimation") } override func layoutSubviews() { super.layoutSubviews() if let superview = superview { if layerLoader.superlayer == nil { superview.layer.addSublayer(layerLoader) } if layerSeparator.superlayer == nil { superview.layer.addSublayer(layerSeparator) } let bezierPathLoader = UIBezierPath() bezierPathLoader.moveToPoint(CGPointMake(0, superview.frame.height - 3)) bezierPathLoader.addLineToPoint(CGPoint(x: superview.frame.width, y: superview.frame.height - 3)) let bezierPathSeparator = UIBezierPath() bezierPathSeparator.moveToPoint(CGPointMake(0, superview.frame.height - 1)) bezierPathSeparator.addLineToPoint(CGPoint(x: superview.frame.width, y: superview.frame.height - 1)) layerLoader.path = bezierPathLoader.CGPath layerSeparator.path = bezierPathSeparator.CGPath } } }
93b55887e158b2e13ebd50bbe6f757d9
39.58
112
0.690734
false
false
false
false
PekanMmd/Pokemon-XD-Code
refs/heads/master
Objects/struct tables/PokespotsTables.swift
gpl-2.0
1
// // File.swift // GoD Tool // // Created by Stars Momodu on 22/03/2021. // import Foundation let pokespotPokemonStructFormat: [GoDStructProperties] = [ .byte(name: "Min Level", description: "", type: .uint), .byte(name: "Max Level", description: "", type: .uint), .short(name: "Species", description: "", type: .pokemonID), .word(name: "Encounter Percentage", description: "", type: .percentage), .word(name: "Steps per snack", description: "How many steps it takes for the pokemon to eat 1 snack", type: .uint) ] let oasisPokespotTable = CommonStructTable(index: .PokespotOasis, properties: GoDStruct(name: "Pokespot Oasis", format: pokespotPokemonStructFormat)) let rockPokespotTable = CommonStructTable(index: .PokespotRock, properties: GoDStruct(name: "Pokespot Rock", format: pokespotPokemonStructFormat)) let cavePokespotTable = CommonStructTable(index: .PokespotCave, properties: GoDStruct(name: "Pokespot Cave", format: pokespotPokemonStructFormat)) let allPokespotsTable = CommonStructTable(index: .PokespotAll, properties: GoDStruct(name: "Pokespot All", format: pokespotPokemonStructFormat)) let pokespotStruct = GoDStruct(name: "Pokespot", format: [ .word(name: "Current Number Of Snacks Flag", description: "", type: .flagID), .word(name: "Unknown Flag 2", description: "", type: .flagID), .word(name: "Unknown Flag 3", description: "", type: .flagID), .word(name: "Current Pokemon Spawn Flag", description: "", type: .flagID), .word(name: "Unknown Flag 5", description: "", type: .flagID), .word(name: "Unknown Flag 6", description: "", type: .flagID), .word(name: "Unknown Pointer", description: "Filled in at run time, 0 in the ROM data", type: .pointer), ]) let pokespotsTable = CommonStructTable(index: .Pokespots, properties: pokespotStruct)
9322fa3f4e1f0db0abc133a308e7c1ea
53.030303
149
0.731913
false
false
false
false
Koshub/UICollectionViewPageViewModel
refs/heads/master
Pod/Classes/UICollectionViewPageViewModel.swift
mit
1
// // UICollectionViewPageViewModel.swift // // Created by Konstantin Gerasimov on 5/4/15. // Copyright (c) 2015 itdumka.com.ua. All rights reserved. // import UIKit extension UICollectionView { public func pageSize() -> CGSize { let size = CGSize(width: frame.size.width, height: frame.size.height) return size } public func currentPageIndex() -> Int? { if pagingEnabled { let size = pageSize() if let flowLayout = self.collectionViewLayout as? UICollectionViewFlowLayout { switch flowLayout.scrollDirection { case .Horizontal: let pageIndex = max(0, Int(contentOffset.x / size.width)) return pageIndex case .Vertical: let pageIndex = max(0, Int(contentOffset.y / size.height)) return pageIndex } } } return nil } public func scrollToPageIndex(pageIndex: Int, animated: Bool) { if let pagesCount = pagesCount() where pageIndex < pagesCount { let numberOfItems = dataSource?.collectionView(self, numberOfItemsInSection: 0) ?? 0 if numberOfItems > 0, let flowLayout = self.collectionViewLayout as? UICollectionViewFlowLayout { let newContentOffset: CGPoint switch flowLayout.scrollDirection { case .Horizontal: let pageOffset = CGFloat(pageIndex) * pageSize().width newContentOffset = CGPoint(x: pageOffset, y: contentOffset.y) case .Vertical: let pageOffset = CGFloat(pageIndex) * pageSize().height newContentOffset = CGPoint(x: contentOffset.x, y: pageOffset) } setContentOffset(newContentOffset, animated: animated) } } } public func pagesCount() -> Int? { if let flowLayout = self.collectionViewLayout as? UICollectionViewFlowLayout { let pageSize = self.pageSize() let contentSize = flowLayout.collectionViewContentSize() switch flowLayout.scrollDirection { case .Horizontal: let pagesCount = Int(ceil(contentSize.width / pageSize.width)); return pagesCount case .Vertical: let pagesCount = Int(ceil(contentSize.height / pageSize.height)); return pagesCount } } else { return nil } } }
c5bde1e4b6cf787e676a1ef9bb37667c
36.535211
96
0.550844
false
false
false
false
AlbertXYZ/HDCP
refs/heads/develop
BarsAroundMe/Pods/RxCocoa/RxCocoa/CocoaUnits/Driver/Driver.swift
apache-2.0
29
// // Driver.swift // RxCocoa // // Created by Krunoslav Zaher on 9/26/16. // Copyright © 2016 Krunoslav Zaher. All rights reserved. // #if !RX_NO_MODULE import RxSwift #endif /** Unit that represents observable sequence with following properties: - it never fails - it delivers events on `MainScheduler.instance` - `shareReplayLatestWhileConnected()` behavior - all observers share sequence computation resources - it's stateful, upon subscription (calling subscribe) last element is immediatelly replayed if it was produced - computation of elements is reference counted with respect to the number of observers - if there are no subscribers, it will release sequence computation resources `Driver<Element>` can be considered a builder pattern for observable sequences that drive the application. If observable sequence has produced at least one element, after new subscription is made last produced element will be immediately replayed on the same thread on which the subscription was made. When using `drive*`, `subscribe*` and `bind*` family of methods, they should always be called from main thread. If `drive*`, `subscribe*` and `bind*` are called from background thread, it is possible that initial replay will happen on background thread, and subsequent events will arrive on main thread. To find out more about units and how to use them, please visit `Documentation/Units.md`. */ public typealias Driver<E> = SharedSequence<DriverSharingStrategy, E> public struct DriverSharingStrategy: SharingStrategyProtocol { public static var scheduler: SchedulerType { return driverObserveOnScheduler } public static func share<E>(_ source: Observable<E>) -> Observable<E> { return source.shareReplayLatestWhileConnected() } } extension SharedSequenceConvertibleType where SharingStrategy == DriverSharingStrategy { /// Adds `asDriver` to `SharingSequence` with `DriverSharingStrategy`. public func asDriver() -> Driver<E> { return self.asSharedSequence() } } /** This method can be used in unit tests to ensure that driver is using mock schedulers instead of main schedulers. **This shouldn't be used in normal release builds.** */ public func driveOnScheduler(_ scheduler: SchedulerType, action: () -> ()) { let originalObserveOnScheduler = driverObserveOnScheduler driverObserveOnScheduler = scheduler action() // If you remove this line , compiler buggy optimizations will change behavior of this code _forceCompilerToStopDoingInsaneOptimizationsThatBreakCode(driverObserveOnScheduler) // Scary, I know driverObserveOnScheduler = originalObserveOnScheduler } #if os(Linux) import Glibc #else import func Foundation.arc4random #endif func _forceCompilerToStopDoingInsaneOptimizationsThatBreakCode(_ scheduler: SchedulerType) { let a: Int32 = 1 #if os(Linux) let b = 314 + Int32(Glibc.random() & 1) #else let b = 314 + Int32(arc4random() & 1) #endif if a == b { print(scheduler) } } fileprivate var driverObserveOnScheduler: SchedulerType = MainScheduler.instance
393fd6e4a7032d6666a684dafcca82a7
33.6
119
0.754335
false
false
false
false
silence0201/Swift-Study
refs/heads/master
Swifter/Swifter.playground/Pages/local-scope.xcplaygroundpage/Contents.swift
apache-2.0
2
import UIKit import PlaygroundSupport func local(_ closure: ()->()) { closure() } func loadView() { let view = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 480)) view.backgroundColor = .white local { let titleLabel = UILabel(frame: CGRect(x: 150, y: 30, width: 200, height: 40)) titleLabel.textColor = .red titleLabel.text = "Title" view.addSubview(titleLabel) } local { let textLabel = UILabel(frame: CGRect(x: 150, y: 80, width: 200, height: 40)) textLabel.textColor = .red textLabel.text = "Text" view.addSubview(textLabel) } PlaygroundPage.current.liveView = view } loadView() let titleLabel: UILabel = { let label = UILabel(frame: CGRect(x: 150, y: 30, width: 200, height: 40)) label.textColor = .red label.text = "Title" return label }()
f32facd50e15aaf9ac6ab40e7fc04e85
23
86
0.600902
false
false
false
false
bjvanlinschoten/Pala
refs/heads/master
Pala/Pala/EventsViewController.swift
mit
1
// // EventsViewController.swift // Pala // // Created by Boris van Linschoten on 07-06-15. // Copyright (c) 2015 bjvanlinschoten. All rights reserved. // import UIKit class EventsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { // Properties var wallViewController: WallCollectionViewController? var wallUserArray: [Person]? var wall: Wall? var currentUser: User? var refreshControl: UIRefreshControl! @IBOutlet var eventsTable: UITableView! override func viewDidLoad() { super.viewDidLoad() self.automaticallyAdjustsScrollViewInsets = false self.wall = Wall() // Pull to refresh self.refreshControl = UIRefreshControl() self.refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh") self.refreshControl.addTarget(self, action: "refreshEventsTable", forControlEvents: UIControlEvents.ValueChanged) self.eventsTable.addSubview(self.refreshControl) // Navigation bar appearance self.navigationController?.navigationBar.barTintColor = UIColor(hexString: "FF7400") self.navigationController?.navigationBar.tintColor = UIColor.whiteColor() self.navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()] self.title = "Menu" // Get data for table and reload self.currentUser?.getUserEvents() { () -> Void in self.eventsTable.reloadData() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // Refresh events func refreshEventsTable() { self.currentUser?.getUserEvents() { () -> Void in self.eventsTable.reloadData() self.refreshControl.endRefreshing() } } // Gender selecton @IBAction func genderSelectChange(sender: UISegmentedControl) { if self.wall!.selectedEvent != nil { MBProgressHUD.showHUDAddedTo(self.wallViewController?.view, animated: true) self.wall!.selectedGender = sender.selectedSegmentIndex self.wallViewController?.wall = self.wall! self.wallViewController?.appearsFromEventSelect() self.closeLeft() } else { self.wall!.selectedGender = sender.selectedSegmentIndex } } // MARK: TableView Delegate methods func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 2 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 0 { return 1 } else { if let user = self.currentUser { if let events = user.events { return events.count } } return 0 } } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if indexPath.section == 0 { // Make header cell let cell = tableView.dequeueReusableCellWithIdentifier("headerCell", forIndexPath: indexPath) as! HeaderCell let id = self.currentUser?.parseUser["facebookId"] as! NSString // Set profile picture let picURL: NSURL! = NSURL(string: "https://graph.facebook.com/\(id)/picture?width=600&height=600") cell.profilePicture.sd_setImageWithURL(picURL) cell.profilePicture.layer.masksToBounds = false cell.profilePicture.layer.shadowOpacity = 0.3 cell.profilePicture.layer.shadowRadius = 1.0 cell.profilePicture.layer.shadowOffset = CGSize(width: 2, height: 2) // Set label with name and age if let age = self.currentUser?.getUserAge() as NSInteger! { if let name = self.currentUser?.parseUser.valueForKey("name") as? String { cell.nameLabel.text = "\(name) (\(age))" } } // Get initial gender value self.wall!.selectedGender = cell.genderSelect.selectedSegmentIndex // Cell not selectable cell.selectionStyle = UITableViewCellSelectionStyle.None return cell } else { let cell = tableView.dequeueReusableCellWithIdentifier("eventCell", forIndexPath: indexPath) as! EventsTableViewCell // Event for this cell let event = self.currentUser!.events?[indexPath.row] as! NSDictionary let eventId = event["id"] as! String // Set event picutre let picURL: NSURL! = NSURL(string: "https://graph.facebook.com/\(eventId)/picture?width=600&height=600") cell.eventImageView.sd_setImageWithURL(picURL) cell.eventImageView.layer.masksToBounds = true cell.eventImageView.layer.cornerRadius = 4 // Set appearance of cell cell.eventView.layer.masksToBounds = false cell.eventView.layer.shadowOpacity = 0.3 cell.eventView.layer.shadowRadius = 1.0 cell.eventView.layer.shadowOffset = CGSize(width: 2, height: 2) // Set label with event title cell.eventLabel.text = event["name"] as? String return cell } } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if indexPath.section == 1 { // Loading MBProgressHUD.showHUDAddedTo(self.wallViewController?.view, animated: true) // Selected event let selectedEvent = self.currentUser?.events?[indexPath.row] as! NSDictionary // Pass information to wall and go there self.wall!.currentUser = self.currentUser self.wall!.selectedEvent = selectedEvent self.wallViewController!.wall = self.wall self.wallViewController!.appearsFromEventSelect() self.closeLeft() tableView.deselectRowAtIndexPath(indexPath, animated: true) } } func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if section == 0 { return "Menu" } else { return "Events" } } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if indexPath.section == 0 { return 280 } else { return 75 } } }
5727388e34fb2dca85df680d19d566c9
35.328042
128
0.60268
false
false
false
false
hustlzp/bemyeyes-ios
refs/heads/development
BeMyEyes/Source/Views/PointsBarView.swift
mit
2
// // PointsBarView.swift // BeMyEyes // // Created by Tobias DM on 23/09/14. // Copyright (c) 2014 Be My Eyes. All rights reserved. // import UIKit @IBDesignable class PointsBarView: UIView { @IBInspectable var color: UIColor = UIColor.lightTextColor() { didSet { setup() } } @IBInspectable var text: String = "" { didSet { label.text = text } } @IBInspectable var progress: Float { set { label.split = newValue } get { return label.split } } private lazy var label: SplitMaskedLabel = { let label = SplitMaskedLabel(frame: CGRectZero) label.font = UIFont.preferredFontForTextStyle(UIFontTextStyleBody) label.text = self.text label.textAlignment = .Center label.color = self.color self.addSubview(label) return label }() override func layoutSubviews() { super.layoutSubviews() label.frame = bounds setup() } override func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() setup() text = "100 points untill next level" progress = 0.5 } } extension PointsBarView { func setup() { backgroundColor = UIColor.clearColor() label.textColor = color } }
235e34cc3b5f9b8f6bd52353f84cdb28
20.378788
74
0.562721
false
false
false
false
GRSource/GRTabBarController
refs/heads/master
Example/Controllers/RootTabViewController.swift
mit
1
// // RootTabViewController.swift // GRTabBarController // // Created by iOS_Dev5 on 2017/2/9. // Copyright © 2017年 GRSource. All rights reserved. // import UIKit class RootTabViewController: GRTabBarController, GRTabBarControllerProtocol { override func viewDidLoad() { super.viewDidLoad() self.setupViewControllers() self.customizeTabBarForController() self.delegate = self } //MARK: - Methods func setupViewControllers() { let firstViewController = GRFirst_RootViewController() let firstNavigationController = UINavigationController.init(rootViewController: firstViewController) let secondViewController = GRSecond_RootViewController() let secondNavigationController = UINavigationController.init(rootViewController: secondViewController) let thirdViewController = GRThird_RootViewController() let thirdNavigationController = UINavigationController.init(rootViewController: thirdViewController) self.viewControllers = [firstNavigationController, secondNavigationController, thirdNavigationController] } func customizeTabBarForController() { let finishedImage = UIImage(named: "tabbar_selected_background") let unfinishedImage = UIImage(named: "tabbar_normal_background") let tabBarItemImages = ["first", "second", "third"] var index = 0 for item in self.tabBar.items { item.setBackgroundSelectedImage(finishedImage!, withUnselectedImage: unfinishedImage!) let selectedimage = UIImage(named: "\(tabBarItemImages[index])_selected") let unselectedimage = UIImage(named: "\(tabBarItemImages[index])_normal") item.setFinishedSelectedImage(selectedimage!, withFinishedUnselectedImage: unselectedimage!) item.title = tabBarItemImages[index] index+=1 } } //MARK: - RDVTabBarControllerDelegate func tabBarController(_ tabBarController: GRTabBarController, shouldSelectViewController viewController: UIViewController) -> Bool { return true } func tabBarController(_ tabBarController: GRTabBarController, didSelectViewController viewController: UIViewController) { print("select \(viewController.title)") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
80ee4f800956f538aed127394785aa68
35.544304
136
0.694839
false
false
false
false
zhuyunfeng1224/XiheMtxx
refs/heads/master
XiheMtxx/VC/EditImage/ScaleSelectionCollectionViewCell.swift
mit
1
// // ScaleSelectionCollectionViewCell.swift // EasyCard // // Created by echo on 2017/2/17. // Copyright © 2017年 羲和. All rights reserved. // import UIKit class ScaleSelectionCollectionViewCell: UICollectionViewCell { lazy var itemButton: VerticalButton = { let _itemButton = VerticalButton(frame: CGRect.zero) _itemButton.translatesAutoresizingMaskIntoConstraints = false _itemButton.imageView?.contentMode = .center _itemButton.setTitleColor(UIColor.colorWithHexString(hex: "#578fff"), for: .highlighted) _itemButton.setTitleColor(UIColor.colorWithHexString(hex: "#578fff"), for: .selected) _itemButton.setTitleColor(UIColor.gray, for: .normal) _itemButton.titleLabel?.font = UIFont.systemFont(ofSize: 10) return _itemButton }() override init(frame: CGRect) { super.init(frame: frame) self.contentView.addSubview(self.itemButton) self.setNeedsUpdateConstraints() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func updateConstraints() { super.updateConstraints() let itemButtonHConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[itemButton]-0-|", options: NSLayoutFormatOptions(rawValue:0), metrics: nil, views: ["itemButton": itemButton]) self.contentView.addConstraints(itemButtonHConstraints) let itemButtonVConstraints = NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[itemButton]-0-|", options: NSLayoutFormatOptions(rawValue:0), metrics: nil, views: ["itemButton": itemButton]) self.contentView.addConstraints(itemButtonVConstraints) } }
5c478c4726869f38c89c102bf104bea4
41.268293
204
0.70629
false
false
false
false
ivygulch/IVGFoundation
refs/heads/master
IVGFoundation/source/common/Synchronizer.swift
mit
1
// // Synchronizer.swift // IVGFoundation // // Created by Douglas Sjoquist on 3/20/16. // Copyright © 2016 Ivy Gulch LLC. All rights reserved. // import Foundation public class Synchronizer { private let queue: DispatchQueue public init() { let uuid = UUID().uuidString self.queue = DispatchQueue(label: "Sync.\(uuid)",attributes: []) } public init(queueName: String) { self.queue = DispatchQueue(label: queueName,attributes: []) } public init(queue: DispatchQueue) { self.queue = queue } public func execute(_ closure: ()->Void) { queue.sync(execute: { closure() }) } public func valueOf<T>(_ closure: ()->T) -> T { var result: T! queue.sync(execute: { result = closure() }) return result } }
33ed4e1993c8d0074b2913e40a7b9768
19.853659
72
0.569591
false
false
false
false
JGiola/swift
refs/heads/main
test/Concurrency/predates_concurrency_swift6.swift
apache-2.0
9
// RUN: %target-typecheck-verify-swift -disable-availability-checking -swift-version 6 // REQUIRES: concurrency // REQUIRES: asserts @preconcurrency func unsafelySendableClosure(_ closure: @Sendable () -> Void) { } @preconcurrency func unsafelyMainActorClosure(_ closure: @MainActor () -> Void) { } @preconcurrency func unsafelyDoEverythingClosure(_ closure: @MainActor @Sendable () -> Void) { } struct X { @preconcurrency func unsafelyDoEverythingClosure(_ closure: @MainActor @Sendable () -> Void) { } @preconcurrency var sendableVar: @Sendable () -> Void @preconcurrency var mainActorVar: @MainActor () -> Void @preconcurrency subscript(_: @MainActor () -> Void) -> (@Sendable () -> Void) { {} } @preconcurrency static subscript(statically _: @MainActor () -> Void) -> (@Sendable () -> Void) { { } } } @MainActor func onMainActor() { } func testInAsync(x: X) async { let _: Int = unsafelySendableClosure // expected-error{{type '(@Sendable () -> Void) -> ()'}} let _: Int = unsafelyMainActorClosure // expected-error{{type '(@MainActor () -> Void) -> ()'}} let _: Int = unsafelyDoEverythingClosure // expected-error{{type '(@MainActor @Sendable () -> Void) -> ()'}} let _: Int = x.unsafelyDoEverythingClosure // expected-error{{type '(@MainActor @Sendable () -> Void) -> ()'}} let _: Int = X.unsafelyDoEverythingClosure // expected-error{{type '(X) -> (@MainActor @Sendable () -> Void) -> ()'}} let _: Int = (X.unsafelyDoEverythingClosure)(x) // expected-error{{type '(@MainActor @Sendable () -> Void) -> ()'}} let _: Int = x.sendableVar // expected-error{{type '@Sendable () -> Void'}} let _: Int = x.mainActorVar // expected-error{{type '@MainActor () -> Void'}} let _: Int = x[{ onMainActor() }] // expected-error{{type '@Sendable () -> Void'}} let _: Int = X[statically: { onMainActor() }] // expected-error{{type '@Sendable () -> Void'}} } func testElsewhere(x: X) { let _: Int = unsafelySendableClosure // expected-error{{type '(@Sendable () -> Void) -> ()'}} let _: Int = unsafelyMainActorClosure // expected-error{{type '(@MainActor () -> Void) -> ()'}} let _: Int = unsafelyDoEverythingClosure // expected-error{{type '(@MainActor @Sendable () -> Void) -> ()'}} let _: Int = x.unsafelyDoEverythingClosure // expected-error{{type '(@MainActor @Sendable () -> Void) -> ()'}} let _: Int = X.unsafelyDoEverythingClosure // expected-error{{type '(X) -> (@MainActor @Sendable () -> Void) -> ()'}} let _: Int = (X.unsafelyDoEverythingClosure)(x) // expected-error{{type '(@MainActor @Sendable () -> Void) -> ()'}} let _: Int = x.sendableVar // expected-error{{type '@Sendable () -> Void'}} let _: Int = x.mainActorVar // expected-error{{type '@MainActor () -> Void'}} let _: Int = x[{ onMainActor() }] // expected-error{{type '@Sendable () -> Void'}} let _: Int = X[statically: { onMainActor() }] // expected-error{{type '@Sendable () -> Void'}} } @MainActor @preconcurrency func onMainActorAlways() { } // expected-note@-1{{are implicitly asynchronous}} @preconcurrency @MainActor class MyModelClass { // expected-note@-1{{are implicitly asynchronous}} func f() { } // expected-note@-1{{are implicitly asynchronous}} } func testCalls(x: X) { // expected-note@-1 3{{add '@MainActor' to make global function 'testCalls(x:)' part of global actor 'MainActor'}} onMainActorAlways() // expected-error{{call to main actor-isolated global function 'onMainActorAlways()' in a synchronous nonisolated context}} let _: () -> Void = onMainActorAlways // expected-error{{converting function value of type '@MainActor () -> ()' to '() -> Void' loses global actor 'MainActor'}} let c = MyModelClass() // expected-error{{call to main actor-isolated initializer 'init()' in a synchronous nonisolated context}} c.f() // expected-error{{call to main actor-isolated instance method 'f()' in a synchronous nonisolated context}} } func testCallsWithAsync() async { onMainActorAlways() // expected-error{{expression is 'async' but is not marked with 'await'}} // expected-note@-1{{calls to global function 'onMainActorAlways()' from outside of its actor context are implicitly asynchronous}} let _: () -> Void = onMainActorAlways // expected-error{{converting function value of type '@MainActor () -> ()' to '() -> Void' loses global actor 'MainActor'}} let c = MyModelClass() // expected-error{{expression is 'async' but is not marked with 'await'}} // expected-note@-1{{calls to initializer 'init()' from outside of its actor context are implicitly asynchronous}} c.f() // expected-error{{expression is 'async' but is not marked with 'await'}} // expected-note@-1{{calls to instance method 'f()' from outside of its actor context are implicitly asynchronous}} } // --------------------------------------------------------------------------- // Protocols that inherit Sendable and predate concurrency. // --------------------------------------------------------------------------- @preconcurrency protocol P: Sendable { } protocol Q: P { } class NS { } // expected-note 3{{class 'NS' does not conform to the 'Sendable' protocol}} struct S1: P { var ns: NS // expected-error{{stored property 'ns' of 'Sendable'-conforming struct 'S1' has non-sendable type 'NS'}} } struct S2: Q { var ns: NS // expected-error{{stored property 'ns' of 'Sendable'-conforming struct 'S2' has non-sendable type 'NS'}} } struct S3: Q, Sendable { var ns: NS // expected-error{{stored property 'ns' of 'Sendable'-conforming struct 'S3' has non-sendable type 'NS'}} } // --------------------------------------------------------------------------- // Historical attribute names do nothing (but are permitted) // --------------------------------------------------------------------------- func aFailedExperiment(@_unsafeSendable _ body: @escaping () -> Void) { } // expected-warning@-1{{'_unsafeSendable' attribute has been removed in favor of @preconcurrency}} func anothingFailedExperiment(@_unsafeMainActor _ body: @escaping () -> Void) { } // expected-warning@-1{{'_unsafeMainActor' attribute has been removed in favor of @preconcurrency}}
00bfad7209eef0865a2f3e58b628097f
52.666667
163
0.639752
false
false
false
false
SteveBarnegren/SwiftChess
refs/heads/master
SwiftChess/Source/BoardRaterCenterDominance.swift
mit
1
// // BoardRaterCenterDominance.swift // SwiftChess // // Created by Steve Barnegren on 13/12/2016. // Copyright © 2016 Steve Barnegren. All rights reserved. // import Foundation /* Rates the board according to which player's pieces are able to move to the squares at the center of the board */ class BoardRaterCenterDominance: BoardRater { override func ratingFor(board: Board, color: Color) -> Double { var rating = Double(0) for sourceLocation in BoardLocation.all { guard let piece = board.getPiece(at: sourceLocation) else { continue } for targetLocation in BoardLocation.all { if sourceLocation == targetLocation || piece.movement.canPieceMove(from: sourceLocation, to: targetLocation, board: board) { let value = dominanceValueFor(location: targetLocation) rating += (piece.color == color) ? value : -value } } } return rating * configuration.boardRaterCenterDominanceWeighting.value } func dominanceValueFor(location: BoardLocation) -> Double { let axisMiddle = 3.5 let x = Double(location.x) let y = Double(location.y) let xDiff = abs(axisMiddle - x) let yDiff = abs(axisMiddle - y) let distance = sqrt((xDiff*xDiff)+(yDiff*yDiff)) return axisMiddle - distance } }
9d100aad21d1eef0e7969b2d09a6aea2
28.206897
110
0.527155
false
false
false
false
avito-tech/Marshroute
refs/heads/master
Marshroute/Sources/Transitions/TransitionContexts/WeakTransitionsHandlerBox.swift
mit
1
public enum WeakTransitionsHandlerBox { case animating(WeakBox<AnimatingTransitionsHandler>) case containing(WeakBox<ContainingTransitionsHandler>) // MARK: - Init public init(transitionsHandlerBox: TransitionsHandlerBox) { switch transitionsHandlerBox { case .animating(let strongBox): let animatingTransitionsHandler = strongBox.unbox() self = .init(animatingTransitionsHandler: animatingTransitionsHandler) case .containing(let strongBox): let containingTransitionsHandler = strongBox.unbox() self = .init(containingTransitionsHandler: containingTransitionsHandler) } } public init(animatingTransitionsHandler: AnimatingTransitionsHandler) { self = .animating(WeakBox(animatingTransitionsHandler)) } public init(containingTransitionsHandler: ContainingTransitionsHandler) { self = .containing(WeakBox(containingTransitionsHandler)) } // MARK: - Public public func unbox() -> TransitionsHandler? { switch self { case .animating(let animatingTransitionsHandlerBox): return animatingTransitionsHandlerBox.unbox() case .containing(let containingTransitionsHandlerBox): return containingTransitionsHandlerBox.unbox() } } } public extension WeakTransitionsHandlerBox { func transitionsHandlerBox() -> TransitionsHandlerBox? { switch self { case .animating(let animatingTransitionsHandlerBox): if let animatingTransitionsHandler = animatingTransitionsHandlerBox.unbox() { return TransitionsHandlerBox(animatingTransitionsHandler: animatingTransitionsHandler) } case .containing(let containingTransitionsHandlerBox): if let containingTransitionsHandler = containingTransitionsHandlerBox.unbox() { return TransitionsHandlerBox(containingTransitionsHandler: containingTransitionsHandler) } } return nil } } public extension TransitionsHandlerBox { func weakTransitionsHandlerBox() -> WeakTransitionsHandlerBox { switch self { case .animating(let animatingTransitionsHandlerBox): return WeakTransitionsHandlerBox(animatingTransitionsHandler: animatingTransitionsHandlerBox.unbox()) case .containing(let containingTransitionsHandlerBox): return WeakTransitionsHandlerBox(containingTransitionsHandler: containingTransitionsHandlerBox.unbox()) } } }
1cd04c3de46fe99ab1ab0c2cabea03b2
38.074627
115
0.695569
false
false
false
false
grpc/grpc-swift
refs/heads/main
Tests/GRPCTests/LazyEventLoopPromiseTests.swift
apache-2.0
1
/* * Copyright 2020, gRPC Authors All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @testable import GRPC import NIOCore import NIOEmbedded import XCTest class LazyEventLoopPromiseTests: GRPCTestCase { func testGetFutureAfterSuccess() { let loop = EmbeddedEventLoop() var promise = loop.makeLazyPromise(of: String.self) promise.succeed("foo") XCTAssertEqual(try promise.getFutureResult().wait(), "foo") } func testGetFutureBeforeSuccess() { let loop = EmbeddedEventLoop() var promise = loop.makeLazyPromise(of: String.self) let future = promise.getFutureResult() promise.succeed("foo") XCTAssertEqual(try future.wait(), "foo") } func testGetFutureAfterError() { let loop = EmbeddedEventLoop() var promise = loop.makeLazyPromise(of: String.self) promise.fail(GRPCStatus.processingError) XCTAssertThrowsError(try promise.getFutureResult().wait()) { error in XCTAssertTrue(error is GRPCStatus) } } func testGetFutureBeforeError() { let loop = EmbeddedEventLoop() var promise = loop.makeLazyPromise(of: String.self) let future = promise.getFutureResult() promise.fail(GRPCStatus.processingError) XCTAssertThrowsError(try future.wait()) { error in XCTAssertTrue(error is GRPCStatus) } } func testGetFutureMultipleTimes() { let loop = EmbeddedEventLoop() var promise = loop.makeLazyPromise(of: String.self) let f1 = promise.getFutureResult() let f2 = promise.getFutureResult() promise.succeed("foo") XCTAssertEqual(try f1.wait(), try f2.wait()) } func testMultipleResolutionsIgnored() { let loop = EmbeddedEventLoop() var promise = loop.makeLazyPromise(of: String.self) promise.succeed("foo") XCTAssertEqual(try promise.getFutureResult().wait(), "foo") promise.succeed("bar") XCTAssertEqual(try promise.getFutureResult().wait(), "foo") promise.fail(GRPCStatus.processingError) XCTAssertEqual(try promise.getFutureResult().wait(), "foo") } func testNoFuture() { let loop = EmbeddedEventLoop() var promise = loop.makeLazyPromise(of: String.self) promise.succeed("foo") } }
5aa2c003e84427475ddfb1b2a5f6bd5c
31.107143
75
0.717835
false
true
false
false
filmhomage/swift_tutorial
refs/heads/master
swift_tutorial/Util/SWProgress.swift
mit
1
// // SWProgress.swift // swift_tutorial // // Created by JonghyunKim on 5/18/16. // Copyright © 2016 kokaru.com. All rights reserved. // import Foundation import UIKit import MBProgressHUD class SWProgress : NSObject { static let sharedInstance = SWProgress() override init() { print("SWProgress init!") } func showProgress() { self.hideProgress() let hud = MBProgressHUD.showHUDAddedTo(UIApplication.topViewController()!.view, animated: true) hud.mode = MBProgressHUDMode.Indeterminate hud.color = colorOrange hud.alpha = 0.95 hud.minSize = CGSize(width: 100.0, height:100.0) } func showProgress(labelText : String?) { self.hideProgress() let hud = MBProgressHUD.showHUDAddedTo(UIApplication.topViewController()!.view, animated: true) hud.mode = MBProgressHUDMode.Indeterminate hud.color = colorOrange hud.alpha = 0.95 hud.minSize = CGSize(width: 100.0, height:100.0) hud.labelText = labelText } func showProgress(labelText: String?, mode: MBProgressHUDMode = MBProgressHUDMode.Indeterminate, alpha: CGFloat = 0.95, color: UIColor = UIColor.redColor(), backgroundColor: UIColor, minsize: CGSize = CGSize(width: 100.0, height: 100.0)) { self.hideProgress() let hud = MBProgressHUD.showHUDAddedTo(UIApplication.topViewController()!.view, animated: true) hud.mode = mode hud.color = color hud.alpha = alpha hud.minSize = minsize hud.labelText = labelText } func hideProgress () { MBProgressHUD .hideHUDForView(UIApplication.topViewController()!.view, animated: true) } }
46e9540d8dfb0295560d67ce7108e571
30.220339
103
0.614883
false
false
false
false
cctao/UIViewFrame-Swift-
refs/heads/master
UIView+Frame/UIView+Frame.swift
mit
1
// // UIView+Frame.swift // UIView+Frame // // Created by cctao on 15/3/7. // Copyright (c) 2015年 cctao. All rights reserved. // import UIKit extension UIView { var x :CGFloat{ set{ var rect = self.frame as CGRect rect.origin.x = newValue self.frame = rect } get{ return self.frame.origin.y } } var y :CGFloat { set{ var rect = self.frame rect.origin.y = newValue self.frame = rect } get{ return self.frame.origin.y } } var width:CGFloat { set{ var rect = self.frame rect.size.width = newValue self.frame = rect } get{ return self.frame.size.width } } var height:CGFloat { set{ var rect = self.frame rect.size.height = newValue self.frame = rect } get{ return self.frame.size.height } } var centerX:CGFloat { set{ var center = self.center center.x = newValue self.center = center } get{ return self.center.x } } var centerY:CGFloat { set{ var center = self.center center.y = newValue self.center = center } get{ return self.center.y } } }
a645fd01f25e57cd57b52141cb167619
14.416667
51
0.449324
false
false
false
false
prosperence/prosperence-ios
refs/heads/master
Prosperance/Prosperance/AddProfileViewController.swift
mit
1
import UIKit class AddProfileViewController: UIViewController { @IBOutlet weak var profileNameTextField: UITextField! @IBOutlet weak var usernameTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var rememberPasswordSwitch: UISwitch! var simpleProfile = SimpleProfile() @IBAction func handleUIUpdate(sender: AnyObject) { simpleProfile.profileName = profileNameTextField.text simpleProfile.username = usernameTextField.text simpleProfile.password = passwordTextField.text simpleProfile.rememberPassword = rememberPasswordSwitch.on == true ? 1 : 0 } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if(segue.identifier == "saveProfile") { var mvc = segue.destinationViewController as! MasterViewController mvc.newProfile = simpleProfile; } } }
15db6ab9c51693ee6ad2a9483fdbe375
29.71875
83
0.682281
false
false
false
false
ziyincody/MTablesView
refs/heads/master
MTablesView/Classes/extensions.swift
mit
1
// // extensions.swift // Pods // // Created by Ziyin Wang on 2017-02-18. // // import UIKit extension UIView { @available(iOS 9.0, *) func anchor(_ top:NSLayoutYAxisAnchor? = nil, left:NSLayoutXAxisAnchor? = nil, bottom:NSLayoutYAxisAnchor? = nil, right:NSLayoutXAxisAnchor? = nil, topConstant:CGFloat = 0, leftConstant:CGFloat = 0, bottomConstant:CGFloat = 0, rightConstant:CGFloat = 0, widthConstant:CGFloat = 0, heightConstant:CGFloat = 0) -> [NSLayoutConstraint] { translatesAutoresizingMaskIntoConstraints = false var anchors = [NSLayoutConstraint]() if let top = top { anchors.append(topAnchor.constraint(equalTo: top,constant: topConstant)) } if let bottom = bottom { anchors.append(bottomAnchor.constraint(equalTo: bottom,constant: bottomConstant)) } if let left = left { anchors.append(leftAnchor.constraint(equalTo: left,constant: leftConstant)) } if let right = right { anchors.append(rightAnchor.constraint(equalTo: right,constant: -rightConstant)) } if widthConstant > 0 { anchors.append(widthAnchor.constraint(equalToConstant: widthConstant)) } if heightConstant > 0 { anchors.append(heightAnchor.constraint(equalToConstant: heightConstant)) } anchors.forEach({$0.isActive = true}) return anchors } }
bb23217f03c583ae146ac6397713dade
30.833333
338
0.61322
false
false
false
false
metova/MetovaTestKit
refs/heads/develop
MetovaTestKitTests/TestingUtilities/MTKBaseTestCase.swift
mit
1
// // BaseTestCase.swift // MetovaTestKit // // Created by Nick Griffith on 7/30/16. // Copyright © 2016 Metova. All rights reserved. // // MIT License // // 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. // /* This base test class allows us to verify that the various assertions we're creating through MTK actually throw failures. The current implementation just allows one failed test per `expectTestFailure` block. We can potentially modify this in the future, but I think for now, the expectation should be that tests are written expecting just one failure. Any assertion failures after the first will fail as normal. The idea for this implementation came from an answer received on this Stack Overflow question: http://stackoverflow.com/q/38675192/2792531 */ import XCTest class MTKBaseTestCase: XCTestCase { // MARK: Properties var testWindow = UIWindow(frame: UIScreen.main.bounds) private var expectingFailure: TestFailureExpectation? private var descriptionForUnexpectedFailure: String? // MARK: Setup/Teardown override func setUp() { super.setUp() testWindow = UIWindow(frame: UIScreen.main.bounds) } // MARK: Failure Expectations override func recordFailure(withDescription description: String, inFile filePath: String, atLine lineNumber: Int, expected: Bool) { guard let expectedFailure = expectingFailure, expected else { super.recordFailure(withDescription: description, inFile: filePath, atLine: lineNumber, expected: expected) return } var descriptionsForUnexpectedFailures = [String]() if case .mismatch(let failureReason) = expectedFailure.verifyDescription(description) { descriptionsForUnexpectedFailures.append(failureReason) } if case .mismatch(let failureReason) = expectedFailure.verifyFilePath(filePath) { descriptionsForUnexpectedFailures.append(failureReason) } if case .mismatch(let failureReason) = expectedFailure.verifyLineNumber(lineNumber) { descriptionsForUnexpectedFailures.append(failureReason) } if descriptionsForUnexpectedFailures.isEmpty { expectingFailure = nil } else { descriptionForUnexpectedFailure = descriptionsForUnexpectedFailures.joined(separator: " ") super.recordFailure(withDescription: description, inFile: filePath, atLine: lineNumber, expected: true) } } func expectTestFailure(_ failure: TestFailureExpectation = BasicTestFailureExpectation(), message: @autoclosure () -> String? = nil, file: StaticString = #file, line: UInt = #line, inBlock testBlock: () -> Void) { expectingFailure = failure testBlock() if expectingFailure != nil { expectingFailure = nil let message = [message(), descriptionForUnexpectedFailure].compactMap({ $0 }).joined(separator: " ") descriptionForUnexpectedFailure = nil XCTFail(message, file: file, line: line) } } }
c656f722ca014fdb0051d72f69410f48
40.792079
411
0.697702
false
true
false
false
gb-6k-house/YsSwift
refs/heads/master
Sources/Animal/String+YS.swift
mit
1
/****************************************************************************** ** auth: liukai ** date: 2017/7 ** ver : 1.0 ** desc: String 相关的扩展功能 ** Copyright © 2017年 尧尚信息科技(www.yourshares.cn). All rights reserved ******************************************************************************/ import Foundation public class YSStringCompatible { public let base: String public init(_ base: String) { self.base = base } } public extension String { public var ys: YSStringCompatible { return YSStringCompatible(self) } } extension YSStringCompatible { public func trim() -> String { return self.base.trimmingCharacters(in: CharacterSet.whitespaces) } public func double() -> Double { let charset = CharacterSet(charactersIn: ",+%") let string = self.base.trimmingCharacters(in: charset).replacingOccurrences(of: ",", with: "") guard let double = Double(string) else { return 0 } return double } public func matches(_ regex: String!) -> [String] { do { let regex = try NSRegularExpression(pattern: regex, options: []) let nsString = self.base as NSString let results = regex.matches(in: self.base, options: [], range: NSMakeRange(0, nsString.length)) return results.map { nsString.substring(with: $0.range) } } catch let error as NSError { print("invalid regex: \(error.localizedDescription)") return [] } } }
c2a03860a3274bc6d4767a700eea44a0
28.611111
102
0.527205
false
false
false
false
victorchee/DynamicAnimator
refs/heads/master
DynamicAnimator/DynamicAnimator/PendulumBehavior.swift
mit
1
// // PendulumBehavior.swift // DynamicAnimator // // Created by qihaijun on 12/24/15. // Copyright © 2015 VictorChee. All rights reserved. // import UIKit class PendulumBehavior: UIDynamicBehavior { private var draggingBehavior: UIAttachmentBehavior! private var pushBehavior: UIPushBehavior! convenience init(item: UIDynamicItem, suspendedFromPoint point: CGPoint) { self.init() let gravityBehavior = UIGravityBehavior(items: [item]) let attachmentBehavior = UIAttachmentBehavior(item: item, attachedToAnchor: point) draggingBehavior = UIAttachmentBehavior(item: item, attachedToAnchor: CGPoint.zero) pushBehavior = UIPushBehavior(items: [item], mode: .instantaneous) pushBehavior.active = false addChildBehavior(gravityBehavior) addChildBehavior(attachmentBehavior) addChildBehavior(pushBehavior) } func beginDraggingWeightAtPoint(point: CGPoint) { draggingBehavior.anchorPoint = point addChildBehavior(draggingBehavior) } func dragWeightToPoint(point: CGPoint) { draggingBehavior.anchorPoint = point } func endDraggingWeightWithVelocity(velocity: CGPoint) { var magnitude = sqrt(pow(velocity.x, 2.0) + pow(velocity.y, 2.0)) let angle = atan2(velocity.y, velocity.x) magnitude /= 100.0 pushBehavior.angle = angle pushBehavior.magnitude = magnitude pushBehavior.active = true removeChildBehavior(draggingBehavior) } }
afbccf452bba83de41145a6d497fe444
30.66
91
0.676563
false
false
false
false
ThornTechPublic/InteractiveSlideOutMenu
refs/heads/master
InteractiveSlideoutMenu/PresentMenuAnimator.swift
mit
1
// // PresentMenuAnimator.swift // InteractiveSlideoutMenu // // Created by Robert Chen on 2/7/16. // // Copyright (c) 2016 Thorn Technologies LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit class PresentMenuAnimator : NSObject { } extension PresentMenuAnimator : UIViewControllerAnimatedTransitioning { func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.6 } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { guard let fromVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from), let toVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) else { return } let containerView = transitionContext.containerView containerView.insertSubview(toVC.view, belowSubview: fromVC.view) // replace main view with snapshot if let snapshot = fromVC.view.snapshotView(afterScreenUpdates: false) { snapshot.tag = MenuHelper.snapshotNumber snapshot.isUserInteractionEnabled = false snapshot.layer.shadowOpacity = 0.7 containerView.insertSubview(snapshot, aboveSubview: toVC.view) fromVC.view.isHidden = true UIView.animate( withDuration: transitionDuration(using: transitionContext), animations: { snapshot.center.x += UIScreen.main.bounds.width * MenuHelper.menuWidth }, completion: { _ in fromVC.view.isHidden = false transitionContext.completeTransition(!transitionContext.transitionWasCancelled) } ) } } }
ae0a30c9b2efac59ac4f6bbbca78e734
41.852941
109
0.688401
false
false
false
false
SunLiner/Floral
refs/heads/master
Floral/Floral/Classes/Malls/Malls/View/View/MallFlowLayout.swift
mit
1
// // MallFlowLayout.swift // Floral // // Created by 孙林 on 16/5/15. // Copyright © 2016年 ALin. All rights reserved. // import UIKit class MallFlowLayout: UICollectionViewFlowLayout { override func prepareLayout() { super.prepareLayout() // 基本设置 minimumLineSpacing = 1 minimumInteritemSpacing = 1 scrollDirection = .Vertical let width = (ScreenWidth - 2) / 2.0 itemSize = CGSize(width: width, height: width) // 即使界面内容没有超过界面大小,也要竖直方向滑动 // collectionView?.alwaysBounceVertical = true collectionView?.backgroundColor = UIColor.whiteColor() } }
71d0f2d16964559e3da3dc1ce910bcd5
23.769231
62
0.636646
false
false
false
false
gu704823/huobanyun
refs/heads/master
DemoSocketIO/Utils/Spring/DesignableTextView.swift
gpl-3.0
4
// The MIT License (MIT) // // Copyright (c) 2015 Meng To ([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. import UIKit @IBDesignable public class DesignableTextView: SpringTextView { @IBInspectable public var borderColor: UIColor = UIColor.clear { didSet { layer.borderColor = borderColor.cgColor } } @IBInspectable public var borderWidth: CGFloat = 0 { didSet { layer.borderWidth = borderWidth } } @IBInspectable public var cornerRadius: CGFloat = 0 { didSet { layer.cornerRadius = cornerRadius } } @IBInspectable public var lineHeight: CGFloat = 1.5 { didSet { let font = UIFont(name: self.font!.fontName, size: self.font!.pointSize) let text = self.text let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineSpacing = lineHeight let attributedString = NSMutableAttributedString(string: text!) attributedString.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: NSRange(location: 0, length: attributedString.length)) attributedString.addAttribute(NSFontAttributeName, value: font!, range: NSRange(location: 0, length: attributedString.length)) self.attributedText = attributedString } } }
79e2ef733f946f98e628021339ddc93d
39.131148
157
0.69281
false
false
false
false
ranesr/SwiftIcons
refs/heads/master
SwiftIconsApp/IconsViewController.swift
mit
1
// The MIT License (MIT) // // Copyright © 2017 Saurabh Rane // // 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 SwiftIcons private let reuseIdentifier = "fontIcons" class IconsViewController: UICollectionViewController { var index: Int! var iconColors = ["e74c3c", "e67e22", "f1c40f", "2ecc71", "1abc9c", "3498db", "9b59b6", "e4Accf", "95a5a6", "34495e", "6c6998", "00695C"] var fonts = ["DRIPICONS", "EMOJI", "FONT-AWESOME-REGULAR", "ICO FONT", "IONICONS", "LINEARICONS", "MAP-ICONS", "MATERIAL ICONS", "OPEN ICONIC", "STATE FACE", "WEATHER ICONS", "TYPICONS"] override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Do any additional setup after loading the view. let color = UIColor.init(hex: iconColors[index]) let font = UIFont(name: "AppleSDGothicNeo-Bold", size: 20) let attributes = [NSAttributedString.Key.font: font!, NSAttributedString.Key.foregroundColor: color] navigationController?.navigationBar.titleTextAttributes = attributes navigationItem.title = fonts[index] navigationItem.leftBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: self, action: #selector(goBack(sender:))) navigationItem.leftBarButtonItem?.setIcon(icon: .fontAwesomeSolid(.longArrowAltLeft), iconSize: 30, color: color) let screenSize = UIScreen.main.bounds let screenWidth = screenSize.width var spacing: CGFloat if screenWidth == 320 { spacing = 70/6 } else if screenWidth == 375 { spacing = 75/7 } else if screenWidth == 414 { spacing = 114/8 } else { spacing = 5 } let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout() layout.sectionInset = UIEdgeInsets(top: spacing, left: spacing, bottom: spacing, right: spacing) layout.itemSize = CGSize(width: 50, height: 50) layout.minimumInteritemSpacing = spacing layout.minimumLineSpacing = spacing collectionView!.collectionViewLayout = layout } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Navigation @objc func goBack(sender: UIBarButtonItem) { _ = navigationController?.popViewController(animated: true) } /* // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ // MARK: UICollectionViewDataSource override func numberOfSections(in collectionView: UICollectionView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of items var count = 0 switch index! { case 0: count = DripiconType.count case 1: count = EmojiType.count case 2: count = FARegularType.count case 3: count = IcofontType.count case 4: count = IoniconsType.count case 5: count = LinearIconType.count case 6: count = MapiconsType.count case 7: count = GoogleMaterialDesignType.count case 8: count = OpenIconicType.count case 9: count = StatefaceType.count case 10: count = WeatherType.count case 11: count = TypIconsType.count default: break } return count } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) // Configure the cell let imgView = cell.viewWithTag(1) as! UIImageView let color = UIColor.init(hex: iconColors[index!]) switch index! { case 0: let icon: DripiconType = DripiconType(rawValue: indexPath.row)! imgView.setIcon(icon: .dripicon(icon), textColor: color, backgroundColor: .clear, size: nil) case 1: let icon: EmojiType = EmojiType(rawValue: indexPath.row)! imgView.setIcon(icon: .emoji(icon), textColor: color, backgroundColor: .clear, size: nil) case 2: let icon: FARegularType = FARegularType(rawValue: indexPath.row)! imgView.setIcon(icon: .fontAwesomeRegular(icon), textColor: color, backgroundColor: .clear, size: nil) case 3: let icon: IcofontType = IcofontType(rawValue: indexPath.row)! imgView.setIcon(icon: .icofont(icon), textColor: color, backgroundColor: .clear, size: nil) case 4: let icon: IoniconsType = IoniconsType(rawValue: indexPath.row)! imgView.setIcon(icon: .ionicons(icon), textColor: color, backgroundColor: .clear, size: nil) case 5: let icon: LinearIconType = LinearIconType(rawValue: indexPath.row)! imgView.setIcon(icon: .linearIcons(icon), textColor: color, backgroundColor: .clear, size: nil) case 6: let icon: MapiconsType = MapiconsType(rawValue: indexPath.row)! imgView.setIcon(icon: .mapicons(icon), textColor: color, backgroundColor: .clear, size: nil) case 7: let icon: GoogleMaterialDesignType = GoogleMaterialDesignType(rawValue: indexPath.row)! imgView.setIcon(icon: .googleMaterialDesign(icon), textColor: color, backgroundColor: .clear, size: nil) case 8: let icon: OpenIconicType = OpenIconicType(rawValue: indexPath.row)! imgView.setIcon(icon: .openIconic(icon), textColor: color, backgroundColor: .clear, size: nil) case 9: let icon: StatefaceType = StatefaceType(rawValue: indexPath.row)! imgView.setIcon(icon: .state(icon), textColor: color, backgroundColor: .clear, size: nil) case 10: let icon: WeatherType = WeatherType(rawValue: indexPath.row)! imgView.setIcon(icon: .weather(icon), textColor: color, backgroundColor: .clear, size: nil) case 11: let icon: TypIconsType = TypIconsType(rawValue: indexPath.row)! imgView.setIcon(icon: .typIcons(icon), textColor: color, backgroundColor: .clear, size: nil) default: break } return cell } // MARK: - 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. if (segue.identifier == "iconSelectionSegue") { let indexPath = (collectionView?.indexPathsForSelectedItems?[0])! as IndexPath let viewController = segue.destination as! IconDetailViewController viewController.index = index viewController.indexPath = indexPath switch index! { case 0: let icon: DripiconType = DripiconType(rawValue: indexPath.row)! viewController.icon = .dripicon(icon) case 1: let icon: EmojiType = EmojiType(rawValue: indexPath.row)! viewController.icon = .emoji(icon) case 2: let icon: FARegularType = FARegularType(rawValue: indexPath.row)! viewController.icon = .fontAwesomeRegular(icon) case 3: let icon: IcofontType = IcofontType(rawValue: indexPath.row)! viewController.icon = .icofont(icon) case 4: let icon: IoniconsType = IoniconsType(rawValue: indexPath.row)! viewController.icon = .ionicons(icon) case 5: let icon: LinearIconType = LinearIconType(rawValue: indexPath.row)! viewController.icon = .linearIcons(icon) case 6: let icon: MapiconsType = MapiconsType(rawValue: indexPath.row)! viewController.icon = .mapicons(icon) case 7: let icon: GoogleMaterialDesignType = GoogleMaterialDesignType(rawValue: indexPath.row)! viewController.icon = .googleMaterialDesign(icon) case 8: let icon: OpenIconicType = OpenIconicType(rawValue: indexPath.row)! viewController.icon = .openIconic(icon) case 9: let icon: StatefaceType = StatefaceType(rawValue: indexPath.row)! viewController.icon = .state(icon) case 10: let icon: WeatherType = WeatherType(rawValue: indexPath.row)! viewController.icon = .weather(icon) case 11: let icon: TypIconsType = TypIconsType(rawValue: indexPath.row)! viewController.icon = .typIcons(icon) default: break } } } }
b1f8c27aa2fb5b2daa83dd220d60050d
43.267782
190
0.64017
false
false
false
false
Binlogo/One3-iOS-Swift
refs/heads/master
One3-iOS/Controllers/Read/ReadViewController.swift
mit
1
// // ReadViewController.swift // One3-iOS // // Created by Binboy_王兴彬 on 2016/12/29. // Copyright © 2016年 Binboy. All rights reserved. // import UIKit class ReadViewController: BaseViewController { var readObject = "" @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() setupUI() } func setupUI() { tableView.layer.masksToBounds = false; tableView.layer.shadowColor = UIColor(hex: 0x666666).cgColor tableView.layer.shadowRadius = 2; tableView.layer.shadowOffset = CGSize.zero; tableView.layer.shadowOpacity = 0.5; tableView.layer.cornerRadius = 5; } } extension ReadViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 3 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "ReadIntroCellIdentifier") cell?.textLabel?.text = "复杂世界,一个就够了" return cell! } }
9004ab8a4305ed610c6606f3443e24fb
24.148936
100
0.659898
false
false
false
false
KnuffApp/Knuff-iOS
refs/heads/master
Knuff/Views/PushIllustrationView.swift
mit
1
// // UIColorExtensions.swift // Knuff // // Created by Simon Blommegard on 26/03/15. // Copyright (c) 2015 Bowtie. All rights reserved. // import UIKit import pop class PushIllustrationView: UIView { let device: DeviceView let mac, bubble, arrow1, arrow2, arrow3 : UIImageView override init(frame: CGRect) { mac = UIImageView(image: UIImage(named: "Mac")) device = DeviceView() bubble = UIImageView(image: UIImage(named: "Bubble")) arrow1 = UIImageView(image: UIImage(named: "Arrow1")) arrow2 = UIImageView(image: UIImage(named: "Arrow2")) arrow3 = UIImageView(image: UIImage(named: "Arrow3")) super.init(frame: frame) let phone = (UIDevice.current.userInterfaceIdiom == .phone) device.frame.origin = CGPoint( x: 175, y: phone ? 14 : 2 ) bubble.frame.origin = CGPoint( x: phone ? 209 : 229, y: phone ? 0 : -12 ) arrow1.frame.origin = CGPoint(x: 150, y: 34) arrow2.frame.origin = CGPoint(x: 156, y: 31) arrow3.frame.origin = CGPoint(x: 163, y: 28) addSubview(mac) addSubview(device) addSubview(bubble) addSubview(arrow1) addSubview(arrow2) addSubview(arrow3) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func didMoveToSuperview() { super.didMoveToSuperview() if (superview != nil) { startAnimations(0) } else { arrow1.pop_removeAllAnimations() arrow2.pop_removeAllAnimations() arrow3.pop_removeAllAnimations() bubble.pop_removeAllAnimations() device.screenshotView.pop_removeAllAnimations() } } override func sizeThatFits(_ size: CGSize) -> CGSize { return CGSize( width: self.device.frame.maxX, height: self.mac.frame.maxY ) } func startAnimations(_ delay:CFTimeInterval) { animate(arrow1, delay: delay) animate(arrow2, delay: delay + 0.1) animate(arrow3, delay: delay + 0.2) animate(bubble, delay: delay + 0.6) animateScreenshot(delay + 0.6) } func animate(_ view: UIView, delay:CFTimeInterval) { let visibleTime: CFTimeInterval = 2; let hiddenTime: CFTimeInterval = 1; view.alpha = 0 view.transform = CGAffineTransform(scaleX: 0.8, y: 0.8) view.pop_removeAllAnimations() // Appear var alphaAni = POPSpringAnimation(propertyNamed: kPOPViewAlpha) alphaAni?.toValue = 1 alphaAni?.beginTime = delay + CACurrentMediaTime() var scaleAni = POPSpringAnimation(propertyNamed: kPOPViewScaleXY) scaleAni?.toValue = NSValue(cgPoint: CGPoint(x: 1, y: 1)) scaleAni?.beginTime = delay + CACurrentMediaTime() scaleAni?.springBounciness = 15; alphaAni?.completionBlock = { (animation:POPAnimation?, completion:Bool) in // Dissapear alphaAni = POPSpringAnimation(propertyNamed: kPOPViewAlpha) alphaAni?.toValue = 0 alphaAni?.beginTime = CACurrentMediaTime() + visibleTime scaleAni = POPSpringAnimation(propertyNamed: kPOPViewScaleXY) scaleAni?.toValue = NSValue(cgPoint: CGPoint(x: 0.8, y: 0.8)) scaleAni?.beginTime = CACurrentMediaTime() + visibleTime scaleAni?.springBounciness = 15; view.pop_add(alphaAni, forKey: "alpha") view.pop_add(scaleAni, forKey: "scale") // Restart, kind of ugly, but they get out of sync if we dont restart them at the same time if (view == self.bubble) { alphaAni?.completionBlock = { (animation:POPAnimation?, completion:Bool) in self.startAnimations(hiddenTime) } } } view.pop_add(alphaAni, forKey: "alpha") view.pop_add(scaleAni, forKey: "scale") } func animateScreenshot(_ delay: CFTimeInterval) { let visibleTime: CFTimeInterval = 2; device.screenshotView.alpha = 0 device.screenshotView.pop_removeAllAnimations() var alphaAni = POPSpringAnimation(propertyNamed: kPOPViewAlpha) alphaAni?.toValue = 1 alphaAni?.beginTime = delay + CACurrentMediaTime() alphaAni?.completionBlock = { (animation:POPAnimation?, completion:Bool) in alphaAni = POPSpringAnimation(propertyNamed: kPOPViewAlpha) alphaAni?.toValue = 0 alphaAni?.beginTime = CACurrentMediaTime() + visibleTime self.device.screenshotView.pop_add(alphaAni, forKey: nil) } device.screenshotView.pop_add(alphaAni, forKey: nil) } }
35890c8cd9d2af30e12764ac20f6e236
28.892617
97
0.662326
false
false
false
false
nakau1/NerobluCore
refs/heads/master
NerobluCore/NBReflection.swift
apache-2.0
1
// ============================================================================= // NerobluCore // Copyright (C) NeroBlu. All rights reserved. // ============================================================================= import UIKit // MARK: - NBReflection - /// クラスについての処理を行うクラス public class NBReflection { private let target: Any? /// イニシャライザ /// - parameter target: 対象 public init(_ target: Any?) { self.target = target } /// パッケージ名を含めないクラス名を返却する public var shortClassName: String { return self.className(false) } /// パッケージ名を含めたクラス名を返却する public var fullClassName: String { return self.className(true) } /// パッケージ名を返却する public var packageName: String? { let full = self.fullClassName let short = self.shortClassName if full == short { return nil } guard let range = full.rangeOfString(".\(short)") else { return nil } return full.substringToIndex(range.startIndex) } private func className(full: Bool) -> String { if let target = self.target { if let cls = target as? AnyClass { return self.classNameByClass(cls, full) } else if let obj = target as? AnyObject { return self.classNameByClass(obj.dynamicType, full) } else { return self.classNameByClass(nil, full) } } else { return "nil" } } private func classNameByClass(cls: AnyClass?, _ full: Bool) -> String { let unknown = "unknown" guard let cls = cls else { return unknown } let fullName = NSStringFromClass(cls) if full { return fullName } guard let name = fullName.componentsSeparatedByString(".").last else { return unknown } return name } } // MARK: - NSObject拡張 - public extension NSObject { /// パッケージ名を含めないクラス名を返却する public var shortClassName: String { return NBReflection(self).shortClassName } /// パッケージ名を含めたクラス名を返却する public var fullClassName: String { return NBReflection(self).fullClassName } /// パッケージ名を返却する public var packageName: String? { return NBReflection(self).packageName } }
f1a7a0bbce8be0e0c393a55150fcd684
26.406977
82
0.537123
false
false
false
false
penniooi/TestKichen
refs/heads/master
TestKitchen/TestKitchen/classes/cookbook/homePage/CookbookViewController.swift
mit
1
// // CookbookViewController.swift // TestKitchen // // Created by aloha on 16/8/15. // Copyright © 2016年 胡颉禹. All rights reserved. // import UIKit class CookbookViewController: BaseViewController { //食材首页的推荐视图 private var recommentView:CBRecommenView? //首页的食材视图 private var foodView:CBMaterialView? //分类视图 private var categoryView:CBMaterialView? //导航的标题视图 private var segCtrl:KTCSegmentController? //滚动视图 private var scrollerView:UIScrollView? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.creatMyNav() //初始化视图 self.downloadRecommendData() downloadFoodData() downloadCategoryData() creatHomePageView() } //下载食材的数据 func downloadFoodData(){ //methodName=MaterialSubtype&token=&user_id=&version=4.32 let dict = ["methodName":"MaterialSubtype"] let downloader = KTCDownloader() downloader.type = .FoodMaterial downloader.delegate = self downloader.postWithUrlString(kHostUrl, params: dict) } //下载推荐的数据 func downloadRecommendData(){ ////methodName=SceneHome&token=&user_id=&version=4.5 let dict = ["methodName":"SceneHome"] let downloader = KTCDownloader() downloader.delegate = self downloader.postWithUrlString(kHostUrl, params: dict) downloader.type = .Recommend } //下载分类的数据 func downloadCategoryData(){ let dict = ["methodName":"CategoryIndex"] let downloader = KTCDownloader() downloader.delegate = self downloader.type = .Category downloader.postWithUrlString(kHostUrl, params: dict) } func creatHomePageView(){ self.automaticallyAdjustsScrollViewInsets = false //创建一个滚动视图 scrollerView = UIScrollView() scrollerView!.pagingEnabled = true scrollerView?.delegate = self view.addSubview(scrollerView!) scrollerView!.snp_makeConstraints { [weak self] (make) in make.edges.equalTo(self!.view).inset(UIEdgeInsetsMake(64, 0, 49, 0)) } //添加scroller上的容器视图 let containerView = UIView.creatView() scrollerView!.addSubview(containerView) containerView.snp_makeConstraints { (make) in make.edges.equalTo(scrollerView!) make.height.equalTo(scrollerView!.snp_height) } //添加子视图 //推荐 recommentView = CBRecommenView() containerView.addSubview(recommentView!) recommentView?.snp_makeConstraints(closure: { (make) in make.top.bottom.equalTo(containerView) make.width.equalTo(kScreenWidth) make.left.equalTo(containerView) }) //食材 foodView = CBMaterialView() foodView?.backgroundColor = UIColor.cyanColor() containerView.addSubview(foodView!) //约束 foodView?.snp_makeConstraints(closure: { (make) in make.top.bottom.equalTo(containerView) make.width.equalTo(kScreenWidth) make.left.equalTo((recommentView?.snp_right)!) }) //分类 categoryView = CBMaterialView() categoryView?.backgroundColor = UIColor.blueColor() containerView.addSubview(categoryView!) //约束 categoryView?.snp_makeConstraints(closure: { (make) in make.top.bottom.equalTo(containerView) make.width.equalTo(kScreenWidth) make.left.equalTo((foodView?.snp_right)!) }) // containerView.snp_makeConstraints { (make) in make.right.equalTo(categoryView!) } } func creatMyNav(){ //标题位置 segCtrl = KTCSegmentController(frame: CGRectMake(80, 0, kScreenWidth-80*2, 44), titleNames: ["推荐","食材","分类"]) navigationItem.titleView = segCtrl segCtrl?.delegate = self //扫一扫 addNavBtn("saoyisao@2x", target: self, isLeft: true, action: #selector(scanAction)) //搜索 addNavBtn("search@2x", target: self, isLeft: false, action: #selector(searchAction)) } func scanAction(){ } func searchAction(){ } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } //MARK:KTCDownloadDelegate extension CookbookViewController:KTCDownloaderDelegate{ func downloader(downloader: KTCDownloader, didFailWithError error: NSError) { print(error) } func downloader(downloader: KTCDownloader, didFinishWithData data: NSData?) { if downloader.type == .Recommend{ if let jsonData = data{ let model = CBRecommendModel.parseModel(jsonData) dispatch_async(dispatch_get_main_queue(), { [weak self] in self!.recommentView?.model = model }) } }else if downloader.type == .FoodMaterial{ let str = NSString(data: data!, encoding: NSUTF8StringEncoding) print(str!) if let jsonData = data{ let model = CBMaterialModel.parseModelWithData(jsonData) dispatch_async(dispatch_get_main_queue(), { [weak self] in self!.foodView?.model = model }) } }else if downloader.type == .Category{ if let jsonData = data{ let model = CBMaterialModel.parseModelWithData(jsonData) dispatch_async(dispatch_get_main_queue(), { [weak self] in self!.categoryView?.model = model }) } } } } extension CookbookViewController:KTCSegmentControllerDelegate{ func didSelectSegCtrl(segCtrl: KTCSegmentController, atIndex index: Int) { scrollerView?.setContentOffset(CGPointMake(kScreenWidth*CGFloat(index), 0), animated: true) } } extension CookbookViewController:UIScrollViewDelegate{ func scrollViewDidEndDecelerating(scrollView: UIScrollView) { let index = Int((scrollerView?.contentOffset.x)!/(scrollerView?.bounds.width)!) segCtrl?.selectBtnAtIndex(index) } }
78f2970ff2f599256a21b6e2cc09ac3a
26.884921
117
0.59166
false
false
false
false
jbennett/Bugology
refs/heads/master
Bugology/IssuesCoordinator.swift
mit
1
// // IssuesCoordinator.swift // Bugology // // Created by Jonathan Bennett on 2016-01-21. // Copyright © 2016 Jonathan Bennett. All rights reserved. // import UIKit import BugKit import BugUIKit public class IssuesCoordinator { public weak var delegate: IssuesCoordinatorDelegate? let presentationContext: PresentationContext public init(presentationContext: PresentationContext) { self.presentationContext = presentationContext } public func showIssuesForProject(project: Project, client: Client) { let viewController = IssuesViewController() viewController.delegate = self viewController.client = client viewController.project = project presentationContext.showViewController(viewController, sender: self) } } extension IssuesCoordinator: IssuesViewControllerDelegate { public func issuesViewController(viewController: IssuesViewController, didSelectIssue issue: Issue) { delegate?.issuesCoordinator(self, didSelectIssue: issue) } } public protocol IssuesCoordinatorDelegate: class { func issuesCoordinator(issuesCoordinator: IssuesCoordinator, didSelectIssue issue: Issue) }
402a64ff3819418e946253ee97901bf6
23.847826
103
0.785652
false
false
false
false
0gajun/mal
refs/heads/cpp14
swift3/Sources/types.swift
mpl-2.0
14
enum MalError: Error { case Reader(msg: String) case General(msg: String) case MalException(obj: MalVal) } class MutableAtom { var val: MalVal init(val: MalVal) { self.val = val } } enum MalVal { case MalNil case MalTrue case MalFalse case MalInt(Int) case MalFloat(Float) case MalString(String) case MalSymbol(String) case MalList(Array<MalVal>, meta: Array<MalVal>?) case MalVector(Array<MalVal>, meta: Array<MalVal>?) case MalHashMap(Dictionary<String,MalVal>, meta: Array<MalVal>?) // TODO: internal MalVals are wrapped in arrays because otherwise // compiler throws a fault case MalFunc((Array<MalVal>) throws -> MalVal, ast: Array<MalVal>?, env: Env?, params: Array<MalVal>?, macro: Bool, meta: Array<MalVal>?) case MalAtom(MutableAtom) } typealias MV = MalVal // General functions func wraptf(_ a: Bool) -> MalVal { return a ? MV.MalTrue : MV.MalFalse } // equality functions func cmp_seqs(_ a: Array<MalVal>, _ b: Array<MalVal>) -> Bool { if a.count != b.count { return false } var idx = a.startIndex while idx < a.endIndex { if !equal_Q(a[idx], b[idx]) { return false } idx = a.index(after:idx) } return true } func cmp_maps(_ a: Dictionary<String,MalVal>, _ b: Dictionary<String,MalVal>) -> Bool { if a.count != b.count { return false } for (k,v1) in a { if b[k] == nil { return false } if !equal_Q(v1, b[k]!) { return false } } return true } func equal_Q(_ a: MalVal, _ b: MalVal) -> Bool { switch (a, b) { case (MV.MalNil, MV.MalNil): return true case (MV.MalFalse, MV.MalFalse): return true case (MV.MalTrue, MV.MalTrue): return true case (MV.MalInt(let i1), MV.MalInt(let i2)): return i1 == i2 case (MV.MalString(let s1), MV.MalString(let s2)): return s1 == s2 case (MV.MalSymbol(let s1), MV.MalSymbol(let s2)): return s1 == s2 case (MV.MalList(let l1,_), MV.MalList(let l2,_)): return cmp_seqs(l1, l2) case (MV.MalList(let l1,_), MV.MalVector(let l2,_)): return cmp_seqs(l1, l2) case (MV.MalVector(let l1,_), MV.MalList(let l2,_)): return cmp_seqs(l1, l2) case (MV.MalVector(let l1,_), MV.MalVector(let l2,_)): return cmp_seqs(l1, l2) case (MV.MalHashMap(let d1,_), MV.MalHashMap(let d2,_)): return cmp_maps(d1, d2) default: return false } } // list and vector functions func list(_ lst: Array<MalVal>) -> MalVal { return MV.MalList(lst, meta:nil) } func list(_ lst: Array<MalVal>, meta: MalVal) -> MalVal { return MV.MalList(lst, meta:[meta]) } func vector(_ lst: Array<MalVal>) -> MalVal { return MV.MalVector(lst, meta:nil) } func vector(_ lst: Array<MalVal>, meta: MalVal) -> MalVal { return MV.MalVector(lst, meta:[meta]) } // hash-map functions func _assoc(_ src: Dictionary<String,MalVal>, _ mvs: Array<MalVal>) throws -> Dictionary<String,MalVal> { var d = src if mvs.count % 2 != 0 { throw MalError.General(msg: "Odd number of args to assoc_BANG") } var pos = mvs.startIndex while pos < mvs.count { switch (mvs[pos], mvs[pos+1]) { case (MV.MalString(let k), let mv): d[k] = mv default: throw MalError.General(msg: "Invalid _assoc call") } pos += 2 } return d } func _dissoc(_ src: Dictionary<String,MalVal>, _ mvs: Array<MalVal>) throws -> Dictionary<String,MalVal> { var d = src for mv in mvs { switch mv { case MV.MalString(let k): d.removeValue(forKey: k) default: throw MalError.General(msg: "Invalid _dissoc call") } } return d } func hash_map(_ dict: Dictionary<String,MalVal>) -> MalVal { return MV.MalHashMap(dict, meta:nil) } func hash_map(_ dict: Dictionary<String,MalVal>, meta:MalVal) -> MalVal { return MV.MalHashMap(dict, meta:[meta]) } func hash_map(_ arr: Array<MalVal>) throws -> MalVal { let d = Dictionary<String,MalVal>(); return MV.MalHashMap(try _assoc(d, arr), meta:nil) } // function functions func malfunc(_ fn: @escaping (Array<MalVal>) throws -> MalVal) -> MalVal { return MV.MalFunc(fn, ast: nil, env: nil, params: nil, macro: false, meta: nil) } func malfunc(_ fn: @escaping (Array<MalVal>) throws -> MalVal, ast: Array<MalVal>?, env: Env?, params: Array<MalVal>?) -> MalVal { return MV.MalFunc(fn, ast: ast, env: env, params: params, macro: false, meta: nil) } func malfunc(_ fn: @escaping (Array<MalVal>) throws -> MalVal, ast: Array<MalVal>?, env: Env?, params: Array<MalVal>?, macro: Bool, meta: MalVal?) -> MalVal { return MV.MalFunc(fn, ast: ast, env: env, params: params, macro: macro, meta: meta != nil ? [meta!] : nil) } func malfunc(_ fn: @escaping (Array<MalVal>) throws -> MalVal, ast: Array<MalVal>?, env: Env?, params: Array<MalVal>?, macro: Bool, meta: Array<MalVal>?) -> MalVal { return MV.MalFunc(fn, ast: ast, env: env, params: params, macro: macro, meta: meta) } // sequence functions func _rest(_ a: MalVal) throws -> Array<MalVal> { switch a { case MV.MalList(let lst,_): let start = lst.index(after: lst.startIndex) let slc = lst[start..<lst.endIndex] return Array(slc) case MV.MalVector(let lst,_): let start = lst.index(after: lst.startIndex) let slc = lst[start..<lst.endIndex] return Array(slc) default: throw MalError.General(msg: "Invalid rest call") } } func rest(_ a: MalVal) throws -> MalVal { return list(try _rest(a)) } func _nth(_ a: MalVal, _ idx: Int) throws -> MalVal { switch a { case MV.MalList(let l,_): return l[l.startIndex.advanced(by: idx)] case MV.MalVector(let l,_): return l[l.startIndex.advanced(by: idx)] default: throw MalError.General(msg: "Invalid nth call") } }
62fe645bb105c2fcf36ede8cdc2ee9ce
28.386792
74
0.583146
false
false
false
false
peferron/algo
refs/heads/master
EPI/Arrays/Compute a random subset/swift/test.swift
mit
1
// swiftlint:disable variable_name import Darwin let fns = [randomSubsetArray, randomSubsetDictionary] func test(_ fn: (Int, Int) -> [Int] ) { let n = Int(arc4random_uniform(100)) let k = Int(arc4random_uniform(UInt32(n) + 1)) let subset = fn(n, k) guard isValidSubset(subset, n: n, k: k) else { print("For n \(n) and k \(k), got invalid subset \(subset)") exit(1) } } func isValidSubset(_ subset: [Int], n: Int, k: Int) -> Bool { // Verify that subset has the expected count. guard subset.count == k else { return false } // Verify that subset has no duplicates. guard Set(subset).count == k else { return false } // Verify that the elements of subset are in 0..<n. guard !(subset.contains { $0 < 0 && $0 >= n }) else { return false } return true } for fn in fns { for _ in 0...100 { test(fn) } }
bb089ebda24dd0914ccf1005b8c1cb2c
21.512195
68
0.574215
false
false
false
false
programmerC/JNews
refs/heads/master
JNews/InputView.swift
gpl-3.0
1
// // InputView.swift // JNews // // Created by ChenKaijie on 16/8/20. // Copyright © 2016年 com.ckj. All rights reserved. // import UIKit class InputView: UIView { @IBOutlet weak var account: UITextField! @IBOutlet weak var password: UITextField! @IBOutlet weak var loginButton: UIButton! @IBOutlet weak var bgImageView: UIImageView! @IBOutlet weak var accountView: UIView! @IBOutlet weak var passwordView: UIView! @IBOutlet weak var accountIcon: UIImageView! @IBOutlet weak var passwordIcon: UIImageView! init() { super.init(frame: CGRectZero) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func awakeFromNib() { configuration() } func configuration() { // Background Image bgImageView.image = UIImage.drawImage(self.frame, cornerRadius: 8.0, color: UIColor.whiteColor()) // Button Image let buttonImage = UIImage.drawImage(CGRectMake(0, 0, 233, 30), cornerRadius: 5.0, color: UIColor.RGBColor(0, green: 140, blue: 212, alpha: 1)) loginButton.setBackgroundImage(buttonImage, forState: .Normal) // Input Background Border accountView.layer.borderWidth = 1 passwordView.layer.borderWidth = 1 accountView.layer.cornerRadius = 5.0 passwordView.layer.cornerRadius = 5.0 accountView.layer.masksToBounds = true passwordView.layer.masksToBounds = true accountView.layer.borderColor = UIColor.RGBColor(97, green: 97, blue: 97, alpha: 1.0).CGColor passwordView.layer.borderColor = UIColor.RGBColor(97, green: 97, blue: 97, alpha: 1.0).CGColor } } extension InputView { class func instantiateFromNib() -> InputView { return NSBundle.mainBundle().loadNibNamed("InputView", owner: nil, options: nil)![0] as! InputView } }
329b2ac6b0a6c49639431a7806400bee
31.965517
150
0.661611
false
false
false
false
Njko/BlinkingLabel
refs/heads/master
Example/BlinkingLabel/ViewController.swift
mit
1
// // ViewController.swift // BlinkingLabel // // Created by nicolas.linard on 09/21/2015. // Copyright (c) 2015 nicolas.linard. All rights reserved. // import UIKit import BlinkingLabel class ViewController: UIViewController { var isBlinking = false let blinkinLabel = BlinkingLabel(frame: CGRectMake(10, 20, 200, 30)) override func viewDidLoad() { super.viewDidLoad() blinkinLabel.text = "I blink!" blinkinLabel.font = UIFont.systemFontOfSize(20) view.addSubview(blinkinLabel) blinkinLabel.startBlinking() isBlinking = true let toggleButton = UIButton(frame: CGRectMake(10, 60, 125, 30)) toggleButton.setTitle("Toggle Blinking", forState: .Normal) toggleButton.setTitleColor(UIColor.redColor(), forState: .Normal) toggleButton.addTarget(self, action: "toggleBlinking", forControlEvents: .TouchUpInside) view.addSubview(toggleButton) } func toggleBlinking() { if (isBlinking) { blinkinLabel.stopBlinking() } else { blinkinLabel.startBlinking() } isBlinking = !isBlinking } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
fb6189a1dfe0190d2433ba6e39915e41
26.770833
96
0.647412
false
false
false
false
edx/edx-app-ios
refs/heads/master
Source/CourseCardViewModel.swift
apache-2.0
1
// // CourseCardViewModel.swift // edX // // Created by Michael Katz on 8/31/15. // Copyright (c) 2015 edX. All rights reserved. // import Foundation class CourseCardViewModel : NSObject { private let dateText: String private let persistImage: Bool private let wrapTitle: Bool private let course: OEXCourse private init(course: OEXCourse, dateText: String, persistImage: Bool, wrapTitle: Bool = false) { self.dateText = dateText self.persistImage = persistImage self.course = course self.wrapTitle = wrapTitle } var title : String? { return course.name } var courseImageURL: String? { return course.courseImageURL } static func onHome(course: OEXCourse) -> CourseCardViewModel { return CourseCardViewModel(course: course, dateText: course.nextRelevantDate ?? "", persistImage: true, wrapTitle: true) } static func onDashboard(course: OEXCourse) -> CourseCardViewModel { return CourseCardViewModel(course: course, dateText: course.nextRelevantDate ?? "", persistImage: true, wrapTitle: true) } static func onCourseCatalog(course: OEXCourse, wrapTitle: Bool = false) -> CourseCardViewModel { return CourseCardViewModel(course: course, dateText: course.nextRelevantDate ?? "", persistImage: false, wrapTitle: wrapTitle) } static func onCourseOutline(course: OEXCourse) -> CourseCardViewModel { return CourseCardViewModel(course: course, dateText: course.nextRelevantDate ?? "", persistImage: true, wrapTitle: true) } func apply(card : CourseCardView, networkManager: NetworkManager) { card.titleText = title card.dateText = dateText card.course = course if wrapTitle { card.wrapTitleLabel() } let remoteImage : RemoteImage let placeholder = UIImage(named: "placeholderCourseCardImage") if let relativeImageURL = courseImageURL, let imageURL = URL(string: relativeImageURL, relativeTo: networkManager.baseURL) { remoteImage = RemoteImageImpl( url: imageURL.absoluteString, networkManager: networkManager, placeholder: placeholder, persist: persistImage) } else { remoteImage = RemoteImageJustImage(image: placeholder) } card.coverImage = remoteImage } } extension OEXCourse { var nextRelevantDate : String? { // If start date is older than current date if isStartDateOld { if let _ = audit_expiry_date { return formattedAuditExpiryDate } guard let end = end else { return nil } let formattedEndDate = (DateFormatting.format(asMonthDayString: end as NSDate)) ?? "" return isEndDateOld ? Strings.Course.ended(endDate: formattedEndDate) : Strings.Course.ending(endDate: formattedEndDate) } else { // Start date is newer than current date switch start_display_info.type { case .string where start_display_info.displayDate != nil: return Strings.Course.starting(startDate: start_display_info.displayDate!) case .timestamp where start_display_info.date != nil: let formattedStartDate = DateFormatting.format(asMonthDayString: start_display_info.date! as NSDate) return Strings.Course.starting(startDate: formattedStartDate ?? "") case .none, .timestamp, .string: return Strings.Course.starting(startDate: Strings.soon) @unknown default: return "" } } } private var formattedAuditExpiryDate: String { guard let auditExpiry = audit_expiry_date as NSDate? else {return "" } let formattedExpiryDate = (DateFormatting.format(asMonthDayString: auditExpiry)) ?? "" let timeSpan = 30 // number of days if isAuditExpired { let days = auditExpiry.daysAgo() if days < 1 { // showing time for better readability return Strings.Course.Audit.expiredAgo(timeDuaration: auditExpiry.displayDate) } if days <= timeSpan { return Strings.Course.Audit.expiredDaysAgo(days: "\(days)") } else { return Strings.Course.Audit.expiredOn(expiryDate: formattedExpiryDate) } } else { let days = auditExpiry.daysUntil() if days < 1 { return Strings.Course.Audit.expiresIn(timeDuration: remainingTime) } if days <= timeSpan { return Strings.Course.Audit.expiresIn(timeDuration: Strings.Course.Audit.days(days: "\(days)")) } else { return Strings.Course.Audit.expiresOn(expiryDate: formattedExpiryDate) } } } private var remainingTime: String { guard let auditExpiry = audit_expiry_date else { return "" } let calendar = NSCalendar.current let unitFlags = Set<Calendar.Component>([.second,.minute,.hour]) let components = calendar.dateComponents(unitFlags, from: Date(), to: auditExpiry) let hours = components.hour ?? 0 let minutes = components.minute ?? 0 let seconds = components.second ?? 0 if hours >= 1 { return Strings.courseAuditRemainingHours(hours: hours) } if minutes >= 1 { return Strings.courseAuditRemainingMinutes(minutes: minutes) } if seconds >= 1 { return Strings.courseAuditRemainingSeconds(seconds: seconds) } return "" } }
329880b499a9d45824c45cdc99f0a79b
33.810651
134
0.609213
false
false
false
false
lizhenning87/SwiftZhiHu
refs/heads/master
SwiftZhiHu/SwiftZhiHu/ZNHttpRequest.swift
apache-2.0
1
// // ZNHttpRequest.swift // SwiftZhiHu // // Created by lizhenning on 14/10/21. // Copyright (c) 2014年 lizhenning. All rights reserved. // import UIKit import Foundation class ZNHttpRequest: NSObject { override init() { super.init() } class func requestWithURL (urlString:String , completionHandler:(data:AnyObject) -> Void) { var URL = NSURL(string: urlString) var req = NSURLRequest(URL: URL!) var queue = NSOperationQueue () NSURLConnection.sendAsynchronousRequest(req, queue: queue, completionHandler: { response , data , error in if (error != nil) { dispatch_async(dispatch_get_main_queue(), { completionHandler(data: NSNull()) }) }else { let jsonData = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary dispatch_async(dispatch_get_main_queue(), { completionHandler(data:jsonData) }) } }) } }
946aef04e0e15ef723418778ba9bd5ed
25.375
152
0.519747
false
false
false
false
Sadmansamee/quran-ios
refs/heads/master
Pods/GenericDataSources/Sources/GeneralCollectionView.swift
mit
1
// // GeneralCollectionView.swift // GenericDataSource // // Created by Mohamed Afifi on 2/13/16. // Copyright © 2016 mohamede1945. All rights reserved. // import Foundation /** The GeneralCollectionView protocol unifies the interface of the `UICollectionView` and `UITableView` so that similar methods with different names will have the same name now that starts with "ds_" prefix. Besides, `CompositeDataSource` has different implementation that allows children data sources to manipulate the `UICollectionView` and/or `UITableView` as if the children data sources are in the same top level first section even if it's in a different section. */ @objc public protocol GeneralCollectionView: class { /** Represents the underlying scroll view. Use this method if you want to get the `UICollectionView`/`UITableView` itself not a wrapper. So, if you have for example an instance like the following ``` let generalCollectionView: GeneralCollectionView = <...> // Not Recommented, can result crashes if there is a CompositeDataSource. let underlyingTableView = generalCollectionView as! UITableView // Recommended, safer let underlyingTableView = generalCollectionView.ds_scrollView as! UITableView ``` The later can result a crash if the scroll view is a UICollectionView not a UITableView. */ var ds_scrollView: UIScrollView { get } // MARK:- Register, dequeue /** Check documentation of the corresponding methods from `UICollectionView` and `UITableView`. */ @objc(ds_registerNib:forCellWithReuseIdentifier:) func ds_register(_ nib: UINib?, forCellWithReuseIdentifier identifier: String) /** Check documentation of the corresponding methods from `UICollectionView` and `UITableView`. */ @objc(ds_registerClass:forCellWithReuseIdentifier:) func ds_register(_ cellClass: AnyClass?, forCellWithReuseIdentifier identifier: String) /** Check documentation of the corresponding methods from `UICollectionView` and `UITableView`. */ func ds_dequeueReusableCell(withIdentifier identifier: String, for indexPath: IndexPath) -> ReusableCell // MARK:- Numbers /** Check documentation of the corresponding methods from `UICollectionView` and `UITableView`. */ func ds_numberOfSections() -> Int /** Check documentation of the corresponding methods from `UICollectionView` and `UITableView`. */ func ds_numberOfItems(inSection section: Int) -> Int // MARK:- Manpulate items and sections /** Check documentation of the corresponding methods from `UICollectionView` and `UITableView`. */ func ds_reloadData() /** Check documentation of the corresponding methods from `UICollectionView` and `UITableView`. */ func ds_performBatchUpdates(_ updates: (() -> Void)?, completion: ((Bool) -> Void)?) /** Check documentation of the corresponding methods from `UICollectionView` and `UITableView`. */ func ds_insertSections(_ sections: IndexSet, with animation: UITableViewRowAnimation) /** Check documentation of the corresponding methods from `UICollectionView` and `UITableView`. */ func ds_deleteSections(_ sections: IndexSet, with animation: UITableViewRowAnimation) /** Check documentation of the corresponding methods from `UICollectionView` and `UITableView`. */ func ds_reloadSections(_ sections: IndexSet, with animation: UITableViewRowAnimation) /** Check documentation of the corresponding methods from `UICollectionView` and `UITableView`. */ func ds_moveSection(_ section: Int, toSection newSection: Int) /** Check documentation of the corresponding methods from `UICollectionView` and `UITableView`. */ func ds_insertItems(at indexPaths: [IndexPath], with animation: UITableViewRowAnimation) /** Check documentation of the corresponding methods from `UICollectionView` and `UITableView`. */ func ds_deleteItems(at indexPaths: [IndexPath], with animation: UITableViewRowAnimation) /** Check documentation of the corresponding methods from `UICollectionView` and `UITableView`. */ func ds_reloadItems(at indexPaths: [IndexPath], with animation: UITableViewRowAnimation) /** Check documentation of the corresponding methods from `UICollectionView` and `UITableView`. */ func ds_moveItem(at indexPath: IndexPath, to newIndexPath: IndexPath) // MARK:- Scroll /** Check documentation of the corresponding methods from `UICollectionView` and `UITableView`. */ func ds_scrollToItem(at indexPath: IndexPath, at scrollPosition: UICollectionViewScrollPosition, animated: Bool) // MARK:- Select/Deselect /** Check documentation of the corresponding methods from `UICollectionView` and `UITableView`. */ func ds_selectItem(at indexPath: IndexPath?, animated: Bool, scrollPosition: UICollectionViewScrollPosition) func ds_deselectItem(at indexPath: IndexPath, animated: Bool) // MARK:- IndexPaths, Cells /** Check documentation of the corresponding methods from `UICollectionView` and `UITableView`. */ func ds_indexPath(for cell: ReusableCell) -> IndexPath? /** Check documentation of the corresponding methods from `UICollectionView` and `UITableView`. */ func ds_indexPathForItem(at point: CGPoint) -> IndexPath? /** Check documentation of the corresponding methods from `UICollectionView` and `UITableView`. */ func ds_indexPathsForVisibleItems() -> [IndexPath] /** Check documentation of the corresponding methods from `UICollectionView` and `UITableView`. */ func ds_indexPathsForSelectedItems() -> [IndexPath] /** Check documentation of the corresponding methods from `UICollectionView` and `UITableView`. */ func ds_visibleCells() -> [ReusableCell] /** Check documentation of the corresponding methods from `UICollectionView` and `UITableView`. */ func ds_cellForItem(at indexPath: IndexPath) -> ReusableCell? // MARK: - Local, Global /** Converts an index path value relative to the composite data source to an index path value relative to a specific data source. - parameter indexPath: The index path relative to the compsite data source. - returns: The global index path relative to the composite data source. */ func ds_localIndexPathForGlobalIndexPath(_ globalIndex: IndexPath) -> IndexPath /** Converts an index path value relative to a specific data source to an index path value relative to the composite data source. - parameter indexPath: The local index path relative to the passed data source. - returns: The global index path relative to the composite data source. */ func ds_globalIndexPathForLocalIndexPath(_ localIndex: IndexPath) -> IndexPath /** Converts a section value relative to a specific data source to a section value relative to the composite data source. - parameter section: The local section relative to the passed data source. - returns: The global section relative to the composite data source. */ func ds_globalSectionForLocalSection(_ localSection: Int) -> Int } extension GeneralCollectionView { func ds_localIndexPathsForGlobalIndexPaths(_ globalIndexPaths: [IndexPath]) -> [IndexPath] { return globalIndexPaths.map { ds_localIndexPathForGlobalIndexPath($0) } } func ds_globalIndexPathsForLocalIndexPaths(_ localIndexPaths: [IndexPath]) -> [IndexPath] { return localIndexPaths.map { ds_globalIndexPathForLocalIndexPath($0) } } func ds_globalSectionSetForLocalSectionSet(_ localSections: IndexSet) -> IndexSet { let globalSections = NSMutableIndexSet() for section in localSections { let globalSection = ds_globalSectionForLocalSection(section) globalSections.add(globalSection) } return globalSections as IndexSet } }
3f62a4365a44aebbdf9cdf94704bcc1f
39.512315
261
0.705861
false
false
false
false
gerardogrisolini/Webretail
refs/heads/master
Sources/Webretail/Models/Tag.swift
apache-2.0
1
// // Tag.swift // Webretail // // Created by Gerardo Grisolini on 07/11/17. // class Tag: Codable, JsonbProtocol, Comparable { public var groupId : Int = 0 public var valueId : Int = 0 public var valueName : String = "" static func <(lhs: Tag, rhs: Tag) -> Bool { return lhs.groupId < rhs.groupId && lhs.valueId < rhs.valueId } static func ==(lhs: Tag, rhs: Tag) -> Bool { return lhs.groupId == rhs.groupId && lhs.valueId == rhs.valueId } }
8ef55b52ace8351b01ff0e00a0c0141c
22.666667
71
0.595573
false
false
false
false
tylerbrockett/cse394-principles-of-mobile-applications
refs/heads/master
lab-3/lab-3/lab-3/TableViewController.swift
mit
1
/* * @author Tyler Brockett * @project CSE 394 Lab 4 * @version February 16, 2016 * * The MIT License (MIT) * * Copyright (c) 2016 Tyler Brockett * * 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 TableViewController: UITableViewController { let locations:Locations = Locations() @IBOutlet weak var locationsTV: UITableView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.navigationItem.leftBarButtonItem = self.editButtonItem() loadList() } func loadList(){ self.locations.sort() self.tableView.reloadData() } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return locations.getSize() } override func tableView(tableView: UITableView,cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("tableCell", forIndexPath: indexPath) cell.textLabel?.text = locations.get(indexPath.row).getName() cell.detailTextLabel?.textAlignment = .Right return cell; } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if(segue.identifier == "detailViewSegue"){ let selectedIndex: NSIndexPath = self.locationsTV.indexPathForCell(sender as! UITableViewCell)! if let detailviewController: DetailViewController = segue.destinationViewController as? DetailViewController { detailviewController.location = locations.get(selectedIndex.row) } } } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { locations.remove(indexPath.row) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
440e569a352d9380153c95dfcef43272
38.512195
157
0.709568
false
false
false
false
icapps/ios_objective_c_workshop
refs/heads/master
Teacher/General Objective-C example/Pods/Faro/Sources/ServiceQueue.swift
mit
1
import Foundation /// Tasks can be autostarted or started manualy. The taks are still handled bij an URLSession like in `Service`, but /// we store the TaskIdentifiers. When a task completes it is removed from the queue and `final()`. /// It has its own `URLSession` which it invalidates once the queue is finished. You need to create another instance of `ServiceQueue` to be able to /// perform new request after you fired the first queue. open class ServiceQueue: Service { var taskQueue: Set<URLSessionDataTask> var failedTasks: Set<URLSessionTask>? private let final: (_ failedTasks: Set<URLSessionTask>?)->() /// Creates a queue that lasts until final is called. When all request in the queue are finished the session becomes invalid. /// For future queued request you have to create a new ServiceQueue instance. /// - parameter configuration: Faro service configuration /// - parameter faroSession: You can provide a custom `URLSession` via `FaroQueueSession`. /// - parameter final: closure is callen when all requests are performed. public init(configuration: Configuration, faroSession: FaroQueueSessionable = FaroQueueSession(), final: @escaping(_ failedTasks: Set<URLSessionTask>?)->()) { self.final = final taskQueue = Set<URLSessionDataTask>() super.init(configuration: configuration, faroSession: faroSession) } open override func performJsonResult<M: Deserializable>(_ call: Call, autoStart: Bool = false, jsonResult: @escaping (Result<M>) -> ()) -> URLSessionDataTask? { var task: URLSessionDataTask? task = super.performJsonResult(call, autoStart: autoStart) { [weak self] (stage1JsonResult: Result<M>) in guard let strongSelf = self else { jsonResult(stage1JsonResult) return } /// Store ID of failed tasks to report switch stage1JsonResult { case .json(_), .ok: strongSelf.cleanupQueue(for: task) case .failure(_): strongSelf.cleanupQueue(for: task, didFail: true) default: strongSelf.cleanupQueue(for: task) } jsonResult(stage1JsonResult) strongSelf.shouldCallFinal() } add(task) return task } open override func performWrite(_ writeCall: Call, autoStart: Bool, writeResult: @escaping (WriteResult) -> ()) -> URLSessionDataTask? { var task: URLSessionDataTask? task = super.performWrite(writeCall, autoStart: autoStart) { [weak self] (result) in guard let strongSelf = self else { writeResult(result) return } switch result { case .ok: strongSelf.cleanupQueue(for: task) default: strongSelf.cleanupQueue(for: task, didFail: true) } writeResult(result) strongSelf.shouldCallFinal() } add(task) return task } private func add(_ task: URLSessionDataTask?) { guard let createdTask = task else { printFaroError(FaroError.invalidSession(message: "\(self) tried to ")) return } taskQueue.insert(createdTask) } private func cleanupQueue(for task: URLSessionDataTask?, didFail: Bool = false) { if let task = task { let _ = taskQueue.remove(task) if(didFail) { if failedTasks == nil { failedTasks = Set<URLSessionTask>() } failedTasks?.insert(task) } } } private func shouldCallFinal() { if !hasOustandingTasks { final(failedTasks) finishTasksAndInvalidate() } } // MARK: - Interact with tasks open var hasOustandingTasks: Bool { get { return taskQueue.count > 0 } } open func resume(_ task: URLSessionDataTask) { faroSession.resume(task) } open func resumeAll() { let notStartedTasks = taskQueue.filter { $0.state != .running || $0.state != .completed} notStartedTasks.forEach { (task) in faroSession.resume(task) } } // MARK: - Invalidate session overrides override open func invalidateAndCancel() { taskQueue.removeAll() failedTasks?.removeAll() faroSession.invalidateAndCancel() } deinit { faroSession.finishTasksAndInvalidate() } }
fe3cca9daac83870398ea57c20107b5d
34.169231
164
0.609799
false
false
false
false
wikimedia/wikipedia-ios
refs/heads/main
Wikipedia/Code/CollectionViewUpdater.swift
mit
1
import Foundation import CocoaLumberjackSwift protocol CollectionViewUpdaterDelegate: NSObjectProtocol { func collectionViewUpdater<T>(_ updater: CollectionViewUpdater<T>, didUpdate collectionView: UICollectionView) func collectionViewUpdater<T>(_ updater: CollectionViewUpdater<T>, updateItemAtIndexPath indexPath: IndexPath, in collectionView: UICollectionView) } class CollectionViewUpdater<T: NSFetchRequestResult>: NSObject, NSFetchedResultsControllerDelegate { let fetchedResultsController: NSFetchedResultsController<T> let collectionView: UICollectionView var isSlidingNewContentInFromTheTopEnabled: Bool = false var sectionChanges: [WMFSectionChange] = [] var objectChanges: [WMFObjectChange] = [] weak var delegate: CollectionViewUpdaterDelegate? var isGranularUpdatingEnabled: Bool = true // when set to false, individual updates won't be pushed to the collection view, only reloadData() required init(fetchedResultsController: NSFetchedResultsController<T>, collectionView: UICollectionView) { self.fetchedResultsController = fetchedResultsController self.collectionView = collectionView super.init() self.fetchedResultsController.delegate = self } deinit { self.fetchedResultsController.delegate = nil } public func performFetch() { do { try fetchedResultsController.performFetch() } catch let error { assert(false) DDLogError("Error fetching \(String(describing: fetchedResultsController.fetchRequest.predicate)) for \(String(describing: self.delegate)): \(error)") } sectionCounts = fetchSectionCounts() collectionView.reloadData() } @objc func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { sectionChanges = [] objectChanges = [] } @objc func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) { let objectChange = WMFObjectChange() objectChange.fromIndexPath = indexPath objectChange.toIndexPath = newIndexPath objectChange.type = type objectChanges.append(objectChange) } @objc func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) { let sectionChange = WMFSectionChange() sectionChange.sectionIndex = sectionIndex sectionChange.type = type sectionChanges.append(sectionChange) } private var previousSectionCounts: [Int] = [] private var sectionCounts: [Int] = [] private func fetchSectionCounts() -> [Int] { let sections = fetchedResultsController.sections ?? [] return sections.map { $0.numberOfObjects } } @objc func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { previousSectionCounts = sectionCounts sectionCounts = fetchSectionCounts() guard isGranularUpdatingEnabled else { collectionView.reloadData() delegate?.collectionViewUpdater(self, didUpdate: self.collectionView) return } var didInsertFirstSection = false var didOnlyChangeItems = true var sectionDelta = 0 var objectsInSectionDelta = 0 var forceReload = false for sectionChange in sectionChanges { didOnlyChangeItems = false switch sectionChange.type { case .delete: guard sectionChange.sectionIndex < previousSectionCounts.count else { forceReload = true break } sectionDelta -= 1 case .insert: sectionDelta += 1 objectsInSectionDelta += sectionCounts[sectionChange.sectionIndex] if sectionChange.sectionIndex == 0 { didInsertFirstSection = true } default: break } } for objectChange in objectChanges { switch objectChange.type { case .delete: guard let fromIndexPath = objectChange.fromIndexPath, fromIndexPath.section < previousSectionCounts.count, fromIndexPath.item < previousSectionCounts[fromIndexPath.section] else { forceReload = true break } // there seems to be a very specific bug about deleting the item at index path 0,2 when there are 3 items in the section ¯\_(ツ)_/¯ if fromIndexPath.section == 0 && fromIndexPath.item == 2 && previousSectionCounts[0] == 3 { forceReload = true break } default: break } } let sectionCountsMatch = (previousSectionCounts.count + sectionDelta) == sectionCounts.count let currentNumberOfSections = collectionView.numberOfSections let previousSectionCountsEqualCurrentNumberOfSections = previousSectionCounts.count == currentNumberOfSections guard !forceReload, sectionCountsMatch, previousSectionCountsEqualCurrentNumberOfSections, objectChanges.count < 1000 && sectionChanges.count < 10 else { // reload data for invalid changes & larger changes collectionView.reloadData() delegate?.collectionViewUpdater(self, didUpdate: self.collectionView) return } guard isSlidingNewContentInFromTheTopEnabled else { performBatchUpdates(consideredNumberOfSections: currentNumberOfSections) return } guard let columnarLayout = collectionView.collectionViewLayout as? ColumnarCollectionViewLayout else { performBatchUpdates(consideredNumberOfSections: currentNumberOfSections) return } guard !previousSectionCounts.isEmpty && didInsertFirstSection && sectionDelta > 0 else { if didOnlyChangeItems { columnarLayout.animateItems = true columnarLayout.slideInNewContentFromTheTop = false UIView.animate(withDuration: 0.8, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: .allowUserInteraction, animations: { self.performBatchUpdates(consideredNumberOfSections: currentNumberOfSections) }, completion: nil) } else { columnarLayout.animateItems = false columnarLayout.slideInNewContentFromTheTop = false performBatchUpdates(consideredNumberOfSections: currentNumberOfSections) } return } columnarLayout.animateItems = true columnarLayout.slideInNewContentFromTheTop = true UIView.animate(withDuration: 0.7 + 0.1 * TimeInterval(objectsInSectionDelta), delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: .allowUserInteraction, animations: { self.performBatchUpdates(consideredNumberOfSections: currentNumberOfSections) }, completion: nil) } func performBatchUpdates(consideredNumberOfSections: Int) { let collectionView = self.collectionView // Here we are giving it one last chance to force reload, in case the numberOfSections have changed since the last time we considered it for force reloading, to try to avoid invalid update crashes. //https://phabricator.wikimedia.org/T253762 guard consideredNumberOfSections == collectionView.numberOfSections else { collectionView.reloadData() delegate?.collectionViewUpdater(self, didUpdate: self.collectionView) return } collectionView.performBatchUpdates({ DDLogDebug("=== WMFBU BATCH UPDATE START \(String(describing: self.delegate)) ===") for objectChange in objectChanges { switch objectChange.type { case .delete: if let fromIndexPath = objectChange.fromIndexPath { DDLogDebug("WMFBU object delete: \(fromIndexPath)") collectionView.deleteItems(at: [fromIndexPath]) } else { assert(false, "unhandled delete") DDLogError("Unhandled delete: \(objectChange)") } case .insert: if let toIndexPath = objectChange.toIndexPath { DDLogDebug("WMFBU object insert: \(toIndexPath)") collectionView.insertItems(at: [toIndexPath]) } else { assert(false, "unhandled insert") DDLogError("Unhandled insert: \(objectChange)") } case .move: if let fromIndexPath = objectChange.fromIndexPath, let toIndexPath = objectChange.toIndexPath { DDLogDebug("WMFBU object move delete: \(fromIndexPath)") collectionView.deleteItems(at: [fromIndexPath]) DDLogDebug("WMFBU object move insert: \(toIndexPath)") collectionView.insertItems(at: [toIndexPath]) } else { assert(false, "unhandled move") DDLogError("Unhandled move: \(objectChange)") } break case .update: if let updatedIndexPath = objectChange.toIndexPath ?? objectChange.fromIndexPath { delegate?.collectionViewUpdater(self, updateItemAtIndexPath: updatedIndexPath, in: collectionView) } else { assert(false, "unhandled update") DDLogDebug("WMFBU unhandled update: \(objectChange)") } @unknown default: break } } for sectionChange in sectionChanges { switch sectionChange.type { case .delete: DDLogDebug("WMFBU section delete: \(sectionChange.sectionIndex)") collectionView.deleteSections(IndexSet(integer: sectionChange.sectionIndex)) case .insert: DDLogDebug("WMFBU section insert: \(sectionChange.sectionIndex)") collectionView.insertSections(IndexSet(integer: sectionChange.sectionIndex)) default: DDLogDebug("WMFBU section update: \(sectionChange.sectionIndex)") collectionView.reloadSections(IndexSet(integer: sectionChange.sectionIndex)) } } DDLogDebug("=== WMFBU BATCH UPDATE END ===") }) { (finished) in self.delegate?.collectionViewUpdater(self, didUpdate: collectionView) } } }
26f519bf92bdf27518e78875304c65ed
46.714286
249
0.621257
false
false
false
false
LawrenceHan/iOS-project-playground
refs/heads/master
2016 Plan/10月/链式编程、函数式编程/1025-ReactiveCocoa/RAC第一天备课代码/04-导入ReactiveCocoa/Pods/ReactiveCocoa/ReactiveCocoa/Swift/ObjectiveCBridging.swift
apache-2.0
32
// // ObjectiveCBridging.swift // ReactiveCocoa // // Created by Justin Spahr-Summers on 2014-07-02. // Copyright (c) 2014 GitHub, Inc. All rights reserved. // import Result extension RACDisposable: Disposable {} extension RACScheduler: DateSchedulerType { public var currentDate: NSDate { return NSDate() } public func schedule(action: () -> ()) -> Disposable? { return self.schedule(action) } public func scheduleAfter(date: NSDate, action: () -> ()) -> Disposable? { return self.after(date, schedule: action) } public func scheduleAfter(date: NSDate, repeatingEvery: NSTimeInterval, withLeeway: NSTimeInterval, action: () -> ()) -> Disposable? { return self.after(date, repeatingEvery: repeatingEvery, withLeeway: withLeeway, schedule: action) } } extension ImmediateScheduler { public func toRACScheduler() -> RACScheduler { return RACScheduler.immediateScheduler() } } extension UIScheduler { public func toRACScheduler() -> RACScheduler { return RACScheduler.mainThreadScheduler() } } extension QueueScheduler { public func toRACScheduler() -> RACScheduler { return RACTargetQueueScheduler(name: "org.reactivecocoa.ReactiveCocoa.QueueScheduler.toRACScheduler()", targetQueue: queue) } } private func defaultNSError(message: String, file: String, line: Int) -> NSError { return Result<(), NSError>.error(message, file: file, line: line) } extension RACSignal { /// Creates a SignalProducer which will subscribe to the receiver once for /// each invocation of start(). public func toSignalProducer(file: String = __FILE__, line: Int = __LINE__) -> SignalProducer<AnyObject?, NSError> { return SignalProducer { observer, disposable in let next = { (obj: AnyObject?) -> () in sendNext(observer, obj) } let error = { (nsError: NSError?) -> () in sendError(observer, nsError ?? defaultNSError("Nil RACSignal error", file: file, line: line)) } let completed = { sendCompleted(observer) } disposable += self.subscribeNext(next, error: error, completed: completed) } } } private extension SignalType { /// Turns each value into an Optional. private func optionalize() -> Signal<T?, E> { return signal.map { Optional($0) } } } /// Creates a RACSignal that will start() the producer once for each /// subscription. /// /// Any `Interrupted` events will be silently discarded. public func toRACSignal<T: AnyObject, E>(producer: SignalProducer<T, E>) -> RACSignal { return toRACSignal(producer.lift { $0.optionalize() }) } /// Creates a RACSignal that will start() the producer once for each /// subscription. /// /// Any `Interrupted` events will be silently discarded. public func toRACSignal<T: AnyObject, E>(producer: SignalProducer<T?, E>) -> RACSignal { return RACSignal.createSignal { subscriber in let selfDisposable = producer.start { event in switch event { case let .Next(value): subscriber.sendNext(value) case let .Error(error): subscriber.sendError(error as NSError) case .Completed: subscriber.sendCompleted() default: break } } return RACDisposable { selfDisposable.dispose() } } } /// Creates a RACSignal that will observe the given signal. /// /// Any `Interrupted` event will be silently discarded. public func toRACSignal<T: AnyObject, E>(signal: Signal<T, E>) -> RACSignal { return toRACSignal(signal.optionalize()) } /// Creates a RACSignal that will observe the given signal. /// /// Any `Interrupted` event will be silently discarded. public func toRACSignal<T: AnyObject, E>(signal: Signal<T?, E>) -> RACSignal { return RACSignal.createSignal { subscriber in let selfDisposable = signal.observe { event in switch event { case let .Next(value): subscriber.sendNext(value) case let .Error(error): subscriber.sendError(error as NSError) case .Completed: subscriber.sendCompleted() default: break } } return RACDisposable { selfDisposable?.dispose() } } } extension RACCommand { /// Creates an Action that will execute the receiver. /// /// Note that the returned Action will not necessarily be marked as /// executing when the command is. However, the reverse is always true: /// the RACCommand will always be marked as executing when the action is. public func toAction(file: String = __FILE__, line: Int = __LINE__) -> Action<AnyObject?, AnyObject?, NSError> { let enabledProperty = MutableProperty(true) enabledProperty <~ self.enabled.toSignalProducer() .map { $0 as! Bool } .flatMapError { _ in SignalProducer<Bool, NoError>(value: false) } return Action(enabledIf: enabledProperty) { (input: AnyObject?) -> SignalProducer<AnyObject?, NSError> in let executionSignal = RACSignal.`defer` { return self.execute(input) } return executionSignal.toSignalProducer(file, line: line) } } } extension Action { private var commandEnabled: RACSignal { let enabled = self.enabled.producer.map { $0 as NSNumber } return toRACSignal(enabled) } } /// Creates a RACCommand that will execute the action. /// /// Note that the returned command will not necessarily be marked as /// executing when the action is. However, the reverse is always true: /// the Action will always be marked as executing when the RACCommand is. public func toRACCommand<Output: AnyObject, E>(action: Action<AnyObject?, Output, E>) -> RACCommand { return RACCommand(enabled: action.commandEnabled) { (input: AnyObject?) -> RACSignal in return toRACSignal(action.apply(input)) } } /// Creates a RACCommand that will execute the action. /// /// Note that the returned command will not necessarily be marked as /// executing when the action is. However, the reverse is always true: /// the Action will always be marked as executing when the RACCommand is. public func toRACCommand<Output: AnyObject, E>(action: Action<AnyObject?, Output?, E>) -> RACCommand { return RACCommand(enabled: action.commandEnabled) { (input: AnyObject?) -> RACSignal in return toRACSignal(action.apply(input)) } }
a67d864a7df87f99b9cb1a1ed41c1817
29.866667
135
0.716232
false
false
false
false
ntaku/SwiftEssential
refs/heads/master
SwiftEssential/ExtDouble.swift
mit
1
import Foundation public extension Double { /** 秒数を0:00:00の形式に変換 */ func toTimeString() -> String { if self.isNaN { return "--:--" } var remained = Int(self + 0.9) // 切り上げ let hour = remained / 3600 remained %= 3600 let min = remained / 60 remained %= 60 let sec = remained let time = NSMutableString() if hour > 0 { time.appendFormat("%d:%02d:%02d", hour, min, sec) } else { time.appendFormat("%d:%02d", min, sec) } return time as String } /** 秒数を00:00.00の形式に変換(最大99:59.99) */ func toMsecTimeString() -> String { if self.isNaN { return "--:--" } var remained = self let hour = Int(remained / 3600.0) remained -= Double(hour * 3600) var min = Int(remained / 60.0) remained -= Double(min * 60) var sec = Int(remained) remained -= Double(sec) var msec = Int(remained * 100) // 99.99.99が上限 min += hour * 60 if min > 99 { min = 99 sec = 59 msec = 99 } let time = NSMutableString() time.appendFormat("%02d:%02d.%02d", min, sec, msec) return time as String } }
0660e95d272a60ddeccbf4c7258489ca
20.532258
61
0.472659
false
false
false
false
JackieQu/QP_DouYu
refs/heads/master
QP_DouYu/QP_DouYu/Classes/Main/Controller/BaseAnchorViewController.swift
mit
1
// // BaseAnchorViewController.swift // QP_DouYu // // Created by JackieQu on 2017/3/4. // Copyright © 2017年 JackieQu. All rights reserved. // import UIKit private let kItemMargin : CGFloat = 10 private let kHeaderViewH : CGFloat = 50 private let kNormalCellID = "kNormalCellID" private let kHeaderViewID = "kHeaderViewID" let kPrettyCellID = "kPrettyCellID" let kNormalItemW = (kScreenW - 3 * kItemMargin) / 2 let kNormalItemH = kNormalItemW * 3 / 4 let kPrettyItemH = kNormalItemW * 4 / 3 class BaseAnchorViewController: BaseViewController { // MARK:- 定义属性 var baseVM : BaseViewModel! lazy var collectionView : UICollectionView = {[unowned self] in // 1.创建布局 let layout = UICollectionViewFlowLayout() layout.itemSize = CGSize(width: kNormalItemW, height: kNormalItemH) layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = kItemMargin layout.headerReferenceSize = CGSize(width: kScreenW, height: kHeaderViewH) layout.sectionInset = UIEdgeInsets(top: 0, left: kItemMargin, bottom: 0, right: kItemMargin) // 2.创建 UICollectionView let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout) collectionView.backgroundColor = UIColor.white collectionView.dataSource = self collectionView.delegate = self collectionView.autoresizingMask = [.flexibleWidth, .flexibleHeight] collectionView.register(UINib(nibName: "CollectionViewNormalCell", bundle: nil), forCellWithReuseIdentifier: kNormalCellID) collectionView.register(UINib(nibName: "CollectionViewPrettyCell", bundle: nil), forCellWithReuseIdentifier: kPrettyCellID) collectionView.register(UINib(nibName: "CollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderViewID) return collectionView }() // MARK:- 系统回调 override func viewDidLoad() { super.viewDidLoad() setupUI() loadData() } } // MARK:- 设置 UI extension BaseAnchorViewController { override func setupUI() { // 1.给父类中的内容 view 的引用进行赋值 contentView = collectionView // 2.添加 view.addSubview(collectionView) // 3.调用 super.setupUI() super.setupUI() } } // MARK:- 请求数据 extension BaseAnchorViewController { func loadData() { } } // MARK:- 遵守 UICollectioView 的数据源协议 extension BaseAnchorViewController : UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { return baseVM.anchorGroups.count } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return baseVM.anchorGroups[section].anchors.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { // 1.取出 cell let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kNormalCellID, for: indexPath) as! CollectionViewNormalCell // 2.给 cell 设置数据 cell.anchor = baseVM.anchorGroups[indexPath.section].anchors[indexPath.item] return cell } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { // 1.取出 headerView let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: kHeaderViewID, for: indexPath) as! CollectionHeaderView // 2.给 headerView 设置数据 headerView.group = baseVM.anchorGroups[indexPath.section] return headerView } } // MARK:- 遵守 UICollectioView 的代理协议 extension BaseAnchorViewController : UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { // print("点击了:\(indexPath)") // 1.取出对应的主播信息 let anchor = baseVM.anchorGroups[indexPath.section].anchors[indexPath.item] // 2.判断是秀场房间还是普通房间 anchor.isVertical == 0 ? pushNormalRoomVC() : presentShowRoomVC() } private func presentShowRoomVC() { // 1.创建 showRoomVC let showRoomVC = RoomShowViewController() // 2.以 model 方式弹出 present(showRoomVC, animated: true, completion: nil) } private func pushNormalRoomVC() { let normalRoomVC = RoomNormalViewController() navigationController?.pushViewController(normalRoomVC, animated: true) } }
615de211fac52cee4efcd33b460c4250
33.108696
186
0.687912
false
false
false
false