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
hilen/TSWeChat
TSWeChat/Classes/Chat/Views/TSChatEmotionInputView.swift
1
6659
// // TSChatEmotionInputView.swift // TSWeChat // // Created by Hilen on 12/16/15. // Copyright © 2015 Hilen. All rights reserved. // import UIKit import Dollar import RxSwift private let itemHeight: CGFloat = 50 private let kOneGroupCount = 23 private let kNumberOfOneRow: CGFloat = 8 class TSChatEmotionInputView: UIView { @IBOutlet fileprivate weak var emotionPageControl: UIPageControl! @IBOutlet fileprivate weak var sendButton: UIButton!{ didSet{ sendButton.layer.borderColor = UIColor.lightGray.cgColor sendButton.layer.borderWidth = 0.5 sendButton.layer.cornerRadius = 3.0 sendButton.layer.masksToBounds = true }} @IBOutlet fileprivate weak var listCollectionView: TSChatEmotionScollView! fileprivate var groupDataSouce = [[EmotionModel]]() //大数组包含小数组 fileprivate var emotionsDataSouce = [EmotionModel]() //Model 数组 weak internal var delegate: ChatEmotionInputViewDelegate? required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! self.initialize() } func initialize() { } override func awakeFromNib() { self.isUserInteractionEnabled = true //calculate width and height let itemWidth = (UIScreen.ts_width - 10 * 2) / kNumberOfOneRow let padding = (UIScreen.ts_width - kNumberOfOneRow * itemWidth) / 2.0 let paddingLeft = padding let paddingRight = UIScreen.ts_width - paddingLeft - itemWidth * kNumberOfOneRow //init FlowLayout let layout = UICollectionViewFlowLayout() layout.scrollDirection = .horizontal layout.itemSize = CGSize(width: itemWidth, height: itemHeight) layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.sectionInset = UIEdgeInsets.init(top: 0, left: paddingLeft, bottom: 0, right: paddingRight) //init listCollectionView self.listCollectionView.collectionViewLayout = layout self.listCollectionView.register(TSChatEmotionCell.ts_Nib(), forCellWithReuseIdentifier: TSChatEmotionCell.identifier) self.listCollectionView.isPagingEnabled = true self.listCollectionView.emotionScrollDelegate = self //init dataSource guard let emojiArray = NSArray(contentsOfFile: TSConfig.ExpressionPlist!) else { return } for data in emojiArray { let model = EmotionModel.init(fromDictionary: data as! NSDictionary) self.emotionsDataSouce.append(model) } self.groupDataSouce = Dollar.chunk(self.emotionsDataSouce, size: kOneGroupCount) //将数组切割成 每23个 一组 self.listCollectionView.reloadData() self.emotionPageControl.numberOfPages = self.groupDataSouce.count } @IBAction func sendTaped(_ sender: AnyObject) { if let delegate = self.delegate { delegate.chatEmoticonInputViewDidTapSend() } } //transpose line/row fileprivate func emoticonForIndexPath(_ indexPath: IndexPath) -> EmotionModel? { let page = indexPath.section var index = page * kOneGroupCount + indexPath.row let ip = index / kOneGroupCount //重新计算的所在 page let ii = index % kOneGroupCount //重新计算的所在 index let reIndex = (ii % 3) * Int(kNumberOfOneRow) + (ii / 3) //最终在数据源里的 Index index = reIndex + ip * kOneGroupCount if index < self.emotionsDataSouce.count { return self.emotionsDataSouce[index] } else { return nil } } } // MARK: - @protocol UICollectionViewDelegate extension TSChatEmotionInputView: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool { return false } func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool { return false } } // MARK: - @protocol UICollectionViewDataSource extension TSChatEmotionInputView: UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { return self.groupDataSouce.count } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return kOneGroupCount + 1 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: TSChatEmotionCell.identifier, for: indexPath) as! TSChatEmotionCell if indexPath.row == kOneGroupCount { cell.setDeleteCellContnet() } else { cell.setCellContnet(self.emoticonForIndexPath(indexPath)) } return cell } } // MARK: - @protocol UIScrollViewDelegate extension TSChatEmotionInputView: UIScrollViewDelegate { func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { let pageWidth: CGFloat = self.listCollectionView.ts_width self.emotionPageControl.currentPage = Int(self.listCollectionView.contentOffset.x / pageWidth) } func scrollViewDidScroll(_ scrollView: UIScrollView) { self.listCollectionView.hideMagnifierView() self.listCollectionView.endBackspaceTimer() } } // MARK: - @protocol UIInputViewAudioFeedback extension TSChatEmotionInputView: UIInputViewAudioFeedback { internal var enableInputClicksWhenVisible: Bool { get { return true } } } // MARK: - @protocol ChatEmotionScollViewDelegate extension TSChatEmotionInputView: ChatEmotionScollViewDelegate { func emoticonScrollViewDidTapCell(_ cell: TSChatEmotionCell) { guard let delegate = self.delegate else { return } if cell.isDelete { delegate.chatEmoticonInputViewDidTapBackspace(cell) } else { delegate.chatEmoticonInputViewDidTapCell(cell) } } } /** * 表情键盘的代理方法 */ // MARK: - @delegate ChatEmotionInputViewDelegate protocol ChatEmotionInputViewDelegate: class { /** 点击表情 Cell - parameter cell: 表情 cell */ func chatEmoticonInputViewDidTapCell(_ cell: TSChatEmotionCell) /** 点击表情退后键 - parameter cell: 退后的 cell */ func chatEmoticonInputViewDidTapBackspace(_ cell: TSChatEmotionCell) /** 点击发送键 */ func chatEmoticonInputViewDidTapSend() }
mit
957baf3e65b04a0222e08a8cce1665ec
31.247525
142
0.683144
4.93859
false
false
false
false
iOkay/MiaoWuWu
Pods/Material/Sources/iOS/TextField.swift
1
19919
/* * Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.io>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of CosmicMind nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY 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 HOLDER 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 UIKit private var TextFieldContext: UInt8 = 0 @objc(TextFieldDelegate) public protocol TextFieldDelegate: UITextFieldDelegate { /** A delegation method that is executed when the textField changed. - Parameter textField: A UITextField. - Parameter didChange text: An optional String. */ @objc optional func textField(textField: UITextField, didChange text: String?) /** A delegation method that is executed when the textField will clear. - Parameter textField: A UITextField. - Parameter willClear text: An optional String. */ @objc optional func textField(textField: UITextField, willClear text: String?) /** A delegation method that is executed when the textField is cleared. - Parameter textField: A UITextField. - Parameter didClear text: An optional String. */ @objc optional func textField(textField: UITextField, didClear text: String?) } open class TextField: UITextField { /// Will layout the view. open var willLayout: Bool { return 0 < width && 0 < height && nil != superview } /// Default size when using AutoLayout. open override var intrinsicContentSize: CGSize { return CGSize(width: width, height: 32) } /// A Boolean that indicates if the placeholder label is animated. @IBInspectable open var isPlaceholderAnimated = true /// A Boolean that indicates if the TextField is in an animating state. open internal(set) var isAnimating = false open override var leftView: UIView? { didSet { prepareLeftView() layoutSubviews() } } /// A boolean indicating whether the text is empty. open var isEmpty: Bool { return true == text?.isEmpty } /// The leftView width value. open var leftViewWidth: CGFloat { guard nil != leftView else { return 0 } return leftViewOffset + height } /// The leftView width value. open var leftViewOffset: CGFloat = 16 /// Divider normal height. @IBInspectable open var dividerNormalHeight: CGFloat = 1 /// Divider active height. @IBInspectable open var dividerActiveHeight: CGFloat = 2 /// Divider normal color. @IBInspectable open var dividerNormalColor = Color.darkText.dividers { didSet { guard !isEditing else { return } dividerColor = dividerNormalColor } } /// Divider active color. @IBInspectable open var dividerActiveColor = Color.blue.base { didSet { guard isEditing else { return } dividerColor = dividerActiveColor } } /// The placeholderLabel font value. @IBInspectable open override var font: UIFont? { didSet { placeholderLabel.font = font } } /// TextField's text property observer. @IBInspectable open override var text: String? { didSet { guard isEmpty else { return } guard !isFirstResponder else { return } placeholderEditingDidEndAnimation() } } /// The placeholderLabel text value. @IBInspectable open override var placeholder: String? { get { return placeholderLabel.text } set(value) { placeholderLabel.text = value } } /// The placeholder UILabel. @IBInspectable open private(set) lazy var placeholderLabel = UILabel() /// Placeholder normal text @IBInspectable open var placeholderNormalColor = Color.darkText.others { didSet { updatePlaceholderLabelColor() } } /// Placeholder active text @IBInspectable open var placeholderActiveColor = Color.blue.base { didSet { tintColor = placeholderActiveColor updatePlaceholderLabelColor() } } /// This property adds a padding to placeholder y position animation @IBInspectable open var placeholderVerticalOffset: CGFloat = 0 /// The detailLabel UILabel that is displayed. @IBInspectable open private(set) lazy var detailLabel = UILabel() /// The detailLabel text value. @IBInspectable open var detail: String? { get { return detailLabel.text } set(value) { detailLabel.text = value } } /// Detail text @IBInspectable open var detailColor = Color.darkText.others { didSet { updateDetailLabelColor() } } /// Vertical distance for the detailLabel from the divider. @IBInspectable open var detailVerticalOffset: CGFloat = 8 { didSet { layoutDetailLabel() } } /// Handles the textAlignment of the placeholderLabel. open override var textAlignment: NSTextAlignment { get { return super.textAlignment } set(value) { super.textAlignment = value placeholderLabel.textAlignment = value detailLabel.textAlignment = value } } /// A reference to the clearIconButton. open private(set) var clearIconButton: IconButton? /// Enables the clearIconButton. @IBInspectable open var isClearIconButtonEnabled: Bool { get { return nil != clearIconButton } set(value) { guard value else { clearIconButton?.removeTarget(self, action: #selector(handleClearIconButton), for: .touchUpInside) clearIconButton = nil return } guard nil == clearIconButton else { return } clearIconButton = IconButton(image: Icon.cm.clear, tintColor: placeholderNormalColor) clearIconButton!.contentEdgeInsetsPreset = .none clearIconButton!.pulseAnimation = .none clearButtonMode = .never rightViewMode = .whileEditing rightView = clearIconButton isClearIconButtonAutoHandled = isClearIconButtonAutoHandled ? true : false layoutSubviews() } } /// Enables the automatic handling of the clearIconButton. @IBInspectable open var isClearIconButtonAutoHandled = true { didSet { clearIconButton?.removeTarget(self, action: #selector(handleClearIconButton), for: .touchUpInside) guard isClearIconButtonAutoHandled else { return } clearIconButton?.addTarget(self, action: #selector(handleClearIconButton), for: .touchUpInside) } } /// A reference to the visibilityIconButton. open private(set) var visibilityIconButton: IconButton? /// Enables the visibilityIconButton. @IBInspectable open var isVisibilityIconButtonEnabled: Bool { get { return nil != visibilityIconButton } set(value) { guard value else { visibilityIconButton?.removeTarget(self, action: #selector(handleVisibilityIconButton), for: .touchUpInside) visibilityIconButton = nil return } guard nil == visibilityIconButton else { return } visibilityIconButton = IconButton(image: Icon.visibility, tintColor: placeholderNormalColor.withAlphaComponent(isSecureTextEntry ? 0.38 : 0.54)) visibilityIconButton!.contentEdgeInsetsPreset = .none visibilityIconButton!.pulseAnimation = .none isSecureTextEntry = true clearButtonMode = .never rightViewMode = .whileEditing rightView = visibilityIconButton isVisibilityIconButtonAutoHandled = isVisibilityIconButtonAutoHandled ? true : false layoutSubviews() } } /// Enables the automatic handling of the visibilityIconButton. @IBInspectable open var isVisibilityIconButtonAutoHandled: Bool = true { didSet { visibilityIconButton?.removeTarget(self, action: #selector(handleVisibilityIconButton), for: .touchUpInside) guard isVisibilityIconButtonAutoHandled else { return } visibilityIconButton?.addTarget(self, action: #selector(handleVisibilityIconButton), for: .touchUpInside) } } open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { guard "placeholderLabel.text" != keyPath else { updatePlaceholderLabelColor() return } guard "detailLabel.text" != keyPath else { updateDetailLabelColor() return } super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context) } deinit { removeObserver(self, forKeyPath: "placeholderLabel.text") removeObserver(self, forKeyPath: "detailLabel.text") } /** An initializer that initializes the object with a NSCoder object. - Parameter aDecoder: A NSCoder instance. */ public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) prepare() } /** An initializer that initializes the object with a CGRect object. If AutoLayout is used, it is better to initilize the instance using the init() initializer. - Parameter frame: A CGRect instance. */ public override init(frame: CGRect) { super.init(frame: frame) prepare() } /// A convenience initializer. public convenience init() { self.init(frame: .zero) } open override func layoutSubviews() { super.layoutSubviews() reload() } open override func layoutSublayers(of layer: CALayer) { super.layoutSublayers(of: layer) guard self.layer == layer else { return } layoutShape() } /// Handles the text editing did begin state. @objc open func handleEditingDidBegin() { placeholderEditingDidBeginAnimation() dividerEditingDidBeginAnimation() } // Live updates the textField text. @objc internal func handleEditingChanged(textField: UITextField) { (delegate as? TextFieldDelegate)?.textField?(textField: self, didChange: textField.text) } /// Handles the text editing did end state. @objc open func handleEditingDidEnd() { placeholderEditingDidEndAnimation() dividerEditingDidEndAnimation() } /// Handles the clearIconButton TouchUpInside event. @objc open func handleClearIconButton() { guard nil == delegate?.textFieldShouldClear || true == delegate?.textFieldShouldClear?(self) else { return } let t = text (delegate as? TextFieldDelegate)?.textField?(textField: self, willClear: t) text = nil (delegate as? TextFieldDelegate)?.textField?(textField: self, didClear: t) } /// Handles the visibilityIconButton TouchUpInside event. @objc open func handleVisibilityIconButton() { isSecureTextEntry = !isSecureTextEntry if !isSecureTextEntry { super.font = nil font = placeholderLabel.font } visibilityIconButton?.tintColor = visibilityIconButton?.tintColor.withAlphaComponent(isSecureTextEntry ? 0.38 : 0.54) } /** Prepares the view instance when intialized. When subclassing, it is recommended to override the prepare method to initialize property values and other setup operations. The super.prepare method should always be called immediately when subclassing. */ open func prepare() { clipsToBounds = false borderStyle = .none backgroundColor = nil contentScaleFactor = Device.scale prepareDivider() preparePlaceholderLabel() prepareDetailLabel() prepareTargetHandlers() prepareTextAlignment() } /// Ensures that the components are sized correctly. open func reload() { guard willLayout else { return } guard !isAnimating else { return } layoutPlaceholderLabel() layoutDetailLabel() layoutButton(button: clearIconButton) layoutButton(button: visibilityIconButton) layoutDivider() layoutLeftView() } /// Layout the placeholderLabel. open func layoutPlaceholderLabel() { let w = leftViewWidth let h = 0 == height ? intrinsicContentSize.height : height guard isEditing || !isEmpty || !isPlaceholderAnimated else { placeholderLabel.frame = CGRect(x: w, y: 0, width: width - w, height: h) return } placeholderLabel.transform = CGAffineTransform.identity placeholderLabel.frame = CGRect(x: w, y: 0, width: width - w, height: h) placeholderLabel.transform = CGAffineTransform(scaleX: 0.75, y: 0.75) switch textAlignment { case .left, .natural: placeholderLabel.x = w case .right: placeholderLabel.x = width - placeholderLabel.width default:break } placeholderLabel.y = -placeholderLabel.height + placeholderVerticalOffset } /// Layout the detailLabel. open func layoutDetailLabel() { let c = dividerContentEdgeInsets detailLabel.sizeToFit() detailLabel.x = c.left detailLabel.y = height + detailVerticalOffset detailLabel.width = width - c.left - c.right } /// Layout the a button. open func layoutButton(button: UIButton?) { guard 0 < width && 0 < height else { return } button?.frame = CGRect(x: width - height, y: 0, width: height, height: height) } /// Layout the divider. open func layoutDivider() { divider.reload() } /// Layout the leftView. open func layoutLeftView() { guard let v = leftView else { return } let w = leftViewWidth v.frame = CGRect(x: 0, y: 0, width: w, height: height) dividerContentEdgeInsets.left = w } /// The animation for the divider when editing begins. open func dividerEditingDidBeginAnimation() { dividerThickness = dividerActiveHeight dividerColor = dividerActiveColor } /// The animation for the divider when editing ends. open func dividerEditingDidEndAnimation() { dividerThickness = dividerNormalHeight dividerColor = dividerNormalColor } /// The animation for the placeholder when editing begins. open func placeholderEditingDidBeginAnimation() { guard isPlaceholderAnimated else { return } guard isEmpty && !isAnimating else { return } isAnimating = true UIView.animate(withDuration: 0.15, animations: { [weak self] in guard let s = self else { return } s.placeholderLabel.transform = CGAffineTransform(scaleX: 0.75, y: 0.75) switch s.textAlignment { case .left, .natural: s.placeholderLabel.x = s.leftViewWidth case .right: s.placeholderLabel.x = s.width - s.placeholderLabel.width default:break } s.placeholderLabel.y = -s.placeholderLabel.height + s.placeholderVerticalOffset }) { [weak self] _ in self?.isAnimating = false } } /// The animation for the placeholder when editing ends. open func placeholderEditingDidEndAnimation() { guard isPlaceholderAnimated else { return } guard isEmpty && !isAnimating else { return } isAnimating = true UIView.animate(withDuration: 0.15, animations: { [weak self] in guard let s = self else { return } s.placeholderLabel.transform = CGAffineTransform.identity s.placeholderLabel.x = s.leftViewWidth s.placeholderLabel.y = 0 s.placeholderLabel.textColor = s.placeholderNormalColor }) { [weak self] _ in self?.isAnimating = false } } /// Prepares the divider. private func prepareDivider() { dividerColor = dividerNormalColor } /// Prepares the placeholderLabel. private func preparePlaceholderLabel() { font = RobotoFont.regular(with: 16) placeholderNormalColor = Color.darkText.others addSubview(placeholderLabel) addObserver(self, forKeyPath: "placeholderLabel.text", options: [], context: &TextFieldContext) } /// Prepares the detailLabel. private func prepareDetailLabel() { detailLabel.font = RobotoFont.regular(with: 12) detailLabel.numberOfLines = 0 detailColor = Color.darkText.others addSubview(detailLabel) addObserver(self, forKeyPath: "detailLabel.text", options: [], context: &TextFieldContext) } /// Prepares the leftView. private func prepareLeftView() { leftView?.contentMode = .left } /// Prepares the target handlers. private func prepareTargetHandlers() { addTarget(self, action: #selector(handleEditingDidBegin), for: .editingDidBegin) addTarget(self, action: #selector(handleEditingChanged), for: .editingChanged) addTarget(self, action: #selector(handleEditingDidEnd), for: .editingDidEnd) } /// Prepares the textAlignment. private func prepareTextAlignment() { textAlignment = .rightToLeft == UIApplication.shared.userInterfaceLayoutDirection ? .right : .left } /// Updates the placeholderLabel attributedText. private func updatePlaceholderLabelColor() { guard let v = placeholder else { return } placeholderLabel.attributedText = NSAttributedString(string: v, attributes: [NSForegroundColorAttributeName: isEditing ? placeholderActiveColor : placeholderNormalColor]) } /// Updates the detailLabel attributedText. private func updateDetailLabelColor() { guard let v = detail else { return } detailLabel.attributedText = NSAttributedString(string: v, attributes: [NSForegroundColorAttributeName: detailColor]) } }
gpl-3.0
84985814754a17d7d7d3421158ab7054
29.089124
178
0.644912
5.013592
false
false
false
false
TwoRingSoft/shared-utils
Examples/OperationDemo/OperationDemo/CompoundOperation.swift
1
2376
// // CompoundOperation.swift // FABOperationDemo // // Created by Andrew McKnight on 3/15/16. // Copyright © 2016 Twitter. All rights reserved. // import Cocoa import Pippin class DemoCompoundOperation: FABCompoundOperation { var delegate: OperationStateChangeDelegate! var imageView: NSImageView var color: NSColor init(imageView: NSImageView, color: NSColor, delegate: OperationStateChangeDelegate, name: String) { self.imageView = imageView self.color = color self.delegate = delegate super.init() self.completionBlock = { delegate.operationSyncCompletionCalled(self) } self.asyncCompletion = { errorOptional in if let error = errorOptional { delegate.operationAsyncCompletionCalled(self, withError: error) } else { delegate.operationAsyncCompletionCalled(self) } } self.name = name self.compoundQueue.maxConcurrentOperationCount = 1 let op1 = DemoAsyncOperation(url: "https://upload.wikimedia.org/wikipedia/commons/c/c5/Number-One.JPG", imageView: imageView, color: NSColor.blueColor(), delegate: delegate, name: "\(name) async suboperation 1") op1.asyncCompletion = { error in delegate.operationAsyncCompletionCalled(op1) } op1.completionBlock = { delegate.operationSyncCompletionCalled(op1) } let op2 = DemoAsyncOperation(url: "https://upload.wikimedia.org/wikipedia/commons/1/18/Roman_Numeral_2.gif", imageView: imageView, color: NSColor.redColor(), delegate: delegate, name: "\(name) async suboperation 2") op2.asyncCompletion = { error in delegate.operationAsyncCompletionCalled(op2) } op2.completionBlock = { delegate.operationSyncCompletionCalled(op2) } let op3 = DemoAsyncOperation(url: "https://upload.wikimedia.org/wikipedia/commons/0/0a/Number-three.JPG", imageView: imageView, color: NSColor.orangeColor(), delegate: delegate, name: "\(name) async suboperation 3") op3.asyncCompletion = { error in delegate.operationAsyncCompletionCalled(op3) } op3.completionBlock = { delegate.operationSyncCompletionCalled(op3) } self.operations = [ op1, op2, op3 ] } }
mit
42e71829da21e8e563c890c500cb26ba
35.538462
223
0.657684
4.447566
false
false
false
false
wftllc/hahastream
Haha Stream/Features/Home/HomeViewController.swift
1
1608
import UIKit class HomeViewController: HahaTabBarController { override func viewDidLoad() { super.viewDidLoad() var viewControllers:[UIViewController] = [] self.provider.getSports(success: { (theSports) in let sports = theSports.sorted(by: { (a, b) -> Bool in return a.name < b.name }) viewControllers.append(self.appRouter.nowPlayingViewController()); var haveVCS = false; for sport in sports { let tabBarItem = UITabBarItem(title: sport.name, image: nil, selectedImage: nil) let vc:UIViewController if sport.name.lowercased() == "vue" { haveVCS = true } else { vc = self.appRouter.viewController(forSport: sport) vc.tabBarItem = tabBarItem viewControllers.append(vc) } } if haveVCS { viewControllers.append(self.appRouter.vcsViewController()) } viewControllers.append(self.appRouter.accountViewController()) self.setViewControllers(viewControllers, animated: false) self.setNeedsFocusUpdate(); // self.updateFocusIfNeeded(); }, apiError: apiErrorClosure, networkFailure: networkFailureClosure) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* override var preferredFocusEnvironments: [UIFocusEnvironment] { let def = super.preferredFocusEnvironments; guard let vcs = self.viewControllers else { return def; } if vcs.count == 2 { //if only one sport, focus on it by default var res = def; res.insert(vcs[0], at: 0) return res } else { return def; } } */ }
mit
3f2ad489db04b50d01e65a29c2d47cb9
23
84
0.69092
3.605381
false
false
false
false
MyHammer/MHAppIndexing
Example/Tests/MHUserActivityManagerTest.swift
1
5639
// // MHUserActivityManagerTest.swift // MHAppIndexing // // Created by Andre Hess on 27.05.16. // Copyright © 2016 CocoaPods. All rights reserved. // import XCTest import Nimble import CoreSpotlight @testable import MHAppIndexing class MHUserActivityManagerTest: XCTestCase { let activityManager = MHUserActivityManager.sharedInstance var userActivity:NSUserActivity! override func setUp() { super.setUp() self.activityManager.activities = [] } override func tearDown() { super.tearDown() } func testContentAttributeSetFromSearchObjectOnAddObjectToSearchIndex() { class TestUserActivityManager:MHUserActivityManager { var contentAttributeSetFromSearchObjectWasCalled = false override func contentAttributeSetFromSearchObject(searchObject: MHUserActivityObject, completion: ((attributeSet: CSSearchableItemAttributeSet) -> Void)?) { contentAttributeSetFromSearchObjectWasCalled = true } } let testObject:ExampleObject = ExampleObject() let testActivityManager = TestUserActivityManager() testActivityManager.addObjectToSearchIndex(testObject) expect(testActivityManager.contentAttributeSetFromSearchObjectWasCalled).to(equal(true)) } func testSettingCorrectValuesOnAddObjectToSearchIndex() { class TestUserActivityManager:MHUserActivityManager { var activityTypeString:String! var testUserActivity:NSUserActivity! override func createUserActivity(activityType:String) -> NSUserActivity { testUserActivity = NSUserActivity(activityType:activityType) return testUserActivity } } let testObject:ExampleObject = ExampleObject() testObject.mhDomainIdentifier = "com.sowas.tolles.hier" testObject.mhUniqueIdentifier = "1234567891" testObject.mhTitle = "Beispiel26" testObject.mhContentDescription = "Hier steht die ContentDescription1" testObject.mhWebpageURL = NSURL(string:"https://www.leo.org") testObject.mhEligibleForSearch = true testObject.mhUserInfo = ["userInfoKey": "userInfoValue"] let testActivityManager = TestUserActivityManager() testActivityManager.addObjectToSearchIndex(testObject) expect(testActivityManager.testUserActivity.title).to(equal(testObject.mhTitle)) expect(testActivityManager.testUserActivity.activityType).to(equal(testObject.mhDomainIdentifier+":"+testObject.mhUniqueIdentifier)) expect(testActivityManager.testUserActivity.eligibleForSearch).to(equal(true)) expect(testActivityManager.testUserActivity.eligibleForPublicIndexing).to(equal(false)) expect(testActivityManager.testUserActivity.eligibleForHandoff).to(equal(false)) expect(testActivityManager.testUserActivity.webpageURL).to(equal(testObject.mhWebpageURL)) } func testLoadImageFromImageInfoOnContentAttributeSetFromSearchObject() { class TestUserActivityManager:MHUserActivityManager { var loadImageFromImageInfoCalled = false override func loadImageFromImageInfo(imageInfo: MHImageInfo?, attributes: CSSearchableItemAttributeSet, completion: ((attributeSet: CSSearchableItemAttributeSet) -> Void)?) { loadImageFromImageInfoCalled = true } } let testObject:ExampleObject = ExampleObject() let testActivityManager = TestUserActivityManager() testActivityManager.addObjectToSearchIndex(testObject) expect(testActivityManager.loadImageFromImageInfoCalled).to(equal(true)) } func testSettingAttributesOfAttributeSetCorrectlyOnAddObjectToSearchIndexCompletely() { let testObject:ExampleObject = ExampleObject() testObject.mhDomainIdentifier = "com.sowas.tolles.hier" testObject.mhUniqueIdentifier = "1234567891" testObject.mhTitle = "Beispiel26" testObject.mhContentDescription = "Hier steht die ContentDescription1" testObject.mhKeywords = ["apfel", "birne", "banane"] testObject.mhImageInfo = MHImageInfo(assetImageName:"homer") testObject.mhEligibleForSearch = true class TestUserActivityManager:MHUserActivityManager { override func makeActivityCurrent(activity: NSUserActivity) { expect(activity.contentAttributeSet!.relatedUniqueIdentifier).to(equal("1234567891")) expect(activity.contentAttributeSet!.title).to(equal("Beispiel26")) expect(activity.contentAttributeSet!.contentDescription).to(equal("Hier steht die ContentDescription1")) expect(activity.contentAttributeSet!.keywords).to(equal(["apfel", "birne", "banane"])) } } let testActivityManager = TestUserActivityManager() testActivityManager.addObjectToSearchIndex(testObject) } func testAddingObjectToActivitiesOnMakeActivityCurrent() { self.userActivity = NSUserActivity(activityType:"TestActivity") self.activityManager.makeActivityCurrent(userActivity) expect(self.activityManager.activities.count).to(equal(1)) } func testAddObjectOnMakeActivityCurrent() { class TestArray:NSMutableArray { var addObjectWasCalled = false override func addObject(anObject: AnyObject) { addObjectWasCalled = true } } let testActivities:TestArray = TestArray() self.userActivity = NSUserActivity(activityType:"TestActivity") self.activityManager.activities = testActivities self.activityManager.makeActivityCurrent(userActivity) expect(testActivities.addObjectWasCalled).to(equal(true)) } func testBecomeCurrentOnMakeFirstActivityCurrent() { class TestUserActivity:NSUserActivity { var becomeCurrentCalled = false override func becomeCurrent() { becomeCurrentCalled = true } } let testActivity = TestUserActivity(activityType:"TestActivity") self.activityManager.activities = [testActivity] self.activityManager.makeFirstActivityCurrent() expect(testActivity.becomeCurrentCalled).to(equal(true)) } }
apache-2.0
ebec8f2b470338db5ab8107cddb75088
40.153285
177
0.801703
4.488854
false
true
false
false
ilyathewhite/Euler
EulerSketch/EulerSketch/Commands/Sketch+Combined.playground/Pages/butterfly.xcplaygroundpage/Contents.swift
1
1357
//: Playground - noun: a place where people can play import Cocoa import PlaygroundSupport import EulerSketchOSX let sketch = Sketch() sketch.addPoint("O", hint: (300, 300)) sketch.addCircle("c", withCenter: "O", hintRadius: 200) sketch.addPoint("A", onCircle: "c", hint: (120, 400)) sketch.addPoint("B", onCircle: "c", hint: (467, 400)) sketch.addSegment("AB") sketch.addMidPoint("M", ofSegment: "AB") sketch.addPoint("P", onCircle: "c", hint: (350, 500)) sketch.addPoint("Q", onCircle: "c", hint: (150, 500)) sketch.addIntersection("P1", ofRay: "PM", andCircle: "c", selector: bottomPoint) sketch.addIntersection("Q1", ofRay: "QM", andCircle: "c", selector: bottomPoint) sketch.addSegment("PP1") sketch.addSegment("QQ1") sketch.addSegment("QP1") sketch.addSegment("PQ1") sketch.addIntersection("Q2", ofSegment: "QP1", andSegment: "AB") sketch.addIntersection("P2", ofSegment: "PQ1", andSegment: "AB") sketch.addSegment("MQ2", style: .emphasized) sketch.addSegment("MP2", style: .emphasized) // result sketch.setMarkCount(1, forSegment: "MP2") sketch.setMarkCount(1, forSegment: "MQ2") sketch.assert("MQ2 == MP2") { [unowned sketch] in let MQ2 = try sketch.getSegment("MQ2") let MP2 = try sketch.getSegment("MP2") return same(MQ2.length, MP2.length) } sketch.eval() // live view PlaygroundPage.current.liveView = sketch.quickView()
mit
3fad3a3c59892735f222e4b8c4bcfd14
26.693878
80
0.707443
3.042601
false
false
false
false
ben-ng/swift
validation-test/compiler_crashers_fixed/02101-getselftypeforcontainer.swift
1
663
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck var b { protocol A { typealias e = a() -> T : [l: d { self] { var c, range.E == a"\(e!) protocol f f = a<p { return { _, e where I) -> { } } }()] = b static let a { } var e: a { } enum j { } protocol a { func b: d: P { c: B? = b> ((")(true { typealias A : e() -> T
apache-2.0
8c586a991eea18f1c57f55cb4dfb00f2
23.555556
79
0.641026
3.069444
false
false
false
false
dbahat/conventions-ios
Conventions/Conventions/events/ImportedTicketsView.swift
1
1271
// // ImportedTicketsView.swift // Conventions // // Created by Bahat David on 11/09/2021. // Copyright © 2021 Amai. All rights reserved. // import Foundation class ImportedTicketsView : UIView { @IBOutlet weak var topLabel: UILabel! @IBOutlet weak var image: UIImageView! @IBOutlet weak var midLabel: UILabel! @IBOutlet weak var bottomLabel: UILabel! @IBOutlet weak var logoutButton: UIButton! @IBOutlet weak var updatesButtonImage: UIImageView! var onLogoutClicked: (() -> Void)? var onRefreshClicked: (() -> Void)? required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder); let view = Bundle.main.loadNibNamed(String(describing: ImportedTicketsView.self), owner: self, options: nil)![0] as! UIView; view.frame = self.bounds; addSubview(view); topLabel.textColor = Colors.textColor bottomLabel.textColor = Colors.textColor midLabel.textColor = Colors.textColor logoutButton.tintColor = Colors.buttonColor } @IBAction func refreshWasClicked(_ sender: UITapGestureRecognizer) { onRefreshClicked?() } @IBAction func logoutWasClicked(_ sender: UIButton) { onLogoutClicked?() } }
apache-2.0
01b248dce4ea0e532c97d282cff47bc2
28.534884
132
0.662992
4.568345
false
false
false
false
luanlzsn/pos
pos/pos_iphone/AppDelegate.swift
1
3360
// // AppDelegate.swift // pos_iphone // // Created by luan on 2017/5/14. // Copyright © 2017年 luan. All rights reserved. // import UIKit import IQKeyboardManagerSwift @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { UIApplication.shared.statusBarStyle = .lightContent UINavigationBar.appearance().tintColor = UIColor.white UINavigationBar.appearance().barTintColor = UIColor.init(rgb: 0xe60a16) UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName:UIColor.white] IQKeyboardManager.sharedManager().enable = true IQKeyboardManager.sharedManager().shouldResignOnTouchOutside = true LanguageManager.setupCurrentLanguage() AntManage.iphonePostRequest(path: "route=feed/rest_api/gettoken&grant_type=client_credentials", params: nil, successResult: { (response) in if let data = response["data"] as? [String : Any] { if let accseeToken = data["access_token"] as? String { AntManage.iphoneToken = accseeToken } } }, failureResult: {}) Thread.detachNewThreadSelector(#selector(runOnNewThread), toTarget: self, with: nil) while AntManage.iphoneToken.isEmpty { RunLoop.current.run(mode: .defaultRunLoopMode, before: Date.distantFuture) } return true } func runOnNewThread() { sleep(1) } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
7b46a49700e731cabeb58d42dddf6ca2
44.364865
285
0.711349
5.512315
false
false
false
false
netyouli/WHC_Debuger
WHC_DebugerSwift/WHC_DebugerSwift/WHC_AutoLayoutKit/WHC_AutoCellHeight.swift
1
17379
// // WHC_AutoHeightCell.swift // WHC_AutoLayoutExample // // Created by WHC on 16/7/8. // Copyright © 2016年 吴海超. All rights reserved. // // Github <https://github.com/netyouli/WHC_AutoLayoutKit> // // 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 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 rhs < lhs } } extension UITableView { fileprivate var cacheHeightDictionary:[Int : [Int: CGFloat]]! { set { objc_setAssociatedObject(self, &WHC_AssociatedObjectKey.kCacheHeightDictionary, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } get { let value = objc_getAssociatedObject(self, &WHC_AssociatedObjectKey.kCacheHeightDictionary) return value as? [Int : [Int: CGFloat]] } } open override class func initialize() { struct WHC_TableViewLoad { static var token: Int = 0 } if (WHC_TableViewLoad.token == 0) { WHC_TableViewLoad.token = 1; let reloadData = class_getInstanceMethod(self, #selector(UITableView.reloadData)) let whc_ReloadData = class_getInstanceMethod(self, #selector(UITableView.whc_ReloadData)) method_exchangeImplementations(reloadData, whc_ReloadData) let reloadDataRow = class_getInstanceMethod(self, #selector(UITableView.reloadRows(at:with:))) let whc_ReloadDataRow = class_getInstanceMethod(self, #selector(UITableView.whc_ReloadRowsAtIndexPaths(_:withRowAnimation:))) method_exchangeImplementations(reloadDataRow, whc_ReloadDataRow) let sectionReloadData = class_getInstanceMethod(self, #selector(UITableView.reloadSections(_:with:))) let whc_SectionReloadData = class_getInstanceMethod(self, #selector(UITableView.whc_ReloadSections(_:withRowAnimation:))) method_exchangeImplementations(sectionReloadData, whc_SectionReloadData) let deleteCell = class_getInstanceMethod(self, #selector(UITableView.deleteRows(at:with:))) let whc_deleteCell = class_getInstanceMethod(self, #selector(UITableView.whc_DeleteRowsAtIndexPaths(_:withRowAnimation:))) method_exchangeImplementations(deleteCell, whc_deleteCell) let deleteSection = class_getInstanceMethod(self, #selector(UITableView.deleteSections(_:with:))) let whc_deleteSection = class_getInstanceMethod(self, #selector(UITableView.whc_DeleteSections(_:withRowAnimation:))) method_exchangeImplementations(deleteSection, whc_deleteSection) let moveSection = class_getInstanceMethod(self, #selector(UITableView.moveSection(_:toSection:))) let whc_moveSection = class_getInstanceMethod(self, #selector(UITableView.whc_MoveSection(_:toSection:))) method_exchangeImplementations(moveSection, whc_moveSection) let moveRowAtIndexPath = class_getInstanceMethod(self, #selector(UITableView.moveRow(at:to:))) let whc_moveRowAtIndexPath = class_getInstanceMethod(self, #selector(UITableView.whc_MoveRowAtIndexPath(_:toIndexPath:))) method_exchangeImplementations(moveRowAtIndexPath, whc_moveRowAtIndexPath) let insertSections = class_getInstanceMethod(self, #selector(UITableView.self.insertSections(_:with:))) let whc_insertSections = class_getInstanceMethod(self, #selector(UITableView.whc_InsertSections(_:withRowAnimation:))) method_exchangeImplementations(insertSections, whc_insertSections) let insertRowsAtIndexPaths = class_getInstanceMethod(self, #selector(UITableView.insertRows(at:with:))) let whc_insertRowsAtIndexPaths = class_getInstanceMethod(self, #selector(UITableView.whc_InsertRowsAtIndexPaths(_:withRowAnimation:))) method_exchangeImplementations(insertRowsAtIndexPaths, whc_insertRowsAtIndexPaths) } } @objc fileprivate func whc_ReloadData() { cacheHeightDictionary?.removeAll() self.whc_ReloadData() } @objc fileprivate func whc_ReloadRowsAtIndexPaths(_ indexPaths: [IndexPath], withRowAnimation: UITableViewRowAnimation) { if cacheHeightDictionary != nil { for indexPath in indexPaths { let sectionCacheHeightDictionary = cacheHeightDictionary[(indexPath as NSIndexPath).section] if sectionCacheHeightDictionary != nil { cacheHeightDictionary[(indexPath as NSIndexPath).section]!.removeValue(forKey: (indexPath as NSIndexPath).row) } } } self.whc_ReloadRowsAtIndexPaths(indexPaths, withRowAnimation: withRowAnimation) } @objc fileprivate func whc_ReloadSections(_ sections: IndexSet, withRowAnimation animation: UITableViewRowAnimation) { if cacheHeightDictionary != nil { for (idx,_) in sections.enumerated() { let _ = self.cacheHeightDictionary?.removeValue(forKey: idx) } } self.whc_ReloadSections(sections, withRowAnimation: animation) } @objc fileprivate func whc_DeleteRowsAtIndexPaths(_ indexPaths: [IndexPath], withRowAnimation animation: UITableViewRowAnimation) { if cacheHeightDictionary != nil { for indexPath in indexPaths { if cacheHeightDictionary[(indexPath as NSIndexPath).section] != nil { cacheHeightDictionary[(indexPath as NSIndexPath).section]!.removeValue(forKey: (indexPath as NSIndexPath).row) } } } self.whc_DeleteRowsAtIndexPaths(indexPaths, withRowAnimation: animation) } @objc fileprivate func whc_DeleteSections(_ sections: IndexSet, withRowAnimation animation: UITableViewRowAnimation) { if cacheHeightDictionary != nil { for (idx,_) in sections.enumerated() { let _ = self.cacheHeightDictionary?.removeValue(forKey: idx) } handleCacheHeightDictionary() } self.whc_DeleteSections(sections, withRowAnimation: animation) } @objc fileprivate func whc_MoveSection(_ section: Int, toSection newSection: Int) { if cacheHeightDictionary != nil { let sectionMap = cacheHeightDictionary[section] cacheHeightDictionary[section] = cacheHeightDictionary[newSection] cacheHeightDictionary[newSection] = sectionMap } self.whc_MoveSection(section, toSection: newSection) } @objc fileprivate func whc_MoveRowAtIndexPath(_ indexPath: IndexPath, toIndexPath newIndexPath: IndexPath) { if cacheHeightDictionary != nil { var indexPathMap = cacheHeightDictionary[(indexPath as NSIndexPath).section] let indexPathHeight = indexPathMap![(indexPath as NSIndexPath).row] var newIndexPathMap = cacheHeightDictionary[(newIndexPath as NSIndexPath).section] let newIndexPathHeight = newIndexPathMap![(newIndexPath as NSIndexPath).row] let _ = indexPathMap?.updateValue(newIndexPathHeight!, forKey: (indexPath as NSIndexPath).row) let _ = newIndexPathMap?.updateValue(indexPathHeight!, forKey: (newIndexPath as NSIndexPath).row) cacheHeightDictionary.updateValue(indexPathMap!, forKey: (indexPath as NSIndexPath).section) cacheHeightDictionary.updateValue(newIndexPathMap!, forKey: (newIndexPath as NSIndexPath).section) } self.whc_MoveRowAtIndexPath(indexPath, toIndexPath: newIndexPath) } @objc fileprivate func whc_InsertSections(_ sections: IndexSet, withRowAnimation animation: UITableViewRowAnimation) { if cacheHeightDictionary != nil { let firstSection = sections.first let moveSection = cacheHeightDictionary.count if moveSection > firstSection { for section in firstSection! ..< moveSection { let map = cacheHeightDictionary[section] if map != nil { cacheHeightDictionary.removeValue(forKey: section) cacheHeightDictionary.updateValue(map!, forKey: section + sections.count) } } } } self.whc_InsertSections(sections, withRowAnimation: animation) } @objc fileprivate func whc_InsertRowsAtIndexPaths(_ indexPaths: [IndexPath], withRowAnimation animation: UITableViewRowAnimation) { if cacheHeightDictionary != nil { for indexPath in indexPaths { var sectionMap = cacheHeightDictionary[(indexPath as NSIndexPath).section] if sectionMap != nil { let moveRow = sectionMap!.count if moveRow > (indexPath as NSIndexPath).row { for index in (indexPath as NSIndexPath).row ..< moveRow { let height = sectionMap?[index] if height != nil { let _ = sectionMap?.removeValue(forKey: index) let _ = sectionMap?.updateValue(height!, forKey: index + 1) } } cacheHeightDictionary.updateValue(sectionMap!, forKey: (indexPath as NSIndexPath).section) } } } } self.whc_InsertRowsAtIndexPaths(indexPaths, withRowAnimation: animation) } fileprivate func handleCacheHeightDictionary() { if cacheHeightDictionary != nil { let allKey = cacheHeightDictionary.keys.sorted{$0 < $1} var frontKey = -1 var index = 0 for (idx, key) in allKey.enumerated() { if frontKey == -1 { frontKey = key }else { if key - frontKey > 1 { if index == 0 { index = frontKey } cacheHeightDictionary.updateValue(cacheHeightDictionary[key]!, forKey: allKey[index] + 1) cacheHeightDictionary.removeValue(forKey: key) index = idx } frontKey = key } } } } } public extension UITableViewCell { /// cell上最底部的视图 public var whc_CellBottomView: UIView! { set { objc_setAssociatedObject(self, &WHC_AssociatedObjectKey.kCellBottomView, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } get { let value = objc_getAssociatedObject(self, &WHC_AssociatedObjectKey.kCellBottomView) if value != nil { return value as! UIView } return nil } } /// cell上最底部的视图集合 public var whc_CellBottomViews: [UIView]! { set { objc_setAssociatedObject(self, &WHC_AssociatedObjectKey.kCellBottomViews, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } get { let value = objc_getAssociatedObject(self, &WHC_AssociatedObjectKey.kCellBottomViews) if value != nil { return value as! [UIView] } return nil } } /// cell上最底部的视图与cell底部偏移量 public var whc_CellBottomOffset: CGFloat { set { objc_setAssociatedObject(self, &WHC_AssociatedObjectKey.kCellBottomOffset, NSNumber(value: Float(newValue) as Float), .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } get { let value = objc_getAssociatedObject(self, &WHC_AssociatedObjectKey.kCellBottomOffset) if value != nil { return CGFloat((value as! NSNumber).floatValue) } return 0 } } /// cell上嵌套tableview对象 public var whc_CellTableView: UITableView! { set { objc_setAssociatedObject(self, &WHC_AssociatedObjectKey.kCellTableView, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } get { let value = objc_getAssociatedObject(self, &WHC_AssociatedObjectKey.kCellTableView) if value != nil { return value as! UITableView } return nil } } public var whc_TableViewWidth: CGFloat { set { objc_setAssociatedObject(self, &WHC_AssociatedObjectKey.kCellTableViewWidth, NSNumber(value: Float(newValue) as Float), .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } get { let value = objc_getAssociatedObject(self, &WHC_AssociatedObjectKey.kCellTableViewWidth) if value != nil { return CGFloat((value as! NSNumber).floatValue) } return 0.0 } } /** * 说明: 自动计算cell高度 * @param indexPath 当前cell index * @param tableView 当前列表对象 * @return cell高度 */ public class func whc_CellHeightForIndexPath(_ indexPath: IndexPath, tableView: UITableView) -> CGFloat { if tableView.cacheHeightDictionary == nil { tableView.cacheHeightDictionary = [Int : [Int: CGFloat]]() } var sectionCacheHeightDictionary = tableView.cacheHeightDictionary[(indexPath as NSIndexPath).section] if sectionCacheHeightDictionary != nil { let cellHeight = sectionCacheHeightDictionary![(indexPath as NSIndexPath).row] if cellHeight != nil { return cellHeight! } }else { sectionCacheHeightDictionary = [Int: CGFloat]() tableView.cacheHeightDictionary[(indexPath as NSIndexPath).section] = sectionCacheHeightDictionary } let cell = tableView.dataSource?.tableView(tableView, cellForRowAt: indexPath) if cell == nil {return 0} cell?.whc_CellTableView?.whc_Height((cell?.whc_CellTableView?.contentSize.height)!) var tableViewWidth = cell?.whc_TableViewWidth if tableViewWidth != nil && tableViewWidth == 0 { tableView.layoutIfNeeded() tableViewWidth = tableView.frame.width } if tableViewWidth == 0 {return 0} var cellFrame = cell?.frame var contentFrame = cell?.contentView.frame contentFrame?.size.width = tableViewWidth! cellFrame?.size.width = tableViewWidth! cell?.contentView.frame = contentFrame! cell?.frame = cellFrame! cell?.layoutIfNeeded() var bottomView: UIView! if cell?.whc_CellBottomView != nil { bottomView = cell?.whc_CellBottomView }else if cell?.whc_CellBottomViews?.count > 0 { bottomView = cell?.whc_CellBottomViews[0] for i in 1 ..< cell!.whc_CellBottomViews.count { let view: UIView! = cell?.whc_CellBottomViews[i] if bottomView.frame.maxY < view.frame.maxY { bottomView = view } } }else { let cellSubViews = cell?.contentView.subviews if cellSubViews?.count > 0 { bottomView = cellSubViews![0] for i in 1 ..< cellSubViews!.count { let view = cellSubViews![i] if bottomView.frame.maxY < view.frame.maxY { bottomView = view } } }else { bottomView = cell?.contentView } } let cellHeight = bottomView.frame.maxY + cell!.whc_CellBottomOffset let _ = sectionCacheHeightDictionary?.updateValue(cellHeight, forKey: (indexPath as NSIndexPath).row) tableView.cacheHeightDictionary.updateValue(sectionCacheHeightDictionary!, forKey: (indexPath as NSIndexPath).section) return cellHeight } }
mit
22bea3e9caf78f4feff944bd61207121
43.963542
167
0.62458
5.112822
false
false
false
false
webim/webim-client-sdk-ios
Example/Tests/WebimInternalLoggerTests.swift
1
4242
// // WebimInternalLoggerTests.swift // WebimClientLibrary // // Created by Nikita Lazarev-Zubov on 16.01.18. // Copyright © 2018 Webim. All rights reserved. // // 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 XCTest @testable import WebimClientLibrary class WebimInternalLoggerTests: XCTestCase { // MARK: - Properties let webimInternalLogger = WebimInternalLogger.shared var logEntry: String? // MARK: Methods override func setUp() { super.setUp() logEntry = nil } // MARK: - Tests func testSetup() { // When: Low verbosity level installed and high verbosity level log message is send. WebimInternalLogger.setup(webimLogger: self, verbosityLevel: .error) webimInternalLogger.log(entry: "Test", verbosityLevel: .verbose) // Then: WebimLogger method should not be called. XCTAssertNil(logEntry) } func testLogWithSameVerbosityLevelIsPassed() { // Setup. let verbosityLevel = SessionBuilder.WebimLoggerVerbosityLevel.debug let logString = "Test" // When: Logger installed and log entry passed with the same verbosity level. WebimInternalLogger.setup(webimLogger: self, verbosityLevel: verbosityLevel) webimInternalLogger.log(entry: logString, verbosityLevel: verbosityLevel) // Then: Log entry should be passed to WebimLogger. XCTAssertNotNil(logEntry) } func testLogWithLowerVerbosityLevelIsPassed() { // Setup. let verbosityLevel = SessionBuilder.WebimLoggerVerbosityLevel.debug let higherVerbosityLevel = SessionBuilder.WebimLoggerVerbosityLevel.verbose let logString = "Test" // When: Logger installed and log entry passed with lower verbosity level. WebimInternalLogger.setup(webimLogger: self, verbosityLevel: higherVerbosityLevel) webimInternalLogger.log(entry: logString, verbosityLevel: verbosityLevel) // Then: Log entry should be passed to WebimLogger. XCTAssertNotNil(logEntry) } func testLogWithHigherVerbosityLevelIsNotPassed() { // Setup. let verbosityLevel = SessionBuilder.WebimLoggerVerbosityLevel.debug let lowerVerbosityLevel = SessionBuilder.WebimLoggerVerbosityLevel.info let logString = "Test" // When: Logger installed and log entry passed with higher verbosity level. WebimInternalLogger.setup(webimLogger: self, verbosityLevel: lowerVerbosityLevel) webimInternalLogger.log(entry: logString, verbosityLevel: verbosityLevel) // Then: Log entry should be passed to WebimLogger. XCTAssertNil(logEntry) } } // MARK: - WebimLogger extension WebimInternalLoggerTests: WebimLogger { func log(entry: String) { logEntry = entry } }
mit
396b3e75bfb7a5152e2f72c54e8cc71c
36.866071
92
0.658335
4.983549
false
true
false
false
seuzl/iHerald
Herald/CenterViewController.swift
1
8866
// // CenterViewController.swift // 先声 // // Created by Wangshuo on 14-8-1. // Copyright (c) 2014年 WangShuo. All rights reserved. // import UIKit class CenterViewController: UIViewController ,UIScrollViewDelegate{ var scrollView:UIScrollView! var pageControl:UIPageControl! var imageView:UIImageView! var imageView1:UIImageView? var imageView2:UIImageView? var imageView3:UIImageView? var imageView4:UIImageView? var imageView5:UIImageView? var screenSize:CGSize = UIScreen.mainScreen().bounds.size let imageCache:SDImageCache = SDImageCache() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.navigationItem.title = "先声" self.setupLeftMenuButton() self.setupScrollPic() } func setupLeftMenuButton() { let image = UIImage(named: "leftButton.png") let leftDrawerButton = UIButton(frame: CGRectMake(0, 0, 28, 28)) leftDrawerButton.setBackgroundImage(image, forState: UIControlState.Normal) leftDrawerButton.addTarget(self, action: Selector("leftDrawerButtonPress:"), forControlEvents: UIControlEvents.TouchUpInside) let leftButton:UIBarButtonItem = UIBarButtonItem(customView: leftDrawerButton) self.navigationItem.setLeftBarButtonItem(leftButton, animated: true) } func leftDrawerButtonPress(sender:AnyObject) { self.mm_drawerController.toggleDrawerSide(MMDrawerSide.Left, animated: true, completion: nil) } func setupScrollPic() { let color = UIColor(red: 255/255, green: 255/255, blue: 255/255, alpha: 1) self.navigationController?.navigationBar.barTintColor = color self.scrollView = UIScrollView(frame: CGRectMake(0, 64, self.screenSize.width, self.screenSize.height/2.5)) self.scrollView.delegate = self let scrollSize:CGSize = CGSizeMake(self.screenSize.width * 5, 0) self.scrollView.contentSize = scrollSize self.scrollView.showsHorizontalScrollIndicator = false self.scrollView.pagingEnabled = true self.scrollView.maximumZoomScale = 2.0 self.scrollView.bounces = false let pageControlSize:CGSize = CGSizeMake(120, 40) let framePageControl:CGRect = CGRectMake((self.scrollView.frame.width-pageControlSize.width)/2, self.screenSize.height/2.25, pageControlSize.width, pageControlSize.height) self.pageControl = UIPageControl(frame: framePageControl) self.pageControl.hidesForSinglePage = true self.pageControl.userInteractionEnabled = false self.pageControl.backgroundColor = UIColor.clearColor() self.pageControl.numberOfPages = 5 var imageArray :[UIImageView!] = [self.imageView1,self.imageView2,self.imageView3,self.imageView4,self.imageView5] var count:CGFloat = 0 for i in 0..<5 { let nameCounter = String(i + 1) let imageName:String = "image" + nameCounter + ".png" //get the image1.png to image5.png let xPosition = self.screenSize.width * count imageArray[i] = UIImageView(frame: CGRectMake(xPosition, -64, self.screenSize.width, self.scrollView!.frame.height)) imageArray[i].image = UIImage(named: imageName) self.scrollView!.addSubview(imageArray[i]) count = count + 1 } self.imageView = UIImageView(frame: CGRectMake(0, 64 + self.scrollView.frame.height, self.screenSize.width, self.screenSize.height - 64 - self.scrollView.frame.height)) self.imageView.image = UIImage(named: "MainPagePic.jpg") self.imageView.userInteractionEnabled = true self.view.addSubview(self.scrollView) self.view.addSubview(self.pageControl) self.view.addSubview(self.imageView) let schoolLifeButton = UIButton(frame: CGRectMake(0, 0, self.imageView.frame.width / 2, self.imageView.frame.height / 2)) schoolLifeButton.addTarget(self, action: Selector("schoolLifeClicked"), forControlEvents: UIControlEvents.TouchUpInside) self.imageView.addSubview(schoolLifeButton) let studyLecture = UIButton(frame: CGRectMake(0, self.imageView.frame.width / 2, self.imageView.frame.width / 2, self.imageView.frame.height / 2)) studyLecture.addTarget(self, action: Selector("studyLectureClicked"), forControlEvents: UIControlEvents.TouchUpInside) self.imageView.addSubview(studyLecture) let libraryButton = UIButton(frame: CGRectMake(self.imageView.frame.width / 2, 0, self.imageView.frame.width / 2, self.imageView.frame.height / 2)) libraryButton.addTarget(self, action: Selector("libraryClicked"), forControlEvents: UIControlEvents.TouchUpInside) self.imageView.addSubview(libraryButton) let simSimiButton = UIButton(frame: CGRectMake(self.imageView.frame.width / 2, self.imageView.frame.width / 2, self.imageView.frame.width / 2, self.imageView.frame.height / 2)) simSimiButton.addTarget(self, action: Selector("simsimiClicked"), forControlEvents: UIControlEvents.TouchUpInside) self.imageView.addSubview(simSimiButton) } func scrollViewDidEndDecelerating(scrollView: UIScrollView) { let index = fabs(self.scrollView!.contentOffset.x) / self.screenSize.width let i = Int(index) self.pageControl.currentPage = i } func schoolLifeClicked() { let mydrawerController = self.mm_drawerController let schoolLifeViewController:SchoolLifeViewController = SchoolLifeViewController(nibName: "SchoolLifeViewController", bundle: nil) let navSchoolLifeViewController = CommonNavViewController(rootViewController: schoolLifeViewController) self.mm_drawerController.toggleDrawerSide(MMDrawerSide.Left, animated: true, completion:{(complete) in if complete{ mydrawerController.setCenterViewController(navSchoolLifeViewController, withCloseAnimation: true, completion: nil) mydrawerController.closeDrawerAnimated(true, completion:nil) } }) } func libraryClicked() { let mydrawerController = self.mm_drawerController let LibraryVC = LibraryViewController(nibName: "LibraryViewController", bundle: nil) let navLibraryViewController = CommonNavViewController(rootViewController: LibraryVC) self.mm_drawerController.toggleDrawerSide(MMDrawerSide.Left, animated: true, completion: {(complete) in if complete{ mydrawerController.setCenterViewController(navLibraryViewController, withCloseAnimation: true, completion: nil) mydrawerController.closeDrawerAnimated(true, completion:nil) } }) } func studyLectureClicked() { let mydrawerController = self.mm_drawerController let studyLectureViewController:StudyLectureViewController = StudyLectureViewController(nibName: "StudyLectureViewController", bundle: nil) let navStudyLectureViewController = CommonNavViewController(rootViewController: studyLectureViewController) self.mm_drawerController.toggleDrawerSide(MMDrawerSide.Left, animated: true, completion:{(complete) in if complete{ mydrawerController.setCenterViewController(navStudyLectureViewController, withCloseAnimation: true, completion: nil) mydrawerController.closeDrawerAnimated(true, completion:nil) } }) } func simsimiClicked() { let mydrawerController = self.mm_drawerController let simsimiViewController:SimSimiViewController = SimSimiViewController(nibName: "SimSimiViewController", bundle: nil) let navSimSimiViewController = CommonNavViewController(rootViewController: simsimiViewController) self.mm_drawerController.toggleDrawerSide(MMDrawerSide.Left, animated: true, completion:{(complete) in if complete{ mydrawerController.setCenterViewController(navSimSimiViewController, withCloseAnimation: true, completion: nil) mydrawerController.closeDrawerAnimated(true, completion:nil) } }) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
e918c5bf14efcf5a6eb1c428f4a30e92
43.28
184
0.692073
4.992108
false
false
false
false
mapsme/omim
iphone/Maps/UI/Promo/PromoAfterBookingViewController.swift
6
3055
@objc class PromoAfterBookingViewController: UIViewController { private let transitioning = FadeTransitioning<PromoBookingPresentationController>() private var cityImageUrl: String private var okClosure: MWMVoidBlock private var cancelClosure: MWMVoidBlock private var isOnButtonClosed: Bool = false @IBOutlet var cityImageView: UIImageView! @IBOutlet var descriptionLabel: UILabel! { didSet { let desc = L("popup_booking_download_guides_message") let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineSpacing = 3 let attributedDesc = NSAttributedString(string: desc, attributes: [ .font : UIFont.regular14(), .foregroundColor : UIColor.blackSecondaryText(), .paragraphStyle : paragraphStyle ]) descriptionLabel.attributedText = attributedDesc } } @objc init(cityImageUrl: String, okClosure: @escaping MWMVoidBlock, cancelClosure: @escaping MWMVoidBlock) { self.cityImageUrl = cityImageUrl self.okClosure = okClosure self.cancelClosure = cancelClosure super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { setCityImage(cityImageUrl) let eventParams = [kStatProvider: kStatMapsmeGuides, kStatScenario: kStatBooking] Statistics.logEvent(kStatMapsmeInAppSuggestionShown, withParameters: eventParams) } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) if !isOnButtonClosed { let eventParams = [kStatProvider: kStatMapsmeGuides, kStatScenario: kStatBooking, kStatOption: kStatOffscreen] Statistics.logEvent(kStatMapsmeInAppSuggestionClosed, withParameters: eventParams) } } private func setCityImage(_ imageUrl: String) { cityImageView.image = UIColor.isNightMode() ? UIImage(named: "img_booking_popup_pholder_dark") : UIImage(named: "img_booking_popup_pholder_light") if !imageUrl.isEmpty, let url = URL(string: imageUrl) { cityImageView.wi_setImage(with: url, transitionDuration: kDefaultAnimationDuration) } } @IBAction func onOk() { let eventParams = [kStatProvider: kStatMapsmeGuides, kStatScenario: kStatBooking] Statistics.logEvent(kStatMapsmeInAppSuggestionClicked, withParameters: eventParams) isOnButtonClosed = true okClosure() } @IBAction func onCancel() { let eventParams = [kStatProvider: kStatMapsmeGuides, kStatScenario: kStatBooking, kStatOption: kStatCancel] Statistics.logEvent(kStatMapsmeInAppSuggestionClosed, withParameters: eventParams) isOnButtonClosed = true cancelClosure() } override var transitioningDelegate: UIViewControllerTransitioningDelegate? { get { return transitioning } set { } } override var modalPresentationStyle: UIModalPresentationStyle { get { return .custom } set { } } }
apache-2.0
325b882369cb0ea7394a03ca8141fbd0
34.941176
110
0.714239
4.833861
false
false
false
false
cpmpercussion/microjam
chirpey/MicrojamTabBarController.swift
1
5074
// // MicrojamTabBarController.swift // microjam // // Created by Charles Martin on 17/12/16. // Copyright © 2016 Charles Martin. All rights reserved. // import UIKit /// Subclass of UITabBarController to set up tabs programmatically in MicroJam. class MicrojamTabBarController: UITabBarController { /// User Settings View Controller override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) setColourTheme() } override func viewDidLoad() { super.viewDidLoad() print("TABVC: Loaded main tab bar.") // setupWorldTab() setupJamTab() // FIXME test that this does actually work properly. setupProfileTab() // Set up the profile tab. NotificationCenter.default.addObserver(self, selector: #selector(setColourTheme), name: .setColourTheme, object: nil) // notification for colour theme. } deinit { NotificationCenter.default.removeObserver(self, name: .setColourTheme, object: nil) } /// Setup the world tab func setupWorldTab() { // not implemented yet - still done in Main.storyboard // let controller = ExploreController() // controller.tabBarItem = UITabBarItem(title: "explore", image: #imageLiteral(resourceName: "remotejamsTabIcon"), selectedImage: nil) // let navigation = UINavigationController(rootViewController: controller) // viewControllers?.insert(navigation, at: 0) } /// Setup the jam screen func setupJamTab() { let controller = ChirpJamViewController.instantiateJamController() controller.tabBarItem = UITabBarItem(title: TabBarItemTitles.jamTab, image: #imageLiteral(resourceName: "localjamsTabIcon"), selectedImage: nil) let navigation = UINavigationController(rootViewController: controller) viewControllers?.append(navigation) // Accessibility elements controller.isAccessibilityElement = true controller.accessibilityTraits = UIAccessibilityTraits.button controller.accessibilityLabel = "Jam button" controller.accessibilityHint = "Tap to create a new Jam" controller.title = "jam!" } /// Setup profile screen func setupProfileTabStackVersion() { if let controller = ProfileScreenController.storyboardInstance() { controller.tabBarItem = UITabBarItem(title: TabBarItemTitles.profileTab, image: #imageLiteral(resourceName: "profileTabIcon"), selectedImage: nil) // controller.view.translatesAutoresizingMaskIntoConstraints = false let navigation = UINavigationController(rootViewController: controller) viewControllers?.append(navigation) // Accessibility elements controller.isAccessibilityElement = true controller.accessibilityTraits = UIAccessibilityTraits.button controller.accessibilityLabel = "Profile button" controller.accessibilityHint = "Tap to access your user profile" } else { print("TABVC: User Settings Tab could not be initialised.") } } /// Setup new profile screen func setupProfileTab() { if let controller = ProfileScreenController.storyboardInstance() { controller.tabBarItem = UITabBarItem(title: TabBarItemTitles.profileTab, image: #imageLiteral(resourceName: "profileTabIcon"), selectedImage: nil) // controller.view.translatesAutoresizingMaskIntoConstraints = false let navigation = UINavigationController(rootViewController: controller) viewControllers?.append(navigation) // Accessibility elements controller.isAccessibilityElement = true controller.accessibilityTraits = UIAccessibilityTraits.button controller.accessibilityLabel = "Profile button" controller.accessibilityHint = "Tap to access your user profile" } else { print("TABVC: Profile Tab could not be initialised.") } } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } } // Set up dark and light mode. extension MicrojamTabBarController { @objc func setColourTheme() { UserDefaults.standard.bool(forKey: SettingsKeys.darkMode) ? setDarkMode() : setLightMode() } func setDarkMode() { self.tabBar.backgroundColor = DarkMode.background self.tabBar.barTintColor = DarkMode.background self.tabBar.tintColor = DarkMode.highlight } func setLightMode() { self.tabBar.backgroundColor = LightMode.background self.tabBar.barTintColor = LightMode.background self.tabBar.tintColor = LightMode.highlight } }
mit
91dcce4f3aa8c7367b4964791ff19eff
40.581967
159
0.682042
5.408316
false
false
false
false
Osnobel/GDGameExtensions
GDGameExtensions/GDOpenSocial/GDOpenSocial+QQ.swift
1
10837
// // GDOpenSocial+QQ.swift // GDOpenSocial // // Created by Bell on 16/5/28. // Copyright © 2016年 GoshDo <http://goshdo.sinaapp.com>. All rights reserved. // import UIKit public extension GDOpenSocial { public static var isQQInstalled: Bool { get { return self.canOpenURLString("mqqapi://") } } public static var getQQInstallUrl: NSURL { get { return NSURL(string: "https://itunes.apple.com/cn/app/id444934666?mt=8")! } } public static var isQQApiAvailable: Bool { get { return self.isQQInstalled && (self.appId(OSServiceTypeQQ) != nil) } } public static func registerQQApi(appId: String) { self.cacheService(OSServiceTypeQQ, schemes: [self.qqCallbackName(appId), "tencent\(appId)", "tencent\(appId).content"], appId: appId, handleOpenURLHandler: self.qqHandleOpenURL) } public static func shareToQQFriends(message: GDOSMessage, completionHandler handler: GDOSServiceCompletionHandler?) { if self.canService(OSServiceTypeQQ, completionHandler: handler) { self.openURLString(self.genQQShareUrl(message, to:0)) } } public static func shareToQQZone(message: GDOSMessage, completionHandler handler: GDOSServiceCompletionHandler?) { if self.canService(OSServiceTypeQQ, completionHandler: handler) { self.openURLString(self.genQQShareUrl(message, to:1)) } } public static func shareToQQFavorites(message: GDOSMessage, completionHandler handler: GDOSServiceCompletionHandler?) { if self.canService(OSServiceTypeQQ, completionHandler: handler) { self.openURLString(self.genQQShareUrl(message, to:8)) } } public static func shareToQQDataline(message: GDOSMessage, completionHandler handler: GDOSServiceCompletionHandler?) { if self.canService(OSServiceTypeQQ, completionHandler: handler) { self.openURLString(self.genQQShareUrl(message, to:16)) } } // scope = "get_user_info,get_simple_userinfo,add_album,add_idol,add_one_blog,add_pic_t,add_share,add_topic,check_page_fans,del_idol,del_t,get_fanslist,get_idollist,get_info,get_other_info,get_repost_list,list_album,upload_pic,get_vip_info,get_vip_rich_info,get_intimate_friends_weibo,match_nick_tips_weibo" public static func authQQ(scope: String = "get_user_info,get_simple_userinfo,add_share", completionHandler handler: GDOSServiceCompletionHandler?) { if self.canService(OSServiceTypeQQ, completionHandler: handler) { let appid = self.appId(OSServiceTypeQQ)! let authData: Dictionary<String, AnyObject> = ["app_id" : appid, "app_name" : self.bundleDisplayName, "client_id" : appid, "response_type" : "token", "scope" : scope, "sdkp" : "i", "sdkv" : "2.9.3", "status_machine" : UIDevice.currentDevice().model, "status_os" : UIDevice.currentDevice().systemVersion, "status_version" : UIDevice.currentDevice().systemVersion] self.setGeneralPasteboardData("com.tencent.tencent\(appid)", value: authData, encoding: .KeyedArchiver) let authUrlString = "mqqOpensdkSSoLogin://SSoLogin/tencent\(appid)/com.tencent.tencent\(appid)?generalpastboard=1&sdkv=2.9.3" self.openURLString(authUrlString) } } public static func getQQUserInfo(accessToken: String, openId: String, completionHandler handler: GDOSServiceCompletionHandler?) { guard let appid = self.appId(OSServiceTypeQQ) else { print("place register\(OSServiceTypeQQ)Api before you can use service with it!!!") return } let urlString = "https://openmobile.qq.com/user/get_simple_userinfo?openid=\(openId)&oauth_consumer_key=\(appid)&access_token=\(accessToken)" let url = NSURL(string: urlString) let request = NSURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.UseProtocolCachePolicy, timeoutInterval: 20) let session = NSURLSession(configuration: NSURLSessionConfiguration.ephemeralSessionConfiguration()) let task = session.dataTaskWithRequest(request) { (data, response, error) -> Void in guard error == nil else { dispatch_async(dispatch_get_main_queue(), { () -> Void in handler?([:], error) }) return } guard let validData = data where validData.length > 0 else { // print("JSON could not be serialized. Input data was nil or zero length.") dispatch_async(dispatch_get_main_queue(), { () -> Void in let err = NSError(domain: "com.opensocial.getqquserinfo", code: -1, userInfo: [NSLocalizedDescriptionKey:"Get User Info with \(OSServiceTypeQQ) Failed"]) handler?([:], err) }) return } print(String(data: validData, encoding: NSUTF8StringEncoding)!) do { let JSON = try NSJSONSerialization.JSONObjectWithData(validData, options: .AllowFragments) if let result = JSON as? [String: AnyObject] { var err: NSError? = nil let errcode = result["ret"] as? Int ?? -1 if errcode != 0 { let errmsg = result["msg"] as? String ?? "" err = NSError(domain: "com.opensocial.getqquserinfo", code: errcode, userInfo: [NSLocalizedDescriptionKey:"Get User Info with \(OSServiceTypeQQ) Failed: \(errmsg)"]) } dispatch_async(dispatch_get_main_queue(), { () -> Void in handler?(result, err) }) } else { dispatch_async(dispatch_get_main_queue(), { () -> Void in let err = NSError(domain: "com.opensocial.getqquserinfo", code: -1, userInfo: [NSLocalizedDescriptionKey:"Get User Info with \(OSServiceTypeQQ) Failed"]) handler?([:], err) }) } return } catch let e as NSError { dispatch_async(dispatch_get_main_queue(), { () -> Void in handler?([:], e) }) return } } task.resume() session.finishTasksAndInvalidate() } private static let OSServiceTypeQQ: String = "QQ" private static func qqCallbackName(appId: String) -> String { return String(format: "QQ%08llx", NSString(string: appId).longLongValue) } private static func genQQShareUrl(message: GDOSMessage, to: Int) -> String { let msg = message var ret: String = "mqqapi://share/to_fri?thirdAppDisplayName=" ret += self.base64Encode(self.bundleDisplayName) ret += "&version=1&cflag=\(to)" ret += "&callback_type=scheme&generalpastboard=1&callback_name=\(self.qqCallbackName(self.appId(OSServiceTypeQQ)!))" ret += "&src_type=app&shareType=0&file_type=" if msg.link != nil && msg.multimediaType == nil { msg.multimediaType = .News } if msg.image == nil && msg.link == nil && msg.title != nil { //纯文本分享 ret += "text&file_data=" ret += self.urlEncode(self.base64Encode(msg.title!)) } else if msg.link == nil && msg.title != nil && msg.image != nil && msg.description != nil { //图片分享 var data: Dictionary<String, AnyObject> = [:] data["file_data"] = self.imageData(msg.image!) data["previewimagedata"] = msg.thumbnail != nil ? self.imageData(msg.thumbnail!) : self.imageData(msg.image!, toSize: CGSizeMake(36, 36)) self.setGeneralPasteboardData("com.tencent.mqq.api.apiLargeData", value: data, encoding: .KeyedArchiver) ret += "img&title=" ret += self.base64Encode(msg.title!) ret += "&objectlocation=pasteboard&description=" ret += self.base64Encode(msg.description!) } else if msg.title != nil && msg.image != nil && msg.description != nil && msg.link != nil && msg.multimediaType != nil { //新闻/多媒体分享(图片加链接)发送新闻消息 预览图像数据,最大1M字节 URL地址,必填 最长512个字符 let data: Dictionary<String, AnyObject> = ["previewimagedata": self.imageData(msg.image!)] self.setGeneralPasteboardData("com.tencent.mqq.api.apiLargeData", value: data, encoding: .KeyedArchiver) var msgType = "news" if (msg.multimediaType == .Audio) { msgType = "audio" } ret += msgType ret += "&title=" + self.urlEncode(self.base64Encode(msg.title!)) ret += "&url=" + self.urlEncode(self.base64Encode(msg.link!)) ret += "&description=" + self.urlEncode(self.base64Encode(msg.description!)) ret += "&objectlocation=pasteboard" } return ret } private static let qqHandleOpenURL: GDOSHandleOpenURLHandler = {(url) -> Bool in var result = false var data = Dictionary<String, AnyObject>() var error: NSError? = nil if url.scheme.hasPrefix("QQ") { //分享 data = GDOpenSocial.parseUrl(url) if let err_desc = data["error_description"] as? String { data["error_description"] = GDOpenSocial.base64Decode(err_desc) } let err_code = (data["error"] as? NSString)?.integerValue ?? -1 if err_code != 0 { error = NSError(domain: "com.opensocial.sharetoqq", code: err_code, userInfo: [NSLocalizedDescriptionKey:data["error_description"] as? String ?? "Share to \(OSServiceTypeQQ) Failed"]) } result = true } else if url.scheme.hasPrefix("tencent") { //登陆auth let appId = GDOpenSocial.appId(OSServiceTypeQQ)! data = GDOpenSocial.generalPasteboardData("com.tencent.tencent\(appId)", encoding: .KeyedArchiver) let ret_code = data["ret"] as? Int ?? -1 if ret_code != 0 { error = NSError(domain: "com.opensocial.authwithqq", code: ret_code, userInfo: [NSLocalizedDescriptionKey:"Auth with \(OSServiceTypeQQ) Failed"]) } result = true } if result { GDOpenSocial.serviceCompletionHandler?(data, error) GDOpenSocial.serviceCompletionHandler = nil } return result } }
mit
d0b0d9e467433aaf395782ddfbaf9e13
48.662037
311
0.595282
4.309361
false
false
false
false
shuuchen/SwiftTips
initialization_2.swift
1
4851
// class inheritance & initialization // designated & convenience initializers // initializer delegation for class types // A designated initializer must call a designated initializer from its immediate superclass. // A convenience initializer must call another initializer from the same class. // A convenience initializer must ultimately call a designated initializer. // two-phase initialization // step 1: each stored property is assigned an initial value // step 2: customize stored properties further // safe // convenience intializer cannot modify any stored properties before a designated initializer is called within it // initializer inheritance & overriding // by default, swift subclasses do not inherite their superclasses initializers // using "override" when overriding a superclass' designated initializer, even for subclasses' convenience initializers // do not use "override" when overriding a superclass' convenience initializer class Vehicle { var numberOfWheels = 0 var description: String { return "\(numberOfWheels) wheel(s)" } } let vehicle = Vehicle() print("Vehicle: \(vehicle.description)") class Bicycle: Vehicle { override init() { super.init() numberOfWheels = 2 } } let bicycle = Bicycle() print("Bicycle: \(bicycle.description)") // automatic initializer inheritance // if you provided default values for any new properties in the subclass : // if subclass does not define any (designated) initializer, it inherites all of superclass's (designated) initializers // if subclass inherites all of superclass's designated initializers, it automatically inherites all of superclass's convenience initializers class Food { var name: String init(name: String) { self.name = name } convenience init() { self.init(name: "[Unnamed]") } } let namedMeat = Food(name: "Bacon") let mysteryMeat = Food() class RecipeIngredient: Food { var quantity: Int init(name: String, quantity: Int) { self.quantity = quantity super.init(name: name) } override convenience init(name: String) { self.init(name: name, quantity: 1) } } let oneMysteryItem = RecipeIngredient() let oneBacon = RecipeIngredient(name: "Bacon") let sixEggs = RecipeIngredient(name: "Eggs", quantity: 6) class ShoppingListItem: RecipeIngredient { var purchased = false var description: String { var output = "\(quantity) x \(name)" output += purchased ? " ✔" : " ✘" return output } } var breakfastList = [ ShoppingListItem(), ShoppingListItem(name: "Bacon"), ShoppingListItem(name: "Eggs", quantity: 6), ] breakfastList[0].name = "Orange juice" breakfastList[0].purchased = true for item in breakfastList { print(item.description) } // failable initializers // define which initializer can fail, using "init?" // create an optional value of the type it initializes, using "return nil" to trigger initialization failure struct Animal { let species: String init?(species: String) { if species.isEmpty { return nil } self.species = species } } let someCreature = Animal(species: "Giraffe") if let giraffe = someCreature { print("An animal was initialized with a species of \(giraffe.species)") } let anonymousCreature = Animal(species: "") if anonymousCreature == nil { print("The anonymous creature could not be initialized") } // failable initializers for enumerations // trigger initialization failure if the provided parameters do not match a case enum TemperatureUnit { case Kelvin, Celsius, Fahrenheit init?(symbol: Character) { switch symbol { case "K": self = .Kelvin case "C": self = .Celsius case "F": self = .Fahrenheit default: return nil } } } let fahrenheitUnit = TemperatureUnit(symbol: "F") if fahrenheitUnit != nil { print("This is a defined temperature unit, so initialization succeeded.") } let unknownUnit = TemperatureUnit(symbol: "X") if unknownUnit == nil { print("This is not a defined temperature unit, so initialization failed.") } // with raw values // automatically recieve a failable initializer: init?(rawValue:) enum TemperatureUnit2: Character { case Kelvin = "K", Celsius = "C", Fahrenheit = "F" } let fahrenheitUnit = TemperatureUnit2(rawValue: "F") if fahrenheitUnit != nil { print("This is a defined temperature unit, so initialization succeeded.") } let unknownUnit2 = TemperatureUnit2(rawValue: "X") if unknownUnit2 == nil { print("This is not a defined temperature unit, so initialization failed.") }
mit
c4a814660070ebe8e891dd54ae39405a
23.114428
141
0.677945
4.607414
false
false
false
false
Antondomashnev/ADPuzzleAnimation
Source/Private/Piece.swift
1
1193
// // Piece.swift // ADPuzzleLoader // // Created by Anton Domashnev on 1/7/16. // Copyright © 2016 Anton Domashnev. All rights reserved. // import UIKit class Piece: NSObject { /// What corner piece's view in superview belongs to var corner: Corner! /// Original underlined view position in it's superview var originalPosition: CGPoint /// Animation to position var desiredPosition: CGPoint! /// Animation from position var initialPosition: CGPoint! { didSet { self.view.frame = CGRect(origin: initialPosition, size: self.view.frame.size) } } let view: UIView init(pieceView: UIView) { view = pieceView if view.layer.anchorPoint != CGPointZero { let anchorDelta: CGPoint = view.layer.anchorPoint view.layer.anchorPoint = CGPointZero view.frame.origin = CGPoint(x: view.frame.origin.x - view.frame.width * anchorDelta.x, y: view.frame.origin.y - view.frame.height * anchorDelta.y) view.layer.position = view.frame.origin } originalPosition = pieceView.frame.origin super.init() } }
mit
6ece3df85b0f1b1b463a0213bb3b862b
26.090909
158
0.624161
4.303249
false
false
false
false
HarrisLee/Utils
MySampleCode-master/Enum/Enum/Tree.swift
1
4701
// // Tree.swift // Enum // // Created by 张星宇 on 16/1/12. // Copyright © 2016年 张星宇. All rights reserved. // import Foundation /** 节点颜色 */ enum Color { case R, B } /** 用枚举定义一颗红黑树 - Empty: 值为Empty表示是空的 - Node: 表示这是一个非空节点 */ indirect enum Tree<Element: Comparable> { case Empty case Node(Color,Tree<Element>,Element,Tree<Element>) init() { self = .Empty } //创建空红黑树 /** 创建非空红黑树 :param: x 根节点存储的值 :param: color 根节点的颜色,默认为黑丝 :param: left 左子树,默认为空树 :param: right 右子树,默认为空树 :returns: 返回创建好了的红黑树 */ init(_ x: Element, color: Color = .B, left: Tree<Element> = .Empty, right: Tree<Element> = .Empty){ self = .Node(color, left, x, right) } } /** 向红黑树中插入新的元素 :param: into 原来的树 :param: x 新插入的值 :returns: 插入值后的树 */ private func ins<T>(into: Tree<T>, _ x: T) -> Tree<T> { /// 如果原来的树为空,就返回一颗新建的数,根节点的值为x guard case let .Node(c, l, y, r) = into else { return Tree(x, color: .R) } if x < y { return balance(Tree(y, color: c, left: ins(l,x), right: r)) } if y < x { return balance(Tree(y, color: c, left: l, right: ins(r, x))) } return into } /** 平衡红黑树,需要调整元素的位置与颜色 :param: tree 需要处理的树 :returns: 处理后的树 */ private func balance<T>(tree: Tree<T>) -> Tree<T> { switch tree { case let .Node(.B, .Node(.R, .Node(.R, a, x, b), y, c), z, d): return .Node(.R, .Node(.B,a,x,b),y,.Node(.B,c,z,d)) case let .Node(.B, .Node(.R, a, x, .Node(.R, b, y, c)), z, d): return .Node(.R, .Node(.B,a,x,b),y,.Node(.B,c,z,d)) case let .Node(.B, a, x, .Node(.R, .Node(.R, b, y, c), z, d)): return .Node(.R, .Node(.B,a,x,b),y,.Node(.B,c,z,d)) case let .Node(.B, a, x, .Node(.R, b, y, .Node(.R, c, z, d))): return .Node(.R, .Node(.B,a,x,b),y,.Node(.B,c,z,d)) default: return tree } } // MARK: - 实现contains方法 extension Tree { /** 判断树中是否包含某个元素,递归实现 :param: x 待寻找的元素 :returns: 是否找到 */ func contains(x: Element) -> Bool { guard case let .Node(_,left,y,right) = self else { return false } if x < y { return left.contains(x) } if y < x { return right.contains(x) } return true } } // MARK: - 实现insert方法 extension Tree { /** 向树中插入新的元素,返回值可能是一颗新的树而非原来的树 :param: x 新插入的元素 :returns: 插入元素后的树 */ func insert(x: Element) -> Tree { guard case let .Node(_,l,y,r) = ins(self, x) else { fatalError("ins should never return an empty tree") } return .Node(.B,l,y,r) } } // MARK: - 实现SequenceType协议,遍历树 extension Tree: SequenceType { /** 中序遍历树 :returns: 返回一个生成器,通过for循环遍历树,在main.swift中对这个方法进行了测试 */ func generate() -> AnyGenerator<Element> { var stack: [Tree] = [] var current: Tree = self return anyGenerator { _ -> Element? in while true { // if there's a left-hand node, head down it if case let .Node(_,l,_,_) = current { stack.append(current) current = l } // if there isn’t, head back up, going right as // soon as you can: else if !stack.isEmpty, case let .Node(_,_,x,r) = stack.removeLast() { current = r return x } else { // otherwise, we’re done return nil } } } } } // MARK: - 实现ArrayLiteralConvertible协议,通过数组字面量生成红黑树 extension Tree: ArrayLiteralConvertible { /** 初始化方法,把数组中每个元素插入到树中 :param: source 数组字面量 :returns: 初始化完成的树 */ init <S: SequenceType where S.Generator.Element == Element>(_ source: S) { self = source.reduce(Tree()) { $0.insert($1) } } init(arrayLiteral elements: Element...) { self = Tree(elements) } }
mit
15a99b9fdaccd7f45b30c13620cf5937
22.745562
86
0.50997
3.064935
false
false
false
false
wujianguo/esmerization
esmerization/AppDelegate.swift
1
6104
// // AppDelegate.swift // esmerization // // Created by 吴建国 on 16/2/18. // Copyright © 2016年 wujianguo. 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 "org.wujianguo.esmerization" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("esmerization", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns 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 let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch { // 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 as NSError let wrappedError = 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 \(wrappedError), \(wrappedError.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 var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // 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. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
mit
e5be995a6a68f07f7ece54373f24ee3e
53.90991
291
0.719934
5.849328
false
false
false
false
naokits/my-programming-marathon
iPhoneSensorDemo/Pods/RxCocoa/RxCocoa/Common/CLLocationManager+Rx.swift
7
7050
// // CLLocationManager+Rx.swift // RxCocoa // // Created by Carlos García on 8/7/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import CoreLocation #if !RX_NO_MODULE import RxSwift #endif extension CLLocationManager { /** Reactive wrapper for `delegate`. For more information take a look at `DelegateProxyType` protocol documentation. */ public var rx_delegate: DelegateProxy { return proxyForObject(RxCLLocationManagerDelegateProxy.self, self) } // MARK: Responding to Location Events /** Reactive wrapper for `delegate` message. */ public var rx_didUpdateLocations: Observable<[CLLocation]> { return rx_delegate.observe(#selector(CLLocationManagerDelegate.locationManager(_:didUpdateLocations:))) .map { a in return try castOrThrow([CLLocation].self, a[1]) } } /** Reactive wrapper for `delegate` message. */ public var rx_didFailWithError: Observable<NSError> { return rx_delegate.observe(#selector(CLLocationManagerDelegate.locationManager(_:didFailWithError:))) .map { a in return try castOrThrow(NSError.self, a[1]) } } #if os(iOS) || os(OSX) /** Reactive wrapper for `delegate` message. */ public var rx_didFinishDeferredUpdatesWithError: Observable<NSError?> { return rx_delegate.observe(#selector(CLLocationManagerDelegate.locationManager(_:didFinishDeferredUpdatesWithError:))) .map { a in return try castOptionalOrThrow(NSError.self, a[1]) } } #endif #if os(iOS) // MARK: Pausing Location Updates /** Reactive wrapper for `delegate` message. */ public var rx_didPauseLocationUpdates: Observable<Void> { return rx_delegate.observe(#selector(CLLocationManagerDelegate.locationManagerDidPauseLocationUpdates(_:))) .map { _ in return () } } /** Reactive wrapper for `delegate` message. */ public var rx_didResumeLocationUpdates: Observable<Void> { return rx_delegate.observe(#selector(CLLocationManagerDelegate.locationManagerDidResumeLocationUpdates(_:))) .map { _ in return () } } // MARK: Responding to Heading Events /** Reactive wrapper for `delegate` message. */ public var rx_didUpdateHeading: Observable<CLHeading> { return rx_delegate.observe(#selector(CLLocationManagerDelegate.locationManager(_:didUpdateHeading:))) .map { a in return try castOrThrow(CLHeading.self, a[1]) } } // MARK: Responding to Region Events /** Reactive wrapper for `delegate` message. */ public var rx_didEnterRegion: Observable<CLRegion> { return rx_delegate.observe(#selector(CLLocationManagerDelegate.locationManager(_:didEnterRegion:))) .map { a in return try castOrThrow(CLRegion.self, a[1]) } } /** Reactive wrapper for `delegate` message. */ public var rx_didExitRegion: Observable<CLRegion> { return rx_delegate.observe(#selector(CLLocationManagerDelegate.locationManager(_:didExitRegion:))) .map { a in return try castOrThrow(CLRegion.self, a[1]) } } #endif #if os(iOS) || os(OSX) /** Reactive wrapper for `delegate` message. */ @available(OSX 10.10, *) public var rx_didDetermineStateForRegion: Observable<(state: CLRegionState, region: CLRegion)> { return rx_delegate.observe(#selector(CLLocationManagerDelegate.locationManager(_:didDetermineState:forRegion:))) .map { a in let stateNumber = try castOrThrow(NSNumber.self, a[1]) let state = CLRegionState(rawValue: stateNumber.integerValue) ?? CLRegionState.Unknown let region = try castOrThrow(CLRegion.self, a[2]) return (state: state, region: region) } } /** Reactive wrapper for `delegate` message. */ public var rx_monitoringDidFailForRegionWithError: Observable<(region: CLRegion?, error: NSError)> { return rx_delegate.observe(#selector(CLLocationManagerDelegate.locationManager(_:monitoringDidFailForRegion:withError:))) .map { a in let region = try castOptionalOrThrow(CLRegion.self, a[1]) let error = try castOrThrow(NSError.self, a[2]) return (region: region, error: error) } } /** Reactive wrapper for `delegate` message. */ public var rx_didStartMonitoringForRegion: Observable<CLRegion> { return rx_delegate.observe(#selector(CLLocationManagerDelegate.locationManager(_:didStartMonitoringForRegion:))) .map { a in return try castOrThrow(CLRegion.self, a[1]) } } #endif #if os(iOS) // MARK: Responding to Ranging Events /** Reactive wrapper for `delegate` message. */ public var rx_didRangeBeaconsInRegion: Observable<(beacons: [CLBeacon], region: CLBeaconRegion)> { return rx_delegate.observe(#selector(CLLocationManagerDelegate.locationManager(_:didRangeBeacons:inRegion:))) .map { a in let beacons = try castOrThrow([CLBeacon].self, a[1]) let region = try castOrThrow(CLBeaconRegion.self, a[2]) return (beacons: beacons, region: region) } } /** Reactive wrapper for `delegate` message. */ public var rx_rangingBeaconsDidFailForRegionWithError: Observable<(region: CLBeaconRegion, error: NSError)> { return rx_delegate.observe(#selector(CLLocationManagerDelegate.locationManager(_:rangingBeaconsDidFailForRegion:withError:))) .map { a in let region = try castOrThrow(CLBeaconRegion.self, a[1]) let error = try castOrThrow(NSError.self, a[2]) return (region: region, error: error) } } // MARK: Responding to Visit Events /** Reactive wrapper for `delegate` message. */ @available(iOS 8.0, *) public var rx_didVisit: Observable<CLVisit> { return rx_delegate.observe(#selector(CLLocationManagerDelegate.locationManager(_:didVisit:))) .map { a in return try castOrThrow(CLVisit.self, a[1]) } } #endif // MARK: Responding to Authorization Changes /** Reactive wrapper for `delegate` message. */ public var rx_didChangeAuthorizationStatus: Observable<CLAuthorizationStatus> { return rx_delegate.observe(#selector(CLLocationManagerDelegate.locationManager(_:didChangeAuthorizationStatus:))) .map { a in let number = try castOrThrow(NSNumber.self, a[1]) return CLAuthorizationStatus(rawValue: Int32(number.integerValue)) ?? .NotDetermined } } }
mit
ef8efbf015e954ad427c4e4946a74ba7
31.330275
133
0.628121
5.027104
false
false
false
false
moltin/ios-sdk
Tests/moltin iOS Tests/Data/Collection.swift
1
3061
// // Collection.swift // moltin iOS Tests // // Created by Craig Tweedy on 03/04/2018. // import Foundation class MockCollectionDataFactory { static let collectionData = """ { "data": { "id": "51b56d92-ab99-4802-a2c1-be150848c629", "type": "collection", "name": "Winter Season", "slug": "winter-season", "description": "Our Winter Season is now live!", "status": "live" } } """ static let multiCollectionData = """ { "data": [{ "id": "51b56d92-ab99-4802-a2c1-be150848c629", "type": "collection", "name": "Winter Season", "slug": "winter-season", "description": "Our Winter Season is now live!", "status": "live" }] } """ static let customCollectionData = """ { "data": { "author": { "name": "Craig" }, "id": "51b56d92-ab99-4802-a2c1-be150848c629", "type": "collection", "name": "Winter Season", "slug": "winter-season", "description": "Our Winter Season is now live!", "status": "live" } } """ static let customMultiCollectionData = """ { "data": [{ "author": { "name": "Craig" }, "id": "51b56d92-ab99-4802-a2c1-be150848c629", "type": "collection", "name": "Winter Season", "slug": "winter-season", "description": "Our Winter Season is now live!", "status": "live" }] } """ static let treeData = """ { "data": [{ "id": "51b56d92-ab99-4802-a2c1-be150848c629", "type": "collection", "name": "Winter Season", "slug": "winter-season", "description": "Our Winter Season is now live!", "status": "live", "children": [{ "id": "41b56d92-ab99-4802-a2c1-be150848c629", "type": "collection", "name": "Sub Collection!", "slug": "sub-collection", "description": "Sub collection", "status": "live" }] }] } """ static let customTreeData = """ { "data": [{ "author": { "name": "Craig" }, "id": "51b56d92-ab99-4802-a2c1-be150848c629", "type": "collection", "name": "Winter Season", "slug": "winter-season", "description": "Our Winter Season is now live!", "status": "live", "children": [{ "id": "41b56d92-ab99-4802-a2c1-be150848c629", "type": "collection", "name": "Sub Collection!", "slug": "sub-collection", "description": "Sub collection", "status": "live" }] }] } """ }
mit
e9086c30d9a3c221fd0edc5d8ef70290
25.850877
61
0.433192
3.860025
false
false
false
false
manavgabhawala/CAEN-Lecture-Scraper
CAEN Lecture Scraper/EncapsulatedRowView.swift
1
727
// // ProgressCellView.swift // CAEN Lecture Scraper // // Created by Manav Gabhawala on 6/3/15. // Copyright (c) 2015 Manav Gabhawala. All rights reserved. // import Cocoa class EncapsulatedRowView: NSTableRowView { @IBOutlet var progressBar : ProgressCellView! @IBOutlet var fileName : NSTableCellView! @IBOutlet var statusLabel : NSTableCellView! var downloadURL : NSURL! var saveTo: NSURL! func setup(video: VideoData) { downloadURL = video.URL saveTo = video.filePath } func beginDownload() { } override func viewAtColumn(column: Int) -> AnyObject? { if column == 0 { return fileName } else if column == 1 { return progressBar } else { return statusLabel } } }
mit
49395041a0ebe37bad7fb4bbd14a9035
14.804348
60
0.685007
3.365741
false
false
false
false
qutheory/vapor
Sources/Vapor/URLEncodedForm/URLEncodedFormEncoder.swift
1
15886
/// Encodes `Encodable` instances to `application/x-www-form-urlencoded` data. /// /// print(user) /// User /// let data = try URLEncodedFormEncoder().encode(user) /// print(data) /// Data /// /// URL-encoded forms are commonly used by websites to send form data via POST requests. This encoding is relatively /// efficient for small amounts of data but must be percent-encoded. `multipart/form-data` is more efficient for sending /// large data blobs like files. /// /// See [Mozilla's](https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST) docs for more information about /// url-encoded forms. /// NOTE: This implementation of the encoder does not support encoding booleans to "flags". public struct URLEncodedFormEncoder: ContentEncoder, URLQueryEncoder { /// Used to capture URLForm Coding Configuration used for encoding. public struct Configuration { /// Supported array encodings. public enum ArrayEncoding { /// Arrays are serialized as separate values with bracket suffixed keys. /// For example, `foo = [1,2,3]` would be serialized as `foo[]=1&foo[]=2&foo[]=3`. case bracket /// Arrays are serialized as a single value with character-separated items. /// For example, `foo = [1,2,3]` would be serialized as `foo=1,2,3`. case separator(Character) /// Arrays are serialized as separate values. /// For example, `foo = [1,2,3]` would be serialized as `foo=1&foo=2&foo=3`. case values } /// Supported date formats public enum DateEncodingStrategy { /// Seconds since 1 January 1970 00:00:00 UTC (Unix Timestamp) case secondsSince1970 /// ISO 8601 formatted date case iso8601 /// Using custom callback case custom((Date, Encoder) throws -> Void) } /// Specified array encoding. public var arrayEncoding: ArrayEncoding public var dateEncodingStrategy: DateEncodingStrategy /// Creates a new `Configuration`. /// /// - parameters: /// - arrayEncoding: Specified array encoding. Defaults to `.bracket`. /// - dateFormat: Format to encode date format too. Defaults to `secondsSince1970` public init( arrayEncoding: ArrayEncoding = .bracket, dateEncodingStrategy: DateEncodingStrategy = .secondsSince1970 ) { self.arrayEncoding = arrayEncoding self.dateEncodingStrategy = dateEncodingStrategy } } private let configuration: Configuration /// Create a new `URLEncodedFormEncoder`. /// /// ContentConfiguration.global.use(urlEncoder: URLEncodedFormEncoder(bracketsAsArray: true, flagsAsBool: true, arraySeparator: nil)) /// /// - parameters: /// - configuration: Defines how encoding is done see `URLEncodedFormCodingConfig` for more information public init( configuration: Configuration = .init() ) { self.configuration = configuration } /// `ContentEncoder` conformance. public func encode<E>(_ encodable: E, to body: inout ByteBuffer, headers: inout HTTPHeaders) throws where E: Encodable { headers.contentType = .urlEncodedForm try body.writeString(self.encode(encodable)) } /// `URLContentEncoder` conformance. public func encode<E>(_ encodable: E, to url: inout URI) throws where E: Encodable { url.query = try self.encode(encodable) } /// Encodes the supplied `Encodable` object to `Data`. /// /// print(user) // User /// let data = try URLEncodedFormEncoder().encode(user) /// print(data) // "name=Vapor&age=3" /// /// - parameters: /// - encodable: Generic `Encodable` object (`E`) to encode. /// - configuration: Overwrides the coding config for this encoding call. /// - returns: Encoded `Data` /// - throws: Any error that may occur while attempting to encode the specified type. public func encode<E>(_ encodable: E) throws -> String where E: Encodable { let encoder = _Encoder(codingPath: [], configuration: self.configuration) try encodable.encode(to: encoder) let serializer = URLEncodedFormSerializer() return try serializer.serialize(encoder.getData()) } } // MARK: Private private protocol _Container { func getData() throws -> URLEncodedFormData } private class _Encoder: Encoder { var codingPath: [CodingKey] private var container: _Container? = nil func getData() throws -> URLEncodedFormData { return try container?.getData() ?? [] } var userInfo: [CodingUserInfoKey: Any] { return [:] } private let configuration: URLEncodedFormEncoder.Configuration init(codingPath: [CodingKey], configuration: URLEncodedFormEncoder.Configuration) { self.codingPath = codingPath self.configuration = configuration } func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> where Key : CodingKey { let container = KeyedContainer<Key>(codingPath: codingPath, configuration: configuration) self.container = container return .init(container) } func unkeyedContainer() -> UnkeyedEncodingContainer { let container = UnkeyedContainer(codingPath: codingPath, configuration: configuration) self.container = container return container } func singleValueContainer() -> SingleValueEncodingContainer { let container = SingleValueContainer(codingPath: codingPath, configuration: configuration) self.container = container return container } private final class KeyedContainer<Key>: KeyedEncodingContainerProtocol, _Container where Key: CodingKey { var codingPath: [CodingKey] var internalData: URLEncodedFormData = [] var childContainers: [String: _Container] = [:] func getData() throws -> URLEncodedFormData { var result = internalData for (key, childContainer) in self.childContainers { result.children[key] = try childContainer.getData() } return result } private let configuration: URLEncodedFormEncoder.Configuration init( codingPath: [CodingKey], configuration: URLEncodedFormEncoder.Configuration ) { self.codingPath = codingPath self.configuration = configuration } /// See `KeyedEncodingContainerProtocol` func encodeNil(forKey key: Key) throws { // skip } private func encodeDate(_ date: Date, forKey key: Key) throws { switch configuration.dateEncodingStrategy { case .secondsSince1970: internalData.children[key.stringValue] = URLEncodedFormData(values: [date.urlQueryFragmentValue]) case .iso8601: internalData.children[key.stringValue] = URLEncodedFormData(values: [ ISO8601DateFormatter.threadSpecific.string(from: date).urlQueryFragmentValue ]) case .custom(let callback): let encoder = _Encoder(codingPath: self.codingPath + [key], configuration: self.configuration) try callback(date, encoder) self.internalData.children[key.stringValue] = try encoder.getData() } } /// See `KeyedEncodingContainerProtocol` func encode<T>(_ value: T, forKey key: Key) throws where T : Encodable { if let date = value as? Date { try encodeDate(date, forKey: key) } else if let convertible = value as? URLQueryFragmentConvertible { internalData.children[key.stringValue] = URLEncodedFormData(values: [convertible.urlQueryFragmentValue]) } else { let encoder = _Encoder(codingPath: self.codingPath + [key], configuration: self.configuration) try value.encode(to: encoder) self.internalData.children[key.stringValue] = try encoder.getData() } } /// See `KeyedEncodingContainerProtocol` func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type, forKey key: Key) -> KeyedEncodingContainer<NestedKey> where NestedKey: CodingKey { let container = KeyedContainer<NestedKey>( codingPath: self.codingPath + [key], configuration: self.configuration ) self.childContainers[key.stringValue] = container return .init(container) } /// See `KeyedEncodingContainerProtocol` func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedEncodingContainer { let container = UnkeyedContainer( codingPath: self.codingPath + [key], configuration: self.configuration ) self.childContainers[key.stringValue] = container return container } /// See `KeyedEncodingContainerProtocol` func superEncoder() -> Encoder { fatalError() } /// See `KeyedEncodingContainerProtocol` func superEncoder(forKey key: Key) -> Encoder { fatalError() } } /// Private `UnkeyedEncodingContainer`. private final class UnkeyedContainer: UnkeyedEncodingContainer, _Container { var codingPath: [CodingKey] var count: Int = 0 var internalData: URLEncodedFormData = [] var childContainers: [Int: _Container] = [:] private let configuration: URLEncodedFormEncoder.Configuration func getData() throws -> URLEncodedFormData { var result = self.internalData for (key, childContainer) in self.childContainers { result.children[String(key)] = try childContainer.getData() } switch self.configuration.arrayEncoding { case .separator(let arraySeparator): var valuesToImplode = result.values result.values = [] if case .bracket = self.configuration.arrayEncoding, let emptyStringChild = self.internalData.children[""] { valuesToImplode = valuesToImplode + emptyStringChild.values result.children[""]?.values = [] } let implodedValue = try valuesToImplode.map({ (value: URLQueryFragment) -> String in return try value.asUrlEncoded() }).joined(separator: String(arraySeparator)) result.values = [.urlEncoded(implodedValue)] case .bracket, .values: break } return result } init( codingPath: [CodingKey], configuration: URLEncodedFormEncoder.Configuration ) { self.codingPath = codingPath self.configuration = configuration } func encodeNil() throws { // skip } func encode<T>(_ value: T) throws where T: Encodable { defer { self.count += 1 } if let convertible = value as? URLQueryFragmentConvertible { let value = convertible.urlQueryFragmentValue switch self.configuration.arrayEncoding { case .bracket: var emptyStringChild = self.internalData.children[""] ?? [] emptyStringChild.values.append(value) self.internalData.children[""] = emptyStringChild case .separator, .values: self.internalData.values.append(value) } } else { let encoder = _Encoder(codingPath: codingPath, configuration: configuration) try value.encode(to: encoder) let childData = try encoder.getData() if childData.hasOnlyValues { switch self.configuration.arrayEncoding { case .bracket: var emptyStringChild = self.internalData.children[""] ?? [] emptyStringChild.values.append(contentsOf: childData.values) self.internalData.children[""] = emptyStringChild case .separator, .values: self.internalData.values.append(contentsOf: childData.values) } } else { self.internalData.children[count.description] = try encoder.getData() } } } /// See UnkeyedEncodingContainer.nestedContainer func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type) -> KeyedEncodingContainer<NestedKey> where NestedKey: CodingKey { defer { count += 1 } let container = KeyedContainer<NestedKey>( codingPath: self.codingPath, configuration: self.configuration ) self.childContainers[self.count] = container return .init(container) } /// See UnkeyedEncodingContainer.nestedUnkeyedContainer func nestedUnkeyedContainer() -> UnkeyedEncodingContainer { defer { count += 1 } let container = UnkeyedContainer( codingPath: self.codingPath, configuration: self.configuration ) self.childContainers[count] = container return container } /// See UnkeyedEncodingContainer.superEncoder func superEncoder() -> Encoder { fatalError() } } /// Private `SingleValueEncodingContainer`. private final class SingleValueContainer: SingleValueEncodingContainer, _Container { /// See `SingleValueEncodingContainer` var codingPath: [CodingKey] func getData() throws -> URLEncodedFormData { return data } /// The data being encoded var data: URLEncodedFormData = [] private let configuration: URLEncodedFormEncoder.Configuration /// Creates a new single value encoder init( codingPath: [CodingKey], configuration: URLEncodedFormEncoder.Configuration ) { self.codingPath = codingPath self.configuration = configuration } /// See `SingleValueEncodingContainer` func encodeNil() throws { // skip } /// See `SingleValueEncodingContainer` func encode<T>(_ value: T) throws where T: Encodable { if let convertible = value as? URLQueryFragmentConvertible { self.data.values.append(convertible.urlQueryFragmentValue) } else { let encoder = _Encoder(codingPath: self.codingPath, configuration: self.configuration) try value.encode(to: encoder) self.data = try encoder.getData() } } } } private extension EncodingError { static func invalidValue(_ value: Any, at path: [CodingKey]) -> EncodingError { let pathString = path.map { $0.stringValue }.joined(separator: ".") let context = EncodingError.Context( codingPath: path, debugDescription: "Invalid value at '\(pathString)': \(value)" ) return Swift.EncodingError.invalidValue(value, context) } }
mit
80cf31bef954904420e9b8fa06090ee5
38.61596
144
0.596878
5.529412
false
true
false
false
connienguyen/volunteers-iOS
VOLA/VOLA/Resources/Theme+Colors.swift
1
719
// // Theme+Colors.swift // VOLA // // Created by Bruno Henriques on 31/05/2017. // Copyright © 2017 Systers-Opensource. All rights reserved. // /// Constants for color palette used for styling app struct ThemeColors { static let crimson = UIColor(hex: 0xEF4135) static let caribbean = UIColor(hex: 0x54BCEB) static let sublime = UIColor(hex: 0xC1D82F) static let tangerine = UIColor(hex: 0xF89728) static let richBlack = UIColor(hex: 0x101B20) static let mediumGrey = UIColor(hex: 0x888B8D) static let lightGrey = UIColor(hex: 0xB1B3B3) static let white = UIColor(hex: 0xFFFFFF) static let emerald = UIColor(hex: 0x00833E) static let marineBlue = UIColor(hex: 0x0076A9) }
gpl-2.0
3e43fc28e5e0493ce28f15d0fc22f4c4
33.190476
61
0.710306
3.094828
false
false
false
false
PedroTrujilloV/TIY-Assignments
36--Now-Thats-What-I-Call-A-Close-Encounter/SkyInvaders - Pedro/SkyInvaders - Pedro/GameScene.swift
1
16650
// // GameScene.swift // SkyInvaders - Pedro // // Created by Pedro Trujillo on 11/23/15. // Copyright (c) 2015 Pedro Trujillo. All rights reserved. // import SpriteKit import CoreMotion class GameScene: SKScene, SKPhysicsContactDelegate { let kInvaderCategory: UInt32 = 0x1 << 0 let kShipFireBulletCategory: UInt32 = 0x1 << 1 let kShipCategory: UInt32 = 0x1 << 2 let kSceneEdgeCategory: UInt32 = 0x1 << 3 let kInvaderFireBulletCategory: UInt32 = 0x1 << 4 enum InvaderType { case A case B case C } enum InvaderMovementDirection { case Right case Left case DownThenRight case DownThenLeft case None } enum BulletType { case ShipFired case InvaderFired } let motionManager: CMMotionManager = CMMotionManager() var tapQueue:Array<Int> = [] var contactQueue:Array<SKPhysicsContact> = [] var contentCreated = false var invaderMovementDirection:InvaderMovementDirection = .Right var timeOfLastMove: CFTimeInterval = 0.0 let timePerMove: CFTimeInterval = 1.0 let kShipFiredBulletName = "shipFiredBullet" let kInvaderFiredBulletName = "invaderFiredBullet" let kBulletSize = CGSize(width: 4.0, height: 3.0) ///bulet size let kInvaderSize = CGSize(width: 24, height: 16) let kInvaderGridSpacing = CGSize(width: 12, height: 12) let kInvaderRowCount = 6 let kInvaderColCount = 6 let kInvaderName = "invader" let kShipSize = CGSize(width: 30, height: 16) let kShipName = "ship" let kScoreHudName = "scoreHud" let kHealthHudName = "healthHud" var score: Int = 0 var shipHealth: Float = 1.0 override func didMoveToView(view: SKView) { /* Setup your scene here */ let myLabel = SKLabelNode(fontNamed:"Chalkduster") // myLabel.text = "Hello, World!"; // myLabel.fontSize = 45; // myLabel.position = CGPoint(x:CGRectGetMidX(self.frame), y:CGRectGetMidY(self.frame)); if !contentCreated { createContent() contentCreated = true motionManager.startAccelerometerUpdates() userInteractionEnabled = true physicsWorld.contactDelegate = self } self.addChild(myLabel) } func createContent() { // let invader = SKSpriteNode(imageNamed: "InvaderA_00.png") // invader.position = CGPoint(x: size.width/2, y: size.height/2) // addChild(invader) backgroundColor = SKColor.blackColor() physicsBody = SKPhysicsBody(edgeLoopFromRect: frame) physicsBody!.categoryBitMask = kSceneEdgeCategory setupInvaders() setUpShip() setupHud() } // func makeInvaderOfType(invaderType:InvaderType) ->(SKNode) // { // var invaderColor:SKColor // switch(invaderType) // { // case .A: // invaderColor = SKColor.redColor() // case .B: // invaderColor = SKColor.greenColor() // case .C: // invaderColor = SKColor.blueColor() // } // // let invader = SKSpriteNode(color: invaderColor, size: kInvaderSize) // // invader.name = kInvaderName // // invader.physicsBody = SKPhysicsBody(rectangleOfSize: invader.frame.size) // invader.physicsBody!.dynamic = false // invader.physicsBody!.categoryBitMask = kInvaderCategory // invader.physicsBody!.contactTestBitMask = 0x0 // invader.physicsBody!.collisionBitMask = 0x0 // // // return invader // } func makeInvaderOfType(invaderType:InvaderType) ->SKNode { let invaderTextures = loadInvadersTexturesOfType(invaderType) let invader = SKSpriteNode(texture: invaderTextures[0]) invader.name = kInvaderName invader.runAction(SKAction.repeatActionForever(SKAction.animateWithNormalTextures(invaderTextures, timePerFrame: timePerMove))) invader.physicsBody = SKPhysicsBody(rectangleOfSize: invader.frame.size) invader.physicsBody!.dynamic = false invader.physicsBody!.categoryBitMask = kInvaderCategory invader.physicsBody!.contactTestBitMask = 0x0 invader.physicsBody!.collisionBitMask = 0x0 return invader } func loadInvadersTexturesOfType(invaderType:InvaderType) -> Array<SKTexture> { var prefix: String switch invaderType { case .A: prefix = "InvaderA" case .B: prefix = "InvaderB" case .C: prefix = "InvaderC" } return [SKTexture(imageNamed: String(format: "%@_00.png", prefix)),SKTexture(imageNamed: String(format: "%@_01.png", prefix))] } func setupInvaders() { let baseOrigin = CGPoint(x: size.width/3 , y: 180) for var row = 1; row <= kInvaderRowCount; row++ { var invaderType:InvaderType if row % 3 == 0 { invaderType = .A } else if row % 3 == 1 { invaderType = .B } else { invaderType = .C } let invaderPositionY = CGFloat(row) * (kInvaderSize.height * 2) + baseOrigin.y var invaderPisition = CGPoint(x: baseOrigin.x, y: invaderPositionY) for var col = 1; col <= kInvaderColCount; col++ { let invader = makeInvaderOfType(invaderType) invader.position = invaderPisition addChild(invader) invaderPisition = CGPoint(x: invaderPisition.x + kInvaderSize.width + kInvaderGridSpacing.width, y: invaderPositionY) } } } func setUpShip() { let ship = makeShip() ship.position = CGPoint(x: size.width/2.0, y: kShipSize.height/2.0) addChild(ship) } func makeShip() -> SKNode { //let ship = SKSpriteNode(color: SKColor.greenColor(), size: kShipSize) let ship = SKSpriteNode(imageNamed: "ship.png") ship.name = kShipName ship.physicsBody = SKPhysicsBody(rectangleOfSize: ship.frame.size) ship.physicsBody!.dynamic = true ship.physicsBody!.affectedByGravity = false ship.physicsBody!.mass = 0.02 ship.physicsBody!.categoryBitMask = kShipCategory ship.physicsBody!.contactTestBitMask = 0x0 ship.physicsBody!.collisionBitMask = kSceneEdgeCategory return ship } func setupHud() { let scoredLabel = SKLabelNode(fontNamed: "Courier") scoredLabel.name = kScoreHudName scoredLabel.fontSize = 25 scoredLabel.fontColor = SKColor.greenColor() scoredLabel.text = String(format: "Score %04u", 0) scoredLabel.position = CGPoint(x: frame.size.width/2, y: size.height - (40 + scoredLabel.frame.size.height/2)) addChild(scoredLabel) let healthLabel = SKLabelNode(fontNamed: "Courier") healthLabel.name = kHealthHudName healthLabel.fontSize = 25 healthLabel.fontColor = SKColor.redColor() healthLabel.text = String(format: "Health: %.1f%%", shipHealth * 100.0) healthLabel.position = CGPoint(x: frame.size.width/2, y: size.height - (80 + healthLabel.frame.size.height/2)) addChild(healthLabel) } func makeBulletIfType(bulletType:BulletType)->SKNode { var bullet:SKNode switch bulletType { case .ShipFired: bullet = SKSpriteNode(color: SKColor.greenColor(), size: kBulletSize) bullet.name = kShipFiredBulletName bullet.physicsBody = SKPhysicsBody(rectangleOfSize: bullet.frame.size) bullet.physicsBody!.dynamic = true bullet.physicsBody!.affectedByGravity = false bullet.physicsBody!.contactTestBitMask = kShipCategory bullet.physicsBody!.contactTestBitMask = kInvaderCategory bullet.physicsBody!.collisionBitMask = 0x0 case .InvaderFired: bullet = SKSpriteNode(color: SKColor.magentaColor(), size: kBulletSize) bullet.name = kInvaderFiredBulletName bullet.name = kShipFiredBulletName bullet.physicsBody = SKPhysicsBody(rectangleOfSize: bullet.frame.size) bullet.physicsBody!.dynamic = true bullet.physicsBody!.affectedByGravity = false bullet.physicsBody!.contactTestBitMask = kInvaderFireBulletCategory bullet.physicsBody!.contactTestBitMask = kShipCategory bullet.physicsBody!.collisionBitMask = 0x0 } return bullet } func firedBullet(bullet:SKNode, toDestination destination:CGPoint, withDuration duration:CFTimeInterval, andSoundFileName soundName: String) { let bulletAction = SKAction.sequence([SKAction.moveTo(destination, duration: duration),SKAction.waitForDuration(3.0/60.0),SKAction.removeFromParent()]) let soundAction = SKAction.playSoundFileNamed(soundName, waitForCompletion: true) bullet.runAction(SKAction.group([bulletAction,soundAction])) addChild(bullet) } func fireShipBullets() { let existingBullet = childNodeWithName(kShipFiredBulletName) if existingBullet == nil { if let ship = childNodeWithName(kShipName) { let bullet = makeBulletIfType(.ShipFired) bullet.position = CGPoint(x: ship.position.x, y: ship.position.y + ship.frame.size.height - bullet.frame.size.height/2) let bulletDestination = CGPoint(x: ship.position.x, y: frame.size.height + bullet.frame.size.height/2) firedBullet(bullet, toDestination: bulletDestination, withDuration: 0.5, andSoundFileName: "fart-01.wav")//"ShipBullet.wav")// } } } func moveInvadersForUpdate(currentTime:CFTimeInterval) { if currentTime - timeOfLastMove < timePerMove { return } determineInvaderMovementDirection() enumerateChildNodesWithName(kInvaderName) { node, stop in switch self.invaderMovementDirection { case .Right: node.position = CGPoint(x: node.position.x + 10, y: node.position.y) case .Left: node.position = CGPoint(x: node.position.x - 10, y: node.position.y) case .DownThenLeft, .DownThenRight: node.position = CGPoint(x: node.position.x, y: node.position.y - 10) case .None: break } self.timeOfLastMove = currentTime } } func determineInvaderMovementDirection() { var proposedMovementDirection: InvaderMovementDirection = invaderMovementDirection enumerateChildNodesWithName(kInvaderName) { node, stop in //stop.memory = true switch self.invaderMovementDirection { case .Right: if CGRectGetMaxX(node.frame) >= node.scene!.size.width - 1.0 { proposedMovementDirection = .DownThenLeft stop.memory = true } case .Left: if CGRectGetMaxX(node.frame) <= 1.0 { proposedMovementDirection = .DownThenRight stop.memory = true } case .DownThenLeft: proposedMovementDirection = .Left stop.memory = true case .DownThenRight: proposedMovementDirection = .Right stop.memory = true case .None: break } } invaderMovementDirection = proposedMovementDirection } func processuserMotionForUpdate(currentTime:CFTimeInterval) { let ship = childNodeWithName(kShipName) as! SKSpriteNode if let data = motionManager.accelerometerData { if (fabs(data.acceleration.x) > 0.2) { print("move the ship") ship.physicsBody!.applyForce(CGVectorMake(40.0 * CGFloat(data.acceleration.x), 0)) } } } func processUserTapsForUpdates(currentTimet:CFTimeInterval) { for tapCount in tapQueue { if tapCount == 1 { fireShipBullets() } tapQueue.removeAtIndex(0) } } func processContactsForUpdate(currentTime:CFTimeInterval) { for contact in contactQueue { handleContact(contact) if let index = (contactQueue as NSArray).indexOfObject(contact) as Int? { contactQueue.removeAtIndex(index) } } } func fireInvaderBulletsForUpdate(currentTime:CFTimeInterval) { let existingBullet = childNodeWithName(kInvaderFiredBulletName) if existingBullet == nil { var allInvaders = Array<SKNode>() enumerateChildNodesWithName(kInvaderName) { node, stop in allInvaders.append(node) } if allInvaders.count > 0 { let allInvadersIndex = Int(arc4random_uniform(UInt32(allInvaders.count))) let invader = allInvaders[allInvadersIndex] let bullet = makeBulletIfType(.InvaderFired) bullet.position = CGPoint(x: invader.position.x, y: invader.position.y - invader.frame.size.height/2 + bullet.frame.height/2) let bulletDestination = CGPoint(x: invader.position.x, y: -(bullet.frame.size.height/2)) firedBullet(bullet, toDestination: bulletDestination, withDuration: 1.0, andSoundFileName: "InvaderBullet.wav") } } } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { /* Called when a touch begins */ } override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { let touche = touches.first! as UITouch if touche.tapCount == 1 { tapQueue.append(1) } } func didBeginContact(contact: SKPhysicsContact) { if contact as SKPhysicsContact? != nil { contactQueue.append(contact) } } func handleContact(contact:SKPhysicsContact) { if contact.bodyA.node?.parent == nil || contact.bodyB.node?.parent == nil { return } let nodeNames = [contact.bodyA.node!.name!, contact.bodyB.node!.name!] if (nodeNames as NSArray).containsObject(kShipName) && (nodeNames as NSArray).containsObject(kInvaderFiredBulletName) { self.runAction(SKAction.playSoundFileNamed("ShipHit.wav", waitForCompletion: false)) contact.bodyA.node!.removeFromParent() contact.bodyA.node!.removeFromParent() } else if (nodeNames as NSArray).containsObject(kInvaderName) && (nodeNames as NSArray).containsObject(kShipFiredBulletName) { self.runAction(SKAction.playSoundFileNamed("InvaderHit.wav", waitForCompletion: false)) contact.bodyA.node!.removeFromParent() contact.bodyA.node!.removeFromParent() } } override func update(currentTime: CFTimeInterval) { /* Called before each frame is rendered */ moveInvadersForUpdate(currentTime) processuserMotionForUpdate(currentTime) processUserTapsForUpdates(currentTime) fireInvaderBulletsForUpdate(currentTime) processContactsForUpdate(currentTime) } }
cc0-1.0
c71328f5905f87a2b64b386c8611decf
31.080925
159
0.578559
4.71805
false
false
false
false
adamyanalunas/Font
Example/Font/ViewController.swift
1
1784
// // ViewController.swift // Font // // Created by Adam Yanalunas on 10/02/2015. // Copyright (c) 2015 Adam Yanalunas. All rights reserved. // import Font import UIKit class ViewController: UIViewController { @IBOutlet weak var example:UILabel! var model:FontViewModel! // MARK: - View lifecycle override func viewDidLoad() { super.viewDidLoad() model = FontViewModel(name: "Source Sans Pro", size: 24, style: .italic, weight: .semibold) updateFont(model) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { super.prepare(for: segue, sender: sender) let vc = segue.destination as! OptionsController vc.model = model } // MARK: - Helpers func updateFont(_ model:FontViewModel) { // Create an instance of your custom font and generate it into a UIFont instance let font = Font.SourceSansPro(size: model.size, weight: model.weight, style: model.style).generate() example.font = font } } extension ViewController: DynamicTypeListener { // Subscribe to UIContentSizeCategoryDidChangeNotification notifications override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) listenForDynamicTypeChanges() updateFont(model) } // Unsubscribe from UIContentSizeCategoryDidChangeNotification notifications override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) ignoreDynamicTypeChanges() } // Do something when UIContentSizeCategoryDidChangeNotification notifications come in func respondToDynamicTypeChanges(_ notification:Notification) { updateFont(model) } }
mit
40977a0a98302ebce8765aca19f341fc
28.245902
108
0.674888
5.011236
false
false
false
false
christopherhelf/TouchHeatmap
Source/TouchHeatmap.swift
2
7565
// // TouchHeatmap.swift // TouchHeatmap // // Created by Christopher Helf on 26.09.15. // Copyright © 2015 Christopher Helf. All rights reserved. import Foundation import UIKit final class TouchHeatmap : NSObject { // A simple struct to capture Touches struct Touch { // The location var point: CGPoint // The date when the touch occurred var date: NSDate // The radius given by the UITouch object var majorRadius: CGFloat // The tolerance given by the UITouch object var majorRadiusTolerance: CGFloat } // A struct keeping count of all touches and screenshots/ViewControllers struct TouchTracking { // The screenshot var screenshot : UIImage? // All stored touches var storedTouches = [Touch]() // An array keeping track how we got to the current ViewController var from = [String : Int]() var start = false init() {} // Function to add a connection to another ViewController mutating func addFrom(name: String?) { // Check whether a name was given, if not, this controller is the starting point guard let n = name else { start = true return } // Increase the counter, or create one if let cnt = from[n] { from[n] = cnt+1 } else { from[n] = 1 } } } // Singleton class static let sharedInstance = TouchHeatmap() // The queue in which we operate let backgroundQueue = DispatchQueue.global(qos: .background) // The error message which is given (unused yet) let errorMessage = "Did not Set UIApplication correctly" // The current viewController var currentController : String? = nil // UIScreen Size var size : CGRect? = nil // The Array for storage, key is the name of the viewcontroller, and value is // the object tracking touches var store = [String : TouchTracking]() // Initializer override init() { super.init() // We will render the TouchHeatmap when entering into background NotificationCenter.default.addObserver(self, selector: #selector(didEnterBackground(_:)), name:UIApplication.didEnterBackgroundNotification, object: nil) // Set the size size = UIApplication.shared.keyWindow!.layer.frame } // Main Entry Point class func start() { _ = UIApplication.shared.next UIApplication.shared.swizzleSendEvent() } // Function to keep things synchronized between threads private func sync(block: () -> ()) { objc_sync_enter(self) block() objc_sync_exit(self) } // Main function that is overwritten in UIApplication, tracks all touches func sendEvent(event: UIEvent) { // We need touches in order to continue, as well as a viewcontroller guard let touches = event.allTouches, let name = self.currentController else { return } // No touches, no tracking guard touches.count > 0 else { return } // Iterate through all touches for touch in touches { // Get the touch phase let phase = touch.phase // Right now we simply track all touches if (phase == UITouch.Phase.ended || true) { // Enter the sync block self.sync { // Get the touch location in the current view let point = touch.location(in: touch.window) // Create our own Touch object let newTouch = Touch(point: point, date: NSDate(), majorRadius: touch.majorRadius, majorRadiusTolerance: touch.majorRadiusTolerance) // Store this touch self.store[name]?.storedTouches.append(newTouch) } } } } // Function that is overwritten for all UIViewControllers func viewDidAppear(name: String) { // Check whether a screenshot is necessary var screenshotNecessary = true sync { guard let item = self.store[name] else { self.store[name] = TouchTracking() self.store[name]!.addFrom(name: self.currentController) screenshotNecessary = true self.currentController = name return } // Assign the current viewController self.currentController = name self.store[name]!.addFrom(name: self.currentController) guard let _ = item.screenshot else { screenshotNecessary = true return } } // Screenshot is necessary, make one if screenshotNecessary { backgroundQueue.async() { self.makeScreenshot(name: name) } } } // Function creating a screenshot, and assigning it to our store dictionary func makeScreenshot(name: String) { DispatchQueue.main.async { let layer = UIApplication.shared.keyWindow!.layer let scale = UIScreen.main.scale UIGraphicsBeginImageContextWithOptions(layer.frame.size, false, scale); layer.render(in: UIGraphicsGetCurrentContext()!) let screenshot = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() self.sync { // Store the Screenshot self.store[name]?.screenshot = screenshot } } } // Render the touches and save to camera roll @objc func didEnterBackground(_ notification: NSNotification) { for (_,item) in self.store{ let screenshot = item.screenshot let touches = item.storedTouches if let image = createImageFromTouches(image: screenshot!, touches: touches) { UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil) } } } // Render the touchmap and blend it with the screenshot func createImageFromTouches(image: UIImage, touches: [Touch]) -> UIImage? { let result = TouchHeatmapRenderer.renderTouches(image: image, touches: touches) let touchImage = result.0 let success = result.1 if success { // A touch heatmap was rendered, blend it with the screenshot let size = image.size let rect = CGRect(origin: CGPoint(x: 0, y :0), size: CGSize(width: size.width, height: size.height)) let scale = UIScreen.main.scale UIGraphicsBeginImageContextWithOptions(size, false, scale); image.draw(in: rect) touchImage.draw(in: rect, blendMode: CGBlendMode.normal, alpha: 1.0) let renderedImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext(); return renderedImage } else { // This is the case when no touches were tracked, then we don't make // a screenshot return nil } } }
mit
3ed716d221f0de297a1a7d1bc1673e8f
31.744589
161
0.563723
5.557678
false
false
false
false
TerryCK/GogoroBatteryMap
GogoroMap/GuidePageViewController.swift
1
2010
// // GuidePageViewController.swift // GogoroMap // // Created by 陳 冠禎 on 2017/8/12. // Copyright © 2017年 陳 冠禎. All rights reserved. // import UIKit import Crashlytics protocol GuidePageViewControllerDelegate: AnyObject { func setCurrentLocation(latDelta: Double, longDelta: Double) } final class GuidePageViewController: UIViewController { weak var delegate: GuidePageViewControllerDelegate? private lazy var guideImageView: UIImageView = { let imageView: UIImageView = UIImageView(frame: view.frame) imageView.image = #imageLiteral(resourceName: "guidePage") imageView.contentMode = .scaleAspectFit imageView.isUserInteractionEnabled = true return imageView }() private lazy var okButton: UIButton = { let button = CustomButton(type: .system) button.setTitle(NSLocalizedString("Press here and continue", comment: ""), for: .normal) button.titleLabel?.font = .boldSystemFont(ofSize: 20) button.addTarget(self, action: #selector(dismissController), for: .touchUpInside) return button }() override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) Answers.log(view: "Guide Page") } override func viewDidLoad() { super.viewDidLoad() view.addSubview(guideImageView) guideImageView.addSubview(okButton) okButton.anchor(top: nil, left: guideImageView.leftAnchor, bottom: guideImageView.bottomAnchor, right: guideImageView.rightAnchor, topPadding: 0, leftPadding: 10, bottomPadding: 20, rightPadding: 10, width: 0, height: 35) okButton.centerXAnchor.constraint(equalTo: guideImageView.centerXAnchor).isActive = true } @objc func dismissController() { UserDefaults.standard.set(true, forKey: Keys.standard.beenHereKey) delegate?.setCurrentLocation(latDelta: 0.05, longDelta: 0.05) dismiss(animated: true, completion: nil) } }
mit
b316156845fd5314a9278ba65fe7ffe8
35.272727
229
0.693233
4.705189
false
false
false
false
loanburger/ImocNZ
ImocNZ/Reachability.swift
1
1174
// // ConnectionStatus.swift // ImocNZ // // Created by Loan Burger on 12/11/14. // Copyright (c) 2014 Loan Burger. All rights reserved. // import Foundation import SystemConfiguration public class Reachability { class func isConnectedToNetwork() -> Bool { var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0)) zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress)) zeroAddress.sin_family = sa_family_t(AF_INET) let defaultRouteReachability = withUnsafePointer(&zeroAddress) { SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)).takeRetainedValue() } var flags: SCNetworkReachabilityFlags = 0 if SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) == 0 { return false } let isReachable = (flags & UInt32(kSCNetworkFlagsReachable)) != 0 let needsConnection = (flags & UInt32(kSCNetworkFlagsConnectionRequired)) != 0 return (isReachable && !needsConnection) ? true : false } }
mit
70171706191d80db5fa9e9473d9dd8b7
29.921053
143
0.632027
4.463878
false
false
false
false
yuanhao/unu-demo-ios
SocketIOClientSwift/SocketParser.swift
2
6978
// // SocketParser.swift // Socket.IO-Client-Swift // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation class SocketParser { private static func isCorrectNamespace(nsp: String, _ socket: SocketIOClient) -> Bool { return nsp == socket.nsp } private static func handleConnect(p: SocketPacket, socket: SocketIOClient) { if p.nsp == "/" && socket.nsp != "/" { socket.joinNamespace() } else if p.nsp != "/" && socket.nsp == "/" { socket.didConnect() } else { socket.didConnect() } } private static func handlePacket(pack: SocketPacket, withSocket socket: SocketIOClient) { switch pack.type { case .Event where isCorrectNamespace(pack.nsp, socket): socket.handleEvent(pack.event, data: pack.args ?? [], isInternalMessage: false, wantsAck: pack.id) case .Ack where isCorrectNamespace(pack.nsp, socket): socket.handleAck(pack.id, data: pack.data) case .BinaryEvent where isCorrectNamespace(pack.nsp, socket): socket.waitingData.append(pack) case .BinaryAck where isCorrectNamespace(pack.nsp, socket): socket.waitingData.append(pack) case .Connect: handleConnect(pack, socket: socket) case .Disconnect: socket.didDisconnect("Got Disconnect") case .Error: socket.didError(pack.data) default: DefaultSocketLogger.Logger.log("Got invalid packet: %@", type: "SocketParser", args: pack.description) } } static func parseString(message: String) -> Either<String, SocketPacket> { var parser = SocketStringReader(message: message) guard let type = SocketPacket.PacketType(rawValue: Int(parser.read(1)) ?? -1) else { return .Left("Invalid packet type") } if !parser.hasNext { return .Right(SocketPacket(type: type, nsp: "/")) } var namespace: String? var placeholders = -1 if type == .BinaryEvent || type == .BinaryAck { if let holders = Int(parser.readUntilStringOccurence("-")) { placeholders = holders } else { return .Left("Invalid packet") } } if parser.currentCharacter == "/" { namespace = parser.readUntilStringOccurence(",") ?? parser.readUntilEnd() } if !parser.hasNext { return .Right(SocketPacket(type: type, id: -1, nsp: namespace ?? "/", placeholders: placeholders)) } var idString = "" if type == .Error { parser.advanceIndexBy(-1) } while parser.hasNext && type != .Error { if let int = Int(parser.read(1)) { idString += String(int) } else { parser.advanceIndexBy(-2) break } } let d = message[parser.currentIndex.advancedBy(1)..<message.endIndex] let noPlaceholders = d["(\\{\"_placeholder\":true,\"num\":(\\d*)\\})"] ~= "\"~~$2\"" switch parseData(noPlaceholders) { case .Left(let err): // If first you don't succeed, try again if case let .Right(data) = parseData("\([noPlaceholders as AnyObject])") { return .Right(SocketPacket(type: type, data: data, id: Int(idString) ?? -1, nsp: namespace ?? "/", placeholders: placeholders)) } else { return .Left(err) } case .Right(let data): return .Right(SocketPacket(type: type, data: data, id: Int(idString) ?? -1, nsp: namespace ?? "/", placeholders: placeholders)) } } // Parses data for events private static func parseData(data: String) -> Either<String, [AnyObject]> { let stringData = data.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) do { if let arr = try NSJSONSerialization.JSONObjectWithData(stringData!, options: NSJSONReadingOptions.MutableContainers) as? [AnyObject] { return .Right(arr) } else { return .Left("Expected data array") } } catch { return .Left("Error parsing data for packet") } } // Parses messages recieved static func parseSocketMessage(message: String, socket: SocketIOClient) { guard !message.isEmpty else { return } DefaultSocketLogger.Logger.log("Parsing %@", type: "SocketParser", args: message) switch parseString(message) { case .Left(let err): DefaultSocketLogger.Logger.error("\(err): %@", type: "SocketParser", args: message) case .Right(let pack): DefaultSocketLogger.Logger.log("Decoded packet as: %@", type: "SocketParser", args: pack.description) handlePacket(pack, withSocket: socket) } } static func parseBinaryData(data: NSData, socket: SocketIOClient) { guard !socket.waitingData.isEmpty else { DefaultSocketLogger.Logger.error("Got data when not remaking packet", type: "SocketParser") return } // Should execute event? guard socket.waitingData[socket.waitingData.count - 1].addData(data) else { return } var packet = socket.waitingData.removeLast() packet.fillInPlaceholders() if packet.type != .BinaryAck { socket.handleEvent(packet.event, data: packet.args ?? [], isInternalMessage: false, wantsAck: packet.id) } else { socket.handleAck(packet.id, data: packet.args) } } }
apache-2.0
70cc646f167669e1faead1b64ffa8d30
38.202247
114
0.588277
4.776181
false
false
false
false
TonnyTao/HowSwift
how_to_update_view_in_mvvm.playground/Sources/RxSwift/RxSwift/Observables/SubscribeOn.swift
8
3765
// // SubscribeOn.swift // RxSwift // // Created by Krunoslav Zaher on 6/14/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // extension ObservableType { /** Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used. This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer callbacks on a `scheduler`, use `observeOn`. - seealso: [subscribeOn operator on reactivex.io](http://reactivex.io/documentation/operators/subscribeon.html) - parameter scheduler: Scheduler to perform subscription and unsubscription actions on. - returns: The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. */ public func subscribe(on scheduler: ImmediateSchedulerType) -> Observable<Element> { SubscribeOn(source: self, scheduler: scheduler) } /** Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used. This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer callbacks on a `scheduler`, use `observeOn`. - seealso: [subscribeOn operator on reactivex.io](http://reactivex.io/documentation/operators/subscribeon.html) - parameter scheduler: Scheduler to perform subscription and unsubscription actions on. - returns: The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. */ @available(*, deprecated, renamed: "subscribe(on:)") public func subscribeOn(_ scheduler: ImmediateSchedulerType) -> Observable<Element> { subscribe(on: scheduler) } } final private class SubscribeOnSink<Ob: ObservableType, Observer: ObserverType>: Sink<Observer>, ObserverType where Ob.Element == Observer.Element { typealias Element = Observer.Element typealias Parent = SubscribeOn<Ob> let parent: Parent init(parent: Parent, observer: Observer, cancel: Cancelable) { self.parent = parent super.init(observer: observer, cancel: cancel) } func on(_ event: Event<Element>) { self.forwardOn(event) if event.isStopEvent { self.dispose() } } func run() -> Disposable { let disposeEverything = SerialDisposable() let cancelSchedule = SingleAssignmentDisposable() disposeEverything.disposable = cancelSchedule let disposeSchedule = self.parent.scheduler.schedule(()) { _ -> Disposable in let subscription = self.parent.source.subscribe(self) disposeEverything.disposable = ScheduledDisposable(scheduler: self.parent.scheduler, disposable: subscription) return Disposables.create() } cancelSchedule.setDisposable(disposeSchedule) return disposeEverything } } final private class SubscribeOn<Ob: ObservableType>: Producer<Ob.Element> { let source: Ob let scheduler: ImmediateSchedulerType init(source: Ob, scheduler: ImmediateSchedulerType) { self.source = source self.scheduler = scheduler } override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Ob.Element { let sink = SubscribeOnSink(parent: self, observer: observer, cancel: cancel) let subscription = sink.run() return (sink: sink, subscription: subscription) } }
mit
160fe250fb916e6aaf497a6881e81057
35.543689
174
0.695271
5.100271
false
false
false
false
mactive/rw-courses-note
your-first-swiftui-app/Bullseye/Bullseye/SceneDelegate.swift
1
2756
// // SceneDelegate.swift // Bullseye // // Created by Qian Meng on 2020/1/19. // Copyright © 2020 Qian Meng. All rights reserved. // import UIKit import SwiftUI class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead). // Create the SwiftUI view that provides the window contents. let contentView = ContentView() // Use a UIHostingController as window root view controller. if let windowScene = scene as? UIWindowScene { let window = UIWindow(windowScene: windowScene) window.rootViewController = UIHostingController(rootView: contentView) self.window = window window.makeKeyAndVisible() } } func sceneDidDisconnect(_ scene: UIScene) { // Called as the scene is being released by the system. // This occurs shortly after the scene enters the background, or when its session is discarded. // Release any resources associated with this scene that can be re-created the next time the scene connects. // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead). } func sceneDidBecomeActive(_ scene: UIScene) { // Called when the scene has moved from an inactive state to an active state. // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive. } func sceneWillResignActive(_ scene: UIScene) { // Called when the scene will move from an active state to an inactive state. // This may occur due to temporary interruptions (ex. an incoming phone call). } func sceneWillEnterForeground(_ scene: UIScene) { // Called as the scene transitions from the background to the foreground. // Use this method to undo the changes made on entering the background. } func sceneDidEnterBackground(_ scene: UIScene) { // Called as the scene transitions from the foreground to the background. // Use this method to save data, release shared resources, and store enough scene-specific state information // to restore the scene back to its current state. } }
mit
dd550502bc5c83c8a4626cb990932710
42.046875
147
0.703085
5.318533
false
false
false
false
apple/swift-argument-parser
Tools/generate-manual/MDoc/MDocMacro.swift
1
47760
//===----------------------------------------------------------*- swift -*-===// // // This source file is part of the Swift Argument Parser open source project // // Copyright (c) 2021 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 // //===----------------------------------------------------------------------===// //===--------------------------------------------------------*- openbsd -*-===// // // This source file contains descriptions of mandoc syntax tree nodes derived // from their original descriptions in the mandoc source found here: // https://github.com/openbsd/src/blob/master/share/man/man7/mdoc.7 // // $Id: LICENSE,v 1.22 2021/09/19 11:02:09 schwarze Exp $ // // With the exceptions noted below, all non-trivial files contained // in the mandoc toolkit are protected by the Copyright of the following // developers: // // Copyright (c) 2008-2012, 2014 Kristaps Dzonsons <[email protected]> // Copyright (c) 2010-2021 Ingo Schwarze <[email protected]> // Copyright (c) 1999, 2004, 2017 Marc Espie <[email protected]> // Copyright (c) 2009, 2010, 2011, 2012 Joerg Sonnenberger <[email protected]> // Copyright (c) 2013 Franco Fichtner <[email protected]> // Copyright (c) 2014 Baptiste Daroussin <[email protected]> // Copyright (c) 2016 Ed Maste <[email protected]> // Copyright (c) 2017 Michael Stapelberg <[email protected]> // Copyright (c) 2017 Anthony Bentley <[email protected]> // Copyright (c) 1998, 2004, 2010, 2015 Todd C. Miller <[email protected]> // Copyright (c) 2008, 2017 Otto Moerbeek <[email protected]> // Copyright (c) 2004 Ted Unangst <[email protected]> // Copyright (c) 1994 Christos Zoulas <[email protected]> // Copyright (c) 2003, 2007, 2008, 2014 Jason McIntyre <[email protected]> // // See the individual files for information about who contributed // to which file during which years. // // // The mandoc distribution as a whole is distributed by its developers // under the following license: // // Permission to use, copy, modify, and distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. // // // The following files included from outside sources are protected by // other people's Copyright and are distributed under various 2-clause // and 3-clause BSD licenses; see these individual files for details. // // soelim.c, soelim.1: // Copyright (c) 2014 Baptiste Daroussin <[email protected]> // // compat_err.c, compat_fts.c, compat_fts.h, // compat_getsubopt.c, compat_strcasestr.c, compat_strsep.c, // man.1: // Copyright (c) 1989,1990,1993,1994 The Regents of the University of California // // compat_stringlist.c, compat_stringlist.h: // Copyright (c) 1994 Christos Zoulas <[email protected]> // // See https://mandoc.bsd.lv/LICENSE for license information // //===----------------------------------------------------------------------===// fileprivate extension Array { mutating func append(optional newElement: Element?) { if let newElement = newElement { append(newElement) } } } /// `MDocMacroProtocol` defines the properties required to serialize a /// strongly-typed mdoc macro to the raw format. public protocol MDocMacroProtocol: MDocASTNode { /// The underlying `mdoc` macro string; used during serialization. static var kind: String { get } /// The arguments passed to the underlying `mdoc` macro; used during /// serialization. var arguments: [MDocASTNode] { get set } } extension MDocMacroProtocol { /// Append unchecked arguments to a `MDocMacroProtocol`. public func withUnsafeChildren(nodes: [MDocASTNode]) -> Self { var copy = self copy.arguments.append(contentsOf: nodes) return copy } } extension MDocMacroProtocol { public func _serialized(context: MDocSerializationContext) -> String { var result = "" // Prepend a dot if we aren't already in a macroLine context if !context.macroLine { result += "." } result += Self.kind if !arguments.isEmpty { var context = context context.macroLine = true result += " " result += arguments .map { $0._serialized(context: context) } .joined(separator: " ") } return result } } /// `MDocMacro` is a namespace for types conforming to ``MDocMacroProtocol``. public enum MDocMacro { /// Comment placed inline in the manual page. /// /// Comment are not displayed by tools consuming serialized manual pages. /// /// __Example Usage__: /// ```swift /// Comment("WIP: History section...") /// ``` public struct Comment: MDocMacroProtocol { public static let kind = #"\""# public var arguments: [MDocASTNode] /// Creates a new `Comment` macro. /// /// - Parameters: /// - comment: A string to insert as an inline comment. public init(_ comment: String) { self.arguments = [comment] } } // MARK: - Document preamble and NAME section macros /// Document date displayed in the manual page footer. /// /// This must be the first macro in any `mdoc` document. /// /// __Example Usage__: /// ```swift /// DocumentDate(day: 9, month: "September", year: 2014) /// ``` public struct DocumentDate: MDocMacroProtocol { public static let kind = "Dd" public var arguments: [MDocASTNode] /// Creates a new `DocumentDate` macro. /// /// - Parameters: /// - day: An integer number day of the month the manual was written. /// - month: The full English month name the manual was written. /// - year: The four digit year the manual was written. public init(day: Int, month: String, year: Int) { arguments = [month, "\(day),", year] } } /// Document title displayed in the manual page header. /// /// This must be the second macro in any `mdoc` document. /// /// __Example Usage__: /// ```swift /// DocumentTitle(title: "swift", section: 1) /// DocumentTitle(title: "swift", section: 1, arch: "arm64e") /// ``` public struct DocumentTitle: MDocMacroProtocol { public static let kind = "Dt" public var arguments: [MDocASTNode] /// Creates a new `DocumentTitle` macro. /// /// - Parameters: /// - title: The document's title or name. By convention the title should /// be all caps. /// - section: The manual section. The section should match the manual /// page's file extension. Must be one of the following values: /// 1. General Commands /// 2. System Calls /// 3. Library Functions /// 4. Device Drivers /// 5. File Formats /// 6. Games /// 7. Miscellaneous Information /// 8. System Manager's Manual /// 9. Kernel Developer's Manual /// - arch: The machine architecture the manual page applies to, for /// example: `alpha`, `i386`, `x86_64` or `arm64e`. public init(title: String, section: Int, arch: String? = nil) { precondition((1...9).contains(section)) self.arguments = [title, section] self.arguments.append(optional: arch) } } /// Operating system and version displayed in the manual page footer. /// /// This must be the third macro in any `mdoc` document. /// /// __Example Usage__: /// ```swift /// OperatingSystem() /// OperatingSystem(name: "macOS") /// OperatingSystem(name: "macOS", version: "10.13") /// ``` public struct OperatingSystem: MDocMacroProtocol { public static let kind = "Os" public var arguments: [MDocASTNode] /// Creates a new `OperatingSystem` macro. /// /// - Note: The `version` parameter must not be specified without the `name` /// parameter. /// /// - Parameters: /// - name: The operating system the manual page contents is valid for. /// Omitting `name` is recommended and will result in the user's /// operating system name being used. /// - version: The version the of the operating system specified by `name` /// the manual page contents is valid for. Omitting `version` is /// recommended. public init(name: String? = nil, version: String? = nil) { precondition(!(name == nil && version != nil)) self.arguments = [] self.arguments.append(optional: name) self.arguments.append(optional: version) } } /// The name of the manual page. /// /// The first use of ``DocumentName`` is typically in the "NAME" section. The /// name provided to the created ``DocumentName`` will be remembered and /// subsequent uses of the ``DocumentName`` can omit the name argument. /// /// - Note: Manual pages in sections 1, 6, and 8 may use the name of command /// or feature documented in the manual page as the name. /// /// In sections 2, 3, and 9 use the ``FunctionName`` macro instead of the /// ``DocumentName`` macro to indicate the name of the document. /// /// __Example Usage__: /// ```swift /// SectionHeader(title: "SYNOPSIS") /// DocumentName(name: "swift") /// OptionalCommandLineComponent(arguments: CommandArgument(arguments: ["h"])) /// ``` public struct DocumentName: MDocMacroProtocol { public static let kind = "Nm" public var arguments: [MDocASTNode] /// Creates a new `DocumentName` macro. /// /// - Parameters: /// - name: The name of the manual page. public init(name: String? = nil) { self.arguments = [] self.arguments.append(optional: name) } } /// Single line description of the manual page. /// /// This must be the last macro in the "NAME" section `mdoc` document and /// should not appear in any other section. /// /// __Example Usage__: /// ```swift /// DocumentDescription(description: "Safe, fast, and expressive general-purpose programming language") /// ``` public struct DocumentDescription: MDocMacroProtocol { public static let kind = "Nd" public var arguments: [MDocASTNode] /// Creates a new `DocumentDescription` macro. /// /// - Parameters: /// - description: The description of the manual page. public init(description: String) { self.arguments = [description] } } // MARK: - Sections and cross references /// Start a new manual section. /// /// See [Manual Structure](http://mandoc.bsd.lv/man/mdoc.7.html#MANUAL_STRUCTURE) /// for a list of standard sections. Custom sections should be avoided though /// can be used. /// /// - Note: Section names should be unique so they can be referenced using a /// ``SectionReference``. /// /// __Example Usage__: /// ```swift /// SectionHeader(title: "NAME") /// ``` public struct SectionHeader: MDocMacroProtocol { public static let kind = "Sh" public var arguments: [MDocASTNode] /// Creates a new `SectionHeader` macro. /// /// - Parameters: /// - title: The title of the section. public init(title: String) { self.arguments = [title] } } /// Start a new manual subsection. /// /// There is no standard naming convention of subsections. /// /// - Note: Subsection names should be unique so they can be referenced using /// a ``SectionReference``. /// /// __Example Usage__: /// ```swift /// SubsectionHeader(title: "DETAILS") /// ``` public struct SubsectionHeader: MDocMacroProtocol { public static let kind = "Ss" public var arguments: [MDocASTNode] /// Creates a new `SubsectionHeader` macro. /// /// - Parameters: /// - title: The title of the subsection. public init(title: String) { self.arguments = [title] } } /// Reference a section or subsection in the same manual page. /// /// The section or subsection title must exactly match the title passed to /// ``SectionReference``. /// /// __Example Usage__: /// ```swift /// SectionReference(title: "NAME") /// ``` public struct SectionReference: MDocMacroProtocol { public static let kind = "Sx" public var arguments: [MDocASTNode] /// Creates a new `SectionReference` macro. /// /// - Parameters: /// - title: The title of the section or subsection to reference. public init(title: String) { self.arguments = [title] } } /// Reference another manual page. /// /// __Example Usage__: /// ```swift /// CrossManualReference(title: "swift", section: 1) /// ``` public struct CrossManualReference: MDocMacroProtocol { public static let kind = "Xr" public var arguments: [MDocASTNode] /// Creates a new `CrossManualReference` macro. /// /// - Parameters: /// - title: The title of the section or subsection to reference. public init(title: String, section: Int) { precondition((1...9).contains(section)) self.arguments = [title, section] } } /// Whitespace break between paragaphs. /// /// Breaks should not be inserted immeediately before or after /// ``SectionHeader``, ``SubsectionHeader``, and ``BeginList`` macros. public struct ParagraphBreak: MDocMacroProtocol { public static let kind = "Pp" public var arguments: [MDocASTNode] /// Creates a new `ParagraphBreak` macro. public init() { self.arguments = [] } } // MARK: - Displays and lists // Display block: -type [-offset width] [-compact]. // TODO: "Ed" // Indented display (one line). // TODO: "D1" // Indented literal display (one line). // TODO: "Dl" // In-line literal display: ‘text’. // TODO: "Ql" // FIXME: Documentation /// Open a list scope. /// /// Closed by an ``EndList`` macro. /// /// Lists are made of ``ListItem``s which are displayed in a variety of styles /// depending on the ``ListStyle`` used to create the list scope. /// List scopes can be nested in other list scopes, however nesting `.column` /// and `ListStyle.enum` lists is not recommended as they may display inconsistently /// between tools. /// /// __Example Usage__: /// ```swift /// BeginList(style: .tag, width: 6) /// ListItem(title: "Hello, Swift!") /// "Welcome to the Swift programming language." /// ListItem(title: "Goodbye!") /// EndList() /// ``` public struct BeginList: MDocMacroProtocol { /// Enumeration of styles supported by the ``BeginList`` macro. public enum ListStyle: String { /// A bulleted list. /// /// Item titles should not be provided, instead item bodies are displayed /// indented from a preceding bullet point using the specified width. case bullet // TODO: case column // /// A columnated list. // case column /// A dashed list. /// /// Identical to `.bullet` except dashes precede each item. case dash /// An unindented list without newlines following important item titles /// without macro parsing. /// /// Identical to `.inset` except item titles are displayed with importance /// and are not parsed for macros. `.diag` is typically used in the /// "DIAGNOSTICS" section with errors as the item titles. case diag /// An enumerated list. /// /// Identical to `.bullet` except increasing numbers starting at 1 precede /// each item. case `enum` /// An indented list without joined item titles and bodies. /// /// Identical to `.tag` except item bodies always on the line after the /// item title. case hang /// Alias for `.dash`. case hyphen /// An unindented list without newlines following item titles. /// /// Identical to `.ohang` except item titles are not followed by newlines. case inset /// An unindented list without item titles. /// /// Identical to `.ohang` except item titles should not be provided and /// are not displayed. case item /// An unindented list. /// /// Item titles are displayed on a single line, with unindented item /// bodies on the succeeding lines. case ohang /// An indented list. /// /// Item titles are displayed on a single line with item bodies indented /// using the specified width on succeeding lines. If the item title is /// shorter than the indentation width, item bodies are displayed on the /// same as the title. case tag } public static let kind = "Bl" public var arguments: [MDocASTNode] /// Creates a new `BeginList` macro. /// /// - Parameters: /// - style: Display style. /// - width: Number of characters to indent item bodies from titles. /// - offset: Number of characters to indent both the item titles and bodies. /// - compact: Disable vertical spacing between list items. public init(style: ListStyle, width: Int? = nil, offset: Int? = nil, compact: Bool = false) { self.arguments = ["-\(style)"] switch style { case .bullet, .dash, .`enum`, .hang, .hyphen, .tag: if let width = width { self.arguments.append(contentsOf: ["-width", "\(width)n"]) } case /*.column, */.diag, .inset, .item, .ohang: assert(width == nil, "`width` should be nil for style: \(style)") } if let offset = offset { self.arguments.append(contentsOf: ["-offset", "\(offset)n"]) } if compact { self.arguments.append(contentsOf: ["-compact"]) } } } /// A list item. /// /// ``ListItem`` begins a list item scope continuing until another /// ``ListItem`` is encountered or the enclosing list scope is closed by /// ``EndList``. ``ListItem``s may include a title if the the enclosing list /// scope was constructed with one of the following styles: /// - `.bullet` /// - `.dash` /// - `.enum` /// - `.hang` /// - `.hyphen` /// - `.tag` /// /// __Example Usage__: /// ```swift /// BeginList(style: .tag, width: 6) /// ListItem(title: "Hello, Swift!") /// "Welcome to the Swift programming language." /// ListItem(title: "Goodbye!") /// EndList() /// ``` public struct ListItem: MDocMacroProtocol { public static let kind = "It" public var arguments: [MDocASTNode] /// Creates a new `ListItem` macro. /// /// - Parameters: /// - title: List item title, only valid depending on the ``ListStyle``. public init(title: MDocASTNode? = nil) { arguments = [] arguments.append(optional: title) } } // Table cell separator in Bl -column lists. // TODO: "Ta" /// Close a list scope opened by a ``BeginList`` macro. public struct EndList: MDocMacroProtocol { public static let kind = "El" public var arguments: [MDocASTNode] /// Creates a new `EndList` macro. public init() { self.arguments = [] } } // Bibliographic block (references). // TODO: "Re" // MARK: Spacing control /// Text without a trailing space. /// /// __Example Usage__: /// ```swift /// WithoutTrailingSpace(text: "swift") /// ``` public struct WithoutTrailingSpace: MDocMacroProtocol { public static let kind = "Pf" public var arguments: [MDocASTNode] /// Creates a new `WithoutTrailingSpace` macro. /// /// - Parameters: /// - text: The text to display without a trailing space. public init(text: String) { self.arguments = [text] } } /// Text without a leading space. /// /// __Example Usage__: /// ```swift /// WithoutLeadingSpace(text: "swift") /// ``` public struct WithoutLeadingSpace: MDocMacroProtocol { public static let kind = "Ns" public var arguments: [MDocASTNode] /// Creates a new `WithoutLeadingSpace` macro. /// /// - Parameters: /// - text: The text to display without a trailing space. public init(text: String) { self.arguments = [text] } } /// An apostrophe without leading and trailing spaces. /// /// __Example Usage__: /// ```swift /// Apostrophe() /// ``` public struct Apostrophe: MDocMacroProtocol { public static let kind = "Ap" public var arguments: [MDocASTNode] /// Creates a new `Apostrophe` macro. public init() { self.arguments = [] } } // TODO: HorizontalSpacing // /// Switch horizontal spacing mode: [on | off]. // public struct HorizontalSpacing: MDocMacroProtocol { // public static let kind = "Sm" // public var arguments: [MDocASTNode] // public init() { // self.arguments = [] // } // } // Keep block: -words. // TODO: "Ek" // MARK: - Semantic markup for command-line utilities /// Command-line flags and options. /// /// Displays a hyphen (`-`) before each argument. ``CommandOption`` is /// typically used in the "SYNOPSIS" and "DESCRIPTION" sections when listing /// and describing options in a manual page. /// /// __Example Usage__: /// ```swift /// CommandOption(arguments: ["-version"]) /// .withUnsafeChildren(CommandArgument(arguments: "version")) /// ``` public struct CommandOption: MDocMacroProtocol { public static let kind = "Fl" public var arguments: [MDocASTNode] /// Creates a new `CommandOption` macro. /// /// - Parameters: /// - arguments: Command-line flags and options. public init(options: [MDocASTNode]) { self.arguments = options } } /// Command-line modifiers. /// /// ``CommandModifier`` is typically used to denote strings exactly passed as /// arguments, if and only if, ``CommandOption`` is not appropriate. /// ``CommandModifier`` can also be used to specify configuration options and /// keys. /// /// __Example Usage__: /// ```swift /// CommandModifier(modifiers: ["Configuration File"]) /// .withUnsafeChildren(nodes: [FilePath(path: "$HOME/.swiftpm")]) /// ``` public struct CommandModifier: MDocMacroProtocol { public static let kind = "Cm" public var arguments: [MDocASTNode] /// Creates a new `CommandModifier` macro. /// /// - Parameters: /// - modifiers: Command-line modifiers. public init(modifiers: [MDocASTNode]) { self.arguments = modifiers } } /// Command-line placeholders. /// /// ``CommandArgument`` displays emphasized placeholders for command-line /// flags, options and arguments. Flag and option names must use /// ``CommandOption`` or `CommandModifier` macros. If no arguments are /// provided to ``CommandArgument``, the string `"file ..."` is used. /// /// __Example Usage__: /// ```swift /// CommandArgument() /// CommandArgument(arguments: [arg1, ",", arg2, "."]) /// CommandOption(arguments: ["-version"]) /// .withUnsafeChildren(CommandArgument(arguments: "version")) /// ``` public struct CommandArgument: MDocMacroProtocol { public static let kind = "Ar" public var arguments: [MDocASTNode] /// Creates a new `CommandArgument` macro. /// /// - Parameters: /// - arguments: Command-line argument placeholders. public init(arguments: [MDocASTNode]) { self.arguments = arguments } } /// Single-line optional command-line components. /// /// Displays the arguments in `[squareBrackets]`. /// ``OptionalCommandLineComponent`` is typically used in the "SYNOPSIS" /// section. /// /// __Example Usage__: /// ```swift /// SectionHeader(title: "SYNOPSIS") /// DocumentName(name: "swift") /// OptionalCommandLineComponent(arguments: CommandArgument(arguments: ["h"])) /// ``` public struct OptionalCommandLineComponent: MDocMacroProtocol { public static let kind = "Op" public var arguments: [MDocASTNode] /// Creates a new `OptionalCommandLineComponent` macro. /// /// - Parameters: /// - arguments: Command-line components to enclose. public init(arguments: [MDocASTNode]) { self.arguments = arguments } } /// Begin a multi-line optional command-line comment scope. /// /// Displays the scope contents in `[squareBrackets]`. /// ``BeginOptionalCommandLineComponent`` is typically used in the "SYNOPSIS" /// section. /// /// Closed by an ``EndOptionalCommandLineComponent`` macro. /// /// __Example Usage__: /// ```swift /// BeginOptionalCommandLineComponent() /// "Hello, Swift!" /// EndOptionalCommandLineComponent() /// ``` public struct BeginOptionalCommandLineComponent: MDocMacroProtocol { public static let kind = "Oo" public var arguments: [MDocASTNode] /// Creates a new `BeginOptionalCommandLineComponent` macro. public init() { self.arguments = [] } } /// Close a ```BeginOptionalCommandLineComponent``` block. public struct EndOptionalCommandLineComponent: MDocMacroProtocol { public static let kind = "Oc" public var arguments: [MDocASTNode] /// Creates a new `EndOptionalCommandLineComponent` macro. public init() { self.arguments = [] } } /// An interactive command. /// /// ``InteractiveCommand`` is similar to ``CommandModifier`` but should be used /// to describe commands instead of arguments. For example, /// ``InteractiveCommand`` can be used to describe the commands to editors /// like `emacs` and `vim` or shells like `bash` or `fish`. /// /// __Example Usage__: /// ```swift /// InteractiveCommand(name: "print") /// InteractiveCommand(name: "save") /// InteractiveCommand(name: "quit") /// ``` public struct InteractiveCommand: MDocMacroProtocol { public static let kind = "Ic" public var arguments: [MDocASTNode] /// Creates a new `InteractiveCommand` macro. /// /// - Parameters: /// - name: Name of the interactive command. public init(name: String) { self.arguments = [name] } } /// An environment variable. /// /// __Example Usage__: /// ```swift /// EnvironmentVariable(variable: "DISPLAY") /// EnvironmentVariable(variable: "PATH") /// ``` public struct EnvironmentVariable: MDocMacroProtocol { public static let kind = "Ev" public var arguments: [MDocASTNode] /// Creates a new `EnvironmentVariable` macro. /// /// - Parameters: /// - name: Name of the environment variable. public init(name: String) { self.arguments = [name] } } /// A file path. /// /// __Example Usage__: /// ```swift /// FilePath() /// FilePath(path: "/usr/bin/swift") /// FilePath(path: "/usr/share/man/man1/swift.1") /// ``` public struct FilePath: MDocMacroProtocol { public static let kind = "Pa" public var arguments: [MDocASTNode] /// Creates a new `FilePath` macro. /// /// - Parameters: /// - path: An optional absolute or relative path or a file or directory. /// Tilde (`~`) will be used, if no path is used. public init(path: String? = nil) { self.arguments = [] self.arguments.append(optional: path) } } // MARK: - Semantic markup for function libraries // Function library (one argument). // TODO: "Lb" // Include file (one argument). // TODO: "In" // Other preprocessor directive (>0 arguments). // TODO: "Fd" // Function type (>0 arguments). // TODO: "Ft" // Function block: funcname. // TODO: "Fc" // Function name: funcname [argument ...]. // TODO: "Fn" // Function argument (>0 arguments). // TODO: "Fa" // Variable type (>0 arguments). // TODO: "Vt" // Variable name (>0 arguments). // TODO: "Va" /// Defined variable or preprocessor constant (>0 arguments). // TODO: "Dv" /// Error constant (>0 arguments). // TODO: "Er" /// Environmental variable (>0 arguments). // TODO: "Ev" // MARK: - Various semantic markup /// An author's name. /// /// ``Author`` can be used to designate any author. Specifying an author of /// the manual page itself should only occur in the "AUTHORS" section. /// /// ``Author`` also controls the display mode of authors. In the split mode, /// a new-line will be inserted before each author, otherwise authors will /// appear inline with other macros and text. Outside of the "AUTHORS" /// section, the default display mode is unsplit. The display mode is reset at /// the start of the "AUTHORS" section. In the "AUTHORS" section, the first /// use of ``Author`` will use the unsplit mode and subsequent uses with use /// the split mode. This behavior can be overridden by inserting an author /// display mode macro before the normal author macro. /// /// __Example Usage__: /// ```swift /// Author(split: false) /// Author(name: "Rauhul Varma") /// ``` public struct Author: MDocMacroProtocol { public static let kind = "An" public var arguments: [MDocASTNode] /// Creates a new `Author` macro. /// /// - Parameters: /// - name: The author name to display. public init(name: String) { self.arguments = [name] } /// Creates a new `Author` macro. /// /// - Parameters: /// - split: The split display mode to use for subsequent uses of /// ``Author``. public init(split: Bool) { self.arguments = [split ? "-split" : "-nosplit"] } } /// A website hyperlink. /// /// __Example Usage__: /// ```swift /// Hyperlink(url: "http://swift.org") /// Hyperlink(url: "http://swift.org", displayText: "Programming in Swift") /// ``` public struct Hyperlink: MDocMacroProtocol { public static let kind = "Lk" public var arguments: [MDocASTNode] /// Creates a new `Hyperlink` macro. /// /// - Parameters: /// - url: The website address to link. /// - displayText: Optional title text accompanying the url. public init(url: String, displayText: String? = nil) { self.arguments = [url] self.arguments.append(optional: displayText) } } /// An email hyperlink. /// /// __Example Usage__: /// ```swift /// MailTo(email: "[email protected]") /// ``` public struct MailTo: MDocMacroProtocol { public static let kind = "Mt" public var arguments: [MDocASTNode] /// Creates a new `MailTo` macro. /// /// - Parameters: /// - email: The email address to link. public init(email: String) { self.arguments = [email] } } // TODO: KernelConfiguration // /// Kernel configuration declaration (>0 arguments). // public struct KernelConfiguration: MDocMacroProtocol { // public static let kind = "Cd" // public var arguments: [MDocASTNode] // public init() { // self.arguments = [] // } // } // TODO: MemoryAddress // /// Memory address (>0 arguments). // public struct MemoryAddress: MDocMacroProtocol { // public static let kind = "Ad" // public var arguments: [MDocASTNode] // public init() { // self.arguments = [] // } // } // TODO: MathematicalSymbol // /// Mathematical symbol (>0 arguments). // public struct MathematicalSymbol: MDocMacroProtocol { // public static let kind = "Ms" // public var arguments: [MDocASTNode] // public init() { // self.arguments = [] // } // } // MARK: - Physical markup /// Emphasize single-line text. /// /// ``Emphasis`` should only be used when no other semantic macros are /// appropriate. ``Emphasis`` is used to express "emphasis"; for example: /// ``Emphasis`` can be used to highlight technical terms and placeholders, /// except when they appear in syntactic elements. ``Emphasis`` should not be /// conflated with "importance" which should be expressed using ``Boldface``. /// /// - Note: Emphasizes text is usually italicized. If the output program does /// not support italicizing text, it is underlined instead. /// /// __Example Usage__: /// ```swift /// Emphasis(arguments: ["Hello", ", "Swift!"]) /// ``` public struct Emphasis: MDocMacroProtocol { public static let kind = "Em" public var arguments: [MDocASTNode] /// Creates a new `Emphasis` macro. /// /// - Parameters: /// - arguments: Text to emphasize. public init(arguments: [MDocASTNode]) { self.arguments = arguments } } /// Embolden single-line text. /// /// ``Boldface`` should only be used when no other semantic macros are /// appropriate. ``Boldface`` is used to express "importance"; for example: /// ``Boldface`` can be used to highlight required arguments and exact text. /// ``Boldface`` should not be conflated with "emphasis" which /// should be expressed using ``Emphasis``. /// /// __Example Usage__: /// ```swift /// Boldface(arguments: ["Hello,", " Swift!"]) /// ``` public struct Boldface: MDocMacroProtocol { public static let kind = "Sy" public var arguments: [MDocASTNode] /// Creates a new `Boldface` macro. /// /// - Parameters: /// - arguments: Text to embolden. public init(arguments: [MDocASTNode]) { self.arguments = arguments } } /// Reset the font style, set by a single-line text macro. /// /// __Example Usage__: /// ```swift /// Boldface(arguments: ["Hello,"]) /// .withUnsafeChildren(nodes: [NormalText(), " Swift!"]) /// ``` public struct NormalText: MDocMacroProtocol { public static let kind = "No" public var arguments: [MDocASTNode] /// Creates a new `NormalText` macro. public init() { self.arguments = [] } } /// Open a font scope with a font style. /// /// Closed by a ``EndFont`` macro. /// /// __Example Usage__: /// ```swift /// BeginFont(style: .boldface) /// "Hello, Swift!" /// EndFont() /// ``` public struct BeginFont: MDocMacroProtocol { /// Enumeration of font styles supported by `mdoc`. public enum FontStyle { /// Italic font style. case emphasis /// Typewriter font style. /// /// `literal` should not be used because it is visually identical to /// normal text. case literal /// Bold font style. case boldface } public static let kind = "Bf" public var arguments: [MDocASTNode] /// Creates a new `BeginFont` macro. /// /// - Parameters: /// - style: The style of font scope the macro opens. public init(style: FontStyle) { switch style { case .emphasis: self.arguments = ["-emphasis"] case .literal: self.arguments = ["-literal"] case .boldface: self.arguments = ["-symbolic"] } } } /// Close a font scope opened by a ``BeginFont`` macro. public struct EndFont: MDocMacroProtocol { public static let kind = "Ef" public var arguments: [MDocASTNode] /// Creates a new `EndFont` macro. public init() { self.arguments = [] } } // MARK: - Physical enclosures /// Open a scope enclosed by `“typographic”` double-quotes. /// /// Closed by a ``EndTypographicDoubleQuotes`` macro. /// /// __Example Usage__: /// ```swift /// BeginTypographicDoubleQuotes() /// "Hello, Swift!" /// EndTypographicDoubleQuotes() /// ``` public struct BeginTypographicDoubleQuotes: MDocMacroProtocol { public static let kind = "Do" public var arguments: [MDocASTNode] /// Creates a new `BeginTypographicDoubleQuotes` macro. public init() { self.arguments = [] } } /// Close a scope opened by a ``BeginTypographicDoubleQuotes`` macro. public struct EndTypographicDoubleQuotes: MDocMacroProtocol { public static let kind = "Dc" public var arguments: [MDocASTNode] /// Creates a new `EndTypographicDoubleQuotes` macro. public init() { self.arguments = [] } } /// Open a scope enclosed by `"typewriter"` double-quotes. /// /// Closed by a ``EndTypewriterDoubleQuotes`` macro. /// /// __Example Usage__: /// ```swift /// BeginTypewriterDoubleQuotes() /// "Hello, Swift!" /// EndTypewriterDoubleQuotes() /// ``` public struct BeginTypewriterDoubleQuotes: MDocMacroProtocol { public static let kind = "Qo" public var arguments: [MDocASTNode] /// Creates a new `BeginTypewriterDoubleQuotes` macro. public init() { self.arguments = [] } } /// Close a scope opened by a ``BeginTypewriterDoubleQuotes`` macro. public struct EndTypewriterDoubleQuotes: MDocMacroProtocol { public static let kind = "Qc" public var arguments: [MDocASTNode] /// Creates a new `EndTypewriterDoubleQuotes` macro. public init() { self.arguments = [] } } /// Open a scope enclosed by `'single'` quotes. /// /// Closed by a ``EndSingleQuotes`` macro. /// /// __Example Usage__: /// ```swift /// BeginSingleQuotes() /// "Hello, Swift!" /// EndSingleQuotes() /// ``` public struct BeginSingleQuotes: MDocMacroProtocol { public static let kind = "So" public var arguments: [MDocASTNode] /// Creates a new `BeginSingleQuotes` macro. public init() { self.arguments = [] } } /// Close a scope opened by a ``BeginSingleQuotes`` macro. public struct EndSingleQuotes: MDocMacroProtocol { public static let kind = "Sc" public var arguments: [MDocASTNode] /// Creates a new `EndSingleQuotes` macro. public init() { self.arguments = [] } } /// Open a scope enclosed by `(parentheses)`. /// /// Closed by a ``EndParentheses`` macro. /// /// __Example Usage__: /// ```swift /// BeginParentheses() /// "Hello, Swift!" /// EndParentheses() /// ``` public struct BeginParentheses: MDocMacroProtocol { public static let kind = "Po" public var arguments: [MDocASTNode] /// Creates a new `BeginParentheses` macro. public init() { self.arguments = [] } } /// Close a scope opened by a ``BeginParentheses`` macro. public struct EndParentheses: MDocMacroProtocol { public static let kind = "Pc" public var arguments: [MDocASTNode] /// Creates a new `EndParentheses` macro. public init() { self.arguments = [] } } /// Open a scope enclosed by `[squareBrackets]`. /// /// Closed by a ``EndSquareBrackets`` macro. /// /// __Example Usage__: /// ```swift /// BeginSquareBrackets() /// "Hello, Swift!" /// EndSquareBrackets() /// ``` public struct BeginSquareBrackets: MDocMacroProtocol { public static let kind = "Bo" public var arguments: [MDocASTNode] /// Creates a new `BeginSquareBrackets` macro. public init() { self.arguments = [] } } /// Close a scope opened by a ``BeginSquareBrackets`` macro. public struct EndSquareBrackets: MDocMacroProtocol { public static let kind = "Bc" public var arguments: [MDocASTNode] /// Creates a new `EndSquareBrackets` macro. public init() { self.arguments = [] } } /// Open a scope enclosed by `{curlyBraces}`. /// /// Closed by a ``EndCurlyBraces`` macro. /// /// __Example Usage__: /// ```swift /// BeginCurlyBraces() /// "Hello, Swift!" /// EndCurlyBraces() /// ``` public struct BeginCurlyBraces: MDocMacroProtocol { public static let kind = "Bro" public var arguments: [MDocASTNode] /// Creates a new `BeginCurlyBraces` macro. public init() { self.arguments = [] } } /// Close a scope opened by a ``BeginCurlyBraces`` macro. public struct EndCurlyBraces: MDocMacroProtocol { public static let kind = "Brc" public var arguments: [MDocASTNode] /// Creates a new `EndCurlyBraces` macro. public init() { self.arguments = [] } } /// Open a scope enclosed by `<angleBrackets>`. /// /// Closed by a ``EndAngleBrackets`` macro. /// /// __Example Usage__: /// ```swift /// BeginAngleBrackets() /// "Hello, Swift!" /// EndAngleBrackets() /// ``` public struct BeginAngleBrackets: MDocMacroProtocol { public static let kind = "Ao" public var arguments: [MDocASTNode] /// Creates a new `BeginAngleBrackets` macro. public init() { self.arguments = [] } } /// Close a scope opened by a ``BeginAngleBrackets`` macro. public struct EndAngleBrackets: MDocMacroProtocol { public static let kind = "Ac" public var arguments: [MDocASTNode] /// Creates a new `EndAngleBrackets` macro. public init() { self.arguments = [] } } // TODO: GenericEnclosure // /// Enclose another element generically. // case genericEnclosure(MDocLowLevelASTNode) // MARK: - Text production /// Display a standard line about the exit code of specified utilities. /// /// This macro indicates the specified utilities exit 0 on success and other /// values on failure. ``ExitStandard``` should be only included in the /// "EXIT STATUS" section. /// /// ``ExitStandard`` should only be used in sections 1, 6, and 8. public struct ExitStandard: MDocMacroProtocol { public static let kind = "Ex" public var arguments: [MDocASTNode] /// Creates a new `ExitStandard` macro. /// /// - Parameters: /// - utilities: A list of utilities the exit standard applies to. If no /// utilities are specified the document's name set by ``DocumentName`` /// is used. public init(utilities: [String] = []) { self.arguments = ["-std"] + utilities } } // TODO: ReturnStandard // /// Insert a standard sentence regarding a function call's return value of 0 on success and -1 on error, with the errno libc global variable set on error. // /// // /// If function is not specified, the document's name set by ``DocumentName`` is used. Multiple function arguments are treated as separate functions. // public struct ReturnStandard: MDocMacroProtocol { // public static let kind = "Rv" // public var arguments: [MDocASTNode] // public init() { // self.arguments = [] // } // } // TODO: StandardsReference // /// Reference to a standards document (one argument). // public struct StandardsReference: MDocMacroProtocol { // public static let kind = "St" // public var arguments: [MDocASTNode] // public init() { // self.arguments = [] // } // } /// Display a formatted version of AT&T UNIX. /// /// __Example Usage__: /// ```swift /// AttUnix() /// AttUnix(version: "V.1") /// ``` public struct AttUnix: MDocMacroProtocol { public static let kind = "At" public var arguments: [MDocASTNode] /// Creates a new `AttUnix` macro. /// /// - Parameters: /// - version: The version of Att Unix to stylize. Omitting /// `version` will result in an unversioned OS being displayed. /// `version` should be one of the following values; /// - `v[1-7] | 32v` - A version of AT&T UNIX. /// - `III` - AT&T System III UNIX. /// - `V | V.[1-4]` - A version of AT&T System V UNIX. public init(version: String? = nil) { self.arguments = [] self.arguments.append(optional: version) } } /// Display a formatted variant and version of BSD. /// /// __Example Usage__: /// ```swift /// BSD() /// BSD(name: "Ghost") /// BSD(name: "Ghost", version: "21.04.27") /// ``` public struct BSD: MDocMacroProtocol { public static let kind = "Bx" public var arguments: [MDocASTNode] /// Creates a new `BSD` macro. /// /// - Note: The `version` parameter must not be specified without /// the `name` parameter. /// /// - Parameters: /// - name: The name of the BSD variant to stylize. /// - version: The version `name` to stylize. Omitting `version` /// will result in an unversioned OS being displayed. public init(name: String? = nil, version: String? = nil) { precondition(!(name == nil && version != nil)) self.arguments = [] self.arguments.append(optional: name) self.arguments.append(optional: version) } } /// Display a formatted version of BSD/OS. /// /// __Example Usage__: /// ```swift /// BSDOS() /// BSDOS(version: "5.1") /// ``` public struct BSDOS: MDocMacroProtocol { public static let kind = "Bsx" public var arguments: [MDocASTNode] /// Creates a new `BSDOS` macro. /// /// - Parameters: /// - version: The version of BSD/OS to stylize. Omitting /// `version` will result in an unversioned OS being displayed. public init(version: String? = nil) { self.arguments = [] self.arguments.append(optional: version) } } /// Display a formatted version of NetBSD. /// /// __Example Usage__: /// ```swift /// NetBSD() /// NetBSD(version: "9.2") /// ``` public struct NetBSD: MDocMacroProtocol { public static let kind = "Nx" public var arguments: [MDocASTNode] /// Creates a new `NetBSD` macro. /// /// - Parameters: /// - version: The version of NetBSD to stylize. Omitting /// `version` will result in an unversioned OS being displayed. public init(version: String? = nil) { self.arguments = [] self.arguments.append(optional: version) } } /// Display a formatted version of FreeBSD. /// /// __Example Usage__: /// ```swift /// FreeBSD() /// FreeBSD(version: "13.0") /// ``` public struct FreeBSD: MDocMacroProtocol { public static let kind = "Fx" public var arguments: [MDocASTNode] /// Creates a new `FreeBSD` macro. /// /// - Parameters: /// - version: The version of FreeBSD to stylize. Omitting /// `version` will result in an unversioned OS being displayed. public init(version: String? = nil) { self.arguments = [] self.arguments.append(optional: version) } } /// Display a formatted version of OpenBSD. /// /// __Example Usage__: /// ```swift /// OpenBSD() /// OpenBSD(version: "6.9") /// ``` public struct OpenBSD: MDocMacroProtocol { public static let kind = "Ox" public var arguments: [MDocASTNode] /// Creates a new `OpenBSD` macro. /// /// - Parameters: /// - version: The version of OpenBSD to stylize. Omitting /// `version` will result in an unversioned OS being displayed. public init(version: String? = nil) { self.arguments = [] self.arguments.append(optional: version) } } /// Display a formatted version of DragonFly. /// /// __Example Usage__: /// ```swift /// DragonFly() /// DragonFly(version: "6.0") /// ``` public struct DragonFly: MDocMacroProtocol { public static let kind = "Dx" public var arguments: [MDocASTNode] /// Creates a new `DragonFly` macro. /// /// - Parameters: /// - version: The version of DragonFly to stylize. Omitting /// `version` will result in an unversioned OS being displayed. public init(version: String? = nil) { self.arguments = [] self.arguments.append(optional: version) } } }
apache-2.0
40146771a84ce73db8962bdcbcd34cef
30.623841
158
0.617775
4.002011
false
false
false
false
letvargo/LVGSwiftAudioFileServices
Source/AudioFileError.swift
1
9216
// // AudioFileError.swift // AudioToolboxTrainer_01 // // Created by doof nugget on 1/5/16. // Copyright © 2016 letvargo. All rights reserved. // import Foundation import AudioToolbox import LVGUtilities /** An enum with cases that represent the `OSStatus` result codes defined by Audio File Services. Each case has a `code` property equivalent to the result code for the corresponding error defined by Audio File Services. Each case also has an associated value of type `String` that can be accessed using the value's `message` property. This is used to provide information about the context from which the error was thrown. For more information about the `OSStatus` codes defined by Audio File Services see the official [Apple Audio File Services documentation](https://developer.apple.com/library/mac/documentation/MusicAudio/Reference/AudioFileConvertRef/index.html#//apple_ref/doc/uid/TP40006072). */ public enum AudioFileError: CodedErrorType { /// The equivalent of `OSStatus` code `kAudioFileBadPropertySizeError`. case badPropertySize(message: String) /// The equivalent of `OSStatus` code `kAudioFileDoesNotAllow64BitDataSizeError`. case doesNotAllow64BitDataSize(message: String) /// The equivalent of `OSStatus` code `kAudioFileEndOfFileError`. case endOfFile(message: String) /// The equivalent of `OSStatus` code `kAudioFileFileNotFoundError`. case fileNotFound(message: String) /// The equivalent of `OSStatus` code `kAudioFileInvalidChunkError`. case invalidChunk(message: String) /// The equivalent of `OSStatus` code `kAudioFileInvalidFileError`. case invalidFile(message: String) /// The equivalent of `OSStatus` code `kAudioFileInvalidPacketOffsetError`. case invalidPacketOffset(message: String) /// The equivalent of `OSStatus` code `kAudioFileNotOpenError`. case notOpen(message: String) /// The equivalent of `OSStatus` code `kAudioFileNotOptimizedError`. case notOptimized(message: String) /// The equivalent of `OSStatus` code `kAudioFileOperationNotSupportedError`. case operationNotSupported(message: String) /// The equivalent of `OSStatus` code `kAudioFilePermissionsError`. case permissions(message: String) /// The equivalent of `OSStatus` code `kAudioFilePositionError`. case position(message: String) /// The equivalent of `OSStatus` code `kAudioFileUnspecifiedError`. case unspecified(message: String) /// The equivalent of `OSStatus` code `kAudioFileUnsupportedDataFormatError`. case unsupportedDataFormat(message: String) /// The equivalent of `OSStatus` code `kAudioFileUnsupportedFileTypeError`. case unsupportedFileType(message: String) /// The equivalent of `OSStatus` code `kAudioFileUnsupportedPropertyError`. case unsupportedProperty(message: String) /// Created when the `OSStatus` code is not defined by Audio File Services. case undefined(status: OSStatus, message: String) /// Initializes a `AudioFileError` using a result code /// defined by Audio File Services and a message that provides /// information about the context from which the error was thrown. public init(status: OSStatus, message: String) { switch status { case kAudioFileUnspecifiedError: self = .unspecified(message: message) case kAudioFileUnsupportedFileTypeError: self = .unsupportedFileType(message: message) case kAudioFileUnsupportedDataFormatError: self = .unsupportedDataFormat(message: message) case kAudioFileUnsupportedPropertyError: self = .unsupportedProperty(message: message) case kAudioFileBadPropertySizeError: self = .badPropertySize(message: message) case kAudioFilePermissionsError: self = .permissions(message: message) case kAudioFileNotOptimizedError: self = .notOptimized(message: message) case kAudioFileInvalidChunkError: self = .invalidChunk(message: message) case kAudioFileDoesNotAllow64BitDataSizeError: self = .doesNotAllow64BitDataSize(message: message) case kAudioFileInvalidPacketOffsetError: self = .invalidPacketOffset(message: message) case kAudioFileInvalidFileError: self = .invalidFile(message: message) case kAudioFileOperationNotSupportedError: self = .operationNotSupported(message: message) case kAudioFileNotOpenError: self = .notOpen(message: message) case kAudioFileEndOfFileError: self = .endOfFile(message: message) case kAudioFilePositionError: self = .position(message: message) case kAudioFileFileNotFoundError: self = .fileNotFound(message: message) default: self = .undefined(status: status, message: message) } } /// The `OSStatus` result code associated with the error. public var code: OSStatus { switch self { case .unspecified: return kAudioFileUnspecifiedError case .unsupportedFileType: return kAudioFileUnsupportedFileTypeError case .unsupportedDataFormat: return kAudioFileUnsupportedDataFormatError case .unsupportedProperty: return kAudioFileUnsupportedPropertyError case .badPropertySize: return kAudioFileBadPropertySizeError case .permissions: return kAudioFilePermissionsError case .notOptimized: return kAudioFileNotOptimizedError case .invalidChunk: return kAudioFileInvalidChunkError case .doesNotAllow64BitDataSize: return kAudioFileDoesNotAllow64BitDataSizeError case .invalidPacketOffset: return kAudioFileInvalidPacketOffsetError case .invalidFile: return kAudioFileInvalidFileError case .operationNotSupported: return kAudioFileOperationNotSupportedError case .notOpen: return kAudioFileNotOpenError case .endOfFile: return kAudioFileEndOfFileError case .position: return kAudioFilePositionError case .fileNotFound: return kAudioFileFileNotFoundError case .undefined(let (status, _)): return status } } /// Returns "Audio File Services Error" for all cases. public var domain: String { return "Audio File Services Error" } /// A message that provides information about the context from which the error was thrown. public var message: String { switch self { case .unspecified(let m): return m case .unsupportedFileType(let m): return m case .unsupportedDataFormat(let m): return m case .unsupportedProperty(let m): return m case .badPropertySize(let m): return m case .permissions(let m): return m case .notOptimized(let m): return m case .invalidChunk(let m): return m case .doesNotAllow64BitDataSize(let m): return m case .invalidPacketOffset(let m): return m case .invalidFile(let m): return m case .operationNotSupported(let m): return m case .notOpen(let m): return m case .endOfFile(let m): return m case .position(let m): return m case .fileNotFound(let m): return m case .undefined(let (_, m)): return m } } /// A short description of the error. public var shortDescription: String { switch self { case .unspecified: return "Unspecified error." case .unsupportedFileType: return "Unsupported file type." case .unsupportedDataFormat: return "Unsupported data format." case .unsupportedProperty: return "Unsupported property." case .badPropertySize: return "Bad property size." case .permissions: return "Invalid permissions." case .notOptimized: return "Not optimized." case .invalidChunk: return "Invalid chunk." case .doesNotAllow64BitDataSize: return "Does not allow 64-bit data size." case .invalidPacketOffset: return "Invalid packet offset." case .invalidFile: return "Invalid file." case .operationNotSupported: return "Operation not supported." case .notOpen: return "File not open." case .endOfFile: return "End of file." case .position: return "Invalid position." case .fileNotFound: return "File not found." case .undefined: return "This error is not defined by Audio File Services." } } }
mit
b5a48457dd283e6514c4d772d84994fb
49.911602
198
0.650353
5.156687
false
false
false
false
mohamede1945/quran-ios
BatchDownloader/Download.swift
2
1507
// // Download.swift // Quran // // Created by Mohamed Afifi on 2/14/17. // // Quran for iOS is a Quran reading application for iOS. // Copyright (C) 2017 Quran.com // // 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. // import Foundation public struct Download { public enum Status: Int { case downloading = 0 case completed = 1 // case failed = 2 // we shouldn't keep a failed download case pending = 3 } public let batchId: Int64 public let request: DownloadRequest public var status: Status public var taskId: Int? public init(taskId: Int? = nil, request: DownloadRequest, status: Status = .downloading, batchId: Int64) { self.taskId = taskId self.request = request self.status = status self.batchId = batchId } } public struct DownloadBatch { public let id: Int64 public let downloads: [Download] public init(id: Int64, downloads: [Download]) { self.id = id self.downloads = downloads } }
gpl-3.0
8ede5e866b27442a964e67d70ae420ca
27.433962
110
0.66357
4.072973
false
false
false
false
minikin/Algorithmics
Pods/PSOperations/PSOperations/LocationCapability-iOS.swift
1
3472
// // LocationCapability.swift // PSOperations // // Created by Dev Team on 10/4/15. // Copyright © 2015 Pluralsight. All rights reserved. // #if os(iOS) || os(watchOS) import Foundation import CoreLocation public enum Location: CapabilityType { public static let name = "Location" case WhenInUse case Always public func requestStatus(completion: CapabilityStatus -> Void) { guard CLLocationManager.locationServicesEnabled() else { completion(.NotAvailable) return } let actual = CLLocationManager.authorizationStatus() switch actual { case .NotDetermined: completion(.NotDetermined) case .Restricted: completion(.NotAvailable) case .Denied: completion(.Denied) case .AuthorizedAlways: completion(.Authorized) case .AuthorizedWhenInUse: if self == .WhenInUse { completion(.Authorized) } else { // the user wants .Always, but has .WhenInUse // return .NotDetermined so that we can prompt to upgrade the permission completion(.NotDetermined) } } } public func authorize(completion: CapabilityStatus -> Void) { Authorizer.authorize(self, completion: completion) } } private let Authorizer = LocationAuthorizer() private class LocationAuthorizer: NSObject, CLLocationManagerDelegate { private let manager = CLLocationManager() private var completion: (CapabilityStatus -> Void)? private var kind = Location.WhenInUse override init() { super.init() manager.delegate = self } func authorize(kind: Location, completion: CapabilityStatus -> Void) { guard self.completion == nil else { fatalError("Attempting to authorize location when a request is already in-flight") } self.completion = completion self.kind = kind let key: String switch kind { case .WhenInUse: key = "NSLocationWhenInUseUsageDescription" manager.requestWhenInUseAuthorization() case .Always: key = "NSLocationAlwaysUsageDescription" manager.requestAlwaysAuthorization() } // This is helpful when developing an app. assert(NSBundle.mainBundle().objectForInfoDictionaryKey(key) != nil, "Requesting location permission requires the \(key) key in your Info.plist") } @objc func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) { if let completion = self.completion where manager == self.manager && status != .NotDetermined { self.completion = nil switch status { case .AuthorizedAlways: completion(.Authorized) case .AuthorizedWhenInUse: completion(kind == .WhenInUse ? .Authorized : .Denied) case .Denied: completion(.Denied) case .Restricted: completion(.NotAvailable) case .NotDetermined: fatalError("Unreachable due to the if statement, but included to keep clang happy") } } } } #endif
mit
f8fab412df9c1d172bbd89b8cdd0775a
32.057143
153
0.59032
5.883051
false
false
false
false
YoungGary/Sina
Sina/Sina/Classes/Home首页/HomeTableViewCell.swift
1
5912
// // HomeTableViewCell.swift // Sina // // Created by YOUNG on 16/9/13. // Copyright © 2016年 Young. All rights reserved. // import UIKit import SDWebImage private let edgeMargin : CGFloat = 10 private let imageMargin : CGFloat = 10 class HomeTableViewCell: UITableViewCell { //MARK:contentLabel的宽度的constant @IBOutlet weak var contentLabelWidth: NSLayoutConstraint! @IBOutlet weak var collectionWidth: NSLayoutConstraint! @IBOutlet weak var collectionHeight: NSLayoutConstraint! @IBOutlet weak var collection2bottom: NSLayoutConstraint! @IBOutlet weak var retweed2content: NSLayoutConstraint! //MARK:cell中的控件 @IBOutlet weak var iconImage: UIImageView! @IBOutlet weak var screenName: UILabel! @IBOutlet weak var created_at: UILabel!//time @IBOutlet weak var verifiedImage: UIImageView! @IBOutlet weak var contentLabel: UILabel! @IBOutlet weak var source: UILabel!//来源 @IBOutlet weak var vipImage: UIImageView! @IBOutlet weak var picCollectionView: PictureCollectionView! @IBOutlet weak var retweed_label: UILabel! @IBOutlet weak var bgView: UIView! //MARK:set model var model : StatusViewModel?{ didSet{ guard let viewModel = model else{ return } // set icon image let iconUrl = NSURL(string: (viewModel.status?.user?.profile_image_url)!) let placeHolderImage = UIImage(named: "avatar_default_small") iconImage.sd_setImageWithURL(iconUrl, placeholderImage: placeHolderImage) //set screen name screenName.text = viewModel.status?.user?.screen_name // set created_at created_at.text = viewModel.createText //set 认证图片 verifiedImage.image = viewModel.verifiedImage //正文label 图文混排 //contentLabel.text = viewModel.status?.text contentLabel.attributedText = FindEmoticon.shareIntance.findAttrString(viewModel.status?.text, font: contentLabel.font) // set 来源 if let weiboSource = viewModel.sourceText { source.text = "来自" + weiboSource }else{ source.text = nil } //vip vipImage.image = viewModel.vipImage //会员显示橙色 screenName.textColor = viewModel.vipImage == nil ? UIColor.blackColor() : UIColor.orangeColor() //处理collection的height和width let collectionSize = calculateCollectionSizeWithImageCount(viewModel.picUrls.count) collectionWidth.constant = collectionSize.width collectionHeight.constant = collectionSize.height //传递collectionView的数据 picCollectionView.picUrls = viewModel.picUrls //转发weibo的正文 图文混排 if viewModel.status?.retweeted_status != nil { if let screenname = viewModel.status?.retweeted_status?.user?.screen_name, retweed_text = viewModel.status?.retweeted_status?.text { let attrStr = "@ \(screenname) :" + retweed_text; retweed_label.attributedText = FindEmoticon.shareIntance.findAttrString(attrStr, font: retweed_label.font) } //设置背景 bgView.hidden = false //设置constant retweed2content.constant = 15 }else{ retweed_label.text = nil bgView.hidden = true //设置constant retweed2content.constant = 0 } } } override func awakeFromNib() { super.awakeFromNib() //根据屏幕的宽来确定正文的宽度 contentLabelWidth.constant = UIScreen.mainScreen().bounds.width - 2 * edgeMargin } } //处理collectionVIEW的size extension HomeTableViewCell{ private func calculateCollectionSizeWithImageCount(count : Int) ->CGSize{ //计算image的宽高 let imageWidthHeight = (UIScreen.mainScreen().bounds.width - 2 * imageMargin - 2 * edgeMargin)/3 //取到collectionView 的flow layout let layout = picCollectionView.collectionViewLayout as! UICollectionViewFlowLayout //没有图 if count == 0 { //constant collection2bottom.constant = 0 return CGSizeZero } //constant collection2bottom.constant = 10 //单张图要返回图片的真实宽高 if count == 1{ let picUrlstr = model?.picUrls.first?.absoluteString let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(picUrlstr) //sdwebImage默认讲下载的图片压缩了 let imageSize = CGSize(width: image.size.width * 2, height: image.size.height * 2) //设置itemsize layout.itemSize = imageSize return imageSize } //其他count的itemsize layout.itemSize = CGSize(width: imageWidthHeight, height: imageWidthHeight) //4个图 if count == 4 { let collectionWidthHeight = 2 * imageWidthHeight + imageMargin return CGSize(width: collectionWidthHeight, height: collectionWidthHeight) } //其他 let rows = CGFloat((count - 1)/3 + 1) let viewWidth = UIScreen.mainScreen().bounds.width - 2 * edgeMargin let viewHeight : CGFloat = rows * imageWidthHeight + (rows - 1) * imageMargin return CGSize(width: viewWidth, height: viewHeight) } }
apache-2.0
d7a04c7d5eb00d644f20f6c18dc77b1f
30.703911
148
0.598943
5.140399
false
false
false
false
PureSwift/LittleCMS
Sources/LittleCMS/DateComponents.swift
1
3758
// // DateComponents.swift // SwiftFoundation // // Created by David Ask on 07/12/15. // Copyright © 2015 PureSwift. All rights reserved. // #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) import Darwin.C #elseif os(Linux) import Glibc #endif import struct Foundation.Date import typealias Foundation.TimeInterval // Use internally to avoid collisions internal struct DateComponents { public enum Component { case second case minute case hour case dayOfMonth case month case year case weekday case dayOfYear } public var second: Int32 = 0 public var minute: Int32 = 0 public var hour: Int32 = 0 public var dayOfMonth: Int32 = 1 public var month: Int32 = 1 public var year: Int32 = 0 public var weekday: Int32 public var dayOfYear: Int32 = 1 /// Intializes from a time interval interval between the current date and 1 January 1970, GMT. public init(timeIntervalSince1970 timeinterval: TimeInterval) { self.init(brokenDown: tm(UTCSecondsSince1970: timeval(timeInterval: timeinterval).tv_sec )) } public init() { weekday = 0 } /// Initializes from a `Date`. public init(date: Date) { self.init(timeIntervalSince1970: date.timeIntervalSince1970) } public var date: Date { return Date(timeIntervalSince1970: timeInterval) } /// Get the value for the specified component. public subscript(component: Component) -> Int32 { get { switch component { case .second: return second case .minute: return minute case .hour: return hour case .dayOfMonth: return dayOfMonth case .month: return month case .year: return year case .weekday: return weekday case .dayOfYear: return dayOfYear } } set { switch component { case .second: second = newValue break case .minute: minute = newValue break case .hour: hour = newValue break case .dayOfMonth: dayOfMonth = newValue break case .month: month = newValue break case .year: year = newValue break case .weekday: weekday = newValue break case .dayOfYear: dayOfYear = newValue break } } } public init(brokenDown: tm) { second = brokenDown.tm_sec minute = brokenDown.tm_min hour = brokenDown.tm_hour dayOfMonth = brokenDown.tm_mday month = brokenDown.tm_mon + 1 year = 1900 + brokenDown.tm_year weekday = brokenDown.tm_wday dayOfYear = brokenDown.tm_yday } public var brokenDown: tm { return tm.init( tm_sec: second, tm_min: minute, tm_hour: hour, tm_mday: dayOfMonth, tm_mon: month - 1, tm_year: year - 1900, tm_wday: weekday, tm_yday: dayOfYear, tm_isdst: -1, tm_gmtoff: 0, tm_zone: nil ) } private var timeInterval: TimeInterval { var time = brokenDown return TimeInterval(timegm(&time)) } }
mit
0921becef3c5be36a4152c4b6a694001
24.214765
99
0.507586
4.982759
false
false
false
false
OneBusAway/onebusaway-iphone
OBAKit/Helpers/OBAHandoff.swift
3
1993
// // OBAHandoff.swift // OBAKit // // Created by Alan Chu on 1/6/17. // Copyright © 2017 OneBusAway. All rights reserved. // import Foundation import Intents @objc public class OBAHandoff: NSObject { @objc static let activityTypeStop = "org.onebusaway.iphone.handoff.stop" @objc static let activityTypeTripURL = "org.onebusaway.iphone.handoff.tripurl" @objc static let stopIDKey = "stopID" @objc static let regionIDKey = "regionID" @objc public class func createUserActivity(name: String, stopID: String, regionID: Int) -> NSUserActivity { let activity = NSUserActivity(activityType: OBAHandoff.activityTypeStop) activity.title = name activity.isEligibleForHandoff = true // Per WWDC 2018 Session "Intro to Siri Shortcuts", this must be set to `true` // for `isEligibleForPrediction` to have any effect. Timecode: 8:30 activity.isEligibleForSearch = true if #available(iOS 12.0, *) { activity.isEligibleForPrediction = true activity.suggestedInvocationPhrase = NSLocalizedString("handoff.show_me_my_bus", comment: "Suggested invocation phrase for Siri Shortcut") activity.persistentIdentifier = "region_\(regionID)_stop_\(stopID)" } activity.requiredUserInfoKeys = [OBAHandoff.stopIDKey, OBAHandoff.regionIDKey] activity.userInfo = [OBAHandoff.stopIDKey: stopID, OBAHandoff.regionIDKey: regionID] let deepLinkRouter = DeepLinkRouter(baseURL: URL(string: OBADeepLinkServerAddress)!) activity.webpageURL = deepLinkRouter.deepLinkURL(stopID: stopID, regionID: regionID) return activity } @objc public class func createUserActivityForTrip(name: String, URL: URL) -> NSUserActivity { let activity = NSUserActivity(activityType: OBAHandoff.activityTypeTripURL) activity.title = name activity.isEligibleForHandoff = true activity.webpageURL = URL return activity } }
apache-2.0
454cab2cb6ff550e27319b55b16b4046
37.307692
150
0.703815
4.339869
false
false
false
false
february29/Learning
swift/Fch_Contact/Fch_Contact/AppClasses/Model/TimeTelBookModel.swift
1
1855
// // TimeTelBookModel.swift // Fch_Contact // // Created by bai on 2017/11/21. // Copyright © 2017年 北京仙指信息技术有限公司. All rights reserved. // import Foundation import HandyJSON class TimeTelBookModel: HandyJSON,NSCoding { required init() { } var days : Int! var telBook : TelBookModel! /** * Instantiate the instance using the passed dictionary values to set the properties values */ init(fromDictionary dictionary: [String:Any]){ days = dictionary["days"] as? Int if let telBookData = dictionary["telBook"] as? [String:Any]{ telBook = TelBookModel(fromDictionary: telBookData) } } /** * Returns all the available property values in the form of [String:Any] object where the key is the approperiate json key and the value is the value of the corresponding property */ func toDictionary() -> [String:Any] { var dictionary = [String:Any]() if days != nil{ dictionary["days"] = days } if telBook != nil{ dictionary["telBook"] = telBook.toDictionary() } return dictionary } /** * NSCoding required initializer. * Fills the data from the passed decoder */ @objc required init(coder aDecoder: NSCoder) { days = aDecoder.decodeObject(forKey: "days") as? Int telBook = aDecoder.decodeObject(forKey: "telBook") as? TelBookModel } /** * NSCoding required method. * Encodes mode properties into the decoder */ @objc func encode(with aCoder: NSCoder) { if days != nil{ aCoder.encode(days, forKey: "days") } if telBook != nil{ aCoder.encode(telBook, forKey: "telBook") } } }
mit
226d2bbdb6afb0deb2a7e88005d600f1
24.746479
183
0.585339
4.53598
false
false
false
false
JustasL/mapbox-navigation-ios
MapboxCoreNavigation/RouteController.swift
1
13885
import Foundation import CoreLocation import MapboxDirections /* RouteController helps user navigate along a route. */ @objc(MBRouteController) open class RouteController: NSObject { var lastUserDistanceToStartOfRoute = Double.infinity var lastTimeStampSpentMovingAwayFromStart = Date() /* Monitor users location along route. The variable can be provided by the developer so options on it can be set. */ public var locationManager = CLLocationManager() /* `routeProgress` is a class containing all progress information of user along the route, leg and step. */ public var routeProgress: RouteProgress /* If true, the user puck is snapped to closest location on the route. */ public var snapsUserLocationAnnotationToRoute = false public var simulatesLocationUpdates: Bool = false { didSet { locationManager.delegate = simulatesLocationUpdates ? nil : self } } /* Intializes a new `RouteController`. - parameter Route: A `Route` object representing the users route it will follow. */ public init(route: Route) { self.routeProgress = RouteProgress(route: route) super.init() locationManager.delegate = self if CLLocationManager.authorizationStatus() == .notDetermined { locationManager.requestWhenInUseAuthorization() } } deinit { suspendLocationUpdates() } /* Starts monitoring user location along route. Will continue monitoring until `suspend()` is called. */ public func resume() { locationManager.startUpdatingLocation() locationManager.startUpdatingHeading() } /* Stops monitoring users location along route. */ public func suspendLocationUpdates() { locationManager.stopUpdatingLocation() locationManager.stopUpdatingHeading() } } extension RouteController: CLLocationManagerDelegate { public func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { guard let location = locations.last else { return } let userSnapToStepDistanceFromManeuver = distance(along: routeProgress.currentLegProgress.currentStep.coordinates!, from: location.coordinate) let secondsToEndOfStep = userSnapToStepDistanceFromManeuver / location.speed guard routeProgress.currentLegProgress.alertUserLevel != .arrive else { // Don't advance nor check progress if the user has arrived at their destination suspendLocationUpdates() NotificationCenter.default.post(name: RouteControllerProgressDidChange, object: self, userInfo: [ RouteControllerProgressDidChangeNotificationProgressKey: routeProgress, RouteControllerProgressDidChangeNotificationLocationKey: location, RouteControllerProgressDidChangeNotificationSecondsRemainingOnStepKey: secondsToEndOfStep ]) return } // Notify observers if the step’s remaining distance has changed. let currentStepProgress = routeProgress.currentLegProgress.currentStepProgress let currentStep = currentStepProgress.step if let closestCoordinate = closestCoordinate(on: currentStep.coordinates!, to: location.coordinate) { let remainingDistance = distance(along: currentStep.coordinates!, from: closestCoordinate.coordinate) let distanceTraveled = currentStep.distance - remainingDistance if distanceTraveled != currentStepProgress.distanceTraveled { currentStepProgress.distanceTraveled = distanceTraveled NotificationCenter.default.post(name: RouteControllerProgressDidChange, object: self, userInfo: [ RouteControllerProgressDidChangeNotificationProgressKey: routeProgress, RouteControllerProgressDidChangeNotificationLocationKey: location, RouteControllerProgressDidChangeNotificationSecondsRemainingOnStepKey: secondsToEndOfStep ]) } } let step = routeProgress.currentLegProgress.currentStepProgress.step if step.maneuverType == .depart && !userIsOnRoute(location) { guard let userSnappedDistanceToClosestCoordinate = closestCoordinate(on: step.coordinates!, to: location.coordinate)?.distance else { return } // Give the user x seconds of moving away from the start of the route before rerouting guard Date().timeIntervalSince(lastTimeStampSpentMovingAwayFromStart) > MaxSecondsSpentTravelingAwayFromStartOfRoute else { lastUserDistanceToStartOfRoute = userSnappedDistanceToClosestCoordinate return } // Don't check `userIsOnRoute` if the user has not moved guard userSnappedDistanceToClosestCoordinate != lastUserDistanceToStartOfRoute else { lastUserDistanceToStartOfRoute = userSnappedDistanceToClosestCoordinate return } if userSnappedDistanceToClosestCoordinate > lastUserDistanceToStartOfRoute { lastTimeStampSpentMovingAwayFromStart = location.timestamp } lastUserDistanceToStartOfRoute = userSnappedDistanceToClosestCoordinate } guard userIsOnRoute(location) else { resetStartCounter() NotificationCenter.default.post(name: RouteControllerShouldReroute, object: self, userInfo: [ RouteControllerNotificationShouldRerouteKey: location ]) return } monitorStepProgress(location) } public func resetStartCounter() { lastTimeStampSpentMovingAwayFromStart = Date() lastUserDistanceToStartOfRoute = Double.infinity } public func userIsOnRoute(_ location: CLLocation) -> Bool { // Find future location of user let metersInFrontOfUser = location.speed * RouteControllerDeadReckoningTimeInterval let locationInfrontOfUser = location.coordinate.coordinate(at: metersInFrontOfUser, facing: location.course) let newLocation = CLLocation(latitude: locationInfrontOfUser.latitude, longitude: locationInfrontOfUser.longitude) let radius = min(RouteControllerMaximumDistanceBeforeRecalculating, location.horizontalAccuracy + RouteControllerUserLocationSnappingDistance) let isCloseToCurrentStep = newLocation.isWithin(radius, of: routeProgress.currentLegProgress.currentStep) // If the user is moving away from the maneuver location // and they are close to the next step // we can safely say they have completed the maneuver. // This is intended to be a fallback case when we do find // that the users course matches the exit bearing. if let upComingStep = routeProgress.currentLegProgress.upComingStep { let isCloseToUpComingStep = newLocation.isWithin(radius, of: upComingStep) if !isCloseToCurrentStep && isCloseToUpComingStep { // Increment the step routeProgress.currentLegProgress.stepIndex += 1 // and reset the alert level since we're on the next step let userSnapToStepDistanceFromManeuver = distance(along: routeProgress.currentLegProgress.currentStep.coordinates!, from: location.coordinate) let secondsToEndOfStep = userSnapToStepDistanceFromManeuver / location.speed incrementRouteProgressAlertLevel(secondsToEndOfStep <= RouteControllerMediumAlertInterval ? .medium : .low, location: location) return true } } return isCloseToCurrentStep } func incrementRouteProgressAlertLevel(_ newlyCalculatedAlertLevel: AlertLevel, location: CLLocation) { if routeProgress.currentLegProgress.alertUserLevel != newlyCalculatedAlertLevel { routeProgress.currentLegProgress.alertUserLevel = newlyCalculatedAlertLevel // Use fresh user location distance to end of step // since the step could of changed let userDistance = distance(along: routeProgress.currentLegProgress.currentStep.coordinates!, from: location.coordinate) NotificationCenter.default.post(name: RouteControllerAlertLevelDidChange, object: self, userInfo: [ RouteControllerAlertLevelDidChangeNotificationRouteProgressKey: routeProgress, RouteControllerAlertLevelDidChangeNotificationDistanceToEndOfManeuverKey: userDistance ]) } } func monitorStepProgress(_ location: CLLocation) { // Force an announcement when the user begins a route var alertLevel: AlertLevel = routeProgress.currentLegProgress.alertUserLevel == .none ? .depart : routeProgress.currentLegProgress.alertUserLevel let profileIdentifier = routeProgress.route.routeOptions.profileIdentifier let userSnapToStepDistanceFromManeuver = distance(along: routeProgress.currentLegProgress.currentStep.coordinates!, from: location.coordinate) let secondsToEndOfStep = userSnapToStepDistanceFromManeuver / location.speed var courseMatchesManeuverFinalHeading = false let minimumDistanceForHighAlert = RouteControllerMinimumDistanceForHighAlert(identifier: profileIdentifier) let minimumDistanceForMediumAlert = RouteControllerMinimumDistanceForMediumAlert(identifier: profileIdentifier) // Bearings need to normalized so when the `finalHeading` is 359 and the user heading is 1, // we count this as within the `RouteControllerMaximumAllowedDegreeOffsetForTurnCompletion` if let finalHeading = routeProgress.currentLegProgress.upComingStep?.finalHeading { let finalHeadingNormalized = wrap(finalHeading, min: 0, max: 360) let userHeadingNormalized = wrap(location.course, min: 0, max: 360) courseMatchesManeuverFinalHeading = differenceBetweenAngles(finalHeadingNormalized, userHeadingNormalized) <= RouteControllerMaximumAllowedDegreeOffsetForTurnCompletion } // When departing, `userSnapToStepDistanceFromManeuver` is most often less than `RouteControllerManeuverZoneRadius` // since the user will most often be at the beginning of the route, in the maneuver zone if alertLevel == .depart && userSnapToStepDistanceFromManeuver <= RouteControllerManeuverZoneRadius { // If the user is close to the maneuver location, // don't give a depature instruction. // Instead, give a `.high` alert. if secondsToEndOfStep <= RouteControllerHighAlertInterval { alertLevel = .high } } else if userSnapToStepDistanceFromManeuver <= RouteControllerManeuverZoneRadius { // Use the currentStep if there is not a next step // This occurs when arriving let step = routeProgress.currentLegProgress.upComingStep?.maneuverLocation ?? routeProgress.currentLegProgress.currentStep.maneuverLocation let userAbsoluteDistance = step - location.coordinate // userAbsoluteDistanceToManeuverLocation is set to nil by default // If it's set to nil, we know the user has never entered the maneuver radius if routeProgress.currentLegProgress.currentStepProgress.userDistanceToManeuverLocation == nil { routeProgress.currentLegProgress.currentStepProgress.userDistanceToManeuverLocation = RouteControllerManeuverZoneRadius } let lastKnownUserAbsoluteDistance = routeProgress.currentLegProgress.currentStepProgress.userDistanceToManeuverLocation // The objective here is to make sure the user is moving away from the maneuver location // This helps on maneuvers where the difference between the exit and enter heading are similar if userAbsoluteDistance <= lastKnownUserAbsoluteDistance! { routeProgress.currentLegProgress.currentStepProgress.userDistanceToManeuverLocation = userAbsoluteDistance } if routeProgress.currentLegProgress.upComingStep?.maneuverType == ManeuverType.arrive { alertLevel = .high } else if courseMatchesManeuverFinalHeading { routeProgress.currentLegProgress.stepIndex += 1 let userSnapToStepDistanceFromManeuver = distance(along: routeProgress.currentLegProgress.currentStep.coordinates!, from: location.coordinate) let secondsToEndOfStep = userSnapToStepDistanceFromManeuver / location.speed alertLevel = secondsToEndOfStep <= RouteControllerMediumAlertInterval ? .medium : .low } } else if secondsToEndOfStep <= RouteControllerHighAlertInterval && routeProgress.currentLegProgress.currentStep.distance > minimumDistanceForHighAlert { alertLevel = .high } else if secondsToEndOfStep <= RouteControllerMediumAlertInterval && // Don't alert if the route segment is shorter than X // However, if it's the beginning of the route // There needs to be an alert routeProgress.currentLegProgress.currentStep.distance > minimumDistanceForMediumAlert { alertLevel = .medium } incrementRouteProgressAlertLevel(alertLevel, location: location) } }
isc
8224aabd092d845e930299fef0c8e4a5
49.85348
180
0.692358
5.772557
false
false
false
false
matthewcheok/JSONCodable
JSONCodableTests/User.swift
1
1471
// // User.swift // JSONCodable // // Created by Matthew Cheok on 13/10/15. // // import JSONCodable struct User: Equatable { let id: Int var likes: Int? let name: String var email: String? var company: Company? var friends: [User] = [] var friendsLookup: [String: User]? } func ==(lhs: User, rhs: User) -> Bool { return lhs.id == rhs.id && lhs.name == rhs.name && lhs.email == rhs.email && lhs.company == rhs.company && lhs.friends == rhs.friends } extension User: JSONEncodable { func toJSON() throws -> Any { return try JSONEncoder.create { (encoder) -> Void in try encoder.encode(id, key: "id") try encoder.encode(name, key: "full_name") try encoder.encode(email, key: "email") try encoder.encode(company, key: "company") try encoder.encode(friends, key: "friends") try encoder.encode(friendsLookup, key: "friendsLookup") } } } extension User: JSONDecodable { init(object: JSONObject) throws { let decoder = JSONDecoder(object: object) id = try decoder.decode("id") likes = try decoder.decode("properties[0].likes") name = try decoder.decode("full_name") email = try decoder.decode("email") company = try decoder.decode("company") friends = try decoder.decode("friends") friendsLookup = try decoder.decode("friendsLookup") } }
mit
301a2d65fa991787519a839c80810c73
26.754717
67
0.592794
3.881266
false
false
false
false
icanzilb/EventBlankApp
EventBlank/EventBlank/ViewControllers/Speakers/SpeakersViewController.swift
2
6650
// // SpeakersViewController.swift // Twitter_test // // Created by Marin Todorov on 6/19/15. // Copyright (c) 2015 Underplot ltd. All rights reserved. // import UIKit import SQLite class SpeakersViewController: UIViewController { @IBOutlet weak var tableView: UITableView! var appData: Database { return DatabaseProvider.databases[appDataFileName]! } let speakers = SpeakersModel() var lastSelectedSpeaker: Row? var btnFavorites = UIButton() var event: Row { return (UIApplication.sharedApplication().delegate as! AppDelegate).event } let searchController = UISearchController(searchResultsController: nil) var initialized = false //MARK: - view controller required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) backgroundQueue(loadSpeakers) } func loadSpeakers() { speakers.refreshFavorites() speakers.load(searchTerm: searchController.searchBar.text, showOnlyFavorites: self.btnFavorites.selected) if self.tableView != nil { mainQueue({ if self.speakers.currentNumberOfItems == 0 { self.view.addSubview(MessageView(text: "You currently have no favorited speakers")) } else { MessageView.removeViewFrom(self.view) } }) } } override func viewDidLoad() { super.viewDidLoad() //notifications observeNotification(kFavoritesChangedNotification, selector: "didFavoritesChange:") observeNotification(kDidReplaceEventFileNotification, selector: "didChangeEventFile") } deinit { observeNotification(kFavoritesChangedNotification, selector: nil) observeNotification(kDidReplaceEventFileNotification, selector: nil) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if let _ = btnFavorites.superview where btnFavorites.hidden == true { btnFavorites.hidden = false } if !initialized { initialized = true if speakers.currentItems.count == 0 { backgroundQueue(loadSpeakers, completion: tableView.reloadData) } //set up the fav button btnFavorites.frame = CGRect(x: navigationController!.navigationBar.bounds.size.width - 40, y: 0, width: 40, height: 38) btnFavorites.setImage(UIImage(named: "like-empty")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate), forState: .Normal) btnFavorites.setImage(UIImage(named: "like-full")?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate), forState: UIControlState.Selected) btnFavorites.addTarget(self, action: Selector("actionToggleFavorites:"), forControlEvents: .TouchUpInside) btnFavorites.tintColor = UIColor.whiteColor() navigationController!.navigationBar.addSubview(btnFavorites) //add button background let gradient = CAGradientLayer() gradient.frame = btnFavorites.bounds gradient.colors = [UIColor(hexString: event[Event.mainColor]).colorWithAlphaComponent(0.1).CGColor, UIColor(hexString: event[Event.mainColor]).CGColor] gradient.locations = [0, 0.25] gradient.startPoint = CGPoint(x: 0.0, y: 0.5) gradient.endPoint = CGPoint(x: 1.0, y: 0.5) btnFavorites.layer.insertSublayer(gradient, below: btnFavorites.imageView!.layer) //search bar searchController.searchResultsUpdater = self searchController.delegate = self searchController.searchBar.delegate = self searchController.hidesNavigationBarDuringPresentation = false searchController.dimsBackgroundDuringPresentation = false searchController.searchBar.center = CGPoint( x: CGRectGetMidX(navigationController!.navigationBar.frame) + 4, y: 20) searchController.searchBar.hidden = true //search controller is the worst let iOSVersion = NSString(string: UIDevice.currentDevice().systemVersion).doubleValue if iOSVersion < 9.0 { //position the bar on iOS8 searchController.searchBar.center = CGPoint( x: CGRectGetMinX(navigationController!.navigationBar.frame) + 4, y: 20) } navigationController!.navigationBar.addSubview( searchController.searchBar ) } if count(searchController.searchBar.text) > 0 { actionSearch(self) } observeNotification(kTabItemSelectedNotification, selector: "didTapTabItem:") } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) //search bar didDismissSearchController(searchController) btnFavorites.hidden = true observeNotification(kTabItemSelectedNotification, selector: nil) } func didTapTabItem(notification: NSNotification) { if let index = notification.userInfo?["object"] as? Int where index == EventBlankTabIndex.Speakers.rawValue { mainQueue({ if self.speakers.currentNumberOfItems > 0 { self.tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 0), atScrollPosition: UITableViewScrollPosition.Top, animated: true) } }) } } override func willMoveToParentViewController(parent: UIViewController?) { super.willMoveToParentViewController(parent) //search bar if parent == nil { searchController.searchBar.removeFromSuperview() } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let speakerDetails = segue.destinationViewController as? SpeakerDetailsViewController { speakerDetails.speaker = lastSelectedSpeaker speakerDetails.speakers = speakers } searchController.searchBar.endEditing(true) } //notifications func didChangeEventFile() { backgroundQueue(loadSpeakers, completion: { self.navigationController?.popToRootViewControllerAnimated(true) self.tableView.reloadData() }) } }
mit
2b0f63b6a540ac03edc0c80a68006773
35.95
163
0.630827
5.688623
false
false
false
false
practicalswift/swift
test/SILGen/decls.swift
12
6541
// RUN: %target-swift-emit-silgen -Xllvm -sil-full-demangle -parse-as-library %s | %FileCheck %s // CHECK-LABEL: sil hidden [ossa] @$s5decls11void_returnyyF // CHECK: = tuple // CHECK: return func void_return() { } // CHECK-LABEL: sil hidden [ossa] @$s5decls14typealias_declyyF func typealias_decl() { typealias a = Int } // CHECK-LABEL: sil hidden [ossa] @$s5decls15simple_patternsyyF func simple_patterns() { _ = 4 var _ : Int } // CHECK-LABEL: sil hidden [ossa] @$s5decls13named_patternSiyF func named_pattern() -> Int { var local_var : Int = 4 var defaulted_var : Int // Defaults to zero initialization return local_var + defaulted_var } func MRV() -> (Int, Float, (), Double) {} // CHECK-LABEL: sil hidden [ossa] @$s5decls14tuple_patternsyyF func tuple_patterns() { var (a, b) : (Int, Float) // CHECK: [[ABOX:%[0-9]+]] = alloc_box ${ var Int } // CHECK: [[AADDR:%[0-9]+]] = mark_uninitialized [var] [[ABOX]] // CHECK: [[PBA:%.*]] = project_box [[AADDR]] // CHECK: [[BBOX:%[0-9]+]] = alloc_box ${ var Float } // CHECK: [[BADDR:%[0-9]+]] = mark_uninitialized [var] [[BBOX]] // CHECK: [[PBB:%.*]] = project_box [[BADDR]] var (c, d) = (a, b) // CHECK: [[CADDR:%[0-9]+]] = alloc_box ${ var Int } // CHECK: [[PBC:%.*]] = project_box [[CADDR]] // CHECK: [[DADDR:%[0-9]+]] = alloc_box ${ var Float } // CHECK: [[PBD:%.*]] = project_box [[DADDR]] // CHECK: [[READA:%.*]] = begin_access [read] [unknown] [[PBA]] : $*Int // CHECK: copy_addr [[READA]] to [initialization] [[PBC]] // CHECK: [[READB:%.*]] = begin_access [read] [unknown] [[PBB]] : $*Float // CHECK: copy_addr [[READB]] to [initialization] [[PBD]] // CHECK: [[EADDR:%[0-9]+]] = alloc_box ${ var Int } // CHECK: [[PBE:%.*]] = project_box [[EADDR]] // CHECK: [[FADDR:%[0-9]+]] = alloc_box ${ var Float } // CHECK: [[PBF:%.*]] = project_box [[FADDR]] // CHECK: [[GADDR:%[0-9]+]] = alloc_box ${ var () } // CHECK: [[HADDR:%[0-9]+]] = alloc_box ${ var Double } // CHECK: [[PBH:%.*]] = project_box [[HADDR]] // CHECK: [[EFGH:%[0-9]+]] = apply // CHECK: ([[E:%[0-9]+]], [[F:%[0-9]+]], [[H:%[0-9]+]]) = destructure_tuple // CHECK: store [[E]] to [trivial] [[PBE]] // CHECK: store [[F]] to [trivial] [[PBF]] // CHECK: store [[H]] to [trivial] [[PBH]] var (e,f,g,h) : (Int, Float, (), Double) = MRV() // CHECK: [[IADDR:%[0-9]+]] = alloc_box ${ var Int } // CHECK: [[PBI:%.*]] = project_box [[IADDR]] // CHECK-NOT: alloc_box ${ var Float } // CHECK: [[READA:%.*]] = begin_access [read] [unknown] [[PBA]] : $*Int // CHECK: copy_addr [[READA]] to [initialization] [[PBI]] // CHECK: [[READB:%.*]] = begin_access [read] [unknown] [[PBB]] : $*Float // CHECK: [[B:%[0-9]+]] = load [trivial] [[READB]] // CHECK-NOT: store [[B]] var (i,_) = (a, b) // CHECK: [[JADDR:%[0-9]+]] = alloc_box ${ var Int } // CHECK: [[PBJ:%.*]] = project_box [[JADDR]] // CHECK-NOT: alloc_box ${ var Float } // CHECK: [[KADDR:%[0-9]+]] = alloc_box ${ var () } // CHECK-NOT: alloc_box ${ var Double } // CHECK: [[J_K_:%[0-9]+]] = apply // CHECK: ([[J:%[0-9]+]], [[K:%[0-9]+]], {{%[0-9]+}}) = destructure_tuple // CHECK: store [[J]] to [trivial] [[PBJ]] var (j,_,k,_) : (Int, Float, (), Double) = MRV() } // CHECK-LABEL: sil hidden [ossa] @$s5decls16simple_arguments{{[_0-9a-zA-Z]*}}F // CHECK: bb0(%0 : $Int, %1 : $Int): // CHECK: [[X:%[0-9]+]] = alloc_box ${ var Int } // CHECK-NEXT: [[PBX:%.*]] = project_box [[X]] // CHECK-NEXT: store %0 to [trivial] [[PBX]] // CHECK-NEXT: [[Y:%[0-9]+]] = alloc_box ${ var Int } // CHECK-NEXT: [[PBY:%[0-9]+]] = project_box [[Y]] // CHECK-NEXT: store %1 to [trivial] [[PBY]] func simple_arguments(x: Int, y: Int) -> Int { var x = x var y = y return x+y } // CHECK-LABEL: sil hidden [ossa] @$s5decls14tuple_argument{{[_0-9a-zA-Z]*}}F // CHECK: bb0(%0 : $Int, %1 : $Float): // CHECK: [[UNIT:%[0-9]+]] = tuple () // CHECK: [[TUPLE:%[0-9]+]] = tuple (%0 : $Int, %1 : $Float, [[UNIT]] : $()) func tuple_argument(x: (Int, Float, ())) { } // CHECK-LABEL: sil hidden [ossa] @$s5decls14inout_argument{{[_0-9a-zA-Z]*}}F // CHECK: bb0(%0 : $*Int, %1 : $Int): // CHECK: [[X_LOCAL:%[0-9]+]] = alloc_box ${ var Int } // CHECK: [[PBX:%.*]] = project_box [[X_LOCAL]] func inout_argument(x: inout Int, y: Int) { var y = y x = y } var global = 42 // CHECK-LABEL: sil hidden [ossa] @$s5decls16load_from_global{{[_0-9a-zA-Z]*}}F func load_from_global() -> Int { return global // CHECK: [[ACCESSOR:%[0-9]+]] = function_ref @$s5decls6globalSivau // CHECK: [[PTR:%[0-9]+]] = apply [[ACCESSOR]]() // CHECK: [[ADDR:%[0-9]+]] = pointer_to_address [[PTR]] // CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[ADDR]] : $*Int // CHECK: [[VALUE:%[0-9]+]] = load [trivial] [[READ]] // CHECK: return [[VALUE]] } // CHECK-LABEL: sil hidden [ossa] @$s5decls15store_to_global{{[_0-9a-zA-Z]*}}F func store_to_global(x: Int) { var x = x global = x // CHECK: [[XADDR:%[0-9]+]] = alloc_box ${ var Int } // CHECK: [[PBX:%.*]] = project_box [[XADDR]] // CHECK: [[ACCESSOR:%[0-9]+]] = function_ref @$s5decls6globalSivau // CHECK: [[PTR:%[0-9]+]] = apply [[ACCESSOR]]() // CHECK: [[ADDR:%[0-9]+]] = pointer_to_address [[PTR]] // CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PBX]] : $*Int // CHECK: [[COPY:%.*]] = load [trivial] [[READ]] : $*Int // CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[ADDR]] : $*Int // CHECK: assign [[COPY]] to [[WRITE]] : $*Int // CHECK: end_access [[WRITE]] : $*Int // CHECK: return } struct S { var x:Int // CHECK-LABEL: sil hidden [ossa] @$s5decls1SVACycfC init() { x = 219 } init(a:Int, b:Int) { x = a + b } } // CHECK-LABEL: StructWithStaticVar.init // rdar://15821990 - Don't emit default value for static var in instance init() struct StructWithStaticVar { static var a : String = "" var b : String = "" init() { } } // Make sure unbound method references on class hierarchies are // properly represented in the AST class Base { func method1() -> Self { return self } func method2() -> Self { return self } } class Derived : Base { override func method2() -> Self { return self } } func generic<T>(arg: T) { } func unboundMethodReferences() { generic(arg: Derived.method1) generic(arg: Derived.method2) _ = type(of: Derived.method1) _ = type(of: Derived.method2) } // CHECK-LABEL: sil_vtable EscapeKeywordsInDottedPaths class EscapeKeywordsInDottedPaths { // CHECK: #EscapeKeywordsInDottedPaths.`switch`!getter.1 var `switch`: String = "" }
apache-2.0
feb8719e3f286998064c137d2e4cd89c
32.716495
96
0.55863
2.922699
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/Platform/Sources/PlatformUIKit/Components/CurrentBalanceTableViewCell/AccountCurrentBalanceCellPresenter.swift
1
6905
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Localization import PlatformKit import RxCocoa import RxSwift import ToolKit public final class AccountCurrentBalanceCellPresenter: CurrentBalanceCellPresenting { private typealias AccessibilityId = Accessibility.Identifier.AccountPicker.AccountCell public var iconImageViewContent: Driver<BadgeImageViewModel> { iconImageViewContentRelay.asDriver() } public var badgeImageViewModel: Driver<BadgeImageViewModel> { badgeRelay.asDriver() } /// Returns the description of the balance public var title: Driver<String> { titleRelay.asDriver() } /// Returns the description of the balance public var description: Driver<String> { descriptionRelay.asDriver() } public var pending: Driver<String> { .empty() } public var pendingLabelVisibility: Driver<Visibility> { .just(.hidden) } public var separatorVisibility: Driver<Visibility> { separatorVisibilityRelay.asDriver() } public let multiBadgeViewModel = MultiBadgeViewModel( layoutMargins: UIEdgeInsets( top: 8, left: 60, bottom: 16, right: 8 ), height: 24 ) public let viewAccessibilitySuffix: String public let titleAccessibilitySuffix: String public let descriptionAccessibilitySuffix: String public let pendingAccessibilitySuffix: String public let assetBalanceViewPresenter: AssetBalanceViewPresenter // MARK: - Private Properties public let badgeRelay = BehaviorRelay<BadgeImageViewModel>(value: .empty) private let separatorVisibilityRelay: BehaviorRelay<Visibility> public let iconImageViewContentRelay = BehaviorRelay<BadgeImageViewModel>(value: .empty) private let titleRelay = BehaviorRelay<String>(value: "") private let descriptionRelay = BehaviorRelay<String>(value: "") private let disposeBag = DisposeBag() private let badgeFactory = SingleAccountBadgeFactory() public let account: SingleAccount public init( account: SingleAccount, assetAction: AssetAction, interactor: AssetBalanceViewInteracting, separatorVisibility: Visibility = .visible ) { self.account = account separatorVisibilityRelay = BehaviorRelay<Visibility>(value: separatorVisibility) viewAccessibilitySuffix = "\(AccessibilityId.view)" titleAccessibilitySuffix = "\(AccessibilityId.titleLabel)" descriptionAccessibilitySuffix = "\(AccessibilityId.descriptionLabel)" pendingAccessibilitySuffix = "\(AccessibilityId.pendingLabel)" assetBalanceViewPresenter = AssetBalanceViewPresenter( alignment: .trailing, interactor: interactor, descriptors: .default( cryptoAccessiblitySuffix: "\(AccessibilityId.cryptoAmountLabel)", fiatAccessiblitySuffix: "\(AccessibilityId.fiatAmountLabel)" ) ) badgeFactory .badge(account: account, action: assetAction) .subscribe { [weak self] models in self?.multiBadgeViewModel.badgesRelay.accept(models) } .disposed(by: disposeBag) switch account.currencyType { case .fiat(let fiatCurrency): let badgeImageViewModel: BadgeImageViewModel = .primary( image: fiatCurrency.logoResource, contentColor: .white, backgroundColor: fiatCurrency.brandColor, accessibilityIdSuffix: "\(AccessibilityId.badgeImageView)" ) badgeImageViewModel.marginOffsetRelay.accept(0) badgeRelay.accept(badgeImageViewModel) case .crypto(let cryptoCurrency): let badgeImageViewModel: BadgeImageViewModel = .default( image: cryptoCurrency.logoResource, cornerRadius: .round, accessibilityIdSuffix: "\(AccessibilityId.badgeImageView)" ) badgeImageViewModel.marginOffsetRelay.accept(0) badgeRelay.accept(badgeImageViewModel) } let model: BadgeImageViewModel switch account { case is BankAccount: model = .template( image: .local(name: "ic-trading-account", bundle: .platformUIKit), templateColor: account.currencyType.brandUIColor, backgroundColor: .red, cornerRadius: .round, accessibilityIdSuffix: "" ) case is TradingAccount: model = .template( image: .local(name: "ic-trading-account", bundle: .platformUIKit), templateColor: account.currencyType.brandUIColor, backgroundColor: .white, cornerRadius: .round, accessibilityIdSuffix: "" ) case is CryptoInterestAccount: model = .template( image: .local(name: "ic-interest-account", bundle: .platformUIKit), templateColor: account.currencyType.brandUIColor, backgroundColor: .white, cornerRadius: .round, accessibilityIdSuffix: "" ) case is ExchangeAccount: model = .template( image: .local(name: "ic-exchange-account", bundle: .platformUIKit), templateColor: account.currencyType.brandUIColor, backgroundColor: .white, cornerRadius: .round, accessibilityIdSuffix: "" ) case is NonCustodialAccount: model = .template( image: .local(name: "ic-private-account", bundle: .platformUIKit), templateColor: account.currencyType.brandUIColor, backgroundColor: .white, cornerRadius: .round, accessibilityIdSuffix: "" ) case is FiatAccount: model = .template( image: .local(name: "ic-trading-account", bundle: .platformUIKit), templateColor: account.currencyType.brandUIColor, backgroundColor: .white, cornerRadius: .round, accessibilityIdSuffix: "" ) default: fatalError("Unsupported account type:\(String(describing: account))") } model.marginOffsetRelay.accept(1) iconImageViewContentRelay.accept(model) titleRelay.accept(account.label) descriptionRelay.accept(account.currencyType.displayCode) } } extension AccountCurrentBalanceCellPresenter: Equatable { public static func == (lhs: AccountCurrentBalanceCellPresenter, rhs: AccountCurrentBalanceCellPresenter) -> Bool { lhs.account.identifier == rhs.account.identifier } }
lgpl-3.0
72c6a320c69bafae60891fe1b7851997
36.726776
118
0.634705
5.663659
false
false
false
false
NordicSemiconductor/IOS-Pods-DFU-Library
Example/Pods/ZIPFoundation/Sources/ZIPFoundation/FileManager+ZIP.swift
1
16288
// // FileManager+ZIP.swift // ZIPFoundation // // Copyright © 2017-2020 Thomas Zoechling, https://www.peakstep.com and the ZIP Foundation project authors. // Released under the MIT License. // // See https://github.com/weichsel/ZIPFoundation/blob/master/LICENSE for license information. // import Foundation extension FileManager { typealias CentralDirectoryStructure = Entry.CentralDirectoryStructure /// Zips the file or direcory contents at the specified source URL to the destination URL. /// /// If the item at the source URL is a directory, the directory itself will be /// represented within the ZIP `Archive`. Calling this method with a directory URL /// `file:///path/directory/` will create an archive with a `directory/` entry at the root level. /// You can override this behavior by passing `false` for `shouldKeepParent`. In that case, the contents /// of the source directory will be placed at the root of the archive. /// - Parameters: /// - sourceURL: The file URL pointing to an existing file or directory. /// - destinationURL: The file URL that identifies the destination of the zip operation. /// - shouldKeepParent: Indicates that the directory name of a source item should be used as root element /// within the archive. Default is `true`. /// - compressionMethod: Indicates the `CompressionMethod` that should be applied. /// By default, `zipItem` will create uncompressed archives. /// - progress: A progress object that can be used to track or cancel the zip operation. /// - Throws: Throws an error if the source item does not exist or the destination URL is not writable. public func zipItem(at sourceURL: URL, to destinationURL: URL, shouldKeepParent: Bool = true, compressionMethod: CompressionMethod = .none, progress: Progress? = nil) throws { let fileManager = FileManager() guard fileManager.itemExists(at: sourceURL) else { throw CocoaError(.fileReadNoSuchFile, userInfo: [NSFilePathErrorKey: sourceURL.path]) } guard !fileManager.itemExists(at: destinationURL) else { throw CocoaError(.fileWriteFileExists, userInfo: [NSFilePathErrorKey: destinationURL.path]) } guard let archive = Archive(url: destinationURL, accessMode: .create) else { throw Archive.ArchiveError.unwritableArchive } let isDirectory = try FileManager.typeForItem(at: sourceURL) == .directory if isDirectory { let subPaths = try self.subpathsOfDirectory(atPath: sourceURL.path) var totalUnitCount = Int64(0) if let progress = progress { totalUnitCount = subPaths.reduce(Int64(0), { let itemURL = sourceURL.appendingPathComponent($1) let itemSize = archive.totalUnitCountForAddingItem(at: itemURL) return $0 + itemSize }) progress.totalUnitCount = totalUnitCount } // If the caller wants to keep the parent directory, we use the lastPathComponent of the source URL // as common base for all entries (similar to macOS' Archive Utility.app) let directoryPrefix = sourceURL.lastPathComponent for entryPath in subPaths { let finalEntryPath = shouldKeepParent ? directoryPrefix + "/" + entryPath : entryPath let finalBaseURL = shouldKeepParent ? sourceURL.deletingLastPathComponent() : sourceURL if let progress = progress { let itemURL = sourceURL.appendingPathComponent(entryPath) let entryProgress = archive.makeProgressForAddingItem(at: itemURL) progress.addChild(entryProgress, withPendingUnitCount: entryProgress.totalUnitCount) try archive.addEntry(with: finalEntryPath, relativeTo: finalBaseURL, compressionMethod: compressionMethod, progress: entryProgress) } else { try archive.addEntry(with: finalEntryPath, relativeTo: finalBaseURL, compressionMethod: compressionMethod) } } } else { progress?.totalUnitCount = archive.totalUnitCountForAddingItem(at: sourceURL) let baseURL = sourceURL.deletingLastPathComponent() try archive.addEntry(with: sourceURL.lastPathComponent, relativeTo: baseURL, compressionMethod: compressionMethod, progress: progress) } } /// Unzips the contents at the specified source URL to the destination URL. /// /// - Parameters: /// - sourceURL: The file URL pointing to an existing ZIP file. /// - destinationURL: The file URL that identifies the destination directory of the unzip operation. /// - skipCRC32: Optional flag to skip calculation of the CRC32 checksum to improve performance. /// - progress: A progress object that can be used to track or cancel the unzip operation. /// - preferredEncoding: Encoding for entry paths. Overrides the encoding specified in the archive. /// - Throws: Throws an error if the source item does not exist or the destination URL is not writable. public func unzipItem(at sourceURL: URL, to destinationURL: URL, skipCRC32: Bool = false, progress: Progress? = nil, preferredEncoding: String.Encoding? = nil) throws { let fileManager = FileManager() guard fileManager.itemExists(at: sourceURL) else { throw CocoaError(.fileReadNoSuchFile, userInfo: [NSFilePathErrorKey: sourceURL.path]) } guard let archive = Archive(url: sourceURL, accessMode: .read, preferredEncoding: preferredEncoding) else { throw Archive.ArchiveError.unreadableArchive } // Defer extraction of symlinks until all files & directories have been created. // This is necessary because we can't create links to files that haven't been created yet. let sortedEntries = archive.sorted { (left, right) -> Bool in switch (left.type, right.type) { case (.directory, .file): return true case (.directory, .symlink): return true case (.file, .symlink): return true default: return false } } var totalUnitCount = Int64(0) if let progress = progress { totalUnitCount = sortedEntries.reduce(0, { $0 + archive.totalUnitCountForReading($1) }) progress.totalUnitCount = totalUnitCount } for entry in sortedEntries { let path = preferredEncoding == nil ? entry.path : entry.path(using: preferredEncoding!) let destinationEntryURL = destinationURL.appendingPathComponent(path) guard destinationEntryURL.isContained(in: destinationURL) else { throw CocoaError(.fileReadInvalidFileName, userInfo: [NSFilePathErrorKey: destinationEntryURL.path]) } if let progress = progress { let entryProgress = archive.makeProgressForReading(entry) progress.addChild(entryProgress, withPendingUnitCount: entryProgress.totalUnitCount) _ = try archive.extract(entry, to: destinationEntryURL, skipCRC32: skipCRC32, progress: entryProgress) } else { _ = try archive.extract(entry, to: destinationEntryURL, skipCRC32: skipCRC32) } } } // MARK: - Helpers func itemExists(at url: URL) -> Bool { // Use `URL.checkResourceIsReachable()` instead of `FileManager.fileExists()` here // because we don't want implicit symlink resolution. // As per documentation, `FileManager.fileExists()` traverses symlinks and therefore a broken symlink // would throw a `.fileReadNoSuchFile` false positive error. // For ZIP files it may be intended to archive "broken" symlinks because they might be // resolvable again when extracting the archive to a different destination. return (try? url.checkResourceIsReachable()) == true } func createParentDirectoryStructure(for url: URL) throws { let parentDirectoryURL = url.deletingLastPathComponent() try self.createDirectory(at: parentDirectoryURL, withIntermediateDirectories: true, attributes: nil) } class func attributes(from entry: Entry) -> [FileAttributeKey: Any] { let centralDirectoryStructure = entry.centralDirectoryStructure let entryType = entry.type let fileTime = centralDirectoryStructure.lastModFileTime let fileDate = centralDirectoryStructure.lastModFileDate let defaultPermissions = entryType == .directory ? defaultDirectoryPermissions : defaultFilePermissions var attributes = [.posixPermissions: defaultPermissions] as [FileAttributeKey: Any] // Certain keys are not yet supported in swift-corelibs #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) attributes[.modificationDate] = Date(dateTime: (fileDate, fileTime)) #endif let versionMadeBy = centralDirectoryStructure.versionMadeBy guard let osType = Entry.OSType(rawValue: UInt(versionMadeBy >> 8)) else { return attributes } let externalFileAttributes = centralDirectoryStructure.externalFileAttributes let permissions = self.permissions(for: externalFileAttributes, osType: osType, entryType: entryType) attributes[.posixPermissions] = NSNumber(value: permissions) return attributes } class func permissions(for externalFileAttributes: UInt32, osType: Entry.OSType, entryType: Entry.EntryType) -> UInt16 { switch osType { case .unix, .osx: let permissions = mode_t(externalFileAttributes >> 16) & (~S_IFMT) let defaultPermissions = entryType == .directory ? defaultDirectoryPermissions : defaultFilePermissions return permissions == 0 ? defaultPermissions : UInt16(permissions) default: return entryType == .directory ? defaultDirectoryPermissions : defaultFilePermissions } } class func externalFileAttributesForEntry(of type: Entry.EntryType, permissions: UInt16) -> UInt32 { var typeInt: UInt16 switch type { case .file: typeInt = UInt16(S_IFREG) case .directory: typeInt = UInt16(S_IFDIR) case .symlink: typeInt = UInt16(S_IFLNK) } var externalFileAttributes = UInt32(typeInt|UInt16(permissions)) externalFileAttributes = (externalFileAttributes << 16) return externalFileAttributes } class func permissionsForItem(at URL: URL) throws -> UInt16 { let fileManager = FileManager() let entryFileSystemRepresentation = fileManager.fileSystemRepresentation(withPath: URL.path) var fileStat = stat() lstat(entryFileSystemRepresentation, &fileStat) let permissions = fileStat.st_mode return UInt16(permissions) } class func fileModificationDateTimeForItem(at url: URL) throws -> Date { let fileManager = FileManager() guard fileManager.itemExists(at: url) else { throw CocoaError(.fileReadNoSuchFile, userInfo: [NSFilePathErrorKey: url.path]) } let entryFileSystemRepresentation = fileManager.fileSystemRepresentation(withPath: url.path) var fileStat = stat() lstat(entryFileSystemRepresentation, &fileStat) #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) let modTimeSpec = fileStat.st_mtimespec #else let modTimeSpec = fileStat.st_mtim #endif let timeStamp = TimeInterval(modTimeSpec.tv_sec) + TimeInterval(modTimeSpec.tv_nsec)/1000000000.0 let modDate = Date(timeIntervalSince1970: timeStamp) return modDate } class func fileSizeForItem(at url: URL) throws -> UInt32 { let fileManager = FileManager() guard fileManager.itemExists(at: url) else { throw CocoaError(.fileReadNoSuchFile, userInfo: [NSFilePathErrorKey: url.path]) } let entryFileSystemRepresentation = fileManager.fileSystemRepresentation(withPath: url.path) var fileStat = stat() lstat(entryFileSystemRepresentation, &fileStat) return UInt32(fileStat.st_size) } class func typeForItem(at url: URL) throws -> Entry.EntryType { let fileManager = FileManager() guard url.isFileURL, fileManager.itemExists(at: url) else { throw CocoaError(.fileReadNoSuchFile, userInfo: [NSFilePathErrorKey: url.path]) } let entryFileSystemRepresentation = fileManager.fileSystemRepresentation(withPath: url.path) var fileStat = stat() lstat(entryFileSystemRepresentation, &fileStat) return Entry.EntryType(mode: fileStat.st_mode) } } extension Date { init(dateTime: (UInt16, UInt16)) { var msdosDateTime = Int(dateTime.0) msdosDateTime <<= 16 msdosDateTime |= Int(dateTime.1) var unixTime = tm() unixTime.tm_sec = Int32((msdosDateTime&31)*2) unixTime.tm_min = Int32((msdosDateTime>>5)&63) unixTime.tm_hour = Int32((Int(dateTime.1)>>11)&31) unixTime.tm_mday = Int32((msdosDateTime>>16)&31) unixTime.tm_mon = Int32((msdosDateTime>>21)&15) unixTime.tm_mon -= 1 // UNIX time struct month entries are zero based. unixTime.tm_year = Int32(1980+(msdosDateTime>>25)) unixTime.tm_year -= 1900 // UNIX time structs count in "years since 1900". let time = timegm(&unixTime) self = Date(timeIntervalSince1970: TimeInterval(time)) } var fileModificationDateTime: (UInt16, UInt16) { return (self.fileModificationDate, self.fileModificationTime) } var fileModificationDate: UInt16 { var time = time_t(self.timeIntervalSince1970) guard let unixTime = gmtime(&time) else { return 0 } var year = unixTime.pointee.tm_year + 1900 // UNIX time structs count in "years since 1900". // ZIP uses the MSDOS date format which has a valid range of 1980 - 2099. year = year >= 1980 ? year : 1980 year = year <= 2099 ? year : 2099 let month = unixTime.pointee.tm_mon + 1 // UNIX time struct month entries are zero based. let day = unixTime.pointee.tm_mday return (UInt16)(day + ((month) * 32) + ((year - 1980) * 512)) } var fileModificationTime: UInt16 { var time = time_t(self.timeIntervalSince1970) guard let unixTime = gmtime(&time) else { return 0 } let hour = unixTime.pointee.tm_hour let minute = unixTime.pointee.tm_min let second = unixTime.pointee.tm_sec return (UInt16)((second/2) + (minute * 32) + (hour * 2048)) } } #if swift(>=4.2) #else #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) #else // The swift-corelibs-foundation version of NSError.swift was missing a convenience method to create // error objects from error codes. (https://github.com/apple/swift-corelibs-foundation/pull/1420) // We have to provide an implementation for non-Darwin platforms using Swift versions < 4.2. public extension CocoaError { public static func error(_ code: CocoaError.Code, userInfo: [AnyHashable: Any]? = nil, url: URL? = nil) -> Error { var info: [String: Any] = userInfo as? [String: Any] ?? [:] if let url = url { info[NSURLErrorKey] = url } return NSError(domain: NSCocoaErrorDomain, code: code.rawValue, userInfo: info) } } #endif #endif public extension URL { func isContained(in parentDirectoryURL: URL) -> Bool { // Ensure this URL is contained in the passed in URL let parentDirectoryURL = URL(fileURLWithPath: parentDirectoryURL.path, isDirectory: true).standardized return self.standardized.absoluteString.hasPrefix(parentDirectoryURL.absoluteString) } }
bsd-3-clause
37b3e86efb1a85347e08f99a6f32bf1c
48.960123
118
0.656966
4.827208
false
false
false
false
Daij-Djan/DDUtils
swift/ddutils-ios/ui/CloudEmitterView [ios + demo]/CloudEmitterView.swift
1
4808
// // CloudEmitterView.swift // Created by D.Pich based on view created with Particle Playground on 8/23/16 // import UIKit class CloudEmitterView: UIView { override class var layerClass: AnyClass { get { return CAEmitterLayer.self } } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } override init(frame: CGRect) { super.init(frame: frame) setup() } func setup() { backgroundColor = UIColor.clear isUserInteractionEnabled = false let emitterLayer = layer as! CAEmitterLayer //setup layer emitterLayer.name = "emitterLayer" emitterLayer.emitterSize = CGSize(width: 1.00, height: 5000) emitterLayer.emitterDepth = 100.00 emitterLayer.emitterShape = kCAEmitterLayerRectangle emitterLayer.emitterMode = kCAEmitterLayerOutline emitterLayer.seed = 2491098502 // Create the emitter Cell // let emitterCell1 = createEmitterForClouds1() let emitterCell2 = createEmitterForClouds2() //assign the emitter to the layer // emitterLayer.emitterCells = [emitterCell1, emitterCell2] emitterLayer.emitterCells = [emitterCell2] } func createEmitterForClouds1() -> CAEmitterCell { // Create the emitter Cell let emitterCell = CAEmitterCell() emitterCell.name = "Clouds1" emitterCell.isEnabled = true let img = UIImage(named: "Clouds1") emitterCell.contents = img?.cgImage emitterCell.contentsRect = CGRect(x:0.00, y:0.00, width:3.00, height:1.00) emitterCell.magnificationFilter = kCAFilterLinear emitterCell.minificationFilter = kCAFilterLinear emitterCell.minificationFilterBias = 0.00 emitterCell.scale = 0.3 emitterCell.scaleRange = 0.2 emitterCell.scaleSpeed = 0.1 let color = UIColor(red:1, green:1, blue:1, alpha:1) emitterCell.color = color.cgColor emitterCell.redRange = 0.00 emitterCell.greenRange = 0.00 emitterCell.blueRange = 0.00 emitterCell.alphaRange = 1.00 emitterCell.redSpeed = 0.00 emitterCell.greenSpeed = 0.00 emitterCell.blueSpeed = 0.00 emitterCell.alphaSpeed = 0.00 emitterCell.lifetime = 500.00 emitterCell.lifetimeRange = 0.00 emitterCell.birthRate = 1 emitterCell.velocity = 5.00 emitterCell.velocityRange = 5.00 emitterCell.xAcceleration = 1.00 emitterCell.yAcceleration = 0.00 emitterCell.zAcceleration = 0.00 // these values are in radians, in the UI they are in degrees emitterCell.spin = 0.000 emitterCell.spinRange = 0.000 emitterCell.emissionLatitude = 0.017 emitterCell.emissionLongitude = 0.017 emitterCell.emissionRange = 1.745 return emitterCell } func createEmitterForClouds2() -> CAEmitterCell { // Create the emitter Cell let emitterCell = CAEmitterCell() emitterCell.name = "Clouds2" emitterCell.isEnabled = true let img = UIImage(named: "Clouds2.png") emitterCell.contents = img?.cgImage emitterCell.contentsRect = CGRect(x:0.00, y:0.00, width:3.00, height:1.00) emitterCell.magnificationFilter = kCAFilterLinear emitterCell.minificationFilter = kCAFilterLinear emitterCell.minificationFilterBias = 0.00 emitterCell.scale = 0.30 emitterCell.scaleRange = 0.20 emitterCell.scaleSpeed = 0.00 let color = UIColor(red:1, green:1, blue:1, alpha:1) emitterCell.color = color.cgColor emitterCell.redRange = 0.00 emitterCell.greenRange = 0.00 emitterCell.blueRange = 0.00 emitterCell.alphaRange = 1.00 emitterCell.redSpeed = 0.00 emitterCell.greenSpeed = 0.00 emitterCell.blueSpeed = 0.00 emitterCell.alphaSpeed = 0.00 emitterCell.lifetime = 500.00 emitterCell.lifetimeRange = 0.00 emitterCell.birthRate = 1 emitterCell.velocity = 5.00 emitterCell.velocityRange = 5.00 emitterCell.xAcceleration = 1.00 emitterCell.yAcceleration = 0.00 emitterCell.zAcceleration = 0.00 // these values are in radians, in the UI they are in degrees emitterCell.spin = 0.000 emitterCell.spinRange = 0.000 emitterCell.emissionLatitude = 0.017 emitterCell.emissionLongitude = 0.017 emitterCell.emissionRange = 1.745 return emitterCell } }
mit
beeb9c29e9e2dc6b9e25ef09e61fd793
31.931507
82
0.622088
4.832161
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/CryptoAssets/Sources/ERC20DataKit/Repository/ERC20ActivityRepository.swift
1
3357
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Combine import ERC20Kit import Errors import EthereumKit import MoneyKit import PlatformKit import ToolKit final class ERC20ActivityRepository: ERC20ActivityRepositoryAPI { private struct Key: Hashable { let erc20Asset: AssetModel let address: EthereumAddress } private let client: ERC20ActivityClientAPI private let cachedValue: CachedValueNew< Key, [ERC20HistoricalTransaction], NetworkError > init(client: ERC20ActivityClientAPI) { self.client = client let cache: AnyCache<Key, [ERC20HistoricalTransaction]> = InMemoryCache( configuration: .onLoginLogout(), refreshControl: PeriodicCacheRefreshControl(refreshInterval: 60) ).eraseToAnyCache() cachedValue = CachedValueNew( cache: cache, fetch: { [client] key in guard let contractAddress = key.erc20Asset.kind.erc20ContractAddress else { return .just([]) } guard let network = key.erc20Asset.evmNetwork else { return .just([]) } switch network { case .ethereum: return client .ethereumERC20Activity( from: key.address.publicKey, contractAddress: contractAddress ) .map(\.transfers) .map { transfers -> [ERC20HistoricalTransaction] in transfers.map { item in ERC20HistoricalTransaction( response: item, cryptoCurrency: key.erc20Asset.cryptoCurrency!, source: key.address ) } } .eraseToAnyPublisher() case .polygon: fatalError("Shouldn't use ERC20ActivityRepository for polygon.") } } ) } func transactions( erc20Asset: AssetModel, address: EthereumAddress ) -> AnyPublisher<[ERC20HistoricalTransaction], NetworkError> { cachedValue.get(key: Key(erc20Asset: erc20Asset, address: address)) } } extension ERC20HistoricalTransaction { init( response: ERC20TransfersResponse.Transfer, cryptoCurrency: CryptoCurrency, source: EthereumAddress ) { let createdAt: Date = Double(response.timestamp) .flatMap(Date.init(timeIntervalSince1970:)) ?? Date() let fromAddress = EthereumAddress(address: response.from)! let amount = CryptoValue.create( minor: response.value, currency: cryptoCurrency ) ?? .zero(currency: cryptoCurrency) self.init( fromAddress: fromAddress, toAddress: EthereumAddress(address: response.to)!, direction: fromAddress == source ? .credit : .debit, amount: amount, transactionHash: response.transactionHash, createdAt: createdAt, fee: nil, note: nil ) } }
lgpl-3.0
d1e024533d2f2d261a93ec042d43be2e
32.56
91
0.54559
5.726962
false
false
false
false
johndpope/tensorflow
tensorflow/swift/Sources/GoGraph.swift
1
12113
/* Copyright 2016 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. https://github.com/tensorflow/tensorflow/blob/master/tensorflow/go/graph.go */ import CTensorFlow import Foundation import IOSwift import func Darwin.C.stdlib.malloc import func Darwin.C.stdlib.posix_memalign import func Darwin.C.stdlib.free import func Darwin.C.string.memset import func Darwin.C.string.memcpy import func Darwin.malloc.malloc_size import gRPCTensorFlow typealias Byte = UInt8 // Graph represents a computation graph. Graphs may be shared between sessions. class Graph { var c:TF_Graph! // TODO work out how to use runtime.SetFinalizer(g, (*Graph).finalizer) on struct in swift deinit { finalizer(g:self) } } func newGraph()-> Graph{ let g = Graph() g.c = tf.NewGraph() return g } func finalizer(g :Graph) { tf.DeleteGraph(g.c) } // WriteTo writes out a serialized representation of g to w. // // Implements the io.WriterTo interface. extension Graph{ func writeTo( w:Writer)-> (Int, NSError?) { if let buffer = tf.NewBuffer(){ var status = newStatus() defer { tf.DeleteStatus(status.c) tf.DeleteBuffer(buffer) } tf.GraphToGraphDef(self.c, buffer, status.c) if let msg = status.errorMessage(){ return (0, NSError.newIoError(msg, code: 111)) } if buffer.pointee.length > (1 << 30) { // For very large graphs, the writes can be chunked. // Punt on that for now. return (0, NSError.newIoError("Graph is too large to write out, Graph.WriteTo needs to be updated", code: 111)) } // A []byte slice backed by C memory. // See: https://github.com/golang/go/wiki/cgo#turning-c-arrays-into-go-slices return w.write(data: buffer.pointee.data.load(as: NSData.self)) // TODO - Is this correct? }else{ return (0,NSError.newIoError("couldn't access buffer", code: 111)) } } } // Import imports the nodes and edges from a serialized representation of // another Graph into g. // // Names of imported nodes will be prefixed with prefix. extension Graph{ func Import(def:[Byte], prefix:String)-> NSError? { let opts = tf.NewImportGraphDefOptions() defer { tf.DeleteImportGraphDefOptions(opts) } tf.ImportGraphDefOptionsSetPrefix(opts, prefix); if let buffer = tf.NewBufferFromString(def,def.count ){ let status = newStatus() defer { tf.DeleteStatus(status.c) tf.DeleteBuffer(buffer) // free(def) TODO } tf.GraphImportGraphDef(self.c, buffer, opts, status.c) if let error = status.error() { return error } }else{ return NSError.newIoError("couldn't allocate buffer", code: 123) } return nil } } // Operation returns the Operation named name in the Graph, or nil if no such // operation is present. extension Graph{ func Operation(name:String)->GoOperation? { let cOperation = tf.GraphOperationByName(self.c, name) if let cOperation = cOperation { return GoOperation(cOperation, self) } return nil } } // OpSpec is the specification of an Operation to be added to a Graph // (using Graph.AddOperation). struct OpSpec { // Type of the operation (e.g., "Add", "MatMul"). var OpType:String // Name by which the added operation will be referred to in the Graph. // If omitted, defaults to Type. var Name:String = "Type" // Inputs to this operation, which in turn must be outputs // of other operations already added to the Graph. // // An operation may have multiple inputs with individual inputs being // either a single tensor produced by another operation or a list of // tensors produced by multiple operations. For example, the "Concat" // operation takes two inputs: (1) the dimension along which to // concatenate and (2) a list of tensors to concatenate. Thus, for // Concat, len(Input) must be 2, with the first element being an Output // and the second being an OutputList. //private outputList = var Input:[Any] // Map from attribute name to its value that will be attached to this // operation. var Attrs: Dictionary<String,Tensorflow_AttrValue.OneOf_Value> = [:] // Other possible fields: Device, ColocateWith, ControlInputs. } // AddOperation adds an operation to g. // https://github.com/tensorflow/tensorflow/blob/master/tensorflow/go/graph.go#L147 extension Graph{ func AddOperation ( args:OpSpec)-> (GoOperation?, NSError?) { print("TODO - flesh out implementation") let cOperationDesc = tf.NewOperation(self.c, args.OpType, args.Name) for input in args.Input { // switch input. = in.(type) { // case Output: // TF_AddInput(cOperationDesc, in.c()) // case OutputList: // size = len(in) // list = make([]TF_Output, size) // for i, v = range in { // list[i] = v.c() // } // if size > 0 { // TF_AddInputList(cOperationDesc, &list[0], C.int(size)) // } else { // TF_AddInputList(cOperationDesc, nil, 0) // } // } } var status = newStatus() for (name, value) in args.Attrs { if let err = setAttr(cOperationDesc, status.c, name, value) { // Memory leak here as the TF_OperationDescription // object will not be cleaned up. At the time of this // writing, this was next to impossible since it // required value to be a string tensor with // incorrectly encoded strings. Given this rarity, live // with the memory leak. If it becomes a real problem, // consider adding a TF_DeleteOperationDescription // function to the C API. return (nil, NSError.newIoError(" (memory will be leaked)", code: 444)) } } let op = GoOperation( tf.FinishOperation(cOperationDesc, status.c), self ) return (op, status.error()) } } // TODO - review Tensorflow_AttrValue in proto library to simplify this. // https://github.com/tensorflow/tensorflow/blob/master/tensorflow/go/graph.go#L195 func setAttr(_ cDesc:TF_OperationDescription?,_ status:TF_Status,_ name:String,_ value:Tensorflow_AttrValue.OneOf_Value) -> NSError? { // switch value.type { // case .dtBfloat16: // print("test") // // default: // print("default") // } /*switch value = value.(type) { case string: cstr = C.CString(value) TF_SetAttrString(cDesc, cAttrName, unsafe.Pointer(cstr), C.size_t(len(value))) C.free(unsafe.Pointer(cstr)) case []string: size = len(value) list = make([]unsafe.Pointer, size) lens = make([]C.size_t, size) for i, s = range value { list[i] = unsafe.Pointer(C.CString(s)) lens[i] = C.size_t(len(s)) } if size > 0 { TF_SetAttrStringList(cdesc, cAttrName, &list[0], &lens[0], C.int(size)) } else { TF_SetAttrStringList(cdesc, cAttrName, nil, nil, 0) } for _, s = range list { C.free(s) } case int64: TF_SetAttrInt(cdesc, cAttrName, C.int64_t(value)) case []int64: size = len(value) list = make([]C.int64_t, size) for i, v = range value { list[i] = C.int64_t(v) } if size > 0 { TF_SetAttrIntList(cdesc, cAttrName, &list[0], C.int(size)) } else { TF_SetAttrIntList(cdesc, cAttrName, nil, 0) } case float32: TF_SetAttrFloat(cdesc, cAttrName, C.float(value)) case []float32: size = len(value) list = make([]C.float, size) for i, v = range value { list[i] = C.float(v) } if size > 0 { TF_SetAttrFloatList(cdesc, cAttrName, &list[0], C.int(size)) } else { TF_SetAttrFloatList(cdesc, cAttrName, nil, 0) } case bool: v = C.uchar(0) if value { v = 1 } TF_SetAttrBool(cdesc, cAttrName, v) case []bool: size = len(value) list = make([]C.uchar, size) for i, v = range value { if v { list[i] = 1 } } if size > 0 { TF_SetAttrBoolList(cdesc, cAttrName, &list[0], C.int(size)) } else { TF_SetAttrBoolList(cdesc, cAttrName, nil, 0) } case DataType: TF_SetAttrType(cdesc, cAttrName, TF_DataType(value)) case []DataType: var list *TF_DataType if len(value) > 0 { list = (*TF_DataType)(&value[0]) } TF_SetAttrTypeList(cdesc, cAttrName, list, C.int(len(value))) case *Tensor: TF_SetAttrTensor(cdesc, cAttrName, value.c, status.c) if let err = status.error() { return NSError.newIoError("bad value for attribute %q: %v", name, err) } case []*Tensor: size = len(value) list = make([]*TF_Tensor, size) for i, v = range value { list[i] = v.c } var plist **TF_Tensor if size > 0 { plist = &list[0] } TF_SetAttrTensorList(cdesc, cAttrName, plist, C.int(size), status.c) if let err = status.error() { return NSError.newIoError("bad value for attribute %q: %v", name, err) } case Shape: ndims, dims = cshape(value) var dimsp *C.int64_t if ndims > 0 { dimsp = &dims[0] } TF_SetAttrShape(cdesc, cAttrName, dimsp, ndims) case []Shape: ndims = make([]C.int, len(value)) dims = make([][]C.int64_t, len(value)) dimsp = make([]*C.int64_t, len(value)) for i, s = range value { ndims[i], dims[i] = cshape(s) if ndims[i] > 0 { dimsp[i] = &dims[i][0] } } if len(value) > 0 { TF_SetAttrShapeList(cdesc, cAttrName, &dimsp[0], &ndims[0], C.int(len(value))) } else { TF_SetAttrShapeList(cdesc, cAttrName, nil, nil, 0) } default: return NSError.newIoError("attribute %q has a type (%T) which is not valid for operation attributes", name, value) }*/ return nil } // TODO - let's use Tensorflow_AttrValue.shape value from attr_value.pb.swift instead of this logic. /*func cshape(s:Shape)-> (CInt, [Int64]?) { let ndims = s.NumDimensions() if ndims < 0 { return (-1, nil) } var dims:[Int64] = [] for (index) in s.dims { dims[index] = Int64(s) } return (ndims, dims) }*/
apache-2.0
4bbf782f1094b166f668e29befb409cd
31.561828
135
0.555684
3.892352
false
false
false
false
jensmeder/DarkLightning
Examples/Messenger/OSX/Sources/RootView.swift
1
4532
// // RootView.swift // OSX // // Created by Jens Meder on 16.05.17. // // import Cocoa class RootView: NSView, NSTextFieldDelegate { private let scrollView: NSScrollView private let borderView: NSView private let textField: NSTextField private let textView: NSTextView private let delegate: RootViewDelegate convenience init(frame: NSRect, delegate: RootViewDelegate) { self.init(frame: frame, scrollView: NSScrollView(), borderView: NSView(), textField: NSTextField(), textView: NSTextView(), delegate: delegate) } required init(frame: NSRect, scrollView: NSScrollView, borderView: NSView, textField: NSTextField, textView: NSTextView, delegate: RootViewDelegate) { self.scrollView = scrollView self.borderView = borderView self.textField = textField self.textView = textView self.delegate = delegate super.init(frame: frame) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setup() { let viewLayer = CALayer() viewLayer.backgroundColor = CGColor(gray: 1.0, alpha: 1.0) self.wantsLayer = true self.layer = viewLayer self.addSubviews() } func appendMessage(message: String) { textView.textStorage?.append(NSAttributedString(string: message)) textView.textStorage?.append(NSAttributedString(string: "\r")) textView.scrollToEndOfDocument(nil) } private func addSubviews() { self.addSubview(textField) self.addSubview(scrollView) self.addSubview(borderView) self.setupScrollView() self.setupBorderView() self.setupTextView() self.setupTextField() self.setupConstraints() } private func setupTextField() { textField.translatesAutoresizingMaskIntoConstraints = false textField.focusRingType = .none textField.isBezeled = false textField.font = NSFont.systemFont(ofSize: 14.0) textField.delegate = self textField.setContentHuggingPriority(NSLayoutPriorityDefaultHigh, for:.vertical) textField.placeholderString = "Type a message here and hit Enter to send" } private func setupScrollView() { scrollView.translatesAutoresizingMaskIntoConstraints = false scrollView.hasVerticalScroller = true scrollView.setContentCompressionResistancePriority(NSLayoutPriorityDefaultHigh, for: .horizontal) scrollView.contentView.autoresizingMask = .viewHeightSizable scrollView.documentView = textView; } private func setupBorderView() { borderView.translatesAutoresizingMaskIntoConstraints = false let viewLayer = CALayer() viewLayer.backgroundColor = CGColor(red: 0.8, green: 0.8, blue: 0.8, alpha: 1.0) borderView.wantsLayer = true borderView.layer = viewLayer } private func setupTextView() { textView.isEditable = false textView.isVerticallyResizable = true textView.isHorizontallyResizable = true textView.textContainerInset = NSSize(width: 20, height: 20) textView.font = NSFont.systemFont(ofSize: 14.0) } private func setupConstraints() { textField.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 20).isActive = true textField.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -20).isActive = true textField.topAnchor.constraint(equalTo: borderView.bottomAnchor, constant: 20).isActive = true textField.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -20).isActive = true scrollView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true scrollView.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true scrollView.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true borderView.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 20).isActive = true borderView.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -20).isActive = true borderView.heightAnchor.constraint(equalToConstant: 1).isActive = true borderView.topAnchor.constraint(equalTo: scrollView.bottomAnchor).isActive = true } // MARK: NSTextFieldDelegate override func controlTextDidEndEditing(_ obj: Notification) { delegate.sendMessage(message: textField.stringValue) textField.stringValue = "" } }
mit
11b554b4d12267442191519cefb27839
38.408696
154
0.692851
5.221198
false
false
false
false
skyylex/Algorithmus
Source/PrefixTree.swift
2
2954
class Node { let value: Character? var children = Array<Node>() let level: Int var root = false var isLeaf: Bool { return children.count == 0 } init(isRoot: Bool, value: Character? = nil, level: Int = 0) { self.root = isRoot self.value = value self.level = level } } public class PrefixTree { public init() { } public func allSequences() -> [[Character]] { let sequences = search([]) return sequences } public func insertSequence(newSequence:[Character]) { insertSequence(newSequence, currentNode: root) } public func search(symbols: [Character]) -> [[Character]] { return search(symbols, currentSequence:[], currentNode:root) } private let root = Node(isRoot: true) private func search(symbols: [Character], currentSequence: Array<Character>, currentNode: Node) -> [[Character]] { var canMoveFurther = false var extendedSequence = Array<Character>() if currentNode.root == false { if let currentValue = currentNode.value { if symbols.count < currentNode.level || currentValue == symbols[currentNode.level - 1] { extendedSequence = currentSequence + [currentValue] canMoveFurther = true } } } else { canMoveFurther = true } if canMoveFurther { if currentNode.isLeaf { return [extendedSequence] } else { let foundSequences = currentNode.children.map { search(symbols, currentSequence: extendedSequence, currentNode:$0) } return foundSequences.reduce([[Character]]()) { $0 + $1} } } return [[Character]]() } private func insertSequence(sequence: Array<Character>, currentNode:Node, level: Int = 0) { if let currentValueToInsert = sequence.first { let existingNodes = currentNode.children.filter { $0.value == currentValueToInsert } if let firstExistingNode = existingNodes.first { let subSequence = sequence[1...(sequence.count - 1)] self.insertSequence(Array(subSequence), currentNode: firstExistingNode, level: level + 1) } else { directInsert(sequence, parentNode:currentNode, currentLevel:level + 1) } } } private func directInsert(sequence: Array<Character>, parentNode: Node, currentLevel: Int) { if let first = sequence.first { let node = Node(isRoot:false, value:first, level:currentLevel) parentNode.children.append(node) if sequence.count >= 2 { let otherSequencePart = sequence[1...(sequence.count - 1)] directInsert(Array(otherSequencePart), parentNode:node, currentLevel:currentLevel + 1) } } } }
mit
b2fda14d4099601c0f03b8bd25874eb9
32.954023
132
0.585308
4.842623
false
false
false
false
LeeCenY/iRent
Sources/iRent/Handlers/APNs.swift
1
2005
// // APNs.swift // iRent // // Created by nil on 2018/7/14. // import Foundation import PerfectLib import PerfectHTTP import PerfectCRUD import PerfectNotifications public class APNs: BaseHandler { static func add() -> RequestHandler { return { request, response in do { let userReq = try request.decode(User.self) guard !userReq.deviceid.isEmpty else { resError(request, response, error: "deviceid 请求参数不正确") return } guard !userReq.token.isEmpty else { resError(request, response, error: "token 请求参数不正确") return } let userDB = db().table(User.self) let isDeviceid = userDB.where(\User.deviceid == userReq.deviceid) if try isDeviceid.count() == 0 { do { try userDB .insert(userReq) } catch { resError(request, response, error: "添加失败") } try response.setBody(json: ["success": true, "status": 200, "data": "添加成功"]) response.completed() return } do { try userDB .where(\User.deviceid == userReq.deviceid) .update(userReq, setKeys: \.deviceid, \.token) } catch { resError(request, response, error: "添加失败") } try response.setBody(json: ["success": true, "status": 200, "data": "添加成功"]) response.completed() }catch { resError(request, response, error: "请求参数类型不对") } } } }
mit
69eaf2a4072533b4308e65bc0df4844d
29.140625
96
0.437532
4.958869
false
false
false
false
vvit/Koloda
Pod/Classes/KolodaView/KolodaViewAnimatior.swift
1
4790
// // KolodaViewAnimatior.swift // Koloda // // Created by Eugene Andreyev on 3/30/16. // // import Foundation import UIKit import pop open class KolodaViewAnimator { public typealias AnimationCompletionBlock = ((Bool) -> Void)? private weak var koloda: KolodaView? public init(koloda: KolodaView) { self.koloda = koloda } open func animateAppearance(_ duration: TimeInterval, completion: AnimationCompletionBlock = nil) { let kolodaAppearScaleAnimation = POPBasicAnimation(propertyNamed: kPOPLayerScaleXY) kolodaAppearScaleAnimation?.beginTime = CACurrentMediaTime() + cardSwipeActionAnimationDuration kolodaAppearScaleAnimation?.duration = duration kolodaAppearScaleAnimation?.fromValue = NSValue(cgPoint: CGPoint(x: 0.1, y: 0.1)) kolodaAppearScaleAnimation?.toValue = NSValue(cgPoint: CGPoint(x: 1.0, y: 1.0)) kolodaAppearScaleAnimation?.completionBlock = { (_, finished) in completion?(finished) } let kolodaAppearAlphaAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha) kolodaAppearAlphaAnimation?.beginTime = CACurrentMediaTime() + cardSwipeActionAnimationDuration kolodaAppearAlphaAnimation?.fromValue = NSNumber(value: 0.0) kolodaAppearAlphaAnimation?.toValue = NSNumber(value: 1.0) kolodaAppearAlphaAnimation?.duration = duration koloda?.pop_add(kolodaAppearAlphaAnimation, forKey: "kolodaAppearScaleAnimation") koloda?.layer.pop_add(kolodaAppearScaleAnimation, forKey: "kolodaAppearAlphaAnimation") } open func applyReverseAnimation(_ card: DraggableCardView, completion: AnimationCompletionBlock = nil) { let firstCardAppearAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha) firstCardAppearAnimation?.toValue = NSNumber(value: 1.0) firstCardAppearAnimation?.fromValue = NSNumber(value: 0.0) firstCardAppearAnimation?.duration = 1.0 firstCardAppearAnimation?.completionBlock = { _, finished in completion?(finished) card.alpha = 1.0 } card.pop_add(firstCardAppearAnimation, forKey: "reverseCardAlphaAnimation") } open func applyScaleAnimation(_ card: DraggableCardView, scale: CGSize, frame: CGRect, duration: TimeInterval, completion: AnimationCompletionBlock = nil) { let scaleAnimation = POPBasicAnimation(propertyNamed: kPOPLayerScaleXY) scaleAnimation?.duration = duration scaleAnimation?.toValue = NSValue(cgSize: scale) card.layer.pop_add(scaleAnimation, forKey: "scaleAnimation") let frameAnimation = POPBasicAnimation(propertyNamed: kPOPViewFrame) frameAnimation?.duration = duration frameAnimation?.toValue = NSValue(cgRect: frame) if let completion = completion { frameAnimation?.completionBlock = { _, finished in completion(finished) } } card.pop_add(frameAnimation, forKey: "frameAnimation") } open func applyAlphaAnimation(_ card: DraggableCardView, alpha: CGFloat, duration: TimeInterval = 0.2, completion: AnimationCompletionBlock = nil) { let alphaAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha) alphaAnimation?.toValue = alpha alphaAnimation?.duration = duration alphaAnimation?.completionBlock = { _, finished in completion?(finished) } card.pop_add(alphaAnimation, forKey: "alpha") } open func applyInsertionAnimation(_ cards: [DraggableCardView], completion: AnimationCompletionBlock = nil) { cards.forEach { $0.alpha = 0.0 } UIView.animate( withDuration: 0.2, animations: { cards.forEach { $0.alpha = 1.0 } }, completion: { finished in completion?(finished) } ) } open func applyRemovalAnimation(_ cards: [DraggableCardView], completion: AnimationCompletionBlock = nil) { UIView.animate( withDuration: 0.05, animations: { cards.forEach { $0.alpha = 0.0 } }, completion: { finished in completion?(finished) } ) } internal func resetBackgroundCardsWithCompletion(_ completion: AnimationCompletionBlock = nil) { UIView.animate( withDuration: 0.2, delay: 0.0, options: .curveLinear, animations: { self.koloda?.moveOtherCardsWithPercentage(0) }, completion: { finished in completion?(finished) }) } }
mit
ceeb49f8d1d464a28a827d4ce5738089
37.629032
160
0.644676
5.595794
false
false
false
false
chrisjmendez/swift-exercises
Walkthroughs/MyPresentation/Carthage/Checkouts/Presentation/Pod/Tests/Specs/Extensions/CGPointExtensionSpec.swift
8
698
import Quick import Nimble import Presentation class CGPointExtensionSpec: QuickSpec { override func spec() { describe("CGPointExtension") { var point: CGPoint! let frame = CGRect(x: 0.0, y: 0.0, width: 100.0, height: 80.0) beforeEach { point = CGPoint(x: 100.0, y: 80.0) } describe("#positionInFrame") { it ("returns correct position") { var left = point.x / CGRectGetWidth(frame) var top = point.y / CGRectGetHeight(frame) let position = point.positionInFrame(frame) expect(Double(position.left)) ≈ Double(left) expect(Double(position.top)) ≈ Double(top) } } } } }
mit
35ccb081fd4b8ee4ed11f0b8c6b66b88
23.785714
68
0.59366
3.920904
false
false
false
false
chrisjmendez/swift-exercises
Menus/DualPanel/DualPanel/LeftSideViewController.swift
1
4794
// // LeftSideViewController.swift // DualPanel // // Created by Tommy Trojan on 12/19/15. // Copyright © 2015 Chris Mendez. All rights reserved. // // // !!! Don't forget to create outlets for "dataSource" and "delegate" http://imgur.com/a/lVJ0u import UIKit class LeftSideViewController: UIViewController { var menuItems = [ "Main Page", "About Page", "Log Out Page" ] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension LeftSideViewController:UITableViewDataSource{ //Create three rows to reflect "menuItem" func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return menuItems.count } //For each "menuItem", we much instantiate and return a UITableViewCell func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { //You Created a custom cell like this => http://imgur.com/7rorjBf let myCustomCell = tableView.dequeueReusableCellWithIdentifier("myCustomCell", forIndexPath: indexPath) as UITableViewCell myCustomCell.textLabel?.text = menuItems[indexPath.row] return myCustomCell } } extension LeftSideViewController:UITableViewDelegate{ //This is called when one of the user taps the rows in our tableview func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { switch(indexPath.row){ //Main Page case 0: print("Main Page Tapped \(indexPath.row)") //Instantiate MainPageViewController. Remember, identifer is "m" not "M" http://imgur.com/jyGblaR let mainPageViewController = self.storyboard?.instantiateViewControllerWithIdentifier("mainViewController") as! MainPageViewController //Wrap it into Navigation Controller let mainPageNav = UINavigationController(rootViewController: mainPageViewController) //Set Navigation Controller to Navigation Drawer which was created in AppDelegate let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate //Assign mainPageNav is the Center View Controller appDelegate.drawerContainer?.centerViewController = mainPageNav //Toggle the LeftPanel and close it appDelegate.drawerContainer?.toggleDrawerSide(MMDrawerSide.Left, animated: true, completion: nil) case 1: print("About Page Tapped \(indexPath.row)") //Instantiate MainPageViewController. Remember, identifer is "a" not "A" let aboutViewController = self.storyboard?.instantiateViewControllerWithIdentifier("aboutViewController") as! AboutViewController //Wrap it into Navigation Controller let aboutPageNav = UINavigationController(rootViewController: aboutViewController) //Set Navigation Controller to Navigation Drawer which was created in AppDelegate let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate //Swap the Center View Controller with the active item appDelegate.drawerContainer?.centerViewController = aboutPageNav //Toggle the LeftPanel and close it appDelegate.drawerContainer?.toggleDrawerSide(MMDrawerSide.Left, animated: true, completion: nil) break case 2: print("Logout Tapped \(indexPath.row)") let mainPageViewController = self.storyboard?.instantiateViewControllerWithIdentifier("mainViewController") as! MainPageViewController mainPageViewController.signOut() /* let userDefaults = NSUserDefaults.standardUserDefaults() userDefaults.removeObjectForKey("userFirstName") userDefaults.removeObjectForKey("userLastName") userDefaults.removeObjectForKey("userID") userDefaults.synchronize() let signInPage = self.storyboard?.instantiateViewControllerWithIdentifier("viewController") as! ViewController let signInNav = UINavigationController(rootViewController: signInPage) let appDelegate = UIApplication.sharedApplication().delegate appDelegate?.window??.rootViewController = signInNav */ break default: print("Not Handled") break } } }
mit
c2f18a6ab4ff9527c28bde083ce1aac4
41.415929
146
0.666597
6.059418
false
false
false
false
Rypac/hn
hn/FirebaseItem.swift
1
1642
import Foundation struct FirebaseItem: Decodable { typealias Id = Int enum PostType: String, Decodable { case story case comment case job case poll case pollOption enum CodingKeys: String, CodingKey { case story = "story" case comment = "comment" case job = "job" case poll = "poll" case pollOption = "pollopt" } } let id: Id let type: PostType let title: String? let text: String? let score: Int? let author: String? let time: Int? let url: String? let parent: Int? let descendants: Int? let parts: [Int]? let kids: [Id]? let dead: Bool? let deleted: Bool? init( id: Int, type: PostType, title: String?, text: String?, score: Int?, author: String?, time: Int?, url: String?, parent: Int?, descendants: Int?, kids: [Id]?, parts: [Int]?, dead: Bool, deleted: Bool ) { self.id = id self.type = type self.title = title self.text = text self.score = score self.author = author self.time = time self.url = url self.parent = parent self.descendants = descendants self.kids = kids self.parts = parts self.dead = dead self.deleted = deleted } enum CodingKeys: String, CodingKey { case id = "id" case type = "type" case title = "title" case text = "text" case score = "score" case author = "by" case time = "time" case url = "url" case parent = "parent" case descendants = "descendants" case kids = "kids" case parts = "parts" case deleted = "deleted" case dead = "dead" } }
mit
a888153612e0c379a79d5102b4a9044c
18.317647
40
0.584044
3.600877
false
false
false
false
yonadev/yona-app-ios
Yona/Yona/MeDashBoard/YonaUserProfileViewController.swift
1
17230
// // ProfileViewController.swift // Yona // // Created by Chandan on 23/03/16. // Copyright © 2016 Yona. All rights reserved. // import UIKit enum validateError { case firstname case lastname case nickname case phone case none } class YonaUserProfileViewController: UIViewController, UINavigationControllerDelegate { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var rightSideButton : UIBarButtonItem! var topCell : YonaUserHeaderWithTwoTabTableViewCell? fileprivate let nederlandPhonePrefix = "+31 (0) " var aUser : Users? var isShowingProfile = true var rightSideButtonItems : [UIBarButtonItem]? var currentImage: UIImage? //MARK: view life cycle override func viewDidLoad() { super.viewDidLoad() self.navigationController?.isNavigationBarHidden = false registerTableViewCells() dataLoading() currentImage = nil } override func viewWillAppear(_ animated: Bool) { let tracker = GAI.sharedInstance().defaultTracker tracker?.set(kGAIScreenName, value: "YonaUserProfileViewController") let builder = GAIDictionaryBuilder.createScreenView() tracker?.send(builder?.build() as? [AnyHashable: Any]) if UserDefaults.standard.bool(forKey: YonaConstants.nsUserDefaultsKeys.confirmPinFromProfile) { self.navigationItem.leftBarButtonItem = UIBarButtonItem() self.navigationItem.hidesBackButton = true self.tabBarController?.tabBar.isHidden = true } else { let backBtn:UIBarButtonItem = UIBarButtonItem.init(image: UIImage.init(named: "icnBack"), style: UIBarButtonItem.Style.plain, target:self, action:#selector(self.backBtnAction)) self.navigationItem.setLeftBarButtonItems([backBtn], animated: true) self.navigationItem.hidesBackButton = false self.tabBarController?.tabBar.isHidden = false } } func registerTableViewCells () { var nib = UINib(nibName: "YonaUserDisplayTableViewCell", bundle: nil) tableView.register(nib, forCellReuseIdentifier: "YonaUserDisplayTableViewCell") nib = UINib(nibName: "YonaUserHeaderWithTwoTabTableViewCell", bundle: nil) tableView.register(nib, forCellReuseIdentifier: "YonaUserHeaderWithTwoTabTableViewCell") } func dataLoading () { UserRequestManager.sharedInstance.getUser(GetUserRequest.notAllowed) { (success, message, code, user) in Loader.Hide() //success so get the user? if success { self.aUser = user if let img = self.currentImage { self.aUser?.avatarImg = img } if UserDefaults.standard.bool(forKey: YonaConstants.nsUserDefaultsKeys.confirmPinFromProfile){ self.navigateToConfirmMobileNumberVC(self.aUser); } //success so get the user self.tableView.reloadData() } else { //response from request failed } } } // MARK: - Button Actions @objc func backBtnAction(){ self.navigationController?.popViewController(animated: true) self.navigationController?.dismiss(animated: true, completion: nil) } func showUserProfileInEditMode() { self.navigationItem.title = NSLocalizedString("profile.tab.editaccounttitle", comment: "") rightSideButton.image = UIImage.init(named: "icnCreate") tableView.setEditing(true, animated: true) topCell?.setTopViewInEditMode() } func userProfileInNormalMode() { rightSideButton.image = UIImage.init(named: "icnEdit") tableView.setEditing(false, animated: true) topCell?.setTopViewInNormalMode() updateUser() } func showUserProfileInNormalMode() { self.navigationItem.title = "" let result = isUserDataValid() if result == .none { userProfileInNormalMode() } else { switch result { case .firstname: let cell = tableView.cellForRow(at: IndexPath(row: 0, section: 1)) as! YonaUserDisplayTableViewCell cell.setActive() case .lastname: let cell = tableView.cellForRow(at: IndexPath(row: 1, section: 1)) as! YonaUserDisplayTableViewCell cell.setActive() case .nickname: let cell = tableView.cellForRow(at: IndexPath(row: 2, section: 1)) as! YonaUserDisplayTableViewCell cell.setActive() case .phone: let cell = tableView.cellForRow(at: IndexPath(row: 2, section: 1)) as! YonaUserDisplayTableViewCell cell.setActive() default: return } } } @IBAction func userDidSelectEdit(_ sender: AnyObject) { weak var tracker = GAI.sharedInstance().defaultTracker tracker!.send(GAIDictionaryBuilder.createEvent(withCategory: "ui_action", action: "userDidSelectEditUserProfile", label: "Edit user profile button selected", value: nil).build() as? [AnyHashable: Any]) if tableView.isEditing { showUserProfileInNormalMode() } else { showUserProfileInEditMode() } } func userDidStartEdit() { rightSideButtonItems = self.navigationItem.rightBarButtonItems self.navigationItem.rightBarButtonItems = nil } func userDidEndEdit() { self.navigationItem.rightBarButtonItems = rightSideButtonItems } // MARK: - server call func updateUser() { if isUserDataValid() != .none { return } Loader.Show() UserRequestManager.sharedInstance.getUser(GetUserRequest.allowed) { (success, message, code, user) in if success { if self.currentImage != nil { self.uploadImg() } // check for is any update in user info if user?.firstName != self.aUser?.firstName || user?.lastName != self.aUser?.lastName || user?.nickname != self.aUser?.nickname || user?.mobileNumber != self.aUser?.mobileNumber { self.uploadUserData() } else { Loader.Hide() // no update in info, just remove loader } } } } func uploadImg() { guard let img = currentImage, let editlink = aUser?.editUserAvatar else { return } APIServiceManager.sharedInstance.uploadPhoto(img, path: editlink, httpMethod: httpMethods.put, onCompletion: {(success, imgdata, code) in Loader.Hide() }) } fileprivate func navigateToConfirmMobileNumberVC(_ user: Users?) { self.aUser = user if let _ = user?.confirmMobileNumberLink{ setViewControllerToDisplay(ViewControllerTypeString.userProfile, key: YonaConstants.nsUserDefaultsKeys.screenToDisplay) if let controller : ConfirmMobileValidationVC = R.storyboard.login.confirmationCodeValidationViewController(()) { controller.isFromUserProfile = true UserDefaults.standard.set(true, forKey: YonaConstants.nsUserDefaultsKeys.confirmPinFromProfile) self.navigationController?.pushViewController(controller, animated: false) } } self.tableView.reloadData() } func uploadUserData() { UserRequestManager.sharedInstance.updateUser((aUser?.userDataDictionaryForServer())!, onCompletion: {(success, message, code, user) in //success so get the user? Loader.Hide() if success { self.navigateToConfirmMobileNumberVC(user) } else { if let alertMessage = message, let code = code { self.displayAlertMessage(code, alertDescription: alertMessage) } } }) } func isUserDataValid() -> validateError { if aUser?.firstName.count == 0 { self.displayAlertMessage("", alertDescription:NSLocalizedString("enter-first-name-validation", comment: "")) return .firstname } else if aUser?.lastName.count == 0 { self.displayAlertMessage("", alertDescription: NSLocalizedString("enter-last-name-validation", comment: "")) return .lastname } else if aUser?.mobileNumber.count == 0 { self.displayAlertMessage("", alertDescription:NSLocalizedString("enter-number-validation", comment: "")) return .phone } else if aUser?.nickname.count == 0 { self.displayAlertMessage("", alertDescription: NSLocalizedString("enter-nickname-validation", comment: "")) return .nickname } else { if var mobileNumber = aUser?.mobileNumber { mobileNumber = mobileNumber.formatNumber(prefix: "") if !mobileNumber.isValidMobileNumber() { self.displayAlertMessage("", alertDescription: NSLocalizedString("enter-number-validation", comment: "")) return .phone } aUser?.mobileNumber = mobileNumber } } return .none } func chooseImage(_ sender: Any) { let imagePickerController = UIImagePickerController() imagePickerController.navigationBar.isTranslucent = false imagePickerController.navigationBar.barTintColor = .yiGrapeTwoColor() // Background color imagePickerController.allowsEditing = true imagePickerController.delegate = self let actionSheet = UIAlertController(title: "Photo Source", message: "Choose a source", preferredStyle: .actionSheet) let act = UIAlertAction(title: "Camera", style: .default, handler: {(action:UIAlertAction) in if UIImagePickerController.isSourceTypeAvailable(.camera) { imagePickerController.sourceType = .camera self.present(imagePickerController, animated: true, completion: nil) } }) actionSheet.addAction(act) let act1 = UIAlertAction(title: "Photo Library", style: .default, handler: { (action:UIAlertAction) in imagePickerController.sourceType = .photoLibrary self.present(imagePickerController, animated: true, completion: nil) }) actionSheet.addAction(act1) actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) self.present(actionSheet, animated: true, completion: nil) } func resizeImage(_ image: UIImage, targetSize: CGSize) -> UIImage? { let size = image.size let widthRatio = targetSize.width / size.width let heightRatio = targetSize.height / size.height // Figure out what our orientation is, and use that to form the rectangle var newSize: CGSize if(widthRatio > heightRatio) { newSize = CGSize(width: size.width * heightRatio, height: size.height * heightRatio) } else { newSize = CGSize(width: size.width * widthRatio, height: size.height * widthRatio) } // This is the rect that we've calculated out and this is what is actually used below let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height) // Actually do the resizing to the rect using the ImageContext stuff UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0) image.draw(in: rect) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage } } //MARK: YonaUserHeaderTabProtocol extension YonaUserProfileViewController: YonaUserHeaderTabProtocol { func didSelectProfileTab() { isShowingProfile = true if let items = rightSideButtonItems { self.navigationItem.rightBarButtonItems = items } tableView.reloadData() } func didSelectBadgesTab() { isShowingProfile = false rightSideButtonItems = self.navigationItem.rightBarButtonItems self.navigationItem.rightBarButtonItems = nil tableView.reloadData() } func didAskToAddProfileImage() { chooseImage(self) } } //MARK: UITableViewDelegate and UITableViewDataSource extension YonaUserProfileViewController: UITableViewDelegate, UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 2 // return 2 section, one for user avatar image, profile tab and badge tab and other section for user info(firstName, lastname, nickname and mobile number) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 0 { return 1 // For section 0, return only 1 row for user avatar image, profile tab and badge tab --> YonaUserHeaderWithTwoTabTableViewCell } if isShowingProfile { return 4 //if profile tab selected, return 4 rows for firstName, lastname, nickname and mobile number --> YonaUserDisplayTableViewCell } else { return 0 // if badge tab selected return 0 } } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return nil } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.section == 0 { if topCell == nil { topCell = (tableView.dequeueReusableCell(withIdentifier: "YonaUserHeaderWithTwoTabTableViewCell", for: indexPath) as! YonaUserHeaderWithTwoTabTableViewCell) topCell?.delegate = self } if let theUser = aUser { topCell!.avatarImageView.image = currentImage topCell!.setUser(theUser) } return topCell! } if isShowingProfile { let cell: YonaUserDisplayTableViewCell = tableView.dequeueReusableCell(withIdentifier: "YonaUserDisplayTableViewCell", for: indexPath) as! YonaUserDisplayTableViewCell cell.setData(delegate: self, cellType: ProfileCategoryHeader(rawValue: indexPath.row)!) return cell } else { // must be changed to show badges let cell: YonaUserDisplayTableViewCell = tableView.dequeueReusableCell(withIdentifier: "YonaUserDisplayTableViewCell", for: indexPath) as! YonaUserDisplayTableViewCell cell.setData(delegate: self, cellType: ProfileCategoryHeader(rawValue: indexPath.row)!) return cell } } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if indexPath.section == 0 { return 221 // section 0 , YonaUserHeaderWithTwoTabTableViewCell height which is fixed in xib(cell UI design) } return 87 // section 1 , YonaUserDisplayTableViewCell height which is fixed in xib(cell UI design) } func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle { return UITableViewCell.EditingStyle.none } func tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool { return false } } //MARK: UIImagePickerControllerDelegate extension YonaUserProfileViewController: UIImagePickerControllerDelegate { func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]){ var image : UIImage! if let img = info[.editedImage] as? UIImage { image = img } else if let img = info[.originalImage] as? UIImage { image = img } currentImage = resizeImage(image, targetSize: CGSize(width:200, height: 200)) topCell!.avatarImageView.image = currentImage topCell!.avatarInitialsLabel.text = "" picker.dismiss( animated: true, completion: nil) UINavigationBar.appearance().tintColor = UIColor.yiWhiteColor() UINavigationBar.appearance().titleTextAttributes = [NSAttributedString.Key.foregroundColor : UIColor.white, NSAttributedString.Key.font: UIFont(name: "SFUIDisplay-Bold", size: 14)!] UINavigationBar.appearance().barTintColor = UIColor.yiWhiteColor() } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { picker.dismiss( animated: true, completion: nil) UINavigationBar.appearance().tintColor = UIColor.yiWhiteColor() UINavigationBar.appearance().titleTextAttributes = [NSAttributedString.Key.foregroundColor : UIColor.white, NSAttributedString.Key.font: UIFont(name: "SFUIDisplay-Bold", size: 14)!] UINavigationBar.appearance().barTintColor = UIColor.yiWhiteColor() } }
mpl-2.0
effacb59aa4efeb4ee63ef225300928e
43.176923
209
0.642115
5.424748
false
false
false
false
PureSwift/Bluetooth
Sources/BluetoothGATT/ATTFindByTypeRequest.swift
1
2673
// // ATTFindByTypeRequest.swift // Bluetooth // // Created by Alsey Coleman Miller on 6/13/18. // Copyright © 2018 PureSwift. All rights reserved. // import Foundation /// Find By Type Value Request /// /// The *Find By Type Value Request* is used to obtain the handles of attributes that /// have a 16-bit UUID attribute type and attribute value. /// This allows the range of handles associated with a given attribute to be discovered when /// the attribute type determines the grouping of a set of attributes. /// /// - Note: Generic Attribute Profile defines grouping of attributes by attribute type. @frozen public struct ATTFindByTypeRequest: ATTProtocolDataUnit, Equatable { public static var attributeOpcode: ATTOpcode { return .findByTypeRequest } /// First requested handle number public var startHandle: UInt16 /// Last requested handle number public var endHandle: UInt16 /// 2 octet UUID to find. public var attributeType: UInt16 /// Attribute value to find. public var attributeValue: Data public init(startHandle: UInt16, endHandle: UInt16, attributeType: UInt16, attributeValue: Data) { self.startHandle = startHandle self.endHandle = endHandle self.attributeType = attributeType self.attributeValue = attributeValue } } public extension ATTFindByTypeRequest { init?(data: Data) { guard data.count >= 7, type(of: self).validateOpcode(data) else { return nil } let startHandle = UInt16(littleEndian: UInt16(bytes: (data[1], data[2]))) let endHandle = UInt16(littleEndian: UInt16(bytes: (data[3], data[4]))) let attributeType = UInt16(littleEndian: UInt16(bytes: (data[5], data[6]))) let attributeValue = data.suffixCheckingBounds(from: 7) self.init(startHandle: startHandle, endHandle: endHandle, attributeType: attributeType, attributeValue: attributeValue) } var data: Data { return Data(self) } } // MARK: - DataConvertible extension ATTFindByTypeRequest: DataConvertible { var dataLength: Int { return 7 + attributeValue.count } static func += <T: DataContainer> (data: inout T, value: ATTFindByTypeRequest) { data += attributeOpcode.rawValue data += value.startHandle.littleEndian data += value.endHandle.littleEndian data += value.attributeType.littleEndian data += value.attributeValue } }
mit
092243bb57e8eaa3cc01d58f38e85789
28.688889
92
0.638473
4.720848
false
false
false
false
dangnguyenhuu/JSQMessagesSwift
Sources/Models/JSQMediaItem.swift
1
4326
// // JSQMediaItem.swift // JSQMessagesViewController // // Created by Sylvain FAY-CHATELARD on 19/08/2015. // Copyright (c) 2015 Dviance. All rights reserved. // import UIKit open class JSQMediaItem: NSObject, JSQMessageMediaData, NSCoding, NSCopying { var cachedPlaceholderView: UIView? open var appliesMediaViewMaskAsOutgoing: Bool = true { didSet { self.cachedPlaceholderView = nil } } public override required init() { super.init() self.appliesMediaViewMaskAsOutgoing = true NotificationCenter.default.addObserver(self, selector: #selector(JSQMediaItem.didReceiveMemoryWarningNotification(_:)), name: NSNotification.Name.UIApplicationDidReceiveMemoryWarning, object: nil) } public required init(maskAsOutgoing: Bool) { super.init() self.appliesMediaViewMaskAsOutgoing = maskAsOutgoing NotificationCenter.default.addObserver(self, selector: #selector(JSQMediaItem.didReceiveMemoryWarningNotification(_:)), name: NSNotification.Name.UIApplicationDidReceiveMemoryWarning, object: nil) } deinit { NotificationCenter.default.removeObserver(self) self.cachedPlaceholderView = nil } func clearCachedMediaViews() { self.cachedPlaceholderView = nil } // MARK: - Notifications func didReceiveMemoryWarningNotification(_ notification: Notification) { self.clearCachedMediaViews() } // MARK: - JSQMessageMediaData protocol open var mediaView: UIView? { get { print("Error! required method not implemented in subclass. Need to implement \(#function)") abort() } } open var mediaViewDisplaySize: CGSize { get { if UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad { return CGSize(width: 315, height: 225) } return CGSize(width: 210, height: 150) } } open var mediaPlaceholderView: UIView { get { if let cachedPlaceholderView = self.cachedPlaceholderView { return cachedPlaceholderView } let size = self.mediaViewDisplaySize let view = JSQMessagesMediaPlaceholderView.viewWithActivityIndicator() view.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height) JSQMessagesMediaViewBubbleImageMasker.applyBubbleImageMaskToMediaView(view, isOutgoing: self.appliesMediaViewMaskAsOutgoing) self.cachedPlaceholderView = view return view } } open var mediaHash: Int { get { return self.hash } } // MARK: - NSObject open override func isEqual(_ object: Any?) -> Bool { if let item = object as? JSQMediaItem { return self.appliesMediaViewMaskAsOutgoing == item.appliesMediaViewMaskAsOutgoing } return false } open override var hash:Int { get { return NSNumber(value: self.appliesMediaViewMaskAsOutgoing as Bool).hash } } open override var description: String { get { return "<\(type(of: self)): appliesMediaViewMaskAsOutgoing=\(self.appliesMediaViewMaskAsOutgoing)>" } } func debugQuickLookObject() -> AnyObject? { return self.mediaPlaceholderView } // MARK: - NSCoding public required init(coder aDecoder: NSCoder) { super.init() self.appliesMediaViewMaskAsOutgoing = aDecoder.decodeBool(forKey: "appliesMediaViewMaskAsOutgoing") } open func encode(with aCoder: NSCoder) { aCoder.encode(self.appliesMediaViewMaskAsOutgoing, forKey: "appliesMediaViewMaskAsOutgoing") } // MARK: - NSCopying open func copy(with zone: NSZone?) -> Any { return type(of: self).init(maskAsOutgoing: self.appliesMediaViewMaskAsOutgoing) } }
apache-2.0
649a14e830ea96bdfd49e0985bee9bf4
25.539877
204
0.595007
5.455233
false
false
false
false
manavgabhawala/swift
test/SILGen/borrow.swift
1
1227
// RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -parse-stdlib -emit-silgen %s | %FileCheck %s import Swift final class D {} // Make sure that we insert the borrow for a ref_element_addr lvalue in the // proper place. final class C { var d: D = D() } func useD(_ d: D) {} // CHECK-LABEL: sil hidden @_T06borrow44lvalueBorrowShouldBeAtEndOfFormalAccessScope{{.*}} : $@convention(thin) () -> () { // CHECK: bb0: // CHECK: [[BOX:%.*]] = alloc_box ${ var C }, var, name "c" // CHECK: [[PB_BOX:%.*]] = project_box [[BOX]] // CHECK: [[FUNC:%.*]] = function_ref @_T06borrow4useD{{.*}} : $@convention(thin) (@owned D) -> () // CHECK: [[CLASS:%.*]] = load [copy] [[PB_BOX]] // CHECK: [[BORROWED_CLASS:%.*]] = begin_borrow [[CLASS]] // CHECK: [[OFFSET:%.*]] = ref_element_addr [[BORROWED_CLASS]] // CHECK: [[LOADED_VALUE:%.*]] = load [copy] [[OFFSET]] // CHECK: end_borrow [[BORROWED_CLASS]] from [[CLASS]] // CHECK: apply [[FUNC]]([[LOADED_VALUE]]) // CHECK: destroy_value [[CLASS]] // CHECK: destroy_value [[BOX]] // CHECK: } // end sil function '_T06borrow44lvalueBorrowShouldBeAtEndOfFormalAccessScope{{.*}}' func lvalueBorrowShouldBeAtEndOfFormalAccessScope() { var c = C() useD(c.d) }
apache-2.0
53998a430e21c84f8bde0f25321ae1cf
37.34375
122
0.617767
3.212042
false
false
false
false
selfzhou/Swift3
Playground/Swift3-I.playground/Pages/Control-Flow.xcplaygroundpage/Contents.swift
1
2608
//: [Previous](@previous) import Foundation // Switch 区间匹配s let approximateCount = 62 let countedThings = "moon orbiting Saturn" var naturalCount: String switch approximateCount { case 0: naturalCount = "no" case 1..<5: naturalCount = "a few" case 5..<12: naturalCount = "several" default: naturalCount = "many" } print(naturalCount) // Switch 元组 let somePoint = (1, 1) switch somePoint { case (0, 0): print("(0, 0)") default: print("\(somePoint.0) \(somePoint.1)") } // Swift 允许多个 case 匹配到同一个值。 // 如果存在多个匹配,只会执行第一个被匹配到的 case 分支。 // 值绑定 let anotherPoint = (2, 0) switch anotherPoint { case (let x, 0): print(x) case (let x, let y): print("\(x) - \(y)") } // MARK: 控制转移语句 /** continue break fallthrough return throw */ // `continue` 告诉一个循环体立刻停止本次循环,重写开始下一次循环。 let puzzleInput = "great minds think alike" var puzzleOutput = "" for character in puzzleInput.characters { switch character { case "a", "e", "i", "o", "u", " ": continue default: puzzleOutput.append(character) } } puzzleOutput /** `break` 立刻结束整个控制流的执行。 循环语句中的 break 当一个循环体中使用 break,会立即终端改循环体的执行,然后跳到表示循环体结束的大括号 `}` 后的第一行代码。 不会再有本次循环代码被执行,也不会再有下次循环产生。 Switch 中的 break 当在switch代码块中使用 break 时,会立即终端该 switch 代码的执行,并且跳转到表示 switch 代码块结束的大括号 `}` 后的第一行代码。 */ /** `fallthrough` 贯穿 */ let integerToDescribe = 5 var description = "The number \(integerToDescribe) is" switch integerToDescribe { case 2, 3, 5, 7, 11, 13, 17, 19: description += " a prime number, and also" fallthrough default: description += " an integer." } // 带标签的语句: `label name`: while `condition` { `statements` } func greet(_ person: [String: String]) { guard let name = person["name"] else { return } print(name) } greet(["name": "John"]) greet(["nickname": "Jhoni"]) // 检测 API 可用性 // * 必须的,用于指定在其他平台中,如果版本号高于你的设备指定最低版本,if 语句将会执行。 if #available(iOS 10, macOS 10.12, *) { // 在 iOS 使用 iOS 10 的 API // macOS 使用 macOS 10.12 的 API } else { // 使用先前版本的 iOS 和 macOS 的 API }
mit
de6b47cfc9bf4904ea21f5d8d20197dd
16.418803
81
0.646222
2.846369
false
false
false
false
sundance2000/LegoDimensionsCalculator
LegoDimensionsCalculator/Ability.swift
1
5824
// // Ability.swift // LegoDimensionsCalculator // // Created by Christian Oberdörfer on 04.05.16. // Copyright © 2016 sundance. All rights reserved. // protocol EnumerableEnum: RawRepresentable { static func allValues() -> [Self] } extension EnumerableEnum where RawValue == Int { static func allValues() -> [Self] { var index = -1 return Array(AnyGenerator { index += 1 return Self(rawValue: Int(index)) }) } } enum Ability: Int, EnumerableEnum { case AcceleratorSwitches case Acrobat case Atlantis case BigTransform case Boomerang case CanBeRiddenAsATurret case CanRideThisModel case CanUseRetroGamesToCompletePuzzles case CapturesGoonsAsWellAsGhosts case Chi case CrackedLegoObjects case Dig case Dive case Drill case Drone case Electricity case ElectricitySwitches case FixIt case FlightDocksAndFlightCargoHooks case Flying case FlyingModel case FlyingVehicle case FreezeBreath case GhostTrap case Grapple case GoldLegoBlowup case Guardian case Growth case GyrosphereSwitch case Hacking case HazardCleaner case HazardProtection case Hoverboard case Illumination case Invulnerability case Laser case LaserDeflector case Magic case MagicalShield case MasterBuild case MechWalker case MindControl case MiniAccess case ModelCanDiveUnderwater case ModelSailsOnWater case Music case PoleVault case PortalGun case RainbowLegoObjectsBuild // Unitkitty und Cloud Cuckoo Car have RainbowLegoObjects but only Unitkitty can build with rainbow objects case RainbowLegoObjects case RefillsHealthWhenNear case RelicDetector case SpeedBoost case SilverLegoBlowup case SlimeBeam case SlimeBolts case SlimeBomb case SonarSmash case SpecialAttack case SpecialWeapon case Speed case Spinjitzu case Stealth case SuperStrength case SuspendGhost case Target case TauntsEnemies case Technology case TheTardisCanTravelToAnyPointInAllOfTimeAndSpace case TimeTravel case TowBar case Tracking case VineCut case WaterSpray case WeightSwitch case XrayVision // Dive case DiveAcrobat case DiveAtlantis case DiveBoomerang case DiveBigTransform case DiveChi case DiveDig case DiveDrone case DiveFreezeBreath case DiveGrowth case DiveHacking case DiveHazardCleaner case DiveHazardProtection case DiveIllumination case DiveInvulnerability case DiveLaser case DiveMindControl case DiveMiniAccess case DiveSilverLegoBlowup case DiveSonarSmash case DiveSpinjitzu case DiveStealth case DiveSuperStrength case DiveTarget case DiveTechnology case DiveTracking case DiveXrayVision // Worlds case BackToTheFutureWorld case DcComicsWorld case DoctorWhoWorld case GhostbustersWorld case JurassicWorld case LegendsOfChimaWorld case MidwayArcadeWorld case NinjagoWorld case Portal2World case ScoobyDooWorld case TheLegoMovieWorld case TheLordOfTheRingsWorld case TheSimpsonsWorld case WizardOfOzWorld // Levels case BackToTheFutureLevel case DoctorWhoLevel case GhostbustersLevel case MidwayArcadeLevel case Portal2Level case TheSimpsonsLevel } let worldAbilities: [Ability] = [ .BackToTheFutureWorld, .DcComicsWorld, .DoctorWhoWorld, .GhostbustersWorld, .JurassicWorld, .LegendsOfChimaWorld, .MidwayArcadeWorld, .NinjagoWorld, .Portal2World, .ScoobyDooWorld, .TheLegoMovieWorld, .TheLordOfTheRingsWorld, .TheSimpsonsWorld, .WizardOfOzWorld ] let levelAbilities: [Ability] = [ .BackToTheFutureLevel, .DoctorWhoLevel, .GhostbustersLevel, .MidwayArcadeLevel, .Portal2Level, .TheSimpsonsLevel, .CanBeRiddenAsATurret, // Only needed in Portal level ] /// These abilities can be used while diving let diveAbilities: [Ability] = [ .DiveAcrobat, .DiveAtlantis, .DiveBoomerang, .DiveBigTransform, .DiveChi, .DiveDig, .DiveDrone, .DiveFreezeBreath, .DiveGrowth, .DiveHacking, .DiveHazardCleaner, .DiveHazardProtection, .DiveIllumination, .DiveInvulnerability, .DiveLaser, .DiveMindControl, .DiveMiniAccess, .DiveSilverLegoBlowup, .DiveSonarSmash, .DiveSpinjitzu, .DiveStealth, .DiveSuperStrength, .DiveTarget, .DiveTechnology, .DiveTracking, .DiveXrayVision ] /// These abilities are ignored because they do not have any function (drive/ride abilities are not even listed in the Ability enum) let ignoredAbilities: [Ability] = [ .BigTransform, // SuperStrength is better .CanRideThisModel, // No real ability .CapturesGoonsAsWellAsGhosts, //Not needed .CrackedLegoObjects, // SuperStrength is better .FreezeBreath, // Not needed .GoldLegoBlowup, // Laser is better .Guardian, // No real ability .HazardProtection, // Invulnerability is better .MechWalker, // No real ability .ModelSailsOnWater, // No real ability .RefillsHealthWhenNear, // Not needed .SlimeBeam, .SlimeBolts, .SlimeBomb, .SpecialAttack, .SpecialWeapon, .Speed, // Not needed .SpeedBoost, // Not needed .TauntsEnemies, // Already covered by the Ghost Trap .DiveBigTransform, .DiveFreezeBreath, .DiveHazardProtection ] let mappedAbilities: [Ability: Ability] = [ .ModelCanDiveUnderwater: .Dive, .ElectricitySwitches: .Electricity, .FlyingModel: .Flying, .FlyingVehicle: .Flying, .Growth: .WaterSpray, .HazardCleaner: .WaterSpray ]
mit
1aae19159d634c22c5fcbc41b2ffb492
23.258333
140
0.707145
3.70828
false
false
false
false
avaidyam/Parrot
Parrot/ConversationCell.swift
1
14794
import MochaUI import protocol ParrotServiceExtension.Message import protocol ParrotServiceExtension.Conversation // A visual representation of a Conversation in a ListView. public class ConversationCell: NSCollectionViewItem, DroppableViewDelegate { private static var wallclock = Wallclock() // global private var timeObserver: Any? = nil private lazy var effectView: NSVisualEffectView = { let v = NSVisualEffectView().modernize(wantsLayer: true) v.material = .selection v.blendingMode = .behindWindow v.state = .followsWindowActiveState return v }() private lazy var photoView: NSImageView = { let v = NSImageView().modernize(wantsLayer: true) v.allowsCutCopyPaste = false v.isEditable = false v.animates = true return v }() private lazy var badgeLabel: NSTextField = { let v = NSTextField(labelWithString: " ").modernize(wantsLayer: true) v.cornerRadius = 4.0 v.layer?.backgroundColor = .ns(.selectedMenuItemColor) v.textColor = .white v.font = .systemFont(ofSize: 9.0, weight: .medium) v.usesSingleLineMode = true v.lineBreakMode = .byClipping return v }() private lazy var nameLabel: NSTextField = { let v = NSTextField(labelWithString: "").modernize() v.textColor = .labelColor v.font = .systemFont(ofSize: 13.0, weight: .semibold) v.lineBreakMode = .byTruncatingTail v.setContentCompressionResistancePriority(NSLayoutConstraint.Priority(rawValue: 1), for: .horizontal) return v }() private lazy var textLabel: NSTextField = { let v = NSTextField(labelWithString: "").modernize() v.textColor = .secondaryLabelColor v.font = .systemFont(ofSize: 11.0) v.usesSingleLineMode = false v.lineBreakMode = .byWordWrapping return v }() private lazy var timeLabel: NSTextField = { let v = NSTextField(labelWithString: "").modernize() v.textColor = .tertiaryLabelColor v.font = .systemFont(ofSize: 11.0, weight: .light) v.alignment = .right v.setContentCompressionResistancePriority(NSLayoutConstraint.Priority(rawValue: 1000), for: .horizontal) return v }() private lazy var dropZone: DroppableView = { let v = DroppableView().modernize() v.acceptedTypes = [.of(kUTTypeImage)] v.operation = .copy v.allowsSpringLoading = true v.delegate = self return v }() private var visualSubscriptions: [Any] = [] // Constraint setup here. public override func loadView() { self.view = NSView() self.view.wantsLayer = true self.view.set(allowsVibrancy: true) self.view.add(subviews: self.effectView, self.photoView, self.nameLabel, self.timeLabel, self.textLabel, self.dropZone, self.badgeLabel) { self.edgeAnchors == self.effectView.edgeAnchors self.photoView.leftAnchor == self.view.leftAnchor + 8 self.photoView.centerYAnchor == self.view.centerYAnchor self.photoView.widthAnchor == 48 self.photoView.heightAnchor == 48 self.photoView.rightAnchor == self.nameLabel.leftAnchor - 8 self.photoView.rightAnchor == self.textLabel.leftAnchor - 8 self.nameLabel.topAnchor == self.view.topAnchor + 8 self.nameLabel.rightAnchor == self.timeLabel.leftAnchor - 4 self.nameLabel.bottomAnchor == self.textLabel.topAnchor - 4 self.nameLabel.centerYAnchor == self.timeLabel.centerYAnchor self.timeLabel.topAnchor == self.view.topAnchor + 8 self.timeLabel.rightAnchor == self.view.rightAnchor - 8 self.timeLabel.bottomAnchor == self.textLabel.topAnchor - 4 self.textLabel.rightAnchor == self.view.rightAnchor - 8 self.textLabel.bottomAnchor == self.view.bottomAnchor - 8 self.dropZone.leftAnchor == self.view.leftAnchor self.dropZone.rightAnchor == self.view.rightAnchor self.dropZone.topAnchor == self.view.topAnchor self.dropZone.bottomAnchor == self.view.bottomAnchor self.photoView.centerXAnchor == self.badgeLabel.centerXAnchor self.photoView.bottomAnchor == self.badgeLabel.bottomAnchor self.photoView.edgeAnchors <= self.badgeLabel.edgeAnchors } self.photoView.addTrackingArea(NSTrackingArea(rect: self.photoView.bounds, options: [.activeAlways, .mouseEnteredAndExited, .inVisibleRect], owner: self, userInfo: ["item": "photo"])) self.view.addTrackingArea(NSTrackingArea(rect: self.view.bounds, options: [.activeAlways, .mouseEnteredAndExited, .inVisibleRect], owner: self, userInfo: ["item": "cell"])) // Set up dark/light notifications. self.visualSubscriptions = [ Settings.observe(\.effectiveInterfaceStyle, options: [.initial, .new]) { _, _ in let appearance = InterfaceStyle.current.appearance() self.effectView.appearance = appearance == .light ? .dark : .light }, Settings.observe(\.vibrancyStyle, options: [.initial, .new]) { _, _ in self.effectView.state = VibrancyStyle.current.state() }, ] } // Upon assignment of the represented object, configure the subview contents. public override var representedObject: Any? { didSet { guard let conversation = self.representedObject as? Conversation else { return } let messageSender = (conversation.eventStream.last as? Message)?.sender.identifier ?? "" let selfSender = conversation.participants.filter { $0.me }.first?.identifier // Get the first (last) participant to have sent a message in the conv: let firstParticipant = conversation.eventStream.lazy.compactMap { ($0 as? Message)?.sender }.filter { !$0.me }.last ?? (conversation.participants.filter { !$0.me }.first) self.photoView.image = firstParticipant?.image ?? NSImage(monogramOfSize: NSSize(width: 64.0, height: 64.0), string: "?", color: #colorLiteral(red: 0.2605174184, green: 0.2605243921, blue: 0.260520637, alpha: 1), fontName: .compactRoundedMedium) // Set the badge if SMS or GROUP conversation: if firstParticipant?.locations.contains("OffNetworkPhone") ?? false { // GVoice self.badgeLabel.isHidden = false self.badgeLabel.stringValue = "SMS" } else if conversation.participants.count > 2 { // Group self.badgeLabel.isHidden = false self.badgeLabel.stringValue = "GROUP" } else { self.badgeLabel.isHidden = true self.badgeLabel.stringValue = "" } self.prefix = conversation.muted ? "◉ " : (messageSender != selfSender ? "↙ " : "↗ ") let subtitle = ((conversation.eventStream.last as? Message)?.text ?? "") let time = conversation.eventStream.last?.timestamp ?? .origin self.time = time self.nameLabel.stringValue = conversation.name self.nameLabel.toolTip = conversation.name self.textLabel.stringValue = subtitle self.textLabel.toolTip = subtitle self.timeLabel.stringValue = self.prefix + time.relativeString() self.timeLabel.toolTip = (conversation.muted ? "(muted) " : "") + time.fullString() if conversation.unreadCount > 0 && (messageSender != selfSender) { self.timeLabel.textColor = #colorLiteral(red: 0, green: 0.5843137503, blue: 0.9607843161, alpha: 1) } else { self.timeLabel.textColor = .tertiaryLabelColor } self.view.menu = ConversationDetailsViewController.menu(for: conversation) self.visualSelect = self.highlightState != .none || self.isSelected } } // Dynamically update the visible timestamp for the Conversation. private var time: Date = .origin private var prefix = " " public func updateTimestamp() { self.timeLabel.stringValue = self.prefix + self.time.relativeString() } private var visualSelect: Bool = false { didSet { let appearance = self.view.effectiveAppearance if self.visualSelect { //self.layer.backgroundColor = CGColor.ns(.selectedMenuItemColor).copy(alpha: 0.25) self.view.appearance = appearance == .light ? .light : .dark self.effectView.isEmphasized = false self.effectView.isHidden = false } else { //self.layer.backgroundColor = .ns(.clear) self.view.appearance = appearance == .light ? .dark : .light self.effectView.isEmphasized = false self.effectView.isHidden = true } } } public override var highlightState: NSCollectionViewItem.HighlightState { didSet { self.visualSelect = self.highlightState != .none || self.isSelected } } public override var isSelected: Bool { didSet { self.visualSelect = self.highlightState != .none || self.isSelected } } // Return a complete dragging component for this ConversationView. // Note that we hide the separator and show it again after snapshot. public override var draggingImageComponents: [NSDraggingImageComponent] { return [self.view.draggingComponent("Person")] } // Allows the photo view's circle crop to dynamically match size. public override func viewDidLayout() { self.photoView.clipPath = NSBezierPath(ovalIn: self.photoView.bounds) //let p = self.photoView//, b = self.badgeLayer //b.frame = NSRect(x: p.frame.minX, y: p.frame.midY, width: p.frame.width / 2, // height: p.frame.width / 2).insetBy(dx: 4.0, dy: 4.0) //p.layer!.cornerRadius = p.frame.width / 2.0 //b.cornerRadius = b.frame.width / 2.0 } public override func viewDidAppear() { self.timeObserver = ConversationCell.wallclock.observe(self.updateTimestamp) } public override func viewDidDisappear() { self.timeObserver = nil } public func springLoading(phase: DroppableView.SpringLoadingPhase, for: NSDraggingInfo) { guard case .activated = phase else { return } NSAlert(message: "Sending document...").beginPopover(for: self.view, on: .minY) } public override func mouseEntered(with event: NSEvent) { guard let trackingArea = event.trackingArea else { return } if let item = trackingArea.userInfo?["item"] as? String, item == "cell" { let v = CATransaction.disableActions() CATransaction.setDisableActions(false) let layer = self.collectionView?.hoverLayer layer?.frame = self.view.bounds.insetBy(dx: 10, dy: 10) layer?.opacity = 0.5 CATransaction.setDisableActions(v) } else if let item = trackingArea.userInfo?["item"] as? String, item == "photo" { guard let conversation = self.representedObject as? Conversation else { return } if conversation.participants.count > 2 { // group! guard let vc = GroupIndicatorToolTipController.popover.contentViewController as? GroupIndicatorToolTipController else { return } vc.images = conversation.participants.filter { !$0.me }.map { $0.image } GroupIndicatorToolTipController.popover.show(relativeTo: self.photoView.bounds, of: self.photoView, preferredEdge: .minY) } else { guard let vc = PersonIndicatorToolTipController.popover.contentViewController as? PersonIndicatorToolTipController, let firstParticipant = (conversation.participants.filter { !$0.me }.first) else { return } var prefix = "" switch firstParticipant.reachability { case .unavailable: break case .phone: prefix = "📱 " case .tablet: prefix = "📱 " //💻 case .desktop: prefix = "🖥 " } _ = vc.view // loadView() vc.text?.stringValue = prefix + firstParticipant.fullName PersonIndicatorToolTipController.popover.show(relativeTo: self.photoView.bounds, of: self.photoView, preferredEdge: .minY) } } } public override func mouseExited(with event: NSEvent) { guard let trackingArea = event.trackingArea else { return } if let item = trackingArea.userInfo?["item"] as? String, item == "cell" { let v = CATransaction.disableActions() CATransaction.setDisableActions(false) let layer = self.collectionView?.hoverLayer layer?.frame = self.view.bounds.insetBy(dx: 10, dy: 10) layer?.opacity = 0.0 CATransaction.setDisableActions(v) } else if let item = trackingArea.userInfo?["item"] as? String, item == "photo" { guard let conversation = self.representedObject as? Conversation else { return } if conversation.participants.count > 2 { // group! GroupIndicatorToolTipController.popover.performClose(nil) } else { PersonIndicatorToolTipController.popover.performClose(nil) } } } } public extension NSCollectionView { private static var hoverProp = AssociatedProperty<NSCollectionView, CALayer>(.strong) @nonobjc fileprivate var hoverLayer: CALayer? { get { return NSCollectionView.hoverProp[self, creating: _newHoverLayer()] } set { NSCollectionView.hoverProp[self] = newValue } } private func _newHoverLayer() -> CALayer { let c = CALayer() c.backgroundColor = .black c.opacity = 0.0 c.cornerRadius = 5.0 c.zPosition = 200 self.layer?.addSublayer(c) return c } }
mpl-2.0
2305704358f467f40e8e4683404430ab
44.186544
206
0.6049
4.863726
false
false
false
false
brentdax/swift
stdlib/public/core/Dictionary.swift
1
75605
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // Implementation notes // ==================== // // `Dictionary` uses two storage schemes: native storage and Cocoa storage. // // Native storage is a hash table with open addressing and linear probing. The // bucket array forms a logical ring (e.g., a chain can wrap around the end of // buckets array to the beginning of it). // // The logical bucket array is implemented as three arrays: Key, Value, and a // bitmap that marks valid entries. An unoccupied entry marks the end of a // chain. There is always at least one unoccupied entry among the // buckets. `Dictionary` does not use tombstones. // // In addition to the native storage, `Dictionary` can also wrap an // `NSDictionary` in order to allow bridging `NSDictionary` to `Dictionary` in // `O(1)`. // // Native dictionary storage uses a data structure like this:: // // struct Dictionary<K,V> // +------------------------------------------------+ // | enum Dictionary<K,V>._Variant | // | +--------------------------------------------+ | // | | [struct _NativeDictionary<K,V> | | // | +---|----------------------------------------+ | // +----/-------------------------------------------+ // / // | // V // class _RawDictionaryStorage // +-----------------------------------------------------------+ // | <isa> | // | <refcount> | // | _count | // | _capacity | // | _scale | // | _age | // | _seed | // | _rawKeys | // | _rawValue | // | [inline bitset of occupied entries] | // | [inline array of keys] | // | [inline array of values] | // +-----------------------------------------------------------+ // // Cocoa storage uses a data structure like this: // // struct Dictionary<K,V> // +----------------------------------------------+ // | enum Dictionary<K,V>._Variant | // | +----------------------------------------+ | // | | [ struct _CocoaDictionary | | // | +---|------------------------------------+ | // +----/-----------------------------------------+ // / // | // V // class NSDictionary // +--------------+ // | [refcount#1] | // | etc. | // +--------------+ // ^ // | // \ struct _CocoaDictionary.Index // +--|------------------------------------+ // | * base: _CocoaDictionary | // | allKeys: array of all keys | // | currentKeyIndex: index into allKeys | // +---------------------------------------+ // // // The Native Kinds of Storage // --------------------------- // // The native backing store is represented by three different classes: // * `_RawDictionaryStorage` // * `_EmptyDictionarySingleton` (extends Raw) // * `_DictionaryStorage<K: Hashable, V>` (extends Raw) // // (Hereafter `Raw`, `Empty`, and `Storage`, respectively) // // In a less optimized implementation, `Raw` and `Empty` could be eliminated, as // they exist only to provide special-case behaviors. // // `Empty` is the a type-punned empty singleton storage. Its single instance is // created by the runtime during process startup. Because we use the same // instance for all empty dictionaries, it cannot declare type parameters. // // `Storage` provides backing storage for regular native dictionaries. All // non-empty native dictionaries use an instance of `Storage` to store their // elements. `Storage` is a generic class with a nontrivial deinit. // // `Raw` is the base class for both `Empty` and `Storage`. It defines a full set // of ivars to access dictionary contents. Like `Empty`, `Raw` is also // non-generic; the base addresses it stores are represented by untyped raw // pointers. The only reason `Raw` exists is to allow `_NativeDictionary` to // treat `Empty` and `Storage` in a unified way. // // Storage classes don't contain much logic; `Raw` in particular is just a // collection of ivars. `Storage` provides allocation/deinitialization logic, // while `Empty`/`Storage` implement NSDictionary methods. All other operations // are actually implemented by the `_NativeDictionary` and `_HashTable` structs. // // The `_HashTable` struct provides low-level hash table metadata operations. // (Lookups, iteration, insertion, removal.) It owns and maintains the // tail-allocated bitmap. // // `_NativeDictionary` implements the actual Dictionary operations. It // consists of a reference to a `Raw` instance, to allow for the possibility of // the empty singleton. // // // Index Invalidation // ------------------ // // FIXME: decide if this guarantee is worth making, as it restricts // collision resolution to first-come-first-serve. The most obvious alternative // would be robin hood hashing. The Rust code base is the best // resource on a *practical* implementation of robin hood hashing I know of: // https://github.com/rust-lang/rust/blob/ac919fcd9d4a958baf99b2f2ed5c3d38a2ebf9d0/src/libstd/collections/hash/map.rs#L70-L178 // // Indexing a container, `c[i]`, uses the integral offset stored in the index // to access the elements referenced by the container. Generally, an index into // one container has no meaning for another. However copy-on-write currently // preserves indices under insertion, as long as reallocation doesn't occur: // // var (i, found) = d.find(k) // i is associated with d's storage // if found { // var e = d // now d is sharing its data with e // e[newKey] = newValue // e now has a unique copy of the data // return e[i] // use i to access e // } // // The result should be a set of iterator invalidation rules familiar to anyone // familiar with the C++ standard library. Note that because all accesses to a // dictionary storage are bounds-checked, this scheme never compromises memory // safety. // // As a safeguard against using invalid indices, Set and Dictionary maintain a // mutation counter in their storage header (`_age`). This counter gets bumped // every time an element is removed and whenever the contents are // rehashed. Native indices include a copy of this counter so that index // validation can verify it matches with current storage. This can't catch all // misuse, because counters may match by accident; but it does make indexing a // lot more reliable. // // Bridging // ======== // // Bridging `NSDictionary` to `Dictionary` // --------------------------------------- // // FIXME(eager-bridging): rewrite this based on modern constraints. // // `NSDictionary` bridges to `Dictionary<NSObject, AnyObject>` in `O(1)`, // without memory allocation. // // Bridging to `Dictionary<AnyHashable, AnyObject>` takes `O(n)` time, as the // keys need to be fully rehashed after conversion to `AnyHashable`. // // Bridging `NSDictionary` to `Dictionary<Key, Value>` is O(1) if both Key and // Value are bridged verbatim. // // Bridging `Dictionary` to `NSDictionary` // --------------------------------------- // // `Dictionary<K, V>` bridges to `NSDictionary` in O(1) // but may incur an allocation depending on the following conditions: // // * If the Dictionary is freshly allocated without any elements, then it // contains the empty singleton Storage which is returned as a toll-free // implementation of `NSDictionary`. // // * If both `K` and `V` are bridged verbatim, then `Dictionary<K, V>` is // still toll-free bridged to `NSDictionary` by returning its Storage. // // * If the Dictionary is actually a lazily bridged NSDictionary, then that // NSDictionary is returned. // // * Otherwise, bridging the `Dictionary` is done by wrapping it in a // `_SwiftDeferredNSDictionary<K, V>`. This incurs an O(1)-sized allocation. // // Complete bridging of the native Storage's elements to another Storage // is performed on first access. This is O(n) work, but is hopefully amortized // by future accesses. // // This design ensures that: // - Every time keys or values are accessed on the bridged `NSDictionary`, // new objects are not created. // - Accessing the same element (key or value) multiple times will return // the same pointer. // // Bridging `NSSet` to `Set` and vice versa // ---------------------------------------- // // Bridging guarantees for `Set<Element>` are the same as for // `Dictionary<Element, NSObject>`. // /// A collection whose elements are key-value pairs. /// /// A dictionary is a type of hash table, providing fast access to the entries /// it contains. Each entry in the table is identified using its key, which is /// a hashable type such as a string or number. You use that key to retrieve /// the corresponding value, which can be any object. In other languages, /// similar data types are known as hashes or associated arrays. /// /// Create a new dictionary by using a dictionary literal. A dictionary literal /// is a comma-separated list of key-value pairs, in which a colon separates /// each key from its associated value, surrounded by square brackets. You can /// assign a dictionary literal to a variable or constant or pass it to a /// function that expects a dictionary. /// /// Here's how you would create a dictionary of HTTP response codes and their /// related messages: /// /// var responseMessages = [200: "OK", /// 403: "Access forbidden", /// 404: "File not found", /// 500: "Internal server error"] /// /// The `responseMessages` variable is inferred to have type `[Int: String]`. /// The `Key` type of the dictionary is `Int`, and the `Value` type of the /// dictionary is `String`. /// /// To create a dictionary with no key-value pairs, use an empty dictionary /// literal (`[:]`). /// /// var emptyDict: [String: String] = [:] /// /// Any type that conforms to the `Hashable` protocol can be used as a /// dictionary's `Key` type, including all of Swift's basic types. You can use /// your own custom types as dictionary keys by making them conform to the /// `Hashable` protocol. /// /// Getting and Setting Dictionary Values /// ===================================== /// /// The most common way to access values in a dictionary is to use a key as a /// subscript. Subscripting with a key takes the following form: /// /// print(responseMessages[200]) /// // Prints "Optional("OK")" /// /// Subscripting a dictionary with a key returns an optional value, because a /// dictionary might not hold a value for the key that you use in the /// subscript. /// /// The next example uses key-based subscripting of the `responseMessages` /// dictionary with two keys that exist in the dictionary and one that does /// not. /// /// let httpResponseCodes = [200, 403, 301] /// for code in httpResponseCodes { /// if let message = responseMessages[code] { /// print("Response \(code): \(message)") /// } else { /// print("Unknown response \(code)") /// } /// } /// // Prints "Response 200: OK" /// // Prints "Response 403: Access Forbidden" /// // Prints "Unknown response 301" /// /// You can also update, modify, or remove keys and values from a dictionary /// using the key-based subscript. To add a new key-value pair, assign a value /// to a key that isn't yet a part of the dictionary. /// /// responseMessages[301] = "Moved permanently" /// print(responseMessages[301]) /// // Prints "Optional("Moved permanently")" /// /// Update an existing value by assigning a new value to a key that already /// exists in the dictionary. If you assign `nil` to an existing key, the key /// and its associated value are removed. The following example updates the /// value for the `404` code to be simply "Not found" and removes the /// key-value pair for the `500` code entirely. /// /// responseMessages[404] = "Not found" /// responseMessages[500] = nil /// print(responseMessages) /// // Prints "[301: "Moved permanently", 200: "OK", 403: "Access forbidden", 404: "Not found"]" /// /// In a mutable `Dictionary` instance, you can modify in place a value that /// you've accessed through a keyed subscript. The code sample below declares a /// dictionary called `interestingNumbers` with string keys and values that /// are integer arrays, then sorts each array in-place in descending order. /// /// var interestingNumbers = ["primes": [2, 3, 5, 7, 11, 13, 17], /// "triangular": [1, 3, 6, 10, 15, 21, 28], /// "hexagonal": [1, 6, 15, 28, 45, 66, 91]] /// for key in interestingNumbers.keys { /// interestingNumbers[key]?.sort(by: >) /// } /// /// print(interestingNumbers["primes"]!) /// // Prints "[17, 13, 11, 7, 5, 3, 2]" /// /// Iterating Over the Contents of a Dictionary /// =========================================== /// /// Every dictionary is an unordered collection of key-value pairs. You can /// iterate over a dictionary using a `for`-`in` loop, decomposing each /// key-value pair into the elements of a tuple. /// /// let imagePaths = ["star": "/glyphs/star.png", /// "portrait": "/images/content/portrait.jpg", /// "spacer": "/images/shared/spacer.gif"] /// /// for (name, path) in imagePaths { /// print("The path to '\(name)' is '\(path)'.") /// } /// // Prints "The path to 'star' is '/glyphs/star.png'." /// // Prints "The path to 'portrait' is '/images/content/portrait.jpg'." /// // Prints "The path to 'spacer' is '/images/shared/spacer.gif'." /// /// The order of key-value pairs in a dictionary is stable between mutations /// but is otherwise unpredictable. If you need an ordered collection of /// key-value pairs and don't need the fast key lookup that `Dictionary` /// provides, see the `KeyValuePairs` type for an alternative. /// /// You can search a dictionary's contents for a particular value using the /// `contains(where:)` or `firstIndex(where:)` methods supplied by default /// implementation. The following example checks to see if `imagePaths` contains /// any paths in the `"/glyphs"` directory: /// /// let glyphIndex = imagePaths.firstIndex(where: { $0.value.hasPrefix("/glyphs") }) /// if let index = glyphIndex { /// print("The '\(imagesPaths[index].key)' image is a glyph.") /// } else { /// print("No glyphs found!") /// } /// // Prints "The 'star' image is a glyph.") /// /// Note that in this example, `imagePaths` is subscripted using a dictionary /// index. Unlike the key-based subscript, the index-based subscript returns /// the corresponding key-value pair as a nonoptional tuple. /// /// print(imagePaths[glyphIndex!]) /// // Prints "("star", "/glyphs/star.png")" /// /// A dictionary's indices stay valid across additions to the dictionary as /// long as the dictionary has enough capacity to store the added values /// without allocating more buffer. When a dictionary outgrows its buffer, /// existing indices may be invalidated without any notification. /// /// When you know how many new values you're adding to a dictionary, use the /// `init(minimumCapacity:)` initializer to allocate the correct amount of /// buffer. /// /// Bridging Between Dictionary and NSDictionary /// ============================================ /// /// You can bridge between `Dictionary` and `NSDictionary` using the `as` /// operator. For bridging to be possible, the `Key` and `Value` types of a /// dictionary must be classes, `@objc` protocols, or types that bridge to /// Foundation types. /// /// Bridging from `Dictionary` to `NSDictionary` always takes O(1) time and /// space. When the dictionary's `Key` and `Value` types are neither classes /// nor `@objc` protocols, any required bridging of elements occurs at the /// first access of each element. For this reason, the first operation that /// uses the contents of the dictionary may take O(*n*). /// /// Bridging from `NSDictionary` to `Dictionary` first calls the `copy(with:)` /// method (`- copyWithZone:` in Objective-C) on the dictionary to get an /// immutable copy and then performs additional Swift bookkeeping work that /// takes O(1) time. For instances of `NSDictionary` that are already /// immutable, `copy(with:)` usually returns the same dictionary in O(1) time; /// otherwise, the copying performance is unspecified. The instances of /// `NSDictionary` and `Dictionary` share buffer using the same copy-on-write /// optimization that is used when two instances of `Dictionary` share /// buffer. @_fixed_layout public struct Dictionary<Key: Hashable, Value> { /// The element type of a dictionary: a tuple containing an individual /// key-value pair. public typealias Element = (key: Key, value: Value) @usableFromInline internal var _variant: _Variant @inlinable internal init(_native: __owned _NativeDictionary<Key, Value>) { _variant = _Variant(native: _native) } #if _runtime(_ObjC) @inlinable internal init(_cocoa: __owned _CocoaDictionary) { _variant = _Variant(cocoa: _cocoa) } /// Private initializer used for bridging. /// /// Only use this initializer when both conditions are true: /// /// * it is statically known that the given `NSDictionary` is immutable; /// * `Key` and `Value` are bridged verbatim to Objective-C (i.e., /// are reference types). @inlinable public // SPI(Foundation) init(_immutableCocoaDictionary: __owned _NSDictionary) { _sanityCheck( _isBridgedVerbatimToObjectiveC(Key.self) && _isBridgedVerbatimToObjectiveC(Value.self), """ Dictionary can be backed by NSDictionary buffer only when both Key \ and Value are bridged verbatim to Objective-C """) self.init(_cocoa: _CocoaDictionary(_immutableCocoaDictionary)) } #endif /// Creates an empty dictionary. @inlinable public init() { self.init(_native: _NativeDictionary()) } /// Creates an empty dictionary with preallocated space for at least the /// specified number of elements. /// /// Use this initializer to avoid intermediate reallocations of a dictionary's /// storage buffer when you know how many key-value pairs you are adding to a /// dictionary after creation. /// /// - Parameter minimumCapacity: The minimum number of key-value pairs that /// the newly created dictionary should be able to store without /// reallocating its storage buffer. public // FIXME(reserveCapacity): Should be inlinable init(minimumCapacity: Int) { _variant = _Variant(native: _NativeDictionary(capacity: minimumCapacity)) } /// Creates a new dictionary from the key-value pairs in the given sequence. /// /// You use this initializer to create a dictionary when you have a sequence /// of key-value tuples with unique keys. Passing a sequence with duplicate /// keys to this initializer results in a runtime error. If your /// sequence might have duplicate keys, use the /// `Dictionary(_:uniquingKeysWith:)` initializer instead. /// /// The following example creates a new dictionary using an array of strings /// as the keys and the integers in a countable range as the values: /// /// let digitWords = ["one", "two", "three", "four", "five"] /// let wordToValue = Dictionary(uniqueKeysWithValues: zip(digitWords, 1...5)) /// print(wordToValue["three"]!) /// // Prints "3" /// print(wordToValue) /// // Prints "["three": 3, "four": 4, "five": 5, "one": 1, "two": 2]" /// /// - Parameter keysAndValues: A sequence of key-value pairs to use for /// the new dictionary. Every key in `keysAndValues` must be unique. /// - Returns: A new dictionary initialized with the elements of /// `keysAndValues`. /// - Precondition: The sequence must not have duplicate keys. @inlinable public init<S: Sequence>( uniqueKeysWithValues keysAndValues: __owned S ) where S.Element == (Key, Value) { if let d = keysAndValues as? Dictionary<Key, Value> { self = d return } var native = _NativeDictionary<Key, Value>( capacity: keysAndValues.underestimatedCount) // '_MergeError.keyCollision' is caught and handled with an appropriate // error message one level down, inside native.merge(_:...). try! native.merge( keysAndValues, isUnique: true, uniquingKeysWith: { _, _ in throw _MergeError.keyCollision }) self.init(_native: native) } /// Creates a new dictionary from the key-value pairs in the given sequence, /// using a combining closure to determine the value for any duplicate keys. /// /// You use this initializer to create a dictionary when you have a sequence /// of key-value tuples that might have duplicate keys. As the dictionary is /// built, the initializer calls the `combine` closure with the current and /// new values for any duplicate keys. Pass a closure as `combine` that /// returns the value to use in the resulting dictionary: The closure can /// choose between the two values, combine them to produce a new value, or /// even throw an error. /// /// The following example shows how to choose the first and last values for /// any duplicate keys: /// /// let pairsWithDuplicateKeys = [("a", 1), ("b", 2), ("a", 3), ("b", 4)] /// /// let firstValues = Dictionary(pairsWithDuplicateKeys, /// uniquingKeysWith: { (first, _) in first }) /// // ["b": 2, "a": 1] /// /// let lastValues = Dictionary(pairsWithDuplicateKeys, /// uniquingKeysWith: { (_, last) in last }) /// // ["b": 4, "a": 3] /// /// - Parameters: /// - keysAndValues: A sequence of key-value pairs to use for the new /// dictionary. /// - combine: A closure that is called with the values for any duplicate /// keys that are encountered. The closure returns the desired value for /// the final dictionary. @inlinable public init<S: Sequence>( _ keysAndValues: __owned S, uniquingKeysWith combine: (Value, Value) throws -> Value ) rethrows where S.Element == (Key, Value) { var native = _NativeDictionary<Key, Value>( capacity: keysAndValues.underestimatedCount) try native.merge(keysAndValues, isUnique: true, uniquingKeysWith: combine) self.init(_native: native) } /// Creates a new dictionary whose keys are the groupings returned by the /// given closure and whose values are arrays of the elements that returned /// each key. /// /// The arrays in the "values" position of the new dictionary each contain at /// least one element, with the elements in the same order as the source /// sequence. /// /// The following example declares an array of names, and then creates a /// dictionary from that array by grouping the names by first letter: /// /// let students = ["Kofi", "Abena", "Efua", "Kweku", "Akosua"] /// let studentsByLetter = Dictionary(grouping: students, by: { $0.first! }) /// // ["E": ["Efua"], "K": ["Kofi", "Kweku"], "A": ["Abena", "Akosua"]] /// /// The new `studentsByLetter` dictionary has three entries, with students' /// names grouped by the keys `"E"`, `"K"`, and `"A"`. /// /// - Parameters: /// - values: A sequence of values to group into a dictionary. /// - keyForValue: A closure that returns a key for each element in /// `values`. @inlinable public init<S: Sequence>( grouping values: __owned S, by keyForValue: (S.Element) throws -> Key ) rethrows where Value == [S.Element] { try self.init(_native: _NativeDictionary(grouping: values, by: keyForValue)) } } // // All APIs below should dispatch to `_variant`, without doing any // additional processing. // extension Dictionary: Sequence { /// Returns an iterator over the dictionary's key-value pairs. /// /// Iterating over a dictionary yields the key-value pairs as two-element /// tuples. You can decompose the tuple in a `for`-`in` loop, which calls /// `makeIterator()` behind the scenes, or when calling the iterator's /// `next()` method directly. /// /// let hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156] /// for (name, hueValue) in hues { /// print("The hue of \(name) is \(hueValue).") /// } /// // Prints "The hue of Heliotrope is 296." /// // Prints "The hue of Coral is 16." /// // Prints "The hue of Aquamarine is 156." /// /// - Returns: An iterator over the dictionary with elements of type /// `(key: Key, value: Value)`. @inlinable @inline(__always) public __consuming func makeIterator() -> Iterator { return _variant.makeIterator() } } // This is not quite Sequence.filter, because that returns [Element], not Self extension Dictionary { /// Returns a new dictionary containing the key-value pairs of the dictionary /// that satisfy the given predicate. /// /// - Parameter isIncluded: A closure that takes a key-value pair as its /// argument and returns a Boolean value indicating whether the pair /// should be included in the returned dictionary. /// - Returns: A dictionary of the key-value pairs that `isIncluded` allows. @inlinable @available(swift, introduced: 4.0) public __consuming func filter( _ isIncluded: (Element) throws -> Bool ) rethrows -> [Key: Value] { // FIXME(performance): Try building a bitset of elements to keep, so that we // eliminate rehashings during insertion. var result = _NativeDictionary<Key, Value>() for element in self { if try isIncluded(element) { result.insertNew(key: element.key, value: element.value) } } return Dictionary(_native: result) } } extension Dictionary: Collection { /// The position of the first element in a nonempty dictionary. /// /// If the collection is empty, `startIndex` is equal to `endIndex`. /// /// - Complexity: Amortized O(1) if the dictionary does not wrap a bridged /// `NSDictionary`. If the dictionary wraps a bridged `NSDictionary`, the /// performance is unspecified. @inlinable public var startIndex: Index { return _variant.startIndex } /// The dictionary's "past the end" position---that is, the position one /// greater than the last valid subscript argument. /// /// If the collection is empty, `endIndex` is equal to `startIndex`. /// /// - Complexity: Amortized O(1) if the dictionary does not wrap a bridged /// `NSDictionary`; otherwise, the performance is unspecified. @inlinable public var endIndex: Index { return _variant.endIndex } @inlinable public func index(after i: Index) -> Index { return _variant.index(after: i) } @inlinable public func formIndex(after i: inout Index) { _variant.formIndex(after: &i) } /// Returns the index for the given key. /// /// If the given key is found in the dictionary, this method returns an index /// into the dictionary that corresponds with the key-value pair. /// /// let countryCodes = ["BR": "Brazil", "GH": "Ghana", "JP": "Japan"] /// let index = countryCodes.index(forKey: "JP") /// /// print("Country code for \(countryCodes[index!].value): '\(countryCodes[index!].key)'.") /// // Prints "Country code for Japan: 'JP'." /// /// - Parameter key: The key to find in the dictionary. /// - Returns: The index for `key` and its associated value if `key` is in /// the dictionary; otherwise, `nil`. @inlinable @inline(__always) public func index(forKey key: Key) -> Index? { // Complexity: amortized O(1) for native dictionary, O(*n*) when wrapping an // NSDictionary. return _variant.index(forKey: key) } /// Accesses the key-value pair at the specified position. /// /// This subscript takes an index into the dictionary, instead of a key, and /// returns the corresponding key-value pair as a tuple. When performing /// collection-based operations that return an index into a dictionary, use /// this subscript with the resulting value. /// /// For example, to find the key for a particular value in a dictionary, use /// the `firstIndex(where:)` method. /// /// let countryCodes = ["BR": "Brazil", "GH": "Ghana", "JP": "Japan"] /// if let index = countryCodes.firstIndex(where: { $0.value == "Japan" }) { /// print(countryCodes[index]) /// print("Japan's country code is '\(countryCodes[index].key)'.") /// } else { /// print("Didn't find 'Japan' as a value in the dictionary.") /// } /// // Prints "("JP", "Japan")" /// // Prints "Japan's country code is 'JP'." /// /// - Parameter position: The position of the key-value pair to access. /// `position` must be a valid index of the dictionary and not equal to /// `endIndex`. /// - Returns: A two-element tuple with the key and value corresponding to /// `position`. @inlinable public subscript(position: Index) -> Element { return _variant.lookup(position) } /// The number of key-value pairs in the dictionary. /// /// - Complexity: O(1). @inlinable public var count: Int { return _variant.count } // // `Sequence` conformance // /// A Boolean value that indicates whether the dictionary is empty. /// /// Dictionaries are empty when created with an initializer or an empty /// dictionary literal. /// /// var frequencies: [String: Int] = [:] /// print(frequencies.isEmpty) /// // Prints "true" @inlinable public var isEmpty: Bool { return count == 0 } /// The first element of the dictionary. /// /// The first element of the dictionary is not necessarily the first element /// added to the dictionary. Don't expect any particular ordering of /// dictionary elements. /// /// If the dictionary is empty, the value of this property is `nil`. @inlinable public var first: Element? { var it = makeIterator() return it.next() } } extension Dictionary { /// Accesses the value associated with the given key for reading and writing. /// /// This *key-based* subscript returns the value for the given key if the key /// is found in the dictionary, or `nil` if the key is not found. /// /// The following example creates a new dictionary and prints the value of a /// key found in the dictionary (`"Coral"`) and a key not found in the /// dictionary (`"Cerise"`). /// /// var hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156] /// print(hues["Coral"]) /// // Prints "Optional(16)" /// print(hues["Cerise"]) /// // Prints "nil" /// /// When you assign a value for a key and that key already exists, the /// dictionary overwrites the existing value. If the dictionary doesn't /// contain the key, the key and value are added as a new key-value pair. /// /// Here, the value for the key `"Coral"` is updated from `16` to `18` and a /// new key-value pair is added for the key `"Cerise"`. /// /// hues["Coral"] = 18 /// print(hues["Coral"]) /// // Prints "Optional(18)" /// /// hues["Cerise"] = 330 /// print(hues["Cerise"]) /// // Prints "Optional(330)" /// /// If you assign `nil` as the value for the given key, the dictionary /// removes that key and its associated value. /// /// In the following example, the key-value pair for the key `"Aquamarine"` /// is removed from the dictionary by assigning `nil` to the key-based /// subscript. /// /// hues["Aquamarine"] = nil /// print(hues) /// // Prints "["Coral": 18, "Heliotrope": 296, "Cerise": 330]" /// /// - Parameter key: The key to find in the dictionary. /// - Returns: The value associated with `key` if `key` is in the dictionary; /// otherwise, `nil`. @inlinable public subscript(key: Key) -> Value? { @inline(__always) get { return _variant.lookup(key) } set(newValue) { if let x = newValue { _variant.setValue(x, forKey: key) } else { removeValue(forKey: key) } } _modify { // FIXME: This code should be moved to _variant, with Dictionary.subscript // yielding `&_variant[key]`. let (bucket, found) = _variant.mutatingFind(key) // FIXME: Mark this entry as being modified in hash table metadata // so that lldb can recognize it's not valid. // Move the old value (if any) out of storage, wrapping it into an // optional before yielding it. let native = _variant.asNative var value: Value? if found { value = (native._values + bucket.offset).move() } else { value = nil } yield &value // Value is now potentially different. Check which one of the four // possible cases apply. switch (value, found) { case (let value?, true): // Mutation // Initialize storage to new value. (native._values + bucket.offset).initialize(to: value) case (let value?, false): // Insertion // Insert the new entry at the correct place. // We've already ensured we have enough capacity. native._insert(at: bucket, key: key, value: value) case (nil, true): // Removal // We've already removed the value; deinitialize and remove the key too. (native._values + bucket.offset).deinitialize(count: 1) native._delete(at: bucket) case (nil, false): // Noop // Easy! break } _fixLifetime(self) } } } extension Dictionary: ExpressibleByDictionaryLiteral { /// Creates a dictionary initialized with a dictionary literal. /// /// Do not call this initializer directly. It is called by the compiler to /// handle dictionary literals. To use a dictionary literal as the initial /// value of a dictionary, enclose a comma-separated list of key-value pairs /// in square brackets. /// /// For example, the code sample below creates a dictionary with string keys /// and values. /// /// let countryCodes = ["BR": "Brazil", "GH": "Ghana", "JP": "Japan"] /// print(countryCodes) /// // Prints "["BR": "Brazil", "JP": "Japan", "GH": "Ghana"]" /// /// - Parameter elements: The key-value pairs that will make up the new /// dictionary. Each key in `elements` must be unique. @inlinable @_effects(readonly) public init(dictionaryLiteral elements: (Key, Value)...) { let native = _NativeDictionary<Key, Value>(capacity: elements.count) for (key, value) in elements { let (bucket, found) = native.find(key) _precondition(!found, "Dictionary literal contains duplicate keys") native._insert(at: bucket, key: key, value: value) } self.init(_native: native) } } extension Dictionary { /// Accesses the value with the given key. If the dictionary doesn't contain /// the given key, accesses the provided default value as if the key and /// default value existed in the dictionary. /// /// Use this subscript when you want either the value for a particular key /// or, when that key is not present in the dictionary, a default value. This /// example uses the subscript with a message to use in case an HTTP response /// code isn't recognized: /// /// var responseMessages = [200: "OK", /// 403: "Access forbidden", /// 404: "File not found", /// 500: "Internal server error"] /// /// let httpResponseCodes = [200, 403, 301] /// for code in httpResponseCodes { /// let message = responseMessages[code, default: "Unknown response"] /// print("Response \(code): \(message)") /// } /// // Prints "Response 200: OK" /// // Prints "Response 403: Access Forbidden" /// // Prints "Response 301: Unknown response" /// /// When a dictionary's `Value` type has value semantics, you can use this /// subscript to perform in-place operations on values in the dictionary. /// The following example uses this subscript while counting the occurences /// of each letter in a string: /// /// let message = "Hello, Elle!" /// var letterCounts: [Character: Int] = [:] /// for letter in message { /// letterCounts[letter, defaultValue: 0] += 1 /// } /// // letterCounts == ["H": 1, "e": 2, "l": 4, "o": 1, ...] /// /// When `letterCounts[letter, defaultValue: 0] += 1` is executed with a /// value of `letter` that isn't already a key in `letterCounts`, the /// specified default value (`0`) is returned from the subscript, /// incremented, and then added to the dictionary under that key. /// /// - Note: Do not use this subscript to modify dictionary values if the /// dictionary's `Value` type is a class. In that case, the default value /// and key are not written back to the dictionary after an operation. /// /// - Parameters: /// - key: The key the look up in the dictionary. /// - defaultValue: The default value to use if `key` doesn't exist in the /// dictionary. /// - Returns: The value associated with `key` in the dictionary`; otherwise, /// `defaultValue`. @inlinable public subscript( key: Key, default defaultValue: @autoclosure () -> Value ) -> Value { @inline(__always) get { return _variant.lookup(key) ?? defaultValue() } @inline(__always) _modify { let (bucket, found) = _variant.mutatingFind(key) let native = _variant.asNative if !found { let value = defaultValue() native._insert(at: bucket, key: key, value: value) } let address = native._values + bucket.offset yield &address.pointee _fixLifetime(self) } } /// Returns a new dictionary containing the keys of this dictionary with the /// values transformed by the given closure. /// /// - Parameter transform: A closure that transforms a value. `transform` /// accepts each value of the dictionary as its parameter and returns a /// transformed value of the same or of a different type. /// - Returns: A dictionary containing the keys and transformed values of /// this dictionary. /// /// - Complexity: O(*n*), where *n* is the length of the dictionary. @inlinable public func mapValues<T>( _ transform: (Value) throws -> T ) rethrows -> Dictionary<Key, T> { return try Dictionary<Key, T>(_native: _variant.mapValues(transform)) } /// Returns a new dictionary containing only the key-value pairs that have /// non-`nil` values as the result from the transform by the given closure. /// /// Use this method to receive a dictionary of nonoptional values when your /// transformation can produce an optional value. /// /// In this example, note the difference in the result of using `mapValues` /// and `compactMapValues` with a transformation that returns an optional /// `Int` value. /// /// let data = ["a": "1", "b": "three", "c": "///4///"] /// /// let m: [String: Int?] = data.mapValues { str in Int(str) } /// // ["a": 1, "b": nil, "c": nil] /// /// let c: [String: Int] = data.compactMapValues { str in Int(str) } /// // ["a": 1] /// /// - Parameter transform: A closure that transforms a value. `transform` /// accepts each value of the dictionary as its parameter and returns an /// optional transformed value of the same or of a different type. /// - Returns: A dictionary containing the keys and non-`nil` transformed /// values of this dictionary. /// /// - Complexity: O(*m* + *n*), where *n* is the length of the original /// dictionary and *m* is the length of the resulting dictionary. @inlinable public func compactMapValues<T>( _ transform: (Value) throws -> T? ) rethrows -> Dictionary<Key, T> { let result: _NativeDictionary<Key, T> = try self.reduce(into: _NativeDictionary<Key, T>()) { (result, element) in if let value = try transform(element.value) { result.insertNew(key: element.key, value: value) } } return Dictionary<Key, T>(_native: result) } /// Updates the value stored in the dictionary for the given key, or adds a /// new key-value pair if the key does not exist. /// /// Use this method instead of key-based subscripting when you need to know /// whether the new value supplants the value of an existing key. If the /// value of an existing key is updated, `updateValue(_:forKey:)` returns /// the original value. /// /// var hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156] /// /// if let oldValue = hues.updateValue(18, forKey: "Coral") { /// print("The old value of \(oldValue) was replaced with a new one.") /// } /// // Prints "The old value of 16 was replaced with a new one." /// /// If the given key is not present in the dictionary, this method adds the /// key-value pair and returns `nil`. /// /// if let oldValue = hues.updateValue(330, forKey: "Cerise") { /// print("The old value of \(oldValue) was replaced with a new one.") /// } else { /// print("No value was found in the dictionary for that key.") /// } /// // Prints "No value was found in the dictionary for that key." /// /// - Parameters: /// - value: The new value to add to the dictionary. /// - key: The key to associate with `value`. If `key` already exists in /// the dictionary, `value` replaces the existing associated value. If /// `key` isn't already a key of the dictionary, the `(key, value)` pair /// is added. /// - Returns: The value that was replaced, or `nil` if a new key-value pair /// was added. @inlinable @discardableResult public mutating func updateValue( _ value: __owned Value, forKey key: Key ) -> Value? { return _variant.updateValue(value, forKey: key) } /// Merges the key-value pairs in the given sequence into the dictionary, /// using a combining closure to determine the value for any duplicate keys. /// /// Use the `combine` closure to select a value to use in the updated /// dictionary, or to combine existing and new values. As the key-value /// pairs are merged with the dictionary, the `combine` closure is called /// with the current and new values for any duplicate keys that are /// encountered. /// /// This example shows how to choose the current or new values for any /// duplicate keys: /// /// var dictionary = ["a": 1, "b": 2] /// /// // Keeping existing value for key "a": /// dictionary.merge(zip(["a", "c"], [3, 4])) { (current, _) in current } /// // ["b": 2, "a": 1, "c": 4] /// /// // Taking the new value for key "a": /// dictionary.merge(zip(["a", "d"], [5, 6])) { (_, new) in new } /// // ["b": 2, "a": 5, "c": 4, "d": 6] /// /// - Parameters: /// - other: A sequence of key-value pairs. /// - combine: A closure that takes the current and new values for any /// duplicate keys. The closure returns the desired value for the final /// dictionary. @inlinable public mutating func merge<S: Sequence>( _ other: __owned S, uniquingKeysWith combine: (Value, Value) throws -> Value ) rethrows where S.Element == (Key, Value) { try _variant.merge(other, uniquingKeysWith: combine) } /// Merges the given dictionary into this dictionary, using a combining /// closure to determine the value for any duplicate keys. /// /// Use the `combine` closure to select a value to use in the updated /// dictionary, or to combine existing and new values. As the key-values /// pairs in `other` are merged with this dictionary, the `combine` closure /// is called with the current and new values for any duplicate keys that /// are encountered. /// /// This example shows how to choose the current or new values for any /// duplicate keys: /// /// var dictionary = ["a": 1, "b": 2] /// /// // Keeping existing value for key "a": /// dictionary.merge(["a": 3, "c": 4]) { (current, _) in current } /// // ["b": 2, "a": 1, "c": 4] /// /// // Taking the new value for key "a": /// dictionary.merge(["a": 5, "d": 6]) { (_, new) in new } /// // ["b": 2, "a": 5, "c": 4, "d": 6] /// /// - Parameters: /// - other: A dictionary to merge. /// - combine: A closure that takes the current and new values for any /// duplicate keys. The closure returns the desired value for the final /// dictionary. @inlinable public mutating func merge( _ other: __owned [Key: Value], uniquingKeysWith combine: (Value, Value) throws -> Value ) rethrows { try _variant.merge( other.lazy.map { ($0, $1) }, uniquingKeysWith: combine) } /// Creates a dictionary by merging key-value pairs in a sequence into the /// dictionary, using a combining closure to determine the value for /// duplicate keys. /// /// Use the `combine` closure to select a value to use in the returned /// dictionary, or to combine existing and new values. As the key-value /// pairs are merged with the dictionary, the `combine` closure is called /// with the current and new values for any duplicate keys that are /// encountered. /// /// This example shows how to choose the current or new values for any /// duplicate keys: /// /// let dictionary = ["a": 1, "b": 2] /// let newKeyValues = zip(["a", "b"], [3, 4]) /// /// let keepingCurrent = dictionary.merging(newKeyValues) { (current, _) in current } /// // ["b": 2, "a": 1] /// let replacingCurrent = dictionary.merging(newKeyValues) { (_, new) in new } /// // ["b": 4, "a": 3] /// /// - Parameters: /// - other: A sequence of key-value pairs. /// - combine: A closure that takes the current and new values for any /// duplicate keys. The closure returns the desired value for the final /// dictionary. /// - Returns: A new dictionary with the combined keys and values of this /// dictionary and `other`. @inlinable public __consuming func merging<S: Sequence>( _ other: __owned S, uniquingKeysWith combine: (Value, Value) throws -> Value ) rethrows -> [Key: Value] where S.Element == (Key, Value) { var result = self try result._variant.merge(other, uniquingKeysWith: combine) return result } /// Creates a dictionary by merging the given dictionary into this /// dictionary, using a combining closure to determine the value for /// duplicate keys. /// /// Use the `combine` closure to select a value to use in the returned /// dictionary, or to combine existing and new values. As the key-value /// pairs in `other` are merged with this dictionary, the `combine` closure /// is called with the current and new values for any duplicate keys that /// are encountered. /// /// This example shows how to choose the current or new values for any /// duplicate keys: /// /// let dictionary = ["a": 1, "b": 2] /// let otherDictionary = ["a": 3, "b": 4] /// /// let keepingCurrent = dictionary.merging(otherDictionary) /// { (current, _) in current } /// // ["b": 2, "a": 1] /// let replacingCurrent = dictionary.merging(otherDictionary) /// { (_, new) in new } /// // ["b": 4, "a": 3] /// /// - Parameters: /// - other: A dictionary to merge. /// - combine: A closure that takes the current and new values for any /// duplicate keys. The closure returns the desired value for the final /// dictionary. /// - Returns: A new dictionary with the combined keys and values of this /// dictionary and `other`. @inlinable public __consuming func merging( _ other: __owned [Key: Value], uniquingKeysWith combine: (Value, Value) throws -> Value ) rethrows -> [Key: Value] { var result = self try result.merge(other, uniquingKeysWith: combine) return result } /// Removes and returns the key-value pair at the specified index. /// /// Calling this method invalidates any existing indices for use with this /// dictionary. /// /// - Parameter index: The position of the key-value pair to remove. `index` /// must be a valid index of the dictionary, and must not equal the /// dictionary's end index. /// - Returns: The key-value pair that correspond to `index`. /// /// - Complexity: O(*n*), where *n* is the number of key-value pairs in the /// dictionary. @inlinable @discardableResult public mutating func remove(at index: Index) -> Element { return _variant.remove(at: index) } /// Removes the given key and its associated value from the dictionary. /// /// If the key is found in the dictionary, this method returns the key's /// associated value. On removal, this method invalidates all indices with /// respect to the dictionary. /// /// var hues = ["Heliotrope": 296, "Coral": 16, "Aquamarine": 156] /// if let value = hues.removeValue(forKey: "Coral") { /// print("The value \(value) was removed.") /// } /// // Prints "The value 16 was removed." /// /// If the key isn't found in the dictionary, `removeValue(forKey:)` returns /// `nil`. /// /// if let value = hues.removeValueForKey("Cerise") { /// print("The value \(value) was removed.") /// } else { /// print("No value found for that key.") /// } /// // Prints "No value found for that key."" /// /// - Parameter key: The key to remove along with its associated value. /// - Returns: The value that was removed, or `nil` if the key was not /// present in the dictionary. /// /// - Complexity: O(*n*), where *n* is the number of key-value pairs in the /// dictionary. @inlinable @discardableResult public mutating func removeValue(forKey key: Key) -> Value? { return _variant.removeValue(forKey: key) } /// Removes all key-value pairs from the dictionary. /// /// Calling this method invalidates all indices with respect to the /// dictionary. /// /// - Parameter keepCapacity: Whether the dictionary should keep its /// underlying buffer. If you pass `true`, the operation preserves the /// buffer capacity that the collection has, otherwise the underlying /// buffer is released. The default is `false`. /// /// - Complexity: O(*n*), where *n* is the number of key-value pairs in the /// dictionary. @inlinable public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) { // The 'will not decrease' part in the documentation comment is worded very // carefully. The capacity can increase if we replace Cocoa dictionary with // native dictionary. _variant.removeAll(keepingCapacity: keepCapacity) } } extension Dictionary { /// A collection containing just the keys of the dictionary. /// /// When iterated over, keys appear in this collection in the same order as /// they occur in the dictionary's key-value pairs. Each key in the keys /// collection has a unique value. /// /// let countryCodes = ["BR": "Brazil", "GH": "Ghana", "JP": "Japan"] /// print(countryCodes) /// // Prints "["BR": "Brazil", "JP": "Japan", "GH": "Ghana"]" /// /// for k in countryCodes.keys { /// print(k) /// } /// // Prints "BR" /// // Prints "JP" /// // Prints "GH" @inlinable @available(swift, introduced: 4.0) public var keys: Keys { // FIXME(accessors): Provide a _read get { return Keys(_dictionary: self) } } /// A collection containing just the values of the dictionary. /// /// When iterated over, values appear in this collection in the same order as /// they occur in the dictionary's key-value pairs. /// /// let countryCodes = ["BR": "Brazil", "GH": "Ghana", "JP": "Japan"] /// print(countryCodes) /// // Prints "["BR": "Brazil", "JP": "Japan", "GH": "Ghana"]" /// /// for v in countryCodes.values { /// print(v) /// } /// // Prints "Brazil" /// // Prints "Japan" /// // Prints "Ghana" @inlinable @available(swift, introduced: 4.0) public var values: Values { // FIXME(accessors): Provide a _read get { return Values(_dictionary: self) } _modify { var values: Values do { var temp = _Variant(dummy: ()) swap(&temp, &_variant) values = Values(_variant: temp) } yield &values self._variant = values._variant } } /// A view of a dictionary's keys. @_fixed_layout public struct Keys : Collection, Equatable, CustomStringConvertible, CustomDebugStringConvertible { public typealias Element = Key @usableFromInline internal var _variant: Dictionary<Key, Value>._Variant @inlinable internal init(_dictionary: __owned Dictionary) { self._variant = _dictionary._variant } // Collection Conformance // ---------------------- @inlinable public var startIndex: Index { return _variant.startIndex } @inlinable public var endIndex: Index { return _variant.endIndex } @inlinable public func index(after i: Index) -> Index { return _variant.index(after: i) } @inlinable public func formIndex(after i: inout Index) { _variant.formIndex(after: &i) } @inlinable public subscript(position: Index) -> Element { return _variant.key(at: position) } // Customization // ------------- /// The number of keys in the dictionary. /// /// - Complexity: O(1). @inlinable public var count: Int { return _variant.count } @inlinable public var isEmpty: Bool { return count == 0 } @inlinable @inline(__always) public func _customContainsEquatableElement(_ element: Element) -> Bool? { return _variant.contains(element) } @inlinable @inline(__always) public func _customIndexOfEquatableElement(_ element: Element) -> Index?? { return Optional(_variant.index(forKey: element)) } @inlinable @inline(__always) public func _customLastIndexOfEquatableElement(_ element: Element) -> Index?? { // The first and last elements are the same because each element is unique. return _customIndexOfEquatableElement(element) } @inlinable public static func ==(lhs: Keys, rhs: Keys) -> Bool { // Equal if the two dictionaries share storage. #if _runtime(_ObjC) if lhs._variant.isNative, rhs._variant.isNative, lhs._variant.asNative._storage === rhs._variant.asNative._storage { return true } if !lhs._variant.isNative, !rhs._variant.isNative, lhs._variant.asCocoa.object === rhs._variant.asCocoa.object { return true } #else if lhs._variant.asNative._storage === rhs._variant.asNative._storage { return true } #endif // Not equal if the dictionaries are different sizes. if lhs.count != rhs.count { return false } // Perform unordered comparison of keys. for key in lhs { if !rhs.contains(key) { return false } } return true } public var description: String { return _makeCollectionDescription() } public var debugDescription: String { return _makeCollectionDescription(withTypeName: "Dictionary.Keys") } } /// A view of a dictionary's values. @_fixed_layout public struct Values : MutableCollection, CustomStringConvertible, CustomDebugStringConvertible { public typealias Element = Value @usableFromInline internal var _variant: Dictionary<Key, Value>._Variant @inlinable internal init(_variant: __owned Dictionary<Key, Value>._Variant) { self._variant = _variant } @inlinable internal init(_dictionary: __owned Dictionary) { self._variant = _dictionary._variant } // Collection Conformance // ---------------------- @inlinable public var startIndex: Index { return _variant.startIndex } @inlinable public var endIndex: Index { return _variant.endIndex } @inlinable public func index(after i: Index) -> Index { return _variant.index(after: i) } @inlinable public func formIndex(after i: inout Index) { _variant.formIndex(after: &i) } @inlinable public subscript(position: Index) -> Element { // FIXME(accessors): Provide a _read get { return _variant.value(at: position) } _modify { let native = _variant.ensureUniqueNative() let bucket = native.validatedBucket(for: position) let address = native._values + bucket.offset yield &address.pointee _fixLifetime(self) } } // Customization // ------------- /// The number of values in the dictionary. /// /// - Complexity: O(1). @inlinable public var count: Int { return _variant.count } @inlinable public var isEmpty: Bool { return count == 0 } public var description: String { return _makeCollectionDescription() } public var debugDescription: String { return _makeCollectionDescription(withTypeName: "Dictionary.Values") } @inlinable public mutating func swapAt(_ i: Index, _ j: Index) { guard i != j else { return } #if _runtime(_ObjC) if !_variant.isNative { _variant = .init(native: _NativeDictionary(_variant.asCocoa)) } #endif let isUnique = _variant.isUniquelyReferenced() let native = _variant.asNative let a = native.validatedBucket(for: i) let b = native.validatedBucket(for: j) _variant.asNative.swapValuesAt(a, b, isUnique: isUnique) } } } extension Dictionary.Keys { @_fixed_layout public struct Iterator: IteratorProtocol { @usableFromInline internal var _base: Dictionary<Key, Value>.Iterator @inlinable @inline(__always) internal init(_ base: Dictionary<Key, Value>.Iterator) { self._base = base } @inlinable @inline(__always) public mutating func next() -> Key? { #if _runtime(_ObjC) if case .cocoa(let cocoa) = _base._variant { _base._cocoaPath() guard let cocoaKey = cocoa.nextKey() else { return nil } return _forceBridgeFromObjectiveC(cocoaKey, Key.self) } #endif return _base._asNative.nextKey() } } @inlinable @inline(__always) public __consuming func makeIterator() -> Iterator { return Iterator(_variant.makeIterator()) } } extension Dictionary.Values { @_fixed_layout public struct Iterator: IteratorProtocol { @usableFromInline internal var _base: Dictionary<Key, Value>.Iterator @inlinable @inline(__always) internal init(_ base: Dictionary<Key, Value>.Iterator) { self._base = base } @inlinable @inline(__always) public mutating func next() -> Value? { #if _runtime(_ObjC) if case .cocoa(let cocoa) = _base._variant { _base._cocoaPath() guard let (_, cocoaValue) = cocoa.next() else { return nil } return _forceBridgeFromObjectiveC(cocoaValue, Value.self) } #endif return _base._asNative.nextValue() } } @inlinable @inline(__always) public __consuming func makeIterator() -> Iterator { return Iterator(_variant.makeIterator()) } } extension Dictionary: Equatable where Value: Equatable { @inlinable public static func == (lhs: [Key: Value], rhs: [Key: Value]) -> Bool { #if _runtime(_ObjC) switch (lhs._variant.isNative, rhs._variant.isNative) { case (true, true): return lhs._variant.asNative.isEqual(to: rhs._variant.asNative) case (false, false): return lhs._variant.asCocoa.isEqual(to: rhs._variant.asCocoa) case (true, false): return lhs._variant.asNative.isEqual(to: rhs._variant.asCocoa) case (false, true): return rhs._variant.asNative.isEqual(to: lhs._variant.asCocoa) } #else return lhs._variant.asNative.isEqual(to: rhs._variant.asNative) #endif } } extension Dictionary: Hashable where Value: Hashable { /// Hashes the essential components of this value by feeding them into the /// given hasher. /// /// - Parameter hasher: The hasher to use when combining the components /// of this instance. @inlinable public func hash(into hasher: inout Hasher) { var commutativeHash = 0 for (k, v) in self { // Note that we use a copy of our own hasher here. This makes hash values // dependent on its state, eliminating static collision patterns. var elementHasher = hasher elementHasher.combine(k) elementHasher.combine(v) commutativeHash ^= elementHasher._finalize() } hasher.combine(commutativeHash) } } extension Dictionary: _HasCustomAnyHashableRepresentation where Value: Hashable { public __consuming func _toCustomAnyHashable() -> AnyHashable? { return AnyHashable(_box: _DictionaryAnyHashableBox(self)) } } internal struct _DictionaryAnyHashableBox<Key: Hashable, Value: Hashable> : _AnyHashableBox { internal let _value: Dictionary<Key, Value> internal let _canonical: Dictionary<AnyHashable, AnyHashable> internal init(_ value: __owned Dictionary<Key, Value>) { self._value = value self._canonical = value as Dictionary<AnyHashable, AnyHashable> } internal var _base: Any { return _value } internal var _canonicalBox: _AnyHashableBox { return _DictionaryAnyHashableBox<AnyHashable, AnyHashable>(_canonical) } internal func _isEqual(to other: _AnyHashableBox) -> Bool? { guard let other = other as? _DictionaryAnyHashableBox<AnyHashable, AnyHashable> else { return nil } return _canonical == other._value } internal var _hashValue: Int { return _canonical.hashValue } internal func _hash(into hasher: inout Hasher) { _canonical.hash(into: &hasher) } internal func _rawHashValue(_seed: Int) -> Int { return _canonical._rawHashValue(seed: _seed) } internal func _unbox<T: Hashable>() -> T? { return _value as? T } internal func _downCastConditional<T>( into result: UnsafeMutablePointer<T> ) -> Bool { guard let value = _value as? T else { return false } result.initialize(to: value) return true } } extension Collection { // Utility method for KV collections that wish to implement // CustomStringConvertible and CustomDebugStringConvertible using a bracketed // list of elements. // FIXME: Doesn't use the withTypeName argument yet internal func _makeKeyValuePairDescription<K, V>( withTypeName type: String? = nil ) -> String where Element == (key: K, value: V) { if self.count == 0 { return "[:]" } var result = "[" var first = true for (k, v) in self { if first { first = false } else { result += ", " } debugPrint(k, terminator: "", to: &result) result += ": " debugPrint(v, terminator: "", to: &result) } result += "]" return result } } extension Dictionary: CustomStringConvertible, CustomDebugStringConvertible { /// A string that represents the contents of the dictionary. public var description: String { return _makeKeyValuePairDescription() } /// A string that represents the contents of the dictionary, suitable for /// debugging. public var debugDescription: String { return _makeKeyValuePairDescription() } } @usableFromInline @_frozen internal enum _MergeError: Error { case keyCollision } extension Dictionary { /// The position of a key-value pair in a dictionary. /// /// Dictionary has two subscripting interfaces: /// /// 1. Subscripting with a key, yielding an optional value: /// /// v = d[k]! /// /// 2. Subscripting with an index, yielding a key-value pair: /// /// (k, v) = d[i] @_fixed_layout public struct Index { // Index for native dictionary is efficient. Index for bridged NSDictionary // is not, because neither NSEnumerator nor fast enumeration support moving // backwards. Even if they did, there is another issue: NSEnumerator does // not support NSCopying, and fast enumeration does not document that it is // safe to copy the state. So, we cannot implement Index that is a value // type for bridged NSDictionary in terms of Cocoa enumeration facilities. @_frozen @usableFromInline internal enum _Variant { case native(_HashTable.Index) #if _runtime(_ObjC) case cocoa(_CocoaDictionary.Index) #endif } @usableFromInline internal var _variant: _Variant @inlinable @inline(__always) internal init(_variant: __owned _Variant) { self._variant = _variant } @inlinable @inline(__always) internal init(_native index: _HashTable.Index) { self.init(_variant: .native(index)) } #if _runtime(_ObjC) @inlinable @inline(__always) internal init(_cocoa index: __owned _CocoaDictionary.Index) { self.init(_variant: .cocoa(index)) } #endif } } extension Dictionary.Index { #if _runtime(_ObjC) @usableFromInline @_transparent internal var _guaranteedNative: Bool { return _canBeClass(Key.self) == 0 || _canBeClass(Value.self) == 0 } // Allow the optimizer to consider the surrounding code unreachable if Element // is guaranteed to be native. @usableFromInline @_transparent internal func _cocoaPath() { if _guaranteedNative { _conditionallyUnreachable() } } @inlinable @inline(__always) internal mutating func _isUniquelyReferenced() -> Bool { defer { _fixLifetime(self) } var handle = _asCocoa.handleBitPattern return handle == 0 || _isUnique_native(&handle) } @usableFromInline @_transparent internal var _isNative: Bool { switch _variant { case .native: return true case .cocoa: _cocoaPath() return false } } #endif @usableFromInline @_transparent internal var _asNative: _HashTable.Index { switch _variant { case .native(let nativeIndex): return nativeIndex #if _runtime(_ObjC) case .cocoa: _preconditionFailure( "Attempting to access Dictionary elements using an invalid index") #endif } } #if _runtime(_ObjC) @usableFromInline internal var _asCocoa: _CocoaDictionary.Index { @_transparent get { switch _variant { case .native: _preconditionFailure( "Attempting to access Dictionary elements using an invalid index") case .cocoa(let cocoaIndex): return cocoaIndex } } _modify { guard case .cocoa(var cocoa) = _variant else { _preconditionFailure( "Attempting to access Dictionary elements using an invalid index") } let dummy = _HashTable.Index(bucket: _HashTable.Bucket(offset: 0), age: 0) _variant = .native(dummy) yield &cocoa _variant = .cocoa(cocoa) } } #endif } extension Dictionary.Index: Equatable { @inlinable public static func == ( lhs: Dictionary<Key, Value>.Index, rhs: Dictionary<Key, Value>.Index ) -> Bool { switch (lhs._variant, rhs._variant) { case (.native(let lhsNative), .native(let rhsNative)): return lhsNative == rhsNative #if _runtime(_ObjC) case (.cocoa(let lhsCocoa), .cocoa(let rhsCocoa)): lhs._cocoaPath() return lhsCocoa == rhsCocoa default: _preconditionFailure("Comparing indexes from different dictionaries") #endif } } } extension Dictionary.Index: Comparable { @inlinable public static func < ( lhs: Dictionary<Key, Value>.Index, rhs: Dictionary<Key, Value>.Index ) -> Bool { switch (lhs._variant, rhs._variant) { case (.native(let lhsNative), .native(let rhsNative)): return lhsNative < rhsNative #if _runtime(_ObjC) case (.cocoa(let lhsCocoa), .cocoa(let rhsCocoa)): lhs._cocoaPath() return lhsCocoa < rhsCocoa default: _preconditionFailure("Comparing indexes from different dictionaries") #endif } } } extension Dictionary.Index: Hashable { public // FIXME(cocoa-index): Make inlinable func hash(into hasher: inout Hasher) { #if _runtime(_ObjC) guard _isNative else { hasher.combine(1 as UInt8) hasher.combine(_asCocoa.storage.currentKeyIndex) return } hasher.combine(0 as UInt8) hasher.combine(_asNative.bucket.offset) #else hasher.combine(_asNative.bucket.offset) #endif } } extension Dictionary { /// An iterator over the members of a `Dictionary<Key, Value>`. @_fixed_layout public struct Iterator { // Dictionary has a separate IteratorProtocol and Index because of // efficiency and implementability reasons. // // Native dictionaries have efficient indices. // Bridged NSDictionary instances don't. // // Even though fast enumeration is not suitable for implementing // Index, which is multi-pass, it is suitable for implementing a // IteratorProtocol, which is being consumed as iteration proceeds. @usableFromInline @_frozen internal enum _Variant { case native(_NativeDictionary<Key, Value>.Iterator) #if _runtime(_ObjC) case cocoa(_CocoaDictionary.Iterator) #endif } @usableFromInline internal var _variant: _Variant @inlinable internal init(_variant: __owned _Variant) { self._variant = _variant } @inlinable internal init(_native: __owned _NativeDictionary<Key, Value>.Iterator) { self.init(_variant: .native(_native)) } #if _runtime(_ObjC) @inlinable internal init(_cocoa: __owned _CocoaDictionary.Iterator) { self.init(_variant: .cocoa(_cocoa)) } #endif } } extension Dictionary.Iterator { #if _runtime(_ObjC) @usableFromInline @_transparent internal var _guaranteedNative: Bool { return _canBeClass(Key.self) == 0 || _canBeClass(Value.self) == 0 } /// Allow the optimizer to consider the surrounding code unreachable if /// Dictionary<Key, Value> is guaranteed to be native. @usableFromInline @_transparent internal func _cocoaPath() { if _guaranteedNative { _conditionallyUnreachable() } } @usableFromInline @_transparent internal var _isNative: Bool { switch _variant { case .native: return true case .cocoa: _cocoaPath() return false } } #endif @usableFromInline @_transparent internal var _asNative: _NativeDictionary<Key, Value>.Iterator { get { switch _variant { case .native(let nativeIterator): return nativeIterator #if _runtime(_ObjC) case .cocoa: _sanityCheckFailure("internal error: does not contain a native index") #endif } } set { self._variant = .native(newValue) } } #if _runtime(_ObjC) @usableFromInline @_transparent internal var _asCocoa: _CocoaDictionary.Iterator { get { switch _variant { case .native: _sanityCheckFailure("internal error: does not contain a Cocoa index") case .cocoa(let cocoa): return cocoa } } } #endif } extension Dictionary.Iterator: IteratorProtocol { /// Advances to the next element and returns it, or `nil` if no next element /// exists. /// /// Once `nil` has been returned, all subsequent calls return `nil`. @inlinable @inline(__always) public mutating func next() -> (key: Key, value: Value)? { #if _runtime(_ObjC) guard _isNative else { if let (cocoaKey, cocoaValue) = _asCocoa.next() { let nativeKey = _forceBridgeFromObjectiveC(cocoaKey, Key.self) let nativeValue = _forceBridgeFromObjectiveC(cocoaValue, Value.self) return (nativeKey, nativeValue) } return nil } #endif return _asNative.next() } } extension Dictionary.Iterator: CustomReflectable { /// A mirror that reflects the iterator. public var customMirror: Mirror { return Mirror( self, children: EmptyCollection<(label: String?, value: Any)>()) } } extension Dictionary: CustomReflectable { /// A mirror that reflects the dictionary. public var customMirror: Mirror { let style = Mirror.DisplayStyle.dictionary return Mirror(self, unlabeledChildren: self, displayStyle: style) } } extension Dictionary { /// Removes and returns the first key-value pair of the dictionary if the /// dictionary isn't empty. /// /// The first element of the dictionary is not necessarily the first element /// added. Don't expect any particular ordering of key-value pairs. /// /// - Returns: The first key-value pair of the dictionary if the dictionary /// is not empty; otherwise, `nil`. /// /// - Complexity: Averages to O(1) over many calls to `popFirst()`. @inlinable public mutating func popFirst() -> Element? { guard !isEmpty else { return nil } return remove(at: startIndex) } /// The total number of key-value pairs that the dictionary can contain without /// allocating new storage. @inlinable public var capacity: Int { return _variant.capacity } /// Reserves enough space to store the specified number of key-value pairs. /// /// If you are adding a known number of key-value pairs to a dictionary, use this /// method to avoid multiple reallocations. This method ensures that the /// dictionary has unique, mutable, contiguous storage, with space allocated /// for at least the requested number of key-value pairs. /// /// Calling the `reserveCapacity(_:)` method on a dictionary with bridged /// storage triggers a copy to contiguous storage even if the existing /// storage has room to store `minimumCapacity` key-value pairs. /// /// - Parameter minimumCapacity: The requested number of key-value pairs to /// store. public // FIXME(reserveCapacity): Should be inlinable mutating func reserveCapacity(_ minimumCapacity: Int) { _variant.reserveCapacity(minimumCapacity) _sanityCheck(self.capacity >= minimumCapacity) } } public typealias DictionaryIndex<Key: Hashable, Value> = Dictionary<Key, Value>.Index public typealias DictionaryIterator<Key: Hashable, Value> = Dictionary<Key, Value>.Iterator
apache-2.0
e5b4096aefb4d99493d140d08253882f
34.197858
126
0.630739
4.247711
false
false
false
false
Produkt/Pelican
src/Pelican.swift
1
3302
// // Pelican.swift // Pelican // // Created by Daniel Garcia on 06/12/2016. // Copyright © 2016 Produkt Studio. All rights reserved. // import Result public enum PelicanFormat: String { case ZIP case RAR } public enum PelicanType: String { case packer case unpacker } open class Pelican { open static func zipUnpacker(operationQueue: OperationQueue? = nil) -> ZipUnpacker { return ZipUnpacker(operationQueue: operationQueue ?? buildOperationQueue(type: .unpacker, format: .ZIP)) } open static func zipPacker(operationQueue: OperationQueue? = nil) -> ZipPacker { return ZipPacker(operationQueue: operationQueue ?? buildOperationQueue(type: .packer, format: .ZIP)) } open static func rarUnpacker(operationQueue: OperationQueue? = nil) -> RarUnpacker { return RarUnpacker(operationQueue: operationQueue ?? buildOperationQueue(type: .unpacker, format: .RAR)) } private static func buildOperationQueue(type: PelicanType, format: PelicanFormat) -> OperationQueue { let operationQueue = OperationQueue() operationQueue.name = "com.pelican.\(type.rawValue)-\(format.rawValue)-\(Date().timeIntervalSince1970)" return operationQueue } } // MARK: Packing public struct PackError: Error { } public typealias PackTaskCompletion = (Result<Void, PackError>) -> Void public protocol Packer { @discardableResult func pack(files filePaths: [String], in filePath: String, completion: @escaping PackTaskCompletion) -> PackTask } public protocol PackTask { func cancel() } // MARK: Unpacking public struct UnpackError: Error { let underlyingError: Error? init(underlyingError: Error? = nil) { self.underlyingError = underlyingError } } public struct UnpackContentSummary { public let startDate: Date public let finishDate: Date public let unpackedFiles: [FileInfo] } public typealias UnpackContentResult = Result<UnpackContentSummary, UnpackError> public typealias UnpackContentTaskCompletion = (UnpackContentResult) -> Void public typealias UnpackFileResult = Result<Data, UnpackError> public typealias UnpackFileTaskCompletion = (UnpackFileResult) -> Void public protocol Unpacker { associatedtype FileInfoType typealias ContentInfoResult = Result<[FileInfoType], UnpackError> typealias ContentInfoCompletion = (ContentInfoResult) -> Void @discardableResult func unpack(fileAt filePath: String, in destinationPath: String, completion: @escaping UnpackContentTaskCompletion) -> UnpackTask @discardableResult func unpack(fileAt filePath: String, in destinationPath: String) -> UnpackContentResult @discardableResult func unpack(fileWith fileInfo: FileInfoType, from filePath: String, completion: @escaping UnpackFileTaskCompletion) -> UnpackTask func unpack(fileWith fileInfo: FileInfoType, from filePath: String) -> UnpackFileResult @discardableResult func contentInfo(in filePath: String, completion: @escaping ContentInfoCompletion) -> UnpackTask func contentInfo(in filePath: String) -> ContentInfoResult } public protocol UnpackTask { func cancel() } // MARK: File Info public protocol FileInfo { var fileName: String { get } var fileCRC: UInt { get } var index: UInt { get } }
gpl-3.0
d79c8374d5389ad06a9354fdfb6689af
29.284404
133
0.737352
4.366402
false
false
false
false
apple/swift-experimental-string-processing
Tests/Prototypes/PEG/PEGVMExecute.swift
1
1285
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2021-2022 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // //===----------------------------------------------------------------------===// extension PEG.VM { // TODO: Consumers need a concept of forward progress. // They can return `nil` and `startIndex`, both which may // have the same effect for many API, but others might wish // to differentiate it. We should think through this issue // and likely make forward progress a more established // concept. func consume(_ input: Input) -> Input.Index? { var core = Core( instructions, input, enableTracing: enableTracing) while true { switch core.state { case .accept: return core.current.pos case .fail: return nil case .processing: core.cycle() } } } } extension PEG { public struct Consumer<Input: Collection> where Input.Element == Element { var vm: PEG.VM<Input> public func consume(_ input: Input) -> Input.Index? { vm.consume(input) } } }
apache-2.0
5d07d034e2c89db38729c84f4bcf5de4
29.595238
80
0.590661
4.493007
false
false
false
false
openHPI/xikolo-ios
iOS/ViewControllers/Courses/DocumentListViewController.swift
1
5341
// // Created for xikolo-ios under GPL-3.0 license. // Copyright © HPI. All rights reserved. // import BrightFutures import Common import CoreData import UIKit class DocumentListViewController: UITableViewController { var course: Course! private var dataSource: CoreDataTableViewDataSourceWrapper<DocumentLocalization>! weak var scrollDelegate: CourseAreaScrollDelegate? var inOfflineMode = !ReachabilityHelper.hasConnection { didSet { if oldValue != self.inOfflineMode { self.tableView.reloadData() } } } override func viewDidLoad() { super.viewDidLoad() self.tableView.sectionHeaderHeight = UITableView.automaticDimension self.tableView.estimatedSectionHeaderHeight = 44 // register custom section header view self.tableView.register(UINib(resource: R.nib.documentHeader), forHeaderFooterViewReuseIdentifier: R.nib.documentHeader.name) self.addRefreshControl() // setup table view data let request = DocumentLocalizationHelper.FetchRequest.publicDocumentLocalizations(forCourse: course) let reuseIdentifier = R.reuseIdentifier.documentCell.identifier let resultsController = CoreDataHelper.createResultsController(request, sectionNameKeyPath: "document.title") // must be the first sort descriptor self.dataSource = CoreDataTableViewDataSource.dataSource(for: self.tableView, fetchedResultsController: resultsController, cellReuseIdentifier: reuseIdentifier, delegate: self) self.refresh() self.tableView.reloadData() // needs to be called in order to display the header view correctly self.tableView.layoutIfNeeded() self.setupEmptyState() NotificationCenter.default.addObserver(self, selector: #selector(reachabilityChanged), name: Notification.Name.reachabilityChanged, object: nil) } override func scrollViewDidScroll(_ scrollView: UIScrollView) { self.scrollDelegate?.scrollViewDidScroll(scrollView) } override func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { self.scrollDelegate?.scrollViewDidEndDragging(scrollView, willDecelerate: decelerate) } override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { self.scrollDelegate?.scrollViewDidEndDecelerating(scrollView) } @objc func reachabilityChanged() { self.inOfflineMode = !ReachabilityHelper.hasConnection } } extension DocumentListViewController { // TableViewDelegate override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let documentLocalization = self.dataSource.object(at: indexPath) guard let url = DocumentsPersistenceManager.shared.localFileLocation(for: documentLocalization) ?? documentLocalization.fileURL else { return } let pdfViewController = R.storyboard.pdfWebViewController.instantiateInitialViewController().require() pdfViewController.configure(for: url, filename: documentLocalization.filename) self.show(pdfViewController, sender: self) } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { guard let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: R.nib.documentHeader.name) as? DocumentHeader else { return nil } guard let firstItemInSection = self.dataSource?.sectionInfos?[section].objects?.first as? DocumentLocalization else { return nil } header.configure(for: firstItemInSection.document) return header } } extension DocumentListViewController: CoreDataTableViewDataSourceDelegate { func configure(_ cell: DocumentLocalizationCell, for object: DocumentLocalization) { cell.delegate = self cell.configure(for: object) } } extension DocumentListViewController: CourseAreaViewController { var area: CourseArea { return .documents } func configure(for course: Course, with area: CourseArea, delegate: CourseAreaViewControllerDelegate) { assert(area == self.area) self.course = course self.scrollDelegate = delegate } } extension DocumentListViewController: RefreshableViewController { func refreshingAction() -> Future<Void, XikoloError> { return DocumentHelper.syncDocuments(forCourse: self.course).asVoid() } } extension DocumentListViewController: EmptyStateDataSource, EmptyStateDelegate { var emptyStateTitleText: String { return NSLocalizedString("empty-view.course-documents.title", comment: "title for empty course documents list") } func didTapOnEmptyStateView() { self.refresh() } func setupEmptyState() { self.tableView.emptyStateDataSource = self self.tableView.emptyStateDelegate = self self.tableView.tableFooterView = UIView() } }
gpl-3.0
d4a4b9455183f37247bd2acfa998d9c1
33.451613
154
0.682772
5.855263
false
false
false
false
pubnub/SwiftConsole
PubNubSwiftConsole/Classes/UI/CollectionView/Cells/TextViewCollectionViewCell.swift
1
1896
// // TextViewCollectionViewCell.swift // Pods // // Created by Jordan Zucker on 8/8/16. // // import Foundation protocol TextViewItem: UpdatableTitleContentsItem { } @objc public protocol TextViewCollectionViewCellDelegate: NSObjectProtocol { optional func textViewCell(cell: TextViewCollectionViewCell, textViewDidEndEditing textView: UITextView) } public class TextViewCollectionViewCell: CollectionViewCell, UITextViewDelegate { var delegate: TextViewCollectionViewCellDelegate? private let textView: UITextView override class var reuseIdentifier: String { return String(self.dynamicType) } override init(frame: CGRect) { self.textView = UITextView(frame: CGRect(x: 0.0, y: 0.0, width: frame.size.width, height: frame.size.height)) super.init(frame: frame) self.textView.delegate = self contentView.addSubview(self.textView) contentView.layer.borderWidth = 3 } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func updateTextView(item: TextViewItem) { // TODO: investigate if this should always be replaced self.textView.text = item.contents self.setNeedsLayout() // make sure this occurs during the next update cycle } override func updateCell(item: Item) { guard let textViewItem = item as? TextViewItem else { fatalError("init(coder:) has not been implemented") } updateTextView(textViewItem) } // MARK: - UITextViewDelegate public func textViewDidEndEditing(textView: UITextView) { self.delegate?.textViewCell?(self, textViewDidEndEditing: textView) } class override func size(collectionViewSize: CGSize) -> CGSize { return CGSize(width: 300.0, height: 300.0) } }
mit
47aed010aa006e80a40d171dda90241b
29.095238
117
0.681435
4.836735
false
false
false
false
firebase/firebase-ios-sdk
FirebaseMLModelDownloader/Sources/LocalModelInfo.swift
2
3148
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation /// Model info object with details about downloaded and locally available model. class LocalModelInfo { /// Model name. let name: String /// Hash of the model, as returned by server. let modelHash: String /// Size of the model, as returned by server. let size: Int init(name: String, modelHash: String, size: Int) { self.name = name self.modelHash = modelHash self.size = size } /// Convenience init to create local model info from remotely downloaded model info. convenience init(from remoteModelInfo: RemoteModelInfo) { self.init( name: remoteModelInfo.name, modelHash: remoteModelInfo.modelHash, size: remoteModelInfo.size ) } /// Convenience init to create local model info from stored info in user defaults. convenience init?(fromDefaults defaults: UserDefaults, name: String, appName: String) { let defaultsPrefix = LocalModelInfo.getUserDefaultsKeyPrefix(appName: appName, modelName: name) guard let modelHash = defaults.string(forKey: "\(defaultsPrefix).model-hash") else { return nil } let size = defaults.integer(forKey: "\(defaultsPrefix).model-size") self.init(name: name, modelHash: modelHash, size: size) } } /// Extension to write local model info to user defaults. extension LocalModelInfo: DownloaderUserDefaultsWriteable { // Get user defaults key prefix. private static func getUserDefaultsKeyPrefix(appName: String, modelName: String) -> String { let bundleID = Bundle.main.bundleIdentifier ?? "" return "\(bundleID).\(appName).\(modelName)" } /// Write local model info to user defaults. func writeToDefaults(_ defaults: UserDefaults, appName: String) { let defaultsPrefix = LocalModelInfo.getUserDefaultsKeyPrefix(appName: appName, modelName: name) defaults.setValue(modelHash, forKey: "\(defaultsPrefix).model-hash") defaults.setValue(size, forKey: "\(defaultsPrefix).model-size") } func removeFromDefaults(_ defaults: UserDefaults, appName: String) { let defaultsPrefix = LocalModelInfo.getUserDefaultsKeyPrefix(appName: appName, modelName: name) defaults.removeObject(forKey: "\(defaultsPrefix).model-hash") defaults.removeObject(forKey: "\(defaultsPrefix).model-size") } } /// Named user defaults for FirebaseML. extension UserDefaults { static var firebaseMLDefaults: UserDefaults { let suiteName = "com.google.firebase.ml" guard let defaults = UserDefaults(suiteName: suiteName) else { return UserDefaults.standard } return defaults } }
apache-2.0
8b4e6e1c1dbfe274d367027534f3220b
36.035294
99
0.73094
4.360111
false
false
false
false
colemancda/NetworkObjects
Source/Client.swift
1
4470
// // Client.swift // NetworkObjects // // Created by Alsey Coleman Miller on 9/1/15. // Copyright © 2015 ColemanCDA. All rights reserved. // import SwiftFoundation import CoreModel /// Namespace struct for **NetworkObjects** client classes: /// /// - NetworkObjects.Client.HTTP /// - NetworkObjects.Client.WebSocket public struct Client { } /// Connects to the **NetworkObjects** server. public protocol ClientType: class { /// The URL of the **NetworkObjects** server that this client will connect to. var serverURL: String { get } var model: Model { get } var requestTimeout: TimeInterval { get set } var JSONOptions: [JSON.Serialization.WritingOption] { get set } /// Event handler that fires before each request. /// /// - Returns: The metadata that will be sent. var willSendRequest: (Request -> [String: String])? { get set } /// Event handler that fires with each response. var didRecieveResponse: (ResponseMessage -> Void)? { get set } /// Sends the request and parses the response. func send(request: Request) throws -> Response } public extension ClientType { /// Queries the server for resources that match the fetch request. public func search(fetchRequest: FetchRequest) throws -> [Resource] { let request = Request.Search(fetchRequest) let response = try self.send(request) switch response { case let .Search(resourceIDs): let results = resourceIDs.map({ (element) -> Resource in return Resource(fetchRequest.entityName, element) }) return results case let .Error(errorCode): throw NetworkObjects.Client.Error.ErrorStatusCode(errorCode) default: fatalError() } } /// Creates an entity on the server with the specified initial values. public func create(entityName: String, initialValues: ValuesObject) throws -> (Resource, ValuesObject) { let request = Request.Create(entityName, initialValues) let response = try self.send(request) switch response { case let .Create(resourceID, values): let resource = Resource(entityName, resourceID) return (resource, values) case let .Error(errorCode): throw NetworkObjects.Client.Error.ErrorStatusCode(errorCode) default: fatalError() } } /// Fetches the values specified resource. public func get(resource: Resource) throws -> ValuesObject { let request = Request.Get(resource) let response = try self.send(request) switch response { case let .Get(values): return values case let .Error(errorCode): throw NetworkObjects.Client.Error.ErrorStatusCode(errorCode) default: fatalError() } } /// Edits the specified entity. public func edit(resource: Resource, changes: ValuesObject) throws -> ValuesObject { let request = Request.Edit(resource, changes) let response = try self.send(request) switch response { case let .Edit(values): return values case let .Error(errorCode): throw NetworkObjects.Client.Error.ErrorStatusCode(errorCode) default: fatalError() } } /// Deletes the specified entity. public func delete(resource: Resource) throws { let request = Request.Delete(resource) let response = try self.send(request) switch response { case .Delete: return case let .Error(errorCode): throw NetworkObjects.Client.Error.ErrorStatusCode(errorCode) default: fatalError() } } /// Performs the specified function on a resource. public func performFunction(resource: Resource, functionName: String, parameters: JSONObject? = nil) throws -> JSONObject? { let request = Request.Function(resource, functionName, parameters) let response = try self.send(request) switch response { case let .Function(jsonObject): return jsonObject case let .Error(errorCode): throw NetworkObjects.Client.Error.ErrorStatusCode(errorCode) default: fatalError() } } }
mit
f2dbaf1d0d29a1b0d094c2c703b05533
30.702128
128
0.618035
5.084187
false
false
false
false
jptmoore/lifx-dsl
src/Lifx.swift
1
5477
// // Lifx.swift // lifx // // Created by John Moore on 12/06/2016. // Copyright © 2016 John P. T. Moore. All rights reserved. // import Foundation class Lifx { var token: String var selector: String init(token: String, selector: String = "all") { self.token = token self.selector = selector } private func eval(expression: Light) { switch expression { case let .Bulb(lightbulb): parse(lightbulb.description) case let .Scheme(array): array.forEach { eval($0) } } } private func parse(command: CommandType) { switch command { case ("Color", _): color(command.1) case ("Breathe", _): breathe(command.1) case ("Pulse", _): pulse(command.1) case ("Wait", _): wait(command.1) case ("Power", _): power(command.1) default: print("default") } } private func toJsonData(dict: AnyObject) -> NSData? { do { let jsonData = try NSJSONSerialization.dataWithJSONObject(dict, options: NSJSONWritingOptions.PrettyPrinted) return jsonData } catch let error as NSError { print(error) } return nil } private func webQuery(request: NSMutableURLRequest, data: NSData) { let session = NSURLSession.sharedSession() request.addValue("Bearer \(token)", forHTTPHeaderField: "Authorization") request.HTTPBody = data let task = session.dataTaskWithRequest(request) { (data, response, error) in //print(response) guard let _ = data else { print("Did not receive data") return } guard error == nil else { print(error) return } } task.resume() } private func setState(dict: [String: AnyObject]) { let endpoint = "https://api.lifx.com/v1/lights/\(selector)/state" guard let url = NSURL(string: endpoint) else { print("Error: cannot create URL") return } let request = NSMutableURLRequest(URL: url) request.HTTPMethod = "PUT" if let jsonData = toJsonData(dict), jsonString = NSString(data: jsonData, encoding: NSUTF8StringEncoding) { print(jsonString) webQuery(request, data: jsonData) } } private func setEffect(endpoint: String, dict: [String: AnyObject]) { guard let url = NSURL(string: endpoint) else { print("Error: cannot create URL") return } let request = NSMutableURLRequest(URL: url) request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type") request.HTTPMethod = "POST" if let jsonData = toJsonData(dict), jsonString = NSString(data: jsonData, encoding: NSUTF8StringEncoding) { print(jsonString) webQuery(request, data: jsonData) } } private func setBreatheEffect(dict: [String: AnyObject]) { let endpoint = "https://api.lifx.com/v1/lights/\(selector)/effects/breathe" setEffect(endpoint, dict: dict) } private func setPulseEffect(dict: [String: AnyObject]) { let endpoint = "https://api.lifx.com/v1/lights/\(selector)/effects/pulse" setEffect(endpoint, dict: dict) } private func power(dict: [String: AnyObject]) { if let on: Bool = dict["on"] as? Bool { if on { setState(["power": "on"]) } else { setState(["power": "off"]) } } } private func wait(dict: [String: AnyObject]) { if let duration: Double = dict["duration"] as? Double { NSThread.sleepForTimeInterval(duration) } } private func color(dict: [String: AnyObject]) { if let color: String = dict["color"] as? String { setState(["color": color]) } } private func breathe(dict: [String: AnyObject]) { if let color = dict["color"], let period = dict["period"], let cycles = dict["cycles"] { setBreatheEffect(["color": color, "period": period, "cycles": cycles]) } } private func pulse(dict: [String: AnyObject]) { if let color = dict["color"], let period = dict["period"], let cycles = dict["cycles"] { setPulseEffect(["color": color, "period": period, "cycles": cycles]) } } // loop to allow web requests to complete private func readStdin(scheme: Light) { let delim:Character = "\n" var input:String = "" print("Available commands: 'repeat', 'quit'.") print("> ", terminator:"") while true { let c = Character(UnicodeScalar(UInt32(fgetc(stdin)))) if c == delim { switch input { case "quit": exit(EXIT_SUCCESS) case "repeat": eval(scheme) default: break } input = "" print("> ", terminator:"") } else { input.append(c) } } } func play(scheme: Light) { eval(scheme) readStdin(scheme) } }
mit
897ed75ea251ff8d89e5f8d00afbce41
29.943503
120
0.529766
4.510708
false
false
false
false
yuzawa-san/ico-saver
Polyhedra/DefaultsManager.swift
1
1670
import ScreenSaver class DefaultsManager { private var defaults: UserDefaults init() { let identifier = Bundle(for: DefaultsManager.self).bundleIdentifier defaults = ScreenSaverDefaults(forModuleWithName: identifier!)! } func synchronize() { defaults.synchronize() } var polyhedronName: String { get { return defaults.string(forKey: "polyhedron_name") ?? PolyhedraRegistry.defaultName } set(value) { defaults.setValue(value, forKey: "polyhedron_name") } } var useColorOverride: Bool { get { return defaults.bool(forKey: "use_color_override") } set(value) { defaults.setValue(value, forKey: "use_color_override") } } var showPolyhedronName: Bool { get { return defaults.bool(forKey: "show_polyhedron_name") } set(value) { defaults.setValue(value, forKey: "show_polyhedron_name") } } var colorOverride: NSColor { get { guard let storedData = defaults.data(forKey: "color_override"), let unarchivedData = try? NSKeyedUnarchiver.unarchivedObject(ofClass: NSColor.self, from: storedData), let color = unarchivedData as NSColor? else { return NSColor.red } return color } set(color) { if let data = try? NSKeyedArchiver.archivedData(withRootObject: color, requiringSecureCoding: false) { defaults.set(data, forKey: "color_override") } } } }
mit
74b1ee550a399e1ef2456d73bb776295
27.305085
118
0.567066
4.626039
false
false
false
false
resmio/TastyTomato
TastyTomato/Code/Types/ButtonClasses/FilledButton.swift
1
4853
// // FilledButton.swift // TastyTomato // // Created by Jan Nash on 7/28/16. // Copyright © 2016 resmio. All rights reserved. // import Foundation // MARK: // Public // MARK: Interface public extension FilledButton { // Factories static func makeBlueButton(title: String) -> FilledButton { return ._makeBlueButton(title: title) } static func makeSignInButton() -> FilledButton { return .makeBlueButton(title: NSL_("Sign in")) } static func makeSelectButton() -> FilledButton { return .makeBlueButton(title: NSL_("Select")) } static func makeCreateButton() -> FilledButton { return ._makeCreateButton() } static func makeDeleteButton() -> FilledButton { return ._makeDeleteButton() } static func makeNextButton() -> FilledButton { return ._makeNextButton() } // Dim func dim(_ dim: Bool) { self._dim(dim) } } // MARK: Class Declaration public class FilledButton: BaseButton { // Public Constants public let highlightedAlpha: CGFloat = 0.6 // Private Variables private var _isDimmed: Bool = false private var _fillColor: UIColor = .blue00A7C4 } // MARK: // Private // MARK: Factories private extension FilledButton { static func _makeBlueButton(title: String) -> FilledButton { let button: FilledButton = ._makeDefaultButton(title: title) button.setColorAdjustment({ guard let filledButton: FilledButton = $0 as? FilledButton else { return } let background: ColorScheme.Background = ColorScheme.background let dimmed: Bool = filledButton._isDimmed let fillColor: UIColor = dimmed ? background.filledButtonDimmed : background.filledButton filledButton.setColor(fillColor, for: .normal) filledButton.setColor(fillColor.withAlpha(filledButton.highlightedAlpha), for: .highlighted) filledButton.setTitleColor(ColorScheme.text.filledButton, for: .normal) }) return button } static func _makeCreateButton() -> FilledButton { let button: FilledButton = ._makeDefaultButton(title: NSL_("Create")) button.titleLabel!.font = .xs button.setColorAdjustment({ guard let filledButton: FilledButton = $0 as? FilledButton else { return } let fillColor: UIColor = ColorScheme.background.createButton filledButton.setColor(fillColor, for: .normal) filledButton.setColor(fillColor.withAlpha(filledButton.highlightedAlpha), for: .highlighted) filledButton.setTitleColor(ColorScheme.text.filledButton, for: .normal) }) return button } static func _makeDeleteButton() -> FilledButton { let button: FilledButton = ._makeDefaultButton(title: NSL_("Delete")) button.titleLabel!.font = .xs button.setColorAdjustment({ guard let filledButton: FilledButton = $0 as? FilledButton else { return } let fillColor: UIColor = ColorScheme.background.deleteButton filledButton.setColor(fillColor, for: .normal) filledButton.setColor(fillColor.withAlpha(filledButton.highlightedAlpha), for: .highlighted) filledButton.setTitleColor(ColorScheme.text.filledButton, for: .normal) }) return button } static func _makeNextButton() -> FilledButton { let button: FilledButton = ._makeDefaultButton(title: NSL_("Next")) let image: UIImage = ArrowIcon.Right.asTemplate() button.setImage(image, for: .normal) button.setColorAdjustment({ guard let filledButton: FilledButton = $0 as? FilledButton else { return } let background: ColorScheme.Background = ColorScheme.background let dimmed: Bool = filledButton._isDimmed let fillColor: UIColor = dimmed ? background.filledButtonDimmed : background.filledButton filledButton.setColor(fillColor, for: .normal) filledButton.setColor(fillColor.withAlpha(filledButton.highlightedAlpha), for: .highlighted) filledButton.setTitleColor(ColorScheme.text.filledButton, for: .normal) filledButton.tintColor = ColorScheme.lines.filledNextButtonImage }) return button } static func _makeDefaultButton(title: String) -> FilledButton { let button: FilledButton = FilledButton() button.setTitle(title) button.titleLabel!.font = .s button.adjustsWidthOnTitleSet = false button.height = 44 return button } } // MARK: Dim Implementation private extension FilledButton { func _dim(_ dim: Bool) { guard dim != self._isDimmed else { return } self._isDimmed = dim self.adjustColors() } }
mit
0fc7385d85cc0d612b313b8674466399
34.676471
104
0.653957
4.651965
false
false
false
false
ktmswzw/FeelingClientBySwift
Pods/IBAnimatable/IBAnimatable/AnimatableStackView.swift
1
3957
// // Created by Jake Lin on 12/11/15. // Copyright © 2015 Jake Lin. All rights reserved. // import UIKit // FIXME: almost same as `AnimatableView`, Need to refactor to encasuplate. @available(iOS 9, *) @IBDesignable public class AnimatableStackView: UIStackView, CornerDesignable, FillDesignable, BorderDesignable, RotationDesignable, ShadowDesignable, BlurDesignable, TintDesignable, GradientDesignable, MaskDesignable, Animatable { // MARK: - CornerDesignable @IBInspectable public var cornerRadius: CGFloat = CGFloat.NaN { didSet { configCornerRadius() } } // MARK: - FillDesignable @IBInspectable public var fillColor: UIColor? { didSet { configFillColor() } } @IBInspectable public var predefinedColor: String? { didSet { configFillColor() } } @IBInspectable public var opacity: CGFloat = CGFloat.NaN { didSet { configOpacity() } } // MARK: - BorderDesignable @IBInspectable public var borderColor: UIColor? { didSet { configBorder() } } @IBInspectable public var borderWidth: CGFloat = CGFloat.NaN { didSet { configBorder() } } @IBInspectable public var borderSide: String? { didSet { configBorder() } } // MARK: - RotationDesignable @IBInspectable public var rotate: CGFloat = CGFloat.NaN { didSet { configRotate() } } // MARK: - ShadowDesignable @IBInspectable public var shadowColor: UIColor? { didSet { configShadowColor() } } @IBInspectable public var shadowRadius: CGFloat = CGFloat.NaN { didSet { configShadowRadius() } } @IBInspectable public var shadowOpacity: CGFloat = CGFloat.NaN { didSet { configShadowOpacity() } } @IBInspectable public var shadowOffset: CGPoint = CGPoint(x: CGFloat.NaN, y: CGFloat.NaN) { didSet { configShadowOffset() } } // MARK: - BlurDesignable @IBInspectable public var blurEffectStyle: String? @IBInspectable public var blurOpacity: CGFloat = CGFloat.NaN // MARK: - TintDesignable @IBInspectable public var tintOpacity: CGFloat = CGFloat.NaN @IBInspectable public var shadeOpacity: CGFloat = CGFloat.NaN @IBInspectable public var toneColor: UIColor? @IBInspectable public var toneOpacity: CGFloat = CGFloat.NaN // MARK: - GradientDesignable @IBInspectable public var startColor: UIColor? @IBInspectable public var endColor: UIColor? @IBInspectable public var predefinedGradient: String? @IBInspectable public var startPoint: String? // MARK: - MaskDesignable @IBInspectable public var maskType: String? { didSet { configMask() configBorder() } } // MARK: - Animatable @IBInspectable public var animationType: String? @IBInspectable public var autoRun: Bool = true @IBInspectable public var duration: Double = Double.NaN @IBInspectable public var delay: Double = Double.NaN @IBInspectable public var damping: CGFloat = CGFloat.NaN @IBInspectable public var velocity: CGFloat = CGFloat.NaN @IBInspectable public var force: CGFloat = CGFloat.NaN @IBInspectable public var repeatCount: Float = Float.NaN @IBInspectable public var x: CGFloat = CGFloat.NaN @IBInspectable public var y: CGFloat = CGFloat.NaN // MARK: - Lifecycle public override func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() configInspectableProperties() } public override func awakeFromNib() { super.awakeFromNib() configInspectableProperties() } public override func layoutSubviews() { super.layoutSubviews() configAfterLayoutSubviews() autoRunAnimation() } // MARK: - Private private func configInspectableProperties() { configAnimatableProperties() configTintedColor() configBlurEffectStyle() configGradient() } private func configAfterLayoutSubviews() { configBorder() } }
mit
618dffdb2abaf6f445c9ea4a550c105f
24.856209
231
0.693377
4.859951
false
true
false
false
guumeyer/MarveListHeroes
MarvelHeroes/ServerConfig.swift
1
1076
// // ServerConfig.swift // MarvelHeros // // Created by gustavo r meyer on 8/12/17. // Copyright © 2017 gustavo r meyer. All rights reserved. // import Foundation struct ServerConfig { struct HttpSettings { static let url = "https://gateway.marvel.com/" static func getDefaultParametersHttp() -> [String:Any] { let timestamp = NSDate().timeIntervalSince1970.description let hash = Marvel.getHash(timestamp) return [ "apikey": Marvel.publicKey, "ts": timestamp, "hash": hash ] } } struct Marvel { //TODO: Create a Setting.plist file static let publicKey = "7d9dfb0b23ab31ec67d181f5fe09f230" static let privateKey = "25e5b55b1124843c966cbc3121d5d57b9237eaf1" static func getHash(_ timestamp:String) -> String{ return "\(timestamp)\(Marvel.privateKey)\(Marvel.publicKey)".md5() } } }
apache-2.0
3ac171094173c0154e250d17831fcee2
24
78
0.546977
4.249012
false
false
false
false
Harshvk/T20Exibition
T20Exibition/T20Exibition/DataModel.swift
1
1714
import UIKit import SwiftyJSON struct ImageInfo { let id : String! var isFav : Bool = false var comments = 0 var downloads = 0 var favorites = 0 var likes = 0 var views = 0 var pageURL : String = "" var userImageURL : String = "" var webformatURL : String = "" var previewURL : String = "" init(withJSON json: JSON) { self.id = json["id"].stringValue self.comments = json["comments"].intValue self.downloads = json["downloads"].intValue self.favorites = json["favorites"].intValue self.likes = json["likes"].intValue self.views = json["views"].intValue self.pageURL = json["pageURL"].stringValue self.userImageURL = json["userImageURL"].stringValue self.webformatURL = json["webformatURL"].stringValue self.previewURL = json["previewURL"].stringValue } } // comments = 12; // downloads = 20875; // favorites = 80; // id = 1212400; // imageHeight = 2296; // imageWidth = 3514; // likes = 94; // pageURL = "https://pixabay.com/en/dog-water-run-movement-joy-1212400/"; // previewHeight = 97; // previewURL = "https://cdn.pixabay.com/photo/2016/02/20/17/05/dog-1212400_150.jpg"; // previewWidth = 150; // tags = "dog, water, run"; // type = photo; // user = howo; // userImageURL = "https://cdn.pixabay.com/user/2016/02/21/16-58-44-476_250x250.jpg"; // "user_id" = 1747689; // views = 30819; // webformatHeight = 418; // webformatURL = "https://pixabay.com/get/e837b00d2cf4013ed95c4518b7484096e67ee7d204b0154992f5c878aee9b1_640.jpg"; // webformatWidth = 640;
mit
ff031a202f5b3a1b07c68fc0d100d32b
26.645161
118
0.60035
3.400794
false
false
false
false
stefanilie/swift-playground
Swift3 and iOS10/Playgrounds/Optionals.playground/Contents.swift
1
1641
//: Playground - noun: a place where people can play // tl;dr: // ? - used for variables that we don't know if they will have a value // ! - used for variables that we know FOR SURE that at one point in time we add value import UIKit //Question mark is for when we don't know // if we will have a value in there var lotteryWinnings: Int? if lotteryWinnings != nil { print(lotteryWinnings!) } lotteryWinnings = 100; if let winnings = lotteryWinnings{ print(winnings); } class Car { var model: String? } var vehicle: Car? vehicle = Car(); //This is an optional and I don't know what is going to happen with it vehicle?.model = "Bronco"; //If vehicle has a value, it adds it to v. if let v = vehicle { if let m = v.model { print(m); } } //This is the same as the above, but in one line if let v = vehicle, let m = v.model{ print(m); } var cars: [Car]? cars = [Car](); if let carArr = cars{ if carArr.count>0{ //do stuff } } if let carArr = cars , carArr.count > 0{ //do stuff //same as abouve } else { cars?.append(Car()); print(cars?.count); } class Person { //This means that I am going to give this one a value sometime. private var _age: Int!; var age: Int { if _age == nil{ _age=15; } return _age; } func setAge(newAge: Int){ self._age = newAge; } } var jack = Person(); print(jack.age); class Doc { var species: String; init(someSpecies: String){ self.species = someSpecies } } var lab = Doc(someSpecies: "Black Lab"); print(lab.species);
mit
f54146e8ca752217123e7c8493070433
16.273684
86
0.600244
3.321862
false
false
false
false
CulturaMobile/culturamobile-api
Sources/App/Models/VenueOpenHours.swift
1
2373
import Vapor import FluentProvider import AuthProvider import HTTP final class VenueOpenHours: Model { fileprivate static let databaseTableName = "venue_open_hours" static var entity = "venue_open_hours" let storage = Storage() static let idKey = "id" static let foreignIdKey = "venue_open_hours_id" var venue: Identifier? var openHours: Identifier? init(venue: Venue, openHours: OpenHour) { self.venue = venue.id self.openHours = openHours.id } // MARK: Row /// Initializes from the database row init(row: Row) throws { venue = try row.get("venue_id") openHours = try row.get("open_hours_id") } // Serializes object to the database func makeRow() throws -> Row { var row = Row() try row.set("venue_id", venue) try row.set("open_hours_id", openHours) return row } } // MARK: Preparation extension VenueOpenHours: Preparation { /// Prepares a table/collection in the database for storing objects static func prepare(_ database: Database) throws { try database.create(self) { builder in builder.id() builder.int("venue_id") builder.int("open_hours_id") } } /// Undoes what was done in `prepare` static func revert(_ database: Database) throws { try database.delete(self) } } // MARK: JSON // How the model converts from / to JSON. // extension VenueOpenHours: JSONConvertible { convenience init(json: JSON) throws { try self.init( venue: json.get("venue_id"), openHours: json.get("open_hours_id") ) id = try json.get("id") } func makeJSON() throws -> JSON { var json = JSON() let currentOpenHours = try OpenHour.makeQuery().filter("id", openHours).all() for oh in currentOpenHours { try json.set("day", oh.day) try json.set("open_in", oh.open) try json.set("close_in", oh.close) } return json } } extension VenueOpenHours: ResponseRepresentable { } extension VenueOpenHours: Timestampable { static var updatedAtKey: String { return "updated_at" } static var createdAtKey: String { return "created_at" } }
mit
8b1f5aad51a2bb9059c3b2de8330823f
24.244681
85
0.589971
4.185185
false
false
false
false
tectijuana/patrones
Bloque1SwiftArchivado/PracticasSwift/PalaciosArlette/Ejercicio20.swift
1
1592
/* Palacios Lee Arlette 12211431 Programa para resolver el siguiente problema: 20. Dos botes deportivos abandonan un muelle al mismo tiempo. Uno va hacia el norte, a razón de 57 km/h y el otro a 63 km/h, en una direccion de 40° W respecto al N. Después de 2h, ¿a qué distancia se encuentran entre sí los botes? */ //Librería para utilizar funciones trigonométricas import Foundation //Declaración de variables var ladoa: Float = 57 var ladob: Float = 63 var anguloC: Float = 40 //Se multiplica la distancia por 2 var ladoa2: Float = 57 * 2 var ladob2: Float = 63 * 2 //Utilizando la ley de coseno se calcula el lado faltante var coseno = cos(anguloC * Float.pi / 180) //Calcular el coseno var lados = pow(ladoa2,2) + pow(ladob2,2) //Realizar la suma del cuadrado de los lados //Se obtiene el doble del la suma de los lados por el coseno y se le resta el cuadradod de los lados y se obtiene la raíz cuadrada de esto var ladoc = sqrt(lados - (2*ladoa2*ladob2*coseno)) //Utilizado la ley de senos se calculan los ángulos faltantes var anguloB = asin((ladob2 * sin(anguloC * Float.pi / 180))/ladoc) * 180 / Float.pi var anguloA = asin((ladoa2 * sin(anguloB * Float.pi / 180))/ladob2) * 180 / Float.pi //Se imprime el problema print("Problema \n20. Dos botes deportivos abandonan un muelle al mismo tiempo. Uno va hacia el norte, a razón de 57 km/h y el otro a 63 km/h, en una direccion de 40° W respecto al N. Después de 2h, ¿a qué distancia se encuentran entre sí los botes?") //Se imprime el resultado print(" \nResultado: \(ladoc)")
gpl-3.0
16e9534e6883a257f07a4d2b6eeb05aa
42.75
251
0.72
2.660473
false
false
false
false
AlphaJian/LarsonApp
LarsonApp/LarsonApp/Class/Appointment/Views/Cell/CompleteAppointmentTableViewCell.swift
1
1238
// // CompleteAppointmentTableViewCell.swift // LarsonApp // // Created by Perry Z Chen on 11/7/16. // Copyright © 2016 Jian Zhang. All rights reserved. // import UIKit class CompleteAppointmentTableViewCell: UITableViewCell { @IBOutlet weak var placeholderLabel: UILabel! @IBOutlet weak var legacyIdLabel: UILabel! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var containerView: UIView! override func awakeFromNib() { super.awakeFromNib() self.containerView.layer.cornerRadius = 4.0 self.containerView.layer.shadowColor = UIColor.lightGray.cgColor self.containerView.layer.shadowOffset = CGSize(width: 3, height: 3) self.containerView.layer.shadowOpacity = 1; self.containerView.layer.shadowRadius = 3.0; // Initialization code } func setupCellData(model: AppointmentModel) { self.placeholderLabel.text = model.jobType self.legacyIdLabel.text = model.legacyId self.nameLabel.text = model.customerName } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
apache-2.0
80514b7b6b47e7c5a7689f9e3781313b
29.170732
75
0.688763
4.598513
false
false
false
false
ngthduy90/Yummy
Source/Views/BusinessTableViewCell.swift
1
1604
// // BusinessTableViewCell.swift // Yummy // // Created by Duy Nguyen on 6/25/17. // Copyright © 2017 Duy Nguyen. All rights reserved. // import UIKit import AFNetworking class BusinessTableViewCell: UITableViewCell { @IBOutlet weak var backgroundEffectView: UIVisualEffectView! @IBOutlet weak var businessImageView: UIImageView! @IBOutlet weak var ratingImageView: UIImageView! @IBOutlet weak var milesLabel: UILabel! @IBOutlet weak var reviewsLabel: UILabel! @IBOutlet weak var adressLabel: UILabel! @IBOutlet weak var categoriesLabel: UILabel! @IBOutlet weak var nameLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } func render() { self.layoutIfNeeded() businessImageView.layer.cornerRadius = 16.0 backgroundEffectView.layer.cornerRadius = 16.0 businessImageView.layer.borderWidth = 2.0 businessImageView.layer.borderColor = UIColor.white.cgColor } func display(_ business: Business) { self.nameLabel.text = business.name self.milesLabel.text = business.distanceInMiles self.reviewsLabel.text = "\(business.reviewCount)" + ((business.reviewCount < 2) ? " review" : " reviews") self.adressLabel.text = business.location.address self.businessImageView.setImageWith(business.imageURL!) self.ratingImageView.setImageWith(business.ratingImageURL!) } }
apache-2.0
0d4d46c56455753b954f1705c7e15f08
30.431373
114
0.687461
4.673469
false
false
false
false
tylerbrockett/cse394-principles-of-mobile-applications
lab-6/lab-6/lab-6/DetailViewController.swift
1
2857
/* * @author Tyler Brockett mailto:[email protected] * @course ASU CSE 394 * @project Lab 6 * @version March 21, 2016 * @project-description Collects data from www.geonames.org and presents it to the user. * @class-name DetailViewController.swift * @class-description Displays specific details about single earthquake event to the user. * * The MIT License (MIT) * * Copyright (c) 2016 Tyler Brockett * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ import UIKit class DetailViewController: UIViewController { var location:String = "" var coordinates:String = "" var dictionary:NSDictionary = NSDictionary() @IBOutlet weak var locationLabel: UILabel! @IBOutlet weak var coordinatesLabel: UILabel! @IBOutlet weak var datetimeLabel: UILabel! @IBOutlet weak var magnitudeLabel: UILabel! @IBOutlet weak var latLabel: UILabel! @IBOutlet weak var lonLabel: UILabel! @IBOutlet weak var idLabel: UILabel! @IBOutlet weak var depthLabel: UILabel! @IBOutlet weak var srcLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. locationLabel.text! = location coordinatesLabel.text! = coordinates datetimeLabel.text! = dictionary.valueForKey("datetime") as! String magnitudeLabel.text! = "\(dictionary.valueForKey("magnitude") as! Double)" latLabel.text! = "\(dictionary.valueForKey("lat") as! Double)" lonLabel.text! = "\(dictionary.valueForKey("lng") as! Double)" idLabel.text! = dictionary.valueForKey("eqid") as! String depthLabel.text! = "\(dictionary.valueForKey("depth") as! Double)" srcLabel.text! = dictionary.valueForKey("src") as! String } }
mit
99f03e8d2faa78dc947d673a79254aae
42.953846
92
0.715086
4.402157
false
false
false
false
kesun421/firefox-ios
L10nSnapshotTests/L10nSnapshotTests.swift
1
8971
/* 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 XCTest let testPageBase = "http://wopr.norad.org/~sarentz/fxios/testpages" let loremIpsumURL = "\(testPageBase)/index.html" class L10nSnapshotTests: L10nBaseSnapshotTests { func test02DefaultTopSites() { navigator.toggleOff(userState.pocketInNewTab, withAction: Action.TogglePocketInNewTab) navigator.goto(HomePanelsScreen) snapshot("02DefaultTopSites-01") navigator.toggleOn(userState.pocketInNewTab, withAction: Action.TogglePocketInNewTab) navigator.goto(HomePanelsScreen) snapshot("02DefaultTopSites-with-pocket-02") } func test03MenuOnTopSites() { navigator.goto(NewTabScreen) navigator.goto(BrowserTabMenu) snapshot("03MenuOnTopSites-01") } func test04Settings() { let table = app.tables.element(boundBy: 0) navigator.goto(SettingsScreen) table.forEachScreen { i in snapshot("04Settings-main-\(i)") } allSettingsScreens.forEach { nodeName in self.navigator.goto(nodeName) table.forEachScreen { i in snapshot("04Settings-\(nodeName)-\(i)") } } } func test05PrivateBrowsingTabsEmptyState() { navigator.toggleOn(userState.isPrivate, withAction: Action.TogglePrivateMode) snapshot("05PrivateBrowsingTabsEmptyState-01") } func test06PanelsEmptyState() { var i = 0 navigator.visitNodes(allHomePanels) { nodeName in snapshot("06PanelsEmptyState-\(i)-\(nodeName)") i += 1 } } // From here on it is fine to load pages func test07AddSearchProvider() { navigator.openURL("\(testPageBase)/addSearchProvider.html") app.webViews.element(boundBy: 0).buttons["focus"].tap() snapshot("07AddSearchProvider-01", waitForLoadingIndicator: false) app.buttons["BrowserViewController.customSearchEngineButton"].tap() snapshot("07AddSearchProvider-02", waitForLoadingIndicator: false) let alert = XCUIApplication().alerts.element(boundBy: 0) expectation(for: NSPredicate(format: "exists == 1"), evaluatedWith: alert, handler: nil) waitForExpectations(timeout: 3, handler: nil) alert.buttons.element(boundBy: 0).tap() } func test08URLBar() { navigator.goto(URLBarOpen) snapshot("08URLBar-01") userState.url = "moz" navigator.performAction(Action.SetURLByTyping) snapshot("08URLBar-02") } func test09URLBarContextMenu() { // Long press with nothing on the clipboard navigator.goto(URLBarLongPressMenu) snapshot("09LocationBarContextMenu-01-no-url") navigator.back() // Long press with a URL on the clipboard UIPasteboard.general.string = "https://www.mozilla.com" navigator.goto(URLBarLongPressMenu) snapshot("09LocationBarContextMenu-02-with-url") } func test10MenuOnWebPage() { navigator.openURL(loremIpsumURL) navigator.goto(BrowserTabMenu) snapshot("10MenuOnWebPage-01") navigator.back() navigator.toggleOn(userState.noImageMode, withAction: Action.ToggleNoImageMode) navigator.toggleOn(userState.nightMode, withAction: Action.ToggleNightMode) navigator.goto(BrowserTabMenu) snapshot("10MenuOnWebPage-02") navigator.back() } func test10PageMenuOnWebPage() { navigator.goto(PageOptionsMenu) snapshot("10MenuOnWebPage-03") navigator.back() } func test11WebViewContextMenu() { // Link navigator.openURL("\(testPageBase)/link.html") navigator.goto(WebLinkContextMenu) snapshot("11WebViewContextMenu-01-link") navigator.back() // Image navigator.openURL("\(testPageBase)/image.html") navigator.goto(WebImageContextMenu) snapshot("11WebViewContextMenu-02-image") navigator.back() // Image inside Link navigator.openURL("\(testPageBase)/imageWithLink.html") navigator.goto(WebLinkContextMenu) snapshot("11WebViewContextMenu-03-imageWithLink") navigator.back() } func test12WebViewAuthenticationDialog() { navigator.openURL("\(testPageBase)/basicauth/index.html", waitForLoading: false) navigator.goto(BasicAuthDialog) snapshot("12WebViewAuthenticationDialog-01", waitForLoadingIndicator: false) navigator.back() } func test13ReloadButtonContextMenu() { navigator.openURL(loremIpsumURL) navigator.toggleOff(userState.requestDesktopSite, withAction: Action.ToggleRequestDesktopSite) navigator.goto(ReloadLongPressMenu) snapshot("13ContextMenuReloadButton-01") navigator.toggleOn(userState.requestDesktopSite, withAction: Action.ToggleRequestDesktopSite) navigator.goto(ReloadLongPressMenu) snapshot("13ContextMenuReloadButton-02", waitForLoadingIndicator: false) navigator.back() } func test16PasscodeSettings() { navigator.goto(SetPasscodeScreen) snapshot("16SetPasscodeScreen-1-nopasscode") userState.newPasscode = "111111" navigator.performAction(Action.SetPasscodeTypeOnce) snapshot("16SetPasscodeScreen-2-typepasscode") userState.newPasscode = "111112" navigator.performAction(Action.SetPasscodeTypeOnce) snapshot("16SetPasscodeScreen-3-passcodesmustmatch") userState.newPasscode = "111111" navigator.performAction(Action.SetPasscode) snapshot("16SetPasscodeScreen-3") navigator.goto(PasscodeIntervalSettings) snapshot("16PasscodeIntervalScreen-1") } func test17PasswordSnackbar() { navigator.openURL("\(testPageBase)/password.html") app.webViews.element(boundBy: 0).buttons["submit"].tap() snapshot("17PasswordSnackbar-01") app.buttons["SaveLoginPrompt.saveLoginButton"].tap() // The password is pre-filled with a random value so second this this will cause the update prompt navigator.openURL("\(testPageBase)/password.html") app.webViews.element(boundBy: 0).buttons["submit"].tap() snapshot("17PasswordSnackbar-02") } func test18TopSitesMenu() { navigator.openURL(loremIpsumURL) navigator.goto(TopSitesPanelContextMenu) snapshot("18TopSitesMenu-01") } func test19HistoryTableContextMenu() { navigator.openURL(loremIpsumURL) navigator.goto(HistoryPanelContextMenu) snapshot("19HistoryTableContextMenu-01") } func test20BookmarksTableContextMenu() { navigator.openURL(loremIpsumURL) navigator.performAction(Action.Bookmark) navigator.goto(BookmarksPanelContextMenu) snapshot("20BookmarksTableContextMenu-01") } func test21ReaderModeSettingsMenu() { let app = XCUIApplication() loadWebPage(url: loremIpsumURL, waitForOtherElementWithAriaLabel: "body") app.buttons["TabLocationView.readerModeButton"].tap() app.buttons["ReaderModeBarView.settingsButton"].tap() snapshot("21ReaderModeSettingsMenu-01") } func test22ReadingListTableContextMenu() { let app = XCUIApplication() loadWebPage(url: loremIpsumURL, waitForOtherElementWithAriaLabel: "body") app.buttons["TabLocationView.readerModeButton"].tap() app.buttons["ReaderModeBarView.listStatusButton"].tap() app.textFields["url"].tap() app.buttons["HomePanels.ReadingList"].tap() app.tables["ReadingTable"].cells.element(boundBy: 0).press(forDuration: 2.0) snapshot("22ReadingListTableContextMenu-01") } func test23ReadingListTableRowMenu() { let app = XCUIApplication() loadWebPage(url: loremIpsumURL, waitForOtherElementWithAriaLabel: "body") app.buttons["TabLocationView.readerModeButton"].tap() app.buttons["ReaderModeBarView.listStatusButton"].tap() app.textFields["url"].tap() app.buttons["HomePanels.ReadingList"].tap() app.tables["ReadingTable"].cells.element(boundBy: 0).swipeLeft() snapshot("23ReadingListTableRowMenu-01") app.tables["ReadingTable"].cells.element(boundBy: 0).buttons.element(boundBy: 1).tap() app.tables["ReadingTable"].cells.element(boundBy: 0).swipeLeft() snapshot("23ReadingListTableRowMenu-02") } func test24BookmarksListTableRowMenu() { navigator.openURL(loremIpsumURL) navigator.performAction(Action.Bookmark) navigator.goto(BookmarksPanelContextMenu) app.tables["Bookmarks List"].cells.element(boundBy: 0).swipeLeft() snapshot("24BookmarksListTableRowMenu-01") } }
mpl-2.0
7014061e01f81b86201daff24d79e264
36.852321
106
0.684093
4.699319
false
true
false
false
WTGrim/WTOfo_Swift
Ofo_Swift/Ofo_Swift/ScanViewController.swift
1
2494
// // ScanViewController.swift // Ofo_Swift // // Created by Dwt on 2017/9/29. // Copyright © 2017年 Dwt. All rights reserved. // import UIKit import swiftScan import FTIndicator class ScanViewController: LBXScanViewController { @IBOutlet weak var bottomView: UIView! @IBOutlet weak var topView: UIView! @IBOutlet weak var openTorch: ScanButton! @IBOutlet weak var inputNo: ScanButton! @IBOutlet weak var closeBtn: UIButton! var isFlashOn = false override func viewDidLoad() { super.viewDidLoad() setupUI() } override func handleCodeResult(arrayResult: [LBXScanResult]) { if let result = arrayResult.first{ let msg = result.strScanned FTIndicator.setIndicatorStyle(.dark) FTIndicator.showToastMessage(msg) } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.navigationBar.isHidden = true } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) view.bringSubview(toFront: bottomView) view.bringSubview(toFront: topView) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) navigationController?.navigationBar.isHidden = false } } extension ScanViewController{ fileprivate func setupUI(){ closeBtn.addTarget(self, action: #selector(closeBtnClick), for: .touchUpInside) openTorch.addTarget(self, action: #selector(openTorchClick), for: .touchUpInside) inputNo.addTarget(self, action: #selector(inputNoClick), for: .touchUpInside) var style = LBXScanViewStyle() style.anmiationStyle = .NetGrid style.animationImage = UIImage(named:"qrcode_scan_full_net") scanStyle = style } @objc fileprivate func closeBtnClick(){ dismiss(animated: true) { } } @objc fileprivate func openTorchClick(){ print("打开手电筒") isFlashOn = !isFlashOn scanObj?.changeTorch() if isFlashOn{ openTorch.setImage(UIImage(named:"btn_enableTorch_w_21x21_"), for: .normal) }else{ openTorch.setImage(UIImage(named:"btn_unenableTorch_w_15x23_"), for: .normal) } } @objc fileprivate func inputNoClick(){ print("手动输入车牌号") } }
mit
98badaa9266f0ccd61f69090dcc4497b
24.968421
89
0.635184
4.534926
false
false
false
false
mobilabsolutions/jenkins-ios
JenkinsiOS/Other/Constants.swift
1
13617
// // Constants.swift // JenkinsiOS // // Created by Robert on 25.09.16. // Copyright © 2016 MobiLab Solutions. All rights reserved. // import Foundation import UIKit struct Constants { struct Defaults { /// The default port that should be used. 443 because the default protocol is https static let defaultPort = 443 static let defaultReloadInterval: TimeInterval = 4 static let apiTokenFAQItemId = "api_token" static let apiTokenFAQItem: FAQItem = { guard let url = URL(string: "https://mobilabsolutions.com/butler-tutorial/") else { fatalError("Could not initialize api token faq url!") } return FAQItem(key: Constants.Defaults.apiTokenFAQItemId, question: "How can I generate an API token?", url: url) }() } enum SupportedSchemes: String { case http case https } struct Paths { static let userPath = PersistenceUtils.getDocumentDirectory()!.appendingPathComponent("User") static let sharedUserPath = PersistenceUtils.getSharedDirectory()?.appendingPathComponent("Storage").appendingPathComponent("User") static let accountsPath = PersistenceUtils.getDocumentDirectory()!.appendingPathComponent("Account") static let sharedAccountsPath = PersistenceUtils.getSharedDirectory()?.appendingPathComponent("Storage").appendingPathComponent("Account") } struct Config { static var keychainAccessGroup: String? { guard let dict = NSDictionary(contentsOfFile: Bundle.main.path(forResource: "Config", ofType: "plist")!) else { return nil } guard let prefix = dict.value(forKey: "App ID Prefix") as? String, let identifier = dict.value(forKey: "Shared Keychain Identifier") as? String else { return nil } return "\(prefix).\(identifier)" } } struct UI { static let defaultLabelFont = "Lato" static let paleGreyColor = UIColor(red: 229.0 / 255.0, green: 236.0 / 255.0, blue: 237.0 / 255.0, alpha: 1.0) static let darkGrey = UIColor(red: 140.0 / 255.0, green: 150.0 / 255.0, blue: 171.0 / 255.0, alpha: 1.0) static let silver = UIColor(red: 198.0 / 255.0, green: 203.0 / 255.0, blue: 213.0 / 255.0, alpha: 1.0) static let greyBlue = UIColor(red: 107.0 / 255.0, green: 120.0 / 255.0, blue: 151.0 / 255.0, alpha: 1.0) static let skyBlue = UIColor(red: 96.0 / 255.0, green: 205.0 / 255.0, blue: 1.0, alpha: 1.0) static let steel = UIColor(red: 108.0 / 255.0, green: 117.0 / 255.0, blue: 155.0 / 255.0, alpha: 1.0) static let backgroundColor = UIColor(red: 244.0 / 255.0, green: 245 / 255.0, blue: 248 / 255.0, alpha: 1.0) static let brightAqua = UIColor(red: 8.0 / 255.0, green: 232.0 / 255.0, blue: 222.0 / 255.0, alpha: 1.0) static let clearBlue = UIColor(red: 46.0 / 255.0, green: 126.0 / 255.0, blue: 242.0 / 255.0, alpha: 1.0) static let grapefruit = UIColor(red: 255.0 / 255.0, green: 98.0 / 255.0, blue: 96.0 / 255.0, alpha: 1.0) static let weirdGreen = UIColor(red: 59.0 / 255, green: 222.0 / 255, blue: 134.0 / 255, alpha: 1.0) static let veryLightBlue = UIColor(red: 225.0 / 255.0, green: 232.0 / 255.0, blue: 245.0 / 255.0, alpha: 1.0) } struct Identifiers { static let accountCell = "accountCell" static let jobCell = "jobCell" static let folderCell = "folderCell" static let buildCell = "buildCell" static let buildQueueCell = "buildQueueCell" static let favoritesCell = "favoritesCell" static let favoritesHeaderCell = "favoritesHeaderCell" static let jobsHeaderCell = "jobsHeaderCell" static let jenkinsCell = "jenkinsCell" static let staticBuildInfoCell = "staticBuildInfoCell" static let longBuildInfoCell = "longBuildInfoCell" static let moreInfoBuildCell = "moreInfoBuildCell" static let changeCell = "changeCell" static let testResultCell = "testResultCell" static let testResultErrorDetailsCell = "testResultErrorDetailsCell" static let computerCell = "computerCell" static let pluginCell = "pluginCell" static let userCell = "userCell" static let artifactsCell = "artifactsCell" static let parameterCell = "parameterCell" static let buildsFilteringCell = "buildsFilteringCell" static let titleCell = "titleCell" static let jobOverViewCell = "jobOverViewCell" static let specialBuildCell = "specialBuildCell" static let headerCell = "headerCell" static let settingsCell = "settingsCell" static let actionCell = "actionCell" static let buildCauseCell = "buildCauseCell" static let dependencyDataCell = "dependencyDataCell" static let creationCell = "creationCell" static let faqCell = "faqCell" static let detailContentCell = "detailContentCell" static let actionHeader = "actionHeader" static let showJobsSegue = "showJobsSegue" static let showJobSegue = "showJobSegue" static let showBuildsSegue = "showBuildsSegue" static let showBuildSegue = "showBuildSegue" static let showBuildQueueSegue = "showBuildQueueSegue" static let showJenkinsSegue = "showJenkinsSegue" static let showConsoleOutputSegue = "showConsoleOutputSegue" static let showChangesSegue = "showChangesSegue" static let showTestResultsSegue = "showTestResultsSegue" static let showTestResultSegue = "showTestResultSegue" static let showComputersSegue = "showComputersSegue" static let showComputerSegue = "showComputerSegue" static let showUsersSegue = "showUsersSegue" static let showPluginsSegue = "showPluginsSegue" static let editAccountSegue = "editAccountSegue" static let showArtifactsSegue = "showArtifactsSegue" static let showFolderSegue = "showFolderSegue" static let showParametersSegue = "showParametersSegue" static let didAddAccountSegue = "didAddAccountSegue" static let showInformationSegue = "showInformationSegue" static let showAccountsSegue = "showAccountsSegue" static let showUserSegue = "showUserSegue" static let showPluginSegue = "showPluginSegue" static let githubAccountSegue = "githubAccountSegue" static let aboutSegue = "aboutSegue" static let faqSegue = "FAQSegue" static let favoritesShortcutItemType = "com.mobilabsolutions.favorites.shortcutItem" static let currentAccountBaseUrlUserDefaultsKey = "currentAccountBaseUrlUserDefaultsKey" static let favoriteStatusToggledNotification: Notification.Name = .init(rawValue: "favoriteStatusToggledNotification") static let remoteConfigNewAccountDesignKey = "new_account_design_active" static let remoteConfigShowDisplayNameFieldKey = "display_name_field_active" static let remoteConfigFAQListKey = "faq_item_list" } struct JSON { static let allViews = "All" static let views = "views" static let name = "name" static let url = "url" static let jobs = "jobs" static let color = "color" static let builds = "builds" static let firstBuild = "firstBuild" static let absoluteUrl = "absoluteUrl" static let fullName = "fullName" static let blocked = "blocked" static let buildable = "buildable" static let id = "id" static let inQueueSince = "inQueueSince" static let params = "params" static let stuck = "stuck" static let why = "why" static let task = "task" static let buildableStartMilliseconds = "buildableStartMilliseconds" static let actions = "actions" static let items = "items" static let age = "age" static let className = "className" static let duration = "duration" static let errorDetails = "errorDetails" static let errorStackTrace = "errorStackTrace" static let failedSince = "failedSince" static let skipped = "skipped" static let skippedMessage = "skippedMessage" static let status = "status" static let stdout = "stdout" static let stderr = "stderr" static let reportUrl = "reportUrl" static let cases = "cases" static let timestamp = "timestamp" static let number = "number" static let empty = "empty" static let failCount = "failCount" static let passCount = "passCount" static let skipCount = "skipCount" static let suites = "suites" static let child = "child" static let result = "result" static let totalCount = "totalCount" static let childReports = "childReports" static let urlName = "urlName" static let active = "active" static let shortName = "shortName" static let bundled = "bundled" static let deleted = "deleted" static let downgradable = "downgradable" static let enabled = "enabled" static let hasUpdate = "hasUpdate" static let longName = "longName" static let pinned = "pinned" static let supportsDynamicLoad = "supportsDynamicLoad" static let version = "version" static let dependencies = "dependencies" static let optional = "optional" static let plugins = "plugins" static let description = "description" static let nodeDescription = "nodeDescription" static let mode = "mode" static let nodeName = "nodeName" static let lastChange = "lastChange" static let project = "project" static let user = "user" static let users = "users" static let availablePhysicalMemory = "availablePhysicalMemory" static let availableSwapSpace = "availableSwapSpace" static let totalPhysicalMemory = "totalPhysicalMemory" static let totalSwapSpace = "totalSwapSpace" static let artifacts = "artifacts" static let fileName = "fileName" static let relativePath = "relativePath" static let crumb = "crumb" static let crumbRequestField = "crumbRequestField" static let type = "type" static let defaultParameterValue = "defaultParameterValue" static let value = "value" static let parameterDefinitions = "parameterDefinitions" static let property = "property" static let choices = "choices" static let projectName = "projectName" } struct Networking { static let successCodes = [200, 201, 202, 203, 204, 205, 206, 207, 208, 226] } struct API { static let consoleOutput = "/consoleText" static let jobListAdditionalQueryItems = [ URLQueryItem(name: "tree", value: "views[name,url,jobs[name,url,color,healthReport[description,score,iconClassName],lastBuild[timestamp,number,url]]],nodeDescription,nodeName,mode,description"), ] static let jobListQuietingDownAdditionalQueryItems = [ URLQueryItem(name: "tree", value: "quietingDown"), ] static let jobAdditionalQueryItems: [URLQueryItem] = { let changeSetFields = "kind,items[commitId,timestamp,comment,date,msg,affectedPaths,author[absoluteUrl,fullName]]" let buildFields = "duration,timestamp,fullDisplayName,result,id,url,artifacts,actions,number,artifacts[fileName,relativePath],changeSet[\(changeSetFields)],changeSets[\(changeSetFields)]" return [ URLQueryItem(name: "tree", value: "color,url,name,healthReport[description,score,iconClassName],lastBuild[\(buildFields)],lastStableBuild[\(buildFields)],lastSuccessfulBuild[\(buildFields)],lastCompletedBuilds[\(buildFields)],builds[\(buildFields)],property[parameterDefinitions[*]],actions[*[*]]"), ] }() static let jobBuildIdsAdditionalQueryItems: [URLQueryItem] = [URLQueryItem(name: "tree", value: "builds[id]")] static let testReport = "/testReport" static let testReportAdditionalQueryItems = [ URLQueryItem(name: "tree", value: "suites[name,cases[className,name,status]],childReports[child[url],result[suites[name,cases[className,name,status]],failCount,passCount,skipCount]],failCount,skipCount,passCount,totalCount"), ] static let buildQueue = "/queue" static let buildQueueAdditionalQueryItems = [URLQueryItem(name: "tree", value: "items[url,why,blocked,buildable,id,inQueueSince,params,stuck,task[name,url,color,healthReport[description,score,iconClassName]],actions[causes[shortDescription,userId,username],failCount,skipCount,totalCount,urlName],buildableStartMilliseconds]")] static let computer = "/computer" static let plugins = "/pluginManager" static let pluginsAdditionalQueryItems = [ URLQueryItem(name: "depth", value: "2"), ] static let users = "/asynchPeople" static let usersAdditionalQueryItems = [ URLQueryItem(name: "tree", value: "users[*,user[id,fullName,description,absoluteUrl]]"), ] static let artifact = "/artifact" static let crumbIssuer = "/crumbIssuer" static let quietDown = "/quietDown" static let cancelQuietDown = "/cancelQuietDown" static let restart = "/restart" static let safeRestart = "/safeRestart" static let exit = "/exit" static let safeExit = "/safeExit" } }
mit
c9ee3aea660c1cca340fc377eea44c57
49.058824
335
0.666275
4.386598
false
false
false
false
garyshirk/ThriftStoreLocator1
ThriftStoreLocator/ModelManager.swift
1
6375
// // ModelManager.swift // ThriftStoreLocator // // Created by Gary Shirk on 2/28/17. // Copyright © 2017 Gary Shirk. All rights reserved. // import Foundation import CoreData private let _shareManager = ModelManager() class ModelManager { class var shareManager: ModelManager { return _shareManager } var networkLayer = NetworkLayer() var dataLayer = DataLayer() func getAllStoresOnMainThread() -> [Store] { return dataLayer.getAllStoresOnMainThread() } func getLocationFilteredStores(forPredicate predicate: NSPredicate) -> [Store] { return dataLayer.getLocationFilteredStoresOnMainThread(forPredicate: predicate) } func deleteAllStoresFromCoreDataExceptFavs(modelManagerDeleteAllCoreDataExceptFavsUpdater: @escaping (ErrorType) -> Void) { self.dataLayer.deleteCoreDataObjectsExceptFavorites(deleteAllStoresExceptFavsUpdater: { error in modelManagerDeleteAllCoreDataExceptFavsUpdater(error) }) } func postFavoriteToServer(store: Store, forUser user: String, modelManagerPostFavUpdater: @escaping (ErrorType) -> Void) { self.networkLayer.postFavorite(store: store, forUser: user, networkLayerPostFavUpdater: { [weak self] networkError in guard let strongSelf = self else { return } if networkError == .none { strongSelf.dataLayer.updateFavorite(isFavOn: true, forStoreEntity: store, saveInBackgroundSuccess: { dataLayerError in if dataLayerError == .none { modelManagerPostFavUpdater(ErrorType.none) } else { modelManagerPostFavUpdater(dataLayerError) } }) } else { modelManagerPostFavUpdater(networkError) } }) } func removeFavoriteFromServer(store: Store, forUser user: String, modelManagerPostFavUpdater: @escaping (ErrorType) -> Void) { self.networkLayer.removeFavorite(store: store, forUser: user, networkLayerRemoveFavUpdater: { [weak self] networkError in guard let strongSelf = self else { return } if networkError == .none { strongSelf.dataLayer.updateFavorite(isFavOn: false, forStoreEntity: store, saveInBackgroundSuccess: { dataLayerError in if dataLayerError == .none { modelManagerPostFavUpdater(.none) } else { modelManagerPostFavUpdater(dataLayerError) } }) } else { modelManagerPostFavUpdater(networkError) } }) } func listFavorites(modelManagerListFavoritesUpdater: ([Store]) -> Void) { let stores = self.dataLayer.getFavoriteStoresOnMainThread() modelManagerListFavoritesUpdater(stores) } func loadFavoritesFromServer(forUser user: String, modelManagerLoadFavoritesUpdater: @escaping([Store], ErrorType) -> Void) { self.networkLayer.loadFavoritesFromServer(forUser: user, networkLayerLoadFavoritesUpdater: { [weak self] (stores, networkError) in guard let strongSelf = self else { return } if networkError == .none { strongSelf.dataLayer.saveInBackground(stores: stores, withDeleteOld: true, isFavs: true, saveInBackgroundSuccess: { dataLayerError in if dataLayerError == .none { let storeEntities = strongSelf.getAllStoresOnMainThread() modelManagerLoadFavoritesUpdater(storeEntities, .none) } else { modelManagerLoadFavoritesUpdater([Store](), dataLayerError) } }) } else { modelManagerLoadFavoritesUpdater([Store](), networkError) } }) } // Use for loading stores by county func loadStoresFromServer(forQuery query: String, withDeleteOld deleteOld: Bool, modelManagerStoresUpdater: @escaping ([Store], ErrorType) -> Void) { self.networkLayer.loadStoresFromServer(forQuery: query, networkLayerStoreUpdater: { [weak self] (stores, networkError) in guard let strongSelf = self else { return } if networkError == .none { strongSelf.dataLayer.saveInBackground(stores: stores, withDeleteOld: deleteOld, isFavs: false, saveInBackgroundSuccess: { dataLayerError in if dataLayerError == .none { let storeEntities = strongSelf.getAllStoresOnMainThread() modelManagerStoresUpdater(storeEntities, ErrorType.none) } else { modelManagerStoresUpdater([Store](), dataLayerError) } }) } else { modelManagerStoresUpdater([Store](), networkError) } }) } // Use for loading stores by state func loadStoresFromServer(forQuery query: String, withDeleteOld deleteOld: Bool, withLocationPred predicate: NSPredicate, modelManagerStoresUpdater: @escaping ([Store], ErrorType) -> Void) { self.networkLayer.loadStoresFromServer(forQuery: query, networkLayerStoreUpdater: { [weak self] (stores, networkError) in guard let strongSelf = self else { return } if networkError == .none { strongSelf.dataLayer.saveInBackground(stores: stores, withDeleteOld: deleteOld, isFavs: false, saveInBackgroundSuccess: { dataLayerError in if dataLayerError == .none { let storeEntities = strongSelf.getLocationFilteredStores(forPredicate: predicate) modelManagerStoresUpdater(storeEntities, ErrorType.none) } else { modelManagerStoresUpdater([Store](), dataLayerError) } }) } else { modelManagerStoresUpdater([Store](), networkError) } }) } }
mit
2e571cf8f5a76c3764cd00e6de9f67e6
40.934211
194
0.594603
5.518615
false
false
false
false
kevinwl02/Swift-BDD-with-MVP-example
BeerSearch/BeerSearch/Source/Search/SearchPresenter.swift
1
1166
// // SearchPresenter.swift // BeerSearch // // Created by Kevin on 6/17/17. // Copyright © 2017 Kevin Wong. All rights reserved. // import Foundation class SearchPresenter: SearchContractPresenter { weak var view: SearchContractView? let searchService: SearchService init(view: SearchContractView, searchService: SearchService) { self.view = view self.searchService = searchService } func search(text: String) { guard let view = view else { return } let searchTerm = SearchTerm(text: text) if searchTerm.hasValidWordCount() { searchService.searchBeers(foodText: text, completion: { (beerList, error) in if error != nil { view.displayErrorMessage("There was a problem fetching your beers. Please try again later.") } else { view.displayBeerImages(beerList.map({ beer -> String in return beer.imageURL })) } }) } else { view.displayMessage("Don't go too crazy with the food!") } } }
mit
fb519388501400ed73a901a4cb32560a
28.125
112
0.571674
4.716599
false
false
false
false
coolster01/PokerTouch
PokerTouch/GameViewController.swift
1
12667
// // GameViewController.swift // PokerTouch // // Created by Subhi Sbahi on 5/28/17. // Copyright © 2017 Rami Sbahi. All rights reserved. // import UIKit class GameViewController: UIViewController { static var myRunner = PokerRunner(players: []) var myCurrentPlayer = Player(name: "") static var count = 0 static var allIn = false static var smallBlind = false static var bigBlind = false @IBOutlet weak var Card1: UIImageView! @IBOutlet weak var Card2: UIImageView! @IBOutlet weak var Card3: UIImageView! @IBOutlet weak var Card4: UIImageView! @IBOutlet weak var Card5: UIImageView! @IBOutlet weak var PlayerLabel1: UILabel! @IBOutlet weak var PlayerLabel2: UILabel! @IBOutlet weak var PlayerLabel3: UILabel! @IBOutlet weak var PlayerLabel4: UILabel! @IBOutlet weak var PlayerLabel5: UILabel! @IBOutlet weak var PlayerLabel6: UILabel! @IBOutlet weak var PlayerLabel7: UILabel! @IBOutlet weak var PlayerLabel8: UILabel! @IBOutlet weak var PlayerLabel9: UILabel! @IBOutlet weak var MoneyLabel1: UILabel! @IBOutlet weak var MoneyLabel2: UILabel! @IBOutlet weak var MoneyLabel3: UILabel! @IBOutlet weak var MoneyLabel4: UILabel! @IBOutlet weak var MoneyLabel5: UILabel! @IBOutlet weak var MoneyLabel6: UILabel! @IBOutlet weak var MoneyLabel7: UILabel! @IBOutlet weak var MoneyLabel8: UILabel! @IBOutlet weak var MoneyLabel9: UILabel! @IBOutlet weak var BetLabel1: UILabel! @IBOutlet weak var BetLabel2: UILabel! @IBOutlet weak var BetLabel3: UILabel! @IBOutlet weak var BetLabel4: UILabel! @IBOutlet weak var BetLabel5: UILabel! @IBOutlet weak var BetLabel6: UILabel! @IBOutlet weak var BetLabel7: UILabel! @IBOutlet weak var BetLabel8: UILabel! @IBOutlet weak var BetLabel9: UILabel! @IBOutlet weak var TurnLabel: UILabel! @IBOutlet weak var PotLabel: UILabel! @IBOutlet weak var ScrollView: UIScrollView! @IBOutlet weak var RaiseButton: UIButton! @IBOutlet weak var CallButton: UIButton! @IBOutlet weak var CheckButton: UIButton! @IBOutlet weak var FoldButton: UIButton! var flipped = false @IBOutlet weak var Card1Image: UIImageView! @IBOutlet weak var Card2Image: UIImageView! @IBOutlet weak var EndButton: UIButton! @IBAction func flip(_ sender: Any) { if(flipped == false) { Card1Image.image = UIImage(named: myCurrentPlayer.card1.getImage()) Card2Image.image = UIImage(named: myCurrentPlayer.card2.getImage()) flipped = true } else { Card1Image.image = UIImage(named: "back") Card2Image.image = UIImage(named: "back") flipped = false } } @IBAction func fold(_ sender: Any) { GameViewController.myRunner.fold() if(GameViewController.myRunner.othersFolded()) { GameViewController.myRunner.win(winner: GameViewController.myRunner.remainingIndex()) self.performSegue(withIdentifier: "foldSegue", sender: nil) } self.postButton() } @IBAction func check(_ sender: Any) { self.postButton() } @IBAction func call(_ sender: Any) // match bet { GameViewController.myRunner.call() self.postButton() } // Ask how much to add, tell currentNecessary, make raise if valid @IBAction func raise(_ sender: Any) { if(GameViewController.allIn) { GameViewController.myRunner.allIn() self.postButton() } else if(GameViewController.smallBlind) { GameViewController.myRunner.smallBlind() self.postButton() } else if(GameViewController.bigBlind) { GameViewController.myRunner.bigBlind() self.postButton() } else { //1. Create the alert controller. var myMessage: String = "" if(GameViewController.myRunner.currentNecessary > 0) { myMessage = "Bet at least " + String(GameViewController.myRunner.currentNecessary) } let alert = UIAlertController(title: "How much would you like to add?", message: myMessage, preferredStyle: .alert) //2. Add the text field. alert.addTextField { (textField) in textField.text = "" textField.keyboardType = .numberPad } // 3. Grab the value from the text field alert.addAction(UIAlertAction(title: "Enter", style: .default, handler: { [weak alert] (_) in let textField = alert?.textFields![0] // Force unwrapping because we know it exists. let eAmount: Int? = Int((textField?.text)!) if(eAmount != nil && eAmount! >= GameViewController.myRunner.currentNecessary) { GameViewController.myRunner.bet(amount: eAmount!) self.postButton() } else { let otherAlert = UIAlertController(title: "Please bet at least \(GameViewController.myRunner.currentNecessary)", message: "", preferredStyle: .alert) otherAlert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.cancel, handler: nil)) self.present(otherAlert, animated: true, completion: nil) // ask again - no input } })) alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: nil)) // 4. Present the alert. self.present(alert, animated: true, completion: nil) } } /* Standard updates after raise/check/call/fold */ func postButton() { self.updateLabels() self.disableButtons() GameViewController.myRunner.nextPlayer() self.EndButton.isHidden = false } func disableButtons() { RaiseButton.isEnabled = false CallButton.isEnabled = false CheckButton.isEnabled = false FoldButton.isEnabled = false } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(false) if(ViewController.newGame) // make sure only runs when new game { var myPlayers: [Player] = [] for playerName in ViewController.playerNames { myPlayers.append(Player(name: playerName)) } GameViewController.myRunner = PokerRunner(players: myPlayers) TurnLabel.text = myPlayers[0].myName + "'s Turn" PotLabel.text = "Pot: 0" EndButton.isHidden = true flipped = false self.updateLabels() ViewController.newGame = false } myCurrentPlayer = GameViewController.myRunner.currentPlayer let currentDeck = GameViewController.myRunner.myDeck if(GameViewController.myRunner.stage >= 2) { Card1.image = UIImage(named:currentDeck.communityCards[0].getImage()) Card2.image = UIImage(named: currentDeck.communityCards[1].getImage()) Card3.image = UIImage(named: currentDeck.communityCards[2].getImage()) } if(GameViewController.myRunner.stage >= 3) { Card4.image = UIImage(named: currentDeck.communityCards[3].getImage()) } if(GameViewController.myRunner.stage >= 4) { Card5.image = UIImage(named: currentDeck.communityCards[4].getImage()) } if(GameViewController.myRunner.currentPlayerIndex > 5) { var offset = ScrollView.contentOffset offset.y = ScrollView.contentSize.height + ScrollView.contentInset.bottom - ScrollView.bounds.size.height ScrollView.setContentOffset(offset, animated: true) } EndButton.isHidden = true flipped = false GameViewController.allIn = false GameViewController.smallBlind = false GameViewController.bigBlind = false self.updateLabels() self.adaptButtons() } // disables buttons that are not permitted func adaptButtons() { if(!GameViewController.myRunner.canCheck()) // can't check b/c doesn't have max bet (so can call) { CheckButton.isEnabled = false } else // can check b/c has max bet (so call doesn't make sense) { CallButton.isEnabled = false } if(!GameViewController.myRunner.canRaise()) { RaiseButton.isEnabled = false } else if(GameViewController.myRunner.mustAllIn()) { RaiseButton.setTitle("All-In", for: .normal) GameViewController.allIn = true CallButton.isEnabled = false } else if(GameViewController.myRunner.isSmallBlind()) { RaiseButton.setTitle("Small Blind", for: .normal) GameViewController.smallBlind = true CheckButton.isEnabled = false } else if(GameViewController.myRunner.isBigBlind()) { RaiseButton.setTitle("Big Blind", for: .normal) GameViewController.bigBlind = true CallButton.isEnabled = false } } func updateLabels() { let playerLabels = [PlayerLabel1, PlayerLabel2, PlayerLabel3, PlayerLabel4, PlayerLabel5, PlayerLabel6, PlayerLabel7, PlayerLabel8, PlayerLabel9] let moneyLabels = [MoneyLabel1, MoneyLabel2, MoneyLabel3, MoneyLabel4, MoneyLabel5, MoneyLabel6, MoneyLabel7, MoneyLabel8, MoneyLabel9] let betLabels = [BetLabel1, BetLabel2, BetLabel3, BetLabel4, BetLabel5, BetLabel6, BetLabel7, BetLabel8, BetLabel9] let myPlayers = GameViewController.myRunner.myPlayers for i in 0...8 { if(i < myPlayers.count) { playerLabels[i]?.text = myPlayers[i].myName if(myPlayers[i].allIn) { betLabels[i]?.text = "Bet: " + String(myPlayers[i].bet) moneyLabels[i]?.text = "ALL-IN" betLabels[i]?.textColor = UIColor.red playerLabels[i]?.textColor = UIColor.red moneyLabels[i]?.textColor = UIColor.red } else if(myPlayers[i].isBetting) { betLabels[i]?.text = "Betting: " + String(myPlayers[i].bet) moneyLabels[i]?.text = "Money: " + String(myPlayers[i].money) } else // folded { betLabels[i]?.text = "Bet: " + String(myPlayers[i].bet) moneyLabels[i]?.text = "Money: " + String(myPlayers[i].money) betLabels[i]?.textColor = UIColor.lightGray playerLabels[i]?.textColor = UIColor.lightGray moneyLabels[i]?.textColor = UIColor.lightGray } } else // player doesn't exist { playerLabels[i]?.text = "" moneyLabels[i]?.text = "" betLabels[i]?.text = "" } } PotLabel.text = "Pot: " + String(GameViewController.myRunner.pot) TurnLabel.text = myCurrentPlayer.myName + "'s Turn" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func EndTurn(_ sender: Any) { if(GameViewController.myRunner.stage == 5) { GameViewController.myRunner.determineWinner() self.performSegue(withIdentifier: "EndToHands", sender: nil) } else { self.performSegue(withIdentifier: "EndToHandOff", sender: nil) } } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation /* override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
apache-2.0
46db3763ec72711783437241c76c5e7a
33.418478
165
0.5919
4.632772
false
false
false
false
borglab/SwiftFusion
Sources/SwiftFusion/Inference/Factor.swift
1
13611
// Copyright 2020 The SwiftFusion Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import _Differentiation import PenguinParallelWithFoundation import PenguinStructures /// A factor in a factor graph. public protocol Factor { /// A tuple type whose instances contain the values of the variables adjacent to this factor. associatedtype Variables: VariableTuple /// The IDs of the variables adjacent to this factor. var edges: Variables.Indices { get } /// Returns the error at `x`. /// /// This is typically interpreted as negative log-likelihood. func error(at x: Variables) -> Double } /// A factor whose `error` is a function of a vector-valued `errorVector` function. public protocol VectorFactor: Factor { /// The type of the error vector. // TODO: Add a description of what an error vector is. associatedtype ErrorVector: Vector /// Returns the error vector at `x`. func errorVector(at x: Variables) -> ErrorVector /// A factor whose variables are the `Differentiable` subset of `Self`'s variables. associatedtype LinearizableComponent: LinearizableFactor where LinearizableComponent.ErrorVector == ErrorVector /// Returns the linearizable component of `self` at `x`, and returns the `Differentiable` subset /// of `x`. func linearizableComponent(at x: Variables) -> (LinearizableComponent, LinearizableComponent.Variables) /// Returns the linearizations of `factors` at `x`. /// /// The reason this method operates on a collection instead of a single element is so that the /// result can be type-erased without paying a huge performance cost. The type-erasure lets the /// implementation choose the most efficient type for storing the linearization, without /// affecting the callers. /// /// A default implementation using Automatic Differentiation is provided. Conforming types may /// want to override this implementation if they have a faster manual linearization /// implementation. static func linearized<C: Collection>(_ factors: C, at x: VariableAssignments) -> AnyGaussianFactorArrayBuffer where C.Element == Self } /// A factor whose `errorVector` function is linearizable with respect to all the variables. public protocol LinearizableFactor: VectorFactor where Variables: DifferentiableVariableTuple, Variables.TangentVector: Vector { /// Returns the error vector given the values of the adjacent variables. @differentiable func errorVector(at x: Variables) -> ErrorVector } extension LinearizableFactor { public func linearizableComponent(at x: Variables) -> (Self, Variables) { return (self, x) } } /// A factor whose `errorVector` is a linear function of the variables, plus a constant. public protocol GaussianFactor: LinearizableFactor where LinearizableComponent.Variables.TangentVector == Variables { /// The linear component of `errorVector`. func errorVector_linearComponent(_ x: Variables) -> ErrorVector /// The adjoint (aka "transpose" or "dual") of the linear component of `errorVector`. func errorVector_linearComponent_adjoint(_ y: ErrorVector) -> Variables } /// A linear approximation of a linearizable factor. public protocol LinearApproximationFactor: GaussianFactor { /// Creates a factor that linearly approximates `f` at `x`. init<F: LinearizableFactor>(linearizing f: F, at x: F.Variables) where F.Variables.TangentVector == Variables, F.ErrorVector == ErrorVector } // MARK: - `VariableTuple`. /// The variable values adjacent to a factor. public protocol VariableTuple: TupleProtocol where Tail: VariableTuple { /// `UnsafePointer`s to the base addresss of buffers containing values of the variable types in /// `Self`. associatedtype BufferBaseAddresses: TupleProtocol /// `UnsafeMutablePointer`s to the base addresss of buffers containing values of the variable /// types in `Self`. associatedtype MutableBufferBaseAddresses: TupleProtocol /// The indices used to address a `VariableTuple` scattered across per-type buffers. associatedtype Indices: TupleProtocol /// Invokes `body` with the base addressess of buffers from `v` storing /// instances of the variable types in `self`. // TODO: `v` should be the receiver. static func withMutableBufferBaseAddresses<R>( _ v: inout VariableAssignments, _ body: (MutableBufferBaseAddresses) -> R ) -> R /// Invokes `body` with the base addressess of buffers from `v` storing instances of the variable /// types in `self`. // TODO: `v` should be the receiver. static func withBufferBaseAddresses<R>( _ v: VariableAssignments, _ body: (BufferBaseAddresses) -> R ) -> R /// Returns a copy of `p` through which memory can't be mutated. // TODO: Maybe `pointers` should be the receiver. static func withoutMutation(_ p: MutableBufferBaseAddresses) -> BufferBaseAddresses /// Gathers the values at the given `positions` in the buffers having the given `baseAddresses`. init(at positions: Indices, in baseAddresses: BufferBaseAddresses) /// Scatters `self` into the given positions of buffers having the given `baseAddresses`. func assign(into positions: Indices, in baseAddresses: MutableBufferBaseAddresses) } extension Empty: VariableTuple { public typealias BufferBaseAddresses = Self public typealias MutableBufferBaseAddresses = Self public typealias Indices = Self public static func withMutableBufferBaseAddresses<R>( _ : inout VariableAssignments, _ body: (MutableBufferBaseAddresses) -> R ) -> R { return body(Empty()) } public static func withBufferBaseAddresses<R>( _ : VariableAssignments, _ body: (BufferBaseAddresses) -> R ) -> R { return body(Empty()) } public static func withoutMutation(_ p: MutableBufferBaseAddresses) -> BufferBaseAddresses { Self() } public init(at _: Indices, in _: MutableBufferBaseAddresses) { self.init() } public func assign(into _: Indices, in _: MutableBufferBaseAddresses) {} } extension Tuple: VariableTuple where Tail: VariableTuple { /// `UnsafePointer`s to the base addresss of buffers containing values of the variable types in /// `Self`. public typealias BufferBaseAddresses = Tuple<UnsafePointer<Head>, Tail.BufferBaseAddresses> /// `UnsafeMutablePointer`s to the base addresss of buffers containing values of the variable /// types in `Self`. public typealias MutableBufferBaseAddresses = Tuple<UnsafeMutablePointer<Head>, Tail.MutableBufferBaseAddresses> public typealias Indices = Tuple<TypedID<Head>, Tail.Indices> /// Invokes `body` with the base addressess of buffers from `v` storing instances of the variable /// types in `self`. public static func withMutableBufferBaseAddresses<R>( _ v: inout VariableAssignments, _ body: (MutableBufferBaseAddresses) -> R ) -> R { let headPointer = v.storage[ existingKey: ObjectIdentifier(Head.self) ][ existingElementType: Type<Head>() ].withUnsafeMutableBufferPointer { $0.baseAddress.unsafelyUnwrapped } return Tail.withMutableBufferBaseAddresses(&v) { body(.init(head: headPointer, tail: $0)) } } /// Invokes `body` with the base addressess of buffers from `v` storing instances of the variable /// types in `self`. // TODO: `v` should be the receiver. public static func withBufferBaseAddresses<R>( _ v: VariableAssignments, _ body: (BufferBaseAddresses) -> R ) -> R { let headPointer = v.storage[ existingKey: ObjectIdentifier(Head.self) ][ existingElementType: Type<Head>() ].withUnsafeBufferPointer { $0.baseAddress.unsafelyUnwrapped } return Tail.withBufferBaseAddresses(v) { body(.init(head: headPointer, tail: $0)) } } public static func withoutMutation(_ p: MutableBufferBaseAddresses) -> BufferBaseAddresses { return BufferBaseAddresses( head: .init(p.head), tail: Tail.withoutMutation(p.tail) ) } /// Gathers the values at the given `positions` in the buffers having the given `baseAddresses`. public init(at positions: Indices, in baseAddresses: BufferBaseAddresses) { self.init( head: baseAddresses.head[positions.head.perTypeID], tail: Tail(at: positions.tail, in: baseAddresses.tail) ) } /// Scatters `self` into the given positions of buffers having the given `baseAddresses`. public func assign(into positions: Indices, in variableBufferBases: MutableBufferBaseAddresses) { (variableBufferBases.head + positions.head.perTypeID) .assign(repeating: self.head, count: 1) self.tail.assign(into: positions.tail, in: variableBufferBases.tail) } } /// Tuple of differentiable variable types suitable for a factor. public protocol DifferentiableVariableTuple: Differentiable & VariableTuple where TangentVector: DifferentiableVariableTuple { /// Returns the indices of the linearized variables corresponding to `indices` in the linearized /// factor graph. static func linearized(_ indices: Indices) -> TangentVector.Indices } extension Empty: DifferentiableVariableTuple { public static func linearized(_ indices: Indices) -> TangentVector.Indices { indices } } extension Tuple: DifferentiableVariableTuple where Head: Differentiable, Tail: DifferentiableVariableTuple { public static func linearized(_ indices: Indices) -> TangentVector.Indices { TangentVector.Indices( head: TypedID<Head.TangentVector>(indices.head.perTypeID), tail: Tail.linearized(indices.tail) ) } } // MARK: - Default implementation of `linearized`. extension VectorFactor { /// Returns the linearizations of `factors` at `x`. /// /// The reason this method operates on a collection instead of a single element is so that the /// result can be type-erased without paying a huge performance cost. The type-erasure lets the /// implementation choose the most efficient type for storing the linearization, without /// affecting the callers. public static func linearized<C: Collection>(_ factors: C, at x: VariableAssignments) -> AnyGaussianFactorArrayBuffer where C.Element == Self { typealias TangentVector = LinearizableComponent.Variables.TangentVector typealias Linearization<A> = Type<JacobianFactor<A, ErrorVector>> where A: SourceInitializableCollection, A.Element: Vector & DifferentiableVariableTuple // For small dimensions, we use a fixed size array in the linearization because the allocation // and indirection overheads of a dynamically sized array are relatively big. // // For larger dimensions, dynamically sized array are more convenient (no need to define a // new type and case for each size) and in some cases also happen to be faster than fixed size // arrays. // // We chose 4 as the cutoff based on benchmark results: // - "Pose2SLAM.FactorGraph", which heavily uses 3 dimensional error vectors, is ~30% faster // with a fixed size array than with a dynamically sized array. // - "Pose3SLAM.FactorGraph", which heavily uses 6 dimensional error vectors, is ~3% faster // with a dynamically sized array than with a fixed size array. // - "Pose3SLAM.sphere2500", which heavily uses 12 dimensional error vectors, has the same // performance with fixed size and dynamically sized arrays. switch TypeID(ErrorVector.self) { case TypeID(Vector1.self): return .init( Self.linearized(factors, at: x, linearization: Linearization<Array1<TangentVector>>())) case TypeID(Vector2.self): return .init( Self.linearized(factors, at: x, linearization: Linearization<Array2<TangentVector>>())) case TypeID(Vector3.self): return .init( Self.linearized(factors, at: x, linearization: Linearization<Array3<TangentVector>>())) case TypeID(Vector4.self): return .init( Self.linearized(factors, at: x, linearization: Linearization<Array4<TangentVector>>())) default: return .init( Self.linearized(factors, at: x, linearization: Linearization<Array<TangentVector>>())) } } /// Returns the linearizations of `factors` at `x`, as an array of `Linearization`s. private static func linearized<C: Collection, Linearization: LinearApproximationFactor>( _ factors: C, at x: VariableAssignments, linearization: Type<Linearization> ) -> ArrayBuffer<Linearization> where C.Element == Self, Linearization.Variables == LinearizableComponent.Variables.TangentVector, Linearization.ErrorVector == ErrorVector { Variables.withBufferBaseAddresses(x) { varsBufs in .init(ArrayBuffer<Linearization>( count: factors.count, minimumCapacity: factors.count) { b in ComputeThreadPools.local.parallelFor(n: factors.count) { (i, _) in let f = factors[factors.index(factors.startIndex, offsetBy: i)] let (fLinearizable, xLinearizable) = f.linearizableComponent(at: Variables(at: f.edges, in: varsBufs)) (b + i).initialize(to: Linearization(linearizing: fLinearizable, at: xLinearizable)) } }) } } }
apache-2.0
ba80393d339c1f60469a947c35d7c01c
39.751497
99
0.729557
4.445134
false
false
false
false
wendyabrantes/WAActivityIndicatorView
WAActivityIndicatorView/Animations/DotTriangleAnimation.swift
1
2348
// // DotTriangleAnimation.swift // WAActivityIndicatorViewExample // // Created by Wendy Abrantes on 03/10/2015. // Copyright © 2015 ABRANTES DIGITAL LTD. All rights reserved. // import UIKit struct DotTriangleAnimation: WAActivityIndicatorProtocol { func setupAnimationInLayer(layer: CALayer, size: CGFloat, tintColor: UIColor) { let dotSize = size / 4 let transformX : CGFloat = size-dotSize let dot = CAShapeLayer() dot.frame = CGRect( x: 0, y: 0, width:dotSize, height: dotSize) dot.path = UIBezierPath(ovalInRect: CGRect(x: 0, y:0, width: dotSize, height: dotSize)).CGPath dot.strokeColor = tintColor.CGColor dot.lineWidth = 1 dot.fillColor = UIColor.clearColor().CGColor let replicatorLayer = CAReplicatorLayer() replicatorLayer.frame = CGRect(x: 0,y: 0,width: dotSize,height: dotSize) replicatorLayer.instanceDelay = 0.0 replicatorLayer.instanceCount = 3 var transform = CATransform3DIdentity transform = CATransform3DTranslate(transform, transformX, 0, 0.0) transform = CATransform3DRotate(transform, (CGFloat(120.0)*CGFloat(M_PI))/CGFloat(180.0), 0.0, 0.0, 1.0) replicatorLayer.instanceTransform = transform replicatorLayer.addSublayer(dot) layer.addSublayer(replicatorLayer) dot.addAnimation(rotationAnimation(transformX), forKey: "rotateAnimation") } func rotationAnimation(transformX: CGFloat) -> CABasicAnimation{ let rotateAnim = CABasicAnimation(keyPath: "transform") let t = CATransform3DIdentity let t2 = CATransform3DRotate(t, 0.0, 0.0, 0.0, 0.0) rotateAnim.fromValue = NSValue.init(CATransform3D: t2) var t3 = CATransform3DTranslate(t, transformX, 0.0, 0.0) t3 = CATransform3DRotate(t3, (CGFloat(120.0)*CGFloat(M_PI))/CGFloat(180.0), 0.0, 0.0, 1.0) rotateAnim.toValue = NSValue.init(CATransform3D: t3) rotateAnim.autoreverses = false rotateAnim.repeatCount = HUGE rotateAnim.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) rotateAnim.duration = 0.8 return rotateAnim } }
mit
10464d2132f54e1c1a23fe39286734d7
34.560606
112
0.644653
4.362454
false
false
false
false
caicai0/ios_demo
load/thirdpart/SwiftKuery/Index.swift
1
3889
/** Copyright IBM Corporation 2017 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. */ // MARK: Index /// The SQL INDEX. public struct Index { private var name: String private var isUnique: Bool private var table: Table private var columns: [IndexColumn] /// Initialize an instance of Index. /// /// - Parameter name: The name of the index. /// - Parameter unique: An indication whether the index has to be unique. /// - Parameter on table: The table of the index. /// - Parameter columns: An array of columns of the index. public init(_ name: String, unique: Bool = false, on table: Table, columns: [IndexColumn]) { self.name = name self.isUnique = unique self.table = table self.columns = columns } /// Initialize an instance of Index. /// /// - Parameter name: The name of the index. /// - Parameter unique: An indication whether the index has to be unique. /// - Parameter on table: The table of the index. /// - Parameter columns: A list of columns of the index. public init(_ name: String, unique: Bool = false, on table: Table, columns: IndexColumn...) { self.init(name, unique: unique, on: table, columns: columns) } /// Create the index in the database. /// /// - Parameter connection: The connection to the database. /// - Parameter onCompletion: The function to be called when the execution of the query has completed. public func create(connection: Connection, onCompletion: @escaping ((QueryResult) -> ())) { do { let query = try description(connection: connection) connection.execute(query, onCompletion: onCompletion) } catch { onCompletion(.error(error)) } } /// Drop the index from the database. /// /// - Parameter connection: The connection to the database. /// - Parameter onCompletion: The function to be called when the execution of the query has completed. public func drop(connection: Connection, onCompletion: @escaping ((QueryResult) -> ())) { let queryBuilder = connection.queryBuilder var query = "DROP INDEX " + Utils.packName(name, queryBuilder: queryBuilder) if queryBuilder.dropIndexRequiresOnTableName { query += " ON " + Utils.packName(table._name, queryBuilder: queryBuilder) } connection.execute(query, onCompletion: onCompletion) } /// Return a String representation of the index create statement. /// /// - Returns: A String representation of the index create statement. /// - Throws: QueryError.syntaxError if statement build fails. public func description(connection: Connection) throws -> String { for column in columns { if column.table._name != table._name { throw QueryError.syntaxError("Index contains columns that do not belong to its table.") } } var query = "CREATE \(isUnique ? "UNIQUE" : "") INDEX " let queryBuilder = connection.queryBuilder query += Utils.packName(name, queryBuilder: queryBuilder) + " ON " + Utils.packName(table._name, queryBuilder: queryBuilder) + " (" query += columns.map { $0.buildIndex(queryBuilder: queryBuilder) }.joined(separator: ", ") + ")" return query } }
mit
3f5e81f18ac5b42fc653adc1823ae624
39.510417
140
0.65081
4.748474
false
false
false
false
RichardLClark/TimeView
UILabel+Additions.swift
1
744
// // UILabel+Additions.swift // TestClockFaceEditor // // Created by Richard Clark on 11/13/15. // Copyright © 2015 Richard Clark. All rights reserved. // import UIKit public extension UILabel { var glyphInsets: UIEdgeInsets { get { if let text = text { let glyphRect = text.boundingRect(font) let left = glyphRect.x let top = glyphRect.y let right = width - glyphRect.rightX let bottom = height - glyphRect.bottomY return UIEdgeInsets(top: top, left: left, bottom: bottom, right: right) } else { return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) } } } }
mit
c6ca5035ddd85a6627d1f7c95e1ba187
26.518519
87
0.549125
4.345029
false
false
false
false
stowy/LayoutKit
LayoutKitSampleApp/Benchmarks/FeedItemAutoLayoutView.swift
5
10230
// Copyright 2016 LinkedIn Corp. // 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. import UIKit /// A LinkedIn feed item that is implemented with Auto Layout. class FeedItemAutoLayoutView: UIView, DataBinder { let topBarView = TopBarView() let miniProfileView = MiniProfileView() let miniContentView = MiniContentView() let socialActionsView = SocialActionsView() let commentView = CommentView() override init(frame: CGRect) { super.init(frame: frame) backgroundColor = UIColor.white let views: [String: UIView] = [ "topBarView": topBarView, "miniProfileView": miniProfileView, "miniContentView": miniContentView, "socialActionsView": socialActionsView, "commentView": commentView ] addAutoLayoutSubviews(views) addConstraints(withVisualFormat: "V:|-0-[topBarView]-0-[miniProfileView]-0-[miniContentView]-0-[socialActionsView]-0-[commentView]-0-|", views: views) addConstraints(withVisualFormat: "H:|-0-[topBarView]-0-|", views: views) addConstraints(withVisualFormat: "H:|-0-[miniProfileView]-0-|", views: views) addConstraints(withVisualFormat: "H:|-0-[miniContentView]-0-|", views: views) addConstraints(withVisualFormat: "H:|-0-[socialActionsView]-0-|", views: views) addConstraints(withVisualFormat: "H:|-0-[commentView]-0-|", views: views) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setData(_ data: FeedItemData) { topBarView.actionLabel.text = data.actionText miniProfileView.posterNameLabel.text = data.posterName miniProfileView.posterHeadlineLabel.text = data.posterHeadline miniProfileView.posterTimeLabel.text = data.posterTimestamp miniProfileView.posterCommentLabel.text = data.posterComment miniContentView.contentTitleLabel.text = data.contentTitle miniContentView.contentDomainLabel.text = data.contentDomain commentView.actorCommentLabel.text = data.actorComment } override func sizeThatFits(_ size: CGSize) -> CGSize { return systemLayoutSizeFitting(CGSize(width: size.width, height: 0)) } } class CommentView: UIView { let actorImageView: UIImageView = { let i = UIImageView() i.image = UIImage(named: "50x50.png") i.setContentHuggingPriority(UILayoutPriorityRequired, for: .horizontal) i.setContentCompressionResistancePriority(UILayoutPriorityRequired, for: .horizontal) return i }() let actorCommentLabel: UILabel = UILabel() init() { super.init(frame: .zero) let views: [String: UIView] = [ "actorImageView": actorImageView, "actorCommentLabel": actorCommentLabel ] addAutoLayoutSubviews(views) addConstraints(withVisualFormat: "H:|-0-[actorImageView]-0-[actorCommentLabel]-0-|", views: views) addConstraints(withVisualFormat: "V:|-0-[actorImageView]-(>=0)-|", views: views) addConstraints(withVisualFormat: "V:|-0-[actorCommentLabel]-(>=0)-|", views: views) addConstraints(withVisualFormat: "V:[actorImageView]-(0@749)-|", views: views) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class MiniContentView: UIView { let contentImageView: UIImageView = { let i = UIImageView() i.image = UIImage(named: "350x200.png") i.contentMode = .scaleAspectFit i.backgroundColor = UIColor.orange return i }() let contentTitleLabel: UILabel = UILabel() let contentDomainLabel: UILabel = UILabel() init() { super.init(frame: .zero) let views: [String: UIView] = [ "contentImageView": contentImageView, "contentTitleLabel": contentTitleLabel, "contentDomainLabel": contentDomainLabel ] addAutoLayoutSubviews(views) addConstraints(withVisualFormat: "V:|-0-[contentImageView]-0-[contentTitleLabel]-0-[contentDomainLabel]-0-|", views: views) addConstraints(withVisualFormat: "H:|-0-[contentImageView]-0-|", views: views) addConstraints(withVisualFormat: "H:|-0-[contentTitleLabel]-0-|", views: views) addConstraints(withVisualFormat: "H:|-0-[contentDomainLabel]-0-|", views: views) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class MiniProfileView: UIView { let posterImageView: UIImageView = { let i = UIImageView() i.image = UIImage(named: "50x50.png") i.backgroundColor = UIColor.orange i.contentMode = .center i.setContentHuggingPriority(UILayoutPriorityRequired, for: .horizontal) i.setContentCompressionResistancePriority(UILayoutPriorityRequired, for: .horizontal) return i }() let posterNameLabel: UILabel = UILabel() let posterHeadlineLabel: UILabel = { let l = UILabel() l.numberOfLines = 3 return l }() let posterTimeLabel: UILabel = UILabel() let posterCommentLabel: UILabel = UILabel() init() { super.init(frame: .zero) let views: [String: UIView] = [ "posterImageView": posterImageView, "posterNameLabel": posterNameLabel, "posterHeadlineLabel": posterHeadlineLabel, "posterTimeLabel": posterTimeLabel, "posterCommentLabel": posterCommentLabel ] addAutoLayoutSubviews(views) addConstraints(withVisualFormat: "V:|-0-[posterImageView]-(>=0)-[posterCommentLabel]-0-|", views: views) addConstraints(withVisualFormat: "V:|-1-[posterNameLabel]-1-[posterHeadlineLabel]-1-[posterTimeLabel]-(>=3)-[posterCommentLabel]", views: views) addConstraints(withVisualFormat: "V:[posterImageView]-(0@749)-[posterCommentLabel]", views: views) addConstraints(withVisualFormat: "H:|-0-[posterImageView]-2-[posterNameLabel]-4-|", views: views) addConstraints(withVisualFormat: "H:[posterImageView]-2-[posterHeadlineLabel]-4-|", views: views) addConstraints(withVisualFormat: "H:[posterImageView]-2-[posterTimeLabel]-4-|", views: views) addConstraints(withVisualFormat: "H:|-0-[posterCommentLabel]-0-|", views: views) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class SocialActionsView: UIView { let likeLabel: UILabel = { let l = UILabel() l.text = "Like" l.backgroundColor = UIColor(red: 0, green: 0.9, blue: 0, alpha: 1) return l }() let commentLabel: UILabel = { let l = UILabel() l.text = "Comment" l.backgroundColor = UIColor(red: 0, green: 1.0, blue: 0, alpha: 1) l.textAlignment = .center return l }() let shareLabel: UILabel = { let l = UILabel() l.text = "Share" l.textAlignment = .right l.backgroundColor = UIColor(red: 0, green: 0.8, blue: 0, alpha: 1) return l }() init() { super.init(frame: .zero) let views: [String: UIView] = [ "likeLabel": likeLabel, "commentLabel": commentLabel, "shareLabel": shareLabel ] addAutoLayoutSubviews(views) addConstraints(withVisualFormat: "V:|-0-[likeLabel]-0-|", views: views) addConstraints(withVisualFormat: "V:|-0-[commentLabel]-0-|", views: views) addConstraints(withVisualFormat: "V:|-0-[shareLabel]-0-|", views: views) addConstraints([ NSLayoutConstraint(item: likeLabel, attribute: .leadingMargin, relatedBy: .equal, toItem: self, attribute: .leadingMargin, multiplier: 1, constant: 0), NSLayoutConstraint(item: commentLabel, attribute: .centerX, relatedBy: .equal, toItem: self, attribute: .centerX, multiplier: 1, constant: 0), NSLayoutConstraint(item: shareLabel, attribute: .trailingMargin, relatedBy: .equal, toItem: self, attribute: .trailingMargin, multiplier: 1, constant: 0) ]) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class TopBarView: UIView { let actionLabel: UILabel = UILabel() let optionsLabel: UILabel = { let l = UILabel() l.text = "..." l.setContentHuggingPriority(UILayoutPriorityRequired, for: .horizontal) l.setContentCompressionResistancePriority(UILayoutPriorityRequired, for: .horizontal) return l }() init() { super.init(frame: .zero) backgroundColor = UIColor.blue let views: [String: UIView] = ["actionLabel": actionLabel, "optionsLabel": optionsLabel] addAutoLayoutSubviews(views) addConstraints(withVisualFormat: "H:|-0-[actionLabel]-0-[optionsLabel]-0-|", views: views) addConstraints(withVisualFormat: "V:|-0-[actionLabel]-(>=0)-|", views: views) addConstraints(withVisualFormat: "V:|-0-[optionsLabel]-(>=0)-|", views: views) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } private extension UIView { func addAutoLayoutSubviews(_ subviews: [String: UIView]) { for (_, view) in subviews { addAutoLayoutSubview(view) } } func addAutoLayoutSubview(_ subview: UIView) { subview.translatesAutoresizingMaskIntoConstraints = false addSubview(subview) } func addConstraints(withVisualFormat visualFormat: String, views: [String: UIView]) { addConstraints(NSLayoutConstraint.constraints(withVisualFormat: visualFormat, options: [], metrics: nil, views: views)) } }
apache-2.0
a1c8836ad2a8031a52d0dcf80e6ee990
37.314607
165
0.656598
4.647887
false
false
false
false
lorentey/swift
test/SILGen/foreach.swift
5
20637
// RUN: %target-swift-emit-silgen -module-name foreach %s | %FileCheck %s ////////////////// // Declarations // ////////////////// class C {} @_silgen_name("loopBodyEnd") func loopBodyEnd() -> () @_silgen_name("condition") func condition() -> Bool @_silgen_name("loopContinueEnd") func loopContinueEnd() -> () @_silgen_name("loopBreakEnd") func loopBreakEnd() -> () @_silgen_name("funcEnd") func funcEnd() -> () struct TrivialStruct { var value: Int32 } struct NonTrivialStruct { var value: C } struct GenericStruct<T> { var value: T var value2: C } protocol P {} protocol ClassP : class {} protocol GenericCollection : Collection { } /////////// // Tests // /////////// //===----------------------------------------------------------------------===// // Trivial Struct //===----------------------------------------------------------------------===// // CHECK-LABEL: sil hidden [ossa] @$s7foreach13trivialStructyySaySiGF : $@convention(thin) (@guaranteed Array<Int>) -> () { // CHECK: bb0([[ARRAY:%.*]] : @guaranteed $Array<Int>): // CHECK: [[ITERATOR_BOX:%.*]] = alloc_box ${ var IndexingIterator<Array<Int>> }, var, name "$x$generator" // CHECK: [[PROJECT_ITERATOR_BOX:%.*]] = project_box [[ITERATOR_BOX]] // CHECK: br [[LOOP_DEST:bb[0-9]+]] // // CHECK: [[LOOP_DEST]]: // CHECK: switch_enum [[IND_VAR:%.*]] : $Optional<Int>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // // CHECK: [[SOME_BB]]([[VAR:%.*]] : $Int): // CHECK: [[LOOP_END_FUNC:%.*]] = function_ref @loopBodyEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_END_FUNC]]() // CHECK: br [[LOOP_DEST]] // // CHECK: [[NONE_BB]]: // CHECK: destroy_value [[ITERATOR_BOX]] // CHECK: [[FUNC_END_FUNC:%.*]] = function_ref @funcEnd : $@convention(thin) () -> () // CHECK: apply [[FUNC_END_FUNC]]() // CHECK: } // end sil function '$s7foreach13trivialStructyySaySiGF' func trivialStruct(_ xx: [Int]) { for x in xx { loopBodyEnd() } funcEnd() } // TODO: Write this test func trivialStructContinue(_ xx: [Int]) { for x in xx { if (condition()) { loopContinueEnd() continue } loopBodyEnd() } funcEnd() } // TODO: Write this test func trivialStructBreak(_ xx: [Int]) { for x in xx { if (condition()) { loopBreakEnd() break } loopBodyEnd() } funcEnd() } // CHECK-LABEL: sil hidden [ossa] @$s7foreach26trivialStructContinueBreakyySaySiGF : $@convention(thin) (@guaranteed Array<Int>) -> () { // CHECK: bb0([[ARRAY:%.*]] : @guaranteed $Array<Int>): // CHECK: [[ITERATOR_BOX:%.*]] = alloc_box ${ var IndexingIterator<Array<Int>> }, var, name "$x$generator" // CHECK: [[PROJECT_ITERATOR_BOX:%.*]] = project_box [[ITERATOR_BOX]] // CHECK: [[BORROWED_ARRAY_STACK:%.*]] = alloc_stack $Array<Int> // CHECK: store [[ARRAY_COPY:%.*]] to [init] [[BORROWED_ARRAY_STACK]] // CHECK: [[MAKE_ITERATOR_FUNC:%.*]] = function_ref @$sSlss16IndexingIteratorVyxG0B0RtzrlE04makeB0ACyF // CHECK: apply [[MAKE_ITERATOR_FUNC]]<Array<Int>>([[PROJECT_ITERATOR_BOX]], [[BORROWED_ARRAY_STACK]]) // CHECK: br [[LOOP_DEST:bb[0-9]+]] // // CHECK: [[LOOP_DEST]]: // CHECK: [[GET_ELT_STACK:%.*]] = alloc_stack $Optional<Int> // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PROJECT_ITERATOR_BOX]] : $*IndexingIterator<Array<Int>> // CHECK: [[FUNC_REF:%.*]] = function_ref @$ss16IndexingIteratorV4next7ElementQzSgyF : $@convention(method) // CHECK: apply [[FUNC_REF]]<Array<Int>>([[GET_ELT_STACK]], [[WRITE]]) // CHECK: [[IND_VAR:%.*]] = load [trivial] [[GET_ELT_STACK]] // CHECK: switch_enum [[IND_VAR]] : $Optional<Int>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // // CHECK: [[SOME_BB]]([[VAR:%.*]] : $Int): // CHECK: cond_br {{%.*}}, [[LOOP_BREAK_END_BLOCK:bb[0-9]+]], [[CONTINUE_CHECK_BLOCK:bb[0-9]+]] // // CHECK: [[LOOP_BREAK_END_BLOCK]]: // CHECK: [[LOOP_BREAK_FUNC:%.*]] = function_ref @loopBreakEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_BREAK_FUNC]]() // CHECK: br [[CONT_BLOCK:bb[0-9]+]] // // CHECK: [[CONTINUE_CHECK_BLOCK]]: // CHECK: cond_br {{%.*}}, [[LOOP_CONTINUE_END:bb[0-9]+]], [[LOOP_END_BLOCK:bb[0-9]+]] // // CHECK: [[LOOP_CONTINUE_END]]: // CHECK: [[LOOP_CONTINUE_FUNC:%.*]] = function_ref @loopContinueEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_CONTINUE_FUNC]]() : $@convention(thin) () -> () // CHECK: br [[LOOP_DEST]] // // CHECK: [[LOOP_END_BLOCK]]: // CHECK: [[LOOP_BODY_FUNC:%.*]] = function_ref @loopBodyEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_BODY_FUNC]]() // CHECK: br [[LOOP_DEST]] // // CHECK: [[NONE_BB]]: // CHECK: br [[CONT_BLOCK]] // // CHECK: [[CONT_BLOCK]] // CHECK: destroy_value [[ITERATOR_BOX]] : ${ var IndexingIterator<Array<Int>> } // CHECK: [[FUNC_END_FUNC:%.*]] = function_ref @funcEnd : $@convention(thin) () -> () // CHECK: apply [[FUNC_END_FUNC]]() // CHECK: } // end sil function '$s7foreach26trivialStructContinueBreakyySaySiGF' func trivialStructContinueBreak(_ xx: [Int]) { for x in xx { if (condition()) { loopBreakEnd() break } if (condition()) { loopContinueEnd() continue } loopBodyEnd() } funcEnd() } //===----------------------------------------------------------------------===// // Existential //===----------------------------------------------------------------------===// func existential(_ xx: [P]) { for x in xx { loopBodyEnd() } funcEnd() } func existentialContinue(_ xx: [P]) { for x in xx { if (condition()) { loopContinueEnd() continue } loopBodyEnd() } funcEnd() } func existentialBreak(_ xx: [P]) { for x in xx { if (condition()) { loopBreakEnd() break } loopBodyEnd() } funcEnd() } // CHECK-LABEL: sil hidden [ossa] @$s7foreach24existentialContinueBreakyySayAA1P_pGF : $@convention(thin) (@guaranteed Array<P>) -> () { // CHECK: bb0([[ARRAY:%.*]] : @guaranteed $Array<P>): // CHECK: [[ITERATOR_BOX:%.*]] = alloc_box ${ var IndexingIterator<Array<P>> }, var, name "$x$generator" // CHECK: [[PROJECT_ITERATOR_BOX:%.*]] = project_box [[ITERATOR_BOX]] // CHECK: [[BORROWED_ARRAY_STACK:%.*]] = alloc_stack $Array<P> // CHECK: store [[ARRAY_COPY:%.*]] to [init] [[BORROWED_ARRAY_STACK]] // CHECK: [[MAKE_ITERATOR_FUNC:%.*]] = function_ref @$sSlss16IndexingIteratorVyxG0B0RtzrlE04makeB0ACyF // CHECK: apply [[MAKE_ITERATOR_FUNC]]<Array<P>>([[PROJECT_ITERATOR_BOX]], [[BORROWED_ARRAY_STACK]]) // CHECK: [[ELT_STACK:%.*]] = alloc_stack $Optional<P> // CHECK: br [[LOOP_DEST:bb[0-9]+]] // // CHECK: [[LOOP_DEST]]: // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PROJECT_ITERATOR_BOX]] : $*IndexingIterator<Array<P>> // CHECK: [[FUNC_REF:%.*]] = function_ref @$ss16IndexingIteratorV4next7ElementQzSgyF : $@convention(method) // CHECK: apply [[FUNC_REF]]<Array<P>>([[ELT_STACK]], [[WRITE]]) // CHECK: switch_enum_addr [[ELT_STACK]] : $*Optional<P>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // // CHECK: [[SOME_BB]]: // CHECK: [[T0:%.*]] = alloc_stack $P, let, name "x" // CHECK: [[ELT_STACK_TAKE:%.*]] = unchecked_take_enum_data_addr [[ELT_STACK]] : $*Optional<P>, #Optional.some!enumelt.1 // CHECK: copy_addr [take] [[ELT_STACK_TAKE]] to [initialization] [[T0]] // CHECK: cond_br {{%.*}}, [[LOOP_BREAK_END_BLOCK:bb[0-9]+]], [[CONTINUE_CHECK_BLOCK:bb[0-9]+]] // // CHECK: [[LOOP_BREAK_END_BLOCK]]: // CHECK: [[LOOP_BREAK_FUNC:%.*]] = function_ref @loopBreakEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_BREAK_FUNC]]() // CHECK: destroy_addr [[T0]] // CHECK: dealloc_stack [[T0]] // CHECK: br [[CONT_BLOCK:bb[0-9]+]] // // CHECK: [[CONTINUE_CHECK_BLOCK]]: // CHECK: cond_br {{%.*}}, [[LOOP_CONTINUE_END:bb[0-9]+]], [[LOOP_END_BLOCK:bb[0-9]+]] // // CHECK: [[LOOP_CONTINUE_END]]: // CHECK: [[LOOP_CONTINUE_FUNC:%.*]] = function_ref @loopContinueEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_CONTINUE_FUNC]]() : $@convention(thin) () -> () // CHECK: destroy_addr [[T0]] // CHECK: dealloc_stack [[T0]] // CHECK: br [[LOOP_DEST]] // // CHECK: [[LOOP_END_BLOCK]]: // CHECK: [[LOOP_BODY_FUNC:%.*]] = function_ref @loopBodyEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_BODY_FUNC]]() // CHECK: destroy_addr [[T0]] // CHECK: dealloc_stack [[T0]] // CHECK: br [[LOOP_DEST]] // // CHECK: [[NONE_BB]]: // CHECK: br [[CONT_BLOCK]] // // CHECK: [[CONT_BLOCK]] // CHECK: dealloc_stack [[ELT_STACK]] // CHECK: destroy_value [[ITERATOR_BOX]] : ${ var IndexingIterator<Array<P>> } // CHECK: [[FUNC_END_FUNC:%.*]] = function_ref @funcEnd : $@convention(thin) () -> () // CHECK: apply [[FUNC_END_FUNC]]() // CHECK: } // end sil function '$s7foreach24existentialContinueBreakyySayAA1P_pGF' func existentialContinueBreak(_ xx: [P]) { for x in xx { if (condition()) { loopBreakEnd() break } if (condition()) { loopContinueEnd() continue } loopBodyEnd() } funcEnd() } //===----------------------------------------------------------------------===// // Class Constrainted Existential //===----------------------------------------------------------------------===// func existentialClass(_ xx: [ClassP]) { for x in xx { loopBodyEnd() } funcEnd() } func existentialClassContinue(_ xx: [ClassP]) { for x in xx { if (condition()) { loopContinueEnd() continue } loopBodyEnd() } funcEnd() } func existentialClassBreak(_ xx: [ClassP]) { for x in xx { if (condition()) { loopBreakEnd() break } loopBodyEnd() } funcEnd() } func existentialClassContinueBreak(_ xx: [ClassP]) { for x in xx { if (condition()) { loopBreakEnd() break } if (condition()) { loopContinueEnd() continue } loopBodyEnd() } funcEnd() } //===----------------------------------------------------------------------===// // Generic Struct //===----------------------------------------------------------------------===// func genericStruct<T>(_ xx: [GenericStruct<T>]) { for x in xx { loopBodyEnd() } funcEnd() } func genericStructContinue<T>(_ xx: [GenericStruct<T>]) { for x in xx { if (condition()) { loopContinueEnd() continue } loopBodyEnd() } funcEnd() } func genericStructBreak<T>(_ xx: [GenericStruct<T>]) { for x in xx { if (condition()) { loopBreakEnd() break } loopBodyEnd() } funcEnd() } // CHECK-LABEL: sil hidden [ossa] @$s7foreach26genericStructContinueBreakyySayAA07GenericC0VyxGGlF : $@convention(thin) <T> (@guaranteed Array<GenericStruct<T>>) -> () { // CHECK: bb0([[ARRAY:%.*]] : @guaranteed $Array<GenericStruct<T>>): // CHECK: [[ITERATOR_BOX:%.*]] = alloc_box $<τ_0_0> { var IndexingIterator<Array<GenericStruct<τ_0_0>>> } <T>, var, name "$x$generator" // CHECK: [[PROJECT_ITERATOR_BOX:%.*]] = project_box [[ITERATOR_BOX]] // CHECK: [[BORROWED_ARRAY_STACK:%.*]] = alloc_stack $Array<GenericStruct<T>> // CHECK: store [[ARRAY_COPY:%.*]] to [init] [[BORROWED_ARRAY_STACK]] // CHECK: [[MAKE_ITERATOR_FUNC:%.*]] = function_ref @$sSlss16IndexingIteratorVyxG0B0RtzrlE04makeB0ACyF // CHECK: apply [[MAKE_ITERATOR_FUNC]]<Array<GenericStruct<T>>>([[PROJECT_ITERATOR_BOX]], [[BORROWED_ARRAY_STACK]]) // CHECK: [[ELT_STACK:%.*]] = alloc_stack $Optional<GenericStruct<T>> // CHECK: br [[LOOP_DEST:bb[0-9]+]] // // CHECK: [[LOOP_DEST]]: // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PROJECT_ITERATOR_BOX]] : $*IndexingIterator<Array<GenericStruct<T>>> // CHECK: [[FUNC_REF:%.*]] = function_ref @$ss16IndexingIteratorV4next7ElementQzSgyF : $@convention(method) // CHECK: apply [[FUNC_REF]]<Array<GenericStruct<T>>>([[ELT_STACK]], [[WRITE]]) // CHECK: switch_enum_addr [[ELT_STACK]] : $*Optional<GenericStruct<T>>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // // CHECK: [[SOME_BB]]: // CHECK: [[T0:%.*]] = alloc_stack $GenericStruct<T>, let, name "x" // CHECK: [[ELT_STACK_TAKE:%.*]] = unchecked_take_enum_data_addr [[ELT_STACK]] : $*Optional<GenericStruct<T>>, #Optional.some!enumelt.1 // CHECK: copy_addr [take] [[ELT_STACK_TAKE]] to [initialization] [[T0]] // CHECK: cond_br {{%.*}}, [[LOOP_BREAK_END_BLOCK:bb[0-9]+]], [[CONTINUE_CHECK_BLOCK:bb[0-9]+]] // // CHECK: [[LOOP_BREAK_END_BLOCK]]: // CHECK: [[LOOP_BREAK_FUNC:%.*]] = function_ref @loopBreakEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_BREAK_FUNC]]() // CHECK: destroy_addr [[T0]] // CHECK: dealloc_stack [[T0]] // CHECK: br [[CONT_BLOCK:bb[0-9]+]] // // CHECK: [[CONTINUE_CHECK_BLOCK]]: // CHECK: cond_br {{%.*}}, [[LOOP_CONTINUE_END:bb[0-9]+]], [[LOOP_END_BLOCK:bb[0-9]+]] // // CHECK: [[LOOP_CONTINUE_END]]: // CHECK: [[LOOP_CONTINUE_FUNC:%.*]] = function_ref @loopContinueEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_CONTINUE_FUNC]]() : $@convention(thin) () -> () // CHECK: destroy_addr [[T0]] // CHECK: dealloc_stack [[T0]] // CHECK: br [[LOOP_DEST]] // // CHECK: [[LOOP_END_BLOCK]]: // CHECK: [[LOOP_BODY_FUNC:%.*]] = function_ref @loopBodyEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_BODY_FUNC]]() // CHECK: destroy_addr [[T0]] // CHECK: dealloc_stack [[T0]] // CHECK: br [[LOOP_DEST]] // // CHECK: [[NONE_BB]]: // CHECK: br [[CONT_BLOCK]] // // CHECK: [[CONT_BLOCK]] // CHECK: dealloc_stack [[ELT_STACK]] // CHECK: destroy_value [[ITERATOR_BOX]] // CHECK: [[FUNC_END_FUNC:%.*]] = function_ref @funcEnd : $@convention(thin) () -> () // CHECK: apply [[FUNC_END_FUNC]]() // CHECK: } // end sil function '$s7foreach26genericStructContinueBreakyySayAA07GenericC0VyxGGlF' func genericStructContinueBreak<T>(_ xx: [GenericStruct<T>]) { for x in xx { if (condition()) { loopBreakEnd() break } if (condition()) { loopContinueEnd() continue } loopBodyEnd() } funcEnd() } //===----------------------------------------------------------------------===// // Fully Generic Collection //===----------------------------------------------------------------------===// func genericCollection<T : Collection>(_ xx: T) { for x in xx { loopBodyEnd() } funcEnd() } func genericCollectionContinue<T : Collection>(_ xx: T) { for x in xx { if (condition()) { loopContinueEnd() continue } loopBodyEnd() } funcEnd() } func genericCollectionBreak<T : Collection>(_ xx: T) { for x in xx { if (condition()) { loopBreakEnd() break } loopBodyEnd() } funcEnd() } // CHECK-LABEL: sil hidden [ossa] @$s7foreach30genericCollectionContinueBreakyyxSlRzlF : $@convention(thin) <T where T : Collection> (@in_guaranteed T) -> () { // CHECK: bb0([[COLLECTION:%.*]] : $*T): // CHECK: [[ITERATOR_BOX:%.*]] = alloc_box $<τ_0_0 where τ_0_0 : Collection> { var τ_0_0.Iterator } <T>, var, name "$x$generator" // CHECK: [[PROJECT_ITERATOR_BOX:%.*]] = project_box [[ITERATOR_BOX]] // CHECK: [[MAKE_ITERATOR_FUNC:%.*]] = witness_method $T, #Sequence.makeIterator!1 // CHECK: apply [[MAKE_ITERATOR_FUNC]]<T>([[PROJECT_ITERATOR_BOX]], [[COLLECTION_COPY:%.*]]) // CHECK: [[ELT_STACK:%.*]] = alloc_stack $Optional<T.Element> // CHECK: br [[LOOP_DEST:bb[0-9]+]] // // CHECK: [[LOOP_DEST]]: // CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PROJECT_ITERATOR_BOX]] : $*T.Iterator // CHECK: [[GET_NEXT_FUNC:%.*]] = witness_method $T.Iterator, #IteratorProtocol.next!1 : <Self where Self : IteratorProtocol> (inout Self) -> () -> Self.Element? : $@convention(witness_method: IteratorProtocol) <τ_0_0 where τ_0_0 : IteratorProtocol> (@inout τ_0_0) -> @out Optional<τ_0_0.Element> // CHECK: apply [[GET_NEXT_FUNC]]<T.Iterator>([[ELT_STACK]], [[WRITE]]) // CHECK: switch_enum_addr [[ELT_STACK]] : $*Optional<T.Element>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // // CHECK: [[SOME_BB]]: // CHECK: [[T0:%.*]] = alloc_stack $T.Element, let, name "x" // CHECK: [[ELT_STACK_TAKE:%.*]] = unchecked_take_enum_data_addr [[ELT_STACK]] : $*Optional<T.Element>, #Optional.some!enumelt.1 // CHECK: copy_addr [take] [[ELT_STACK_TAKE]] to [initialization] [[T0]] // CHECK: cond_br {{%.*}}, [[LOOP_BREAK_END_BLOCK:bb[0-9]+]], [[CONTINUE_CHECK_BLOCK:bb[0-9]+]] // // CHECK: [[LOOP_BREAK_END_BLOCK]]: // CHECK: [[LOOP_BREAK_FUNC:%.*]] = function_ref @loopBreakEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_BREAK_FUNC]]() // CHECK: destroy_addr [[T0]] // CHECK: dealloc_stack [[T0]] // CHECK: br [[CONT_BLOCK:bb[0-9]+]] // // CHECK: [[CONTINUE_CHECK_BLOCK]]: // CHECK: cond_br {{%.*}}, [[LOOP_CONTINUE_END:bb[0-9]+]], [[LOOP_END_BLOCK:bb[0-9]+]] // // CHECK: [[LOOP_CONTINUE_END]]: // CHECK: [[LOOP_CONTINUE_FUNC:%.*]] = function_ref @loopContinueEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_CONTINUE_FUNC]]() : $@convention(thin) () -> () // CHECK: destroy_addr [[T0]] // CHECK: dealloc_stack [[T0]] // CHECK: br [[LOOP_DEST]] // // CHECK: [[LOOP_END_BLOCK]]: // CHECK: [[LOOP_BODY_FUNC:%.*]] = function_ref @loopBodyEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_BODY_FUNC]]() // CHECK: destroy_addr [[T0]] // CHECK: dealloc_stack [[T0]] // CHECK: br [[LOOP_DEST]] // // CHECK: [[NONE_BB]]: // CHECK: br [[CONT_BLOCK]] // // CHECK: [[CONT_BLOCK]] // CHECK: dealloc_stack [[ELT_STACK]] // CHECK: destroy_value [[ITERATOR_BOX]] // CHECK: [[FUNC_END_FUNC:%.*]] = function_ref @funcEnd : $@convention(thin) () -> () // CHECK: apply [[FUNC_END_FUNC]]() // CHECK: } // end sil function '$s7foreach30genericCollectionContinueBreakyyxSlRzlF' func genericCollectionContinueBreak<T : Collection>(_ xx: T) { for x in xx { if (condition()) { loopBreakEnd() break } if (condition()) { loopContinueEnd() continue } loopBodyEnd() } funcEnd() } //===----------------------------------------------------------------------===// // Pattern Match Tests //===----------------------------------------------------------------------===// // CHECK-LABEL: sil hidden [ossa] @$s7foreach13tupleElementsyySayAA1CC_ADtGF func tupleElements(_ xx: [(C, C)]) { // CHECK: bb{{.*}}([[PAYLOAD:%.*]] : @owned $(C, C)): // CHECK: ([[A:%.*]], [[B:%.*]]) = destructure_tuple [[PAYLOAD]] // CHECK: destroy_value [[B]] // CHECK: destroy_value [[A]] for (a, b) in xx {} // CHECK: bb{{.*}}([[PAYLOAD:%.*]] : @owned $(C, C)): // CHECK: ([[A:%.*]], [[B:%.*]]) = destructure_tuple [[PAYLOAD]] // CHECK: destroy_value [[B]] // CHECK: destroy_value [[A]] for (a, _) in xx {} // CHECK: bb{{.*}}([[PAYLOAD:%.*]] : @owned $(C, C)): // CHECK: ([[A:%.*]], [[B:%.*]]) = destructure_tuple [[PAYLOAD]] // CHECK: destroy_value [[A]] // CHECK: destroy_value [[B]] for (_, b) in xx {} // CHECK: bb{{.*}}([[PAYLOAD:%.*]] : @owned $(C, C)): // CHECK: ([[A:%.*]], [[B:%.*]]) = destructure_tuple [[PAYLOAD]] // CHECK: destroy_value [[B]] // CHECK: destroy_value [[A]] for (_, _) in xx {} // CHECK: bb{{.*}}([[PAYLOAD:%.*]] : @owned $(C, C)): // CHECK: ([[A:%.*]], [[B:%.*]]) = destructure_tuple [[PAYLOAD]] // CHECK: destroy_value [[B]] // CHECK: destroy_value [[A]] for _ in xx {} } // Make sure that when we have an unused value, we properly iterate over the // loop rather than run through the loop once. // // CHECK-LABEL: sil hidden [ossa] @$s7foreach16unusedArgPatternyySaySiGF : $@convention(thin) (@guaranteed Array<Int>) -> () { // CHECK: bb0([[ARG:%.*]] : @guaranteed $Array<Int>): // CHECK: br [[LOOP_DEST:bb[0-9]+]] // // CHECK: [[LOOP_DEST]]: // CHECK: switch_enum [[OPT_VAL:%.*]] : $Optional<Int>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // // CHECK: [[SOME_BB]]([[VAL:%.*]] : $Int): // CHECK: [[LOOP_END_FUNC:%.*]] = function_ref @loopBodyEnd : $@convention(thin) () -> () // CHECK: apply [[LOOP_END_FUNC]] func unusedArgPattern(_ xx: [Int]) { for _ in xx { loopBodyEnd() } } // Test for SR-11269. Make sure that the sil contains the needed upcast. // // CHECK-LABEL: sil hidden [ossa] @$s7foreach25genericFuncWithConversion4listySayxG_tAA1CCRbzlF // CHECK: bb2([[ITER_VAL:%.*]] : @owned $T): // CHECK: [[ITER_VAL_UPCAST:%.*]] = upcast [[ITER_VAL]] : $T to $C func genericFuncWithConversion<T: C>(list : [T]) { for item: C in list { print(item) } }
apache-2.0
df85675ec62d003fea947ed5b579d041
33.095868
298
0.562245
3.337324
false
false
false
false
pksprojects/ElasticSwift
Sources/ElasticSwiftQueryDSL/ElasticSwiftDSL.swift
1
15675
import ElasticSwiftCodableUtils import ElasticSwiftCore import Foundation // MARK: - Query Types public enum QueryTypes: String, Codable { case matchAll = "match_all" case matchNone = "match_none" case constantScore = "constant_score" case bool case disMax = "dis_max" case functionScore = "function_score" case boosting case match case matchPhrase = "match_phrase" case matchPhrasePrefix = "match_phrase_prefix" case multiMatch = "multi_match" case common case queryString = "query_string" case simpleQueryString = "simple_query_string" case term case terms case range case exists case prefix case wildcard case regexp case fuzzy case type case ids case nested case hasChild = "has_child" case hasParent = "has_parent" case parentId = "parent_id" case geoShape = "geo_shape" case geoBoundingBox = "geo_bounding_box" case geoDistance = "geo_distance" case geoPolygon = "geo_polygon" case moreLikeThis = "more_like_this" case script case percolate case wrapper case spanTerm = "span_term" case spanMulti = "span_multi" case spanFirst = "span_first" case spanNear = "span_near" case spanOr = "span_or" case spanNot = "span_not" case spanContaining = "span_containing" case spanWithin = "span_within" case spanFieldMasking = "field_masking_span" } extension QueryTypes: QueryType { public var metaType: Query.Type { switch self { case .matchAll: return MatchAllQuery.self case .matchNone: return MatchNoneQuery.self case .constantScore: return ConstantScoreQuery.self case .bool: return BoolQuery.self case .disMax: return DisMaxQuery.self case .functionScore: return FunctionScoreQuery.self case .boosting: return BoostingQuery.self case .match: return MatchQuery.self case .matchPhrase: return MatchPhraseQuery.self case .matchPhrasePrefix: return MatchPhrasePrefixQuery.self case .multiMatch: return MultiMatchQuery.self case .common: return CommonTermsQuery.self case .queryString: return QueryStringQuery.self case .simpleQueryString: return SimpleQueryStringQuery.self case .term: return TermQuery.self case .terms: return TermsQuery.self case .range: return RangeQuery.self case .exists: return ExistsQuery.self case .prefix: return PrefixQuery.self case .wildcard: return WildCardQuery.self case .regexp: return RegexpQuery.self case .fuzzy: return FuzzyQuery.self case .type: return TypeQuery.self case .ids: return IdsQuery.self case .nested: return NestedQuery.self case .hasChild: return HasChildQuery.self case .hasParent: return HasParentQuery.self case .parentId: return ParentIdQuery.self case .geoShape: return GeoShapeQuery.self case .geoBoundingBox: return GeoBoundingBoxQuery.self case .geoDistance: return GeoDistanceQuery.self case .geoPolygon: return GeoPolygonQuery.self case .moreLikeThis: return MoreLikeThisQuery.self case .script: return ScriptQuery.self case .percolate: return PercolateQuery.self case .wrapper: return WrapperQuery.self case .spanTerm: return SpanTermQuery.self case .spanMulti: return SpanMultiTermQuery.self case .spanFirst: return SpanFirstQuery.self case .spanNear: return SpanNearQuery.self case .spanOr: return SpanOrQuery.self case .spanNot: return SpanNotQuery.self case .spanContaining: return SpanContainingQuery.self case .spanWithin: return SpanWithinQuery.self case .spanFieldMasking: return SpanFieldMaskingQuery.self } } } // MARK: - Score Function Types public enum ScoreFunctionType: String, Codable { case weight case randomScore = "random_score" case scriptScore = "script_score" case linear case gauss case exp case fieldValueFactor = "field_value_factor" var metaType: ScoreFunction.Type { switch self { case .weight: return WeightScoreFunction.self case .randomScore: return RandomScoreFunction.self case .scriptScore: return ScriptScoreFunction.self case .linear: return LinearDecayScoreFunction.self case .gauss: return GaussScoreFunction.self case .exp: return ExponentialDecayScoreFunction.self case .fieldValueFactor: return FieldValueFactorScoreFunction.self } } } // MARK: - SCRIPT public struct Script: Codable, Equatable { public let source: String public let lang: String? public let params: [String: CodableValue]? public init(_ source: String, lang: String? = nil, params: [String: CodableValue]? = nil) { self.source = source self.lang = lang self.params = params } public init(from decoder: Decoder) throws { if let container = try? decoder.container(keyedBy: CodingKeys.self) { source = try container.decodeString(forKey: .source) lang = try container.decodeStringIfPresent(forKey: .lang) params = try container.decodeIfPresent([String: CodableValue].self, forKey: .params) return } else if let container = try? decoder.singleValueContainer() { source = try container.decodeString() params = nil lang = nil return } else { throw Swift.DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "Unable to decode Script as String/Dic")) } } public func encode(to encoder: Encoder) throws { if lang == nil, params == nil { var container = encoder.singleValueContainer() try container.encode(source) return } var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(source, forKey: .source) try container.encodeIfPresent(lang, forKey: .lang) try container.encodeIfPresent(params, forKey: .params) } enum CodingKeys: String, CodingKey { case source case lang case params } } // MARK: - Script Type public enum ScriptType: String, Codable { case inline case stored } // MARK: - Enums public enum Fuzziness: String, Codable { case zero = "ZERO" case one = "ONE" case two = "TWO" case auto = "AUTO" } public enum ShapeRelation: String, Codable { case intersects case disjoint case within case contains } public enum RegexFlag: String, Codable { case intersection = "INTERSECTION" case complement = "COMPLEMENT" case empty = "EMPTY" case anyString = "ANYSTRING" case interval = "INTERVAL" case none = "NONE" case all = "ALL" } public enum ScoreMode: String, Codable { case first case avg case max case sum case min case multiply case total } public enum BoostMode: String, Codable { case multiply case replace case sum case avg case min case max } public enum MultiMatchQueryType: String, Codable { case bestFields = "best_fields" case mostFields = "most_fields" case crossFields = "cross_fields" case phrase case phrasePrefix = "phrase_prefix" } public enum ZeroTermQuery: String, Codable { case none case all } public enum Operator: String, Codable { case and case or } /// A helper function compares two queries wrapped as optional public func isEqualQueries(_ lhs: Query?, _ rhs: Query?) -> Bool { if lhs == nil, rhs == nil { return true } if let lhs = lhs, let rhs = rhs { return lhs.isEqualTo(rhs) } return false } /// Extention for DynamicCodingKeys public extension DynamicCodingKeys { static func key(named queryType: QueryType) -> DynamicCodingKeys { return .key(named: queryType.name) } static func key(named scoreFunctionType: ScoreFunctionType) -> DynamicCodingKeys { return .key(named: scoreFunctionType.rawValue) } } // MARK: - Codable Extenstions public extension KeyedEncodingContainer { mutating func encode(_ value: Query, forKey key: KeyedEncodingContainer<K>.Key) throws { try value.encode(to: superEncoder(forKey: key)) } mutating func encode(_ value: ScoreFunction, forKey key: KeyedEncodingContainer<K>.Key) throws { try value.encode(to: superEncoder(forKey: key)) } mutating func encode(_ value: [Query], forKey key: KeyedEncodingContainer<K>.Key) throws { let queriesEncoder = superEncoder(forKey: key) var queriesContainer = queriesEncoder.unkeyedContainer() for query in value { let queryEncoder = queriesContainer.superEncoder() try query.encode(to: queryEncoder) } } mutating func encode(_ value: [ScoreFunction], forKey key: KeyedEncodingContainer<K>.Key) throws { let scoreFunctionEncoder = superEncoder(forKey: key) var scoreFunctionsContainer = scoreFunctionEncoder.unkeyedContainer() for scoreFunction in value { let scoreFunctionEncoder = scoreFunctionsContainer.superEncoder() try scoreFunction.encode(to: scoreFunctionEncoder) } } mutating func encodeIfPresent(_ value: Query?, forKey key: KeyedEncodingContainer<K>.Key) throws { if let value = value { try value.encode(to: superEncoder(forKey: key)) } } mutating func encodeIfPresent(_ value: ScoreFunction?, forKey key: KeyedEncodingContainer<K>.Key) throws { if let value = value { try encode(value, forKey: key) } } mutating func encodeIfPresent(_ value: [Query]?, forKey key: KeyedEncodingContainer<K>.Key) throws { if let value = value { try encode(value, forKey: key) } } mutating func encodeIfPresent(_ value: [ScoreFunction]?, forKey key: KeyedEncodingContainer<K>.Key) throws { if let value = value { try encode(value, forKey: key) } } } public extension KeyedDecodingContainer { func decodeQuery(forKey key: KeyedDecodingContainer<K>.Key) throws -> Query { let qContainer = try nestedContainer(keyedBy: DynamicCodingKeys.self, forKey: key) for qKey in qContainer.allKeys { if let qType = QueryTypes(qKey.stringValue) { return try qType.metaType.init(from: superDecoder(forKey: key)) } } throw Swift.DecodingError.typeMismatch(QueryTypes.self, .init(codingPath: codingPath, debugDescription: "Unable to identify query type from key(s) \(qContainer.allKeys)")) } func decodeQueryIfPresent(forKey key: KeyedDecodingContainer<K>.Key) throws -> Query? { guard contains(key) else { return nil } return try decodeQuery(forKey: key) } func decodeQueries(forKey key: KeyedDecodingContainer<K>.Key) throws -> [Query] { var arrayContainer = try nestedUnkeyedContainer(forKey: key) var result = [Query]() if let count = arrayContainer.count { while !arrayContainer.isAtEnd { let query = try arrayContainer.decodeQuery() result.append(query) } if result.count != count { throw Swift.DecodingError.dataCorrupted(.init(codingPath: arrayContainer.codingPath, debugDescription: "Unable to decode all Queries expected: \(count) actual: \(result.count). Probable cause: Unable to determine QueryType form key(s)")) } } return result } func decodeQueriesIfPresent(forKey key: KeyedDecodingContainer<K>.Key) throws -> [Query]? { guard contains(key) else { return nil } return try decodeQueries(forKey: key) } func decodeScoreFunction(forKey key: KeyedDecodingContainer<K>.Key) throws -> ScoreFunction { let fContainer = try nestedContainer(keyedBy: DynamicCodingKeys.self, forKey: key) for fKey in fContainer.allKeys { if let fType = ScoreFunctionType(rawValue: fKey.stringValue) { return try fType.metaType.init(from: superDecoder(forKey: key)) } } throw Swift.DecodingError.typeMismatch(ScoreFunctionType.self, .init(codingPath: codingPath, debugDescription: "Unable to identify score function type from key(s) \(fContainer.allKeys)")) } func decodeScoreFunctionIfPresent(forKey key: KeyedDecodingContainer<K>.Key) throws -> ScoreFunction? { guard contains(key) else { return nil } return try decodeScoreFunction(forKey: key) } func decodeScoreFunctions(forKey key: KeyedDecodingContainer<K>.Key) throws -> [ScoreFunction] { var arrayContainer = try nestedUnkeyedContainer(forKey: key) var result = [ScoreFunction]() if let count = arrayContainer.count { while !arrayContainer.isAtEnd { let function = try arrayContainer.decodeScoreFunction() result.append(function) } if result.count != count { throw Swift.DecodingError.dataCorrupted(.init(codingPath: arrayContainer.codingPath, debugDescription: "Unable to decode all ScoreFunctions expected: \(count) actual: \(result.count). Probable cause: Unable to determine ScoreFunctionType form key(s)")) } } return result } func decodeScoreFunctionsIfPresent(forKey key: KeyedDecodingContainer<K>.Key) throws -> [ScoreFunction]? { guard contains(key) else { return nil } return try decodeScoreFunctions(forKey: key) } } extension UnkeyedDecodingContainer { mutating func decodeQuery() throws -> Query { var copy = self let elementContainer = try copy.nestedContainer(keyedBy: DynamicCodingKeys.self) for qKey in elementContainer.allKeys { if let qType = QueryTypes(qKey.stringValue) { return try qType.metaType.init(from: superDecoder()) } } throw Swift.DecodingError.typeMismatch(QueryTypes.self, .init(codingPath: codingPath, debugDescription: "Unable to identify query type from key(s) \(elementContainer.allKeys)")) } mutating func decodeScoreFunction() throws -> ScoreFunction { var copy = self let elementContainer = try copy.nestedContainer(keyedBy: DynamicCodingKeys.self) for fKey in elementContainer.allKeys { if let fType = ScoreFunctionType(rawValue: fKey.stringValue) { return try fType.metaType.init(from: superDecoder()) } } throw Swift.DecodingError.typeMismatch(ScoreFunctionType.self, .init(codingPath: codingPath, debugDescription: "Unable to identify score function type from key(s) \(elementContainer.allKeys)")) } }
mit
453bc5c80e364181510e94ce1483dce2
31.386364
268
0.637512
4.658247
false
false
false
false
kickstarter/ios-oss
Kickstarter-iOS/Features/ProjectActivities/Views/Cells/ProjectActivityNegativeStateChangeCell.swift
1
1745
import KsApi import Library import Prelude import Prelude_UIKit import UIKit internal final class ProjectActivityNegativeStateChangeCell: UITableViewCell, ValueCell { fileprivate let viewModel: ProjectActivityNegativeStateChangeCellViewModelType = ProjectActivityNegativeStateChangeCellViewModel() @IBOutlet fileprivate var cardView: UIView! @IBOutlet fileprivate var titleLabel: UILabel! internal func configureWith(value activityAndProject: (Activity, Project)) { self.viewModel.inputs.configureWith( activity: activityAndProject.0, project: activityAndProject.1 ) } internal override func bindViewModel() { super.bindViewModel() self.viewModel.outputs.title.observeForUI() .observeValues { [weak titleLabel] title in guard let titleLabel = titleLabel else { return } titleLabel.attributedText = title.simpleHtmlAttributedString( font: .ksr_body(), bold: UIFont.ksr_body().bolded, italic: nil ) _ = titleLabel |> projectActivityStateChangeLabelStyle |> UILabel.lens.textColor .~ .ksr_support_400 } } internal override func bindStyles() { super.bindStyles() _ = self |> baseTableViewCellStyle() |> ProjectActivityNegativeStateChangeCell.lens.contentView.layoutMargins %~~ { layoutMargins, cell in cell.traitCollection.isRegularRegular ? projectActivityRegularRegularLayoutMargins : layoutMargins } |> UITableViewCell.lens.accessibilityHint %~ { _ in Strings.Opens_project() } _ = self.cardView |> cardStyle() |> dropShadowStyleMedium() |> UIView.lens.layer.borderColor .~ UIColor.ksr_support_400.cgColor } }
apache-2.0
b9efd77475c275c0a57da00d58978a48
29.614035
107
0.702006
5.256024
false
false
false
false
lintmachine/RxEasing
Example/Pods/RxOptional/Sources/RxOptional/SharedSequence+Optional.swift
1
2805
import RxCocoa public extension SharedSequenceConvertibleType where Element: OptionalType { /** Unwraps and filters out `nil` elements. - returns: `Driver` of source `Driver`'s elements, with `nil` elements filtered out. */ func filterNil() -> SharedSequence<SharingStrategy, Element.Wrapped> { return flatMap { element -> SharedSequence<SharingStrategy, Element.Wrapped> in guard let value = element.value else { return SharedSequence<SharingStrategy, Element.Wrapped>.empty() } return SharedSequence<SharingStrategy, Element.Wrapped>.just(value) } } /** Unwraps optional elements and replaces `nil` elements with `valueOnNil`. - parameter valueOnNil: value to use when `nil` is encountered. - returns: `Driver` of the source `Driver`'s unwrapped elements, with `nil` elements replaced by `valueOnNil`. */ func replaceNilWith(_ valueOnNil: Element.Wrapped) -> SharedSequence<SharingStrategy, Element.Wrapped> { return map { element -> Element.Wrapped in guard let value = element.value else { return valueOnNil } return value } } /** Unwraps optional elements and replaces `nil` elements with result returned by `handler`. - parameter handler: `nil` handler function that returns `Driver` of non-`nil` elements. - returns: `Driver` of the source `Driver`'s unwrapped elements, with `nil` elements replaced by the handler's returned non-`nil` elements. */ func catchOnNil(_ handler: @escaping () -> SharedSequence<SharingStrategy, Element.Wrapped>) -> SharedSequence<SharingStrategy, Element.Wrapped> { return flatMap { element -> SharedSequence<SharingStrategy, Element.Wrapped> in guard let value = element.value else { return handler() } return SharedSequence<SharingStrategy, Element.Wrapped>.just(value) } } } #if !swift(>=3.3) || (swift(>=4.0) && !swift(>=4.1)) public extension SharedSequenceConvertibleType where Element: OptionalType, Element.Wrapped: Equatable { /** Returns an observable sequence that contains only distinct contiguous elements according to equality operator. - seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html) - returns: An observable sequence only containing the distinct contiguous elements, based on equality operator, from the source sequence. */ func distinctUntilChanged() -> SharedSequence<SharingStrategy, Element> { return self.distinctUntilChanged { (lhs, rhs) -> Bool in return lhs.value == rhs.value } } } #endif
mit
5b74f51b0451addfbe383499ed17c0be
39.071429
150
0.664171
5.063177
false
false
false
false
AlexanderMazaletskiy/iOS-Open-GPX-Tracker
OpenGpxTracker/AppDelegate.swift
1
6151
// // AppDelegate.swift // OpenGpxTracker // // Created by merlos on 13/09/14. // Copyright (c) 2014 TransitBox. 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 "org.transitbox.OpenGpxTracker" 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("OpenGpxTracker", 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("OpenGpxTracker.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. let dict = NSMutableDictionary() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error error = NSError(domain: "org.merlos.gpx-tracker", 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() } } } }
gpl-3.0
b4ef8b877e02abd3a1ac712902da740a
52.95614
290
0.717119
5.753976
false
false
false
false
ICTatRTI/pam
ema/WithdrawViewController.swift
1
1262
// // WithdrawViewController.swift // ema // // Created by Adam Preston on 4/20/16. // Copyright © 2016 RTI. All rights reserved. // import UIKit import ResearchKit class WithdrawViewController: ORKTaskViewController { // MARK: Initialization init() { let instructionStep = ORKInstructionStep(identifier: "WithdrawlInstruction") instructionStep.title = NSLocalizedString("Are you sure you want to withdraw?", comment: "") instructionStep.text = NSLocalizedString("Withdrawing from the study will reset the app to the state it was in prior to you originally joining the study.", comment: "") let completionStep = ORKCompletionStep(identifier: "Withdraw") completionStep.title = NSLocalizedString("We appreciate your time.", comment: "") completionStep.text = NSLocalizedString("Thank you for your contribution to this study. We are sorry that you could not continue.", comment: "") let withdrawTask = ORKOrderedTask(identifier: "Withdraw", steps: [instructionStep, completionStep]) super.init(task: withdrawTask, taskRun: nil) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
e8cf7321d8fb934232f8cccc59483f97
37.212121
176
0.693101
4.740602
false
false
false
false
ggu/2D-RPG-Template
Borba/game objects/characters/PlayerSprite.swift
2
1557
// // Player.swift // Borba // // Created by Gabriel Uribe on 7/25/15. // Copyright (c) 2015 Team Five Three. All rights reserved. // import SpriteKit class PlayerSprite: Sprite { init() { let texture = AssetManager.heroTexture super.init(texture: texture, color: UIColor.whiteColor(), size: texture.size()) setup() } func changeDirection(angle: CGFloat) { zRotation = angle + CGFloat(M_PI) } private func setup() { properties() physics() lightSource() } private func properties() { position = PlayerStartingPosition zPosition = zPositions.mapObjects } private func physics() { physicsBody = SKPhysicsBody(rectangleOfSize: size) physicsBody?.affectedByGravity = false physicsBody?.mass = 1 physicsBody?.categoryBitMask = CategoryBitMasks.hero physicsBody?.collisionBitMask = CategoryBitMasks.map | CategoryBitMasks.enemy } private func lightSource() { let lightNode = SKLightNode() lightNode.enabled = true lightNode.lightColor = SKColor.whiteColor() lightNode.ambientColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.1) lightNode.position = CGPoint(x: 0, y: 0) lightNode.shadowColor = SKColor(red: 0, green: 0, blue: 0, alpha: 0.2) lightNode.alpha = 1 lightNode.categoryBitMask = 1 lightNode.falloff = 0.01 lightingBitMask = 1 lightNode.zPosition = zPositions.map addChild(lightNode) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
f993505b2f1ca66d16166e4bd8cc8f28
24.52459
83
0.676301
4.129973
false
false
false
false