repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
pixelglow/PredicatePal
PredicatePal/IntersectExpression.swift
1
2178
// // SetExpression.swift // PredicatePal // // Created by Glen Low on 7/12/2015. // Copyright © 2015 Glen Low. All rights reserved. // import Foundation /// Set intersect expression composing a set subexpression and a sequence subexpression. /// - parameter E1: Full type of the LHS set subexpression. /// - parameter E2: Full type of the RHS sequence subexpression. public struct IntersectExpression<E1: Expression, E2: Expression where E1.ExpressionType: SetType, E2.ExpressionType: CollectionType, E1.ExpressionType.Element == E2.ExpressionType.Generator.Element>: Expression { public typealias ExpressionType = E1.ExpressionType let leftSub: E1 let rightSub: E2 } /// Build the `NSExpression`. public prefix func*<E1, E2>(expression: IntersectExpression<E1, E2>) -> NSExpression { return NSExpression(forIntersectSet: *expression.leftSub, with: *expression.rightSub) } /// Intersect an expression with another expression. /// - parameter leftSub: The LHS set subexpression. /// - parameter rightSub: The RHS sequence subexpression. /// - returns: The resulting set expression. public func &<E1: Expression, E2: Expression>(leftSub: E1, rightSub: E2) -> IntersectExpression<E1, E2> { return IntersectExpression(leftSub: leftSub, rightSub: rightSub) } /// Intersect an expression with a constant. /// - parameter leftSub: The LHS set subexpression. /// - parameter rightConst: The RHS sequence constant. /// - returns: The resulting set expression. public func &<E1: Expression, C: SequenceType where E1.ExpressionType.Element == C.Generator.Element>(leftSub: E1, rightConst: C) -> IntersectExpression<E1, Const<C>> { return IntersectExpression(leftSub: leftSub, rightSub: Const(rightConst)) } /// Intersect a constant with an expression. /// - parameter leftConst: The LHS set constant. /// - parameter rightSub: The RHS sequence subexpression. /// - returns: The resulting set expression. public func &<E2: Expression, C: SetType where E2.ExpressionType.Generator.Element == C.Element>(leftConst: C, rightSub: E2) -> IntersectExpression<Const<C>, E2> { return IntersectExpression(leftSub: Const(leftConst), rightSub: rightSub) }
bsd-2-clause
db68638b6032a32e9c6ccefc16fcfe4a
44.354167
213
0.747359
3.908438
false
false
false
false
kongtomorrow/ProjectEuler-Swift
ProjectEuler/p11.swift
1
5006
// // p11.swift // ProjectEuler // // Created by Ken Ferry on 8/7/14. // Copyright (c) 2014 Understudy. All rights reserved. // import Foundation extension Problems { func p11() -> Int { /* Largest product in a grid Problem 11 Published on 22 February 2002 at 06:00 pm [Server Time] In the 20×20 grid below, four numbers along a diagonal line have been marked in red. 08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91 22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80 24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50 32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70 67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21 24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72 21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95 78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92 16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57 86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58 19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40 04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66 88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69 04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36 20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16 20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54 01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48 The product of these numbers is 26 × 63 × 78 × 14 = 1788696. What is the greatest product of four adjacent numbers in the same direction (up, down, left, right, or diagonally) in the 20×20 grid? */ let runLen = 4 let grid :[[Int]] = [ [08, 02, 22, 97, 38, 15, 00, 40, 00, 75, 04, 05, 07, 78, 52, 12, 50, 77, 91, 08], [49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 04, 56, 62, 00], [81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 03, 49, 13, 36, 65], [52, 70, 95, 23, 04, 60, 11, 42, 69, 24, 68, 56, 01, 32, 56, 71, 37, 02, 36, 91], [22, 31, 16, 71, 51, 67, 63, 89, 41, 92, 36, 54, 22, 40, 40, 28, 66, 33, 13, 80], [24, 47, 32, 60, 99, 03, 45, 02, 44, 75, 33, 53, 78, 36, 84, 20, 35, 17, 12, 50], [32, 98, 81, 28, 64, 23, 67, 10, 26, 38, 40, 67, 59, 54, 70, 66, 18, 38, 64, 70], [67, 26, 20, 68, 02, 62, 12, 20, 95, 63, 94, 39, 63, 08, 40, 91, 66, 49, 94, 21], [24, 55, 58, 05, 66, 73, 99, 26, 97, 17, 78, 78, 96, 83, 14, 88, 34, 89, 63, 72], [21, 36, 23, 09, 75, 00, 76, 44, 20, 45, 35, 14, 00, 61, 33, 97, 34, 31, 33, 95], [78, 17, 53, 28, 22, 75, 31, 67, 15, 94, 03, 80, 04, 62, 16, 14, 09, 53, 56, 92], [16, 39, 05, 42, 96, 35, 31, 47, 55, 58, 88, 24, 00, 17, 54, 24, 36, 29, 85, 57], [86, 56, 00, 48, 35, 71, 89, 07, 05, 44, 44, 37, 44, 60, 21, 58, 51, 54, 17, 58], [19, 80, 81, 68, 05, 94, 47, 69, 28, 73, 92, 13, 86, 52, 17, 77, 04, 89, 55, 40], [04, 52, 08, 83, 97, 35, 99, 16, 07, 97, 57, 32, 16, 26, 26, 79, 33, 27, 98, 66], [88, 36, 68, 87, 57, 62, 20, 72, 03, 46, 33, 67, 46, 55, 12, 32, 63, 93, 53, 69], [04, 42, 16, 73, 38, 25, 39, 11, 24, 94, 72, 18, 08, 46, 29, 32, 40, 62, 76, 36], [20, 69, 36, 41, 72, 30, 23, 88, 34, 62, 99, 69, 82, 67, 59, 85, 74, 04, 36, 16], [20, 73, 35, 29, 78, 31, 90, 01, 74, 31, 49, 71, 48, 86, 81, 16, 23, 57, 05, 54], [01, 70, 54, 71, 83, 51, 54, 69, 16, 92, 33, 48, 61, 43, 52, 01, 89, 19, 67, 48], ] let dim = grid.count func zeroExGrid(row:Int,col:Int)->Int{ if 0..<dim ~= row && 0..<dim ~= col { return grid[row][col] } else { return 0 } } var runAccum = Accumulator(initial: Int.min) { (best:Int, run:[(Int,Int)]) -> Int in return max(best, run.map(zeroExGrid).reduce(1, combine: *)) } let advances :[(Int,Int)->(Int,Int)] = [ {($0+1,$1)}, // right {($0,$1+1)}, // down {($0+1,$1+1)}, // down-right {($0+1,$1-1)}, // up-right ] for (startRow, startCol) in cartesianProduct(0..<dim, 0..<dim) { for advance in advances { var run : [(Int,Int)] = [(startRow,startCol)] for i in 1...runLen-1 { run.append(advance(run.last!)) } runAccum.merge(run) } } return runAccum.val // 70600674 } }
mit
358de7d33e36cb0c6caf180087342f43
50.040816
141
0.489702
2.912638
false
false
false
false
bitboylabs/selluv-ios
selluv-ios/selluv-ios/Classes/Controller/UI/Tabs/Tab1SelluvMain/SLV_110_SelluvMainController.swift
1
8889
// // SLV_110_SelluvMainController.swift // selluv-ios // // Created by 조백근 on 2016. 11. 8.. // Copyright © 2016년 BitBoy Labs. All rights reserved. // /* 셀럽 탭1 메인뷰 컨트롤러 */ import Foundation import UIKit class SLV_110_SelluvMainController: ButtonBarPagerTabStripViewController { @IBOutlet weak var shadowView: UIView! @IBOutlet weak var hConstraint: NSLayoutConstraint! var containerDefaultFrame: CGRect? let blueInstagramColor = UIColor(red: 37/255.0, green: 111/255.0, blue: 206/255.0, alpha: 1.0) required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { self.resetupNavigationBar() self.setupButtonBar() super.viewDidLoad() self.navigationController?.navigationBar.tintColor = UIColor.white self.navigationItem.hidesBackButton = true self.extendedLayoutIncludesOpaqueBars = true self.automaticallyAdjustsScrollViewInsets = false self.setupNavigationButtons() self.contentInsetY = 44 self.containerView.contentInset = UIEdgeInsets(top: contentInsetY, left: 0, bottom: 0, right: 0) // let barFrame = self.buttonBarView.frame // self.buttonBarView.frame = CGRect(x: barFrame.origin.x, y: barFrame.origin.y, width: 210, height: barFrame.size.height) // self.buttonBarView.clipsToBounds = true } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.resetupNavigationBar() tabController.animationTabBarHidden(false)//탭바 보여준다. tabController.hideFab() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func resetupNavigationBar() { self.navigationBar?.isHidden = false self.navigationBar?.barHeight = 64 _ = self.navigationBar?.sizeThatFits(.zero) } func setupButtonBar() { // change selected bar color settings.style.buttonBarBackgroundColor = .white settings.style.buttonBarItemBackgroundColor = .white settings.style.selectedBarBackgroundColor = text_color_bl51 settings.style.buttonBarItemFont = .systemFont(ofSize: 16, weight: UIFontWeightMedium) settings.style.selectedBarHeight = 4.0 //스토리보드에서 높이만큼 컨테이너 뷰의 간격을 더 내려준다.(높이의 배수?) settings.style.buttonBarMinimumLineSpacing = 0 settings.style.buttonBarItemTitleColor = text_color_bl51 settings.style.buttonBarItemsShouldFillAvailiableWidth = true settings.style.buttonBarLeftContentInset = 40 settings.style.buttonBarRightContentInset = 40 settings.style.buttonBarHeight = 44 settings.style.buttonBarItemsLine = 2 changeCurrentIndexProgressive = { [weak self] (oldCell: ButtonBarViewCell?, newCell: ButtonBarViewCell?, progressPercentage: CGFloat, changeCurrentIndex: Bool, animated: Bool) -> Void in guard changeCurrentIndex == true else { return } oldCell?.label.textColor = text_color_g153 oldCell?.label.font = UIFont.systemFont(ofSize: 16, weight: UIFontWeightRegular) newCell?.label.textColor = text_color_bl51 newCell?.label.font = UIFont.systemFont(ofSize: 16, weight: UIFontWeightSemibold) if newCell != nil { // let path = self?.buttonBarView.indexPath(for: newCell!)//TODO: 작업 중 nil 확인하고, 스크롤 관련 spliter 처리할 것... // log.debug("pathInfo ---> \(path?.item)") // if path != nil { // } } self?.resetupNavigationBar() } } func setupNavigationButtons() { let view = UIView(frame: CGRect(x:0, y:0, width:56, height: 30)) let iv = UIImageView() iv.frame = CGRect(x:7, y:0, width:43, height: 35) iv.image = UIImage(named:"style_symbol.png") view.addSubview(iv) let heart = UIButton() heart.frame = CGRect(x:0, y:0, width:56, height: 35) heart.addTarget(self, action: #selector(SLV_110_SelluvMainController.changeStyle(sender:)), for: .touchUpInside) view.addSubview(heart) let item2 = UIBarButtonItem(customView: view) self.navigationItem.rightBarButtonItem = item2 } // MARK: - PagerTabStripDataSource override func viewControllers(for pagerTabStripController: PagerTabStripViewController) -> [UIViewController] { let board = UIStoryboard(name:"Product", bundle: nil) //로드할 컨트롤러들이 네비의 루트뷰들이라 네비를 먼저 로드하지 않으면 읽어오지 못함... _ = board.instantiateViewController(withIdentifier: "FEED") as! NTNavigationController _ = board.instantiateViewController(withIdentifier:"HOT") as! NTNavigationController _ = board.instantiateViewController(withIdentifier:"NEO") as! NTNavigationController let feedController = board.instantiateViewController(withIdentifier: "SLV_111_SelluvMainFeed") as! SLV_111_SelluvMainFeed feedController.linkDelegate(controller: self) let hotController = board.instantiateViewController(withIdentifier:"SLV_112_SelluvMainHot") as! SLV_112_SelluvMainHot hotController.linkDelegate(controller: self) let neoController = board.instantiateViewController(withIdentifier:"SLV_1a5_SelluvMainNew") as! SLV_1a5_SelluvMainNew neoController.linkDelegate(controller: self) return [feedController, hotController, neoController] } override var prefersStatusBarHidden: Bool { return true } func changeStyle(sender: UIButton?) { let isStyle = SelluvHomeTabModel.shared.isOnlyStyles SelluvHomeTabModel.shared.isOnlyStyles = !isStyle self.reloadPagerTabStripView() } func delay(time: Double, closure: @escaping () -> ()) { DispatchQueue.main.asyncAfter(deadline: .now() + time) { closure() } } } extension SLV_110_SelluvMainController: SLVButtonBarDelegate { func showByScroll() {//down scroll if self.hConstraint.constant > 0 { return } tabController.hideFab() tabController.animationTabBarHidden(false) tabController.tabBar.needsUpdateConstraints() self.hConstraint.constant = 44 self.buttonBarView.needsUpdateConstraints() self.contentInsetY = 44 self.containerView.contentInset = UIEdgeInsets(top: contentInsetY, left: 0, bottom: 64, right: 0) self.containerView.needsUpdateConstraints() UIView.animate(withDuration: 0.2, animations: { self.buttonBarView.layoutIfNeeded() self.containerView.layoutIfNeeded() }, completion: { completed in }) } func hideByScroll() {// up scroll //top if self.hConstraint.constant == 0 { return } tabController.showFab() tabController.animationTabBarHidden(true) tabController.tabBar.needsUpdateConstraints() self.hConstraint.constant = 0 self.buttonBarView.needsUpdateConstraints() self.contentInsetY = 0 self.containerView.contentInset = UIEdgeInsets(top: contentInsetY, left: 0, bottom: 20, right: 0) self.containerView.needsUpdateConstraints() UIView.animate(withDuration: 0.5, animations: { self.buttonBarView.layoutIfNeeded() self.containerView.layoutIfNeeded() }, completion: { completed in }) } } extension SLV_110_SelluvMainController: SLVNavigationControllerDelegate { func linkMyNavigationForTransition() -> UINavigationController? { return self.navigationController } // 현재의 탭정보를 반환하다. func currentTabIndex() -> Int! { return self.currentIndex } } //extension SLV_110_SelluvMainController: ModalTransitionDelegate { // // func modalViewControllerDismiss(callbackData data:AnyObject?) { // log.debug("SLV_110_SelluvMainController(callbackData:)") // tr_dismissViewController(completion: { // if let back = data { // let cb = back as! [String: String] // let keys = cb.keys // if keys.contains("from") == true { // let key = cb["from"] // if key != nil { // } // } // } // }) // } //}
mit
c93a15290ffc2e1df4b68441a30f3cc6
36.175966
194
0.641076
4.644504
false
false
false
false
s-aska/Justaway-for-iOS
Justaway/ThemeUI.swift
1
11758
// // ThemeUI.swift // Justaway // // Created by Shinichiro Aska on 1/9/15. // Copyright (c) 2015 Shinichiro Aska. All rights reserved. // import UIKit import AVFoundation import EventBox import Async // MARK: - ContainerView class MenuView: UIView {} class MenuShadowView: MenuView { override func awakeFromNib() { super.awakeFromNib() self.layer.shadowColor = UIColor.black.cgColor self.layer.shadowOffset = CGSize(width: 0, height: -2.0) self.layer.shadowOpacity = ThemeController.currentTheme.shadowOpacity() self.layer.shadowRadius = 1.0 } } class SideMenuShadowView: MenuShadowView { override func awakeFromNib() { super.awakeFromNib() self.layer.shadowColor = UIColor.black.cgColor self.layer.shadowOffset = CGSize(width: 2.0, height: 0) self.layer.shadowOpacity = ThemeController.currentTheme.shadowOpacity() self.layer.shadowRadius = 1.0 } } class SideMenuSeparator: UIView {} class NavigationShadowView: MenuView { override func awakeFromNib() { super.awakeFromNib() self.layer.shadowColor = UIColor.black.cgColor self.layer.shadowOffset = CGSize(width: 0, height: 2.0) self.layer.shadowOpacity = ThemeController.currentTheme.shadowOpacity() self.layer.shadowRadius = 1.0 } } class BackgroundView: UIView {} class BackgroundShadowView: BackgroundView { override func awakeFromNib() { super.awakeFromNib() self.layer.shadowColor = UIColor.black.cgColor self.layer.shadowOffset = CGSize(width: 0, height: -2.0) self.layer.shadowOpacity = ThemeController.currentTheme.shadowOpacity() self.layer.shadowRadius = 1.0 } } class BackgroundTableView: UITableView {} class BackgroundTableViewCell: UITableViewCell {} class BackgroundScrollView: UIScrollView {} class CurrentTabMaskView: UIView {} class QuotedStatusContainerView: UIView { override func awakeFromNib() { super.awakeFromNib() layer.borderColor = ThemeController.currentTheme.cellSeparatorColor().cgColor layer.borderWidth = (1.0 / UIScreen.main.scale) / 1 } } class ShowMoreTweetBackgroundView: UIView {} class ShowMoreTweetLabel: UILabel {} class ShowMoreTweetIndicatorView: UIActivityIndicatorView {} // MARK: - Buttons class StreamingButton: UIButton { var connectedColor = UIColor.green var normalColor = UIColor.gray var errorColor = UIColor.red override func awakeFromNib() { super.awakeFromNib() normalColor = ThemeController.currentTheme.bodyTextColor() connectedColor = ThemeController.currentTheme.streamingConnected() errorColor = ThemeController.currentTheme.streamingError() EventBox.onMainThread(self, name: Twitter.Event.StreamingStatusChanged.Name()) { _ in self.setTitleColor() } setTitleColor() } func setTitleColor() { switch Twitter.connectionStatus { case .connected: setTitleColor(connectedColor, for: UIControlState()) case .connecting: setTitleColor(normalColor, for: UIControlState()) case .disconnected: if Twitter.enableStreaming { setTitleColor(errorColor, for: UIControlState()) } else { setTitleColor(normalColor, for: UIControlState()) } case .disconnecting: setTitleColor(normalColor, for: UIControlState()) } } deinit { EventBox.off(self) } } class MenuButton: BaseButton {} class TabButton: BaseButton { var streaming = false { didSet { if streaming { setTitleColor(ThemeController.currentTheme.streamingConnected(), for: UIControlState()) } else { setTitleColor(ThemeController.currentTheme.menuTextColor(), for: UIControlState()) } } } } class FavoritesButton: BaseButton {} class ReplyButton: BaseButton {} class RetweetButton: BaseButton {} class FollowButton: BaseButton {} class UnfollowButton: BaseButton { override func awakeFromNib() { super.awakeFromNib() layerColor = ThemeController.currentTheme.followButtonSelected() borderColor = ThemeController.currentTheme.followButtonSelected() } } // MARK: - Lable class TextLable: UILabel {} class MenuLable: UILabel {} class DisplayNameLable: UILabel {} class ScreenNameLable: UILabel {} class RelativeDateLable: UILabel {} class AbsoluteDateLable: UILabel {} class ClientNameLable: UILabel {} class StatusLable: UITextView { var status: TwitterStatus? var message: TwitterMessage? var threadMode = false var links = [Link]() let playerView = AVPlayerView() struct Link { let entity: Entity let range: NSRange init(entity: Entity, range: NSRange) { self.entity = entity self.range = range } } enum Entity { case url(TwitterURL) case media(TwitterMedia) case hashtag(TwitterHashtag) case user(TwitterUser) } override func awakeFromNib() { super.awakeFromNib() textContainer.lineFragmentPadding = 0 textContainerInset = UIEdgeInsets.zero addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(StatusLable.touchesText(_:)))) } // Disable text selection override func addGestureRecognizer(_ gestureRecognizer: UIGestureRecognizer) { if gestureRecognizer.isKind(of: UILongPressGestureRecognizer.self) { gestureRecognizer.isEnabled = false } super.addGestureRecognizer(gestureRecognizer) } func setStatus(_ status: TwitterStatus) { self.status = status self.text = status.text var newlinks = [Link]() for url in status.urls { for result in findString(url.displayURL) { let link = Link(entity: Entity.url(url), range: result.range) newlinks.append(link) } } for media in status.media { for result in findString(media.displayURL) { let link = Link(entity: Entity.media(media), range: result.range) newlinks.append(link) } } for hashtag in status.hashtags { for result in findString("#" + hashtag.text) { let link = Link(entity: Entity.hashtag(hashtag), range: result.range) newlinks.append(link) } } for mention in status.mentions { for result in findString("@" + mention.screenName) { let link = Link(entity: Entity.user(mention), range: result.range) newlinks.append(link) } } links = newlinks setAttributes() } func setMessage(_ message: TwitterMessage, threadMode: Bool) { self.threadMode = threadMode self.message = message self.text = message.text var newlinks = [Link]() for url in message.urls { for result in findString(url.displayURL) { let link = Link(entity: Entity.url(url), range: result.range) newlinks.append(link) } } for media in message.media { for result in findString(media.displayURL) { let link = Link(entity: Entity.media(media), range: result.range) newlinks.append(link) } } for hashtag in message.hashtags { for result in findString("#" + hashtag.text) { let link = Link(entity: Entity.hashtag(hashtag), range: result.range) newlinks.append(link) } } for mention in message.mentions { for result in findString("@" + mention.screenName) { let link = Link(entity: Entity.user(mention), range: result.range) newlinks.append(link) } } links = newlinks setAttributes() } func setAttributes() { backgroundColor = ThemeController.currentTheme.mainBackgroundColor() let attributedText = NSMutableAttributedString(string: text) attributedText.addAttribute(NSForegroundColorAttributeName, value: ThemeController.currentTheme.bodyTextColor(), range: NSRange.init(location: 0, length: text.utf16.count)) if let font = font { attributedText.addAttribute(NSFontAttributeName, value: UIFont.systemFont(ofSize: font.pointSize), range: NSRange.init(location: 0, length: text.utf16.count)) } for link in links { attributedText.addAttribute(NSForegroundColorAttributeName, value: ThemeController.currentTheme.menuSelectedTextColor(), range: link.range) } self.attributedText = attributedText } fileprivate func findString(_ string: String) -> [NSTextCheckingResult] { let pattern = NSRegularExpression.escapedPattern(for: string) // swiftlint:disable:next force_try let regexp = try! NSRegularExpression(pattern: pattern, options: NSRegularExpression.Options(rawValue: 0)) return regexp.matches(in: text, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSRange.init(location: 0, length: text.utf16.count)) } func touchesText(_ gestureRecognizer: UITapGestureRecognizer) { let location = gestureRecognizer.location(in: self) guard let position = closestPosition(to: location) else { return } let selectedPosition = offset(from: beginningOfDocument, to: position) for link in links { if NSLocationInRange(selectedPosition, link.range) { touchesLink(link) return } } if let status = status { if !status.isRoot { TweetsViewController.show(status) } } else if let message = message, let account = AccountSettingsStore.get()?.account() { if threadMode { if let messages = Twitter.messages[account.userID] { let threadMessages = messages.filter({ $0.collocutor.userID == message.collocutor.userID }) Async.main { MessagesViewController.show(message.collocutor, messages: threadMessages) } } } else { Async.main { DirectMessageAlert.show(account, message: message) } } } } func touchesLink(_ link: Link) { switch link.entity { case .url(let url): Safari.openURL(URL(string: url.expandedURL)!) case .media(let media): if !media.videoURL.isEmpty { if let videoURL = URL(string: media.videoURL) { showVideo(videoURL) } } else { ImageViewController.show([media.mediaURL], initialPage: 0) } case .hashtag(let hashtag): SearchViewController.show("#" + hashtag.text) case .user(let user): ProfileViewController.show(user) } } func showVideo(_ videoURL: URL) { guard let view = UIApplication.shared.keyWindow else { return } playerView.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height) playerView.player = AVPlayer(url: videoURL) playerView.player?.actionAtItemEnd = AVPlayerActionAtItemEnd.none playerView.setVideoFillMode(AVLayerVideoGravityResizeAspect) view.addSubview(playerView) playerView.player?.play() } }
mit
f5ff448d3446642b006400de654c33c7
34.957187
180
0.628848
4.950737
false
false
false
false
pocketworks/Spring
Spring/Misc.swift
1
7532
// The MIT License (MIT) // // Copyright (c) 2015 Meng To ([email protected]) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit public extension String { public var length: Int { return self.characters.count } public func toURL() -> NSURL? { return NSURL(string: self) } } public func htmlToAttributedString(text: String) -> NSAttributedString! { let htmlData = text.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) let htmlString = try? NSAttributedString(data: htmlData!, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil) return htmlString } public func degreesToRadians(degrees: CGFloat) -> CGFloat { return degrees * CGFloat(M_PI / 180) } public func delay(delay:Double, closure:()->()) { dispatch_after( dispatch_time( DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC)) ), dispatch_get_main_queue(), closure) } public func imageFromURL(URL: String) -> UIImage { let url = NSURL(string: URL) let data = NSData(contentsOfURL: url!) return UIImage(data: data!)! } public extension UIColor { convenience init(hex: String) { var red: CGFloat = 0.0 var green: CGFloat = 0.0 var blue: CGFloat = 0.0 var alpha: CGFloat = 1.0 var hex: String = hex if hex.hasPrefix("#") { let index = hex.startIndex.advancedBy(1) hex = hex.substringFromIndex(index) } let scanner = NSScanner(string: hex) var hexValue: CUnsignedLongLong = 0 if scanner.scanHexLongLong(&hexValue) { switch (hex.characters.count) { case 3: red = CGFloat((hexValue & 0xF00) >> 8) / 15.0 green = CGFloat((hexValue & 0x0F0) >> 4) / 15.0 blue = CGFloat(hexValue & 0x00F) / 15.0 case 4: red = CGFloat((hexValue & 0xF000) >> 12) / 15.0 green = CGFloat((hexValue & 0x0F00) >> 8) / 15.0 blue = CGFloat((hexValue & 0x00F0) >> 4) / 15.0 alpha = CGFloat(hexValue & 0x000F) / 15.0 case 6: red = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0 green = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0 blue = CGFloat(hexValue & 0x0000FF) / 255.0 case 8: red = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0 green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0 blue = CGFloat((hexValue & 0x0000FF00) >> 8) / 255.0 alpha = CGFloat(hexValue & 0x000000FF) / 255.0 default: print("Invalid RGB string, number of characters after '#' should be either 3, 4, 6 or 8", terminator: "") } } else { print("Scan hex error") } self.init(red:red, green:green, blue:blue, alpha:alpha) } } public func rgbaToUIColor(red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) -> UIColor { return UIColor(red: red, green: green, blue: blue, alpha: alpha) } public func UIColorFromRGB(rgbValue: UInt) -> UIColor { return UIColor( red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0, green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0, blue: CGFloat(rgbValue & 0x0000FF) / 255.0, alpha: CGFloat(1.0) ) } public func stringFromDate(date: NSDate, format: String) -> String { let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = format return dateFormatter.stringFromDate(date) } public func dateFromString(date: String, format: String) -> NSDate { let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = format if let date = dateFormatter.dateFromString(date) { return date } else { return NSDate(timeIntervalSince1970: 0) } } public func randomStringWithLength (len : Int) -> NSString { let letters : NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" let randomString : NSMutableString = NSMutableString(capacity: len) for (var i=0; i < len; i++){ let length = UInt32 (letters.length) let rand = arc4random_uniform(length) randomString.appendFormat("%C", letters.characterAtIndex(Int(rand))) } return randomString } public func timeAgoSinceDate(date:NSDate, numericDates:Bool) -> String { let calendar = NSCalendar.currentCalendar() let unitFlags: NSCalendarUnit = [NSCalendarUnit.Minute, NSCalendarUnit.Hour, NSCalendarUnit.Day, NSCalendarUnit.WeekOfYear, NSCalendarUnit.Month, NSCalendarUnit.Year, NSCalendarUnit.Second] let now = NSDate() let earliest = now.earlierDate(date) let latest = now.laterDate(date) let components:NSDateComponents = calendar.components(unitFlags, fromDate: earliest, toDate: latest, options: []) if (components.year >= 2) { return "\(components.year)y" } else if (components.year >= 1){ if (numericDates){ return "1y" } else { return "1y" } } else if (components.month >= 2) { return "\(components.month * 4)w" } else if (components.month >= 1){ if (numericDates){ return "4w" } else { return "4w" } } else if (components.weekOfYear >= 2) { return "\(components.weekOfYear)w" } else if (components.weekOfYear >= 1){ if (numericDates){ return "1w" } else { return "1w" } } else if (components.day >= 2) { return "\(components.day)d" } else if (components.day >= 1){ if (numericDates){ return "1d" } else { return "1d" } } else if (components.hour >= 2) { return "\(components.hour)h" } else if (components.hour >= 1){ if (numericDates){ return "1h" } else { return "1h" } } else if (components.minute >= 2) { return "\(components.minute)m" } else if (components.minute >= 1){ if (numericDates){ return "1m" } else { return "1m" } } else if (components.second >= 3) { return "\(components.second)s" } else { return "now" } }
mit
33b70e39361c62ff6da6ce47a703ac15
34.701422
193
0.601567
4.224341
false
false
false
false
ScoutHarris/WordPress-iOS
WordPress/Classes/ViewRelated/Me/AppSettingsViewController.swift
1
16021
import Foundation import UIKit import Gridicons import WordPressShared import SVProgressHUD class AppSettingsViewController: UITableViewController { enum Sections: Int { case media case editor case other } fileprivate var handler: ImmuTableViewHandler! fileprivate static let aztecEditorFooterHeight = CGFloat(34.0) // MARK: - Initialization override init(style: UITableViewStyle) { super.init(style: style) navigationItem.title = NSLocalizedString("App Settings", comment: "App Settings Title") } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } required convenience init() { self.init(style: .grouped) } override func viewDidLoad() { super.viewDidLoad() ImmuTable.registerRows([ DestructiveButtonRow.self, TextRow.self, ImageSizingRow.self, SwitchRow.self, NavigationItemRow.self ], tableView: self.tableView) handler = ImmuTableViewHandler(takeOver: self) reloadViewModel() WPStyleGuide.configureColors(for: view, andTableView: tableView) WPStyleGuide.configureAutomaticHeightRows(for: tableView) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) updateMediaCacheSize() } // MARK: - Model mapping fileprivate func reloadViewModel() { handler.viewModel = tableViewModel() } func tableViewModel() -> ImmuTable { let mediaHeader = NSLocalizedString("Media", comment: "Title label for the media settings section in the app settings") let imageSizingRow = ImageSizingRow( title: NSLocalizedString("Max Image Upload Size", comment: "Title for the image size settings option."), value: Int(MediaSettings().maxImageSizeSetting), onChange: imageSizeChanged()) let videoSizingRow = NavigationItemRow( title: NSLocalizedString("Max Video Upload Size", comment: "Title for the video size settings option."), detail: MediaSettings().maxVideoSizeSetting.description, action: pushVideoResolutionSettings()) let mediaRemoveLocation = SwitchRow( title: NSLocalizedString("Remove Location From Media", comment: "Option to enable the removal of location information/gps from photos and videos"), value: Bool(MediaSettings().removeLocationSetting), onChange: mediaRemoveLocationChanged() ) let mediaCacheRow = TextRow(title: NSLocalizedString("Media Cache Size", comment: "Label for size of media cache in the app."), value: mediaCacheRowDescription) let mediaClearCacheRow = DestructiveButtonRow( title: NSLocalizedString("Clear Media Cache", comment: "Label for button that clears all media cache."), action: { [weak self] row in self?.clearMediaCache() }, accessibilityIdentifier: "mediaClearCacheButton") let editorSettings = EditorSettings() let editorHeader = NSLocalizedString("Editor", comment: "Title label for the editor settings section in the app settings") var editorRows = [ImmuTableRow]() let editor = editorSettings.editor let textEditor = CheckmarkRow( title: NSLocalizedString("Plain Text", comment: "Option to enable the plain text (legacy) editor"), checked: (editor == .legacy), action: visualEditorChanged(editor: .legacy) ) editorRows.append(textEditor) let visualEditor = CheckmarkRow( title: NSLocalizedString("Visual", comment: "Option to enable the hybrid visual editor"), checked: (editor == .hybrid), action: visualEditorChanged(editor: .hybrid) ) editorRows.append(visualEditor) let nativeEditor = CheckmarkRow( title: NSLocalizedString("Visual 2.0", comment: "Option to enable the beta native editor (Aztec)"), checked: (editor == .aztec), action: visualEditorChanged(editor: .aztec) ) editorRows.append(nativeEditor) let usageTrackingHeader = NSLocalizedString("Usage Statistics", comment: "App usage data settings section header") let usageTrackingRow = SwitchRow( title: NSLocalizedString("Send Statistics", comment: "Label for switch to turn on/off sending app usage data"), value: WPAppAnalytics.isTrackingUsage(), onChange: usageTrackingChanged()) let usageTrackingFooter = NSLocalizedString("Automatically send usage statistics to help us improve WordPress for iOS", comment: "App usage data settings section footer describing what the setting does.") let otherHeader = NSLocalizedString("Other", comment: "Link to About section (contains info about the app)") let settingsRow = NavigationItemRow( title: NSLocalizedString("Open Device Settings", comment: "Opens iOS's Device Settings for WordPress App"), action: openApplicationSettings() ) let aboutRow = NavigationItemRow( title: NSLocalizedString("About WordPress for iOS", comment: "Link to About screen for WordPress for iOS"), action: pushAbout() ) return ImmuTable(sections: [ ImmuTableSection( headerText: mediaHeader, rows: [ imageSizingRow, videoSizingRow, mediaRemoveLocation, mediaCacheRow, mediaClearCacheRow ], footerText: nil), ImmuTableSection( headerText: editorHeader, rows: editorRows, footerText: nil), ImmuTableSection( headerText: usageTrackingHeader, rows: [usageTrackingRow], footerText: usageTrackingFooter ), ImmuTableSection( headerText: otherHeader, rows: [ settingsRow, aboutRow ], footerText: nil) ]) } // MARK: - UITableViewDelegate override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { if shouldShowEditorFooterForSection(section) { let footer = UITableViewHeaderFooterView(frame: CGRect(x: 0.0, y: 0.0, width: tableView.frame.width, height: AppSettingsViewController.aztecEditorFooterHeight)) footer.textLabel?.text = NSLocalizedString("Editor release notes & bug reporting", comment: "Label for button linking to release notes and bug reporting help for the new beta Aztec editor") footer.textLabel?.font = UIFont.preferredFont(forTextStyle: .footnote) footer.textLabel?.isUserInteractionEnabled = true let tap = UITapGestureRecognizer(target: self, action: #selector(handleEditorFooterTap(_:))) footer.addGestureRecognizer(tap) return footer } return nil } override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { if shouldShowEditorFooterForSection(section) { return AppSettingsViewController.aztecEditorFooterHeight } return UITableViewAutomaticDimension } private func shouldShowEditorFooterForSection(_ section: Int) -> Bool { return section == Sections.editor.rawValue && EditorSettings().editor == .aztec } @objc fileprivate func handleEditorFooterTap(_ sender: UITapGestureRecognizer) { WPAppAnalytics.track(.editorAztecBetaLink) WPWebViewController.presentWhatsNewWebView(from: self) } // MARK: - Media cache methods fileprivate enum MediaCacheSettingsStatus { case calculatingSize case clearingCache case unknown case empty } fileprivate var mediaCacheRowDescription = "" { didSet { reloadViewModel() } } fileprivate func setMediaCacheRowDescription(allocatedSize: Int64?) { guard let allocatedSize = allocatedSize else { setMediaCacheRowDescription(status: .unknown) return } if allocatedSize == 0 { setMediaCacheRowDescription(status: .empty) return } mediaCacheRowDescription = ByteCountFormatter.string(fromByteCount: allocatedSize, countStyle: ByteCountFormatter.CountStyle.file) } fileprivate func setMediaCacheRowDescription(status: MediaCacheSettingsStatus) { switch status { case .clearingCache: mediaCacheRowDescription = NSLocalizedString("Clearing...", comment: "Label for size of media while it's being cleared.") case .calculatingSize: mediaCacheRowDescription = NSLocalizedString("Calculating...", comment: "Label for size of media while it's being calculated.") case .unknown: mediaCacheRowDescription = NSLocalizedString("Unknown", comment: "Label for size of media when it's not possible to calculate it.") case .empty: mediaCacheRowDescription = NSLocalizedString("Empty", comment: "Label for size of media when the cache is empty.") } } fileprivate func updateMediaCacheSize() { setMediaCacheRowDescription(status: .calculatingSize) MediaFileManager.calculateSizeOfMediaCacheDirectory { [weak self] (allocatedSize) in self?.setMediaCacheRowDescription(allocatedSize: allocatedSize) } } fileprivate func clearMediaCache() { setMediaCacheRowDescription(status: .clearingCache) MediaFileManager.clearAllMediaCacheFiles(onCompletion: { [weak self] in self?.updateMediaCacheSize() }, onError: { [weak self] (error) in self?.updateMediaCacheSize() }) } // MARK: - Actions func imageSizeChanged() -> (Int) -> Void { return { value in MediaSettings().maxImageSizeSetting = value ShareExtensionService.configureShareExtensionMaximumMediaDimension(value) var properties = [String: AnyObject]() properties["enabled"] = (value != Int.max) as AnyObject properties["value"] = value as Int as AnyObject WPAnalytics.track(.appSettingsImageOptimizationChanged, withProperties: properties) } } func pushVideoResolutionSettings() -> ImmuTableAction { return { [weak self] row in let values = [MediaSettings.VideoResolution.size640x480, MediaSettings.VideoResolution.size1280x720, MediaSettings.VideoResolution.size1920x1080, MediaSettings.VideoResolution.size3840x2160, MediaSettings.VideoResolution.sizeOriginal] let titles = values.map({ (settings: MediaSettings.VideoResolution) -> String in settings.description }) let currentVideoResolution = MediaSettings().maxVideoSizeSetting let settingsSelectionConfiguration = [SettingsSelectionDefaultValueKey: currentVideoResolution, SettingsSelectionTitleKey: NSLocalizedString("Resolution", comment: "The largest resolution allowed for uploading"), SettingsSelectionTitlesKey: titles, SettingsSelectionValuesKey: values] as [String : Any] let viewController = SettingsSelectionViewController(dictionary: settingsSelectionConfiguration) viewController?.onItemSelected = { (resolution: Any!) -> () in let newResolution = resolution as! MediaSettings.VideoResolution MediaSettings().maxVideoSizeSetting = newResolution var properties = [String: AnyObject]() properties["enabled"] = (newResolution != MediaSettings.VideoResolution.sizeOriginal) as AnyObject properties["value"] = newResolution.description as AnyObject WPAnalytics.track(.appSettingsVideoOptimizationChanged, withProperties: properties) } self?.navigationController?.pushViewController(viewController!, animated: true) } } func mediaRemoveLocationChanged() -> (Bool) -> Void { return { value in MediaSettings().removeLocationSetting = value WPAnalytics.track(.appSettingsMediaRemoveLocationChanged, withProperties: ["enabled": value as AnyObject]) } } func visualEditorChanged(editor: EditorSettings.Editor) -> ImmuTableAction { return { [weak self] row in let currentEditorIsAztec = EditorSettings().nativeEditorEnabled switch editor { case .legacy: EditorSettings().nativeEditorEnabled = false EditorSettings().visualEditorEnabled = false if currentEditorIsAztec { WPAnalytics.track(.editorToggledOff) } case .hybrid: EditorSettings().nativeEditorEnabled = false EditorSettings().visualEditorEnabled = true if currentEditorIsAztec { WPAnalytics.track(.editorToggledOff) } case .aztec: EditorSettings().visualEditorEnabled = true EditorSettings().nativeEditorEnabled = true if !currentEditorIsAztec { WPAnalytics.track(.editorToggledOn) } } self?.reloadViewModel() } } func nativeEditorChanged() -> (Bool) -> Void { return { enabled in EditorSettings().nativeEditorEnabled = enabled } } func usageTrackingChanged() -> (Bool) -> Void { return { enabled in let appAnalytics = WordPressAppDelegate.sharedInstance().analytics appAnalytics?.setTrackingUsage(enabled) } } func pushAbout() -> ImmuTableAction { return { [weak self] row in let controller = AboutViewController() self?.navigationController?.pushViewController(controller, animated: true) } } func openApplicationSettings() -> ImmuTableAction { return { [weak self] row in if let targetURL = URL(string: UIApplicationOpenSettingsURLString) { UIApplication.shared.open(targetURL) } else { assertionFailure("Couldn't unwrap Settings URL") } self?.tableView.deselectSelectedRowWithAnimation(true) } } } fileprivate struct ImageSizingRow: ImmuTableRow { typealias CellType = MediaSizeSliderCell static let cell: ImmuTableCell = { let nib = UINib(nibName: "MediaSizeSliderCell", bundle: Bundle(for: CellType.self)) return ImmuTableCell.nib(nib, CellType.self) }() static let customHeight: Float? = CellType.height let title: String let value: Int let onChange: (Int) -> Void let action: ImmuTableAction? = nil func configureCell(_ cell: UITableViewCell) { let cell = cell as! CellType cell.title = title cell.value = value cell.onChange = onChange cell.selectionStyle = .none (cell.minValue, cell.maxValue) = MediaSettings().allowedImageSizeRange } }
gpl-2.0
6794e2c0e618b5bf7ac7d790868b0c04
38.853234
212
0.623182
5.681206
false
false
false
false
rpistorello/rp-game-engine
rp-game-engine-src/Util/SKTUtils/Int+Extensions.swift
1
2677
/* * Copyright (c) 2013-2014 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import CoreGraphics public extension Int { /** * Ensures that the integer value stays with the specified range. */ public func clamped(range: Range<Int>) -> Int { return (self < range.startIndex) ? range.startIndex : ((self >= range.endIndex) ? range.endIndex - 1: self) } /** * Ensures that the integer value stays with the specified range. */ public mutating func clamp(range: Range<Int>) -> Int { self = clamped(range) return self } /** * Ensures that the integer value stays between the given values, inclusive. */ public func clamped(v1: Int, _ v2: Int) -> Int { let min = v1 < v2 ? v1 : v2 let max = v1 > v2 ? v1 : v2 return self < min ? min : (self > max ? max : self) } /** * Ensures that the integer value stays between the given values, inclusive. */ public mutating func clamp(v1: Int, _ v2: Int) -> Int { self = clamped(v1, v2) return self } /** * Returns a random integer in the specified range. */ public static func random(range: Range<Int>) -> Int { return Int(arc4random_uniform(UInt32(range.endIndex - range.startIndex))) + range.startIndex } /** * Returns a random integer between 0 and n-1. */ public static func random(n: Int) -> Int { return Int(arc4random_uniform(UInt32(n))) } /** * Returns a random integer in the range min...max, inclusive. */ public static func random(min min: Int, max: Int) -> Int { assert(min <= max) return Int(arc4random_uniform(UInt32(max - min + 1))) + min } }
mit
7d17311e4f696c429770afae29db35dc
32.886076
111
0.682854
3.960059
false
false
false
false
BenziAhamed/Nevergrid
NeverGrid/Source/SpriteManager.swift
1
2558
// // SpriteManager.swift // gettingthere // // Created by Benzi on 01/07/14. // Copyright (c) 2014 Benzi Ahamed. All rights reserved. // import Foundation import SpriteKit import UIKit class SpriteManager { struct Shared { static let gameover = SpriteManager(atlasName: "GameOverSprites") static let entities = SpriteManager(atlasName: "EntitySprites") static let grid = SpriteManager(atlasName: "GridSprites") static let text = SpriteManager(atlasName: "TextSprites") static let clouds = SpriteManager(atlasName: "CloudSprites") static let messages = SpriteManager(atlasName: "HelpMessageSprites") static func preload(callback:()->Void) { let atlases = [ gameover.atlas, entities.atlas, grid.atlas, text.atlas, clouds.atlas ] SKTextureAtlas.preloadTextureAtlases(atlases, withCompletionHandler: callback) } } var atlas:SKTextureAtlas // provides a mechanism to load a texture // textures are cached func texture(name:String) -> SKTexture { return atlas.textureNamed(name) } init(atlasName:String, useSizeTraits:Bool = false) { if useSizeTraits { self.atlas = SKTextureAtlas.atlasWithName(atlasName) } else { self.atlas = SKTextureAtlas(named: atlasName) } } } func messageSprite(name:String) -> SKSpriteNode { let node = SKSpriteNode(texture: SpriteManager.Shared.messages.texture(name)) node.adjustSizeForIpad() return node } func textSprite(name:String) -> SKSpriteNode { let node = SKSpriteNode(texture: SpriteManager.Shared.text.texture(name)) node.adjustSizeForIpad() return node } func cloudSprite(name:String) -> SKSpriteNode { let node = SKSpriteNode(texture: SpriteManager.Shared.clouds.texture(name)) node.adjustSizeForIpad() return node } func entitySprite(name:String) -> SKSpriteNode { return SKSpriteNode(texture: SpriteManager.Shared.entities.texture(name)) } func gridSprite(name:String) -> SKSpriteNode { return SKSpriteNode(texture: SpriteManager.Shared.grid.texture(name)) } func backgroundSprite(name:String) -> SKSpriteNode { return SKSpriteNode(imageNamed: name) } func gameOverSprite(name:String) -> SKSpriteNode { let node = SKSpriteNode(texture: SpriteManager.Shared.gameover.texture(name)) node.adjustSizeForIpad() return node }
isc
ef17749a10441f937dcc91a4da8db95a
27.10989
90
0.664973
4.200328
false
false
false
false
huangboju/Moots
UICollectionViewLayout/SectionReactor-master/Examples/ArticleFeed/ArticleFeed/Sources/CompositionRoot.swift
1
3005
// // CompositionRoot.swift // ArticleFeed // // Created by Suyeol Jeon on 08/09/2017. // Copyright © 2017 Suyeol Jeon. All rights reserved. // import UIKit final class CompositionRoot { static func rootViewController() -> UIViewController { let articleService = ArticleService() let articleSectionReactorFactory: (Article) -> ArticleSectionReactor = { article in return ArticleSectionReactor( article: article, authorCellReactorFactory: ArticleCardAuthorCellReactor.init, textCellReactorFactory: ArticleCardTextCellReactor.init, reactionCellReactorFactory: ArticleCardReactionCellReactor.init, commentCellReactorFactory: ArticleCardCommentCellReactor.init ) } let presentArticleViewControllerFactory: (Article, UIViewController) -> () -> Void = { (article: Article, from: UIViewController) in return { [weak from] in guard let from = from else { return } let reactor = ArticleViewReactor( article: article, articleSectionReactorFactory: articleSectionReactorFactory ) let viewController = ArticleViewController( reactor: reactor, articleCardAuthorCellDependencyFactory: { _, _ in .init(presentArticleViewController: {}) }, articleCardTextCellDependencyFactory: { _, _ in .init(presentArticleViewController: {}) }, articleCardReactionCellDependencyFactory: { _, _ in .init(presentArticleViewController: {}) } ) from.navigationController?.pushViewController(viewController, animated: true) } } let articleCardAuthorCellDependencyFactory: (Article, UIViewController) -> ArticleCardAuthorCell.Dependency = { article, fromViewController in .init(presentArticleViewController: presentArticleViewControllerFactory(article, fromViewController)) } let articleCardTextCellDependencyFactory: (Article, UIViewController) -> ArticleCardTextCell.Dependency = { article, fromViewController in .init(presentArticleViewController: presentArticleViewControllerFactory(article, fromViewController)) } let articleCardReactionCellDependencyFactory: (Article, UIViewController) -> ArticleCardReactionCell.Dependency = { article, fromViewController in .init(presentArticleViewController: presentArticleViewControllerFactory(article, fromViewController)) } let reactor = ArticleListViewReactor( articleService: articleService, articleSectionReactorFactory: articleSectionReactorFactory ) let viewController = ArticleListViewController( reactor: reactor, articleCardAuthorCellDependencyFactory: articleCardAuthorCellDependencyFactory, articleCardTextCellDependencyFactory: articleCardTextCellDependencyFactory, articleCardReactionCellDependencyFactory: articleCardReactionCellDependencyFactory ) let navigationController = UINavigationController(rootViewController: viewController) return navigationController } }
mit
b92e9b1f6c04c974c3b8da29b6fc6862
44.515152
150
0.754993
6.02004
false
false
false
false
Czajnikowski/TrainTrippin
Pods/RxSwift/RxSwift/Subjects/PublishSubject.swift
3
3726
// // PublishSubject.swift // RxSwift // // Created by Krunoslav Zaher on 2/11/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation /** Represents an object that is both an observable sequence as well as an observer. Each notification is broadcasted to all subscribed observers. */ final public class PublishSubject<Element> : Observable<Element> , SubjectType , Cancelable , ObserverType , SynchronizedUnsubscribeType { public typealias SubjectObserverType = PublishSubject<Element> typealias DisposeKey = Bag<AnyObserver<Element>>.KeyType /** Indicates whether the subject has any observers */ public var hasObservers: Bool { _lock.lock(); defer { _lock.unlock() } return _observers.count > 0 } private var _lock = NSRecursiveLock() // state private var _isDisposed = false private var _observers = Bag<AnyObserver<Element>>() private var _stopped = false private var _stoppedEvent = nil as Event<Element>? /** Indicates whether the subject has been isDisposed. */ public var isDisposed: Bool { return _isDisposed } /** Creates a subject. */ public override init() { super.init() } /** Notifies all subscribed observers about next event. - parameter event: Event to send to the observers. */ public func on(_ event: Event<Element>) { _lock.lock(); defer { _lock.unlock() } _synchronized_on(event) } func _synchronized_on(_ event: Event<E>) { switch event { case .next(_): if _isDisposed || _stopped { return } _observers.on(event) case .completed, .error: if _stoppedEvent == nil { _stoppedEvent = event _stopped = true _observers.on(event) _observers.removeAll() } } } /** Subscribes an observer to the subject. - parameter observer: Observer to subscribe to the subject. - returns: Disposable object that can be used to unsubscribe the observer from the subject. */ public override func subscribe<O : ObserverType>(_ observer: O) -> Disposable where O.E == Element { _lock.lock(); defer { _lock.unlock() } return _synchronized_subscribe(observer) } func _synchronized_subscribe<O : ObserverType>(_ observer: O) -> Disposable where O.E == E { if let stoppedEvent = _stoppedEvent { observer.on(stoppedEvent) return Disposables.create() } if _isDisposed { observer.on(.error(RxError.disposed(object: self))) return Disposables.create() } let key = _observers.insert(observer.asObserver()) return SubscriptionDisposable(owner: self, key: key) } func synchronizedUnsubscribe(_ disposeKey: DisposeKey) { _lock.lock(); defer { _lock.unlock() } _synchronized_unsubscribe(disposeKey) } func _synchronized_unsubscribe(_ disposeKey: DisposeKey) { _ = _observers.removeKey(disposeKey) } /** Returns observer interface for subject. */ public func asObserver() -> PublishSubject<Element> { return self } /** Unsubscribe all observers and release resources. */ public func dispose() { _lock.lock(); defer { _lock.unlock() } _synchronized_dispose() } final func _synchronized_dispose() { _isDisposed = true _observers.removeAll() _stoppedEvent = nil } }
mit
0d947a7b7219d2e0a2fa0d3e165e47d9
25.798561
104
0.591946
4.882045
false
false
false
false
ayvazj/BrundleflyiOS
Pod/Classes/Model/BtfyShape.swift
1
1615
/* * Copyright (c) 2015 James Ayvaz * * 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. */ struct BtfyShape { var shapeName: String struct Name { static let rectangle = "rectangle" static let ellipse = "ellipse" } var name: String { get { return self.shapeName } set { if BtfyShape.Name.ellipse == newValue { self.shapeName = newValue } else { self.shapeName = BtfyShape.Name.rectangle } } } init() { shapeName = BtfyShape.Name.rectangle } }
mit
1d50ed5f597549b9d8812dcc6c3fbc9c
33.361702
79
0.68483
4.486111
false
false
false
false
huonw/swift
test/Interpreter/unicode_scalar_literal.swift
19
1705
// RUN: %target-run-simple-swift // RUN: %target-build-swift -O %s -o %t/a.out.optimized // RUN: %target-run %t/a.out.optimized // REQUIRES: executable_test import StdlibUnittest private let testSuite = TestSuite("UnicodeScalar literals") private struct Expressible<T: _ExpressibleByBuiltinUnicodeScalarLiteral> : ExpressibleByUnicodeScalarLiteral { var value: T init(unicodeScalarLiteral value: T) { self.value = value } } private func string(_ characters: UInt32...) -> String { return String(characters.map { Character(UnicodeScalar($0)!) }) } private func expressible<T>(_ literal: Expressible<T>, as type: T.Type) -> String where T: CustomStringConvertible { return literal.value.description } let b = string(0x62) let β = string(0x03_B2) let 𝔹 = string(0x01_D5_39) testSuite.test("String literal type") { expectEqual(expressible("b", as: String.self), b) expectEqual(expressible("β", as: String.self), β) expectEqual(expressible("𝔹", as: String.self), 𝔹) } testSuite.test("StaticString literal type") { expectEqual(expressible("b", as: StaticString.self), b) expectEqual(expressible("β", as: StaticString.self), β) expectEqual(expressible("𝔹", as: StaticString.self), 𝔹) } testSuite.test("Character literal type") { expectEqual(expressible("b", as: Character.self), b) expectEqual(expressible("β", as: Character.self), β) expectEqual(expressible("𝔹", as: Character.self), 𝔹) } testSuite.test("UnicodeScalar literal type") { expectEqual(expressible("b", as: UnicodeScalar.self), b) expectEqual(expressible("β", as: UnicodeScalar.self), β) expectEqual(expressible("𝔹", as: UnicodeScalar.self), 𝔹) } runAllTests()
apache-2.0
83aaff9e65bb0f0e4347c274e1ad3f1b
29.907407
72
0.722588
3.434156
false
true
false
false
eure/ReceptionApp
iOS/Pods/RxCocoa/RxCocoa/iOS/UICollectionView+Rx.swift
6
8745
// // UICollectionView+Rx.swift // RxCocoa // // Created by Krunoslav Zaher on 4/2/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if os(iOS) || os(tvOS) import Foundation #if !RX_NO_MODULE import RxSwift #endif import UIKit // Items extension UICollectionView { /** Binds sequences of elements to collection view items. - parameter source: Observable sequence of items. - parameter cellFactory: Transform between sequence elements and view cells. - returns: Disposable object that can be used to unbind. */ public func rx_itemsWithCellFactory<S: SequenceType, O: ObservableType where O.E == S> (source: O) -> (cellFactory: (UICollectionView, Int, S.Generator.Element) -> UICollectionViewCell) -> Disposable { return { cellFactory in let dataSource = RxCollectionViewReactiveArrayDataSourceSequenceWrapper<S>(cellFactory: cellFactory) return self.rx_itemsWithDataSource(dataSource)(source: source) } } /** Binds sequences of elements to collection view items. - parameter cellIdentifier: Identifier used to dequeue cells. - parameter source: Observable sequence of items. - parameter configureCell: Transform between sequence elements and view cells. - parameter cellType: Type of table view cell. - returns: Disposable object that can be used to unbind. */ public func rx_itemsWithCellIdentifier<S: SequenceType, Cell: UICollectionViewCell, O : ObservableType where O.E == S> (cellIdentifier: String, cellType: Cell.Type = Cell.self) -> (source: O) -> (configureCell: (Int, S.Generator.Element, Cell) -> Void) -> Disposable { return { source in return { configureCell in let dataSource = RxCollectionViewReactiveArrayDataSourceSequenceWrapper<S> { (cv, i, item) in let indexPath = NSIndexPath(forItem: i, inSection: 0) let cell = cv.dequeueReusableCellWithReuseIdentifier(cellIdentifier, forIndexPath: indexPath) as! Cell configureCell(i, item, cell) return cell } return self.rx_itemsWithDataSource(dataSource)(source: source) } } } /** Binds sequences of elements to collection view items using a custom reactive data used to perform the transformation. - parameter dataSource: Data source used to transform elements to view cells. - parameter source: Observable sequence of items. - returns: Disposable object that can be used to unbind. */ public func rx_itemsWithDataSource<DataSource: protocol<RxCollectionViewDataSourceType, UICollectionViewDataSource>, S: SequenceType, O: ObservableType where DataSource.Element == S, O.E == S> (dataSource: DataSource) -> (source: O) -> Disposable { return { source in return source.subscribeProxyDataSourceForObject(self, dataSource: dataSource, retainDataSource: false) { [weak self] (_: RxCollectionViewDataSourceProxy, event) -> Void in guard let collectionView = self else { return } dataSource.collectionView(collectionView, observedEvent: event) } } } } extension UICollectionView { /** Factory method that enables subclasses to implement their own `rx_delegate`. - returns: Instance of delegate proxy that wraps `delegate`. */ public override func rx_createDelegateProxy() -> RxScrollViewDelegateProxy { return RxCollectionViewDelegateProxy(parentObject: self) } /** Factory method that enables subclasses to implement their own `rx_dataSource`. - returns: Instance of delegate proxy that wraps `dataSource`. */ public func rx_createDataSourceProxy() -> RxCollectionViewDataSourceProxy { return RxCollectionViewDataSourceProxy(parentObject: self) } /** Reactive wrapper for `dataSource`. For more information take a look at `DelegateProxyType` protocol documentation. */ public var rx_dataSource: DelegateProxy { get { return proxyForObject(RxCollectionViewDataSourceProxy.self, self) } } /** Installs data source as forwarding delegate on `rx_dataSource`. It enables using normal delegate mechanism with reactive delegate mechanism. - parameter dataSource: Data source object. - returns: Disposable object that can be used to unbind the data source. */ public func rx_setDataSource(dataSource: UICollectionViewDataSource) -> Disposable { let proxy = proxyForObject(RxCollectionViewDataSourceProxy.self, self) return installDelegate(proxy, delegate: dataSource, retainDelegate: false, onProxyForObject: self) } /** Reactive wrapper for `delegate` message `collectionView:didSelectItemAtIndexPath:`. */ public var rx_itemSelected: ControlEvent<NSIndexPath> { let source = rx_delegate.observe("collectionView:didSelectItemAtIndexPath:") .map { a in return a[1] as! NSIndexPath } return ControlEvent(events: source) } /** Reactive wrapper for `delegate` message `collectionView:didSelectItemAtIndexPath:`. */ public var rx_itemDeselected: ControlEvent<NSIndexPath> { let source = rx_delegate.observe("collectionView:didDeselectItemAtIndexPath:") .map { a in return a[1] as! NSIndexPath } return ControlEvent(events: source) } /** Reactive wrapper for `delegate` message `collectionView:didSelectItemAtIndexPath:`. It can be only used when one of the `rx_itemsWith*` methods is used to bind observable sequence, or any other data source conforming to `SectionedViewDataSourceType` protocol. ``` collectionView.rx_modelSelected(MyModel.self) .map { ... ``` */ public func rx_modelSelected<T>(modelType: T.Type) -> ControlEvent<T> { let source: Observable<T> = rx_itemSelected.flatMap { [weak self] indexPath -> Observable<T> in guard let view = self else { return Observable.empty() } return Observable.just(try view.rx_modelAtIndexPath(indexPath)) } return ControlEvent(events: source) } /** Reactive wrapper for `delegate` message `collectionView:didSelectItemAtIndexPath:`. It can be only used when one of the `rx_itemsWith*` methods is used to bind observable sequence, or any other data source conforming to `SectionedViewDataSourceType` protocol. ``` collectionView.rx_modelDeselected(MyModel.self) .map { ... ``` */ public func rx_modelDeselected<T>(modelType: T.Type) -> ControlEvent<T> { let source: Observable<T> = rx_itemDeselected.flatMap { [weak self] indexPath -> Observable<T> in guard let view = self else { return Observable.empty() } return Observable.just(try view.rx_modelAtIndexPath(indexPath)) } return ControlEvent(events: source) } /** Syncronous helper method for retrieving a model at indexPath through a reactive data source */ public func rx_modelAtIndexPath<T>(indexPath: NSIndexPath) throws -> T { let dataSource: SectionedViewDataSourceType = castOrFatalError(self.rx_dataSource.forwardToDelegate(), message: "This method only works in case one of the `rx_itemsWith*` methods was used.") let element = try dataSource.modelAtIndexPath(indexPath) return element as! T } } #endif #if os(tvOS) extension UICollectionView { /** Reactive wrapper for `delegate` message `collectionView:didUpdateFocusInContext:withAnimationCoordinator:`. */ public var rx_didUpdateFocusInContextWithAnimationCoordinator: ControlEvent<(context: UIFocusUpdateContext, animationCoordinator: UIFocusAnimationCoordinator)> { let source = rx_delegate.observe("collectionView:didUpdateFocusInContext:withAnimationCoordinator:") .map { a -> (context: UIFocusUpdateContext, animationCoordinator: UIFocusAnimationCoordinator) in let context = a[1] as! UIFocusUpdateContext let animationCoordinator = a[2] as! UIFocusAnimationCoordinator return (context: context, animationCoordinator: animationCoordinator) } return ControlEvent(events: source) } } #endif
mit
e85cf1ecf96e6b07d56bd6b69f2aed9d
36.050847
198
0.660339
5.397531
false
false
false
false
LouisLWang/curly-garbanzo
weibo-swift/Classes/Module/Discover/Controller/LWDiscoverViewController.swift
1
3234
// // LWDiscoverViewController.swift // weibo-swift // // Created by Louis on 10/27/15. // Copyright © 2015 louis. All rights reserved. // import UIKit class LWDiscoverViewController: LWBaseViewController { override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 0 } /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
apache-2.0
8fa61487e254312cd1ba77f53ebdcf14
33.031579
157
0.686978
5.564544
false
false
false
false
scoremedia/Fisticuffs
Sources/Fisticuffs/AnySubscribable.swift
1
1755
// The MIT License (MIT) // // Copyright (c) 2016 theScore Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. public protocol AnySubscribable: AnyObject { func subscribe(_ options: SubscriptionOptions, block: @escaping () -> Void) -> Disposable func subscribe(_ block: @escaping () -> Void) -> Disposable } // MARK: - // Allows us to wrap a AnySubscribable for equality & hashing internal struct AnySubscribableBox: Equatable, Hashable { let subscribable: AnySubscribable func hash(into hasher: inout Hasher) { hasher.combine(ObjectIdentifier(subscribable)) } } func == (lhs: AnySubscribableBox, rhs: AnySubscribableBox) -> Bool { lhs.subscribable === rhs.subscribable }
mit
e2a92ee68646eb16eaadbf81375a0556
40.785714
93
0.736182
4.333333
false
false
false
false
qingtianbuyu/Mono
Moon/Classes/Explore/Model/MNFollowingEntity.swift
1
662
// // MNFollowingEntity.swift // Moon // // Created by YKing on 16/6/1. // Copyright © 2016年 YKing. All rights reserved. // import UIKit class MNFollowingEntity: MNExploreEntity { var status: String? var user_id: String? var moment_id: String? var uk: String? var bang_num: Int = 0 var action: Int = 0 var created_at: Int = 0 var comment_num: Int = 0 override init(dict: [String : AnyObject]) { super.init(dict: dict) setValuesForKeys(dict) } override func setValue(_ value: Any?, forKey key: String) { if key == "action_user" { return } super.setValue(value, forKey: key) } }
mit
7dfc780a66d36fa65727cbdf061247e7
16.342105
61
0.617602
3.311558
false
false
false
false
itsaboutcode/WordPress-iOS
WordPress/WordPressUITests/Screens/MySiteScreen.swift
1
4201
import UITestsFoundation import XCTest private struct ElementStringIDs { static let navBarTitle = "my-site-navigation-bar" static let blogTable = "Blog Details Table" static let removeSiteButton = "BlogDetailsRemoveSiteCell" static let activityLogButton = "Activity Log Row" static let jetpackScanButton = "Scan Row" static let jetpackBackupButton = "Backup Row" static let postsButton = "Blog Post Row" static let mediaButton = "Media Row" static let statsButton = "Stats Row" static let settingsButton = "Settings Row" static let createButton = "floatingCreateButton" static let ReaderButton = "Reader" static let switchSiteButton = "SwitchSiteButton" } /// The home-base screen for an individual site. Used in many of our UI tests. class MySiteScreen: BaseScreen { let tabBar: TabNavComponent let navBar: XCUIElement let removeSiteButton: XCUIElement let removeSiteSheet: XCUIElement let removeSiteAlert: XCUIElement let activityLogButton: XCUIElement let jetpackScanButton: XCUIElement let jetpackBackupButton: XCUIElement let postsButton: XCUIElement let mediaButton: XCUIElement let statsButton: XCUIElement let siteSettingsButton: XCUIElement let createButton: XCUIElement let readerButton: XCUIElement let switchSiteButton: XCUIElement static var isVisible: Bool { let app = XCUIApplication() let blogTable = app.tables[ElementStringIDs.blogTable] return blogTable.exists && blogTable.isHittable } init() { let app = XCUIApplication() tabBar = TabNavComponent() removeSiteButton = app.cells[ElementStringIDs.removeSiteButton] removeSiteSheet = app.sheets.buttons.element(boundBy: 0) removeSiteAlert = app.alerts.buttons.element(boundBy: 1) activityLogButton = app.cells[ElementStringIDs.activityLogButton] jetpackScanButton = app.cells[ElementStringIDs.jetpackScanButton] jetpackBackupButton = app.cells[ElementStringIDs.jetpackBackupButton] postsButton = app.cells[ElementStringIDs.postsButton] mediaButton = app.cells[ElementStringIDs.mediaButton] statsButton = app.cells[ElementStringIDs.statsButton] siteSettingsButton = app.cells[ElementStringIDs.settingsButton] createButton = app.buttons[ElementStringIDs.createButton] readerButton = app.buttons[ElementStringIDs.ReaderButton] switchSiteButton = app.buttons[ElementStringIDs.switchSiteButton] navBar = app.navigationBars[ElementStringIDs.navBarTitle] super.init(element: navBar) } func showSiteSwitcher() -> MySitesScreen { switchSiteButton.tap() return MySitesScreen() } func removeSelfHostedSite() { removeSiteButton.tap() if XCUIDevice.isPad { removeSiteAlert.tap() } else { removeSiteSheet.tap() } } func gotoActivityLog() -> ActivityLogScreen { activityLogButton.tap() return ActivityLogScreen() } func gotoJetpackScan() -> JetpackScanScreen { jetpackScanButton.tap() return JetpackScanScreen() } func gotoJetpackBackup() -> JetpackBackupScreen { jetpackBackupButton.tap() return JetpackBackupScreen() } func gotoPostsScreen() -> PostsScreen { // A hack for iPad, because sometimes tapping "posts" doesn't load it the first time if XCUIDevice.isPad { mediaButton.tap() } postsButton.tap() return PostsScreen() } func gotoMediaScreen() -> MediaScreen { mediaButton.tap() return MediaScreen() } func gotoStatsScreen() -> StatsScreen { statsButton.tap() return StatsScreen() } func gotoSettingsScreen() -> SiteSettingsScreen { siteSettingsButton.tap() return SiteSettingsScreen() } func gotoCreateSheet() -> ActionSheetComponent { createButton.tap() return ActionSheetComponent() } static func isLoaded() -> Bool { return XCUIApplication().navigationBars[ElementStringIDs.navBarTitle].exists } }
gpl-2.0
48bc0fb6adf9fa546c273fcdf1611b89
31.820313
92
0.690788
4.752262
false
false
false
false
kevintavog/WatchThis
Source/WatchThis/SlideshowData.swift
1
4093
// // import RangicCore import SwiftyJSON class SlideshowData { enum FileError : Error { case filenameNotSet, nameNotSet, noFolders, saveFailed(Int, String), loadFailed(Int, String), invalidSlideshowFile(filename: String, message: String) } var filename:String? var name:String? { didSet { hasChanged = true } } var slideSeconds:Double = 10.0 { didSet { hasChanged = true } } var slideSecondsMax: Double = 10.0 { didSet { hasChanged = true } } var folderList = [String]() { didSet { hasChanged = true } } var searchQuery:String? { didSet { hasChanged = true } } fileprivate(set) var hasChanged = false init() { reset() } static func load(_ fromFile: String) throws -> SlideshowData { do { let fileText = try String(contentsOfFile: fromFile, encoding: String.Encoding.utf8) let json = try JSON(data: fileText.data(using: String.Encoding.utf8, allowLossyConversion: false)!) guard json["name"].string != nil else { throw FileError.invalidSlideshowFile(filename: fromFile, message: "Missing name") } let slideshowData = SlideshowData() slideshowData.name = json["name"].stringValue slideshowData.slideSeconds = json["slideSeconds"].doubleValue if let maxTime = json["slideSecondsMax"].double { slideshowData.slideSecondsMax = maxTime } else { slideshowData.slideSecondsMax = slideshowData.slideSeconds } for folderJson in json["folders"].arrayValue { slideshowData.folderList.append(folderJson["path"].stringValue) } slideshowData.searchQuery = json["searchQuery"].string slideshowData.hasChanged = false return slideshowData } catch let f as FileError { throw f } catch let e as NSError { Logger.error("Load failed: \(e.code): \(e.localizedDescription)") throw FileError.loadFailed(e.code, e.localizedDescription) } } func save() throws { guard filename != nil else { throw FileError.filenameNotSet } guard name != nil else { throw FileError.nameNotSet } guard folderList.count > 0 else { throw FileError.noFolders } Logger.info("Saving to \(filename!)") // Form up json var json = JSON([String: AnyObject]()) json["name"].string = name! json["slideSeconds"].double = slideSeconds json["slideSecondsMax"].double = slideSecondsMax var jsonFolderList = [AnyObject]() for folder in folderList { var jsonFolder = [String: AnyObject]() jsonFolder["path"] = folder as AnyObject? jsonFolderList.append(jsonFolder as AnyObject) } json["folders"].object = jsonFolderList do { if !FileManager.default.fileExists(atPath: Preferences.slideshowFolder) { Logger.info("Creating slideshow folder: \(Preferences.slideshowFolder)") try FileManager.default.createDirectory(atPath: Preferences.slideshowFolder, withIntermediateDirectories: false, attributes: nil) } try json.rawString()!.write(toFile: filename!, atomically: false, encoding: String.Encoding.utf8) hasChanged = false } catch let e as NSError { Logger.error("Save failed: \(e.code): \(e.localizedDescription)") throw FileError.saveFailed(e.code, e.localizedDescription) } } func reset() { filename = nil name = nil slideSeconds = 10.0 slideSecondsMax = 10.0 folderList = [] hasChanged = false } static func getFilenameForName(_ name: String) -> String { return ((Preferences.slideshowFolder as NSString).appendingPathComponent(name) as NSString).appendingPathExtension(Preferences.SlideshowFileExtension)! } }
mit
d7fc5454a62ef4b8d9a5964239038990
32.826446
159
0.609577
4.866825
false
false
false
false
calkinssean/TIY-Assignments
Day 6/HeroesApp/HeroesApp/ViewController.swift
1
3711
// // ViewController.swift // HeroesApp // // Created by Sean Calkins on 2/8/16. // Copyright © 2016 Sean Calkins. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { typealias JSONDictionary = [String:AnyObject] typealias JSONArray = [AnyObject] var jsonString = "" @IBOutlet weak var tableView: UITableView! var shieldHeroes = [Hero]() var currentHero: Hero? override func viewDidLoad() { super.viewDidLoad() getJsonHeroes() print(shieldHeroes) } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return shieldHeroes.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { self.currentHero = self.shieldHeroes[indexPath.row] let cell = UITableViewCell() cell.textLabel?.text = "\(self.currentHero!.name)" return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { self.currentHero = self.shieldHeroes[indexPath.row] performSegueWithIdentifier("segueToDetailView", sender: self) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "segueToDetailView" { let detailViewController = segue.destinationViewController as! DetailViewController detailViewController.hero = self.currentHero } } func getJsonHeroes() { if let filePath = NSBundle.mainBundle().pathForResource("heros", ofType: "json") { do { jsonString = try NSString(contentsOfFile: filePath, usedEncoding: nil) as String } catch { print("Could not load data") } } else { print("heros not found") } let str = String(jsonString) let data = str.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) do { if let data = data, namesArray = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? JSONArray { for result in namesArray { if let jsonResult = result as? JSONDictionary { print(jsonResult) var hero = Hero(name: "", homeworld: "", powers: "", imageName: "") if let name = jsonResult["name"] as? String { hero.name = name print(name) } if let homeworld = jsonResult["homeworld"] as? String { hero.homeworld = homeworld print(homeworld) } if let powers = jsonResult["powers"] as? String { hero.powers = powers } if let imageName = jsonResult["imageName"] as? String { hero.imageName = imageName } shieldHeroes.append(hero) } } } } catch { print("An error occurred") } } }
cc0-1.0
00bc9db43288a536b4d231d5b5a1e3f1
36.484848
109
0.498922
6.256324
false
false
false
false
itsaboutcode/WordPress-iOS
WordPress/Classes/ViewRelated/Suggestions/SuggestionsTableView.swift
1
5996
import Foundation extension SuggestionType { var trigger: String { switch self { case .mention: return "@" case .xpost: return "+" } } } @objc public extension SuggestionsTableView { func userSuggestions(for siteID: NSNumber, completion: @escaping ([UserSuggestion]?) -> Void) { guard let blog = Blog.lookup(withID: siteID, in: ContextManager.shared.mainContext) else { return } SuggestionService.shared.suggestions(for: blog, completion: completion) } func siteSuggestions(for siteID: NSNumber, completion: @escaping ([SiteSuggestion]?) -> Void) { guard let blog = Blog.lookup(withID: siteID, in: ContextManager.shared.mainContext) else { return } SiteSuggestionService.shared.suggestions(for: blog, completion: completion) } var suggestionTrigger: String { return suggestionType.trigger } func predicate(for searchQuery: String) -> NSPredicate { switch suggestionType { case .mention: return NSPredicate(format: "(displayName contains[c] %@) OR (username contains[c] %@)", searchQuery, searchQuery) case .xpost: return NSPredicate(format: "(title contains[cd] %@) OR (siteURL.absoluteString contains[cd] %@)", searchQuery, searchQuery) } } func title(for suggestion: AnyObject) -> String? { let title: String? switch (suggestionType, suggestion) { case (.mention, let suggestion as UserSuggestion): title = suggestion.username case (.xpost, let suggestion as SiteSuggestion): title = suggestion.subdomain default: return nil } return title.map { suggestionType.trigger.appending($0) } } func subtitle(for suggestion: AnyObject) -> String? { switch (suggestionType, suggestion) { case (.mention, let suggestion as UserSuggestion): return suggestion.displayName case (.xpost, let suggestion as SiteSuggestion): return suggestion.title default: return nil } } private func imageURLForSuggestion(at indexPath: IndexPath) -> URL? { let suggestion = searchResults[indexPath.row] switch (suggestionType, suggestion) { case (.mention, let suggestion as UserSuggestion): return suggestion.imageURL case (.xpost, let suggestion as SiteSuggestion): return suggestion.blavatarURL default: return nil } } func loadImage(for suggestion: AnyObject, in cell: SuggestionsTableViewCell, at indexPath: IndexPath) { cell.iconImageView.image = UIImage(named: "gravatar") guard let imageURL = imageURLForSuggestion(at: indexPath) else { return } cell.imageDownloadHash = imageURL.hashValue retrieveIcon(for: imageURL) { image in guard indexPath.row < self.searchResults.count else { return } if let reloadedImageURL = self.imageURLForSuggestion(at: indexPath), reloadedImageURL.hashValue == cell.imageDownloadHash { cell.iconImageView.image = image } } } func fetchSuggestions(for siteID: NSNumber) { switch self.suggestionType { case .mention: userSuggestions(for: siteID) { userSuggestions in self.suggestions = userSuggestions self.showSuggestions(forWord: self.searchText) } case .xpost: siteSuggestions(for: siteID) { siteSuggestions in self.suggestions = siteSuggestions self.showSuggestions(forWord: self.searchText) } } } private func suggestionText(for suggestion: Any) -> String? { switch (suggestionType, suggestion) { case (.mention, let suggestion as UserSuggestion): return suggestion.username case (.xpost, let suggestion as SiteSuggestion): return suggestion.subdomain default: return nil } } private func retrieveIcon(for imageURL: URL?, success: @escaping (UIImage?) -> Void) { let imageSize = CGSize(width: SuggestionsTableViewCellIconSize, height: SuggestionsTableViewCellIconSize) if let image = cachedIcon(for: imageURL, with: imageSize) { success(image) } else { fetchIcon(for: imageURL, with: imageSize, success: success) } } private func cachedIcon(for imageURL: URL?, with size: CGSize) -> UIImage? { var hash: NSString? let type = avatarSourceType(for: imageURL, with: &hash) if let hash = hash, let type = type { return WPAvatarSource.shared()?.cachedImage(forAvatarHash: hash as String, of: type, with: size) } return nil } private func fetchIcon(for imageURL: URL?, with size: CGSize, success: @escaping ((UIImage?) -> Void)) { var hash: NSString? let type = avatarSourceType(for: imageURL, with: &hash) if let hash = hash, let type = type { WPAvatarSource.shared()?.fetchImage(forAvatarHash: hash as String, of: type, with: size, success: success) } else { success(nil) } } } extension SuggestionsTableView { func avatarSourceType(for imageURL: URL?, with hash: inout NSString?) -> WPAvatarSourceType? { if let imageURL = imageURL { return WPAvatarSource.shared()?.parseURL(imageURL, forAvatarHash: &hash) } return .unknown } } extension SuggestionsTableView: UITableViewDelegate { public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let suggestion = searchResults[indexPath.row] let text = suggestionText(for: suggestion) let currentSearchText = String(searchText.dropFirst()) suggestionsDelegate?.suggestionsTableView?(self, didSelectSuggestion: text, forSearchText: currentSearchText) } }
gpl-2.0
ca2407603a44223f78e1a4f326543f1d
36.949367
135
0.640427
4.874797
false
false
false
false
lorentey/swift
test/SourceKit/Indexing/index.swift
5
2652
// RUN: %sourcekitd-test -req=index %s -- -Xfrontend -serialize-diagnostics-path -Xfrontend %t.dia %s | %sed_clean | sed -e 's/key.usr: \".*\"/key.usr: <usr>/g' > %t.response // RUN: diff -u %s.response %t.response var globV: Int class CC { init() {} var instV: CC func meth() {} func instanceFunc0(_ a: Int, b: Float) -> Int { return 0 } func instanceFunc1(a x: Int, b y: Float) -> Int { return 0 } class func smeth() {} } func +(a : CC, b: CC) -> CC { return a } struct S { func meth() {} static func smeth() {} } enum E { case EElem } protocol Prot { func protMeth(_ a: Prot) } func foo(_ a: CC, b: inout E) { globV = 0 a + a.instV a.meth() CC.smeth() b = E.EElem var local: CC class LocalCC {} var local2: LocalCC } typealias CCAlias = CC extension CC : Prot { func meth2(_ x: CCAlias) {} func protMeth(_ a: Prot) {} var extV : Int { return 0 } } class SubCC : CC {} var globV2: SubCC class ComputedProperty { var value : Int { get { var result = 0 return result } set(newVal) { // completely ignore it! } } var readOnly : Int { return 0 } } class BC2 { func protMeth(_ a: Prot) {} } class SubC2 : BC2, Prot { override func protMeth(_ a: Prot) {} } class CC2 { subscript (i : Int) -> Int { get { return i } set(v) { v+1 } } } func test1(_ cp: ComputedProperty, sub: CC2) { var x = cp.value x = cp.readOnly cp.value = x ++cp.value x = sub[0] sub[0] = x ++sub[0] } struct S2 { func sfoo() {} } var globReadOnly : S2 { get { return S2(); } } func test2() { globReadOnly.sfoo() } class B1 { func foo() {} } class SB1 : B1 { override func foo() { foo() self.foo() super.foo() } } func test3(_ c: SB1, s: S2) { test2() c.foo() s.sfoo() } extension Undeclared { func meth() {} } class CC4 { convenience init(x: Int) { self.init(x:0) } } class SubCC4 : CC4 { init(x: Int) { super.init(x:0) } } class Observing { init() {} var globObserving : Int { willSet { test2() } didSet { test2() } } } // <rdar://problem/18640140> :: Crash in swift::Mangle::Mangler::mangleIdentifier() class rdar18640140 { // didSet is not compatible with set/get var S1: Int { get { return 1 } set { } didSet { } } } protocol rdar18640140Protocol { var S1: Int { get set get } } @available(*, unavailable) class AlwaysUnavailableClass { } @available(iOS 99.99, *) class ConditionalUnavailableClass1{ } @available(OSX 99.99, *) class ConditionalUnavailableClass2{ }
apache-2.0
b1a9d07ec119a4bca55bc4aab2967f87
12.740933
174
0.56184
2.879479
false
false
false
false
lorentey/swift
test/Constraints/dictionary_literal.swift
5
5861
// RUN: %target-typecheck-verify-swift final class DictStringInt : ExpressibleByDictionaryLiteral { typealias Key = String typealias Value = Int init(dictionaryLiteral elements: (String, Int)...) { } } final class MyDictionary<K, V> : ExpressibleByDictionaryLiteral { typealias Key = K typealias Value = V init(dictionaryLiteral elements: (K, V)...) { } } func useDictStringInt(_ d: DictStringInt) {} func useDict<K, V>(_ d: MyDictionary<K,V>) {} // Concrete dictionary literals. useDictStringInt(["Hello" : 1]) useDictStringInt(["Hello" : 1, "World" : 2]) useDictStringInt(["Hello" : 1, "World" : 2.5]) // expected-error@-1 {{cannot convert value of type 'Double' to expected dictionary value type 'DictStringInt.Value' (aka 'Int')}} useDictStringInt([4.5 : 2]) // expected-error@-1 {{cannot convert value of type 'Double' to expected dictionary key type 'DictStringInt.Key' (aka 'String')}} useDictStringInt([nil : 2]) // expected-error@-1 {{'nil' is not compatible with expected dictionary key type 'DictStringInt.Key' (aka 'String')}} useDictStringInt([7 : 1, "World" : 2]) // expected-error@-1 {{cannot convert value of type 'Int' to expected dictionary key type 'DictStringInt.Key' (aka 'String')}} useDictStringInt(["Hello" : nil]) // expected-error@-1 {{'nil' is not compatible with expected dictionary value type 'DictStringInt.Value' (aka 'Int')}} typealias FuncBoolToInt = (Bool) -> Int let dict1: MyDictionary<String, FuncBoolToInt> = ["Hello": nil] // expected-error@-1 {{'nil' is not compatible with expected dictionary value type 'MyDictionary<String, FuncBoolToInt>.Value' (aka '(Bool) -> Int')}} // Generic dictionary literals. useDict(["Hello" : 1]) useDict(["Hello" : 1, "World" : 2]) useDict(["Hello" : 1.5, "World" : 2]) useDict([1 : 1.5, 3 : 2.5]) // Fall back to Swift.Dictionary<K, V> if no context is otherwise available. var a = ["Hello" : 1, "World" : 2] var a2 : Dictionary<String, Int> = a var a3 = ["Hello" : 1] var b = [1 : 2, 1.5 : 2.5] var b2 : Dictionary<Double, Double> = b var b3 = [1 : 2.5] // <rdar://problem/22584076> QoI: Using array literal init with dictionary produces bogus error // expected-note @+1 {{did you mean to use a dictionary literal instead?}} var _: MyDictionary<String, (Int) -> Int>? = [ // expected-error {{dictionary of type 'MyDictionary<String, (Int) -> Int>' cannot be initialized with array literal}} "closure_1" as String, {(Int) -> Int in 0}, "closure_2", {(Int) -> Int in 0}] var _: MyDictionary<String, Int>? = ["foo", 1] // expected-error {{dictionary of type 'MyDictionary<String, Int>' cannot be initialized with array literal}} // expected-note @-1 {{did you mean to use a dictionary literal instead?}} {{43-44=:}} var _: MyDictionary<String, Int>? = ["foo", 1, "bar", 42] // expected-error {{dictionary of type 'MyDictionary<String, Int>' cannot be initialized with array literal}} // expected-note @-1 {{did you mean to use a dictionary literal instead?}} {{43-44=:}} {{53-54=:}} var _: MyDictionary<String, Int>? = ["foo", 1.0, 2] // expected-error {{cannot convert value of type '[Double]' to specified type 'MyDictionary<String, Int>?'}} // expected-error@-1 {{cannot convert value of type 'String' to expected element type 'Double'}} var _: MyDictionary<String, Int>? = ["foo" : 1.0] // expected-error {{cannot convert value of type 'Double' to expected dictionary value type 'MyDictionary<String, Int>.Value' (aka 'Int')}} // <rdar://problem/24058895> QoI: Should handle [] in dictionary contexts better var _: [Int: Int] = [] // expected-error {{use [:] to get an empty dictionary literal}} {{22-22=:}} class A { } class B : A { } class C : A { } func testDefaultExistentials() { let _ = ["a" : 1, "b" : 2.5, "c" : "hello"] // expected-error@-1{{heterogeneous collection literal could only be inferred to '[String : Any]'; add explicit type annotation if this is intentional}}{{46-46= as [String : Any]}} let _: [String : Any] = ["a" : 1, "b" : 2.5, "c" : "hello"] let _ = ["a" : 1, "b" : nil, "c" : "hello"] // expected-error@-1{{heterogeneous collection literal could only be inferred to '[String : Any?]'; add explicit type annotation if this is intentional}}{{46-46= as [String : Any?]}} let _: [String : Any?] = ["a" : 1, "b" : nil, "c" : "hello"] let d2 = [:] // expected-error@-1{{empty collection literal requires an explicit type}} let _: Int = d2 // expected-error{{value of type '[AnyHashable : Any]'}} let _ = ["a": 1, "b": ["a", 2, 3.14159], "c": ["a": 2, "b": 3.5]] // expected-error@-3{{heterogeneous collection literal could only be inferred to '[String : Any]'; add explicit type annotation if this is intentional}} let d3 = ["b" : B(), "c" : C()] let _: Int = d3 // expected-error{{value of type '[String : A]'}} let _ = ["a" : B(), 17 : "seventeen", 3.14159 : "Pi"] // expected-error@-1{{heterogeneous collection literal could only be inferred to '[AnyHashable : Any]'}} let _ = ["a" : "hello", 17 : "string"] // expected-error@-1{{heterogeneous collection literal could only be inferred to '[AnyHashable : String]'}} } // SR-4952, rdar://problem/32330004 - Assertion failure during swift::ASTVisitor<::FailureDiagnosis,...>::visit func rdar32330004_1() -> [String: Any] { return ["a""one": 1, "two": 2, "three": 3] // expected-note {{did you mean to use a dictionary literal instead?}} // expected-error@-1 {{expected ',' separator}} // expected-error@-2 {{dictionary of type '[String : Any]' cannot be used with array literal}} } func rdar32330004_2() -> [String: Any] { return ["a", 0, "one", 1, "two", 2, "three", 3] // expected-error@-1 {{dictionary of type '[String : Any]' cannot be used with array literal}} // expected-note@-2 {{did you mean to use a dictionary literal instead?}} {{14-15=:}} {{24-25=:}} {{34-35=:}} {{46-47=:}} }
apache-2.0
6f4a3ad4e4f660c7a65c685c5d03ce0a
47.040984
190
0.65296
3.470101
false
false
false
false
noppoMan/aws-sdk-swift
Sources/Soto/Services/SWF/SWF_Error.swift
1
4851
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import SotoCore /// Error enum for SWF public struct SWFErrorType: AWSErrorType { enum Code: String { case defaultUndefinedFault = "DefaultUndefinedFault" case domainAlreadyExistsFault = "DomainAlreadyExistsFault" case domainDeprecatedFault = "DomainDeprecatedFault" case limitExceededFault = "LimitExceededFault" case operationNotPermittedFault = "OperationNotPermittedFault" case tooManyTagsFault = "TooManyTagsFault" case typeAlreadyExistsFault = "TypeAlreadyExistsFault" case typeDeprecatedFault = "TypeDeprecatedFault" case unknownResourceFault = "UnknownResourceFault" case workflowExecutionAlreadyStartedFault = "WorkflowExecutionAlreadyStartedFault" } private let error: Code public let context: AWSErrorContext? /// initialize SWF public init?(errorCode: String, context: AWSErrorContext) { guard let error = Code(rawValue: errorCode) else { return nil } self.error = error self.context = context } internal init(_ error: Code) { self.error = error self.context = nil } /// return error code string public var errorCode: String { self.error.rawValue } /// The StartWorkflowExecution API action was called without the required parameters set. Some workflow execution parameters, such as the decision taskList, must be set to start the execution. However, these parameters might have been set as defaults when the workflow type was registered. In this case, you can omit these parameters from the StartWorkflowExecution call and Amazon SWF uses the values defined in the workflow type. If these parameters aren't set and no default parameters were defined in the workflow type, this error is displayed. public static var defaultUndefinedFault: Self { .init(.defaultUndefinedFault) } /// Returned if the domain already exists. You may get this fault if you are registering a domain that is either already registered or deprecated, or if you undeprecate a domain that is currently registered. public static var domainAlreadyExistsFault: Self { .init(.domainAlreadyExistsFault) } /// Returned when the specified domain has been deprecated. public static var domainDeprecatedFault: Self { .init(.domainDeprecatedFault) } /// Returned by any operation if a system imposed limitation has been reached. To address this fault you should either clean up unused resources or increase the limit by contacting AWS. public static var limitExceededFault: Self { .init(.limitExceededFault) } /// Returned when the caller doesn't have sufficient permissions to invoke the action. public static var operationNotPermittedFault: Self { .init(.operationNotPermittedFault) } /// You've exceeded the number of tags allowed for a domain. public static var tooManyTagsFault: Self { .init(.tooManyTagsFault) } /// Returned if the type already exists in the specified domain. You may get this fault if you are registering a type that is either already registered or deprecated, or if you undeprecate a type that is currently registered. public static var typeAlreadyExistsFault: Self { .init(.typeAlreadyExistsFault) } /// Returned when the specified activity or workflow type was already deprecated. public static var typeDeprecatedFault: Self { .init(.typeDeprecatedFault) } /// Returned when the named resource cannot be found with in the scope of this operation (region or domain). This could happen if the named resource was never created or is no longer available for this operation. public static var unknownResourceFault: Self { .init(.unknownResourceFault) } /// Returned by StartWorkflowExecution when an open execution with the same workflowId is already running in the specified domain. public static var workflowExecutionAlreadyStartedFault: Self { .init(.workflowExecutionAlreadyStartedFault) } } extension SWFErrorType: Equatable { public static func == (lhs: SWFErrorType, rhs: SWFErrorType) -> Bool { lhs.error == rhs.error } } extension SWFErrorType: CustomStringConvertible { public var description: String { return "\(self.error.rawValue): \(self.message ?? "")" } }
apache-2.0
e459b909ab512048ba69ede46fefef6d
56.75
553
0.725005
5.058394
false
false
false
false
powerytg/Accented
Accented/Core/API/Requests/SearchPhotosRequest.swift
1
4181
// // SearchPhotosRequest.swift // Accented // // Created by Tiangong You on 5/21/17. // Copyright © 2017 Tiangong You. All rights reserved. // import UIKit class SearchPhotosRequest: APIRequest { private var keyword : String? private var tag : String? private var page : Int private var sorting : PhotoSearchSortingOptions init(keyword : String, page : Int = 1, sort : PhotoSearchSortingOptions, params : [String : String], success : SuccessAction?, failure : FailureAction?) { self.keyword = keyword self.page = page self.sorting = sort super.init(success: success, failure: failure) cacheKey = "search_photos/\(keyword)/\(page)" url = "\(APIRequest.baseUrl)photos/search" parameters = params parameters[RequestParameters.term] = keyword parameters[RequestParameters.page] = String(page) parameters[RequestParameters.sort] = sort.rawValue parameters[RequestParameters.includeStates] = "1" if params[RequestParameters.imageSize] == nil { parameters[RequestParameters.imageSize] = APIRequest.defaultImageSizesForStream.map({ (size) -> String in return size.rawValue }).joined(separator: ",") } // By default, exclude node content parameters[RequestParameters.excludeNude] = "1" if params[RequestParameters.exclude] == nil { // Apply default filters parameters[RequestParameters.exclude] = APIRequest.defaultExcludedCategories.joined(separator: ",") } } init(tag : String, page : Int = 1, sort : PhotoSearchSortingOptions, params : [String : String], success : SuccessAction?, failure : FailureAction?) { self.tag = tag self.page = page self.sorting = sort super.init(success: success, failure: failure) cacheKey = "search_photos/\(tag)/\(page)" url = "\(APIRequest.baseUrl)photos/search" parameters = params parameters[RequestParameters.tag] = tag parameters[RequestParameters.page] = String(page) parameters[RequestParameters.sort] = sort.rawValue parameters[RequestParameters.includeStates] = "1" if params[RequestParameters.imageSize] == nil { parameters[RequestParameters.imageSize] = APIRequest.defaultImageSizesForStream.map({ (size) -> String in return size.rawValue }).joined(separator: ",") } // By default, exclude node content parameters[RequestParameters.excludeNude] = "1" if params[RequestParameters.exclude] == nil { // Apply default filters parameters[RequestParameters.exclude] = APIRequest.defaultExcludedCategories.joined(separator: ",") } } override func handleSuccess(data: Data, response: HTTPURLResponse?) { super.handleSuccess(data: data, response: response) var userInfo : [String : Any] = [RequestParameters.feature : StreamType.Search.rawValue, RequestParameters.page : page, RequestParameters.response : data, RequestParameters.sort : sorting] if keyword != nil { userInfo[RequestParameters.term] = keyword! } else if tag != nil { userInfo[RequestParameters.tag] = tag! } NotificationCenter.default.post(name: APIEvents.streamPhotosDidReturn, object: nil, userInfo: userInfo) if let success = successAction { success() } } override func handleFailure(_ error: Error) { super.handleFailure(error) let userInfo : [String : String] = [RequestParameters.errorMessage : error.localizedDescription] NotificationCenter.default.post(name: APIEvents.streamPhotosFailedReturn, object: nil, userInfo: userInfo) if let failure = failureAction { failure(error.localizedDescription) } } }
mit
799ada2adb0881339afc46630f221812
37.703704
158
0.612679
5.135135
false
false
false
false
DivineDominion/mac-multiproc-code
RelocationManager/AppDelegate.swift
1
5256
// // AppDelegate.swift // RelocationManager // // Created by Christian Tietze on 19/01/15. // Copyright (c) 2015 Christian Tietze. All rights reserved. // import Cocoa import ServiceManagement func createXPCConnection(loginItemName: NSString, error: NSErrorPointer) -> NSXPCConnection? { let mainBundleURL = NSBundle.mainBundle().bundleURL let loginItemDirURL = mainBundleURL.URLByAppendingPathComponent("Contents/Library/LoginItems", isDirectory: true) let loginItemURL = loginItemDirURL.URLByAppendingPathComponent(loginItemName) return createXPCConnection(loginItemURL, error) } /// Constant for 1 as a true Boolean let TRUE: Boolean = 1 as Boolean /// Constant for 0 as a true Boolean let FALSE: Boolean = 0 as Boolean func createXPCConnection(loginItemURL: NSURL, error: NSErrorPointer) -> NSXPCConnection? { let loginItemBundle = NSBundle(URL: loginItemURL) if loginItemBundle == nil { if error != nil { error.memory = NSError(domain:NSPOSIXErrorDomain, code:Int(EINVAL), userInfo: [ NSLocalizedFailureReasonErrorKey: "failed to load bundle", NSURLErrorKey: loginItemURL ]) } return nil } // Lookup the bundle identifier for the login item. // LaunchServices implicitly registers a mach service for the login // item whose name is the name as the login item's bundle identifier. if loginItemBundle!.bundleIdentifier? == nil { if error != nil { error.memory = NSError(domain:NSPOSIXErrorDomain, code:Int(EINVAL), userInfo:[ NSLocalizedFailureReasonErrorKey: "bundle has no identifier", NSURLErrorKey: loginItemURL ]) } return nil } let loginItemBundleId = loginItemBundle!.bundleIdentifier! // The login item's file name must match its bundle Id. let loginItemBaseName = loginItemURL.lastPathComponent!.stringByDeletingPathExtension if loginItemBundleId != loginItemBaseName { if error != nil { let message = NSString(format: "expected bundle identifier \"%@\" for login item \"%@\", got \"%@\"", loginItemBaseName, loginItemURL, loginItemBundleId) error.memory = NSError(domain:NSPOSIXErrorDomain, code:Int(EINVAL), userInfo:[ NSLocalizedFailureReasonErrorKey: "bundle identifier does not match file name", NSLocalizedDescriptionKey: message, NSURLErrorKey: loginItemURL ]) } return nil } // Enable the login item. // This will start it running if it wasn't already running. if SMLoginItemSetEnabled(loginItemBundleId as CFString, TRUE) != TRUE { if error != nil { error.memory = NSError(domain:NSPOSIXErrorDomain, code:Int(EINVAL), userInfo:[ NSLocalizedFailureReasonErrorKey: "SMLoginItemSetEnabled() failed" ]) } return nil } return NSXPCConnection(machServiceName: loginItemBundleId, options: NSXPCConnectionOptions(0)) } @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { @IBOutlet weak var window: NSWindow! var connection: NSXPCConnection? var helper: ManagesBoxesAndItems? func applicationDidFinishLaunching(aNotification: NSNotification) { var error: NSError? connect(&error) if (connection == nil) { NSLog("conn failed %@", error!.description) return } connection!.remoteObjectInterface = NSXPCInterface(`protocol`: ManagesBoxesAndItems.self) // connection!.exportedInterface = NSXPCInterface(`protocol`: UsesBoxesAndItems.self) // connection!.exportedObject = self connection!.invalidationHandler = { NSLog("invalidated") } connection!.interruptionHandler = { NSLog("interrupted") } connection!.resume() // Get a proxy DecisionAgent object for the connection. helper = connection!.remoteObjectProxyWithErrorHandler() { err in // This block is run when an error occurs communicating with // the launch item service. This will not be invoked on the // main queue, so re-schedule a block on the main queue to // update the U.I. dispatch_async(dispatch_get_main_queue()) { NSLog("Failed to query oracle: %@\n\n", err.description) } } as? ManagesBoxesAndItems if helper == nil { NSLog("No helper") } } func connect(error: NSErrorPointer) { connection = createXPCConnection("FRMDA3XRGC.de.christiantietze.relocman.Service.app", error) } func windowWillClose(notification: NSNotification) { NSApplication.sharedApplication().terminate(self) } func updateTicker(tick: Int) { NSLog("Tick #\(tick)") } func applicationWillTerminate(aNotification: NSNotification) { //helper = nil connection?.invalidate() } func applicationShouldTerminate(sender: NSApplication) -> NSApplicationTerminateReply { return .TerminateNow } }
mit
2ab635d67b328937ce4b20ef9a284444
35.248276
165
0.651446
5.168142
false
false
false
false
apple/swift-corelibs-foundation
Darwin/Foundation-swiftoverlay-Tests/TestAffineTransform.swift
1
19030
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2020 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 // //===----------------------------------------------------------------------===// import Foundation import XCTest #if os(macOS) extension AffineTransform { func transform(_ aRect: NSRect) -> NSRect { return NSRect(origin: transform(aRect.origin), size: transform(aRect.size)) } } class TestAffineTransform : XCTestCase { private let accuracyThreshold = 0.001 func checkPointTransformation(_ transform: AffineTransform, point: NSPoint, expectedPoint: NSPoint, _ message: String = "", file: StaticString = #file, line: UInt = #line) { let newPoint = transform.transform(point) XCTAssertEqual(Double(newPoint.x), Double(expectedPoint.x), accuracy: accuracyThreshold, "x (expected: \(expectedPoint.x), was: \(newPoint.x)): \(message)", file: file, line: line) XCTAssertEqual(Double(newPoint.y), Double(expectedPoint.y), accuracy: accuracyThreshold, "y (expected: \(expectedPoint.y), was: \(newPoint.y)): \(message)", file: file, line: line) } func checkSizeTransformation(_ transform: AffineTransform, size: NSSize, expectedSize: NSSize, _ message: String = "", file: StaticString = #file, line: UInt = #line) { let newSize = transform.transform(size) XCTAssertEqual(Double(newSize.width), Double(expectedSize.width), accuracy: accuracyThreshold, "width (expected: \(expectedSize.width), was: \(newSize.width)): \(message)", file: file, line: line) XCTAssertEqual(Double(newSize.height), Double(expectedSize.height), accuracy: accuracyThreshold, "height (expected: \(expectedSize.height), was: \(newSize.height)): \(message)", file: file, line: line) } func checkRectTransformation(_ transform: AffineTransform, rect: NSRect, expectedRect: NSRect, _ message: String = "", file: StaticString = #file, line: UInt = #line) { let newRect = transform.transform(rect) checkPointTransformation(transform, point: newRect.origin, expectedPoint: expectedRect.origin, "origin (expected: \(expectedRect.origin), was: \(newRect.origin)): \(message)", file: file, line: line) checkSizeTransformation(transform, size: newRect.size, expectedSize: expectedRect.size, "size (expected: \(expectedRect.size), was: \(newRect.size)): \(message)", file: file, line: line) } func test_BasicConstruction() { let defaultAffineTransform = AffineTransform() let identityTransform = AffineTransform.identity XCTAssertEqual(defaultAffineTransform, identityTransform) // The diagonal entries (1,1) and (2,2) of the identity matrix are ones. The other entries are zeros. // TODO: These should use DBL_MAX but it's not available as part of Glibc on Linux XCTAssertEqual(Double(identityTransform.m11), Double(1), accuracy: accuracyThreshold) XCTAssertEqual(Double(identityTransform.m22), Double(1), accuracy: accuracyThreshold) XCTAssertEqual(Double(identityTransform.m12), Double(0), accuracy: accuracyThreshold) XCTAssertEqual(Double(identityTransform.m21), Double(0), accuracy: accuracyThreshold) XCTAssertEqual(Double(identityTransform.tX), Double(0), accuracy: accuracyThreshold) XCTAssertEqual(Double(identityTransform.tY), Double(0), accuracy: accuracyThreshold) } func test_IdentityTransformation() { let identityTransform = AffineTransform.identity func checkIdentityPointTransformation(_ point: NSPoint) { checkPointTransformation(identityTransform, point: point, expectedPoint: point) } checkIdentityPointTransformation(NSPoint()) checkIdentityPointTransformation(NSPoint(x: CGFloat(24.5), y: CGFloat(10.0))) checkIdentityPointTransformation(NSPoint(x: CGFloat(-7.5), y: CGFloat(2.0))) func checkIdentitySizeTransformation(_ size: NSSize) { checkSizeTransformation(identityTransform, size: size, expectedSize: size) } checkIdentitySizeTransformation(NSSize()) checkIdentitySizeTransformation(NSSize(width: CGFloat(13.0), height: CGFloat(12.5))) checkIdentitySizeTransformation(NSSize(width: CGFloat(100.0), height: CGFloat(-100.0))) } func test_Translation() { let point = NSPoint(x: CGFloat(0.0), y: CGFloat(0.0)) var noop = AffineTransform.identity noop.translate(x: CGFloat(), y: CGFloat()) checkPointTransformation(noop, point: point, expectedPoint: point) var translateH = AffineTransform.identity translateH.translate(x: CGFloat(10.0), y: CGFloat()) checkPointTransformation(translateH, point: point, expectedPoint: NSPoint(x: CGFloat(10.0), y: CGFloat())) var translateV = AffineTransform.identity translateV.translate(x: CGFloat(), y: CGFloat(20.0)) checkPointTransformation(translateV, point: point, expectedPoint: NSPoint(x: CGFloat(), y: CGFloat(20.0))) var translate = AffineTransform.identity translate.translate(x: CGFloat(-30.0), y: CGFloat(40.0)) checkPointTransformation(translate, point: point, expectedPoint: NSPoint(x: CGFloat(-30.0), y: CGFloat(40.0))) } func test_Scale() { let size = NSSize(width: CGFloat(10.0), height: CGFloat(10.0)) var noop = AffineTransform.identity noop.scale(CGFloat(1.0)) checkSizeTransformation(noop, size: size, expectedSize: size) var shrink = AffineTransform.identity shrink.scale(CGFloat(0.5)) checkSizeTransformation(shrink, size: size, expectedSize: NSSize(width: CGFloat(5.0), height: CGFloat(5.0))) var grow = AffineTransform.identity grow.scale(CGFloat(3.0)) checkSizeTransformation(grow, size: size, expectedSize: NSSize(width: CGFloat(30.0), height: CGFloat(30.0))) var stretch = AffineTransform.identity stretch.scale(x: CGFloat(2.0), y: CGFloat(0.5)) checkSizeTransformation(stretch, size: size, expectedSize: NSSize(width: CGFloat(20.0), height: CGFloat(5.0))) } func test_Rotation_Degrees() { let point = NSPoint(x: CGFloat(10.0), y: CGFloat(10.0)) var noop = AffineTransform.identity noop.rotate(byDegrees: CGFloat()) checkPointTransformation(noop, point: point, expectedPoint: point) var tenEighty = AffineTransform.identity tenEighty.rotate(byDegrees: CGFloat(1080.0)) checkPointTransformation(tenEighty, point: point, expectedPoint: point) var rotateCounterClockwise = AffineTransform.identity rotateCounterClockwise.rotate(byDegrees: CGFloat(90.0)) checkPointTransformation(rotateCounterClockwise, point: point, expectedPoint: NSPoint(x: CGFloat(-10.0), y: CGFloat(10.0))) var rotateClockwise = AffineTransform.identity rotateClockwise.rotate(byDegrees: CGFloat(-90.0)) checkPointTransformation(rotateClockwise, point: point, expectedPoint: NSPoint(x: CGFloat(10.0), y: CGFloat(-10.0))) var reflectAboutOrigin = AffineTransform.identity reflectAboutOrigin.rotate(byDegrees: CGFloat(180.0)) checkPointTransformation(reflectAboutOrigin, point: point, expectedPoint: NSPoint(x: CGFloat(-10.0), y: CGFloat(-10.0))) } func test_Rotation_Radians() { let point = NSPoint(x: CGFloat(10.0), y: CGFloat(10.0)) var noop = AffineTransform.identity noop.rotate(byRadians: CGFloat()) checkPointTransformation(noop, point: point, expectedPoint: point) var tenEighty = AffineTransform.identity tenEighty.rotate(byRadians: 6 * .pi) checkPointTransformation(tenEighty, point: point, expectedPoint: point) var rotateCounterClockwise = AffineTransform.identity rotateCounterClockwise.rotate(byRadians: .pi / 2) checkPointTransformation(rotateCounterClockwise, point: point, expectedPoint: NSPoint(x: CGFloat(-10.0), y: CGFloat(10.0))) var rotateClockwise = AffineTransform.identity rotateClockwise.rotate(byRadians: -.pi / 2) checkPointTransformation(rotateClockwise, point: point, expectedPoint: NSPoint(x: CGFloat(10.0), y: CGFloat(-10.0))) var reflectAboutOrigin = AffineTransform.identity reflectAboutOrigin.rotate(byRadians: .pi) checkPointTransformation(reflectAboutOrigin, point: point, expectedPoint: NSPoint(x: CGFloat(-10.0), y: CGFloat(-10.0))) var scaleThenRotate = AffineTransform(scale: 2) scaleThenRotate.rotate(byRadians: .pi / 2) checkPointTransformation(scaleThenRotate, point: point, expectedPoint: NSPoint(x: CGFloat(-20.0), y: CGFloat(20.0))) } func test_Inversion() { let point = NSPoint(x: CGFloat(10.0), y: CGFloat(10.0)) var translate = AffineTransform.identity translate.translate(x: CGFloat(-30.0), y: CGFloat(40.0)) var rotate = AffineTransform.identity translate.rotate(byDegrees: CGFloat(30.0)) var scale = AffineTransform.identity scale.scale(CGFloat(2.0)) var identityTransform = AffineTransform.identity // append transformations identityTransform.append(translate) identityTransform.append(rotate) identityTransform.append(scale) // invert transformations scale.invert() rotate.invert() translate.invert() // append inverse transformations in reverse order identityTransform.append(scale) identityTransform.append(rotate) identityTransform.append(translate) checkPointTransformation(identityTransform, point: point, expectedPoint: point) } func test_TranslationComposed() { var xyPlus5 = AffineTransform.identity xyPlus5.translate(x: CGFloat(2.0), y: CGFloat(3.0)) xyPlus5.translate(x: CGFloat(3.0), y: CGFloat(2.0)) checkPointTransformation(xyPlus5, point: NSPoint(x: CGFloat(-2.0), y: CGFloat(-3.0)), expectedPoint: NSPoint(x: CGFloat(3.0), y: CGFloat(2.0))) } func test_Scaling() { var xyTimes5 = AffineTransform.identity xyTimes5.scale(CGFloat(5.0)) checkPointTransformation(xyTimes5, point: NSPoint(x: CGFloat(-2.0), y: CGFloat(3.0)), expectedPoint: NSPoint(x: CGFloat(-10.0), y: CGFloat(15.0))) var xTimes2YTimes3 = AffineTransform.identity xTimes2YTimes3.scale(x: CGFloat(2.0), y: CGFloat(-3.0)) checkPointTransformation(xTimes2YTimes3, point: NSPoint(x: CGFloat(-1.0), y: CGFloat(3.5)), expectedPoint: NSPoint(x: CGFloat(-2.0), y: CGFloat(-10.5))) } func test_TranslationScaling() { var xPlus2XYTimes5 = AffineTransform.identity xPlus2XYTimes5.translate(x: CGFloat(2.0), y: CGFloat()) xPlus2XYTimes5.scale(x: CGFloat(5.0), y: CGFloat(-5.0)) checkPointTransformation(xPlus2XYTimes5, point: NSPoint(x: CGFloat(1.0), y: CGFloat(2.0)), expectedPoint: NSPoint(x: CGFloat(7.0), y: CGFloat(-10.0))) } func test_ScalingTranslation() { var xyTimes5XPlus3 = AffineTransform.identity xyTimes5XPlus3.scale(CGFloat(5.0)) xyTimes5XPlus3.translate(x: CGFloat(3.0), y: CGFloat()) checkPointTransformation(xyTimes5XPlus3, point: NSPoint(x: CGFloat(1.0), y: CGFloat(2.0)), expectedPoint: NSPoint(x: CGFloat(20.0), y: CGFloat(10.0))) } func test_AppendTransform() { let point = NSPoint(x: CGFloat(10.0), y: CGFloat(10.0)) var identityTransform = AffineTransform.identity identityTransform.append(identityTransform) checkPointTransformation(identityTransform, point: point, expectedPoint: point) let translate = AffineTransform(translationByX: 10.0, byY: 0.0) let scale = AffineTransform(scale: 2.0) var translateThenScale = translate translateThenScale.append(scale) checkPointTransformation(translateThenScale, point: point, expectedPoint: NSPoint(x: CGFloat(40.0), y: CGFloat(20.0))) } func test_PrependTransform() { let point = NSPoint(x: CGFloat(10.0), y: CGFloat(10.0)) var identityTransform = AffineTransform.identity identityTransform.append(identityTransform) checkPointTransformation(identityTransform, point: point, expectedPoint: point) let translate = AffineTransform(translationByX: 10.0, byY: 0.0) let scale = AffineTransform(scale: 2.0) var scaleThenTranslate = translate scaleThenTranslate.prepend(scale) checkPointTransformation(scaleThenTranslate, point: point, expectedPoint: NSPoint(x: CGFloat(30.0), y: CGFloat(20.0))) } func test_TransformComposition() { let origin = NSPoint(x: CGFloat(10.0), y: CGFloat(10.0)) let size = NSSize(width: CGFloat(40.0), height: CGFloat(20.0)) let rect = NSRect(origin: origin, size: size) let center = NSPoint(x: NSMidX(rect), y: NSMidY(rect)) let rotate = AffineTransform(rotationByDegrees: 90.0) let moveOrigin = AffineTransform(translationByX: -center.x, byY: -center.y) var moveBack = moveOrigin moveBack.invert() var rotateAboutCenter = rotate rotateAboutCenter.prepend(moveOrigin) rotateAboutCenter.append(moveBack) // center of rect shouldn't move as its the rotation anchor checkPointTransformation(rotateAboutCenter, point: center, expectedPoint: center) } func test_hashing() { guard #available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) else { return } // the transforms are made up and the values don't matter let a = AffineTransform(m11: 1.0, m12: 2.5, m21: 66.2, m22: 40.2, tX: -5.5, tY: 3.7) let b = AffineTransform(m11: -55.66, m12: 22.7, m21: 1.5, m22: 0.0, tX: -22, tY: -33) let c = AffineTransform(m11: 4.5, m12: 1.1, m21: 0.025, m22: 0.077, tX: -0.55, tY: 33.2) let d = AffineTransform(m11: 7.0, m12: -2.3, m21: 6.7, m22: 0.25, tX: 0.556, tY: 0.99) let e = AffineTransform(m11: 0.498, m12: -0.284, m21: -0.742, m22: 0.3248, tX: 12, tY: 44) // Samples testing that every component is properly hashed let x1 = AffineTransform(m11: 1.0, m12: 2.0, m21: 3.0, m22: 4.0, tX: 5.0, tY: 6.0) let x2 = AffineTransform(m11: 1.5, m12: 2.0, m21: 3.0, m22: 4.0, tX: 5.0, tY: 6.0) let x3 = AffineTransform(m11: 1.0, m12: 2.5, m21: 3.0, m22: 4.0, tX: 5.0, tY: 6.0) let x4 = AffineTransform(m11: 1.0, m12: 2.0, m21: 3.5, m22: 4.0, tX: 5.0, tY: 6.0) let x5 = AffineTransform(m11: 1.0, m12: 2.0, m21: 3.0, m22: 4.5, tX: 5.0, tY: 6.0) let x6 = AffineTransform(m11: 1.0, m12: 2.0, m21: 3.0, m22: 4.0, tX: 5.5, tY: 6.0) let x7 = AffineTransform(m11: 1.0, m12: 2.0, m21: 3.0, m22: 4.0, tX: 5.0, tY: 6.5) @inline(never) func bridged(_ t: AffineTransform) -> NSAffineTransform { return t as NSAffineTransform } let values: [[AffineTransform]] = [ [AffineTransform.identity, NSAffineTransform() as AffineTransform], [a, bridged(a) as AffineTransform], [b, bridged(b) as AffineTransform], [c, bridged(c) as AffineTransform], [d, bridged(d) as AffineTransform], [e, bridged(e) as AffineTransform], [x1], [x2], [x3], [x4], [x5], [x6], [x7] ] checkHashableGroups(values) } func test_AnyHashable() { func makeNSAffineTransform(rotatedByDegrees angle: CGFloat) -> NSAffineTransform { let result = NSAffineTransform() result.rotate(byDegrees: angle) return result } let s1 = AffineTransform.identity let s2 = AffineTransform(m11: -55.66, m12: 22.7, m21: 1.5, m22: 0.0, tX: -22, tY: -33) let s3 = AffineTransform(m11: -55.66, m12: 22.7, m21: 1.5, m22: 0.0, tX: -22, tY: -33) let s4 = makeNSAffineTransform(rotatedByDegrees: 10) as AffineTransform let s5 = makeNSAffineTransform(rotatedByDegrees: 10) as AffineTransform let c1 = NSAffineTransform(transform: s1) let c2 = NSAffineTransform(transform: s2) let c3 = NSAffineTransform(transform: s3) let c4 = makeNSAffineTransform(rotatedByDegrees: 10) let c5 = makeNSAffineTransform(rotatedByDegrees: 10) let groups: [[AnyHashable]] = [ [s1, c1], [s2, c2, s3, c3], [s4, c4, s5, c5] ] checkHashableGroups(groups) expectEqual(AffineTransform.self, type(of: (s1 as AnyHashable).base)) expectEqual(AffineTransform.self, type(of: (s2 as AnyHashable).base)) expectEqual(AffineTransform.self, type(of: (s3 as AnyHashable).base)) expectEqual(AffineTransform.self, type(of: (s4 as AnyHashable).base)) expectEqual(AffineTransform.self, type(of: (s5 as AnyHashable).base)) expectEqual(AffineTransform.self, type(of: (c1 as AnyHashable).base)) expectEqual(AffineTransform.self, type(of: (c2 as AnyHashable).base)) expectEqual(AffineTransform.self, type(of: (c3 as AnyHashable).base)) expectEqual(AffineTransform.self, type(of: (c4 as AnyHashable).base)) expectEqual(AffineTransform.self, type(of: (c5 as AnyHashable).base)) } func test_unconditionallyBridgeFromObjectiveC() { XCTAssertEqual(AffineTransform(), AffineTransform._unconditionallyBridgeFromObjectiveC(nil)) } func test_rotation_compose() { var t = AffineTransform.identity t.translate(x: 1.0, y: 1.0) t.rotate(byDegrees: 90) t.translate(x: -1.0, y: -1.0) let result = t.transform(NSPoint(x: 1.0, y: 2.0)) XCTAssertEqual(0.0, Double(result.x), accuracy: accuracyThreshold) XCTAssertEqual(1.0, Double(result.y), accuracy: accuracyThreshold) } } #endif
apache-2.0
a96640b0ff04861e9abe028600aaa660
47.055556
177
0.634157
4.250614
false
true
false
false
roambotics/swift
test/SILOptimizer/string_optimization.swift
2
4653
// RUN: %target-build-swift -O %s -module-name=test -Xfrontend -sil-verify-all -emit-sil | %FileCheck %s // RUN: %empty-directory(%t) // RUN: %target-build-swift -O -module-name=test %s -o %t/a.out // RUN: %target-run %t/a.out | %FileCheck %s -check-prefix=CHECK-OUTPUT // REQUIRES: executable_test,swift_stdlib_no_asserts // REQUIRES: swift_in_compiler // Test needs to be updated for 32bit. // rdar://74810823 // UNSUPPORTED: PTRSIZE=32 #if _runtime(_ObjC) import Foundation #endif struct Outer { struct Inner { } class InnerClass { } static let staticString = "static" } class C { @inline(never) func f() -> String { return "\(Self.self)" } } // More types are tested in test/stdlib/TypeName.swift and // test/stdlib/TypeNameInterpolation.swift // CHECK-LABEL: sil [noinline] @$s4test0A21TypeNameInterpolationSSyF // CHECK-NOT: apply // CHECK-NOT: bb1 // CHECK: } // end sil function '$s4test0A21TypeNameInterpolationSSyF' @inline(never) public func testTypeNameInterpolation() -> String { return "-\(Outer.Inner.self)+" } // CHECK-LABEL: sil [noinline] @$s4test0A25FoldCompleteInterpolationSSyF // CHECK-NOT: apply // CHECK-NOT: bb1 // CHECK: } // end sil function '$s4test0A25FoldCompleteInterpolationSSyF' @inline(never) public func testFoldCompleteInterpolation() -> String { let s = "is" return "-\([Int].self) \(s) \("cool")+" } // CHECK-LABEL: sil [noinline] @$s4test0A13FoldStaticLetSSyF // CHECK-NOT: apply // CHECK-NOT: bb1 // CHECK: } // end sil function '$s4test0A13FoldStaticLetSSyF' @inline(never) public func testFoldStaticLet() -> String { return "-\(Outer.staticString)+" } // CHECK-LABEL: sil [noinline] @$s4test0A10FoldConcatSSyF // CHECK-NOT: apply // CHECK-NOT: bb1 // CHECK: } // end sil function '$s4test0A10FoldConcatSSyF' @inline(never) public func testFoldConcat() -> String { return "a" + "b" + "c" } // CHECK-LABEL: sil [noinline] @$s4test0A19UnqualifiedTypeNameSSyF // CHECK-NOT: apply // CHECK-NOT: bb1 // CHECK: } // end sil function '$s4test0A19UnqualifiedTypeNameSSyF' @inline(never) public func testUnqualifiedTypeName() -> String { return _typeName(Outer.Inner.self, qualified: false) } // CHECK-LABEL: sil [noinline] @$s4test0A17QualifiedTypeNameSSyF // CHECK-NOT: apply // CHECK-NOT: bb1 // CHECK: } // end sil function '$s4test0A17QualifiedTypeNameSSyF' @inline(never) public func testQualifiedTypeName() -> String { return _typeName(Outer.Inner.self, qualified: true) } // CHECK-LABEL: sil [noinline] @$s4test0A20UnqualifiedLocalTypeSSyF // CHECK-NOT: apply // CHECK-NOT: bb1 // CHECK: } // end sil function '$s4test0A20UnqualifiedLocalTypeSSyF' @inline(never) public func testUnqualifiedLocalType() -> String { struct LocalStruct { } return _typeName(LocalStruct.self, qualified: false) } // CHECK-LABEL: sil [noinline] @$s4test0A18QualifiedLocalTypeSSyF // CHECK: [[F:%[0-9]+]] = function_ref @$ss9_typeName_9qualifiedSSypXp_SbtF // CHECK: apply [[F]] // CHECK: } // end sil function '$s4test0A18QualifiedLocalTypeSSyF' @inline(never) public func testQualifiedLocalType() -> String { struct LocalStruct { } return _typeName(LocalStruct.self, qualified: true) } // CHECK-LABEL: sil [noinline] @$s4test0A10InnerClassSSyF // CHECK-NOT: apply // CHECK-NOT: bb1 // CHECK: } // end sil function '$s4test0A10InnerClassSSyF' @inline(never) public func testInnerClass() -> String { return _typeName(Outer.InnerClass.self, qualified: true) } #if _runtime(_ObjC) @inline(never) public func testObjcClassName(qualified: Bool) -> String { return _typeName(NSObject.self, qualified: qualified) } #endif @inline(never) func printEmbedded(_ s: String) { print("<\(s)>") } // CHECK-OUTPUT: <-Inner+> printEmbedded(testTypeNameInterpolation()) // CHECK-OUTPUT: <-Array<Int> is cool+> printEmbedded(testFoldCompleteInterpolation()) // CHECK-OUTPUT: <-static+> printEmbedded(testFoldStaticLet()) // CHECK-OUTPUT: <abc> printEmbedded(testFoldConcat()) // CHECK-OUTPUT: <Inner> printEmbedded(testUnqualifiedTypeName()) // CHECK-OUTPUT: <test.Outer.Inner> printEmbedded(testQualifiedTypeName()) // CHECK-OUTPUT: <LocalStruct> printEmbedded(testUnqualifiedLocalType()) // CHECK-OUTPUT: <test.(unknown context at {{.*}}).LocalStruct> printEmbedded(testQualifiedLocalType()) // CHECK-OUTPUT: <test.Outer.InnerClass> printEmbedded(testInnerClass()) // CHECK-OUTPUT: <C> printEmbedded(C().f()) #if _runtime(_ObjC) // Can't use check-output here, because for non ObjC runtimes it would not match. if testObjcClassName(qualified: false) != "NSObject" { fatalError() } if testObjcClassName(qualified: true) != "NSObject" { fatalError() } #endif
apache-2.0
a3c0d4b00604ce8138e5e5e50ab81ff3
25.741379
104
0.716957
3.235744
false
true
false
false
jegumhon/URWeatherView
URWeatherView/SpriteAssets/URRainEmitterNode.swift
1
1853
// // URRainEmitterNode.swift // URWeatherView // // Created by DongSoo Lee on 2017. 6. 15.. // Copyright © 2017년 zigbang. All rights reserved. // import SpriteKit open class URRainEmitterNode: SKEmitterNode { public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public override init() { super.init() let bundle = Bundle(for: URRainEmitterNode.self) let particleImage = UIImage(named: "rainDrop-1", in: bundle, compatibleWith: nil)! self.particleTexture = SKTexture(image: particleImage) self.particleBirthRate = 100.0 // self.particleBirthRateMax? self.particleLifetime = 8.0 self.particleLifetimeRange = 0.0 self.particlePositionRange = CGVector(dx: 600.0, dy: 0.0) self.zPosition = 0.0 self.emissionAngle = CGFloat(240.0 * .pi / 180.0) self.emissionAngleRange = 0.0 self.particleSpeed = 200.0 self.particleSpeedRange = 150.0 self.xAcceleration = -100.0 self.yAcceleration = -150.0 self.particleAlpha = 0.7 self.particleAlphaRange = 1.0 self.particleAlphaSpeed = 0.0 self.particleScale = 0.1 self.particleScaleRange = 0.05 self.particleScaleSpeed = 0.0 self.particleRotation = CGFloat(-38.0 * .pi / 180.0) self.particleRotationRange = 0.0 self.particleRotationSpeed = 0.0 self.particleColorBlendFactor = 0.0 self.particleColorBlendFactorRange = 0.0 self.particleColorBlendFactorSpeed = 0.0 self.particleColorSequence = SKKeyframeSequence(keyframeValues: [UIColor(red: 247.0/255.0, green: 247.0/255.0, blue: 1.0, alpha: 1.0), UIColor(red: 247.0/255.0, green: 247.0/255.0, blue: 1.0, alpha: 1.0)], times: [0.0, 1.0]) self.particleBlendMode = .alpha } }
mit
0d794efc53d103329e123d4fcaf9ff77
36.755102
232
0.647027
3.620352
false
false
false
false
soapyigu/LeetCode_Swift
Array/IslandPerimeter.swift
1
837
/** * Question Link: https://leetcode.com/problems/island-perimeter/ * Primary idea: Go through the matrix and check right and down neighbors. * Time Complexity: O(nm), Space Complexity: O(1) * */ class IslandPerimeter { func islandPerimeter(_ grid: [[Int]]) -> Int { var islands = 0, neighbors = 0 for i in 0 ..< grid.count { for j in 0 ..< grid[0].count { if grid[i][j] == 1 { islands += 1 if i < grid.count - 1 && grid[i + 1][j] == 1 { neighbors += 1 } if (j < grid[0].count - 1 && grid[i][j + 1] == 1) { neighbors += 1 } } } } return islands * 4 - neighbors * 2 } }
mit
72e5ef47b35ca9f3f187cbd518fbf1f8
28.928571
74
0.41816
4.227273
false
false
false
false
yar1vn/Swiftilities
Swiftilities/Swiftilities/UIViewController+.swift
1
2967
// // UIViewController+.swift // Swiftilities // // Created by Yariv on 12/4/14. // Copyright (c) 2014 Yariv. All rights reserved. // import UIKit extension UIViewController { // MARK:- Layout Guides var layoutGuidesInsets: UIEdgeInsets { return UIEdgeInsets(top: topLayoutGuide.length, left: 0, bottom: bottomLayoutGuide.length, right: 0) } // MARK:- UINavigationController var rootViewControllerOrSelf: UIViewController { return rootViewController ?? self } var rootViewController: UIViewController? { if let navigationController = self as? UINavigationController { return navigationController.rootViewController } return nil } // MARK:- Launch Safari func presentAlertForURL(#string: String) { presentAlertForURL(url: NSURL(string: string)) } func presentAlertForURL(#url: NSURL?) { if let alert = alertForURL(url: url) { presentViewController(alert, animated: true, completion: nil) } } func alertForURL(#url: NSURL?) -> UIAlertController? { if let url = url { if url.canOpen() { let alert = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet) alert.addAction(UIAlertAction(title: "Open in Safari", style: .Default) { action in url.launchInSafari() }) alert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)) return alert } } return nil } // MARK:- Done button for Compact size class // Call this method for every adapted view controller // Override on the PresentedViewController to relocate the button func createDismissButton() { createDismissButton(onLeftBarButton: true) } func createDismissButton(onLeftBarButton isOnLeft: Bool, type: UIBarButtonSystemItem = .Done) { let button = UIBarButtonItem(barButtonSystemItem: type, target: self, action: "dismiss") if isOnLeft { navigationItem.leftBarButtonItem = button } else { navigationItem.rightBarButtonItem = button } } func presentAlertController(title: String? = nil, message: String? = nil) { presentViewController(UIAlertController(title: title, message: message), animated: true, completion: nil) } // MARK:- Dismissing View Controllers func dismiss() { presentingViewController?.dismissViewControllerAnimated(true, completion: nil) } // Dismiss currently presented view controller, if exists, then present the new one func dissmissAndPresentViewController(viewControllerToPresent: UIViewController, animated flag: Bool, completion: (() -> Void)?) { if let presentedViewController = presentedViewController { dismissViewControllerAnimated(flag) { self.presentViewController(viewControllerToPresent, animated: flag, completion: completion) } } else { presentViewController(viewControllerToPresent, animated: flag, completion: completion) } } }
mit
b4c3644e735ceafa6b11dba110c2c95e
29.916667
132
0.701719
4.953255
false
false
false
false
Tsiems/mobile-sensing-apps
AirDrummer/AIToolbox/MetalNeuralNetwork.swift
1
28642
// // MetalNeuralNetwork.swift // AIToolbox // // Created by Kevin Coble on 1/7/16. // Copyright © 2016 Kevin Coble. All rights reserved. // import Foundation import Accelerate import Metal @available(OSX 10.11, iOS 8.0, *) final class MetalNeuralLayer { let activationFunction: NeuralActivationFunction; let numInputs : Int let numWeights : Int let numNodes : Int var weights : [Float] // Weight array in [Node][input] order. sized to nodes and inputs + 1 (bias term) var z : [Float] // Weighted sum for each node var σ : [Float] // Non-linear result for each node var delta : [Float] // Difference in expected output to calculated result - weighted sum from all nodes this node outputs too /// Create the neural network layer based on a tuple (number of nodes, activation function) init(numInputs : Int, layerDefinition: (numNodes: Int, activation: NeuralActivationFunction)) { // Remember the definition of the layer activationFunction = layerDefinition.activation self.numInputs = numInputs numWeights = numInputs + 1 // One for the bias term numNodes = layerDefinition.numNodes // Create a matrix of the weights for all nodes weights = [Float](repeating: 0.0, count: numNodes * numWeights) // Create the linear sum result array z = [Float](repeating: 0.0, count: numNodes) // Create the non-linear result array σ = [Float](repeating: 0.0, count: numNodes) // Create the delta array delta = [Float](repeating: 0.0, count: numNodes) // Initialize the weights for index in 0..<weights.count { var standardDeviation = 1.0 // Bias weights to one standard dev if ((index % numWeights) != numInputs) { standardDeviation = 1.0 / Double(numInputs) } weights[index] = MetalNeuralLayer.gaussianRandom(0.0, standardDeviation: standardDeviation) // input weights - Initialize to a random number to break initial symmetry of the network, scaled to the inputs } } static var y2 = 0.0 static var use_last = false static func gaussianRandom(_ mean : Float, standardDeviation : Double) -> Float { var y1 : Double if (use_last) /* use value from previous call */ { y1 = y2 use_last = false } else { var w = 1.0 var x1 = 0.0 var x2 = 0.0 repeat { x1 = 2.0 * (Double(arc4random()) / Double(UInt32.max)) - 1.0 x2 = 2.0 * (Double(arc4random()) / Double(UInt32.max)) - 1.0 w = x1 * x1 + x2 * x2 } while ( w >= 1.0 ) w = sqrt( (-2.0 * log( w ) ) / w ) y1 = x1 * w y2 = x2 * w use_last = true } return mean + Float(y1 * standardDeviation) } func getLayerOutputs(_ inputs: MTLBuffer, device: MTLDevice, commandQueue: MTLCommandQueue, metalLibrary: MTLLibrary) -> MTLBuffer { // Assume input array already has bias constant 1.0 appended // Fully-connected nodes means all nodes get the same input array // Create a buffer for storing encoded commands that are sent to GPU let commandBuffer = commandQueue.makeCommandBuffer() // Create an encoder for GPU commands let computeCommandEncoder = commandBuffer.makeComputeCommandEncoder() // Get the name of the metal shader for the layer's non-linearity var programName: String switch (activationFunction) { case .none: programName = "sumForward" case .hyperbolicTangent: programName = "tanhForward" case .sigmoid: programName = "sigmoidForward" case .sigmoidWithCrossEntropy: programName = "sigmoidForward" case .rectifiedLinear: programName = "rectLinearForward" case .softSign: programName = "softSignForward" case .softMax: // Only valid on output (last) layer programName = "softMaxForward" } // Set up a compute pipeline with activation function and add it to encoder let layerOutputProgram = metalLibrary.makeFunction(name: programName) var computePipelineFilter : MTLComputePipelineState? do { try computePipelineFilter = device.makeComputePipelineState(function: layerOutputProgram!) } catch { print("Error creating pipeline filter") } computeCommandEncoder.setComputePipelineState(computePipelineFilter!) // Create a MTLBuffer for the weight matrix let matrixByteLength = weights.count * MemoryLayout.size(ofValue: weights[0]) let matrixBuffer = device.makeBuffer(bytes: &weights, length: matrixByteLength, options: MTLResourceOptions(rawValue: 0)) // Set the input vector for the activation function, e.g. inputs // atIndex: 0 here corresponds to buffer(0) in the activation function computeCommandEncoder.setBuffer(inputs, offset: 0, at: 0) // Set the matrix vector for the activation function, e.g. matrix // atIndex: 1 here corresponds to buffer(1) in the activation function computeCommandEncoder.setBuffer(matrixBuffer, offset: 0, at: 1) // Create the output vector for the summation function, e.g. zBuffer // atIndex: 2 here corresponds to buffer(2) in the activation function let sumResultByteLength = z.count * MemoryLayout<Float>.size let zBuffer = device.makeBuffer(length: sumResultByteLength, options: MTLResourceOptions(rawValue: 0)) computeCommandEncoder.setBuffer(zBuffer, offset: 0, at: 2) // Create the output vector for the activation function, e.g. σBuffer // atIndex: 3 here corresponds to buffer(3) in the activation function let nextLayerInputByteLength = (σ.count + 1) * MemoryLayout<Float>.size // Add one for the bias term let σBuffer = device.makeBuffer(length: nextLayerInputByteLength, options: MTLResourceOptions(rawValue: 0)) computeCommandEncoder.setBuffer(σBuffer, offset: 0, at: 3) // Create the sizing array let sizeArray : [__CLPK_integer] = [__CLPK_integer(numNodes), __CLPK_integer(numWeights)] let sizeArrayByteLength = sizeArray.count * MemoryLayout<Int32>.size let sizeBuffer = device.makeBuffer(bytes: sizeArray, length: sizeArrayByteLength, options: MTLResourceOptions(rawValue: 0)) computeCommandEncoder.setBuffer(sizeBuffer, offset: 0, at: 4) // Hardcoded to 32 for now (recommendation: read about threadExecutionWidth) let threadsPerGroup = MTLSize(width:32,height:1,depth:1) let numThreadgroups = MTLSize(width:((numNodes+1)+31)/32, height:1, depth:1) // Add one to guarantee the bias offset addition thread is performed computeCommandEncoder.dispatchThreadgroups(numThreadgroups, threadsPerThreadgroup: threadsPerGroup) computeCommandEncoder.endEncoding() commandBuffer.commit() commandBuffer.waitUntilCompleted() // Extract the z values let zData = Data(bytesNoCopy: zBuffer.contents(), count: sumResultByteLength, deallocator: .none) (zData as NSData).getBytes(&z, length:sumResultByteLength) // Extract the σ values let activationResultByteLength = σ.count * MemoryLayout<Float>.size let σData = NSMutableData(bytesNoCopy: σBuffer.contents(), length: activationResultByteLength, freeWhenDone: false) σData.getBytes(&σ, length:activationResultByteLength) // Add the bias term to the buffer so it is ready for the next layer let byteRange = NSMakeRange(activationResultByteLength, MemoryLayout<Float>.size) var bias : Float = 1.0 σData.replaceBytes(in: byteRange, withBytes: &bias) if (activationFunction == .softMax) { // Get the sum of the output nodes var sum: Float = 0.0; vDSP_vswsum(σ, 1, &sum, 1, 1, vDSP_Length(numNodes)); // Divide each element by the sum vDSP_vsdiv(σ, 1, &sum, &σ, 1, vDSP_Length(numNodes)); // Get the outputs into the passed-back buffer let byteRange = NSMakeRange(0, activationResultByteLength) σData.replaceBytes(in: byteRange, withBytes: &σ) } return σBuffer } // Get the partial derivitive of the error with respect to the weighted sum func getFinalLayerDelta(_ expectedOutputs: [Float], device: MTLDevice, commandQueue: MTLCommandQueue, metalLibrary: MTLLibrary) { // error = (result - expected value)^2 (squared error) - not the case for softmax or cross entropy // derivitive of error = 2 * (result - expected value) * result' (chain rule - result is a function of the sum through the non-linearity) // derivitive of the non-linearity: tanh' -> 1 - result^2, sigmoid -> result - result^2, rectlinear -> 0 if result<0 else 1 // derivitive of error = 2 * (result - expected value) * derivitive from above // Create a buffer for storing encoded commands that are sent to GPU let commandBuffer = commandQueue.makeCommandBuffer() // Create an encoder for GPU commands let computeCommandEncoder = commandBuffer.makeComputeCommandEncoder() // Get the name of the metal shader for the layer's non-linearity var programName: String switch (activationFunction) { case .none: programName = "sumFinal" case .hyperbolicTangent: programName = "tanhFinal" case .sigmoid: programName = "sigmoidFinal" case .sigmoidWithCrossEntropy: programName = "sigmoidCrossEntropyFinal" case .rectifiedLinear: programName = "rectLinearFinal" case .softSign: programName = "softSignFinal" case .softMax: // Only valid on output (last) layer programName = "softMaxFinal" } // Set up a compute pipeline with activation function and add it to encoder let layerOutputProgram = metalLibrary.makeFunction(name: programName) var computePipelineFilter : MTLComputePipelineState? do { try computePipelineFilter = device.makeComputePipelineState(function: layerOutputProgram!) } catch { print("Error creating pipeline filter") } computeCommandEncoder.setComputePipelineState(computePipelineFilter!) // Create a MTLBuffer for the σ vector let resultsByteLength = σ.count * MemoryLayout<Float>.size let σBuffer = device.makeBuffer(bytes: &σ, length: resultsByteLength, options: MTLResourceOptions(rawValue: 0)) // Set the result vector for the final delta function, e.g. σBuffer // atIndex: 0 here corresponds to buffer(0) in the activation function computeCommandEncoder.setBuffer(σBuffer, offset: 0, at: 0) // Create a MTLBuffer for the expected results vector let expectedBuffer = device.makeBuffer(bytes: expectedOutputs, length: resultsByteLength, options: MTLResourceOptions(rawValue: 0)) // Set the result vector for the sigma value, e.g. expectedBuffer // atIndex: 0 here corresponds to buffer(0) in the activation function computeCommandEncoder.setBuffer(expectedBuffer, offset: 0, at: 1) // Create the output vector for the final delta value, e.g. deltaBuffer // atIndex: 3 here corresponds to buffer(3) in the activation function let deltaBuffer = device.makeBuffer(length: resultsByteLength, options: MTLResourceOptions(rawValue: 0)) computeCommandEncoder.setBuffer(deltaBuffer, offset: 0, at: 2) // Hardcoded to 32 for now (recommendation: read about threadExecutionWidth) let threadsPerGroup = MTLSize(width:32,height:1,depth:1) let numThreadgroups = MTLSize(width:((numNodes+1)+31)/32, height:1, depth:1) // Add one to guarantee the bias offset addition thread is performed computeCommandEncoder.dispatchThreadgroups(numThreadgroups, threadsPerThreadgroup: threadsPerGroup) computeCommandEncoder.endEncoding() commandBuffer.commit() commandBuffer.waitUntilCompleted() // Extract the delta values let deltaData = Data(bytesNoCopy: deltaBuffer.contents(), count: resultsByteLength, deallocator: .none) (deltaData as NSData).getBytes(&delta, length:resultsByteLength) } // Transfer the delta from the forward layer to this one func getLayerDelta(_ nextLayer: MetalNeuralLayer, device: MTLDevice, commandQueue: MTLCommandQueue, metalLibrary: MTLLibrary) { // Create a buffer for storing encoded commands that are sent to GPU let commandBuffer = commandQueue.makeCommandBuffer() // Create an encoder for GPU commands let computeCommandEncoder = commandBuffer.makeComputeCommandEncoder() // Get the name of the metal shader for the layer's delta calculation var programName: String switch (activationFunction) { case .none: programName = "sumDelta" case .hyperbolicTangent: programName = "tanhDelta" case .sigmoid: programName = "sigmoidDelta" case .sigmoidWithCrossEntropy: programName = "sigmoidDelta" case .rectifiedLinear: programName = "rectLinearDelta" case .softSign: programName = "softSignDelta" case .softMax: // Only valid on output (last) layer print("SoftMax activation function on non-last layer") return } // Set up a compute pipeline with activation function and add it to encoder let layerOutputProgram = metalLibrary.makeFunction(name: programName) var computePipelineFilter : MTLComputePipelineState? do { try computePipelineFilter = device.makeComputePipelineState(function: layerOutputProgram!) } catch { print("Error creating pipeline filter") } computeCommandEncoder.setComputePipelineState(computePipelineFilter!) // Create a MTLBuffer for the weight matrix from the next layer and assign to buffer 0 let weightsByteLength = nextLayer.weights.count * MemoryLayout<Float>.size let weightBuffer = device.makeBuffer(bytes: &nextLayer.weights, length: weightsByteLength, options: MTLResourceOptions(rawValue: 0)) computeCommandEncoder.setBuffer(weightBuffer, offset: 0, at: 0) // Create a MTLBuffer for the delta vector from the next layer and assign to buffer 1 let deltaByteLength = nextLayer.delta.count * MemoryLayout<Float>.size let deltaBuffer = device.makeBuffer(bytes: &nextLayer.delta, length: deltaByteLength, options: MTLResourceOptions(rawValue: 0)) computeCommandEncoder.setBuffer(deltaBuffer, offset: 0, at: 1) // Create a MTLBuffer for the sizing array from the next layer and assign to buffer 2 let sizeArray : [__CLPK_integer] = [__CLPK_integer(nextLayer.numNodes), __CLPK_integer(numNodes)] let sizeArrayByteLength = sizeArray.count * MemoryLayout<Int32>.size let sizeBuffer = device.makeBuffer(bytes: sizeArray, length: sizeArrayByteLength, options: MTLResourceOptions(rawValue: 0)) computeCommandEncoder.setBuffer(sizeBuffer, offset: 0, at: 2) // Create a MTLBuffer for the σ vector and assign to buffer 3 let resultsByteLength = delta.count * MemoryLayout<Float>.size let σBuffer = device.makeBuffer(bytes: &σ, length: resultsByteLength, options: MTLResourceOptions(rawValue: 0)) computeCommandEncoder.setBuffer(σBuffer, offset: 0, at: 3) // Create the output vector for the final delta function, e.g. resultBuffer and assignt to buffer 4 // atIndex: 3 here corresponds to buffer(3) in the activation function let resultBuffer = device.makeBuffer(length: resultsByteLength, options: MTLResourceOptions(rawValue: 0)) computeCommandEncoder.setBuffer(resultBuffer, offset: 0, at: 4) // Hardcoded to 32 for now (recommendation: read about threadExecutionWidth) let threadsPerGroup = MTLSize(width:32,height:1,depth:1) let numThreadgroups = MTLSize(width:((numNodes+1)+31)/32, height:1, depth:1) // Add one to guarantee the bias offset addition thread is performed computeCommandEncoder.dispatchThreadgroups(numThreadgroups, threadsPerThreadgroup: threadsPerGroup) computeCommandEncoder.endEncoding() commandBuffer.commit() commandBuffer.waitUntilCompleted() // Extract the delta values let deltaData = Data(bytesNoCopy: deltaBuffer.contents(), count: resultsByteLength, deallocator: .none) (deltaData as NSData).getBytes(&delta, length:resultsByteLength) } func updateWeights(_ inputs: MTLBuffer, trainingRate: Float, weightDecay: Float, device: MTLDevice, commandQueue: MTLCommandQueue, metalLibrary: MTLLibrary) { // Assume input array already has bias constant 1.0 appended // Fully-connected nodes means all nodes get the same input array // Create a buffer for storing encoded commands that are sent to GPU let commandBuffer = commandQueue.makeCommandBuffer() // Create an encoder for GPU commands let computeCommandEncoder = commandBuffer.makeComputeCommandEncoder() // Get the name of the metal shader for the layer's weight update let programName = "updateWeights" // Set up a compute pipeline with activation function and add it to encoder let layerOutputProgram = metalLibrary.makeFunction(name: programName) var computePipelineFilter : MTLComputePipelineState? do { try computePipelineFilter = device.makeComputePipelineState(function: layerOutputProgram!) } catch { print("Error creating pipeline filter") } computeCommandEncoder.setComputePipelineState(computePipelineFilter!) // Set the input vector as the first buffer computeCommandEncoder.setBuffer(inputs, offset: 0, at: 0) // Create a MTLBuffer for the delta vector and assign to buffer 1 let deltaByteLength = delta.count * MemoryLayout<Float>.size let deltaBuffer = device.makeBuffer(bytes: &delta, length: deltaByteLength, options: MTLResourceOptions(rawValue: 0)) computeCommandEncoder.setBuffer(deltaBuffer, offset: 0, at: 1) // Create the parameter array let paramArray : [Float] = [trainingRate, weightDecay] let paramArrayByteLength = paramArray.count * MemoryLayout<Float>.size let paramBuffer = device.makeBuffer(bytes: paramArray, length: paramArrayByteLength, options: MTLResourceOptions(rawValue: 0)) computeCommandEncoder.setBuffer(paramBuffer, offset: 0, at: 2) // Create the sizing array let sizeArray : [__CLPK_integer] = [__CLPK_integer(numNodes), __CLPK_integer(numWeights)] let sizeArrayByteLength = sizeArray.count * MemoryLayout<Int32>.size let sizeBuffer = device.makeBuffer(bytes: sizeArray, length: sizeArrayByteLength, options: MTLResourceOptions(rawValue: 0)) computeCommandEncoder.setBuffer(sizeBuffer, offset: 0, at: 3) // Create a MTLBuffer for the weight matrix let matrixByteLength = weights.count * MemoryLayout.size(ofValue: weights[0]) let matrixBuffer = device.makeBuffer(bytes: &weights, length: matrixByteLength, options: MTLResourceOptions(rawValue: 0)) computeCommandEncoder.setBuffer(matrixBuffer, offset: 0, at: 4) // Hardcoded to 32 for now (recommendation: read about threadExecutionWidth) let threadsPerGroup = MTLSize(width:32,height:1,depth:1) let numThreadgroups = MTLSize(width:((numNodes+1)+31)/32, height:1, depth:1) // Add one to guarantee the bias offset addition thread is performed computeCommandEncoder.dispatchThreadgroups(numThreadgroups, threadsPerThreadgroup: threadsPerGroup) computeCommandEncoder.endEncoding() commandBuffer.commit() commandBuffer.waitUntilCompleted() // Extract the updated weights let weightData = Data(bytesNoCopy: matrixBuffer.contents(), count: matrixByteLength, deallocator: .none) (weightData as NSData).getBytes(&weights, length:matrixByteLength) } } @available(OSX 10.11, iOS 8.0, *) open class MetalNeuralNetwork { let device: MTLDevice? var commandQueue: MTLCommandQueue? var metalNNLibrary: MTLLibrary? // Layers var layers : [MetalNeuralLayer] public init?(numInputs : Int, layerDefinitions: [(numNodes: Int, activation: NeuralActivationFunction)]) { self.commandQueue = nil self.metalNNLibrary = nil self.layers = [] // Get access to GPU self.device = MTLCreateSystemDefaultDevice() if device == nil { return nil } // Queue to handle an ordered list of command buffers self.commandQueue = device!.makeCommandQueue() // Access to Metal functions that are stored in MetalNeuralNetworkShaders string, e.g. sigmoid() self.metalNNLibrary = try? device!.makeLibrary(source: metalNNShaders, options: nil) if metalNNLibrary == nil { return nil } // Set up the layers var numInputsFromPreviousLayer = numInputs for layerDefinition in layerDefinitions { let layer = MetalNeuralLayer(numInputs: numInputsFromPreviousLayer, layerDefinition: layerDefinition) layers.append(layer) numInputsFromPreviousLayer = layerDefinition.numNodes } } open func feedForward(_ inputs: [Float]) -> [Float] { // Start with the inputs for the first layer var layerInputs = inputs // Add a bias constant 1.0 to the input array layerInputs.append(1.0) // Create a MTLBuffer for the input vector let inputsByteLength = layerInputs.count * MemoryLayout<Float>.size var inputBuffer = device!.makeBuffer(bytes: &layerInputs, length: inputsByteLength, options: MTLResourceOptions(rawValue: 0)) // Go through each layer for layer in layers { // Calculate the outputs from the layer inputBuffer = layer.getLayerOutputs(inputBuffer, device: device!, commandQueue: commandQueue!, metalLibrary: metalNNLibrary!) } return layers.last!.σ } open func trainOne(_ inputs: [Float], expectedOutputs: [Float], trainingRate: Float, weightDecay: Float) { // Get the results of a feedForward run (each node remembers its own output) _ = feedForward(inputs) // Calculate the delta for the final layer layers.last!.getFinalLayerDelta(expectedOutputs, device: device!, commandQueue: commandQueue!, metalLibrary: metalNNLibrary!) // Get the deltas for the other layers if (layers.count > 1) { for nLayerIndex in stride(from: (layers.count - 2), through: 0, by: -1) { layers[nLayerIndex].getLayerDelta(layers[nLayerIndex+1], device: device!, commandQueue: commandQueue!, metalLibrary: metalNNLibrary!) } } // Set the inputs for calculating the weight changes var layerInputs = inputs // Add a bias constant 1.0 to the input array layerInputs.append(1.0) // Create a MTLBuffer for the input vector var inputsByteLength = layerInputs.count * MemoryLayout<Float>.size var inputBuffer = device!.makeBuffer(bytes: &layerInputs, length: inputsByteLength, options: MTLResourceOptions(rawValue: 0)) // Go through each layer for nLayerIndex in 0..<layers.count { // Update the weights in the layer layers[nLayerIndex].updateWeights(inputBuffer, trainingRate: trainingRate, weightDecay: weightDecay, device: device!, commandQueue: commandQueue!, metalLibrary: metalNNLibrary!) if (nLayerIndex < layers.count - 1) { layerInputs = layers[nLayerIndex].σ layerInputs.append(1.0) inputsByteLength = layerInputs.count * MemoryLayout<Float>.size inputBuffer = device!.makeBuffer(bytes: &layerInputs, length: inputsByteLength, options: MTLResourceOptions(rawValue: 0)) } } } /* public func testMetal() { // Create a buffer for storing encoded commands that are sent to GPU let commandBuffer = commandQueue!.commandBuffer() // Create an encoder for GPU commands let computeCommandEncoder = commandBuffer.computeCommandEncoder() // Set up a compute pipeline with Sigmoid function and add it to encoder let sigmoidProgram = metalNNLibrary!.newFunctionWithName("sigmoid") var computePipelineFilter : MTLComputePipelineState? do { try computePipelineFilter = device!.newComputePipelineStateWithFunction(sigmoidProgram!) } catch { print("Error creating pipeline filter") } computeCommandEncoder.setComputePipelineState(computePipelineFilter!) var myvector = [Float](count: 123456, repeatedValue: 0) for (index, _) in myvector.enumerate() { myvector[index] = Float(index) } // Calculate byte length of input data - myvector let myvectorByteLength = myvector.count*sizeofValue(myvector[0]) // Create a MTLBuffer - input data that the GPU and Metal and produce let inVectorBuffer = device!.newBufferWithBytes(&myvector, length: myvectorByteLength, options: MTLResourceOptions(rawValue: 0)) // Set the input vector for the Sigmoid() function, e.g. inVector // atIndex: 0 here corresponds to buffer(0) in the Sigmoid function computeCommandEncoder.setBuffer(inVectorBuffer, offset: 0, atIndex: 0) // Create the output vector for the Sigmoid() function, e.g. outVector // atIndex: 1 here corresponds to buffer(1) in the Sigmoid function var resultdata = [Float](count:myvector.count, repeatedValue: 0) let outVectorBuffer = device!.newBufferWithBytes(&resultdata, length: myvectorByteLength, options: MTLResourceOptions(rawValue: 0)) computeCommandEncoder.setBuffer(outVectorBuffer, offset: 0, atIndex: 1) // Hardcoded to 32 for now (recommendation: read about threadExecutionWidth) let threadsPerGroup = MTLSize(width:32,height:1,depth:1) let numThreadgroups = MTLSize(width:(myvector.count+31)/32, height:1, depth:1) computeCommandEncoder.dispatchThreadgroups(numThreadgroups, threadsPerThreadgroup: threadsPerGroup) computeCommandEncoder.endEncoding() commandBuffer.commit() commandBuffer.waitUntilCompleted() // Get GPU data // outVectorBuffer.contents() returns UnsafeMutablePointer roughly equivalent to char* in C let data = NSData(bytesNoCopy: outVectorBuffer.contents(), length: myvector.count*sizeof(Float), freeWhenDone: false) // Prepare Swift array large enough to receive data from GPU var finalResultArray = [Float](count: myvector.count, repeatedValue: 0) // Get data from GPU into Swift array data.getBytes(&finalResultArray, length:myvector.count * sizeof(Float)) } */ }
mit
dae05ffed2941b2fd2c353c4582653f8
48.412781
218
0.653058
4.920881
false
false
false
false
mleiv/MEGameTracker
MEGameTracker/Views/Common/Data Rows/Origin Hint/OriginHintType.swift
1
1788
// // OriginHintType.swift // MEGameTracker // // Created by Emily Ivie on 5/26/16. // Copyright © 2016 urdnot. All rights reserved. // import UIKit public struct OriginHintType: TextDataRowType { public typealias RowType = TextDataRow var view: RowType? { return row } public var row: TextDataRow? public var identifier: String = "\(UUID().uuidString)" public var controller: OriginHintable? public var overrideOriginHint: String? public var overrideOriginPrefix: String? public var text: String? { if let originHint = overrideOriginHint ?? controller?.originHint, !originHint.isEmpty { if let originPrefix = overrideOriginPrefix ?? controller?.originPrefix, !originPrefix.isEmpty { return "\(originPrefix): \(originHint)" } else { return originHint } } else if UIWindow.isInterfaceBuilder { return "From: Sahrabarik" } return nil } var viewController: UIViewController? { return controller as? UIViewController } let defaultPaddingBottom: CGFloat = 5.0 let defaultPaddingSides: CGFloat = 10.0 public init() {} public init(controller: OriginHintable, view: TextDataRow?) { self.controller = controller self.row = view } public mutating func setupView() { setupView(type: RowType.self) } public mutating func setup(view: UIView?) { guard let view = view as? RowType else { return } if !view.didSetup { // view.backgroundColor = UIColor.red view.textView?.textRenderingTextColor = UIColor.secondaryLabel view.textView?.textRenderingFont = UIFont.preferredFont(forTextStyle: .caption1) view.bottomPaddingConstraint?.constant = defaultPaddingBottom view.leadingPaddingConstraint?.constant = defaultPaddingSides view.trailingPaddingConstraint?.constant = defaultPaddingSides } } }
mit
97880c56583c084a7def7e4f1cce0edb
27.822581
98
0.73643
4.042986
false
false
false
false
WaterReporter/WaterReporter-iOS
WaterReporter/WaterReporter/ForgotPasswordTableViewController.swift
1
8923
// // ForgotPasswordTableViewController.swift // Water-Reporter // // Created by Viable Industries on 9/22/16. // Copyright © 2016 Viable Industries, L.L.C. All rights reserved. // import Alamofire import Foundation import UIKit class ForgotPasswordTableViewController: UITableViewController { @IBOutlet weak var textfieldEmailAddress: UITextField! @IBOutlet weak var buttonResetPassword: UIButton! @IBOutlet weak var indicatorResetPassword: UIActivityIndicatorView! override func viewDidLoad() { super.viewDidLoad() // // Make sure we are getting 'auto layout' specific sizes // otherwise any math we do will be messed up // self.view.setNeedsLayout() self.view.layoutIfNeeded() // // Set all table row separators to appear transparent // self.tableView.separatorColor = UIColor(white: 1.0, alpha: 0.0) // // // let cancelButton = UIBarButtonItem(title: "Cancel", style: UIBarButtonItemStyle.Plain, target: self, action:#selector(goBack)) navigationItem.leftBarButtonItem = cancelButton // // Alter the appearence of the Log In button // buttonResetPassword.layer.borderWidth = 1.0 buttonResetPassword.layer.borderColor = CGColor.colorBrand() buttonResetPassword.layer.cornerRadius = 4.0 // // Set all table row separators to appear transparent // self.tableView.separatorColor = UIColor(white: 1.0, alpha: 0.0) // // Alter the appearence of the Log In button // self.buttonResetPassword.layer.borderWidth = 1.0 self.buttonResetPassword.setTitleColor(UIColor.colorBrand(0.35), forState: .Normal) self.buttonResetPassword.setTitleColor(UIColor.colorBrand(), forState: .Highlighted) self.buttonResetPassword.layer.borderColor = CGColor.colorBrand(0.35) self.buttonResetPassword.layer.cornerRadius = 4.0 buttonResetPassword.addTarget(self, action: #selector(buttonClickLogin(_:)), forControlEvents: .TouchUpInside) // // Watch the Email Address and Password field's for changes. // We will be enabling and disabling the "Login Button" based // on whether or not the fields contain content. // textfieldEmailAddress.addTarget(self, action: #selector(LoginTableViewController.textFieldDidChange(_:)), forControlEvents: UIControlEvents.EditingChanged) // // // if let _email_address = NSUserDefaults.standardUserDefaults().objectForKey("currentUserAccountEmailAddress") { self.textfieldEmailAddress.text = _email_address as? String self.isReady() self.enableLoginButton() } else { // // Hide the "Log in attempt" indicator by default, we do not // need this indicator until a user interacts with the login // button // self.isReady() } } // // Basic Login Button Feedback States // func isReady() { buttonResetPassword.hidden = false buttonResetPassword.enabled = false indicatorResetPassword.hidden = true } func isLoading() { buttonResetPassword.hidden = true indicatorResetPassword.hidden = false indicatorResetPassword.startAnimating() } func isFinishedLoadingWithError() { buttonResetPassword.hidden = false indicatorResetPassword.hidden = true indicatorResetPassword.stopAnimating() } func enableLoginButton() { buttonResetPassword.enabled = true buttonResetPassword.setTitleColor(UIColor.colorBrand(), forState: .Normal) } func disableLoginButton() { buttonResetPassword.enabled = false buttonResetPassword.setTitleColor(UIColor.colorBrand(0.35), forState: .Normal) } func displayErrorMessage(title: String, message: String) { let alertController = UIAlertController(title: title, message:message, preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(alertController, animated: true, completion: nil) } // // // func textFieldDidChange(textField: UITextField) { // // - IF a textfield is not an empty string, enable the login button // - ELSE disable the button so that a user cannot tap it to submit an invalid request // if (self.textfieldEmailAddress.text == "") { self.disableLoginButton() } else { self.enableLoginButton() } } // // // func buttonClickLogin(sender:UIButton) { // // Hide the log in button so that the user cannot tap // it more than once. If they did tap it more than once // this would cause multiple requests to be sent to the // server and then multiple responses back to the app // which could cause the wrong `access_token` to be saved // to the user's Locksmith keychain. // self.isLoading() // // Send the email address and password along to the Authentication endpoint // for verification and processing // self.attemptPasswordReset(self.textfieldEmailAddress.text!) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. NSLog("LoginViewController::didReceiveMemoryWarning") } // // MARK: - Custom methods and functions // func goBack(){ dismissViewControllerAnimated(true, completion: nil) } func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true } func attemptPasswordReset(email: String) { // // Send a request to the defined endpoint with the given parameters // let parameters = [ "email": email ] Alamofire.request(.POST, Endpoints.POST_PASSWORD_RESET, parameters: parameters, encoding: .JSON) .responseJSON { response in switch response.result { case .Success(let value): print(value) if let responseCode = value["code"] { if responseCode != nil { print("!= nil") self.isFinishedLoadingWithError() self.displayErrorMessage("An Error Occurred", message:"Please check the email address you entered and try again.") } else { print("nil") // self.displayErrorMessage("We sent you an email", message:"We have sent an email to " + self.textfieldEmailAddress.text! + " with further instructions to help you reset your password.") // self.dismissViewControllerAnimated(true, completion: nil) let alertController = UIAlertController(title: "We sent you an email", message:"We‘ve sent an email to " + self.textfieldEmailAddress.text! + " with further instructions to help you reset your password.", preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default) { UIAlertAction in self.dismissViewControllerAnimated(true, completion: { self.dismissViewControllerAnimated(true, completion: nil) }) }) self.presentViewController(alertController, animated: true, completion: nil) self.isReady() } } case .Failure(let error): print(error) self.isFinishedLoadingWithError() self.displayErrorMessage("An Error Occurred", message:"Please check the email address and password you entered and try again.") break } } } }
agpl-3.0
6b6efe0a0e530e6f616da7cf204b323f
35.557377
278
0.577578
5.876153
false
false
false
false
itlijunjie/JJDemo
SwiftDemo/MyPlayground.playground/Contents.swift
1
4975
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" var myVarible = 42 myVarible = 50 let myConstent = 42 let implicitInteger = 70 let implicitDouble = 70.0 let explicitDouble : Double = 70 let explicitFloat : Float = 10 let label = "The width is " let width = 94 let widthLabel = label + String(width) let apples = 3 let oranges = 5 let appleSummray = "I have \(apples)" let fruitSummary = "I have \(apples + oranges) pieces of fruit." var shoppingList = ["catfish", "water", "tulips", "bule paint"] shoppingList[1] = "bottole of water" var occupations = [ "Malcolm" : "Captain", "Kaylee" : "Mechanic" ] occupations["Jayne"] = "Public Relations" let emptyArray = [String]() let emptyDictionary = Dictionary<String, Float>() shoppingList = [] let individualScores = [75, 43 , 103, 87, 12] var teamScore = 0 for score in individualScores { if score > 50 { teamScore += 3 } else { teamScore += 1 } } teamScore var optionalString: String? = "Hello" optionalString == nil var optionalName: String? = "John Appleseed" var greeting = "Hello" if let name = optionalName { greeting = "Hello, \(name)" } protocol ExampleProtocol { var simpleDescription: String { get } mutating func adjust() } class SimpleClass: ExampleProtocol { var simpleDescription: String = "A very simple class." var anotherProperty: Int = 69105 func adjust() { simpleDescription += " Now 100% adjusted." } } var a = SimpleClass() a.adjust() let aDescription = a.simpleDescription struct SimpleStructure: ExampleProtocol { var simpleDescription: String = "A simple Structure" mutating func adjust() { simpleDescription += " (adjusted)" } } var b = SimpleStructure() b.adjust() let bDescription = b.simpleDescription extension Int: ExampleProtocol { var simpleDescription: String { return "The number \(self)" } mutating func adjust() { self += 42 } } 7.simpleDescription let protocolValue: ExampleProtocol = a protocolValue.simpleDescription func anyCommonElements <T, U where T: SequenceType,U: SequenceType,T.Generator.Element: Equatable,T.Generator.Element == U.Generator.Element> (lhs: T, rhs: U) -> Bool { for lhsItem in lhs { for rhsItem in rhs { if lhsItem == rhsItem { return true } } } return false } anyCommonElements([1,2,3], rhs: [3]) let languageName = "Swift" //languageName = "Swift ++" print(languageName) let minValue = UInt8.min let maxValue = UInt8.max let decimalInteger = 17 let binaryInteger = 0b10001 let twoThousand: UInt16 = 2_000 let one: UInt8 = 1 let twoThousandAndOne = twoThousand + UInt16(one) typealias AudioSample = UInt16 //var aaaa = AudioSample.min let http404Error = (404,"NotFound") let (statusCode, statusMessage) = http404Error print("The status code is \(statusCode)") print("The status message is \(statusMessage)") let http200Status = (statusCode: 200, description:"NotFound") print("The status code is \(http200Status.statusCode)") print("The status Message is \(http200Status.description)") let possibleNumber = "123" let convertedNumber = Int(possibleNumber) if (convertedNumber != nil) { print(convertedNumber) } else { print(convertedNumber) } if let con = convertedNumber { con } var serverResponceCode: Int? = 404 serverResponceCode = nil var surveyAnswer: String? let possibleString: String? = "An optional string." print(possibleString!) let assumedString: String! = "An implicitly unwrapped optional string." print(assumedString) let age = -3 //assert(age >= 0, "a") // //let (x, y) = (1, 2) // //println(x) // //println(y) // //let str111: String = "aa" + "bb" // //str111 // //let aNum = 3 // //let bNum = 2 // //aNum % bNum // //for index in 1...5 { // println(index) //} // //let names = ["a", "b", "c", "d"] //let count = names.count //for i in 0...count { // println(i) //} for character in "aaaaaaa".characters { print(character) } let aaaaa = "aaaaa" print(aaaaa.characters.count) let dogg = "Dog!🐶" for codeUnit in dogg.utf8 { print("\(codeUnit)", terminator: "") } for codeUnit in dogg.utf16 { print("\(codeUnit)", terminator: "") } for codeUnit in dogg.unicodeScalars { print("\(codeUnit)", terminator: "") } var airports: Dictionary <String, String> = ["TYO": "Tokyo", "DUB": "Dublin"] airports.count airports["LHR"] = "London" if let oldValue = airports.updateValue("Dublin Internation", forKey:"DUB") { print("The old value for DUB was \(oldValue).") } if let airportName = airports["DUB"] { print("The name of the airport is \(airportName).") } else { print("That airport is not in the airports dictionary.") } //var namesOfIntegers = Dictionary<Int, String>() let arraya = [1,2,3] arraya[0] = 2
gpl-2.0
aa1872a31c92baa27b1027600fa2baca
14.251534
168
0.654465
3.452778
false
false
false
false
codeliling/DesignResearch
DesignBase/DesignBase/views/TipsView.swift
1
931
// // TipsView.swift // DesignBase // // Created by lotusprize on 15/5/29. // Copyright (c) 2015年 geekTeam. All rights reserved. // import Foundation class TipsView: UIView { convenience init(){ self.init(frame:CGRectZero) self.layer.contents = UIImage(named: "nothing")?.CGImage } override init(frame: CGRect) { super.init(frame: frame) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func drawRect(rect: CGRect) { } func showNothingTips(){ self.hidden = false UIView.animateWithDuration(2.5, animations: { () -> Void in var alpha:CGFloat = self.alpha alpha -= 1.0 self.alpha = alpha }) { (Bool) -> Void in self.hidden = true self.alpha = 1.0 } } }
apache-2.0
81045f9ffeaea704f69e12b53ac6e358
20.627907
67
0.544672
4.20362
false
false
false
false
Harrison1/several-levels-ios-wp-app
several levels/WebViewController.swift
1
4115
// // WebViewController.swift // several levels // // Created by Harrison McGuire on 6/13/16. // Copyright © 2016 severallevels. All rights reserved. // import UIKit import SwiftyJSON class WebViewController: UIViewController, UIWebViewDelegate { @IBOutlet weak var webView: UIWebView! var viewPost : JSON = JSON.null @IBOutlet var myProgressView: UIProgressView! var theBool: Bool = false var myTimer: NSTimer! override func viewDidLoad() { super.viewDidLoad() // set user agent NSUserDefaults.standardUserDefaults().registerDefaults(["UserAgent": "several-levels"]) navigationController?.navigationBarHidden = false navigationController?.toolbarHidden = false navigationController?.hidesBarsOnSwipe = true loadPage() } func loadPage() { if let postLink = self.viewPost["link"].string { // convert url stirng to NSURL object let requestURL = NSURL(string: postLink) // create request from NSURL let request = NSURLRequest(URL: requestURL!) webView.delegate = self // load the post webView.loadRequest(request) // set title of navbar to title of wordpress post if let title = self.viewPost["title"]["rendered"].string { self.title = title } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func webViewDidStartLoad(webView: UIWebView) { startProgressBar() } func webViewDidFinishLoad(webView: UIWebView) { endProgresBar() } @IBAction func refresh(sender: UIBarButtonItem) { myProgressView.hidden = false loadPage() } func startProgressBar() { self.myProgressView.progress = 0.0 self.theBool = false self.myTimer = NSTimer.scheduledTimerWithTimeInterval(0.3, target: self, selector: #selector(WebViewController.timerCallback), userInfo: nil, repeats: true) } func endProgresBar() { self.theBool = true } func timerCallback() { if self.theBool { if self.myProgressView.progress >= 1 { self.myProgressView.hidden = true self.myTimer.invalidate() } else { self.myProgressView.progress += 0.1 } } else { self.myProgressView.progress += 0.05 if self.myProgressView.progress >= 0.75 { self.myProgressView.progress = 0.75 } } } func displayShareSheet(shareContent:NSURL) { let activityViewController = UIActivityViewController(activityItems: [shareContent as NSURL], applicationActivities: nil) presentViewController(activityViewController, animated: true, completion: {}) } func displayAlert(title: String, message: String) { let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert) alertController.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) presentViewController(alertController, animated: true, completion: nil) return } @IBAction func shareButton(sender: UIButton) { if let shareUrl = NSURL(string: self.viewPost["link"].string!) { displayShareSheet(shareUrl) } else { displayAlert("Oops", message: "something went wrong, you might have to try again") } } /* // 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
875a98ceb743f57d6604436767897055
30.646154
164
0.613029
5.267606
false
false
false
false
jeremy-pereira/EnigmaMachine
EnigmaMachine/AppDelegate.swift
1
2866
// // AppDelegate.swift // EnigmaMachine // // Created by Jeremy Pereira on 24/02/2015. // Copyright (c) 2015 Jeremy Pereira. 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 Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { @IBOutlet weak var window: NSWindow! @IBOutlet weak var showPrinterItem: NSMenuItem! var abstractEnigmas: [AbstractEnigmaController] = [] func applicationDidFinishLaunching(aNotification: NSNotification) { NotificationCenter.default.addObserver(self, selector: #selector(AppDelegate.aWindowBecameMain(_:)), name: NSWindow.didBecomeMainNotification, object: nil) } func applicationWillTerminate(aNotification: NSNotification) { // Insert code here to tear down your application } @IBAction func showAbstractEnigma(_ sender: AnyObject) { let controller = AbstractEnigmaController() abstractEnigmas.append(controller) controller.showWindow(sender) // TODO: A mechanism to get rid of the controller when we are done } var currentEnigma: AbstractEnigmaController? { didSet(oldValue) { if let newValue = currentEnigma { setShowPrinterTitle(printerIsVisible: newValue.printerIsVisible) } } } @objc func aWindowBecameMain(_ theNotification: NSNotification) { if let window: NSWindow = theNotification.object as? NSWindow { if let enigmaController = findEnigmaControllerForWindow(aWindow: window) { currentEnigma = enigmaController } } } func setShowPrinterTitle(printerIsVisible: Bool) { // TODO: Localisation needed if printerIsVisible { showPrinterItem.title = "Hide Printer" } else { showPrinterItem.title = "Show Printer" } } func findEnigmaControllerForWindow(aWindow: NSWindow) -> AbstractEnigmaController? { for controller in abstractEnigmas { if controller.window === aWindow { return controller } } return nil; } }
apache-2.0
da3e092832e6d591d774978896ffa533
26.825243
98
0.632938
4.915952
false
false
false
false
mojio/mojio-ios-sdk
sdkv2.0.0/Pods/ObjectMapper/ObjectMapper/Core/FromJSON.swift
11
6220
// // FromJSON.swift // ObjectMapper // // Created by Tristan Himmelman on 2014-10-09. // // The MIT License (MIT) // // Copyright (c) 2014-2015 Hearst // // 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. internal final class FromJSON { /// Basic type class func basicType<FieldType>(inout field: FieldType, object: FieldType?) { if let value = object { field = value } } /// optional basic type class func optionalBasicType<FieldType>(inout field: FieldType?, object: FieldType?) { field = object } /// Implicitly unwrapped optional basic type class func optionalBasicType<FieldType>(inout field: FieldType!, object: FieldType?) { field = object } /// Mappable object class func object<N: Mappable>(inout field: N, map: Map) { if map.toObject { Mapper().map(map.currentValue, toObject: field) } else if let value: N = Mapper().map(map.currentValue) { field = value } } /// Optional Mappable Object class func optionalObject<N: Mappable>(inout field: N?, map: Map) { if let field = field where map.toObject && map.currentValue != nil { Mapper().map(map.currentValue, toObject: field) } else { field = Mapper().map(map.currentValue) } } /// Implicitly unwrapped Optional Mappable Object class func optionalObject<N: Mappable>(inout field: N!, map: Map) { if let field = field where map.toObject && map.currentValue != nil { Mapper().map(map.currentValue, toObject: field) } else { field = Mapper().map(map.currentValue) } } /// mappable object array class func objectArray<N: Mappable>(inout field: Array<N>, map: Map) { if let objects = Mapper<N>().mapArray(map.currentValue) { field = objects } } /// optional mappable object array class func optionalObjectArray<N: Mappable>(inout field: Array<N>?, map: Map) { if let objects: Array<N> = Mapper().mapArray(map.currentValue) { field = objects } else { field = nil } } /// Implicitly unwrapped optional mappable object array class func optionalObjectArray<N: Mappable>(inout field: Array<N>!, map: Map) { if let objects: Array<N> = Mapper().mapArray(map.currentValue) { field = objects } else { field = nil } } /// mappable object array class func twoDimensionalObjectArray<N: Mappable>(inout field: Array<Array<N>>, map: Map) { if let objects = Mapper<N>().mapArrayOfArrays(map.currentValue) { field = objects } } /// optional mappable 2 dimentional object array class func optionalTwoDimensionalObjectArray<N: Mappable>(inout field: Array<Array<N>>?, map: Map) { field = Mapper().mapArrayOfArrays(map.currentValue) } /// Implicitly unwrapped optional 2 dimentional mappable object array class func optionalTwoDimensionalObjectArray<N: Mappable>(inout field: Array<Array<N>>!, map: Map) { field = Mapper().mapArrayOfArrays(map.currentValue) } /// Dctionary containing Mappable objects class func objectDictionary<N: Mappable>(inout field: Dictionary<String, N>, map: Map) { if map.toObject { Mapper<N>().mapDictionary(map.currentValue, toDictionary: field) } else { if let objects = Mapper<N>().mapDictionary(map.currentValue) { field = objects } } } /// Optional dictionary containing Mappable objects class func optionalObjectDictionary<N: Mappable>(inout field: Dictionary<String, N>?, map: Map) { if let field = field where map.toObject && map.currentValue != nil { Mapper().mapDictionary(map.currentValue, toDictionary: field) } else { field = Mapper().mapDictionary(map.currentValue) } } /// Implicitly unwrapped Dictionary containing Mappable objects class func optionalObjectDictionary<N: Mappable>(inout field: Dictionary<String, N>!, map: Map) { if let field = field where map.toObject && map.currentValue != nil { Mapper().mapDictionary(map.currentValue, toDictionary: field) } else { field = Mapper().mapDictionary(map.currentValue) } } /// Dictionary containing Array of Mappable objects class func objectDictionaryOfArrays<N: Mappable>(inout field: Dictionary<String, [N]>, map: Map) { if let objects = Mapper<N>().mapDictionaryOfArrays(map.currentValue) { field = objects } } /// Optional Dictionary containing Array of Mappable objects class func optionalObjectDictionaryOfArrays<N: Mappable>(inout field: Dictionary<String, [N]>?, map: Map) { field = Mapper<N>().mapDictionaryOfArrays(map.currentValue) } /// Implicitly unwrapped Dictionary containing Array of Mappable objects class func optionalObjectDictionaryOfArrays<N: Mappable>(inout field: Dictionary<String, [N]>!, map: Map) { field = Mapper<N>().mapDictionaryOfArrays(map.currentValue) } /// mappable object Set class func objectSet<N: Mappable>(inout field: Set<N>, map: Map) { if let objects = Mapper<N>().mapSet(map.currentValue) { field = objects } } /// optional mappable object array class func optionalObjectSet<N: Mappable>(inout field: Set<N>?, map: Map) { field = Mapper().mapSet(map.currentValue) } /// Implicitly unwrapped optional mappable object array class func optionalObjectSet<N: Mappable>(inout field: Set<N>!, map: Map) { field = Mapper().mapSet(map.currentValue) } }
mit
9a70d318fdf96e02fa844ebd83bc96f1
33.555556
108
0.713987
3.785758
false
false
false
false
CreatorWilliam/WMNetImageKit
WMNetImageKit/NetImge/WMImageManager.swift
1
6801
// // WMImageManager.swift // WMSDK // // Created by William on 20/12/2016. // Copyright © 2016 William. All rights reserved. // import UIKit public class WMImageManager: NSObject { public typealias ProgressingAction = (_ received : Int64 ,_ total : Int64, _ partialImage: UIImage) -> Void public typealias CompleteAction = (_ image: UIImage) -> Void private static let `default` = WMImageManager() private let imageQueue : OperationQueue = OperationQueue() override init() { super.init() self.imageQueue.maxConcurrentOperationCount = 3 } /// 显示图片 /// /// - Parameters: /// - url: 图片地址 /// - target: 设置图片的视图 /// - progress: 监听进度 /// - complete: 监听完成 public class func showImage(from url: URL, for target: UIView, mode: UIImage.WMDrawMode = .default, progress: ProgressingAction?, complete: @escaping CompleteAction) { let size = target.bounds.size //从内存获取 let drawedImage: UIImage? = WMImageStore.fromMemory(with: url) if let drawedImage = drawedImage, Int(drawedImage.size.width) >= Int(size.width), Int(drawedImage.size.height) >= Int(size.height) { DispatchQueue.main.async { complete(drawedImage) } return } //从磁盘获取 if let drawedImage = WMImageStore.fromDisk(with: url)?.wm_draw(size, mode: mode) { WMImageStore.toMemory(for: drawedImage, with: url) DispatchQueue.main.async { complete(drawedImage) } return } //从网络获取 WMImageDownloader.fromInternet(url, progress: { (recieved, total, partialData) in guard let imageData = partialData, let drawedImage = UIImage(data: imageData)?.wm_draw(size, mode: mode) else { return } DispatchQueue.main.async { progress?(recieved, total, drawedImage) } }, complete: { (imageData) in guard let image = UIImage(data: imageData) else { return } WMImageStore.toDisk(for: imageData, with: url) guard let drawedImage = image.wm_draw(size, mode: mode) else { return } WMImageStore.toMemory(for: drawedImage, with: url) DispatchQueue.main.async { complete(drawedImage) } }) } /// 隐藏图片,同时也会停止相应的图片下载任务 /// /// - Parameters: /// - url: 图片地址 /// - target: 隐藏图片的视图 public class func hideImage(url: URL, target: UIView) { DispatchQueue.global().async { WMImageDownloader.pause(url) } } /// 获取磁盘缓存的图片总大小 /// /// - Returns: 缓存的图片大小,单位B public class func sizeOfDiskCache() -> Int64 { return WMImageStore.chacheSize() } /// 清除磁盘缓存 public class func clearDiskCache() { WMImageStore.clearDiskCache() } /// 将通过ImagePicker获得的图片储存到本地 /// /// - Parameters: /// - image: 图片 /// - name: 图片名 /// - Returns: 缓存图片所在地址 public class func storeImage(_ image: UIImage, with name: String) -> URL? { let path = WMImageStore.imagePath(with: name) let url = URL(fileURLWithPath: path) guard let imageData = UIImageJPEGRepresentation(image, 1) else { return nil } WMImageStore.toDisk(for: imageData, with: url, isReplace: true) return url } public class func storeImage(_ url: URL, complete: @escaping CompleteAction) { //从磁盘获取 if let image = WMImageStore.fromDisk(with: url) { complete(image) return } //从网络获取 WMImageDownloader.fromInternet(url, progress: { (recieved, total, partialData) in }, complete: { (imageData) in guard let image = UIImage(data: imageData) else { return } WMImageStore.toDisk(for: imageData, with: url) complete(image) }) } } public extension UIImage { /// 裁剪模式不会造成图片比例失真,配合wm_draw函数使用 /// /// - default: 按原图宽高比进行缩放,图片宽度等于给定(默认)宽度,图片高度可能不等于(大于或小于)给定(默认)高度 /// - fill: 按原图宽高比进行缩放,填充给定(默认)大小,保证图片宽度等于给定(默认)的宽度,图片高度不小于给定(默认)的高度,或者图片高度等于给定(默认)的高度,图片宽度不小于给定(默认)的宽度 /// - fit: 按原图宽高比进行缩放,适应给定(默认)大小,保证图片宽度等于给定(默认)的宽度,图片高度不大于给定(默认)的高度,或者图片高度等于给定(默认)的高度,图片宽度不大于给定(默认)的宽度 enum WMDrawMode { case `default` case fill case fit } func wm_draw(_ size: CGSize = UIScreen.main.bounds.size, mode: WMDrawMode = .default) -> UIImage? { var drawedSize = size let imageSize = self.size if drawedSize.equalTo(CGSize.zero) { drawedSize = UIScreen.main.bounds.size } var scale: CGFloat switch mode { case .fill: let imageScale = imageSize.width / imageSize.height let drawedScale = drawedSize.width / drawedSize.height scale = imageScale > drawedScale ? drawedSize.height / imageSize.height : drawedSize.width / imageSize.width case .fit: let imageScale = imageSize.width / imageSize.height let tailoredScale = drawedSize.width / drawedSize.height scale = imageScale > tailoredScale ? drawedSize.width / imageSize.width : drawedSize.height / imageSize.height default: scale = drawedSize.width / imageSize.width break } drawedSize = CGSize(width: Int(imageSize.width * scale), height: Int(imageSize.height * scale)) let tailoredRect = CGRect(origin: CGPoint.zero, size: drawedSize) UIGraphicsBeginImageContextWithOptions(drawedSize, true, 0) self.draw(in: tailoredRect) let tailoredImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return tailoredImage } }
apache-2.0
a03e34505c3ac81a07ea2214148fa21c
20.761733
128
0.583444
4.084011
false
false
false
false
gregomni/swift
test/ClangImporter/experimental_diagnostics_cmacros.swift
2
7440
// RUN: not %target-swift-frontend(mock-sdk: %clang-importer-sdk) -typecheck %s 2>&1 | %FileCheck %s --strict-whitespace import macros _ = INVALID_INTEGER_LITERAL_2 // CHECK: experimental_diagnostics_cmacros.swift:{{[0-9]+}}:{{[0-9]+}}: error: cannot find 'INVALID_INTEGER_LITERAL_2' in scope // CHECK-NEXT: _ = INVALID_INTEGER_LITERAL_2 // CHECK-NEXT: ^~~~~~~~~~~~~~~~~~~~~~~~~ // CHECK-NEXT: macros.h:{{[0-9]+}}:9: note: macro 'INVALID_INTEGER_LITERAL_2' not imported // CHECK-NEXT: #define INVALID_INTEGER_LITERAL_2 10abc // CHECK-NEXT: {{^}} ^ // CHECK-NEXT: macros.h:{{[0-9]+}}:35: note: invalid numeric literal // CHECK-NEXT: #define INVALID_INTEGER_LITERAL_2 10abc // CHECK-NEXT: {{^}} ^ _ = FUNC_LIKE_MACRO() // CHECK: experimental_diagnostics_cmacros.swift:{{[0-9]+}}:{{[0-9]+}}: error: cannot find 'FUNC_LIKE_MACRO' in scope // CHECK-NEXT: _ = FUNC_LIKE_MACRO() // CHECK-NEXT: ^~~~~~~~~~~~~~~ // CHECK-NEXT: macros.h:{{[0-9]+}}:9: note: macro 'FUNC_LIKE_MACRO' not imported: function like macros not supported // CHECK-NEXT: #define FUNC_LIKE_MACRO() 0 // CHECK-NEXT: {{^}} ^ _ = FUNC_LIKE_MACRO() // CHECK: experimental_diagnostics_cmacros.swift:{{[0-9]+}}:{{[0-9]+}}: error: cannot find 'FUNC_LIKE_MACRO' in scope // CHECK-NEXT: _ = FUNC_LIKE_MACRO() // CHECK-NEXT: ^~~~~~~~~~~~~~~ // CHECK-NEXT: macros.h:{{[0-9]+}}:9: note: macro 'FUNC_LIKE_MACRO' not imported: function like macros not supported // CHECK-NEXT: #define FUNC_LIKE_MACRO() 0 // CHECK-NEXT: {{^}} ^ _ = INVALID_ARITHMETIC_1 // CHECK: experimental_diagnostics_cmacros.swift:{{[0-9]+}}:{{[0-9]+}}: error: cannot find 'INVALID_ARITHMETIC_1' in scope // CHECK-NEXT: _ = INVALID_ARITHMETIC_1 // CHECK-NEXT: ^~~~~~~~~~~~~~~~~~~~ // CHECK-NEXT: macros.h:{{[0-9]+}}:9: note: macro 'INVALID_ARITHMETIC_1' not imported: structure not supported // CHECK-NEXT: #define INVALID_ARITHMETIC_1 5 + INVALID_INTERGER_LITERAL_1 // CHECK-NEXT: {{^}} ^ _ = INVALID_ARITHMETIC_2 // CHECK: experimental_diagnostics_cmacros.swift:{{[0-9]+}}:{{[0-9]+}}: error: cannot find 'INVALID_ARITHMETIC_2' in scope // CHECK-NEXT: _ = INVALID_ARITHMETIC_2 // CHECK-NEXT: ^~~~~~~~~~~~~~~~~~~~ // CHECK-NEXT: macros.h:{{[0-9]+}}:9: note: macro 'INVALID_ARITHMETIC_2' not imported: structure not supported // CHECK-NEXT: #define INVALID_ARITHMETIC_2 INVALID_INTEGER_LITERAL_1 + ADD_TWO // CHECK-NEXT: {{^}} ^ _ = INVALID_ARITHMETIC_3 // CHECK: experimental_diagnostics_cmacros.swift:{{[0-9]+}}:{{[0-9]+}}: error: cannot find 'INVALID_ARITHMETIC_3' in scope // CHECK-NEXT: _ = INVALID_ARITHMETIC_3 // CHECK-NEXT: ^~~~~~~~~~~~~~~~~~~~ // CHECK-NEXT: macros.h:{{[0-9]+}}:9: note: macro 'INVALID_ARITHMETIC_3' not imported: structure not supported // CHECK-NEXT: #define INVALID_ARITHMETIC_3 ADD_TWO + INVALID_INTEGER_LITERAL_1 // CHECK-NEXT: {{^}} ^ _ = INVALID_ARITHMETIC_4 // CHECK: experimental_diagnostics_cmacros.swift:{{[0-9]+}}:{{[0-9]+}}: error: cannot find 'INVALID_ARITHMETIC_4' in scope // CHECK-NEXT: _ = INVALID_ARITHMETIC_4 // CHECK-NEXT: ^~~~~~~~~~~~~~~~~~~~ // CHECK-NEXT: macros.h:{{[0-9]+}}:9: note: macro 'INVALID_ARITHMETIC_4' not imported: structure not supported // CHECK-NEXT: #define INVALID_ARITHMETIC_4 \ // CHECK-NEXT: {{^}} ^ _ = INVALID_ARITHMETIC_5 // CHECK: experimental_diagnostics_cmacros.swift:{{[0-9]+}}:{{[0-9]+}}: error: cannot find 'INVALID_ARITHMETIC_5' in scope // CHECK-NEXT: _ = INVALID_ARITHMETIC_5 // CHECK-NEXT: ^~~~~~~~~~~~~~~~~~~~ // CHECK-NEXT: macros.h:{{[0-9]+}}:9: note: macro 'INVALID_ARITHMETIC_5' not imported: structure not supported // CHECK-NEXT: #define INVALID_ARITHMETIC_5 1 + VERSION_STRING // CHECK-NEXT: {{^}} ^ _ = INVALID_ARITHMETIC_6 // CHECK: experimental_diagnostics_cmacros.swift:{{[0-9]+}}:{{[0-9]+}}: error: cannot find 'INVALID_ARITHMETIC_6' in scope // CHECK-NEXT: _ = INVALID_ARITHMETIC_6 // CHECK-NEXT: ^~~~~~~~~~~~~~~~~~~~ // CHECK-NEXT: macros.h:{{[0-9]+}}:9: note: macro 'INVALID_ARITHMETIC_6' not imported: structure not supported // CHECK-NEXT: #define INVALID_ARITHMETIC_6 1 + 'c' // CHECK-NEXT: {{^}} ^ _ = INVALID_ARITHMETIC_7 // CHECK: experimental_diagnostics_cmacros.swift:{{[0-9]+}}:{{[0-9]+}}: error: cannot find 'INVALID_ARITHMETIC_7' in scope // CHECK-NEXT: _ = INVALID_ARITHMETIC_7 // CHECK-NEXT: ^~~~~~~~~~~~~~~~~~~~ // CHECK-NEXT: macros.h:{{[0-9]+}}:9: note: macro 'INVALID_ARITHMETIC_7' not imported // CHECK-NEXT: #define INVALID_ARITHMETIC_7 3 % 2 // CHECK-NEXT: {{^}} ^ // CHECK-NEXT: macros.h:{{[0-9]+}}:32: note: operator '%' not supported in macro arithmetic // CHECK-NEXT: #define INVALID_ARITHMETIC_7 3 % 2 // CHECK-NEXT: {{^}} ^ _ = CHAR_LITERAL // CHECK: experimental_diagnostics_cmacros.swift:{{[0-9]+}}:{{[0-9]+}}: error: cannot find 'CHAR_LITERAL' in scope // CHECK-NEXT: _ = CHAR_LITERAL // CHECK-NEXT: ^~~~~~~~~~~~ // CHECK-NEXT: macros.h:{{[0-9]+}}:9: note: macro 'CHAR_LITERAL' not imported // CHECK-NEXT: #define CHAR_LITERAL 'a' // CHECK-NEXT: {{^}} ^ // CHECK-NEXT: macros.h:{{[0-9]+}}:22: note: only numeric and string macro literals supported // CHECK-NEXT: #define CHAR_LITERAL 'a' // CHECK-NEXT: {{^}} ^ UNSUPPORTED_1 // CHECK: experimental_diagnostics_cmacros.swift:{{[0-9]+}}:{{[0-9]+}}: error: cannot find 'UNSUPPORTED_1' in scope // CHECK-NEXT: UNSUPPORTED_1 // CHECK-NEXT: ^~~~~~~~~~~~~ // CHECK-NEXT: macros.h:{{[0-9]+}}:9: note: macro 'UNSUPPORTED_1' not imported: structure not supported // CHECK-NEXT: #define UNSUPPORTED_1 FUNC_LIKE_MACRO() // CHECK-NEXT: {{^}} ^ UNSUPPORTED_2 // CHECK: experimental_diagnostics_cmacros.swift:{{[0-9]+}}:{{[0-9]+}}: error: cannot find 'UNSUPPORTED_2' in scope // CHECK-NEXT: UNSUPPORTED_2 // CHECK-NEXT: ^~~~~~~~~~~~~ // CHECK-NEXT: macros.h:{{[0-9]+}}:9: note: macro 'UNSUPPORTED_2' not imported: structure not supported // CHECK-NEXT: #define UNSUPPORTED_2 FUNC_LIKE_MACRO_2(1) // CHECK-NEXT: {{^}} ^ UNSUPPORTED_3 // CHECK: experimental_diagnostics_cmacros.swift:{{[0-9]+}}:{{[0-9]+}}: error: cannot find 'UNSUPPORTED_3' in scope // CHECK-NEXT: UNSUPPORTED_3 // CHECK-NEXT: ^~~~~~~~~~~~~ // CHECK-NEXT: macros.h:{{[0-9]+}}:9: note: macro 'UNSUPPORTED_3' not imported: structure not supported // CHECK-NEXT: #define UNSUPPORTED_3 1 + FUNC_LIKE_MACRO_2(1) // CHECK-NEXT: {{^}} ^ UNSUPPORTED_4 // CHECK: experimental_diagnostics_cmacros.swift:{{[0-9]+}}:{{[0-9]+}}: error: cannot find 'UNSUPPORTED_4' in scope // CHECK-NEXT: UNSUPPORTED_4 // CHECK-NEXT: ^~~~~~~~~~~~~ // CHECK-NEXT: macros.h:{{[0-9]+}}:9: note: macro 'UNSUPPORTED_4' not imported: structure not supported // CHECK-NEXT: #define UNSUPPORTED_4 \ // CHECK-NEXT: {{^}} ^ UNSUPPORTED_5 // CHECK: experimental_diagnostics_cmacros.swift:{{[0-9]+}}:{{[0-9]+}}: error: cannot find 'UNSUPPORTED_5' in scope // CHECK-NEXT: UNSUPPORTED_5 // CHECK-NEXT: ^~~~~~~~~~~~~ // CHECK-NEXT: macros.h:{{[0-9]+}}:9: note: macro 'UNSUPPORTED_5' not imported: structure not supported // CHECK-NEXT: #define UNSUPPORTED_5 1 + 1 + 1 // CHECK-NEXT: {{^}} ^
apache-2.0
9988525b53983ab5b35239b27bdf7966
51.394366
132
0.594355
3.144548
false
false
false
false
mennovf/Swift-MathEagle
MathEagle/Source/Complex.swift
1
10714
// // Complex.swift // MathEagle // // Created by Rugen Heidbuchel on 05/03/15. // Copyright (c) 2015 Jorestha Solutions. All rights reserved. // import Accelerate public struct Complex: Equatable, Comparable, Addable, Negatable, Substractable, Multiplicable, Dividable, NaturalPowerable, IntegerPowerable, RealPowerable, SetCompliant, Conjugatable, MatrixCompatible, IntegerLiteralConvertible, FloatLiteralConvertible, CustomStringConvertible { public typealias NaturalPowerType = Complex public typealias IntegerPowerType = Complex public typealias RealPowerType = Complex public var real: Double public var imaginary: Double var DSPDoubleComplexValue: DSPDoubleComplex { return DSPDoubleComplex(real: real, imag: imaginary) } var DSPDoubleSplitComplexValue: DSPDoubleSplitComplex { let r = UnsafeMutablePointer<Double>.alloc(1) r[0] = real let i = UnsafeMutablePointer<Double>.alloc(1) i[0] = imaginary return DSPDoubleSplitComplex(realp: r, imagp: i) } // MARK: Initialisation public init(_ complex: Complex) { self.real = complex.real self.imaginary = complex.imaginary } public init(_ real: Double, _ imaginary: Double) { self.real = real self.imaginary = imaginary } public init(modulus: Double, argument: Double) { self.real = modulus * cos(argument) self.imaginary = modulus * sin(argument) } public init(integerLiteral value: IntegerLiteralType) { self.real = Double(value) self.imaginary = 0 } public init(floatLiteral value: FloatLiteralType) { self.real = Double(value) self.imaginary = 0 } init(_ DSPDoubleSplitComplexValue: DSPDoubleSplitComplex) { self.real = DSPDoubleSplitComplexValue.realp[0] self.imaginary = DSPDoubleSplitComplexValue.imagp[0] } public static var imaginaryUnit: Complex { return Complex(0, 1) } // MARK: Basic Properties /** Returns the modulus of the complex number. */ public var modulus: Double { return sqrt(self.real**2 + self.imaginary**2) } /** Returns the argument of the complex number. */ public var argument: Double { return (self.real == 0.0 && self.imaginary == 0.0) ? 0 : atan(self.imaginary / self.real) + (self.quadrant.rawValue >= 3 ? PI : 0) } /** Returns the conjugate of the complex number. */ public var conjugate: Complex { return Complex(self.real, -self.imaginary) } /** Returns the quadrant of the complex plane in which the complex number lies. */ public var quadrant: Quadrant { if self.real >= 0 { return self.imaginary >= 0 ? .First : .Fourth } else { return self.imaginary >= 0 ? .Second : .Third } } /** Returns a description of the complex number of the form "a ± bi" */ public var description: String { return self.imaginary < 0 ? "\(self.real) - \(-self.imaginary)i" : "\(self.real) + \(self.imaginary)i" } // MARK: Set Conformance public var isNatural: Bool { return self.real.isNatural && self.imaginary == 0.0 } public var isInteger: Bool { return self.real.isInteger && self.imaginary == 0.0 } public var isReal: Bool { return self.imaginary == 0.0 } // MARK: Fuzzy Equality /** Returns true if the real and imaginary parts are equal. */ public func equals(z: Complex) -> Bool { return self.real == z.real && self.imaginary == z.imaginary } public func equals(z: Complex, accuracy: Double) -> Bool { return self.real.equals(z.real, accuracy: accuracy) && self.imaginary.equals(z.imaginary, accuracy: accuracy) } // MARK: Randomizable Conformance /** Returns a random complex number. */ public static func random() -> Complex { return Complex(Double.random(), Double.random()) } /** Returns a random complex number in the given interval(s). When no interval is provided, random() will be used. When one interval is provided this interval will be used to restrict the real and imaginary parts. When two intervals are provided the first will be used for the real part, the second for the imaginary part. */ public static func randomInInterval(intervals: ClosedInterval<Double>...) -> Complex { return randomInInterval(intervals) } /** Returns a random complex number in the given interval(s). When no interval is provided, random() will be used. When one interval is provided this interval will be used to restrict the real and imaginary parts. When two intervals are provided the first will be used for the real part, the second for the imaginary part. */ public static func randomInInterval(intervals: [ClosedInterval<Double>]) -> Complex { if intervals.isEmpty { return self.random() } if intervals.count == 1 { return Complex(Double.randomInInterval([intervals[0]]), Double.randomInInterval([intervals[0]])) } return Complex(Double.randomInInterval([intervals[0]]), Double.randomInInterval([intervals[1]])) } /** Returns an array of random complex numbers of the given length. */ public static func randomArrayOfLength(length: Int) -> [Complex] { var array = [Complex]() for _ in 0 ..< length { array.append(self.random()) } return array } } // MARK: Function Extensions public func sqrt(z: Complex) -> Complex { return Complex(modulus: sqrt(z.modulus), argument: z.argument / 2) } public func exp(z: Complex) -> Complex { let c = exp(z.real) return Complex(c * cos(z.imaginary), c * sin(z.imaginary)) } public func log(z: Complex) -> Complex { return Complex(log(z.modulus), z.argument) } // MARK: Equatable Protocol Conformance public func == (left: Complex, right: Complex) -> Bool { return left.equals(right) } public func == (left: Double, right: Complex) -> Bool { return left == right.real && right.imaginary == 0.0 } public func == (left: Complex, right: Double) -> Bool { return right == left } // MARK: Comparable Protocol Conformance public func < (left: Complex, right: Complex) -> Bool { return left.modulus < right.modulus } public func > (left: Complex, right: Complex) -> Bool { return right < left } // MARK: Addable Protocol Conformance public func + (left: Complex, right: Complex) -> Complex { return Complex(left.real + right.real, left.imaginary + right.imaginary) } public func + (left: Double, right: Complex) -> Complex { return Complex(left + right.real, right.imaginary) } public func + (left: Complex, right: Double) -> Complex { return right + left } // MARK: Negatable Protocol Conformance public prefix func - (z: Complex) -> Complex { return Complex(-z.real, -z.imaginary) } // MARK: Substractable Protocol Conformance public func - (left: Complex, right: Complex) -> Complex { return Complex(left.real - right.real, left.imaginary - right.imaginary) } public func - (left: Double, right: Complex) -> Complex { return Complex(left - right.real, -right.imaginary) } public func - (left: Complex, right: Double) -> Complex { return Complex(left.real - right, left.imaginary) } // MARK: Multiplicable Protocol Conformance public func * (left: Complex, right: Complex) -> Complex { return Complex(left.real * right.real - left.imaginary * right.imaginary, left.real * right.imaginary + left.imaginary * right.real) } public func * (left: Double, right: Complex) -> Complex { return Complex(left * right.real, left * right.imaginary) } public func * (left: Complex, right: Double) -> Complex { return right * left } public func * (left: UInt, right: Complex) -> Complex { return Complex(Double(left) * right.real, Double(left) * right.imaginary) } public func * (left: Complex, right: UInt) -> Complex { return right * left } public func * (left: Int, right: Complex) -> Complex { return Complex(Double(left) * right.real, Double(left) * right.imaginary) } public func * (left: Complex, right: Int) -> Complex { return right * left } // MARK: Dividable Protocol Conformance public func / (left: Complex, right: Complex) -> Complex { let d = right.real**2 + right.imaginary**2 return Complex((left.real * right.real + left.imaginary * right.imaginary) / d, (left.imaginary * right.real - left.real * right.imaginary) / d) } public func / (left: Double, right: Complex) -> Complex { let d = right.real**2 + right.imaginary**2 return Complex((left * right.real) / d, (-left * right.imaginary) / d) } public func / (left: Complex, right: Double) -> Complex { return Complex(left.real / right, left.imaginary / right) } // MARK: Powers public func ** (left: Complex, right: Complex) -> Complex { return Complex(0, 0) } public func ** (left: Double, right: Complex) -> Complex { return Complex(modulus: left ** right.real, argument: log(left) * right.imaginary) } public func ** (left: Complex, right: UInt) -> Complex { return Complex(modulus: left.modulus ** right, argument: Double(right) * left.argument) } public func ** (left: Complex, right: Int) -> Complex { return Complex(modulus: left.modulus ** right, argument: Double(right) * left.argument) } public func ** (left: Complex, right: Double) -> Complex { return Complex(modulus: left.modulus ** right, argument: right * left.argument) } // MARK: Quadrant Enum public enum Quadrant: Int { case First = 1, Second, Third, Fourth } // MARK: DSPDoubleSplitComplex extension extension DSPDoubleSplitComplex { init(_ complex: Complex) { self.realp = UnsafeMutablePointer<Double>.alloc(1) self.realp[0] = complex.real self.imagp = UnsafeMutablePointer<Double>.alloc(1) self.imagp[0] = complex.imaginary } }
mit
c0dc07307bff78bc3e3cf544701c974a
23.916279
281
0.617754
4.242772
false
false
false
false
ryancrosby/ECLibrary
Example/Tests/Tests.swift
1
1181
// https://github.com/Quick/Quick import Quick import Nimble import ECLibrary class TableOfContentsSpec: QuickSpec { override func spec() { describe("these will fail") { // it("can do maths") { // expect(1) == 2 // } // // it("can read") { // expect("number") == "string" // } // // it("will eventually fail") { // expect("time").toEventually( equal("done") ) // } context("these will pass") { it("can do maths") { expect(23) == 23 } it("can read") { expect("🐮") == "🐮" } it("will eventually pass") { var time = "passing" DispatchQueue.main.async { time = "done" } waitUntil { done in Thread.sleep(forTimeInterval: 0.5) expect(time) == "done" done() } } } } } }
mit
da78c3523f03fbe70ade8b8fa6a47b31
22.5
62
0.350638
5.042918
false
false
false
false
maranathApp/GojiiFramework
GojiiFrameWork/CGPointExtensions.swift
1
4201
// // CGFloatExtensions.swift // GojiiFrameWork // // Created by Stency Mboumba on 01/06/2017. // Copyright © 2017 Stency Mboumba. All rights reserved. // import CoreGraphics import AVFoundation /* --------------------------------------------------------------------------- */ // MARK: - CGPoint → Equatable /* --------------------------------------------------------------------------- */ /** + - parameter left: CGPoint - parameter right: CGPoint - returns: CGPoint */ public func + (left: CGPoint, right: CGPoint) -> CGPoint { return CGPoint(x: left.x + right.x, y: left.y + right.y) } /** - - parameter left: CGPoint - parameter right: CGPoint - returns: CGPoint */ public func - (left: CGPoint, right: CGPoint) -> CGPoint { return CGPoint(x: left.x - right.x, y: left.y - right.y) } /** * - parameter left: CGPoint - parameter right: CGPoint - returns: CGPoint */ public func * (point: CGPoint, scalar: CGFloat) -> CGPoint { return CGPoint(x: point.x * scalar, y: point.y * scalar) } /** / - parameter left: CGPoint - parameter right: CGPoint - returns: CGPoint */ public func / (point: CGPoint, scalar: CGFloat) -> CGPoint { return CGPoint(x: point.x / scalar, y: point.y / scalar) } /* --------------------------------------------------------------------------- */ // MARK: - CGPoint → Helper /* --------------------------------------------------------------------------- */ // MARK: - Extension CGPoint BSFramework public extension CGPoint { /// Length public var length:CGFloat { get { return sqrt(self.x * self.x + self.y * self.y) } } /// Description public var normalized:CGPoint { return self / self.length } /// CGPoint to CGAffineTransform public var toCGAffineTransform:CGAffineTransform { get { return CGAffineTransform(translationX: self.x, y: self.y) } } } /* --------------------------------------------------------------------------- */ // MARK: - CGPoint → Anchor Point /* --------------------------------------------------------------------------- */ /** Enum of Position view - TopLeft: Top Left (0, 0) - TopCenter: Top Center (0.5, 0) - TopRight: Top Right (1,0) - MidLeft: Mid Left (0, 0.5) - MidCenter: Mid Center (0.5 , 0.5) - MidRight: Mid Right (1, 0.5) - BottomLeft: Bottom Left (0, 0) - BottomCenter: Bottom Center (0.5, 1) - BottomRight: Bottom Right (1, 1) */ //public enum AnchorPosition: CGPoint { // public typealias RawValue = // // // case TopLeft = "{0, 0}" // case TopCenter = "{0.5, 0}" // case TopRight = "{1, 0}" // // case MidLeft = "{0, 0.5}" // case MidCenter = "{0.5, 0.5}" // case MidRight = "{1, 0.5}" // // case BottomLeft = "{0, 1}" // case BottomCenter = "{0.5, 1}" // case BottomRight = "{1, 1}" // //} /* --------------------------------------------------------------------------- */ // MARK: - CGPoint → StringLiteralConvertible /* --------------------------------------------------------------------------- */ // MARK: - Extensions CGPoint, Anchor Point extension CGPoint { /** Create an instance initialized to value (StringLiteralConvertible) - parameter value: StringLiteralType - returns: CGPoint */ public init(stringLiteral value: StringLiteralType) { self = CGPoint.init(stringLiteral: value) } /** Create an instance initialized to value (StringLiteralConvertible) - parameter value: StringLiteralType - returns: CGPoint */ public init(extendedGraphemeClusterLiteral value: StringLiteralType) { self = CGPoint.init(stringLiteral: value) } /** Create an instance initialized to value (StringLiteralConvertible) - parameter value: StringLiteralType - returns: CGPoint */ public init(unicodeScalarLiteral value: StringLiteralType) { self = CGPoint.init(stringLiteral: value) } }
mit
7b3105d1ecd85e689726b8a964cb4694
24.876543
81
0.49666
4.366667
false
false
false
false
danielsaidi/KeyboardKit
Sources/KeyboardKit/Actions/StandardKeyboardActionHandler.swift
1
8326
// // StandardKeyboardActionHandler.swift // KeyboardKit // // Created by Daniel Saidi on 2019-04-24. // Copyright © 2021 Daniel Saidi. All rights reserved. // import UIKit /** This action handler provides standard ways of how to handle keyboard actions. You can inherit this class and override any open properties and functions to customize the standard behavior. You can provide a custom `haptic` and `audio` configuration when you create an instance of this class. The standard aim at mimicing the behavior of a native keyboard. You can also provide a custom `spaceDragSensitivity`. */ open class StandardKeyboardActionHandler: NSObject, KeyboardActionHandler { // MARK: - Initialization public init( keyboardContext: KeyboardContext, keyboardBehavior: KeyboardBehavior, autocompleteAction: @escaping () -> Void, changeKeyboardTypeAction: @escaping (KeyboardType) -> Void, hapticConfiguration: HapticFeedbackConfiguration = .standard, audioConfiguration: AudioFeedbackConfiguration = .standard, spaceDragSensitivity: SpaceDragSensitivity = .medium) { self.keyboardContext = keyboardContext self.keyboardBehavior = keyboardBehavior self.autocompleteAction = autocompleteAction self.changeKeyboardTypeAction = changeKeyboardTypeAction self.hapticConfiguration = hapticConfiguration self.audioConfiguration = audioConfiguration self.spaceDragSensitivity = spaceDragSensitivity } public init( inputViewController: KeyboardInputViewController, hapticConfiguration: HapticFeedbackConfiguration = .standard, audioConfiguration: AudioFeedbackConfiguration = .standard, spaceDragSensitivity: SpaceDragSensitivity = .medium) { self.keyboardContext = inputViewController.keyboardContext self.keyboardBehavior = inputViewController.keyboardBehavior self.autocompleteAction = inputViewController.performAutocomplete self.changeKeyboardTypeAction = inputViewController.changeKeyboardType self.hapticConfiguration = hapticConfiguration self.audioConfiguration = audioConfiguration self.spaceDragSensitivity = spaceDragSensitivity } // MARK: - Dependencies public let audioConfiguration: AudioFeedbackConfiguration public let keyboardBehavior: KeyboardBehavior public let keyboardContext: KeyboardContext public let hapticConfiguration: HapticFeedbackConfiguration public let spaceDragSensitivity: SpaceDragSensitivity public let autocompleteAction: () -> Void public let changeKeyboardTypeAction: (KeyboardType) -> Void // MARK: - Properties private var currentDragStartLocation: CGPoint? private var currentDragTextPositionOffset: Int = 0 private var keyboardInputViewController: KeyboardInputViewController { .shared } // MARK: - Types public typealias GestureAction = KeyboardAction.GestureAction // MARK: - KeyboardActionHandler public func canHandle(_ gesture: KeyboardGesture, on action: KeyboardAction, sender: Any?) -> Bool { self.action(for: gesture, on: action) != nil } /** Handle a certain `gesture` on a certain `action` */ open func handle(_ gesture: KeyboardGesture, on action: KeyboardAction, sender: Any?) { guard let gestureAction = self.action(for: gesture, on: action) else { return } gestureAction(keyboardInputViewController) triggerAudioFeedback(for: gesture, on: action, sender: sender) triggerHapticFeedback(for: gesture, on: action, sender: sender) autocompleteAction() tryEndSentence(after: gesture, on: action) tryChangeKeyboardType(after: gesture, on: action) tryRegisterEmoji(after: gesture, on: action) } /** Handle a drag gesture on a certain action, from a start location to the drag gesture's current location. */ open func handleDrag(on action: KeyboardAction, from startLocation: CGPoint, to currentLocation: CGPoint) { switch action { case .space: handleSpaceCursorDragGesture(from: startLocation, to: currentLocation) default: break } } /** This function is called from `handleDrag` and moves the text cursor according to the last handled offset. */ open func handleSpaceCursorDragGesture(from startLocation: CGPoint, to currentLocation: CGPoint) { tryStartNewSpaceCursorDragGesture(from: startLocation, to: currentLocation) let dragDelta = startLocation.x - currentLocation.x let textPositionOffset = Int(dragDelta / CGFloat(spaceDragSensitivity.points)) guard textPositionOffset != currentDragTextPositionOffset else { return } let offsetDelta = textPositionOffset - currentDragTextPositionOffset keyboardContext.textDocumentProxy.adjustTextPosition(byCharacterOffset: -offsetDelta) currentDragTextPositionOffset = textPositionOffset } // MARK: - Actions /** This is the standard action that is used by the handler when a gesture is performed on a certain action. */ open func action(for gesture: KeyboardGesture, on action: KeyboardAction) -> KeyboardAction.GestureAction? { switch gesture { case .doubleTap: return action.standardDoubleTapAction case .longPress: return action.standardLongPressAction case .press: return action.standardPressAction case .release: return action.standardReleaseAction case .repeatPress: return action.standardRepeatAction case .tap: return action.standardTapAction } } // MARK: - Action Handling open func triggerAudioFeedback(for gesture: KeyboardGesture, on action: KeyboardAction, sender: Any?) { if action == .backspace { return audioConfiguration.deleteFeedback.trigger() } if action.isInputAction { return audioConfiguration.inputFeedback.trigger() } if action.isSystemAction { return audioConfiguration.systemFeedback.trigger() } } open func triggerHapticFeedback(for gesture: KeyboardGesture, on action: KeyboardAction, sender: Any?) { switch gesture { case .doubleTap: hapticConfiguration.doubleTapFeedback.trigger() case .longPress: hapticConfiguration.longPressFeedback.trigger() case .press: hapticConfiguration.tapFeedback.trigger() case .release: hapticConfiguration.tapFeedback.trigger() case .repeatPress: hapticConfiguration.repeatFeedback.trigger() case .tap: hapticConfiguration.tapFeedback.trigger() } } open func triggerHapticFeedbackForLongPressOnSpaceDragGesture() { hapticConfiguration.longPressOnSpaceFeedback.trigger() } open func tryEndSentence(after gesture: KeyboardGesture, on action: KeyboardAction) { guard keyboardBehavior.shouldEndSentence(after: gesture, on: action) else { return } keyboardContext.textDocumentProxy.endSentence() } open func tryChangeKeyboardType(after gesture: KeyboardGesture, on action: KeyboardAction) { guard keyboardBehavior.shouldSwitchToPreferredKeyboardType(after: gesture, on: action) else { return } let newType = keyboardBehavior.preferredKeyboardType(after: gesture, on: action) changeKeyboardTypeAction(newType) } // TODO: Unit test open func tryRegisterEmoji(after gesture: KeyboardGesture, on action: KeyboardAction) { guard gesture == .tap else { return } switch action { case .emoji(let emoji): return EmojiCategory.frequentEmojiProvider.registerEmoji(emoji) default: return } } } // MARK: - Private Functions private extension StandardKeyboardActionHandler { private func tryStartNewSpaceCursorDragGesture(from startLocation: CGPoint, to currentLocation: CGPoint) { let isNewDrag = currentDragStartLocation != startLocation currentDragStartLocation = startLocation guard isNewDrag else { return } currentDragTextPositionOffset = 0 triggerHapticFeedbackForLongPressOnSpaceDragGesture() } }
mit
8369d9d686442cd7aac1edb96d39061c
39.024038
112
0.716156
5.239144
false
true
false
false
einsteinx2/iSub
Classes/Data Model/Song.swift
1
5396
// // Song.swift // iSub // // Created by Benjamin Baron on 1/15/17. // Copyright © 2017 Ben Baron. All rights reserved. // import Foundation extension Song: Item, Equatable { var itemId: Int64 { return songId } var itemName: String { return title } } final class Song { let repository: SongRepository let songId: Int64 let serverId: Int64 let contentTypeId: Int64 let transcodedContentTypeId: Int64? let mediaFolderId: Int64? let folderId: Int64? let artistId: Int64? let artistName: String? let albumId: Int64? let albumName: String? let genreId: Int64? let coverArtId: String? let title: String let duration: Int? let bitRate: Int? let trackNumber: Int? let discNumber: Int? let year: Int? let size: Int64 let path: String var lastPlayed: Date? var folder: Folder? var artist: Artist? var album: Album? var genre: Genre? var contentType: ContentType? var transcodedContentType: ContentType? init(songId: Int64, serverId: Int64, contentTypeId: Int64, transcodedContentTypeId: Int64?, mediaFolderId: Int64?, folderId: Int64?, artistId: Int64?, artistName: String?, albumId: Int64?, albumName: String?, genreId: Int64?, coverArtId: String?, title: String, duration: Int?, bitRate: Int?, trackNumber: Int?, discNumber: Int?, year: Int?, size: Int64, path: String, lastPlayed: Date?, genre: Genre?, contentType: ContentType?, transcodedContentType: ContentType?, repository: SongRepository = SongRepository.si) { self.songId = songId self.serverId = serverId self.contentTypeId = contentTypeId self.transcodedContentTypeId = transcodedContentTypeId self.mediaFolderId = mediaFolderId self.folderId = folderId self.artistId = artistId self.artistName = artistName self.albumId = albumId self.albumName = albumName self.genreId = genreId self.coverArtId = coverArtId self.title = title self.duration = duration self.bitRate = bitRate self.trackNumber = trackNumber self.discNumber = discNumber self.year = year self.size = size self.path = path self.lastPlayed = lastPlayed self.genre = genre self.contentType = contentType self.transcodedContentType = transcodedContentType self.repository = repository } } // Calcuated properties extension Song { var currentContentType: ContentType? { return transcodedContentType ?? contentType } var basicType: BasicContentType? { return contentType?.basicType } // Automatically chooses either the artist/album model name or uses the song property if it's not available // NOTE: Not every song has an Artist or Album object in Subsonic. So when folder browsing this is especially // important. var artistDisplayName: String? { return artist?.name ?? artistName } var albumDisplayName: String? { return album?.name ?? albumName } var fileName: String { return "\(serverId)-\(songId)" } var localPath: String { return songCachePath + "/" + fileName } var localTempPath: String { return tempCachePath + "/" + fileName } var currentPath: String { return isTempCached ? localTempPath : localPath } var isTempCached: Bool { return FileManager.default.fileExists(atPath: localTempPath) } var localFileSize: Int64 { // Using C instead of FileManager because of a weird crash on iOS 5 and up devices in the audio engine // Asked question here: http://stackoverflow.com/questions/10289536/sigsegv-segv-accerr-crash-in-nsfileattributes-dealloc-when-autoreleasepool-is-dr // Still waiting on Apple to fix their bug, so this is my (now 5 years old) "temporary" solution var fileInfo = stat() stat(currentPath, &fileInfo) return fileInfo.st_size } var fileExists: Bool { // Using C instead of FileManager because of a weird crash in the bass callback functions var fileInfo = stat() stat(currentPath, &fileInfo) return fileInfo.st_dev > 0 } var estimatedBitRate: Int { let currentMaxBitRate = SavedSettings.si.currentMaxBitRate; // Default to 128 if there is no bitRate for this song object (should never happen) var rate = (bitRate == nil || bitRate == 0) ? 128 : bitRate! // Check if this is being transcoded to the best of our knowledge if transcodedContentType == nil { // This is not being transcoded between formats, however bitRate limiting may be active if rate > currentMaxBitRate && currentMaxBitRate != 0 { rate = currentMaxBitRate } } else { // This is probably being transcoded, so attempt to determine the bitRate if rate > 128 && currentMaxBitRate == 0 { rate = 128 // Subsonic default transcoding bitRate } else if rate > currentMaxBitRate && currentMaxBitRate != 0 { rate = currentMaxBitRate } } return rate; } }
gpl-3.0
2db9cae7569fd72bf1172b8d449bc985
31.896341
520
0.635403
4.821269
false
false
false
false
ykpaco/LayoutComposer
Example/LayoutComposer/ExampleViewController.swift
1
2334
// // ExampleViewController.swift // LayoutComposer // // Created by Yusuke Kawakami on 2015/08/22. // Copyright (c) 2015年 CocoaPods. All rights reserved. // import UIKit import LayoutComposer class ExampleViewController: BaseViewController { let headerTitle: String var contentView: UIView! init(headerTitle: String) { self.headerTitle = headerTitle super.init(nibName: nil, bundle: nil) } required init(coder aDecoder: NSCoder) { fatalError("not supported") } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func loadView() { view = UIView() view.backgroundColor = UIColor.white let header = UIView() header.backgroundColor = UIColor.black let titleLabel = UILabel() titleLabel.text = headerTitle titleLabel.textColor = UIColor.white let backBtn = UIButton(type: .system) backBtn.setTitle("Back", for: UIControlState()) backBtn.addTarget(self, action: #selector(ExampleViewController.onBackTapped(_:)), for: .touchUpInside) contentView = UIView() contentView.backgroundColor = UIColor.gray view.applyLayout(VBox(), items: [ $(header, height: 65, layout: Relative(), items: [ $(backBtn, halign: .left, marginTop: 20, marginLeft: 10), $(titleLabel, halign: .center, marginTop: 20) ]), $(contentView, flex: 1) ]) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func onBackTapped(_ sender: UIButton) { _ = navigationController?.popViewController(animated: true) } func makeItemView(title: String, color: UIColor) -> UIView { let retView = UIView() retView.backgroundColor = color let titleLabel = UILabel() titleLabel.textColor = UIColor.black titleLabel.textAlignment = .center titleLabel.text = title titleLabel.numberOfLines = 0 retView.applyLayout(Fit(), item: $(titleLabel)) return retView } }
mit
6c3a3e68b80b59e13fef8c30ef664ed3
28.518987
111
0.611063
5.08061
false
false
false
false
DiorStone/DSPopup
Sources/PopupWindow.swift
1
4547
// // PopupWindow.swift // The MIT License (MIT) // Copyright © 2017 DSPopup // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit import Foundation import ObjectiveC fileprivate let PopupableViewIsAdd = UnsafeRawPointer.init(bitPattern: "PopupableViewIsAdd".hashValue) extension Popupable { fileprivate var isAdd: Bool { set { objc_setAssociatedObject(self, PopupableViewIsAdd, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY_NONATOMIC) } get { var returnValue = false if let value = objc_getAssociatedObject(self, PopupableViewIsAdd) { returnValue = value as! Bool } return returnValue } } } open class PopupWindow: UIWindow,UIGestureRecognizerDelegate { /// default is NO. When YES, popup view will be hidden when user touch the translucent background. public var tochToHide: Bool = false // MARK: private public var attchView: UIView { return self.rootViewController!.view } var poppuped: Bool = false var popupViews: [Popupable] = [] // MARK: public open static let `default`: PopupWindow = { let window = PopupWindow(frame: UIScreen.main.bounds) window.rootViewController = UIViewController() return window }() public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } internal func showPopupView(_ popupView: Popupable, completion: (() -> Void)? = nil) { if !popupView.isAdd { popupView.isAdd = true popupViews.append(popupView) } //no popup if !poppuped { poppuped = true // show let attachView: UIView = popupView.ds_attachedView ?? self.attchView if attachView == self.attchView { self.isHidden = false self.makeKeyAndVisible() } popupView.ds_showPopup(inView: attachView, completion: completion) } } internal func hiddenPopupView(_ popupView: Popupable, completion: (() -> Void)? = nil) { let attachView: UIView = popupView.ds_attachedView ?? self.attchView popupView.ds_hidePopup(inView: attachView) { [unowned self] in self.poppuped = false if attachView == self.attchView { self.isHidden = true UIApplication.shared.delegate?.window??.makeKeyAndVisible() } completion?() if self.popupViews.count > 0 { self.popupViews.removeFirst() if let popupView = self.popupViews.first { self.showPopupView(popupView, completion: nil) } } } } // MARK: private fileprivate override init(frame: CGRect) { super.init(frame: frame) self.windowLevel = UIWindowLevelNormal let gesture = UITapGestureRecognizer(target: self, action: #selector(actionTap)) gesture.delegate = self self.addGestureRecognizer(gesture) } func actionTap() { if let view = popupViews.first { self.hiddenPopupView(view) } } // MARK: UIGestureRecognizerDelegate public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { return self.tochToHide } }
mit
7a9c369968affe38b3ef807d2bac420a
34.24031
128
0.637703
4.815678
false
false
false
false
ryuichis/swift-ast
Sources/AST/Expression/ClosureExpression.swift
2
5189
/* Copyright 2016-2018 Ryuichi Intellectual Property and the Yanagiba project contributors 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. */ public class ClosureExpression : ASTNode, PrimaryExpression { public struct Signature { public struct CaptureItem { public enum Specifier : String { case weak case unowned case unownedSafe = "unowned(safe)" case unownedUnsafe = "unowned(unsafe)" } public let specifier: Specifier? public let expression: Expression public init(specifier: Specifier? = nil, expression: Expression) { self.specifier = specifier self.expression = expression } } public enum ParameterClause { public struct Parameter { public let name: Identifier public let typeAnnotation: TypeAnnotation? public let isVarargs: Bool public init( name: Identifier, typeAnnotation: TypeAnnotation? = nil, isVarargs: Bool = false ) { self.name = name self.typeAnnotation = typeAnnotation self.isVarargs = isVarargs } } case parameterList([Parameter]) case identifierList(IdentifierList) } public let captureList: [CaptureItem]? public let parameterClause: ParameterClause? public let canThrow: Bool public let functionResult: FunctionResult? public init(captureList: [CaptureItem]) { self.captureList = captureList self.parameterClause = nil self.canThrow = false self.functionResult = nil } public init( captureList: [CaptureItem]? = nil, parameterClause: ParameterClause, canThrow: Bool = false, functionResult: FunctionResult? = nil ) { self.captureList = captureList self.parameterClause = parameterClause self.canThrow = canThrow self.functionResult = functionResult } } public let signature: Signature? public private(set) var statements: Statements? public init(signature: Signature? = nil, statements: Statements? = nil) { self.signature = signature self.statements = statements } // MARK: - Node Mutations public func replaceStatement(at index: Int, with statement: Statement) { guard index >= 0 && index < (statements?.count ?? 0) else { return } statements?[index] = statement } // MARK: - ASTTextRepresentable override public var textDescription: String { var signatureText = "" var stmtsText = "" if let signature = signature { signatureText = " \(signature.textDescription) in" if statements == nil { stmtsText = " " } } if let stmts = statements { if signature == nil && stmts.count == 1 { stmtsText = " \(stmts.textDescription) " } else { stmtsText = "\n\(stmts.textDescription)\n" } } return "{\(signatureText)\(stmtsText)}" } } extension ClosureExpression.Signature.CaptureItem.Specifier : ASTTextRepresentable { public var textDescription: String { return rawValue } } extension ClosureExpression.Signature.CaptureItem : ASTTextRepresentable { public var textDescription: String { let exprText = expression.textDescription guard let specifier = specifier else { return exprText } return "\(specifier.textDescription) \(exprText)" } } extension ClosureExpression.Signature.ParameterClause.Parameter : ASTTextRepresentable { public var textDescription: String { var paramText = name.textDescription if let typeAnnotation = typeAnnotation { paramText += typeAnnotation.textDescription if isVarargs { paramText += "..." } } return paramText } } extension ClosureExpression.Signature.ParameterClause : ASTTextRepresentable { public var textDescription: String { switch self { case .parameterList(let params): return "(\(params.map({ $0.textDescription }).joined(separator: ", ")))" case .identifierList(let idList): return idList.textDescription } } } extension ClosureExpression.Signature : ASTTextRepresentable { public var textDescription: String { var signatureText = [String]() if let captureList = captureList { signatureText.append("[\(captureList.map({ $0.textDescription }).joined(separator: ", "))]") } if let parameterClause = parameterClause { signatureText.append(parameterClause.textDescription) } if canThrow { signatureText.append("throws") } if let funcResult = functionResult { signatureText.append(funcResult.textDescription) } return signatureText.joined(separator: " ") } }
apache-2.0
92f2ce1f9d489f726cbc329deae406f3
27.988827
98
0.673926
4.849533
false
false
false
false
buyiyang/iosstar
iOSStar/General/Base/BaseCustomTableViewController.swift
4
6118
// // BaseCustomTableViewController.swift // viossvc // // Created by yaowang on 2016/10/29. // Copyright © 2016年 ywwlcom.yundian. All rights reserved. // import UIKit class BaseCustomTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource,TableViewHelperProtocol { @IBOutlet weak var tableView: UITableView! var tableViewHelper:TableViewHelper = TableViewHelper(); override func viewDidLoad() { super.viewDidLoad() initTableView(); } //友盟页面统计 override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // MobClick.beginLogPageView(NSStringFromClass(self.classForCoder)) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) // MobClick.beginLogPageView(NSStringFromClass(self.classForCoder)) } final func initTableView() { if tableView == nil { for view:UIView in self.view.subviews { if view.isKind(of: UITableView.self) { tableView = view as? UITableView; break; } } } if tableView.tableFooterView == nil { tableView.tableFooterView = UIView(frame:CGRect(x: 0,y: 0,width: 0,height: 0.5)); } tableView.delegate = self; tableView.dataSource = self; } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } //MARK:TableViewHelperProtocol func isSections() ->Bool { return false; } func isCacheCellHeight() -> Bool { return false; } func isCalculateCellHeight() ->Bool { return isCacheCellHeight(); } func tableView(_ tableView:UITableView ,cellIdentifierForRowAtIndexPath indexPath: IndexPath) -> String? { return tableViewHelper.tableView(tableView, cellIdentifierForRowAtIndexPath: indexPath, controller: self); } func tableView(_ tableView:UITableView ,cellDataForRowAtIndexPath indexPath: IndexPath) -> AnyObject? { return nil; } //MARK: -UITableViewDelegate func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { return tableViewHelper.tableView(tableView, cellForRowAtIndexPath: indexPath, controller: self); } func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { tableViewHelper.tableView(tableView, willDisplayCell: cell, forRowAtIndexPath: indexPath, controller: self); } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if( isCalculateCellHeight() ) { let cellHeight:CGFloat = tableViewHelper.tableView(tableView, heightForRowAtIndexPath: indexPath, controller: self); if( cellHeight != CGFloat.greatestFiniteMagnitude ) { return cellHeight; } } return tableView.rowHeight; } func numberOfSections(in tableView: UITableView) -> Int { return 1; } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 0; } } class BaseCustomRefreshTableViewController :BaseCustomTableViewController { override func viewDidLoad() { super.viewDidLoad(); self.setupRefreshControl(); } internal func didRequestComplete(_ data:AnyObject?) { endRefreshing(); self.tableView.reloadData(); } func completeBlockFunc()->CompleteBlock { return { [weak self] (obj) in self?.didRequestComplete(obj) } } override func didRequestError(_ error:NSError) { self.endRefreshing() super.didRequestError(error) } deinit { performSelectorRemoveRefreshControl(); } } class BaseCustomListTableViewController :BaseCustomRefreshTableViewController { internal var dataSource:Array<AnyObject>?; override func didRequestComplete(_ data: AnyObject?) { dataSource = data as? Array<AnyObject>; super.didRequestComplete(dataSource as AnyObject?); } //MARK: -UITableViewDelegate override func numberOfSections(in tableView: UITableView) -> Int { var count:Int = dataSource != nil ? 1 : 0; if isSections() && count != 0 { count = dataSource!.count; } return count; } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { var datas:Array<AnyObject>? = dataSource; if dataSource != nil && isSections() { datas = dataSource![section] as? Array<AnyObject>; } return datas == nil ? 0 : datas!.count; } //MARK:TableViewHelperProtocol override func tableView(_ tableView:UITableView ,cellDataForRowAtIndexPath indexPath: IndexPath) -> AnyObject? { var datas:Array<AnyObject>? = dataSource; if dataSource != nil && isSections() { datas = dataSource![indexPath.section] as? Array<AnyObject>; } return (datas != nil && datas!.count > indexPath.row ) ? datas![indexPath.row] : nil; } } class BaseCustomPageListTableViewController :BaseCustomListTableViewController { override func viewDidLoad() { super.viewDidLoad(); setupLoadMore(); } override func didRequestComplete(_ data: AnyObject?) { tableViewHelper.didRequestComplete(&self.dataSource, pageDatas: data as? Array<AnyObject>, controller: self); super.didRequestComplete(self.dataSource as AnyObject?); } override func didRequestError(_ error:NSError) { if (!(self.pageIndex == 1) ) { self.errorLoadMore() } self.setIsLoadData(true) super.didRequestError(error) } deinit { removeLoadMore(); } }
gpl-3.0
94eda4706bcd44937b9da2c4b4efe1af
29.979695
128
0.630182
5.348817
false
false
false
false
iluuu1994/2048
2048/Classes/GameBoard.swift
1
9579
// // GameBoard.swift // 2048 // // Created by Ilija Tovilo on 30/07/14. // Copyright (c) 2014 Ilija Tovilo. All rights reserved. // import Foundation /** * The GameBoardDelegate is used to define an interface that can be used to receive information about the progress of the game. */ protocol GameBoardDelegate: class { func playerScoreIncreased(by: Int, totalScore: Int) func playerWonWithScore(score: Int) func gameOverWithScore(score: Int) } /** * The ForInLoop is used to define an interface for for loops */ private struct ForLoop<T> { let initialValue: T let condition: (T) -> Bool let incrementalValue: T init(_ initialValue: T, _ condition: (T) -> Bool, _ incrementalValue: T) { self.initialValue = initialValue self.condition = condition self.incrementalValue = incrementalValue } } typealias TilePosition = (x: Int, y: Int) @objc(TFGameBoard) public class GameBoard: GameObject { // MARK: Instance Variables let gridSize: Int internal(set) var score: Int = 0 // TODO: Check why program crashes when this is set to GameBoardDelegate weak var delegate: GameScene? internal let _tiles: Matrix<Tile> private var _didShowYouWinScene = false public var gameBoardView: GameBoardView! { get { return view as GameBoardView } } // MARK: Initialization init(gridSize: Int) { assert(gridSize > 0, "Game Board must have a grid size of greater than 0!") self.gridSize = gridSize _tiles = Matrix<Tile>(width: self.gridSize, height: self.gridSize) super.init() for times in 0..<2 { spawnRandomTile() } } override func loadView() { view = GameBoardView(gameBoard: self) } // MARK: Game Logic func spawnRandomTile() { let possiblePositions = emptyTiles() let position = possiblePositions[randomWhole(0, possiblePositions.count - 1)] let value = randomWhole(0, 6) <= 5 ? 2 : 4 let tile = Tile(value: value) addTile(tile, to: position) gameBoardView.spawnTileView(tile.tileView, at: position) } func emptyTiles() -> [TilePosition] { var emptyTiles = Array<TilePosition>() for x in 0..<_tiles.width { for y in 0..<_tiles.height { if _tiles[x, y] == nil { emptyTiles += [(x, y)] } } } return emptyTiles } func addTile(tile: Tile, to: TilePosition) { assert(_tiles[to.x, to.y] == nil, "The tile position is not free.") _tiles[to.x, to.y] = tile } func removeTile(at: TilePosition) { assert(_tiles[at.x, at.y] != nil, "There is no tile at this position.") if let tile = _tiles[at.x, at.y] { _tiles[at.x, at.y] = nil } } func moveTile(at: TilePosition, to:TilePosition) { assert(!(at.x == to.x && at.y == to.y), "The tile is already at this location.") assert(_tiles[to.x, to.y] == nil, "The new tile position is not free.") if let tile = _tiles[at.x, at.y] { _tiles[at.x, at.y] = nil _tiles[to.x, to.y] = tile gameBoardView.moveTileView(tile.tileView, to: to) } } func performSwipeInDirection(direction: SwipeDirection) { var firstI: ForLoop<Int>! var secondI: ForLoop<Int>! var ppI: ForLoop<Int>! var gV: (Int, Int) -> TilePosition switch direction { case .Left: firstI = ForLoop(1, {$0 < self._tiles.width}, 1) secondI = ForLoop(0, {$0 < self._tiles.height}, 1) ppI = ForLoop(0 /* Ignored */, {$0 >= 0}, -1) gV = {($0,$1)} case .Right: firstI = ForLoop(self._tiles.width - 2, {$0 >= 0}, -1) secondI = ForLoop(0, {$0 < self._tiles.height}, 1) ppI = ForLoop(0 /* Ignored */, {$0 < self._tiles.height}, 1) gV = {($0,$1)} case .Up: firstI = ForLoop(self._tiles.height - 2, {$0 >= 0}, -1) secondI = ForLoop(0, {$0 < self._tiles.width}, 1) ppI = ForLoop(0 /* Ignored */, {$0 < self._tiles.height}, 1) gV = {($1,$0)} case .Down: firstI = ForLoop(1, {$0 < self._tiles.height}, 1) secondI = ForLoop(0, {$0 < self._tiles.width}, 1) ppI = ForLoop(0 /* Ignored */, {$0 >= 0}, -1) gV = {($1,$0)} } var validSwipe = false for var firstV = firstI.initialValue; firstI.condition(firstV); firstV += firstI.incrementalValue { for var secondV = secondI.initialValue; secondI.condition(secondV); secondV += secondI.incrementalValue { let tilePos = gV(firstV, secondV) if let tile = _tiles[tilePos.x, tilePos.y] { var newPos: TilePosition? possiblePositions: for var pp = firstV + ppI.incrementalValue; ppI.condition(pp); pp += ppI.incrementalValue { let possiblePos = gV(pp, secondV) if let fixedTile = _tiles[possiblePos.x, possiblePos.y] { if tile.canMergeWith(fixedTile) { newPos = possiblePos } break possiblePositions } else { newPos = possiblePos } } if let nnNewPos = newPos { validSwipe = true if let fixedTile = _tiles[nnNewPos.x, nnNewPos.y] { // Move the tile and merge it with the other tile removeTile(nnNewPos) removeTile(tilePos) let mergedTile = Tile(value: tile.value + fixedTile.value) mergedTile.locked = true addTile(mergedTile, to: nnNewPos) gameBoardView.mergeTileView( tile.tileView, fixedTile.tileView, intoTileView: mergedTile.tileView, mergePosition: nnNewPos ) increaseScore(mergedTile.value) } else { // Just move the tile moveTile(tilePos, to: nnNewPos) } } } } } if validSwipe { // Spawn a new tile on every move view.scheduleBlock({ (timer) in self.spawnRandomTile() self.checkForGameOver() }, delay: kTileSpawnDelay) } unlockAllTiles() } func increaseScore(by: Int) { score += by if let nnDelegate = delegate { nnDelegate.playerScoreIncreased(by, totalScore: score) if by == 2048 { youWin() } } } func unlockAllTiles() { for x in 0..<_tiles.width { for y in 0..<_tiles.height { if let tile = _tiles[x, y] { tile.locked = false } } } } func enclosingTilesOfTile(at: TilePosition) -> [Tile] { var enclosingTiles = [Tile]() if let tile = _tiles[at.x, at.y] { for (etX, etY) in [(at.x + 1, at.y), (at.x - 1, at.y), (at.x, at.y + 1), (at.x, at.y - 1)] { if etX >= 0 && etX < _tiles.width && etY >= 0 && etY < _tiles.height { if let enclosingTile = _tiles[etX, etY] { enclosingTiles += [enclosingTile] } } } } return enclosingTiles } func checkForGameOver() { if emptyTiles().count == 0 { for x in 0..<_tiles.width { for y in 0..<_tiles.height { if let tile = _tiles[x, y] { let enclosingTiles = enclosingTilesOfTile((x: x, y: y)) for enclosingTile in enclosingTiles { if tile.value == enclosingTile.value { return } } } } } gameOver() } } func gameOver() { if let nnDelegate = delegate { nnDelegate.gameOverWithScore(score) } } func youWin() { if !_didShowYouWinScene { if let nnDelegate = delegate { nnDelegate.playerWonWithScore(score) } _didShowYouWinScene = true } } }
bsd-3-clause
8c37172137eb5422c4a3e25bab3c0541
30.82392
130
0.456937
4.495073
false
false
false
false
xianglin123/douyuzhibo
douyuzhibo/douyuzhibo/Classes/Home/Controllers/XLHomeViewController.swift
1
3516
// // XLHomeViewController.swift // douyuzhibo // // Created by xianglin on 16/10/4. // Copyright © 2016年 xianglin. All rights reserved. // import UIKit private let kChannelH : CGFloat = 40 class XLHomeViewController: UIViewController { //MARK: - 懒加载控件 //1.标题栏 fileprivate lazy var channelView : XLChannelView = {[weak self] in let frame = CGRect(x: 0, y: kStatusBarH + kNaviBarH, width: kScreenW, height: kChannelH) let channels = ["推荐", "游戏", "娱乐", "趣玩"] let channelView = XLChannelView(frame: frame, channels: channels) channelView.delegate = self return channelView }() //2.内容视图 fileprivate lazy var contentView : XLContentView = {[weak self] in // 1.确定内容的frame let contentH = kScreenH - kStatusBarH - kNaviBarH - kChannelH - kTabbarH let contentFrame = CGRect(x: 0, y: kStatusBarH + kNaviBarH + kChannelH, width: kScreenW, height: contentH) // 2.确定所有的子控制器 var childVcs = [UIViewController]() childVcs.append(XLRecommendController()) childVcs.append(XLGameViewController()) for _ in 1..<3 { let vc = UIViewController() vc.view.backgroundColor = UIColor(r: CGFloat(arc4random_uniform(255)), g: CGFloat(arc4random_uniform(255)), b: CGFloat(arc4random_uniform(255))) childVcs.append(vc) } let contentView = XLContentView(frame: contentFrame, childVcs: childVcs, parentController: self) contentView.delegate = self return contentView }() //MARK: - 系统回调 override func viewDidLoad() { super.viewDidLoad() //设置UI setupUI() } //MARK: - 设置UI fileprivate func setupUI() { //是否自动调整UIScrollView的内边距 automaticallyAdjustsScrollViewInsets = false //设置导航栏 setupNavi() //添加channel标题栏 view.addSubview(channelView) //添加内容视图 view.addSubview(contentView) } //MARK: - 设置导航栏 fileprivate func setupNavi() { //1.设置左侧item self.navigationItem.leftBarButtonItem = UIBarButtonItem(normalImageName: "logo") //2.设置右侧items let size = CGSize(width: 40, height: 40) let historyItem = UIBarButtonItem(normalImageName: "image_my_history", highImageName: "Image_my_history_click", size: size) let codeItem = UIBarButtonItem(normalImageName: "Image_scan", highImageName: "Image_scan_click", size: size) let searchItem = UIBarButtonItem(normalImageName: "btn_search", highImageName: "btn_search_clicked", size: size) self.navigationItem.rightBarButtonItems = [searchItem, codeItem, historyItem] } } //MARK: - channelView的代理方法 extension XLHomeViewController : XLChannelViewDelegate{ func channelView(_ titleView: XLChannelView, selectedIndex: Int) { //切换contentView contentView.setContentViewWithIndex(selectedIndex) } } //MARK: - contentView的代理方法 extension XLHomeViewController : XLContentViewDelegate{ func contentView(_ contentView: XLContentView, progress: CGFloat, sourceIndex: Int, targetIndex: Int) { //切换channel channelView.setChannelView(progress, sourceIndex: sourceIndex, targetIndex: targetIndex) } }
apache-2.0
85b4a324e0db6113cc910b0c254bdccc
32.565657
156
0.646103
4.558299
false
false
false
false
Tonkpils/SpaceRun
SpaceRun/GameScene.swift
1
11751
// // GameScene.swift // SpaceRun // // Created by Leonardo Correa on 11/29/15. // Copyright (c) 2015 Leonardo Correa. All rights reserved. // import SpriteKit import Foundation class GameScene: SKScene { weak var shipTouch : UITouch? var tapGesture : UITapGestureRecognizer! var easyMode : Bool? var endGameCallback : dispatch_block_t? var lastUpdateTime : CFTimeInterval = 0 var lastShotFiredTime : CFTimeInterval = 0 var shipFireRate : CGFloat = 0.5 let shootSound = SKAction.playSoundFileNamed("shoot.m4a", waitForCompletion: false) let shipExplodeSound = SKAction.playSoundFileNamed("shipExplode.m4a", waitForCompletion: false) let obstacleExplodeSound = SKAction.playSoundFileNamed("obstacleExplode.m4a", waitForCompletion: false) let shipExplodeTemplate = SKEmitterNode(fileNamed: "ShipExplode.sks") as SKEmitterNode! let obstacleExplodeTemplate = SKEmitterNode(fileNamed: "ObstacleExplode.sks") as SKEmitterNode! override func didMoveToView(view: SKView) { self.backgroundColor = SKColor.blackColor() let starField = StarField() self.addChild(starField) let ship = SKSpriteNode(imageNamed: "Spaceship.png") ship.position = CGPoint(x: CGRectGetMidX(self.frame), y: CGRectGetMidY(self.frame)) ship.size = CGSize(width: 40, height: 40) ship.name = "ship" let thrust = SKEmitterNode(fileNamed: "Thrust.sks") as SKEmitterNode! thrust.position = CGPoint(x: 0, y: -20) ship.addChild(thrust) self.addChild(ship) let hud = HUDNode() hud.name = "hud" hud.zPosition = 100 hud.position = CGPoint(x: self.size.width / 2, y: self.size.height / 2) self.addChild(hud) hud.layoutForScene() hud.startGame() } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { /* Called when a touch begins */ self.shipTouch = touches.first } override func update(currentTime: CFTimeInterval) { /* Called before each frame is rendered */ if self.lastUpdateTime == 0 { self.lastUpdateTime = currentTime } let timeDelta = currentTime - self.lastUpdateTime if let shipTouch = self.shipTouch { self.moveShipTowards(shipTouch.locationInNode(self), by: timeDelta) if CGFloat(currentTime - self.lastShotFiredTime) > shipFireRate { self.shoot() self.lastShotFiredTime = currentTime } } var thingProbability : Int if self.easyMode == true { thingProbability = 15 } else { thingProbability = 30 } if Int(arc4random_uniform(1000)) <= thingProbability { dropThing() } self.checkCollitions() self.lastUpdateTime = currentTime } func dropThing() { let dice = arc4random_uniform(100) if dice < 5 { dropPowerUp() }else if dice < 20 { dropEnemyShip() } else { dropAsteroid() } } func dropPowerUp() { let sideSize : CGFloat = 30 let startX = CGFloat(arc4random_uniform(UInt32(self.size.width - CGFloat(60))) + 30) let startY = CGFloat(self.size.height + sideSize) let endY = CGFloat(0 - sideSize) let powerUp = SKSpriteNode(imageNamed: "powerup") powerUp.name = "powerup" powerUp.size = CGSize(width: sideSize, height: sideSize) powerUp.position = CGPoint(x: startX, y: startY) self.addChild(powerUp) let move = SKAction.moveTo(CGPoint(x: startX, y: endY), duration: 6) let spin = SKAction.rotateByAngle(-1, duration: 1) let remove = SKAction.removeFromParent() let spinForever = SKAction.repeatActionForever(spin) let travelAndRemove = SKAction.sequence([move, remove]) let all = SKAction.group([spinForever, travelAndRemove]) powerUp.runAction(all) } func dropEnemyShip() { let sideSize : CGFloat = 30 let startX : CGFloat = CGFloat(arc4random_uniform(UInt32(self.size.width - CGFloat(40))) + 20) let startY : CGFloat = self.size.height + sideSize let enemy = SKSpriteNode(imageNamed: "enemy") enemy.size = CGSize(width: sideSize, height: sideSize) enemy.position = CGPoint(x: startX, y: startY) enemy.name = "obstacle" addChild(enemy) let shipPath : CGPathRef = buildEnemyShipMovementPath() let followPath = SKAction.followPath(shipPath, asOffset: true, orientToPath: true, duration: 7) let remove = SKAction.removeFromParent() let all = SKAction.sequence([followPath, remove]) enemy.runAction(all) } func buildEnemyShipMovementPath() -> CGPathRef { let bezierPath = UIBezierPath() bezierPath.moveToPoint(CGPoint(x: 0.5, y: -0.5)) bezierPath.addCurveToPoint(CGPoint(x: -2.5, y: -59.5), controlPoint1: CGPoint(x: 0.5, y: -0.5), controlPoint2: CGPoint(x: 4.55, y: -29.48)) bezierPath.addCurveToPoint(CGPoint(x: -27.5, y: -154.5), controlPoint1: CGPoint(x: -9.55, y: -89.52), controlPoint2: CGPoint(x: -43.32, y: -115.43)) bezierPath.addCurveToPoint(CGPoint(x: 30.5, y: -243.5), controlPoint1: CGPoint(x: -11.68, y: -193.57), controlPoint2: CGPoint(x: 17.28, y: -186.95)) bezierPath.addCurveToPoint(CGPoint(x: -52.5, y: -379.5), controlPoint1: CGPoint(x: 43.72, y: -300.05), controlPoint2: CGPoint(x: -47.71, y: -335.76)) bezierPath.addCurveToPoint(CGPoint(x: 54.5, y: -449.5), controlPoint1: CGPoint(x: -57.29, y: -423.24), controlPoint2: CGPoint(x: -8.14, y: -482.24)) bezierPath.addCurveToPoint(CGPoint(x: -5.5, y: -348.5), controlPoint1: CGPoint(x: 117.14, y: -416.55), controlPoint2: CGPoint(x: 52.25, y: -308.62)) bezierPath.addCurveToPoint(CGPoint(x: 10.5, y: -494.5), controlPoint1: CGPoint(x: -63.25, y: -388.38), controlPoint2: CGPoint(x: -14.48, y: -457.43)) bezierPath.addCurveToPoint(CGPoint(x: 0.5, y: -559.5), controlPoint1: CGPoint(x: 23.74, y: -514.16), controlPoint2: CGPoint(x: 6.93, y: -537.57)) bezierPath.addCurveToPoint(CGPoint(x: -2.5, y: -644.5), controlPoint1: CGPoint(x: -5.2, y: -578.93), controlPoint2: CGPoint(x: -2.5, y: -644.5)) return bezierPath.CGPath } func checkCollitions() { guard let ship = self.childNodeWithName("ship") else { return } self.enumerateChildNodesWithName("powerup") { (powerup, stop) -> Void in if ship.intersectsNode(powerup) { powerup.removeFromParent() self.shipFireRate = 0.1 let powerdown = SKAction.runBlock({ () -> Void in self.shipFireRate = 0.5 }) let wait = SKAction.waitForDuration(5) let waitAndPowerdown = SKAction.sequence([wait, powerdown]) ship.removeActionForKey("waitAndPowerdown") ship.runAction(waitAndPowerdown, withKey: "waitAndPowerdown") } } self.enumerateChildNodesWithName("obstacle") { (obstacle, stop) -> Void in if ship.intersectsNode(obstacle) { self.shipTouch = nil self.endGame() ship.removeFromParent() obstacle.removeFromParent() self.runAction(self.shipExplodeSound) let explosion = self.shipExplodeTemplate.copy() as! SKEmitterNode explosion.position = ship.position explosion.dieOutOn(0.3) self.addChild(explosion) } self.enumerateChildNodesWithName("photon") { (photon, stop) -> Void in if photon.intersectsNode(obstacle) { photon.removeFromParent() obstacle.removeFromParent() self.runAction(self.obstacleExplodeSound) let explosion = self.obstacleExplodeTemplate.copy() as! SKEmitterNode explosion.position = obstacle.position explosion.dieOutOn(0.1) self.addChild(explosion) stop.memory = true guard let hud = self.childNodeWithName("hud") as? HUDNode else { return } let score = Int(10 * hud.elapsedTime * (self.easyMode! ? 1 : 2)) hud.addPoints(score) } } } } func dropAsteroid() { let sideSize : CGFloat = 15 + CGFloat(arc4random_uniform(30)) let maxX : CGFloat = self.size.width let quarterX : CGFloat = maxX / 4 let startX : CGFloat = CGFloat(arc4random_uniform(UInt32(maxX + (quarterX * 2)))) - quarterX let startY : CGFloat = self.size.height + sideSize let endX : CGFloat = CGFloat(arc4random_uniform(UInt32(maxX))) let endY : CGFloat = 0 - sideSize let asteroid = SKSpriteNode(imageNamed: "asteroid") asteroid.size = CGSize(width: sideSize, height: sideSize) asteroid.position = CGPoint(x: startX, y: startY) asteroid.name = "obstacle" self.addChild(asteroid) let move = SKAction.moveTo(CGPoint(x: endX, y: endY), duration: CFTimeInterval(3 + Int(arc4random_uniform(4)))) let remove = SKAction.removeFromParent() let travelAndRemove = SKAction.sequence([move, remove]) let spin = SKAction.rotateByAngle(3, duration: CFTimeInterval(Int(arc4random_uniform(2) + 1))) let spinForever = SKAction.repeatActionForever(spin) let all = SKAction.group([spinForever, travelAndRemove]) asteroid.runAction(all) } func shoot() { guard let ship = self.childNodeWithName("ship") else { return } let photon = SKSpriteNode(imageNamed: "photon") photon.name = "photon" photon.position = ship.position self.addChild(photon) let fly = SKAction.moveByX(0, y: self.size.height+photon.size.height, duration: 0.5) let remove = SKAction.removeFromParent() let flyAndRemove = SKAction.sequence([fly, remove]) photon.runAction(flyAndRemove) self.runAction(shootSound) } func moveShipTowards(point : CGPoint, by timeDelta: CFTimeInterval) { let shipSpeed : CGFloat = 360 // points per second guard let ship = self.childNodeWithName("ship") else { return } let distanceLeft = sqrt(pow(ship.position.x - point.x, 2) + pow(ship.position.y - point.y, 2)) if distanceLeft > 4 { let distanceToTravel = CGFloat(timeDelta) * shipSpeed let angle = atan2(point.y - ship.position.y, point.x - ship.position.x) let yOffset = distanceToTravel * sin(angle) let xOffset = distanceToTravel * cos(angle) ship.position = CGPoint(x: ship.position.x + xOffset, y: ship.position.y + yOffset) } } func endGame() { self.tapGesture = UITapGestureRecognizer(target: self, action: "tapped") self.view?.addGestureRecognizer(tapGesture) let gameOverNode = GameOverNode() gameOverNode.position = CGPoint(x: self.size.width / 2, y: self.size.height / 2) self.addChild(gameOverNode) guard let hud = childNodeWithName("hud") as? HUDNode else { return } hud.endGame() } func tapped() { guard let endGameCallback = self.endGameCallback else { assert(false, "Forgot to set endGameCallback") } endGameCallback() } }
mit
587072b8c765eb2ed46b4d785d40ba8c
37.782178
157
0.611948
4.158174
false
false
false
false
hilen/TSWeChat
TSWeChat/Classes/Web/TSWebViewController.swift
1
3451
// // TSWebViewController.swift // TSWeChat // // Created by Hilen on 1/29/16. // Copyright © 2016 Hilen. All rights reserved. // import UIKit import WebKit private let kKVOContentSizekey: String = "contentSize" private let kKVOTitlekey: String = "title" class TSWebViewController: UIViewController { var webView: WKWebView? var URLString: String! var titleString: String? init(title: String? = nil, URLString: String) { super.init(nibName: nil, bundle: nil) if let theTitle = title { self.title = theTitle self.titleString = theTitle } self.URLString = URLString } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.init(ts_hexString: "#2D3132") let preferences = WKPreferences() preferences.javaScriptEnabled = false let configuration = WKWebViewConfiguration() configuration.preferences = preferences self.webView = WKWebView(frame: self.view.bounds, configuration: configuration) guard let theWebView = self.webView else { return } theWebView.scrollView.bounces = true theWebView.scrollView.isScrollEnabled = true theWebView.navigationDelegate = self let urlRequest = URLRequest(url: URL(string: URLString!)!) theWebView.load(urlRequest) self.view.addSubview(theWebView) theWebView.addObserver(self, forKeyPath:kKVOContentSizekey, options:.new, context:nil) theWebView.addObserver(self, forKeyPath:kKVOTitlekey, options:.new, context:nil) } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { switch keyPath { case kKVOContentSizekey?: if let height = change![NSKeyValueChangeKey.newKey] as? Float { self.webView?.scrollView.contentSize.height = CGFloat(height) } break case kKVOTitlekey?: if self.titleString != nil { return } if let title = change![NSKeyValueChangeKey.newKey] as? String { self.title = title } break default: break } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } deinit { self.webView?.removeObserver(self, forKeyPath:kKVOContentSizekey) self.webView?.removeObserver(self, forKeyPath:kKVOTitlekey) } } // MARK: - @delegate WKNavigationDelegate extension TSWebViewController: WKNavigationDelegate { func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation){ UIApplication.shared.isNetworkActivityIndicatorVisible = true } func webView(_ webView: WKWebView, didFinish navigation: WKNavigation){ UIApplication.shared.isNetworkActivityIndicatorVisible = false } func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: (@escaping (WKNavigationResponsePolicy) -> Void)){ decisionHandler(.allow) } }
mit
3138cd9d6fe810c7277333e5d7080630
31.242991
164
0.649275
5.195783
false
false
false
false
ahoppen/swift
test/Interpreter/protocol_initializers.swift
21
15141
// RUN: %empty-directory(%t) // // RUN: %target-build-swift %s -o %t/a.out // RUN: %target-codesign %t/a.out // RUN: %target-run %t/a.out // RUN: %empty-directory(%t) // // RUN: %target-build-swift -swift-version 5 %s -o %t/a.out // RUN: %target-codesign %t/a.out // RUN: %target-run %t/a.out // REQUIRES: executable_test import StdlibUnittest var ProtocolInitTestSuite = TestSuite("ProtocolInit") func mustThrow<T>(_ f: () throws -> T) { do { _ = try f() preconditionFailure("Didn't throw") } catch {} } func mustFail<T>(f: () -> T?) { if f() != nil { preconditionFailure("Didn't fail") } } enum E : Error { case X } protocol TriviallyConstructible { init(x: LifetimeTracked) init(x: LifetimeTracked, throwsDuring: Bool) throws init?(x: LifetimeTracked, failsDuring: Bool) } extension TriviallyConstructible { init(x: LifetimeTracked, throwsBefore: Bool) throws { if throwsBefore { throw E.X } self.init(x: x) } init(x: LifetimeTracked, throwsAfter: Bool) throws { self.init(x: x) if throwsAfter { throw E.X } } init(x: LifetimeTracked, throwsBefore: Bool, throwsDuring: Bool) throws { if throwsBefore { throw E.X } try self.init(x: x, throwsDuring: throwsDuring) } init(x: LifetimeTracked, throwsBefore: Bool, throwsAfter: Bool) throws { if throwsBefore { throw E.X } self.init(x: x) if throwsAfter { throw E.X } } init(x: LifetimeTracked, throwsDuring: Bool, throwsAfter: Bool) throws { try self.init(x: x, throwsDuring: throwsDuring) if throwsAfter { throw E.X } } init(x: LifetimeTracked, throwsBefore: Bool, throwsDuring: Bool, throwsAfter: Bool) throws { if throwsBefore { throw E.X } try self.init(x: x, throwsDuring: throwsDuring) if throwsAfter { throw E.X } } init?(x: LifetimeTracked, failsBefore: Bool) { if failsBefore { return nil } self.init(x: x) } init?(x: LifetimeTracked, failsAfter: Bool) { self.init(x: x) if failsAfter { return nil } } init?(x: LifetimeTracked, failsBefore: Bool, failsDuring: Bool) { if failsBefore { return nil } self.init(x: x, failsDuring: failsDuring) } init?(x: LifetimeTracked, failsBefore: Bool, failsAfter: Bool) { if failsBefore { return nil } self.init(x: x) if failsAfter { return nil } } init?(x: LifetimeTracked, failsDuring: Bool, failsAfter: Bool) { self.init(x: x, failsDuring: failsDuring) if failsAfter { return nil } } init?(x: LifetimeTracked, failsBefore: Bool, failsDuring: Bool, failsAfter: Bool) { if failsBefore { return nil } self.init(x: x, failsDuring: failsDuring) if failsAfter { return nil } } } class TrivialClass : TriviallyConstructible { let tracker: LifetimeTracked // Protocol requirements required init(x: LifetimeTracked) { self.tracker = x } required convenience init(x: LifetimeTracked, throwsDuring: Bool) throws { self.init(x: x) if throwsDuring { throw E.X } } required convenience init?(x: LifetimeTracked, failsDuring: Bool) { self.init(x: x) if failsDuring { return nil } } // Class initializers delegating to protocol initializers convenience init(throwsBefore: Bool) throws { if throwsBefore { throw E.X } self.init(x: LifetimeTracked(0)) } convenience init(throwsAfter: Bool) throws { self.init(x: LifetimeTracked(0)) if throwsAfter { throw E.X } } convenience init(throwsBefore: Bool, throwsDuring: Bool) throws { if throwsBefore { throw E.X } try self.init(x: LifetimeTracked(0), throwsDuring: throwsDuring) } convenience init(throwsBefore: Bool, throwsAfter: Bool) throws { if throwsBefore { throw E.X } self.init(x: LifetimeTracked(0)) if throwsAfter { throw E.X } } convenience init(throwsDuring: Bool, throwsAfter: Bool) throws { try self.init(x: LifetimeTracked(0), throwsDuring: throwsDuring) if throwsAfter { throw E.X } } convenience init(throwsBefore: Bool, throwsDuring: Bool, throwsAfter: Bool) throws { if throwsBefore { throw E.X } try self.init(x: LifetimeTracked(0), throwsDuring: throwsDuring) if throwsAfter { throw E.X } } convenience init?(failsBefore: Bool) { if failsBefore { return nil } self.init(x: LifetimeTracked(0)) } convenience init?(failsAfter: Bool) { self.init(x: LifetimeTracked(0)) if failsAfter { return nil } } convenience init?(failsBefore: Bool, failsDuring: Bool) { if failsBefore { return nil } self.init(x: LifetimeTracked(0), failsDuring: failsDuring) } convenience init?(failsBefore: Bool, failsAfter: Bool) { if failsBefore { return nil } self.init(x: LifetimeTracked(0)) if failsAfter { return nil } } convenience init?(failsDuring: Bool, failsAfter: Bool) { self.init(x: LifetimeTracked(0), failsDuring: failsDuring) if failsAfter { return nil } } convenience init?(failsBefore: Bool, failsDuring: Bool, failsAfter: Bool) { if failsBefore { return nil } self.init(x: LifetimeTracked(0), failsDuring: failsDuring) if failsAfter { return nil } } } ProtocolInitTestSuite.test("ExtensionInit_Success") { _ = try! TrivialClass(x: LifetimeTracked(0), throwsBefore: false) _ = try! TrivialClass(x: LifetimeTracked(0), throwsAfter: false) _ = try! TrivialClass(x: LifetimeTracked(0), throwsBefore: false, throwsDuring: false) _ = try! TrivialClass(x: LifetimeTracked(0), throwsDuring: false, throwsAfter: false) _ = try! TrivialClass(x: LifetimeTracked(0), throwsBefore: false, throwsAfter: false) _ = try! TrivialClass(x: LifetimeTracked(0), throwsBefore: false, throwsDuring: false, throwsAfter: false) _ = TrivialClass(x: LifetimeTracked(0), failsBefore: false)! _ = TrivialClass(x: LifetimeTracked(0), failsAfter: false)! _ = TrivialClass(x: LifetimeTracked(0), failsBefore: false, failsDuring: false)! _ = TrivialClass(x: LifetimeTracked(0), failsDuring: false, failsAfter: false)! _ = TrivialClass(x: LifetimeTracked(0), failsBefore: false, failsAfter: false)! _ = TrivialClass(x: LifetimeTracked(0), failsBefore: false, failsDuring: false, failsAfter: false)! } ProtocolInitTestSuite.test("ClassInit_Success") { _ = try! TrivialClass(throwsBefore: false) _ = try! TrivialClass(throwsAfter: false) _ = try! TrivialClass(throwsBefore: false, throwsDuring: false) _ = try! TrivialClass(throwsDuring: false, throwsAfter: false) _ = try! TrivialClass(throwsBefore: false, throwsAfter: false) _ = try! TrivialClass(throwsBefore: false, throwsDuring: false, throwsAfter: false) _ = TrivialClass(failsBefore: false)! _ = TrivialClass(failsAfter: false)! _ = TrivialClass(failsBefore: false, failsDuring: false)! _ = TrivialClass(failsDuring: false, failsAfter: false)! _ = TrivialClass(failsBefore: false, failsAfter: false)! _ = TrivialClass(failsBefore: false, failsDuring: false, failsAfter: false)! } ProtocolInitTestSuite.test("ExtensionInit_Failure") { mustThrow { try TrivialClass(x: LifetimeTracked(0), throwsBefore: true) } mustThrow { try TrivialClass(x: LifetimeTracked(0), throwsAfter: true) } mustThrow { try TrivialClass(x: LifetimeTracked(0), throwsBefore: true, throwsDuring: false) } mustThrow { try TrivialClass(x: LifetimeTracked(0), throwsBefore: false, throwsDuring: true) } mustThrow { try TrivialClass(x: LifetimeTracked(0), throwsDuring: true, throwsAfter: false) } mustThrow { try TrivialClass(x: LifetimeTracked(0), throwsDuring: false, throwsAfter: true) } mustThrow { try TrivialClass(x: LifetimeTracked(0), throwsBefore: true, throwsAfter: false) } mustThrow { try TrivialClass(x: LifetimeTracked(0), throwsBefore: false, throwsAfter: true) } mustThrow { try TrivialClass(x: LifetimeTracked(0), throwsBefore: true, throwsDuring: false, throwsAfter: false) } mustThrow { try TrivialClass(x: LifetimeTracked(0), throwsBefore: false, throwsDuring: true, throwsAfter: false) } mustThrow { try TrivialClass(x: LifetimeTracked(0), throwsBefore: false, throwsDuring: false, throwsAfter: true) } mustFail { TrivialClass(x: LifetimeTracked(0), failsBefore: true) } mustFail { TrivialClass(x: LifetimeTracked(0), failsAfter: true) } mustFail { TrivialClass(x: LifetimeTracked(0), failsBefore: true, failsDuring: false) } mustFail { TrivialClass(x: LifetimeTracked(0), failsBefore: false, failsDuring: true) } mustFail { TrivialClass(x: LifetimeTracked(0), failsDuring: true, failsAfter: false) } mustFail { TrivialClass(x: LifetimeTracked(0), failsDuring: false, failsAfter: true) } mustFail { TrivialClass(x: LifetimeTracked(0), failsBefore: true, failsAfter: false) } mustFail { TrivialClass(x: LifetimeTracked(0), failsBefore: false, failsAfter: true) } mustFail { TrivialClass(x: LifetimeTracked(0), failsBefore: true, failsDuring: false, failsAfter: false) } mustFail { TrivialClass(x: LifetimeTracked(0), failsBefore: false, failsDuring: true, failsAfter: false) } mustFail { TrivialClass(x: LifetimeTracked(0), failsBefore: false, failsDuring: false, failsAfter: true) } } ProtocolInitTestSuite.test("ClassInit_Failure") { mustThrow { try TrivialClass(throwsBefore: true) } mustThrow { try TrivialClass(throwsAfter: true) } mustThrow { try TrivialClass(throwsBefore: true, throwsDuring: false) } mustThrow { try TrivialClass(throwsBefore: false, throwsDuring: true) } mustThrow { try TrivialClass(throwsDuring: true, throwsAfter: false) } mustThrow { try TrivialClass(throwsDuring: false, throwsAfter: true) } mustThrow { try TrivialClass(throwsBefore: true, throwsAfter: false) } mustThrow { try TrivialClass(throwsBefore: false, throwsAfter: true) } mustThrow { try TrivialClass(throwsBefore: true, throwsDuring: false, throwsAfter: false) } mustThrow { try TrivialClass(throwsBefore: false, throwsDuring: true, throwsAfter: false) } mustThrow { try TrivialClass(throwsBefore: false, throwsDuring: false, throwsAfter: true) } mustFail { TrivialClass(failsBefore: true) } mustFail { TrivialClass(failsAfter: true) } mustFail { TrivialClass(failsBefore: true, failsDuring: false) } mustFail { TrivialClass(failsBefore: false, failsDuring: true) } mustFail { TrivialClass(failsDuring: true, failsAfter: false) } mustFail { TrivialClass(failsDuring: false, failsAfter: true) } mustFail { TrivialClass(failsBefore: true, failsAfter: false) } mustFail { TrivialClass(failsBefore: false, failsAfter: true) } mustFail { TrivialClass(failsBefore: true, failsDuring: false, failsAfter: false) } mustFail { TrivialClass(failsBefore: false, failsDuring: true, failsAfter: false) } mustFail { TrivialClass(failsBefore: false, failsDuring: false, failsAfter: true) } } struct TrivialStruct : TriviallyConstructible { let x: LifetimeTracked init(x: LifetimeTracked) { self.x = x } init(x: LifetimeTracked, throwsDuring: Bool) throws { self.init(x: x) if throwsDuring { throw E.X } } init?(x: LifetimeTracked, failsDuring: Bool) { self.init(x: x) if failsDuring { return nil } } } struct AddrOnlyStruct : TriviallyConstructible { let x: LifetimeTracked let y: Any init(x: LifetimeTracked) { self.x = x self.y = "Hello world" } init(x: LifetimeTracked, throwsDuring: Bool) throws { self.init(x: x) if throwsDuring { throw E.X } } init?(x: LifetimeTracked, failsDuring: Bool) { self.init(x: x) if failsDuring { return nil } } } extension TriviallyConstructible { init(throwsFirst: Bool, throwsSecond: Bool, initThenInit: ()) throws { try self.init(x: LifetimeTracked(0), throwsDuring: throwsFirst) try self.init(x: LifetimeTracked(0), throwsDuring: throwsSecond) } init(throwsFirst: Bool, throwsSecond: Bool, initThenAssign: ()) throws { try self.init(x: LifetimeTracked(0), throwsDuring: throwsFirst) self = try Self(x: LifetimeTracked(0), throwsDuring: throwsSecond) } init(throwsFirst: Bool, throwsSecond: Bool, assignThenInit: ()) throws { self = try Self(x: LifetimeTracked(0), throwsDuring: throwsFirst) try self.init(x: LifetimeTracked(0), throwsDuring: throwsSecond) } init(throwsFirst: Bool, throwsSecond: Bool, assignThenAssign: ()) throws { self = try Self(x: LifetimeTracked(0), throwsDuring: throwsFirst) try self.init(x: LifetimeTracked(0), throwsDuring: throwsSecond) } } ProtocolInitTestSuite.test("Struct_Success") { _ = try! TrivialStruct(throwsFirst: false, throwsSecond: false, initThenInit: ()) _ = try! TrivialStruct(throwsFirst: false, throwsSecond: false, initThenAssign: ()) _ = try! TrivialStruct(throwsFirst: false, throwsSecond: false, assignThenInit: ()) _ = try! TrivialStruct(throwsFirst: false, throwsSecond: false, assignThenAssign: ()) } ProtocolInitTestSuite.test("Struct_Failure") { mustThrow { try TrivialStruct(throwsFirst: true, throwsSecond: false, initThenInit: ()) } mustThrow { try TrivialStruct(throwsFirst: false, throwsSecond: true, initThenInit: ()) } mustThrow { try TrivialStruct(throwsFirst: true, throwsSecond: false, initThenAssign: ()) } mustThrow { try TrivialStruct(throwsFirst: false, throwsSecond: true, initThenAssign: ()) } mustThrow { try TrivialStruct(throwsFirst: true, throwsSecond: false, assignThenInit: ()) } mustThrow { try TrivialStruct(throwsFirst: false, throwsSecond: true, assignThenInit: ()) } mustThrow { try TrivialStruct(throwsFirst: true, throwsSecond: false, assignThenAssign: ()) } mustThrow { try TrivialStruct(throwsFirst: false, throwsSecond: true, assignThenAssign: ()) } } ProtocolInitTestSuite.test("AddrOnlyStruct_Success") { _ = try! AddrOnlyStruct(throwsFirst: false, throwsSecond: false, initThenInit: ()) _ = try! AddrOnlyStruct(throwsFirst: false, throwsSecond: false, initThenAssign: ()) _ = try! AddrOnlyStruct(throwsFirst: false, throwsSecond: false, assignThenInit: ()) _ = try! AddrOnlyStruct(throwsFirst: false, throwsSecond: false, assignThenAssign: ()) } ProtocolInitTestSuite.test("AddrOnlyStruct_Failure") { mustThrow { try AddrOnlyStruct(throwsFirst: true, throwsSecond: false, initThenInit: ()) } mustThrow { try AddrOnlyStruct(throwsFirst: false, throwsSecond: true, initThenInit: ()) } mustThrow { try AddrOnlyStruct(throwsFirst: true, throwsSecond: false, initThenAssign: ()) } mustThrow { try AddrOnlyStruct(throwsFirst: false, throwsSecond: true, initThenAssign: ()) } mustThrow { try AddrOnlyStruct(throwsFirst: true, throwsSecond: false, assignThenInit: ()) } mustThrow { try AddrOnlyStruct(throwsFirst: false, throwsSecond: true, assignThenInit: ()) } mustThrow { try AddrOnlyStruct(throwsFirst: true, throwsSecond: false, assignThenAssign: ()) } mustThrow { try AddrOnlyStruct(throwsFirst: false, throwsSecond: true, assignThenAssign: ()) } } runAllTests()
apache-2.0
e5099a0958ef20eff699ef8d41d6eec6
32.872483
116
0.700614
4.104364
false
false
false
false
eoger/firefox-ios
Client/Frontend/Browser/SimpleToast.swift
1
2712
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import Shared struct SimpleToastUX { static let ToastHeight = BottomToolbarHeight static let ToastAnimationDuration = 0.5 static let ToastDefaultColor = UIColor.Photon.Blue50 static let ToastFont = UIFont.systemFont(ofSize: 15) static let ToastDismissAfter = DispatchTimeInterval.milliseconds(4500) // 4.5 seconds. static let ToastDelayBefore = DispatchTimeInterval.milliseconds(0) // 0 seconds static let ToastPrivateModeDelayBefore = DispatchTimeInterval.milliseconds(750) static let BottomToolbarHeight = CGFloat(45) } struct SimpleToast { func showAlertWithText(_ text: String, bottomContainer: UIView) { let toast = self.createView() toast.text = text bottomContainer.addSubview(toast) toast.snp.makeConstraints { (make) in make.width.equalTo(bottomContainer) make.left.equalTo(bottomContainer) make.height.equalTo(SimpleToastUX.ToastHeight) make.bottom.equalTo(bottomContainer) } animate(toast) } fileprivate func createView() -> UILabel { let toast = UILabel() toast.textColor = UIColor.Photon.White100 toast.backgroundColor = SimpleToastUX.ToastDefaultColor toast.font = SimpleToastUX.ToastFont toast.textAlignment = .center return toast } fileprivate func dismiss(_ toast: UIView) { UIView.animate(withDuration: SimpleToastUX.ToastAnimationDuration, animations: { var frame = toast.frame frame.origin.y = frame.origin.y + SimpleToastUX.ToastHeight frame.size.height = 0 toast.frame = frame }, completion: { finished in toast.removeFromSuperview() } ) } fileprivate func animate(_ toast: UIView) { UIView.animate(withDuration: SimpleToastUX.ToastAnimationDuration, animations: { var frame = toast.frame frame.origin.y = frame.origin.y - SimpleToastUX.ToastHeight frame.size.height = SimpleToastUX.ToastHeight toast.frame = frame }, completion: { finished in let dispatchTime = DispatchTime.now() + SimpleToastUX.ToastDismissAfter DispatchQueue.main.asyncAfter(deadline: dispatchTime, execute: { self.dismiss(toast) }) } ) } }
mpl-2.0
b71fceb4c20a339508b26105ac5b5ef8
36.150685
90
0.634218
5.097744
false
false
false
false
turekj/ReactiveTODO
ReactiveTODOTests/Classes/Logic/Dates/DateResolverSpec.swift
1
986
@testable import ReactiveTODOFramework import Nimble import Quick class DateResolverSpec: QuickSpec { override func spec() { describe("DateResolver") { let sut = DateResolver() it("Should resolve incremental dates") { let firstDate = NSDate(timeIntervalSinceNow: 0) usleep(1) let secondDate = sut.now() usleep(1) let thirdDate = sut.now() usleep(1) let fourhDate = NSDate(timeIntervalSinceNow: 0) expect(firstDate.timeIntervalSince1970) .to(beLessThan(secondDate.timeIntervalSince1970)) expect(secondDate.timeIntervalSince1970) .to(beLessThan(thirdDate.timeIntervalSince1970)) expect(thirdDate.timeIntervalSince1970) .to(beLessThan(fourhDate.timeIntervalSince1970)) } } } }
mit
10de683fb12eccf274862322c1f74ef8
33
69
0.552738
5.602273
false
false
false
false
daniel-barros/TV-Calendar
TV Calendar/RealmCollection<Episode>+filters.swift
1
1907
// // RealmCollection<Episode>+filters.swift // TV Calendar // // Created by Daniel Barros López on 1/18/17. // Copyright © 2017 Daniel Barros. All rights reserved. // import Foundation import RealmSwift extension Episode { enum SortCriterion { case premiereDate, season } } // Convenient filtering and sorting functions to avoid using key path strings elsewhere extension RealmCollection where Element == Episode { func filter(season: Int) -> Results<Element> { return filter("season == \(season)") } func filter(premiereDateAfterOrEqual date: Date) -> Results<Element> { return filter("premiereDate >= %@", date) } func filter(hasPremiereDate: Bool) -> Results<Element> { return filter("premiereDate " + (hasPremiereDate ? "!=" : "==") + " nil") } func filter(premiereDateBefore date: Date) -> Results<Element> { return filter("premiereDate < %@", date) } func filter(premiereDateEquals date: Date) -> Results<Element> { return filter("premiereDate == %@", date) } func filter(hasEventIdentifier: Bool) -> Results<Element> { return filter("eventIdentifier " + (hasEventIdentifier ? "!=" : "==") + "nil") } func filter(isWholeSeasonReleasedOnTheSameDay: Bool) -> Results<Element> { return filter("isWholeSeasonReleasedOnTheSameDay == %@", isWholeSeasonReleasedOnTheSameDay) } func filter(hasTitle: Bool) -> Results<Element> { return filter("title " + (hasTitle ? "!=" : "==") + " nil") } func sorted(by criterion: Episode.SortCriterion, ascending: Bool = true) -> Results<Element> { switch criterion { case .premiereDate: return sorted(byKeyPath: "premiereDate", ascending: ascending) case .season: return sorted(byKeyPath: "season", ascending: ascending) } } }
gpl-3.0
c352fdcf578ec9cb69ce36f77a6a33f3
30.229508
99
0.635171
4.205298
false
false
false
false
codeliling/HXDYWH
dywh/dywh/controllers/ArticleMapViewController.swift
1
4755
// // MapViewController.swift // dywh // // Created by lotusprize on 15/5/22. // Copyright (c) 2015年 geekTeam. All rights reserved. // import UIKit import Haneke class ArticleMapViewController: UIViewController,BMKMapViewDelegate { let cache = Shared.imageCache var mapView:BMKMapView! var articleList:[ArticleModel] = [] var mAPView:MapArticlePanelView! var articleModel:ArticleModel? override func viewDidLoad() { super.viewDidLoad() mapView = BMKMapView() mapView.frame = self.view.frame mapView.mapType = UInt(BMKMapTypeStandard) mapView.zoomLevel = 5 mapView.showMapScaleBar = true mapView.mapScaleBarPosition = CGPointMake(10, 10) mapView.showsUserLocation = true mapView.compassPosition = CGPointMake(self.view.frame.width - 50, 10) mapView.setCenterCoordinate(CLLocationCoordinate2DMake(26.2038,109.8151), animated: true) mapView.delegate = self self.view.addSubview(mapView) mAPView = MapArticlePanelView(frame: CGRectMake(10, UIScreen.mainScreen().bounds.size.height - 300, UIScreen.mainScreen().bounds.size.width - 20, 130), title: "", articleDescription: "") mAPView.backgroundColor = UIColor.whiteColor() mAPView.alpha = 0.8 mAPView.hidden = true mAPView.userInteractionEnabled = true var tapView:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "panelClick:") self.mAPView.addGestureRecognizer(tapView) self.view.addSubview(mAPView) } func mapView(mapView: BMKMapView!, didSelectAnnotationView view: BMKAnnotationView!) { var title:String = view.annotation.title!() for aModle in articleList{ if title == aModle.articleName{ articleModel = aModle } } if (articleModel != nil){ mAPView.hidden = false self.loadImageByUrl(mAPView, url: articleModel!.articleImageUrl!) mAPView.title = articleModel!.articleName mAPView.articleDescription = articleModel!.articleDescription mAPView.setNeedsDisplay() } } func addMapPoint(articleModel:ArticleModel){ var annotation:BMKPointAnnotation = BMKPointAnnotation() annotation.coordinate = CLLocationCoordinate2DMake(Double(articleModel.latitude), Double(articleModel.longitude)); annotation.title = articleModel.articleName mapView.addAnnotation(annotation) articleList.append(articleModel) } func mapView(mapView: BMKMapView!, viewForAnnotation annotation: BMKAnnotation!) -> BMKAnnotationView! { if annotation.isKindOfClass(BMKPointAnnotation.classForCoder()) { var newAnnotationView:BMKPinAnnotationView = BMKPinAnnotationView(annotation: annotation, reuseIdentifier: "articleAnnotation"); newAnnotationView.pinColor = UInt(BMKPinAnnotationColorPurple) newAnnotationView.animatesDrop = true;// 设置该标注点动画显示 newAnnotationView.annotation = annotation; newAnnotationView.image = UIImage(named: "locationIcon") newAnnotationView.frame = CGRectMake(newAnnotationView.frame.origin.x, newAnnotationView.frame.origin.y, 30, 30) newAnnotationView.paopaoView = nil return newAnnotationView } return nil } func mapView(mapView: BMKMapView!, annotationViewForBubble view: BMKAnnotationView!) { } func panelClick(gesture:UIGestureRecognizer){ if articleModel != nil{ var detailViewController:ArticleDetailViewController? = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("ArticleDetail") as? ArticleDetailViewController detailViewController?.articleModel = articleModel self.navigationController?.pushViewController(detailViewController!, animated: true) } } func loadImageByUrl(view:MapArticlePanelView, url:String){ let URL = NSURL(string: url)! let fetcher = NetworkFetcher<UIImage>(URL: URL) cache.fetch(fetcher: fetcher).onSuccess { image in // Do something with image view.imageLayer.contents = image.CGImage } } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) mapView.delegate = self } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) mapView.delegate = nil } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
apache-2.0
9345a107cdf2a38db0ef5e1716cfaacd
37.795082
196
0.672723
5.013771
false
false
false
false
mrdepth/Neocom
Neocom/Neocom/Character/ImplantsRows.swift
2
1627
// // ImplantsRows.swift // Neocom // // Created by Artem Shimanski on 1/21/20. // Copyright © 2020 Artem Shimanski. All rights reserved. // import SwiftUI import Expressible struct ImplantsRows: View { var implants: [Int] @Environment(\.managedObjectContext) private var managedObjectContext var body: some View { let implants = self.implants.compactMap { try? self.managedObjectContext.from(SDEInvType.self).filter(/\SDEInvType.typeID == Int32($0)).first() } .map {(type: $0, slot: $0[SDEAttributeID.implantness]?.value ?? 100)} .sorted{$0.slot < $1.slot} .map{$0.type} return Group { if implants.isEmpty { Text("No Implants").foregroundColor(.secondary).frame(maxWidth: .infinity) } else { ForEach(implants, id: \.objectID) { i in ImplantTypeCell(implant: i) } } } } } #if DEBUG struct ImplantsRows_Previews: PreviewProvider { static var previews: some View { let implant = try? Storage.testStorage.persistentContainer.viewContext .from(SDEInvType.self) .filter((/\SDEInvType.attributes).subquery(/\SDEDgmTypeAttribute.attributeType?.attributeID == SDEAttributeID.intelligenceBonus.rawValue).count > 0) .first() return List { Section(header: Text("IMPLANTS")) { ImplantsRows(implants: [Int(implant!.typeID)]) } }.listStyle(GroupedListStyle()) .modifier(ServicesViewModifier.testModifier()) } } #endif
lgpl-2.1
18edfdcff98b3d15a0e082828a750fb1
30.882353
160
0.603936
4.467033
false
false
false
false
tmandry/Swindler
SwindlerTests/FakeSpec.swift
1
12527
import Cocoa import Quick import Nimble @testable import Swindler import AXSwift import PromiseKit class FakeSpec: QuickSpec { override func spec() { describe("FakeWindow") { var fake: FakeWindow! beforeEach { waitUntil { done in FakeState.initialize() .then { FakeApplicationBuilder(parent: $0).build() } .then { FakeWindowBuilder(parent: $0) .setTitle("I'm a test window") .setPosition(CGPoint(x: 100, y: 100)) .build() }.done { fw -> () in fake = fw done() }.cauterize() } } it("builds with the requested properties") { expect(fake.title).to(equal("I'm a test window")) expect(fake.frame.origin).to(equal(CGPoint(x: 100, y: 100))) expect(fake.window.title.value).to(equal("I'm a test window")) expect(fake.window.frame.value.origin).to(equal(CGPoint(x: 100, y: 100))) expect(fake.isMinimized).to(beFalse()) expect(fake.isFullscreen).to(beFalse()) } it("sees changes from Swindler") { fake.window.frame.value.origin = CGPoint(x: 99, y: 100) expect(fake.frame.origin).toEventually(equal(CGPoint(x: 99, y: 100))) fake.window.size.value = CGSize(width: 1111, height: 2222) expect(fake.frame.size).toEventually(equal(CGSize(width: 1111, height: 2222))) fake.window.isMinimized.value = true expect(fake.isMinimized).toEventually(beTrue()) fake.window.isMinimized.value = false expect(fake.isMinimized).toEventually(beFalse()) fake.window.isFullscreen.value = true expect(fake.isFullscreen).toEventually(beTrue()) } it("publishes changes to Swindler") { fake.title = "My title changes" expect(fake.window.title.value).toEventually(equal("My title changes")) fake.frame.origin = CGPoint(x: 200, y: 200) expect(fake.window.frame.value.origin).toEventually(equal(CGPoint(x: 200, y: 200))) fake.frame.size = CGSize(width: 3333, height: 4444) expect(fake.window.size.value).toEventually(equal(CGSize(width: 3333, height: 4444))) fake.isMinimized = true expect(fake.window.isMinimized.value).toEventually(beTrue()) fake.isMinimized = false expect(fake.window.isMinimized.value).toEventually(beFalse()) fake.isFullscreen = true expect(fake.window.isFullscreen.value).toEventually(beTrue()) } } describe("FakeApplication") { var fakeState: FakeState! var fakeApp: FakeApplication! var fakeWindow1: FakeWindow! var fakeWindow2: FakeWindow! beforeEach { waitUntil { done in FakeState.initialize() .map { fakeState = $0 } .then { FakeApplicationBuilder(parent: fakeState).build() } .map { fakeApp = $0 } .then { FakeWindowBuilder(parent: fakeApp).build() } .map { fakeWindow1 = $0 } .then { FakeWindowBuilder(parent: fakeApp).build() } .map { fakeWindow2 = $0 } .done { done() } .cauterize() } } it("sees changes from Swindler") { fakeApp.application.mainWindow.value = fakeWindow1.window expect(fakeApp.mainWindow).toEventually(equal(fakeWindow1)) fakeApp.application.mainWindow.value = fakeWindow2.window expect(fakeApp.mainWindow).toEventually(equal(fakeWindow2)) assert(fakeApp.isHidden == false) fakeApp.application.isHidden.value = true expect(fakeApp.isHidden).toEventually(equal(true)) } it("publishes changes to Swindler") { fakeApp.mainWindow = fakeWindow1 expect(fakeApp.application.mainWindow.value).toEventually(equal(fakeWindow1.window)) fakeApp.mainWindow = fakeWindow2 expect(fakeApp.application.mainWindow.value).toEventually(equal(fakeWindow2.window)) fakeApp.focusedWindow = fakeWindow1 expect( fakeApp.application.focusedWindow.value ).toEventually(equal(fakeWindow1.window)) fakeApp.focusedWindow = fakeWindow2 expect( fakeApp.application.focusedWindow.value ).toEventually(equal(fakeWindow2.window)) assert(fakeApp.application.isHidden.value == false) fakeApp.isHidden = true expect(fakeApp.application.isHidden.value).toEventually(equal(true)) } it("changes are mirrored in the Application object returned by Swindler State") { fakeApp.application.mainWindow.value = fakeWindow1.window expect(fakeState.state.runningApplications[0].mainWindow.value).toEventually(equal(fakeWindow1.window)) fakeApp.application.mainWindow.value = fakeWindow2.window expect(fakeState.state.runningApplications[0].mainWindow.value).toEventually(equal(fakeWindow2.window)) } it("updates focusedWindow when mainWindow changes") { fakeApp.mainWindow = fakeWindow1 expect(fakeApp.application.mainWindow.value).toEventually(equal(fakeWindow1.window)) expect(fakeApp.application.focusedWindow.value).toEventually(equal(fakeWindow1.window)) fakeApp.mainWindow = fakeWindow2 expect(fakeApp.application.mainWindow.value).toEventually(equal(fakeWindow2.window)) expect(fakeApp.application.focusedWindow.value).toEventually(equal(fakeWindow2.window)) } it("emits events when new windows are created") { () -> Promise<()> in var events: [WindowCreatedEvent] = [] fakeState.state.on { (event: WindowCreatedEvent) in events.append(event) } return FakeWindowBuilder(parent: fakeApp) .build() .done { win in expect(events).to(haveCount(1)) expect(events.first!.window).to(equal(win.window)) } } } describe("FakeState") { context("") { var fakeState: FakeState! var fakeScreen: FakeScreen! var fakeApp1: FakeApplication! var fakeApp2: FakeApplication! beforeEach { waitUntil { done in fakeScreen = FakeScreen() FakeState.initialize(screens: [fakeScreen]) .map { fakeState = $0 } .then { FakeApplicationBuilder(parent: fakeState).build() } .map { fakeApp1 = $0 } .then { FakeApplicationBuilder(parent: fakeState).build() } .map { fakeApp2 = $0 } .done { done() } .cauterize() } } it("sees changes from Swindler objects") { fakeState.state.frontmostApplication.value = fakeApp1.application expect(fakeState.frontmostApplication).toEventually(equal(fakeApp1)) fakeState.state.frontmostApplication.value = fakeApp2.application expect(fakeState.frontmostApplication).toEventually(equal(fakeApp2)) } it("publishes changes to Swindler objects") { fakeState.frontmostApplication = fakeApp1 expect(fakeState.state.frontmostApplication.value).toEventually( equal(fakeApp1.application)) fakeState.frontmostApplication = fakeApp2 expect(fakeState.state.frontmostApplication.value).toEventually( equal(fakeApp2.application)) let newSpace = fakeState.newSpaceId expect(fakeScreen.spaceId) != newSpace fakeScreen.spaceId = newSpace expect(fakeState.state.screens.first!.spaceId).toEventually(equal(newSpace)) } } context("") { var fakeState: FakeState! var fakeApp: FakeApplication! beforeEach { waitUntil { done in FakeState.initialize() .map { fakeState = $0 } .then { FakeApplicationBuilder(parent: fakeState).build() } .map { fakeApp = $0 } .done { done() } .cauterize() } } it("registers objects with Swindler state") { let app = fakeState.state.runningApplications[0] expect(fakeApp.isHidden).to(beFalse()) expect(app.isHidden.value).to(beFalse()) fakeApp.isHidden = true expect(fakeApp.isHidden).to(beTrue()) expect(app.isHidden.value).toEventually(beTrue()) } it("emits events when new applications are created") { () -> Promise<()> in var events: [ApplicationLaunchedEvent] = [] fakeState.state.on { (event: ApplicationLaunchedEvent) in events.append(event) } return FakeApplicationBuilder(parent: fakeState) .build() .done { app in expect(events).to(haveCount(1)) expect(events.first!.application).to(equal(app.application)) } } } } describe("spaces") { var fakeState: FakeState! beforeEach { waitUntil { done in FakeState.initialize() .map { fakeState = $0 } .then { FakeApplicationBuilder(parent: fakeState).build() } .asVoid() .done { done() } .cauterize() } } it("can be set") { var beforeEvents: [SpaceWillChangeEvent] = [] fakeState.state.on { (event: SpaceWillChangeEvent) in beforeEvents.append(event) } var afterEvents: [SpaceDidChangeEvent] = [] fakeState.state.on { (event: SpaceDidChangeEvent) in afterEvents.append(event) } let spaceA = fakeState.mainScreen!.spaceId let spaceB = fakeState.newSpaceId expect(spaceA) != spaceB fakeState.mainScreen!.spaceId = spaceB expect(fakeState.mainScreen!.screen.spaceId).toEventually(equal(spaceB)) expect(afterEvents).toEventually(haveCount(1)) expect(beforeEvents).to(haveCount(1)) expect(beforeEvents[0].ids) == [spaceB] expect(afterEvents[0].ids) == [spaceB] beforeEvents = [] afterEvents = [] fakeState.mainScreen!.spaceId = spaceA expect(fakeState.mainScreen!.screen.spaceId).toEventually(equal(spaceA)) expect(afterEvents).toEventually(haveCount(1)) expect(beforeEvents).to(haveCount(1)) expect(beforeEvents[0].ids) == [spaceA] expect(afterEvents[0].ids) == [spaceA] } } } }
mit
0164c3af40bdc66469c49924f02a24d2
43.580071
119
0.513531
5.174308
false
false
false
false
Restofire/Restofire
Sources/Configuration/Retry.swift
1
838
// // Retry.swift // Restofire // // Created by Rahul Katariya on 23/04/16. // Copyright © 2016 Restofire. All rights reserved. // import Foundation /// A Retry for RESTful Services. /// /// ```swift /// var retry = Retry() /// retry.retryErrorCodes = [.timedOut,.networkConnectionLost] /// retry.retryInterval = 20 /// retry.maxRetryAttempts = 10 /// ``` public struct Retry { /// The default retry. public static var `default` = Retry() /// The retry error codes. `empty` by default. public var retryErrorCodes: Set<URLError.Code> = [] /// The retry interval. `10` by default. public var retryInterval: TimeInterval = 10 /// The max retry attempts. `5` by default. public var maxRetryAttempts = 5 /// `Retry` Intializer /// /// - returns: new `Retry` object public init() {} }
mit
16ea5c635dec6489119d9189b74da5aa
22.25
62
0.635603
3.893023
false
false
false
false
Wakup/Wakup-iOS-SDK
Wakup/UIViewController+CouponUtils.swift
1
2014
// // UIViewController+CouponUtils.swift // Wuakup // // Created by Guillermo Gutiérrez on 20/02/15. // Copyright (c) 2015 Yellow Pineapple. All rights reserved. // import Foundation import SDWebImage public extension UIViewController { func showMap(forOffer offer: Coupon) { let mapVC = WakupManager.manager.mapController(for: offer) self.navigationController?.pushViewController(mapVC, animated: true) } @objc func shareTextImageAndURL(sharingText: String?, sharingImage: UIImage?, sharingURL: URL?) { var sharingItems = [AnyObject]() if let text = sharingText { sharingItems.append(text as AnyObject) } if let image = sharingImage { sharingItems.append(image) } if let url = sharingURL { sharingItems.append(url as AnyObject) } let activityViewController = UIActivityViewController(activityItems: sharingItems, applicationActivities: nil) activityViewController.excludedActivityTypes = [UIActivity.ActivityType.addToReadingList, UIActivity.ActivityType.print, UIActivity.ActivityType.assignToContact] self.present(activityViewController, animated: true, completion: nil) } @objc func shareTextImageAndURL(text: String?, imageURL: URL?, linkURL: URL?, loadingProtocol: LoadingViewProtocol) { if let imageUrl = imageURL { loadingProtocol.showLoadingView(animated: true) SDWebImageManager.shared.imageLoader.requestImage(with: imageUrl, options: .highPriority, context: nil, progress: nil, completed: { (image, data, error, finished) in loadingProtocol.dismissLoadingView(animated: true, completion: { self.shareTextImageAndURL(sharingText: text, sharingImage: image, sharingURL: linkURL) }) }) } else { self.shareTextImageAndURL(sharingText: text, sharingImage: nil, sharingURL: linkURL) } } }
mit
001849286a5c7d05a4becdd57b66e5a6
40.081633
177
0.675112
4.933824
false
false
false
false
KrishMunot/swift
test/TypeCoercion/unknowable.swift
10
1566
// RUN: %target-parse-verify-swift //===----------------------------------------------------------------------===// // Refer to members of literals //===----------------------------------------------------------------------===// func testLiteralMembers() { _ = 0._value Int(0._value) // expected-warning{{unused}} } //===----------------------------------------------------------------------===// // Overloading with literals //===----------------------------------------------------------------------===// func ovlLitA(_: Int32) -> Int32 {} func ovlLitA(_: Int64) -> Int64 {} func ovlLitB(_: Int32) -> Int32 {} // expected-note{{}} func ovlLitB(_: Int64) -> Int64 {} // expected-note{{}} func testLiteralOverloadingovlLitB() { var y32 : Int32 = ovlLitA(ovlLitB(0)) var y64 : Int64 = ovlLitA(ovlLitB(0)) var y /*: Int*/ = ovlLitA(ovlLitB(0)) // expected-error{{ambiguous use of 'ovlLitB'}} } func literalOverloadSameReturn(_ i: Int) -> Int {} func literalOverloadSameReturn(_ i: Int32) -> Int {} func literalOverload2() { var _ : Int = literalOverloadSameReturn(literalOverloadSameReturn(1)) } //===----------------------------------------------------------------------===// // Literals and protocols //===----------------------------------------------------------------------===// protocol CanWibble { func wibble() } extension Int : CanWibble { func wibble() {} } func doWibble(_: CanWibble) {} func testWibble() { doWibble(1) doWibble(3.14) // expected-error{{argument type 'Double' does not conform to expected type 'CanWibble'}} }
apache-2.0
b4d3f0482df23e5b899c18d9c092ed3c
31.625
106
0.466794
4.578947
false
true
false
false
jlyu/swift-demo
HypnoTime/HypnoTime/AppDelegate.swift
1
2852
// // AppDelegate.swift // HypnoTime // // Created by chain on 14-6-21. // Copyright (c) 2014 chain. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool { application.setStatusBarHidden(true, animated: true) self.window = UIWindow(frame: UIScreen.mainScreen().bounds) var hypnoViewContrller: HypnosisViewController = HypnosisViewController() var timeViewController: TimeViewController = TimeViewController() var tabBarController: UITabBarController = UITabBarController() var viewControllers = [hypnoViewContrller, timeViewController] tabBarController.setViewControllers(viewControllers, animated: true) self.window!.rootViewController = tabBarController //timeViewController //hypnoViewContrller self.window!.backgroundColor = UIColor.whiteColor() self.window!.makeKeyAndVisible() return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
8eb803ffd6172a07ee7c0c504afcd6d5
45
285
0.730365
5.761616
false
false
false
false
Dibel/androidtool-mac
AndroidTool/AppDelegate.swift
1
7623
// // AppDelegate.swift // AndroidTool // // Created by Morten Just Petersen on 4/22/15. // Copyright (c) 2015 Morten Just Petersen. All rights reserved. // import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { @IBOutlet weak var window: NSWindow! @IBOutlet weak var scriptsMenu: NSMenu! var preferencesWindowController: PreferencesWindowController! var masterViewController: MasterViewController! func applicationDidFinishLaunching(aNotification: NSNotification) { checkForUpdate() updateScriptFilesInMenu() checkForPreferences() if !Util().isMavericks() { window.movableByWindowBackground = true if #available(OSX 10.10, *) { window.titleVisibility = NSWindowTitleVisibility.Hidden window.titlebarAppearsTransparent = true; window.styleMask |= NSFullSizeContentViewWindowMask; } else { // Fallback on earlier versions } } masterViewController = MasterViewController(nibName: "MasterViewController", bundle: nil) masterViewController.window = window window.contentView!.addSubview(masterViewController.view) //masterViewController.view.frame = window.contentView.bounds var insertedView = masterViewController.view var containerView = window.contentView as NSView! insertedView.translatesAutoresizingMaskIntoConstraints = false let viewDict = ["inserted":insertedView, "container":containerView] let viewConstraintH = NSLayoutConstraint.constraintsWithVisualFormat( "H:|[inserted]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewDict) let viewConstraintV = NSLayoutConstraint.constraintsWithVisualFormat( "V:|[inserted]|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewDict) containerView.addConstraints(viewConstraintH) containerView.addConstraints(viewConstraintV) } func application(sender: NSApplication, openFile filename: String) -> Bool { print("opening \(filename). If it's an APK we'll show a list of devices") masterViewController.installApk(filename) return true } @IBAction func revealFolderClicked(sender: NSMenuItem) { Util().revealScriptsFolder() } func checkForPreferences(){ let ud = NSUserDefaults.standardUserDefaults() let bitratePref = ud.doubleForKey("bitratePref") let scalePref = ud.doubleForKey("scalePref") print("bit: \(bitratePref)") if bitratePref == 0.0 { ud.setDouble(Double(3025000), forKey: "bitratePref") } if scalePref == 0.0 { ud.setDouble(1, forKey: "scalePref") } } // populate nsmenu with all scripts // run this script on all devices func updateScriptFilesInMenu(){ scriptsMenu.removeAllItems() let screenshotItem = NSMenuItem(title: "Screenshots", action: "screenshotsOfAllTapped:", keyEquivalent: "S") let sepItem = NSMenuItem.separatorItem() let sepItem2 = NSMenuItem.separatorItem() let revealFolderItem = NSMenuItem(title: "Reveal Scripts Folder", action: "revealFolderClicked:", keyEquivalent: "F") scriptsMenu.addItem(screenshotItem) scriptsMenu.addItem(sepItem) let supportDir = Util().getSupportFolderScriptPath() let scriptFiles = Util().getFilesInScriptFolder(supportDir)! var i = 0 for scriptFile in scriptFiles { // for scripts 0..9, add a keyboard shortcut var keyEq = "" if i<10 { keyEq = "\(i)" } let scriptItem = NSMenuItem(title: scriptFile.stringByReplacingOccurrencesOfString(".sh", withString: ""), action: "runScript:", keyEquivalent: keyEq) scriptsMenu.addItem(scriptItem) i++ } scriptsMenu.addItem(sepItem2) scriptsMenu.addItem(revealFolderItem) } func runScript(sender:NSMenuItem){ Util().stopRefreshingDeviceList() let scriptPath = "\(Util().getSupportFolderScriptPath())/\(sender.title).sh" print("ready to run \(scriptPath) on all Android devices") let deviceVCs = masterViewController.deviceVCs for deviceVC in deviceVCs { if deviceVC.device.deviceOS == DeviceOS.Android { let adbIdentifier = deviceVC.device.adbIdentifier! deviceVC.startProgressIndication() ShellTasker(scriptFile: scriptPath).run(arguments: ["\(adbIdentifier)"], isUserScript: true) { (output) -> Void in deviceVC.stopProgressIndication() } } } Util().restartRefreshingDeviceList() } @IBAction func screenshotsOfAllTapped(sender: NSMenuItem) { // TODO:clicked, not tapped Util().stopRefreshingDeviceList() let deviceVCs = masterViewController.deviceVCs for deviceVC in deviceVCs { deviceVC.takeScreenshot() } Util().restartRefreshingDeviceList() } func checkForUpdate(){ dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) { let url = NSURL(string: "http://mortenjust.com/androidtool/latestversion") if let version = try? NSString(contentsOfURL: url!, encoding: NSUTF8StringEncoding) { let nsu = NSUserDefaults.standardUserDefaults() let knowsAboutNewVersion = nsu.boolForKey("UserKnowsAboutNewVersion") dispatch_async(dispatch_get_main_queue()) { let currentVersion = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as! String if (currentVersion != version) && !knowsAboutNewVersion { // var alert = NSAlert() // alert.messageText = "An update is available! Go to mortenjust.com/androidtool to download" // alert.runModal() nsu.setObject(true, forKey: "UserKnowsAboutNewVersion") } } } } } func applicationWillResignActive(notification: NSNotification) { masterViewController.discoverer.updateInterval = 120 } @IBAction func refreshDeviceListClicked(sender: NSMenuItem) { masterViewController.discoverer.pollDevices() } @IBAction func showLogFileClicked(sender: NSMenuItem) { } @IBAction func preferencesClicked(sender: NSMenuItem) { print("pref") preferencesWindowController = PreferencesWindowController(windowNibName: "PreferencesWindowController") preferencesWindowController.showWindow(sender) } func applicationDidBecomeActive(notification: NSNotification) { // Util().restartRefreshingDeviceList() masterViewController.discoverer.updateInterval = 3 updateScriptFilesInMenu() masterViewController.discoverer.pollDevices() } func applicationWillTerminate(aNotification: NSNotification) { // Insert code here to tear down your application } }
apache-2.0
fc63758ec1f342a67ebdefdbde9b2eea
34.291667
162
0.623901
5.58871
false
false
false
false
danilotorrisi/SyncthingKit
Sources/Syncthing.swift
1
1244
// // Syncthing.swift // Syncthing-Finder // // Created by Danilo Torrisi on 18/01/15. // Copyright (c) 2015 Danilo Torrisi. All rights reserved. // import Foundation import Alamofire import BrightFutures import SwiftyJSON public struct Syncthing { /** The address used to establish a connection with the Syncthing REST API. Default: localhost. */ static public var address: String = "localhost" /** The port used to establish a connection with the Syncthing REST API. Default: 8080. */ static public var port: UInt16 = 8080 /** Returns a future JSON object obtained by a GET request to the Syncthing API on the given action passing the given data. */ public static func get(action: String, parameters: [String: NSObject] = [:]) -> Future<JSON> { let promise = Promise<JSON>() // Send a GET request. request(.GET, "http://\(address):\(port)/rest/\(action)", parameters: parameters).responseSwiftyJSON { (_, _, res, error) in // Return the promise success or failure. if let anError = error { promise.failure(anError) } else { promise.success(res) } } return promise.future } }
mit
d865d4a003d3968ffff56d1f8c344ef5
28.642857
132
0.634244
4.289655
false
false
false
false
GYLibrary/A_Y_T
GYVideo/Pods/EZPlayer/EZPlayer/EZPlayerControlView.swift
1
15647
// // EZPlayerControlView.swift // EZPlayer // // Created by yangjun zhu on 2016/12/28. // Copyright © 2016年 yangjun zhu. All rights reserved. // import UIKit import AVFoundation import MediaPlayer open class EZPlayerControlView: UIView{ weak public var player: EZPlayer?{ didSet{ player?.setControlsHidden(false, animated: true) self.autohideControlView() } } // open var tapGesture: UITapGestureRecognizer! var hideControlViewTask: Task? public var autohidedControlViews = [UIView]() // var controlsHidden = false @IBOutlet weak var navBarContainer: UIView! @IBOutlet weak var navBarContainerTopConstraint: NSLayoutConstraint! @IBOutlet weak var toolBarContainer: UIView! @IBOutlet weak var timeLabel: UILabel! @IBOutlet weak var progressView: UIProgressView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var playPauseButton: UIButton! @IBOutlet weak var fullEmbeddedScreenButton: UIButton! @IBOutlet weak var fullEmbeddedScreenButtonWidthConstraint: NSLayoutConstraint! @IBOutlet weak var timeSlider: UISlider! @IBOutlet weak var videoshotPreview: UIView! @IBOutlet weak var videoshotPreviewLeadingConstraint: NSLayoutConstraint! @IBOutlet weak var videoshotImageView: UIImageView! @IBOutlet weak var loading: EZPlayerLoading! @IBOutlet weak var audioSubtitleCCButtonWidthConstraint: NSLayoutConstraint! @IBOutlet weak var airplayContainer: UIView! // MARK: - Life cycle deinit { } override open func awakeFromNib() { super.awakeFromNib() self.timeSlider.value = 0 self.progressView.progress = 0 self.progressView.progressTintColor = UIColor.yellow self.progressView.trackTintColor = UIColor.clear self.progressView.backgroundColor = UIColor.clear self.videoshotPreview.isHidden = true self.audioSubtitleCCButtonWidthConstraint.constant = 0 self.autohidedControlViews = [self.navBarContainer,self.toolBarContainer] // self.tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.tapGestureTapped(_:))) // self.tapGesture.delegate = self // self.addGestureRecognizer(self.tapGesture) let airplayImage = UIImage(named: "btn_airplay", in: Bundle(for: EZPlayerControlView.self),compatibleWith: nil) let airplayView = MPVolumeView(frame: self.airplayContainer.bounds) airplayView.showsVolumeSlider = false airplayView.showsRouteButton = true airplayView.setRouteButtonImage(airplayImage, for: .normal) self.airplayContainer.addSubview(airplayView) // self.loading.start() } // MARK: - EZPlayerCustomControlView fileprivate var isProgressSliderSliding = false { didSet{ if !(self.player?.isM3U8 ?? true) { // self.videoshotPreview.isHidden = !isProgressSliderSliding } } } @IBAction func progressSliderTouchBegan(_ sender: Any) { guard let player = self.player else { return } self.player(player, progressWillChange: TimeInterval(self.timeSlider.value)) } @IBAction func progressSliderValueChanged(_ sender: Any) { guard let player = self.player else { return } self.player(player, progressChanging: TimeInterval(self.timeSlider.value)) if !player.isM3U8 { self.videoshotPreview.isHidden = false player.generateThumbnails(times: [ TimeInterval(self.timeSlider.value)],maximumSize:CGSize(width: self.videoshotImageView.bounds.size.width, height: self.videoshotImageView.bounds.size.height)) { (thumbnails) in let trackRect = self.timeSlider.convert(self.timeSlider.bounds, to: nil) let thumbRect = self.timeSlider.thumbRect(forBounds: self.timeSlider.bounds, trackRect: trackRect, value: self.timeSlider.value) var lead = thumbRect.origin.x + thumbRect.size.width/2 - self.videoshotPreview.bounds.size.width/2 if lead < 0 { lead = 0 }else if lead + self.videoshotPreview.bounds.size.width > player.view.bounds.width { lead = player.view.bounds.width - self.videoshotPreview.bounds.size.width } self.videoshotPreviewLeadingConstraint.constant = lead if thumbnails.count > 0 { let thumbnail = thumbnails[0] if thumbnail.result == .succeeded { self.videoshotImageView.image = thumbnail.image } } } } } @IBAction func progressSliderTouchEnd(_ sender: Any) { self.videoshotPreview.isHidden = true guard let player = self.player else { return } self.player(player, progressDidChange: TimeInterval(self.timeSlider.value)) } // public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool{ // self.autohideControlView() // return !self.autohidedControlViews.contains(touch.view!) && !self.autohidedControlViews.contains(touch.view!.superview!) // // return true // } // // MARK: - private // @objc fileprivate func tapGestureTapped(_ sender: UIGestureRecognizer) { // guard let player = self.player else { // return // } // player.controlsHidden = !player.controlsHidden // } fileprivate func hideControlView(_ animated: Bool) { // if self.controlsHidden == true{ // return // } if animated{ UIView.setAnimationsEnabled(false) UIView.animate(withDuration: ezAnimatedDuration, delay: 0,options: .curveEaseInOut, animations: { self.autohidedControlViews.forEach{ $0.alpha = 0 } }, completion: {finished in self.autohidedControlViews.forEach{ $0.isHidden = true } UIView.setAnimationsEnabled(true) }) }else{ self.autohidedControlViews.forEach{ $0.alpha = 0 $0.isHidden = true } } } fileprivate func showControlView(_ animated: Bool) { // if self.controlsHidden == false{ // return // } if animated{ UIView.setAnimationsEnabled(false) self.autohidedControlViews.forEach{ $0.isHidden = false } UIView.animate(withDuration: ezAnimatedDuration, delay: 0,options: .curveEaseInOut, animations: { if self.player?.displayMode == .fullscreen{ self.navBarContainerTopConstraint.constant = 20 }else{ self.navBarContainerTopConstraint.constant = 0 } self.autohidedControlViews.forEach{ $0.alpha = 1 } }, completion: {finished in self.autohideControlView() UIView.setAnimationsEnabled(true) }) }else{ self.autohidedControlViews.forEach{ $0.isHidden = false $0.alpha = 1 } if self.player?.displayMode == .fullscreen{ self.navBarContainerTopConstraint.constant = 20 }else{ self.navBarContainerTopConstraint.constant = 0 } self.autohideControlView() } } fileprivate func autohideControlView(){ guard let player = self.player , player.autohiddenTimeInterval > 0 else { return } cancel(self.hideControlViewTask) self.hideControlViewTask = delay(5, task: { [weak self] in guard let weakSelf = self else { return } // weakSelf.hideControlView() weakSelf.player?.setControlsHidden(true, animated: true) }) } } extension EZPlayerControlView: EZPlayerCustom { // MARK: - EZPlayerCustomAction @IBAction public func playPauseButtonPressed(_ sender: Any) { guard let player = self.player else { return } if player.isPlaying { player.pause() }else{ player.play() } } @IBAction public func fullEmbeddedScreenButtonPressed(_ sender: Any) { guard let player = self.player else { return } switch player.displayMode { case .embedded: player.toFull() case .fullscreen: if player.lastDisplayMode == .embedded{ player.toEmbedded() }else if player.lastDisplayMode == .float{ player.toFloat() } default: break } } @IBAction public func audioSubtitleCCButtonPressed(_ sender: Any) { guard let player = self.player else { return } let audibleLegibleViewController = EZPlayerAudibleLegibleViewController(nibName: String(describing: EZPlayerAudibleLegibleViewController.self),bundle: Bundle(for: EZPlayerAudibleLegibleViewController.self),player:player, sourceView:sender as? UIView) EZPlayerUtils.viewController(from: self)?.present(audibleLegibleViewController, animated: true, completion: { }) } @IBAction public func backButtonPressed(_ sender: Any) { guard let player = self.player else { return } let displayMode = player.displayMode if displayMode == .fullscreen { if player.lastDisplayMode == .embedded{ player.toEmbedded() }else if player.lastDisplayMode == .float{ player.toFloat() } } player.backButtonBlock?(displayMode) } // MARK: - EZPlayerGestureRecognizer public func player(_ player: EZPlayer, singleTapGestureTapped singleTap: UITapGestureRecognizer) { player.setControlsHidden(!player.controlsHidden, animated: true) } public func player(_ player: EZPlayer, doubleTapGestureTapped doubleTap: UITapGestureRecognizer) { self.playPauseButtonPressed(doubleTap) } // MARK: - EZPlayerHorizontalPan public func player(_ player: EZPlayer, progressWillChange value: TimeInterval) { if player.isLive ?? true{ return } cancel(self.hideControlViewTask) self.isProgressSliderSliding = true } public func player(_ player: EZPlayer, progressChanging value: TimeInterval) { if player.isLive ?? true{ return } self.timeLabel.text = EZPlayerUtils.formatTime(position: value, duration: self.player?.duration ?? 0) if !self.timeSlider.isTracking { self.timeSlider.value = Float(value) } } public func player(_ player: EZPlayer, progressDidChange value: TimeInterval) { if player.isLive ?? true{ return } self.autohideControlView() // self.isProgressSliderSliding = false self.player?.seek(to: value, completionHandler: { (isFinished) in self.isProgressSliderSliding = false }) } // MARK: - EZPlayerDelegate public func playerHeartbeat(_ player: EZPlayer) { if let asset = player.playerasset, let playerIntem = player.playerItem ,playerIntem.status == .readyToPlay{ if asset.audios != nil || asset.subtitles != nil || asset.closedCaption != nil{ self.audioSubtitleCCButtonWidthConstraint.constant = 50 }else{ self.audioSubtitleCCButtonWidthConstraint.constant = 0 } } self.airplayContainer.isHidden = !player.allowsExternalPlayback } public func player(_ player: EZPlayer, playerDisplayModeDidChange displayMode: EZPlayerDisplayMode) { switch displayMode { case .none: break case .embedded: self.fullEmbeddedScreenButtonWidthConstraint.constant = 50 self.fullEmbeddedScreenButton.setImage(UIImage(named: "btn_fullscreen22x22", in: Bundle(for: EZPlayerControlView.self), compatibleWith: nil), for: .normal) case .fullscreen: self.fullEmbeddedScreenButtonWidthConstraint.constant = 50 self.fullEmbeddedScreenButton.setImage(UIImage(named: "btn_normalscreen22x22", in: Bundle(for: EZPlayerControlView.self), compatibleWith: nil), for: .normal) if player.lastDisplayMode == .none{ self.fullEmbeddedScreenButtonWidthConstraint.constant = 0 } case .float: break } } public func player(_ player: EZPlayer, playerStateDidChange state: EZPlayerState) { //播放器按钮状态 switch state { case .playing ,.buffering: //播放状态 // self.playPauseButton.isSelected = true //暂停按钮 self.playPauseButton.setImage(UIImage(named: "btn_pause22x22", in: Bundle(for: EZPlayerControlView.self), compatibleWith: nil), for: .normal) case .seekingBackward ,.seekingForward: break default: // self.playPauseButton.isSelected = false // 播放按钮 self.playPauseButton.setImage(UIImage(named: "btn_play22x22", in: Bundle(for: EZPlayerControlView.self), compatibleWith: nil), for: .normal) } // switch state { // case .playing ,.pause,.seekingForward,.seekingBackward,.stopped,.bufferFinished: // self.loading.stop() // break // default: // self.loading.start() // break // } } public func player(_ player: EZPlayer, bufferDurationDidChange bufferDuration: TimeInterval, totalDuration: TimeInterval) { if totalDuration.isNaN || bufferDuration.isNaN || totalDuration == 0 || bufferDuration == 0{ self.progressView.progress = 0 }else{ self.progressView.progress = Float(bufferDuration/totalDuration) } } public func player(_ player: EZPlayer, currentTime: TimeInterval, duration: TimeInterval) { if currentTime.isNaN { return } self.timeSlider.isEnabled = !duration.isNaN self.timeSlider.minimumValue = 0 self.timeSlider.maximumValue = duration.isNaN ? Float(currentTime) : Float(duration) self.titleLabel.text = player.contentItem?.title ?? player.playerasset?.title if !self.isProgressSliderSliding { self.timeSlider.value = Float(currentTime) self.timeLabel.text = duration.isNaN ? "Live" : EZPlayerUtils.formatTime(position: currentTime, duration: duration) } } public func player(_ player: EZPlayer, playerControlsHiddenDidChange controlsHidden: Bool, animated: Bool) { if controlsHidden { self.hideControlView(animated) }else{ self.showControlView(animated) } } public func player(_ player: EZPlayer ,showLoading: Bool){ if showLoading { self.loading.start() }else{ self.loading.stop() } } }
mit
8094d2c15220248e7163768b78935492
33.991031
259
0.610598
4.9669
false
false
false
false
NottingHack/instrumentation-lighting
Sources/nh-lighting/Models/Lighting.swift
1
1683
// // Light.swift // instrumentation-lighting // // Created by Matt Lloyd on 22/09/2017. // // import Foundation enum ChannelState: String, Codable { case ON case OFF case TOGGLE } struct Building { var id: Int var name: String } struct Floor { var id: Int var name: String var level: Int var buildingId: Int } struct Room { var id: Int var name: String var floorId: Int } struct Light { var id: Int var name: String? var roomId: Int var outputChannelId: Int } struct OutputChannel { var id: Int var channel: Int var controllerId: Int } struct InputChannel { var id: Int var channel: Int var controllerId: Int var patternId: Int? var statefull: Bool } struct Pattern { var id: Int var name: String var nextPatternId: Int? var timeout: Int? } struct Controller { var id: Int var name: String var roomId: Int } struct LigthPattern { var lightId: Int var patternId: Int var state: ChannelState } struct Lighting { var buildings = [Building]() var floors = [Floor]() var rooms = [Room]() var lights = [Light]() var outputChannels = [OutputChannel]() var inputChannels = [InputChannel]() var controllers = [Controller]() var patterns = [Pattern]() var lightPatterns = [LigthPattern]() } var lighting = Lighting() var inputChannelStateTracking: [Int : Bool] = [:] class CurrentLightState { let id: Int var state: ChannelState init(id: Int, state: ChannelState) { self.id = id self.state = state } } extension CurrentLightState: CustomStringConvertible { var description: String { get { return "\nCurrentLightState(id: \(id) state: \(state))" } } }
mit
210af6896fe917842873959aa6f2a1c4
14.877358
61
0.667261
3.441718
false
false
false
false
danielallsopp/Charts
Source/Charts/Renderers/BarChartRenderer.swift
14
24920
// // BarChartRenderer.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics #if !os(OSX) import UIKit #endif public class BarChartRenderer: ChartDataRendererBase { public weak var dataProvider: BarChartDataProvider? public init(dataProvider: BarChartDataProvider?, animator: ChartAnimator?, viewPortHandler: ChartViewPortHandler) { super.init(animator: animator, viewPortHandler: viewPortHandler) self.dataProvider = dataProvider } public override func drawData(context context: CGContext) { guard let dataProvider = dataProvider, barData = dataProvider.barData else { return } for i in 0 ..< barData.dataSetCount { guard let set = barData.getDataSetByIndex(i) else { continue } if set.isVisible && set.entryCount > 0 { if !(set is IBarChartDataSet) { fatalError("Datasets for BarChartRenderer must conform to IBarChartDataset") } drawDataSet(context: context, dataSet: set as! IBarChartDataSet, index: i) } } } public func drawDataSet(context context: CGContext, dataSet: IBarChartDataSet, index: Int) { guard let dataProvider = dataProvider, barData = dataProvider.barData, animator = animator else { return } CGContextSaveGState(context) let trans = dataProvider.getTransformer(dataSet.axisDependency) let drawBarShadowEnabled: Bool = dataProvider.isDrawBarShadowEnabled let dataSetOffset = (barData.dataSetCount - 1) let groupSpace = barData.groupSpace let groupSpaceHalf = groupSpace / 2.0 let barSpace = dataSet.barSpace let barSpaceHalf = barSpace / 2.0 let containsStacks = dataSet.isStacked let isInverted = dataProvider.isInverted(dataSet.axisDependency) let barWidth: CGFloat = 0.5 let phaseY = animator.phaseY var barRect = CGRect() var barShadow = CGRect() let borderWidth = dataSet.barBorderWidth let borderColor = dataSet.barBorderColor let drawBorder = borderWidth > 0.0 var y: Double // do the drawing for j in 0 ..< Int(ceil(CGFloat(dataSet.entryCount) * animator.phaseX)) { guard let e = dataSet.entryForIndex(j) as? BarChartDataEntry else { continue } // calculate the x-position, depending on datasetcount let x = CGFloat(e.xIndex + e.xIndex * dataSetOffset) + CGFloat(index) + groupSpace * CGFloat(e.xIndex) + groupSpaceHalf var vals = e.values if (!containsStacks || vals == nil) { y = e.value let left = x - barWidth + barSpaceHalf let right = x + barWidth - barSpaceHalf var top = isInverted ? (y <= 0.0 ? CGFloat(y) : 0) : (y >= 0.0 ? CGFloat(y) : 0) var bottom = isInverted ? (y >= 0.0 ? CGFloat(y) : 0) : (y <= 0.0 ? CGFloat(y) : 0) // multiply the height of the rect with the phase if (top > 0) { top *= phaseY } else { bottom *= phaseY } barRect.origin.x = left barRect.size.width = right - left barRect.origin.y = top barRect.size.height = bottom - top trans.rectValueToPixel(&barRect) if (!viewPortHandler.isInBoundsLeft(barRect.origin.x + barRect.size.width)) { continue } if (!viewPortHandler.isInBoundsRight(barRect.origin.x)) { break } // if drawing the bar shadow is enabled if (drawBarShadowEnabled) { barShadow.origin.x = barRect.origin.x barShadow.origin.y = viewPortHandler.contentTop barShadow.size.width = barRect.size.width barShadow.size.height = viewPortHandler.contentHeight CGContextSetFillColorWithColor(context, dataSet.barShadowColor.CGColor) CGContextFillRect(context, barShadow) } // Set the color for the currently drawn value. If the index is out of bounds, reuse colors. CGContextSetFillColorWithColor(context, dataSet.colorAt(j).CGColor) CGContextFillRect(context, barRect) if drawBorder { CGContextSetStrokeColorWithColor(context, borderColor.CGColor) CGContextSetLineWidth(context, borderWidth) CGContextStrokeRect(context, barRect) } } else { var posY = 0.0 var negY = -e.negativeSum var yStart = 0.0 // if drawing the bar shadow is enabled if (drawBarShadowEnabled) { y = e.value let left = x - barWidth + barSpaceHalf let right = x + barWidth - barSpaceHalf var top = isInverted ? (y <= 0.0 ? CGFloat(y) : 0) : (y >= 0.0 ? CGFloat(y) : 0) var bottom = isInverted ? (y >= 0.0 ? CGFloat(y) : 0) : (y <= 0.0 ? CGFloat(y) : 0) // multiply the height of the rect with the phase if (top > 0) { top *= phaseY } else { bottom *= phaseY } barRect.origin.x = left barRect.size.width = right - left barRect.origin.y = top barRect.size.height = bottom - top trans.rectValueToPixel(&barRect) barShadow.origin.x = barRect.origin.x barShadow.origin.y = viewPortHandler.contentTop barShadow.size.width = barRect.size.width barShadow.size.height = viewPortHandler.contentHeight CGContextSetFillColorWithColor(context, dataSet.barShadowColor.CGColor) CGContextFillRect(context, barShadow) } // fill the stack for k in 0 ..< vals!.count { let value = vals![k] if value >= 0.0 { y = posY yStart = posY + value posY = yStart } else { y = negY yStart = negY + abs(value) negY += abs(value) } let left = x - barWidth + barSpaceHalf let right = x + barWidth - barSpaceHalf var top: CGFloat, bottom: CGFloat if isInverted { bottom = y >= yStart ? CGFloat(y) : CGFloat(yStart) top = y <= yStart ? CGFloat(y) : CGFloat(yStart) } else { top = y >= yStart ? CGFloat(y) : CGFloat(yStart) bottom = y <= yStart ? CGFloat(y) : CGFloat(yStart) } // multiply the height of the rect with the phase top *= phaseY bottom *= phaseY barRect.origin.x = left barRect.size.width = right - left barRect.origin.y = top barRect.size.height = bottom - top trans.rectValueToPixel(&barRect) if (k == 0 && !viewPortHandler.isInBoundsLeft(barRect.origin.x + barRect.size.width)) { // Skip to next bar break } // avoid drawing outofbounds values if (!viewPortHandler.isInBoundsRight(barRect.origin.x)) { break } // Set the color for the currently drawn value. If the index is out of bounds, reuse colors. CGContextSetFillColorWithColor(context, dataSet.colorAt(k).CGColor) CGContextFillRect(context, barRect) if drawBorder { CGContextSetStrokeColorWithColor(context, borderColor.CGColor) CGContextSetLineWidth(context, borderWidth) CGContextStrokeRect(context, barRect) } } } } CGContextRestoreGState(context) } /// Prepares a bar for being highlighted. public func prepareBarHighlight(x x: CGFloat, y1: Double, y2: Double, barspacehalf: CGFloat, trans: ChartTransformer, inout rect: CGRect) { let barWidth: CGFloat = 0.5 let left = x - barWidth + barspacehalf let right = x + barWidth - barspacehalf let top = CGFloat(y1) let bottom = CGFloat(y2) rect.origin.x = left rect.origin.y = top rect.size.width = right - left rect.size.height = bottom - top trans.rectValueToPixel(&rect, phaseY: animator?.phaseY ?? 1.0) } public override func drawValues(context context: CGContext) { // if values are drawn if (passesCheck()) { guard let dataProvider = dataProvider, barData = dataProvider.barData, animator = animator else { return } var dataSets = barData.dataSets let drawValueAboveBar = dataProvider.isDrawValueAboveBarEnabled var posOffset: CGFloat var negOffset: CGFloat for dataSetIndex in 0 ..< barData.dataSetCount { guard let dataSet = dataSets[dataSetIndex] as? IBarChartDataSet else { continue } if !dataSet.isDrawValuesEnabled || dataSet.entryCount == 0 { continue } let isInverted = dataProvider.isInverted(dataSet.axisDependency) // calculate the correct offset depending on the draw position of the value let valueOffsetPlus: CGFloat = 4.5 let valueFont = dataSet.valueFont let valueTextHeight = valueFont.lineHeight posOffset = (drawValueAboveBar ? -(valueTextHeight + valueOffsetPlus) : valueOffsetPlus) negOffset = (drawValueAboveBar ? valueOffsetPlus : -(valueTextHeight + valueOffsetPlus)) if (isInverted) { posOffset = -posOffset - valueTextHeight negOffset = -negOffset - valueTextHeight } guard let formatter = dataSet.valueFormatter else { continue } let trans = dataProvider.getTransformer(dataSet.axisDependency) let phaseY = animator.phaseY let dataSetCount = barData.dataSetCount let groupSpace = barData.groupSpace // if only single values are drawn (sum) if (!dataSet.isStacked) { for j in 0 ..< Int(ceil(CGFloat(dataSet.entryCount) * animator.phaseX)) { guard let e = dataSet.entryForIndex(j) as? BarChartDataEntry else { continue } let valuePoint = trans.getTransformedValueBarChart( entry: e, xIndex: e.xIndex, dataSetIndex: dataSetIndex, phaseY: phaseY, dataSetCount: dataSetCount, groupSpace: groupSpace ) if (!viewPortHandler.isInBoundsRight(valuePoint.x)) { break } if (!viewPortHandler.isInBoundsY(valuePoint.y) || !viewPortHandler.isInBoundsLeft(valuePoint.x)) { continue } let val = e.value drawValue(context: context, value: formatter.stringFromNumber(val)!, xPos: valuePoint.x, yPos: valuePoint.y + (val >= 0.0 ? posOffset : negOffset), font: valueFont, align: .Center, color: dataSet.valueTextColorAt(j)) } } else { // if we have stacks for j in 0 ..< Int(ceil(CGFloat(dataSet.entryCount) * animator.phaseX)) { guard let e = dataSet.entryForIndex(j) as? BarChartDataEntry else { continue } let values = e.values let valuePoint = trans.getTransformedValueBarChart(entry: e, xIndex: e.xIndex, dataSetIndex: dataSetIndex, phaseY: phaseY, dataSetCount: dataSetCount, groupSpace: groupSpace) // we still draw stacked bars, but there is one non-stacked in between if (values == nil) { if (!viewPortHandler.isInBoundsRight(valuePoint.x)) { break } if (!viewPortHandler.isInBoundsY(valuePoint.y) || !viewPortHandler.isInBoundsLeft(valuePoint.x)) { continue } drawValue(context: context, value: formatter.stringFromNumber(e.value)!, xPos: valuePoint.x, yPos: valuePoint.y + (e.value >= 0.0 ? posOffset : negOffset), font: valueFont, align: .Center, color: dataSet.valueTextColorAt(j)) } else { // draw stack values let vals = values! var transformed = [CGPoint]() var posY = 0.0 var negY = -e.negativeSum for k in 0 ..< vals.count { let value = vals[k] var y: Double if value >= 0.0 { posY += value y = posY } else { y = negY negY -= value } transformed.append(CGPoint(x: 0.0, y: CGFloat(y) * animator.phaseY)) } trans.pointValuesToPixel(&transformed) for k in 0 ..< transformed.count { let x = valuePoint.x let y = transformed[k].y + (vals[k] >= 0 ? posOffset : negOffset) if (!viewPortHandler.isInBoundsRight(x)) { break } if (!viewPortHandler.isInBoundsY(y) || !viewPortHandler.isInBoundsLeft(x)) { continue } drawValue(context: context, value: formatter.stringFromNumber(vals[k])!, xPos: x, yPos: y, font: valueFont, align: .Center, color: dataSet.valueTextColorAt(j)) } } } } } } } /// Draws a value at the specified x and y position. public func drawValue(context context: CGContext, value: String, xPos: CGFloat, yPos: CGFloat, font: NSUIFont, align: NSTextAlignment, color: NSUIColor) { ChartUtils.drawText(context: context, text: value, point: CGPoint(x: xPos, y: yPos), align: align, attributes: [NSFontAttributeName: font, NSForegroundColorAttributeName: color]) } public override func drawExtras(context context: CGContext) { } private var _highlightArrowPtsBuffer = [CGPoint](count: 3, repeatedValue: CGPoint()) public override func drawHighlighted(context context: CGContext, indices: [ChartHighlight]) { guard let dataProvider = dataProvider, barData = dataProvider.barData, animator = animator else { return } CGContextSaveGState(context) let setCount = barData.dataSetCount let drawHighlightArrowEnabled = dataProvider.isDrawHighlightArrowEnabled var barRect = CGRect() for high in indices { let minDataSetIndex = high.dataSetIndex == -1 ? 0 : high.dataSetIndex let maxDataSetIndex = high.dataSetIndex == -1 ? barData.dataSetCount : (high.dataSetIndex + 1) if maxDataSetIndex - minDataSetIndex < 1 { continue } for dataSetIndex in minDataSetIndex..<maxDataSetIndex { guard let set = barData.getDataSetByIndex(dataSetIndex) as? IBarChartDataSet else { continue } if (!set.isHighlightEnabled) { continue } let barspaceHalf = set.barSpace / 2.0 let trans = dataProvider.getTransformer(set.axisDependency) CGContextSetFillColorWithColor(context, set.highlightColor.CGColor) CGContextSetAlpha(context, set.highlightAlpha) let index = high.xIndex // check outofbounds if (CGFloat(index) < (CGFloat(dataProvider.chartXMax) * animator.phaseX) / CGFloat(setCount)) { let e = set.entryForXIndex(index) as! BarChartDataEntry! if (e === nil || e.xIndex != index) { continue } let groupspace = barData.groupSpace let isStack = high.stackIndex < 0 ? false : true // calculate the correct x-position let x = CGFloat(index * setCount + dataSetIndex) + groupspace / 2.0 + groupspace * CGFloat(index) let y1: Double let y2: Double if (isStack) { y1 = high.range?.from ?? 0.0 y2 = high.range?.to ?? 0.0 } else { y1 = e.value y2 = 0.0 } prepareBarHighlight(x: x, y1: y1, y2: y2, barspacehalf: barspaceHalf, trans: trans, rect: &barRect) CGContextFillRect(context, barRect) if (drawHighlightArrowEnabled) { CGContextSetAlpha(context, 1.0) // distance between highlight arrow and bar let offsetY = animator.phaseY * 0.07 CGContextSaveGState(context) let pixelToValueMatrix = trans.pixelToValueMatrix let xToYRel = abs(sqrt(pixelToValueMatrix.b * pixelToValueMatrix.b + pixelToValueMatrix.d * pixelToValueMatrix.d) / sqrt(pixelToValueMatrix.a * pixelToValueMatrix.a + pixelToValueMatrix.c * pixelToValueMatrix.c)) let arrowWidth = set.barSpace / 2.0 let arrowHeight = arrowWidth * xToYRel let yArrow = (y1 > -y2 ? y1 : y1) * Double(animator.phaseY) _highlightArrowPtsBuffer[0].x = CGFloat(x) + 0.4 _highlightArrowPtsBuffer[0].y = CGFloat(yArrow) + offsetY _highlightArrowPtsBuffer[1].x = CGFloat(x) + 0.4 + arrowWidth _highlightArrowPtsBuffer[1].y = CGFloat(yArrow) + offsetY - arrowHeight _highlightArrowPtsBuffer[2].x = CGFloat(x) + 0.4 + arrowWidth _highlightArrowPtsBuffer[2].y = CGFloat(yArrow) + offsetY + arrowHeight trans.pointValuesToPixel(&_highlightArrowPtsBuffer) CGContextBeginPath(context) CGContextMoveToPoint(context, _highlightArrowPtsBuffer[0].x, _highlightArrowPtsBuffer[0].y) CGContextAddLineToPoint(context, _highlightArrowPtsBuffer[1].x, _highlightArrowPtsBuffer[1].y) CGContextAddLineToPoint(context, _highlightArrowPtsBuffer[2].x, _highlightArrowPtsBuffer[2].y) CGContextClosePath(context) CGContextFillPath(context) CGContextRestoreGState(context) } } } } CGContextRestoreGState(context) } internal func passesCheck() -> Bool { guard let dataProvider = dataProvider, barData = dataProvider.barData else { return false } return CGFloat(barData.yValCount) < CGFloat(dataProvider.maxVisibleValueCount) * viewPortHandler.scaleX } }
apache-2.0
235f752a9f57ac68edc9f1b2917eec86
40.604341
236
0.440851
6.738778
false
false
false
false
JohnCoates/Aerial
Aerial/Source/Views/Layers/Weather/WeatherLayer.swift
1
9436
// // WeatherLayer.swift // Aerial // // Created by Guillaume Louel on 16/04/2020. // Copyright © 2020 Guillaume Louel. All rights reserved. // import Foundation import AVKit class WeatherLayer: AnimationLayer { var config: PrefsInfo.Weather? var wasSetup = false var todayCond: ConditionLayer? var forecastCond: ForecastLayer? var cscale: CGFloat? private static let cachedWeatherURL = URL(fileURLWithPath: Cache.supportPath, isDirectory: true).appendingPathComponent("Weather.json") private static let cachedWeatherForecastURL = URL(fileURLWithPath: Cache.supportPath, isDirectory: true).appendingPathComponent("Forecast.json") private static let cachedWeatherUpdateInterval: TimeInterval = 60 * 15 var cachedWeather: OWeather? { get { let fm = FileManager.default guard fm.fileExists(atPath: WeatherLayer.cachedWeatherURL.path) else { return nil } do { guard let date = try fm.attributesOfItem(atPath: WeatherLayer.cachedWeatherURL.path)[.modificationDate] as? Date else { assertionFailure("Couldn't get modificationDate from File System!") return nil } // Make sure the cache was written in the last "update interval" seconds, otherwise download now guard date >= Date().addingTimeInterval(-WeatherLayer.cachedWeatherUpdateInterval) else { return nil } let data = try Data(contentsOf: WeatherLayer.cachedWeatherURL) let result = try JSONDecoder().decode(OWeather.self, from: data) return result } catch { // Handle error assertionFailure("Error decoding Weather: \(error.localizedDescription)") return nil } } set { do { guard let newValue else { /* Don't store nil */ return } let data = try JSONEncoder().encode(newValue) try FileManager.default.createDirectory(atPath: Cache.supportPath, withIntermediateDirectories: true) try data.write(to: Self.cachedWeatherURL) } catch { // Handle error assertionFailure("Error encoding Weather: \(error.localizedDescription)") } } } var cachedForecast: ForecastElement? { get { let fm = FileManager.default guard fm.fileExists(atPath: WeatherLayer.cachedWeatherForecastURL.path) else { return nil } do { guard let date = try fm.attributesOfItem(atPath: WeatherLayer.cachedWeatherForecastURL.path)[.modificationDate] as? Date else { assertionFailure("Couldn't get modificationDate from File System!") return nil } // Make sure the cache was written in the last "update interval" seconds, otherwise download now guard date >= Date().addingTimeInterval(-WeatherLayer.cachedWeatherUpdateInterval) else { return nil } let data = try Data(contentsOf: WeatherLayer.cachedWeatherForecastURL) let result = try JSONDecoder().decode(ForecastElement.self, from: data) return result } catch { // Handle error assertionFailure("Error decoding Weather: \(error.localizedDescription)") return nil } } set { do { guard let newValue else { /* Don't store nil */ return } let data = try JSONEncoder().encode(newValue) try FileManager.default.createDirectory(atPath: Cache.supportPath, withIntermediateDirectories: true) try data.write(to: Self.cachedWeatherForecastURL) } catch { // Handle error assertionFailure("Error encoding Weather: \(error.localizedDescription)") } } } override init(layer: Any) { super.init(layer: layer) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } // Our inits override init(withLayer: CALayer, isPreview: Bool, offsets: LayerOffsets, manager: LayerManager) { super.init(withLayer: withLayer, isPreview: isPreview, offsets: offsets, manager: manager) // Always on layers should start with full opacity self.opacity = 1 } convenience init(withLayer: CALayer, isPreview: Bool, offsets: LayerOffsets, manager: LayerManager, config: PrefsInfo.Weather) { self.init(withLayer: withLayer, isPreview: isPreview, offsets: offsets, manager: manager) self.config = config /* // Set our layer's font & corner now (self.font, self.fontSize) = getFont(name: config.fontName, size: config.fontSize)*/ self.corner = config.corner } override func setContentScale(scale: CGFloat) { if let todayCond = todayCond { todayCond.contentsScale = scale if todayCond.sublayers != nil { for layer in todayCond.sublayers! { layer.contentsScale = scale } } } if let forecastCond = forecastCond { forecastCond.contentsScale = scale } // In case we haven't called displayWeatherBlock yet (should be all the time but hmm) cscale = scale } // Called at each new video, we only setup once though ! override func setupForVideo(video: AerialVideo, player: AVPlayer) { // Only run this once if !wasSetup { wasSetup = true frame.size = CGSize(width: 100, height: 1) update() } if PrefsInfo.weather.mode == .current { if cachedWeather != nil { displayWeatherBlock() } else { print("fetching") OpenWeather.fetch { result in switch result { case .success(let openWeather): self.cachedWeather = openWeather self.displayWeatherBlock() case .failure(let error): debugLog(error.localizedDescription) } } } } else { if cachedForecast != nil && cachedWeather != nil { displayWeatherBlock() } else { Forecast.fetch { result in switch result { case .success(let openWeather): self.cachedForecast = openWeather // self.displayWeatherBlock() OpenWeather.fetch { result in switch result { case .success(let openWeather): self.cachedWeather = openWeather self.displayWeatherBlock() case .failure(let error): debugLog(error.localizedDescription) } } case .failure(let error): debugLog(error.localizedDescription) } } } } } func displayWeatherBlock() { guard cachedWeather != nil || cachedForecast != nil else { errorLog("No weather info in dWB please report") return } todayCond?.removeFromSuperlayer() todayCond = nil forecastCond?.removeFromSuperlayer() forecastCond = nil if PrefsInfo.weather.mode == .current { todayCond = ConditionLayer(condition: cachedWeather!, scale: contentsScale) if cscale != nil { todayCond!.contentsScale = cscale! } todayCond!.anchorPoint = CGPoint(x: 0, y: 0) todayCond!.position = CGPoint(x: 0, y: 10) addSublayer(todayCond!) self.frame.size = todayCond!.frame.size } else { todayCond = ConditionLayer(condition: cachedWeather!, scale: contentsScale) if cscale != nil { todayCond!.contentsScale = cscale! } todayCond!.anchorPoint = CGPoint(x: 0, y: 0) addSublayer(todayCond!) forecastCond = ForecastLayer(condition: cachedForecast!, scale: contentsScale) if cscale != nil { forecastCond!.contentsScale = cscale! } forecastCond!.anchorPoint = CGPoint(x: 0, y: 0) forecastCond!.position = CGPoint(x: todayCond!.frame.width, y: 10) addSublayer(forecastCond!) todayCond!.position = CGPoint(x: 0, y: forecastCond!.frame.height - todayCond!.frame.height + 10) self.frame.size = CGSize(width: todayCond!.frame.width + forecastCond!.frame.width, height: forecastCond!.frame.height) // self.frame.size = forecastCond!.frame.size } update(redraw: true) let fadeAnimation = self.createFadeInAnimation() add(fadeAnimation, forKey: "weatherfade") } }
mit
99d77c9bfe37c426f569183d70b394f5
39.493562
148
0.558453
5.385274
false
false
false
false
windless/SqlWrapper
Example/SqlWrapper/ViewController.swift
1
1832
// // ViewController.swift // SqlWrapper // // Created by Abner Zhong on 03/23/2016. // Copyright (c) 2016 Abner Zhong. All rights reserved. // import UIKit import SqlWrapper import FMDB class ViewController: UIViewController { var session: FMDatabaseQueue! override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.whiteColor() let libraryPath = NSSearchPathForDirectoriesInDomains(.LibraryDirectory, .UserDomainMask, true)[0] as NSString let dbPath = libraryPath.stringByAppendingPathComponent("database.db") session = FMDatabaseQueue(path: dbPath) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } } class Student: ActiveRecord { var name: String var age: Int var sex: Int var grade: Double? var classId: Int? var height: Int? init(name: String, age: Int, sex: Int) { self.name = name self.age = age self.sex = sex super.init() } required init() { name = "" age = 0 sex = 0 } override class var primaryKey: String { return "ID" } override class func map<T: ActiveRecord>(resultSet: ResultSet) -> T? { let name = resultSet.string("name")! let age = resultSet.integer("age")! let sex = resultSet.integer("sex")! let grade = resultSet.double("grade") let classId = resultSet.integer("classId") let height = resultSet.integer("height") let id = resultSet.integer("ID")! let student = Student(name: name, age: age, sex: sex) student.ID = id student.grade = grade student.classId = classId student.height = height return student as? T } }
mit
485c0abb01cb564eeeb5aa05f5d81a69
24.802817
80
0.607533
4.435835
false
false
false
false
narner/AudioKit
Playgrounds/AudioKitPlaygrounds/Playgrounds/Synthesis.playground/Pages/Telephone.xcplaygroundpage/Contents.swift
1
4041
//: ## Telephone //: AudioKit is great for sound design. This playground creates canonical telephone sounds. import AudioKitPlaygrounds import AudioKit import AudioKitUI //: ### Dial Tone //: A dial tone is simply two sine waves at specific frequencies let dialTone = AKOperationGenerator { _ in let dialTone1 = AKOperation.sineWave(frequency: 350) let dialTone2 = AKOperation.sineWave(frequency: 440) return mixer(dialTone1, dialTone2) * 0.3 } //: ### Telephone Ringing //: The ringing sound is also a pair of frequencies that play for 2 seconds, //: and repeats every 6 seconds. let ringing = AKOperationGenerator { _ in let ringingTone1 = AKOperation.sineWave(frequency: 480) let ringingTone2 = AKOperation.sineWave(frequency: 440) let ringingToneMix = mixer(ringingTone1, ringingTone2) let ringTrigger = AKOperation.metronome(frequency: 0.166_6) // 1 / 6 seconds let rings = ringingToneMix.triggeredWithEnvelope( trigger: ringTrigger, attack: 0.01, hold: 2, release: 0.01) return rings * 0.4 } //: ### Busy Signal //: The busy signal is similar as well, just a different set of parameters. let busy = AKOperationGenerator { _ in let busySignalTone1 = AKOperation.sineWave(frequency: 480) let busySignalTone2 = AKOperation.sineWave(frequency: 620) let busySignalTone = mixer(busySignalTone1, busySignalTone2) let busyTrigger = AKOperation.metronome(frequency: 2) let busySignal = busySignalTone.triggeredWithEnvelope( trigger: busyTrigger, attack: 0.01, hold: 0.25, release: 0.01) return busySignal * 0.4 } //: ## Key presses //: All the digits are also just combinations of sine waves //: //: The canonical specification of DTMF Tones: var keys = [String: [Double]]() keys["1"] = [697, 1_209] keys["2"] = [697, 1_336] keys["3"] = [697, 1_477] keys["4"] = [770, 1_209] keys["5"] = [770, 1_336] keys["6"] = [770, 1_477] keys["7"] = [852, 1_209] keys["8"] = [852, 1_336] keys["9"] = [852, 1_477] keys["*"] = [941, 1_209] keys["0"] = [941, 1_336] keys["#"] = [941, 1_477] let keypad = AKOperationGenerator { parameters in let keyPressTone = AKOperation.sineWave(frequency: AKOperation.parameters[1]) + AKOperation.sineWave(frequency: AKOperation.parameters[2]) let momentaryPress = keyPressTone.triggeredWithEnvelope( trigger:AKOperation.trigger, attack: 0.01, hold: 0.1, release: 0.01) return momentaryPress * 0.4 } AudioKit.output = AKMixer(dialTone, ringing, busy, keypad) AudioKit.start() dialTone.start() keypad.start() //: User Interface Set up class LiveView: AKLiveViewController { override func viewDidLoad() { addTitle("Telephone") addView(AKPhoneView { key, state in switch key { case "CALL": if state == "down" { busy.stop() dialTone.stop() if ringing.isStarted { ringing.stop() dialTone.start() } else { ringing.start() } } case "BUSY": if state == "down" { ringing.stop() dialTone.stop() if busy.isStarted { busy.stop() dialTone.start() } else { busy.start() } } default: if state == "down" { dialTone.stop() ringing.stop() busy.stop() keypad.parameters[1] = keys[key]![0] keypad.parameters[2] = keys[key]![1] keypad.parameters[0] = 1 } else { keypad.parameters[0] = 0 } } }) } } import PlaygroundSupport PlaygroundPage.current.needsIndefiniteExecution = true PlaygroundPage.current.liveView = LiveView()
mit
e86667b361a4027fab2271c33fd6c7cd
30.325581
91
0.580549
4.187565
false
false
false
false
kevin-zqw/play-swift
swift-lang/08. Enumerations.playground/section-1.swift
1
7438
// ------------------------------------------------------------------------------------------------ // Things to know: // // * Enumerations in Swift are different from their popular counterparts in C-like languages. // Rather that containing "one of a set of integer values" like most C-like languages, Swift's // enumerations can be thought of as holding one named type of a given set of named types. // // To clarify: Rather than holding an integer value that has been pre-defined integer value // (Error = -1, Success = 0) an enumeration in Swift only associates a name with a type (like // Int, String, Tuple, etc.) These elements of the enumeration can then be assigned "Associated // Values." For example, an enumeration can store an "Error" which is a Tuple with an Int value // for the error code and a String containing the message. Each time a function or piece of code // assignes or returns an Error(Int, String), it can set populate the Tuple with Int/String par // for the specific error condition. // // * Alternative to the enumeration storing named types, Swift enumerations can have a type. If // that type is Int, then they will behave more like their C-style counterparts. // ------------------------------------------------------------------------------------------------ // Here is the simple enumeration. // // Unlike their C counterparts, the members of the enumeration below are not integer values (0, // 1, 2, etc.) Instead, each member is a fully-fledged value in its own right. enum Planet { case Mercury case Venus case Earth case Mars case Jupiter case Saturn case Uranus case Neptune } enum Sex { case Male, Female } var mySex = Sex.Male // You can use shorter dot syntax mySex = .Female switch mySex { case .Male: print("a man") case .Female: print("a women") } // You can also combine members onto a single line if you prefer, or mix them up. This has no // effect on the enumeration itself. enum CompassPoint { case North, South case East, West } // Let's store an enumeration value into a variable. We'll let the compiler infer the type: var directionToHead = CompassPoint.West // Now that directionToHead has a CompassPoint type (which was inferred) we can set it to a // different CompassPoint value using a shorter syntax: directionToHead = .East // We can use a switch to match values from an enumeration. // // Remember that switches have to be exhaustive. But in this case, Swift knows that the CompassType // enumeration only has 4 values, so as long as we cover all 4, we don't need the default case. switch directionToHead { case .North: "North" case .South: "South" case .East: "East" case .West: "West" } // ------------------------------------------------------------------------------------------------ // Associated Values // // Associated values allows us to store information with each member of the switch using a Tuple. // // The following enumeration will store not only the type of a barcode (UPCA, QR Code) but also // the data of the barcode (this is likely a foreign concept for most.) enum Barcode { case UPCA(Int, Int, Int) // UPCA with associated value type (Int, Int, Int) case QRCode(String) // QRCode with associated value type of String } enum MyBarcode { case UPCA(Int, Int, Int) case QRCode(String) } let code = MyBarcode.QRCode("hello") let simpleCode = MyBarcode.UPCA(1, 1, 1) switch simpleCode { case .UPCA(let a, let b, let c): print("upca \(a) \(b) \(c)") case .QRCode(let code): print("QRCode: \(code)") } // case all constants, you can use one let switch simpleCode { case let .UPCA(a, b, c): print("upca \(a) \(b) \(c)") case let .QRCode(code): print("QRCode: \(code)") } // Let's specify a UPCA code (letting the compiler infer the enum type of Barcode): var productBarcode = Barcode.UPCA(0, 8590951226, 3) // Let's change that to a QR code (still of a Barcode type) productBarcode = .QRCode("ABCDEFGHIJKLMNOP") // We use a switch to check the value and extract the associated value: switch productBarcode { case .UPCA(let numberSystem, let identifier, let check): "UPCA: \(numberSystem), \(identifier), \(check)" case .QRCode(let productCode): "QR: \(productCode)" } // Using the switch statement simplification (see the Switch statement section) to reduce the // number of occurrances of the 'let' introducer: switch productBarcode { // All constants case let .UPCA(numberSystem, identifier, check): "UPCA: \(numberSystem), \(identifier), \(check)" // All variables case var .QRCode(productCode): "QR: \(productCode)" } // ------------------------------------------------------------------------------------------------ // Raw values // // We can assign a type to an enumeration. If we use Int as the type, then we are effectively // making an enumeration that functions like its C counterpart: enum StatusCode: Int { case Error = -1 case Success = 9 case OtherResult = 1 case YetAnotherResult // Unspecified values are auto-incremented from the previous value } enum ASCIICharacter: Character { case Tab = "\t" case LineFeed = "\n" case CarriageReturn = "\r" } // String and Integer will get implicit raw value if you specified enum ImplicitRawValueInt: Int { case AA // raw value 0 case BB // raw value 1 case CC // raw value 2 case DD // raw value 3 } enum ImplicitRawValueString: String { case SS // raw value "SS" case BB // raw value "BB" case AA // raw value "AA" } // Raw values can be strings, characters, or any of the integer or floating-point number types // Each raw value must be unique within its enumeration declaration // We can get the raw value of an enumeration value with the rawValue member: StatusCode.OtherResult.rawValue // We can give enumerations many types. Here's one of type Character: enum ASCIIControlCharacter: Character { case Tab = "\t" case LineFeed = "\n" case CarriageReturn = "\r" // Note that only Int type enumerations can auto-increment. Since this is a Character type, // the following line of code won't compile: // // case VerticalTab } print(StatusCode.Error.rawValue) // Alternatively, we could also use Strings enum FamilyPet: String { case Cat = "Cat" case Dog = "Dog" case Ferret = "Ferret" } // And we can get their raw value as well: FamilyPet.Ferret.rawValue // If you define an enumeration with a raw-value type, the enumeration automcatically receives an initializer that takes a value of the raw values's type(as a parameter called rawValue) and returns either an enumeration case or nil let myEnum = ASCIICharacter(rawValue: "A") // We can also generate the enumeration value from the raw value. Note that this is an optional // because not all raw values will have a matching enumeration: var pet = FamilyPet(rawValue: "Ferret") // Let's verify this: if pet != .None { "We have a pet!" } else { "No pet :(" } // An example of when a raw doesn't translate to an enum, leaving us with a nil optional: pet = FamilyPet(rawValue: "Snake") if pet != .None { "We have a pet" } else { "No pet :(" } // Use indirect to indicate that an enumeration case is recursive enum ArithmeticExpression { case Number(Int) indirect case Addition(ArithmeticExpression) indirect case Multiplication(ArithmeticExpression) } // Arecursive function is a straightforward way to work with data that has a recursive structure.
apache-2.0
71a5c64bc1736140a5c0b9b71138ce8c
30.516949
231
0.680828
3.939619
false
false
false
false
labi3285/QXConsMaker
QXConsMaker/QXConsMaker/QXConsMaker.swift
1
12230
// // QXConsMaker.swift // QXAutoLayoutDemo // // Created by Richard.q.x on 16/5/6. // Copyright © 2016年 labi3285_lab. All rights reserved. // import UIKit //MARK: - extension UIView { public var LEFT: QXConsMaker { return QXConsMaker.updateMaker(view: self, attribute: .left) } public var RIGHT: QXConsMaker { return QXConsMaker.updateMaker(view: self, attribute: .right) } public var TOP: QXConsMaker { return QXConsMaker.updateMaker(view: self, attribute: .top) } public var BOTTOM: QXConsMaker { return QXConsMaker.updateMaker(view: self, attribute: .bottom) } public var LEADING: QXConsMaker { return QXConsMaker.updateMaker(view: self, attribute: .leading) } public var TRAILING: QXConsMaker { return QXConsMaker.updateMaker(view: self, attribute: .trailing) } public var WIDTH: QXConsMaker { return QXConsMaker.updateMaker(view: self, attribute: .width) } public var HEIGHT: QXConsMaker { return QXConsMaker.updateMaker(view: self, attribute: .height) } public var CENTER_X: QXConsMaker { return QXConsMaker.updateMaker(view: self, attribute: .centerX) } public var CENTER_Y: QXConsMaker { return QXConsMaker.updateMaker(view: self, attribute: .centerY) } public var BASELINE: QXConsMaker { return QXConsMaker.updateMaker(view: self, attribute: .lastBaseline) } public var FIRST_BASELINE: QXConsMaker { return QXConsMaker.updateMaker(view: self, attribute: .firstBaseline) } public var LEFT_MARGIN: QXConsMaker { return QXConsMaker.updateMaker(view: self, attribute: .leftMargin) } public var RIGHT_MARGIN: QXConsMaker { return QXConsMaker.updateMaker(view: self, attribute: .rightMargin) } public var TOP_MARGIN: QXConsMaker { return QXConsMaker.updateMaker(view: self, attribute: .topMargin) } public var BOTTOM_MARGIN: QXConsMaker { return QXConsMaker.updateMaker(view: self, attribute: .bottomMargin) } public var LEADING_MARGIN: QXConsMaker { return QXConsMaker.updateMaker(view: self, attribute: .leadingMargin) } public var TRAILING_MARGIN: QXConsMaker { return QXConsMaker.updateMaker(view: self, attribute: .trailingMargin) } public var CENTER_X_WITHIN_MARGINS: QXConsMaker { return QXConsMaker.updateMaker(view: self, attribute: .centerXWithinMargins) } public var CENTER_Y_WITHIN_MARGINS: QXConsMaker { return QXConsMaker.updateMaker(view: self, attribute: .centerYWithinMargins) } public var NOT_AN_ATTRIBUTE: QXConsMaker { return QXConsMaker.updateMaker(view: self, attribute: .notAnAttribute) } public func OFFSET(_ O: CGFloat) -> QXConsMaker { return QXConsMaker.updateMaker(offset: O) } public func RATIO(_ R: CGFloat) -> QXConsMaker { return QXConsMaker.updateMaker(ratio: R) } public func REMOVE_CONSES() { QXConsMaker.removeConstraints(view: self) } } //MARK: - extension QXConsMaker { public var LEFT: QXConsMaker { return QXConsMaker.updateMaker(attribute: .left) } public var RIGHT: QXConsMaker { return QXConsMaker.updateMaker(attribute: .right) } public var TOP: QXConsMaker { return QXConsMaker.updateMaker(attribute: .top) } public var BOTTOM: QXConsMaker { return QXConsMaker.updateMaker(attribute: .bottom) } public var LEADING: QXConsMaker { return QXConsMaker.updateMaker(attribute: .leading) } public var TRAILING: QXConsMaker { return QXConsMaker.updateMaker(attribute: .trailing) } public var WIDTH: QXConsMaker { return QXConsMaker.updateMaker(attribute: .width) } public var HEIGHT: QXConsMaker { return QXConsMaker.updateMaker(attribute: .height) } public var CENTER_X: QXConsMaker { return QXConsMaker.updateMaker(attribute: .centerX) } public var CENTER_Y: QXConsMaker { return QXConsMaker.updateMaker(attribute: .centerY) } public var BASELINE: QXConsMaker { return QXConsMaker.updateMaker(attribute: .lastBaseline) } public var FIRST_BASELINE: QXConsMaker { return QXConsMaker.updateMaker(attribute: .firstBaseline) } public var LEFT_MARGIN: QXConsMaker { return QXConsMaker.updateMaker(attribute: .leftMargin) } public var RIGHT_MARGIN: QXConsMaker { return QXConsMaker.updateMaker(attribute: .rightMargin) } public var TOP_MARGIN: QXConsMaker { return QXConsMaker.updateMaker(attribute: .topMargin) } public var BOTTOM_MARGIN: QXConsMaker { return QXConsMaker.updateMaker(attribute: .bottomMargin) } public var LEADING_MARGIN: QXConsMaker { return QXConsMaker.updateMaker(attribute: .leadingMargin) } public var TRAILING_MARGIN: QXConsMaker { return QXConsMaker.updateMaker(attribute: .trailingMargin) } public var CENTER_X_WITHIN_MARGINS: QXConsMaker { return QXConsMaker.updateMaker(attribute: .centerXWithinMargins) } public var CENTER_Y_WITHIN_MARGINS: QXConsMaker { return QXConsMaker.updateMaker(attribute: .centerYWithinMargins) } public var NOT_AN_ATTRIBUTE: QXConsMaker { return QXConsMaker.updateMaker(attribute: .notAnAttribute) } public func EQUAL(_ V: UIView) -> QXConsMaker { return QXConsMaker.updateMaker(view: V, relationship: .equal) } public func GREAT_THAN_OR_EQUAL(_ V: UIView) -> QXConsMaker { return QXConsMaker.updateMaker(view: V, relationship: .greaterThanOrEqual) } public func LESS_THAN_OR_EQUAL(_ V: UIView) -> QXConsMaker { return QXConsMaker.updateMaker(view: V, relationship: .lessThanOrEqual) } public func EQUAL(_ V: CGFloat) -> QXConsMaker { return QXConsMaker.updateMaker(value: V, relationship: .equal) } public func GREAT_THAN_OR_EQUAL(_ V: CGFloat) -> QXConsMaker { return QXConsMaker.updateMaker(value: V, relationship: .greaterThanOrEqual) } public func LESS_THAN_OR_EQUAL(_ V: CGFloat) -> QXConsMaker { return QXConsMaker.updateMaker(value: V, relationship: .lessThanOrEqual) } public func OFFSET(_ O: CGFloat) -> QXConsMaker { return QXConsMaker.updateMaker(offset: O) } public func RATIO(_ R: CGFloat) -> QXConsMaker { return QXConsMaker.updateMaker(ratio: R) } public func PRIORITY(_ P: CGFloat) -> QXConsMaker { return QXConsMaker.updateMaker(priority: P) } @discardableResult public func MAKE() -> NSLayoutConstraint { return QXConsMaker.makeUpConstraint(scale: 1) } @discardableResult public func MAKE(_ scale: CGFloat) -> NSLayoutConstraint { return QXConsMaker.makeUpConstraint(scale: scale) } } //MARK: - public struct QXConsMaker { //MARK: vars fileprivate var newProcess: Bool = true fileprivate weak var firstItem: UIView? = nil fileprivate weak var secondItem: UIView? = nil fileprivate var firstItemAttribute: NSLayoutConstraint.Attribute? = nil fileprivate var relationship: NSLayoutConstraint.Relation? = nil fileprivate var secondItemAttribute: NSLayoutConstraint.Attribute? = nil fileprivate var ratio: CGFloat = 1.0 fileprivate var offset: CGFloat = 0 fileprivate var priority: CGFloat = 1000 //MARK: shared one fileprivate static var maker = QXConsMaker() //MARK: base tools fileprivate static func updateMaker(view v: UIView, attribute a: NSLayoutConstraint.Attribute) -> QXConsMaker { if self.maker.newProcess { self.maker.firstItem = v self.maker.firstItemAttribute = a self.maker.secondItemAttribute = a self.maker.newProcess = false } else { self.maker.secondItem = v self.maker.secondItemAttribute = a } return self.maker } fileprivate static func updateMaker(attribute a: NSLayoutConstraint.Attribute) -> QXConsMaker { self.maker.secondItemAttribute = a return self.maker } fileprivate static func updateMaker(view v: UIView, relationship r: NSLayoutConstraint.Relation) -> QXConsMaker { self.maker.relationship = r self.maker.secondItem = v return self.maker } fileprivate static func updateMaker(value v: CGFloat, relationship r: NSLayoutConstraint.Relation) -> QXConsMaker { self.maker.relationship = r self.maker.secondItem = nil self.maker.offset = v return self.maker } fileprivate static func updateMaker(ratio r: CGFloat) -> QXConsMaker { self.maker.ratio = r return self.maker } fileprivate static func updateMaker(offset o: CGFloat) -> QXConsMaker { self.maker.offset = o return self.maker } fileprivate static func updateMaker(priority p: CGFloat = 1000) -> QXConsMaker { self.maker.priority = p return self.maker } fileprivate static func makeUpConstraint(scale s: CGFloat) -> NSLayoutConstraint { if let v = QXConsMaker.maker.firstItem { v.translatesAutoresizingMaskIntoConstraints = false } let cons = NSLayoutConstraint(item: self.maker.firstItem!, attribute: self.maker.firstItemAttribute!, relatedBy: self.maker.relationship!, toItem: self.maker.secondItem, attribute: self.maker.secondItemAttribute!, multiplier: self.maker.ratio, constant: self.maker.offset * s) QXConsMaker.install(constraint: cons) QXConsMaker.maker.firstItem!.CONSES.add(cons) QXConsMaker.maker = QXConsMaker() return cons } fileprivate static func removeConstraints(view v: UIView) { for c in v.CONSES { let cons = c as! NSLayoutConstraint var view: UIView? let v1 = cons.firstItem as! UIView if let obj = cons.secondItem { if let v2 = obj as? UIView { view = getAncestorView(view1: v1, view2: v2) } } if view == nil { view = v1 } view!.removeConstraint(cons) } } //MARK: other tools fileprivate static func getAncestorView(view1 v1: UIView, view2 v2: UIView) -> UIView? { if v1 == v2 { return v1 } var svForLoop: UIView? var arr1 = [v1] svForLoop = v1.superview while svForLoop != nil { arr1.append(svForLoop!) svForLoop = svForLoop!.superview } var arr2 = [v2] svForLoop = v2.superview while svForLoop != nil { arr2.append(svForLoop!) svForLoop = svForLoop!.superview } if arr1.contains(v2) { return v2 } if arr2.contains(v1) { return v1 } for v in arr1 { if arr2.contains(v) { return v } } return nil } fileprivate static func install(constraint c: NSLayoutConstraint, priority p: CGFloat = 1000) { let v1 = c.firstItem as! UIView if let v2 = c.secondItem as? UIView { if let v = getAncestorView(view1: v1, view2: v2) { c.priority = UILayoutPriority(Float(p)) v.addConstraint(c) } else { assert(true, "\(c) install failed!") } } else { c.priority = UILayoutPriority(Float(p)) v1.addConstraint(c) } } } private var kUIViewConsesAssociateKey:UInt = 1202328501 extension UIView { var CONSES:NSMutableArray { get { var obj = objc_getAssociatedObject(self, &kUIViewConsesAssociateKey) if obj == nil { obj = NSMutableArray() objc_setAssociatedObject(self, &kUIViewConsesAssociateKey, obj, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } return obj as! NSMutableArray } } }
apache-2.0
e3a1e8018172237dcf28e468dc07aa5a
44.794007
144
0.644557
4.041983
false
false
false
false
apple/swift-async-algorithms
Sources/AsyncAlgorithms/AsyncCompactedSequence.swift
1
2066
//===----------------------------------------------------------------------===// // // This source file is part of the Swift Async Algorithms open source project // // Copyright (c) 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 // //===----------------------------------------------------------------------===// /// An `AsyncSequence` that iterates over every non-nil element from the original /// `AsyncSequence`. @frozen public struct AsyncCompactedSequence<Base: AsyncSequence, Element>: AsyncSequence where Base.Element == Element? { @usableFromInline let base: Base @inlinable init(_ base: Base) { self.base = base } /// The iterator for an `AsyncCompactedSequence` instance. @frozen public struct Iterator: AsyncIteratorProtocol { @usableFromInline var base: Base.AsyncIterator @inlinable init(_ base: Base.AsyncIterator) { self.base = base } @inlinable public mutating func next() async rethrows -> Element? { while let wrapped = try await base.next() { guard let some = wrapped else { continue } return some } return nil } } @inlinable public func makeAsyncIterator() -> Iterator { Iterator(base.makeAsyncIterator()) } } extension AsyncSequence { /// Returns a new `AsyncSequence` that iterates over every non-nil element from the /// original `AsyncSequence`. /// /// Produces the same result as `c.compactMap { $0 }`. /// /// - Returns: An `AsyncSequence` where the element is the unwrapped original /// element and iterates over every non-nil element from the original /// `AsyncSequence`. /// /// Complexity: O(1) @inlinable public func compacted<Unwrapped>() -> AsyncCompactedSequence<Self, Unwrapped> where Element == Unwrapped? { AsyncCompactedSequence(self) } } extension AsyncCompactedSequence: Sendable where Base: Sendable, Base.Element: Sendable { }
apache-2.0
f7c0f9bdf050473dc8b036e7c88fbb1d
28.098592
91
0.633591
4.793503
false
false
false
false
skedgo/tripkit-ios
Sources/TripKitUI/views/results/TKUIResultsTitleView.swift
1
5175
// // TKUIResultsTitleView.swift // TripKit-iOS // // Created by Kuan Lun Huang on 3/10/19. // Copyright © 2019 SkedGo Pty Ltd. All rights reserved. // import UIKit import TGCardViewController import RxSwift import RxCocoa import TripKit class TKUIResultsTitleView: UIView, TGPreferrableView { @IBOutlet weak var originLabel: UILabel! @IBOutlet weak var destinationLabel: UILabel! @IBOutlet weak var dismissButton: UIButton! @IBOutlet private weak var fromToStack: UIStackView! @IBOutlet private weak var topLevelStack: UIStackView! @IBOutlet private weak var accessoryViewContainer: UIView! @IBOutlet private weak var topLevelStackBottomSpacing: NSLayoutConstraint! var enableTappingLocation: Bool = true private let locationSearchPublisher = PublishSubject<Void>() var locationTapped: Signal<Void> { return locationSearchPublisher.asSignal(onErrorSignalWith: .empty()) } public var preferredView: UIView? { fromToStack } var accessoryView: UIView? { get { return accessoryViewContainer.subviews.first } set { accessoryViewContainer.subviews.forEach { $0.removeFromSuperview() } guard let accessory = newValue else { accessoryViewContainer.isHidden = true topLevelStack.spacing = 0 topLevelStackBottomSpacing.constant = 16 return } accessoryViewContainer.isHidden = false topLevelStack.spacing = 16 topLevelStackBottomSpacing.constant = 0 accessoryViewContainer.addSubview(accessory) accessory.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ accessory.leadingAnchor.constraint(equalTo: accessoryViewContainer.leadingAnchor), accessory.topAnchor.constraint(equalTo: accessoryViewContainer.topAnchor), accessory.trailingAnchor.constraint(equalTo: accessoryViewContainer.trailingAnchor), accessory.bottomAnchor.constraint(equalTo: accessoryViewContainer.bottomAnchor) ] ) } } static func newInstance() -> TKUIResultsTitleView { return Bundle.tripKitUI.loadNibNamed("TKUIResultsTitleView", owner: self, options: nil)?.first as! TKUIResultsTitleView } override func awakeFromNib() { super.awakeFromNib() backgroundColor = .tkBackground originLabel.font = TKStyleManager.customFont(forTextStyle: .footnote) originLabel.textColor = .tkLabelSecondary destinationLabel.font = TKStyleManager.boldCustomFont(forTextStyle: .title3) destinationLabel.textColor = .tkLabelPrimary let fromToTapper = UITapGestureRecognizer(target: self, action: #selector(fromToTapped)) fromToTapper.delegate = self fromToStack.isUserInteractionEnabled = true fromToStack.addGestureRecognizer(fromToTapper) dismissButton.setImage(TGCard.closeButtonImage, for: .normal) dismissButton.setTitle(nil, for: .normal) dismissButton.accessibilityLabel = Loc.Close } func configure(destination: String?, origin: String?) { let destinationText: String if let name = destination { destinationText = Loc.To(location: name) } else { destinationText = Loc.PlanTrip } destinationLabel.text = destinationText let originName = origin ?? "…" let originText = Loc.From(location: originName) let attributedOrigin = NSMutableAttributedString(string: originText) attributedOrigin.addAttribute( .foregroundColor, value: UIColor.tkLabelSecondary, range: NSRange(location: 0, length: (originText as NSString).length) ) attributedOrigin.addAttribute( .foregroundColor, value: UIColor.tkAppTintColor, range: (originText as NSString).range(of: originName) ) originLabel.attributedText = attributedOrigin originLabel.isAccessibilityElement = false destinationLabel.isAccessibilityElement = false fromToStack.isAccessibilityElement = true if destination != nil, origin != nil { fromToStack.accessibilityLabel = originText + " - " + destinationText } else if destination != nil { fromToStack.accessibilityLabel = Loc.PlanTrip + " - " + destinationText } else if origin != nil { fromToStack.accessibilityLabel = Loc.PlanTrip + " - " + originText } else { fromToStack.accessibilityLabel = Loc.PlanTrip } fromToStack.accessibilityHint = Loc.TapToChangeStartAndEndLocations fromToStack.accessibilityTraits = .button accessibilityElements = [ dismissButton, fromToStack, accessoryView ].compactMap { $0 } } @objc @IBAction private func fromToTapped() { guard enableTappingLocation else { return } locationSearchPublisher.onNext(()) } } extension TKUIResultsTitleView: UIGestureRecognizerDelegate { func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } }
apache-2.0
f6846ce67dc6c367a28618ef3225fb8e
31.942675
155
0.730085
5.095567
false
false
false
false
imindeu/iMindLib.swift
Source/iMindLib/Extensions/Int+Extensions.swift
1
1656
// // Int+Extensions.swift // iMindLib // // Created by Mate Gregor on 2017. 01. 26.. // Copyright © 2017. iMind. All rights reserved. // import Foundation public extension Int { /// Converts to a shorter format /// - returns: The abbreviated string object public func abbreviate() -> String { let absValue = abs(self) let sign = self < 0 ? "-" : "" guard absValue >= 1000 else { return "\(sign)\(absValue)" } let doubleValue = Double(absValue) let exp = Int(log10(doubleValue) / 3.0 ) let units = ["k", "M", "G", "T", "P", "E"] let roundedValue = round(10 * doubleValue / pow(1000.0, Double(exp))) / 10 return "\(sign)\(Int(roundedValue))\(units[exp-1])" } /// Converts to it's roman number format /// - returns: The roman number string object public func toRoman() -> String { var number = self guard number > 0 else { return "" } let values = [("M", 1000), ("CM", 900), ("D", 500), ("CD", 400), ("C", 100), ("XC", 90), ("L", 50), ("XL", 40), ("X", 10), ("IX", 9), ("V", 5), ("IV", 4), ("I", 1)] return values.reduce("", { (result, value) -> String in let count = number / value.1 if count != 0 { return result + (1...count).reduce("", { (res, _) -> String in number -= value.1 return res + value.0 }) } return result }) } }
mit
eaded17664683cc850ed4e8fb2b28552
28.035088
82
0.45136
4.1375
false
false
false
false
jmgc/swift
test/Interop/Cxx/templates/function-template.swift
1
1159
// RUN: %target-run-simple-swift(-I %S/Inputs -Xfrontend -enable-cxx-interop) // // REQUIRES: executable_test import FunctionTemplates import StdlibUnittest var FunctionTemplateTestSuite = TestSuite("Function Templates") FunctionTemplateTestSuite.test("passThrough<T> where T == Int") { let result = passThrough(42) expectEqual(42, result) } FunctionTemplateTestSuite.test("add<T> where T == Int") { let result = add(42, 23) expectEqual(65, result) } FunctionTemplateTestSuite.test("add<T, U> where T, U == Int") { let result = addTwoTemplates(42, 23) expectEqual(65, result) } FunctionTemplateTestSuite.test("lvalueReference<T> where T == Int") { var value = 0 lvalueReference(&value) expectEqual(value, 42) } // TODO: currently "Any" is imported as an Objective-C "id". // This doesn't work without the Objective-C runtime. #if _runtime(_ObjC) FunctionTemplateTestSuite.test("passThrough<T> where T == Any") { let result = passThrough(42 as Any) expectEqual(42, result as! Int) } #endif // TODO: Generics, Any, and Protocols should be tested here but need to be // better supported in ClangTypeConverter first. runAllTests()
apache-2.0
4d2fe35fa847bd56b3de4baafa24fe2e
25.953488
77
0.728214
3.544343
false
true
false
false
bryanrezende/Audiobook-Player
Carthage/Checkouts/Chameleon/ChameleonExtension/KeyboardViewController.swift
3
2183
// // KeyboardViewController.swift // ChameleonExtension // // Created by Vicc Alexander on 9/17/16. // Copyright © 2016 Vicc Alexander. All rights reserved. // import UIKit import Chameleon class KeyboardViewController: UIInputViewController { @IBOutlet var nextKeyboardButton: UIButton! override func updateViewConstraints() { super.updateViewConstraints() // Add custom view sizing constraints here } override func viewDidLoad() { super.viewDidLoad() // Perform custom UI setup here self.nextKeyboardButton = UIButton(type: .system) self.nextKeyboardButton.setTitle(NSLocalizedString("Next Keyboard", comment: "Title for 'Next Keyboard' button"), for: []) self.nextKeyboardButton.sizeToFit() self.nextKeyboardButton.translatesAutoresizingMaskIntoConstraints = false self.nextKeyboardButton.addTarget(self, action: #selector(handleInputModeList(from:with:)), for: .allTouchEvents) self.view.addSubview(self.nextKeyboardButton) self.nextKeyboardButton.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true self.nextKeyboardButton.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true inputView?.backgroundColor = .flatGreen() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated } override func textWillChange(_ textInput: UITextInput?) { // The app is about to change the document's contents. Perform any preparation here. } override func textDidChange(_ textInput: UITextInput?) { // The app has just changed the document's contents, the document context has been updated. var textColor: UIColor let proxy = self.textDocumentProxy if proxy.keyboardAppearance == UIKeyboardAppearance.dark { textColor = UIColor.white } else { textColor = UIColor.black } self.nextKeyboardButton.setTitleColor(textColor, for: []) } }
gpl-3.0
cb2f217ba3a7c083daa09755792e2b41
33.09375
130
0.672319
5.455
false
false
false
false
hgani/ganilib-ios
glib/Classes/View/Layout/GSplitPanel.swift
1
4133
import UIKit open class GSplitPanel: UIView, IView { private var helper: ViewHelper! private var event: EventHelper<GSplitPanel>! public var size: CGSize { return helper.size } public init() { super.init(frame: .zero) initialize() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initialize() } private func initialize() { helper = ViewHelper(self) event = EventHelper(self) _ = paddings(top: 0, left: 0, bottom: 0, right: 0) } open override func didMoveToSuperview() { super.didMoveToSuperview() helper.didMoveToSuperview() } public func withViews(left: UIView, right: UIView) -> Self { // The hope is this makes things more predictable left.translatesAutoresizingMaskIntoConstraints = false right.translatesAutoresizingMaskIntoConstraints = false addSubview(left) addSubview(right) initConstraints(left: left, center: nil, right: right) return self } public func withViews(_ left: UIView, _ center: UIView, _ right: UIView) -> Self { // The hope is this makes things more predictable left.translatesAutoresizingMaskIntoConstraints = false center.translatesAutoresizingMaskIntoConstraints = false right.translatesAutoresizingMaskIntoConstraints = false // Avoid squashing the right view ViewHelper.decreaseResistance(view: center, axis: .horizontal) // Stretch the center view ViewHelper.minimumHugging(view: center, axis: .horizontal) addSubview(left) addSubview(center) addSubview(right) initConstraints(left: left, center: center, right: right) return self } private func initConstraints(left: UIView, center: UIView?, right: UIView) { left.snp.makeConstraints { make in make.top.equalTo(self.snp.topMargin) make.left.equalTo(self.snp.leftMargin) // make.right.greaterThanOrEqualTo(right.snp.left) // make.right.lessThanOrEqualTo(right.snp.left) } center?.snp.makeConstraints { make in make.top.equalTo(self.snp.topMargin) make.left.equalTo(left.snp.right) make.right.equalTo(right.snp.left) // make.width.equalTo(self) } right.snp.makeConstraints { make in make.top.equalTo(self.snp.topMargin) make.right.equalTo(self.snp.rightMargin) } snp.makeConstraints { make in // make.bottomMargin.equalTo(left.snp.bottom) // make.bottomMargin.equalTo(center.snp.bottom) // make.bottomMargin.equalTo(right.snp.bottom) make.bottomMargin.greaterThanOrEqualTo(left.snp.bottom) if let centerView = center { make.bottomMargin.greaterThanOrEqualTo(centerView.snp.bottom) } make.bottomMargin.greaterThanOrEqualTo(right.snp.bottom) } } public func width(_ width: Int) -> Self { helper.width(width) return self } public func width(_ width: LayoutSize) -> Self { helper.width(width) return self } public func height(_ height: Int) -> Self { helper.height(height) return self } public func height(_ height: LayoutSize) -> Self { helper.height(height) return self } public func paddings(top: Float? = nil, left: Float? = nil, bottom: Float? = nil, right: Float? = nil) -> Self { helper.paddings(t: top, l: left, b: bottom, r: right) return self } public func color(bg: UIColor) -> Self { backgroundColor = bg return self } public func onClick(_ command: @escaping (GSplitPanel) -> Void) -> Self { event.onClick(command) return self } public func interaction(_ enabled: Bool) -> Self { isUserInteractionEnabled = enabled return self } }
mit
858470f718ccaf448a9482aba4d6b73e
28.733813
116
0.607065
4.685941
false
false
false
false
lyimin/EyepetizerApp
EyepetizerApp/EyepetizerApp/Views/VideoDetailView/EYEVideoDetailView.swift
1
9208
// // EYEVideoDetailView.swift // EyepetizerApp // // Created by 梁亦明 on 16/3/23. // Copyright © 2016年 xiaoming. All rights reserved. // import UIKit protocol EYEVideoDetailViewDelegate { // 点击播放按钮 func playImageViewDidClick() // 点击返回按钮 func backBtnDidClick() } class EYEVideoDetailView: UIView { //MARK: --------------------------- Life Cycle -------------------------- override init(frame: CGRect) { super.init(frame: frame) self.clipsToBounds = true self.addSubview(albumImageView) self.addSubview(blurImageView) self.addSubview(blurView) self.addSubview(backBtn) self.addSubview(playImageView) self.addSubview(videoTitleLabel) self.addSubview(lineView) self.addSubview(classifyLabel) self.addSubview(describeLabel) self.addSubview(bottomToolView) // 添加底部item let itemSize: CGFloat = 80 for i in 0..<bottomImgArray.count { let btn = BottomItemBtn(frame: CGRect(x: UIConstant.UI_MARGIN_15+CGFloat(i)*itemSize, y: 0, width: itemSize, height: bottomToolView.height), title: "0", image: bottomImgArray[i]!) itemArray.append(btn) bottomToolView.addSubview(btn) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } var model : ItemModel! { didSet { // self.albumImageView.yy_setImageWithURL(NSURL(string: model.feed), placeholder: UIImage.colorImage(UIColor.lightGrayColor(), size: albumImageView.size)) // self.albumImageView.yy_setImageWithURL(NSURL(string: model.feed), options: .ProgressiveBlur) self.blurImageView.yy_setImageWithURL(NSURL(string:model.feed), placeholder: UIImage(named: "7e42a62065ef37cfa233009fb364fd1e_0_0")) videoTitleLabel.animationString = model.title self.classifyLabel.text = model.subTitle // 显示底部数据 self.itemArray.first?.setTitle("\(model.collectionCount)", forState: .Normal) self.itemArray[1].setTitle("\(model.shareCount)", forState: .Normal) self.itemArray[2].setTitle("\(model.replyCount)", forState: .Normal) self.itemArray.last?.setTitle("缓存", forState: .Normal) // 计算宽度 self.describeLabel.text = model.description let size = self.describeLabel.boundingRectWithSize(describeLabel.size) self.describeLabel.frame = CGRectMake(describeLabel.x, describeLabel.y, size.width, size.height) } } //MARK: --------------------------- Event response -------------------------- /** 点击播放按钮 */ @objc private func playImageViewDidClick() { delegate.playImageViewDidClick() } /** 点击返回按钮 */ @objc private func backBtnDidClick() { delegate.backBtnDidClick() } //MARK: --------------------------- Getter or Setter -------------------------- // 代理 var delegate: EYEVideoDetailViewDelegate! // 图片 lazy var albumImageView : UIImageView = { // 图片大小 1242 x 777 // 6 621*388.5 // 5 621*388.5 let photoW : CGFloat = 1222.0 let photoH : CGFloat = 777.0 let albumImageViewH = self.height*0.6 let albumImageViewW = photoW*albumImageViewH/photoH let albumImageViewX = (albumImageViewW-self.width)*0.5 // let imageViewH = self.width*photoH / UIConstant.IPHONE6_WIDTH var albumImageView = UIImageView(frame: CGRect(x: -albumImageViewX, y: 0, width: albumImageViewW, height: albumImageViewH)) albumImageView.clipsToBounds = true albumImageView.contentMode = .ScaleAspectFill albumImageView.userInteractionEnabled = true return albumImageView }() // 模糊背景 lazy var blurImageView : UIImageView = { var blurImageView = UIImageView(frame: CGRect(x: 0, y: self.albumImageView.height, width: self.width, height: self.height-self.albumImageView.height)) return blurImageView }() lazy var blurView : UIVisualEffectView = { let blurEffect : UIBlurEffect = UIBlurEffect(style: .Light) var blurView = UIVisualEffectView(effect: blurEffect) blurView.frame = self.blurImageView.frame return blurView }() // 返回按钮 lazy var backBtn : UIButton = { var backBtn = UIButton(frame: CGRect(x: UIConstant.UI_MARGIN_10, y: UIConstant.UI_MARGIN_20, width: 40, height: 40)) backBtn.setImage(UIImage(named: "play_back_full"), forState: .Normal) backBtn.addTarget(self, action: #selector(EYEVideoDetailView.backBtnDidClick), forControlEvents: .TouchUpInside) return backBtn }() // 播放按钮 lazy var playImageView : UIImageView = { var playImageView = UIImageView(image: UIImage(named: "ic_action_play")) playImageView.frame = CGRect(x: 0, y: 0, width: 60, height: 60) playImageView.center = self.albumImageView.center playImageView.contentMode = .ScaleAspectFit playImageView.viewAddTarget(self, action: #selector(EYEVideoDetailView.playImageViewDidClick)) return playImageView }() // 标题 lazy var videoTitleLabel : EYEShapeView = { let rect = CGRect(x: UIConstant.UI_MARGIN_10, y: CGRectGetMaxY(self.albumImageView.frame)+UIConstant.UI_MARGIN_10, width: self.width-2*UIConstant.UI_MARGIN_10, height: 20) let font = UIFont.customFont_FZLTZCHJW(fontSize: UIConstant.UI_FONT_16) var videoTitleLabel = EYEShapeView(frame: rect) videoTitleLabel.font = font videoTitleLabel.fontSize = UIConstant.UI_FONT_16 return videoTitleLabel }() // 分割线 private lazy var lineView : UIView = { var lineView = UIView(frame: CGRect(x: UIConstant.UI_MARGIN_10, y: CGRectGetMaxY(self.videoTitleLabel.frame)+UIConstant.UI_MARGIN_10, width: self.width-2*UIConstant.UI_MARGIN_10, height: 0.5)) lineView.backgroundColor = UIColor.whiteColor() return lineView }() // 分类/时间 lazy var classifyLabel : UILabel = { var classifyLabel = UILabel(frame: CGRect(x: UIConstant.UI_MARGIN_10, y: CGRectGetMaxY(self.lineView.frame)+UIConstant.UI_MARGIN_10, width: self.width-2*UIConstant.UI_MARGIN_10, height: 20)) classifyLabel.textColor = UIColor.whiteColor() classifyLabel.font = UIFont.customFont_FZLTXIHJW(fontSize: UIConstant.UI_FONT_13) return classifyLabel }() // 描述 lazy var describeLabel : UILabel = { var describeLabel = UILabel(frame: CGRect(x: UIConstant.UI_MARGIN_10, y: CGRectGetMaxY(self.classifyLabel.frame)+UIConstant.UI_MARGIN_10, width: self.width-2*UIConstant.UI_MARGIN_10, height: 200)) describeLabel.numberOfLines = 0 describeLabel.textColor = UIColor.whiteColor() describeLabel.font = UIFont.customFont_FZLTXIHJW(fontSize: UIConstant.UI_FONT_13) return describeLabel }() // 底部 喜欢 分享 评论 缓存 lazy var bottomToolView : UIView = { var bottomToolView = UIView(frame: CGRect(x: 0, y: self.height-50, width: self.width, height: 30)) bottomToolView.backgroundColor = UIColor.clearColor() return bottomToolView }() private var itemArray: [BottomItemBtn] = [BottomItemBtn]() // 底部图片数组 private var bottomImgArray = [UIImage(named: "ic_action_favorites_without_padding"), UIImage(named: "ic_action_share_without_padding"), UIImage(named: "ic_action_reply_nopadding"), UIImage(named: "action_download_cut")] /// 底部item private class BottomItemBtn : UIButton { // 标题 private var title: String! // 图片 private var image: UIImage! override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor.clearColor() self.titleLabel?.font = UIFont.customFont_FZLTXIHJW() self.setTitleColor(UIColor.whiteColor(), forState: .Normal) } convenience init(frame: CGRect, title: String, image: UIImage) { self.init(frame: frame) self.title = title self.image = image self.setImage(image, forState: .Normal) self.setTitle(title, forState: .Normal) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } /** 文字的frame */ private override func titleRectForContentRect(contentRect: CGRect) -> CGRect { return CGRect(x: self.height-8, y: 0, width: self.width-self.height+8, height: self.height) } /** 图片的frame */ private override func imageRectForContentRect(contentRect: CGRect) -> CGRect { return CGRect(x: 0, y: 8, width: self.height-16, height: self.height-16) } } }
mit
625a0e3fe855545fb9307e09a0e2adad
39.728507
223
0.63093
4.35462
false
false
false
false
jfosterdavis/Charles
Charles/AppStoreProductDetail.swift
1
3659
// // AppStoreProductDetail.swift // Charles // // Created by Jacob Foster Davis on 6/15/17. // Copyright © 2017 Zero Mu, LLC. All rights reserved. // import Foundation import UIKit import CoreData /******************************************************/ /*******************///MARK: This holds the local information (UI based) about products available on the app store /******************************************************/ public enum AppStoreProductDetailType { case givesPoints } class AppStoreProductDetail: CoreDataNSObject { //Note: name, description, price is kept at App Store //CoreData let keyCurrentScore = "CurrentScore" var productID: String var name: String var gameDescription: String var icon: UIImage var value: Int var type: AppStoreProductDetailType var minutesLocked: Int //once player buys this, how many minutes will this be locked var displayColor: UIColor var price: NSDecimalNumber var levelEligibleAt: Int? //nil if there is no level requirement var requiredPartyMembers: [Character] // MARK: Initializers init(productID: String, name: String, description: String, icon: UIImage, value: Int, type: AppStoreProductDetailType, minutesLocked: Int, displayColor: UIColor, price: NSDecimalNumber, levelEligibleAt: Int?, requiredPartyMembers: [Character] ) { self.productID = productID self.name = name self.gameDescription = description self.icon = icon self.value = value self.type = type self.minutesLocked = minutesLocked self.displayColor = displayColor self.price = price self.levelEligibleAt = levelEligibleAt self.requiredPartyMembers = requiredPartyMembers super.init() } //TODO: Impliment a more general function for in apps ///this function should be overriden. When called, it will deliver the product // func deliverProduct() { // switch self.type { // case .givesPoints: // givePointsToPlayer() // } // } func givePointsToPlayer() { //setup CoreData _ = setupFetchedResultsController(frcKey: keyCurrentScore, entityName: "CurrentScore", sortDescriptors: [], predicate: nil) guard let fc = frcDict[keyCurrentScore] else { fatalError("Could not get frcDict") } guard let currentScores = fc.fetchedObjects as? [CurrentScore] else { fatalError("Could not get array of currentScores") } let purchasedScorePoints = self.value if (currentScores.count) == 0 { print("No CurrentScore exists. Creating.") let currentScore = CurrentScore(entity: NSEntityDescription.entity(forEntityName: "CurrentScore", in: stack.context)!, insertInto: fc.managedObjectContext) currentScore.value += Int64(purchasedScorePoints) stack.save() return } else { switch purchasedScorePoints { //TODO: if the score is already 0 don't set it again. case let x where x < 0: currentScores[0].value = Int64(0) return default: //set score for the first element currentScores[0].value += Int64(purchasedScorePoints) //print("There are \(currentScores.count) score entries in the database.") return } } } }
apache-2.0
af651f242dc9679f6ee57d4d110f9bc1
31.087719
167
0.589666
4.970109
false
false
false
false
biohazardlover/ROer
CharacterSimulator/Character.swift
1
711
import SwiftyJSON struct Character { enum Gender: Int { case male case female } enum State: Int { case stand case waiting case casting case walking case sit case dead } enum Direction: Int { case south case southwest case southeast case west case northwest case north case northeast } struct Hair { } var state: State = .stand var headDirection: Direction = .south var bodyDirection: Direction = .south var otherDirection: Direction = .south var gender: Gender = .male var hair = Hair() }
mit
b34950a4105bd0d69e19fcc63908d4f4
15.928571
42
0.52602
5.152174
false
false
false
false
chrisdhaan/CDMarkdownKit
Source/CDMarkdownCode.swift
1
3176
// // CDMarkdownCode.swift // CDMarkdownKit // // Created by Christopher de Haan on 11/7/16. // // Copyright © 2016-2022 Christopher de Haan <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #if os(iOS) || os(tvOS) || os(watchOS) import UIKit #elseif os(macOS) import Cocoa #endif open class CDMarkdownCode: CDMarkdownCommonElement { fileprivate static let regex = "(\\s+|^|\\()(`{1})(\\s*[^`]*?\\s*)(\\2)(?!`)(\\)?)" open var font: CDFont? open var color: CDColor? open var backgroundColor: CDColor? open var paragraphStyle: NSParagraphStyle? open var regex: String { return CDMarkdownCode.regex } public init(font: CDFont? = CDFont(name: "Menlo-Regular", size: 12), color: CDColor? = CDColor.codeTextRed(), backgroundColor: CDColor? = CDColor.codeBackgroundRed(), paragraphStyle: NSParagraphStyle? = nil) { self.font = font self.color = color self.backgroundColor = backgroundColor self.paragraphStyle = paragraphStyle } open func addAttributes(_ attributedString: NSMutableAttributedString, range: NSRange) { let matchString: String = attributedString.attributedSubstring(from: range).string guard let unescapedString = matchString.unescapeUTF16() else { return } attributedString.replaceCharacters(in: range, with: unescapedString) let range = NSRange(location: range.location, length: unescapedString.characterCount()) attributedString.addAttributes(attributes, range: range) let mutableString = attributedString.mutableString // Remove \n if in string, not valid in Code element // Use Syntax element for \n to parse in string mutableString.replaceOccurrences(of: "\n", with: "", options: [], range: range) } }
mit
64ba710f0145c2521a357d0db27d922a
41.333333
90
0.64126
4.76012
false
false
false
false
jasnig/UsefulPickerView
UsefulPickerView/Example/Vc1Controller.swift
1
6339
// // Vc1Controller.swift // UsefulPickerVIew // // Created by jasnig on 16/4/24. // Copyright © 2016年 ZeroJ. All rights reserved. // github: https://github.com/jasnig // 简书: http://www.jianshu.com/users/fb31a3d1ec30/latest_articles // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit let singleData = ["swift", "ObjecTive-C", "C", "C++", "java", "php", "python", "ruby", "js"] // 每一列为数组 let multipleData = [["1天", "2天", "3天", "4天", "5天", "6天", "7天"],["1小时", "2小时", "3小时", "4小时", "5小时"], ["1分钟","2分钟","3分钟","4分钟","5分钟","6分钟","7分钟","8分钟","9分钟","10分钟"]] // 注意这个数据的格式!!!!!! let multipleAssociatedData: [[[String: [String]?]]] = [// 数组 [ ["交通工具": ["陆地", "空中", "水上"]],//字典 ["食品": ["健康食品", "垃圾食品"]], ["游戏": ["益智游戏", "角色游戏"]] ],// 数组 [ ["陆地": ["公交车", "小轿车", "自行车"]], ["空中": ["飞机"]], ["水上": ["轮船"]], ["健康食品": ["蔬菜", "水果"]], ["垃圾食品": ["辣条", "不健康小吃"]], ["益智游戏": ["消消乐", "消灭星星"]], ["角色游戏": ["lol", "cf"]] ] ] class Vc1Controller: UIViewController { @IBOutlet weak var selectedDataLabel: UILabel! @IBAction func singleBtnOnClick(_ sender: UIButton) { UsefulPickerView.showSingleColPicker("编程语言选择", data: singleData, defaultSelectedIndex: 2) {[unowned self] (selectedIndex, selectedValue) in self.selectedDataLabel.text = "选中了第\(selectedIndex)行----选中的数据为\(selectedValue)" } } @IBAction func multipleBtnOnClick(_ sender: UIButton) { UsefulPickerView.showMultipleColsPicker("持续时间选择", data: multipleData, defaultSelectedIndexs: [0,1,1]) {[unowned self] (selectedIndexs, selectedValues) in self.selectedDataLabel.text = "选中了第\(selectedIndexs)行----选中的数据为\(selectedValues)" } } @IBAction func multipleAssociatedBtnOnClick(_ sender: UIButton) { // 注意这里设置的是默认的选中值, 而不是选中的下标,省得去数关联数组里的下标 UsefulPickerView.showMultipleAssociatedColsPicker("多列关联数据", data: multipleAssociatedData, defaultSelectedValues: ["交通工具","陆地","自行车"]) {[unowned self] (selectedIndexs, selectedValues) in self.selectedDataLabel.text = "选中了第\(selectedIndexs)行----选中的数据为\(selectedValues)" } } @IBAction func citiesBtnOnClick(_ sender: UIButton) { // 注意设置默认值得时候, 必须设置完整, 不能进行省略 ["四川", "成都", "成华区"] 比如不能设置为["四川", "成都"] // ["北京", "通州"] 不能设置为["北京"] UsefulPickerView.showCitiesPicker("省市区选择", defaultSelectedValues: ["北京", "/", "/"], selectTopLevel: true) {[unowned self] (selectedIndexs, selectedValues) in // 处理数据 let combinedString = selectedValues.reduce("", { (result, value) -> String in result + " " + value }) self.selectedDataLabel.text = "选中了第\(selectedIndexs)行----选中的数据为\(combinedString)" } } @IBAction func dateBtnOnClick(_ sender: UIButton) { UsefulPickerView.showDatePicker("日期选择") {[unowned self] ( selectedDate) in let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd" let string = formatter.string(from: selectedDate) self.selectedDataLabel.text = "选中了的日期是\(string)" } } @IBAction func timeBtnOnClick(_ sender: UIButton) { /// /// @author ZeroJ, 16-04-25 17:04:28 // style里面可以更改的和系统的DatePicker属性是一一对应的 var dateStyle = DatePickerSetting() dateStyle.dateMode = .time UsefulPickerView.showDatePicker("时间选择", datePickerSetting: dateStyle) { (selectedDate) in let formatter = DateFormatter() // H -> 24小时制 formatter.dateFormat = "HH: mm" let string = formatter.string(from: selectedDate) self.selectedDataLabel.text = "选中了的日期是\(string)" } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
78207aa8d67375d38d088fc923c44b47
36.271523
193
0.617271
3.865385
false
false
false
false
nderkach/FlightKit
Pod/Classes/CVCalendar/CVCalendarDayView.swift
4
18620
// // CVCalendarDayView.swift // CVCalendar // // Created by E. Mozharovsky on 12/26/14. // Copyright (c) 2014 GameApp. All rights reserved. // import UIKit public final class CVCalendarDayView: UIView { // MARK: - Public properties public let weekdayIndex: Int! public weak var weekView: CVCalendarWeekView! public var date: CVDate! public var dayLabel: UILabel! public var circleView: CVAuxiliaryView? public var topMarker: CALayer? public var dotMarkers = [CVAuxiliaryView?]() public var isOut = false public var isCurrentDay = false public weak var monthView: CVCalendarMonthView! { get { var monthView: MonthView! if let weekView = weekView, let activeMonthView = weekView.monthView { monthView = activeMonthView } return monthView } } public weak var calendarView: CVCalendarView! { get { var calendarView: CVCalendarView! if let weekView = weekView, let activeCalendarView = weekView.calendarView { calendarView = activeCalendarView } return calendarView } } public override var frame: CGRect { didSet { if oldValue != frame { circleView?.setNeedsDisplay() topMarkerSetup() preliminarySetup() supplementarySetup() } } } public override var hidden: Bool { didSet { userInteractionEnabled = hidden ? false : true } } // MARK: - Initialization public init(weekView: CVCalendarWeekView, weekdayIndex: Int) { self.weekView = weekView self.weekdayIndex = weekdayIndex if let size = weekView.calendarView.dayViewSize { let hSpace = weekView.calendarView.appearance.spaceBetweenDayViews! let x = (CGFloat(weekdayIndex - 1) * (size.width + hSpace)) + (hSpace/2) super.init(frame: CGRectMake(x, 0, size.width, size.height)) } else { super.init(frame: CGRectZero) } date = dateWithWeekView(weekView, andWeekIndex: weekdayIndex) labelSetup() setupDotMarker() topMarkerSetup() if (frame.width > 0) { preliminarySetup() supplementarySetup() } if !calendarView.shouldShowWeekdaysOut && isOut { hidden = true } } public func dateWithWeekView(weekView: CVCalendarWeekView, andWeekIndex index: Int) -> CVDate { func hasDayAtWeekdayIndex(weekdayIndex: Int, weekdaysDictionary: [Int : [Int]]) -> Bool { for key in weekdaysDictionary.keys { if key == weekdayIndex { return true } } return false } var day: Int! let weekdaysIn = weekView.weekdaysIn if let weekdaysOut = weekView.weekdaysOut { if hasDayAtWeekdayIndex(weekdayIndex, weekdaysDictionary: weekdaysOut) { isOut = true day = weekdaysOut[weekdayIndex]![0] } else if hasDayAtWeekdayIndex(weekdayIndex, weekdaysDictionary: weekdaysIn!) { day = weekdaysIn![weekdayIndex]![0] } } else { day = weekdaysIn![weekdayIndex]![0] } if day == monthView.currentDay && !isOut { let dateRange = Manager.dateRange(monthView.date) let currentDateRange = Manager.dateRange(NSDate()) if dateRange.month == currentDateRange.month && dateRange.year == currentDateRange.year { isCurrentDay = true } } let dateRange = Manager.dateRange(monthView.date) let year = dateRange.year let week = weekView.index + 1 var month = dateRange.month if isOut { day > 20 ? month-- : month++ } return CVDate(day: day, month: month, week: week, year: year) } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: - Subviews setup extension CVCalendarDayView { public func labelSetup() { let appearance = calendarView.appearance dayLabel = UILabel() dayLabel!.text = String(date.day) dayLabel!.textAlignment = NSTextAlignment.Center dayLabel!.frame = bounds var font = appearance.dayLabelWeekdayFont var color: UIColor? if isOut { color = appearance.dayLabelWeekdayOutTextColor } else if isCurrentDay { let coordinator = calendarView.coordinator if coordinator.selectedDayView == nil { let touchController = calendarView.touchController touchController.receiveTouchOnDayView(self) calendarView.didSelectDayView(self) } else { color = appearance.dayLabelPresentWeekdayTextColor if appearance.dayLabelPresentWeekdayInitallyBold! { font = appearance.dayLabelPresentWeekdayBoldFont } else { font = appearance.dayLabelPresentWeekdayFont } } } else { color = appearance.dayLabelWeekdayInTextColor } if color != nil && font != nil { dayLabel!.textColor = color! dayLabel!.font = font } addSubview(dayLabel!) } public func preliminarySetup() { if let delegate = calendarView.delegate, shouldShow = delegate.preliminaryView?(shouldDisplayOnDayView: self) where shouldShow { if let preView = delegate.preliminaryView?(viewOnDayView: self) { insertSubview(preView, atIndex: 0) preView.layer.zPosition = CGFloat(-MAXFLOAT) } } } public func supplementarySetup() { if let delegate = calendarView.delegate, shouldShow = delegate.supplementaryView?(shouldDisplayOnDayView: self) where shouldShow { if let supView = delegate.supplementaryView?(viewOnDayView: self) { insertSubview(supView, atIndex: 0) } } } // TODO: Make this widget customizable public func topMarkerSetup() { safeExecuteBlock({ func createMarker() { let height = CGFloat(0.5) let layer = CALayer() layer.borderColor = UIColor.grayColor().CGColor layer.borderWidth = height layer.frame = CGRectMake(0, 1, CGRectGetWidth(self.frame), height) self.topMarker = layer self.layer.addSublayer(self.topMarker!) } if let delegate = self.calendarView.delegate { if self.topMarker != nil { self.topMarker?.removeFromSuperlayer() self.topMarker = nil } if let shouldDisplay = delegate.topMarker?(shouldDisplayOnDayView: self) where shouldDisplay { createMarker() } } else { if self.topMarker == nil { createMarker() } else { self.topMarker?.removeFromSuperlayer() self.topMarker = nil createMarker() } } }, collapsingOnNil: false, withObjects: weekView, weekView.monthView, weekView.monthView) } public func setupDotMarker() { for (index, dotMarker) in dotMarkers.enumerate() { dotMarkers[index]!.removeFromSuperview() dotMarkers[index] = nil } if let delegate = calendarView.delegate { if let shouldShow = delegate.dotMarker?(shouldShowOnDayView: self) where shouldShow { let (width, height):(CGFloat, CGFloat) = (13, 13) let colors = isOut ? [.grayColor()] : delegate.dotMarker?(colorOnDayView: self) var yOffset = bounds.height / 5 if let y = delegate.dotMarker?(moveOffsetOnDayView: self) { yOffset = y } let y = CGRectGetMidY(frame) + yOffset let markerFrame = CGRectMake(0, 0, width, height) if (colors!.count > 3) { assert(false, "Only 3 dot markers allowed per day") } for (index, color) in (colors!).enumerate() { var x: CGFloat = 0 switch(colors!.count) { case 1: x = frame.width / 2 case 2: x = frame.width * CGFloat(2+index)/5.00 // frame.width * (2/5, 3/5) case 3: x = frame.width * CGFloat(2+index)/6.00 // frame.width * (1/3, 1/2, 2/3) default: break } let dotMarker = CVAuxiliaryView(dayView: self, rect: markerFrame, shape: .Circle) dotMarker.fillColor = color dotMarker.center = CGPointMake(x, y) insertSubview(dotMarker, atIndex: 0) dotMarker.setNeedsDisplay() dotMarkers.append(dotMarker) } let coordinator = calendarView.coordinator if self == coordinator.selectedDayView { moveDotMarkerBack(true, coloring: false) } } } } } // MARK: - Dot marker movement extension CVCalendarDayView { public func moveDotMarkerBack(unwinded: Bool, var coloring: Bool) { for dotMarker in dotMarkers { if let calendarView = calendarView, let dotMarker = dotMarker { var shouldMove = true if let delegate = calendarView.delegate, let move = delegate.dotMarker?(shouldMoveOnHighlightingOnDayView: self) where !move { shouldMove = move } func colorMarker() { if let delegate = calendarView.delegate { let appearance = calendarView.appearance let frame = dotMarker.frame var color: UIColor? if unwinded { if let myColor = delegate.dotMarker?(colorOnDayView: self) { color = (isOut) ? appearance.dayLabelWeekdayOutTextColor : myColor.first } } else { color = appearance.dotMarkerColor } dotMarker.fillColor = color dotMarker.setNeedsDisplay() } } func moveMarker() { var transform: CGAffineTransform! if let circleView = circleView { let point = pointAtAngle(CGFloat(-90).toRadians(), withinCircleView: circleView) let spaceBetweenDotAndCircle = CGFloat(1) let offset = point.y - dotMarker.frame.origin.y - dotMarker.bounds.height/2 + spaceBetweenDotAndCircle transform = unwinded ? CGAffineTransformIdentity : CGAffineTransformMakeTranslation(0, offset) if dotMarker.center.y + offset > CGRectGetMaxY(frame) { coloring = true } } else { transform = CGAffineTransformIdentity } if !coloring { UIView.animateWithDuration(0.3, delay: 0, usingSpringWithDamping: 0.6, initialSpringVelocity: 0, options: UIViewAnimationOptions.CurveEaseOut, animations: { dotMarker.transform = transform }, completion: { _ in }) } else { moveDotMarkerBack(unwinded, coloring: coloring) } } if shouldMove && !coloring { moveMarker() } else { colorMarker() } } } } } // MARK: - Circle geometry extension CGFloat { public func toRadians() -> CGFloat { return CGFloat(self) * CGFloat(M_PI / 180) } public func toDegrees() -> CGFloat { return CGFloat(180/M_PI) * self } } extension CVCalendarDayView { public func pointAtAngle(angle: CGFloat, withinCircleView circleView: UIView) -> CGPoint { let radius = circleView.bounds.width / 2 let xDistance = radius * cos(angle) let yDistance = radius * sin(angle) let center = circleView.center let x = floor(cos(angle)) < 0 ? center.x - xDistance : center.x + xDistance let y = center.y - yDistance let result = CGPointMake(x, y) return result } public func moveView(view: UIView, onCircleView circleView: UIView, fromAngle angle: CGFloat, toAngle endAngle: CGFloat, straight: Bool) { let condition = angle > endAngle ? angle > endAngle : angle < endAngle if straight && angle < endAngle || !straight && angle > endAngle { UIView.animateWithDuration(pow(10, -1000), delay: 0, usingSpringWithDamping: 0.4, initialSpringVelocity: 10, options: UIViewAnimationOptions.CurveEaseIn, animations: { let angle = angle.toRadians() view.center = self.pointAtAngle(angle, withinCircleView: circleView) }) { _ in let speed = CGFloat(750).toRadians() let newAngle = straight ? angle + speed : angle - speed self.moveView(view, onCircleView: circleView, fromAngle: newAngle, toAngle: endAngle, straight: straight) } } } } // MARK: - Day label state management extension CVCalendarDayView { public func setSelectedWithType(type: SelectionType) { let appearance = calendarView.appearance var backgroundColor: UIColor! var backgroundAlpha: CGFloat! var shape: CVShape! switch type { case let .Single: shape = .Circle if isCurrentDay { dayLabel?.textColor = appearance.dayLabelPresentWeekdaySelectedTextColor! dayLabel?.font = appearance.dayLabelPresentWeekdaySelectedFont backgroundColor = appearance.dayLabelPresentWeekdaySelectedBackgroundColor backgroundAlpha = appearance.dayLabelPresentWeekdaySelectedBackgroundAlpha } else { dayLabel?.textColor = appearance.dayLabelWeekdaySelectedTextColor dayLabel?.font = appearance.dayLabelWeekdaySelectedFont backgroundColor = appearance.dayLabelWeekdaySelectedBackgroundColor backgroundAlpha = appearance.dayLabelWeekdaySelectedBackgroundAlpha } case let .Range: shape = .Rect if isCurrentDay { dayLabel?.textColor = appearance.dayLabelPresentWeekdayHighlightedTextColor! dayLabel?.font = appearance.dayLabelPresentWeekdayHighlightedFont backgroundColor = appearance.dayLabelPresentWeekdayHighlightedBackgroundColor backgroundAlpha = appearance.dayLabelPresentWeekdayHighlightedBackgroundAlpha } else { dayLabel?.textColor = appearance.dayLabelWeekdayHighlightedTextColor dayLabel?.font = appearance.dayLabelWeekdayHighlightedFont backgroundColor = appearance.dayLabelWeekdayHighlightedBackgroundColor backgroundAlpha = appearance.dayLabelWeekdayHighlightedBackgroundAlpha } default: break } if let circleView = circleView where circleView.frame != dayLabel.bounds { circleView.frame = dayLabel.bounds } else { circleView = CVAuxiliaryView(dayView: self, rect: dayLabel.bounds, shape: shape) } circleView!.fillColor = backgroundColor circleView!.alpha = backgroundAlpha circleView!.setNeedsDisplay() insertSubview(circleView!, atIndex: 0) moveDotMarkerBack(false, coloring: false) } public func setDeselectedWithClearing(clearing: Bool) { if let calendarView = calendarView, let appearance = calendarView.appearance { var color: UIColor? if isOut { color = appearance.dayLabelWeekdayOutTextColor } else if isCurrentDay { color = appearance.dayLabelPresentWeekdayTextColor } else { color = appearance.dayLabelWeekdayInTextColor } var font: UIFont? if isCurrentDay { if appearance.dayLabelPresentWeekdayInitallyBold! { font = appearance.dayLabelPresentWeekdayBoldFont } else { font = appearance.dayLabelWeekdayFont } } else { font = appearance.dayLabelWeekdayFont } dayLabel?.textColor = color dayLabel?.font = font moveDotMarkerBack(true, coloring: false) if clearing { circleView?.removeFromSuperview() } } } } // MARK: - Content reload extension CVCalendarDayView { public func reloadContent() { setupDotMarker() dayLabel?.frame = bounds let shouldShowDaysOut = calendarView.shouldShowWeekdaysOut! if !shouldShowDaysOut { if isOut { hidden = true } } else { if isOut { hidden = false } } if circleView != nil { setSelectedWithType(.Single) } } } // MARK: - Safe execution extension CVCalendarDayView { public func safeExecuteBlock(block: Void -> Void, collapsingOnNil collapsing: Bool, withObjects objects: AnyObject?...) { for object in objects { if object == nil { if collapsing { fatalError("Object { \(object) } must not be nil!") } else { return } } } block() } }
mit
017274bff4f9e810d74caf18a8ef66a9
33.738806
180
0.556391
5.540018
false
false
false
false
YinChangDao/DouYu
DouYU/DouYU/Classes/Tools/View/PageContentView.swift
1
2711
// // PageContentView.swift // DouYU // // Created by 饮长刀 on 2017/4/4. // Copyright © 2017年 饮长刀. All rights reserved. // import UIKit private let pageContentViewCellId = "pageContentViewCellId" class PageContentView: UIView { fileprivate var childVcs : [UIViewController] fileprivate weak var parentVc : UIViewController? fileprivate lazy var collectionView : UICollectionView = {[weak self] in let layout = UICollectionViewFlowLayout() layout.itemSize = (self?.bounds.size)! layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.scrollDirection = .horizontal let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout) collectionView.showsHorizontalScrollIndicator = false collectionView.backgroundColor = UIColor.white collectionView.isPagingEnabled = true collectionView.bounces = true collectionView.dataSource = self collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: pageContentViewCellId) return collectionView }() init(frame: CGRect, childVcs: [UIViewController], parentVc: UIViewController?) { self.childVcs = childVcs self.parentVc = parentVc super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension PageContentView { fileprivate func setupUI() { for childVc in childVcs { parentVc?.addChildViewController(childVc) } addSubview(collectionView) collectionView.frame = bounds } } extension PageContentView : UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return childVcs.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: pageContentViewCellId, for: indexPath) for view in cell.contentView.subviews { view.removeFromSuperview() } let childVc = childVcs[indexPath.item] childVc.view.frame = cell.contentView.bounds cell.contentView.addSubview(childVc.view) return cell } } extension PageContentView { func setCurrentIndex(currentIndex : Int) { let offsetX = CGFloat(currentIndex) * collectionView.frame.width collectionView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: false) } }
mit
f506b3585a17e80f136da11694ae7cb7
31.481928
121
0.687685
5.490835
false
false
false
false
Performador/Pickery
Pickery/Appearance.swift
1
2036
// // Appearance.swift // Pickery // // Created by Okan Arikan on 8/12/16. // // import Foundation import UIKit import FontAwesome_swift /// Defines the functionality for defining the app appearance class Appearance { /// The constants related to the appearance struct Constants { /// Some predefined font sizes static let kMainFontName = "Heiti SC" static let kXLargeFontSize = CGFloat(24) static let kLargeFontSize = CGFloat(20) static let kBaseFontSize = CGFloat(18) static let kSmallFontSize = CGFloat(12) /// System fonts static let kXLargeSysFont = UIFont.systemFont(ofSize: kXLargeFontSize) static let kLargeSysFont = UIFont.systemFont(ofSize: kLargeFontSize) static let kBaseSysFont = UIFont.systemFont(ofSize: kBaseFontSize) static let kSmallSysFont = UIFont.systemFont(ofSize: kSmallFontSize) /// FontAwesome fonts static let kXLargeIconFont = UIFont.fontAwesome(ofSize: kXLargeFontSize) static let kLargeIconFont = UIFont.fontAwesome(ofSize: kLargeFontSize) static let kBaseIconFont = UIFont.fontAwesome(ofSize: kBaseFontSize) static let kSmallIconFont = UIFont.fontAwesome(ofSize: kSmallFontSize) /// The nice fonts static let kXLargeFont = UIFont(name: kMainFontName, size: kXLargeFontSize) ?? kXLargeSysFont static let kLargeFont = UIFont(name: kMainFontName, size: kLargeFontSize) ?? kLargeSysFont static let kBaseFont = UIFont(name: kMainFontName, size: kBaseFontSize) ?? kBaseSysFont static let kSmallFont = UIFont(name: kMainFontName, size: kSmallFontSize) ?? kSmallSysFont } /// Setup the app appearance here class func setupAppearance() { } }
mit
e6172a0083d0b7c56d9fe9ca62a534e0
41.416667
116
0.610511
4.55481
false
false
false
false
silence0201/Swift-Study
AdvancedSwift/集合/Dictionary/Dictionaries - Some Useful Dictionary Extensions.playgroundpage/Contents.swift
1
4173
/*: ### Some Useful Dictionary Extensions What if we wanted to combine the default settings dictionary with any custom settings the user has changed? Custom settings should override defaults, but the resulting dictionary should still include default values for any keys that haven't been customized. Essentially, we want to merge two dictionaries, where the dictionary that's being merged in overwrites duplicate keys. The standard library doesn't include a function for this, so let's write one. We can extend `Dictionary` with a `merge` method that takes the key-value pairs to be merged in as its only argument. We could make this argument another `Dictionary`, but this is a good opportunity for a more generic solution. Our requirements for the argument are that it must be a sequence we can loop over, and the sequence's elements must be key-value pairs of the same type as the receiving dictionary. Any `Sequence` whose `Iterator.Element` is a `(Key, Value)` pair meets these requirements, so that's what the method's generic constraints should express (`Key` and `Value` here are the generic type parameters of the `Dictionary` type we're extending): */ //#-editable-code extension Dictionary { mutating func merge<S>(_ other: S) where S: Sequence, S.Iterator.Element == (key: Key, value: Value) { for (k, v) in other { self[k] = v } } } //#-end-editable-code /*: We can use this to merge one dictionary into another, as shown in the following example, but the method argument could just as well be an array of key-value pairs or any other sequence: */ //#-hidden-code enum Setting { case text(String) case int(Int) case bool(Bool) } let defaultSettings: [String:Setting] = [ "Airplane Mode": .bool(true), "Name": .text("My iPhone"), ] //#-end-hidden-code //#-editable-code var settings = defaultSettings let overriddenSettings: [String:Setting] = ["Name": .text("Jane's iPhone")] settings.merge(overriddenSettings) settings //#-end-editable-code /*: Another interesting extension is creating a dictionary from a sequence of `(Key, Value)` pairs. The standard library provides a similar initializer for arrays that comes up very frequently; you use it every time you create an array from a range (`Array(1...10)`) or convert an `ArraySlice` back into a proper array (`Array(someSlice)`). However, there's no such initializer for `Dictionary`. (There is a Swift-Evolution proposal [to add one](https://github.com/apple/swift-evolution/blob/master/proposals/0100-add-sequence-based-init-and-merge-to-dictionary.md), though, so we may see it in the future.) We can start with an empty dictionary and then just merge in the sequence. This makes use of the `merge` method defined above to do the heavy lifting: */ //#-editable-code extension Dictionary { init<S: Sequence>(_ sequence: S) where S.Iterator.Element == (key: Key, value: Value) { self = [:] self.merge(sequence) } } // All alarms are turned off by default let defaultAlarms = (1..<5).map { (key: "Alarm \($0)", value: false) } let alarmsDictionary = Dictionary(defaultAlarms) //#-end-editable-code /*: A third useful extension is a `map` over the dictionary's values. Because `Dictionary` is a `Sequence`, it already has a `map` method that produces an array. However, sometimes we want to keep the dictionary structure intact and only transform its values. Our `mapValues` method first calls the standard `map` to create an array of *(key, transformed value)* pairs and then uses the new initializer we defined above to turn it back into a dictionary: */ //#-editable-code extension Dictionary { func mapValues<NewValue>(transform: (Value) -> NewValue) -> [Key:NewValue] { return Dictionary<Key, NewValue>(map { (key, value) in return (key, transform(value)) }) } } let settingsAsStrings = settings.mapValues { setting -> String in switch setting { case .text(let text): return text case .int(let number): return String(number) case .bool(let value): return String(value) } } settingsAsStrings //#-end-editable-code
mit
9d4d39ce000cff752cf47fcec0b82a81
34.364407
125
0.719387
4.047527
false
false
false
false
tranhieutt/Swiftz
SwiftzTests/IdentitySpec.swift
1
2567
// // IdentitySpec.swift // Swiftz // // Created by Robert Widmann on 8/19/15. // Copyright © 2015 TypeLift. All rights reserved. // import XCTest import Swiftz import SwiftCheck extension Identity where T : Arbitrary { public static var arbitrary : Gen<Identity<A>> { return Identity.pure <^> A.arbitrary } } extension Identity : WitnessedArbitrary { public typealias Param = T public static func forAllWitnessed<A : Arbitrary>(wit : A -> T)(pf : (Identity<T> -> Testable)) -> Property { return forAllShrink(Identity<A>.arbitrary, shrinker: const([]), f: { bl in return pf(bl.fmap(wit)) }) } } class IdentitySpec : XCTestCase { func testProperties() { property("Identity obeys the Functor identity law") <- forAll { (x : Identity<Int>) in return (x.fmap(identity)) == identity(x) } property("Identity obeys the Functor composition law") <- forAll { (f : ArrowOf<Int, Int>, g : ArrowOf<Int, Int>) in return forAll { (x : Identity<Int>) in return ((f.getArrow • g.getArrow) <^> x) == (x.fmap(g.getArrow).fmap(f.getArrow)) } } property("Identity obeys the Applicative identity law") <- forAll { (x : Identity<Int>) in return (Identity.pure(identity) <*> x) == x } property("Identity obeys the first Applicative composition law") <- forAll { (fl : Identity<ArrowOf<Int8, Int8>>, gl : Identity<ArrowOf<Int8, Int8>>, x : Identity<Int8>) in let f = fl.fmap({ $0.getArrow }) let g = gl.fmap({ $0.getArrow }) let l = (curry(•) <^> f <*> g <*> x) let r = (f <*> (g <*> x)) return l == r } property("Identity obeys the second Applicative composition law") <- forAll { (fl : Identity<ArrowOf<Int8, Int8>>, gl : Identity<ArrowOf<Int8, Int8>>, x : Identity<Int8>) in let f = fl.fmap({ $0.getArrow }) let g = gl.fmap({ $0.getArrow }) let l = (Identity.pure(curry(•)) <*> f <*> g <*> x) let r = (f <*> (g <*> x)) return l == r } property("Identity obeys the Monad left identity law") <- forAll { (a : Int, fa : ArrowOf<Int, Int>) in let f = Identity.pure • fa.getArrow return (Identity.pure(a) >>- f) == f(a) } property("Identity obeys the Monad right identity law") <- forAll { (m : Identity<Int>) in return (m >>- Identity.pure) == m } property("Identity obeys the Monad associativity law") <- forAll { (fa : ArrowOf<Int, Int>, ga : ArrowOf<Int, Int>) in let f = Identity.pure • fa.getArrow let g = Identity.pure • ga.getArrow return forAll { (m : Identity<Int>) in return ((m >>- f) >>- g) == (m >>- { x in f(x) >>- g }) } } } }
bsd-3-clause
486e88e2d654e1199c5b9350a83577d9
30.925
175
0.62177
3.232911
false
false
false
false
mpclarkson/StravaSwift
Sources/StravaSwift/Route.swift
1
1493
// // Route.swift // Pods // // Created by MATTHEW CLARKSON on 25/05/2016. // // import SwiftyJSON /** Routes are manually-created paths made up of sections called legs. **/ public final class Route: Strava { public let id: Int? public let resourceState: ResourceState? public let name: String? public let description: String? public let athlete: Athlete? public let distance: Double? public let elevationGain: Double? public let map: Map? public let type: RouteType? public let subType: RouteSubType? public let `private`: Bool? public let starred: Bool? public let timeStamp: Int? public let segments: [Segment]? /** Initializer - Parameter json: SwiftyJSON object - Internal **/ required public init(_ json: JSON) { id = json["id"].int resourceState = json["resource_state"].strava(ResourceState.self) name = json["name"].string description = json["description"].string athlete = json["athlete"].strava(Athlete.self) distance = json["distance"].double elevationGain = json["elevation_gain"].double map = json["map"].strava(Map.self) type = json["type"].strava(RouteType.self) subType = json["sub_type"].strava(RouteSubType.self) `private` = json["private"].bool starred = json["starred"].bool timeStamp = json["time_stamp"].int segments = json["segments"].strava(Segment.self) } }
mit
4833e78a0519695718bf70a395f3ef61
27.711538
73
0.635633
4.101648
false
false
false
false
thabz/NDHpple
NDHpple/AppDelegate.swift
1
3072
// // AppDelegate.swift // NDHpple // // Created by Nicolai on 24/06/14. // Copyright (c) 2014 Nicolai Davidsson. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func showNDHpple() { NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: "http://www.reddit.com/r/swift")!) { data, response, error in let html = NSString(data: data, encoding: NSUTF8StringEncoding) let parser = NDHpple(HTMLData: html!) let old_xpath = "/html/body/div[3]/div[2]/div/div[2]/p[@class='title']/a" let xpath = "//*[@id='siteTable']/div/div[2]/p[@class='title']/a" let titles = parser.searchWithXPathQuery(xpath)! for node in titles { println(node.firstChild?.content?) } }.resume() } func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool { self.window = UIWindow(frame: UIScreen.mainScreen().bounds) // Override point for customization after application launch. self.window!.backgroundColor = UIColor.whiteColor() self.window!.makeKeyAndVisible() showNDHpple() 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:. } }
mit
06faaa3d3c91e303baaaff68d1e17728
42.885714
285
0.683268
5.278351
false
false
false
false
safx/IIJMioKit
IIJMioKit/OAuth2AccountStore.swift
1
3530
// // OAuth2AccountStore.swift // IIJMioKit // // Created by Safx Developer on 2014/09/22. // Copyright (c) 2014年 Safx Developers. All rights reserved. // import Foundation public enum KeychainResult: String { case Success = "No error." case Unimplemented = "Function or operation not implemented." case Param = "One or more parameters passed to the function were not valid." case Allocate = "Failed to allocate memory." case NotAvailable = "No trust results are available." case AuthFailed = "Authorization/Authentication failed." case DuplicateItem = "The item already exists." case ItemNotFound = "The item cannot be found." case InteractionNotAllowed = "Interaction with the Security Server is not allowed." case Decode = "Unable to decode the provided data." case Unknown = "Unknown error." public init(status: OSStatus) { switch status { case OSStatus(errSecSuccess) : self = .Success case OSStatus(errSecUnimplemented) : self = .Unimplemented case OSStatus(errSecParam) : self = .Param case OSStatus(errSecAllocate) : self = .Allocate case OSStatus(errSecNotAvailable) : self = .NotAvailable case OSStatus(errSecAuthFailed) : self = .AuthFailed case OSStatus(errSecDuplicateItem) : self = .DuplicateItem case OSStatus(errSecItemNotFound) : self = .ItemNotFound case OSStatus(errSecInteractionNotAllowed) : self = .InteractionNotAllowed case OSStatus(errSecDecode) : self = .Decode default : self = .Unknown } } } public class OAuth2AccountStore { private let serviceName: String init(serviceName: String) { self.serviceName = serviceName } private var attributes: [String:AnyObject] { return [ kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: serviceName, ] } public func loadAccessToken() -> (status: KeychainResult, token: String?) { var attrs = attributes attrs[kSecReturnAttributes as String] = kCFBooleanTrue var result: AnyObject? let status = withUnsafeMutablePointer(&result) { SecItemCopyMatching(attrs, UnsafeMutablePointer($0)) } if status == OSStatus(errSecSuccess) { let q = result as! NSDictionary let k = String(kSecAttrGeneric) if let data = q[k] as? NSString { return (KeychainResult(status: status), data as String) } else { return (.Unknown, nil) } } return (KeychainResult(status: status), nil) } public func removeAccessToken() -> KeychainResult { return KeychainResult(status: SecItemDelete(attributes)) } public func saveAccessToken(token: String) -> KeychainResult { var attrs = attributes attrs[kSecAttrGeneric as String] = token as NSString var result: AnyObject? let status = withUnsafeMutablePointer(&result) { SecItemAdd(attrs, UnsafeMutablePointer($0)) } if status != OSStatus(errSecDuplicateItem) { return KeychainResult(status: status) } return KeychainResult(status: SecItemUpdate(attributes, attrs)) } }
mit
7e3037a8e3d6fcb100640b52c2d90ea7
36.946237
111
0.610261
5.195876
false
false
false
false
shemana/ConnectMusics
ConnectMusics/CMSpotifyProviderManager.swift
1
3358
// // CMSpotifyProviderManager.swift // ConnectMusics // // Created by Meryl Barantal on 12/02/2017. // Copyright © 2017 com.github.shemana.application. All rights reserved. // import UIKit public class CMSpotifyProviderManager: CMBaseProvider { public var type: ProviderType = .spotify var spotifyNetwork:CMSpotifyProviderNetwork init(){ spotifyNetwork = CMSpotifyProviderNetwork() } fileprivate init(cliendID: String?, clientSecret: String?, redirect_uri: String?, scopeNeeded: String?) { spotifyNetwork = CMSpotifyProviderNetwork(clientID: cliendID!, clientSecret: clientSecret!, redirectURI: redirect_uri!, scopeNeeded: scopeNeeded) } public static func createProviderInstance(cliendID: String?, clientSecret: String?, redirect_uri: String?, scopeNeeded: String?) -> CMBaseProvider { let managerInstance:CMSpotifyProviderManager = CMSpotifyProviderManager(cliendID: cliendID, clientSecret: clientSecret, redirect_uri: redirect_uri, scopeNeeded: scopeNeeded) return managerInstance } public func login(withAuthenticationCode: String) { spotifyNetwork.getUserToken(authenticationCode: withAuthenticationCode) } public func getPlaylists(completionHandler:@escaping (_ error:String?) -> Void) { guard spotifyNetwork.clientInformation["access_token"] != nil else { completionHandler("NO TOKEN AVAILABLE") return } spotifyNetwork.getPlaylists(completionHandler: { (result:[CMSpotifyPlaylist]?, error:String?) in if error == nil { var playlists:[CMPlaylist] = [] for spotifyPlaylist in result! { playlists.append(CMPlaylist.initPlaylistFromSpotify(playlistItem: spotifyPlaylist)) } CMSharedProviders.sharedInstance.appendPlaylists(provider:.spotify,playlistsToAdd:playlists) completionHandler(nil) } else { completionHandler(error) } }) } public func getMe(completionHandler:@escaping (_ error:String?) -> Void){ guard spotifyNetwork.clientInformation["access_token"] != nil else { completionHandler("NO TOKEN AVAILABLE") return } spotifyNetwork.getMe { (error:String?) in if error != nil { completionHandler(error) } else { completionHandler(nil) } } } public func getTracks(playlistToUpdate:CMPlaylist,completionHandler:@escaping (_ playlistUpdated:CMPlaylist?,_ error:String?) -> Void) { guard playlistToUpdate.provider == .spotify else { completionHandler(nil,"ERROR - Playlist : \(playlistToUpdate.name) IS NOT A SPOTIFY Playlist") return } let playlistID = (playlistToUpdate.mediaItem as? CMSpotifyPlaylist)?.id spotifyNetwork.getTracks(playlistID:playlistID!) { (tracks:[CMSpotifyTrack]?, error:String?) in if error == nil { (playlistToUpdate.mediaItem as! CMSpotifyPlaylist).tracks = tracks! completionHandler(playlistToUpdate,nil) } else { completionHandler(nil,error) } } } }
apache-2.0
d36cf9d5332d8c0956594e728aac2e2c
38.034884
181
0.636282
4.944035
false
false
false
false
apple/swift
tools/swift-inspect/Sources/swift-inspect/Operations/DumpRawMetadata.swift
5
1647
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2020 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 // //===----------------------------------------------------------------------===// import ArgumentParser import SwiftRemoteMirror internal struct DumpRawMetadata: ParsableCommand { static let configuration = CommandConfiguration( abstract: "Print the target's metadata allocations.") @OptionGroup() var options: UniversalOptions @OptionGroup() var backtraceOptions: BacktraceOptions func run() throws { try inspect(options: options) { process in let stacks: [swift_reflection_ptr_t:[swift_reflection_ptr_t]]? = backtraceOptions.style == nil ? nil : try process.context.allocationStacks try process.context.allocations.forEach { allocation in let name: String = process.context.name(allocation: allocation.tag) ?? "<unknown>" print("Metadata allocation at: \(hex: allocation.ptr) size: \(allocation.size) tag: \(allocation.tag) (\(name))") if let style = backtraceOptions.style { if let stack = stacks?[allocation.ptr] { print(backtrace(stack, style: style, process.symbolicate)) } else { print(" No stack trace available") } } } } } }
apache-2.0
dd26d429c2d9f8d84f5734fbddc1dde6
34.804348
121
0.605343
4.858407
false
false
false
false
peiei/PJPhototLibrary
JPhotoLibrary/Class/SelectImageCenter.swift
1
2216
// // SelectImageCenter.swift // JPhotoLibrary // // Created by AidenLance on 2017/3/15. // Copyright © 2017年 AidenLance. All rights reserved. // import Foundation import Photos enum ImageDataType { case file case data } class SelectImageCenter { static let shareManager = SelectImageCenter() var collectionArray:[Bool] = [] var selectArray: [PHAsset] = [] { willSet { UpdateSelectNum(num: newValue.count) } } var isSelectOriginData: Bool = false var imageType = ImageDataType.data let assetManager = AssetManager() var result: (([PHAsset]) -> Void)? = nil func initData(collectionCout: Int) { collectionArray = Array.init(repeating: false, count: collectionCout) } func cleanData() { collectionArray.removeAll() selectArray.removeAll() } //reload cell select status func addSelectImage(isNotify: Bool = false, index: Int, imageAsset: PHAsset) { collectionArray[index] = true selectArray.append(imageAsset) if isNotify { UpdateAlbumThumbnailCellData(index: index) } } func removeSelectImage(isNotify: Bool = false, index: Int, imageAsset: PHAsset) { collectionArray[index] = false for (indexTemp, valueTemp) in selectArray.enumerated() { if valueTemp == imageAsset { selectArray.remove(at: indexTemp) break } } if isNotify { UpdateAlbumThumbnailCellData(index: index) } } func UpdateAlbumThumbnailCellData(index: Int) { NotificationCenter.default.post(name: .UpdateAlbumThumbnailCellData, object: index) } func UpdateSelectNum(num: Int) { NotificationCenter.default.post(name: .UpdateSelectNum, object: num, userInfo: nil) } } extension NSNotification.Name { static let UpdateAlbumThumbnailCellData: NSNotification.Name = NSNotification.Name.init("com.peijie.jphtotolibrary.UpdateAlbumThumbnailCellData") static let UpdateSelectNum: NSNotification.Name = NSNotification.Name.init("com.peijie.jphotolibrary.UpdateSelectNum") }
mit
757df96dacf5022ce00c5a83f61ff82b
25.987805
149
0.647989
4.373518
false
false
false
false
antonio081014/LeetCode-CodeBase
Swift/last-stone-weight.swift
2
9311
/** * https://leetcode.com/problems/last-stone-weight/ * * */ // // Heap.swift // // Created by Yi Ding on 9/30/19. // Copyright © 2019 Yi Ding. All rights reserved. // import Foundation public struct Heap<T> { /** The array that stores the heap's nodes. */ private(set) var nodes: [T] /** * Determines how to compare two nodes in the heap. * Use '>' for a max-heap or '<' for a min-heap, * or provide a comparing method if the heap is made * of custom elements, for example tuples. */ fileprivate let sortingComparator: (T, T) -> Bool /** * Creates an empty heap. * The sort function determines whether this is a min-heap or max-heap. * For comparable data types, > makes a max-heap, < makes a min-heap. */ public init(sortingComparator: @escaping (T, T) -> Bool) { self.nodes = [] self.sortingComparator = sortingComparator } /** * Creates a heap from an array. The order of the array does not matter; * the elements are inserted into the heap in the order determined by the * sort function. For comparable data types, '>' makes a max-heap, * '<' makes a min-heap. */ public init(array: [T], sortingComparator: @escaping (T, T) -> Bool) { self.nodes = [] self.sortingComparator = sortingComparator self.buildHeap(from: array) } /** * Configures the max-heap or min-heap from an array, in a bottom-up manner. * Performance: This runs pretty much in O(n). */ private mutating func buildHeap(from array: [T]) { // self.insert(array) self.nodes = array for index in stride(from: array.count / 2 - 1, through: 0, by: -1) { self.shiftDown(from: index) } } } // MARK: - Peek, Insert, Remove, Replace extension Heap { public var isEmpty: Bool { return self.nodes.isEmpty } public var count: Int { return self.nodes.count } /** * Returns the maximum value in the heap (for a max-heap) or the minimum * value (for a min-heap). * Performance: O(1) */ public func peek() -> T? { return self.nodes.first } /** * Adds a new value to the heap. This reorders the heap so that the max-heap * or min-heap property still holds. * Performance: O(log n). */ public mutating func insert(element: T) { self.nodes.append(element) self.shiftUp(from: self.nodes.count - 1) } /** * Adds a sequence of values to the heap. This reorders the heap so that * the max-heap or min-heap property still holds. * Performance: O(log n). */ public mutating func insert<S: Sequence>(_ sequence: S) where S.Iterator.Element == T { for value in sequence { insert(element: value) } } /** * Allows you to change an element. This reorders the heap so that * the max-heap or min-heap property still holds. * Performance: O(log n) */ public mutating func replace(at index: Int, value: T) { guard index < nodes.count else { return } remove(at: index) insert(element: value) } /** * Removes the root node from the heap. For a max-heap, this is the maximum * value; for a min-heap it is the minimum value. * Performance: O(log n). */ @discardableResult public mutating func remove() -> T? { guard self.nodes.count > 0 else { return nil } if self.nodes.count == 1 { return self.nodes.removeLast() } else { let value = self.nodes.first self.nodes[0] = self.nodes.removeLast() self.shiftDown(from: 0) return value } } /** * Removes an arbitrary node from the heap. * Note that you need to know the node's index. * Performance: O(log n) */ @discardableResult public mutating func remove(at index: Int) -> T? { guard index < self.count else { return nil } self.nodes.swapAt(index, self.nodes.count - 1) let value = self.nodes.removeLast() self.shiftDown(from: index) self.shiftUp(from: index) return value } } // MARK: - Index extension Heap { /** * Returns the index of the parent of the element at index i. * The element at index 0 is the root of the tree and has no parent. * Performance: O(1) */ func parentIndex(ofIndex i: Int) -> Int { return (i - 1) / 2 } /** * Returns the index of the left child of the element at index i. * Note that this index can be greater than the heap size, in which case * there is no left child. * Performance: O(1) */ func leftChildIndex(ofIndex index: Int) -> Int { return index * 2 + 1 } /** * Returns the index of the right child of the element at index i. * Note that this index can be greater than the heap size, in which case * there is no right child. * Performance: O(1) */ func rightChildIndex(ofIndex index: Int) -> Int { return index * 2 + 2 } } // MARK: - Shift Up / Down extension Heap { /** * Takes a child node and looks at its parents; if a parent is not larger * (max-heap) or not smaller (min-heap) than the child, we exchange them. * Performance: O(log n) */ mutating func shiftUp(from index: Int) { var childIndex = index var parentIndex = self.parentIndex(ofIndex: childIndex) while parentIndex < childIndex, !self.sortingComparator(self.nodes[parentIndex], self.nodes[childIndex]) { self.nodes.swapAt(childIndex, parentIndex) childIndex = parentIndex parentIndex = self.parentIndex(ofIndex: childIndex) } } /** * Looks at a parent node and makes sure it is still larger (max-heap) or * smaller (min-heap) than its childeren. * Performance: O(log n) */ mutating func shiftDown(from index: Int) { let parentIndex = index let leftChildIndex = self.leftChildIndex(ofIndex: parentIndex) let rightChildIndex = self.rightChildIndex(ofIndex: parentIndex) var subIndex = parentIndex if leftChildIndex < self.nodes.count, self.sortingComparator(self.nodes[subIndex], self.nodes[leftChildIndex]) == false { subIndex = leftChildIndex } if rightChildIndex < self.nodes.count, self.sortingComparator(self.nodes[subIndex], self.nodes[rightChildIndex]) == false { subIndex = rightChildIndex } if parentIndex == subIndex { return } self.nodes.swapAt(subIndex, index) self.shiftDown(from: subIndex) } } extension Heap where T: Equatable { /** * Get the index of a node in the heap. * Performance: O(n). */ public func index(of node: T) -> Int? { return self.nodes.firstIndex(of: node) } /** * Removes the first occurrence of a node from the heap. * Performance: O(n + log n) => O(n). */ @discardableResult public mutating func remove(node: T) -> T? { if let index = self.index(of: node) { return self.remove(at: index) } return nil } } // // PriorityQueue.swift // // Created by Yi Ding on 10/8/19. // Copyright © 2019 Yi Ding. All rights reserved. // import Foundation public struct PriorityQueue<T> { fileprivate var heap: Heap<T> /* To create a max-priority queue, supply a > sort function. For a min-priority queue, use <. */ public init(sortingComparator: @escaping (T, T) -> Bool) { self.heap = Heap(sortingComparator: sortingComparator) } public var isEmpty: Bool { return self.heap.isEmpty } public var count: Int { return self.heap.count } public func peek() -> T? { return self.heap.peek() } public mutating func enqueue(element: T) { self.heap.insert(element: element) } public mutating func dequeue() -> T? { return self.heap.remove() } /* Allows you to change the priority of an element. In a max-priority queue, the new priority should be larger than the old one; in a min-priority queue it should be smaller. */ public mutating func changePriority(at index: Int, value: T) { return self.heap.replace(at: index, value: value) } } extension PriorityQueue where T: Equatable { public func index(of element: T) -> Int? { return self.heap.index(of: element) } } class Solution { func lastStoneWeight(_ stones: [Int]) -> Int { var priorityQueue = PriorityQueue<Int>(sortingComparator: >= ) for n in stones { priorityQueue.enqueue(element: n) } while priorityQueue.count >= 2 { let n1 = priorityQueue.dequeue()! let n2 = priorityQueue.dequeue()! if n1 > n2 { priorityQueue.enqueue(element: n1 - n2) } } return priorityQueue.peek() ?? 0 } }
mit
27d184925ef7f39a544fff7b0750774c
28
131
0.587066
4.03686
false
false
false
false
ianyh/Amethyst
Amethyst/Layout/Layouts/BinarySpacePartitioningLayout.swift
1
12496
// // BinarySpacePartitioningLayout.swift // Amethyst // // Created by Ian Ynda-Hummel on 5/29/16. // Copyright © 2016 Ian Ynda-Hummel. All rights reserved. // import Silica class TreeNode<Window: WindowType>: Codable { typealias WindowID = Window.WindowID private enum CodingKeys: String, CodingKey { case left case right case windowID } weak var parent: TreeNode? var left: TreeNode? var right: TreeNode? var windowID: WindowID? init() {} required init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) self.left = try values.decodeIfPresent(TreeNode.self, forKey: .left) self.right = try values.decodeIfPresent(TreeNode.self, forKey: .right) self.windowID = try values.decodeIfPresent(WindowID.self, forKey: .windowID) self.left?.parent = self self.right?.parent = self guard valid else { throw LayoutDecodingError.invalidLayout } } var valid: Bool { return (left != nil && right != nil && windowID == nil) || (left == nil && right == nil && windowID != nil) } func findWindowID(_ windowID: WindowID) -> TreeNode? { guard self.windowID == windowID else { return left?.findWindowID(windowID) ?? right?.findWindowID(windowID) } return self } func orderedWindowIDs() -> [WindowID] { guard let windowID = windowID else { let leftWindowIDs = left?.orderedWindowIDs() ?? [] let rightWindowIDs = right?.orderedWindowIDs() ?? [] return leftWindowIDs + rightWindowIDs } return [windowID] } func insertWindowIDAtEnd(_ windowID: WindowID) { guard left == nil && right == nil else { right?.insertWindowIDAtEnd(windowID) return } insertWindowID(windowID) } func insertWindowID(_ windowID: WindowID, atPoint insertionPoint: WindowID) { guard self.windowID == insertionPoint else { left?.insertWindowID(windowID, atPoint: insertionPoint) right?.insertWindowID(windowID, atPoint: insertionPoint) return } insertWindowID(windowID) } func removeWindowID(_ windowID: WindowID) { guard let node = findWindowID(windowID) else { log.error("Trying to remove window not in tree") return } guard let parent = node.parent else { return } guard let grandparent = parent.parent else { if node == parent.left { parent.windowID = parent.right?.windowID } else { parent.windowID = parent.left?.windowID } parent.left = nil parent.right = nil return } if parent == grandparent.left { if node == parent.left { grandparent.left = parent.right } else { grandparent.left = parent.left } grandparent.left?.parent = grandparent } else { if node == parent.left { grandparent.right = parent.right } else { grandparent.right = parent.left } grandparent.right?.parent = grandparent } } func insertWindowID(_ windowID: WindowID) { guard parent != nil || self.windowID != nil else { self.windowID = windowID return } if let parent = parent { let newParent = TreeNode() let newNode = TreeNode() newNode.parent = newParent newNode.windowID = windowID newParent.left = self newParent.right = newNode newParent.parent = parent if self == parent.left { parent.left = newParent } else { parent.right = newParent } self.parent = newParent } else { let newSelf = TreeNode() let newNode = TreeNode() newSelf.windowID = self.windowID self.windowID = nil newNode.windowID = windowID left = newSelf left?.parent = self right = newNode right?.parent = self } } } extension TreeNode: Equatable { static func == (lhs: TreeNode, rhs: TreeNode) -> Bool { return lhs.windowID == rhs.windowID && lhs.left == rhs.left && lhs.right == rhs.right } } class BinarySpacePartitioningLayout<Window: WindowType>: StatefulLayout<Window> { typealias WindowID = Window.WindowID private typealias TraversalNode = (node: TreeNode<Window>, frame: CGRect) private enum CodingKeys: String, CodingKey { case rootNode } override static var layoutName: String { return "Binary Space Partitioning" } override static var layoutKey: String { return "bsp" } override var layoutDescription: String { return "\(lastKnownFocusedWindowID.debugDescription)" } private var rootNode = TreeNode<Window>() private var lastKnownFocusedWindowID: WindowID? required init() { super.init() } required init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.rootNode = try container.decode(TreeNode<Window>.self, forKey: .rootNode) super.init() } override func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(rootNode, forKey: .rootNode) } private func constructInitialTreeWithWindows(_ windows: [LayoutWindow<Window>]) { for window in windows { guard rootNode.findWindowID(window.id) == nil else { continue } rootNode.insertWindowIDAtEnd(window.id) if window.isFocused { lastKnownFocusedWindowID = window.id } } } override func updateWithChange(_ windowChange: Change<Window>) { switch windowChange { case let .add(window): guard rootNode.findWindowID(window.id()) == nil else { log.warning("Trying to add a window already in the tree") return } if let insertionPoint = lastKnownFocusedWindowID, window.id() != insertionPoint { log.info("insert \(window) - \(window.id()) at point: \(insertionPoint)") rootNode.insertWindowID(window.id(), atPoint: insertionPoint) } else { log.info("insert \(window) - \(window.id()) at end") rootNode.insertWindowIDAtEnd(window.id()) } if window.isFocused() { lastKnownFocusedWindowID = window.id() } case let .remove(window): log.info("remove: \(window) - \(window.id())") rootNode.removeWindowID(window.id()) case let .focusChanged(window): lastKnownFocusedWindowID = window.id() case let .windowSwap(window, otherWindow): let windowID = window.id() let otherWindowID = otherWindow.id() guard let windowNode = rootNode.findWindowID(windowID), let otherWindowNode = rootNode.findWindowID(otherWindowID) else { log.error("Tried to perform an unbalanced window swap: \(windowID) <-> \(otherWindowID)") return } windowNode.windowID = otherWindowID otherWindowNode.windowID = windowID case .applicationDeactivate, .applicationActivate, .spaceChange, .layoutChange, .unknown: break } } override func nextWindowIDCounterClockwise() -> WindowID? { guard let focusedWindow = Window.currentlyFocused() else { return nil } let orderedIDs = rootNode.orderedWindowIDs() guard let focusedWindowIndex = orderedIDs.index(of: focusedWindow.id()) else { return nil } let nextWindowIndex = (focusedWindowIndex == 0 ? orderedIDs.count - 1 : focusedWindowIndex - 1) return orderedIDs[nextWindowIndex] } override func nextWindowIDClockwise() -> WindowID? { guard let focusedWindow = Window.currentlyFocused() else { return nil } let orderedIDs = rootNode.orderedWindowIDs() guard let focusedWindowIndex = orderedIDs.index(of: focusedWindow.id()) else { return nil } let nextWindowIndex = (focusedWindowIndex == orderedIDs.count - 1 ? 0 : focusedWindowIndex + 1) return orderedIDs[nextWindowIndex] } override func frameAssignments(_ windowSet: WindowSet<Window>, on screen: Screen) -> [FrameAssignmentOperation<Window>]? { let windows = windowSet.windows guard !windows.isEmpty else { return [] } if rootNode.left == nil && rootNode.right == nil { constructInitialTreeWithWindows(windows) } let windowIDMap: [WindowID: LayoutWindow<Window>] = windows.reduce([:]) { (windowMap, window) -> [WindowID: LayoutWindow<Window>] in var mutableWindowMap = windowMap mutableWindowMap[window.id] = window return mutableWindowMap } let baseFrame = screen.adjustedFrame() var ret: [FrameAssignmentOperation<Window>] = [] var traversalNodes: [TraversalNode] = [(node: rootNode, frame: baseFrame)] while !traversalNodes.isEmpty { let traversalNode = traversalNodes[0] traversalNodes = [TraversalNode](traversalNodes.dropFirst(1)) if let windowID = traversalNode.node.windowID { guard let window = windowIDMap[windowID] else { log.warning("Could not find window for ID: \(windowID)") continue } let resizeRules = ResizeRules(isMain: true, unconstrainedDimension: .horizontal, scaleFactor: 1) let frameAssignment = FrameAssignment<Window>( frame: traversalNode.frame, window: window, screenFrame: baseFrame, resizeRules: resizeRules ) ret.append(FrameAssignmentOperation(frameAssignment: frameAssignment, windowSet: windowSet)) } else { guard let left = traversalNode.node.left, let right = traversalNode.node.right else { log.error("Encountered an invalid node") continue } let frame = traversalNode.frame if frame.width > frame.height { let leftFrame = CGRect( x: frame.origin.x, y: frame.origin.y, width: frame.width / 2.0, height: frame.height ) let rightFrame = CGRect( x: frame.origin.x + frame.width / 2.0, y: frame.origin.y, width: frame.width / 2.0, height: frame.height ) traversalNodes.append((node: left, frame: leftFrame)) traversalNodes.append((node: right, frame: rightFrame)) } else { let topFrame = CGRect( x: frame.origin.x, y: frame.origin.y, width: frame.width, height: frame.height / 2.0 ) let bottomFrame = CGRect( x: frame.origin.x, y: frame.origin.y + frame.height / 2.0, width: frame.width, height: frame.height / 2.0 ) traversalNodes.append((node: left, frame: topFrame)) traversalNodes.append((node: right, frame: bottomFrame)) } } } return ret } } extension BinarySpacePartitioningLayout: Equatable { static func == (lhs: BinarySpacePartitioningLayout<Window>, rhs: BinarySpacePartitioningLayout<Window>) -> Bool { return lhs.rootNode == rhs.rootNode } }
mit
86912a532f0381c1456f8d8747571bf6
32.32
140
0.562225
4.871345
false
false
false
false
ronakdev/swift-datastructures
DataStructures/LinkedList.swift
1
2255
// // LinkedList.swift // LinkedLists // // Created by Ronak Shah on 7/1/15. // Copyright (c) 2015 Shah Industries. All rights reserved. // Version 1.2 // import Foundation class LinkedList<T>: SequenceType, CustomStringConvertible { var head: ListNode<T>? var first: T? { return head?.value } var count: Int { var num = 0 var temp = head while temp != nil { temp = temp!.nextNode() num++ } return num } var description: String { var toReturn = "" var temp = head while temp != nil { if let val = temp?.getValue() { toReturn += "\(val)\n" } else { toReturn += "nil value\n" } temp = temp!.nextNode() } return toReturn } init(){ head = nil } func addArray(values: [T]){ for value in values { add(value) } } ///adds value T to last index func add(value: T) { addLast(value) } func removeFirst() -> T? { if let cleanHead = head { let val = cleanHead.value head = head?.next return val } return nil } func generate() -> LinkedListIterator<T> { return LinkedListIterator(node: head) } //private methods func addLast(value: T){ let node: ListNode<T>? = ListNode(nodeValue: value) if head != nil { var temp : ListNode? = head var back : ListNode<T>? back = nil while temp != nil { back = temp temp = temp!.next } temp = back! //when temp.next is null temp!.setNext(node) } else{ head = ListNode(nodeValue: value) } } func addFirst(value: T) { if head != nil { head = ListNode(nextNode: head!, nodeValue: value) } else { head = ListNode(nodeValue: value) } } }
gpl-3.0
a629b359f3c725c6baabf13254497183
18.789474
62
0.435477
4.697917
false
false
false
false
Rapid-SDK/ios
Examples/RapiDO - ToDo list/RapiDO tvOS/FilterViewController.swift
1
5957
// // FilterViewController.swift // ExampleApp // // Created by Jan on 05/05/2017. // Copyright © 2017 Rapid. All rights reserved. // import UIKit import Rapid protocol FilterViewControllerDelegate: class { func filterViewControllerDidCancel(_ controller: FilterViewController) func filterViewControllerDidFinish(_ controller: FilterViewController, withFilter filter: RapidFilter?) } class FilterViewController: UIViewController { weak var delegate: FilterViewControllerDelegate? var filter: RapidFilter? @IBOutlet weak var segmentedControl: UISegmentedControl! @IBOutlet weak var tagsTableView: TagsTableView! @IBOutlet weak var doneButton: UIButton! @IBOutlet weak var cancelButton: UIButton! override func viewDidLoad() { super.viewDidLoad() setupUI() } // MARK: Actions @IBAction func cancel(_ sender: Any) { delegate?.filterViewControllerDidCancel(self) } @IBAction func done(_ sender: Any) { var operands = [RapidFilter]() // Segmented control selected index equal to 1 means "show all tasks regardless completion state", so no filter is needed // Otherwise, create filter for either completed or incompleted tasks if segmentedControl.selectedSegmentIndex != 1 { let completed = segmentedControl.selectedSegmentIndex == 0 operands.append(RapidFilter.equal(keyPath: Task.completedAttributeName, value: completed)) } // Create filter for selected tags let selectedTags = tagsTableView.selectedTags if selectedTags.count > 0 { var tagFilters = [RapidFilter]() for tag in selectedTags { tagFilters.append(RapidFilter.arrayContains(keyPath: Task.tagsAttributeName, value: tag.rawValue)) } // Combine single tag filters with logical "OR" operator operands.append(RapidFilter.or(tagFilters)) } // If there are any filters combine them with logical "AND" let filter: RapidFilter? if operands.count > 0 { filter = RapidFilter.and(operands) } else { filter = nil } delegate?.filterViewControllerDidFinish(self, withFilter: filter) } } fileprivate extension FilterViewController { func setupUI() { if let expression = filter?.expression, case .compound(_, let operands) = expression { var tagsSet = false var completionSet = false for operand in operands { switch operand { case .simple(_, _, let value): completionSet = true let done = value as? Bool ?? false let index = done ? 0 : 2 segmentedControl.selectedSegmentIndex = index case .compound(_, let operands): tagsSet = true var tags = [Tag]() for case .simple(_, _, let value) in operands { switch value as? String { case .some(Tag.home.rawValue): tags.append(.home) case .some(Tag.work.rawValue): tags.append(.work) case .some(Tag.other.rawValue): tags.append(.other) default: break } } tagsTableView.selectTags(tags) } } if !tagsSet { tagsTableView.selectTags([]) } if !completionSet { segmentedControl.selectedSegmentIndex = 1 } } else { segmentedControl.selectedSegmentIndex = 1 tagsTableView.selectTags([]) } setupFocusGuide() } func setupFocusGuide() { let doneGuide = UIFocusGuide() doneGuide.preferredFocusEnvironments = [doneButton] view.addLayoutGuide(doneGuide) view.addConstraint(NSLayoutConstraint(item: doneGuide, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 1)) view.addConstraint(NSLayoutConstraint(item: doneGuide, attribute: .bottom, relatedBy: .equal, toItem: doneButton, attribute: .top, multiplier: 1, constant: 0)) view.addConstraint(NSLayoutConstraint(item: doneGuide, attribute: .left, relatedBy: .equal, toItem: cancelButton, attribute: .right, multiplier: 1, constant: 0)) view.addConstraint(NSLayoutConstraint(item: doneGuide, attribute: .right, relatedBy: .equal, toItem: doneButton, attribute: .left, multiplier: 1, constant: 0)) let segmentGuide = UIFocusGuide() segmentGuide.preferredFocusEnvironments = [segmentedControl] view.addLayoutGuide(segmentGuide) view.addConstraint(NSLayoutConstraint(item: segmentGuide, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 1)) view.addConstraint(NSLayoutConstraint(item: segmentGuide, attribute: .centerY, relatedBy: .equal, toItem: segmentedControl, attribute: .centerY, multiplier: 1, constant: 0)) view.addConstraint(NSLayoutConstraint(item: segmentGuide, attribute: .left, relatedBy: .equal, toItem: cancelButton, attribute: .left, multiplier: 1, constant: 0)) view.addConstraint(NSLayoutConstraint(item: segmentGuide, attribute: .right, relatedBy: .equal, toItem: doneButton, attribute: .right, multiplier: 1, constant: 0)) } }
mit
d719d8fb9350feb78a30240fb3652c4d
38.973154
181
0.588146
5.519926
false
false
false
false