repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
vector-im/riot-ios
Riot/Modules/SetPinCode/SetPinCoordinator.swift
1
6055
// File created from FlowTemplate // $ createRootCoordinator.sh SetPinCode SetPin EnterPinCode /* Copyright 2020 New Vector Ltd 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 @objcMembers final class SetPinCoordinator: SetPinCoordinatorType { // MARK: - Properties // MARK: Private private let navigationRouter: NavigationRouterType private let session: MXSession? private var viewMode: SetPinCoordinatorViewMode private let pinCodePreferences: PinCodePreferences // MARK: Public // Must be used only internally var childCoordinators: [Coordinator] = [] weak var delegate: SetPinCoordinatorDelegate? // MARK: - Setup init(session: MXSession?, viewMode: SetPinCoordinatorViewMode, pinCodePreferences: PinCodePreferences) { self.navigationRouter = NavigationRouter(navigationController: RiotNavigationController()) self.session = session self.viewMode = viewMode self.pinCodePreferences = pinCodePreferences } private func getRootCoordinator() -> Coordinator & Presentable { switch viewMode { case .unlock: if pinCodePreferences.isBiometricsSet { return createSetupBiometricsCoordinator() } else { return createEnterPinCodeCoordinator() } case .setPin, .confirmPinToDeactivate: return createEnterPinCodeCoordinator() case .setupBiometricsAfterLogin, .setupBiometricsFromSettings, .confirmBiometricsToDeactivate: return createSetupBiometricsCoordinator() } } // MARK: - Public methods func start() { let rootCoordinator = getRootCoordinator() setRootCoordinator(rootCoordinator) } func toPresentable() -> UIViewController { return self.navigationRouter.toPresentable() } // MARK: - Private methods private func setRootCoordinator(_ coordinator: Coordinator & Presentable) { coordinator.start() self.add(childCoordinator: coordinator) self.navigationRouter.setRootModule(coordinator) } private func createEnterPinCodeCoordinator() -> EnterPinCodeCoordinator { let coordinator = EnterPinCodeCoordinator(session: self.session, viewMode: self.viewMode) coordinator.delegate = self return coordinator } private func createSetupBiometricsCoordinator() -> SetupBiometricsCoordinator { let coordinator = SetupBiometricsCoordinator(session: self.session, viewMode: self.viewMode) coordinator.delegate = self return coordinator } private func storePin(_ pin: String) { pinCodePreferences.pin = pin } private func removePin() { pinCodePreferences.pin = nil } private func setupBiometrics() { pinCodePreferences.biometricsEnabled = true } private func removeBiometrics() { pinCodePreferences.biometricsEnabled = nil } } // MARK: - EnterPinCodeCoordinatorDelegate extension SetPinCoordinator: EnterPinCodeCoordinatorDelegate { func enterPinCodeCoordinatorDidComplete(_ coordinator: EnterPinCodeCoordinatorType) { if viewMode == .confirmPinToDeactivate { removePin() } self.delegate?.setPinCoordinatorDidComplete(self) } func enterPinCodeCoordinatorDidCompleteWithReset(_ coordinator: EnterPinCodeCoordinatorType) { self.delegate?.setPinCoordinatorDidCompleteWithReset(self) } func enterPinCodeCoordinator(_ coordinator: EnterPinCodeCoordinatorType, didCompleteWithPin pin: String) { storePin(pin) if pinCodePreferences.forcePinProtection && pinCodePreferences.isBiometricsAvailable { viewMode = .setupBiometricsAfterLogin setRootCoordinator(createSetupBiometricsCoordinator()) } else { self.delegate?.setPinCoordinatorDidComplete(self) } } func enterPinCodeCoordinatorDidCancel(_ coordinator: EnterPinCodeCoordinatorType) { self.delegate?.setPinCoordinatorDidCancel(self) } } extension SetPinCoordinator: SetupBiometricsCoordinatorDelegate { func setupBiometricsCoordinatorDidComplete(_ coordinator: SetupBiometricsCoordinatorType) { switch viewMode { case .setupBiometricsAfterLogin, .setupBiometricsFromSettings: setupBiometrics() case .confirmBiometricsToDeactivate: removeBiometrics() default: break } self.delegate?.setPinCoordinatorDidComplete(self) } func setupBiometricsCoordinatorDidCompleteWithReset(_ coordinator: SetupBiometricsCoordinatorType) { self.delegate?.setPinCoordinatorDidCompleteWithReset(self) } func setupBiometricsCoordinatorDidCancel(_ coordinator: SetupBiometricsCoordinatorType) { switch viewMode { case .unlock: // if trying to unlock if pinCodePreferences.isPinSet { // and user also has set a pin, so fallback to it setRootCoordinator(createEnterPinCodeCoordinator()) } else { // no pin set, cascade cancellation self.delegate?.setPinCoordinatorDidCancel(self) } case .setupBiometricsAfterLogin: self.delegate?.setPinCoordinatorDidComplete(self) default: self.delegate?.setPinCoordinatorDidCancel(self) } } }
apache-2.0
088b7dbc24fc619efca38f82866a36d3
32.638889
110
0.687696
6.097684
false
false
false
false
jkufver/NSSpainEnteranceTracker
NSSpainEnteranceTracker/MonitoringEngine.swift
1
5719
// // MonitoringEngine.swift // NSSpainEnteranceTracker // // Created by Jens Kufver on 2014-09-17. // Copyright (c) 2014 Jens Kufver. All rights reserved. // import Foundation import CoreLocation import UIKit // General search criteria for beacons that are broadcasting //let BEACON_PROXIMITY_UUID = NSUUID(UUIDString: "B9407F30-F5F8-466E-AFF9-25556B57FE6D") // Estimote let BEACON_PROXIMITY_UUID = NSUUID(UUIDString: "8C2486A0-3E4F-11E4-916C-0800200C9A66") // NSSpain // Beacons are hardcoded into our app so we can easily filter for them in a noisy environment let BEACON_OUTSIDE_MINOR = 0 //33011 let BEACON_INSIDE_MINOR = 1 //42851 let region = CLBeaconRegion(proximityUUID:BEACON_PROXIMITY_UUID, identifier:"Estimote region") protocol MonitoringEngineDelegate : NSObjectProtocol { func monitoringEngine(engine: MonitoringEngine!, didRangeBeacons beacons: [AnyObject]!) } private let _singletonInstance = MonitoringEngine() class MonitoringEngine: NSObject, CLLocationManagerDelegate { class var sharedInstance: MonitoringEngine { return _singletonInstance } var locationManager: CLLocationManager = CLLocationManager() var isMonitoring = false var isRanging = false var delegates = Array<MonitoringEngineDelegate>() func registerDelegate(item:MonitoringEngineDelegate) { delegates.append(item) } func removeDelegate(item:MonitoringEngineDelegate) { for (index, element) in enumerate(delegates) { if element === item { delegates.removeAtIndex(index) } } } override init() { super.init() locationManager.delegate = self let time = dispatch_time(DISPATCH_TIME_NOW, Int64(1 * NSEC_PER_SEC)) dispatch_after(time, dispatch_get_main_queue()) { switch CLLocationManager.authorizationStatus() { case .Authorized: self.startMonitoring() case .AuthorizedWhenInUse: self.locationManager.requestAlwaysAuthorization() case .Denied: UIAlertView(title: "Can't start", message: "Location services are .Denied for this app", delegate: nil, cancelButtonTitle: "OK").show() case .NotDetermined: self.locationManager.requestAlwaysAuthorization() case .Restricted: UIAlertView(title: "Can't start", message: "Location services are .Restricted for this app", delegate: nil, cancelButtonTitle: "OK").show() } } } func startMonitoring() { if !isMonitoring { println("BM start") isMonitoring = true } else { println("BM start (noop - already monitoring)") return } locationManager.startMonitoringForRegion(region) } func stopMonitoring() { println("BM stop") locationManager.stopMonitoringForRegion(region) isMonitoring = false } func startRanging() { if !isRanging { println("BM ranging start") isRanging = true } else { println("BM ranging start (noop - already ranging)") return } locationManager.startRangingBeaconsInRegion(region) } func stopRanging() { println("BM stop") locationManager.stopRangingBeaconsInRegion(region) isMonitoring = false } // CLLocationManagerDelegate methods func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) { println("BM didChangeAuthorizationStatus \(status.toRaw())") if status == .Authorized { startMonitoring() } else { stopMonitoring() } } func locationManager(manager: CLLocationManager!, didStartMonitoringForRegion region: CLRegion!) { println("BM didStartMonitoringForRegion") locationManager.requestStateForRegion(region) // should locationManager be manager? } func locationManager(manager: CLLocationManager, didEnterRegion:CLRegion) { println("BM didEnterRegion \(didEnterRegion.identifier)") if let beaconRegion = didEnterRegion as? CLBeaconRegion { manager.startRangingBeaconsInRegion(beaconRegion) } } func locationManager(manager: CLLocationManager, didExitRegion:CLRegion) { println("BM didExitRegion \(didExitRegion.identifier)") if let beaconRegion = didExitRegion as? CLBeaconRegion { manager.stopRangingBeaconsInRegion(beaconRegion) } } func locationManager(manager: CLLocationManager!, didDetermineState state: CLRegionState, forRegion region: CLRegion!) { println("BM didDetermineState \(state.toRaw())") switch state { case .Inside: println("BeaconManager:didDetermineState CLRegionState.Inside \(region.identifier)") startRanging() case .Outside: println("BeaconManager:didDetermineState CLRegionState.Outside") stopRanging() case .Unknown: println("BeaconManager:didDetermineState CLRegionState.Unknown") default: println("BeaconManager:didDetermineState default") } } func locationManager(manager: CLLocationManager!, didRangeBeacons beacons: [AnyObject]!, inRegion region: CLBeaconRegion!) { println("beacons.count: \(beacons.count)") for beacon in beacons { println("beacon: \(beacon)") } for delegate in delegates { delegate.monitoringEngine(self, didRangeBeacons: beacons) } } }
mit
421fdf8145e4942dd1592e776fb5ab81
33.660606
169
0.65396
5.315056
false
false
false
false
wikimedia/apps-ios-wikipedia
Wikipedia/Code/WMFForgotPasswordViewController.swift
1
5935
import UIKit class WMFForgotPasswordViewController: WMFScrollViewController, Themeable { @IBOutlet fileprivate var titleLabel: UILabel! @IBOutlet fileprivate var subTitleLabel: UILabel! @IBOutlet fileprivate var usernameField: ThemeableTextField! @IBOutlet fileprivate var emailField: ThemeableTextField! @IBOutlet fileprivate var usernameTitleLabel: UILabel! @IBOutlet fileprivate var emailTitleLabel: UILabel! @IBOutlet fileprivate var orLabel: UILabel! @IBOutlet fileprivate var resetPasswordButton: WMFAuthButton! fileprivate var theme = Theme.standard let passwordResetter = WMFPasswordResetter() override func viewDidLoad() { super.viewDidLoad() navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named:"close"), style: .plain, target:self, action:#selector(closeButtonPushed(_:))) navigationItem.leftBarButtonItem?.accessibilityLabel = CommonStrings.closeButtonAccessibilityLabel titleLabel.text = WMFLocalizedString("forgot-password-title", value:"Reset password", comment:"Title for reset password interface\n{{Identical|Reset password}}") subTitleLabel.text = WMFLocalizedString("forgot-password-instructions", value:"Fill in one of the fields below to receive password reset instructions via email", comment:"Instructions for resetting password") usernameField.placeholder = WMFLocalizedString("field-username-placeholder", value:"enter username", comment:"Placeholder text shown inside username field until user taps on it") emailField.placeholder = WMFLocalizedString("field-email-placeholder", value:"[email protected]", comment:"Placeholder text shown inside email address field until user taps on it") usernameTitleLabel.text = WMFLocalizedString("field-username-title", value:"Username", comment:"Title for username field\n{{Identical|Username}}") emailTitleLabel.text = WMFLocalizedString("field-email-title", value:"Email", comment:"Noun. Title for email address field.\n{{Identical|E-mail}}") resetPasswordButton.setTitle(WMFLocalizedString("forgot-password-button-title", value:"Reset", comment:"Title for reset password button\n{{Identical|Reset}}"), for: .normal) orLabel.text = WMFLocalizedString("forgot-password-username-or-email-title", value:"Or", comment:"Title shown between the username and email text fields. User only has to specify either username \"Or\" email address\n{{Identical|Or}}") view.wmf_configureSubviewsForDynamicType() apply(theme: theme) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) enableProgressiveButton(false) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) usernameField.becomeFirstResponder() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) enableProgressiveButton(false) } public func textFieldShouldReturn(_ textField: UITextField) -> Bool { if (textField == usernameField) { emailField.becomeFirstResponder() } else if (textField == emailField) { save() } return true } @IBAction func textFieldDidChange(_ sender: UITextField) { guard let username = usernameField.text, let email = emailField.text else{ enableProgressiveButton(false) return } enableProgressiveButton((!username.isEmpty || !email.isEmpty)) } func enableProgressiveButton(_ highlight: Bool) { resetPasswordButton.isEnabled = highlight } @IBAction fileprivate func resetPasswordButtonTapped(withSender sender: UIButton) { save() } fileprivate func save() { wmf_hideKeyboard() sendPasswordResetEmail(userName: usernameField.text, email: emailField.text) } @objc func closeButtonPushed(_ : UIBarButtonItem) { dismiss(animated: true, completion: nil) } func sendPasswordResetEmail(userName: String?, email: String?) { guard let siteURL = MWKLanguageLinkController.sharedInstance().appLanguage?.siteURL() else { WMFAlertManager.sharedInstance.showAlert("No site url", sticky: true, dismissPreviousAlerts: true, tapCallBack: nil) return } let failure: WMFErrorHandler = { error in DispatchQueue.main.async { WMFAlertManager.sharedInstance.showErrorAlert(error as NSError, sticky: true, dismissPreviousAlerts: true, tapCallBack: nil) } } passwordResetter.resetPassword( siteURL: siteURL, userName: userName, email: email, success: { result in DispatchQueue.main.async { WMFAlertManager.sharedInstance.showSuccessAlert(WMFLocalizedString("forgot-password-email-sent", value:"An email with password reset instructions was sent", comment:"Alert text shown when password reset email is sent"), sticky: true, dismissPreviousAlerts: true, tapCallBack: nil) } }, failure: failure) } func apply(theme: Theme) { self.theme = theme guard viewIfLoaded != nil else { return } view.backgroundColor = theme.colors.paperBackground view.tintColor = theme.colors.link titleLabel.textColor = theme.colors.primaryText let labels = [subTitleLabel, usernameTitleLabel, emailTitleLabel, orLabel] for label in labels { label?.textColor = theme.colors.secondaryText } usernameField.apply(theme: theme) emailField.apply(theme: theme) resetPasswordButton.apply(theme: theme) } }
mit
57404b0a4fb2d5e6ba20253cc7cb10d3
42.962963
300
0.680034
5.652381
false
false
false
false
coach-plus/ios
Pods/Eureka/Source/Core/RowType.swift
2
9505
// RowType.swift // Eureka ( https://github.com/xmartlabs/Eureka ) // // Copyright (c) 2016 Xmartlabs ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import UIKit protocol Disableable: Taggable { func evaluateDisabled() var disabled: Condition? { get set } var isDisabled: Bool { get } } protocol Hidable: Taggable { func evaluateHidden() var hidden: Condition? { get set } var isHidden: Bool { get } } public protocol KeyboardReturnHandler: BaseRowType { var keyboardReturnType: KeyboardReturnTypeConfiguration? { get set } } public protocol Taggable: AnyObject { var tag: String? { get set } } public protocol BaseRowType: Taggable { /// The cell associated to this row. var baseCell: BaseCell! { get } /// The section to which this row belongs. var section: Section? { get } /// Parameter used when creating the cell for this row. var cellStyle: UITableViewCell.CellStyle { get set } /// The title will be displayed in the textLabel of the row. var title: String? { get set } /** Method that should re-display the cell */ func updateCell() /** Method called when the cell belonging to this row was selected. Must call the corresponding method in its cell. */ func didSelect() /** Typically we don't need to explicitly call this method since it is called by Eureka framework. It will validates the row if you invoke it. */ func validate() -> [ValidationError] } public protocol TypedRowType: BaseRowType { associatedtype Cell: BaseCell, TypedCellType /// The typed cell associated to this row. var cell: Cell! { get } /// The typed value this row stores. var value: Cell.Value? { get set } func add<Rule: RuleType>(rule: Rule) where Rule.RowValueType == Cell.Value func remove(ruleWithIdentifier: String) } /** * Protocol that every row type has to conform to. */ public protocol RowType: TypedRowType { init(_ tag: String?, _ initializer: (Self) -> Void) } extension RowType where Self: BaseRow { /** Default initializer for a row */ public init(_ tag: String? = nil, _ initializer: (Self) -> Void = { _ in }) { self.init(tag: tag) RowDefaults.rowInitialization["\(type(of: self))"]?(self) initializer(self) } } extension RowType where Self: BaseRow { /// The default block executed when the cell is updated. Applies to every row of this type. public static var defaultCellUpdate: ((Cell, Self) -> Void)? { set { if let newValue = newValue { let wrapper: (BaseCell, BaseRow) -> Void = { (baseCell: BaseCell, baseRow: BaseRow) in newValue(baseCell as! Cell, baseRow as! Self) } RowDefaults.cellUpdate["\(self)"] = wrapper RowDefaults.rawCellUpdate["\(self)"] = newValue } else { RowDefaults.cellUpdate["\(self)"] = nil RowDefaults.rawCellUpdate["\(self)"] = nil } } get { return RowDefaults.rawCellUpdate["\(self)"] as? ((Cell, Self) -> Void) } } /// The default block executed when the cell is created. Applies to every row of this type. public static var defaultCellSetup: ((Cell, Self) -> Void)? { set { if let newValue = newValue { let wrapper: (BaseCell, BaseRow) -> Void = { (baseCell: BaseCell, baseRow: BaseRow) in newValue(baseCell as! Cell, baseRow as! Self) } RowDefaults.cellSetup["\(self)"] = wrapper RowDefaults.rawCellSetup["\(self)"] = newValue } else { RowDefaults.cellSetup["\(self)"] = nil RowDefaults.rawCellSetup["\(self)"] = nil } } get { return RowDefaults.rawCellSetup["\(self)"] as? ((Cell, Self) -> Void) } } /// The default block executed when the cell becomes first responder. Applies to every row of this type. public static var defaultOnCellHighlightChanged: ((Cell, Self) -> Void)? { set { if let newValue = newValue { let wrapper: (BaseCell, BaseRow) -> Void = { (baseCell: BaseCell, baseRow: BaseRow) in newValue(baseCell as! Cell, baseRow as! Self) } RowDefaults.onCellHighlightChanged ["\(self)"] = wrapper RowDefaults.rawOnCellHighlightChanged["\(self)"] = newValue } else { RowDefaults.onCellHighlightChanged["\(self)"] = nil RowDefaults.rawOnCellHighlightChanged["\(self)"] = nil } } get { return RowDefaults.rawOnCellHighlightChanged["\(self)"] as? ((Cell, Self) -> Void) } } /// The default block executed to initialize a row. Applies to every row of this type. public static var defaultRowInitializer: ((Self) -> Void)? { set { if let newValue = newValue { let wrapper: (BaseRow) -> Void = { (baseRow: BaseRow) in newValue(baseRow as! Self) } RowDefaults.rowInitialization["\(self)"] = wrapper RowDefaults.rawRowInitialization["\(self)"] = newValue } else { RowDefaults.rowInitialization["\(self)"] = nil RowDefaults.rawRowInitialization["\(self)"] = nil } } get { return RowDefaults.rawRowInitialization["\(self)"] as? ((Self) -> Void) } } /// The default block executed to initialize a row. Applies to every row of this type. public static var defaultOnRowValidationChanged: ((Cell, Self) -> Void)? { set { if let newValue = newValue { let wrapper: (BaseCell, BaseRow) -> Void = { (baseCell: BaseCell, baseRow: BaseRow) in newValue(baseCell as! Cell, baseRow as! Self) } RowDefaults.onRowValidationChanged["\(self)"] = wrapper RowDefaults.rawOnRowValidationChanged["\(self)"] = newValue } else { RowDefaults.onRowValidationChanged["\(self)"] = nil RowDefaults.rawOnRowValidationChanged["\(self)"] = nil } } get { return RowDefaults.rawOnRowValidationChanged["\(self)"] as? ((Cell, Self) -> Void) } } /** Sets a block to be called when the value of this row changes. - returns: this row */ @discardableResult public func onChange(_ callback: @escaping (Self) -> Void) -> Self { callbackOnChange = { [unowned self] in callback(self) } return self } /** Sets a block to be called when the cell corresponding to this row is refreshed. - returns: this row */ @discardableResult public func cellUpdate(_ callback: @escaping ((_ cell: Cell, _ row: Self) -> Void)) -> Self { callbackCellUpdate = { [unowned self] in callback(self.cell, self) } return self } /** Sets a block to be called when the cell corresponding to this row is created. - returns: this row */ @discardableResult public func cellSetup(_ callback: @escaping ((_ cell: Cell, _ row: Self) -> Void)) -> Self { callbackCellSetup = { [unowned self] (cell: Cell) in callback(cell, self) } return self } /** Sets a block to be called when the cell corresponding to this row is selected. - returns: this row */ @discardableResult public func onCellSelection(_ callback: @escaping ((_ cell: Cell, _ row: Self) -> Void)) -> Self { callbackCellOnSelection = { [unowned self] in callback(self.cell, self) } return self } /** Sets a block to be called when the cell corresponding to this row becomes or resigns the first responder. - returns: this row */ @discardableResult public func onCellHighlightChanged(_ callback: @escaping (_ cell: Cell, _ row: Self) -> Void) -> Self { callbackOnCellHighlightChanged = { [unowned self] in callback(self.cell, self) } return self } @discardableResult public func onRowValidationChanged(_ callback: @escaping (_ cell: Cell, _ row: Self) -> Void) -> Self { callbackOnRowValidationChanged = { [unowned self] in callback(self.cell, self) } return self } }
mit
33618a9a8585c3a45802f7b3400df38c
35.841085
143
0.617675
4.7525
false
false
false
false
chatappcodepath/ChatAppSwift
LZChat/UserListViewController.swift
1
4252
// // UserListViewController.swift // LZChat // // Created by Kevin Balvantkumar Patel on 12/23/16. // // License // Copyright (c) 2017 chatappcodepath // Released under an MIT license: http://opensource.org/licenses/MIT // // // 1) Get the data // 2) Bind the table // 3) Make the cell // 4) populate the cells import UIKit protocol UserListViewControllerDelegate { func didSelectUser(_ selectedUser: LZUser) } class UserListViewController: UIViewController { @IBOutlet weak var userListTableView: UITableView! @IBOutlet weak var searchBar: UISearchBar! var userList:[LZUser]? { didSet { filteredUsers = userList } } var filteredUsers:[LZUser]? { didSet { if let old = oldValue, let filtered = filteredUsers { if (old == filtered) { return } } userListTableView.reloadData() } } var delegate:UserListViewControllerDelegate? override func viewDidLoad() { super.viewDidLoad() navigationController?.navigationBar.topItem?.title = "Back" bindViews() fetchDataSource() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func bindViews() { self.userListTableView.register(UINib(nibName: UserTableViewCell.nibName, bundle: Bundle.main), forCellReuseIdentifier: UserTableViewCell.reuseID) self.userListTableView.dataSource = self self.userListTableView.delegate = self self.searchBar.delegate = self } func fetchDataSource() { FirebaseUtils.sharedInstance.listAllUsers{ [weak self] (users) in guard let strongSelf = self else {return} strongSelf.userList = users } } } extension UserListViewController: UISearchBarDelegate { func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { if searchText == "" { filteredUsers = userList return } let newfilteredUsers = userList?.filter({ (user) -> Bool in if let userName = user.name?.lowercased(), let userEmail = user.email?.lowercased() { let lowerCaseSearchTerm = searchText.lowercased() let retVal = userName.contains(lowerCaseSearchTerm) || userEmail.contains(lowerCaseSearchTerm) return retVal } return false }) filteredUsers = newfilteredUsers } } extension UserListViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { guard let filteredUsers = filteredUsers else { return 0 } return filteredUsers.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let userCell = tableView.dequeueReusableCell(withIdentifier: UserTableViewCell.reuseID) as! UserTableViewCell userCell.displayUser = filteredUsers![indexPath.row] return userCell } } extension UserListViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UserTableViewCell.cellHeight } func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { // willDisplayCell guard let cell = cell as? UserTableViewCell else {return} cell.fetchImage() } func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) { // didEndDisplayingCell guard let cell = cell as? UserTableViewCell else {return} cell.cancelImageFetching() } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let selectedUser = filteredUsers![indexPath.row] self.delegate?.didSelectUser(selectedUser) } }
mit
17bdeb8b160e094a602003e333942a56
28.943662
154
0.644638
5.465296
false
false
false
false
siberianisaev/NeutronBarrel
NeutronBarrel/NeutronDetector.swift
1
2611
// // NeutronDetector.swift // NeutronBarrel // // Created by Andrey Isaev on 11.05.2021. // Copyright © 2021 Flerov Laboratory. All rights reserved. // import Foundation class NeutronDetector { fileprivate var locations = [Int: CGPoint]() /** Counter coordinates (in mm). */ class func pointFor(counter: Int) -> CGPoint? { return singleton.locations[counter] } class var singleton : NeutronDetector { struct Static { static let sharedInstance : NeutronDetector = NeutronDetector() } return Static.sharedInstance } init() { if let url = Bundle.main.url(forResource: "SFiNx_counters_geometry", withExtension: "csv") { do { let text = try String(contentsOf: url) for row in text.components(separatedBy: CharacterSet.newlines).filter({ !$0.isEmpty }) { let values = row.components(separatedBy: ";") if values.count == 3, let counter = Int(values[0]), let x = Double(values[1]), let y = Double(values[2]) { // TODO: convert them to mm in csv locations[counter] = CGPoint(x: x * 10, y: y * 10) } } } catch { print(error) } } } /** If angle is negative, then neutron is related to fragment from side detector. */ class func angle(neutronPoint: CGPoint, focalFragmentPoint: PointXYZ, sideFragmentPoint: PointXYZ) -> CGFloat { // y = mx + k let m = (sideFragmentPoint.y - focalFragmentPoint.y)/(sideFragmentPoint.x - focalFragmentPoint.x) let k = focalFragmentPoint.y - focalFragmentPoint.x * m let altitude = abs(k + m * neutronPoint.x - neutronPoint.y) / sqrt(1 + pow(m, 2)) let hipotenuse = sqrt(pow(focalFragmentPoint.x - neutronPoint.x, 2) + pow(focalFragmentPoint.y - neutronPoint.y, 2)) let sinus = altitude / hipotenuse let angle = asin(sinus) * 180 / CGFloat.pi func isAtBottomOfPerpindicularLineToFocalFragment(x: CGFloat, y: CGFloat) -> Bool { let perpendicularY = (-1/m)*(x - focalFragmentPoint.x) + focalFragmentPoint.y return y < perpendicularY } if isAtBottomOfPerpindicularLineToFocalFragment(x: neutronPoint.x, y: neutronPoint.y) == isAtBottomOfPerpindicularLineToFocalFragment(x: sideFragmentPoint.x, y: sideFragmentPoint.y) { return -angle } else { return angle } } }
mit
362ffd98d3c385fac09f35885497b461
36.285714
192
0.587739
4.371859
false
false
false
false
ABTSoftware/SciChartiOSTutorial
v2.x/Examples/SciChartSwiftDemo/SciChartSwiftDemo/Views/TooltipsAndHitTest/UsingCursorModifierChartView.swift
1
4085
//****************************************************************************** // SCICHART® Copyright SciChart Ltd. 2011-2018. All rights reserved. // // Web: http://www.scichart.com // Support: [email protected] // Sales: [email protected] // // UsingCursorModifierChartView.swift is part of the SCICHART® Examples. Permission is hereby granted // to modify, create derivative works, distribute and publish any part of this source // code whether for commercial, private or personal use. // // The SCICHART® examples are distributed in the hope that they will be useful, but // without any warranty. It is provided "AS IS" without warranty of any kind, either // expressed or implied. //****************************************************************************** class UsingCursorModifierChartView: SingleChartLayout { let PointsCount: Int32 = 500 override func initExample() { let xAxis = SCINumericAxis(); xAxis.visibleRange = SCIDoubleRange(min: SCIGeneric(3), max: SCIGeneric(6)) let yAxis = SCINumericAxis(); yAxis.growBy = SCIDoubleRange(min: SCIGeneric(0.05), max: SCIGeneric(0.05)) yAxis.autoRange = .always let ds1 = SCIXyDataSeries(xType: .double, yType: .double) ds1.seriesName = "Green Series"; let ds2 = SCIXyDataSeries(xType: .double, yType: .double) ds2.seriesName = "Red Series"; let ds3 = SCIXyDataSeries(xType: .double, yType: .double) ds3.seriesName = "Gray Series"; let ds4 = SCIXyDataSeries(xType: .double, yType: .double) ds4.seriesName = "Gold Series"; let data1 = DataManager.getNoisySinewave(withAmplitude: 300, phase: 1.0, pointCount: PointsCount, noiseAmplitude: 0.25) let data2 = DataManager.getSinewaveWithAmplitude(100, phase: 2.0, pointCount: PointsCount) let data3 = DataManager.getSinewaveWithAmplitude(200, phase: 1.5, pointCount: PointsCount) let data4 = DataManager.getSinewaveWithAmplitude(50, phase: 0.1, pointCount: PointsCount) ds1.appendRangeX(data1!.xValues, y: data1!.yValues, count: data1!.size) ds2.appendRangeX(data2!.xValues, y: data2!.yValues, count: data2!.size) ds3.appendRangeX(data3!.xValues, y: data3!.yValues, count: data3!.size) ds4.appendRangeX(data4!.xValues, y: data4!.yValues, count: data4!.size) let rs1 = SCIFastLineRenderableSeries() rs1.dataSeries = ds1 rs1.strokeStyle = SCISolidPenStyle(colorCode: 0xFF177B17, withThickness: 2) let rs2 = SCIFastLineRenderableSeries() rs2.dataSeries = ds2 rs2.strokeStyle = SCISolidPenStyle(colorCode: 0xFFDD0909, withThickness: 2) let rs3 = SCIFastLineRenderableSeries() rs3.dataSeries = ds3 rs3.strokeStyle = SCISolidPenStyle(colorCode: 0xFF808080, withThickness: 2) let rs4 = SCIFastLineRenderableSeries() rs4.dataSeries = ds4 rs4.strokeStyle = SCISolidPenStyle(colorCode: 0xFFFFD700, withThickness: 2) rs4.isVisible = false let cursorModifier = SCICursorModifier() cursorModifier.style.colorMode = .seriesColorToDataView SCIUpdateSuspender.usingWithSuspendable(surface) { self.surface.xAxes.add(xAxis) self.surface.yAxes.add(yAxis) self.surface.renderableSeries.add(rs1) self.surface.renderableSeries.add(rs2) self.surface.renderableSeries.add(rs3) self.surface.renderableSeries.add(rs4) self.surface.chartModifiers.add(cursorModifier) rs1.addAnimation(SCISweepRenderableSeriesAnimation(duration: 3, curveAnimation: .easeOut)) rs2.addAnimation(SCISweepRenderableSeriesAnimation(duration: 3, curveAnimation: .easeOut)) rs3.addAnimation(SCISweepRenderableSeriesAnimation(duration: 3, curveAnimation: .easeOut)) rs4.addAnimation(SCISweepRenderableSeriesAnimation(duration: 3, curveAnimation: .easeOut)) } } }
mit
c54992831c99a16e035f5678afeb2db2
48.180723
127
0.652376
4.37045
false
false
false
false
Eonil/HomeworkApp1
Driver/HomeworkApp1/API.JSONConversion.swift
1
2979
// // API.Deserialisation.swift // HomeworkApp1 // // Created by Hoon H. on 2015/02/26. // // import Foundation import Standards extension API.Response: ErrorTrappingJSONInitializable { init?(json: JSON.Value, errorTrap: (String) -> ()) { let o = json.object if o == nil { errorTrap("Supplied `JSON.Value` should be an `Object`."); return nil } let r1 = o!["responseData"] if r1 == nil { errorTrap("Supplied `JSON.Value` should have `responseData` field."); return nil } let r2 = ResponseData(json: r1!, errorTrap: errorTrap) if r2 == nil { errorTrap("Could not read `ResponseData` from supplied JSON object."); return nil } self.responseData = r2! } } extension API.Response.ResponseData: ErrorTrappingJSONInitializable { init?(json: JSON.Value, errorTrap: (String) -> ()) { let o = json.object if o == nil { errorTrap("Supplied `JSON.Value` should be an `Object`."); return nil } let r1 = o!["results"] if r1 == nil { errorTrap("Supplied `JSON.Value` shold have `result` field."); return nil } let r2 = r1!.array if r2 == nil { errorTrap("Supplied `JSON.Value` shold have `result` field of `JSON.Array`."); return nil } let r3 = r2!.map({ j in ResultItem(json: j, errorTrap: errorTrap) }) for m in r3 { if m == nil { errorTrap("One or more items from JSON array could not be parsed into `ResultItem`."); return nil } } let r4 = r3.map({ m in m! }) self.results = r4 } } extension API.Response.ResponseData.ResultItem: ErrorTrappingJSONInitializable { init?(json: JSON.Value, errorTrap: (String) -> ()) { let o = json.object if o == nil { errorTrap("Supplied `JSON.Value` should be an `Object`."); return nil } if let s = json.stringObjectFieldForName("titleNoFormatting", errorTrap: errorTrap) { self.titleNoFormatting = s } else { return nil } if let s = json.stringObjectFieldForName("url", errorTrap: errorTrap) { self.url = s } else { return nil } } } private extension JSON.Value { /// Returns `nil` for any error. (`nil` is always an error marker value, and not for replacement for `JSON.Value.Null`) func stringObjectFieldForName(fieldName:Swift.String, errorTrap:(Swift.String)->()) -> Swift.String? { if self.object == nil { errorTrap("Current object is not a `JSON.Object`."); return nil } let v = self.object![fieldName] if v == nil { errorTrap("Current object does not have `\(fieldName)` field."); return nil } let s = v!.string if s == nil { errorTrap("`\(fieldName)` field is not an `JSON.String` value."); return nil } return s! } } protocol ErrorTrappingJSONInitializable { /// :param: errorTrap /// Called immediately for any error. Execution state will be provided in debugger. /// You can do whatever you want. If you do nothing in here, /// object initilization MUST be fail and the initializer SHOULD return `nil`. init?(json: JSON.Value, errorTrap:(String)->()) }
mit
316be224fef13b82b80f3d72e7a6cc38
20.744526
120
0.661631
3.347191
false
false
false
false
karimsallam/Reactive
Pods/ReactiveSwift/Sources/UnidirectionalBinding.swift
4
10988
import Foundation import Dispatch import enum Result.NoError precedencegroup BindingPrecedence { associativity: right // Binds tighter than assignment but looser than everything else higherThan: AssignmentPrecedence } infix operator <~ : BindingPrecedence /// Describes a target to which can be bound. public protocol BindingTargetProtocol: class { associatedtype Value /// The lifetime of `self`. The binding operators use this to determine when /// the binding should be teared down. var lifetime: Lifetime { get } /// Consume a value from the binding. func consume(_ value: Value) /// Binds a signal to a target, updating the target's value to the latest /// value sent by the signal. /// /// - note: The binding will automatically terminate when the target is /// deinitialized, or when the signal sends a `completed` event. /// /// ```` /// let property = MutableProperty(0) /// let signal = Signal({ /* do some work after some time */ }) /// property <~ signal /// ```` /// /// ```` /// let property = MutableProperty(0) /// let signal = Signal({ /* do some work after some time */ }) /// let disposable = property <~ signal /// ... /// // Terminates binding before property dealloc or signal's /// // `completed` event. /// disposable.dispose() /// ```` /// /// - parameters: /// - target: A target to be bond to. /// - signal: A signal to bind. /// /// - returns: A disposable that can be used to terminate binding before the /// deinitialization of the target or the signal's `completed` /// event. @discardableResult static func <~ <Source: SignalProtocol>(target: Self, signal: Source) -> Disposable? where Source.Value == Value, Source.Error == NoError } extension BindingTargetProtocol { /// Binds a signal to a target, updating the target's value to the latest /// value sent by the signal. /// /// - note: The binding will automatically terminate when the target is /// deinitialized, or when the signal sends a `completed` event. /// /// ```` /// let property = MutableProperty(0) /// let signal = Signal({ /* do some work after some time */ }) /// property <~ signal /// ```` /// /// ```` /// let property = MutableProperty(0) /// let signal = Signal({ /* do some work after some time */ }) /// let disposable = property <~ signal /// ... /// // Terminates binding before property dealloc or signal's /// // `completed` event. /// disposable.dispose() /// ```` /// /// - parameters: /// - target: A target to be bond to. /// - signal: A signal to bind. /// /// - returns: A disposable that can be used to terminate binding before the /// deinitialization of the target or the signal's `completed` /// event. @discardableResult public static func <~ <Source: SignalProtocol>(target: Self, signal: Source) -> Disposable? where Source.Value == Value, Source.Error == NoError { return signal .take(during: target.lifetime) .observeValues { [weak target] value in target?.consume(value) } } /// Binds a producer to a target, updating the target's value to the latest /// value sent by the producer. /// /// - note: The binding will automatically terminate when the target is /// deinitialized, or when the producer sends a `completed` event. /// /// ```` /// let property = MutableProperty(0) /// let producer = SignalProducer<Int, NoError>(value: 1) /// property <~ producer /// print(property.value) // prints `1` /// ```` /// /// ```` /// let property = MutableProperty(0) /// let producer = SignalProducer({ /* do some work after some time */ }) /// let disposable = (property <~ producer) /// ... /// // Terminates binding before property dealloc or /// // signal's `completed` event. /// disposable.dispose() /// ```` /// /// - parameters: /// - target: A target to be bond to. /// - producer: A producer to bind. /// /// - returns: A disposable that can be used to terminate binding before the /// deinitialization of the target or the producer's `completed /// event. @discardableResult public static func <~ <Source: SignalProducerProtocol>(target: Self, producer: Source) -> Disposable where Source.Value == Value, Source.Error == NoError { var disposable: Disposable! producer .take(during: target.lifetime) .startWithSignal { signal, signalDisposable in disposable = signalDisposable target <~ signal } return disposable } /// Binds a property to a target, updating the target's value to the latest /// value sent by the property. /// /// - note: The binding will automatically terminate when either the target or /// the property deinitializes. /// /// ```` /// let dstProperty = MutableProperty(0) /// let srcProperty = ConstantProperty(10) /// dstProperty <~ srcProperty /// print(dstProperty.value) // prints 10 /// ```` /// /// ```` /// let dstProperty = MutableProperty(0) /// let srcProperty = ConstantProperty(10) /// let disposable = (dstProperty <~ srcProperty) /// ... /// disposable.dispose() // terminate the binding earlier if /// // needed /// ```` /// /// - parameters: /// - target: A target to be bond to. /// - property: A property to bind. /// /// - returns: A disposable that can be used to terminate binding before the /// deinitialization of the target or the source property. @discardableResult public static func <~ <Source: PropertyProtocol>(target: Self, property: Source) -> Disposable where Source.Value == Value { return target <~ property.producer } } extension BindingTargetProtocol where Value: OptionalProtocol { /// Binds a signal to a target, updating the target's value to the latest /// value sent by the signal. /// /// - note: The binding will automatically terminate when the target is /// deinitialized, or when the signal sends a `completed` event. /// /// ```` /// let property = MutableProperty(0) /// let signal = Signal({ /* do some work after some time */ }) /// property <~ signal /// ```` /// /// ```` /// let property = MutableProperty(0) /// let signal = Signal({ /* do some work after some time */ }) /// let disposable = property <~ signal /// ... /// // Terminates binding before property dealloc or signal's /// // `completed` event. /// disposable.dispose() /// ```` /// /// - parameters: /// - target: A target to be bond to. /// - signal: A signal to bind. /// /// - returns: A disposable that can be used to terminate binding before the /// deinitialization of the target or the signal's `completed` /// event. @discardableResult public static func <~ <Source: SignalProtocol>(target: Self, signal: Source) -> Disposable? where Source.Value == Value.Wrapped, Source.Error == NoError { return target <~ signal.map(Value.init(reconstructing:)) } /// Binds a producer to a target, updating the target's value to the latest /// value sent by the producer. /// /// - note: The binding will automatically terminate when the target is /// deinitialized, or when the producer sends a `completed` event. /// /// ```` /// let property = MutableProperty(0) /// let producer = SignalProducer<Int, NoError>(value: 1) /// property <~ producer /// print(property.value) // prints `1` /// ```` /// /// ```` /// let property = MutableProperty(0) /// let producer = SignalProducer({ /* do some work after some time */ }) /// let disposable = (property <~ producer) /// ... /// // Terminates binding before property dealloc or /// // signal's `completed` event. /// disposable.dispose() /// ```` /// /// - parameters: /// - target: A target to be bond to. /// - producer: A producer to bind. /// /// - returns: A disposable that can be used to terminate binding before the /// deinitialization of the target or the producer's `completed` /// event. @discardableResult public static func <~ <Source: SignalProducerProtocol>(target: Self, producer: Source) -> Disposable where Source.Value == Value.Wrapped, Source.Error == NoError { return target <~ producer.map(Value.init(reconstructing:)) } /// Binds a property to a target, updating the target's value to the latest /// value sent by the property. /// /// - note: The binding will automatically terminate when either the target or /// the property deinitializes. /// /// ```` /// let dstProperty = MutableProperty(0) /// let srcProperty = ConstantProperty(10) /// dstProperty <~ srcProperty /// print(dstProperty.value) // prints 10 /// ```` /// /// ```` /// let dstProperty = MutableProperty(0) /// let srcProperty = ConstantProperty(10) /// let disposable = (dstProperty <~ srcProperty) /// ... /// disposable.dispose() // terminate the binding earlier if /// // needed /// ```` /// /// - note: The binding will automatically terminate when either property is /// deinitialized. /// /// - parameters: /// - target: A target to be bond to. /// - property: A property to bind. /// /// - returns: A disposable that can be used to terminate binding before the /// deinitialization of the target or the source property. @discardableResult public static func <~ <Source: PropertyProtocol>(target: Self, property: Source) -> Disposable where Source.Value == Value.Wrapped { return target <~ property.producer } } /// A binding target that can be used with the `<~` operator. public final class BindingTarget<Value>: BindingTargetProtocol { public let lifetime: Lifetime private let setter: (Value) -> Void /// Creates a binding target. /// /// - parameters: /// - lifetime: The expected lifetime of any bindings towards `self`. /// - setter: The action to consume values. public init(lifetime: Lifetime, setter: @escaping (Value) -> Void) { self.setter = setter self.lifetime = lifetime } /// Creates a binding target which consumes values on the specified scheduler. /// /// - parameters: /// - scheduler: The scheduler on which the `setter` consumes the values. /// - lifetime: The expected lifetime of any bindings towards `self`. /// - setter: The action to consume values. public convenience init(on scheduler: SchedulerProtocol, lifetime: Lifetime, setter: @escaping (Value) -> Void) { let setter: (Value) -> Void = { value in scheduler.schedule { setter(value) } } self.init(lifetime: lifetime, setter: setter) } public func consume(_ value: Value) { setter(value) } @discardableResult public static func <~ <Source: SignalProtocol>(target: BindingTarget<Value>, signal: Source) -> Disposable? where Source.Value == Value, Source.Error == NoError { return signal .take(during: target.lifetime) .observeValues { [setter = target.setter] value in setter(value) } } } private let specificKey = DispatchSpecificKey<ObjectIdentifier>()
apache-2.0
d74c197243530fe1460f573ddb41215f
32.705521
164
0.65071
3.93694
false
false
false
false
kamarshad/CMT40
VideoResume/VideoResume/RecordVideo/View/RecordVideoViewController.swift
1
5902
// // ViewController.swift // VideoResume // // Created by Mohd Kamar on 03/08/17. // Copyright © 2017 Mohd Kamar Shad. All rights reserved. // import UIKit import MZTimerLabel class RecordVideoViewController : SwiftyCamViewController { fileprivate var captureButton: SwiftyRecordButton! fileprivate var flipCameraButton: UIButton! fileprivate var cancel: UIButton! var presenter: RecordVideoPresenter! fileprivate var timer: MZTimerLabel! @IBOutlet fileprivate weak var timerLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() self.setUp() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func setUp() { self.maximumVideoDuration = 10 self.audioEnabled = true self.outputFileName = self.presenter.getOutputFileName() self.cameraDelegate = self self.configureOverylayOptions() } @objc private func cameraSwitchAction(_ sender: Any) { self.switchCamera() } @objc private func cancelVideoRecording(_ sender: Any) { self.presenter.goBackToPreviousScreen() } fileprivate func configureOverylayOptions() { self.captureButton = SwiftyRecordButton(frame: CGRect(x: view.frame.midX - 37.5, y: view.frame.height - 100.0, width: 75.0, height: 75.0)) self.view.addSubview(self.captureButton) self.captureButton.delegate = self self.flipCameraButton = UIButton(frame: CGRect(x: (((view.frame.width / 2 - 37.5) / 2) - 15.0), y: view.frame.height - 74.0, width: 30.0, height: 23.0)) self.flipCameraButton.setImage(#imageLiteral(resourceName: "flipCamera"), for: UIControlState()) self.flipCameraButton.addTarget(self, action: #selector(cameraSwitchAction(_:)), for: .touchUpInside) self.view.addSubview(self.flipCameraButton) let test = CGFloat((view.frame.width - (view.frame.width / 2 + 37.5)) + ((view.frame.width / 2) - 37.5) - 9.0) self.cancel = UIButton(frame: CGRect(x: test, y: view.frame.height - 77.5, width: 60, height: 30.0)) self.cancel.setImage(#imageLiteral(resourceName: "cancel"), for: UIControlState()) self.cancel.addTarget(self, action: #selector(cancelVideoRecording(_:)), for: .touchUpInside) self.view.addSubview(self.cancel) timer = MZTimerLabel(frame: self.timerLabel.frame) timer.isHidden = true timer.timeFormat = "mm:ss" timer.font = UIFont.boldSystemFont(ofSize: 24.0) timer.textAlignment = .center timer.textColor = UIColor.white self.view.addSubview(timer) } fileprivate func showVideoRecoredAlert() { let title = NSLocalizedString("", comment: "") let message = NSLocalizedString("That was a fantastic video if you are not satisfied", comment: "") let recordAgainActionTitle = NSLocalizedString("Record Again", comment: "") let nextActionTitle = NSLocalizedString("Next", comment: "") let alert = UIAlertController (title: title, message: message, preferredStyle: .alert) alert.addAction(UIAlertAction(title: recordAgainActionTitle, style: .default, handler: { (action) in self.captureButton.startStopVideoRecording() })) alert.addAction(UIAlertAction(title: nextActionTitle, style: .default, handler: { (action) in self.presenter.goToNextScreen() })) present(alert, animated: true, completion: nil) } } extension RecordVideoViewController : SwiftyCamViewControllerDelegate { func swiftyCam(_ swiftyCam: SwiftyCamViewController, didBeginRecordingVideo camera: SwiftyCamViewController.CameraSelection) { print("Did Begin Recording") timer.isHidden = false self.timer.reset() self.timer.start() self.captureButton.growButton() UIView.animate(withDuration: 0.25, animations: { self.flipCameraButton.alpha = 0.0 self.cancel.alpha = 0.0 }) } func swiftyCam(_ swiftyCam: SwiftyCamViewController, didFinishRecordingVideo camera: SwiftyCamViewController.CameraSelection) { print("Did finish Recording") self.captureButton.shrinkButton() self.timer.pause() UIView.animate(withDuration: 0.25, animations: { self.flipCameraButton.alpha = 1.0 self.cancel.alpha = 1.0 self.showVideoRecoredAlert() }) } func swiftyCam(_ swiftyCam: SwiftyCamViewController, didFinishProcessVideoAt url: URL) { } func swiftyCam(_ swiftyCam: SwiftyCamViewController, didFocusAtPoint point: CGPoint) { let focusView = UIImageView(image: #imageLiteral(resourceName: "focus")) focusView.center = point focusView.alpha = 0.0 view.addSubview(focusView) UIView.animate(withDuration: 0.25, delay: 0.0, options: .curveEaseInOut, animations: { focusView.alpha = 1.0 focusView.transform = CGAffineTransform(scaleX: 1.25, y: 1.25) }, completion: { (success) in UIView.animate(withDuration: 0.15, delay: 0.5, options: .curveEaseInOut, animations: { focusView.alpha = 0.0 focusView.transform = CGAffineTransform(translationX: 0.6, y: 0.6) }, completion: { (success) in focusView.removeFromSuperview() }) }) } func swiftyCam(_ swiftyCam: SwiftyCamViewController, didChangeZoomLevel zoom: CGFloat) { print(zoom) } func swiftyCam(_ swiftyCam: SwiftyCamViewController, didSwitchCameras camera: SwiftyCamViewController.CameraSelection) { print(camera) } }
mit
80896888ba1e34959744cc32bcfabef7
36.826923
160
0.653449
4.653785
false
false
false
false
MorganCabral/swiftrekt-ios-app-dev-challenge-2015
app-dev-challenge/app-dev-challenge/GameOverSprite.swift
1
1320
// // GameOverSprite.swift // app-dev-challenge // // Created by Tina on 2/8/15. // Copyright (c) 2015 Team SwiftRekt. All rights reserved. // import Foundation import SpriteKit public class GameOverSprite: SKLabelNode{ public override init(){ super.init() } public init( positionOnScene : CGPoint) { super.init(fontNamed: "Palatino") self.text = "" self.fontColor = UIColor.blackColor() self.fontSize = 30 self.position = positionOnScene } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public var winningPlayerID : Int { get { return winningPlayerID } set ( playerID ) { if( playerID == 1 ) { self.text = "Player One Wins!" } else if ( playerID == 0) { self.text = "Player Two Wins!" } else { self.text = "Tie" } } } public func doSlideAnimation(){ var waitAction = SKAction.waitForDuration(NSTimeInterval(1.0)) var slideInAnimation = SKAction.moveToY(500.0, duration: 1.0) self.runAction(SKAction.sequence([waitAction, slideInAnimation])) } }
mit
a624c2019570b6b656746b6923b6ff91
23.462963
73
0.554545
4.385382
false
false
false
false
cxy921126/SoftSwift
Swimmer/Swimmer/LocationTool.swift
1
3802
// // LocationTool.swift // Swimmer // // Created by Mac mini on 16/9/9. // Copyright © 2016年 cxy. All rights reserved. // import UIKit import CoreLocation fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } fileprivate func >= <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l >= r default: return !(lhs < rhs) } } @objc protocol LocationToolDelegate: NSObjectProtocol{ @objc optional func locationTool(_ locationTool: LocationTool, detectedNewLocation city: String) @objc optional func locationTool(_ locationTool: LocationTool, onlyGetCity city: String) } enum LocationToolMode { case fixed case detectOnly } class LocationTool: NSObject { ///保存实例的模式 var toolMode: LocationToolMode? weak var delegate: LocationToolDelegate? var geoCoder = CLGeocoder() lazy var locationMgr: CLLocationManager = { let manager = CLLocationManager() manager.delegate = self if Float(UIDevice.current.systemVersion) >= 8.0 { manager.requestWhenInUseAuthorization() manager.pausesLocationUpdatesAutomatically = true manager.distanceFilter = 1000 manager.startUpdatingLocation() }else{ print("Location Service disabled") } return manager }() init(withMode: LocationToolMode) { super.init() toolMode = withMode fixedLocation(.fixed) } func fixedLocation(_ withMode: LocationToolMode){ guard let location = locationMgr.location else { print("can not get location") return } switch withMode { case .fixed: geoCoder.reverseGeocodeLocation(location) { (places, error) in if error != nil{ print(error) }else{ let detectedCity = places?.first?.locality if let storedCity = UserDefaults.standard.object(forKey: "city") { //若存在已保存的城市,判断是否不同于检测到的城市 if (storedCity as? String) != detectedCity && detectedCity != nil{ self.delegate?.locationTool!(self, detectedNewLocation: detectedCity!) } }else{ self.delegate?.locationTool!(self, detectedNewLocation: detectedCity!) } //self.currentCity = places?.first?.locality } } break //只定位城市不进行比较 case .detectOnly: detectOnly(location, finished: { (city) in self.delegate?.locationTool!(self, onlyGetCity: city) }) break } } func detectOnly(_ location: CLLocation, finished:@escaping (_ city: String)->()){ var city: String? let simpleGeoCoder = CLGeocoder() simpleGeoCoder.reverseGeocodeLocation(location) { (places, error) in if error != nil{ print(error) }else{ if places?.first?.locality != nil{ city = (places?.first?.locality)! finished(city!) } } } } } //MARK: - CLLocationManagerDelegate extension LocationTool: CLLocationManagerDelegate{ func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { print(locations) fixedLocation(toolMode!) } }
mit
ff92c8dd5de2acaae6f31adf09b412f2
28.283465
100
0.558752
4.886991
false
false
false
false
open-telemetry/opentelemetry-swift
Tests/ExportersTests/DatadogExporter/Helpers/SwiftExtensions.swift
1
2364
/* * Copyright The OpenTelemetry Authors * SPDX-License-Identifier: Apache-2.0 */ import Foundation import XCTest /* Set of general extensions over standard types for writting more readable tests. Extensiosn using Datadog domain objects should be put in `DatadogExtensions.swift`. */ extension Optional { struct UnwrappingException: Error {} func unwrapOrThrow(file: StaticString = #file, line: UInt = #line) throws -> Wrapped { switch self { case .some(let unwrappedValue): return unwrappedValue case .none: XCTFail("Expected value, got `nil`.", file: file, line: line) throw UnwrappingException() } } } extension Date { func secondsAgo(_ seconds: TimeInterval) -> Date { return addingTimeInterval(-seconds) } } extension TimeZone { static var UTC: TimeZone { TimeZone(abbreviation: "UTC")! } static var EET: TimeZone { TimeZone(abbreviation: "EET")! } static func mockAny() -> TimeZone { .EET } } extension Calendar { static var gregorian: Calendar { return Calendar(identifier: .gregorian) } } extension String { var utf8Data: Data { data(using: .utf8)! } func removingPrefix(_ prefix: String) -> String { if self.hasPrefix(prefix) { return String(self.dropFirst(prefix.count)) } else { fatalError("`\(self)` has no prefix of `\(prefix)`") } } } extension Data { var utf8String: String { String(decoding: self, as: UTF8.self) } } extension InputStream { func readAllBytes(expectedSize: Int) -> Data { var data = Data() open() let buffer: UnsafeMutablePointer<UInt8> = .allocate(capacity: expectedSize) while hasBytesAvailable { let bytesRead = self.read(buffer, maxLength: expectedSize) guard bytesRead >= 0 else { fatalError("Stream error occured.") } if bytesRead == 0 { break } data.append(buffer, count: bytesRead) } buffer.deallocate() close() return data } } extension URLRequest { func removing(httpHeaderField: String) -> URLRequest { var request = self request.setValue(nil, forHTTPHeaderField: httpHeaderField) return request } }
apache-2.0
cf315028fe3c40026ed2753fc7545742
23.625
90
0.61379
4.528736
false
false
false
false
aulas-lab/ads-mobile
swift/Aula2/Aula2/main.swift
1
1079
// // main.swift // Aula2 // // Created by Mobitec on 14/04/16. // Copyright (c) 2016 Unopar. All rights reserved. // import Foundation func leitura() -> String { var teclado = NSFileHandle.fileHandleWithStandardInput() var lido = teclado.availableData return NSString( data: lido, encoding: NSUTF8StringEncoding) as String } let calc = Calculadora() println("Calculadora Unopar") var op: String do { print("Operacao (+,-,/,*): ") op = leitura() print("Valor: ") let vl = (leitura() as NSString).floatValue switch op { case "+\n": calc.executa(vl, op: EOperacao.Adicao) break case "-\n": calc.executa(vl, op: EOperacao.Subtracao) break case "/\n": calc.executa(vl, op: EOperacao.Divisao) break case "*\n": calc.executa(vl, op: EOperacao.Multiplicacao) break case "\n": break default: println("Operacao Invalida!") break } } while op != "\n" println("Total: \(calc.executa(0.0, op: EOperacao.Adicao))")
mit
41bcc64c887346137c9c9c3ec58ac9c4
16.983333
61
0.588508
3.458333
false
false
false
false
GitHubStuff/SwiftIntervals
SwiftEvents/TimeManager.swift
1
5684
// // TimeManager.swift // SwiftEvents // // Created by Steven Smith on 1/17/17. // Copyright © 2017 LTMM. All rights reserved. // import Foundation enum TimeEnum : String { case asAM, asPM } class TimeManager { let timeManager : Notification.Name = Notification.Name(rawValue: "TimeManager") var result : String { get { return h1 + h2 + ":" + m1 + m2 } } private var h1 = "0" private var h2 = "0" private var m1 = "0" private var m2 = "0" private var position = 0 private var status = CalendarManagerCodes.building private let notificationCenter : NotificationCenter init(notificationCenter: NotificationCenter) { self.notificationCenter = notificationCenter } private func broadcast(reason: CalendarManagerCodes, result: String, digit: String) -> (CalendarManagerCodes, String) { self.status = reason let userInfo = [CalendarManagerCodes.keyStatus : reason, CalendarManagerCodes.keyResult: result, CalendarManagerCodes.keyBuild : digit] as [CalendarManagerCodes : Any] self.notificationCenter.post(name: self.timeManager, object: nil, userInfo: userInfo) return (reason, result) } private func ripple(digit: String) { h1 = h2 h2 = m1 m1 = m2 m2 = digit position += 1 } func add(digit: String) -> (CalendarManagerCodes, String) { guard digit >= "0" && digit <= "9" && self.status != .completed else { return broadcast(reason: .badInput, result: self.result, digit: digit) } switch(position) { case 0: return parseM2(digit: digit) case 1: return parseM1(digit: digit) case 2: return parseH2(digit: digit) case 3: return parseH1(digit: digit) default: return broadcast(reason: .badInput, result: self.result, digit: digit) } } func adjust(clockType: TimeEnum) -> (CalendarManagerCodes, String) { switch clockType { case .asAM: return setAsAM() case .asPM: return setAsPM() } } private func setAsAM() -> (CalendarManagerCodes, String) { let hours = Int(h1+h2)! switch hours { case 12: h1 = "0" h2 = "0" case 13...23: return broadcast(reason: CalendarManagerCodes.badInput, result: self.result, digit: TimeEnum.asAM.rawValue) default: break } return broadcast(reason: CalendarManagerCodes.building, result: self.result, digit: TimeEnum.asAM.rawValue) } private func setAsPM() -> (CalendarManagerCodes, String) { var hours = Int(h1+h2)! if hours == 0 { return broadcast(reason: .building, result: self.result, digit: TimeEnum.asPM.rawValue) } if hours < 12 { hours += 12 } h1 = String(hours / 10) h2 = String(hours % 10) return broadcast(reason: .building, result: self.result, digit: TimeEnum.asPM.rawValue) } private func parseM2(digit: String) -> (CalendarManagerCodes, String) { if digit == "0" { return (.building, self.result) } ripple(digit: digit) return broadcast(reason: .building, result: self.result, digit: digit) } private func parseM1(digit: String) -> (CalendarManagerCodes, String) { if self.m2 >= "6" && self.m2 <= "9" { guard digit <= "5" else { return broadcast(reason: .badInput, result: self.result, digit: digit) } ripple(digit: digit) return broadcast(reason: .incomplete, result: self.result, digit: digit) } if self.m2 >= "3" && digit >= "6" { ripple(digit: digit) return broadcast(reason: .completed, result: self.result, digit: digit) } ripple(digit: digit) return broadcast(reason: .building, result: self.result, digit: digit) } private func parseH2(digit: String) -> (CalendarManagerCodes, String) { if m1 == "1" && (m2 >= "6" && m2 <= "9") { guard digit <= "5" else { return broadcast(reason: .badInput, result: self.result, digit: digit) } ripple(digit: digit) return broadcast(reason: .incomplete, result: self.result, digit: digit) } if m1 >= "3" { ripple(digit: digit) return broadcast(reason: .completed, result: self.result, digit: digit) } if m1 == "2" && (m2 == "4" || m2 == "5") { ripple(digit: digit) return broadcast(reason: .completed, result: self.result, digit: digit) } if m1 == "2" && digit >= "6" { ripple(digit: digit) return broadcast(reason: .completed, result: self.result, digit: digit) } if m1 >= "3" && m1 <= "9" { ripple(digit: digit) return broadcast(reason: .completed, result: self.result, digit: digit) } ripple(digit: digit) return broadcast(reason: .building, result: self.result, digit: digit) } private func parseH1(digit: String) -> (CalendarManagerCodes, String) { guard h2 == "1" || h2 == "2" else { return broadcast(reason: .badInput, result: self.result, digit: digit) } ripple(digit: digit) return broadcast(reason: .completed, result: self.result, digit: digit) } }
unlicense
6bbcc313c08435b01e26c91ee4c7fbed
31.849711
175
0.560267
4.178676
false
false
false
false
laszlokorte/reform-swift
ReformStage/ReformStage/Handle.swift
1
1545
// // Handle.swift // ReformStage // // Created by Laszlo Korte on 15.08.15. // Copyright © 2015 Laszlo Korte. All rights reserved. // import ReformCore import ReformMath public typealias PivotPair = (EntityPoint, EntityPoint) public struct Handle { public let formId : SourceIdentifier public let anchorId : AnchorIdentifier public let pointId : ExposedPointIdentifier public let label : String public let position : Vec2d } public struct AffineHandle { public let formId : SourceIdentifier public let pointId : ExposedPointIdentifier public let label : String public let position : Vec2d public let defaultPivot : PivotPair public let scaleAxis : ScaleAxis } extension Handle { public var runtimePoint : LabeledPoint { return ForeignFormPoint(formId: formId.runtimeId, pointId: pointId) } } extension Handle : Hashable { public var hashValue : Int { return formId.runtimeId.hashValue * 13 + anchorId.hashValue } } public func ==(lhs: Handle, rhs: Handle) -> Bool { return lhs.formId == rhs.formId && lhs.anchorId == rhs.anchorId } extension AffineHandle { public var runtimePoint : LabeledPoint { return ForeignFormPoint(formId: formId.runtimeId, pointId: pointId) } } extension AffineHandle : Hashable { public var hashValue : Int { return formId.hashValue * 13 + pointId.hashValue } } public func ==(lhs: AffineHandle, rhs: AffineHandle) -> Bool { return lhs.formId == rhs.formId && lhs.pointId == rhs.pointId }
mit
b1ffb4ab6131e396b78baa44d83351ef
22.753846
94
0.704016
4.207084
false
false
false
false
adamwaite/AJWValidator
Validator/ValidatorTests/UIKit+Validator/UITextField+ValidatorTests.swift
2
2185
import XCTest @testable import Validator #if os(iOS) private final class TextField: UITextField { } class UITextFieldValidatorTests: XCTestCase { func test_inputValue() { let textField = UITextField() textField.text = "Hello" XCTAssertTrue(textField.inputValue == "Hello") } func test_validate() { let textField = UITextField() textField.text = "Hello" let noRulesValidation = textField.validate() XCTAssertTrue(noRulesValidation.isValid) let rule = ValidationRuleCondition<String>(error: "💣") { ($0?.contains("A"))! } let invalid = textField.validate(rule: rule) XCTAssertFalse(invalid.isValid) textField.text = "Hello Adam" let valid = textField.validate(rule: rule) XCTAssertTrue(valid.isValid) } func test_validateOnInputChange() { var textField = UITextField() var rules = ValidationRuleSet<String>() let rule = ValidationRuleCondition<String>(error: "💣") { ($0?.contains("A"))! } rules.add(rule: rule) var didRegisterInvalid = false var didRegisterValid = false textField.validationRules = rules XCTAssertNotNil(textField.validationRules) textField.validateOnInputChange(enabled: true) let actions = textField.actions(forTarget: textField, forControlEvent: .editingChanged) ?? [] XCTAssertFalse(actions.isEmpty) textField.validationHandler = { result in switch result { case .valid: didRegisterValid = true case .invalid(_): didRegisterInvalid = true } } textField.text = "BCDE" let _ = textField.validate() // textField.sendActionsForControlEvents(.EditingChanged) doesn't seem to work in test env XCTAssert(didRegisterInvalid) XCTAssertFalse(didRegisterValid) textField.text = "ABCDE" let _ = textField.validate() XCTAssert(didRegisterInvalid) XCTAssert(didRegisterValid) } } #endif
mit
38f9ec94f5bcf3a27e1f661be03ce841
28.849315
127
0.6067
5.314634
false
true
false
false
niunaruto/DeDaoAppSwift
testSwift/Pods/Kingfisher/Sources/General/KingfisherOptionsInfo.swift
4
17792
// // KingfisherOptionsInfo.swift // Kingfisher // // Created by Wei Wang on 15/4/23. // // Copyright (c) 2019 Wei Wang <[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. #if os(macOS) import AppKit #else import UIKit #endif /// KingfisherOptionsInfo is a typealias for [KingfisherOptionsInfoItem]. /// You can use the enum of option item with value to control some behaviors of Kingfisher. public typealias KingfisherOptionsInfo = [KingfisherOptionsInfoItem] extension Array where Element == KingfisherOptionsInfoItem { static let empty: KingfisherOptionsInfo = [] } /// Represents the available option items could be used in `KingfisherOptionsInfo`. public enum KingfisherOptionsInfoItem { /// Kingfisher will use the associated `ImageCache` object when handling related operations, /// including trying to retrieve the cached images and store the downloaded image to it. case targetCache(ImageCache) /// The `ImageCache` for storing and retrieving original images. If `originalCache` is /// contained in the options, it will be preferred for storing and retrieving original images. /// If there is no `.originalCache` in the options, `.targetCache` will be used to store original images. /// /// When using KingfisherManager to download and store an image, if `cacheOriginalImage` is /// applied in the option, the original image will be stored to this `originalCache`. At the /// same time, if a requested final image (with processor applied) cannot be found in `targetCache`, /// Kingfisher will try to search the original image to check whether it is already there. If found, /// it will be used and applied with the given processor. It is an optimization for not downloading /// the same image for multiple times. case originalCache(ImageCache) /// Kingfisher will use the associated `ImageDownloader` object to download the requested images. case downloader(ImageDownloader) /// Member for animation transition when using `UIImageView`. Kingfisher will use the `ImageTransition` of /// this enum to animate the image in if it is downloaded from web. The transition will not happen when the /// image is retrieved from either memory or disk cache by default. If you need to do the transition even when /// the image being retrieved from cache, set `.forceRefresh` as well. case transition(ImageTransition) /// Associated `Float` value will be set as the priority of image download task. The value for it should be /// between 0.0~1.0. If this option not set, the default value (`URLSessionTask.defaultPriority`) will be used. case downloadPriority(Float) /// If set, Kingfisher will ignore the cache and try to fire a download task for the resource. case forceRefresh /// If set, Kingfisher will try to retrieve the image from memory cache first. If the image is not in memory /// cache, then it will ignore the disk cache but download the image again from network. This is useful when /// you want to display a changeable image behind the same url at the same app session, while avoiding download /// it for multiple times. case fromMemoryCacheOrRefresh /// If set, setting the image to an image view will happen with transition even when retrieved from cache. /// See `.transition` option for more. case forceTransition /// If set, Kingfisher will only cache the value in memory but not in disk. case cacheMemoryOnly /// If set, Kingfisher will wait for caching operation to be completed before calling the completion block. case waitForCache /// If set, Kingfisher will only try to retrieve the image from cache, but not from network. If the image is /// not in cache, the image retrieving will fail with an error. case onlyFromCache /// Decode the image in background thread before using. It will decode the downloaded image data and do a off-screen /// rendering to extract pixel information in background. This can speed up display, but will cost more time to /// prepare the image for using. case backgroundDecode /// The associated value of this member will be used as the target queue of dispatch callbacks when /// retrieving images from cache. If not set, Kingfisher will use main queue for callbacks. @available(*, deprecated, message: "Use `.callbackQueue(CallbackQueue)` instead.") case callbackDispatchQueue(DispatchQueue?) /// The associated value will be used as the target queue of dispatch callbacks when retrieving images from /// cache. If not set, Kingfisher will use `.mainCurrentOrAsync` for callbacks. /// /// - Note: /// This option does not affect the callbacks for UI related extension methods. You will always get the /// callbacks called from main queue. case callbackQueue(CallbackQueue) /// The associated value will be used as the scale factor when converting retrieved data to an image. /// Specify the image scale, instead of your screen scale. You may need to set the correct scale when you dealing /// with 2x or 3x retina images. Otherwise, Kingfisher will convert the data to image object at `scale` 1.0. case scaleFactor(CGFloat) /// Whether all the animated image data should be preloaded. Default is `false`, which means only following frames /// will be loaded on need. If `true`, all the animated image data will be loaded and decoded into memory. /// /// This option is mainly used for back compatibility internally. You should not set it directly. Instead, /// you should choose the image view class to control the GIF data loading. There are two classes in Kingfisher /// support to display a GIF image. `AnimatedImageView` does not preload all data, it takes much less memory, but /// uses more CPU when display. While a normal image view (`UIImageView` or `NSImageView`) loads all data at once, /// which uses more memory but only decode image frames once. case preloadAllAnimationData /// The `ImageDownloadRequestModifier` contained will be used to change the request before it being sent. /// This is the last chance you can modify the image download request. You can modify the request for some /// customizing purpose, such as adding auth token to the header, do basic HTTP auth or something like url mapping. /// The original request will be sent without any modification by default. case requestModifier(ImageDownloadRequestModifier) /// The `ImageDownloadRedirectHandler` contained will be used to change the request before redirection. /// This is the posibility you can modify the image download request during redirect. You can modify the request for /// some customizing purpose, such as adding auth token to the header, do basic HTTP auth or something like url /// mapping. /// The original redirection request will be sent without any modification by default. case redirectHandler(ImageDownloadRedirectHandler) /// Processor for processing when the downloading finishes, a processor will convert the downloaded data to an image /// and/or apply some filter on it. If a cache is connected to the downloader (it happens when you are using /// KingfisherManager or any of the view extension methods), the converted image will also be sent to cache as well. /// If not set, the `DefaultImageProcessor.default` will be used. case processor(ImageProcessor) /// Supplies a `CacheSerializer` to convert some data to an image object for /// retrieving from disk cache or vice versa for storing to disk cache. /// If not set, the `DefaultCacheSerializer.default` will be used. case cacheSerializer(CacheSerializer) /// An `ImageModifier` is for modifying an image as needed right before it is used. If the image was fetched /// directly from the downloader, the modifier will run directly after the `ImageProcessor`. If the image is being /// fetched from a cache, the modifier will run after the `CacheSerializer`. /// /// Use `ImageModifier` when you need to set properties that do not persist when caching the image on a concrete /// type of `Image`, such as the `renderingMode` or the `alignmentInsets` of `UIImage`. case imageModifier(ImageModifier) /// Keep the existing image of image view while setting another image to it. /// By setting this option, the placeholder image parameter of image view extension method /// will be ignored and the current image will be kept while loading or downloading the new image. case keepCurrentImageWhileLoading /// If set, Kingfisher will only load the first frame from an animated image file as a single image. /// Loading an animated images may take too much memory. It will be useful when you want to display a /// static preview of the first frame from a animated image. /// /// This option will be ignored if the target image is not animated image data. case onlyLoadFirstFrame /// If set and an `ImageProcessor` is used, Kingfisher will try to cache both the final result and original /// image. Kingfisher will have a chance to use the original image when another processor is applied to the same /// resource, instead of downloading it again. You can use `.originalCache` to specify a cache or the original /// images if necessary. /// /// The original image will be only cached to disk storage. case cacheOriginalImage /// If set and a downloading error occurred Kingfisher will set provided image (or empty) /// in place of requested one. It's useful when you don't want to show placeholder /// during loading time but wants to use some default image when requests will be failed. case onFailureImage(Image?) /// If set and used in `ImagePrefetcher`, the prefetching operation will load the images into memory storage /// aggressively. By default this is not contained in the options, that means if the requested image is already /// in disk cache, Kingfisher will not try to load it to memory. case alsoPrefetchToMemory /// If set, the disk storage loading will happen in the same calling queue. By default, disk storage file loading /// happens in its own queue with an asynchronous dispatch behavior. Although it provides better non-blocking disk /// loading performance, it also causes a flickering when you reload an image from disk, if the image view already /// has an image set. /// /// Set this options will stop that flickering by keeping all loading in the same queue (typically the UI queue /// if you are using Kingfisher's extension methods to set an image), with a tradeoff of loading performance. case loadDiskFileSynchronously /// The expiration setting for memory cache. By default, the underlying `MemoryStorage.Backend` uses the /// expiration in its config for all items. If set, the `MemoryStorage.Backend` will use this associated /// value to overwrite the config setting for this caching item. case memoryCacheExpiration(StorageExpiration) /// The expiration setting for memory cache. By default, the underlying `DiskStorage.Backend` uses the /// expiration in its config for all items. If set, the `DiskStorage.Backend` will use this associated /// value to overwrite the config setting for this caching item. case diskCacheExpiration(StorageExpiration) /// Decides on which queue the image processing should happen. By default, Kingfisher uses a pre-defined serial /// queue to process images. Use this option to change this behavior. For example, specify a `.mainCurrentOrAsync` /// to let the image be processed in main queue to prevent a possible flickering (but with a possibility of /// blocking the UI, especially if the processor needs a lot of time to run). case processingQueue(CallbackQueue) } // Improve performance by parsing the input `KingfisherOptionsInfo` (self) first. // So we can prevent the iterating over the options array again and again. /// The parsed options info used across Kingfisher methods. Each property in this type corresponds a case member /// in `KingfisherOptionsInfoItem`. When a `KingfisherOptionsInfo` sent to Kingfisher related methods, it will be /// parsed and converted to a `KingfisherParsedOptionsInfo` first, and pass through the internal methods. public struct KingfisherParsedOptionsInfo { public var targetCache: ImageCache? = nil public var originalCache: ImageCache? = nil public var downloader: ImageDownloader? = nil public var transition: ImageTransition = .none public var downloadPriority: Float = URLSessionTask.defaultPriority public var forceRefresh = false public var fromMemoryCacheOrRefresh = false public var forceTransition = false public var cacheMemoryOnly = false public var waitForCache = false public var onlyFromCache = false public var backgroundDecode = false public var preloadAllAnimationData = false public var callbackQueue: CallbackQueue = .mainCurrentOrAsync public var scaleFactor: CGFloat = 1.0 public var requestModifier: ImageDownloadRequestModifier? = nil public var redirectHandler: ImageDownloadRedirectHandler? = nil public var processor: ImageProcessor = DefaultImageProcessor.default public var imageModifier: ImageModifier? = nil public var cacheSerializer: CacheSerializer = DefaultCacheSerializer.default public var keepCurrentImageWhileLoading = false public var onlyLoadFirstFrame = false public var cacheOriginalImage = false public var onFailureImage: Optional<Image?> = .none public var alsoPrefetchToMemory = false public var loadDiskFileSynchronously = false public var memoryCacheExpiration: StorageExpiration? = nil public var diskCacheExpiration: StorageExpiration? = nil public var processingQueue: CallbackQueue? = nil public init(_ info: KingfisherOptionsInfo?) { guard let info = info else { return } for option in info { switch option { case .targetCache(let value): targetCache = value case .originalCache(let value): originalCache = value case .downloader(let value): downloader = value case .transition(let value): transition = value case .downloadPriority(let value): downloadPriority = value case .forceRefresh: forceRefresh = true case .fromMemoryCacheOrRefresh: fromMemoryCacheOrRefresh = true case .forceTransition: forceTransition = true case .cacheMemoryOnly: cacheMemoryOnly = true case .waitForCache: waitForCache = true case .onlyFromCache: onlyFromCache = true case .backgroundDecode: backgroundDecode = true case .preloadAllAnimationData: preloadAllAnimationData = true case .callbackQueue(let value): callbackQueue = value case .scaleFactor(let value): scaleFactor = value case .requestModifier(let value): requestModifier = value case .redirectHandler(let value): redirectHandler = value case .processor(let value): processor = value case .imageModifier(let value): imageModifier = value case .cacheSerializer(let value): cacheSerializer = value case .keepCurrentImageWhileLoading: keepCurrentImageWhileLoading = true case .onlyLoadFirstFrame: onlyLoadFirstFrame = true case .cacheOriginalImage: cacheOriginalImage = true case .onFailureImage(let value): onFailureImage = .some(value) case .alsoPrefetchToMemory: alsoPrefetchToMemory = true case .loadDiskFileSynchronously: loadDiskFileSynchronously = true case .callbackDispatchQueue(let value): callbackQueue = value.map { .dispatch($0) } ?? .mainCurrentOrAsync case .memoryCacheExpiration(let expiration): memoryCacheExpiration = expiration case .diskCacheExpiration(let expiration): diskCacheExpiration = expiration case .processingQueue(let queue): processingQueue = queue } } if originalCache == nil { originalCache = targetCache } } } extension KingfisherParsedOptionsInfo { var imageCreatingOptions: ImageCreatingOptions { return ImageCreatingOptions( scale: scaleFactor, duration: 0.0, preloadAll: preloadAllAnimationData, onlyFirstFrame: onlyLoadFirstFrame) } }
mit
e9bab6e892ae9684f7b11bbcb803b011
57.143791
120
0.728192
5.38173
false
false
false
false
lorentey/swift
test/Syntax/round_trip_parse_gen.swift
5
10930
// RUN: rm -rf %t // RUN: %swift-syntax-test -input-source-filename %s -parse-gen > %t // RUN: diff -u %s %t // RUN: %swift-syntax-test -input-source-filename %s -parse-gen -print-node-kind > %t.withkinds // RUN: diff -u %S/Outputs/round_trip_parse_gen.swift.withkinds %t.withkinds // RUN: %swift-syntax-test -input-source-filename %s -eof > %t // RUN: diff -u %s %t // RUN: %swift-syntax-test -serialize-raw-tree -input-source-filename %s > %t.dump // RUN: %swift-syntax-test -deserialize-raw-tree -input-source-filename %t.dump -output-filename %t // RUN: diff -u %s %t import ABC import A.B.C @objc import A.B @objc import typealias A.B import struct A.B #warning("test warning") #error("test error") #if Blah class C { func bar(_ a: Int) {} func bar1(_ a: Float) -> Float { return -0.6 + 0.1 - 0.3 } func bar2(a: Int, b: Int, c:Int) -> Int { return 1 } func bar3(a: Int) -> Int { return 1 } func bar4(_ a: Int) -> Int { return 1 } func foo() { var a = /*comment*/"ab\(x)c"/*comment*/ var b = /*comment*/+2/*comment*/ bar(1) bar(+10) bar(-10) bar1(-1.1) bar1(1.1) var f = /*comments*/+0.1/*comments*/ foo() _ = "🙂🤗🤩🤔🤨" } func foo1() { _ = bar2(a:1, b:2, c:2) _ = bar2(a:1 + 1, b:2 * 2 + 2, c:2 + 2) _ = bar2(a : bar2(a: 1, b: 2, c: 3), b: 2, c: 3) _ = bar3(a : bar3(a: bar3(a: 1))) _ = bar4(bar4(bar4(1))) _ = [:] _ = [] _ = [1, 2, 3, 4] _ = [1:1, 2:2, 3:3, 4:4] _ = [bar3(a:1), bar3(a:1), bar3(a:1), bar3(a:1)] _ = ["a": bar3(a:1), "b": bar3(a:1), "c": bar3(a:1), "d": bar3(a:1)] foo(nil, nil, nil) _ = type(of: a).self _ = a.`self` _ = A -> B.C<Int> _ = [(A) throws -> B]() } func boolAnd() -> Bool { return true && false } func boolOr() -> Bool { return true || false } func foo2() { _ = true ? 1 : 0 _ = (true ? 1 : 0) ? (true ? 1 : 0) : (true ? 1 : 0) _ = (1, 2) _ = (first: 1, second: 2) _ = (1) _ = (first: 1) if !true { return } } func foo3() { _ = [Any]() _ = a.a.a _ = a.b _ = 1.a (1 + 1).a.b.foo _ = a as Bool || a as! Bool || a as? Bool _ = a is Bool _ = self _ = Self } func superExpr() { _ = super.foo super.bar() super[12] = 1 super.init() } func implictMember() { _ = .foo _ = .foo(x: 12) _ = .foo { 12 } _ = .foo[12] _ = .foo.bar } init() {} @objc private init(a: Int) init!(a: Int) {} init?(a: Int) {} public init(a: Int) throws {} @objc deinit {} private deinit {} internal subscript(x: Int) -> Int { get {} set {} } subscript() -> Int { return 1 } var x: Int { address { fatalError() } unsafeMutableAddress { fatalError() } } } protocol PP { associatedtype A associatedtype B: Sequence associatedtype C = Int associatedtype D: Sequence = [Int] associatedtype E: Sequence = [[Int]] where A.Element : Sequence private associatedtype F @objc associatedtype G } #endif #if blah typealias A = Any #elseif blahblah typealias B = (Array<Array<Any>>.Element, x: Int) #else typealias C = [Int] #endif typealias D = [Int: String] typealias E = Int?.Protocol typealias F = [Int]!.Type typealias G = (a x: Int, _ y: Int ... = 1) throw -> () -> () typealias H = () rethrows -> () typealias I = (A & B<C>) -> C & D typealias J = inout @autoclosure () -> Int typealias K = (@invalidAttr Int, inout Int, __shared Int, __owned Int) -> () @objc private typealias T<a,b> = Int @objc private typealias T<a,b> class Foo { let bar: Int } class Bar: Foo { var foo: Int = 42 } class C<A, B> where A: Foo, B == Bar {} @available(*, unavailable) private class C {} struct foo { struct foo { struct foo { func foo() { } } } struct foo {} } struct foo { @available(*, unavailable) struct foo {} public class foo { @available(*, unavailable) @objc(fooObjc) private static func foo() {} @objc(fooObjcBar:baz:) private static func foo(bar: String, baz: Int) } } struct S<A, B, C, @objc D> where A:B, B==C, A : C, B.C == D.A, A.B: C.D {} private struct S<A, B>: Base where A: B { private struct S: A, B {} } protocol P: class {} func foo(_ _: Int, a b: Int = 3 + 2, _ c: Int = 2, d _: Int = true ? 2: 3, @objc e: X = true, f: inout Int, g: Int...) throws -> [Int: String] {} func foo(_ a: Int) throws -> Int {} func foo( a: Int) rethrows -> Int {} struct C { @objc @available(*, unavailable) private static override func foo<a, b, c>(a b: Int, c: Int) throws -> [Int] where a==p1, b:p2 { ddd } func rootView() -> Label {} static func ==() -> bool {} static func !=<a, b, c>() -> bool {} } @objc private protocol foo : bar where A==B {} protocol foo { func foo() } private protocol foo{} @objc public protocol foo where A:B {} #if blah func tryfoo() { try foo() try! foo() try? foo() try! foo().bar().foo().bar() } #else func closure() { _ = {[weak a, unowned(safe) self, b = 3, unowned(unsafe) c = foo().bar] in } _ = {[] in } _ = { [] a, b, _ -> Int in return 2 } _ = { [] (a: Int, b: Int, _: Int) -> Int in return 2 } _ = { [] a, b, _ throws -> Int in return 2 } _ = { [] (a: Int, _ b: Int) throws -> Int in return 2 } _ = { a, b in } _ = { (a, b) in } _ = {} _ = { s1, s2 in s1 > s2 } _ = { $0 > $1 } } #endif func postfix() { foo() foo() {} foo {} foo.bar() foo.bar() {} foo.bar {} foo[] foo[1] foo[] {} foo[1] {} foo[1][2,x:3] foo?++.bar!(baz).self foo().0 foo<Int>.bar foo<Int>() foo.bar<Int>() foo(x:y:)() foo(x:)<Int> { } _ = .foo(x:y:) _ = x.foo(x:y:) _ = foo(&d) _ = <#Placeholder#> + <#T##(Int) -> Int#> } #if blah #else #endif class C { var a: Int { @objc mutating set(value) {} mutating get { return 3 } @objc didSet {} willSet(newValue){ } } var a : Int { return 3 } } protocol P { var a: Int { get set } var a: Int {} } private final class D { @objc static private var a: Int = 3 { return 3 }, b: Int, c = 4, d : Int { get {} get {}}, (a, b): (Int, Int) let (a, b) = (1,2), _ = 4 {} func patternTests() { for let (x, _) in foo {} for var x: Int in foo {} } } do { switch foo { case let a: break case let a as Int: break case let (a, b): break case (let a, var b): break case is Int: break case let .bar(x): break case MyEnum.foo: break case let a as Int: break case let a?: break } } func statementTests() { do { } catch (var x, let y) { } catch where false { } catch let e where e.foo == bar { } catch { } repeat { } while true LABEL: repeat { } while false while true { } LABEL: while true { } LABEL: do {} LABEL: switch foo { case 1: fallthrough case 2: break LABEL case 3: break } for a in b { defer { () } if c { throw MyError() continue } else { continue LABEL } } if foo, let a = foo, let b: Int = foo, var c = foo, case (let v, _) = foo, case (let v, _): (Int, Int) = foo { } else if foo { } else { } guard let a = b else {} guard let self = self else {} for var i in foo where i.foo {} for case is Int in foo {} switch Foo { case n1: break case n2, n3l: break #if FOO case let (x, y) where !x, n3l where false: break #elseif BAR case let y: break #else case .foo(let x): break #endif default: break } switch foo { case 1, 2, 3: break default: break } switch foo { case 1, 2, 3: break @unknown default: break } switch foo { case 1, 2, 3: break @unknown case _: break } switch foo { case 1, 2, 3: break // This is rejected in Sema, but should be preserved by Syntax. @unknown case (42, -42) where 1 == 2: break @garbage case 0: break @garbage(foobar) case -1: break } } // MARK: - ExtensionDecl extension ext { var s: Int { return 42 } } @available(*, unavailable) fileprivate extension ext {} extension ext : extProtocol {} extension ext where A == Int, B: Numeric {} extension ext.a.b {} func foo() { var a = "abc \(foo()) def \(a + b + "a \(3)") gh \(bar, default: 1)" var a = """ abc \( foo() + bar() ) de \(3 + 3 + "abc \(foo()) def") fg \(bar, default: 1) """ } func keypath() { _ = \a.?.b _ = \a.b.c _ = \a.b[1] _ = \.a.b _ = \Array<Int>.[] _ = #keyPath(a.b.c) } func objcSelector() { _ = [ #selector(getter: Foo.bar), #selector(setter: Foo.Bar.baz), #selector(Foo.method(x:y:)), #selector(foo[42].bar(x)), #selector({ [x] in return nil }) ] } func objectLiterals() { #fileLiteral(a) #colorLiteral(a, b) #imageLiteral(a, b, c) #column #file #function #dsohandle } enum E1 : String { case foo = 1 case bar = "test", baz(x: Int, String) = 12 indirect case qux(E1) indirect private enum E2<T>: String where T: SomeProtocol { case foo, bar, baz } } precedencegroup FooPrecedence { higherThan: DefaultPrecedence, UnknownPrecedence assignment: false associativity: none } precedencegroup BarPrecedence {} precedencegroup BazPrecedence { associativity: left assignment: true associativity: right lowerThan: DefaultPrecedence } infix operator<++>:FooPrecedence prefix operator..<< postfix operator <- func higherOrderFunc() { let x = [1,2,3] x.reduce(0, +) } if #available(iOS 11, macOS 10.11.2, *) {} @_specialize(where T == Int) @_specialize(exported: true, where T == String) public func specializedGenericFunc<T>(_ t: T) -> T { return t } protocol Q { func g() var x: String { get } func f(x:Int, y:Int) -> Int #if FOO_BAR var conditionalVar: String #endif } struct S : Q, Equatable { @_implements(Q, f(x:y:)) func h(x:Int, y:Int) -> Int { return 6 } @_implements(Equatable, ==(_:_:)) public static func isEqual(_ lhs: S, _ rhs: S) -> Bool { return false } @_implements(P, x) var y: String @_implements(P, g()) func h() { _ = \.self } @available(*, deprecated: 1.2, message: "ABC") fileprivate(set) var x: String } struct ReadModify { var st0 = ("a", "b") var rm0: (String, String) { _read { yield (("a", "b")) } _modify { yield &st0 } } var rm1: (String, String) { _read { yield (st0) } } } @custom @_alignment(16) public struct float3 { public var x, y, z: Float } #sourceLocation(file: "otherFile.swift", line: 5) func foo() {} #sourceLocation() "abc \( } ) def" #assert(true) #assert(false) #assert(true, "hello world") public func anyFoo() -> some Foo {} public func qoo() -> some O & O2 {} func zlop() -> some C & AnyObject & P {} @custom(a, b,c) func foo() {} @custom_attr @custom(A: a, B: b, C:c) func foo() {} "abc" "abc \(foo)" #"abc"# #"abc \#(foo)"# ##"abc"## ##"abc \##(foo)"##
apache-2.0
4cc832ada01f8d53674b357477230f91
17.62628
105
0.5377
2.832122
false
false
false
false
tarunon/Barrel
CoreData/Barrel.swift
1
3587
// // Barrel.swift // Barrel // // Created by Nobuo Saito on 2016/11/22. // Copyright © 2016年 tarunon. All rights reserved. // import Foundation import CoreData import Barrel public protocol GroupType { associatedtype AttributeSourceType: NSManagedObject func groupBy(_ keyPath: @autoclosure @escaping () -> AttributeName) -> Self func having(_ predicate: @autoclosure @escaping () -> NSPredicate) -> Self } extension Group: GroupType { public typealias AttributeSourceType = T } public protocol AggregateType { associatedtype AttributeSourceType: NSManagedObject func aggregate(_ expressionDescription: @autoclosure @escaping () -> NSExpressionDescription) -> Self func groupBy(_ keyPath: @autoclosure @escaping () -> AttributeName) -> Group<AttributeSourceType> } extension Aggregate: AggregateType { public typealias AttributeSourceType = T } public protocol FetchType { associatedtype AttributeSourceType: NSManagedObject func filter(_ predicate: @autoclosure @escaping () -> NSPredicate) -> Self func sorted(_ sortDescriptor: @autoclosure @escaping () -> [NSSortDescriptor]) -> Self func limit(_ limit: Int) -> Self func offset(_ offset: Int) -> Self func aggregate(_ expressionDescription: @autoclosure @escaping () -> NSExpressionDescription) -> Aggregate<AttributeSourceType> } extension Fetch: FetchType { public typealias AttributeSourceType = T } public struct Barrel<Base: Executable> { public let base: Base public func confirm() -> Base { return base } } extension Executable { public var brl: Barrel<Self> { return Barrel(base: self) } } extension Barrel where Base: FetchType { public func filter(_ f: @escaping (Attribute<ExpressionWrapper<Base.AttributeSourceType>>) -> Predicate) -> Barrel { return Barrel(base: base.filter(f(Attribute()).value)) } public func sorted(_ f: @escaping (Attribute<ExpressionWrapper<Base.AttributeSourceType>>, Attribute<ExpressionWrapper<Base.AttributeSourceType>>) -> SortDescriptors) -> Barrel { return Barrel(base: base.sorted(f(Attribute.sortAttributeFirst(), Attribute.sortAttributeSecond()).value)) } public func aggregate<E: ExpressionType, V: ExpressionType>(_ f: @escaping (Attribute<ExpressionWrapper<Base.AttributeSourceType>>) -> E) -> Barrel<Aggregate<Base.AttributeSourceType>> where E.ValueType == V { return Barrel<Aggregate<Base.AttributeSourceType>>(base: base.aggregate(Expression(f(Attribute())).expressionDescription())) } } extension Barrel where Base: AggregateType { public func aggregate<E: ExpressionType, V: ExpressionType>(_ f: @escaping (Attribute<ExpressionWrapper<Base.AttributeSourceType>>) -> E) -> Barrel where E.ValueType == V { return Barrel(base: base.aggregate(Expression(f(Attribute())).expressionDescription())) } public func groupBy<E>(_ f: @escaping (Attribute<ExpressionWrapper<Base.AttributeSourceType>>) -> Attribute<E>) -> Barrel<Group<Base.AttributeSourceType>> { return Barrel<Group<Base.AttributeSourceType>>(base: base.groupBy(f(Attribute()).keyPath)) } } extension Barrel where Base: GroupType { public func groupBy<E>(_ f: @escaping (Attribute<ExpressionWrapper<Base.AttributeSourceType>>) -> Attribute<E>) -> Barrel { return Barrel(base: base.groupBy(f(Attribute()).keyPath)) } public func having(_ f: @escaping (Attribute<ExpressionWrapper<Base.AttributeSourceType>>) -> Predicate) -> Barrel { return Barrel(base: base.having(f(Attribute()).value)) } }
mit
b0d0084feece34057c55969668628ef0
38.384615
213
0.719029
4.728232
false
false
false
false
Chriskuei/Bon-for-Mac
Bon/BonCell.swift
1
3680
// // BonCell.swift // Bon // // Created by Chris on 16/5/14. // Copyright © 2016年 Chris. All rights reserved. // import Cocoa class BonCell: NSTableCellView { @IBOutlet weak var typeImageView: NSImageView! @IBOutlet weak var nameLabel: NSTextField! @IBOutlet weak var infoLabel: NSTextField! //@IBOutlet weak var circleView: NSView! fileprivate let squareWithCircleView: SquareWithCircleView = SquareWithCircleView(frame: CGRect.zero) fileprivate var item: BonItem? fileprivate let cursor = NSCursor.pointingHand fileprivate var trackingArea: NSTrackingArea? fileprivate var mouseInside = false { didSet { updateUI() } } class func view(_ tableView: NSTableView, owner: AnyObject?, subject: AnyObject?) -> NSView { let view = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "BonCell"), owner: owner) as! BonCell if let item = subject as? BonItem { view.setItem(item) } return view } override func awakeFromNib() { super.awakeFromNib() commonInit() } fileprivate func commonInit() { wantsLayer = true typeImageView.wantsLayer = true typeImageView.layer?.masksToBounds = true typeImageView.layer?.cornerRadius = 3 } override func prepareForReuse() { super.prepareForReuse() trackingArea = nil mouseInside = false } override func resetCursorRects() { addCursorRect(bounds, cursor: cursor) cursor.set() } fileprivate func setItem(_ item: BonItem?) { guard let item = item else { return } self.item = item updateUI() } fileprivate func updateUI() { guard let item = item else { return } layer?.backgroundColor = mouseInside ? NSColor.bonHighlight().cgColor : NSColor.bonWhite().cgColor nameLabel.stringValue = item.nameText infoLabel.stringValue = item.infoText //circleView.layer?.backgroundColor = NSColor.bonTintColor().CGColor //circleView.addSubview(squareWithCircleView) //squareWithCircleView.frame = circleView.bounds //squareWithCircleView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] //typeImageView.image = NSImage(named: item.imageType) } fileprivate func createTrackingAreaIfNeeded() { if trackingArea == nil { trackingArea = NSTrackingArea(rect: CGRect.zero, options: [NSTrackingArea.Options.inVisibleRect, NSTrackingArea.Options.mouseEnteredAndExited, NSTrackingArea.Options.activeAlways], owner: self, userInfo: nil) } } override func updateTrackingAreas() { super.updateTrackingAreas() createTrackingAreaIfNeeded() if !trackingAreas.contains(trackingArea!) { addTrackingArea(trackingArea!) } } override func mouseEntered(with theEvent: NSEvent) { mouseInside = true } override func mouseExited(with theEvent: NSEvent) { mouseInside = false } } class SquareWithCircleView: NSView{ override func draw(_ dirtyRect: NSRect) { let circleFillColor = NSColor.bonTint() let circleRect = NSMakeRect(dirtyRect.size.width/4, dirtyRect.size.height/4, dirtyRect.size.width/2, dirtyRect.size.height/2) let path: NSBezierPath = NSBezierPath(ovalIn: circleRect) circleFillColor.set() path.fill() } }
mit
b7c197b8d8fb94168e86acfe205a6658
28.18254
220
0.628773
5.298271
false
false
false
false
insanoid/SwiftyJSONAccelerator
Core/Helpers/StringExtensions.swift
1
2571
// // String+Helpers.swift // SwiftyJSONAccelerator // // Created by Karthikeya Udupa on 01/06/16. // Copyright © 2016 Karthikeya Udupa K M. All rights reserved. // import Foundation // A structure to manage the position of the character in a string-line. public struct CharacterPosition { var character: String var line: Int var column: Int } // Extension for string to provide helper method to generate names. public extension String { /// Fetches the first character of the string. var firstChar: String { return String(self.prefix(1)) } /// Makes the first character of the string uppercase. mutating func uppercaseFirst() { self = firstChar.uppercased() + String(dropFirst()) } /// Makes the first character of the string lowercase. mutating func lowercaseFirst() { self = firstChar.lowercased() + String(dropFirst()) } /// Replace occurrence of multiple strings with a single string. /// /// - Parameters: /// - strings: String to replace. /// - replacementString: String to replace with. mutating func replaceOccurrencesOfStringsWithString(_ strings: [String], _ replacementString: String) { for string in strings { self = replacingOccurrences(of: string, with: replacementString) } } /// Removes whitespace and newline at the ends. mutating func trim() { self = trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) } /// Appends an optional to the string. /// /// - Parameter prefix: String to append. mutating func appendPrefix(_ prefix: String?) { if let checkedPrefix = prefix { self = checkedPrefix + self } } func characterRowAndLineAt(position: Int) -> CharacterPosition { var lineNumber = 0 var characterPosition = 0 for line in components(separatedBy: "\n") { lineNumber += 1 var columnNumber = 0 for column in line { characterPosition += 1 columnNumber += 1 if characterPosition == position { return CharacterPosition(character: String(column), line: lineNumber, column: columnNumber) } } characterPosition += 1 if characterPosition == position { return CharacterPosition(character: "\n", line: lineNumber, column: columnNumber + 1) } } return CharacterPosition(character: "", line: 0, column: 0) } }
mit
f7a162cdd67dc6a160a4fc99a7f7ef30
31.125
111
0.620623
5
false
false
false
false
aestusLabs/ASChatApp
ChatVCAddWidgetsExtension.swift
1
5472
// // ChatVCAddWidgetsExtension.swift // ChatAppOrigionalFiles // // Created by Ian Kohlert on 2017-07-31. // Copyright © 2017 aestusLabs. All rights reserved. // import Foundation import UIKit extension ChatViewController { func updateUIFor(widget: Widget) { var widgetText = "" if widget.multipleTextOptions == false { widgetText = widget.defaultText //getTextFor(widgetTag: widget.tag) } else { widgetText = getTextFor(widgetTag: widget.tag) } addChatTextToScrollView(text: widgetText) print(widget.answerFormat) if widget.answerFormat == .presentedButtons { var buttons: [String] = [] if let buttonTitles = widget.defaultButtonTitles { if widget.multipleButtonTitleOptions { buttons = getButtonTitlesFor(widgetTag: widget.tag) } else { buttons = buttonTitles } } for button in buttons { addChatButtonToScrollView(buttonTitle: button, widget: widget) } } else if widget.answerFormat == .sessionWidgets { print("Session widgets") let modules = getModulesFor(widgetTag: widget.tag) for module in modules { print(module) addModuleToScrollView(module: module, widget: widget) // addSessionWidgetModuleToScrollView(title: module.title, image: module.image, text: "", time: "\(module.length)h", length: module.length, widget: widget) //(title: module.title, image: module.image, text: "", time: "\(module.length)m", widget: widget) } } else if widget.answerFormat == .chooseDaysOfWeek { addChooseDaysOfWeekModuleToScrollView(widget: widget) } // any button/enter on the keyboard needs to run the widget function // update HHBar // answer format dicates if I need to add buttons below the helper chat bubble } func addChooseDaysOfWeekModuleToScrollView(widget: Widget) { let daysOfWeekLetter = ["mo", "tu", "we", "th", "fr", "sa", "su"] var arrayOfDayButtons: [ChooseDayOfWeekButton] = [] for day in daysOfWeekLetter { let button = createChooseDayOfWeekButton(text: day, tag: widget.tag) print(button.buttonTag) button.addTarget(self, action: #selector(self.tapAction(sender:)), for: .touchUpInside) arrayOfDayButtons.append(button) chatView.scrollView.addSubview(button) } arrangeDaysOfWeekButtons(widgets: arrayOfDayButtons) addChatButtonToScrollView(buttonTitle: "add notifications", widget: widget) // let module = createDailyReminderCard(screenWidth: self.view.frame.width) // self.view.addSubview(module) // arrangeHelperWidgets(widget: module) // scrollViewContentHeight += module.frame.height + 10 } // func addSessionWidgetModuleToScrollView(title: String, image: UIImage, text: String, time: String, length: Int, widget: Widget) { // print("add session widget") // let module = createSessionWidget(screenWidth: self.view.frame.width, title: title, image: image, text: text, time: time, length: length, tag: widget.tag) // // module.tag = getValueFor(widgetTagName: widget.tagName) // let tap = UITapGestureRecognizer(target: self, action: #selector(self.tappedWidget(sender:))) // module.addGestureRecognizer(tap) // chatView.scrollView.addSubview(module) // arrangeHelperWidgets(widget: module) // scrollViewContentHeight += module.frame.height + 10 // // } func addModuleToScrollView(module: Modules, widget: Widget) { let module = createModuleForWidget(module: module, widget: widget, screenWidth: self.view.frame.width) let tap = UITapGestureRecognizer(target: self, action: #selector(self.tappedWidget(sender:))) module.addGestureRecognizer(tap) chatView.scrollView.addSubview(module) arrangeHelperWidgets(widget: module) scrollViewContentHeight += module.frame.height + 10 } func addChatTextToScrollView(text: String) { let textSize = textSizingFunctions.getTextLabelSize(text: text, screenWidth: self.view.frame.width) let bubble = createChatBubble(text: text, textWidth: textSize.width, textHeight: textSize.height, isUser: false) chatView.scrollView.addSubview(bubble) arrangeChatBubble(bubble: bubble, isUser: false) scrollViewContentHeight += bubble.frame.height + 10 } func addChatButtonToScrollView(buttonTitle: String, widget: Widget) { let button = createChatButton(text: buttonTitle, tag: widget.tag) // button.tag = getValueFor(widgetTagName: widget.tagName) button.addTarget(self, action: #selector(self.tapAction(sender:)), for: .touchUpInside) activeButtons.append(button) // addTapTo(button: button) chatView.scrollView.addSubview(button) arrangeHelperWidgets(widget: button) scrollViewContentHeight += button.frame.height + 10 } }
mit
b4f554e9de52c1240833735aaef489d7
41.410853
170
0.623469
4.820264
false
false
false
false
diwu/LeetCode-Solutions-in-Swift
Solutions/Solutions/Medium/Medium_024_Swap_Nodes_In_Pairs.swift
1
1217
/* https://leetcode.com/problems/swap-nodes-in-pairs/ #24 Swap Nodes in Pairs Level: medium Given a linked list, swap every two adjacent nodes and return its head. For example, Given 1->2->3->4, you should return the list as 2->1->4->3. Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed. Inspired by @mike3 at https://leetcode.com/discuss/3608/seeking-for-a-better-solution */ import Foundation class Medium_024_Swap_Nodes_In_Pairs { class Node { var value: Int var next: Node? init(value: Int, next: Node?) { self.value = value self.next = next } } class func swap(next1: Node, next2: Node) -> Node { next1.next = next2.next next2.next = next1 return next2 } class func swapPairs(_ head: Node?) -> Node? { let dummy: Node = Node(value: 0, next: nil) dummy.next = head var curr: Node? = dummy while curr?.next != nil && curr?.next?.next != nil { curr?.next = swap(next1: curr!.next!, next2: curr!.next!.next!) curr = curr?.next?.next } return dummy.next } }
mit
13f488fe7f3f0738bbd6d5aade2c8f58
25.456522
123
0.603122
3.537791
false
false
false
false
vodianyk/swift-fc-neural-network
Sources/FullyConnectedNeuralNetwork.swift
1
3553
// // FullyConnectedNeuralNetwork.swift // Created by Dmitry Vodianyk on 1/18/17. // import Foundation class FullyConnectedNeuralNetwork { var weights = [Matrix]() var costFunction: CostFunction init(shape: [Int]) { var previous = -1 for (index, value) in shape.enumerated() { if (index > 0) { let w = Matrix(previous, value) self.weights.append(w) } previous = value } self.costFunction = CrossEntropyCost() } func run(_ input: Matrix) -> Matrix { var result = input for w in self.weights { result = result.dot(w).sigmoid() } return result } func train(_ input: Matrix, _ desiredOutput: Matrix, minibatch: Int = input.count.rows, nEpochs: Int = 1000, learningRate: Double = 0.1, statusCallback: @escaping (_ epochIndex: Int, _ error: Double, _ finished: Bool) -> ()) { DispatchQueue.global().async(execute: { for epochIndex in 1 ... nEpochs { var error = 0.0 let batchSize = input.count.rows % minibatch == 0 ? minibatch : input.count.rows let nMinibatches = (input.count.rows / batchSize) for j in 0 ..< nMinibatches { let inputRowPosition = j * batchSize * input.count.columns let batchInput = Matrix(batchSize, input.count.columns, Array(input.grid[inputRowPosition ..< inputRowPosition + batchSize * input.count.columns])) let outputRowPosition = j * batchSize * desiredOutput.count.columns let batchOutput = Matrix(batchSize, desiredOutput.count.columns, Array(desiredOutput.grid[outputRowPosition ..< outputRowPosition + batchSize * desiredOutput.count.columns])) error += self.trainEpoch(batchInput, batchOutput, learningRate) } DispatchQueue.main.sync(execute: { () -> Void in statusCallback(epochIndex, error, epochIndex == nEpochs) }) } }) } // MARK: Private private func trainEpoch(_ input: Matrix, _ desiredOutput: Matrix, _ learningRate: Double) -> Double { // feedforward var activations = [ input ] var zVectors = [Matrix]() var activation = input for w in self.weights { let z = activation.dot(w) zVectors.append(z) activation = z.sigmoid() activations.append(activation) } // backpropagation var delta = self.costFunction.delta(output: activations.last!, desiredOutput: desiredOutput, zValue: zVectors.last!) var gradients = [ activations[activations.count - 2].T().dot(delta) ] for i in 2 ..< self.weights.count + 1 { let z = zVectors[zVectors.count - i] let sP = z.sigmoidPrime() delta = delta.dot(self.weights[self.weights.count - i + 1].T()) * sP let gradient = activations[activations.count - i - 1].T().dot(delta) gradients.append(gradient) } for (index, gradient) in gradients.reversed().enumerated() { self.weights[index] = self.weights[index] - (gradient * learningRate) } return self.costFunction.calculate(output: activations.last!, desiredOutput: desiredOutput) } }
mit
7f3f63950c140a4ec3102b22a8e8fc2d
37.619565
149
0.558964
4.590439
false
false
false
false
korgx9/QRCodeReader.swift
Sources/QRCodeReaderViewController.swift
1
8469
/* * QRCodeReader.swift * * Copyright 2014-present Yannick Loriot. * http://yannickloriot.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ import UIKit import AVFoundation /// Convenient controller to display a view to scan/read 1D or 2D bar codes like the QRCodes. It is based on the `AVFoundation` framework from Apple. It aims to replace ZXing or ZBar for iOS 7 and over. public class QRCodeReaderViewController: UIViewController { /// The code reader object used to scan the bar code. public let codeReader: QRCodeReader let readerView: QRCodeReaderContainer let startScanningAtLoad: Bool let showCancelButton: Bool let showSwitchCameraButton: Bool let showTorchButton: Bool let showOverlayView: Bool let showInformationLabel: Bool var informationLabelText: String? let handleOrientationChange: Bool // MARK: - Managing the Callback Responders /// The receiver's delegate that will be called when a result is found. public weak var delegate: QRCodeReaderViewControllerDelegate? /// The completion blocak that will be called when a result is found. public var completionBlock: ((QRCodeReaderResult?) -> Void)? deinit { codeReader.stopScanning() NotificationCenter.default.removeObserver(self) } // MARK: - Creating the View Controller /** Initializes a view controller using a builder. - parameter builder: A QRCodeViewController builder object. */ required public init(builder: QRCodeReaderViewControllerBuilder) { readerView = builder.readerView startScanningAtLoad = builder.startScanningAtLoad codeReader = builder.reader showCancelButton = builder.showCancelButton showSwitchCameraButton = builder.showSwitchCameraButton showTorchButton = builder.showTorchButton showOverlayView = builder.showOverlayView showInformationLabel = builder.showInformationLabel informationLabelText = builder.informationLabelText handleOrientationChange = builder.handleOrientationChange super.init(nibName: nil, bundle: nil) view.backgroundColor = .black codeReader.didFindCode = { [weak self] resultAsObject in if let weakSelf = self { if let qrv = weakSelf.readerView.displayable as? QRCodeReaderView { qrv.addGreenBorder() } weakSelf.completionBlock?(resultAsObject) weakSelf.delegate?.reader(weakSelf, didScanResult: resultAsObject) } } codeReader.didFailDecoding = { [weak self] in if let weakSelf = self { if let qrv = weakSelf.readerView.displayable as? QRCodeReaderView { qrv.addRedBorder() } } } setupUIComponentsWithCancelButtonTitle(builder.cancelButtonTitle, informationLabelText: informationLabelText) NotificationCenter.default.addObserver(self, selector: #selector(orientationDidChange), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil) } required public init?(coder aDecoder: NSCoder) { codeReader = QRCodeReader() readerView = QRCodeReaderContainer(displayable: QRCodeReaderView()) startScanningAtLoad = false showCancelButton = false showTorchButton = false showSwitchCameraButton = false showOverlayView = false showInformationLabel = false handleOrientationChange = false super.init(coder: aDecoder) } // MARK: - Responding to View Events override public var supportedInterfaceOrientations: UIInterfaceOrientationMask { return parent?.supportedInterfaceOrientations ?? .all } override public func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if startScanningAtLoad { startScanning() } } override public func viewWillDisappear(_ animated: Bool) { stopScanning() super.viewWillDisappear(animated) } override public func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() codeReader.previewLayer.frame = view.bounds } // MARK: - Managing the Orientation func orientationDidChange(_ notification: Notification) { readerView.view.setNeedsDisplay() if showOverlayView, let qrv = readerView.displayable as? QRCodeReaderView { qrv.overlayView?.setNeedsDisplay() } if handleOrientationChange == true, let device = notification.object as? UIDevice, let connection = codeReader.previewLayer.connection, connection.isVideoOrientationSupported { connection.videoOrientation = QRCodeReader.videoOrientation(deviceOrientation: device.orientation, withSupportedOrientations: supportedInterfaceOrientations, fallbackOrientation: connection.videoOrientation) } } // MARK: - Initializing the AV Components private func setupUIComponentsWithCancelButtonTitle(_ cancelButtonTitle: String, informationLabelText: String? = nil) { view.addSubview(readerView.view) let sscb = showSwitchCameraButton && codeReader.hasFrontDevice let stb = showTorchButton && codeReader.isTorchAvailable readerView.setupComponents(showCancelButton: showCancelButton, showSwitchCameraButton: sscb, showTorchButton: stb, showOverlayView: showOverlayView, showInformationLabel: showInformationLabel) // Setup action methods readerView.displayable.switchCameraButton?.addTarget(self, action: #selector(switchCameraAction), for: .touchUpInside) readerView.displayable.toggleTorchButton?.addTarget(self, action: #selector(toggleTorchAction), for: .touchUpInside) readerView.displayable.cancelButton?.setTitle(cancelButtonTitle, for: .normal) readerView.displayable.cancelButton?.addTarget(self, action: #selector(cancelAction), for: .touchUpInside) readerView.displayable.informationLabel?.text = informationLabelText // Setup camera preview layer codeReader.previewLayer.frame = CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height) if let connection = codeReader.previewLayer.connection, connection.isVideoOrientationSupported { let orientation = UIDevice.current.orientation connection.videoOrientation = QRCodeReader.videoOrientation(deviceOrientation: orientation, withSupportedOrientations: supportedInterfaceOrientations) } readerView.displayable.cameraView.layer.insertSublayer(codeReader.previewLayer, at: 0) // Setup constraints for attribute in [NSLayoutAttribute.left, NSLayoutAttribute.top, NSLayoutAttribute.right, NSLayoutAttribute.bottom] { view.addConstraint(NSLayoutConstraint(item: readerView.view, attribute: attribute, relatedBy: .equal, toItem: view, attribute: attribute, multiplier: 1, constant: 0)) } } // MARK: - Controlling the Reader /// Starts scanning the codes. public func startScanning() { codeReader.startScanning() } /// Stops scanning the codes. public func stopScanning() { codeReader.stopScanning() } // MARK: - Catching Button Events func cancelAction(_ button: UIButton) { codeReader.stopScanning() if let _completionBlock = completionBlock { _completionBlock(nil) } delegate?.readerDidCancel(self) } func switchCameraAction(_ button: SwitchCameraButton) { if let newDevice = codeReader.switchDeviceInput() { delegate?.reader(self, didSwitchCamera: newDevice) } } func toggleTorchAction(_ button: ToggleTorchButton) { codeReader.toggleTorch() } }
mit
6043374a4b1a67d53a4200ac3b56c6e7
36.30837
213
0.746133
5.296435
false
false
false
false
kstaring/swift
test/Interpreter/dynamic_lookup.swift
62
1775
// RUN: %target-run-simple-swift | %FileCheck %s // REQUIRES: executable_test // REQUIRES: objc_interop import Foundation class X { init() {} @objc func f() { print("X.f()") } @objc var myValue : Int { print("X.myValue getter\n") return 17 } } class Y { init() {} @objc class func g() { print("Y.g()") } } class Z { init() {} } extension Z { @objc func f() { print("Z.f()") } } func test_dynamic_lookup_f(_ obj: AnyObject) { var of = obj.f if of != nil { of!() } else { print("Object does not respond to the selector \"f\".\n", terminator: "") } } func test_dynamic_lookup_g(_ obj: AnyObject) { var og = type(of: obj).g if og != nil { og!() } else { print("Class does not respond to the selector \"g\".\n", terminator: "") } } func test_dynamic_lookup_myValue(_ obj: AnyObject) { var ov = obj.myValue if ov != nil { print("myValue = \(ov!)") } else { print("Object does not respond to the selector \"myValue\".") } } // CHECK: X.f() test_dynamic_lookup_f(X()) // CHECK: Object does not respond to the selector "f" test_dynamic_lookup_f(Y()) // CHECK: Z.f() test_dynamic_lookup_f(Z()) // CHECK: Class does not respond to the selector "g" test_dynamic_lookup_g(X()) // CHECK: Y.g() test_dynamic_lookup_g(Y()) // CHECK: X.myValue getter // CHECK: myValue = 17 test_dynamic_lookup_myValue(X()) // CHECK: Object does not respond to the selector "myValue" test_dynamic_lookup_myValue(Y()) // <rdar://problem/16554056> __FUNCTION__ in deinit for NSObject subclasses crashes the compiler // Test __FUNCTION__ class FUNCTION_NAME_TEST : NSObject { override init() { super.init() ; print(#function) } deinit { print(#function) } } FUNCTION_NAME_TEST() // CHECK: init() // CHECK: deinit
apache-2.0
2b4580fe2597d8fe7a685f5bfd3159f2
18.722222
96
0.616901
3.136042
false
true
false
false
robertzhang/Gank.RZ
Gank.RZ/CustomWidget/CircleMenuLib/CircleMenuButton/CircleMenuButton.swift
1
8525
// // CircleMenuButton.swift // // Copyright (c) 18/01/16. Ramotion Inc. (http://ramotion.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit public class CircleMenuButton: UIButton { // MARK: properties public weak var container: UIView? // MARK: life cycle init(size: CGSize, circleMenu: CircleMenu, distance: Float, angle: Float = 0) { super.init(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: size)) self.backgroundColor = UIColor(colorLiteralRed: 0.79, green: 0.24, blue: 0.27, alpha: 1) self.layer.cornerRadius = size.height / 2.0 // add by robertzhang self.titleLabel?.font = UIFont.systemFontOfSize(14) let aContainer = createContainer(CGSize(width: size.width, height:CGFloat(distance)), circleMenu: circleMenu) // hack view for rotate let view = UIView(frame: CGRect(x: 0, y: 0, width: self.bounds.width, height: self.bounds.height)) view.backgroundColor = UIColor.clearColor() view.addSubview(self) //... aContainer.addSubview(view) container = aContainer view.layer.transform = CATransform3DMakeRotation(-CGFloat(angle.degrees), 0, 0, 1) self.rotatedZ(angle: angle, animated: false) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: configure private func createContainer(size: CGSize, circleMenu: CircleMenu) -> UIView { guard let circleMenuSuperView = circleMenu.superview else { fatalError("wront circle menu") } let container = Init(UIView(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: size))) { $0.backgroundColor = UIColor.clearColor() $0.translatesAutoresizingMaskIntoConstraints = false $0.layer.anchorPoint = CGPoint(x: 0.5, y: 1) } circleMenuSuperView.insertSubview(container, belowSubview: circleMenu) // added constraints let height = NSLayoutConstraint(item: container, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .Height, multiplier: 1, constant: size.height) height.identifier = "height" container.addConstraint(height) container.addConstraint(NSLayoutConstraint(item: container, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .Width, multiplier: 1, constant: size.width)) circleMenuSuperView.addConstraint(NSLayoutConstraint(item: circleMenu, attribute: .CenterX, relatedBy: .Equal, toItem: container, attribute: .CenterX, multiplier: 1, constant:0)) circleMenuSuperView.addConstraint(NSLayoutConstraint(item: circleMenu, attribute: .CenterY, relatedBy: .Equal, toItem: container, attribute: .CenterY, multiplier: 1, constant:0)) return container } // MARK: public public func rotatedZ(angle angle: Float, animated: Bool, duration: Double = 0, delay: Double = 0) { guard let container = self.container else { fatalError("contaner don't create") } let rotateTransform = CATransform3DMakeRotation(CGFloat(angle.degrees), 0, 0, 1) if animated { UIView.animateWithDuration( duration, delay: delay, options: UIViewAnimationOptions.CurveEaseInOut, animations: { () -> Void in container.layer.transform = rotateTransform }, completion: nil) } else { container.layer.transform = rotateTransform } } } // MARK: Animations extension CircleMenuButton { public func showAnimation(distance distance: Float, duration: Double, delay: Double = 0) { guard let container = self.container else { fatalError() } let heightConstraint = self.container?.constraints.filter {$0.identifier == "height"}.first guard heightConstraint != nil else { return } self.transform = CGAffineTransformMakeScale(0, 0) self.container?.layoutIfNeeded() self.alpha = 0 heightConstraint?.constant = CGFloat(distance) UIView.animateWithDuration( duration, delay: delay, usingSpringWithDamping: 0.7, initialSpringVelocity: 0, options: UIViewAnimationOptions.CurveLinear, animations: { () -> Void in container.layoutIfNeeded() self.transform = CGAffineTransformMakeScale(1.0, 1.0) self.alpha = 1 }, completion: { (success) -> Void in }) } public func hideAnimation(distance distance: Float, duration: Double, delay: Double = 0) { guard let container = self.container else { fatalError() } let heightConstraint = self.container?.constraints.filter {$0.identifier == "height"}.first guard heightConstraint != nil else { return } heightConstraint?.constant = CGFloat(distance) UIView.animateWithDuration( duration, delay: delay, options: UIViewAnimationOptions.CurveEaseIn, animations: { () -> Void in container.layoutIfNeeded() self.transform = CGAffineTransformMakeScale(0.01, 0.01) }, completion: { (success) -> Void in self.alpha = 0 if let _ = self.container { container.removeFromSuperview() // remove container } }) } public func changeDistance(distance: CGFloat, animated: Bool, duration: Double = 0, delay: Double = 0) { guard let container = self.container else { fatalError() } let heightConstraint = self.container?.constraints.filter {$0.identifier == "height"}.first guard heightConstraint != nil else { return } heightConstraint?.constant = distance UIView.animateWithDuration( duration, delay: delay, options: UIViewAnimationOptions.CurveEaseIn, animations: { () -> Void in container.layoutIfNeeded() }, completion: nil) } // MARK: layer animation public func rotationLayerAnimation(angle: Float, duration: Double) { if let aContainer = container { rotationLayerAnimation(aContainer, angle: angle, duration: duration) } } } extension UIView { public func rotationLayerAnimation(view: UIView, angle: Float, duration: Double) { let rotation = Init(CABasicAnimation(keyPath: "transform.rotation")) { $0.duration = NSTimeInterval(duration) $0.toValue = (angle.degrees) $0.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) } view.layer.addAnimation(rotation, forKey: "rotation") } }
mit
81b2b1f97b2f2b8d5467624c2015b546
33.654472
117
0.599648
5.141737
false
false
false
false
Lves/LLRefresh
LLRefreshDemo/Demos/CustomRefreshTableViewController.swift
1
1624
// // CustomRefreshTableViewController.swift // LLRefreshDemo // // Created by lixingle on 2017/5/16. // Copyright © 2017年 com.lvesli. All rights reserved. // import UIKit import LLRefresh class CustomRefreshTableViewController: UITableViewController { var dataArray:[String] = [] override func viewDidLoad() { super.viewDidLoad() tableView.tableFooterView = UIView() let header = LLCustomHeader(refreshingBlock: {[weak self] _ in self?.loadNewData() }) tableView.ll_header = header tableView.ll_header?.beginRefreshing() } func loadNewData() { //update data let format = DateFormatter() format.dateFormat = "HH:mm:ss" for _ in 0...2 { dataArray.insert(format.string(from: Date()), at: 0) } sleep(2) //end refreshing tableView.ll_header?.endRefreshing() tableView.reloadData() } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataArray.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCell(withIdentifier: "Cell") if cell == nil { cell = UITableViewCell(style: .default, reuseIdentifier: "Cell") } cell?.textLabel?.text = dataArray[indexPath.row] return cell! } }
mit
b79ad241778960ed74c825765155456b
28.472727
109
0.623689
4.753666
false
false
false
false
huangboju/Moots
Examples/边缘侧滑/MagicMove-master/MagicMove/Transition/MagicMovePopTransion.swift
1
1802
// // MagicMovePopTransion.swift // MagicMove // // Created by BourneWeng on 15/7/13. // Copyright (c) 2015年 Bourne. All rights reserved. // import UIKit class MagicMovePopTransion: NSObject, UIViewControllerAnimatedTransitioning { func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.5 } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { let fromVC = transitionContext.viewController(forKey: .from) as! DetailViewController let toVC = transitionContext.viewController(forKey: .to) as! ViewController let container = transitionContext.containerView let snapshotView = fromVC.avatarImageView.snapshotView(afterScreenUpdates: false) snapshotView?.frame = container.convert(fromVC.avatarImageView.frame, from: fromVC.view) fromVC.avatarImageView.isHidden = true toVC.view.frame = transitionContext.finalFrame(for: toVC) toVC.selectedCell.imageView.isHidden = true container.insertSubview(toVC.view, belowSubview: fromVC.view) container.addSubview(snapshotView!) UIView.animate(withDuration: transitionDuration(using: transitionContext), delay: 0, options: .curveEaseInOut, animations: { snapshotView?.frame = container.convert(toVC.selectedCell.imageView.frame, from: toVC.selectedCell) fromVC.view.alpha = 0 }, completion: { _ in toVC.selectedCell.imageView.isHidden = false snapshotView?.removeFromSuperview() fromVC.avatarImageView.isHidden = false transitionContext.completeTransition(!transitionContext.transitionWasCancelled) }) } }
mit
11162af4011106c039634a506517dc77
40.860465
132
0.704444
5.590062
false
false
false
false
tectijuana/patrones
Bloque1SwiftArchivado/PracticasSwift/SalcedoJose/36_C5FechaNacimiento29.swift
1
2120
/* Nombre del programa: Capitulo 5. Problema 36. Autor: Salcedo Morales Jose Manuel Fecha de inicio: 2017-02-12 Descripcion: Usted se encuentra en una habitacion con otras 29 personas. ¿Cual es la probabilidad de una de ellas tengan la misma fecha de nacimiento que usted? */ // LIBRERIAS. import Foundation // CONSTANTES. let PERSONAS: Int = 29 // FUNCIONES. // Funcion para determinar la probabilidad de que al menos una pareja en // un cierto numero de personas en un grupo tenga la misma fecha de nacimiento. // Definir maximo numero de posibles nacimientos antes de repetirse. let NATALICIOS_MAXIMOS: Int = 366 func ProbabilidadMismoNatalicio(numeroPersonas: Int) -> Double { // Definir probabilidad por defecto (si es un grupo menor de 2). var probabilidad: Double = 0.0 // Si el numero de personas es mas que uno y no pasa del maximo numero // de natalicios, calcular probabilidad por cada persona en un grupo. if (numeroPersonas > 1 && NATALICIOS_MAXIMOS >= numeroPersonas) { // Definir numero al cual se repetirian ya nacimientos. let nacimientosRepetidos = NATALICIOS_MAXIMOS + 1 probabilidad = 1.0 var persona: Int = 1 while (persona <= numeroPersonas) { probabilidad = (probabilidad * Double(nacimientosRepetidos - persona)) / Double(NATALICIOS_MAXIMOS) persona = persona + 1 } // Definir probabilidad con la formula de que al menos // dos personas cumplan años el mismo dia. (1-p) probabilidad = (1.0 - probabilidad) * 100.0 } else if (numeroPersonas > NATALICIOS_MAXIMOS) { probabilidad = 100.0 } return probabilidad } // PRINCIPAL. // Definir la probabilidad de tener una misma fecha de nacimiento con otras personas en la misma habitacion. let probabilidadNacimientoRepetido: Double = ProbabilidadMismoNatalicio(numeroPersonas: PERSONAS + 1) // Desplegar la probabilidad para el numero de personas pedido. print("Probabilidad de tener una misma fecha de nacimiento con otras " + String(PERSONAS) + " personas en la misma habitacion es de: ") print(String(probabilidadNacimientoRepetido) + "%") // Desplegar fin de ejecucion. print("\nFIN DE EJECUCION.\n")
gpl-3.0
b7ae9a2963001ac2e0cee578bbb6b47d
34.898305
135
0.752125
3.28882
false
false
false
false
BeitIssieShapiro/IssieBoard
ConfigurableKeyboard/KeyboardKey.swift
2
18176
import UIKit // popup constraints have to be setup with the topmost view in mind; hence these callbacks protocol KeyboardKeyProtocol: class { func frameForPopup(_ key: KeyboardKey, direction: Direction) -> CGRect func willShowPopup(_ key: KeyboardKey, direction: Direction) func willHidePopup(_ key: KeyboardKey) } enum VibrancyType { case lightSpecial case darkSpecial case darkRegular } class KeyboardKey: UIControl { weak var delegate: KeyboardKeyProtocol? var vibrancy: VibrancyType? var text: String { didSet { self.label.text = text self.label.frame = CGRect(x: self.labelInset, y: self.labelInset, width: self.bounds.width - self.labelInset * 2, height: self.bounds.height - self.labelInset * 2) self.redrawText() } } var color: UIColor { didSet { updateColors() }} var underColor: UIColor { didSet { updateColors() }} var borderColor: UIColor { didSet { updateColors() }} var popupColor: UIColor { didSet { updateColors() }} var drawUnder: Bool { didSet { updateColors() }} var drawOver: Bool { didSet { updateColors() }} var drawBorder: Bool { didSet { updateColors() }} var underOffset: CGFloat { didSet { updateColors() }} var textColor: UIColor { didSet { updateColors() }} var downColor: UIColor? { didSet { updateColors() }} var downUnderColor: UIColor? { didSet { updateColors() }} var downBorderColor: UIColor? { didSet { updateColors() }} var downTextColor: UIColor? { didSet { updateColors() }} var labelInset: CGFloat = 0 { didSet { if oldValue != labelInset { self.label.frame = CGRect(x: self.labelInset, y: self.labelInset, width: self.bounds.width - self.labelInset * 2, height: self.bounds.height - self.labelInset * 2) } } } var shouldRasterize: Bool = false { didSet { for view in [self.displayView, self.borderView, self.underView] { view?.layer.shouldRasterize = shouldRasterize view?.layer.rasterizationScale = UIScreen.main.scale } } } var popupDirection: Direction? override var isEnabled: Bool { didSet { updateColors() }} override var isSelected: Bool { didSet { updateColors() } } override var isHighlighted: Bool { didSet { updateColors() } } override var frame: CGRect { didSet { self.redrawText() } } var label: UILabel var popupLabel: UILabel? var shape: Shape? { didSet { if oldValue != nil && shape == nil { oldValue?.removeFromSuperview() } self.redrawShape() updateColors() } } var background: KeyboardKeyBackground var popup: KeyboardKeyBackground? var connector: KeyboardConnector? var displayView: ShapeView var borderView: ShapeView? var underView: ShapeView? var shadowView: UIView var shadowLayer: CALayer init(vibrancy optionalVibrancy: VibrancyType?) { self.vibrancy = optionalVibrancy self.displayView = ShapeView() self.underView = ShapeView() self.borderView = ShapeView() self.shadowLayer = CAShapeLayer() self.shadowView = UIView() self.label = UILabel() self.text = "" self.color = UIColor.white self.underColor = UIColor.gray self.borderColor = UIColor.black self.popupColor = UIColor.white self.drawUnder = true self.drawOver = true self.drawBorder = false self.underOffset = 1 self.background = KeyboardKeyBackground(cornerRadius: 4, underOffset: self.underOffset) self.textColor = UIColor.black self.popupDirection = nil super.init(frame: CGRect.zero) self.addSubview(self.shadowView) self.shadowView.layer.addSublayer(self.shadowLayer) self.addSubview(self.displayView) if let underView = self.underView { self.addSubview(underView) } if let borderView = self.borderView { self.addSubview(borderView) } self.addSubview(self.background) self.background.addSubview(self.label) _ = { self.displayView.isOpaque = false self.underView?.isOpaque = false self.borderView?.isOpaque = false self.shadowLayer.shadowOpacity = Float(0.2) self.shadowLayer.shadowRadius = 4 self.shadowLayer.shadowOffset = CGSize(width: 0, height: 2) self.borderView?.lineWidth = CGFloat(0.5) self.borderView?.fillColor = UIColor.clear self.label.textAlignment = NSTextAlignment.center self.label.baselineAdjustment = UIBaselineAdjustment.alignCenters self.label.font = self.label.font.withSize(20) self.label.adjustsFontSizeToFitWidth = true self.label.minimumScaleFactor = CGFloat(0.1) self.label.isUserInteractionEnabled = false self.label.numberOfLines = 1 }() } required init?(coder: NSCoder) { fatalError("NSCoding not supported") } override func setNeedsLayout() { return super.setNeedsLayout() } var oldBounds: CGRect? override func layoutSubviews() { self.layoutPopupIfNeeded() let boundingBox = (self.popup != nil ? self.bounds.union(self.popup!.frame) : self.bounds) if self.bounds.width == 0 || self.bounds.height == 0 { return } if oldBounds != nil && boundingBox.size.equalTo(oldBounds!.size) { return } oldBounds = boundingBox super.layoutSubviews() CATransaction.begin() CATransaction.setDisableActions(true) self.background.frame = self.bounds self.label.frame = CGRect(x: self.labelInset, y: self.labelInset, width: self.bounds.width - self.labelInset * 2, height: self.bounds.height - self.labelInset * 2) self.displayView.frame = boundingBox self.shadowView.frame = boundingBox self.borderView?.frame = boundingBox self.underView?.frame = boundingBox CATransaction.commit() self.refreshViews() } func refreshViews() { self.refreshShapes() self.redrawText() self.redrawShape() self.updateColors() } func refreshShapes() { self.background.setNeedsLayout() self.background.layoutIfNeeded() self.popup?.layoutIfNeeded() self.connector?.layoutIfNeeded() let testPath = UIBezierPath() let edgePath = UIBezierPath() let unitSquare = CGRect(x: 0, y: 0, width: 1, height: 1) let addCurves = { (fromShape: KeyboardKeyBackground?, toPath: UIBezierPath, toEdgePaths: UIBezierPath) -> Void in if let shape = fromShape { let path = shape.fillPath let translatedUnitSquare = self.displayView.convert(unitSquare, from: shape) let transformFromShapeToView = CGAffineTransform(translationX: translatedUnitSquare.origin.x, y: translatedUnitSquare.origin.y) path?.apply(transformFromShapeToView) if path != nil { toPath.append(path!) } if let edgePaths = shape.edgePaths { for (_, anEdgePath) in edgePaths.enumerated() { let editablePath = anEdgePath editablePath.apply(transformFromShapeToView) toEdgePaths.append(editablePath) } } } } addCurves(self.popup, testPath, edgePath) addCurves(self.connector, testPath, edgePath) let shadowPath = UIBezierPath(cgPath: testPath.cgPath) addCurves(self.background, testPath, edgePath) let underPath = self.background.underPath let translatedUnitSquare = self.displayView.convert(unitSquare, from: self.background) let transformFromShapeToView = CGAffineTransform(translationX: translatedUnitSquare.origin.x, y: translatedUnitSquare.origin.y) underPath?.apply(transformFromShapeToView) CATransaction.begin() CATransaction.setDisableActions(true) if let _ = self.popup { self.shadowLayer.shadowPath = shadowPath.cgPath } self.underView?.curve = underPath self.displayView.curve = testPath self.borderView?.curve = edgePath if let borderLayer = self.borderView?.layer as? CAShapeLayer { borderLayer.strokeColor = UIColor.green.cgColor } CATransaction.commit() } func layoutPopupIfNeeded() { if self.popup != nil && self.popupDirection == nil { self.shadowView.isHidden = false self.borderView?.isHidden = false self.popupDirection = Direction.up self.layoutPopup(self.popupDirection!) self.configurePopup(self.popupDirection!) self.delegate?.willShowPopup(self, direction: self.popupDirection!) } else { self.shadowView.isHidden = true self.borderView?.isHidden = true } } func redrawText() { } func redrawShape() { if let shape = self.shape { self.text = "" shape.removeFromSuperview() self.addSubview(shape) let pointOffset: CGFloat = 4 let size = CGSize(width: self.bounds.width - pointOffset - pointOffset, height: self.bounds.height - pointOffset - pointOffset) shape.frame = CGRect( x: CGFloat((self.bounds.width - size.width) / 2.0), y: CGFloat((self.bounds.height - size.height) / 2.0), width: size.width, height: size.height) shape.setNeedsLayout() } } func updateColors() { CATransaction.begin() CATransaction.setDisableActions(true) let switchColors = self.isHighlighted || self.isSelected if switchColors { if let downColor = self.downColor { self.displayView.fillColor = downColor } else { self.displayView.fillColor = self.color } if let downUnderColor = self.downUnderColor { self.underView?.fillColor = downUnderColor } else { self.underView?.fillColor = self.underColor } if let downBorderColor = self.downBorderColor { self.borderView?.strokeColor = downBorderColor } else { self.borderView?.strokeColor = self.borderColor } if let downTextColor = self.downTextColor { self.label.textColor = downTextColor self.popupLabel?.textColor = downTextColor self.shape?.color = downTextColor } else { self.label.textColor = self.textColor self.popupLabel?.textColor = self.textColor self.shape?.color = self.textColor } } else { self.displayView.fillColor = self.color self.underView?.fillColor = self.underColor self.borderView?.strokeColor = self.borderColor self.label.textColor = self.textColor self.popupLabel?.textColor = self.textColor self.shape?.color = self.textColor } if self.popup != nil { self.displayView.fillColor = self.popupColor } CATransaction.commit() } func layoutPopup(_ dir: Direction) { assert(self.popup != nil, "popup not found") if let popup = self.popup { if let delegate = self.delegate { let frame = delegate.frameForPopup(self, direction: dir) popup.frame = frame popupLabel?.frame = popup.bounds } else { popup.frame = CGRect.zero popup.center = self.center } } } func configurePopup(_ direction: Direction) { assert(self.popup != nil, "popup not found") self.background.attach(direction) self.popup!.attach(direction.opposite()) let kv = self.background let p = self.popup! self.connector?.removeFromSuperview() self.connector = KeyboardConnector(cornerRadius: 4, underOffset: self.underOffset, start: kv, end: p, startConnectable: kv, endConnectable: p, startDirection: direction, endDirection: direction.opposite()) self.connector!.layer.zPosition = -1 self.addSubview(self.connector!) // self.drawBorder = true if direction == Direction.up { // self.popup!.drawUnder = false // self.connector!.drawUnder = false } } func showPopup() { if self.popup == nil { self.layer.zPosition = 1000 let popup = KeyboardKeyBackground(cornerRadius: 9.0, underOffset: self.underOffset) self.popup = popup self.addSubview(popup) let popupLabel = UILabel() popupLabel.textAlignment = self.label.textAlignment popupLabel.baselineAdjustment = self.label.baselineAdjustment popupLabel.font = self.label.font.withSize(20 * 2) popupLabel.adjustsFontSizeToFitWidth = self.label.adjustsFontSizeToFitWidth popupLabel.minimumScaleFactor = CGFloat(0.1) popupLabel.isUserInteractionEnabled = false popupLabel.numberOfLines = 1 popupLabel.frame = popup.bounds popupLabel.text = self.label.text popup.addSubview(popupLabel) self.popupLabel = popupLabel self.label.isHidden = true } } func hidePopup() { if self.popup != nil { self.delegate?.willHidePopup(self) self.popupLabel?.removeFromSuperview() self.popupLabel = nil self.connector?.removeFromSuperview() self.connector = nil self.popup?.removeFromSuperview() self.popup = nil self.label.isHidden = false self.background.attach(nil) self.layer.zPosition = 0 self.popupDirection = nil } } } /* PERFORMANCE NOTES * CAShapeLayer: convenient and low memory usage, but chunky rotations * drawRect: fast, but high memory usage (looks like there's a backing store for each of the 3 views) * if I set CAShapeLayer to shouldRasterize, perf is *almost* the same as drawRect, while mem usage is the same as before * oddly, 3 CAShapeLayers show the same memory usage as 1 CAShapeLayer — where is the backing store? * might want to move to drawRect with combined draw calls for performance reasons — not clear yet */ class ShapeView: UIView { var shapeLayer: CAShapeLayer? override class var layerClass : AnyClass { return CAShapeLayer.self } var curve: UIBezierPath? { didSet { if let layer = self.shapeLayer { layer.path = curve?.cgPath } else { self.setNeedsDisplay() } } } var fillColor: UIColor? { didSet { if let layer = self.shapeLayer { layer.fillColor = fillColor?.cgColor } else { self.setNeedsDisplay() } } } var strokeColor: UIColor? { didSet { if let layer = self.shapeLayer { layer.strokeColor = strokeColor?.cgColor } else { self.setNeedsDisplay() } } } var lineWidth: CGFloat? { didSet { if let layer = self.shapeLayer { if let lineWidth = self.lineWidth { layer.lineWidth = lineWidth } } else { self.setNeedsDisplay() } } } convenience init() { self.init(frame: CGRect.zero) } override init(frame: CGRect) { super.init(frame: frame) self.shapeLayer = self.layer as? CAShapeLayer } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func drawCall(_ rect:CGRect) { if self.shapeLayer == nil { if let curve = self.curve { if let lineWidth = self.lineWidth { curve.lineWidth = lineWidth } if let fillColor = self.fillColor { fillColor.setFill() curve.fill() } if let strokeColor = self.strokeColor { strokeColor.setStroke() curve.stroke() } } } } override func draw(_ rect: CGRect) { if self.shapeLayer == nil { self.drawCall(rect) } } }
apache-2.0
da360d29587a89132651950070536130
31.106007
213
0.557506
5.335291
false
false
false
false
sjtu-meow/iOS
Meow/JSONConvertible.swift
1
3920
import SwiftyJSON import DateToolsSwift public protocol JSONConvertible { static func fromJSON(_ json: JSON) -> Self? } public extension JSON { func toType<T: JSONConvertible>() -> T? { return T.fromJSON(self) } } extension Int : JSONConvertible { public static func fromJSON(_ json: JSON) -> Int? { return json.int ?? Int(json.stringValue) } } extension Float : JSONConvertible { public static func fromJSON(_ json: JSON) -> Float? { return json.float ?? Float(json.stringValue) } } extension Double : JSONConvertible { public static func fromJSON(_ json: JSON) -> Double? { return json.double ?? Double(json.stringValue) } } extension Bool : JSONConvertible { public static func fromJSON(_ json: JSON) -> Bool? { return json.bool ?? Bool(json.stringValue) } } extension String : JSONConvertible { public static func fromJSON(_ json: JSON) -> String? { return json.string } } extension URL : JSONConvertible { public static func fromJSON(_ json: JSON) -> URL? { return URL(string: json.stringValue) } } //ceveat: This is a workaround! //What we want to achieve is to exploit Array's covariance, i.e. if Element : JSONConvertible, [Element] should also be JSONConvertible. //some kind of declaration like //extension Array : JSONConvertible where Element : JSONConvertible //However this cannot be achieved, at least in Swift 3: // Extension of type 'Array' with constraints cannot have an inheritance clause // extension Array : JSONConvertible { public static func fromJSON(_ json: JSON) -> Array? { if let type = Element.self as? JSONConvertible.Type { return json.arrayValue.flatMap { type.fromJSON($0) as? Element } } fatalError("Element \(Element.self) is not JSONConvertible") } } extension Date : JSONConvertible { public static func tryParse(dateString: String, formats: [String]) -> Date? { let dateFormatter = DateFormatter() dateFormatter.dateStyle = .none; dateFormatter.timeStyle = .none; dateFormatter.timeZone = TimeZone.autoupdatingCurrent; for format in formats { dateFormatter.dateFormat = format; if let date = dateFormatter.date(from: dateString) { return date } } return nil } public static func fromJSON(_ json: JSON) -> Date? { return Date.tryParse( dateString: json.stringValue, formats: ["yyyy-MM-dd'T'HH:mm:ssZ", //2014-09-27T17:40:00Z "yyyy-MM-dd HH:mm", //2014-09-27 17:40 "yyyy-MM-dd HH:mm:ss.S", //2014-09-27 17:40:59.0 ]) } } infix operator <- : AssignmentPrecedence func JSON_resolve<T:JSONConvertible>(_ jsons: [JSON]) -> T? { for json in jsons { if let t:T = json.toType() { return t } } return nil } func <- <T:JSONConvertible>(lhs:inout T, rhs:([JSON],T)) -> Void { lhs = (JSON_resolve(rhs.0) ?? rhs.1) } func <- <T:JSONConvertible>(lhs:inout T, rhs:JSON) -> Void { if let newVal:T = JSON_resolve([rhs]) { lhs = newVal } } func <- <T:JSONConvertible>(lhs:inout T!, rhs:JSON) -> Void { if let newVal:T = JSON_resolve([rhs]) { lhs = newVal } } func <- <T:JSONConvertible>(lhs:inout T, rhs:(JSON,T)) -> Void { lhs = (JSON_resolve([rhs.0]) ?? rhs.1) } func <- <T:JSONConvertible>(lhs:inout T?, rhs:JSON) -> Void { lhs = JSON_resolve([rhs]) } func <- <T : JSONConvertible> (lhs: inout T?, rhs: (JSON,T?)) -> Void { lhs = (JSON_resolve([rhs.0]) ?? rhs.1) } func <- <T:JSONConvertible>(lhs:inout T?, rhs:[JSON]) -> Void { lhs = JSON_resolve(rhs) } func <- <T : JSONConvertible> (lhs: inout T?, rhs: ([JSON],T?)) -> Void { lhs = (JSON_resolve(rhs.0) ?? rhs.1) }
apache-2.0
6c15efeab79f22d830114f8658adf7bd
25.849315
136
0.607398
3.828125
false
false
false
false
masters3d/xswift
exercises/pascals-triangle/Sources/PascalsTriangleExample.swift
3
1011
struct PascalsTriangle { let rows: [[Int]] init(_ numberOfRows: Int) { var triangle = [[Int]]() for rowNumber in 0..<numberOfRows { var values = [Int]() if rowNumber == 0 { values.append(1) } else { let lastRow = triangle[rowNumber - 1] let length = lastRow.count for position in 0...length { let left: Int if position == 0 { left = 0 } else { left = lastRow[position - 1] } let right: Int if position < length { right = lastRow[position] } else { right = 0 } values.append(left + right) } } triangle.append(values) } self.rows = triangle } }
mit
37a773ccb5d083859114bb240b0bf133
24.275
53
0.361029
5.744318
false
false
false
false
artemkalinovsky/SwiftyPiper
SwiftyPiper/Model/DataResponse/DataResponse.swift
1
850
// // DataResponse.swift // SwiftyPiper // // Created by Artem Kalinovsky on 17/02/2016. // Copyright © 2016 Artem Kalinovsky. All rights reserved. // import Foundation class DataResponse: NSObject { var requestedOffset: UInt64 var requestedLength: UInt64 var currentOffset: UInt64 var dataOffset: UInt64 var receivedDataLength: UInt64 var data: NSData! init(requestedOffset: UInt64, requestedLenght: UInt64, receivedDataLength: UInt64, data: NSData) { self.requestedOffset = requestedOffset self.requestedLength = requestedLenght self.receivedDataLength = receivedDataLength self.data = data self.dataOffset = self.requestedOffset + self.receivedDataLength - UInt64(self.data.length) self.currentOffset = self.dataOffset + UInt64(self.data.length) } }
gpl-3.0
38a3526e49cf1708b857f20e767b8f87
28.310345
102
0.710247
4.245
false
false
false
false
tid-kijyun/FontAwesome-IconGenerator
FontAwesome-IconGenerator/IconGenerator.swift
1
4817
/**@file IconGenerator.swift FontAwesome-IconGenerator Copyright (c) 2015 Atsushi Kiwaki (@_tid_) 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 AppKit final class IconGenerator { var fontPath: String init(fontPath: String) { self.fontPath = fontPath } func generate(unicode: String, width: Int, height: Int, fontsize: Int) -> NSImage? { let data = NSData(contentsOfFile: fontPath) var error: Unmanaged<CFError>? let provider = CGDataProviderCreateWithCFData(data) let registerFont: CGFont = CGFontCreateWithDataProvider(provider) if CTFontManagerRegisterGraphicsFont(registerFont, &error) == false { return nil } let fontName = CGFontCopyPostScriptName(registerFont) as String NSLog(fontName) if let font = NSFont(name: fontName, size: CGFloat(fontsize)) { let size = CGSizeMake(CGFloat(width), CGFloat(height)) let attrs: [NSObject: AnyObject] = [NSFontAttributeName: font] var attribute = NSMutableAttributedString(string: unicode, attributes: attrs) let rect = getRect(attribute, size: size) if let offscreenRep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: width, pixelsHigh: height, bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: NSDeviceRGBColorSpace, bitmapFormat: NSBitmapFormat.NSAlphaFirstBitmapFormat, bytesPerRow: 0, bitsPerPixel: 0), let g = NSGraphicsContext(bitmapImageRep: offscreenRep) { // begin -------- NSGraphicsContext.saveGraphicsState() NSGraphicsContext.setCurrentContext(g) let ctx = g.CGContext CGContextSetRGBFillColor(ctx, 1, 0, 0, 0.0) CGContextFillRect(ctx, CGRectMake(0, 0, size.width, size.height)) attribute.drawInRect(rect) // end ---------- CTFontManagerUnregisterGraphicsFont(registerFont, &error) NSGraphicsContext.restoreGraphicsState() let img = NSImage(size: size) img.addRepresentation(offscreenRep) return img } } CTFontManagerUnregisterGraphicsFont(registerFont, &error) return nil } func save(path: String, image: NSImage) { var interlaced: Bool = true var properties: [NSObject: AnyObject] = [NSImageInterlaced: NSNumber(bool: interlaced)] if let data = image.TIFFRepresentation, let bitmapImageRep = NSBitmapImageRep(data: data), let png = bitmapImageRep.representationUsingType(.NSPNGFileType, properties: properties) { png.writeToFile(path, atomically: true) } } private func getRect(attributeString: NSAttributedString, size: CGSize) -> CGRect { let iconSize = attributeString.size let xoff = (size.width - iconSize.width) / 2.0 let yoff = (size.height - iconSize.height) / 2.0 return CGRectMake(xoff, yoff, iconSize.width, iconSize.height) } }
mit
0fb44aa3993df77f1b43d63c26b9aae0
45.317308
105
0.584181
5.727705
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/Platform/Sources/PlatformKit/BuySellKit/Core/Service/PaymentMethods/PaymentMethodRemovalData.swift
1
755
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import AnalyticsKit import FeatureCardPaymentDomain public struct PaymentMethodRemovalData { public enum MethodType { case card(CardType) case beneficiary(Beneficiary.AccountType) } public let id: String public let title: String public let description: String public let event: AnalyticsEvents.SimpleBuy public let type: MethodType public init( id: String, title: String, description: String, event: AnalyticsEvents.SimpleBuy, type: MethodType ) { self.id = id self.title = title self.description = description self.event = event self.type = type } }
lgpl-3.0
759c4da04eee52f8457e8484eebbb1bc
23.322581
62
0.65252
4.960526
false
false
false
false
alexktchen/rescue.iOS
Rescue/RescuePhotoView.swift
1
1935
// // File.swift // Rescue // // Created by Alex Chen on 2015/3/4. // Copyright (c) 2015年 KKAwesome. All rights reserved. // import Foundation import UIKit class RescuePhotoView: UIViewController { @IBOutlet weak var imageView: UIImageView! var photoUrl: NSURL? override func viewDidLoad(){ super.viewDidLoad() addButton() } override func viewWillAppear(animated: Bool) { delay(0.0) { if let data = NSData(contentsOfURL: self.photoUrl!){ self.imageView.contentMode = UIViewContentMode.ScaleAspectFit self.imageView.image = UIImage(data: data) } } view.addSubview(self.imageView) } func delay(delay:Double, closure:()->()) { dispatch_after(dispatch_time(DISPATCH_TIME_NOW,Int64(delay * Double(NSEC_PER_SEC)) ),dispatch_get_main_queue(), closure) } func backButtonPressed(){ self.dismissViewControllerAnimated(true, completion: nil) } func addButton(){ var radius = CGFloat(0.5 * 45.0) var bottomPosition = self.view.frame.height-70 var largeradius = CGFloat(0.5 * 60) let srceenWidth = self.view.frame.width / 4 var backbutton = UIButton.buttonWithType(.Custom) as UIButton backbutton.frame = CGRectMake(10, 20, 45, 45) backbutton.layer.cornerRadius = radius backbutton.backgroundColor = UIColor.clearColor() backbutton.layer.borderWidth = 1 backbutton.layer.borderColor = UIColor.lightGrayColor().CGColor backbutton.setImage(UIImage(named:"cancelButton"), forState: .Normal) backbutton.addTarget(self, action: "backButtonPressed", forControlEvents: .TouchUpInside) self.view.addSubview(backbutton) } }
mit
5badbb457d16f659a75d16763b81e84a
26.239437
97
0.601655
4.784653
false
false
false
false
daaavid/TIY-Assignments
18--Mutt-Cutts/MuttCutts/MuttCutts/MapViewController.swift
1
6545
// // ViewController.swift // MuttCutts // // Created by david on 10/28/15. // Copyright © 2015 The Iron Yard. All rights reserved. // import UIKit import MapKit import CoreLocation protocol PopoverViewControllerDelegate { func search(firstLocation: String, secondLocation: String) } class MapViewController: UIViewController, UIPopoverPresentationControllerDelegate, PopoverViewControllerDelegate, MKMapViewDelegate { @IBOutlet weak var mapView: MKMapView! @IBOutlet weak var distanceLabel: UILabel! @IBOutlet weak var blurView: UIVisualEffectView! let geocoder = CLGeocoder() var distance: CLLocationDistance? var annotations = [MKPointAnnotation]() var secondLocation = "" var mapRoute: MKRoute? override func viewDidLoad() { super.viewDidLoad() blurView.hidden = true mapView.delegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "popover" { let popVC = segue.destinationViewController as! PopoverViewController popVC.popoverPresentationController?.delegate = self popVC.delegate = self popVC.preferredContentSize = CGSizeMake(200, 100) } } func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle { return .None } func search(firstLocation: String, secondLocation: String) { self.dismissViewControllerAnimated(true, completion: nil) annotations.removeAll() print(firstLocation); print(secondLocation) geocoderSearch(firstLocation) self.secondLocation = secondLocation } func geocoderSearch(location: String) { geocoder.geocodeAddressString(location, completionHandler: { (placemarks: [CLPlacemark]?, error: NSError?) -> Void in //go do this and run the code once you've found it if let placemark = placemarks?[0] //grab first in placemarks array { let annotation = MKPointAnnotation() annotation.coordinate = (placemark.location?.coordinate)! annotation.title = location self.annotations.append(annotation) print("geocoder closure \(self.annotations)") if self.annotations.count == 1 { self.geocoderSearch(self.secondLocation) } self.showPins() } }) print("geocoder search \(annotations)") } func showPins() { if annotations.count == 2 { // let lineOfSightDistance = firstDist.distanceFromLocation(secondDist) mapView.addAnnotations(annotations) mapView.showAnnotations(annotations, animated: true) mapView.camera.altitude *= 0.8 route() } } func route() { blurView.hidden = true //http://studyswift.blogspot.com/2014/10/mkdirections-draw-route-from-location.html let plot = MKDirectionsRequest() plot.source = MKMapItem(placemark: MKPlacemark(coordinate: annotations[0].coordinate, addressDictionary: nil)) plot.destination = MKMapItem(placemark: MKPlacemark(coordinate: annotations[1].coordinate, addressDictionary: nil)) plot.transportType = .Automobile let route = MKDirections(request: plot) route.calculateDirectionsWithCompletionHandler { (response: MKDirectionsResponse?, error: NSError?) -> Void in if error == nil { self.distance = response!.routes.first?.distance self.mapRoute = response!.routes[0] self.mapView.addOverlay((self.mapRoute?.polyline)!) self.annotations[0].subtitle = "Origin" self.annotations[1].subtitle = "Destination" self.setDistLabel() } else if error != nil { print(error) self.errorOutput() } } } func mapView(mapView: MKMapView, rendererForOverlay overlay: MKOverlay) -> MKOverlayRenderer { let renderer = MKPolylineRenderer(overlay: overlay) renderer.strokeColor = UIColor.redColor() renderer.lineWidth = 3 return renderer } func setDistLabel() { // distanceLabel.text = ("Driving distance between \(annotations[0].title!) and \(annotations[1].title!): " + String(format: "%.2f", distance! * 0.00062137) + " miles") // blurView.hidden = false blurView.hidden = false UIView.animateWithDuration(0.5, animations: { var blurViewTop = self.blurView.frame blurViewTop.origin.y -= self.blurView.frame.size.height self.blurView.frame = blurViewTop self.distanceLabel.text = ("Driving distance between \(self.annotations[0].title!) and \(self.annotations[1].title!): " + String(format: "%.2f", self.distance! * 0.00062137) + " miles") }) UIApplication.sharedApplication().networkActivityIndicatorVisible = false } @IBAction func clearButton(sender: UIBarButtonItem) { mapView.removeAnnotations(annotations) mapView.removeOverlays(mapView.overlays) UIView.animateWithDuration(0.5, animations: { var blurViewTop = self.blurView.frame blurViewTop.origin.y -= self.blurView.frame.size.height self.blurView.frame = blurViewTop self.blurView.hidden = true }) distanceLabel.text = "" } func errorOutput() { UIView.animateWithDuration(0.5, animations: { var blurViewTop = self.blurView.frame blurViewTop.origin.y -= self.blurView.frame.size.height self.blurView.frame = blurViewTop self.distanceLabel.text = "Couldn't access route at this time. Please try again later." }) } }
cc0-1.0
73fd20b5065ee05a311f0f2946e26238
31.39604
197
0.597341
5.453333
false
false
false
false
orucrob/Hoppla
Hoppla/HopplaImage.swift
1
10028
/* The MIT License (MIT) Copyright (c) 2015 Rob Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import Foundation import UIKit //NOTE: constraints were removed, manual layout has better berformence when there is large amount of views @IBDesignable class HopplaImage: UIView { ///animation duration of animateHoppla or show/hide label var animDuration = 0.2; ///font size for label, changes also the label corner radius and padding @IBInspectable var fontSize:CGFloat = 20 { didSet{ if(_labValue != nil){ _labValue!.font = _labValue!.font.fontWithSize(fontSize) layoutLabel() //_heightUpdated() } } } ///enable or disable blur effect instad of opacity background of label (blur needs more resources while scrolling) @IBInspectable var blurEnabled:Bool = false{ didSet{ if(_labValueWrap != nil){ if(blurEnabled){ _labValueWrap!.backgroundColor = nil _effectView = UIVisualEffectView (effect: UIBlurEffect(style: UIBlurEffectStyle.Light)) _labValueWrap!.addSubview(_effectView!) _labValueWrap!.sendSubviewToBack(_effectView!) // _layoutEffectView() }else{ _labValueWrap!.backgroundColor = UIColor(white: 1, alpha: 0.5) _effectView?.removeFromSuperview() _effectView = nil } } } } //main image view private var _imageView : UIImageView? ///name of image for main image view @IBInspectable var imageName:String?{ didSet{ if(imageName != nil){ if(_imageView == nil){ _imageView = UIImageView(image: UIImage(named: imageName!)) addSubview(_imageView!) _imageView!.contentMode = imgContentMode sendSubviewToBack(_imageView!) // _layoutImage() }else{ _imageView!.image = UIImage(named: imageName!) } } } } ///content mode attribute of main image view @IBInspectable var imgContentMode: UIViewContentMode = .ScaleAspectFit{ didSet{ _imageView?.contentMode = imgContentMode } } ///main image view padding in this view @IBInspectable var imagePadding: CGFloat = 0 { didSet{ if(imagePadding != oldValue){ setNeedsLayoutForce() } } } //labels components private var _labValueWrap: UIView? private var _effectView:UIVisualEffectView? private var _labValue:UILabel? ///whether the labale is shown or hidden @IBInspectable var labelHidden:Bool = true { didSet{ if(labelHidden){ if let lw = _labValueWrap{ lw.removeFromSuperview(); _labValueWrap = nil _effectView = nil _labValue = nil } }else{ _labValueWrap = UIView() _labValue = UILabel() addSubview(_labValueWrap!) _labValueWrap!.clipsToBounds = true _labValueWrap!.addSubview(_labValue!) var old = blurEnabled //TODO invoke did set of blur enabled blurEnabled = old _labValue!.text = "\(value)" _labValueWrap!.layer.borderColor = UIColor.blackColor().CGColor _labValueWrap!.layer.borderWidth = 1 _labValue!.textColor = UIColor.blackColor() _labValue!.font = UIFont.boldSystemFontOfSize(fontSize) _labValue!.numberOfLines = 1; _labValue!.textAlignment = NSTextAlignment.Center _labValue!.baselineAdjustment = UIBaselineAdjustment.AlignCenters bringSubviewToFront(_labValueWrap!) setNeedsLayoutForce() } } } //ability to hide label with animation func hideLabel(animate: Bool = true){ if(_labValueWrap != nil){ if(animate){ UIView.animateWithDuration(1, animations: { () -> Void in self._labValueWrap!.alpha = 0 }, completion: { (f) -> Void in self.labelHidden = true }) }else{ labelHidden = true } } } //ability to show label with animation func showLabel(animate:Bool = true){ if(labelHidden){ labelHidden = false if(animate){ _labValueWrap!.alpha = 0 layoutLabel() UIView.animateWithDuration(1, animations: { () -> Void in self._labValueWrap!.alpha = 1 }, completion: { (f) -> Void in }) } } } ///view can cald the value, label displays it var value:Int = 0{ didSet{ _labValue?.text = "\(value)" layoutLabel() } } ///set value with ability to animate increase or decrase func setValue(value:Int, withAnimation:Bool = true){ if(value != self.value){ if(withAnimation){ animateHoppla(value>self.value) } self.value = value } } func setNeedsLayoutForce() { _w = 0 setNeedsLayout() } //MARK - helpers and layout private var _w:CGFloat = 0, _h:CGFloat = 0 override func layoutSubviews() { super.layoutSubviews() if(bounds.width != _w || bounds.height != _h){ _w = bounds.width _h = bounds.height //image layoutImg() //label layoutLabel() } } private func layoutImg(){ if let iv = _imageView{ iv.frame = CGRect(x: imagePadding, y: imagePadding, width: bounds.width - 2*imagePadding, height: bounds.height - 2*imagePadding) } } private func layoutLabel(){ //labelwrap if let lw = _labValueWrap{ if let lv = _labValue{ lv.sizeToFit() var h = ceil(lv.bounds.height/3) lw.layer.cornerRadius = h //lv frame lv.frame.origin.x = h lv.frame.origin.y = 0 //lw frame lw.frame.size.width = lv.bounds.width + 2*h lw.frame.size.height = lv.bounds.height lw.frame.origin.x = bounds.size.width - lw.bounds.width lw.frame.origin.y = bounds.size.height - lw.bounds.height } if let ev = _effectView{ ev.frame = lw.bounds } } } //MARK: - animation (positive or negativ hoppla) func animateHoppla(positive: Bool){ if(_imageView != nil){ var t = CGAffineTransformIdentity var t2 = CGAffineTransformIdentity var t3 = CGAffineTransformIdentity if positive { t = CGAffineTransformScale(t, 1.4, 1.4) t2 = CGAffineTransformScale(t2, 0.9, 0.9) }else{ t = CGAffineTransformScale(t, 0.6, 0.6) t2 = CGAffineTransformScale(t2, 1.1, 1.1) } UIView.animateWithDuration(animDuration, delay: 0.0, options: .CurveEaseIn , animations: { self._imageView!.transform = t }, completion: { finished in UIView.animateWithDuration(self.animDuration, delay: 0.0, options: .CurveEaseOut , animations: { self._imageView!.transform = t2 }, completion:{ finished in UIView.animateWithDuration(self.animDuration, delay: 0.0, options: .CurveEaseOut, animations: { self._imageView!.transform = t3 }, completion:{ finished in self.layoutImg() } ) } ) } ) } } }
mit
5d1d44d521a00b7e34cfcfee23f6b481
33.940767
141
0.504886
5.58663
false
false
false
false
elslooo/hoverboard
OnboardKit/OnboardKit/OnboardFooterView.swift
1
4258
/* * Copyright (c) 2017 Tim van Elsloo * * 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 public class OnboardFooterView : NSView { /** * This is the text that is shown in the footer view. */ public var text: String = "" /** * This is the text in the link that is shown. */ public var link: String = "" /** * This is the closure that gets called when the user presses the link. */ public var action: ((Void) -> Void)? /** * This is the label that shows the regular text. */ private let label: NSTextField = { let label = NSTextField() label.isSelectable = false label.isEditable = false label.isBordered = false label.drawsBackground = false label.textColor = .secondaryLabelColor label.font = .systemFont(ofSize: 14) return label }() /** * This is the link button. */ private let button: Button = { let button = Button() button.isBordered = false return button }() /** * This function initializes a footer view with the given regular text, link * text and action that gets called when the user presses that link. */ public init(text: String, link: String, action: @escaping (Void) -> Void) { super.init(frame: .zero) self.text = text self.link = link self.action = action self.label.stringValue = text self.label.sizeToFit() self.label.frame.origin.x = 94 let underlineStyle = NSUnderlineStyle.styleSingle.rawValue let attributedTitle = NSAttributedString(string: link, attributes: [ NSForegroundColorAttributeName: NSColor.link, NSFontAttributeName: NSFont.systemFont(ofSize: 14), NSUnderlineStyleAttributeName: underlineStyle ]) self.button.attributedTitle = attributedTitle self.button.sizeToFit() self.button.frame.origin.x = self.label.frame.maxX + 2 self.button.target = self self.button.action = #selector(buttonPressed) self.button.cursor = .pointingHand() self.addSubview(self.label) self.addSubview(self.button) } public required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } public override var isFlipped: Bool { return true } public override var allowsVibrancy: Bool { return true } // MARK: - Button /** * This function gets called by the NSButton and propagates that event to * the action closure. */ func buttonPressed(_ sender: NSButton) { self.action?() } // MARK: - Layout /** * We override this function to vertically center the label and button. */ public override func layout() { super.layout() self.label.frame.origin.y = self.bounds.midY - self.label.frame.midY - 3 self.button.frame.origin.y = self.bounds.midY - self.button.frame.midY - 3 } }
mit
0b672388812b30c17cde32bec535361b
30.776119
80
0.626585
4.699779
false
false
false
false
badoo/Chatto
ChattoAdditions/sources/Input/TabInputButton.swift
1
2236
/* The MIT License (MIT) Copyright (c) 2015-present Badoo Trading Limited. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import UIKit public struct TabInputButtonAppearance { public var images: [UIControlStateWrapper: UIImage] public var size: CGSize? public init(images: [UIControlStateWrapper: UIImage], size: CGSize?) { self.images = images self.size = size } } public class TabInputButton: UIButton { static public func makeInputButton(withAppearance appearance: TabInputButtonAppearance, accessibilityID: String? = nil) -> TabInputButton { let images = appearance.images let button = TabInputButton(type: .custom) button.isExclusiveTouch = true images.forEach { (state, image) in button.setImage(image, for: state.controlState) } if let accessibilityIdentifier = accessibilityID { button.accessibilityIdentifier = accessibilityIdentifier } button.size = appearance.size return button } private var size: CGSize? public override var intrinsicContentSize: CGSize { if let size = self.size { return size } return super.intrinsicContentSize } }
mit
61d8d074a0106b17414e709d42eb90b5
35.655738
143
0.72585
5.002237
false
false
false
false
ngageoint/mage-ios
sdk/MageServer.swift
1
12928
// // MageServer.m // mage-ios-sdk // // import Foundation @objc class MageServer: NSObject { static let kServerCompatibilitiesKey = "serverCompatibilities" static let kServerMajorVersionKey = "serverMajorVersion" static let kServerMinorVersionKey = "serverMinorVersion" static let kServerAuthenticationStrategiesKey = "serverAuthenticationStrategies" @objc public var authenticationModules: [AnyHashable: Any]? @objc public static func baseURL() -> URL? { if let baseServerUrl = UserDefaults.standard.baseServerUrl { return URL(string: baseServerUrl) } return nil } @objc public var serverHasLocalAuthenticationStrategy: Bool { get { if let strategies = UserDefaults.standard.serverAuthenticationStrategies, strategies["local"] != nil { return true } return false } } @objc public static var isServerVersion5: Bool { get { return UserDefaults.standard.serverMajorVersion == 5 } } @objc public static var isServerVersion6_0: Bool { get { return UserDefaults.standard.serverMajorVersion == 6 && UserDefaults.standard.serverMinorVersion == 0 } } @objc public var oauthStrategies: [[String: Any]] { get { var _oauthStrategies:[[String: Any]] = [] if let strategies = UserDefaults.standard.serverAuthenticationStrategies { strategies.forEach { key, strategy in if strategy["type"] as? String == "oauth2" { _oauthStrategies.append(["identifier": key, "strategy": strategy]) } } } return _oauthStrategies } } @objc public var strategies: [[String: Any]]? { get { var _strategies: [[String: Any]] = [] if let defaultStrategies = UserDefaults.standard.serverAuthenticationStrategies { defaultStrategies.forEach { key, strategy in if key == "local" { _strategies.append(["identifier": key, "strategy": strategy]) } else { _strategies.insert(["identifier": key, "strategy": strategy], at: 0) } } } return _strategies } } @objc public static func checkServerCompatibility(api: [AnyHashable: Any]?) -> Bool { guard let serverCompatibilities = UserDefaults.standard.serverCompatibilities, let api = api, let apiVersion = api["version"] as? [AnyHashable: Any], let serverMajorVersion = apiVersion["major"] as? Int, let serverMinorVersion = apiVersion["minor"] as? Int else { return false } for compatibility in serverCompatibilities { if let serverCompatibilityMajorVersion = compatibility[MageServer.kServerMajorVersionKey], let serverCompatibilityMinorVersion = compatibility[kServerMinorVersionKey], serverCompatibilityMajorVersion == serverMajorVersion, serverCompatibilityMinorVersion <= serverMinorVersion { // server is compatible, save the version UserDefaults.standard.serverMajorVersion = serverMajorVersion UserDefaults.standard.serverMinorVersion = serverMinorVersion return true } } return false } @objc public static func generateServerCompatibilityError(api: [AnyHashable: Any]?) -> NSError { if let api = api, let apiVersion = api["version"] as? [AnyHashable: Any], let serverMajorVersion = apiVersion["major"] as? Int, let serverMinorVersion = apiVersion["minor"] as? Int, let serverMicroVersion = apiVersion["micro"] as? Int { return NSError(domain: "MAGE", code: 1, userInfo: [ NSLocalizedDescriptionKey: "This version of the app is not compatible with version \(serverMajorVersion).\(serverMinorVersion).\(serverMicroVersion) of the server. Please contact your MAGE administrator for more information." ]) } if let api = api, let prettyApi = String(data: try! JSONSerialization.data(withJSONObject: api, options: .prettyPrinted), encoding: .utf8 ) { return NSError(domain: "MAGE", code: 1, userInfo: [ NSLocalizedDescriptionKey: "Invalid server response \(prettyApi)" ]) } return NSError(domain: "MAGE", code: 1, userInfo: [ NSLocalizedDescriptionKey: "Invalid server response" ]) } @objc public static func server(url: URL?, success: ((MageServer) -> Void)?, failure: ((NSError) -> Void)?) { guard let url = url, url.scheme != nil, url.host != nil else { failure?(NSError(domain: NSURLErrorDomain, code: NSURLErrorBadURL, userInfo: [NSLocalizedDescriptionKey: "Invalid URL"])) return } let server = MageServer(url: url); // TODO: we need a way to force re-fetch the api in case strategies changed if (url.absoluteString == UserDefaults.standard.baseServerUrl && server.authenticationModules != nil) { success?(server) return } let manager = MageSessionManager.shared() let apiURL = "\(url.absoluteString)/api" let methodStart = Date() NSLog("TIMING API @ \(methodStart)") let task = manager?.get_TASK(apiURL, parameters: nil, progress: nil, success: { task, response in NSLog("TIMING Fetched API. Elapsed: \(methodStart.timeIntervalSinceNow) seconds") if let dataResponse = response as? Data { if dataResponse.count == 0 { failure?(NSError(domain: NSURLErrorDomain, code: NSURLErrorBadURL, userInfo: [NSLocalizedDescriptionKey: "Empty API response received from server."])) return } // try to turn it into a string in case it was HTML if let responseString = String(data: dataResponse, encoding: .utf8) { failure?(NSError(domain: NSURLErrorDomain, code: NSURLErrorBadURL, userInfo: [NSLocalizedDescriptionKey: "Invalid API response received from server. \(responseString)"])) return } } guard let apiResponse = response as? [AnyHashable : Any] else { failure?(NSError(domain: NSURLErrorDomain, code: NSURLErrorBadURL, userInfo: [NSLocalizedDescriptionKey: "Unknown API response received from server. \(task.response?.mimeType ?? "unkonwn mime type")"])) return } if MageServer.checkServerCompatibility(api: apiResponse) { UserDefaults.standard.baseServerUrl = url.absoluteString } else { failure?(MageServer.generateServerCompatibilityError(api: apiResponse)) return } UserDefaults.standard.locationServiceDisabled = apiResponse[ApiKey.locationServiceDisabled.key] as? Bool ?? false if let disclaimer = apiResponse[ApiKey.disclaimer.key] as? [String: Any] { UserDefaults.standard.showDisclaimer = disclaimer[DisclaimerKey.show.key] as? Bool ?? false UserDefaults.standard.disclaimerText = disclaimer[DisclaimerKey.text.key] as? String UserDefaults.standard.disclaimerTitle = disclaimer[DisclaimerKey.title.key] as? String } if let contactInfo = apiResponse[ApiKey.contactinfo.key] as? [String: Any] { UserDefaults.standard.contactInfoEmail = contactInfo[ContactInfoKey.email.key] as? String UserDefaults.standard.contactInfoPhone = contactInfo[ContactInfoKey.phone.key] as? String } // TODO: strategies value should be optional in case the server sends back something crazy if let authenticationStrategies = apiResponse[ApiKey.authenticationStrategies.key] as? [String: [AnyHashable: Any]] { UserDefaults.standard.authenticationStrategies = authenticationStrategies UserDefaults.standard.serverAuthenticationStrategies = authenticationStrategies var authenticationModules: [String: Any] = [:] for (authenticationStrategy, parameters) in authenticationStrategies { if let authenticationModule = Authentication.authenticationModule(forStrategy: authenticationStrategy, parameters: parameters) { authenticationModules[authenticationStrategy] = authenticationModule } } if let oldLoginParameters = UserDefaults.standard.loginParameters, let oldUrl = oldLoginParameters[LoginParametersKey.serverUrl.key] as? String, oldUrl == url.absoluteString, StoredPassword.retrieveStoredPassword() != nil { authenticationModules["offline"] = Authentication.authenticationModule(forStrategy:"offline", parameters:nil) } server.authenticationModules = authenticationModules success?(server) return } else { failure?(NSError(domain: NSURLErrorDomain, code: NSURLErrorBadURL, userInfo: [NSLocalizedDescriptionKey: "Invalid response from the MAGE server. \(apiResponse)"])) return } }, failure: { task, error in // check if the error indicates that the network is unavailable and return the offline authentication module let error = error as NSError if error.domain == NSURLErrorDomain && (error.code == NSURLErrorCannotConnectToHost || error.code == NSURLErrorNetworkConnectionLost || error.code == NSURLErrorNotConnectedToInternet || error.code == NSURLErrorTimedOut ) { if let oldLoginParameters = UserDefaults.standard.loginParameters, let oldUrl = oldLoginParameters[LoginParametersKey.serverUrl.key] as? String, oldUrl == url.absoluteString, StoredPassword.retrieveStoredPassword() != nil { if let authentication: AuthenticationProtocol = Authentication.authenticationModule(forStrategy: "offline", parameters: nil), authentication.canHandleLogin(toURL: url.absoluteString) { server.authenticationModules = ["offline":authentication] } success?(server) } else { // we can't log in offline because there are no offline credentials stored failure?(NSError(domain: NSURLErrorDomain, code: NSURLErrorBadURL, userInfo: [NSLocalizedDescriptionKey: "Failed to connect to server. Received error \(error.localizedDescription)"])) } } else { failure?(NSError(domain: NSURLErrorDomain, code: NSURLErrorBadURL, userInfo: [NSLocalizedDescriptionKey: "Failed to connect to server. Received error \(error.localizedDescription)"])) } }) if let task = task { manager?.addTask(task) } } public init(url: URL) { super.init() if url.absoluteString != UserDefaults.standard.baseServerUrl { return } // TODO: strategies value should be optional in case the server sends back something crazy if let authenticationStrategies = UserDefaults.standard.authenticationStrategies { UserDefaults.standard.serverAuthenticationStrategies = authenticationStrategies var authenticationModules: [String: Any] = [:] for (authenticationStrategy, parameters) in authenticationStrategies { if let authenticationModule = Authentication.authenticationModule(forStrategy: authenticationStrategy, parameters: parameters) { authenticationModules[authenticationStrategy] = authenticationModule } } if let oldLoginParameters = UserDefaults.standard.loginParameters, let oldUrl = oldLoginParameters[LoginParametersKey.serverUrl.key] as? String, oldUrl == url.absoluteString, StoredPassword.retrieveStoredPassword() != nil { authenticationModules["offline"] = Authentication.authenticationModule(forStrategy:"offline", parameters:nil) } self.authenticationModules = authenticationModules } } }
apache-2.0
ccf7565488ceef743752c620d4cab7ae
49.897638
242
0.615718
5.841844
false
false
false
false
xedin/swift
benchmark/single-source/ProtocolDispatch2.swift
4
1853
//===--- ProtocolDispatch2.swift ------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // This is a simple benchmark that tests the performance of calls to // existential methods. //===----------------------------------------------------------------------===// import TestsUtils import Foundation public let ProtocolDispatch2 = BenchmarkInfo( name: "ProtocolDispatch2", runFunction: run_ProtocolDispatch2, tags: [.validation, .abstraction]) protocol Pingable { func ping() -> Int; func pong() -> Int} struct Game : Pingable { func zero() -> Int { return 0} func ping() -> Int { return 1} func pong() -> Int { return 2} func puff() -> Int { return 3} } @inline(never) func use_protocol(_ val : Int,_ game1 : Pingable, _ game2 : Pingable) -> Int { var t = game1.ping() + game1.pong() if (val % 2 == 0) { t += game1.pong() + game1.ping() } t += game1.ping() + game1.pong() t += game2.ping() + game2.pong() if (val % 2 == 0) { t += game2.pong() + game2.ping() } t += game2.ping() + game2.pong() return t } @inline(never) func wrapper(_ val : Int,_ game1 : Pingable, _ game2 : Pingable) -> Int { return use_protocol(val, game1, game2) } @inline(never) public func run_ProtocolDispatch2(_ N: Int) { var c = 0 let g1 = Game() let g2 = Game() for _ in 1...10*N { c = 0 for i in 1...5000 { c += wrapper(i, g1, g2) } } CheckResults(c == 75000) }
apache-2.0
99c270c9b80121935c628e061443652d
26.25
80
0.562871
3.654832
false
false
false
false
TimurBK/SwiftSampleProject
Pods/RealmSwift/RealmSwift/RealmCollection.swift
2
66389
//////////////////////////////////////////////////////////////////////////// // // 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 #if swift(>=3.0) /** An iterator for a `RealmCollection` instance. */ public final class RLMIterator<T: Object>: IteratorProtocol { private var i: UInt = 0 private let generatorBase: NSFastEnumerationIterator init(collection: RLMCollection) { generatorBase = NSFastEnumerationIterator(collection) } /// Advance to the next element and return it, or `nil` if no next element exists. public func next() -> T? { // swiftlint:disable:this valid_docs let accessor = unsafeBitCast(generatorBase.next() as! Object?, to: Optional<T>.self) if let accessor = accessor { RLMInitializeSwiftAccessorGenerics(accessor) } return accessor } } /** A `RealmCollectionChange` value encapsulates information about changes to collections that are reported by Realm notifications. The change information is available in two formats: a simple array of row indices in the collection for each type of change, and an array of index paths in a requested section suitable for passing directly to `UITableView`'s batch update methods. The arrays of indices in the `.Update` case follow `UITableView`'s batching conventions, and can be passed as-is to a table view's batch update functions after being converted to index paths. For example, for a simple one-section table view, you can do the following: ```swift self.notificationToken = results.addNotificationBlock { changes in switch changes { case .initial: // Results are now populated and can be accessed without blocking the UI self.tableView.reloadData() break case .update(_, let deletions, let insertions, let modifications): // Query results have changed, so apply them to the TableView self.tableView.beginUpdates() self.tableView.insertRowsAtIndexPaths(insertions.map { NSIndexPath(forRow: $0, inSection: 0) }, withRowAnimation: .Automatic) self.tableView.deleteRowsAtIndexPaths(deletions.map { NSIndexPath(forRow: $0, inSection: 0) }, withRowAnimation: .Automatic) self.tableView.reloadRowsAtIndexPaths(modifications.map { NSIndexPath(forRow: $0, inSection: 0) }, withRowAnimation: .Automatic) self.tableView.endUpdates() break case .error(let err): // An error occurred while opening the Realm file on the background worker thread fatalError("\(err)") break } } ``` */ public enum RealmCollectionChange<T> { /** `.initial` indicates that the initial run of the query has completed (if applicable), and the collection can now be used without performing any blocking work. */ case initial(T) /** `.update` indicates that a write transaction has been committed which either changed which objects are in the collection, and/or modified one or more of the objects in the collection. All three of the change arrays are always sorted in ascending order. - parameter deletions: The indices in the previous version of the collection which were removed from this one. - parameter insertions: The indices in the new collection which were added in this version. - parameter modifications: The indices of the objects in the new collection which were modified in this version. */ case update(T, deletions: [Int], insertions: [Int], modifications: [Int]) /** If an error occurs, notification blocks are called one time with a `.error` result and an `NSError` containing details about the error. This can only currently happen if the Realm is opened on a background worker thread to calculate the change set. */ case error(Error) static func fromObjc(value: T, change: RLMCollectionChange?, error: Error?) -> RealmCollectionChange { if let error = error { return .error(error) } if let change = change { return .update(value, deletions: change.deletions as [Int], insertions: change.insertions as [Int], modifications: change.modifications as [Int]) } return .initial(value) } } /** A homogenous collection of `Object`s which can be retrieved, filtered, sorted, and operated upon. */ public protocol RealmCollection: RandomAccessCollection, LazyCollectionProtocol, CustomStringConvertible, ThreadConfined { // Must also conform to `AssistedObjectiveCBridgeable` /// The type of the objects contained in the collection. associatedtype Element: Object // MARK: Properties /// The Realm which manages the collection, or `nil` for unmanaged collections. var realm: Realm? { get } /** Indicates if the collection can no longer be accessed. The collection can no longer be accessed if `invalidate()` is called on the `Realm` that manages the collection. */ var isInvalidated: Bool { get } /// The number of objects in the collection. var count: Int { get } /// A human-readable description of the objects contained in the collection. var description: String { get } // MARK: Index Retrieval /** Returns the index of an object in the collection, or `nil` if the object is not present. - parameter object: An object. */ func index(of object: Element) -> Int? /** Returns the index of the first object matching the predicate, or `nil` if no objects match. - parameter predicate: The predicate to use to filter the objects. */ func index(matching predicate: NSPredicate) -> Int? /** Returns the index of the first object matching the predicate, or `nil` if no objects match. - parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments. */ func index(matching predicateFormat: String, _ args: Any...) -> Int? // MARK: Filtering /** Returns a `Results` containing all objects matching the given predicate in the collection. - parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments. */ func filter(_ predicateFormat: String, _ args: Any...) -> Results<Element> /** Returns a `Results` containing all objects matching the given predicate in the collection. - parameter predicate: The predicate to use to filter the objects. */ func filter(_ predicate: NSPredicate) -> Results<Element> // MARK: Sorting /** Returns a `Results` containing the objects in the collection, but sorted. Objects are sorted based on the values of the given key path. For example, to sort a collection of `Student`s from youngest to oldest based on their `age` property, you might call `students.sorted(byKeyPath: "age", ascending: true)`. - warning: Collections 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. */ func sorted(byKeyPath keyPath: String, ascending: Bool) -> Results<Element> /** Returns a `Results` containing the objects in the collection, but sorted. Objects are sorted based on the values of the given property. For example, to sort a collection of `Student`s from youngest to oldest based on their `age` property, you might call `students.sorted(byProperty: "age", ascending: true)`. - warning: Collections may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision floating point, integer, and string types. - parameter property: The name of the property to sort by. - parameter ascending: The direction to sort in. */ @available(*, deprecated, renamed: "sorted(byKeyPath:ascending:)") func sorted(byProperty property: String, ascending: Bool) -> Results<Element> /** Returns a `Results` containing the objects in the collection, but sorted. - warning: Collections may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision floating point, integer, and string types. - see: `sorted(byKeyPath:ascending:)` - parameter sortDescriptors: A sequence of `SortDescriptor`s to sort by. */ func sorted<S: Sequence>(by sortDescriptors: S) -> Results<Element> where S.Iterator.Element == SortDescriptor // MARK: Aggregate Operations /** Returns the minimum (lowest) value of the given property among all the objects in the collection, or `nil` if the collection 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. */ func min<U: MinMaxType>(ofProperty property: String) -> U? /** Returns the maximum (highest) value of the given property among all the objects in the collection, or `nil` if the collection 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. */ func max<U: MinMaxType>(ofProperty property: String) -> U? /** Returns the sum of the given property for objects in the collection, or `nil` if the collection is empty. - warning: Only names of properties of a type conforming to the `AddableType` protocol can be used. - parameter property: The name of a property conforming to `AddableType` to calculate sum on. */ func sum<U: AddableType>(ofProperty property: String) -> U /** Returns the sum of the values of a given property over all the objects in the collection. - 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. */ func average<U: AddableType>(ofProperty property: String) -> U? // MARK: Key-Value Coding /** Returns an `Array` containing the results of invoking `valueForKey(_:)` with `key` on each of the collection's objects. - parameter key: The name of the property whose values are desired. */ func value(forKey key: String) -> Any? /** Returns an `Array` containing the results of invoking `valueForKeyPath(_:)` with `keyPath` on each of the collection's objects. - parameter keyPath: The key path to the property whose values are desired. */ func value(forKeyPath keyPath: String) -> Any? /** Invokes `setValue(_:forKey:)` on each of the collection's objects using the specified `value` and `key`. - warning: This method may 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. */ func setValue(_ value: Any?, forKey key: String) // 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.addNotificationBlock { 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 `stop()` 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. */ func addNotificationBlock(_ block: @escaping (RealmCollectionChange<Self>) -> Void) -> NotificationToken /// :nodoc: func _addNotificationBlock(_ block: @escaping (RealmCollectionChange<AnyRealmCollection<Element>>) -> Void) -> NotificationToken } private class _AnyRealmCollectionBase<T: Object>: AssistedObjectiveCBridgeable { typealias Wrapper = AnyRealmCollection<Element> typealias Element = T var realm: Realm? { fatalError() } var isInvalidated: Bool { fatalError() } var count: Int { fatalError() } var description: String { fatalError() } func index(of object: Element) -> Int? { fatalError() } func index(matching predicate: NSPredicate) -> Int? { fatalError() } func index(matching predicateFormat: String, _ args: Any...) -> Int? { fatalError() } func filter(_ predicateFormat: String, _ args: Any...) -> Results<Element> { fatalError() } func filter(_ predicate: NSPredicate) -> Results<Element> { fatalError() } func sorted(byKeyPath keyPath: String, ascending: Bool) -> Results<Element> { fatalError() } func sorted<S: Sequence>(by sortDescriptors: S) -> Results<Element> where S.Iterator.Element == SortDescriptor { fatalError() } func min<U: MinMaxType>(ofProperty property: String) -> U? { fatalError() } func max<U: MinMaxType>(ofProperty property: String) -> U? { fatalError() } func sum<U: AddableType>(ofProperty property: String) -> U { fatalError() } func average<U: AddableType>(ofProperty property: String) -> U? { fatalError() } subscript(position: Int) -> Element { fatalError() } func makeIterator() -> RLMIterator<T> { fatalError() } var startIndex: Int { fatalError() } var endIndex: Int { fatalError() } func value(forKey key: String) -> Any? { fatalError() } func value(forKeyPath keyPath: String) -> Any? { fatalError() } func setValue(_ value: Any?, forKey key: String) { fatalError() } func _addNotificationBlock(_ block: @escaping (RealmCollectionChange<Wrapper>) -> Void) -> NotificationToken { fatalError() } class func bridging(from objectiveCValue: Any, with metadata: Any?) -> Self { fatalError() } var bridged: (objectiveCValue: Any, metadata: Any?) { fatalError() } } private final class _AnyRealmCollection<C: RealmCollection>: _AnyRealmCollectionBase<C.Element> { let base: C init(base: C) { self.base = base } // MARK: Properties override var realm: Realm? { return base.realm } override var isInvalidated: Bool { return base.isInvalidated } override var count: Int { return base.count } override var description: String { return base.description } // MARK: Index Retrieval override func index(of object: C.Element) -> Int? { return base.index(of: object) } override func index(matching predicate: NSPredicate) -> Int? { return base.index(matching: predicate) } override func index(matching predicateFormat: String, _ args: Any...) -> Int? { return base.index(matching: NSPredicate(format: predicateFormat, argumentArray: args)) } // MARK: Filtering override func filter(_ predicateFormat: String, _ args: Any...) -> Results<C.Element> { return base.filter(NSPredicate(format: predicateFormat, argumentArray: args)) } override func filter(_ predicate: NSPredicate) -> Results<C.Element> { return base.filter(predicate) } // MARK: Sorting override func sorted(byKeyPath keyPath: String, ascending: Bool) -> Results<C.Element> { return base.sorted(byKeyPath: keyPath, ascending: ascending) } override func sorted<S: Sequence> (by sortDescriptors: S) -> Results<C.Element> where S.Iterator.Element == SortDescriptor { return base.sorted(by: sortDescriptors) } // MARK: Aggregate Operations override func min<U: MinMaxType>(ofProperty property: String) -> U? { return base.min(ofProperty: property) } override func max<U: MinMaxType>(ofProperty property: String) -> U? { return base.max(ofProperty: property) } override func sum<U: AddableType>(ofProperty property: String) -> U { return base.sum(ofProperty: property) } override func average<U: AddableType>(ofProperty property: String) -> U? { return base.average(ofProperty: property) } // MARK: Sequence Support override subscript(position: Int) -> C.Element { // FIXME: it should be possible to avoid this force-casting return unsafeBitCast(base[position as! C.Index], to: C.Element.self) } override func makeIterator() -> RLMIterator<Element> { // FIXME: it should be possible to avoid this force-casting return base.makeIterator() as! RLMIterator<Element> } // MARK: Collection Support override var startIndex: Int { // FIXME: it should be possible to avoid this force-casting return base.startIndex as! Int } override var endIndex: Int { // FIXME: it should be possible to avoid this force-casting return base.endIndex as! Int } // MARK: Key-Value Coding override func value(forKey key: String) -> Any? { return base.value(forKey: key) } override func value(forKeyPath keyPath: String) -> Any? { return base.value(forKeyPath: keyPath) } override func setValue(_ value: Any?, forKey key: String) { base.setValue(value, forKey: key) } // MARK: Notifications /// :nodoc: override func _addNotificationBlock(_ block: @escaping (RealmCollectionChange<Wrapper>) -> Void) -> NotificationToken { return base._addNotificationBlock(block) } // MARK: AssistedObjectiveCBridgeable override class func bridging(from objectiveCValue: Any, with metadata: Any?) -> _AnyRealmCollection { return _AnyRealmCollection( base: (C.self as! AssistedObjectiveCBridgeable.Type).bridging(from: objectiveCValue, with: metadata) as! C) } override var bridged: (objectiveCValue: Any, metadata: Any?) { return (base as! AssistedObjectiveCBridgeable).bridged } } /** A type-erased `RealmCollection`. Instances of `RealmCollection` forward operations to an opaque underlying collection having the same `Element` type. */ public final class AnyRealmCollection<T: Object>: RealmCollection { public func index(after i: Int) -> Int { return i + 1 } public func index(before i: Int) -> Int { return i - 1 } /// The type of the objects contained in the collection. public typealias Element = T fileprivate let base: _AnyRealmCollectionBase<T> fileprivate init(base: _AnyRealmCollectionBase<T>) { self.base = base } /// Creates an `AnyRealmCollection` wrapping `base`. public init<C: RealmCollection>(_ base: C) where C.Element == T { self.base = _AnyRealmCollection(base: base) } // MARK: Properties /// The Realm which manages the collection, or `nil` if the collection is unmanaged. public var realm: Realm? { return base.realm } /** Indicates if the collection can no longer be accessed. The collection can no longer be accessed if `invalidate()` is called on the containing `realm`. */ public var isInvalidated: Bool { return base.isInvalidated } /// The number of objects in the collection. public var count: Int { return base.count } /// A human-readable description of the objects contained in the collection. public var description: String { return base.description } // MARK: Index Retrieval /** Returns the index of the given object, or `nil` if the object is not in the collection. - parameter object: An object. */ public func index(of object: Element) -> Int? { return base.index(of: object) } /** Returns the index of the first object matching the given 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 base.index(matching: predicate) } /** Returns the index of the first object matching the given 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 base.index(matching: NSPredicate(format: predicateFormat, argumentArray: args)) } // MARK: Filtering /** Returns a `Results` containing all objects matching the given predicate in the collection. - parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments. */ public func filter(_ predicateFormat: String, _ args: Any...) -> Results<Element> { return base.filter(NSPredicate(format: predicateFormat, argumentArray: args)) } /** Returns a `Results` containing all objects matching the given predicate in the collection. - parameter predicate: The predicate with which to filter the objects. - returns: A `Results` containing objects that match the given predicate. */ public func filter(_ predicate: NSPredicate) -> Results<Element> { return base.filter(predicate) } // MARK: Sorting /** Returns a `Results` containing the objects in the collection, but sorted. Objects are sorted based on the values of the given key path. For example, to sort a collection of `Student`s from youngest to oldest based on their `age` property, you might call `students.sorted(byKeyPath: "age", ascending: true)`. - warning: Collections 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) -> Results<Element> { return base.sorted(byKeyPath: keyPath, ascending: ascending) } /** Returns a `Results` containing the objects in the collection, but sorted. Objects are sorted based on the values of the given property. For example, to sort a collection of `Student`s from youngest to oldest based on their `age` property, you might call `students.sorted(byProperty: "age", ascending: true)`. - warning: Collections may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision floating point, integer, and string types. - parameter property: The name of the property to sort by. - parameter ascending: The direction to sort in. */ @available(*, deprecated, renamed: "sorted(byKeyPath:ascending:)") public func sorted(byProperty property: String, ascending: Bool) -> Results<Element> { return sorted(byKeyPath: property, ascending: ascending) } /** Returns a `Results` containing the objects in the collection, but sorted. - warning: Collections may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision floating point, integer, and string types. - see: `sorted(byKeyPath:ascending:)` - parameter sortDescriptors: A sequence of `SortDescriptor`s to sort by. */ public func sorted<S: Sequence>(by sortDescriptors: S) -> Results<Element> where S.Iterator.Element == SortDescriptor { return base.sorted(by: sortDescriptors) } // MARK: Aggregate Operations /** Returns the minimum (lowest) value of the given property among all the objects in the collection, or `nil` if the collection 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<U: MinMaxType>(ofProperty property: String) -> U? { return base.min(ofProperty: property) } /** Returns the maximum (highest) value of the given property among all the objects in the collection, or `nil` if the collection 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 max<U: MinMaxType>(ofProperty property: String) -> U? { return base.max(ofProperty: property) } /** Returns the sum of the values of a given property over all the objects in the collection. - 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<U: AddableType>(ofProperty property: String) -> U { return base.sum(ofProperty: property) } /** Returns the average value of a given property over all the objects in the collection, or `nil` if the collection is empty. - warning: Only the name of 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<U: AddableType>(ofProperty property: String) -> U? { return base.average(ofProperty: property) } // MARK: Sequence Support /** Returns the object at the given `index`. - parameter index: The index. */ public subscript(position: Int) -> T { return base[position] } /// Returns a `RLMIterator` that yields successive elements in the collection. public func makeIterator() -> RLMIterator<T> { return base.makeIterator() } // MARK: Collection Support /// The position of the first element in a non-empty collection. /// Identical to endIndex in an empty collection. public var startIndex: Int { return base.startIndex } /// 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 base.endIndex } // MARK: Key-Value Coding /** Returns an `Array` containing the results of invoking `valueForKey(_:)` with `key` on each of the collection's objects. - parameter key: The name of the property whose values are desired. */ public func value(forKey key: String) -> Any? { return base.value(forKey: key) } /** Returns an `Array` containing the results of invoking `valueForKeyPath(_:)` with `keyPath` on each of the collection's objects. - parameter keyPath: The key path to the property whose values are desired. */ public func value(forKeyPath keyPath: String) -> Any? { return base.value(forKeyPath: keyPath) } /** Invokes `setValue(_:forKey:)` on each of the collection's objects using the specified `value` and `key`. - warning: This method may only be called during a write transaction. - parameter value: The value to set the property to. - parameter key: The name of the property whose value should be set on each object. */ public func setValue(_ value: Any?, forKey key: String) { base.setValue(value, forKey: key) } // 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.addNotificationBlock { 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 `stop()` 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 addNotificationBlock(_ block: @escaping (RealmCollectionChange<AnyRealmCollection>) -> Void) -> NotificationToken { return base._addNotificationBlock(block) } /// :nodoc: public func _addNotificationBlock(_ block: @escaping (RealmCollectionChange<AnyRealmCollection>) -> Void) -> NotificationToken { return base._addNotificationBlock(block) } } // MARK: AssistedObjectiveCBridgeable private struct AnyRealmCollectionBridgingMetadata<T: Object> { var baseMetadata: Any? var baseType: _AnyRealmCollectionBase<T>.Type } extension AnyRealmCollection: AssistedObjectiveCBridgeable { static func bridging(from objectiveCValue: Any, with metadata: Any?) -> AnyRealmCollection { guard let metadata = metadata as? AnyRealmCollectionBridgingMetadata<T> else { preconditionFailure() } return AnyRealmCollection(base: metadata.baseType.bridging(from: objectiveCValue, with: metadata.baseMetadata)) } var bridged: (objectiveCValue: Any, metadata: Any?) { return ( objectiveCValue: base.bridged.objectiveCValue, metadata: AnyRealmCollectionBridgingMetadata(baseMetadata: base.bridged.metadata, baseType: type(of: base)) ) } } // MARK: Unavailable extension AnyRealmCollection { @available(*, unavailable, renamed: "isInvalidated") public var invalidated: Bool { fatalError() } @available(*, unavailable, renamed: "index(matching:)") public func index(of predicate: NSPredicate) -> Int? { fatalError() } @available(*, unavailable, renamed: "index(matching:_:)") public func index(of predicateFormat: String, _ args: AnyObject...) -> Int? { fatalError() } @available(*, unavailable, renamed: "sorted(byKeyPath:ascending:)") public func sorted(_ property: String, ascending: Bool = true) -> Results<T> { fatalError() } @available(*, unavailable, renamed: "sorted(by:)") public func sorted<S: Sequence>(_ sortDescriptors: S) -> Results<T> where S.Iterator.Element == SortDescriptor { fatalError() } @available(*, unavailable, renamed: "min(ofProperty:)") public func min<U: MinMaxType>(_ property: String) -> U? { fatalError() } @available(*, unavailable, renamed: "max(ofProperty:)") public func max<U: MinMaxType>(_ property: String) -> U? { fatalError() } @available(*, unavailable, renamed: "sum(ofProperty:)") public func sum<U: AddableType>(_ property: String) -> U { fatalError() } @available(*, unavailable, renamed: "average(ofProperty:)") public func average<U: AddableType>(_ property: String) -> U? { fatalError() } } #else /** An iterator for a `RealmCollectionType` instance. */ public final class RLMGenerator<T: Object>: GeneratorType { private let generatorBase: NSFastGenerator internal init(collection: RLMCollection) { generatorBase = NSFastGenerator(collection) } /// Advance to the next element and return it, or `nil` if no next element exists. public func next() -> T? { // swiftlint:disable:this valid_docs let accessor = unsafeBitCast(generatorBase.next() as! Object?, Optional<T>.self) if let accessor = accessor { RLMInitializeSwiftAccessorGenerics(accessor) } return accessor } } /** A `RealmCollectionChange` value encapsulates information about changes to collections that are reported by Realm notifications. The change information is available in two formats: a simple array of row indices in the collection for each type of change, and an array of index paths in a requested section suitable for passing directly to `UITableView`'s batch update methods. The arrays of indices in the `.Update` case follow `UITableView`'s batching conventions, and can be passed as-is to a table view's batch update functions after being converted to index paths. For example, for a simple one-section table view, you can do the following: ```swift self.notificationToken = results.addNotificationBlock { changes in switch changes { case .Initial: // Results are now populated and can be accessed without blocking the UI self.tableView.reloadData() break case .Update(_, let deletions, let insertions, let modifications): // Query results have changed, so apply them to the TableView self.tableView.beginUpdates() self.tableView.insertRowsAtIndexPaths(insertions.map { NSIndexPath(forRow: $0, inSection: 0) }, withRowAnimation: .Automatic) self.tableView.deleteRowsAtIndexPaths(deletions.map { NSIndexPath(forRow: $0, inSection: 0) }, withRowAnimation: .Automatic) self.tableView.reloadRowsAtIndexPaths(modifications.map { NSIndexPath(forRow: $0, inSection: 0) }, withRowAnimation: .Automatic) self.tableView.endUpdates() break case .Error(let err): // An error occurred while opening the Realm file on the background worker thread fatalError("\(err)") break } } ``` */ public enum RealmCollectionChange<T> { /// `.Initial` indicates that the initial run of the query has completed (if applicable), and the /// collection can now be used without performing any blocking work. case Initial(T) /// `.Update` indicates that a write transaction has been committed which either changed which objects /// are in the collection, and/or modified one or more of the objects in the collection. /// /// All three of the change arrays are always sorted in ascending order. /// /// - parameter deletions: The indices in the previous version of the collection /// which were removed from this one. /// - parameter insertions: The indices in the new collection which were added in /// this version. /// - parameter modifications: The indices of the objects in the new collection which /// were modified in this version. case Update(T, deletions: [Int], insertions: [Int], modifications: [Int]) /// If an error occurs, notification blocks are called one time with a /// `.Error` result and an `NSError` containing details about the error. This can only currently happen if the /// Realm is opened on a background worker thread to calculate the change set. case Error(NSError) static func fromObjc(value: T, change: RLMCollectionChange?, error: NSError?) -> RealmCollectionChange { if let error = error { return .Error(error) } if let change = change { return .Update(value, deletions: change.deletions as! [Int], insertions: change.insertions as! [Int], modifications: change.modifications as! [Int]) } return .Initial(value) } } /** A homogenous collection of `Object`s which can be retrieved, filtered, sorted, and operated upon. */ public protocol RealmCollectionType: CollectionType, CustomStringConvertible, ThreadConfined { // Must also conform to `AssistedObjectiveCBridgeable` /// The type of the objects contained in the collection. associatedtype Element: Object // MARK: Properties /// The Realm which manages the collection, or `nil` for unmanaged collections. var realm: Realm? { get } /// Indicates if the collection can no longer be accessed. /// /// The collection can no longer be accessed if `invalidate()` is called on the `Realm` that manages the collection. var invalidated: Bool { get } /// The number of objects in the collection. var count: Int { get } /// A human-readable description of the objects contained in the collection. var description: String { get } // MARK: Index Retrieval /** Returns the index of an object in the collection, or `nil` if the object is not present. - parameter object: An object. */ func indexOf(object: Element) -> Int? /** Returns the index of the first object matching the predicate, or `nil` if no objects match. - parameter predicate: The predicate to use to filter the objects. */ func indexOf(predicate: NSPredicate) -> Int? /** Returns the index of the first object matching the predicate, or `nil` if no objects match. - parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments. */ func indexOf(predicateFormat: String, _ args: AnyObject...) -> Int? // MARK: Filtering /** Returns all objects matching the given predicate in the collection. - parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments. */ func filter(predicateFormat: String, _ args: AnyObject...) -> Results<Element> /** Returns all objects matching the given predicate in the collection. - parameter predicate: The predicate to use to filter the objects. */ func filter(predicate: NSPredicate) -> Results<Element> // MARK: Sorting /** Returns a `Results` containing the objects in the collection, but sorted. Objects are sorted based on the values of the given key path. For example, to sort a collection of `Student`s from youngest to oldest based on their `age` property, you might call `students.sorted(byKeyPath: "age", ascending: true)`. - warning: Collections 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. */ func sorted(byKeyPath: String, ascending: Bool) -> Results<Element> /** Returns a `Results` containing the objects in the collection, but sorted. - warning: Collections may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision floating point, integer, and string types. - see: `sorted(byKeyPath:ascending:)` - parameter sortDescriptors: A sequence of `SortDescriptor`s to sort by. */ func sorted<S: SequenceType where S.Generator.Element == SortDescriptor>(sortDescriptors: S) -> Results<Element> // MARK: Aggregate Operations /** Returns the minimum (lowest) value of the given property among all the objects in the collection, or `nil` if the collection 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. */ func min<U: MinMaxType>(property: String) -> U? /** Returns the maximum (highest) value of the given property among all the objects in the collection, or `nil` if the collection 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. */ func max<U: MinMaxType>(property: String) -> U? /** Returns the sum of the values of a given property over all the objects represented by the collection. - 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. */ func sum<U: AddableType>(property: String) -> U /** Returns the average value of a given property over all the objects in the collection, or `nil` if the collection is empty. - warning: Only the name of 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. */ func average<U: AddableType>(property: String) -> U? // MARK: Key-Value Coding /** Returns an `Array` containing the results of invoking `valueForKey(_:)` with `key` on each of the collection's objects. - parameter key: The name of the property whose values are desired. */ func valueForKey(key: String) -> AnyObject? /** Returns an `Array` containing the results of invoking `valueForKeyPath(_:)` with `keyPath` on each of the collection's objects. - parameter keyPath: The key path to the property whose values are desired. */ func valueForKeyPath(keyPath: String) -> AnyObject? /** Invokes `setValue(_:forKey:)` on each of the collection's objects using the specified `value` and `key`. - warning: This method may 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. */ func setValue(value: AnyObject?, forKey key: String) // 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.addNotificationBlock { 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 `stop()` 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. */ func addNotificationBlock(block: (RealmCollectionChange<Self>) -> Void) -> NotificationToken /// :nodoc: func _addNotificationBlock(block: (RealmCollectionChange<AnyRealmCollection<Element>>) -> Void) -> NotificationToken } private class _AnyRealmCollectionBase<T: Object>: AssistedObjectiveCBridgeable { typealias Wrapper = AnyRealmCollection<Element> typealias Element = T var realm: Realm? { fatalError() } var invalidated: Bool { fatalError() } var count: Int { fatalError() } var description: String { fatalError() } func indexOf(object: Element) -> Int? { fatalError() } func indexOf(predicate: NSPredicate) -> Int? { fatalError() } func indexOf(predicateFormat: String, _ args: AnyObject...) -> Int? { fatalError() } func filter(predicateFormat: String, _ args: AnyObject...) -> Results<Element> { fatalError() } func filter(predicate: NSPredicate) -> Results<Element> { fatalError() } func sorted(property: String, ascending: Bool) -> Results<Element> { fatalError() } func sorted<S: SequenceType where S.Generator.Element == SortDescriptor>(sortDescriptors: S) -> Results<Element> { fatalError() } func min<U: MinMaxType>(property: String) -> U? { fatalError() } func max<U: MinMaxType>(property: String) -> U? { fatalError() } func sum<U: AddableType>(property: String) -> U { fatalError() } func average<U: AddableType>(property: String) -> U? { fatalError() } subscript(index: Int) -> Element { fatalError() } func generate() -> RLMGenerator<T> { fatalError() } var startIndex: Int { fatalError() } var endIndex: Int { fatalError() } func valueForKey(key: String) -> AnyObject? { fatalError() } func valueForKeyPath(keyPath: String) -> AnyObject? { fatalError() } func setValue(value: AnyObject?, forKey key: String) { fatalError() } func _addNotificationBlock(block: (RealmCollectionChange<Wrapper>) -> Void) -> NotificationToken { fatalError() } class func bridging(from objectiveCValue: Any, with metadata: Any?) -> Self { fatalError() } var bridged: (objectiveCValue: Any, metadata: Any?) { fatalError() } } private final class _AnyRealmCollection<C: RealmCollectionType>: _AnyRealmCollectionBase<C.Element> { let base: C init(base: C) { self.base = base } override var realm: Realm? { return base.realm } override var invalidated: Bool { return base.invalidated } override var count: Int { return base.count } override var description: String { return base.description } // MARK: Index Retrieval override func indexOf(object: C.Element) -> Int? { return base.indexOf(object) } override func indexOf(predicate: NSPredicate) -> Int? { return base.indexOf(predicate) } override func indexOf(predicateFormat: String, _ args: AnyObject...) -> Int? { return base.indexOf(NSPredicate(format: predicateFormat, argumentArray: args)) } // MARK: Filtering override func filter(predicateFormat: String, _ args: AnyObject...) -> Results<C.Element> { return base.filter(NSPredicate(format: predicateFormat, argumentArray: args)) } override func filter(predicate: NSPredicate) -> Results<C.Element> { return base.filter(predicate) } // MARK: Sorting override func sorted(property: String, ascending: Bool) -> Results<C.Element> { return base.sorted(property, ascending: ascending) } override func sorted<S: SequenceType where S.Generator.Element == SortDescriptor> (sortDescriptors: S) -> Results<C.Element> { return base.sorted(sortDescriptors) } // MARK: Aggregate Operations override func min<U: MinMaxType>(property: String) -> U? { return base.min(property) } override func max<U: MinMaxType>(property: String) -> U? { return base.max(property) } override func sum<U: AddableType>(property: String) -> U { return base.sum(property) } override func average<U: AddableType>(property: String) -> U? { return base.average(property) } // MARK: Sequence Support override subscript(index: Int) -> C.Element { // FIXME: it should be possible to avoid this force-casting return unsafeBitCast(base[index as! C.Index], C.Element.self) } override func generate() -> RLMGenerator<Element> { // FIXME: it should be possible to avoid this force-casting return base.generate() as! RLMGenerator<Element> } // MARK: Collection Support override var startIndex: Int { // FIXME: it should be possible to avoid this force-casting return base.startIndex as! Int } override var endIndex: Int { // FIXME: it should be possible to avoid this force-casting return base.endIndex as! Int } // MARK: Key-Value Coding override func valueForKey(key: String) -> AnyObject? { return base.valueForKey(key) } override func valueForKeyPath(keyPath: String) -> AnyObject? { return base.valueForKeyPath(keyPath) } override func setValue(value: AnyObject?, forKey key: String) { base.setValue(value, forKey: key) } // MARK: Notifications /// :nodoc: override func _addNotificationBlock(block: (RealmCollectionChange<Wrapper>) -> Void) -> NotificationToken { return base._addNotificationBlock(block) } // MARK: AssistedObjectiveCBridgeable override class func bridging(from objectiveCValue: Any, with metadata: Any?) -> _AnyRealmCollection { return _AnyRealmCollection( base: (C.self as! AssistedObjectiveCBridgeable.Type).bridging(from: objectiveCValue, with: metadata) as! C) } override var bridged: (objectiveCValue: Any, metadata: Any?) { return (base as! AssistedObjectiveCBridgeable).bridged } } /** A type-erased `RealmCollectionType`. Instances of `RealmCollectionType` forward operations to an opaque underlying collection having the same `Element` type. */ public final class AnyRealmCollection<T: Object>: RealmCollectionType { /// The type of the objects contained in the collection. public typealias Element = T private let base: _AnyRealmCollectionBase<T> private init(base: _AnyRealmCollectionBase<T>) { self.base = base } /// Creates an `AnyRealmCollection` wrapping `base`. public init<C: RealmCollectionType where C.Element == T>(_ base: C) { self.base = _AnyRealmCollection(base: base) } // MARK: Properties /// The Realm which manages this collection, or `nil` if the collection is unmanaged. public var realm: Realm? { return base.realm } /// Indicates if the collection can no longer be accessed. /// /// The collection can no longer be accessed if `invalidate()` is called on the containing `realm`. public var invalidated: Bool { return base.invalidated } /// The number of objects in the collection. public var count: Int { return base.count } /// A human-readable description of the objects contained in the collection. public var description: String { return base.description } // MARK: Index Retrieval /** Returns the index of the given object, or `nil` if the object is not in the collection. - parameter object: An object. */ public func indexOf(object: Element) -> Int? { return base.indexOf(object) } /** Returns the index of the first object matching the given predicate, or `nil` if no objects match. - parameter predicate: The predicate with which to filter the objects. */ public func indexOf(predicate: NSPredicate) -> Int? { return base.indexOf(predicate) } /** Returns the index of the first object matching the given predicate, or `nil` if no objects match. - parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments. */ public func indexOf(predicateFormat: String, _ args: AnyObject...) -> Int? { return base.indexOf(NSPredicate(format: predicateFormat, argumentArray: args)) } // MARK: Filtering /** Returns a `Results` containing all objects matching the given predicate in the collection. - parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments. */ public func filter(predicateFormat: String, _ args: AnyObject...) -> Results<Element> { return base.filter(NSPredicate(format: predicateFormat, argumentArray: args)) } /** Returns a `Results` containing all objects matching the given predicate in the collection. - parameter predicate: The predicate with which to filter the objects. */ public func filter(predicate: NSPredicate) -> Results<Element> { return base.filter(predicate) } // MARK: Sorting /** Returns a `Results` containing the objects in the collection, but sorted. Objects are sorted based on the values of the given property. For example, to sort a collection of `Student`s from youngest to oldest based on their `age` property, you might call `students.sorted("age", ascending: true)`. - warning: Collections may only be sorted by properties of boolean, `NSDate`, single and double-precision floating point, integer, and string types. - parameter property: The name of the property to sort by. - parameter ascending: The direction to sort in. */ public func sorted(property: String, ascending: Bool) -> Results<Element> { return base.sorted(property, ascending: ascending) } /** Returns a `Results` containing the objects in the collection, but sorted. - warning: Collections may only be sorted by properties of boolean, `NSDate`, single and double-precision floating point, integer, and string types. - see: `sorted(_:ascending:)` - parameter sortDescriptors: A sequence of `SortDescriptor`s to sort by. */ public func sorted<S: SequenceType where S.Generator.Element == SortDescriptor> (sortDescriptors: S) -> Results<Element> { return base.sorted(sortDescriptors) } // MARK: Aggregate Operations /** Returns the minimum (lowest) value of the given property among all the objects in the collection, or `nil` if the collection 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<U: MinMaxType>(property: String) -> U? { return base.min(property) } /** Returns the maximum (highest) value of the given property among all the objects in the collection, or `nil` if the collection 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 max<U: MinMaxType>(property: String) -> U? { return base.max(property) } /** Returns the sum of the values of a given property over all the objects in the collection. - 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<U: AddableType>(property: String) -> U { return base.sum(property) } /** Returns the average value of a given property over all the objects in the collection, or `nil` if the collection is empty. - warning: Only the name of 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<U: AddableType>(property: String) -> U? { return base.average(property) } // MARK: Sequence Support /** Returns the object at the given `index`. - parameter index: An index to retrieve or set an object from. */ public subscript(index: Int) -> T { return base[index] } /// Returns an `RLMGenerator` that yields successive elements in the collection. public func generate() -> RLMGenerator<T> { return base.generate() } // MARK: Collection Support /// The position of the first element in a non-empty collection. /// Identical to `endIndex` in an empty collection. public var startIndex: Int { return base.startIndex } /// 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 base.endIndex } // MARK: Key-Value Coding /** Returns an `Array` containing the results of invoking `valueForKey(_:)` with `key` on each of the collection's objects. - parameter key: The name of the property whose values are desired. */ public func valueForKey(key: String) -> AnyObject? { return base.valueForKey(key) } /** Returns an `Array` containing the results of invoking `valueForKeyPath(_:)` with `keyPath` on each of the collection's objects. - parameter keyPath: The key path to the property whose values are desired. */ public func valueForKeyPath(keyPath: String) -> AnyObject? { return base.valueForKeyPath(keyPath) } /** Invokes `setValue(_:forKey:)` on each of the collection's objects using the specified `value` and `key`. - warning: This method may only be called during a write transaction. - parameter value: The value to set the property to. - parameter key: The name of the property whose value should be set on each object. */ public func setValue(value: AnyObject?, forKey key: String) { base.setValue(value, forKey: key) } // 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.addNotificationBlock { 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 `stop()` 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 addNotificationBlock(block: (RealmCollectionChange<AnyRealmCollection>) -> Void) -> NotificationToken { return base._addNotificationBlock(block) } /// :nodoc: public func _addNotificationBlock(block: (RealmCollectionChange<AnyRealmCollection>) -> Void) -> NotificationToken { return base._addNotificationBlock(block) } } // MARK: AssistedObjectiveCBridgeable private struct AnyRealmCollectionBridgingMetadata<T: Object> { var baseMetadata: Any? var baseType: _AnyRealmCollectionBase<T>.Type } extension AnyRealmCollection: AssistedObjectiveCBridgeable { static func bridging(from objectiveCValue: Any, with metadata: Any?) -> AnyRealmCollection { guard let metadata = metadata as? AnyRealmCollectionBridgingMetadata<T> else { preconditionFailure() } return AnyRealmCollection(base: metadata.baseType.bridging(from: objectiveCValue, with: metadata.baseMetadata)) } var bridged: (objectiveCValue: Any, metadata: Any?) { return ( objectiveCValue: base.bridged.objectiveCValue, metadata: AnyRealmCollectionBridgingMetadata(baseMetadata: base.bridged.metadata, baseType: base.dynamicType) ) } } #endif
mit
f70c414693fbfc47298b0f5b64b7896d
39.138452
132
0.682944
4.811843
false
false
false
false
AllLuckly/LBSwift_PersonalPageDemo
LBSwift_PersonalPage/LBSwift_PersonalPage.swift
1
7260
// // LBSwift_PersonalPage.swift // LBSwift_PersonalPage // // Created by chenlei_mac on 15/9/7. // Copyright (c) 2015年 Bison. All rights reserved. // import UIKit class LBSwift_PersonalPage: UIViewController,UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate { let LBWIDTH = UIScreen.mainScreen().bounds.size.width let LBHEIGHT = UIScreen.mainScreen().bounds.size.height var BackGroupHeight:CGFloat = 200 var HeadImageHeight:CGFloat = 80 var dataArr = NSMutableArray() var tabView :UITableView? var BGView :UIView? var headImageView :UIImageView? var imageBG:UIImageView? var nameLabel:UILabel? var leftBtn:UIButton? var rightBtn:UIButton? override func viewDidLoad() { super.viewDidLoad() self .createUI() } func createUI(){ self.automaticallyAdjustsScrollViewInsets = false; self.navigationController?.navigationBar.translucent = true self.navigationController?.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: UIBarMetrics.Default) self.navigationController?.navigationBar.shadowImage = UIImage() // var rect = CGRectMake(0, 0, LBWIDTH, LBHEIGHT) tabView = UITableView(frame:UIScreen.mainScreen().bounds,style:.Plain) tabView!.delegate = self tabView!.dataSource = self tabView!.contentInset = UIEdgeInsetsMake(200, 0, 0, 0) self.view.addSubview(tabView!) tabView!.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell") tabView?.tableFooterView = UIView(frame: CGRectZero) imageBG = UIImageView(frame: CGRectMake(0, -200, LBWIDTH, 200)) imageBG?.image = UIImage (named: "BG.jpg") tabView!.addSubview(imageBG!) BGView = UIView(frame: CGRectMake(0, -200, 0,200)) BGView?.backgroundColor = UIColor.clearColor() tabView!.addSubview(BGView!) let X = (LBWIDTH - 80)/2 as CGFloat headImageView = UIImageView(frame: CGRectMake(X, 40, 80, 80)) headImageView?.layer.cornerRadius = 80/2 headImageView?.clipsToBounds = true headImageView?.image = UIImage(named: "myheadimage.jpeg") BGView!.addSubview(headImageView!) nameLabel = UILabel(frame: CGRectMake(X, CGRectGetMaxY(headImageView!.frame)+5, 80, 20)) nameLabel?.text = "BISON" nameLabel?.textAlignment = NSTextAlignment.Center BGView!.addSubview(nameLabel!) leftBtn = UIButton(frame: CGRectMake(0, 0, 45, 20)) leftBtn!.setTitle("lift", forState: .Normal) leftBtn!.setTitleColor(UIColor.whiteColor(), forState: .Normal) leftBtn!.addTarget(self, action: "leftBtnClick", forControlEvents: .TouchUpInside) let leftItem:UIBarButtonItem = UIBarButtonItem(customView: leftBtn!) self.navigationItem.leftBarButtonItem = leftItem rightBtn = UIButton(frame: CGRectMake(0, 0, 45, 20)) rightBtn!.setTitle("right", forState: .Normal) rightBtn!.setTitleColor(UIColor.whiteColor(), forState: .Normal) rightBtn!.addTarget(self, action: "rightBtnClick", forControlEvents: .TouchUpInside) let rightItem:UIBarButtonItem = UIBarButtonItem(customView: rightBtn!) self.navigationItem.rightBarButtonItem = rightItem } func leftBtnClick(){ print("点了我的左边") } func rightBtnClick(){ print("点了我的右边") } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 4; } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) cell.textLabel?.text = "BISON" return cell } func scrollViewDidScroll(scrollView: UIScrollView) { let yOffset:CGFloat = scrollView.contentOffset.y let xOffset:CGFloat = (yOffset + 200)/2 if yOffset < -200{ var rect:CGRect = imageBG!.frame rect.origin.y = yOffset rect.size.height = -yOffset rect.origin.x = xOffset rect.size.width = LBWIDTH + fabs(xOffset)*2 imageBG?.frame = rect var HeadImageRect:CGRect = CGRectMake((LBWIDTH - 80)/2, 40, 80, 80) HeadImageRect.origin.y = headImageView!.frame.origin.y HeadImageRect.size.height = HeadImageHeight + fabs(xOffset)*0.5 HeadImageRect.origin.x = LBWIDTH/2 - HeadImageRect.size.height/2 HeadImageRect.size.width = HeadImageHeight + fabs(xOffset)*0.5 headImageView?.frame = HeadImageRect headImageView?.layer.cornerRadius = HeadImageRect.size.height/2 headImageView?.clipsToBounds = true var NameRect:CGRect = nameLabel!.frame NameRect.origin.y = CGRectGetMaxY(headImageView!.frame)+5 NameRect.size.height = 20 + fabs(xOffset)*0.5 NameRect.origin.x = LBWIDTH/2 - NameRect.size.width/2 NameRect.size.width = HeadImageHeight + fabs(xOffset)*0.5 nameLabel?.font = UIFont.systemFontOfSize(17 + fabs(xOffset)*0.2) nameLabel?.frame = NameRect }else{ var HeadImageRect:CGRect = CGRectMake((LBWIDTH - 80)/2, 40, 80, 80) HeadImageRect.origin.y = 40 HeadImageRect.size.height = HeadImageHeight - fabs(xOffset)*0.5 HeadImageRect.origin.x = LBWIDTH/2 - HeadImageRect.size.height/2 HeadImageRect.size.width = HeadImageHeight - fabs(xOffset)*0.5 headImageView?.frame = HeadImageRect headImageView?.layer.cornerRadius = HeadImageRect.size.height/2 headImageView?.clipsToBounds = true var NameRect:CGRect = CGRectMake((LBWIDTH - 80)/2, 120+5, 80, 20) NameRect.origin.y = HeadImageRect.origin.y + HeadImageRect.size.width + 5 NameRect.size.height = 20 NameRect.origin.x = LBWIDTH/2 - HeadImageRect.size.height/2 NameRect.size.width = HeadImageHeight - fabs(xOffset)*0.5 nameLabel?.font = UIFont.systemFontOfSize(17 - fabs(xOffset)*0.2) nameLabel?.frame = NameRect } } // func imageWiwhColor(color :UIColor)->UIImage{ // // // 描述矩形 // var rect:CGRect = CGRectMake(0.0, 0.0, 1.0, 1.0) // // 开启位图上下文 // UIGraphicsBeginImageContext(rect.size) // // 获取位图上下文 // var context:CGContextRef = UIGraphicsGetCurrentContext() // // 使用color演示填充上下文 // CGContextSetFillColorWithColor(context, color.CGColor) // // 渲染上下文 // CGContextFillEllipseInRect(context, rect) // // 从上下文中获取图片 // var theImage:UIImage = UIGraphicsGetImageFromCurrentImageContext() // // 结束上下文 // UIGraphicsEndImageContext() // // // return theImage // } }
mit
160322cf407de040d74f7089752cd1f7
38.677778
115
0.630776
4.822417
false
false
false
false
rothomp3/weatherDjinni
ios/WeatherDjinni/WeatherDjinni/AppDelegate.swift
1
6156
// // AppDelegate.swift // WeatherDjinni // // Created by Robert Thompson on 6/4/15. // Copyright (c) 2015 WillowTree Apps. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.willowtreeapps.WeatherDjinni" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] as! NSURL }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("WeatherDjinni", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("WeatherDjinni.sqlite") var error: NSError? = nil var failureReason = "There was an error creating or loading the application's saved data." if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil { coordinator = nil // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext? = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator if coordinator == nil { return nil } var managedObjectContext = NSManagedObjectContext() managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if let moc = self.managedObjectContext { var error: NSError? = nil if moc.hasChanges && !moc.save(&error) { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } } } }
mit
aa92f75182f7eee71fcfd48f581b895c
54.459459
290
0.716862
5.710575
false
false
false
false
mihaicris/digi-cloud
Digi Cloud/Models/Mount.swift
1
2700
// // Mount.swift // Digi Cloud // // Created by Mihai Cristescu on 19/09/16. // Copyright © 2016 Mihai Cristescu. All rights reserved. // import Foundation struct Mount { // MARK: - Properties let identifier: String let name: String let type: String let origin: String let root: RootMount? let online: Bool let owner: User var users: [User] let isShared: Bool let permissions: Permissions let spaceTotal: Int? let spaceUsed: Int? let isPrimary: Bool let canWrite: Bool let canUpload: Bool let overQuota: Bool let almostOverQuota: Bool let userAdded: TimeInterval } extension Mount { init?(object: Any?) { guard let jsonDictionary = object as? [String: Any], let identifier = jsonDictionary["id"] as? String, let name = jsonDictionary["name"] as? String, let type = jsonDictionary["type"] as? String, let origin = jsonDictionary["origin"] as? String, let online = jsonDictionary["online"] as? Bool, let usersJSON = jsonDictionary["users"] as? [Any], let isShared = jsonDictionary["isShared"] as? Bool, let isPrimary = jsonDictionary["isPrimary"] as? Bool, let canWrite = jsonDictionary["canWrite"] as? Bool, let canUpload = jsonDictionary["canUpload"] as? Bool, let overQuota = jsonDictionary["overQuota"] as? Bool, let almostOverQuota = jsonDictionary["almostOverQuota"] as? Bool, let userAdded = jsonDictionary["userAdded"] as? TimeInterval else { return nil } if let owner = User(object: jsonDictionary["owner"]), let permissions = Permissions(object: jsonDictionary["permissions"]) { self.owner = owner self.permissions = permissions } else { return nil } self.identifier = identifier self.name = name self.type = type self.origin = origin self.root = RootMount(object: jsonDictionary["root"]) self.online = online self.users = usersJSON.compactMap { User(object: $0) } self.isShared = isShared self.spaceTotal = jsonDictionary["spaceTotal"] as? Int self.spaceUsed = jsonDictionary["spaceUsed"] as? Int self.isPrimary = isPrimary self.canWrite = canWrite self.canUpload = canUpload self.overQuota = overQuota self.almostOverQuota = almostOverQuota self.userAdded = userAdded } static func == (lhs: Mount, rhs: Mount) -> Bool { return lhs.identifier == rhs.identifier && lhs.name == rhs.name } }
mit
591f7fbd4d70b45faa1918f704613567
31.518072
82
0.611708
4.613675
false
false
false
false
ps2/rileylink_ios
NightscoutUploadKit/Models/ForecastError.swift
1
1271
// // ForecastError.swift // NightscoutUploadKit // // Created by Pete Schwamb on 5/28/18. // Copyright © 2018 Pete Schwamb. All rights reserved. // import Foundation import HealthKit public struct ForecastError { typealias RawValue = [String: Any] let velocity: Double let measurementDuration: TimeInterval public init(velocity: HKQuantity, measurementDuration: TimeInterval) { let glucoseUnit = HKUnit.milligramsPerDeciliter let velocityUnit = glucoseUnit.unitDivided(by: HKUnit.second()) self.velocity = velocity.doubleValue(for: velocityUnit) self.measurementDuration = measurementDuration } public var dictionaryRepresentation: [String: Any] { var rval = [String: Any]() rval["velocity"] = velocity rval["measurementDuration"] = measurementDuration //rval["velocityUnits"] = "mg/dL/s" return rval } init?(rawValue: RawValue) { guard let velocity = rawValue["velocity"] as? Double, let measurementDuration = rawValue["measurementDuration"] as? TimeInterval else { return nil } self.velocity = velocity self.measurementDuration = measurementDuration } }
mit
e70587d9624ba67008eae56a88b79699
26.608696
86
0.651969
5.039683
false
false
false
false
dduan/swift
stdlib/public/core/Unmanaged.swift
1
3735
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// A type for propagating an unmanaged object reference. /// /// When you use this type, you become partially responsible for /// keeping the object alive. public struct Unmanaged<Instance : AnyObject> { internal unowned(unsafe) var _value: Instance @_transparent internal init(_private: Instance) { _value = _private } /// Unsafely turn an opaque C pointer into an unmanaged /// class reference. /// /// This operation does not change reference counts. /// /// let str: CFString = Unmanaged.fromOpaque(ptr).takeUnretainedValue() @_transparent @warn_unused_result public static func fromOpaque(value: OpaquePointer) -> Unmanaged { // Null pointer check is a debug check, because it guards only against one // specific bad pointer value. _debugPrecondition( value != nil, "attempt to create an Unmanaged instance from a null pointer") return Unmanaged(_private: unsafeBitCast(value, to: Instance.self)) } /// Create an unmanaged reference with an unbalanced retain. /// The object will leak if nothing eventually balances the retain. /// /// This is useful when passing an object to an API which Swift /// does not know the ownership rules for, but you know that the /// API expects you to pass the object at +1. @_transparent @warn_unused_result public static func passRetained(value: Instance) -> Unmanaged { return Unmanaged(_private: value).retain() } /// Create an unmanaged reference without performing an unbalanced /// retain. /// /// This is useful when passing a reference to an API which Swift /// does not know the ownership rules for, but you know that the /// API expects you to pass the object at +0. /// /// CFArraySetValueAtIndex(.passUnretained(array), i, /// .passUnretained(object)) @_transparent @warn_unused_result public static func passUnretained(value: Instance) -> Unmanaged { return Unmanaged(_private: value) } /// Get the value of this unmanaged reference as a managed /// reference without consuming an unbalanced retain of it. /// /// This is useful when a function returns an unmanaged reference /// and you know that you're not responsible for releasing the result. @warn_unused_result public func takeUnretainedValue() -> Instance { return _value } /// Get the value of this unmanaged reference as a managed /// reference and consume an unbalanced retain of it. /// /// This is useful when a function returns an unmanaged reference /// and you know that you're responsible for releasing the result. @warn_unused_result public func takeRetainedValue() -> Instance { let result = _value release() return result } /// Perform an unbalanced retain of the object. @_transparent public func retain() -> Unmanaged { Builtin.retain(_value) return self } /// Perform an unbalanced release of the object. @_transparent public func release() { Builtin.release(_value) } #if _runtime(_ObjC) /// Perform an unbalanced autorelease of the object. @_transparent public func autorelease() -> Unmanaged { Builtin.autorelease(_value) return self } #endif }
apache-2.0
67222012243931e31b59cf941b3bc2f7
32.648649
80
0.668273
4.78233
false
false
false
false
ShareKit/ShareKit-Demo-App
ShareKit Swift Demo App (CocoaPods)/ViewController.swift
1
4527
// // ViewController.swift // ShareKit Swift Demo App (Cocoapods) // // Created by Vilém Kurz on 14/12/2017. // Copyright © 2017 Vilém Kurz. All rights reserved. // import UIKit import ShareKit class ViewController: UITableViewController { let cellIdentifier = "Cell" deinit { NotificationCenter.default.removeObserver(self) } override func viewDidLoad() { super.viewDidLoad() setupToolbarButtons() observeShareKitNotifications() //For demonstration purpose. Your app can observe ShareKit's progress notifications. tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellIdentifier) tableView.tableFooterView = UITableViewHeaderFooterView(frame: CGRect.zero) title = "Example" } private func setupToolbarButtons() { let accountsBarButton = UIBarButtonItem(title: "Accounts", style: .plain, target: self, action: #selector(showAccounts)) let uploadsBarButton = UIBarButtonItem(title: "Uploads", style: .plain, target: self, action: #selector(showUploads)) toolbarItems = [accountsBarButton, uploadsBarButton] } private func observeShareKitNotifications() { NotificationCenter.default.addObserver(self, selector: #selector(authDidFinish(notification:)), name: NSNotification.Name.SHKAuthDidFinish, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(sendDidCancel(notification:)), name: NSNotification.Name.SHKSendDidCancel, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(sendDidStart(notification:)), name: NSNotification.Name.SHKSendDidStart, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(sendDidFinish(notification:)), name: NSNotification.Name.SHKSendDidFinish, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(sendDidFail(notification:)), name: NSNotification.Name.SHKSendDidFailWithError, object: nil) } @objc private func showAccounts() { SHKAccountsViewController.open(from: self) } @objc private func showUploads() { SHKUploadsViewController.open(from: self) } //MARK: UITableViewDelegate & UITableViewDataSource override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 4 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) switch indexPath.row { case 0: cell.textLabel?.text = "Sharing a Link" case 1: cell.textLabel?.text = "Sharing an Image" case 2: cell.textLabel?.text = "Sharing Text" case 3: cell.textLabel?.text = "Sharing a File" default: break } return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { var shareController: UIViewController switch indexPath.row { case 0: shareController = ExampleShareLinkViewController(nibName: nil, bundle: nil) case 1: shareController = ExampleShareImageViewController(nibName: nil, bundle: nil) case 2: shareController = ExampleShareTextViewController(nibName: nil, bundle: nil) case 3: shareController = ExampleShareFileViewController(nibName: nil, bundle: nil) default: return } navigationController?.pushViewController(shareController, animated: true) } //MARK: ShareKit notification handling @objc private func authDidFinish(notification: Notification) { if let success = notification.userInfo?["success"] as? Bool { let logString = success ? "authorization did finish successfully" : "authorization failed" NSLog(logString) } } @objc private func sendDidCancel(notification: Notification) { NSLog("sendDidCancel") } @objc private func sendDidStart(notification: Notification) { NSLog("sendDidStart") } @objc private func sendDidFinish(notification: Notification) { NSLog("sendDidFinish") } @objc private func sendDidFail(notification: Notification) { NSLog("sendDidFail") } }
mit
ba77cc568498a11c1e01a3979618fc36
37.666667
165
0.688992
5.066069
false
false
false
false
longitachi/ZLPhotoBrowser
Sources/Camera/ZLCustomCamera.swift
1
43245
// // ZLCustomCamera.swift // ZLPhotoBrowser // // Created by long on 2020/8/11. // // Copyright (c) 2020 Long Zhang <[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 import AVFoundation import CoreMotion open class ZLCustomCamera: UIViewController, CAAnimationDelegate { enum Layout { static let bottomViewH: CGFloat = 150 static let largeCircleRadius: CGFloat = 85 static let smallCircleRadius: CGFloat = 62 static let largeCircleRecordScale: CGFloat = 1.2 static let smallCircleRecordScale: CGFloat = 0.7 } @objc public var takeDoneBlock: ((UIImage?, URL?) -> Void)? @objc public var cancelBlock: (() -> Void)? public lazy var tipsLabel: UILabel = { let label = UILabel() label.font = .zl.font(ofSize: 14) label.textColor = .white label.textAlignment = .center label.numberOfLines = 2 label.lineBreakMode = .byWordWrapping label.alpha = 0 if ZLPhotoConfiguration.default().allowTakePhoto, ZLPhotoConfiguration.default().allowRecordVideo { label.text = localLanguageTextValue(.customCameraTips) } else if ZLPhotoConfiguration.default().allowTakePhoto { label.text = localLanguageTextValue(.customCameraTakePhotoTips) } else if ZLPhotoConfiguration.default().allowRecordVideo { label.text = localLanguageTextValue(.customCameraRecordVideoTips) } return label }() public lazy var bottomView = UIView() public lazy var largeCircleView: UIVisualEffectView = { let view: UIVisualEffectView if #available(iOS 13.0, *) { view = UIVisualEffectView(effect: UIBlurEffect(style: .systemThinMaterialLight)) } else { view = UIVisualEffectView(effect: UIBlurEffect(style: .light)) } view.layer.masksToBounds = true view.layer.cornerRadius = ZLCustomCamera.Layout.largeCircleRadius / 2 return view }() public lazy var smallCircleView: UIView = { let view = UIView() view.layer.masksToBounds = true view.layer.cornerRadius = ZLCustomCamera.Layout.smallCircleRadius / 2 view.isUserInteractionEnabled = false view.backgroundColor = .white return view }() public lazy var animateLayer: CAShapeLayer = { let animateLayerRadius = ZLCustomCamera.Layout.largeCircleRadius let path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: animateLayerRadius, height: animateLayerRadius), cornerRadius: animateLayerRadius / 2) let layer = CAShapeLayer() layer.path = path.cgPath layer.strokeColor = UIColor.zl.cameraRecodeProgressColor.cgColor layer.fillColor = UIColor.clear.cgColor layer.lineWidth = 8 return layer }() public lazy var retakeBtn: ZLEnlargeButton = { let btn = ZLEnlargeButton(type: .custom) btn.setImage(.zl.getImage("zl_retake"), for: .normal) btn.addTarget(self, action: #selector(retakeBtnClick), for: .touchUpInside) btn.isHidden = true btn.adjustsImageWhenHighlighted = false btn.enlargeInset = 30 return btn }() public lazy var doneBtn: UIButton = { let btn = UIButton(type: .custom) btn.titleLabel?.font = ZLLayout.bottomToolTitleFont btn.setTitle(localLanguageTextValue(.done), for: .normal) btn.setTitleColor(.zl.bottomToolViewDoneBtnNormalTitleColor, for: .normal) btn.backgroundColor = .zl.bottomToolViewBtnNormalBgColor btn.addTarget(self, action: #selector(doneBtnClick), for: .touchUpInside) btn.isHidden = true btn.layer.masksToBounds = true btn.layer.cornerRadius = ZLLayout.bottomToolBtnCornerRadius return btn }() public lazy var dismissBtn: ZLEnlargeButton = { let btn = ZLEnlargeButton(type: .custom) btn.setImage(.zl.getImage("zl_arrow_down"), for: .normal) btn.addTarget(self, action: #selector(dismissBtnClick), for: .touchUpInside) btn.adjustsImageWhenHighlighted = false btn.enlargeInset = 30 return btn }() public lazy var switchCameraBtn: ZLEnlargeButton = { let cameraCount = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInWideAngleCamera], mediaType: .video, position: .unspecified).devices.count let btn = ZLEnlargeButton(type: .custom) btn.setImage(.zl.getImage("zl_toggle_camera"), for: .normal) btn.addTarget(self, action: #selector(switchCameraBtnClick), for: .touchUpInside) btn.adjustsImageWhenHighlighted = false btn.enlargeInset = 30 btn.isHidden = cameraCount <= 1 return btn }() public lazy var focusCursorView: UIImageView = { let view = UIImageView(image: .zl.getImage("zl_focus")) view.contentMode = .scaleAspectFit view.clipsToBounds = true view.frame = CGRect(x: 0, y: 0, width: 70, height: 70) view.alpha = 0 return view }() public lazy var takedImageView: UIImageView = { let view = UIImageView() view.backgroundColor = .black view.isHidden = true view.contentMode = .scaleAspectFit return view }() private var hideTipsTimer: Timer? private var takedImage: UIImage? private var videoUrl: URL? private var motionManager: CMMotionManager? private var orientation: AVCaptureVideoOrientation = .portrait private let sessionQueue = DispatchQueue(label: "com.zl.camera.sessionQueue") private let session = AVCaptureSession() private var videoInput: AVCaptureDeviceInput? private var imageOutput: AVCapturePhotoOutput! private var movieFileOutput: AVCaptureMovieFileOutput! private var previewLayer: AVCaptureVideoPreviewLayer? private var recordVideoPlayerLayer: AVPlayerLayer? private var cameraConfigureFinish = false private var layoutOK = false private var dragStart = false private var viewDidAppearCount = 0 private var restartRecordAfterSwitchCamera = false private var cacheVideoOrientation: AVCaptureVideoOrientation = .portrait private var recordUrls: [URL] = [] private var microPhontIsAvailable = true private lazy var focusCursorTapGes: UITapGestureRecognizer = { let tap = UITapGestureRecognizer() tap.addTarget(self, action: #selector(adjustFocusPoint)) tap.delegate = self return tap }() private var cameraFocusPanGes: UIPanGestureRecognizer? private var recordLongGes: UILongPressGestureRecognizer? /// 是否正在调整焦距 private var isAdjustingFocusPoint = false /// 是否正在拍照 private var isTakingPicture = false // 仅支持竖屏 override public var supportedInterfaceOrientations: UIInterfaceOrientationMask { return .portrait } override public var prefersStatusBarHidden: Bool { return true } deinit { zl_debugPrint("ZLCustomCamera deinit") cleanTimer() try? AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation) } @objc public init() { super.init(nibName: nil, bundle: nil) modalPresentationStyle = .fullScreen } @available(*, unavailable) public required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override open func viewDidLoad() { super.viewDidLoad() setupUI() if !UIImagePickerController.isSourceTypeAvailable(.camera) { return } AVCaptureDevice.requestAccess(for: .video) { videoGranted in guard videoGranted else { ZLMainAsync(after: 1) { self.showAlertAndDismissAfterDoneAction(message: String(format: localLanguageTextValue(.noCameraAuthority), getAppName()), type: .camera) } return } guard ZLPhotoConfiguration.default().allowRecordVideo else { self.addNotification() return } AVCaptureDevice.requestAccess(for: .audio) { audioGranted in self.addNotification() if !audioGranted { ZLMainAsync(after: 1) { self.showNoMicrophoneAuthorityAlert() } } } } if ZLPhotoConfiguration.default().allowRecordVideo { do { try AVAudioSession.sharedInstance().setCategory(.playAndRecord, mode: .videoRecording, options: .mixWithOthers) try AVAudioSession.sharedInstance().setActive(true, options: .notifyOthersOnDeactivation) } catch { let err = error as NSError if err.code == AVAudioSession.ErrorCode.insufficientPriority.rawValue || err.code == AVAudioSession.ErrorCode.isBusy.rawValue { microPhontIsAvailable = false } } } setupCamera() sessionQueue.async { self.session.startRunning() } } override open func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) observerDeviceMotion() } override open func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if !UIImagePickerController.isSourceTypeAvailable(.camera) { showAlertAndDismissAfterDoneAction(message: localLanguageTextValue(.cameraUnavailable), type: .camera) } else if !ZLPhotoConfiguration.default().allowTakePhoto, !ZLPhotoConfiguration.default().allowRecordVideo { #if DEBUG fatalError("Error configuration of camera") #else showAlertAndDismissAfterDoneAction(message: "Error configuration of camera", type: nil) #endif } else if cameraConfigureFinish, viewDidAppearCount == 0 { showTipsLabel(animate: true) let animation = getFadeAnimation(fromValue: 0, toValue: 1, duration: 0.15) previewLayer?.add(animation, forKey: nil) setFocusCusor(point: view.center) } viewDidAppearCount += 1 } override open func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) motionManager?.stopDeviceMotionUpdates() motionManager = nil } override open func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) if session.isRunning { session.stopRunning() } } override open func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() guard !layoutOK else { return } layoutOK = true var insets = UIEdgeInsets(top: 20, left: 0, bottom: 0, right: 0) if #available(iOS 11.0, *) { insets = self.view.safeAreaInsets } let previewLayerY: CGFloat = deviceSafeAreaInsets().top > 0 ? 20 : 0 previewLayer?.frame = CGRect(x: 0, y: previewLayerY, width: view.bounds.width, height: view.bounds.height) recordVideoPlayerLayer?.frame = view.bounds takedImageView.frame = view.bounds bottomView.frame = CGRect(x: 0, y: view.bounds.height - insets.bottom - ZLCustomCamera.Layout.bottomViewH - 50, width: view.bounds.width, height: ZLCustomCamera.Layout.bottomViewH) let largeCircleH = ZLCustomCamera.Layout.largeCircleRadius largeCircleView.frame = CGRect(x: (view.bounds.width - largeCircleH) / 2, y: (ZLCustomCamera.Layout.bottomViewH - largeCircleH) / 2, width: largeCircleH, height: largeCircleH) let smallCircleH = ZLCustomCamera.Layout.smallCircleRadius smallCircleView.frame = CGRect(x: (view.bounds.width - smallCircleH) / 2, y: (ZLCustomCamera.Layout.bottomViewH - smallCircleH) / 2, width: smallCircleH, height: smallCircleH) dismissBtn.frame = CGRect(x: 60, y: (ZLCustomCamera.Layout.bottomViewH - 25) / 2, width: 25, height: 25) let tipsTextHeight = (tipsLabel.text ?? " ").zl .boundingRect( font: .zl.font(ofSize: 14), limitSize: CGSize(width: view.bounds.width - 20, height: .greatestFiniteMagnitude) ) .height tipsLabel.frame = CGRect(x: 10, y: bottomView.frame.minY - tipsTextHeight, width: view.bounds.width - 20, height: tipsTextHeight) retakeBtn.frame = CGRect(x: 30, y: insets.top + 10, width: 28, height: 28) switchCameraBtn.frame = CGRect(x: view.bounds.width - 30 - 28, y: insets.top + 10, width: 28, height: 28) let doneBtnW = localLanguageTextValue(.done).zl .boundingRect( font: ZLLayout.bottomToolTitleFont, limitSize: CGSize(width: CGFloat.greatestFiniteMagnitude, height: 40) ) .width + 20 let doneBtnY = view.bounds.height - 57 - insets.bottom doneBtn.frame = CGRect(x: view.bounds.width - doneBtnW - 20, y: doneBtnY, width: doneBtnW, height: ZLLayout.bottomToolBtnH) } private func setupUI() { view.backgroundColor = .black view.addSubview(takedImageView) view.addSubview(focusCursorView) view.addSubview(tipsLabel) view.addSubview(bottomView) bottomView.addSubview(dismissBtn) bottomView.addSubview(largeCircleView) bottomView.addSubview(smallCircleView) var takePictureTap: UITapGestureRecognizer? if ZLPhotoConfiguration.default().allowTakePhoto { takePictureTap = UITapGestureRecognizer(target: self, action: #selector(takePicture)) largeCircleView.addGestureRecognizer(takePictureTap!) } if ZLPhotoConfiguration.default().allowRecordVideo { let longGes = UILongPressGestureRecognizer(target: self, action: #selector(longPressAction(_:))) longGes.minimumPressDuration = 0.3 longGes.delegate = self largeCircleView.addGestureRecognizer(longGes) takePictureTap?.require(toFail: longGes) recordLongGes = longGes let panGes = UIPanGestureRecognizer(target: self, action: #selector(adjustCameraFocus(_:))) panGes.delegate = self panGes.maximumNumberOfTouches = 1 largeCircleView.addGestureRecognizer(panGes) cameraFocusPanGes = panGes recordVideoPlayerLayer = AVPlayerLayer() recordVideoPlayerLayer?.backgroundColor = UIColor.black.cgColor recordVideoPlayerLayer?.videoGravity = .resizeAspect recordVideoPlayerLayer?.isHidden = true view.layer.insertSublayer(recordVideoPlayerLayer!, at: 0) NotificationCenter.default.addObserver(self, selector: #selector(recordVideoPlayFinished), name: .AVPlayerItemDidPlayToEndTime, object: nil) } view.addSubview(retakeBtn) view.addSubview(switchCameraBtn) view.addSubview(doneBtn) view.addGestureRecognizer(focusCursorTapGes) let pinchGes = UIPinchGestureRecognizer(target: self, action: #selector(pinchToAdjustCameraFocus(_:))) view.addGestureRecognizer(pinchGes) } private func observerDeviceMotion() { if !Thread.isMainThread { ZLMainAsync { self.observerDeviceMotion() } return } motionManager = CMMotionManager() motionManager?.deviceMotionUpdateInterval = 0.5 if motionManager?.isDeviceMotionAvailable == true { motionManager?.startDeviceMotionUpdates(to: .main, withHandler: { motion, _ in if let motion = motion { self.handleDeviceMotion(motion) } }) } else { motionManager = nil } } func handleDeviceMotion(_ motion: CMDeviceMotion) { let x = motion.gravity.x let y = motion.gravity.y if abs(y) >= abs(x) || abs(x) < 0.45 { if y >= 0.45 { orientation = .portraitUpsideDown } else { orientation = .portrait } } else { if x >= 0 { orientation = .landscapeLeft } else { orientation = .landscapeRight } } } private func setupCamera() { guard let backCamera = getCamera(position: .back) else { return } guard let input = try? AVCaptureDeviceInput(device: backCamera) else { return } session.beginConfiguration() // 相机画面输入流 videoInput = input // 照片输出流 imageOutput = AVCapturePhotoOutput() let preset = ZLPhotoConfiguration.default().cameraConfiguration.sessionPreset.avSessionPreset if session.canSetSessionPreset(preset) { session.sessionPreset = preset } else { session.sessionPreset = .hd1280x720 } movieFileOutput = AVCaptureMovieFileOutput() // 解决视频录制超过10s没有声音的bug movieFileOutput.movieFragmentInterval = .invalid // 添加视频输入 if let videoInput = videoInput, session.canAddInput(videoInput) { session.addInput(videoInput) } // 添加音频输入 addAudioInput() // 将输出流添加到session if session.canAddOutput(imageOutput) { session.addOutput(imageOutput) } if session.canAddOutput(movieFileOutput) { session.addOutput(movieFileOutput) } session.commitConfiguration() // 预览layer previewLayer = AVCaptureVideoPreviewLayer(session: session) previewLayer?.videoGravity = .resizeAspect previewLayer?.opacity = 0 view.layer.masksToBounds = true view.layer.insertSublayer(previewLayer!, at: 0) cameraConfigureFinish = true } private func getCamera(position: AVCaptureDevice.Position) -> AVCaptureDevice? { let devices = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInWideAngleCamera], mediaType: .video, position: position).devices for device in devices { if device.position == position { return device } } return nil } private func getMicrophone() -> AVCaptureDevice? { return AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInMicrophone], mediaType: .audio, position: .unspecified).devices.first } private func addAudioInput() { guard ZLPhotoConfiguration.default().allowRecordVideo else { return } // 音频输入流 var audioInput: AVCaptureDeviceInput? if let microphone = getMicrophone() { audioInput = try? AVCaptureDeviceInput(device: microphone) } guard microPhontIsAvailable, let ai = audioInput else { return } removeAudioInput() if session.isRunning { session.beginConfiguration() } if session.canAddInput(ai) { session.addInput(ai) } if session.isRunning { session.commitConfiguration() } } private func removeAudioInput() { var audioInput: AVCaptureInput? for input in session.inputs { if (input as? AVCaptureDeviceInput)?.device.deviceType == .builtInMicrophone { audioInput = input } } guard let audioInput = audioInput else { return } if session.isRunning { session.beginConfiguration() } session.removeInput(audioInput) if session.isRunning { session.commitConfiguration() } } private func addNotification() { NotificationCenter.default.addObserver(self, selector: #selector(appWillResignActive), name: UIApplication.willResignActiveNotification, object: nil) if ZLPhotoConfiguration.default().allowRecordVideo { NotificationCenter.default.addObserver(self, selector: #selector(appDidBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(handleAudioSessionInterruption), name: AVAudioSession.interruptionNotification, object: nil) } } private func showNoMicrophoneAuthorityAlert() { let continueAction = ZLCustomAlertAction(title: localLanguageTextValue(.keepRecording), style: .default, handler: nil) let gotoSettingsAction = ZLCustomAlertAction(title: localLanguageTextValue(.gotoSettings), style: .tint) { _ in guard let url = URL(string: UIApplication.openSettingsURLString) else { return } if UIApplication.shared.canOpenURL(url) { UIApplication.shared.open(url, options: [:], completionHandler: nil) } } showAlertController(title: nil, message: String(format: localLanguageTextValue(.noMicrophoneAuthority), getAppName()), style: .alert, actions: [continueAction, gotoSettingsAction], sender: self) } private func showAlertAndDismissAfterDoneAction(message: String, type: ZLNoAuthorityType?) { let action = ZLCustomAlertAction(title: localLanguageTextValue(.done), style: .default) { [weak self] _ in self?.dismiss(animated: true) { if let type = type { ZLPhotoConfiguration.default().noAuthorityCallback?(type) } } } showAlertController(title: nil, message: message, style: .alert, actions: [action], sender: self) } private func showTipsLabel(animate: Bool) { tipsLabel.layer.removeAllAnimations() if animate { UIView.animate(withDuration: 0.25) { self.tipsLabel.alpha = 1 } } else { tipsLabel.alpha = 1 } startHideTipsLabelTimer() } private func hideTipsLabel(animate: Bool) { tipsLabel.layer.removeAllAnimations() if animate { UIView.animate(withDuration: 0.25) { self.tipsLabel.alpha = 0 } } else { tipsLabel.alpha = 0 } } @objc private func hideTipsLabel_timerFunc() { cleanTimer() hideTipsLabel(animate: true) } private func startHideTipsLabelTimer() { cleanTimer() hideTipsTimer = Timer.scheduledTimer(timeInterval: 3, target: ZLWeakProxy(target: self), selector: #selector(hideTipsLabel_timerFunc), userInfo: nil, repeats: false) RunLoop.current.add(hideTipsTimer!, forMode: .common) } private func cleanTimer() { hideTipsTimer?.invalidate() hideTipsTimer = nil } @objc private func appWillResignActive() { if session.isRunning { dismiss(animated: true, completion: nil) } if videoUrl != nil, let player = recordVideoPlayerLayer?.player { player.pause() } } @objc private func appDidBecomeActive() { if videoUrl != nil, let player = recordVideoPlayerLayer?.player { player.play() } } @objc private func handleAudioSessionInterruption(_ notify: Notification) { guard recordVideoPlayerLayer?.isHidden == false, let player = recordVideoPlayerLayer?.player else { return } guard player.rate == 0 else { return } let type = notify.userInfo?[AVAudioSessionInterruptionTypeKey] as? UInt let option = notify.userInfo?[AVAudioSessionInterruptionOptionKey] as? UInt if type == AVAudioSession.InterruptionType.ended.rawValue, option == AVAudioSession.InterruptionOptions.shouldResume.rawValue { player.play() } } @objc private func dismissBtnClick() { dismiss(animated: true) { self.cancelBlock?() } } @objc private func retakeBtnClick() { session.startRunning() resetSubViewStatus() takedImage = nil stopRecordAnimation() if let videoUrl = videoUrl { recordVideoPlayerLayer?.player?.pause() recordVideoPlayerLayer?.player = nil recordVideoPlayerLayer?.isHidden = true self.videoUrl = nil try? FileManager.default.removeItem(at: videoUrl) } } @objc private func switchCameraBtnClick() { do { guard !restartRecordAfterSwitchCamera else { return } guard let currInput = videoInput else { return } var newVideoInput: AVCaptureDeviceInput? if currInput.device.position == .back, let front = getCamera(position: .front) { newVideoInput = try AVCaptureDeviceInput(device: front) } else if currInput.device.position == .front, let back = getCamera(position: .back) { newVideoInput = try AVCaptureDeviceInput(device: back) } else { return } if let newVideoInput = newVideoInput { session.beginConfiguration() session.removeInput(currInput) if session.canAddInput(newVideoInput) { session.addInput(newVideoInput) videoInput = newVideoInput } else { session.addInput(currInput) } session.commitConfiguration() if movieFileOutput.isRecording { let pauseTime = animateLayer.convertTime(CACurrentMediaTime(), from: nil) animateLayer.speed = 0 animateLayer.timeOffset = pauseTime restartRecordAfterSwitchCamera = true } } } catch { zl_debugPrint("切换摄像头失败 \(error.localizedDescription)") } } @objc private func editImage() { guard ZLPhotoConfiguration.default().allowEditImage, let image = takedImage else { return } ZLEditImageViewController.showEditImageVC(parentVC: self, image: image) { [weak self] in self?.retakeBtnClick() } completion: { [weak self] editImage, _ in self?.takedImage = editImage self?.takedImageView.image = editImage self?.doneBtnClick() } } @objc private func doneBtnClick() { recordVideoPlayerLayer?.player?.pause() // 置为nil会导致卡顿,先注释,不影响内存释放 // self.recordVideoPlayerLayer?.player = nil dismiss(animated: true) { self.takeDoneBlock?(self.takedImage, self.videoUrl) } } // 点击拍照 @objc private func takePicture() { guard ZLPhotoManager.hasCameraAuthority(), !isTakingPicture else { return } isTakingPicture = true let connection = imageOutput.connection(with: .video) connection?.videoOrientation = orientation if videoInput?.device.position == .front, connection?.isVideoMirroringSupported == true { connection?.isVideoMirrored = true } let setting = AVCapturePhotoSettings(format: [AVVideoCodecKey: AVVideoCodecJPEG]) if videoInput?.device.hasFlash == true { setting.flashMode = ZLPhotoConfiguration.default().cameraConfiguration.flashMode.avFlashMode } imageOutput.capturePhoto(with: setting, delegate: self) } // 长按录像 @objc private func longPressAction(_ longGes: UILongPressGestureRecognizer) { if longGes.state == .began { guard ZLPhotoManager.hasCameraAuthority(), ZLPhotoManager.hasMicrophoneAuthority() else { return } startRecord() } else if longGes.state == .cancelled || longGes.state == .ended { finishRecord() } } // 调整焦点 @objc private func adjustFocusPoint(_ tap: UITapGestureRecognizer) { guard session.isRunning, !isAdjustingFocusPoint else { return } let point = tap.location(in: view) if point.y > bottomView.frame.minY - 30 { return } setFocusCusor(point: point) } private func setFocusCusor(point: CGPoint) { isAdjustingFocusPoint = true focusCursorView.center = point focusCursorView.layer.removeAllAnimations() focusCursorView.alpha = 1 focusCursorView.layer.transform = CATransform3DMakeScale(1.2, 1.2, 1) UIView.animate(withDuration: 0.5, animations: { self.focusCursorView.layer.transform = CATransform3DIdentity }) { _ in self.isAdjustingFocusPoint = false self.focusCursorView.alpha = 0 } // ui坐标转换为摄像头坐标 let cameraPoint = previewLayer?.captureDevicePointConverted(fromLayerPoint: point) ?? view.center focusCamera( mode: ZLPhotoConfiguration.default().cameraConfiguration.focusMode.avFocusMode, exposureMode: ZLPhotoConfiguration.default().cameraConfiguration.exposureMode.avFocusMode, point: cameraPoint ) } // 调整焦距 @objc private func adjustCameraFocus(_ pan: UIPanGestureRecognizer) { let convertRect = bottomView.convert(largeCircleView.frame, to: view) let point = pan.location(in: view) if pan.state == .began { dragStart = true startRecord() } else if pan.state == .changed { guard dragStart else { return } let maxZoomFactor = getMaxZoomFactor() var zoomFactor = (convertRect.midY - point.y) / convertRect.midY * maxZoomFactor zoomFactor = max(1, min(zoomFactor, maxZoomFactor)) setVideoZoomFactor(zoomFactor) } else if pan.state == .cancelled || pan.state == .ended { guard dragStart else { return } dragStart = false finishRecord() } } @objc private func pinchToAdjustCameraFocus(_ pinch: UIPinchGestureRecognizer) { guard let device = videoInput?.device else { return } var zoomFactor = device.videoZoomFactor * pinch.scale zoomFactor = max(1, min(zoomFactor, getMaxZoomFactor())) setVideoZoomFactor(zoomFactor) pinch.scale = 1 } private func getMaxZoomFactor() -> CGFloat { guard let device = videoInput?.device else { return 1 } if #available(iOS 11.0, *) { return min(15, device.maxAvailableVideoZoomFactor) } else { return min(15, device.activeFormat.videoMaxZoomFactor) } } private func setVideoZoomFactor(_ zoomFactor: CGFloat) { guard let device = videoInput?.device else { return } do { try device.lockForConfiguration() device.videoZoomFactor = zoomFactor device.unlockForConfiguration() } catch { zl_debugPrint("调整焦距失败 \(error.localizedDescription)") } } private func focusCamera(mode: AVCaptureDevice.FocusMode, exposureMode: AVCaptureDevice.ExposureMode, point: CGPoint) { do { guard let device = videoInput?.device else { return } try device.lockForConfiguration() if device.isFocusModeSupported(mode) { device.focusMode = mode } if device.isFocusPointOfInterestSupported { device.focusPointOfInterest = point } if device.isExposureModeSupported(exposureMode) { device.exposureMode = exposureMode } if device.isExposurePointOfInterestSupported { device.exposurePointOfInterest = point } device.unlockForConfiguration() } catch { zl_debugPrint("相机聚焦设置失败 \(error.localizedDescription)") } } private func startRecord() { guard !movieFileOutput.isRecording else { return } dismissBtn.isHidden = true let connection = movieFileOutput.connection(with: .video) connection?.videoScaleAndCropFactor = 1 if !restartRecordAfterSwitchCamera { connection?.videoOrientation = orientation cacheVideoOrientation = orientation } else { connection?.videoOrientation = cacheVideoOrientation } // 解决前置摄像头录制视频时候左右颠倒的问题 if videoInput?.device.position == .front, connection?.isVideoMirroringSupported == true { // 镜像设置 connection?.isVideoMirrored = true } let url = URL(fileURLWithPath: ZLVideoManager.getVideoExportFilePath()) movieFileOutput.startRecording(to: url, recordingDelegate: self) } private func finishRecord() { guard movieFileOutput.isRecording else { return } try? AVAudioSession.sharedInstance().setCategory(.playback) movieFileOutput.stopRecording() stopRecordAnimation() } private func startRecordAnimation() { UIView.animate(withDuration: 0.1, animations: { self.largeCircleView.layer.transform = CATransform3DScale(CATransform3DIdentity, ZLCustomCamera.Layout.largeCircleRecordScale, ZLCustomCamera.Layout.largeCircleRecordScale, 1) self.smallCircleView.layer.transform = CATransform3DScale(CATransform3DIdentity, ZLCustomCamera.Layout.smallCircleRecordScale, ZLCustomCamera.Layout.smallCircleRecordScale, 1) }) { _ in self.largeCircleView.layer.addSublayer(self.animateLayer) let animation = CABasicAnimation(keyPath: "strokeEnd") animation.fromValue = 0 animation.toValue = 1 animation.duration = Double(ZLPhotoConfiguration.default().maxRecordDuration) animation.delegate = self self.animateLayer.add(animation, forKey: nil) } } private func stopRecordAnimation() { animateLayer.removeFromSuperlayer() animateLayer.removeAllAnimations() largeCircleView.transform = .identity smallCircleView.transform = .identity } public func animationDidStop(_ anim: CAAnimation, finished flag: Bool) { finishRecord() } private func resetSubViewStatus() { if session.isRunning { showTipsLabel(animate: true) bottomView.isHidden = false dismissBtn.isHidden = false switchCameraBtn.isHidden = false retakeBtn.isHidden = true doneBtn.isHidden = true takedImageView.isHidden = true takedImage = nil } else { hideTipsLabel(animate: false) bottomView.isHidden = true dismissBtn.isHidden = true switchCameraBtn.isHidden = true retakeBtn.isHidden = false doneBtn.isHidden = false } } private func playRecordVideo(fileUrl: URL) { recordVideoPlayerLayer?.isHidden = false let player = AVPlayer(url: fileUrl) player.automaticallyWaitsToMinimizeStalling = false recordVideoPlayerLayer?.player = player player.play() } @objc private func recordVideoPlayFinished() { recordVideoPlayerLayer?.player?.seek(to: .zero) recordVideoPlayerLayer?.player?.play() } } extension ZLCustomCamera: AVCapturePhotoCaptureDelegate { public func photoOutput(_ output: AVCapturePhotoOutput, willCapturePhotoFor resolvedSettings: AVCaptureResolvedPhotoSettings) { ZLMainAsync { let animation = getFadeAnimation(fromValue: 0, toValue: 1, duration: 0.25) self.previewLayer?.add(animation, forKey: nil) } } public func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photoSampleBuffer: CMSampleBuffer?, previewPhoto previewPhotoSampleBuffer: CMSampleBuffer?, resolvedSettings: AVCaptureResolvedPhotoSettings, bracketSettings: AVCaptureBracketedStillImageSettings?, error: Error?) { ZLMainAsync { defer { self.isTakingPicture = false } if photoSampleBuffer == nil || error != nil { zl_debugPrint("拍照失败 \(error?.localizedDescription ?? "")") return } if let data = AVCapturePhotoOutput.jpegPhotoDataRepresentation(forJPEGSampleBuffer: photoSampleBuffer!, previewPhotoSampleBuffer: previewPhotoSampleBuffer) { self.session.stopRunning() self.takedImage = UIImage(data: data)?.zl.fixOrientation() self.takedImageView.image = self.takedImage self.takedImageView.isHidden = false self.resetSubViewStatus() self.editImage() } else { zl_debugPrint("拍照失败,data为空") } } } } extension ZLCustomCamera: AVCaptureFileOutputRecordingDelegate { public func fileOutput(_ output: AVCaptureFileOutput, didStartRecordingTo fileURL: URL, from connections: [AVCaptureConnection]) { if restartRecordAfterSwitchCamera { restartRecordAfterSwitchCamera = false // 稍微加一个延时,否则切换摄像头后拍摄时间会略小于设置的最大值 ZLMainAsync(after: 0.1) { let pauseTime = self.animateLayer.timeOffset self.animateLayer.speed = 1 self.animateLayer.timeOffset = 0 self.animateLayer.beginTime = 0 let timeSincePause = self.animateLayer.convertTime(CACurrentMediaTime(), from: nil) - pauseTime self.animateLayer.beginTime = timeSincePause } } else { ZLMainAsync { self.startRecordAnimation() } } } public func fileOutput(_ output: AVCaptureFileOutput, didFinishRecordingTo outputFileURL: URL, from connections: [AVCaptureConnection], error: Error?) { ZLMainAsync { if self.restartRecordAfterSwitchCamera { self.recordUrls.append(outputFileURL) self.startRecord() return } self.stopRecordAnimation() self.recordUrls.append(outputFileURL) var duration: Double = 0 if self.recordUrls.count == 1 { duration = output.recordedDuration.seconds } else { for url in self.recordUrls { let temp = AVAsset(url: url) duration += temp.duration.seconds } } // 重置焦距 self.setVideoZoomFactor(1) if duration < Double(ZLPhotoConfiguration.default().minRecordDuration) { showAlertView(String(format: localLanguageTextValue(.minRecordTimeTips), ZLPhotoConfiguration.default().minRecordDuration), self) self.resetSubViewStatus() self.recordUrls.forEach { try? FileManager.default.removeItem(at: $0) } self.recordUrls.removeAll() return } // 拼接视频 self.session.stopRunning() self.resetSubViewStatus() if self.recordUrls.count > 1 { ZLVideoManager.mergeVideos(fileUrls: self.recordUrls) { [weak self] url, error in if let url = url, error == nil { self?.videoUrl = url self?.playRecordVideo(fileUrl: url) } else if let error = error { self?.videoUrl = nil showAlertView(error.localizedDescription, self) } self?.recordUrls.forEach { try? FileManager.default.removeItem(at: $0) } self?.recordUrls.removeAll() } } else { self.videoUrl = outputFileURL self.playRecordVideo(fileUrl: outputFileURL) self.recordUrls.removeAll() } } } } extension ZLCustomCamera: UIGestureRecognizerDelegate { public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { let gesTuples: [(UIGestureRecognizer?, UIGestureRecognizer?)] = [(recordLongGes, cameraFocusPanGes), (recordLongGes, focusCursorTapGes), (cameraFocusPanGes, focusCursorTapGes)] let result = gesTuples.map { ges1, ges2 in (ges1 == gestureRecognizer && ges2 == otherGestureRecognizer) || (ges2 == otherGestureRecognizer && ges1 == gestureRecognizer) }.filter { $0 == true } return result.count > 0 } }
mit
abec6dd478e6047d8bc6760d650eda59
37.513489
299
0.615009
5.4787
false
false
false
false
adamdahan/GraphKit
Source/Bond.swift
1
4862
// // Copyright (C) 2015 GraphKit, Inc. <http://graphkit.io> and other GraphKit contributors. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as published // by the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program located at the root of the software package // in a file called LICENSE. If not, see <http://www.gnu.org/licenses/>. // import Foundation @objc(Bond) public class Bond : NSObject, Comparable { internal let node: ManagedBond /** :name: init :description: Initializes Bond with a given ManagedBond. */ internal init(bond: ManagedBond) { node = bond } /** :name: init :description: An initializer for the wrapped Model Object with a given type. */ public convenience init(type: String) { self.init(bond: ManagedBond(type: type)) } /** :name: nodeClass :description: Retrieves the nodeClass for the Model Object that is wrapped internally. */ public var nodeClass: String { return node.nodeClass } /** :name: type :description: Retrieves the type for the Model Object that is wrapped internally. */ public var type: String { return node.type } /** :name: id :description: Retrieves the ID for the Model Object that is wrapped internally. */ public var id: String { let nodeURL: NSURL = node.objectID.URIRepresentation() let oID: String = nodeURL.lastPathComponent! return nodeClass + type + oID } /** :name: createdDate :description: Retrieves the date the Model Object was created. */ public var createdDate: NSDate { return node.createdDate } /** :name: groups :description: Retrieves the Groups the Bond is a part of. */ public var groups: OrderedSet<String> { var groups: OrderedSet<String> = OrderedSet<String>() for group in node.groupSet { let name: String = group.name groups.insert(name) } return groups } /** :name: addGroup :description: Adds a Group name to the list of Groups if it does not exist. */ public func addGroup(name: String) -> Bool { return node.addGroup(name) } /** :name: hasGroup :description: Checks whether the Node is a part of the Group name passed or not. */ public func hasGroup(name: String) -> Bool { return node.hasGroup(name) } /** :name: removeGroup :description: Removes a Group name from the list of Groups if it exists. */ public func removeGroup(name: String) -> Bool { return node.removeGroup(name) } /** :name: properties :description: Allows for Dictionary style coding, which maps to the wrapped Model Object property values. */ public subscript(name: String) -> AnyObject? { get { return node[name] } set(value) { node[name] = value } } /** :name: properties :description: Retrieves the Properties the Node is a part of. */ public var properties: OrderedDictionary<String, AnyObject> { var properties: OrderedDictionary<String, AnyObject> = OrderedDictionary<String, AnyObject>() for property in node.propertySet { properties.insert((property.name, property.object)) } return properties } /** :name: subject :description: Retrieves an Entity Object. */ public var subject: Entity? { get { return nil == node.subject ? nil : Entity(entity: node.subject!) } set(entity) { node.subject = entity?.node } } /** :name: object :description: Retrieves an Entity Object. */ public var object: Entity? { get { return nil == node.object ? nil : Entity(entity: node.object!) } set(entity) { node.object = entity?.node } } /** :name: delete :description: Marks the Model Object to be deleted from the Graph. */ public func delete() { node.delete() } } extension Bond : Equatable, Printable { override public var description: String { return "[nodeClass: \(nodeClass), id: \(id), type: \(type), groups: \(groups), properties: \(properties), subject: \(subject), object: \(object), createdDate: \(createdDate)]" } } public func ==(lhs: Bond, rhs: Bond) -> Bool { return lhs.id == rhs.id } public func <=(lhs: Bond, rhs: Bond) -> Bool { return lhs.id <= rhs.id } public func >=(lhs: Bond, rhs: Bond) -> Bool { return lhs.id >= rhs.id } public func >(lhs: Bond, rhs: Bond) -> Bool { return lhs.id > rhs.id } public func <(lhs: Bond, rhs: Bond) -> Bool { return lhs.id < rhs.id }
agpl-3.0
dca40bd379937513aeff611255c32380
23.806122
177
0.675031
3.485305
false
false
false
false
laurentVeliscek/AudioKit
AudioKit/Common/Nodes/Generators/Physical Models/Drip/AKDrip.swift
1
8710
// // AKDrip.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright (c) 2016 Aurelius Prochazka. All rights reserved. // import AVFoundation /// Physical model of the sound of dripping water. When triggered, it will /// produce a droplet of water. /// /// - Parameters: /// - intensity: The intensity of the dripping sound. /// - dampingFactor: The damping factor. Maximum value is 2.0. /// - energyReturn: The amount of energy to add back into the system. /// - mainResonantFrequency: Main resonant frequency. /// - firstResonantFrequency: The first resonant frequency. /// - secondResonantFrequency: The second resonant frequency. /// - amplitude: Amplitude. /// public class AKDrip: AKNode { // MARK: - Properties internal var internalAU: AKDripAudioUnit? internal var token: AUParameterObserverToken? private var intensityParameter: AUParameter? private var dampingFactorParameter: AUParameter? private var energyReturnParameter: AUParameter? private var mainResonantFrequencyParameter: AUParameter? private var firstResonantFrequencyParameter: AUParameter? private var secondResonantFrequencyParameter: AUParameter? private var amplitudeParameter: AUParameter? /// Ramp Time represents the speed at which parameters are allowed to change public var rampTime: Double = AKSettings.rampTime { willSet { if rampTime != newValue { internalAU?.rampTime = newValue internalAU?.setUpParameterRamp() } } } /// The intensity of the dripping sound. public var intensity: Double = 10 { willSet { if intensity != newValue { intensityParameter?.setValue(Float(newValue), originator: token!) } } } /// The damping factor. Maximum value is 2.0. public var dampingFactor: Double = 0.2 { willSet { if dampingFactor != newValue { dampingFactorParameter?.setValue(Float(newValue), originator: token!) } } } /// The amount of energy to add back into the system. public var energyReturn: Double = 0 { willSet { if energyReturn != newValue { energyReturnParameter?.setValue(Float(newValue), originator: token!) } } } /// Main resonant frequency. public var mainResonantFrequency: Double = 450 { willSet { if mainResonantFrequency != newValue { mainResonantFrequencyParameter?.setValue(Float(newValue), originator: token!) } } } /// The first resonant frequency. public var firstResonantFrequency: Double = 600 { willSet { if firstResonantFrequency != newValue { firstResonantFrequencyParameter?.setValue(Float(newValue), originator: token!) } } } /// The second resonant frequency. public var secondResonantFrequency: Double = 750 { willSet { if secondResonantFrequency != newValue { secondResonantFrequencyParameter?.setValue(Float(newValue), originator: token!) } } } /// Amplitude. public var amplitude: Double = 0.3 { willSet { if amplitude != newValue { amplitudeParameter?.setValue(Float(newValue), originator: token!) } } } /// Tells whether the node is processing (ie. started, playing, or active) public var isStarted: Bool { return internalAU!.isPlaying() } // MARK: - Initialization /// Initialize the drip with defaults convenience override init() { self.init(intensity: 10) } /// Initialize this drip node /// /// - Parameters: /// - intensity: The intensity of the dripping sound. /// - dampingFactor: The damping factor. Maximum value is 2.0. /// - energyReturn: The amount of energy to add back into the system. /// - mainResonantFrequency: Main resonant frequency. /// - firstResonantFrequency: The first resonant frequency. /// - secondResonantFrequency: The second resonant frequency. /// - amplitude: Amplitude. /// public init( intensity: Double, dampingFactor: Double = 0.2, energyReturn: Double = 0, mainResonantFrequency: Double = 450, firstResonantFrequency: Double = 600, secondResonantFrequency: Double = 750, amplitude: Double = 0.3) { self.intensity = intensity self.dampingFactor = dampingFactor self.energyReturn = energyReturn self.mainResonantFrequency = mainResonantFrequency self.firstResonantFrequency = firstResonantFrequency self.secondResonantFrequency = secondResonantFrequency self.amplitude = amplitude var description = AudioComponentDescription() description.componentType = kAudioUnitType_Generator description.componentSubType = 0x64726970 /*'drip'*/ description.componentManufacturer = 0x41754b74 /*'AuKt'*/ description.componentFlags = 0 description.componentFlagsMask = 0 AUAudioUnit.registerSubclass( AKDripAudioUnit.self, asComponentDescription: description, name: "Local AKDrip", 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? AKDripAudioUnit AudioKit.engine.attachNode(self.avAudioNode) } guard let tree = internalAU?.parameterTree else { return } intensityParameter = tree.valueForKey("intensity") as? AUParameter dampingFactorParameter = tree.valueForKey("dampingFactor") as? AUParameter energyReturnParameter = tree.valueForKey("energyReturn") as? AUParameter mainResonantFrequencyParameter = tree.valueForKey("mainResonantFrequency") as? AUParameter firstResonantFrequencyParameter = tree.valueForKey("firstResonantFrequency") as? AUParameter secondResonantFrequencyParameter = tree.valueForKey("secondResonantFrequency") as? AUParameter amplitudeParameter = tree.valueForKey("amplitude") as? AUParameter token = tree.tokenByAddingParameterObserver { address, value in dispatch_async(dispatch_get_main_queue()) { if address == self.intensityParameter!.address { self.intensity = Double(value) } else if address == self.dampingFactorParameter!.address { self.dampingFactor = Double(value) } else if address == self.energyReturnParameter!.address { self.energyReturn = Double(value) } else if address == self.mainResonantFrequencyParameter!.address { self.mainResonantFrequency = Double(value) } else if address == self.firstResonantFrequencyParameter!.address { self.firstResonantFrequency = Double(value) } else if address == self.secondResonantFrequencyParameter!.address { self.secondResonantFrequency = Double(value) } else if address == self.amplitudeParameter!.address { self.amplitude = Double(value) } } } internalAU?.intensity = Float(intensity) internalAU?.dampingFactor = Float(dampingFactor) internalAU?.energyReturn = Float(energyReturn) internalAU?.mainResonantFrequency = Float(mainResonantFrequency) internalAU?.firstResonantFrequency = Float(firstResonantFrequency) internalAU?.secondResonantFrequency = Float(secondResonantFrequency) internalAU?.amplitude = Float(amplitude) } // MARK: - Control /// Trigger the sound with an optional set of parameters /// public func trigger() { self.internalAU!.start() self.internalAU!.trigger() } /// Function to start, play, or activate the node, all do the same thing public func start() { self.internalAU!.start() } /// Function to stop or bypass the node, both are equivalent public func stop() { self.internalAU!.stop() } }
mit
d5f4d5f61e4fcd18943d0b8e92a48d7f
35.90678
102
0.631343
5.745383
false
false
false
false
Toldy/Clock-In
ClockIn/Controllers/EditTableViewController.swift
1
2096
// // EditTableViewController.swift // ClockIn // // Created by Julien Colin on 06/09/16. // Copyright © 2016 Julien Colin. All rights reserved. // import UIKit class EditTableViewController: UITableViewController { // MARK: Outlets @IBOutlet weak var beginDetailLabel: UILabel! @IBOutlet weak var beginDatePicker: UIDatePicker! @IBOutlet weak var endDetailLabel: UILabel! @IBOutlet weak var endDatePicker: UIDatePicker! var initializationHandler: ((UIDatePicker, UIDatePicker) -> Void)! var completionHandler: ((Date, Date) -> Void)! // MARK: - View Lifecycle override func viewDidLoad() { super.viewDidLoad() initializationHandler(beginDatePicker, endDatePicker) datePickerBeginValue(self) datePickerEndValue(self) } // MARK: User Interaction @IBAction func datePickerBeginValue(_ sender: AnyObject) { beginDetailLabel.text = localizedStringFromDate(beginDatePicker.date) } @IBAction func datePickerEndValue(_ sender: AnyObject) { endDetailLabel.text = localizedStringFromDate(endDatePicker.date) } @IBAction func submitChangesAction(_ sender: AnyObject) { // Begin Time > End Time if beginDatePicker.date > endDatePicker.date { Popup.showDatesReversed(self) { let tmpSwap = self.beginDatePicker.date self.beginDatePicker.date = self.endDatePicker.date self.endDatePicker.date = tmpSwap } return } // Begin Day != End Day if !beginDatePicker.date.compareWithoutTime(endDatePicker.date) { Popup.showWorkMoreThan24h(self) return } completionHandler(beginDatePicker.date, endDatePicker.date) _ = navigationController?.popViewController(animated: true) } // MARK: Additional Helpers func localizedStringFromDate(_ date: Date) -> String { return DateFormatter.localizedString(from: date, dateStyle: DateFormatter.Style.short, timeStyle: DateFormatter.Style.short) } }
mit
89d6598ec23f2798d8de98de9ed73915
28.507042
132
0.672076
4.91784
false
false
false
false
mshhmzh/firefox-ios
SyncTests/MockSyncServer.swift
2
17504
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared import GCDWebServers @testable import Sync import XCTest private let log = Logger.syncLogger private func optTimestamp(x: AnyObject?) -> Timestamp? { guard let str = x as? String else { return nil } return decimalSecondsStringToTimestamp(str) } private func optStringArray(x: AnyObject?) -> [String]? { guard let str = x as? String else { return nil } return str.componentsSeparatedByString(",").map { $0.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) } } private struct SyncRequestSpec { let collection: String let id: String? let ids: [String]? let limit: Int? let offset: String? let sort: SortOption? let newer: Timestamp? let full: Bool static func fromRequest(request: GCDWebServerRequest) -> SyncRequestSpec? { // Input is "/1.5/user/storage/collection", possibly with "/id" at the end. // That means we get five or six path components here, the first being empty. let parts = request.path!.componentsSeparatedByString("/").filter { !$0.isEmpty } let id: String? let ids = optStringArray(request.query["ids"]) let newer = optTimestamp(request.query["newer"]) let full: Bool = request.query["full"] != nil let limit: Int? if let lim = request.query["limit"] as? String { limit = Int(lim) } else { limit = nil } let offset = request.query["offset"] as? String let sort: SortOption? switch request.query["sort"] as? String ?? "" { case "oldest": sort = SortOption.OldestFirst case "newest": sort = SortOption.NewestFirst case "index": sort = SortOption.Index default: sort = nil } if parts.count < 4 { return nil } if parts[2] != "storage" { return nil } // Use dropFirst, you say! It's buggy. switch parts.count { case 4: id = nil case 5: id = parts[4] default: // Uh oh. return nil } return SyncRequestSpec(collection: parts[3], id: id, ids: ids, limit: limit, offset: offset, sort: sort, newer: newer, full: full) } } struct SyncDeleteRequestSpec { let collection: String? let id: GUID? let ids: [GUID]? let wholeCollection: Bool static func fromRequest(request: GCDWebServerRequest) -> SyncDeleteRequestSpec? { // Input is "/1.5/user{/storage{/collection{/id}}}". // That means we get four, five, or six path components here, the first being empty. return SyncDeleteRequestSpec.fromPath(request.path!, withQuery: request.query) } static func fromPath(path: String, withQuery query: [NSObject: AnyObject]) -> SyncDeleteRequestSpec? { let parts = path.componentsSeparatedByString("/").filter { !$0.isEmpty } let queryIDs: [GUID]? = (query["ids"] as? String)?.componentsSeparatedByString(",") guard [2, 4, 5].contains(parts.count) else { return nil } if parts.count == 2 { return SyncDeleteRequestSpec(collection: nil, id: nil, ids: queryIDs, wholeCollection: true) } if parts[2] != "storage" { return nil } if parts.count == 4 { let hasIDs = queryIDs != nil return SyncDeleteRequestSpec(collection: parts[3], id: nil, ids: queryIDs, wholeCollection: !hasIDs) } return SyncDeleteRequestSpec(collection: parts[3], id: parts[4], ids: queryIDs, wholeCollection: false) } } private struct SyncPutRequestSpec { let collection: String let id: String static func fromRequest(request: GCDWebServerRequest) -> SyncPutRequestSpec? { // Input is "/1.5/user/storage/collection/id}}}". // That means we get six path components here, the first being empty. let parts = request.path!.componentsSeparatedByString("/").filter { !$0.isEmpty } guard parts.count == 5 else { return nil } if parts[2] != "storage" { return nil } return SyncPutRequestSpec(collection: parts[3], id: parts[4]) } } class MockSyncServer { let server = GCDWebServer() let username: String var offsets: Int = 0 var continuations: [String: [EnvelopeJSON]] = [:] var collections: [String: (modified: Timestamp, records: [String: EnvelopeJSON])] = [:] var baseURL: String! init(username: String) { self.username = username } class func makeValidEnvelope(guid: GUID, modified: Timestamp) -> EnvelopeJSON { let clientBody: [String: AnyObject] = [ "id": guid, "name": "Foobar", "commands": [], "type": "mobile", ] let clientBodyString = JSON(clientBody).toString(false) let clientRecord: [String : AnyObject] = [ "id": guid, "collection": "clients", "payload": clientBodyString, "modified": Double(modified) / 1000, ] return EnvelopeJSON(JSON(clientRecord).toString(false)) } class func withHeaders(response: GCDWebServerResponse, lastModified: Timestamp? = nil, records: Int? = nil, timestamp: Timestamp? = nil) -> GCDWebServerResponse { let timestamp = timestamp ?? NSDate.now() let xWeaveTimestamp = millisecondsToDecimalSeconds(timestamp) response.setValue("\(xWeaveTimestamp)", forAdditionalHeader: "X-Weave-Timestamp") if let lastModified = lastModified { let xLastModified = millisecondsToDecimalSeconds(lastModified) response.setValue("\(xLastModified)", forAdditionalHeader: "X-Last-Modified") } if let records = records { response.setValue("\(records)", forAdditionalHeader: "X-Weave-Records") } return response; } func storeRecords(records: [EnvelopeJSON], inCollection collection: String, now: Timestamp? = nil) { let now = now ?? NSDate.now() let coll = self.collections[collection] var out = coll?.records ?? [:] records.forEach { out[$0.id] = $0.withModified(now) } let newModified = max(now, coll?.modified ?? 0) self.collections[collection] = (modified: newModified, records: out) } private func splitArray<T>(items: [T], at: Int) -> ([T], [T]) { return (Array(items.dropLast(items.count - at)), Array(items.dropFirst(at))) } private func recordsMatchingSpec(spec: SyncRequestSpec) -> (records: [EnvelopeJSON], offsetID: String?)? { // If we have a provided offset, handle that directly. if let offset = spec.offset { log.debug("Got provided offset \(offset).") guard let remainder = self.continuations[offset] else { log.error("Unknown offset.") return nil } // Remove the old one. self.continuations.removeValueForKey(offset) // Handle the smaller-than-limit or no-provided-limit cases. guard let limit = spec.limit where limit < remainder.count else { log.debug("Returning all remaining items.") return (remainder, nil) } // Record the next continuation and return the first slice of records. let next = "\(self.offsets)" self.offsets += 1 let (returned, remaining) = splitArray(remainder, at: limit) self.continuations[next] = remaining log.debug("Returning \(limit) items; next continuation is \(next).") return (returned, next) } guard let records = self.collections[spec.collection]?.records.values else { // No matching records. return ([], nil) } var items = Array(records) log.debug("Got \(items.count) candidate records.") if spec.newer ?? 0 > 0 { items = items.filter { $0.modified > spec.newer } } if let ids = spec.ids { let ids = Set(ids) items = items.filter { ids.contains($0.id) } } if let sort = spec.sort { switch sort { case SortOption.NewestFirst: items = items.sort { $0.modified > $1.modified } log.debug("Sorted items newest first: \(items.map { $0.modified })") case SortOption.OldestFirst: items = items.sort { $0.modified < $1.modified } log.debug("Sorted items oldest first: \(items.map { $0.modified })") case SortOption.Index: log.warning("Index sorting not yet supported.") } } if let limit = spec.limit where items.count > limit { let next = "\(self.offsets)" self.offsets += 1 let (returned, remaining) = splitArray(items, at: limit) self.continuations[next] = remaining return (returned, next) } return (items, nil) } private func recordResponse(record: EnvelopeJSON) -> GCDWebServerResponse { let body = JSON(record.asJSON()).toString() let bodyData = body.utf8EncodedData let response = GCDWebServerDataResponse(data: bodyData, contentType: "application/json") return MockSyncServer.withHeaders(response, lastModified: record.modified) } private func modifiedResponse(timestamp: Timestamp) -> GCDWebServerResponse { let body = JSON(["modified": NSNumber(unsignedLongLong: timestamp)]).toString() let bodyData = body.utf8EncodedData let response = GCDWebServerDataResponse(data: bodyData, contentType: "application/json") return MockSyncServer.withHeaders(response) } func modifiedTimeForCollection(collection: String) -> Timestamp? { return self.collections[collection]?.modified } func removeAllItemsFromCollection(collection: String, atTime: Timestamp) { if self.collections[collection] != nil { self.collections[collection] = (atTime, [:]) } } func start() { let basePath = "/1.5/\(self.username)" let storagePath = "\(basePath)/storage/" let infoCollectionsPath = "\(basePath)/info/collections" server.addHandlerForMethod("GET", path: infoCollectionsPath, requestClass: GCDWebServerRequest.self) { (request) -> GCDWebServerResponse! in var ic = [String: NSNumber]() var lastModified: Timestamp = 0 for collection in self.collections.keys { if let timestamp = self.modifiedTimeForCollection(collection) { ic[collection] = NSNumber(double: Double(timestamp) / 1000) lastModified = max(lastModified, timestamp) } } let body = JSON(ic).toString() let bodyData = body.utf8EncodedData let response = GCDWebServerDataResponse(data: bodyData, contentType: "application/json") return MockSyncServer.withHeaders(response, lastModified: lastModified, records: ic.count) } let matchPut: GCDWebServerMatchBlock = { method, url, headers, path, query -> GCDWebServerRequest! in guard method == "PUT" && path.startsWith(basePath) else { return nil } return GCDWebServerDataRequest(method: method, url: url, headers: headers, path: path, query: query) } server.addHandlerWithMatchBlock(matchPut) { (request) -> GCDWebServerResponse! in guard let request = request as? GCDWebServerDataRequest else { return MockSyncServer.withHeaders(GCDWebServerDataResponse(statusCode: 400)) } guard let spec = SyncPutRequestSpec.fromRequest(request) else { return MockSyncServer.withHeaders(GCDWebServerDataResponse(statusCode: 400)) } var body = JSON(request.jsonObject).asDictionary! body["modified"] = JSON(millisecondsToDecimalSeconds(NSDate.now())) let record = EnvelopeJSON(JSON(body)) self.storeRecords([record], inCollection: spec.collection) let timestamp = self.modifiedTimeForCollection(spec.collection)! let response = GCDWebServerDataResponse(data: millisecondsToDecimalSeconds(timestamp).utf8EncodedData, contentType: "application/json") return MockSyncServer.withHeaders(response) } let matchDelete: GCDWebServerMatchBlock = { method, url, headers, path, query -> GCDWebServerRequest! in guard method == "DELETE" && path.startsWith(basePath) else { return nil } return GCDWebServerRequest(method: method, url: url, headers: headers, path: path, query: query) } server.addHandlerWithMatchBlock(matchDelete) { (request) -> GCDWebServerResponse! in guard let spec = SyncDeleteRequestSpec.fromRequest(request) else { return GCDWebServerDataResponse(statusCode: 400) } if let collection = spec.collection, id = spec.id { guard var items = self.collections[collection]?.records else { // Unable to find the requested collection. return MockSyncServer.withHeaders(GCDWebServerDataResponse(statusCode: 404)) } guard let item = items[id] else { // Unable to find the requested id. return MockSyncServer.withHeaders(GCDWebServerDataResponse(statusCode: 404)) } items.removeValueForKey(id) return self.modifiedResponse(item.modified) } if let collection = spec.collection { if spec.wholeCollection { self.collections.removeValueForKey(collection) } else { if let ids = spec.ids, var map = self.collections[collection]?.records { for id in ids { map.removeValueForKey(id) } self.collections[collection] = (modified: NSDate.now(), records: map) } } return self.modifiedResponse(NSDate.now()) } self.collections = [:] return MockSyncServer.withHeaders(GCDWebServerDataResponse(data: "{}".utf8EncodedData, contentType: "application/json")) } let match: GCDWebServerMatchBlock = { method, url, headers, path, query -> GCDWebServerRequest! in guard method == "GET" && path.startsWith(storagePath) else { return nil } return GCDWebServerRequest(method: method, url: url, headers: headers, path: path, query: query) } server.addHandlerWithMatchBlock(match) { (request) -> GCDWebServerResponse! in // 1. Decide what the URL is asking for. It might be a collection fetch or // an individual record, and it might have query parameters. guard let spec = SyncRequestSpec.fromRequest(request) else { return MockSyncServer.withHeaders(GCDWebServerDataResponse(statusCode: 400)) } // 2. Grab the matching set of records. Prune based on TTL, exclude with X-I-U-S, etc. if let id = spec.id { guard let collection = self.collections[spec.collection], record = collection.records[id] else { // Unable to find the requested collection/id. return MockSyncServer.withHeaders(GCDWebServerDataResponse(statusCode: 404)) } return self.recordResponse(record) } guard let (items, offset) = self.recordsMatchingSpec(spec) else { // Unable to find the provided offset. return MockSyncServer.withHeaders(GCDWebServerDataResponse(statusCode: 400)) } // TODO: TTL // TODO: X-I-U-S let body = JSON(items.map { $0.asJSON() }).toString() let bodyData = body.utf8EncodedData let response = GCDWebServerDataResponse(data: bodyData, contentType: "application/json") // 3. Compute the correct set of headers: timestamps, X-Weave-Records, etc. if let offset = offset { response.setValue(offset, forAdditionalHeader: "X-Weave-Next-Offset") } let timestamp = self.modifiedTimeForCollection(spec.collection)! log.debug("Returning GET response with X-Last-Modified for \(items.count) records: \(timestamp).") return MockSyncServer.withHeaders(response, lastModified: timestamp, records: items.count) } if server.startWithPort(0, bonjourName: nil) == false { XCTFail("Can't start the GCDWebServer.") } baseURL = "http://localhost:\(server.port)\(basePath)" } }
mpl-2.0
eb8d11cb66649711274c2c7d0dcdd8dd
37.81153
166
0.59872
4.986895
false
false
false
false
sharath-cliqz/browser-ios
Client/Application/AuroraAppDelegate.swift
2
6067
/* 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 Alamofire import MessageUI private let AuroraPropertyListURL = "https://people.mozilla.org/iosbuilds/FennecAurora.plist" private let AuroraDownloadPageURL = "https://people.mozilla.org/iosbuilds/index.html" private let AppUpdateTitle = NSLocalizedString("New version available", comment: "Prompt title for application update") private let AppUpdateMessage = NSLocalizedString("There is a new version available of Firefox Aurora. Tap OK to go to the download page.", comment: "Prompt message for application update") private let AppUpdateCancel = NSLocalizedString("Not Now", comment: "Label for button to cancel application update prompt") private let AppUpdateOK = NSLocalizedString("OK", comment: "Label for OK button in the application update prompt") class AuroraAppDelegate: AppDelegate { fileprivate var naggedAboutAuroraUpdate = false fileprivate let feedbackDelegate = FeedbackSnapshotDelegate() override func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { super.application(application, willFinishLaunchingWithOptions: launchOptions) checkForAuroraUpdate() registerFeedbackNotification() return true } override func applicationDidBecomeActive(_ application: UIApplication) { if !naggedAboutAuroraUpdate { checkForAuroraUpdate() } super.applicationDidBecomeActive(application) } func application(_ application: UIApplication, applicationWillTerminate app: UIApplication) { unregisterFeedbackNotification() } override func applicationWillResignActive(_ application: UIApplication) { super.applicationWillResignActive(application) unregisterFeedbackNotification() } fileprivate func registerFeedbackNotification() { NotificationCenter.default.addObserver( forName: NSNotification.Name.UIApplicationUserDidTakeScreenshot, object: nil, queue: OperationQueue.main) { (notification) -> Void in if let window = self.window { UIGraphicsBeginImageContext(window.bounds.size) window.drawHierarchy(in: window.bounds, afterScreenUpdates: true) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() self.sendFeedbackMailWithImage(image!) } } } fileprivate func unregisterFeedbackNotification() { NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIApplicationUserDidTakeScreenshot, object: nil) } } extension AuroraAppDelegate: UIAlertViewDelegate { fileprivate func checkForAuroraUpdate() { if let localVersion = localVersion() { fetchLatestAuroraVersion() { version in if let remoteVersion = version { if localVersion.compare(remoteVersion as String, options: NSString.CompareOptions.numeric) == ComparisonResult.orderedAscending { self.naggedAboutAuroraUpdate = true let alert = UIAlertView(title: AppUpdateTitle, message: AppUpdateMessage, delegate: self, cancelButtonTitle: AppUpdateCancel, otherButtonTitles: AppUpdateOK) alert.show() } } } } } fileprivate func localVersion() -> NSString? { return Bundle.main.object(forInfoDictionaryKey: String(kCFBundleVersionKey)) as? NSString } fileprivate func fetchLatestAuroraVersion(_ completionHandler: @escaping (NSString?) -> Void) { Alamofire.request(AuroraPropertyListURL, method: .get).responsePropertyList(options: PropertyListSerialization.ReadOptions(), completionHandler: { response -> Void in if let plist = response.result.value as? NSDictionary, let items = plist["items"] as? NSArray, let item = items[0] as? NSDictionary, let metadata = item["metadata"] as? NSDictionary, let remoteVersion = metadata["bundle-version"] as? NSString { completionHandler(remoteVersion) return } completionHandler(nil) }) } func alertView(_ alertView: UIAlertView, clickedButtonAt buttonIndex: Int) { if buttonIndex == 1 { UIApplication.shared.openURL(URL(string: AuroraDownloadPageURL)!) } } } extension AuroraAppDelegate { func sendFeedbackMailWithImage(_ image: UIImage) { if (MFMailComposeViewController.canSendMail()) { if let buildNumber = Bundle.main.object(forInfoDictionaryKey: String(kCFBundleVersionKey)) as? NSString { let mailComposeViewController = MFMailComposeViewController() mailComposeViewController.mailComposeDelegate = self.feedbackDelegate mailComposeViewController.setSubject("Feedback on iOS client version v\(appVersion) (\(buildNumber))") mailComposeViewController.setToRecipients(["[email protected]"]) if let imageData = UIImagePNGRepresentation(image) { mailComposeViewController.addAttachmentData(imageData, mimeType: "image/png", fileName: "feedback.png") window?.rootViewController?.present(mailComposeViewController, animated: true, completion: nil) } } } } } fileprivate class FeedbackSnapshotDelegate: NSObject, MFMailComposeViewControllerDelegate { @objc func mailComposeController(_ mailComposeViewController: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) { mailComposeViewController.dismiss(animated: true, completion: nil) } }
mpl-2.0
97bf3283f5120cd781df50c234c111d2
46.031008
188
0.690786
6.030815
false
false
false
false
wireapp/wire-ios
Wire-iOS/Sources/Helpers/ImageCache.swift
1
1246
// // Wire // Copyright (C) 2018 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation import UIKit /// TODO: remove public after MockUser is convert to Swift public final class ImageCache<T: AnyObject> { var cache: NSCache<NSString, T> = NSCache() var processingQueue = DispatchQueue(label: "ImageCacheQueue", qos: .background, attributes: [.concurrent]) var dispatchGroup: DispatchGroup = DispatchGroup() } extension UIImage { public static var defaultUserImageCache: ImageCache<UIImage> = ImageCache() } final class MediaAssetCache { static var defaultImageCache = ImageCache<AnyObject>() }
gpl-3.0
bca1cb38ecb4df5389f2b423bcb8a6e2
34.6
110
0.747191
4.41844
false
false
false
false
Trxy/TRX
TRXTests/specs/morphable/Morphable+CGRectSpec.swift
1
1283
@testable import TRX import Quick import Nimble class Morphable_CGRectSpec: QuickSpec { override func spec() { var subject: Tween<CGRect>! var currentRect: CGRect? let startingRect = CGRect(x: 1, y: 2, width: 3, height: 4) let finalRect = CGRect(x: 2, y: 4, width: 6, height: 8) beforeEach { subject = Tween(from: startingRect, to: finalRect, time: 1, ease: Ease.linear, update: { currentRect = $0 }) } describe("CGRect") { context("beginning") { beforeEach() { subject.seek(offset: 0) } it("should have correct value") { expect(currentRect) == startingRect } } context("end") { beforeEach() { subject.seek(offset: 1) } it("should have correct value") { expect(currentRect) == finalRect } } context("between") { beforeEach() { subject.seek(offset: 0.5) } it("should have correct value") { expect(currentRect) == CGRect(x:1.5, y: 3, width: 4.5, height: 6) } } } } }
mit
e7d903d3229ac00a0eb7ef15b7f842af
18.439394
75
0.465316
4.334459
false
false
false
false
hdinhof1/CheckSplit
CheckSplit/Person.swift
1
2665
// // Person.swift // CheckSplit // // Created by Henry Dinhofer on 12/22/16. // Copyright © 2016 Henry Dinhofer. All rights reserved. // import Foundation class Person { var name : String var drinks : [Drink] var appetizers : [Appetizer] var entrees : [Food] var total : Double var personUUID : Int var description : String { var description = "\(self.name)\nDrink:" for drink in self.drinks { description += "\t\(drink.description)" } description += "\nFood:\n" for food in entrees { description += "\t\(food.name) - \(food.cost)" } description += "Total: \(self.totalTally)\n" return description } var totalTally : Double { var total : Double = 0.0 for drink in drinks { total += drink.cost } for appetizer in appetizers { total += appetizer.cost } for entree in entrees { total += entree.cost } return total } var subtotal : Double { return self.totalTally } var taxtotal : Double { let taxRate = UserDefaults().getTaxRate() return self.subtotal * taxRate } var grandtotal : Double { return self.subtotal + self.taxtotal } var tiptotal : Double { let grandTotal = self.grandtotal let tipRate = UserDefaults().getTipRate() return grandTotal * tipRate } init(name: String, drinks : [Drink], appetizers: [Appetizer], entrees : [Food]) { self.name = name self.drinks = drinks self.appetizers = appetizers self.entrees = entrees self.total = 0.0 self.personUUID = MealDataStore.sharedInstance.peopleUUID } convenience init(name: String) { self.init(name: name, drinks: [Drink](), appetizers: [Appetizer](), entrees: [Food]()) } //generic method (addItem : [Any]) func addDrink(drink : Drink) { self.drinks.append(drink) total += drink.cost } func removeDrink(drink : Drink) { guard let index = self.drinks.index(where: { $0 == drink } ) else { return } total -= self.drinks[index].cost self.drinks.remove(at: index) } func split(drink : Drink, withPerson person : Person) { drink.splitWith.append(person) person.addDrink(drink: drink) } } func ==(lhs: Person, rhs: Person) -> Bool { return lhs.name == rhs.name //&& lhs.personUUID == rhs.personUUID }
apache-2.0
b7e963d8593253ee771344c92aac0697
23.897196
94
0.548799
4.248804
false
false
false
false
dictav/SwiftLint
Source/SwiftLintFramework/Models/RuleDescription.swift
1
894
// // RuleDescription.swift // SwiftLint // // Created by Chris Eidhof on 25/05/15. // Copyright (c) 2015 Realm. All rights reserved. // public struct RuleDescription: Equatable { public let identifier: String public let name: String public let description: String public let nonTriggeringExamples: [String] public let triggeringExamples: [String] public init(identifier: String, name: String, description: String, nonTriggeringExamples: [String] = [], triggeringExamples: [String] = []) { self.identifier = identifier self.name = name self.description = description self.nonTriggeringExamples = nonTriggeringExamples self.triggeringExamples = triggeringExamples } } // MARK: Equatable public func == (lhs: RuleDescription, rhs: RuleDescription) -> Bool { return lhs.identifier == rhs.identifier }
mit
67bb8866eec060199a0101369928b317
27.83871
70
0.687919
4.755319
false
false
false
false
fleurdeswift/code-editor
CodeEditorCore/Document+InsertText.swift
1
2630
// // Document+InsertText.swift // CodeEditorCore // // Copyright © 2015 Fleur de Swift. All rights reserved. // import Foundation public extension Document { public func insertText(text: String, position: Position, context: ModificationContext) throws -> DocumentCommand? { if text.isEmpty { return nil; } let parts = text.componentsSeparatedByString("\n"); if parts.count == 0 { return nil; } try throwPositionError(position, context: context); let firstLine = lines[position.line]; if (parts.count == 1) { let newPart = toAttributedString(parts[0]); if (position.column == firstLine.length) { firstLine.text.appendAttributedString(newPart); } else { firstLine.text.insertAttributedString(newPart, atIndex: position.column); } context.wasLineModified(firstLine, number: position.line); return context.addDocumentCommand( DocumentCommand(generation: generation, type: .Remove, range: PositionRange(position, position + newPart.length), text: text)); } var newLines = [Line](); let lastLine = firstLine.split(position.column); newLines.append(firstLine); firstLine.text.appendAttributedString(toAttributedString(parts[0])) context.wasLineModified(firstLine, number: position.line); for (var index = 1; index < (parts.count - 1); ++index) { newLines.append(Line(attributedString: toAttributedString(parts[index]))); context.wasLineInserted(newLines[1], number: position.line + index); } newLines.append(lastLine); let lastPart = toAttributedString(parts.last!); lastLine.text.insertAttributedString(lastPart, atIndex: 0); context.wasLineInserted(lastLine, number: position.line + parts.count - 1); lines.replaceRange(Range(start: position.line, end: position.line + 1), with: newLines); return context.addDocumentCommand( DocumentCommand(generation: generation, type: .Remove, range: PositionRange(position, Position(line: position.line + parts.count - 1, column: lastPart.length)), text: text)); } }
mit
5d59507fa5f88c4a0a54eb7e73bdaf75
36.557143
139
0.558768
5.165029
false
false
false
false
Wolox/wolmo-core-ios
WolmoCoreTests/Extensions/Foundation/TimerSpec.swift
1
1169
// // TimerSpec.swift // WolmoCore // // Created by Francisco Depascuali on 7/18/16. // Copyright © 2016 Wolox. All rights reserved. // import Foundation import Quick import Nimble import WolmoCore public class TimerSpec: QuickSpec { override public func spec() { var timer: Timer! afterEach { timer!.invalidate() timer = .none } describe("#schedule(withDelay:)") { it("should trigger handler after delay") { waitUntil(timeout: DispatchTimeInterval.seconds(2)) { done in timer = Timer.schedule(withDelay: 1) { _ in done() } }} } describe("#schedule(repeatInterval:)") { it("should repeteadly trigger handler after delay") { waitUntil(timeout: DispatchTimeInterval.seconds(6)) { done in var timesCalled = 0 timer = Timer.schedule(repeatInterval: 1) { _ in timesCalled += 1 if timesCalled == 2 { done() } } }} } } }
mit
bc86526b76d999797058b847d7d6089a
26.162791
127
0.502568
5.122807
false
false
false
false
zype/ZypeAppleTVBase
ZypeAppleTVBase/Models/ResponseModels/GuideModel.swift
1
821
// // GuideModel.swift // ZypeAppleTVBase // // Created by Top developer on 4/19/19. // import UIKit open class GuideModel: NSObject { fileprivate (set) open var ID = "" fileprivate (set) open var name = "" fileprivate (set) open var video_id = "" open var programs = [GuideProgramModel]() init(json: Dictionary<String, AnyObject>) { super.init() do { self.ID = try SSUtils.stringFromDictionary(json, key: kJSON_Id) self.name = try SSUtils.stringFromDictionary(json, key: kJSONName) if let videoIds = json[kJSONVideoIds] as? [String], videoIds.count > 0 { self.video_id = videoIds[0] } } catch { ZypeLog.error("Exception: GuideModel") } } }
mit
8d3bc8db42d2babccf3b26133b6cf729
23.147059
84
0.560292
3.872642
false
false
false
false
tsolomko/SWCompression
Sources/swcomp/Archives/GZipCommand.swift
1
2972
// Copyright (c) 2022 Timofey Solomko // Licensed under MIT License // // See LICENSE for license information import Foundation import SWCompression import SwiftCLI final class GZipCommand: Command { let name = "gz" let shortDescription = "Creates or extracts a GZip archive" @Flag("-c", "--compress", description: "Compress an input file into a GZip archive") var compress: Bool @Flag("-d", "--decompress", description: "Decompress a GZip archive") var decompress: Bool @Flag("-i", "--info", description: "Print information from a GZip header") var info: Bool @Flag("-n", "--use-gzip-name", description: "Use the name saved inside a GZip archive as an output path, if possible") var useGZipName: Bool var optionGroups: [OptionGroup] { return [.exactlyOne($compress, $decompress, $info)] } @Param var input: String @Param var output: String? func execute() throws { if decompress { let inputURL = URL(fileURLWithPath: self.input) var outputURL: URL? if let outputPath = output { outputURL = URL(fileURLWithPath: outputPath) } else if inputURL.pathExtension == "gz" { outputURL = inputURL.deletingPathExtension() } let fileData = try Data(contentsOf: inputURL, options: .mappedIfSafe) if useGZipName { let header = try GzipHeader(archive: fileData) if let fileName = header.fileName { outputURL = inputURL.deletingLastPathComponent() .appendingPathComponent(fileName, isDirectory: false) } } guard outputURL != nil else { swcompExit(.noOutputPath) } let decompressedData = try GzipArchive.unarchive(archive: fileData) try decompressedData.write(to: outputURL!) } else if compress { let inputURL = URL(fileURLWithPath: self.input) let fileName = inputURL.lastPathComponent let outputURL: URL if let outputPath = output { outputURL = URL(fileURLWithPath: outputPath) } else { outputURL = inputURL.appendingPathExtension("gz") } let fileData = try Data(contentsOf: inputURL, options: .mappedIfSafe) let compressedData = try GzipArchive.archive(data: fileData, fileName: fileName.isEmpty ? nil : fileName, writeHeaderCRC: true) try compressedData.write(to: outputURL) } else if info { let inputURL = URL(fileURLWithPath: self.input) let fileData = try Data(contentsOf: inputURL, options: .mappedIfSafe) let header = try GzipHeader(archive: fileData) print(header) } } }
mit
70302e548b482c414dea7c32c8bfaecd
33.964706
122
0.582436
5.297683
false
false
false
false
weijentu/ResearchKit
Testing/ORKTest/ORKTest/TaskFactory.swift
11
9428
/* Copyright (c) 2015, Ricardo Sánchez-Sáez. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder(s) nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. No license is granted to the trademarks of the copyright holders even if such marks are included in this software. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import Foundation import ResearchKit @objc class TaskFactory : NSObject { class func makeNavigableOrderedTask(taskIdentifier : String) -> ORKNavigableOrderedTask { var steps: [ORKStep] = [] var answerFormat: ORKAnswerFormat var step: ORKStep var textChoices: [ORKTextChoice] // Form step textChoices = [ ORKTextChoice(text: "Good", value: "good"), ORKTextChoice(text: "Bad", value: "bad") ] answerFormat = ORKAnswerFormat.choiceAnswerFormatWithStyle(ORKChoiceAnswerStyle.SingleChoice, textChoices: textChoices) let formItemFeeling: ORKFormItem = ORKFormItem(identifier: "formFeeling", text: "How do you feel", answerFormat: answerFormat) let formItemMood: ORKFormItem = ORKFormItem(identifier: "formMood", text: "How is your mood", answerFormat: answerFormat) let formStep: ORKFormStep = ORKFormStep(identifier: "introForm") formStep.optional = false formStep.formItems = [formItemFeeling, formItemMood] steps.append(formStep) // Question steps textChoices = [ ORKTextChoice(text: "Headache", value: "headache"), ORKTextChoice(text: "Dizziness", value: "dizziness"), ORKTextChoice(text: "Nausea", value: "nausea") ] answerFormat = ORKTextChoiceAnswerFormat(style: ORKChoiceAnswerStyle.SingleChoice, textChoices: textChoices) step = ORKQuestionStep(identifier: "symptom", title: "Which is your most severe symptom?", answer: answerFormat) step.optional = false steps.append(step) answerFormat = ORKAnswerFormat.booleanAnswerFormat() step = ORKQuestionStep(identifier: "severity", title: "Does your symptom interfere with your daily life?", answer: answerFormat) step.optional = false steps.append(step) // Instruction steps step = ORKInstructionStep(identifier: "blank") step.title = "This step is intentionally left blank (you should not see it)" steps.append(step) step = ORKInstructionStep(identifier: "severe_headache") step.title = "You have a severe headache" steps.append(step) step = ORKInstructionStep(identifier: "light_headache") step.title = "You have a light headache" steps.append(step) step = ORKInstructionStep(identifier: "other_symptom") step.title = "Your symptom is not a headache" steps.append(step) step = ORKInstructionStep(identifier: "survey_skipped") step.title = "Please come back to this survey when you don't feel good or your mood is low." steps.append(step) step = ORKInstructionStep(identifier: "end") step.title = "You have finished the task" steps.append(step) step = ORKInstructionStep(identifier: "blankB") step.title = "This step is intentionally left blank (you should not see it)" steps.append(step) let task: ORKNavigableOrderedTask = ORKNavigableOrderedTask(identifier: taskIdentifier, steps: steps) // Navigation rules var predicateRule: ORKPredicateStepNavigationRule // From the feel/mood form step, skip the survey if the user is feeling okay and has a good mood var resultSelector = ORKResultSelector.init(stepIdentifier: "introForm", resultIdentifier: "formFeeling"); let predicateGoodFeeling: NSPredicate = ORKResultPredicate.predicateForChoiceQuestionResultWithResultSelector(resultSelector, expectedAnswerValue: "good") resultSelector = ORKResultSelector.init(stepIdentifier: "introForm", resultIdentifier: "formMood"); let predicateGoodMood: NSPredicate = ORKResultPredicate.predicateForChoiceQuestionResultWithResultSelector(resultSelector, expectedAnswerValue: "good") let predicateGoodMoodAndFeeling: NSPredicate = NSCompoundPredicate(andPredicateWithSubpredicates: [predicateGoodFeeling, predicateGoodMood]) predicateRule = ORKPredicateStepNavigationRule(resultPredicatesAndDestinationStepIdentifiers: [ (predicateGoodMoodAndFeeling, "survey_skipped") ]) task.setNavigationRule(predicateRule, forTriggerStepIdentifier: "introForm") // From the "symptom" step, go to "other_symptom" is user didn't chose headache. // Otherwise, default to going to next step (the regular ORKOrderedTask order applies // when the defaultStepIdentifier argument is omitted). // User chose headache at the symptom step // Equivalent to: // [NSPredicate predicateWithFormat: // @"SUBQUERY(SELF, $x, $x.identifier like 'symptom' \ // AND SUBQUERY($x.answer, $y, $y like 'headache').@count > 0).@count > 0"]; resultSelector = ORKResultSelector.init(resultIdentifier: "symptom"); let predicateHeadache: NSPredicate = ORKResultPredicate.predicateForChoiceQuestionResultWithResultSelector(resultSelector, expectedAnswerValue: "headache") // User didn't chose headache at the symptom step let predicateNotHeadache: NSPredicate = NSCompoundPredicate(notPredicateWithSubpredicate: predicateHeadache) predicateRule = ORKPredicateStepNavigationRule(resultPredicatesAndDestinationStepIdentifiers: [ (predicateNotHeadache, "other_symptom") ]) task.setNavigationRule(predicateRule, forTriggerStepIdentifier: "symptom") // From the "severity" step, go to "severe_headache" or "light_headache" depending on the user answer // User chose YES at the severity step // Equivalent to: // [NSPredicate predicateWithFormat: // @"SUBQUERY(SELF, $x, $x.identifier like 'severity' AND $x.answer == YES).@count > 0"]; resultSelector = ORKResultSelector.init(resultIdentifier: "severity"); let predicateSevereYes: NSPredicate = ORKResultPredicate.predicateForBooleanQuestionResultWithResultSelector(resultSelector, expectedAnswer: true) // User chose NO at the severity step resultSelector = ORKResultSelector.init(resultIdentifier: "severity"); let predicateSevereNo: NSPredicate = ORKResultPredicate.predicateForBooleanQuestionResultWithResultSelector(resultSelector, expectedAnswer: false) let predicateSevereHeadache: NSPredicate = NSCompoundPredicate(andPredicateWithSubpredicates: [predicateHeadache, predicateSevereYes]) let predicateLightHeadache: NSPredicate = NSCompoundPredicate(andPredicateWithSubpredicates: [predicateHeadache, predicateSevereNo]) predicateRule = ORKPredicateStepNavigationRule(resultPredicatesAndDestinationStepIdentifiers: [ (predicateSevereHeadache, "severe_headache"), (predicateLightHeadache, "light_headache") ]) task.setNavigationRule(predicateRule, forTriggerStepIdentifier: "severity") // Direct rules to skip unneeded steps var directRule: ORKDirectStepNavigationRule directRule = ORKDirectStepNavigationRule(destinationStepIdentifier: "end") task.setNavigationRule(directRule, forTriggerStepIdentifier: "severe_headache") task.setNavigationRule(directRule, forTriggerStepIdentifier: "light_headache") task.setNavigationRule(directRule, forTriggerStepIdentifier: "other_symptom") task.setNavigationRule(directRule, forTriggerStepIdentifier: "survey_skipped") directRule = ORKDirectStepNavigationRule(destinationStepIdentifier: ORKNullStepIdentifier) task.setNavigationRule(directRule, forTriggerStepIdentifier: "end") return task } }
bsd-3-clause
d1f982cb970b5f3459946827c1830aaa
55.107143
163
0.716847
5.361775
false
false
false
false
IBM-Swift/BluePic
BluePic-iOS/BluePic/Extensions/UIViewExtensions.swift
1
2495
/** * Copyright IBM Corporation 2016 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import CoreFoundation import Foundation import UIKit extension UIView { /** Method starts rotating a uiview 360 degrees until it is told to stop - parameter duration: Double */ func startRotating(_ duration: Double = 1) { let kAnimationKey = "rotation" self.layer.removeAnimation(forKey: kAnimationKey) if self.layer.animation(forKey: kAnimationKey) == nil { let animate = CABasicAnimation(keyPath: "transform.rotation") animate.duration = duration animate.repeatCount = Float.infinity animate.fromValue = 0.0 animate.toValue = Float.pi * 2.0 self.layer.add(animate, forKey: kAnimationKey) } } /** Method stops rotating a uiview 360 degrees */ func stopRotating() { let kAnimationKey = "rotation" if self.layer.animation(forKey: kAnimationKey) != nil { self.layer.removeAnimation(forKey: kAnimationKey) } } /** Method to simply shake a view back and forth. Most useful on textField to show invalid input */ func shakeView() { let animation = CABasicAnimation(keyPath: "position") animation.duration = 0.06 animation.repeatCount = 3 animation.autoreverses = true animation.fromValue = NSValue(cgPoint: CGPoint(x: self.center.x - 10, y: self.center.y)) animation.toValue = NSValue(cgPoint: CGPoint(x: self.center.x + 10, y: self.center.y)) self.layer.add(animation, forKey: "position") } } /** MARK: IBInspectable */ extension UIView { /// Allows you to modify the corner radius of a view in storyboard @IBInspectable var cornerRadius: CGFloat { get { return layer.cornerRadius } set { layer.cornerRadius = newValue layer.masksToBounds = newValue > 0 } } }
apache-2.0
2b9109c913b862a06b03a84aece270a0
28.702381
97
0.652505
4.561243
false
false
false
false
l4u/ZLSwipeableViewSwift
ZLSwipeableViewSwiftDemo/ZLSwipeableViewSwiftDemo/CustomSwipeDemoViewController.swift
14
1867
// // CustomSwipeDemoViewController.swift // ZLSwipeableViewSwiftDemo // // Created by Zhixuan Lai on 5/25/15. // Copyright (c) 2015 Zhixuan Lai. All rights reserved. // import UIKit class CustomSwipeDemoViewController: ZLSwipeableViewController { override func viewDidLoad() { super.viewDidLoad() leftBarButtonItem.addAction() { item in // custom push location and direction self.swipeableView.swipeTopView(fromPoint: CGPoint(x: 10, y: 300), inDirection: CGVector(dx: -700, dy: -300)) } upBarButtonItem.addAction() { item in self.swipeableView.swipeTopView(fromPoint: CGPoint(x: 100, y: 30), inDirection: CGVector(dx: 100, dy: -800)) } // change how ZLSwipeableViewDirection gets interpreted to location and direction swipeableView.interpretDirection = {(topView: UIView, direction: ZLSwipeableViewDirection, views: [UIView], swipeableView: ZLSwipeableView) in let programmaticSwipeVelocity = CGFloat(500) let location = CGPoint(x: topView.center.x-30, y: topView.center.y*0.1) var directionVector: CGVector? switch direction { case ZLSwipeableViewDirection.Left: directionVector = CGVector(dx: -programmaticSwipeVelocity, dy: 0) case ZLSwipeableViewDirection.Right: directionVector = CGVector(dx: programmaticSwipeVelocity, dy: 0) case ZLSwipeableViewDirection.Up: directionVector = CGVector(dx: 0, dy: -programmaticSwipeVelocity) case ZLSwipeableViewDirection.Down: directionVector = CGVector(dx: 0, dy: programmaticSwipeVelocity) default: directionVector = CGVector(dx: 0, dy: 0) } return (location, directionVector!) } } }
mit
9c87202585dc6e343094af5906d3f174
39.586957
150
0.648634
5.129121
false
false
false
false
Fenrikur/ef-app_ios
EurofurenceTests/Test Doubles/CapturingPreloadInteractor.swift
1
1081
@testable import Eurofurence import EurofurenceModel class CapturingPreloadInteractor: PreloadInteractor { private(set) var didBeginPreloading = false private(set) var beginPreloadInvocationCount = 0 private var delegate: PreloadInteractorDelegate? func beginPreloading(delegate: PreloadInteractorDelegate) { self.delegate = delegate didBeginPreloading = true beginPreloadInvocationCount += 1 } func notifyFailedToPreload() { delegate?.preloadInteractorDidFailToPreload() } func notifySucceededPreload() { delegate?.preloadInteractorDidFinishPreloading() } func simulateOldAppError() { delegate?.preloadInteractorFailedToLoadDueToOldAppDetected() } func notifyProgressMade(current: Int, total: Int, localizedDescription: String) { delegate?.preloadInteractorDidProgress(currentUnitCount: current, totalUnitCount: total, localizedDescription: localizedDescription) } }
mit
79cc5379887777cd2a036c273bf8c8ce
31.757576
90
0.680851
5.907104
false
false
false
false
Ifinity/ifinity-swift-example
IfinitySDK-swift/PushesViewController.swift
1
3049
// // PushesViewController.swift // IfinitySDK-swift // // Created by Ifinity on 15.12.2015. // Copyright © 2015 getifinity.com. All rights reserved. // import UIKit import ifinitySDK class PushesViewController: UITableViewController { var pushes:[AnyObject] = [] override func viewDidLoad() { super.viewDidLoad() self.title = "Pushes" self.listPushes() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func listPushes() { self.pushes = IFPushManager.sharedManager().fetchAll() if self.refreshControl != nil { let formatter: NSDateFormatter = NSDateFormatter() formatter.dateFormat = "MMM d, h:mm a" let lastUpdated: String = "Last updated on \(formatter.stringFromDate(NSDate()))" self.refreshControl?.attributedTitle = NSAttributedString(string: lastUpdated) self.refreshControl?.endRefreshing() } self.tableView.reloadData() } //MARK: - UITableViewDataSource override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.pushes.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell1")! let push = self.pushes[indexPath.row] as! IFMPush cell.textLabel!.text = push.name if Int(push.type) == IFMPushTypeLocal || Int(push.type) == IFMPushTypeLocalBackground { cell.accessoryType = .DisclosureIndicator cell.userInteractionEnabled = true } else { cell.accessoryType = .None cell.userInteractionEnabled = false } return cell } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if sender is UITableViewCell && segue.destinationViewController is ContentViewController { let indexPath = self.tableView.indexPathForCell(sender as! UITableViewCell)! let push = self.pushes[indexPath.row] as! IFMPush let destinationVC = segue.destinationViewController as! ContentViewController switch Int(push.type) { case IFMPushTypeRemote: if push.url != nil { destinationVC.url = NSURL(string: push.url) } else if push.content != nil { destinationVC.content = push.content } case IFMPushTypeLocalBackground: fallthrough case IFMPushTypeLocal: let content = IFMContent.fetchContentWithRemoteID(push.pushLocal.content_id, managedObjectContext: nil) destinationVC.url = NSURL(string: content.getContentURL()!) default: break } } } }
mit
e7a3c9500eced68b8e29d5da2ac1d272
34.858824
119
0.621391
5.39469
false
false
false
false
jlecomte/iOSTwitterApp
Twiddlator/TwitterClient.swift
1
7453
// // TwitterClient.swift // Twiddlator // // Created by Julien Lecomte on 9/26/14. // Copyright (c) 2014 Julien Lecomte. All rights reserved. // import UIKit class TwitterClient: BDBOAuth1RequestOperationManager, UIAlertViewDelegate { class var sharedInstance: TwitterClient { struct Static { static var instance: TwitterClient? static var token: dispatch_once_t = 0 } dispatch_once(&Static.token) { Static.instance = TwitterClient( baseURL: NSURL(string: "https://api.twitter.com/1.1/"), consumerKey: "1zkB4CeczbniHaRH9hVT6139T", consumerSecret: "NDS2Oz485w3Ay4anaii2prfKgxd7tuoXwYq7ktd1jgCVZ4R6DN" ) } return Static.instance! } func authorize() { fetchRequestTokenWithPath( "/oauth/request_token", method: "POST", callbackURL: NSURL(string: "twiddlator://oauth"), scope: nil, success: { (requestToken: BDBOAuthToken!) -> Void in println("Received request token \(requestToken)") var authURL = "https://api.twitter.com/oauth/authorize?oauth_token=\(requestToken.token)" UIApplication.sharedApplication().openURL(NSURL(string: authURL)) }, failure: { (error: NSError!) -> Void in println(error); UIAlertView( title: "Error", message: "Could not acquire OAuth request token. Please try again later.", delegate: self, cancelButtonTitle: "Dismiss").show() }) } func handleOAuthCallback(queryString: String, success: (() -> Void)!) { fetchAccessTokenWithPath( "/oauth/access_token", method: "POST", requestToken: BDBOAuthToken(queryString: queryString), success: { (accessToken: BDBOAuthToken!) -> Void in println("Received access token \(accessToken) -> authentication successful") self.requestSerializer.saveAccessToken(accessToken) if success != nil { success() } }, failure: { (error: NSError!) -> Void in UIAlertView( title: "Error", message: "Could not acquire OAuth access token. Please try again later.", delegate: self, cancelButtonTitle: "Dismiss").show() }) } func isAuthorized() -> Bool { return requestSerializer.accessToken != nil && !requestSerializer.accessToken.expired } func getTimeline(endpoint: String, user_id: String!, since_id: String!, max_id: String!, callback: (tweets: [Tweet]!, error: NSError!) -> Void) { var parameters = [String: String]() if since_id != nil { parameters["since_id"] = since_id } else if max_id != nil { parameters["max_id"] = max_id } else { parameters["since_id"] = "1" } if user_id != nil { parameters["user_id"] = user_id } GET(endpoint, parameters: parameters, success: { // Success (operation: AFHTTPRequestOperation!, response: AnyObject!) -> Void in var objects = response as [NSDictionary] var tweets: [Tweet] = [] for object in objects { var tweet = Tweet(jsonObject: object) tweets.append(tweet) } callback(tweets: tweets, error: nil) }, failure: { // Failure (operation: AFHTTPRequestOperation!, error: NSError!) -> Void in callback(tweets: nil, error: error) }) } func getHomeTimeline(since_id: String!, max_id: String!, callback: (tweets: [Tweet]!, error: NSError!) -> Void) { getTimeline("statuses/home_timeline.json", user_id: nil, since_id: since_id, max_id: max_id, callback: callback) } func getMentionsTimeline(since_id: String!, max_id: String!, callback: (tweets: [Tweet]!, error: NSError!) -> Void) { getTimeline("statuses/mentions_timeline.json", user_id: nil, since_id: since_id, max_id: max_id, callback: callback) } func getUserTimeline(user_id: String!, since_id: String!, max_id: String!, callback: (tweets: [Tweet]!, error: NSError!) -> Void) { getTimeline("statuses/user_timeline.json", user_id: user_id, since_id: since_id, max_id: max_id, callback: callback) } func getMyTimeline(since_id: String!, max_id: String!, callback: (tweets: [Tweet]!, error: NSError!) -> Void) { getUserTimeline(nil, since_id: since_id, max_id: max_id, callback: callback) } func getUserInfo(user_id: String!, callback: (user: User!, error: NSError!) -> Void) { var endpoint: String var parameters = [String: String]() if user_id == nil { endpoint = "account/verify_credentials.json" } else { endpoint = "users/show.json" parameters["user_id"] = user_id } GET(endpoint, parameters: parameters, success: { // Success (operation: AFHTTPRequestOperation!, response: AnyObject!) -> Void in var jsonObject = response as NSDictionary var user = User(jsonObject: jsonObject) callback(user: user, error: nil) }, failure: { // Failure (operation: AFHTTPRequestOperation!, error: NSError!) -> Void in callback(user: nil, error: error) }) } func sendPostRequest(endpoint: String, parameters: [String: String]!, callback: (error: NSError!) -> Void) { POST(endpoint, parameters: parameters, success: { // Success (operation: AFHTTPRequestOperation!, response: AnyObject!) -> Void in callback(error: nil) }, failure: { // Failure (operation: AFHTTPRequestOperation!, error: NSError!) -> Void in callback(error: error) }) } func tweet(status: String, callback: (error: NSError!) -> Void) { sendPostRequest("statuses/update.json", parameters: [ "status": status ], callback: callback) } func retweet(tweet_id: String, callback: (error: NSError!) -> Void) { sendPostRequest("statuses/retweet/\(tweet_id).json", parameters: nil, callback: callback) } func favorite(tweet_id: String, callback: (error: NSError!) -> Void) { sendPostRequest("favorites/create.json", parameters: [ "id": tweet_id ], callback: callback) } func unfavorite(tweet_id: String, callback: (error: NSError!) -> Void) { sendPostRequest("favorites/destroy.json", parameters: [ "id": tweet_id ], callback: callback) } }
mit
98680f547942be3e5aeb64bba94724fe
31.125
149
0.529854
4.783697
false
false
false
false
mariopavlovic/codility-lessons
codility-lessons/codility-lessons/Lesson3.swift
1
1121
import Foundation public class Lesson3 { public func solutionA(X : Int, _ Y : Int, _ D : Int) -> Int { guard X > 0 && Y > 0 && D > 0 else { return 0 } return Int(ceil(Double(Y - X) / Double(D))) } public func solutionB(A : [Int]) -> Int { guard A.count > 0 else { return 0 } let sum = A.reduce(0, combine: +) var min = Int.max for index in 0 ..< A.count - 1 { let sumFirstPart = A[0...index].reduce(0, combine: +) let sumSecondPart = sum - sumFirstPart let absoluteDiff = abs(sumFirstPart - sumSecondPart) if absoluteDiff < min { min = absoluteDiff } } return min } public func solutionC(inout A : [Int]) -> Int { guard A.count > 0 else { return 1 } A = A.sort() for (index, item) in A.enumerate() { if index + 1 != item { return index + 1 } } return A.count + 1 } }
mit
e0bd6caebee2ef9a81684e84ad5548f6
23.933333
65
0.43711
4.151852
false
false
false
false
mkaply/firefox-ios
Client/Frontend/Library/DownloadsPanel.swift
4
17112
/* 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 Shared import Storage private struct DownloadsPanelUX { static let WelcomeScreenPadding: CGFloat = 15 static let WelcomeScreenItemWidth = 170 static let HeaderHeight: CGFloat = 28 } struct DownloadedFile: Equatable { let path: URL let size: UInt64 let lastModified: Date var canShowInWebView: Bool { return MIMEType.canShowInWebView(mimeType) } var filename: String { return path.lastPathComponent } var fileExtension: String { return path.pathExtension } var formattedSize: String { return ByteCountFormatter.string(fromByteCount: Int64(size), countStyle: .file) } var mimeType: String { return MIMEType.mimeTypeFromFileExtension(fileExtension) } static public func ==(lhs: DownloadedFile, rhs: DownloadedFile) -> Bool { return lhs.path == rhs.path } } class DownloadsPanel: UIViewController, UITableViewDelegate, UITableViewDataSource, LibraryPanel, UIDocumentInteractionControllerDelegate { weak var libraryPanelDelegate: LibraryPanelDelegate? let profile: Profile var tableView = UITableView() private let events: [Notification.Name] = [.FileDidDownload, .PrivateDataClearedDownloadedFiles, .DynamicFontChanged] private lazy var emptyStateOverlayView: UIView = self.createEmptyStateOverlayView() private var groupedDownloadedFiles = DateGroupedTableData<DownloadedFile>() private var fileExtensionIcons: [String: UIImage] = [:] // MARK: - Lifecycle init(profile: Profile) { self.profile = profile super.init(nibName: nil, bundle: nil) events.forEach { NotificationCenter.default.addObserver(self, selector: #selector(notificationReceived), name: $0, object: nil) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) (navigationController as? ThemedNavigationController)?.applyTheme() } override func viewDidLoad() { super.viewDidLoad() view.addSubview(tableView) tableView.snp.makeConstraints { make in make.edges.equalTo(self.view) return } tableView.delegate = self tableView.dataSource = self tableView.register(TwoLineTableViewCell.self, forCellReuseIdentifier: "TwoLineTableViewCell") tableView.register(SiteTableViewHeader.self, forHeaderFooterViewReuseIdentifier: "SiteTableViewHeader") tableView.layoutMargins = .zero tableView.keyboardDismissMode = .onDrag tableView.accessibilityIdentifier = "DownloadsTable" tableView.cellLayoutMarginsFollowReadableWidth = false // Set an empty footer to prevent empty cells from appearing in the list. tableView.tableFooterView = UIView() } deinit { // The view might outlive this view controller thanks to animations; // explicitly nil out its references to us to avoid crashes. Bug 1218826. tableView.dataSource = nil tableView.delegate = nil } @objc func notificationReceived(_ notification: Notification) { DispatchQueue.main.async { self.reloadData() switch notification.name { case .FileDidDownload, .PrivateDataClearedDownloadedFiles: break case .DynamicFontChanged: if self.emptyStateOverlayView.superview != nil { self.emptyStateOverlayView.removeFromSuperview() } self.emptyStateOverlayView = self.createEmptyStateOverlayView() break default: // no need to do anything at all print("Error: Received unexpected notification \(notification.name)") break } } } func reloadData() { groupedDownloadedFiles = DateGroupedTableData<DownloadedFile>() let downloadedFiles = fetchData() for downloadedFile in downloadedFiles { groupedDownloadedFiles.add(downloadedFile, timestamp: downloadedFile.lastModified.timeIntervalSince1970) } fileExtensionIcons = [:] tableView.reloadData() updateEmptyPanelState() } private func fetchData() -> [DownloadedFile] { var downloadedFiles: [DownloadedFile] = [] do { let downloadsPath = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent("Downloads") let files = try FileManager.default.contentsOfDirectory(at: downloadsPath, includingPropertiesForKeys: nil, options: [.skipsHiddenFiles, .skipsPackageDescendants, .skipsSubdirectoryDescendants]) for file in files { let attributes = try FileManager.default.attributesOfItem(atPath: file.path) as NSDictionary let downloadedFile = DownloadedFile(path: file, size: attributes.fileSize(), lastModified: attributes.fileModificationDate() ?? Date()) downloadedFiles.append(downloadedFile) } } catch let error { print("Unable to get files in Downloads folder: \(error.localizedDescription)") return [] } return downloadedFiles.sorted(by: { a, b -> Bool in return a.lastModified > b.lastModified }) } private func deleteDownloadedFile(_ downloadedFile: DownloadedFile) -> Bool { do { try FileManager.default.removeItem(at: downloadedFile.path) return true } catch let error { print("Unable to delete downloaded file: \(error.localizedDescription)") } return false } private func shareDownloadedFile(_ downloadedFile: DownloadedFile, indexPath: IndexPath) { let helper = ShareExtensionHelper(url: downloadedFile.path, tab: nil) let controller = helper.createActivityViewController { completed, activityType in print("Shared downloaded file: \(completed)") } if let popoverPresentationController = controller.popoverPresentationController { guard let tableViewCell = tableView.cellForRow(at: indexPath) else { print("Unable to get table view cell at index path: \(indexPath)") return } popoverPresentationController.sourceView = tableViewCell popoverPresentationController.sourceRect = tableViewCell.bounds popoverPresentationController.permittedArrowDirections = .any } present(controller, animated: true, completion: nil) } private func iconForFileExtension(_ fileExtension: String) -> UIImage? { if let icon = fileExtensionIcons[fileExtension] { return icon } guard let icon = roundRectImageWithLabel(fileExtension, width: 29, height: 29) else { return nil } fileExtensionIcons[fileExtension] = icon return icon } private func roundRectImageWithLabel(_ label: String, width: CGFloat, height: CGFloat, radius: CGFloat = 5.0, strokeWidth: CGFloat = 1.0, strokeColor: UIColor = UIColor.theme.homePanel.downloadedFileIcon, fontSize: CGFloat = 9.0) -> UIImage? { UIGraphicsBeginImageContextWithOptions(CGSize(width: width, height: height), false, 0.0) let context = UIGraphicsGetCurrentContext() context?.setStrokeColor(strokeColor.cgColor) let rect = CGRect(x: strokeWidth / 2, y: strokeWidth / 2, width: width - strokeWidth, height: height - strokeWidth) let bezierPath = UIBezierPath(roundedRect: rect, cornerRadius: radius) bezierPath.lineWidth = strokeWidth bezierPath.stroke() let attributedString = NSAttributedString(string: label, attributes: [ .baselineOffset: -(strokeWidth * 2), .font: UIFont.systemFont(ofSize: fontSize), .foregroundColor: strokeColor ]) let stringHeight: CGFloat = fontSize * 2 let stringWidth = attributedString.boundingRect(with: CGSize(width: width, height: stringHeight), options: .usesLineFragmentOrigin, context: nil).size.width attributedString.draw(at: CGPoint(x: (width - stringWidth) / 2 + strokeWidth, y: (height - stringHeight) / 2 + strokeWidth)) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } // MARK: - Empty State private func updateEmptyPanelState() { if groupedDownloadedFiles.isEmpty { if emptyStateOverlayView.superview == nil { view.addSubview(emptyStateOverlayView) view.bringSubviewToFront(emptyStateOverlayView) emptyStateOverlayView.snp.makeConstraints { make in make.edges.equalTo(self.tableView) } } } else { emptyStateOverlayView.removeFromSuperview() } } fileprivate func createEmptyStateOverlayView() -> UIView { let overlayView = UIView() overlayView.backgroundColor = UIColor.theme.homePanel.panelBackground let logoImageView = UIImageView(image: UIImage.templateImageNamed("emptyDownloads")) logoImageView.tintColor = UIColor.Photon.Grey60 overlayView.addSubview(logoImageView) logoImageView.snp.makeConstraints { make in make.centerX.equalTo(overlayView) make.size.equalTo(60) // Sets proper top constraint for iPhone 6 in portait and for iPad. make.centerY.equalTo(overlayView).offset(LibraryPanelUX.EmptyTabContentOffset).priority(100) // Sets proper top constraint for iPhone 4, 5 in portrait. make.top.greaterThanOrEqualTo(overlayView).offset(50) } let welcomeLabel = UILabel() overlayView.addSubview(welcomeLabel) welcomeLabel.text = Strings.DownloadsPanelEmptyStateTitle welcomeLabel.textAlignment = .center welcomeLabel.font = DynamicFontHelper.defaultHelper.DeviceFontLight welcomeLabel.textColor = UIColor.theme.homePanel.welcomeScreenText welcomeLabel.numberOfLines = 0 welcomeLabel.adjustsFontSizeToFitWidth = true welcomeLabel.snp.makeConstraints { make in make.centerX.equalTo(overlayView) make.top.equalTo(logoImageView.snp.bottom).offset(DownloadsPanelUX.WelcomeScreenPadding) make.width.equalTo(DownloadsPanelUX.WelcomeScreenItemWidth) } return overlayView } fileprivate func downloadedFileForIndexPath(_ indexPath: IndexPath) -> DownloadedFile? { let downloadedFilesInSection = groupedDownloadedFiles.itemsForSection(indexPath.section) return downloadedFilesInSection[safe: indexPath.row] } // MARK: - TableView Delegate / DataSource func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "TwoLineTableViewCell", for: indexPath) as! TwoLineTableViewCell return configureDownloadedFile(cell, for: indexPath) } func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { if let header = view as? UITableViewHeaderFooterView { header.textLabel?.textColor = UIColor.theme.tableView.headerTextDark header.contentView.backgroundColor = UIColor.theme.tableView.headerBackground } } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { guard groupedDownloadedFiles.numberOfItemsForSection(section) > 0 else { return 0 } return DownloadsPanelUX.HeaderHeight } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { guard groupedDownloadedFiles.numberOfItemsForSection(section) > 0 else { return nil } let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: "SiteTableViewHeader") as? SiteTableViewHeader switch section { case 0: header?.textLabel?.text = Strings.TableDateSectionTitleToday case 1: header?.textLabel?.text = Strings.TableDateSectionTitleYesterday case 2: header?.textLabel?.text = Strings.TableDateSectionTitleLastWeek case 3: header?.textLabel?.text = Strings.TableDateSectionTitleLastMonth default: assertionFailure("Invalid Downloads section \(section)") } header?.showBorder(for: .top, !isFirstSection(section)) return header } func isFirstSection(_ section: Int) -> Bool { for i in 0..<section { if groupedDownloadedFiles.numberOfItemsForSection(i) > 0 { return false } } return true } func configureDownloadedFile(_ cell: UITableViewCell, for indexPath: IndexPath) -> UITableViewCell { if let downloadedFile = downloadedFileForIndexPath(indexPath), let cell = cell as? TwoLineTableViewCell { cell.setLines(downloadedFile.filename, detailText: downloadedFile.formattedSize) cell.imageView?.image = iconForFileExtension(downloadedFile.fileExtension) } return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) if let downloadedFile = downloadedFileForIndexPath(indexPath) { TelemetryWrapper.recordEvent(category: .action, method: .tap, object: .download, value: .downloadsPanel) if downloadedFile.mimeType == MIMEType.Calendar { let dc = UIDocumentInteractionController(url: downloadedFile.path) dc.delegate = self dc.presentPreview(animated: true) return } guard downloadedFile.canShowInWebView else { shareDownloadedFile(downloadedFile, indexPath: indexPath) return } libraryPanelDelegate?.libraryPanel(didSelectURL: downloadedFile.path, visitType: VisitType.typed) } } func numberOfSections(in tableView: UITableView) -> Int { return 4 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return groupedDownloadedFiles.numberOfItemsForSection(section) } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { // Intentionally blank. Required to use UITableViewRowActions } func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { let deleteTitle = Strings.DownloadsPanelDeleteTitle let shareTitle = Strings.DownloadsPanelShareTitle let delete = UITableViewRowAction(style: .destructive, title: deleteTitle, handler: { (action, indexPath) in if let downloadedFile = self.downloadedFileForIndexPath(indexPath) { if self.deleteDownloadedFile(downloadedFile) { self.tableView.beginUpdates() self.groupedDownloadedFiles.remove(downloadedFile) self.tableView.deleteRows(at: [indexPath], with: .right) self.tableView.endUpdates() self.updateEmptyPanelState() TelemetryWrapper.recordEvent(category: .action, method: .delete, object: .download, value: .downloadsPanel) } } }) let share = UITableViewRowAction(style: .normal, title: shareTitle, handler: { (action, indexPath) in if let downloadedFile = self.downloadedFileForIndexPath(indexPath) { self.shareDownloadedFile(downloadedFile, indexPath: indexPath) TelemetryWrapper.recordEvent(category: .action, method: .share, object: .download, value: .downloadsPanel) } }) share.backgroundColor = view.tintColor return [delete, share] } // MARK: - UIDocumentInteractionControllerDelegate func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController { return self } } extension DownloadsPanel: Themeable { func applyTheme() { emptyStateOverlayView.removeFromSuperview() emptyStateOverlayView = createEmptyStateOverlayView() updateEmptyPanelState() tableView.backgroundColor = UIColor.theme.tableView.rowBackground tableView.separatorColor = UIColor.theme.tableView.separator reloadData() } }
mpl-2.0
90d3dce917fc67387a3e016351bfa258
40.134615
247
0.674381
5.771332
false
false
false
false
NghiaTranUIT/Unofficial-Uber-macOS
UberGo/UberGo/UberMapView.swift
1
10122
// // UberMapView.swift // UberGo // // Created by Nghia Tran on 6/16/17. // Copyright © 2017 Nghia Tran. All rights reserved. // import Mapbox import MapboxDirections import RxSwift import UberGoCore protocol UberMapViewDelegate: class { func uberMapViewTimeEstimateForOriginAnnotation() -> TimeEstimateObj? } class UberMapView: MGLMapView { // MARK: - Variable weak var uberMapDelegate: UberMapViewDelegate? fileprivate var viewModel: MapViewModelProtocol! fileprivate let disposeBag = DisposeBag() // Origin fileprivate var originPoint: OriginAnnotation? // Destination fileprivate var destinationPoint: DestinationAnnotation? // Pickup place fileprivate var pickupPoint: PickupAnnotation? fileprivate var pickupPointSource: MGLShapeSource? fileprivate var pickupPointLine: PickupDashedLine? // Driver Place fileprivate var driverPoint: DriverAnnotation? // Visible Route fileprivate var visibleRoute: MGLPolyline? fileprivate var firstRouteCoordinate: CLLocationCoordinate2D? fileprivate var lastRouteCoordinate: CLLocationCoordinate2D? fileprivate var circleSource: MGLShapeSource? // MARK: - Initilization override init(frame: NSRect) { super.init(frame: frame) initCommon() // Hide all redundant components hideUnnecessaryUI() } required init?(coder: NSCoder) { super.init(coder: coder) } // MARK: - Private fileprivate func initCommon() { zoomLevel = 14 styleURL = MGLStyle.streetsStyleURL(withVersion: 9) delegate = self } public func setupViewModel(_ viewModel: MapViewModelProtocol) { self.viewModel = viewModel binding() } fileprivate func binding() { // Update Location on map viewModel.output.currentPlaceDriver .drive(onNext: {[weak self] placeObj in guard let `self` = self else { return } Logger.info("set current place \(placeObj)") self.addOriginPoint(placeObj) if let pickupPoint = self.pickupPoint { self.drawPickupRoute(pickupPoint.coordinate) } }) .addDisposableTo(disposeBag) // Draw map viewModel.output.selectedDirectionRouteObserver .subscribe(onNext: {[weak self] (route) in guard let `self` = self else { return } self.drawTripRoute(route) }) .addDisposableTo(disposeBag) viewModel.output.routeCurrentTrip .drive(onNext: {[weak self] (route) in guard let `self` = self else { return } self.drawTripRoute(route) }) .addDisposableTo(disposeBag) } // MARK: - Public func configureLayout(_ parentView: NSView, exitBtn: NSButton) { translatesAutoresizingMaskIntoConstraints = false parentView.addSubview(self, positioned: .below, relativeTo: exitBtn) edges(to: parentView) } fileprivate func addOriginPoint(_ placeObj: PlaceObj) { // Remove if need if let originPoint = originPoint { removeAnnotation(originPoint) self.originPoint = nil } originPoint = OriginAnnotation(placeObj: placeObj) addAnnotation(originPoint!) // CentralizeMap centralizeMap() } func addDestinationPlaceObj(_ placeObj: PlaceObj?) { // Remove if need if let currentPoint = destinationPoint { removeAnnotation(currentPoint) destinationPoint = nil } // Remove guard let placeObj = placeObj else { return } // Add destinationPoint = DestinationAnnotation(placeObj: placeObj) addAnnotation(destinationPoint!) // CentralizeMap centralizeMap() } func centralizeMap() { guard let annotations = annotations else { return } // Center if annotations.count == 1 { let centerPoint = annotations.first! setCenter(centerPoint.coordinate, animated: true) return } // Centeralize all visible annotations let edge = EdgeInsets(top: 200, left: 70, bottom: 70, right: 70) showAnnotations(annotations, edgePadding: edge, animated: true) } func updateCurrentTripLayout(_ tripObj: TripObj) { // Pickup // Hack to make sure Pickup point is at the begining point of visible route let pickup = tripObj.pickup if let firstRouteCoordinate = firstRouteCoordinate { pickup?.coordinate = firstRouteCoordinate } addPickupPoint(pickup) drawPickupRoute(pickup?.coordinate) // Driver addDriverPoint(tripObj) } fileprivate func addPickupPoint(_ pickupObj: PickupPointObj?) { // Remove if need if let pickupPoint = pickupPoint { removeAnnotation(pickupPoint) self.pickupPoint = nil } guard let pickupObj = pickupObj else { return } pickupPoint = PickupAnnotation(pickup: pickupObj) addAnnotation(pickupPoint!) } fileprivate func addDriverPoint(_ tripObj: TripObj) { // Remove if need if let driverPoint = driverPoint { removeAnnotation(driverPoint) self.driverPoint = nil } driverPoint = DriverAnnotation(tripObj: tripObj) if let lastRouteCoordinate = lastRouteCoordinate { driverPoint?.coordinate = lastRouteCoordinate } // Add if available if let driverPoint = driverPoint { addAnnotation(driverPoint) } } } // MARK: - Route extension UberMapView { fileprivate func drawTripRoute(_ route: Route?) { // Reset all Draw resetCurrentRoute() guard let route = route else { return } guard route.coordinateCount > 0 else { return } guard var routeCoordinates = route.coordinates else { return } // Convert the route’s coordinates into a polyline. let routeLine = MGLPolyline(coordinates: &routeCoordinates, count: route.coordinateCount) // Add the polyline to the map and fit the viewport to the polyline. addAnnotation(routeLine) visibleRoute = routeLine // Hack to guarantee the Driver Cars is at the end of Route // Look natural lastRouteCoordinate = route.coordinates?.first firstRouteCoordinate = route.coordinates?.last // Centerizal centralizeMap() } fileprivate func drawPickupRoute(_ pickup: CLLocationCoordinate2D?) { guard let pickup = pickup else { return } guard let originPoint = self.originPoint else { return } guard let style = self.style else { return } // Remove if need resetPickupDashedLine() var coordinates = [originPoint.coordinate, pickup] // Source let polyline = MGLPolylineFeature(coordinates: &coordinates, count: UInt(coordinates.count)) let source = MGLShapeSource(identifier: "pickup-dash-line", features: [polyline], options: nil) style.addSource(source) // Dashed line let dashedLine = PickupDashedLine.defaultDashedLine(with: source) style.addLayer(dashedLine) pickupPointLine = dashedLine pickupPointSource = source } } // MARK: - Reset extension UberMapView { public func resetAllData() { // Reset Route resetCurrentRoute() // Remove Annotation, except Origin removeAnnotations(annotationExclusiveOriginPoint()) // Remove dash self.resetPickupDashedLine() // Reset destinationPoint = nil pickupPoint = nil driverPoint = nil } public func resetCurrentRoute() { // Pick and Driver car lastRouteCoordinate = nil firstRouteCoordinate = nil // Visible Route if let visibleRoute = visibleRoute { removeAnnotation(visibleRoute) self.visibleRoute = nil } } fileprivate func resetPickupDashedLine() { guard let style = self.style else { return } if let pickupPointSource = pickupPointSource { style.removeSource(pickupPointSource) style.removeLayer(pickupPointLine!) self.pickupPointSource = nil self.pickupPointLine = nil } } fileprivate func annotationExclusiveOriginPoint() -> [MGLAnnotation] { guard let anno = annotations else { return [] } return anno.filter { ($0 as? OriginAnnotation) == nil } } } // MARK: - MGLMapViewDelegate extension UberMapView: MGLMapViewDelegate { func mapView(_ mapView: MGLMapView, annotationCanShowCallout annotation: MGLAnnotation) -> Bool { return true } func mapView(_ mapView: MGLMapView, alphaForShapeAnnotation annotation: MGLShape) -> CGFloat { return 0.8 } func mapView(_ mapView: MGLMapView, lineWidthForPolylineAnnotation annotation: MGLPolyline) -> CGFloat { return 4.0 } func mapView(_ mapView: MGLMapView, imageFor annotation: MGLAnnotation) -> MGLAnnotationImage? { if let obj = annotation as? UberAnnotationType { return obj.imageAnnotation } return nil } func mapView(_ mapView: MGLMapView, strokeColorForShapeAnnotation annotation: MGLShape) -> NSColor { return NSColor(hexString: "#52565f") } func mapView(_ mapView: MGLMapView, calloutViewControllerFor annotation: MGLAnnotation) -> NSViewController? { if let obj = annotation as? UberAnnotationType { if let annotation = annotation as? OriginAnnotation { let timeObj = uberMapDelegate?.uberMapViewTimeEstimateForOriginAnnotation() annotation.setupCallout(timeObj: timeObj) } return obj.calloutViewController } return nil } }
mit
7648971af0118cf3b61821413de3715c
27.82906
114
0.634055
5.30624
false
false
false
false
danielma/dotfiles
swift/sptf/sptf/sptf.playground/Contents.swift
1
862
import Foundation enum Weekday: Int { case Sunday = 1 case Monday case Tuesday case Wednesday case Thursday case Friday case Saturday } let calendar = Calendar(identifier: .gregorian) let now = Date() var dateComponents = calendar.dateComponents([.weekday], from: now) dateComponents.weekday = Weekday.Friday.rawValue let beginningOfDay = DateComponents(hour: 0) print(Weekday.Sunday.rawValue) print(Weekday.Friday.rawValue) print(dateComponents) //calendar.nextDate(after: now, matching: beginningOfDay, let weekDay = Weekday.Thursday let startDate = Calendar.current.nextDate(after: now, matching: DateComponents(hour: 0, weekday: weekDay.rawValue), matchingPolicy: .nextTime, direction: .backward) let endDate = Calendar.current.nextDate(after: now, matching: DateComponents(hour: 0, weekday: weekDay.rawValue), matchingPolicy: .nextTime)
mit
743a1261d76c456753ad2f18728b946b
29.785714
164
0.780742
4.104762
false
false
false
false
OSzhou/MyTestDemo
PerfectDemoProject(swift写服务端)/.build/checkouts/Perfect-HTTP.git--6392294032632002019/Sources/StaticFileHandler.swift
1
9364
// // StaticFileHandler.swift // PerfectLib // // Created by Kyle Jessup on 2016-01-06. // Copyright © 2016 PerfectlySoft. All rights reserved. // //===----------------------------------------------------------------------===// // // This source file is part of the Perfect.org open source project // // Copyright (c) 2015 - 2016 PerfectlySoft Inc. and the Perfect project authors // Licensed under Apache License v2.0 // // See http://perfect.org/licensing.html for license information // //===----------------------------------------------------------------------===// // import PerfectLib import PerfectNet import Foundation #if os(Linux) import LinuxBridge #endif import COpenSSL extension String.UTF8View { var sha1: [UInt8] { let bytes = UnsafeMutablePointer<UInt8>.allocate(capacity: Int(SHA_DIGEST_LENGTH)) defer { bytes.deallocate(capacity: Int(SHA_DIGEST_LENGTH)) } SHA1(Array<UInt8>(self), (self.count), bytes) var r = [UInt8]() for idx in 0..<Int(SHA_DIGEST_LENGTH) { r.append(bytes[idx]) } return r } } extension UInt8 { // same as String(self, radix: 16) // but outputs two characters. i.e. 0 padded var hexString: String { let s = String(self, radix: 16) if s.characters.count == 1 { return "0" + s } return s } } /// A web request handler which can be used to return static disk-based files to the client. /// Supports byte ranges, ETags and streaming very large files. public struct StaticFileHandler { let chunkedBufferSize = 1024*200 let documentRoot: String let allowResponseFilters: Bool /// Public initializer given a document root. /// If allowResponseFilters is false (which is the default) then the file will be sent in /// the most effecient way possible and output filters will be bypassed. public init(documentRoot: String, allowResponseFilters: Bool = false) { self.documentRoot = documentRoot self.allowResponseFilters = allowResponseFilters } /// Main entry point. A registered URL handler should call this and pass the request and response objects. /// After calling this, the StaticFileHandler owns the request and will handle it until completion. public func handleRequest(request: HTTPRequest, response: HTTPResponse) { var path = request.path if path[path.index(before: path.endIndex)] == "/" { path.append("index.html") // !FIX! needs to be configurable } let file = File(documentRoot + "/" + path) func fnf(msg: String) { response.status = .notFound response.appendBody(string: msg) // !FIX! need 404.html or some such thing response.completed() } guard file.exists else { return fnf(msg: "The file \(path) was not found.") } do { try file.open(.read) self.sendFile(request: request, response: response, file: file) } catch { return fnf(msg: "The file \(path) could not be opened \(error).") } } func shouldSkipSendfile(response: HTTPResponse) -> Bool { if self.allowResponseFilters { return true } // can not use sendfile for SSL requests if let sslCon = response.request.connection as? NetTCPSSL { return sslCon.usingSSL } return false } func sendFile(request: HTTPRequest, response: HTTPResponse, file: File) { response.addHeader(.acceptRanges, value: "bytes") if let rangeRequest = request.header(.range) { return self.performRangeRequest(rangeRequest: rangeRequest, request: request, response: response, file: file) } else if let ifNoneMatch = request.header(.ifNoneMatch) { let eTag = self.getETag(file: file) if ifNoneMatch == eTag { response.status = .notModified return response.next() } } let size = file.size let contentType = MimeType.forExtension(file.path.filePathExtension) response.status = .ok response.addHeader(.contentType, value: contentType) if allowResponseFilters { response.isStreaming = true } else { response.addHeader(.contentLength, value: "\(size)") } self.addETag(response: response, file: file) if case .head = request.method { return response.next() } // send out headers response.push { ok in guard ok else { file.close() return response.completed() } self.sendFile(remainingBytes: size, response: response, file: file) { ok in file.close() response.next() } } } func performRangeRequest(rangeRequest: String, request: HTTPRequest, response: HTTPResponse, file: File) { let size = file.size let ranges = self.parseRangeHeader(fromHeader: rangeRequest, max: size) if ranges.count == 1 { let range = ranges[0] let rangeCount = range.count let contentType = MimeType.forExtension(file.path.filePathExtension) response.status = .partialContent response.addHeader(.contentLength, value: "\(rangeCount)") response.addHeader(.contentType, value: contentType) response.addHeader(.contentRange, value: "bytes \(range.lowerBound)-\(range.upperBound-1)/\(size)") if case .head = request.method { return response.next() } file.marker = range.lowerBound // send out headers response.push { ok in guard ok else { file.close() return response.completed() } return self.sendFile(remainingBytes: rangeCount, response: response, file: file) { ok in file.close() response.next() } } } else if ranges.count > 0 { // !FIX! support multiple ranges response.status = .internalServerError return response.completed() } else { response.status = .badRequest return response.completed() } } func getETag(file: File) -> String { let eTagStr = file.path + "\(file.modificationTime)" let eTag = eTagStr.utf8.sha1 let eTagReStr = eTag.map { $0.hexString }.joined(separator: "") return eTagReStr } func addETag(response: HTTPResponse, file: File) { let eTag = self.getETag(file: file) response.addHeader(.eTag, value: eTag) } func sendFile(remainingBytes remaining: Int, response: HTTPResponse, file: File, completion: @escaping (Bool) -> ()) { if self.shouldSkipSendfile(response: response) { let thisRead = min(chunkedBufferSize, remaining) do { let bytes = try file.readSomeBytes(count: thisRead) response.appendBody(bytes: bytes) response.push { ok in if !ok || thisRead == remaining { // done completion(ok) } else { self.sendFile(remainingBytes: remaining - bytes.count, response: response, file: file, completion: completion) } } } catch { completion(false) } } else { let outFd = response.request.connection.fd.fd let inFd = file.fd #if os(Linux) let toSend = off_t(remaining) let result = sendfile(outFd, Int32(inFd), nil, toSend) if result >= 0 { let newRemaining = remaining - result if newRemaining == 0 { return completion(true) } self.sendFile(remainingBytes: newRemaining, response: response, file: file, completion: completion) } else if result == -1 && errno == EAGAIN { NetEvent.add(socket: outFd, what: .write, timeoutSeconds: 5.0) { socket, what in if case .write = what { self.sendFile(remainingBytes: remaining, response: response, file: file, completion: completion) } else { completion(false) } } } else { completion(false) } #else let offset = off_t(file.marker) var toSend = off_t(remaining) let result = sendfile(Int32(inFd), outFd, offset, &toSend, nil, 0) if result == 0 { completion(true) } else if result == -1 && errno == EAGAIN { file.marker = Int(offset) + Int(toSend) let newRemaining = remaining - Int(toSend) NetEvent.add(socket: outFd, what: .write, timeoutSeconds: 5.0) { socket, what in if case .write = what { self.sendFile(remainingBytes: newRemaining, response: response, file: file, completion: completion) } else { completion(false) } } } else { completion(false) } #endif } } // bytes=0-3/7-9/10-15 func parseRangeHeader(fromHeader header: String, max: Int) -> [Range<Int>] { let initialSplit = header.characters.split(separator: "=") guard initialSplit.count == 2 && String(initialSplit[0]) == "bytes" else { return [Range<Int>]() } let ranges = initialSplit[1] return ranges.split(separator: "/").flatMap { self.parseOneRange(fromString: String($0), max: max) } } // 0-3 // 0- func parseOneRange(fromString string: String, max: Int) -> Range<Int>? { let split = string.characters.split(separator: "-", omittingEmptySubsequences: false).map { String($0) } guard split.count == 2 else { return nil } if split[1].isEmpty { guard let lower = Int(split[0]), lower <= max else { return nil } return Range(uncheckedBounds: (lower, max)) } guard let lower = Int(split[0]), let upperRaw = Int(split[1]) else { return nil } let upper = Swift.min(max, upperRaw+1) guard lower <= upper else { return nil } return Range(uncheckedBounds: (lower, upper)) } }
apache-2.0
0c42d62586157634268776d982b122af
28.913738
121
0.636975
3.752705
false
false
false
false
Constantine-Fry/wunderlist.swift
Source/Shared/Endpoints/Uploads.swift
1
5104
// // Uploads.swift // Wunderlist // // Created by Constantine Fry on 05/12/14. // Copyright (c) 2014 Constantine Fry. All rights reserved. // import Foundation import MobileCoreServices /** Represents Upload endpoint on Wunderilst. https://developer.wunderlist.com/documentation/endpoints/upload */ public class Uploads: Endpoint { override var endpoint: String { return "uploads" } /** Perform three steps for fil uploading: 1. Requests upload URL. 2. Uploads file as on chunk. 3. Marks upload as finished. */ public func uploadFileAtURL(fileURL:NSURL, completionHandler: (uploadInfo: UploadInfo?, error: NSError?) -> Void) { let getURLTask = self.getUploadURLForFileAtURL(fileURL) { (uploadInfo, error) -> Void in if uploadInfo != nil { let uploadTask = self.uploadFile(fileURL, uploadInfo: uploadInfo!) { (uploaded, error) -> Void in if uploaded { let markTask = self.markUploadAsFinished(uploadInfo!.identifier) { (marked, error) -> Void in if marked { completionHandler(uploadInfo: uploadInfo, error: nil) } else { completionHandler(uploadInfo: nil, error: error) } } // self.markUploadAsFinishe markTask.start() } else { completionHandler(uploadInfo: nil, error: error) } } // self.uploadFile uploadTask.start() } else { completionHandler(uploadInfo: nil, error: error) } } // self.getUploadURLForFileAtURL getURLTask.start() } /* This is the first step: receive upload URL. */ public func getUploadURLForFileAtURL(fileURL:NSURL, completionHandler: (uploadInfo: UploadInfo?, error: NSError?) -> Void) -> SessionTask { var UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, fileURL.pathExtension as NSString?, nil) var tag = UTTypeCopyPreferredTagWithClass(UTI.takeUnretainedValue(), kUTTagClassMIMEType) var error: NSError? let properties = fileURL.resourceValuesForKeys([NSURLFileSizeKey], error: &error) as [String: UInt]? if properties == nil { fatalError("Can't read file size \(error)") } let contentType = tag.takeUnretainedValue() as String let fileName = fileURL.lastPathComponent as String! var parameters = [ "content_type" : contentType as String, "file_name" : fileName as String ] as [String: AnyObject] if let fileSize = properties?[NSURLFileSizeKey] { parameters["file_size"] = fileSize } return taskWithPath(nil, parameters: parameters, HTTPMethod: "POST", transformClosure: { UploadInfo(JSON: $0) }) { (result, error) -> Void in completionHandler(uploadInfo: result as UploadInfo?, error: error) } } /* This is the second step: actual upload. */ public func uploadFile(fileURL: NSURL, uploadInfo: UploadInfo, completionHandler: (uploaded: Bool, error: NSError?) -> Void) -> SessionUploadTask { return uploadTaskWithFileURL(fileURL, uploadInfo: uploadInfo) { (finished, error) -> Void in completionHandler(uploaded: finished, error: error) } } /** The last step: finilize uploading. */ public func markUploadAsFinished(uploadId: Int, completionHandler: (marked: Bool, error: NSError?) -> Void) -> SessionTask { let path = String(uploadId) let parameters = [ "state" : "finished" ] return taskWithPath(path, parameters: parameters, HTTPMethod: "PATCH", transformClosure: nil) { (result, error) -> Void in completionHandler(marked: error == nil, error: error) } } private func uploadTaskWithFileURL(fileURL: NSURL, uploadInfo: UploadInfo, completionHandler: ((fineshed: Bool, error: NSError?) -> Void)?) -> SessionUploadTask { if uploadInfo.uploadURL == nil { fatalError("Incorrect upload info") } let request = NSMutableURLRequest(URL: uploadInfo.uploadURL!) request.HTTPMethod = "PUT" request.setValue(uploadInfo.authorization, forHTTPHeaderField: "Authorization") request.setValue(uploadInfo.date, forHTTPHeaderField: "x-amz-date") request.setValue(uploadInfo.contentType, forHTTPHeaderField: "Content-Type") return SessionUploadTask( session: session, fileURL: fileURL, request: request, completionHandler: completionHandler) } }
bsd-2-clause
70410051cbb0f240d93bcabdd062a038
40.495935
166
0.582092
5.350105
false
false
false
false
deepestblue/Lipika_IME
HostingApp/LipikaIME/ViewController.swift
1
3350
/* * LipikaIME is a user-configurable phonetic Input Method Engine for Mac OS X. * Copyright (C) 2017 Ranganath Atreya * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. */ import Cocoa class ViewController: NSViewController { var util = InputSourceUtil() @IBOutlet weak var actionButton: NSButton! @IBAction func doAction(_ sender: NSButton) { let inputSources = util.getInputSources() if inputSources.count > 0 { _ = util.remove(inputSource: inputSources[0]) } // Delete existing input source and install the payload _ = installInputSource() } func installInputSource() -> Bool { let newBundlePath = Bundle.main.path(forResource: "LipikaInputSource", ofType: "app") let serviceName = "com.daivajnanam.LipikaIME" // First register a blessed job with launchd var authRef: AuthorizationRef? let createStatus = AuthorizationCreate(nil, nil, [], &authRef) if createStatus != errAuthorizationSuccess { NSLog("Authorization create failed with: %d", createStatus) return false } var authItem = AuthorizationItem(name: kSMRightBlessPrivilegedHelper, valueLength: 0, value: nil, flags: 0) var authRights = AuthorizationRights(count: 1, items: &authItem) let flags: AuthorizationFlags = [.interactionAllowed, .preAuthorize, .extendRights] let rightsStatus = AuthorizationCopyRights(authRef!, &authRights, nil, flags, nil) if rightsStatus != errAuthorizationSuccess { NSLog("Authorization copy rights failed with: %d", rightsStatus) return false } var errorRef: Unmanaged<CFError>? if !SMJobBless(kSMDomainSystemLaunchd, serviceName as CFString, authRef, &errorRef) { if let error = errorRef { NSLog("Unable to launch install helper due to: %@", error.takeRetainedValue().localizedDescription) } return false } // Now communicate with it using XPC let connection = NSXPCConnection(serviceName: serviceName) connection.remoteObjectInterface = NSXPCInterface(with: InstallProtocol.self) connection.resume() let installer = connection.remoteObjectProxyWithErrorHandler { (error) in NSLog("Remote proxy error: \(error)") } as! InstallProtocol installer.install(payloadPath: newBundlePath! as NSString) { (response) in NSLog("Remote response: \(response ?? "none")") } return true } override func viewDidLoad() { super.viewDidLoad() switch util.getType() { case .new: actionButton.title = "Install Lipika Input Source" case .upgrade: actionButton.title = "Upgrade Lipika Input Source" case .replace: actionButton.title = "Reinstall Lipika Input Source" case .downgrade: actionButton.title = "Newer Version already Installed" actionButton.isEnabled = false } } override var representedObject: Any? { didSet { // Update the view, if already loaded. } } }
gpl-3.0
6853b27c9dc2c514832eda405acce0b0
38.411765
115
0.645672
4.855072
false
false
false
false
noremac/Futures
FuturesPlayground.playground/Contents.swift
1
4298
/* The MIT License (MIT) Copyright (c) 2016 Cameron Pulsford 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 Futures func fibonacci(_ x: Int) -> Int { switch x { case 0, 1: return x default: return fibonacci(x - 1) + fibonacci(x - 2) } } // Create a Future. let f1 = Future { _ in .success(fibonacci(16)) } // Get the Future's value. Blocks until the Future's work has completed. let v1 = f1.value.successValue let e1 = f1.value.error // There is a shorthand for getting a Future's success and error values: let v2 = f1.successValue let e2 = f1.error // The same as `value`, but lets you specify a maximum amount of time to block before giving up. if let fib16 = f1.value(withTimeout: 10)?.successValue { print(fib16) // 987 } // Instead of blocking for a value, you may set optional `onSuccess` and `onError` blocks. let f2 = Future { _ in .success(fibonacci(16)) }.onSuccess { value in // handle value }.onError { error in // handle error } // You may set a completion queue for the `onSuccess` and `onError` blocks as well. The default value is the main queue. f2.completionQueue = DispatchQueue.main // You may set a timeout on a Future as well. If the Future does not complete within the specified timeout, an error will be delivered. f2.timeout = 10 // Futures may be invalidated. f2.invalidate(NSError(domain: NSPOSIXErrorDomain, code: 0, userInfo: nil)) // Futures may be canceled. f1.cancel() // You may also create Promises. // Promises mostly have the same API as Futures. `value/onSuccess/onError/timeout/completionQueue/etc` all work the same. The notable difference is that Promises currently lack cancelation. let p1 = Promise<Int>() // To fulfill a Promise, call the `deliver` or `invalidate` methods. p1.deliver(fibonacci(16)) // Future's may be canceled, and can deliver values indicating either success or an error. // However, there is a shortcut method for creating un-cancel-able, un-fail-able Futures. (Though, they may still be manually invalidated.) let f3 = Future.success { fibonacci(16) } // Normally, a Future's work begins immediately upon creation. // If you'd prefer to delay the work, use the `startDelay` parameter. // If a delayed Future's value is requested, work will begin immediately if necessary. // // Note: The `startDelay` parameter does not currently play nice with the `timeout` parameter. Future.success(startDelay: 5) { fibonacci(16) }.onSuccess { print($0) // 987 } // `FutureCache` is a (hopefully) nice way to store related/expensive Futures. let futureCache = FutureCache<Int>() futureCache.add("fib16", future: Future.success { fibonacci(16) }) futureCache.add("fib17", future: Future.success { fibonacci(17) }) // later... let expensiveResult = futureCache.value(forKey: "fib16")! print(expensiveResult) let a1 = AsyncValueCache<NSData> { completion in let session = URLSession(configuration: .default) session.dataTask(with: URL(string: "https://google.com")!, completionHandler: { (data, _, error) in if let error = error { completion(.error(error)) } else { completion(.success(data ?? Data())) } }).resume() } a1.value { value in print(value.successValue) }
mit
6d9efaa6c5c5b11bca4469e550ec113b
34.520661
189
0.722894
3.972274
false
false
false
false
TouchInstinct/LeadKit
Sources/Extensions/UIColor/UIColor+Hex.swift
1
5269
// // Copyright (c) 2017 Touch Instinct // // 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 UIColor { /** the shorthand three-digit hexadecimal representation of color. #RGB defines to the color #RRGGBB. - parameter hex3: Three-digit hexadecimal value. - parameter alpha: 0.0 - 1.0. The default is 1.0. */ convenience init(hex3: UInt16, alpha: CGFloat = 1) { let red = CGFloat((hex3 & 0xF00) >> 8) / 0xF let green = CGFloat((hex3 & 0x0F0) >> 4) / 0xF let blue = CGFloat((hex3 & 0x00F) >> 0) / 0xF self.init(red: red, green: green, blue: blue, alpha: alpha) } /** the shorthand four-digit hexadecimal representation of color with alpha. #RGBA defines to the color #RRGGBBAA. - parameter hex4: Four-digit hexadecimal value. */ convenience init(hex4: UInt16) { let red = CGFloat((hex4 & 0xF000) >> 12) / 0xF let green = CGFloat((hex4 & 0x0F00) >> 8) / 0xF let blue = CGFloat((hex4 & 0x00F0) >> 4) / 0xF let alpha = CGFloat((hex4 & 0x000F) >> 0) / 0xF self.init(red: red, green: green, blue: blue, alpha: alpha) } /** the six-digit hexadecimal representation of color of the form #RRGGBB. - parameter hex6: Six-digit hexadecimal value. - parameter alpha: alpha: 0.0 - 1.0. The default is 1.0. */ convenience init(hex6: UInt32, alpha: CGFloat = 1) { let red = CGFloat((hex6 & 0xFF0000) >> 16) / 0xFF let green = CGFloat((hex6 & 0x00FF00) >> 8) / 0xFF let blue = CGFloat((hex6 & 0x0000FF) >> 0) / 0xFF self.init(red: red, green: green, blue: blue, alpha: alpha) } /** the six-digit hexadecimal representation of color with alpha of the form #RRGGBBAA. - parameter hex8: Eight-digit hexadecimal value. */ convenience init(hex8: UInt32) { let red = CGFloat((hex8 & 0xFF000000) >> 24) / 0xFF let green = CGFloat((hex8 & 0x00FF0000) >> 16) / 0xFF let blue = CGFloat((hex8 & 0x0000FF00) >> 8) / 0xFF let alpha = CGFloat((hex8 & 0x000000FF) >> 0) / 0xFF self.init(red: red, green: green, blue: blue, alpha: alpha) } /** convenience failable initializer which creates an instance with given hex color values if string has a correct format - parameter hexString: hex string with red green and blue values (can have `#` sign) - parameter alpha: alpha component used if not given in hexString */ convenience init?(hexString: String, alpha: CGFloat = 1) { let hexStr: String if hexString.hasPrefix("#") { hexStr = String(hexString[hexString.index(hexString.startIndex, offsetBy: 1)...]) } else { hexStr = hexString } let charactersCount = hexStr.count switch charactersCount { case 3, 4: if let hex = UInt16(hexStr, radix: 16) { if charactersCount == 3 { self.init(hex3: hex, alpha: alpha) } else { self.init(hex4: hex) } } else { return nil } case 6, 8: if let hex = UInt32(hexStr, radix: 16) { if charactersCount == 6 { self.init(hex6: hex, alpha: alpha) } else { self.init(hex8: hex) } } else { return nil } default: return nil } } } public extension UIColor { /// Hex representation of UIColor as String var hexString: String { var red: CGFloat = 0 var green: CGFloat = 0 var blue: CGFloat = 0 var alpha: CGFloat = 0 getRed(&red, green: &green, blue: &blue, alpha: &alpha) let intRepresentation: Int if alpha == 1 { intRepresentation = Int(red * 255) << 16 | Int(green * 255) << 8 | Int(blue * 255) } else { intRepresentation = Int(red * 255) << 24 | Int(green * 255) << 16 | Int(blue * 255) << 8 | Int(alpha * 255) } return String(intRepresentation, radix: 16) } }
apache-2.0
3af5ff61eeafd3b8c88105aa0bd3dc89
33.89404
122
0.595559
3.994693
false
false
false
false
MartinLep/Swift_Live
SwiftLive/SwiftLive/Classes/Main/View/CollectionBaseCell.swift
1
1161
// // CollectionBaseCell.swift // SwiftLive // // Created by MartinLee on 17/4/11. // Copyright © 2017年 MartinLee. All rights reserved. // import UIKit class CollectionBaseCell: UICollectionViewCell { //控件属性 @IBOutlet weak var iconImageView: UIImageView! @IBOutlet weak var onlineBtn: UIButton! @IBOutlet weak var nickName: UILabel! //定义模型 var anchor : AnchorModel? { didSet{ //检验模型是否有值 guard let anchor = anchor else { return } var onLineStr : String = "" if anchor.online>=10000 { onLineStr = "\(Int(anchor.online / 10000))万人在线" }else{ onLineStr = "\(anchor.online)在线" } onlineBtn.setTitle(onLineStr, for: .normal) //昵称的显示 nickName.text = anchor.nickname // 3.设置封面图片 guard let iconURL = URL(string: anchor.vertical_src) else { return } iconImageView.kf.setImage(with: iconURL) } } }
mit
1186df5756c11c997b240a8e47f16b47
23.818182
80
0.53022
4.686695
false
false
false
false
jordane-quincy/M2_DevMobileIos
JSONProject/Demo/JsonModel.swift
1
3484
// // JsonModel.swift // Demo // // Created by MAC ISTV on 19/03/2017. // Copyright © 2017 UVHC. All rights reserved. // import Foundation enum SerializationError: Error { case missing(String) case invalid(String, Any) } enum Payment: String { case creditCard, bankTransfer, paypal } struct JsonModel { let title: String let description: String let icon: String let commonFields: Set<CommonField> let paymentWays: Set<Payment> let offers: Set<Offer> init?(jsonContent: [String: Any]) throws { guard let title = jsonContent["title"] as? String else { throw SerializationError.missing("title") } guard let description = jsonContent["description"] as? String else { throw SerializationError.missing("description") } let icon = jsonContent["icon"] as? String // Extract and validate payments guard let paymentWaysJSON = jsonContent["paymentWays"] as? [String] else { throw SerializationError.missing("paymentWays") } var paymentWays: Set<Payment> = [] for paymentString in paymentWaysJSON { guard let payment = Payment(rawValue: paymentString) else { throw SerializationError.invalid("payment", paymentString) } paymentWays.insert(payment) } // Extract and validate commonFields guard let commonFieldsJsonArray = jsonContent["commonFields"] as? [[String: Any]] else { throw SerializationError.missing("commonFields") } //print("commonFieldsJsonArray : \(commonFieldsJsonArray)")//FIXME: pour debug uniquement var commonFields: Set<CommonField> = [] for commonFieldJsonElement in commonFieldsJsonArray { //print("commonFieldJsonElement : \(commonFieldJsonElement)")//FIXME: pour debug uniquement do { guard let commonField = try CommonField(jsonContent: commonFieldJsonElement) else { throw SerializationError.invalid("commonField", commonFieldJsonElement) } commonFields.insert(commonField) } catch let serializationError { print(serializationError) } } // Extract and validate commonFields guard let offersJsonArray = jsonContent["offers"] as? [[String: Any]] else { throw SerializationError.missing("offers") } //print("offersJsonArray : \(offersJsonArray)")//FIXME: pour debug uniquement var offers: Set<Offer> = [] for offerJsonElement in offersJsonArray { //print("commonFieldJsonElement : \(commonFieldJsonElement)")//FIXME: pour debug uniquement do { guard let offer = try Offer(jsonContent: offerJsonElement) else { throw SerializationError.invalid("offer", offerJsonElement) } offers.insert(offer) } catch let serializationError { print(serializationError) } } //assignation self.title = title self.description = description self.icon = icon ?? "" self.commonFields = commonFields self.paymentWays = paymentWays self.offers = offers } }
mit
8062ab017ab49d9511588d0d5a9cea6d
33.485149
103
0.589722
5.50237
false
false
false
false
gifsy/Gifsy
Frameworks/Bond/BondTests/ObservableArrayEventTests.swift
13
3151
// // ObservableArrayOperationTests.swift // Bond // // Created by Srđan Rašić on 06/08/15. // Copyright © 2015 Srdan Rasic. All rights reserved. // import XCTest @testable import Bond enum Letters { case A case B case C case D } func ==(lsh: [ObservableArrayEventChangeSet], rhs: [ObservableArrayEventChangeSet]) -> Bool { if lsh.count != rhs.count { return false } else { for (l, r) in zip(lsh, rhs) { if !(l == r) { return false } } return true } } class ObservableArrayEventTests: XCTestCase { // Assuming change set has at most three elements in // the following order: .Inserts, .Updates, .Deletes func testChangeSetInsert() { let operations: [ObservableArrayOperation<Letters>] = [ .Insert(elements: [.A, .B, .C], fromIndex: 1) ] let changeSets = changeSetsFromBatchOperations(operations) XCTAssert(changeSets == [.Inserts([1, 2, 3])]) } func testChangeSetDelete() { let operations: [ObservableArrayOperation<Letters>] = [ .Remove(range: 1..<4) ] let changeSets = changeSetsFromBatchOperations(operations) XCTAssert(changeSets == [.Deletes([1, 2, 3])]) } func testChangeSetUpdate() { let operations: [ObservableArrayOperation<Letters>] = [ .Update(elements: [.A, .B, .C], fromIndex: 1) ] let changeSets = changeSetsFromBatchOperations(operations) XCTAssert(changeSets == [.Updates([1, 2, 3])]) } func testChangeSetInsertDeleteOverlapping() { let operations: [ObservableArrayOperation<Letters>] = [ .Insert(elements: [.A, .B, .C], fromIndex: 1), .Remove(range: 1...2) ] let changeSets = changeSetsFromBatchOperations(operations) XCTAssert(changeSets == [.Inserts([1])]) } func testChangeSetInsertDeleteNonOverlapping1() { let operations: [ObservableArrayOperation<Letters>] = [ .Insert(elements: [.A, .B, .C], fromIndex: 1), .Remove(range: 0..<1) ] let changeSets = changeSetsFromBatchOperations(operations) XCTAssert(changeSets == [.Inserts([0, 1, 2]), .Deletes([0])]) } func testChangeSetInsertDeleteNonOverlapping2() { let operations: [ObservableArrayOperation<Letters>] = [ .Insert(elements: [.A, .B, .C], fromIndex: 1), .Remove(range: 5...6) ] let changeSets = changeSetsFromBatchOperations(operations) XCTAssert(changeSets == [.Inserts([1, 2, 3]), .Deletes([5, 6])]) } func testChangeSetDeleteInsertOverlapping() { let operations: [ObservableArrayOperation<Letters>] = [ .Remove(range: 1...2), .Insert(elements: [.A, .B, .C], fromIndex: 1) ] let changeSets = changeSetsFromBatchOperations(operations) XCTAssert(changeSets == [.Inserts([3]), .Updates([1, 2])]) } func testChangeSetDeleteInsertNonOverlapping1() { let operations: [ObservableArrayOperation<Letters>] = [ .Remove(range: 0...1), .Insert(elements: [.A, .B, .C], fromIndex: 2) ] let changeSets = changeSetsFromBatchOperations(operations) XCTAssert(changeSets == [.Inserts([2, 3, 4]), .Deletes([0, 1])]) } }
apache-2.0
b077a25fda0425411a9fb5ef64cbf4fd
26.849558
93
0.638704
4.151715
false
true
false
false
eleks/digital-travel-book
src/Swift/Weekend In Lviv/ViewControllers/Photo Gallery/WLPhotoGalleryVCSw.swift
1
4997
// // WLPhotoGalleryVCSw.swift // Weekend In Lviv // // Created by Admin on 13.06.14. // Copyright (c) 2014 rnd. All rights reserved. // import UIKit class ImageViewController:UIViewController { // Instance variables var index:UInt = 0 var imageView:UIImageView? = nil var _imagePath:String = "" var imagePath:String { get { return _imagePath } set (imagePath) { _imagePath = imagePath if let imageView_ = imageView? { imageView_.removeFromSuperview() } self.imageView = UIImageView(image: UIImage(contentsOfFile: self.imagePath)) self.imageView!.frame = self.view.bounds self.imageView!.contentMode = UIViewContentMode.ScaleAspectFit self.view = self.imageView! } } } class WLPhotoGalleryVCSw: UIViewController, UIScrollViewDelegate, UIPageViewControllerDataSource { // Outlets @IBOutlet weak var scrollImages:UIScrollView? @IBOutlet weak var lblSwipe:UILabel? @IBOutlet weak var btnClose:UIButton? // Instance variables var imagePathList: [String] = [] var selectedImageIndex:UInt = 0 var pageController:UIPageViewController? = nil // Instance methods override func viewDidLoad() { super.viewDidLoad() self.lblSwipe!.font = WLFontManager.sharedManager.gentiumItalic15 self.pageController = UIPageViewController(transitionStyle: UIPageViewControllerTransitionStyle.Scroll, navigationOrientation: UIPageViewControllerNavigationOrientation.Horizontal, options:nil) let initialViewController:UIViewController? = self.viewControllerAtIndex(Int(self.selectedImageIndex)) if let initVC_ = initialViewController? { self.pageController!.setViewControllers([initVC_], direction:UIPageViewControllerNavigationDirection.Forward, animated:false, completion:nil) } self.addChildViewController(self.pageController!) self.view.addSubview(self.pageController!.view) self.pageController!.didMoveToParentViewController(self) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.pageController!.dataSource = self self.pageController!.view.frame = self.view.bounds self.pageController!.view.frame = self.scrollImages!.frame self.view.addSubview(self.pageController!.view) self.view.bringSubviewToFront(self.btnClose!) self.btnClose!.enabled = true self.view.bringSubviewToFront(self.lblSwipe!) self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: UIView()) } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) NSNotificationCenter.defaultCenter().postNotificationName("ShowPlayer", object:nil) } override func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.LightContent } /* Unavailable in Swift override func shouldAutorotateToInterfaceOrientation(toInterfaceOrientation:UIInterfaceOrientation) -> Bool { return true }*/ func btnMenuTouch(sender:AnyObject) { self.mm_drawerController!.toggleDrawerSide(MMDrawerSide.Left, animated:true, completion:nil) } //#pragma mark - Page view controller delegate func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? { let imageController = viewController as ImageViewController return self.viewControllerAtIndex(Int(imageController.index) - 1) } func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? { let imageController = viewController as ImageViewController return self.viewControllerAtIndex(Int(imageController.index) + 1) } func viewControllerAtIndex(index:Int) -> ImageViewController? { var photoVC:ImageViewController? = nil if index >= 0 && index < self.imagePathList.count { photoVC = ImageViewController() photoVC!.imagePath = self.imagePathList[Int(index)] photoVC!.index = UInt(index) } return photoVC } //#pragma mark - Page view controller data source // Actions @IBAction func btnCloseTouch(sender:AnyObject) { self.navigationController!.popViewControllerAnimated(true) } }
mit
907f9ae82f9085bf416c68046a57f969
32.763514
161
0.644187
5.934679
false
false
false
false
proversity-org/edx-app-ios
Source/VersionParser.swift
2
1573
// // VersionParser.swift // edX // // Created by Saeed Bashir on 7/6/17. // Copyright © 2017 edX. All rights reserved. // import Foundation class Version { private var numbers:[String] = [] /* The first three present dot-separated tokens will be parsed as major, minor, and patch version numbers respectively, and any further tokens will be discarded. */ init(version: String) { numbers = version.components(separatedBy: ".") } func getMajorVersion() -> Int { return getVersion(at: 0) } func getMinorVersion() -> Int { return getVersion(at: 1) } func getPatchVersion() -> Int { return getVersion(at: 2) } // Returns the version number at the provided index. // We are assuming every part of version as Int for calculation // 0 will be returned for non supported values private func getVersion(at index: Int) -> Int { return (index < numbers.count) ? Int(numbers[index]) ?? 0 : 0 } func isNMinorVersionsDiff(otherVersion: Version, minorVersionDiff: Int) -> Bool { // Difference in major version is consider to be valid for any minor versions difference return (getMajorVersion() - otherVersion.getMajorVersion() >= 1) || (getMinorVersion() - otherVersion.getMinorVersion() >= minorVersionDiff) } func isMajorMinorVersionsSame(otherVersion: Version) -> Bool { return getMajorVersion() == otherVersion.getMajorVersion() && getMinorVersion() == otherVersion.getMinorVersion() } }
apache-2.0
1700ec58fd94343c1329b6673c6d2152
31.081633
148
0.650763
4.453258
false
false
false
false
hzy87email/actor-platform
actor-apps/app-ios/ActorApp/View/Cells/BasicCell.swift
7
1237
// // Copyright (c) 2014-2015 Actor LLC. <https://actor.im> // import Foundation class BasicCell : UITableViewCell { let separatorView = TableViewSeparator(color: MainAppTheme.list.separatorColor) let separatorPadding: Int init(reuseIdentifier:String, separatorPadding: Int) { self.separatorPadding = separatorPadding super.init(style: UITableViewCellStyle.Default, reuseIdentifier: reuseIdentifier) self.contentView.addSubview(separatorView); } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { self.separatorPadding = 0 super.init(style: UITableViewCellStyle.Default, reuseIdentifier: reuseIdentifier) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func hideSeparator(hidden: Bool) { separatorView.hidden = hidden } override func layoutSubviews() { super.layoutSubviews() let width = self.contentView.frame.width; let height = self.contentView.frame.height; separatorView.frame = CGRectMake(CGFloat(separatorPadding), CGFloat(height - 0.5), width - CGFloat(separatorPadding), CGFloat(0.5)); } }
mit
65d44d94aee5f83fc8b7a6257a3010cb
31.578947
140
0.689572
4.948
false
false
false
false
PatMurrayDEV/WWDC17
PatMurrayWWDC17.playground/Sources/MusicPlayer.swift
1
4875
// Import all the things! import Foundation import AVFoundation public class SoundPlayer { let engine = AVAudioEngine() let player = AVAudioPlayerNode() let sampler = AVAudioUnitSampler() let fontPath = Bundle.main.path(forResource: "FreeFont", ofType: "sf2") public init?() { let font = NSURL.fileURL(withPath: fontPath!) engine.attach(player) engine.connect(player, to: engine.mainMixerNode, format: engine.mainMixerNode.outputFormat(forBus: 0)) engine.attach(sampler) engine.connect(sampler, to: engine.outputNode, format: nil) do { try engine.start() } catch let e { print(e) return nil } do { try sampler.loadSoundBankInstrument(at: font, program: 0, bankMSB: UInt8(kAUSampler_DefaultMelodicBankMSB), bankLSB: UInt8(kAUSampler_DefaultBankLSB)) } catch let e { print(e) return nil } } public func start(note: UInt8, velocity: UInt8 = 64) { sampler.startNote(note, withVelocity: velocity, onChannel: 0) } public func stop(note: UInt8) { sampler.stopNote(note, onChannel: 0) } public func changePressureTo(_ pressure: UInt8) { sampler.sendPressure(pressure, onChannel: 0) } public func changePitchTo(_ pitch: UInt16) { sampler.sendPitchBend(pitch, onChannel: 0) } public func stopAll() { for key in 1...127 { self.stop(note: UInt8(key)) } } let keys = [ // In the Key of C Major // Thus no black notes 4 : 40 , // E 8 : 41 , // F 12 : 43 , // G 16 : 45 , // A 20 : 47 , // B 24 : 48 , // C 28 : 50 , // D 32 : 52 , // E 36 : 53 , // F 40 : 55 , // G 44 : 57 , // A 48 : 59 , // B 52 : 60 , // Middle C 56 : 62 , // D 60 : 64 , // E 64 : 65 , // F 68 : 67 , // G 72 : 69 , // A 76 : 71 , // B 80 : 72 , // C 84 : 74 , // D 88 : 76 , // E 92 : 77 , // F 96 : 79 , // G 100 : 81 , // A ] // Arrays to hold notes var nowplaying = [UInt8]() func roundTo(x : Double) -> Int { return Int(ceil(Double(4 * Int(round(x / 4.0))))) } public func playRow(_ row: [UInt8]) { var upnext = [UInt8]() let rowCount = Double(row.count/2) for (index, note) in row.enumerated() { if note > 1 { let per = (Double(index) / rowCount) * 100.0 let perRounded = self.roundTo(x: per) if let key = keys[100-perRounded] { upnext.append(UInt8(key)) } } } playNotes(next: upnext) } // Play notes public func playNotes(next: [UInt8]) { let nextUnique = Array(Set(next)) // Notes to be added var addNotes = [UInt8]() // Notes to be sustained var sustainedNotes = [UInt8]() // Notes that need to play next for note in nextUnique { if !nowplaying.contains(note) { addNotes.append(note) } else { sustainedNotes.append(note) } } //Fail Safe if addNotes.count + sustainedNotes.count > 20 { sustainedNotes.removeAll() } // Notes that need to be stopped let removeNotes = Array(Set(nowplaying).subtracting(sustainedNotes)) for note in removeNotes { self.stop(note: note) } // Notes that need to be added for note in addNotes { self.start(note: note) } sustainedNotes.append(contentsOf: addNotes) self.nowplaying = sustainedNotes } // Timer vars var timer = Timer() var counter = 0 // Play all the arrays taking a time and returning a completion handler public func playArrays(_ array: [[UInt8]], time : Double = 20.0,completion: @escaping (_ : Bool) -> Void) { counter = 0 let interval = time/50.0 timer = Timer.init(timeInterval: interval, repeats: true, block: { (timer) in if self.counter < array.count { self.playRow(array[self.counter]) self.counter = self.counter + 1 completion(false) } else { timer.invalidate() completion(true) } }) RunLoop.current.add(timer, forMode: .commonModes) } }
mit
2e29597cd4da159e3c161ef53ee36339
25.351351
162
0.486564
3.976346
false
false
false
false
JohnCoates/Aerial
Aerial/Source/Models/AerialVideo.swift
1
7838
// // AerialVideo.swift // Aerial // // Created by John Coates on 10/23/15. // Copyright © 2015 John Coates. All rights reserved. // import Cocoa import AVFoundation enum Manifests: String { case tvOS10 = "tvos10.json", tvOS11 = "tvos11.json", tvOS12 = "tvos12.json", tvOS13 = "tvos13.json", tvOS13Strings = "TVIdleScreenStrings13.bundle", customVideos = "customvideos.json" } final class AerialVideo: CustomStringConvertible, Equatable { static func ==(lhs: AerialVideo, rhs: AerialVideo) -> Bool { return lhs.id == rhs.id // TODO && lhs.url1080pHEVC == rhs.url1080pHEVC } let id: String let name: String let secondaryName: String let type: String let timeOfDay: String let scene: SourceScene var urls: [VideoFormat: String] let source: Source // var sources: [Manifests] let poi: [String: String] let communityPoi: [String: String] var duration: Double var arrayPosition = 1 var contentLength = 0 var contentLengthChecked = false var isVertical: Bool var isAvailableOffline: Bool { return VideoCache.isAvailableOffline(video: self) } // MARK: - Public getter var url: URL { return getClosestAvailable(wanted: PrefsVideos.videoFormat) } // Returns the closest video we have in the manifests private func getClosestAvailable(wanted: VideoFormat) -> URL { if urls[wanted] != "" { return getURL(string: urls[wanted]!) } else { // Fallback if urls[.v4KHEVC] != "" { return getURL(string: urls[.v4KHEVC]!) } else if urls[.v1080pHEVC] != "" { return getURL(string: urls[.v1080pHEVC]!) } else if urls[.v1080pH264] != "" { // Last resort return getURL(string: urls[.v1080pH264]!) } else { return getURL(string: urls[.v4KHDR]!) } } } private func getURL(string: String) -> URL { if string.starts(with: "/") { return URL(fileURLWithPath: string) } else { return URL(string: string)! } } // swiftlint:disable cyclomatic_complexity // MARK: - Init init(id: String, name: String, secondaryName: String, type: String, timeOfDay: String, scene: String, urls: [VideoFormat: String], source: Source, poi: [String: String], communityPoi: [String: String] ) { self.id = id // We override names for known space videos if SourceInfo.seaVideos.contains(id) { self.name = "Sea" if secondaryName != "" { self.secondaryName = secondaryName } else { self.secondaryName = name } } else if SourceInfo.spaceVideos.contains(id) { self.name = "Space" if secondaryName != "" { self.secondaryName = secondaryName } else { self.secondaryName = name } } else { // We align to the new jsons... if name == "New York City" { self.name = "New York" } else { self.name = name } self.secondaryName = secondaryName // We may have a secondary name from our merges too now ! } self.type = type // We override timeOfDay based on our own list if let val = SourceInfo.timeInformation[id] { self.timeOfDay = val } else { self.timeOfDay = timeOfDay } switch scene { case "sea": self.scene = .sea case "space": self.scene = .space case "city": self.scene = .city case "countryside": self.scene = .countryside case "beach": self.scene = .beach default: self.scene = .nature } self.urls = urls self.source = source // self.sources = [manifest] self.poi = poi self.communityPoi = communityPoi // Default stuff, we double check those below self.duration = 0 self.isVertical = false updateDuration() // We need to have the video duration } func updateDuration() { // We need to retrieve video duration from the cached files. // This is a workaround as currently, the VideoCache infrastructure // relies on AVAsset with an external URL all the time, even when // working on a cached copy which makes the native duration retrieval fail // // And... we also check the orientation now too ;) let fileManager = FileManager.default if let duration = PrefsVideos.durationCache[self.id] { // debugLog("Using cache duration : \(duration)") self.duration = duration return } // With custom videos, we may already store the local path // If so, check it if self.url.absoluteString.starts(with: "file") { if fileManager.fileExists(atPath: self.url.path) { let asset = AVAsset(url: self.url) self.duration = CMTimeGetSeconds(asset.duration) self.isVertical = asset.isVertical() } else { errorLog("Custom video is missing : \(self.url.path)") self.duration = 0 } } else { // If not, iterate through all possible versions to see if any is cached for format in VideoFormat.allCases { // swiftlint:disable:next for_where if urls[format] != "" { let path = VideoList.instance.localPathFor(video: self) if fileManager.fileExists(atPath: path) { let asset = AVAsset(url: URL(fileURLWithPath: path)) self.duration = CMTimeGetSeconds(asset.duration) // debugLog("Caching video duration") PrefsVideos.durationCache[self.id] = self.duration return } } } } } /// Check if a video has HDR files or not func hasHDR() -> Bool { if urls[.v1080pHDR] != "" || urls[.v4KHDR] != "" { return true } else { return false } } /// Check if what we are playing is HDR or not func isHDR() -> Bool { if urls[.v1080pHDR] != "" { if url == URL(string: urls[.v1080pHDR]!) { return true } } if urls[.v4KHDR] != "" { if url == URL(string: urls[.v4KHDR]!) { return true } } return false } func getCurrentFormat() -> String { let wanted = PrefsVideos.videoFormat if urls[wanted] != "" { switch wanted { case .v4KHDR: return "4K HDR" case .v1080pH264: return "1080p" case .v1080pHEVC: return "1080p" case .v1080pHDR: return "1080p HDR" case .v4KHEVC: return "4K" } } else { return getBestFormat() } } private func getBestFormat() -> String { if urls[.v4KHDR] != "" { return "4K HDR" } else if urls[.v4KHEVC] != "" { return "4K" } else { return "1080p" } } var description: String { return """ id=\(id), name=\(name), type=\(type), timeofDay=\(timeOfDay), urls=\(urls) """ } }
mit
45da3280f64e969bbfa89bbefa02171c
28.242537
187
0.518311
4.620873
false
false
false
false
Ramesh-P/virtual-tourist
Virtual Tourist/TravelLocationsMapViewController+Photos.swift
1
2898
// // TravelLocationsMapViewController+Photos.swift // Virtual Tourist // // Created by Ramesh Parthasarathy on 3/7/17. // Copyright © 2017 Ramesh Parthasarathy. All rights reserved. // import Foundation import UIKit import MapKit import CoreData // MARK: TravelLocationsMapViewController+Extension+Photos extension TravelLocationsMapViewController { // MARK: Photos func searchPhotosFor(_ pin: Pin) { let latitude = pin.latitude let longitude = pin.longitude let photosLimit = Flickr.ParameterValues.photosLimit // Searech Flickr for photos at pin location FlickrAPIMethods.sharedInstance().searchPhotoURLsForPinAt(latitude, longitude, photosLimit) { (success, error, result) in // Save urls performUIUpdatesOnMain { if success { self.savePhotoURLsFor(pin, from: result!) } else { self.displayError("Error downloading photos") } } } } func savePhotoURLsFor(_ pin: Pin, from photos: [Photos]) { // Save photo urls and title for pin for photoContents in photos { if (try? photoContents.url) != nil { let image: NSData? = NSData() let photo = Photo(image: image!, title: photoContents.title, url: photoContents.url, context: appDelegate.stack.context) photo.pin = pin } } appDelegate.stack.saveContext() savePhotoImageDataFor(pin) } func savePhotoImageDataFor(_ pin: Pin) { // Fetch photo urls for pin from data store let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Photo") fetchRequest.predicate = NSPredicate(format: "pin == %@", argumentArray: [pin]) do { let results = try appDelegate.stack.context.fetch(fetchRequest) if let results = results as? [Photo] { if (results.count > 0) { for result in results { let url = result.url! // Get photo image data from Flickr FlickrAPIMethods.sharedInstance().getPhotoImageDataFrom(url) { (success, error, data) in // Save image data performUIUpdatesOnMain { if success { result.image = data self.appDelegate.stack.saveContext() } } } } } } } catch { displayError("Could not fetch photos") } } }
mit
5f3dea2c79645f537a99a7945497c4d0
33.082353
136
0.516051
5.592664
false
false
false
false
zhugejunwei/Algorithms-in-Java-Swift-CPP
Dijkstra & Floyd/Carthage/Checkouts/Charts/Charts/Classes/Renderers/ScatterChartRenderer.swift
3
11248
// // ScatterChartRenderer.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics import UIKit @objc public protocol ScatterChartRendererDelegate { func scatterChartRendererData(renderer: ScatterChartRenderer) -> ScatterChartData! func scatterChartRenderer(renderer: ScatterChartRenderer, transformerForAxis which: ChartYAxis.AxisDependency) -> ChartTransformer! func scatterChartDefaultRendererValueFormatter(renderer: ScatterChartRenderer) -> NSNumberFormatter! func scatterChartRendererChartYMax(renderer: ScatterChartRenderer) -> Double func scatterChartRendererChartYMin(renderer: ScatterChartRenderer) -> Double func scatterChartRendererChartXMax(renderer: ScatterChartRenderer) -> Double func scatterChartRendererChartXMin(renderer: ScatterChartRenderer) -> Double func scatterChartRendererMaxVisibleValueCount(renderer: ScatterChartRenderer) -> Int } public class ScatterChartRenderer: LineScatterCandleRadarChartRenderer { public weak var delegate: ScatterChartRendererDelegate? public init(delegate: ScatterChartRendererDelegate?, animator: ChartAnimator?, viewPortHandler: ChartViewPortHandler) { super.init(animator: animator, viewPortHandler: viewPortHandler) self.delegate = delegate } public override func drawData(context context: CGContext?) { let scatterData = delegate!.scatterChartRendererData(self) if (scatterData === nil) { return } for (var i = 0; i < scatterData.dataSetCount; i++) { let set = scatterData.getDataSetByIndex(i) if (set !== nil && set!.isVisible) { drawDataSet(context: context, dataSet: set as! ScatterChartDataSet) } } } private var _lineSegments = [CGPoint](count: 2, repeatedValue: CGPoint()) internal func drawDataSet(context context: CGContext?, dataSet: ScatterChartDataSet) { let trans = delegate!.scatterChartRenderer(self, transformerForAxis: dataSet.axisDependency) let phaseY = _animator.phaseY var entries = dataSet.yVals let shapeSize = dataSet.scatterShapeSize let shapeHalf = shapeSize / 2.0 var point = CGPoint() let valueToPixelMatrix = trans.valueToPixelMatrix let shape = dataSet.scatterShape CGContextSaveGState(context) for (var j = 0, count = Int(min(ceil(CGFloat(entries.count) * _animator.phaseX), CGFloat(entries.count))); j < count; j++) { let e = entries[j] point.x = CGFloat(e.xIndex) point.y = CGFloat(e.value) * phaseY point = CGPointApplyAffineTransform(point, valueToPixelMatrix); if (!viewPortHandler.isInBoundsRight(point.x)) { break } if (!viewPortHandler.isInBoundsLeft(point.x) || !viewPortHandler.isInBoundsY(point.y)) { continue } if (shape == .Square) { CGContextSetFillColorWithColor(context, dataSet.colorAt(j).CGColor) var rect = CGRect() rect.origin.x = point.x - shapeHalf rect.origin.y = point.y - shapeHalf rect.size.width = shapeSize rect.size.height = shapeSize CGContextFillRect(context, rect) } else if (shape == .Circle) { CGContextSetFillColorWithColor(context, dataSet.colorAt(j).CGColor) var rect = CGRect() rect.origin.x = point.x - shapeHalf rect.origin.y = point.y - shapeHalf rect.size.width = shapeSize rect.size.height = shapeSize CGContextFillEllipseInRect(context, rect) } else if (shape == .Cross) { CGContextSetStrokeColorWithColor(context, dataSet.colorAt(j).CGColor) _lineSegments[0].x = point.x - shapeHalf _lineSegments[0].y = point.y _lineSegments[1].x = point.x + shapeHalf _lineSegments[1].y = point.y CGContextStrokeLineSegments(context, _lineSegments, 2) _lineSegments[0].x = point.x _lineSegments[0].y = point.y - shapeHalf _lineSegments[1].x = point.x _lineSegments[1].y = point.y + shapeHalf CGContextStrokeLineSegments(context, _lineSegments, 2) } else if (shape == .Triangle) { CGContextSetFillColorWithColor(context, dataSet.colorAt(j).CGColor) // create a triangle path CGContextBeginPath(context) CGContextMoveToPoint(context, point.x, point.y - shapeHalf) CGContextAddLineToPoint(context, point.x + shapeHalf, point.y + shapeHalf) CGContextAddLineToPoint(context, point.x - shapeHalf, point.y + shapeHalf) CGContextClosePath(context) CGContextFillPath(context) } else if (shape == .Custom) { CGContextSetFillColorWithColor(context, dataSet.colorAt(j).CGColor) let customShape = dataSet.customScatterShape if (customShape === nil) { return } // transform the provided custom path CGContextSaveGState(context) CGContextTranslateCTM(context, point.x, point.y) CGContextBeginPath(context) CGContextAddPath(context, customShape) CGContextFillPath(context) CGContextRestoreGState(context) } } CGContextRestoreGState(context) } public override func drawValues(context context: CGContext?) { let scatterData = delegate!.scatterChartRendererData(self) if (scatterData === nil) { return } let defaultValueFormatter = delegate!.scatterChartDefaultRendererValueFormatter(self) // if values are drawn if (scatterData.yValCount < Int(ceil(CGFloat(delegate!.scatterChartRendererMaxVisibleValueCount(self)) * viewPortHandler.scaleX))) { var dataSets = scatterData.dataSets as! [ScatterChartDataSet] for (var i = 0; i < scatterData.dataSetCount; i++) { let dataSet = dataSets[i] if !dataSet.isDrawValuesEnabled || dataSet.entryCount == 0 { continue } let valueFont = dataSet.valueFont let valueTextColor = dataSet.valueTextColor var formatter = dataSet.valueFormatter if (formatter === nil) { formatter = defaultValueFormatter } var entries = dataSet.yVals var positions = delegate!.scatterChartRenderer(self, transformerForAxis: dataSet.axisDependency).generateTransformedValuesScatter(entries, phaseY: _animator.phaseY) let shapeSize = dataSet.scatterShapeSize let lineHeight = valueFont.lineHeight for (var j = 0, count = Int(ceil(CGFloat(positions.count) * _animator.phaseX)); j < count; j++) { if (!viewPortHandler.isInBoundsRight(positions[j].x)) { break } // make sure the lines don't do shitty things outside bounds if ((!viewPortHandler.isInBoundsLeft(positions[j].x) || !viewPortHandler.isInBoundsY(positions[j].y))) { continue } let val = entries[j].value let text = formatter!.stringFromNumber(val) ChartUtils.drawText(context: context, text: text!, point: CGPoint(x: positions[j].x, y: positions[j].y - shapeSize - lineHeight), align: .Center, attributes: [NSFontAttributeName: valueFont, NSForegroundColorAttributeName: valueTextColor]) } } } } public override func drawExtras(context context: CGContext?) { } private var _highlightPointBuffer = CGPoint() public override func drawHighlighted(context context: CGContext?, indices: [ChartHighlight]) { let scatterData = delegate!.scatterChartRendererData(self) let chartXMax = delegate!.scatterChartRendererChartXMax(self) CGContextSaveGState(context) for (var i = 0; i < indices.count; i++) { let set = scatterData.getDataSetByIndex(indices[i].dataSetIndex) as! ScatterChartDataSet! if (set === nil || !set.isHighlightEnabled) { continue } CGContextSetStrokeColorWithColor(context, set.highlightColor.CGColor) CGContextSetLineWidth(context, set.highlightLineWidth) if (set.highlightLineDashLengths != nil) { CGContextSetLineDash(context, set.highlightLineDashPhase, set.highlightLineDashLengths!, set.highlightLineDashLengths!.count) } else { CGContextSetLineDash(context, 0.0, nil, 0) } let xIndex = indices[i].xIndex; // get the x-position if (CGFloat(xIndex) > CGFloat(chartXMax) * _animator.phaseX) { continue } let yVal = set.yValForXIndex(xIndex) if (yVal.isNaN) { continue } let y = CGFloat(yVal) * _animator.phaseY; // get the y-position _highlightPointBuffer.x = CGFloat(xIndex) _highlightPointBuffer.y = y let trans = delegate!.scatterChartRenderer(self, transformerForAxis: set.axisDependency) trans.pointValueToPixel(&_highlightPointBuffer) // draw the lines drawHighlightLines(context: context, point: _highlightPointBuffer, set: set) } CGContextRestoreGState(context) } }
mit
f6552f35003b134d67ac5c7335c95e68
36.622074
259
0.553965
6.106406
false
false
false
false
radvansky-tomas/NutriFacts
nutri-facts/nutri-facts/Libraries/iOSCharts/Classes/Charts/HorizontalBarChartView.swift
3
6781
// // HorizontalBarChartView.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import UIKit /// BarChart with horizontal bar orientation. In this implementation, x- and y-axis are switched. public class HorizontalBarChartView: BarChartView { internal override func initialize() { super.initialize(); _leftAxisTransformer = ChartTransformerHorizontalBarChart(viewPortHandler: _viewPortHandler); _rightAxisTransformer = ChartTransformerHorizontalBarChart(viewPortHandler: _viewPortHandler); renderer = HorizontalBarChartRenderer(delegate: self, animator: _animator, viewPortHandler: _viewPortHandler); _leftYAxisRenderer = ChartYAxisRendererHorizontalBarChart(viewPortHandler: _viewPortHandler, yAxis: _leftAxis, transformer: _leftAxisTransformer); _rightYAxisRenderer = ChartYAxisRendererHorizontalBarChart(viewPortHandler: _viewPortHandler, yAxis: _rightAxis, transformer: _rightAxisTransformer); _xAxisRenderer = ChartXAxisRendererHorizontalBarChart(viewPortHandler: _viewPortHandler, xAxis: _xAxis, transformer: _leftAxisTransformer, chart: self); } internal override func calculateOffsets() { var offsetLeft: CGFloat = 0.0, offsetRight: CGFloat = 0.0, offsetTop: CGFloat = 0.0, offsetBottom: CGFloat = 0.0; // setup offsets for legend if (_legend !== nil && _legend.isEnabled) { if (_legend.position == .RightOfChart || _legend.position == .RightOfChartCenter) { offsetRight += _legend.textWidthMax + _legend.xOffset * 2.0; } else if (_legend.position == .LeftOfChart || _legend.position == .LeftOfChartCenter) { offsetLeft += _legend.textWidthMax + _legend.xOffset * 2.0; } else if (_legend.position == .BelowChartLeft || _legend.position == .BelowChartRight || _legend.position == .BelowChartCenter) { offsetBottom += _legend.textHeightMax * 3.0; } } // offsets for y-labels if (_leftAxis.needsOffset) { offsetTop += _leftAxis.requiredSize().height; } if (_rightAxis.needsOffset) { offsetBottom += _rightAxis.requiredSize().height; } var xlabelwidth = _xAxis.labelWidth; if (_xAxis.isEnabled) { // offsets for x-labels if (_xAxis.labelPosition == .Bottom) { offsetLeft += xlabelwidth; } else if (_xAxis.labelPosition == .Top) { offsetRight += xlabelwidth; } else if (_xAxis.labelPosition == .BothSided) { offsetLeft += xlabelwidth; offsetRight += xlabelwidth; } } var min: CGFloat = 10.0; _viewPortHandler.restrainViewPort( offsetLeft: max(min, offsetLeft), offsetTop: max(min, offsetTop), offsetRight: max(min, offsetRight), offsetBottom: max(min, offsetBottom)); prepareOffsetMatrix(); prepareValuePxMatrix(); } internal override func prepareValuePxMatrix() { _rightAxisTransformer.prepareMatrixValuePx(chartXMin: _rightAxis.axisMinimum, deltaX: CGFloat(_rightAxis.axisRange), deltaY: _deltaX, chartYMin: _chartXMin); _leftAxisTransformer.prepareMatrixValuePx(chartXMin: _leftAxis.axisMinimum, deltaX: CGFloat(_leftAxis.axisRange), deltaY: _deltaX, chartYMin: _chartXMin); } internal override func calcModulus() { _xAxis.axisLabelModulus = Int(ceil((CGFloat(_data.xValCount) * _xAxis.labelHeight) / (_viewPortHandler.contentHeight * viewPortHandler.touchMatrix.d))); if (_xAxis.axisLabelModulus < 1) { _xAxis.axisLabelModulus = 1; } } public override func getBarBounds(e: BarChartDataEntry) -> CGRect! { var set = _data.getDataSetForEntry(e) as! BarChartDataSet!; if (set === nil) { return nil; } var barspace = set.barSpace; var y = CGFloat(e.value); var x = CGFloat(e.xIndex); var spaceHalf = barspace / 2.0; var top = x - 0.5 + spaceHalf; var bottom = x + 0.5 - spaceHalf; var left = y >= 0.0 ? y : 0.0; var right = y <= 0.0 ? y : 0.0; var bounds = CGRect(x: left, y: top, width: right - left, height: bottom - top); getTransformer(set.axisDependency).rectValueToPixel(&bounds); return bounds; } public override func getPosition(e: ChartDataEntry, axis: ChartYAxis.AxisDependency) -> CGPoint { var vals = CGPoint(x: CGFloat(e.value), y: CGFloat(e.xIndex)); getTransformer(axis).pointValueToPixel(&vals); return vals; } public override func getHighlightByTouchPoint(var pt: CGPoint) -> ChartHighlight! { if (_dataNotSet || _data === nil) { println("Can't select by touch. No data set."); return nil; } _leftAxisTransformer.pixelToValue(&pt); if (pt.y < CGFloat(_chartXMin) || pt.y > CGFloat(_chartXMax)) { return nil; } return getHighlight(xPosition: pt.y, yPosition: pt.x); } public override var lowestVisibleXIndex: Int { var step = CGFloat(_data.dataSetCount); var div = (step <= 1.0) ? 1.0 : step + (_data as! BarChartData).groupSpace; var pt = CGPoint(x: _viewPortHandler.contentLeft, y: _viewPortHandler.contentBottom); getTransformer(ChartYAxis.AxisDependency.Left).pixelToValue(&pt); return Int(((pt.y <= 0.0) ? 0.0 : pt.y / div) + 1.0); } public override var highestVisibleXIndex: Int { var step = CGFloat(_data.dataSetCount); var div = (step <= 1.0) ? 1.0 : step + (_data as! BarChartData).groupSpace; var pt = CGPoint(x: _viewPortHandler.contentLeft, y: _viewPortHandler.contentTop); getTransformer(ChartYAxis.AxisDependency.Left).pixelToValue(&pt); return Int((pt.y >= CGFloat(chartXMax)) ? CGFloat(chartXMax) / div : (pt.y / div)); } }
gpl-2.0
36fab4f1a5e9aeb92621238198b62736
33.779487
165
0.581183
5.102333
false
false
false
false
tristanchu/FlavorFinder
FlavorFinder/FlavorFinder/EditListPage.swift
1
2194
// // EditListPage.swift // FlavorFinder // // Created by Courtney Ligh on 2/7/16. // Copyright © 2016 TeamFive. All rights reserved. // import UIKit import Parse class EditListPage: SearchIngredientsViewController, UITextFieldDelegate { // MARK: Properties: var ingredientList = [PFIngredient]() var listObject: PFObject! var listTitle = "" // Parse related: let listClassName = "List" let ingredientsColumnName = "ingredients" let userColumnName = "user" let ListTitleColumnName = "title" // Visual related: let pageTitle = "Rename List" let alreadyContains = " is already in your list" // MARK: connections: @IBOutlet weak var listNamePromptLabel: UILabel! @IBOutlet weak var listTitleLabel: UILabel! @IBOutlet weak var newNamePromptLabel: UILabel! @IBOutlet weak var newNameTextField: UITextField! @IBOutlet weak var renameListButton: UIButton! @IBOutlet weak var cancelRenameButton: UIButton! @IBAction func submitAction(sender: AnyObject) { if newNameTextField.text != nil && newNameTextField.text != "" { listObject.setObject(newNameTextField.text!, forKey: ListTitleColumnName) listTitleLabel.text = newNameTextField.text listObject.saveInBackground() } } @IBAction func cancelAction(sender: AnyObject) { newNameTextField.text = "" } // MARK: Override methods: ---------------------------------------------- /* viewDidLoad: Additional setup after loading the view (upon open) */ override func viewDidLoad() { // Assign values to parent class variables navTitle = pageTitle // Call super super.viewDidLoad() // Set title label to list title: listTitleLabel.text = listTitle // set up text field newNameTextField.delegate = self newNameTextField.setTextLeftPadding(5) // button borders: setDefaultButtonUI(renameListButton) setSecondaryButtonUI(cancelRenameButton) // grey background: view.backgroundColor = BACKGROUND_COLOR } }
mit
289eb59d920c4f34161fb2d10cbfb618
26.425
85
0.639763
5.064665
false
false
false
false
andersio/MantleData
MantleData/ManagedObjectID.swift
1
751
// // ManagedObjectID.swift // MantleData // // Created by Anders on 20/6/2016. // Copyright © 2016 Anders. All rights reserved. // import CoreData public struct ManagedObjectID<E: NSManagedObject> { public let id: NSManagedObjectID public var isTemporaryID: Bool { return id.isTemporaryID } public init(object: E) { id = object.objectID } public func object(for context: NSManagedObjectContext) -> E { return context.object(with: id) as! E } } extension ManagedObjectID: Hashable { public var hashValue: Int { return id.uriRepresentation().hashValue } } public func ==<E: NSManagedObject>(left: ManagedObjectID<E>, right: ManagedObjectID<E>) -> Bool { return left.id.uriRepresentation() == right.id.uriRepresentation() }
mit
7b0e8d80b82673c47b81c567e49f757d
21.058824
97
0.724
3.571429
false
false
false
false
TonnyTao/HowSwift
Dao of Protocol.playground/Pages/extend for generic.xcplaygroundpage/Contents.swift
1
1074
//: [Previous](@previous) import Foundation protocol Callable { associatedtype PhoneNumberType var phone: PhoneNumberType { get set } } extension Callable { //default implementation func call() { print("calling", phone) } } struct Professor: Callable { var phone: String //'overwrite' implementation func call() { print("calling string phone:", phone, terminator: "\n") } } struct Student: Callable { var phone: Int //use the default call() } //////////////////////////// extension Callable where Self.PhoneNumberType == Int { func call() { var phone = String(describing: self.phone) phone.insert("-", at: phone.index(phone.startIndex, offsetBy: String.IndexDistance(3))) phone.insert("-", at: phone.index(phone.startIndex, offsetBy: String.IndexDistance(7))) print("calling int phone:", phone, terminator: "\n") } } let steve = Professor(phone: "1234567890") steve.call() let tim = Student(phone: 9876543210) tim.call()
mit
2987aae060fe27c1b9dc47045a1fb563
19.264151
95
0.608939
4.228346
false
false
false
false
pirishd/InstantMock
Sources/InstantMock/Arguments/Helpers/ArgumentsConfiguration.swift
1
2137
// // ArgumentsConfiguration.swift // InstantMock // // Created by Patrick on 12/05/2017. // Copyright © 2017 pirishd. All rights reserved. // /** Class representing a configuration of arguments */ final class ArgumentsConfiguration { /// Actual expected arguments let args: [Argument] /** Initialize with expected arguments */ init(_ args: [Argument]) { self.args = args } } /** Extension that returns a description of a configuration */ extension ArgumentsConfiguration: CustomStringConvertible { var description: String { var value = "" if self.args.count > 0 { let valuesDescriptions = self.args.map { $0.description } value = valuesDescriptions.joined(separator: ", ") } else { value = "none" } return value } } /** Extension that returns the number of args of any kinds */ extension ArgumentsConfiguration { /** Returns the number of arguments that must verify a certain value */ func numberOfArgValues() -> Int { return self.args.filter { $0 is ArgumentValue }.count } /** Returns the number of arguments that must verify a certain condition */ func numberOfArgVerify() -> Int { return self.args.filter { $0 is ArgumentVerify }.count } } /** Configurations are comparable depending on how the args must be verified */ extension ArgumentsConfiguration: Comparable {} func ==(lhs: ArgumentsConfiguration, rhs: ArgumentsConfiguration) -> Bool { // configurations are equal if they have the same number of args that must verify a precise value or condition return lhs.numberOfArgValues() == rhs.numberOfArgValues() && lhs.numberOfArgVerify() == rhs.numberOfArgVerify() } func <(lhs: ArgumentsConfiguration, rhs: ArgumentsConfiguration) -> Bool { // when the number of args that must verify a certain value precisely is the same, look for conditions if lhs.numberOfArgValues() == rhs.numberOfArgValues() { return lhs.numberOfArgVerify() < rhs.numberOfArgVerify() } return lhs.numberOfArgValues() < rhs.numberOfArgValues() }
mit
ce11d5f0c6269114726edd98b58514bb
27.48
115
0.679775
4.82167
false
true
false
false
ocrickard/Theodolite
Theodolite/Utility/IteratorWrapper.swift
1
1051
// // IteratorWrapper.swift // Theodolite // // Created by Oliver Rickard on 10/23/17. // Copyright © 2017 Oliver Rickard. All rights reserved. // import Foundation /** Internal iterator struct (probably unnecessary) to make the view reuse algorithm look identical to the C++ version in ComponentKit. TODO: Remove this, and Swiftify the reuse algorithm now that this is tested. */ struct IteratorWrapper<T: AnyObject> { private var array: Array<T> var current: T? = nil var offset: Int = 0 init(_ array: Array<T>, initialOffset: Int = 0) { self.array = array offset = initialOffset if initialOffset < array.count { current = array[initialOffset] } } func find(_ val: T) -> Int? { for i in offset ..< array.count { let v = array[i] if v === val { return i } } return nil } mutating func advance() { if offset + 1 < array.count { offset += 1 current = array[offset] } else { current = nil offset += 0 } } }
mit
698a4960efb78091f70dd615f3db9ea0
19.588235
115
0.604762
3.818182
false
false
false
false
Zewo/TodoBackend
Sources/TodoBackend/Models/Todo.swift
1
2075
import Axis import SQL struct Todo { let title: String let completed: Bool let order: Int } extension Todo : ModelProtocol { typealias PrimaryKey = Int enum Field: String, ModelField { static let tableName = "todo" static let primaryKey = Field.id case id case title case completed // "order" is reserved in psql case order = "order_" } func serialize() -> [Field: ValueConvertible?] { return [ .title: title, .completed: completed ? 1 : 0, .order: order ] } init<Row: RowProtocol>(row: TableRow<Todo, Row>) throws { try self.init( title: row.value(.title), completed: row.value(.completed) == 1, order: row.value(.order) ) } } extension Todo { static func createTable<Connection : ConnectionProtocol>(connection: Connection) throws { //TODO: make a nice dsl for this in sql let query = "CREATE TABLE IF NOT EXISTS todo (" + "id serial PRIMARY KEY NOT NULL," + "title text NOT NULL," + "completed integer NOT NULL DEFAULT 0," + "order_ integer NOT NULL" + ");" try connection.execute(query) } } extension Todo { func update(title: String? = nil, completed: Bool? = nil, order: Int? = nil) -> Todo { return Todo.init( title: title ?? self.title, completed: completed ?? self.completed, order: order ?? self.order ) } func update(map: Map) -> Todo { return self.update( title: map["title"].string, completed: map["completed"].bool, order: map["order"].int ) } } extension Todo : MapConvertible { init(map: Map) throws { try self.init( title: map.get("title"), completed: map["completed"].bool ?? false, order: map["order"].int ?? 0 ) } }
mit
f455599b0bf66f4f3dca2308a38a81ed
24.617284
93
0.520482
4.443255
false
false
false
false
arvedviehweger/swift
test/stdlib/KeyPathAppending.swift
1
4124
// RUN: %target-swift-frontend -typecheck -verify %s // Check that all combinations of key paths produce the expected result type // and choose the expected overloads. #if BUILDING_OUTSIDE_STDLIB import Swift #endif func expect<T>(_: inout T, is: T.Type) {} func wellTypedAppends<T, U, V>(readOnlyLeft: KeyPath<T, U>, writableLeft: WritableKeyPath<T, U>, referenceLeft: ReferenceWritableKeyPath<T, U>, readOnlyRight: KeyPath<U, V>, writableRight: WritableKeyPath<U, V>, referenceRight: ReferenceWritableKeyPath<U, V>){ var a = readOnlyLeft.appending(path: readOnlyRight) expect(&a, is: KeyPath<T, V>.self) var b = readOnlyLeft.appending(path: writableRight) expect(&b, is: KeyPath<T, V>.self) var c = readOnlyLeft.appending(path: referenceRight) expect(&c, is: ReferenceWritableKeyPath<T, V>.self) var d = writableLeft.appending(path: readOnlyRight) expect(&d, is: KeyPath<T, V>.self) var e = writableLeft.appending(path: writableRight) expect(&e, is: WritableKeyPath<T, V>.self) var f = writableLeft.appending(path: referenceRight) expect(&f, is: ReferenceWritableKeyPath<T, V>.self) var g = referenceLeft.appending(path: readOnlyRight) expect(&g, is: KeyPath<T, V>.self) var h = referenceLeft.appending(path: writableRight) expect(&h, is: ReferenceWritableKeyPath<T, V>.self) var i = referenceLeft.appending(path: referenceRight) expect(&i, is: ReferenceWritableKeyPath<T, V>.self) } func mismatchedAppends<T, U, V>(readOnlyLeft: KeyPath<T, U>, writableLeft: WritableKeyPath<T, U>, referenceLeft: ReferenceWritableKeyPath<T, U>, readOnlyRight: KeyPath<U, V>, writableRight: WritableKeyPath<U, V>, referenceRight: ReferenceWritableKeyPath<U, V>){ /* TODO: These crash the compiler // e/xpected-error@+1{{}} _ = readOnlyRight.appending(path: readOnlyLeft) // e/xpected-error@+1{{}} _ = readOnlyRight.appending(path: writableLeft) // e/xpected-error@+1{{}} _ = readOnlyRight.appending(path: referenceLeft) // e/xpected-error@+1{{}} _ = writableRight.appending(path: readOnlyLeft) // e/xpected-error@+1{{}} _ = writableRight.appending(path: writableLeft) // e/xpected-error@+1{{}} _ = writableRight.appending(path: referenceLeft) // e/xpected-error@+1{{}} _ = referenceRight.appending(path: readOnlyLeft) // e/xpected-error@+1{{}} _ = referenceRight.appending(path: writableLeft) // e/xpected-error@+1{{}} _ = referenceRight.appending(path: referenceLeft) */ } func partialAppends<T, U, V>(partial: PartialKeyPath<T>, concrete: KeyPath<U, V>, reference: ReferenceWritableKeyPath<U, V>, any: AnyKeyPath) { var a = any.appending(path: any) expect(&a, is: Optional<AnyKeyPath>.self) var b = any.appending(path: partial) expect(&b, is: Optional<AnyKeyPath>.self) var c = any.appending(path: concrete) expect(&c, is: Optional<AnyKeyPath>.self) var d = any.appending(path: reference) expect(&d, is: Optional<AnyKeyPath>.self) var e = partial.appending(path: any) expect(&e, is: Optional<PartialKeyPath<T>>.self) var f = partial.appending(path: partial) expect(&f, is: Optional<PartialKeyPath<T>>.self) var g = partial.appending(path: concrete) expect(&g, is: Optional<KeyPath<T, V>>.self) var h = partial.appending(path: reference) expect(&h, is: Optional<ReferenceWritableKeyPath<T, V>>.self) /* TODO var i = concrete.appending(path: any) expect(&i, is: Optional<PartialKeyPath<U>>.self) var j = concrete.appending(path: partial) expect(&j, is: Optional<PartialKeyPath<U>>.self) var m = reference.appending(path: any) expect(&m, is: Optional<PartialKeyPath<U>>.self) var n = reference.appending(path: partial) expect(&n, is: Optional<PartialKeyPath<U>>.self) */ }
apache-2.0
d715749fcbe7353def8cf8d6a44ce9f6
31.730159
80
0.639913
4.039177
false
false
false
false
justindarc/firefox-ios
Client/Frontend/Browser/DownloadQueue.swift
2
9065
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation private let downloadOperationQueue = OperationQueue() protocol DownloadDelegate { func download(_ download: Download, didCompleteWithError error: Error?) func download(_ download: Download, didDownloadBytes bytesDownloaded: Int64) func download(_ download: Download, didFinishDownloadingTo location: URL) } class Download: NSObject { var delegate: DownloadDelegate? fileprivate(set) var filename: String fileprivate(set) var mimeType: String fileprivate(set) var isComplete = false fileprivate(set) var totalBytesExpected: Int64? fileprivate(set) var bytesDownloaded: Int64 override init() { self.filename = "unknown" self.mimeType = "application/octet-stream" self.bytesDownloaded = 0 super.init() } func cancel() {} func pause() {} func resume() {} fileprivate func uniqueDownloadPathForFilename(_ filename: String) throws -> URL { let downloadsPath = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent("Downloads") let basePath = downloadsPath.appendingPathComponent(filename) let fileExtension = basePath.pathExtension let filenameWithoutExtension = fileExtension.count > 0 ? String(filename.dropLast(fileExtension.count + 1)) : filename var proposedPath = basePath var count = 0 while FileManager.default.fileExists(atPath: proposedPath.path) { count += 1 let proposedFilenameWithoutExtension = "\(filenameWithoutExtension) (\(count))" proposedPath = downloadsPath.appendingPathComponent(proposedFilenameWithoutExtension).appendingPathExtension(fileExtension) } return proposedPath } } class HTTPDownload: Download { let preflightResponse: URLResponse let request: URLRequest var state: URLSessionTask.State { return task?.state ?? .suspended } fileprivate(set) var session: URLSession? fileprivate(set) var task: URLSessionDownloadTask? private var resumeData: Data? init(preflightResponse: URLResponse, request: URLRequest) { self.preflightResponse = preflightResponse self.request = request super.init() if let filename = preflightResponse.suggestedFilename { self.filename = filename } if let mimeType = preflightResponse.mimeType { self.mimeType = mimeType } self.totalBytesExpected = preflightResponse.expectedContentLength > 0 ? preflightResponse.expectedContentLength : nil self.session = URLSession(configuration: .default, delegate: self, delegateQueue: downloadOperationQueue) self.task = session?.downloadTask(with: request) } override func cancel() { task?.cancel() } override func pause() { task?.cancel(byProducingResumeData: { resumeData in self.resumeData = resumeData }) } override func resume() { guard let resumeData = self.resumeData else { task?.resume() return } task = session?.downloadTask(withResumeData: resumeData) task?.resume() } } extension HTTPDownload: URLSessionTaskDelegate, URLSessionDownloadDelegate { func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { // Don't bubble up cancellation as an error if the // error is `.cancelled` and we have resume data. if let urlError = error as? URLError, urlError.code == .cancelled, resumeData != nil { return } delegate?.download(self, didCompleteWithError: error) } func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { bytesDownloaded = totalBytesWritten totalBytesExpected = totalBytesExpectedToWrite delegate?.download(self, didDownloadBytes: bytesWritten) } func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { do { let destination = try uniqueDownloadPathForFilename(filename) try FileManager.default.moveItem(at: location, to: destination) isComplete = true delegate?.download(self, didFinishDownloadingTo: destination) } catch let error { delegate?.download(self, didCompleteWithError: error) } } } class BlobDownload: Download { fileprivate let data: Data init(filename: String, mimeType: String, size: Int64, data: Data) { self.data = data super.init() self.filename = filename self.mimeType = mimeType self.totalBytesExpected = size } override func resume() { // Wait momentarily before continuing here and firing off the delegate // callbacks. Otherwise, these may end up getting called before the // delegate is set up and the UI may never be notified of completion. DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(500)) { do { let destination = try self.uniqueDownloadPathForFilename(self.filename) try self.data.write(to: destination) self.isComplete = true self.delegate?.download(self, didFinishDownloadingTo: destination) } catch let error { self.delegate?.download(self, didCompleteWithError: error) } } } } protocol DownloadQueueDelegate { func downloadQueue(_ downloadQueue: DownloadQueue, didStartDownload download: Download) func downloadQueue(_ downloadQueue: DownloadQueue, didDownloadCombinedBytes combinedBytesDownloaded: Int64, combinedTotalBytesExpected: Int64?) func downloadQueue(_ downloadQueue: DownloadQueue, download: Download, didFinishDownloadingTo location: URL) func downloadQueue(_ downloadQueue: DownloadQueue, didCompleteWithError error: Error?) } class DownloadQueue { var downloads: [Download] var delegate: DownloadQueueDelegate? var isEmpty: Bool { return downloads.isEmpty } fileprivate var combinedBytesDownloaded: Int64 = 0 fileprivate var combinedTotalBytesExpected: Int64? fileprivate var lastDownloadError: Error? init() { self.downloads = [] } func enqueue(_ download: Download) { // Clear the download stats if the queue was empty at the start. if downloads.isEmpty { combinedBytesDownloaded = 0 combinedTotalBytesExpected = 0 lastDownloadError = nil } downloads.append(download) download.delegate = self if let totalBytesExpected = download.totalBytesExpected, combinedTotalBytesExpected != nil { combinedTotalBytesExpected! += totalBytesExpected } else { combinedTotalBytesExpected = nil } download.resume() delegate?.downloadQueue(self, didStartDownload: download) } func cancelAll() { for download in downloads where !download.isComplete { download.cancel() } } func pauseAll() { for download in downloads where !download.isComplete { download.pause() } } func resumeAll() { for download in downloads where !download.isComplete { download.resume() } } } extension DownloadQueue: DownloadDelegate { func download(_ download: Download, didCompleteWithError error: Error?) { guard let error = error, let index = downloads.firstIndex(of: download) else { return } lastDownloadError = error downloads.remove(at: index) if downloads.isEmpty { delegate?.downloadQueue(self, didCompleteWithError: lastDownloadError) } } func download(_ download: Download, didDownloadBytes bytesDownloaded: Int64) { combinedBytesDownloaded += bytesDownloaded delegate?.downloadQueue(self, didDownloadCombinedBytes: combinedBytesDownloaded, combinedTotalBytesExpected: combinedTotalBytesExpected) } func download(_ download: Download, didFinishDownloadingTo location: URL) { guard let index = downloads.firstIndex(of: download) else { return } downloads.remove(at: index) delegate?.downloadQueue(self, download: download, didFinishDownloadingTo: location) NotificationCenter.default.post(name: .FileDidDownload, object: location) if downloads.isEmpty { delegate?.downloadQueue(self, didCompleteWithError: lastDownloadError) } } }
mpl-2.0
d69392d22e13738758d4f7b1ff0faf89
32.083942
176
0.671815
5.490612
false
false
false
false
groue/GRDB.swift
GRDB/Core/StatementAuthorizer.swift
1
10000
#if os(Linux) import Glibc #endif /// `StatementAuthorizer` provides information about compiled database /// statements, and prevents the truncate optimization when row deletions are /// observed by transaction observers. /// /// <https://www.sqlite.org/c3ref/set_authorizer.html> /// <https://www.sqlite.org/lang_delete.html#the_truncate_optimization> final class StatementAuthorizer { private unowned var database: Database /// What a statement reads. var selectedRegion = DatabaseRegion() /// What a statement writes. var databaseEventKinds: [DatabaseEventKind] = [] /// True if a statement alters the schema in a way that requires /// invalidation of the schema cache. For example, adding a column to a /// table invalidates the schema cache. var invalidatesDatabaseSchemaCache = false /// Not nil if a statement is a BEGIN/COMMIT/ROLLBACK/RELEASE transaction or /// savepoint statement. var transactionEffect: Statement.TransactionEffect? private var isDropStatement = false init(_ database: Database) { self.database = database } /// Registers the authorizer with `sqlite3_set_authorizer`. func register() { let authorizerP = Unmanaged.passUnretained(self).toOpaque() sqlite3_set_authorizer( database.sqliteConnection, { (authorizerP, actionCode, cString1, cString2, cString3, cString4) in Unmanaged<StatementAuthorizer> .fromOpaque(authorizerP.unsafelyUnwrapped) .takeUnretainedValue() .authorize(actionCode, cString1, cString2, cString3, cString4) }, authorizerP) } /// Reset before compiling a new statement func reset() { selectedRegion = DatabaseRegion() databaseEventKinds = [] invalidatesDatabaseSchemaCache = false transactionEffect = nil isDropStatement = false } private func authorize( _ actionCode: CInt, _ cString1: UnsafePointer<Int8>?, _ cString2: UnsafePointer<Int8>?, _ cString3: UnsafePointer<Int8>?, _ cString4: UnsafePointer<Int8>?) -> CInt { // Uncomment when debugging // print(""" // StatementAuthorizer: \ // \(AuthorizerActionCode(rawValue: actionCode)) \ // \([cString1, cString2, cString3, cString4].compactMap { $0.map(String.init) }.joined(separator: ", ")) // """) switch actionCode { case SQLITE_DROP_TABLE, SQLITE_DROP_VTABLE, SQLITE_DROP_TEMP_TABLE, SQLITE_DROP_INDEX, SQLITE_DROP_TEMP_INDEX, SQLITE_DROP_VIEW, SQLITE_DROP_TEMP_VIEW, SQLITE_DROP_TRIGGER, SQLITE_DROP_TEMP_TRIGGER: isDropStatement = true invalidatesDatabaseSchemaCache = true return SQLITE_OK case SQLITE_ATTACH, SQLITE_DETACH, SQLITE_ALTER_TABLE, SQLITE_CREATE_INDEX, SQLITE_CREATE_TABLE, SQLITE_CREATE_TEMP_INDEX, SQLITE_CREATE_TEMP_TABLE, SQLITE_CREATE_TEMP_TRIGGER, SQLITE_CREATE_TEMP_VIEW, SQLITE_CREATE_TRIGGER, SQLITE_CREATE_VIEW, SQLITE_CREATE_VTABLE: invalidatesDatabaseSchemaCache = true return SQLITE_OK case SQLITE_READ: guard let tableName = cString1.map(String.init) else { return SQLITE_OK } guard let columnName = cString2.map(String.init) else { return SQLITE_OK } if columnName.isEmpty { // SELECT COUNT(*) FROM table selectedRegion.formUnion(DatabaseRegion(table: tableName)) } else { // SELECT column FROM table selectedRegion.formUnion(DatabaseRegion(table: tableName, columns: [columnName])) } return SQLITE_OK case SQLITE_INSERT: guard let tableName = cString1.map(String.init) else { return SQLITE_OK } databaseEventKinds.append(.insert(tableName: tableName)) return SQLITE_OK case SQLITE_DELETE: if isDropStatement { return SQLITE_OK } guard let cString1 = cString1 else { return SQLITE_OK } // Deletions from sqlite_master and sqlite_temp_master are not like // other deletions: `sqlite3_update_hook` does not notify them, and // they are prevented when the truncate optimization is disabled. // Let's always authorize such deletions by returning SQLITE_OK: guard strcmp(cString1, "sqlite_master") != 0 else { return SQLITE_OK } guard strcmp(cString1, "sqlite_temp_master") != 0 else { return SQLITE_OK } let tableName = String(cString: cString1) databaseEventKinds.append(.delete(tableName: tableName)) if let observationBroker = database.observationBroker, observationBroker.observesDeletions(on: tableName) { // Prevent the truncate optimization so that // `sqlite3_update_hook` notifies individual row deletions to // transaction observers. return SQLITE_IGNORE } else { return SQLITE_OK } case SQLITE_UPDATE: guard let tableName = cString1.map(String.init) else { return SQLITE_OK } guard let columnName = cString2.map(String.init) else { return SQLITE_OK } insertUpdateEventKind(tableName: tableName, columnName: columnName) return SQLITE_OK case SQLITE_TRANSACTION: guard let cString1 = cString1 else { return SQLITE_OK } if strcmp(cString1, "BEGIN") == 0 { transactionEffect = .beginTransaction } else if strcmp(cString1, "COMMIT") == 0 { transactionEffect = .commitTransaction } else if strcmp(cString1, "ROLLBACK") == 0 { transactionEffect = .rollbackTransaction } return SQLITE_OK case SQLITE_SAVEPOINT: guard let cString1 = cString1 else { return SQLITE_OK } guard let name = cString2.map(String.init) else { return SQLITE_OK } if strcmp(cString1, "BEGIN") == 0 { transactionEffect = .beginSavepoint(name) } else if strcmp(cString1, "RELEASE") == 0 { transactionEffect = .releaseSavepoint(name) } else if strcmp(cString1, "ROLLBACK") == 0 { transactionEffect = .rollbackSavepoint(name) } return SQLITE_OK case SQLITE_FUNCTION: // SQLite 3.37.2 does not report ALTER TABLE DROP COLUMN with the // SQLITE_ALTER_TABLE action code. SQLite 3.38 does. // // Until SQLite 3.38, we need to find another way to set the // `invalidatesDatabaseSchemaCache` flag for such // statement, and it is SQLITE_FUNCTION sqlite_drop_column. // // See <https://github.com/groue/GRDB.swift/pull/1144#issuecomment-1015155717> // See <https://sqlite.org/forum/forumpost/bd47580ec2> if sqlite3_libversion_number() < 3038000, let cString2, strcmp(cString2, "sqlite_drop_column") == 0 { invalidatesDatabaseSchemaCache = true } return SQLITE_OK default: return SQLITE_OK } } private func insertUpdateEventKind(tableName: String, columnName: String) { for (index, eventKind) in databaseEventKinds.enumerated() { if case .update(let t, let columnNames) = eventKind, t == tableName { var columnNames = columnNames columnNames.insert(columnName) databaseEventKinds[index] = .update(tableName: tableName, columnNames: columnNames) return } } databaseEventKinds.append(.update(tableName: tableName, columnNames: [columnName])) } } private struct AuthorizerActionCode: RawRepresentable, CustomStringConvertible { let rawValue: CInt var description: String { switch rawValue { case 1: return "SQLITE_CREATE_INDEX" case 2: return "SQLITE_CREATE_TABLE" case 3: return "SQLITE_CREATE_TEMP_INDEX" case 4: return "SQLITE_CREATE_TEMP_TABLE" case 5: return "SQLITE_CREATE_TEMP_TRIGGER" case 6: return "SQLITE_CREATE_TEMP_VIEW" case 7: return "SQLITE_CREATE_TRIGGER" case 8: return "SQLITE_CREATE_VIEW" case 9: return "SQLITE_DELETE" case 10: return "SQLITE_DROP_INDEX" case 11: return "SQLITE_DROP_TABLE" case 12: return "SQLITE_DROP_TEMP_INDEX" case 13: return "SQLITE_DROP_TEMP_TABLE" case 14: return "SQLITE_DROP_TEMP_TRIGGER" case 15: return "SQLITE_DROP_TEMP_VIEW" case 16: return "SQLITE_DROP_TRIGGER" case 17: return "SQLITE_DROP_VIEW" case 18: return "SQLITE_INSERT" case 19: return "SQLITE_PRAGMA" case 20: return "SQLITE_READ" case 21: return "SQLITE_SELECT" case 22: return "SQLITE_TRANSACTION" case 23: return "SQLITE_UPDATE" case 24: return "SQLITE_ATTACH" case 25: return "SQLITE_DETACH" case 26: return "SQLITE_ALTER_TABLE" case 27: return "SQLITE_REINDEX" case 28: return "SQLITE_ANALYZE" case 29: return "SQLITE_CREATE_VTABLE" case 30: return "SQLITE_DROP_VTABLE" case 31: return "SQLITE_FUNCTION" case 32: return "SQLITE_SAVEPOINT" case 0: return "SQLITE_COPY" case 33: return "SQLITE_RECURSIVE" default: return "\(rawValue)" } } }
mit
1d2340ee8c64e4fe43a8c8d3a5fa0623
40.666667
117
0.5979
4.807692
false
false
false
false