repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
icapps/ios-air-rivet
refs/heads/master
Example/Pods/Stella/Sources/Printing/Print.swift
mit
3
// // Dispatch.swift // Pods // // Created by Jelle Vandebeeck on 06/06/16. // // /** Writes the textual representations of items, prefixed with a 🍞 emoji, into the standard output. This textual representations is used for breadcrumbs. - Parameter items: The items to write to the output. - Returns : text to be printed */ @discardableResult public func printBreadcrumb(_ items: Any...) -> String? { guard Output.level == .verbose else { return nil } let text = "🍞 " + items.map { String(describing: $0) }.joined(separator: " ") print("\(text)") return text } /** Writes the textual representations of items, prefixed with a 🔥 emoji, into the standard output. This textual representations is used for errors. - Parameter items: The items to write to the output. - Returns : text to be printed */ @discardableResult public func printError(_ items: Any...) -> String? { guard Output.level != .nothing || Output.level == .error else { return nil } let text = "🔥 " + items.map { String(describing: $0) }.joined(separator: " ") print(text) return text } /** Writes the textual representations of items, prefixed with a 🎯 emoji, into the standard output. This textual representations is used for user actions. - Parameter items: The items to write to the output. - Returns : text to be printed */ @discardableResult public func printAction(_ items: Any...) -> String? { guard Output.level == .verbose || Output.level == .quiet else { return nil } let text = "🎯 " + items.map { String(describing: $0) }.joined(separator: " ") print("\(text)") return text } /** Writes the textual representations of items, prefixed with a 🤔 emoji, into the standard output. This textual representations is used for times when you want to log a text in conspicuous situations. Like when parsing and a key that is not obligatoiry is missing. You tell the developer:" You use my code but I think this is wrong." - Parameter items: The items to write to the output. - Returns : text to be printed */ @discardableResult public func printQuestion(_ items: Any...) -> String? { guard Output.level == .verbose else { return nil } let text = "❓ " + items.map { String(describing: $0) }.joined(separator: " ") print("\(text)") return text } // MARK: - Print Throw /** Uses `printError` when something is thrown inside `function`. - Parameter function: closure that can potentially throw - Returns : text to be printed */ @discardableResult public func printThrowAsError(_ function: () throws -> Void) -> String? { do { try function() return nil } catch { let result = "\(error)" printError(result) return result } } /** Uses `printQuestion` when something is thrown inside `function`. - Parameter function: closure that can potentially throw - Returns : text to be printed */ @discardableResult public func printThrowAsQuestion(_ function: () throws -> Void) -> String? { do { try function() return nil } catch { let result = "\(error)" printQuestion(result) return result } } /** Uses `printBreadcrumb` when something is thrown inside `function`. - Parameter function: closure that can potentially throw - Returns : text to be printed */ @discardableResult public func printThrowAsBreadcrumb(_ function: () throws -> Void) -> String? { do { try function() return nil } catch { let result = "\(error)" printBreadcrumb(result) return result } } /** Uses `printAction` when something is thrown inside `function`. - Parameter function: closure that can potentially throw - Returns : text to be printed */ @discardableResult public func printThrowAsAction(_ function: () throws -> Void) -> String? { do { try function() return nil } catch { let result = "\(error)" printAction(result) return result } }
bddea1935efd4b3845d27261c6bd0f03
22.962963
235
0.679547
false
false
false
false
easyui/EZPlayer
refs/heads/master
EZPlayer/EZPlayer.swift
mit
1
// // EZPlayer.swift // EZPlayer // // Created by yangjun zhu on 2016/12/28. // Copyright © 2016年 yangjun zhu. All rights reserved. // import Foundation import AVFoundation import AVKit /// 播放器错误类型 public enum EZPlayerError: Error { case invalidContentURL //错误的url case playerFail // AVPlayer failed to load the asset. } /// 播放器的状态 public enum EZPlayerState { case unknown // 播放前 case error(EZPlayerError) // 出现错误 case readyToPlay // 可以播放 case buffering // 缓冲中 case bufferFinished // 缓冲完毕 case playing // 播放 case seekingForward // 快进 case seekingBackward // 快退 case pause // 播放暂停 case stopped // 播放结束 } //播放器浮框模式 public enum EZPlayerFloatMode { case none case auto //支持系统pip的就是system,否则是window case system //iPhone在ios14一下不显示 case window } //播放器显示模式类型 public enum EZPlayerDisplayMode { case none case embedded case fullscreen case float } //播放器全屏模式类型 public enum EZPlayerFullScreenMode { case portrait case landscape } //播放器流的显示比例 public enum EZPlayerVideoGravity : String { case aspect = "AVLayerVideoGravityResizeAspect" //视频值 ,等比例填充,直到一个维度到达区域边界 case aspectFill = "AVLayerVideoGravityResizeAspectFill" //等比例填充,直到填充满整个视图区域,其中一个维度的部分区域会被裁剪 case scaleFill = "AVLayerVideoGravityResize" //非均匀模式。两个维度完全填充至整个视图区域 } //播放器结束原因 public enum EZPlayerPlaybackDidFinishReason { case playbackEndTime case playbackError case stopByUser } //屏幕左右上下划动时的类型 public enum EZPlayerSlideTrigger{ case none case volume case brightness } //public enum EZPlayerFileType: String { // case unknown // case mp4 // case m3u8 // //} open class EZPlayer: NSObject { // MARK: - player utils public static var showLog = true//是否显示log // MARK: - player setting open weak var delegate: EZPlayerDelegate? open var videoGravity = EZPlayerVideoGravity.aspect{ didSet { if let layer = self.playerView?.layer as? AVPlayerLayer{ layer.videoGravity = AVLayerVideoGravity(rawValue: videoGravity.rawValue) } } } /// 设置url会自动播放 open var autoPlay = true /// 设备横屏时自动旋转(phone) open var autoLandscapeFullScreenLandscape = UIDevice.current.userInterfaceIdiom == .phone /// 浮框的模式 open var floatMode = EZPlayerFloatMode.auto /// 全屏的模式 open var fullScreenMode = EZPlayerFullScreenMode.landscape /// 全屏时status bar的样式 open var fullScreenPreferredStatusBarStyle = UIStatusBarStyle.lightContent /// 全屏时status bar的背景色 open var fullScreenStatusbarBackgroundColor = UIColor.black.withAlphaComponent(0.3) /// 支持airplay open var allowsExternalPlayback = true{ didSet{ guard let avplayer = self.player else { return } avplayer.allowsExternalPlayback = allowsExternalPlayback } } /// airplay连接状态 open var isExternalPlaybackActive: Bool { guard let avplayer = self.player else { return false } return avplayer.isExternalPlaybackActive } private var timeObserver: Any?//addPeriodicTimeObserver的返回值 private var timer : Timer?//.EZPlayerHeartbeat使用 // MARK: - player resource open var contentItem: EZPlayerContentItem? open private(set) var contentURL :URL?{//readonly didSet{ guard let url = contentURL else { return } self.isM3U8 = url.absoluteString.hasSuffix(".m3u8") } } open private(set) var player: AVPlayer? open private(set) var playerasset: AVAsset?{ didSet{ if oldValue != playerasset{ if playerasset != nil { self.imageGenerator = AVAssetImageGenerator(asset: playerasset!) }else{ self.imageGenerator = nil } } } } open private(set) var playerItem: AVPlayerItem?{ willSet{ if playerItem != newValue{ if let item = playerItem{ NotificationCenter.default.removeObserver(self, name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: item) item.removeObserver(self, forKeyPath: #keyPath(AVPlayerItem.status)) item.removeObserver(self, forKeyPath: #keyPath(AVPlayerItem.loadedTimeRanges)) item.removeObserver(self, forKeyPath: #keyPath(AVPlayerItem.isPlaybackBufferEmpty)) item.removeObserver(self, forKeyPath: #keyPath(AVPlayerItem.isPlaybackLikelyToKeepUp)) } } } didSet { if playerItem != oldValue{ if let item = playerItem{ NotificationCenter.default.addObserver(self, selector: #selector(self.playerDidPlayToEnd(_:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: playerItem) item.addObserver(self, forKeyPath: #keyPath(AVPlayerItem.status), options: NSKeyValueObservingOptions.new, context: nil) //缓冲区大小 item.addObserver(self, forKeyPath: #keyPath(AVPlayerItem.loadedTimeRanges), options: NSKeyValueObservingOptions.new, context: nil) // 缓冲区空了,需要等待数据 item.addObserver(self, forKeyPath: #keyPath(AVPlayerItem.isPlaybackBufferEmpty), options: NSKeyValueObservingOptions.new, context: nil) // 缓冲区有足够数据可以播放了 item.addObserver(self, forKeyPath: #keyPath(AVPlayerItem.isPlaybackLikelyToKeepUp), options: NSKeyValueObservingOptions.new, context: nil) } } } } /// 视频截图 open private(set) var imageGenerator: AVAssetImageGenerator? /// 视频截图m3u8 open private(set) var videoOutput: AVPlayerItemVideoOutput? open private(set) var isM3U8 = false open var isLive: Bool? { if let duration = self.duration { return duration.isNaN } return nil } /// 上下滑动屏幕的控制类型 open var slideTrigger = (left:EZPlayerSlideTrigger.volume,right:EZPlayerSlideTrigger.brightness) /// 左右滑动屏幕改变视频进度 open var canSlideProgress = true // MARK: - player component //只读 open var controlView : UIView?{ if let view = self.controlViewForIntercept{ return view } switch self.displayMode { case .embedded: return self.controlViewForEmbedded case .fullscreen: return self.controlViewForFullscreen case .float: return self.controlViewForFloat case .none: return self.controlViewForEmbedded } } /// 拦截原来的各种controlView,作用:比如你要插入一个广告的view,广告结束置空即可 open var controlViewForIntercept : UIView? { didSet{ self.updateCustomView() } } ///cactus todo EZPlayerControlView /// 嵌入模式的控制皮肤 open var controlViewForEmbedded : UIView? /// 浮动模式的控制皮肤 open var controlViewForFloat : UIView? /// 全屏模式的控制皮肤 open var controlViewForFullscreen : UIView? /// 全屏模式控制器 open private(set) var fullScreenViewController : EZPlayerFullScreenViewController? /// 视频控制器视图 fileprivate var playerView: EZPlayerView? open var view: UIView{ if self.playerView == nil{ self.playerView = EZPlayerView(controlView: self.controlView) } return self.playerView! } /// 嵌入模式的容器 open weak var embeddedContentView: UIView? /// 嵌入模式的显示隐藏 open private(set) var controlsHidden = false /// 过多久自动消失控件,设置为<=0不消失 open var autohiddenTimeInterval: TimeInterval = 8 /// 返回按钮block open var backButtonBlock:(( _ fromDisplayMode: EZPlayerDisplayMode) -> Void)? open var floatContainer: EZPlayerWindowContainer? open var floatContainerRootViewController: EZPlayerWindowContainerRootViewController? open var floatInitFrame = CGRect(x: UIScreen.main.bounds.size.width - 213 - 10, y: UIScreen.main.bounds.size.height - 120 - 49 - 34 - 10, width: 213, height: 120) // autohideTimeInterval// // MARK: - player status open fileprivate(set) var state = EZPlayerState.unknown{ didSet{ printLog("old state: \(oldValue)") printLog("new state: \(state)") if oldValue != state{ (self.controlView as? EZPlayerDelegate)?.player(self, playerStateDidChange: state) self.delegate?.player(self, playerStateDidChange: state) NotificationCenter.default.post(name: .EZPlayerStatusDidChange, object: self, userInfo: [Notification.Key.EZPlayerNewStateKey: state,Notification.Key.EZPlayerOldStateKey: oldValue]) var loading = false; switch state { case .readyToPlay,.playing ,.pause,.seekingForward,.seekingBackward,.stopped,.bufferFinished://cactus todo loading = false; break default: loading = true; break } (self.controlView as? EZPlayerDelegate)?.player(self, showLoading: loading) self.delegate?.player(self, showLoading: loading) NotificationCenter.default.post(name: .EZPlayerLoadingDidChange, object: self, userInfo: [Notification.Key.EZPlayerLoadingDidChangeKey: loading]) if case .error(_) = state { NotificationCenter.default.post(name: .EZPlayerPlaybackDidFinish, object: self, userInfo: [Notification.Key.EZPlayerPlaybackDidFinishReasonKey: EZPlayerPlaybackDidFinishReason.playbackError]) } } } } open private(set) var displayMode = EZPlayerDisplayMode.none{ didSet{ if oldValue != displayMode{ (self.controlView as? EZPlayerDelegate)?.player(self, playerDisplayModeDidChange: displayMode) self.delegate?.player(self, playerDisplayModeDidChange: displayMode) NotificationCenter.default.post(name: .EZPlayerDisplayModeDidChange, object: self, userInfo: [Notification.Key.EZPlayerDisplayModeDidChangeKey: displayMode]) } } } open private(set) var lastDisplayMode = EZPlayerDisplayMode.none open var isPlaying:Bool{ guard let player = self.player else { return false } if #available(iOS 10.0, *) { return player.timeControlStatus == .playing; }else{ return player.rate > Float(0) && player.error == nil } } /// 视频长度,live是NaN open var duration: TimeInterval? { if let duration = self.player?.duration { return duration } return nil } /// 视频进度 open var currentTime: TimeInterval? { if let currentTime = self.player?.currentTime { return currentTime } return nil } /// 视频播放速率 open var rate: Float{ get { if let player = self.player { return player.rate } return .nan } set { if let player = self.player { player.rate = newValue } } } /// 系统音量 open var systemVolume: Float{ get { return systemVolumeSlider.value } set { systemVolumeSlider.value = newValue } } private let systemVolumeSlider = EZPlayerUtils.systemVolumeSlider open weak var scrollView: UITableView?{ willSet{ if scrollView != newValue{ if let view = scrollView{ view.removeObserver(self, forKeyPath: #keyPath(UITableView.contentOffset)) } } } didSet { if playerItem != oldValue{ if let view = scrollView{ view.addObserver(self, forKeyPath: #keyPath(UITableView.contentOffset), options: NSKeyValueObservingOptions.new, context: nil) } } } } open var indexPath: IndexPath? // MARK: - Picture in Picture open var pipController: AVPictureInPictureController? fileprivate var startPIPWithCompletion : ((Error?) -> Void)? fileprivate var endPIPWithCompletion : (() -> Void)? // MARK: - Life cycle deinit { NotificationCenter.default.removeObserver(self) self.timer?.invalidate() self.timer = nil self.releasePlayerResource() } public override init() { super.init() self.commonInit() } public init(controlView: UIView? ) { super.init() if controlView == nil{ self.controlViewForEmbedded = UIView() }else{ self.controlViewForEmbedded = controlView } self.commonInit() } // MARK: - Player action open func playWithURL(_ url: URL,embeddedContentView contentView: UIView? = nil, title: String? = nil) { self.contentItem = EZPlayerContentItem(url: url, title: title) self.contentURL = url self.prepareToPlay() if contentView != nil { self.embeddedContentView = contentView self.embeddedContentView!.addSubview(self.view) self.view.frame = self.embeddedContentView!.bounds self.displayMode = .embedded }else{ self.toFull() } } open func replaceToPlayWithURL(_ url: URL, title: String? = nil) { self.resetPlayerResource() self.contentItem = EZPlayerContentItem(url: url, title: title) self.contentURL = url guard let url = self.contentURL else { self.state = .error(.invalidContentURL) return } self.playerasset = AVAsset(url: url) let keys = ["tracks","duration","commonMetadata","availableMediaCharacteristicsWithMediaSelectionOptions"] self.playerItem = AVPlayerItem(asset: self.playerasset!, automaticallyLoadedAssetKeys: keys) self.player?.replaceCurrentItem(with: self.playerItem) self.setControlsHidden(false, animated: true) } open func play(){ self.state = .playing self.player?.play() } open func pause(){ self.state = .pause self.player?.pause() } open func stop(){ let lastState = self.state self.state = .stopped self.player?.pause() self.releasePlayerResource() guard case .error(_) = lastState else{ if lastState != .stopped { NotificationCenter.default.post(name: .EZPlayerPlaybackDidFinish, object: self, userInfo: [Notification.Key.EZPlayerPlaybackDidFinishReasonKey: EZPlayerPlaybackDidFinishReason.stopByUser]) } return } } open func seek(to time: TimeInterval, completionHandler: ((Bool) -> Swift.Void )? = nil){ guard let player = self.player else { return } let lastState = self.state if let currentTime = self.currentTime { if currentTime > time { self.state = .seekingBackward }else if currentTime < time { self.state = .seekingForward } } playerItem?.cancelPendingSeeks() playerasset?.cancelLoading() player.seek(to: CMTimeMakeWithSeconds(time,preferredTimescale: CMTimeScale(NSEC_PER_SEC)), toleranceBefore: CMTime.zero, toleranceAfter: CMTime.zero, completionHandler: { [weak self] (finished) in guard let weakSelf = self else { return } switch (weakSelf.state) { case .seekingBackward,.seekingForward: weakSelf.state = lastState default: break } completionHandler?(finished) }) } private var isChangingDisplayMode = false open func toFull(_ orientation:UIDeviceOrientation = .landscapeLeft, animated: Bool = true ,completion: ((Bool) -> Swift.Void)? = nil) { if self.isChangingDisplayMode == true { completion?(false) return } if self.displayMode == .fullscreen { completion?(false) return } guard let activityViewController = EZPlayerUtils.activityViewController() else { completion?(false) return } func __toFull(from view: UIView) { self.isChangingDisplayMode = true self.updateCustomView(toDisplayMode: .fullscreen) NotificationCenter.default.post(name: .EZPlayerDisplayModeChangedWillAppear, object: self, userInfo: [Notification.Key.EZPlayerDisplayModeChangedFrom : self.lastDisplayMode, Notification.Key.EZPlayerDisplayModeChangedTo : EZPlayerDisplayMode.fullscreen]) self.setControlsHidden(true, animated: false) self.fullScreenViewController = EZPlayerFullScreenViewController() self.fullScreenViewController!.preferredlandscapeForPresentation = orientation == .landscapeRight ? .landscapeLeft : .landscapeRight self.fullScreenViewController!.player = self if animated { let rect = view.convert(self.view.frame, to: activityViewController.view) let x = activityViewController.view.bounds.size.width - rect.size.width - rect.origin.x let y = activityViewController.view.bounds.size.height - rect.size.height - rect.origin.y self.fullScreenViewController!.modalPresentationStyle = .fullScreen activityViewController.present(self.fullScreenViewController!, animated: false, completion: { self.view.removeFromSuperview() self.fullScreenViewController!.view.addSubview(self.view) self.fullScreenViewController!.view.sendSubviewToBack(self.view) if self.autoLandscapeFullScreenLandscape && self.fullScreenMode == .landscape{ self.view.transform = CGAffineTransform(rotationAngle:orientation == .landscapeRight ? CGFloat(Double.pi / 2) : -CGFloat(Double.pi / 2)) self.view.frame = orientation == .landscapeRight ? CGRect(x: y, y: rect.origin.x, width: rect.size.height, height: rect.size.width) : CGRect(x: rect.origin.y, y: x, width: rect.size.height, height: rect.size.width) }else{ self.view.frame = rect } UIView.animate(withDuration: EZPlayerAnimatedDuration, animations: { if self.autoLandscapeFullScreenLandscape && self.fullScreenMode == .landscape{ self.view.transform = CGAffineTransform.identity } self.view.bounds = self.fullScreenViewController!.view.bounds self.view.center = self.fullScreenViewController!.view.center }, completion: {finished in self.setControlsHidden(false, animated: true) NotificationCenter.default.post(name: .EZPlayerDisplayModeChangedDidAppear, object: self, userInfo: [Notification.Key.EZPlayerDisplayModeChangedFrom : self.lastDisplayMode, Notification.Key.EZPlayerDisplayModeChangedTo : EZPlayerDisplayMode.fullscreen]) completion?(finished) self.isChangingDisplayMode = false }) }) }else{ self.fullScreenViewController!.modalPresentationStyle = .fullScreen activityViewController.present(self.fullScreenViewController!, animated: false, completion: { self.view.removeFromSuperview() self.fullScreenViewController!.view.addSubview(self.view) self.fullScreenViewController!.view.sendSubviewToBack(self.view) self.view.bounds = self.fullScreenViewController!.view.bounds self.view.center = self.fullScreenViewController!.view.center self.setControlsHidden(false, animated: true) NotificationCenter.default.post(name: .EZPlayerDisplayModeChangedDidAppear, object: self, userInfo: [Notification.Key.EZPlayerDisplayModeChangedFrom : self.lastDisplayMode, Notification.Key.EZPlayerDisplayModeChangedTo : EZPlayerDisplayMode.fullscreen]) completion?(true) self.isChangingDisplayMode = false }) } } let lastDisplayModeTemp = self.displayMode if lastDisplayModeTemp == .embedded{ guard let embeddedContentView = self.embeddedContentView else { completion?(false) return } self.lastDisplayMode = lastDisplayModeTemp __toFull(from: embeddedContentView) }else if lastDisplayModeTemp == .float{ let floatModelSupported = EZPlayerUtils.floatModelSupported(self) if floatModelSupported == .system{ self.lastDisplayMode = .fullscreen//特殊处理:设置目标 self.stopPIP { } }else{ guard let floatContainer = self.floatContainer else { completion?(false) return } self.lastDisplayMode = lastDisplayModeTemp floatContainer.hidden() __toFull(from: floatContainer.floatWindow) } }else{ //直接进入全屏 self.updateCustomView(toDisplayMode: .fullscreen) NotificationCenter.default.post(name: .EZPlayerDisplayModeChangedWillAppear, object: self, userInfo: [Notification.Key.EZPlayerDisplayModeChangedFrom : self.lastDisplayMode, Notification.Key.EZPlayerDisplayModeChangedTo : EZPlayerDisplayMode.fullscreen]) self.setControlsHidden(true, animated: false) self.fullScreenViewController = EZPlayerFullScreenViewController() self.fullScreenViewController!.preferredlandscapeForPresentation = orientation == .landscapeRight ? .landscapeLeft : .landscapeRight self.fullScreenViewController!.player = self self.view.frame = self.fullScreenViewController!.view.bounds self.fullScreenViewController!.view.addSubview(self.view) self.fullScreenViewController!.view.sendSubviewToBack(self.view) self.fullScreenViewController!.modalPresentationStyle = .fullScreen activityViewController.present(self.fullScreenViewController!, animated: animated, completion: { self.floatContainer?.hidden() self.setControlsHidden(false, animated: true) completion?(true) NotificationCenter.default.post(name: .EZPlayerDisplayModeChangedDidAppear, object: self, userInfo: [Notification.Key.EZPlayerDisplayModeChangedFrom : self.lastDisplayMode, Notification.Key.EZPlayerDisplayModeChangedTo : EZPlayerDisplayMode.fullscreen]) }) } } open func toEmbedded(animated: Bool = true , completion: ((Bool) -> Swift.Void)? = nil){ if self.isChangingDisplayMode == true { completion?(false) return } if self.displayMode == .embedded { completion?(false) return } guard let embeddedContentView = self.embeddedContentView else{ completion?(false) return } func __endToEmbedded(finished :Bool) { self.view.removeFromSuperview() embeddedContentView.addSubview(self.view) self.view.frame = embeddedContentView.bounds self.setControlsHidden(false, animated: true) self.fullScreenViewController = nil completion?(finished) NotificationCenter.default.post(name: .EZPlayerDisplayModeChangedDidAppear, object: self, userInfo: [Notification.Key.EZPlayerDisplayModeChangedFrom : self.lastDisplayMode, Notification.Key.EZPlayerDisplayModeChangedTo : EZPlayerDisplayMode.embedded]) self.isChangingDisplayMode = false } let lastDisplayModeTemp = self.displayMode if lastDisplayModeTemp == .fullscreen{ guard let fullScreenViewController = self.fullScreenViewController else{ completion?(false) return } self.lastDisplayMode = lastDisplayModeTemp self.isChangingDisplayMode = true self.updateCustomView(toDisplayMode: .embedded) NotificationCenter.default.post(name: .EZPlayerDisplayModeChangedWillAppear, object: self, userInfo: [Notification.Key.EZPlayerDisplayModeChangedFrom : self.lastDisplayMode, Notification.Key.EZPlayerDisplayModeChangedTo : EZPlayerDisplayMode.embedded]) self.setControlsHidden(true, animated: false) if animated { let rect = fullScreenViewController.view.bounds self.view.removeFromSuperview() UIApplication.shared.keyWindow?.addSubview(self.view) fullScreenViewController.dismiss(animated: false, completion: { if self.autoLandscapeFullScreenLandscape && self.fullScreenMode == .landscape{ self.view.transform = CGAffineTransform(rotationAngle : fullScreenViewController.currentOrientation == .landscapeLeft ? CGFloat(Double.pi / 2) : -CGFloat(Double.pi / 2)) self.view.frame = CGRect(x: rect.origin.x, y: rect.origin.y, width: rect.size.height, height: rect.size.width) }else{ self.view.bounds = embeddedContentView.bounds } UIView.animate(withDuration: EZPlayerAnimatedDuration, animations: { if self.autoLandscapeFullScreenLandscape && self.fullScreenMode == .landscape{ self.view.transform = CGAffineTransform.identity } var center = embeddedContentView.center if let embeddedContentSuperview = embeddedContentView.superview { center = embeddedContentSuperview.convert(embeddedContentView.center, to: UIApplication.shared.keyWindow) } self.view.bounds = embeddedContentView.bounds self.view.center = center }, completion: {finished in __endToEmbedded(finished: finished) }) }) }else{ fullScreenViewController.dismiss(animated: false, completion: { __endToEmbedded(finished: true) }) } }else if lastDisplayModeTemp == .float{ let floatModelSupported = EZPlayerUtils.floatModelSupported(self) if floatModelSupported == .system{ self.lastDisplayMode = .embedded//特殊处理:设置目标 self.stopPIP { } }else{ guard let floatContainer = self.floatContainer else { completion?(false) return } self.lastDisplayMode = lastDisplayModeTemp floatContainer.hidden() // self.controlView = Bundle(for: EZPlayerControlView.self).loadNibNamed(String(describing: EZPlayerControlView.self), owner: self, options: nil)?.last as? EZPlayerControlView // self.displayMode = .embedded self.isChangingDisplayMode = true self.updateCustomView(toDisplayMode: .embedded) NotificationCenter.default.post(name: .EZPlayerDisplayModeChangedWillAppear, object: self, userInfo: [Notification.Key.EZPlayerDisplayModeChangedFrom : self.lastDisplayMode, Notification.Key.EZPlayerDisplayModeChangedTo : EZPlayerDisplayMode.embedded]) self.setControlsHidden(true, animated: false) if animated { let rect = floatContainer.floatWindow.convert(self.view.frame, to: UIApplication.shared.keyWindow) self.view.removeFromSuperview() UIApplication.shared.keyWindow?.addSubview(self.view) self.view.frame = rect UIView.animate(withDuration: EZPlayerAnimatedDuration, animations: { self.view.bounds = embeddedContentView.bounds self.view.center = embeddedContentView.center }, completion: {finished in __endToEmbedded(finished: finished) }) }else{ __endToEmbedded(finished: true) } } }else{ completion?(false) } } /// 进入浮层模式, /// - Parameters: /// - animated: <#animated description#> /// - completion: <#completion description#> open func toFloat(animated: Bool = true, completion: ((Bool) -> Swift.Void)? = nil) { if self.floatMode == .none { completion?(false) return } if self.isChangingDisplayMode == true { completion?(false) return } if self.displayMode == .float { completion?(false) return } let floatModelSupported = EZPlayerUtils.floatModelSupported(self) if floatModelSupported == .system{ self.isChangingDisplayMode = true NotificationCenter.default.post(name: .EZPlayerDisplayModeChangedWillAppear, object: self, userInfo: [Notification.Key.EZPlayerDisplayModeChangedFrom : self.displayMode, Notification.Key.EZPlayerDisplayModeChangedTo : EZPlayerDisplayMode.float]) self.startPIP { [weak self] error in guard let weakSelf = self else{ return } weakSelf.isChangingDisplayMode = false weakSelf.lastDisplayMode = weakSelf.displayMode if weakSelf.lastDisplayMode == .fullscreen{ guard let fullScreenViewController = weakSelf.fullScreenViewController else{ return } fullScreenViewController.dismiss(animated: false) { weakSelf.fullScreenViewController = nil } }else if weakSelf.lastDisplayMode == .embedded{ // weakSelf.view.removeFromSuperview() // weakSelf.controlViewForEmbedded = nil weakSelf.view.isHidden = true } weakSelf.updateCustomView(toDisplayMode: .float) completion?(error != nil ? true : false) NotificationCenter.default.post(name: .EZPlayerDisplayModeChangedDidAppear, object: weakSelf, userInfo: [Notification.Key.EZPlayerDisplayModeChangedFrom : weakSelf.lastDisplayMode, Notification.Key.EZPlayerDisplayModeChangedTo : error != nil ? weakSelf.lastDisplayMode : EZPlayerDisplayMode.float]) } }else{ self.toWindow(animated: animated, completion: completion) } } // MARK: - public open func setControlsHidden(_ hidden: Bool, animated: Bool = false){ self.controlsHidden = hidden (self.controlView as? EZPlayerDelegate)?.player(self, playerControlsHiddenDidChange: hidden ,animated: animated ) self.delegate?.player(self, playerControlsHiddenDidChange: hidden,animated: animated) NotificationCenter.default.post(name: .EZPlayerControlsHiddenDidChange, object: self, userInfo: [Notification.Key.EZPlayerControlsHiddenDidChangeKey: hidden,Notification.Key.EZPlayerControlsHiddenDidChangeByAnimatedKey: animated]) } open func updateCustomView(toDisplayMode: EZPlayerDisplayMode? = nil){ var nextDisplayMode = self.displayMode if toDisplayMode != nil{ nextDisplayMode = toDisplayMode! } if let view = self.controlViewForIntercept{ self.playerView?.controlView = view self.displayMode = nextDisplayMode return } switch nextDisplayMode { case .embedded: //playerView加问号,其实不关心playerView存不存在,存在就更新 if self.playerView?.controlView == nil || self.playerView?.controlView != self.controlViewForEmbedded{ if self.controlViewForEmbedded == nil { self.controlViewForEmbedded = self.controlViewForFullscreen ?? Bundle(for: EZPlayerControlView.self).loadNibNamed(String(describing: EZPlayerControlView.self), owner: self, options: nil)?.last as? EZPlayerControlView } } self.playerView?.controlView = self.controlViewForEmbedded case .fullscreen: if self.playerView?.controlView == nil || self.playerView?.controlView != self.controlViewForFullscreen{ if self.controlViewForFullscreen == nil { self.controlViewForFullscreen = self.controlViewForEmbedded ?? Bundle(for: EZPlayerControlView.self).loadNibNamed(String(describing: EZPlayerControlView.self), owner: self, options: nil)?.last as? EZPlayerControlView } } self.playerView?.controlView = self.controlViewForFullscreen case .float: // if self.controlViewForFloat == nil { // self.controlViewForFloat = Bundle(for: EZPlayerFloatView.self).loadNibNamed(String(describing: EZPlayerFloatView.self), owner: self, options: nil)?.last as? UIView // } let floatModelSupported = EZPlayerUtils.floatModelSupported(self) if self.playerView?.controlView == nil || self.playerView?.controlView != self.controlViewForFloat{ if self.controlViewForFloat == nil { self.controlViewForFloat = floatModelSupported == .window ? Bundle(for: EZPlayerWindowView.self).loadNibNamed(String(describing: EZPlayerWindowView.self), owner: self, options: nil)?.last as? UIView : Bundle(for: EZPlayerControlView.self).loadNibNamed(String(describing: EZPlayerControlView.self), owner: self, options: nil)?.last as? EZPlayerControlView } } self.playerView?.controlView = self.controlViewForFloat break case .none: //初始化的时候 if self.controlView == nil { self.controlViewForEmbedded = Bundle(for: EZPlayerControlView.self).loadNibNamed(String(describing: EZPlayerControlView.self), owner: self, options: nil)?.last as? EZPlayerControlView } } self.displayMode = nextDisplayMode } // MARK: - private private func commonInit() { self.updateCustomView()//走case .none:,防止没有初始化 NotificationCenter.default.addObserver(self, selector: #selector(self.applicationWillEnterForeground(_:)), name: UIApplication.willEnterForegroundNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.applicationDidBecomeActive(_:)), name: UIApplication.didBecomeActiveNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.applicationWillResignActive(_:)), name: UIApplication.willResignActiveNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(self.applicationDidEnterBackground(_:)), name: UIApplication.didEnterBackgroundNotification, object: nil) UIDevice.current.beginGeneratingDeviceOrientationNotifications() NotificationCenter.default.addObserver(self, selector: #selector(self.deviceOrientationDidChange(_:)), name: UIDevice.orientationDidChangeNotification, object: nil) // NotificationCenter.default.addObserver(self, selector: #selector(self.playerDidPlayToEnd(_:)), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: playerItem) self.timer?.invalidate() self.timer = nil self.timer = Timer.timerWithTimeInterval(0.5, block: { [weak self] in // guard let weakself = self, let player = weakself.pl guard let weakSelf = self, let _ = weakSelf.player, let playerItem = weakSelf.playerItem else{ return } if !playerItem.isPlaybackLikelyToKeepUp && weakSelf.state == .playing{ weakSelf.state = .buffering } if playerItem.isPlaybackLikelyToKeepUp && (weakSelf.state == .buffering || weakSelf.state == .readyToPlay){ weakSelf.state = .bufferFinished if weakSelf.autoPlay { weakSelf.state = .playing } } (weakSelf.controlView as? EZPlayerDelegate)?.playerHeartbeat(weakSelf) weakSelf.delegate?.playerHeartbeat(weakSelf) NotificationCenter.default.post(name: .EZPlayerHeartbeat, object: self, userInfo:nil) }, repeats: true) RunLoop.current.add(self.timer!, forMode: RunLoop.Mode.common) } private func prepareToPlay(){ guard let url = self.contentURL else { self.state = .error(.invalidContentURL) return } self.releasePlayerResource() self.playerasset = AVAsset(url: url) let keys = ["tracks","duration","commonMetadata","availableMediaCharacteristicsWithMediaSelectionOptions"] self.playerItem = AVPlayerItem(asset: self.playerasset!, automaticallyLoadedAssetKeys: keys) self.player = AVPlayer(playerItem: playerItem!) // if #available(iOS 10.0, *) { // self.player!.automaticallyWaitsToMinimizeStalling = false // } self.player!.allowsExternalPlayback = self.allowsExternalPlayback if self.playerView == nil { self.playerView = EZPlayerView(controlView: self.controlView ) } (self.playerView?.layer as! AVPlayerLayer).videoGravity = AVLayerVideoGravity(rawValue: self.videoGravity.rawValue) self.playerView?.config(player: self) (self.controlView as? EZPlayerDelegate)?.player(self, showLoading: true) self.delegate?.player(self, showLoading: true) NotificationCenter.default.post(name: .EZPlayerLoadingDidChange, object: self, userInfo: [Notification.Key.EZPlayerLoadingDidChangeKey: true]) self.addPlayerItemTimeObserver() } private func addPlayerItemTimeObserver(){ self.timeObserver = self.player?.addPeriodicTimeObserver(forInterval: CMTimeMakeWithSeconds(0.5, preferredTimescale: CMTimeScale(NSEC_PER_SEC)), queue: DispatchQueue.main, using: { [weak self] time in guard let weakSelf = self else { return } (weakSelf.controlView as? EZPlayerDelegate)?.player(weakSelf, currentTime: weakSelf.currentTime ?? 0, duration: weakSelf.duration ?? 0) weakSelf.delegate?.player(weakSelf, currentTime: weakSelf.currentTime ?? 0, duration: weakSelf.duration ?? 0) NotificationCenter.default.post(name: .EZPlayerPlaybackTimeDidChange, object: self, userInfo:nil) }) } private func resetPlayerResource() { self.contentItem = nil self.contentURL = nil if self.videoOutput != nil { self.playerItem?.remove(self.videoOutput!) } self.videoOutput = nil self.playerasset = nil self.playerItem = nil self.player?.replaceCurrentItem(with: nil) self.playerView?.layer.removeAllAnimations() (self.controlView as? EZPlayerDelegate)?.player(self, bufferDurationDidChange: 0, totalDuration: 0) self.delegate?.player(self, bufferDurationDidChange: 0, totalDuration: 0) (self.controlView as? EZPlayerDelegate)?.player(self, currentTime:0, duration: 0) self.delegate?.player(self, currentTime: 0, duration: 0) NotificationCenter.default.post(name: .EZPlayerPlaybackTimeDidChange, object: self, userInfo:nil) } private func releasePlayerResource() { self.releasePIPResource() if self.fullScreenViewController != nil { self.fullScreenViewController!.dismiss(animated: true, completion: { }) } self.scrollView = nil self.indexPath = nil if self.videoOutput != nil { self.playerItem?.remove(self.videoOutput!) } self.videoOutput = nil self.playerasset = nil self.playerItem = nil self.player?.replaceCurrentItem(with: nil) self.playerView?.layer.removeAllAnimations() self.playerView?.removeFromSuperview() self.playerView = nil if self.timeObserver != nil{ self.player?.removeTimeObserver(self.timeObserver!) self.timeObserver = nil } } } // MARK: - Notification extension EZPlayer { @objc fileprivate func playerDidPlayToEnd(_ notifiaction: Notification) { self.state = .stopped NotificationCenter.default.post(name: .EZPlayerPlaybackDidFinish, object: self, userInfo: [Notification.Key.EZPlayerPlaybackDidFinishReasonKey: EZPlayerPlaybackDidFinishReason.playbackEndTime]) } @objc fileprivate func deviceOrientationDidChange(_ notifiaction: Notification){ // if !self.autoLandscapeFullScreenLandscape || self.embeddedContentView == nil{ //app前后台切换 if UIApplication.shared.applicationState != UIApplication.State.active { return } if !self.autoLandscapeFullScreenLandscape || self.fullScreenMode == .portrait { return } switch UIDevice.current.orientation { case .portrait: //如果后台切回前台保持原来竖屏状态 if self.displayMode == .embedded || self.displayMode == .float { return } if self.lastDisplayMode == .embedded{ self.toEmbedded() }else if self.lastDisplayMode == .float{ self.toFloat() } case .landscapeLeft: self.toFull(UIDevice.current.orientation) case .landscapeRight: self.toFull(UIDevice.current.orientation) default: break } } @objc fileprivate func applicationWillEnterForeground(_ notifiaction: Notification){ } @objc fileprivate func applicationDidBecomeActive(_ notifiaction: Notification){ } @objc fileprivate func applicationWillResignActive(_ notifiaction: Notification){ } @objc fileprivate func applicationDidEnterBackground(_ notifiaction: Notification){ } } // MARK: - KVO extension EZPlayer { override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if let item = object as? AVPlayerItem, let keyPath = keyPath { if item == self.playerItem { switch keyPath { case #keyPath(AVPlayerItem.status): //todo check main thread //3)然后是kAVPlayerItemStatus的变化,从0变为1,即变为readyToPlay printLog("AVPlayerItem's status is changed: \(item.status.rawValue)") if item.status == .readyToPlay {//可以播放 let lastState = self.state if self.state != .playing{ self.state = .readyToPlay } //自动播放 if self.autoPlay && lastState == .unknown{ self.play() } } else if item.status == .failed { self.state = .error(.playerFail) } case #keyPath(AVPlayerItem.loadedTimeRanges): printLog("AVPlayerItem's loadedTimeRanges is changed") (self.controlView as? EZPlayerDelegate)?.player(self, bufferDurationDidChange: item.bufferDuration ?? 0, totalDuration: self.duration ?? 0) self.delegate?.player(self, bufferDurationDidChange: item.bufferDuration ?? 0, totalDuration: self.duration ?? 0) case #keyPath(AVPlayerItem.isPlaybackBufferEmpty): //1)首先是观察到kAVPlayerItemPlaybackBufferEmpty的变化,从1变为0,说有缓存到内容了,已经有loadedTimeRanges了,但这时候还不一定能播放,因为数据可能还不够播放; printLog("AVPlayerItem's playbackBufferEmpty is changed") case #keyPath(AVPlayerItem.isPlaybackLikelyToKeepUp): //2)然后是kAVPlayerItemPlaybackLikelyToKeepUp,从0变到1,说明可以播放了,这时候会自动开始播放 printLog("AVPlayerItem's playbackLikelyToKeepUp is changed") default: break } } }else if let view = object as? UITableView ,let keyPath = keyPath{ switch keyPath { case #keyPath(UITableView.contentOffset): if isChangingDisplayMode == true{ return } if view == self.scrollView { if let index = self.indexPath { let cellrectInTable = view.rectForRow(at: index) let cellrectInTableSuperView = view.convert(cellrectInTable, to: view.superview) if cellrectInTableSuperView.origin.y + cellrectInTableSuperView.size.height/2 < view.frame.origin.y + view.contentInset.top || cellrectInTableSuperView.origin.y + cellrectInTableSuperView.size.height/2 > view.frame.origin.y + view.frame.size.height - view.contentInset.bottom{ self.toFloat() }else{ if let cell = view.cellForRow(at: index){ if !self.view.isDescendant(of: cell){ self.view.removeFromSuperview() self.embeddedContentView = self.embeddedContentView ?? cell.contentView self.embeddedContentView!.addSubview(self.view) } self.toEmbedded(animated: false, completion: { flag in }) } } } } default: break } } } } // MARK: - generateThumbnails extension EZPlayer { //不支持m3u8 open func generateThumbnails(times: [TimeInterval],maximumSize: CGSize, completionHandler: @escaping (([EZPlayerThumbnail]) -> Swift.Void )){ guard let imageGenerator = self.imageGenerator else { return } var values = [NSValue]() for time in times { values.append(NSValue(time: CMTimeMakeWithSeconds(time,preferredTimescale: CMTimeScale(NSEC_PER_SEC)))) } var thumbnailCount = values.count var thumbnails = [EZPlayerThumbnail]() imageGenerator.cancelAllCGImageGeneration() imageGenerator.appliesPreferredTrackTransform = true// 截图的时候调整到正确的方向 imageGenerator.maximumSize = maximumSize//设置后可以获取缩略图 imageGenerator.generateCGImagesAsynchronously(forTimes:values) { (requestedTime: CMTime,image: CGImage?,actualTime: CMTime,result: AVAssetImageGenerator.Result,error: Error?) in let thumbnail = EZPlayerThumbnail(requestedTime: requestedTime, image: image == nil ? nil : UIImage(cgImage: image!) , actualTime: actualTime, result: result, error: error) thumbnails.append(thumbnail) thumbnailCount -= 1 if thumbnailCount == 0 { DispatchQueue.main.async { completionHandler(thumbnails) } } } } //支持m3u8 open func snapshotImage() -> UIImage? { guard let playerItem = self.playerItem else { //playerItem is AVPlayerItem return nil } if self.videoOutput == nil { self.videoOutput = AVPlayerItemVideoOutput(pixelBufferAttributes: nil) playerItem.remove(self.videoOutput!) playerItem.add(self.videoOutput!) } guard let videoOutput = self.videoOutput else { return nil } let time = videoOutput.itemTime(forHostTime: CACurrentMediaTime()) if videoOutput.hasNewPixelBuffer(forItemTime: time) { let lastSnapshotPixelBuffer = videoOutput.copyPixelBuffer(forItemTime: time, itemTimeForDisplay: nil) if lastSnapshotPixelBuffer != nil { let ciImage = CIImage(cvPixelBuffer: lastSnapshotPixelBuffer!) let context = CIContext(options: nil) let rect = CGRect(x: CGFloat(0), y: CGFloat(0), width: CGFloat(CVPixelBufferGetWidth(lastSnapshotPixelBuffer!)), height: CGFloat(CVPixelBufferGetHeight(lastSnapshotPixelBuffer!))) let cgImage = context.createCGImage(ciImage, from: rect) if cgImage != nil { return UIImage(cgImage: cgImage!) } } } return nil } } // MARK: - display Mode extension EZPlayer { private func configFloatVideo(){ if self.floatContainerRootViewController == nil { self.floatContainerRootViewController = EZPlayerWindowContainerRootViewController(nibName: String(describing: EZPlayerWindowContainerRootViewController.self), bundle: Bundle(for: EZPlayerWindowContainerRootViewController.self)) } if self.floatContainer == nil { self.floatContainer = EZPlayerWindowContainer(frame: self.floatInitFrame, rootViewController: self.floatContainerRootViewController!) } } open func toWindow(animated: Bool = true, completion: ((Bool) -> Swift.Void)? = nil) { func __endToWindow(finished :Bool) { self.view.removeFromSuperview() self.floatContainerRootViewController?.addVideoView(self.view) self.floatContainer?.show() self.setControlsHidden(false, animated: true) self.fullScreenViewController = nil completion?(finished) NotificationCenter.default.post(name: .EZPlayerDisplayModeChangedDidAppear, object: self, userInfo: [Notification.Key.EZPlayerDisplayModeChangedFrom : self.lastDisplayMode, Notification.Key.EZPlayerDisplayModeChangedTo : EZPlayerDisplayMode.float]) self.isChangingDisplayMode = false } self.lastDisplayMode = self.displayMode if self.lastDisplayMode == .embedded { self.configFloatVideo() self.isChangingDisplayMode = true self.updateCustomView(toDisplayMode: .float) NotificationCenter.default.post(name: .EZPlayerDisplayModeChangedWillAppear, object: self, userInfo: [Notification.Key.EZPlayerDisplayModeChangedFrom : self.lastDisplayMode, Notification.Key.EZPlayerDisplayModeChangedTo : EZPlayerDisplayMode.float]) self.setControlsHidden(true, animated: false) if animated{ let rect = self.embeddedContentView!.convert(self.view.frame, to: UIApplication.shared.keyWindow) self.view.removeFromSuperview() UIApplication.shared.keyWindow?.addSubview(self.view) self.view.frame = rect UIView.animate(withDuration: EZPlayerAnimatedDuration, animations: { self.view.bounds = self.floatContainer!.floatWindow.bounds self.view.center = self.floatContainer!.floatWindow.center }, completion: {finished in __endToWindow(finished: finished) }) }else{ __endToWindow(finished: true) } }else if self.lastDisplayMode == .fullscreen{ guard let fullScreenViewController = self.fullScreenViewController else{ completion?(false) return } self.configFloatVideo() self.isChangingDisplayMode = true self.updateCustomView(toDisplayMode: .float) NotificationCenter.default.post(name: .EZPlayerDisplayModeChangedWillAppear, object: self, userInfo: [Notification.Key.EZPlayerDisplayModeChangedFrom : self.lastDisplayMode, Notification.Key.EZPlayerDisplayModeChangedTo : EZPlayerDisplayMode.float]) self.setControlsHidden(true, animated: false) if animated{ let rect = fullScreenViewController.view.bounds self.view.removeFromSuperview() UIApplication.shared.keyWindow?.addSubview(self.view) fullScreenViewController.dismiss(animated: false, completion: { if self.autoLandscapeFullScreenLandscape && self.fullScreenMode == .landscape{ self.view.transform = CGAffineTransform(rotationAngle : fullScreenViewController.currentOrientation == .landscapeLeft ? CGFloat(Double.pi / 2) : -CGFloat(Double.pi / 2)) self.view.frame = CGRect(x: rect.origin.x, y: rect.origin.y, width: rect.size.height, height: rect.size.width) }else{ self.view.bounds = self.floatContainer!.floatWindow.bounds } UIView.animate(withDuration: EZPlayerAnimatedDuration, animations: { if self.autoLandscapeFullScreenLandscape && self.fullScreenMode == .landscape{ self.view.transform = CGAffineTransform.identity } self.view.bounds = self.floatContainer!.floatWindow.bounds self.view.center = self.floatContainer!.floatWindow.center }, completion: {finished in __endToWindow(finished: finished) }) }) }else{ fullScreenViewController.dismiss(animated: false, completion: { __endToWindow(finished: true) }) } }else{ completion?(false) } } } // MARK: - Picture in Picture Mode extension EZPlayer: AVPictureInPictureControllerDelegate { /// 是否支持pip open var isPIPSupported: Bool{ return AVPictureInPictureController.isPictureInPictureSupported() } /// 当前是否处于画中画状态显示在屏幕上 open var isPIPActive: Bool{ return self.pipController?.isPictureInPictureActive ?? false } /// 当前画中画是否被挂起。如果你的app因为其他的app在使用PiP而导致你的视频后台播放播放状态为暂停并且不可见,将会返回true。当其他的app离开了PiP时,你的视频会被重新播放 open var isPIPSuspended: Bool{ return self.pipController?.isPictureInPictureSuspended ?? false } /// 告诉你画中画窗口是可用的。如果其他的app再使用PiP模式,他将会返回false。这个实行也能够通过KVO来观察,同样通过观察这种状态的改变,你也能够很好地额处理PiP按钮的的隐藏于展示。 open var isPIPPossible: Bool{ return self.pipController?.isPictureInPicturePossible ?? false } open func startPIP(completion: ((Error?) -> Void)? = nil){ self.configPIP() self.startPIPWithCompletion = completion //isPIPSupported和isPIPPossible为true才有效 // self.pipController?.startPictureInPicture() DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1) { self.pipController?.startPictureInPicture() } } open func stopPIP(completion: (() -> Void)? = nil){ self.endPIPWithCompletion = completion self.pipController?.stopPictureInPicture() } private func configPIP(){ if isPIPSupported && playerView != nil && pipController == nil { pipController = AVPictureInPictureController(playerLayer: playerView!.layer as! AVPlayerLayer) pipController?.delegate = self } } private func releasePIPResource() { pipController?.delegate = nil pipController = nil } /// 即将开启画中画 /// - Parameter pictureInPictureController: <#pictureInPictureController description#> public func pictureInPictureControllerWillStartPictureInPicture(_ pictureInPictureController: AVPictureInPictureController) { printLog("pip 即将开启画中画") (self.controlView as? EZPlayerDelegate)?.player(self, pictureInPictureControllerWillStartPictureInPicture: pictureInPictureController) self.delegate?.player(self, pictureInPictureControllerWillStartPictureInPicture: pictureInPictureController) NotificationCenter.default.post(name: .EZPlayerPIPControllerWillStart, object: self, userInfo: nil) } /// 已经开启画中画 /// - Parameter pictureInPictureController: <#pictureInPictureController description#> public func pictureInPictureControllerDidStartPictureInPicture(_ pictureInPictureController: AVPictureInPictureController) { printLog("pip 已经开启画中画") self.startPIPWithCompletion?(nil) (self.controlView as? EZPlayerDelegate)?.player(self, pictureInPictureControllerDidStartPictureInPicture: pictureInPictureController) self.delegate?.player(self, pictureInPictureControllerDidStartPictureInPicture: pictureInPictureController) NotificationCenter.default.post(name: .EZPlayerPIPControllerDidStart, object: self, userInfo: nil) } /// 开启画中画失败 /// - Parameters: /// - pictureInPictureController: <#pictureInPictureController description#> /// - error: <#error description#> public func pictureInPictureController(_ pictureInPictureController: AVPictureInPictureController, failedToStartPictureInPictureWithError error: Error) { printLog("pip 开启画中画失败") self.releasePIPResource() self.startPIPWithCompletion?(error) (self.controlView as? EZPlayerDelegate)?.player(self, pictureInPictureController: pictureInPictureController, failedToStartPictureInPictureWithError: error) self.delegate?.player(self, pictureInPictureController: pictureInPictureController, failedToStartPictureInPictureWithError: error) NotificationCenter.default.post(name: .EZPlayerPIPFailedToStart, object: self, userInfo: [Notification.Key.EZPlayerPIPFailedToStart: error]) } /// 即将关闭画中画 /// - Parameter pictureInPictureController: <#pictureInPictureController description#> public func pictureInPictureControllerWillStopPictureInPicture(_ pictureInPictureController: AVPictureInPictureController) { printLog("pip 即将关闭画中画") self.isChangingDisplayMode = true NotificationCenter.default.post(name: .EZPlayerDisplayModeChangedWillAppear, object: self, userInfo: [Notification.Key.EZPlayerDisplayModeChangedFrom : self.displayMode, Notification.Key.EZPlayerDisplayModeChangedTo : self.lastDisplayMode]) (self.controlView as? EZPlayerDelegate)?.player(self, pictureInPictureControllerWillStopPictureInPicture: pictureInPictureController) self.delegate?.player(self, pictureInPictureControllerWillStopPictureInPicture: pictureInPictureController) NotificationCenter.default.post(name: .EZPlayerPIPControllerWillEnd, object: self, userInfo: nil) } /// 已经关闭画中画 /// - Parameter pictureInPictureController: <#pictureInPictureController description#> public func pictureInPictureControllerDidStopPictureInPicture(_ pictureInPictureController: AVPictureInPictureController) { printLog("pip 已经关闭画中画") self.releasePIPResource() // 按钮last float x , last x float self.isChangingDisplayMode = false // if self.lastDisplayMode != .float{ let lastDisPlayModeTemp = self.lastDisplayMode self.lastDisplayMode = .float self.updateCustomView(toDisplayMode: lastDisPlayModeTemp) // }else{ // self.updateCustomView(toDisplayMode: lastDisPlayModeTemp) // self.updateCustomView(toDisplayMode: self.displayMode) // } // self.view.removeFromSuperview() // self.embeddedContentView!.addSubview(self.view) // self.view.frame = self.embeddedContentView!.bounds self.endPIPWithCompletion?() NotificationCenter.default.post(name: .EZPlayerDisplayModeChangedDidAppear, object: self, userInfo: [Notification.Key.EZPlayerDisplayModeChangedFrom : .float, Notification.Key.EZPlayerDisplayModeChangedTo : self.displayMode]) (self.controlView as? EZPlayerDelegate)?.player(self, pictureInPictureControllerDidStopPictureInPicture: pictureInPictureController) self.delegate?.player(self, pictureInPictureControllerDidStopPictureInPicture: pictureInPictureController) NotificationCenter.default.post(name: .EZPlayerPIPControllerDidEnd, object: self, userInfo: nil) if self.displayMode == .fullscreen{ if self.state == .playing { self.play() } if self.fullScreenViewController == nil { self.fullScreenViewController = EZPlayerFullScreenViewController() self.fullScreenViewController!.preferredlandscapeForPresentation = UIDevice.current.orientation == .landscapeRight ? .landscapeLeft : .landscapeRight self.fullScreenViewController!.player = self } // guard let fullScreenViewController = self.fullScreenViewController else{ // return // } self.fullScreenViewController!.modalPresentationStyle = .fullScreen guard let activityViewController = EZPlayerUtils.activityViewController() else { return } activityViewController.present(self.fullScreenViewController!, animated: false) { // self.view.removeFromSuperview() self.fullScreenViewController!.view.addSubview(self.view) self.fullScreenViewController!.view.sendSubviewToBack(self.view) self.view.bounds = self.fullScreenViewController!.view.bounds self.view.center = self.fullScreenViewController!.view.center self.view.isHidden = false self.setControlsHidden(false, animated: true) } }else if self.displayMode == .embedded{ self.view.isHidden = false } } /// 关闭画中画且恢复播放界面 /// - Parameters: /// - pictureInPictureController: <#pictureInPictureController description#> /// - completionHandler: <#completionHandler description#> public func pictureInPictureController(_ pictureInPictureController: AVPictureInPictureController, restoreUserInterfaceForPictureInPictureStopWithCompletionHandler completionHandler: @escaping (Bool) -> Void) { printLog("pip 关闭画中画且恢复播放界面") // completionHandler(true) (self.controlView as? EZPlayerDelegate)?.player(self, pictureInPictureController: pictureInPictureController, restoreUserInterfaceForPictureInPictureStopWithCompletionHandler: completionHandler) self.delegate?.player(self, pictureInPictureController: pictureInPictureController, restoreUserInterfaceForPictureInPictureStopWithCompletionHandler: completionHandler) NotificationCenter.default.post(name: .EZPlayerPIPRestoreUserInterfaceForStop, object: self, userInfo: [Notification.Key.EZPlayerPIPStopWithCompletionHandler: completionHandler]) } }
82b50749e1af2d96ea7d7fbf268033be
41.475399
375
0.634144
false
false
false
false
younata/RSSClient
refs/heads/master
TethysKit/WebPageParser.swift
mit
1
import Kanna public final class WebPageParser: Operation { public enum SearchType { case feeds case links case `default` var acceptableTypes: [String] { switch self { case .feeds: return [ "application/rss+xml", "application/rdf+xml", "application/atom+xml", "application/xml", "text/xml" ] case .links, .default: return [] } } } private let webPage: String private let callback: ([URL]) -> Void private var urls = [URL]() public var searchType: SearchType = .default public init(string: String, callback: @escaping ([URL]) -> Void) { self.webPage = string self.callback = callback super.init() } public override func main() { if let doc = try? Kanna.HTML(html: self.webPage, encoding: String.Encoding.utf8) { switch self.searchType { case .feeds: for link in doc.xpath("//link") where link["rel"] == "alternate" && self.searchType.acceptableTypes.contains(link["type"] ?? "") { if let urlString = link["href"], let url = URL(string: urlString) { self.urls.append(url as URL) } } case .links: for link in doc.xpath("//a") { if let urlString = link["href"], let url = URL(string: urlString) { self.urls.append(url as URL) } } default: break } } self.callback(self.urls) } }
c8a218811ba0b32b2130e34e7a4c87d8
29.066667
91
0.45898
false
false
false
false
ngageoint/mage-ios
refs/heads/master
Mage/ObservationViewCardCollectionViewController.swift
apache-2.0
1
// // ObservationViewCardCollectionViewController.swift // MAGE // // Created by Daniel Barela on 12/16/20. // Copyright © 2020 National Geospatial Intelligence Agency. All rights reserved. // import Foundation import UIKit import MaterialComponents.MaterialCollections import MaterialComponents.MDCCard import MaterialComponents.MDCContainerScheme; class ObservationViewCardCollectionViewController: UIViewController { var didSetupConstraints = false; weak var observation: Observation?; var observationForms: [[String: Any]] = []; var cards: [ExpandableCard] = []; var attachmentViewCoordinator: AttachmentViewCoordinator?; var headerCard: ObservationHeaderView?; var observationEditCoordinator: ObservationEditCoordinator?; var bottomSheet: MDCBottomSheetController?; var scheme: MDCContainerScheming?; var attachmentCard: ObservationAttachmentCard?; let attachmentHeader: CardHeader = CardHeader(headerText: "ATTACHMENTS"); let formsHeader = FormsHeader(forAutoLayout: ()); private lazy var event: Event? = { guard let observation = observation, let eventId = observation.eventId, let context = observation.managedObjectContext else { return nil } return Event.getEvent(eventId: eventId, context: context) }() private lazy var eventForms: [Form] = { return event?.forms ?? [] }() private lazy var editFab : MDCFloatingButton = { let fab = MDCFloatingButton(shape: .default); fab.setImage(UIImage(systemName: "pencil", withConfiguration: UIImage.SymbolConfiguration(weight: .black)), for: .normal); fab.addTarget(self, action: #selector(startObservationEditCoordinator), for: .touchUpInside); return fab; }() private lazy var scrollView: UIScrollView = { let scrollView = UIScrollView.newAutoLayout(); scrollView.accessibilityIdentifier = "card scroll"; scrollView.accessibilityLabel = "card scroll"; scrollView.contentInset.bottom = 100; return scrollView; }() private lazy var stackView: UIStackView = { let stackView = UIStackView.newAutoLayout(); stackView.axis = .vertical stackView.alignment = .fill stackView.spacing = 8 stackView.distribution = .fill stackView.directionalLayoutMargins = NSDirectionalEdgeInsets(top: 8, leading: 8, bottom: 8, trailing: 8) stackView.isLayoutMarginsRelativeArrangement = true; return stackView; }() private lazy var syncStatusView: ObservationSyncStatus = { let syncStatusView = ObservationSyncStatus(observation: observation); stackView.addArrangedSubview(syncStatusView); return syncStatusView; }() func applyTheme(withContainerScheme containerScheme: MDCContainerScheming?) { self.scheme = containerScheme; guard let containerScheme = containerScheme else { return; } self.view.backgroundColor = containerScheme.colorScheme.backgroundColor; self.syncStatusView.applyTheme(withScheme: containerScheme); headerCard?.applyTheme(withScheme: containerScheme); attachmentCard?.applyTheme(withScheme: containerScheme); formsHeader.applyTheme(withScheme: containerScheme); attachmentHeader.applyTheme(withScheme: containerScheme); editFab.applySecondaryTheme(withScheme: containerScheme); } override func loadView() { view = UIView(); view.addSubview(scrollView); scrollView.addSubview(stackView); view.addSubview(editFab); let user = User.fetchCurrentUser(context: NSManagedObjectContext.mr_default()) editFab.isHidden = !(user?.hasEditPermission ?? false) view.setNeedsUpdateConstraints(); } override func updateViewConstraints() { if (!didSetupConstraints) { scrollView.autoPinEdgesToSuperviewEdges(with: .zero); stackView.autoPinEdgesToSuperviewEdges(); stackView.autoMatch(.width, to: .width, of: view); editFab.autoPinEdge(toSuperviewMargin: .right); editFab.autoPinEdge(toSuperviewMargin: .bottom, withInset: 25); didSetupConstraints = true; } super.updateViewConstraints(); } init(frame: CGRect) { super.init(nibName: nil, bundle: nil); } convenience public init(observation: Observation, scheme: MDCContainerScheming?) { self.init(frame: CGRect.zero); self.observation = observation; self.scheme = scheme; } required init(coder aDecoder: NSCoder) { fatalError("This class does not support NSCoding") } override func viewDidLoad() { super.viewDidLoad() self.view.accessibilityIdentifier = "ObservationViewCardCollection" self.view.accessibilityLabel = "ObservationViewCardCollection" } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated); ObservationPushService.singleton.addDelegate(delegate: self); setupObservation(); if let scheme = self.scheme { applyTheme(withContainerScheme: scheme); } } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated); let removedSubviews = cards.reduce([]) { (allSubviews, subview) -> [UIView] in stackView.removeArrangedSubview(subview) return allSubviews + [subview] } for v in removedSubviews { if v.superview != nil { v.removeFromSuperview() } } cards = []; ObservationPushService.singleton.removeDelegate(delegate: self); } func setupObservation() { self.title = "Observation"; if let properties = self.observation?.properties as? [String: Any] { if (properties.keys.contains("forms")) { observationForms = properties["forms"] as! [[String: Any]]; } } else { observationForms = []; } syncStatusView.updateObservationStatus(observation: observation); addHeaderCard(stackView: stackView); addLegacyAttachmentCard(stackView: stackView); var headerViews = 2; if (MageServer.isServerVersion5) { headerViews = 4; } if (stackView.arrangedSubviews.count > headerViews) { for v in stackView.arrangedSubviews.suffix(from: headerViews) { v.removeFromSuperview(); } } addFormViews(stackView: stackView); } func addHeaderCard(stackView: UIStackView) { if let observation = observation { if let headerCard = headerCard { headerCard.populate(observation: observation); } else { headerCard = ObservationHeaderView(observation: observation, observationActionsDelegate: self); if let scheme = self.scheme { headerCard!.applyTheme(withScheme: scheme); } stackView.addArrangedSubview(headerCard!); } } } // for legacy servers add the attachment field to common // TODO: this can be removed once all servers are upgraded func addLegacyAttachmentCard(stackView: UIStackView) { if (MageServer.isServerVersion5) { if let observation = observation { if let attachmentCard = attachmentCard { attachmentCard.populate(observation: observation); } else { attachmentCard = ObservationAttachmentCard(observation: observation, attachmentSelectionDelegate: self); if let scheme = self.scheme { attachmentCard!.applyTheme(withScheme: scheme); attachmentHeader.applyTheme(withScheme: scheme); } stackView.addArrangedSubview(attachmentHeader); stackView.addArrangedSubview(attachmentCard!); } let attachmentCount = (observation.attachments)?.filter() { attachment in return !attachment.markedForDeletion }.count if (attachmentCount != 0) { attachmentHeader.isHidden = false; attachmentCard?.isHidden = false; } else { attachmentHeader.isHidden = true; attachmentCard?.isHidden = true; } } } } func addFormViews(stackView: UIStackView) { formsHeader.reorderButton.isHidden = true; stackView.addArrangedSubview(formsHeader); for (index, form) in self.observationForms.enumerated() { let card: ExpandableCard = addObservationFormView(observationForm: form, index: index); card.expanded = index == 0; } } func addObservationFormView(observationForm: [String: Any], index: Int) -> ExpandableCard { let eventForm = event?.form(id: observationForm[EventKey.formId.key] as? NSNumber) var formPrimaryValue: String? = nil; var formSecondaryValue: String? = nil; if let primaryField = eventForm?.primaryFeedField, let primaryFieldName = primaryField[FieldKey.name.key] as? String { if let obsfield = observationForm[primaryFieldName] { formPrimaryValue = Observation.fieldValueText(value: obsfield, field: primaryField) } } if let secondaryField = eventForm?.secondaryFeedField, let secondaryFieldName = secondaryField[FieldKey.name.key] as? String { if let obsfield = observationForm[secondaryFieldName] { formSecondaryValue = Observation.fieldValueText(value: obsfield, field: secondaryField) } } let formView = ObservationFormView(observation: self.observation!, form: observationForm, eventForm: eventForm, formIndex: index, editMode: false, viewController: self, attachmentSelectionDelegate: self, observationActionsDelegate: self); if let scheme = self.scheme { formView.applyTheme(withScheme: scheme); } var formSpacerView: UIView?; if (!formView.isEmpty()) { formSpacerView = UIView(forAutoLayout: ()); let divider = UIView(forAutoLayout: ()); divider.backgroundColor = scheme?.colorScheme.onSurfaceColor.withAlphaComponent(0.12) ?? UIColor.black.withAlphaComponent(0.12); divider.autoSetDimension(.height, toSize: 1); formSpacerView?.addSubview(divider); formSpacerView?.addSubview(formView); divider.autoPinEdgesToSuperviewEdges(with: .zero, excludingEdge: .bottom); formView.autoPinEdgesToSuperviewEdges(with: UIEdgeInsets(top: 16, left: 16, bottom: 16, right: 16)); } var tintColor: UIColor? = nil; if let color = eventForm?.color { tintColor = UIColor(hex: color); } else { tintColor = scheme?.colorScheme.primaryColor } let card = ExpandableCard(header: formPrimaryValue, subheader: formSecondaryValue, systemImageName: "doc.text.fill", title: eventForm?.name, imageTint: tintColor, expandedView: formSpacerView); if let scheme = self.scheme { card.applyTheme(withScheme: scheme); } stackView.addArrangedSubview(card) cards.append(card); return card; } @objc func startObservationEditCoordinator() { guard let observation = self.observation else { return; } observationEditCoordinator = ObservationEditCoordinator(rootViewController: self.navigationController, delegate: self, observation: observation); observationEditCoordinator?.applyTheme(withContainerScheme: self.scheme); observationEditCoordinator?.start(); } } extension ObservationViewCardCollectionViewController: AttachmentSelectionDelegate { func selectedAttachment(_ attachment: Attachment!) { if (attachment.url == nil) { return; } guard let nav = self.navigationController else { return; } attachmentViewCoordinator = AttachmentViewCoordinator(rootViewController: nav, attachment: attachment, delegate: self, scheme: scheme); attachmentViewCoordinator?.start(); } func selectedUnsentAttachment(_ unsentAttachment: [AnyHashable : Any]!) { guard let nav = self.navigationController else { return; } attachmentViewCoordinator = AttachmentViewCoordinator(rootViewController: nav, url: URL(fileURLWithPath: unsentAttachment["localPath"] as! String), contentType: unsentAttachment["contentType"] as! String, delegate: self, scheme: scheme); attachmentViewCoordinator?.start(); } func selectedNotCachedAttachment(_ attachment: Attachment!, completionHandler handler: ((Bool) -> Void)!) { if (attachment.url == nil) { return; } guard let nav = self.navigationController else { return; } attachmentViewCoordinator = AttachmentViewCoordinator(rootViewController: nav, attachment: attachment, delegate: self, scheme: scheme); attachmentViewCoordinator?.start(); } } extension ObservationViewCardCollectionViewController: AttachmentViewDelegate { func doneViewing(coordinator: NSObject) { attachmentViewCoordinator = nil; } } extension ObservationViewCardCollectionViewController: ObservationPushDelegate { func didPush(observation: Observation, success: Bool, error: Error?) { if (observation.objectID != self.observation?.objectID) { return; } headerCard?.populate(observation: observation, ignoreGeometry: true); syncStatusView.updateObservationStatus(); if let scheme = self.scheme { syncStatusView.applyTheme(withScheme: scheme); } view.setNeedsUpdateConstraints(); } } extension ObservationViewCardCollectionViewController: ObservationActionsDelegate { func moreActionsTapped(_ observation: Observation) { let actionsSheet: ObservationActionsSheetController = ObservationActionsSheetController(observation: observation, delegate: self); actionsSheet.applyTheme(withContainerScheme: scheme); bottomSheet = MDCBottomSheetController(contentViewController: actionsSheet); self.navigationController?.present(bottomSheet!, animated: true, completion: nil); } func showFavorites(_ observation: Observation) { var userIds: [String] = []; if let favorites = observation.favorites { for favorite in favorites { if let userId = favorite.userId { userIds.append(userId) } } } if (userIds.count != 0) { let locationViewController = LocationsTableViewController(userIds: userIds, actionsDelegate: nil, scheme: scheme); locationViewController.title = "Favorited By"; self.navigationController?.pushViewController(locationViewController, animated: true); } } func favoriteObservation(_ observation: Observation, completion: ((Observation?) -> Void)?) { observation.toggleFavorite() { success, error in observation.managedObjectContext?.refresh(observation, mergeChanges: false); self.headerCard?.populate(observation: observation); } } func copyLocation(_ locationString: String) { UIPasteboard.general.string = locationString; MDCSnackbarManager.default.show(MDCSnackbarMessage(text: "Location \(locationString) copied to clipboard")) } func getDirectionsToObservation(_ observation: Observation, sourceView: UIView? = nil) { DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) { let notification = DirectionsToItemNotification(observation: observation, user: nil, feedItem: nil, sourceView: sourceView) NotificationCenter.default.post(name: .DirectionsToItem, object: notification) } } func makeImportant(_ observation: Observation, reason: String) { observation.flagImportant(description: reason) { success, error in // update the view observation.managedObjectContext?.refresh(observation, mergeChanges: true); self.headerCard?.populate(observation: observation); } } func removeImportant(_ observation: Observation) { observation.removeImportant() { success, error in // update the view observation.managedObjectContext?.refresh(observation, mergeChanges: false); self.headerCard?.populate(observation: observation); } } func editObservation(_ observation: Observation) { bottomSheet?.dismiss(animated: true, completion: nil); startObservationEditCoordinator() } func reorderForms(_ observation: Observation) { bottomSheet?.dismiss(animated: true, completion: nil); observationEditCoordinator = ObservationEditCoordinator(rootViewController: self.navigationController, delegate: self, observation: self.observation!); observationEditCoordinator?.applyTheme(withContainerScheme: self.scheme); observationEditCoordinator?.startFormReorder(); } func deleteObservation(_ observation: Observation) { bottomSheet?.dismiss(animated: true, completion: nil); ObservationActionHandler.deleteObservation(observation: observation, viewController: self) { (success, error) in self.navigationController?.popViewController(animated: true); } } func cancelAction() { bottomSheet?.dismiss(animated: true, completion: nil); } func viewUser(_ user: User) { bottomSheet?.dismiss(animated: true, completion: nil); let uvc = UserViewController(user: user, scheme: self.scheme!); self.navigationController?.pushViewController(uvc, animated: true); } } extension ObservationViewCardCollectionViewController: ObservationEditDelegate { func editCancel(_ coordinator: NSObject) { observationEditCoordinator = nil; } func editComplete(_ observation: Observation, coordinator: NSObject) { observationEditCoordinator = nil; guard let observation = self.observation else { return; } self.observation!.managedObjectContext?.refresh(observation, mergeChanges: false); // reload the observation setupObservation(); } }
2058c64b0c177ff4bda1017f8284a73e
40.528384
246
0.652313
false
false
false
false
mrdepth/EVEUniverse
refs/heads/master
Legacy/Neocom/Neocom/NCTreeViewController.swift
lgpl-2.1
2
// // NCTreeViewController.swift // Neocom // // Created by Artem Shimanski on 07.07.17. // Copyright © 2017 Artem Shimanski. All rights reserved. // import UIKit import CloudData import EVEAPI import Futures enum NCTreeViewControllerError: LocalizedError { case noResult var errorDescription: String? { switch self { case .noResult: return NSLocalizedString("No Results", comment: "") } } } //extension NCTreeViewControllerError { //} protocol NCSearchableViewController: UISearchResultsUpdating { var searchController: UISearchController? {get set} } extension NCSearchableViewController where Self: UITableViewController { func setupSearchController(searchResultsController: UIViewController) { searchController = UISearchController(searchResultsController: searchResultsController) searchController?.searchBar.searchBarStyle = UISearchBarStyle.default searchController?.searchResultsUpdater = self searchController?.searchBar.barStyle = UIBarStyle.black searchController?.searchBar.isTranslucent = false searchController?.hidesNavigationBarDuringPresentation = false tableView.backgroundView = UIView() tableView.tableHeaderView = searchController?.searchBar definesPresentationContext = true } } class NCTreeViewController: UITableViewController, TreeControllerDelegate, NCAPIController { var accountChangeObserver: NotificationObserver? var becomeActiveObserver: NotificationObserver? var refreshHandler: NCActionHandler<UIRefreshControl>? var treeController: TreeController? override func viewDidLoad() { super.viewDidLoad() tableView.backgroundColor = UIColor.background tableView.estimatedRowHeight = tableView.rowHeight tableView.rowHeight = UITableViewAutomaticDimension treeController = TreeController() treeController?.delegate = self treeController?.tableView = tableView tableView.delegate = treeController tableView.dataSource = treeController if let refreshControl = refreshControl { refreshHandler = NCActionHandler(refreshControl, for: .valueChanged) { [weak self] _ in self?.reload(cachePolicy: .reloadIgnoringLocalCacheData) } } becomeActiveObserver = NotificationCenter.default.addNotificationObserver(forName: .UIApplicationDidBecomeActive, object: nil, queue: nil) { [weak self] _ in self?.reloadIfNeeded() } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) reloadIfNeeded() } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) if let context = NCCache.sharedCache?.viewContext, context.hasChanges { try? context.save() } } //MARK: - NCAPIController var accountChangeAction: AccountChangeAction = .none { didSet { switch accountChangeAction { case .none: accountChangeObserver = nil case .reload: accountChangeObserver = NotificationCenter.default.addNotificationObserver(forName: .NCCurrentAccountChanged, object: nil, queue: nil) { [weak self] _ in self?.reload() } case .update: accountChangeObserver = NotificationCenter.default.addNotificationObserver(forName: .NCCurrentAccountChanged, object: nil, queue: nil) { [weak self] _ in self?.updateContent() } } } } var isLoading: Bool = false lazy var dataManager: NCDataManager = NCDataManager(account: NCAccount.current) // func updateContent(completionHandler: @escaping () -> Void) { // completionHandler() // } func content() -> Future<TreeNode?> { return .init(.failure(NCTreeViewControllerError.noResult)) } @discardableResult func updateContent() -> Future<TreeNode?> { return content().then(on: .main) { content -> TreeNode? in self.tableView.backgroundView = nil self.treeController?.content = content return content }.catch(on: .main) { error in self.tableView.backgroundView = NCTableViewBackgroundLabel(text: error.localizedDescription) } } // func reload(cachePolicy: URLRequest.CachePolicy, completionHandler: @escaping ([NCCacheRecord]) -> Void ) { // completionHandler([]) // } func load(cachePolicy: URLRequest.CachePolicy) -> Future<[NCCacheRecord]> { return .init([]) } func didStartLoading() { tableView.backgroundView = nil } func didFailLoading(error: Error) { treeController?.content = nil tableView.backgroundView = NCTableViewBackgroundLabel(text: error.localizedDescription) if let refreshControl = refreshControl, refreshControl.isRefreshing { refreshControl.endRefreshing() } } func didFinishLoading() { if let refreshControl = refreshControl, refreshControl.isRefreshing { refreshControl.endRefreshing() } } var managedObjectsObserver: NCManagedObjectObserver? lazy var updateGate = NCGate() var updateWork: DispatchWorkItem? var expireDate: Date? //MARK: - TreeControllerDelegate func treeController(_ treeController: TreeController, didSelectCellWithNode node: TreeNode) { if (!isEditing && !tableView.allowsMultipleSelection) || (isEditing && !tableView.allowsMultipleSelectionDuringEditing) { treeController.deselectCell(for: node, animated: true) if let route = (node as? TreeNodeRoutable)?.route { route.perform(source: self, sender: treeController.cell(for: node)) } } else { if isEditing && (self as TreeControllerDelegate).treeController?(treeController, editActionsForNode: node) == nil { treeController.deselectCell(for: node, animated: true) if let route = (node as? TreeNodeRoutable)?.route { route.perform(source: self, sender: treeController.cell(for: node)) } } } } func treeController(_ treeController: TreeController, didDeselectCellWithNode node: TreeNode) { } func treeController(_ treeController: TreeController, accessoryButtonTappedWithNode node: TreeNode) { if let route = (node as? TreeNodeRoutable)?.accessoryButtonRoute { route.perform(source: self, sender: treeController.cell(for: node)) } } } enum AccountChangeAction { case none case reload case update } protocol NCAPIController: class { // func updateContent(completionHandler: @escaping () -> Void) // func reload(cachePolicy: URLRequest.CachePolicy, completionHandler: @escaping ([NCCacheRecord]) -> Void ) func didStartLoading() func didFailLoading(error: Error) func didFinishLoading() func load(cachePolicy: URLRequest.CachePolicy) -> Future<[NCCacheRecord]> func content() -> Future<TreeNode?> @discardableResult func updateContent() -> Future<TreeNode?> var accountChangeAction: AccountChangeAction {get set} var isLoading: Bool {get set} var dataManager: NCDataManager {get set} var managedObjectsObserver: NCManagedObjectObserver? {get set} var updateGate: NCGate {get} var expireDate: Date? {get set} var updateWork: DispatchWorkItem? {get set} } enum NCAPIControllerError: LocalizedError { case authorizationRequired case noResult(String?) var errorDescription: String? { switch self { case .authorizationRequired: return NSLocalizedString("Please Sign In", comment: "") case let .noResult(message): return message ?? NSLocalizedString("No Result", comment: "") } } } extension NCAPIController where Self: UIViewController { func reloadIfNeeded() { if let expireDate = expireDate, expireDate < Date() { reload() } } func reload() { self.reload(cachePolicy: .useProtocolCachePolicy) } fileprivate func delayedUpdate() { let date = Date() expireDate = managedObjectsObserver?.objects.compactMap {($0 as? NCCacheRecord)?.expireDate as Date?}.filter {$0 > date}.min() let progress = NCProgressHandler(viewController: self, totalUnitCount: 1) updateGate.perform { DispatchQueue.main.async { progress.progress.perform { return self.updateContent() } }.wait() progress.finish() } } func reload(cachePolicy: URLRequest.CachePolicy) { guard !isLoading else {return} didStartLoading() let account = NCAccount.current guard accountChangeAction != .reload || account != nil else { didFailLoading(error: NCAPIControllerError.authorizationRequired) return } isLoading = true dataManager = NCDataManager(account: account, cachePolicy: cachePolicy) managedObjectsObserver = nil let progress = NCProgressHandler(viewController: self, totalUnitCount: 2) progress.progress.perform { self.load(cachePolicy: cachePolicy).then(on: .main) { records -> Future<TreeNode?> in let date = Date() self.expireDate = records.compactMap {$0.expireDate as Date?}.filter {$0 > date}.min() self.managedObjectsObserver = NCManagedObjectObserver(managedObjects: records) { [weak self] (_,_) in guard let strongSelf = self else {return} strongSelf.updateWork?.cancel() strongSelf.updateWork = DispatchWorkItem { self?.delayedUpdate() self?.updateWork = nil } DispatchQueue.main.async(execute: strongSelf.updateWork!) } return progress.progress.perform { self.updateContent() } }.then(on: .main) { _ in self.didFinishLoading() }.catch(on: .main) { error in self.didFailLoading(error: error) }.finally(on: .main) { progress.finish() self.isLoading = false } // // self.reload(cachePolicy: cachePolicy) { [weak self] records in // guard let strongSelf = self else { // progress.finish() // return // } // // let date = Date() // strongSelf.expireDate = records.compactMap {$0.expireDate as Date?}.filter {$0 > date}.min() // // progress.progress.perform { // strongSelf.updateContent { // progress.finish() // strongSelf.isLoading = false // strongSelf.didFinishLoading() // } // } // strongSelf.managedObjectsObserver = NCManagedObjectObserver(managedObjects: records) { [weak self] (_,_) in // guard let strongSelf = self else {return} // strongSelf.updateWork?.cancel() // strongSelf.updateWork = DispatchWorkItem { // self?.delayedUpdate() // self?.updateWork = nil // } // DispatchQueue.main.async(execute: strongSelf.updateWork!) // } // } } } } extension NCAPIController where Self: NCTreeViewController { func reloadIfNeeded() { if treeController?.content == nil || (expireDate ?? Date.distantFuture) < Date() { reload() } } }
1cf66224e83e00a3615e33e2ad67204a
28.767442
159
0.732129
false
false
false
false
CodaFi/swift
refs/heads/main
test/IRGen/prespecialized-metadata/struct-outmodule-resilient-1argument-1distinct_use-struct-inmodule.swift
apache-2.0
16
// RUN: %empty-directory(%t) // RUN: %target-build-swift -Xfrontend -prespecialize-generic-metadata -target %module-target-future %S/Inputs/struct-public-nonfrozen-1argument.swift -emit-library -o %t/%target-library-name(Generic) -emit-module -module-name Generic -emit-module-path %t/Generic.swiftmodule -enable-library-evolution // RUN: %swift -prespecialize-generic-metadata -target %module-target-future -emit-ir %s -L %t -I %t -lGeneric -lArgument | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment // REQUIRES: VENDOR=apple || OS=linux-gnu // UNSUPPORTED: CPU=i386 && OS=ios // UNSUPPORTED: CPU=armv7 && OS=ios // UNSUPPORTED: CPU=armv7s && OS=ios // CHECK-NOT: @"$s7Generic11OneArgumentVy4main03TheC0VGMN" = @inline(never) func consume<T>(_ t: T) { withExtendedLifetime(t) { t in } } import Generic struct TheArgument { let value: Int } // CHECK: define hidden swiftcc void @"$s4main4doityyF"() #{{[0-9]+}} { // CHECK: [[METADATA:%[0-9]+]] = call %swift.type* @__swift_instantiateConcreteTypeFromMangledName({ i32, i32 }* @"$s7Generic11OneArgumentVy4main03TheC0VGMD") // CHECK: call swiftcc void @"$s4main7consumeyyxlF"(%swift.opaque* noalias nocapture {{%[0-9]+}}, %swift.type* [[METADATA]]) // CHECK: } func doit() { consume( OneArgument(TheArgument(value: 13)) ) } doit()
6f073e380fbfbc60d1132771368f96ca
41.548387
301
0.711145
false
false
false
false
CodaFi/swift
refs/heads/main
test/IRGen/dynamic_self_metadata_future.swift
apache-2.0
17
// RUN: %target-swift-frontend -prespecialize-generic-metadata %s -target %module-target-future -emit-ir -parse-as-library | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment // REQUIRES: VENDOR=apple || OS=linux-gnu // REQUIRES: CPU=x86_64 // FIXME: Not a SIL test because we can't parse dynamic Self in SIL. // <rdar://problem/16931299> // CHECK: [[TYPE:%.+]] = type <{ [8 x i8] }> @inline(never) func id<T>(_ t: T) -> T { return t } // CHECK-LABEL: define hidden swiftcc void @"$s28dynamic_self_metadata_future2idyxxlF" protocol P { associatedtype T } extension P { func f() {} } struct G<T> : P { var t: T } class C { class func fromMetatype() -> Self? { return nil } // CHECK-LABEL: define hidden swiftcc i64 @"$s28dynamic_self_metadata_future1CC12fromMetatypeACXDSgyFZ"(%swift.type* swiftself %0) // CHECK: ret i64 0 func fromInstance() -> Self? { return nil } // CHECK-LABEL: define hidden swiftcc i64 @"$s28dynamic_self_metadata_future1CC12fromInstanceACXDSgyF"(%T28dynamic_self_metadata_future1CC* swiftself %0) // CHECK: ret i64 0 func dynamicSelfArgument() -> Self? { return id(nil) } // CHECK-LABEL: define hidden swiftcc i64 @"$s28dynamic_self_metadata_future1CC0A12SelfArgumentACXDSgyF"(%T28dynamic_self_metadata_future1CC* swiftself %0) // CHECK: [[GEP1:%.+]] = getelementptr {{.*}} %0 // CHECK: [[TYPE1:%.+]] = load {{.*}} [[GEP1]] // CHECK: [[T0:%.+]] = call swiftcc %swift.metadata_response @"$sSqMa"(i64 0, %swift.type* [[TYPE1]]) // CHECK: [[TYPE2:%.+]] = extractvalue %swift.metadata_response [[T0]], 0 // CHECK: call swiftcc void @"$s28dynamic_self_metadata_future2idyxxlF"({{.*}}, %swift.type* [[TYPE2]]) func dynamicSelfConformingType() -> Self? { _ = G(t: self).f() return nil } // CHECK-LABEL: define hidden swiftcc i64 @"$s28dynamic_self_metadata_future1CC0A18SelfConformingTypeACXDSgyF"(%T28dynamic_self_metadata_future1CC* swiftself %0) // CHECK: [[SELF_GEP:%.+]] = getelementptr {{.*}} %0 // CHECK: [[SELF_TYPE:%.+]] = load {{.*}} [[SELF_GEP]] // CHECK: call i8** @swift_getWitnessTable( // CHECK-SAME: %swift.protocol_conformance_descriptor* bitcast ( // CHECK-SAME: {{.*}} @"$s28dynamic_self_metadata_future1GVyxGAA1PAAMc" // CHECK-SAME: to %swift.protocol_conformance_descriptor* // CHECK-SAME: ), // CHECK-SAME: %swift.type* %{{[0-9]+}}, // CHECK-SAME: i8*** undef // CHECK-SAME: ) }
1215bf280002ee8b12fd08c397e92655
37.714286
191
0.656827
false
false
false
false
noppoMan/aws-sdk-swift
refs/heads/main
Sources/Soto/Services/Kendra/Kendra_Error.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // 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 Kendra public struct KendraErrorType: AWSErrorType { enum Code: String { case accessDeniedException = "AccessDeniedException" case conflictException = "ConflictException" case internalServerException = "InternalServerException" case resourceAlreadyExistException = "ResourceAlreadyExistException" case resourceInUseException = "ResourceInUseException" case resourceNotFoundException = "ResourceNotFoundException" case resourceUnavailableException = "ResourceUnavailableException" case serviceQuotaExceededException = "ServiceQuotaExceededException" case throttlingException = "ThrottlingException" case validationException = "ValidationException" } private let error: Code public let context: AWSErrorContext? /// initialize Kendra 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 } public static var accessDeniedException: Self { .init(.accessDeniedException) } public static var conflictException: Self { .init(.conflictException) } public static var internalServerException: Self { .init(.internalServerException) } public static var resourceAlreadyExistException: Self { .init(.resourceAlreadyExistException) } public static var resourceInUseException: Self { .init(.resourceInUseException) } public static var resourceNotFoundException: Self { .init(.resourceNotFoundException) } public static var resourceUnavailableException: Self { .init(.resourceUnavailableException) } public static var serviceQuotaExceededException: Self { .init(.serviceQuotaExceededException) } public static var throttlingException: Self { .init(.throttlingException) } public static var validationException: Self { .init(.validationException) } } extension KendraErrorType: Equatable { public static func == (lhs: KendraErrorType, rhs: KendraErrorType) -> Bool { lhs.error == rhs.error } } extension KendraErrorType: CustomStringConvertible { public var description: String { return "\(self.error.rawValue): \(self.message ?? "")" } }
2b871d09db514326ea31c896d387b0a6
40.405405
117
0.692559
false
false
false
false
barteljan/VISPER
refs/heads/master
Example/VISPER-Wireframe-Tests/DefaultRouterTests.swift
mit
1
import UIKit import XCTest @testable import VISPER_Core @testable import VISPER_Wireframe class DefaultRouterTests: XCTestCase { func testAddLiteralRoute() throws{ let router = DefaultRouter() let pattern = "/das/ist/ein/test/" try router.add(routePattern: pattern) guard router.routeDefinitions.count == 1 else { XCTFail("There should be exactly one route definition") return } let routeDefinition = router.routeDefinitions[0] guard routeDefinition.components.count == 4 else { XCTFail("There should be 4 route components") return } XCTAssertEqual(pattern, routeDefinition.routePattern) XCTAssertNil(routeDefinition.components[0].name) XCTAssertEqual(routeDefinition.components[0].string,"das") XCTAssertEqual(routeDefinition.components[0].type,RouteDefinition.Component.ComponentType.literal) XCTAssertNil(routeDefinition.components[1].name) XCTAssertEqual(routeDefinition.components[1].string,"ist") XCTAssertEqual(routeDefinition.components[1].type,RouteDefinition.Component.ComponentType.literal) XCTAssertNil(routeDefinition.components[2].name) XCTAssertEqual(routeDefinition.components[2].string,"ein") XCTAssertEqual(routeDefinition.components[2].type,RouteDefinition.Component.ComponentType.literal) XCTAssertNil(routeDefinition.components[3].name) XCTAssertEqual(routeDefinition.components[3].string,"test") XCTAssertEqual(routeDefinition.components[3].type,RouteDefinition.Component.ComponentType.literal) } func testAddVariableRoute() throws { let router = DefaultRouter() let pattern = "/das/ist/:var1/test/" try router.add(routePattern:pattern) guard router.routeDefinitions.count == 1 else { XCTFail("There should be exactly one route definition") return } let routeDefinition = router.routeDefinitions[0] guard routeDefinition.components.count == 4 else { XCTFail("There should be 4 route components") return } XCTAssertEqual(pattern, routeDefinition.routePattern) XCTAssertNil(routeDefinition.components[0].name) XCTAssertEqual(routeDefinition.components[0].string,"das") XCTAssertEqual(routeDefinition.components[0].type,RouteDefinition.Component.ComponentType.literal) XCTAssertNil(routeDefinition.components[1].name) XCTAssertEqual(routeDefinition.components[1].string,"ist") XCTAssertEqual(routeDefinition.components[1].type,RouteDefinition.Component.ComponentType.literal) XCTAssertEqual(routeDefinition.components[2].name,"var1") XCTAssertNil(routeDefinition.components[2].string) XCTAssertEqual(routeDefinition.components[2].type,RouteDefinition.Component.ComponentType.variable) XCTAssertNil(routeDefinition.components[3].name) XCTAssertEqual(routeDefinition.components[3].string,"test") XCTAssertEqual(routeDefinition.components[3].type,RouteDefinition.Component.ComponentType.literal) } func testAddWildcardRoute() throws { let router = DefaultRouter() let pattern = "/das/ist/ein/*" try router.add(routePattern: pattern) guard router.routeDefinitions.count == 1 else { XCTFail("There should be exactly one route definition") return } let routeDefinition = router.routeDefinitions[0] guard routeDefinition.components.count == 4 else { XCTFail("There should be 4 route components") return } XCTAssertEqual(pattern, routeDefinition.routePattern) XCTAssertNil(routeDefinition.components[0].name) XCTAssertEqual(routeDefinition.components[0].string,"das") XCTAssertEqual(routeDefinition.components[0].type,RouteDefinition.Component.ComponentType.literal) XCTAssertNil(routeDefinition.components[1].name) XCTAssertEqual(routeDefinition.components[1].string,"ist") XCTAssertEqual(routeDefinition.components[1].type,RouteDefinition.Component.ComponentType.literal) XCTAssertNil(routeDefinition.components[2].name) XCTAssertEqual(routeDefinition.components[2].string,"ein") XCTAssertEqual(routeDefinition.components[2].type,RouteDefinition.Component.ComponentType.literal) XCTAssertNil(routeDefinition.components[3].name) XCTAssertNil(routeDefinition.components[3].string) XCTAssertEqual(routeDefinition.components[3].type,RouteDefinition.Component.ComponentType.wildcard) } func testAddWrongWildcardRoute() throws { let router = DefaultRouter() do { try router.add(routePattern: "/das/ist/*/Test") XCTFail("Add Route should throw an exception in that case") } catch DefautRouterError.wildcardNotAtTheEndOfPattern { XCTAssert(true) } } func testCorrectRouteWithLiteral() throws { let router = DefaultRouter() let pattern = "/das/ist/ein/test/" try router.add(routePattern: pattern) let url = URL(string: pattern)! if let result = try router.route(url:url) { XCTAssertEqual(result.routePattern, pattern) XCTAssert(result.parameters.count == 4) XCTAssertEqual(result.parameters[DefaultRouter.parametersRoutePatternKey] as! String?, pattern) XCTAssertEqual(result.parameters[DefaultRouter.parametersJLRoutePatternKey] as! String?, pattern) XCTAssertEqual(result.parameters[DefaultRouter.parametersRouteURLKey] as! URL?, url) XCTAssertEqual(result.parameters[DefaultRouter.parametersJLRouteURLKey] as! URL?, url) } else { XCTFail("router should give an result") } } func testWrongRouteWithLiteral() throws { let router = DefaultRouter() let pattern = "/das/ist/ein/test/" try router.add(routePattern: pattern) let url = URL(string: "/das/hier/ist/falsch")! let result = try router.route(url:url) XCTAssertNil(result) } func testWrongRouteWithToLongLiteral() throws { let router = DefaultRouter() let pattern = "/das/ist/ein/test/" try router.add(routePattern: pattern) let url = URL(string: "/das/ist/ein/test/aber/einer/der/zu/Lang/ist")! let result = try router.route(url:url) XCTAssertNil(result) } func testWrongRouteWithToShortLiteral() throws { let router = DefaultRouter() let pattern = "/das/ist/ein/test/" try router.add(routePattern: pattern) let url = URL(string: "/das/ist/ein")! let result = try router.route(url:url) XCTAssertNil(result) } func testCorrectRouteWithVar() throws { let router = DefaultRouter() let pattern = "/das/ist/:var1/test/" try router.add(routePattern: pattern) let url = URL(string: "/das/ist/ein/test/")! if let result = try router.route(url:url) { XCTAssertEqual(result.routePattern, pattern) XCTAssert(result.parameters.count == 5) XCTAssertEqual(result.parameters[DefaultRouter.parametersRoutePatternKey] as! String?, pattern) XCTAssertEqual(result.parameters[DefaultRouter.parametersJLRoutePatternKey] as! String?, pattern) XCTAssertEqual(result.parameters[DefaultRouter.parametersRouteURLKey] as! URL?, url) XCTAssertEqual(result.parameters[DefaultRouter.parametersJLRouteURLKey] as! URL?, url) XCTAssertEqual(result.parameters["var1"] as! String?, "ein") } else { XCTFail("router should give an result") } } func testWrongRouteWithToLongVar() throws { let router = DefaultRouter() let pattern = "/das/ist/:var1/test/" try router.add(routePattern: pattern) let url = URL(string: "/das/ist/ein/test/aber/einer/der/zu/Lang/ist")! let result = try router.route(url:url) XCTAssertNil(result) } func testWrongRouteWithToShortVar() throws { let router = DefaultRouter() let pattern = "/das/ist/:var1/test/" try router.add(routePattern: pattern) let url = URL(string: "/das/ist/ein")! let result = try router.route(url:url) XCTAssertNil(result) } func testCorrectRouteWithWildcard() throws { let router = DefaultRouter() let pattern = "/das/ist/ein/*" try router.add(routePattern: pattern) let url = URL(string: "/das/ist/ein/test")! if let result = try router.route(url:url) { XCTAssertEqual(result.routePattern, pattern) XCTAssert(result.parameters.count == 5) XCTAssertEqual(result.parameters[DefaultRouter.parametersRoutePatternKey] as! String?, pattern) XCTAssertEqual(result.parameters[DefaultRouter.parametersJLRoutePatternKey] as! String?, pattern) XCTAssertEqual(result.parameters[DefaultRouter.parametersRouteURLKey] as! URL?, url) XCTAssertEqual(result.parameters[DefaultRouter.parametersJLRouteURLKey] as! URL?, url) if let wildcardParams = result.parameters[DefaultRouter.parametersWildcardKey] as? [String]{ if wildcardParams.count == 1 { XCTAssertEqual(wildcardParams[0], "test") } else { XCTFail("wildcard parameter shoult be an array of count 1") } } else { XCTFail("parameters do not contain wildcard key") } //XCTAssertEqual(result.parameters["*"] as! [String : String]?, "ein") } else { XCTFail("router should give an result") } } func testCorrectRouteWithLongWildcard() throws { let router = DefaultRouter() let pattern = "/das/ist/ein/*" try router.add(routePattern: pattern) let url = URL(string: "/das/ist/ein/test/der/lang/ist")! if let result = try router.route(url:url) { XCTAssertEqual(result.routePattern, pattern) XCTAssert(result.parameters.count == 5) XCTAssertEqual(result.parameters[DefaultRouter.parametersRoutePatternKey] as! String?, pattern) XCTAssertEqual(result.parameters[DefaultRouter.parametersJLRoutePatternKey] as! String?, pattern) XCTAssertEqual(result.parameters[DefaultRouter.parametersRouteURLKey] as! URL?, url) XCTAssertEqual(result.parameters[DefaultRouter.parametersJLRouteURLKey] as! URL?, url) if let wildcardParams = result.parameters[DefaultRouter.parametersWildcardKey] as? [String]{ if wildcardParams.count == 4 { XCTAssertEqual(wildcardParams[0], "test") XCTAssertEqual(wildcardParams[1], "der") XCTAssertEqual(wildcardParams[2], "lang") XCTAssertEqual(wildcardParams[3], "ist") } else { XCTFail("wildcard parameter shoult be an array of count 4") } } else { XCTFail("parameters do not contain wildcard key") } //XCTAssertEqual(result.parameters["*"] as! [String : String]?, "ein") } else { XCTFail("router should give an result") } } func testWrongToShortRouteWithWildcard() throws { let router = DefaultRouter() let pattern = "/das/ist/ein/*/" try router.add(routePattern: pattern) let url = URL(string: "/das/ist/ein")! let result = try router.route(url:url) XCTAssertNil(result) } func testResolveLastAddedRouteFirst() throws { let router = DefaultRouter() let pattern1 = "/das/ist/ein/:var1" try router.add(routePattern:pattern1) let pattern2 = "/das/ist/ein/:var2" try router.add(routePattern:pattern2) let url = URL(string: "/das/ist/ein/test/")! if let result = try router.route(url:url) { XCTAssertEqual(result.routePattern, pattern2) XCTAssert(result.parameters.count == 5) XCTAssertEqual(result.parameters[DefaultRouter.parametersRoutePatternKey] as! String?, pattern2) XCTAssertEqual(result.parameters[DefaultRouter.parametersJLRoutePatternKey] as! String?, pattern2) XCTAssertEqual(result.parameters[DefaultRouter.parametersRouteURLKey] as! URL?, url) XCTAssertEqual(result.parameters[DefaultRouter.parametersJLRouteURLKey] as! URL?, url) XCTAssertEqual(result.parameters["var2"] as! String?, "test") } else { XCTFail("router should give an result") } } func testParamsAreMerged() throws { let router = DefaultRouter() let pattern1 = "/das/ist/ein/:var1" try router.add(routePattern:pattern1) let url = URL(string: "/das/ist/ein/test/")! if let result = try router.route(url:url, parameters: ["id" : "55"]) { XCTAssertEqual(result.routePattern, pattern1) XCTAssert(result.parameters.count == 6) XCTAssertEqual(result.parameters[DefaultRouter.parametersRoutePatternKey] as! String?, pattern1) XCTAssertEqual(result.parameters[DefaultRouter.parametersJLRoutePatternKey] as! String?, pattern1) XCTAssertEqual(result.parameters[DefaultRouter.parametersRouteURLKey] as! URL?, url) XCTAssertEqual(result.parameters[DefaultRouter.parametersJLRouteURLKey] as! URL?, url) XCTAssertEqual(result.parameters["var1"] as? String, "test") XCTAssertEqual(result.parameters["id"] as? String, "55") } else { XCTFail("router should give an result") } } func testExternalParamsOverwriteParamsExtractedFromTheRouteMerged() throws { let router = DefaultRouter() let pattern1 = "/das/ist/ein/:var1" try router.add(routePattern:pattern1) let url = URL(string: "/das/ist/ein/test/")! if let result = try router.route(url:url, parameters: ["var1" : "55"]) { XCTAssertEqual(result.routePattern, pattern1) XCTAssert(result.parameters.count == 5) XCTAssertEqual(result.parameters[DefaultRouter.parametersRoutePatternKey] as! String?, pattern1) XCTAssertEqual(result.parameters[DefaultRouter.parametersJLRoutePatternKey] as! String?, pattern1) XCTAssertEqual(result.parameters[DefaultRouter.parametersRouteURLKey] as! URL?, url) XCTAssertEqual(result.parameters[DefaultRouter.parametersJLRouteURLKey] as! URL?, url) XCTAssertEqual(result.parameters["var1"] as? String, "55") } else { XCTFail("router should give an result") } } }
55418e8a149b9d377bdf7b2f343e86cd
38.01467
110
0.617723
false
true
false
false
64characters/Telephone
refs/heads/master
Telephone/CallHistoryViewController.swift
gpl-3.0
1
// // CallHistoryViewController.swift // Telephone // // Copyright © 2008-2016 Alexey Kuznetsov // Copyright © 2016-2022 64 Characters // // Telephone is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Telephone is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // import Cocoa final class CallHistoryViewController: NSViewController { @objc var keyView: NSView { return tableView } @objc weak var target: CallHistoryViewEventTarget? { didSet { target?.shouldReloadData() } } var recordCount: Int { return records.count } private var records: [PresentationCallHistoryRecord] = [] private let pasteboard = NSPasteboard.general @IBOutlet private weak var tableView: NSTableView! init() { super.init(nibName: "CallHistoryViewController", bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { target?.shouldReloadData() } override func keyDown(with event: NSEvent) { if isReturnKey(event) { pickRecord(at: tableView.selectedRow) } else if isDeleteKey(event) { removeRecord(at: tableView.selectedRow) } else { super.keyDown(with: event) } } @objc func updateNextKeyView(_ view: NSView) { keyView.nextKeyView = view } @IBAction func didDoubleClick(_ sender: NSTableView) { guard sender.clickedRow != -1 else { return } pickRecord(at: sender.clickedRow) } @IBAction func makeCall(_ sender: Any) { guard clickedOrSelectedRow() != -1 else { return } pickRecord(at: clickedOrSelectedRow()) } @IBAction func copy(_ sender: Any) { guard clickedOrSelectedRow() != -1 else { return } pasteboard.clearContents() pasteboard.writeObjects([records[clickedOrSelectedRow()]]) } @IBAction func delete(_ sender: Any) { guard clickedOrSelectedRow() != -1 else { return } removeRecord(at: clickedOrSelectedRow()) } @IBAction func deleteAll(_ sender: Any) { makeDeleteAllAlert().beginSheetModal(for: view.window!) { if $0 == .alertFirstButtonReturn { self.target?.shouldRemoveAllRecords() } } } } private extension CallHistoryViewController { func pickRecord(at index: Int) { guard !records.isEmpty else { return } target?.didPickRecord(withIdentifier: records[index].identifier) } func removeRecord(at index: Int) { guard !records.isEmpty else { return } let record = records[index] makeDeleteRecordAlert(recordName: record.name).beginSheetModal(for: view.window!) { if $0 == .alertFirstButtonReturn { self.removeTableViewRow(index, andRecordWithIdentifier: record.identifier) } } } func isReturnKey(_ event: NSEvent) -> Bool { return event.keyCode == 0x24 } func isDeleteKey(_ event: NSEvent) -> Bool { return event.keyCode == 0x33 || event.keyCode == 0x75 } func removeTableViewRow(_ row: Int, andRecordWithIdentifier identifier: String) { tableView.removeRows(at: IndexSet(integer: row), withAnimation: .slideUp) records.remove(at: row) target?.shouldRemoveRecord(withIdentifier: identifier) } func clickedOrSelectedRow() -> Int { return tableView.clickedRow != -1 ? tableView.clickedRow : tableView.selectedRow } } extension CallHistoryViewController: CallHistoryView { func show(_ records: [PresentationCallHistoryRecord]) { let oldRecords = self.records let oldIndex = tableView.selectedRow self.records = records reloadTableView(old: oldRecords, new: records) restoreSelection(oldIndex: oldIndex, old: oldRecords, new: records) } private func reloadTableView(old: [PresentationCallHistoryRecord], new: [PresentationCallHistoryRecord]) { let diff = ArrayDifference(before: old, after: new) if case .prepended(count: let count) = diff, count <= 2 { tableView.insertRows(at: IndexSet(integersIn: 0..<count), withAnimation: .slideDown) } else if case .shiftedByOne = diff { tableView.beginUpdates() tableView.insertRows(at: IndexSet(integer: 0), withAnimation: .slideDown) tableView.removeRows(at: IndexSet(integer: old.count), withAnimation: .slideDown) tableView.endUpdates() } else { tableView.reloadData() } } private func restoreSelection(oldIndex: Int, old: [PresentationCallHistoryRecord], new: [PresentationCallHistoryRecord]) { guard !records.isEmpty else { return } tableView.selectRowIndexes( IndexSet(integer: RestoredSelectionIndex(indexBefore: oldIndex, before: old, after: new).value), byExtendingSelection: false ) } } extension CallHistoryViewController: NSTableViewDataSource { func numberOfRows(in view: NSTableView) -> Int { return records.count } func tableView(_ view: NSTableView, objectValueFor column: NSTableColumn?, row: Int) -> Any? { return records[row] } } extension CallHistoryViewController: NSTableViewDelegate { func tableViewSelectionDidChange(_ notification: Notification) { updateSeparators() } func tableViewSelectionIsChanging(_ notification: Notification) { updateSeparators() } func tableView(_ tableView: NSTableView, rowActionsForRow row: Int, edge: NSTableView.RowActionEdge) -> [NSTableViewRowAction] { switch edge { case .trailing: return [makeDeleteAction()] case .leading: return [] @unknown default: return [] } } private func updateSeparators() { tableView.enumerateAvailableRowViews { (view, _) in view.needsDisplay = true } } private func makeDeleteAction() -> NSTableViewRowAction { let a = NSTableViewRowAction( style: .destructive, title: NSLocalizedString("Delete", comment: "Delete button."), handler: removeRowAndRecord ) a.image = NSImage(named: NSImage.touchBarDeleteTemplateName) return a } private func removeRowAndRecord(action: NSTableViewRowAction, row: Int) { removeTableViewRow(row, andRecordWithIdentifier: records[row].identifier) } } extension CallHistoryViewController: NSMenuItemValidation { func validateMenuItem(_ item: NSMenuItem) -> Bool { switch item.action { case #selector(copy(_:)), #selector(makeCall), #selector(delete), #selector(deleteAll): return !records.isEmpty default: return false } } } private func makeDeleteRecordAlert(recordName name: String) -> NSAlert { return makeDeletionAlert( messageText: String( format: NSLocalizedString( "Are you sure you want to delete the record “%@”?", comment: "Call history record removal alert." ), name ) ) } private func makeDeleteAllAlert() -> NSAlert { return makeDeletionAlert( messageText: NSLocalizedString( "Are you sure you want to delete all records?", comment: "Call history all records removal alert." ) ) } private func makeDeletionAlert(messageText text: String) -> NSAlert { let a = NSAlert() a.messageText = text a.informativeText = NSLocalizedString( "This action cannot be undone.", comment: "Call history record removal alert informative text." ) let delete = a.addButton(withTitle: NSLocalizedString("Delete", comment: "Delete button.")) if #available(macOS 11, *) { delete.hasDestructiveAction = true } a.addButton(withTitle: NSLocalizedString("Cancel", comment: "Cancel button.")).keyEquivalent = "\u{1b}" return a }
fd42c0c7d03ef89c75549bb387a9e8a0
32.351779
132
0.649443
false
false
false
false
eduresende/ios-nd-swift-syntax-swift-3
refs/heads/master
Lesson9/L9_Exercises.playground/Contents.swift
mit
1
//: ## Lesson 9 Exercises - Closures import UIKit //: __Problems 1&2__ //: //: In the code snippets below find two sorted arrays. For each: //: //:__a.__ //:Create a new array sorted in the reverse order. //: //:__b.__ //:Rewrite the sorting closure expression to be as concise as possible. // 1 var surnames = ["Silverman", "Fey", "Whig", "Schumer", "Kaling"] let orderedSurnames = surnames.sorted(by: {(name1: String, name2: String) -> Bool in return name2 > name1 }) // 2 let battingAverages = [0.302, 0.556, 0.280, 0.500, 0.281, 0.285] let sortedAverages = battingAverages.sorted(by: {(average1: Double, average2: Double) -> Bool in return average2 > average1 }) //: __Problem 3__ //: //: The following code snippet filters an array for all of the numbers which are divisible by 3. let numbers = [685, 1728, 648, 87, 979, 59175432] let divisibleByThree = numbers.filter({(number: Int) -> Bool in number % 3 == 0 }) //: __3a.__ //:Filter the following array for the numbers which are divisible by 12. let numbersAsStrings = ["685", "1728", "648", "87", "979", "59175432"] //: __3b.__ //: Rewrite the filtering closure expression to be as concise as possible. //: __Problem 4__ //: //: Filtering out particles greater that 20 microns has been shown to reduce exposure to waterborne pathogens. Filter the following array for all of the particles below 20 microns in size. Assign the result to a new array. let particleSizesInMicrons = [150, 16, 82, 30, 10, 57] //: __Problem 5__ //: //: The Array method, map, takes a closure expression as an argument. The closure is applied to each element in the Array, the results are mapped to a new Array, and that new Array is returned. //: In the example below each element in the particleSizeInMicrons array is incorporated into a String to which units are added. // Example let sizesAsStrings = particleSizesInMicrons.map({ (size: Int) -> String in return "\(size) microns" }) //: Ben just got back from India and he is tallying what he spent on gifts for his customs form. //: Use the map() method to transform this array of prices into dollars. Round to the nearest dollar. let pricesInRupees = [750, 825, 2000, 725] //: __Problem 6__ //: //: Katie has a competition going with her old friends from the track team. Each person tries to match her fastest high school time for the 1600m run + 1 second for every year since graduation. //: //:Use the map() method to transform the group members' racing times. Using the oldTimes array and the two helper functions provided below, create a new array of String values called goalTimes. Assume it's been 13 years since graduation. func timeIntervalFromString(_ timeString: String) -> Int { var timeArray = timeString.components(separatedBy: ":") let minutes = Int(String(timeArray[0]))! let seconds = Int(String(timeArray[1]))! return seconds + (minutes * 60) } func timeStringFromInterval(_ timeInterval: Int) -> NSString { let seconds = timeInterval % 60 let minutes = (timeInterval/60) % 60 return NSString(format: "%.1d:%.2d",minutes,seconds) } var oldTimes = ["5:18", "5:45", "5:56", "5:25", "5:27"]
af8f1f8bde3252909ad69f1f54f30966
41.013333
237
0.70073
false
false
false
false
vincent-cheny/DailyRecord
refs/heads/master
DailyRecord/TemplateViewController.swift
gpl-2.0
1
// // TemplateViewController.swift // DailyRecord // // Created by ChenYong on 16/2/12. // Copyright © 2016年 LazyPanda. All rights reserved. // import UIKit import RealmSwift class TemplateViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var templateFilterBtn: UIBarButtonItem! @IBOutlet weak var templateTableView: UITableView! typealias sendValueClosure = (type: String, content: String)->Void var myClosure: sendValueClosure? var templateType = "" let realm = try! Realm() var recordTemplates = try! Realm().objects(RecordTemplate).sorted("id") override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let backItem = UIBarButtonItem() backItem.title = "" self.navigationItem.backBarButtonItem = backItem templateTableView.delegate = self templateTableView.dataSource = self // 解决底部多余行问题 templateTableView.tableFooterView = UIView(frame: CGRectZero) templateType = templateFilterBtn.title! updateRecordTemplates(templateFilterBtn.title!) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.navigationController?.navigationBarHidden = false; templateTableView.reloadData() } func initWithClosure(closure: sendValueClosure){ myClosure = closure } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let templateCell = tableView.dequeueReusableCellWithIdentifier("templateCell", forIndexPath: indexPath) let template = recordTemplates[indexPath.row] let imageView = templateCell.viewWithTag(1) as! UIImageView let title = templateCell.viewWithTag(2) as! UILabel let type = templateCell.viewWithTag(3) as! UILabel let content = templateCell.viewWithTag(4) as! UILabel title.text = template.title type.text = template.type content.text = template.content switch template.type { case "黑业": imageView.image = UIImage(named: "blackdot") title.textColor = UIColor.blackColor() type.textColor = UIColor.blackColor() case "白业": imageView.image = UIImage(named: "whitedot") title.textColor = UIColor.whiteColor() type.textColor = UIColor.whiteColor() case "黑业对治": imageView.image = UIImage(named: "greendot") title.textColor = UIColor.greenColor() type.textColor = UIColor.greenColor() case "白业对治": imageView.image = UIImage(named: "reddot") title.textColor = UIColor.redColor() type.textColor = UIColor.redColor() default: break } // 解决左对齐问题 templateCell.layoutMargins = UIEdgeInsetsZero templateCell.addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(longPressCell(_:)))) return templateCell } func longPressCell(recognizer: UIGestureRecognizer) { if recognizer.state == .Began { let indexPath = templateTableView.indexPathForRowAtPoint(recognizer.locationInView(templateTableView)) let alert = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "编辑", style: UIAlertActionStyle.Default, handler: { (UIAlertAction) -> Void in self.navigateTemplate(indexPath!) })) alert.addAction(UIAlertAction(title: "取消", style: UIAlertActionStyle.Default, handler: nil)) alert.addAction(UIAlertAction(title: "删除", style: UIAlertActionStyle.Destructive, handler: { (UIAlertAction) -> Void in try! self.realm.write { self.realm.delete(self.recordTemplates[indexPath!.row]) } self.templateTableView.reloadData() })) self.presentViewController(alert, animated: true, completion: nil) } } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return recordTemplates.count } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { // 模拟闪动效果 tableView.deselectRowAtIndexPath(indexPath, animated: true) if self.myClosure != nil { let template = recordTemplates[indexPath.row] if template.type == templateType { myClosure!(type: template.type, content: template.content) navigationController?.popViewControllerAnimated(true) } else { let alert = UIAlertController(title: "请选择" + templateType, message: "", preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "确定", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) } } else { navigateTemplate(indexPath) } } func navigateTemplate(indexPath: NSIndexPath) { let addTemplateViewController = storyboard?.instantiateViewControllerWithIdentifier("AddTemplateViewController") as! AddTemplateViewController addTemplateViewController.templateId = recordTemplates[indexPath.row].id navigationController?.pushViewController(addTemplateViewController, animated: true) } @IBAction func templateFilter(sender: AnyObject) { let alert = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.Alert) filterData(alert, filter: "全部") filterData(alert, filter: "黑业") filterData(alert, filter: "黑业对治") filterData(alert, filter: "白业") filterData(alert, filter: "白业对治") self.presentViewController(alert, animated: true, completion: nil) } func filterData(alert: UIAlertController, filter: String) { alert.addAction(UIAlertAction(title: filter, style: UIAlertActionStyle.Default, handler: { (UIAlertAction) -> Void in self.updateRecordTemplates(filter) self.templateTableView.reloadData() })) } func updateRecordTemplates(filter: String) { self.templateFilterBtn.title = filter if filter == "全部" { self.recordTemplates = self.realm.objects(RecordTemplate).sorted("id") } else { self.recordTemplates = self.realm.objects(RecordTemplate).filter("type = %@", filter).sorted("id") } } }
27cda4783831cbd9639275c358a790a1
41.981366
150
0.659199
false
false
false
false
aestusLabs/ASChatApp
refs/heads/master
ChatButton.swift
mit
1
// // ChatButton.swift // ChatAppOrigionalFiles // // Created by Ian Kohlert on 2017-07-19. // Copyright © 2017 aestusLabs. All rights reserved. // import Foundation import UIKit class ChatButton: UIButton { var buttonTag: WidgetTagNames = .error let gradient = CAGradientLayer() override init (frame: CGRect) { super.init(frame: frame) self.layer.shadowColor = UIColor.lightGray.cgColor self.layer.shadowOpacity = 0.25 self.layer.shadowOffset = CGSize(width: 2, height: 4) self.layer.shadowRadius = 4 // gradient.frame = self.bounds // // let red = UIColor(red: 1.0, green: 0.28627451, blue: 0.568627451, alpha: 1.0) // let orange = UIColor(red: 1.0, green: 0.462745098, blue: 0.462745098, alpha: 1.0) // gradient.colors = [red.cgColor, orange.cgColor] // // gradient.startPoint = CGPoint.zero // gradient.endPoint = CGPoint(x: 1, y: 1) // self.layer.insertSublayer(gradient, at: 0) // self.layer.borderColor = appColours.getMainAppColour().cgColor // self.layer.borderWidth = 1 self.backgroundColor = appColours.getMainAppColour() //UIColor.white self.layer.cornerRadius = 18 self.setTitleColor(UIColor.white, for: .normal) self.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: UIFontWeightBold) } required init(coder aDecoder: NSCoder) { fatalError("This class does not support NSCoding") } } func createChatButton(text: String, tag: WidgetTagNames) -> ChatButton{ let button = ChatButton(frame: CGRect(x: 0, y: 0, width: 250, height: 40)) button.setTitle(text, for: .normal) button.buttonTag = tag return button }
a044a08d1f868a7eabd85eda184d4c25
30.732143
91
0.639842
false
false
false
false
logansease/SeaseAssist
refs/heads/master
Pod/Classes/UITextField+BottomBorder.swift
mit
1
// // UITextField+BottomBorder.swift // SeaseAssist // // Created by lsease on 5/16/17. // Copyright © 2017 Logan Sease. All rights reserved. // import UIKit @objc public extension UITextField { @objc func setBottomBorder(color: UIColor = UIColor(hex: "A5A5A5")) { self.borderStyle = .none self.layer.backgroundColor = UIColor.white.cgColor self.layer.masksToBounds = false self.layer.shadowColor = color.cgColor self.layer.shadowOffset = CGSize(width: 0.0, height: 1.0) self.layer.shadowOpacity = 0.5 self.layer.shadowRadius = 0.0 } }
13c0916745c7db22e5deb39ac208010f
26.909091
72
0.656352
false
false
false
false
WaterReporter/WaterReporter-iOS
refs/heads/master
WaterReporter/WaterReporter/Endpoints.swift
agpl-3.0
1
// // Endpoints.swift // WaterReporter // // Created by Viable Industries on 7/25/16. // Copyright © 2016 Viable Industries, L.L.C. All rights reserved. // import Foundation struct Endpoints { static let GET_MANY_REPORTS = "https://api.waterreporter.org/v2/data/report" static let POST_REPORT = "https://api.waterreporter.org/v2/data/report" static let GET_MANY_REPORT_LIKES = "https://api.waterreporter.org/v2/data/like" static let POST_LIKE = "https://api.waterreporter.org/v2/data/like" static let DELETE_LIKE = "https://api.waterreporter.org/v2/data/like" static let GET_MANY_USER = "https://api.waterreporter.org/v2/data/user" static let POST_AUTH_REMOTE = "https://api.waterreporter.org/v2/auth/remote" static let GET_AUTH_AUTHORIZE = "https://www.waterreporter.org/authorize" static let GET_USER_ME = "https://api.waterreporter.org/v2/data/me" static let POST_USER_REGISTER = "https://api.waterreporter.org/v2/user/register" static let GET_USER_PROFILE = "https://api.waterreporter.org/v2/data/user/" static let GET_USER_SNAPSHOT = "https://api.waterreporter.org/v2/data/snapshot/user/" static let POST_USER_PROFILE = "https://api.waterreporter.org/v2/data/user/" static let POST_PASSWORD_RESET = "https://api.waterreporter.org/v2/reset" static let POST_IMAGE = "https://api.waterreporter.org/v2/media/image" static let GET_MANY_ORGANIZATIONS = "https://api.waterreporter.org/v2/data/organization" static let GET_MANY_REPORT_COMMENTS = "https://api.waterreporter.org/v2/data/comment" static let POST_COMMENT = "https://api.waterreporter.org/v2/data/comment" static let GET_MANY_HASHTAGS = "https://api.waterreporter.org/v2/data/hashtag" static let GET_MANY_TERRITORY = "https://api.waterreporter.org/v2/data/territory" static let GET_MANY_HUC8WATERSHEDS = "https://api.waterreporter.org/v2/data/huc-8" static let TRENDING_GROUP = "https://api.waterreporter.org/v2/data/trending/group" static let TRENDING_HASHTAG = "https://api.waterreporter.org/v2/data/trending/hashtag" static let TRENDING_PEOPLE = "https://api.waterreporter.org/v2/data/trending/people" static let TRENDING_TERRITORY = "https://api.waterreporter.org/v2/data/trending/territory" static let TERRITORY = "https://huc.waterreporter.org/8/" // // // var apiUrl: String! = "https://api.waterreporter.org/v2/data" func getManyReportComments(reportId: AnyObject) -> String { let _endpoint = apiUrl, _reportId = String(reportId) return _endpoint + "/report/" + _reportId + "/comments" } }
32a88113581c2c89616effe93fda7fa3
41
94
0.69308
false
false
false
false
rbaladron/SwiftProgramaParaiOS
refs/heads/master
Ejercicios/precedenciaDeOperadores.playground/Contents.swift
mit
1
//: Playground - noun: a place where people can play import UIKit var numeroDeVidas = 5 numeroDeVidas++ numeroDeVidas numeroDeVidas += 1 ++numeroDeVidas --numeroDeVidas -numeroDeVidas var esDeDia = true !esDeDia let numero : Int = 874 % 10 300 - 201 * 9 % 6 / 8 201 * 9 1809 % 6 var infinito = !true var contador = 9 contador = contador++ var puntos = 15 - 7 ++puntos var inicial = 200 var final = -(--inicial) print( final ) let pesos = 10 let dolares = 17.15 let conversion :Double = Double(pesos) * dolares let a = 5 var f = 2 let z = 3 print(" Resultado : \( a % ++f * z)")
8dc40630a203540695e8dd2fb2442fd2
11.913043
52
0.662732
false
false
false
false
tadasz/MistikA
refs/heads/master
MistikA/Classes/FindPalepeViewController.swift
mit
1
// // FindPalepeViewController.swift // MistikA // // Created by Tadas Ziemys on 11/07/14. // Copyright (c) 2014 Tadas Ziemys. All rights reserved. // import UIKit import MapKit class FindPalepeViewController: UIViewController, CLLocationManagerDelegate { @IBOutlet weak var pictureView: UIImageView? @IBOutlet weak var accuracyLabel: UILabel? var locationManager = CLLocationManager() var region = CLBeaconRegion(proximityUUID: NSUUID(UUIDString: "78E408FD-48DA-4325-9123-0AEA40925EFF")!, identifier: "com.identifier") required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. locationManager.delegate = self } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) locationManager.startRangingBeaconsInRegion(region) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // #pragma 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. } */ func locationManager(manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], inRegion region: CLBeaconRegion) { if !beacons.isEmpty { var beacon = beacons[0] as! CLBeacon let accuracy: Double = beacon.accuracy pictureView!.alpha = CGFloat(1.0 / accuracy) accuracyLabel!.text = "\(beacon.accuracy)" if beacon.proximity == CLProximity.Immediate { locationManager.stopMonitoringForRegion(region) UIAlertView(title: "Rrrrr...", message: "kaip tu mane radai? rrr....", delegate: self, cancelButtonTitle: "rrrr") } } } }
872531835cab007a4aabdb2ce300e872
30.208333
137
0.646195
false
false
false
false
apple/swift-format
refs/heads/main
Tests/SwiftFormatPrettyPrintTests/BinaryOperatorExprTests.swift
apache-2.0
1
final class BinaryOperatorExprTests: PrettyPrintTestCase { func testNonRangeFormationOperatorsAreSurroundedByBreaks() { let input = """ x=1+8-9 ^*^ 5*4/10 """ let expected80 = """ x = 1 + 8 - 9 ^*^ 5 * 4 / 10 """ assertPrettyPrintEqual(input: input, expected: expected80, linelength: 80) let expected10 = """ x = 1 + 8 - 9 ^*^ 5 * 4 / 10 """ assertPrettyPrintEqual(input: input, expected: expected10, linelength: 10) } func testRangeFormationOperatorsAreCompactedWhenPossible() { let input = """ x = 1...100 x = 1..<100 x = (1++)...(-100) x = 1 ... 100 x = 1 ..< 100 x = (1++) ... (-100) """ let expected = """ x = 1...100 x = 1..<100 x = (1++)...(-100) x = 1...100 x = 1..<100 x = (1++)...(-100) """ assertPrettyPrintEqual(input: input, expected: expected, linelength: 80) } func testRangeFormationOperatorsAreNotCompactedWhenFollowingAPostfixOperator() { let input = """ x = 1++ ... 100 x = 1-- ..< 100 x = 1++ ... 100 x = 1-- ..< 100 """ let expected80 = """ x = 1++ ... 100 x = 1-- ..< 100 x = 1++ ... 100 x = 1-- ..< 100 """ assertPrettyPrintEqual(input: input, expected: expected80, linelength: 80) let expected10 = """ x = 1++ ... 100 x = 1-- ..< 100 x = 1++ ... 100 x = 1-- ..< 100 """ assertPrettyPrintEqual(input: input, expected: expected10, linelength: 10) } func testRangeFormationOperatorsAreNotCompactedWhenPrecedingAPrefixOperator() { let input = """ x = 1 ... -100 x = 1 ..< -100 x = 1 ... √100 x = 1 ..< √100 """ let expected80 = """ x = 1 ... -100 x = 1 ..< -100 x = 1 ... √100 x = 1 ..< √100 """ assertPrettyPrintEqual(input: input, expected: expected80, linelength: 80) let expected10 = """ x = 1 ... -100 x = 1 ..< -100 x = 1 ... √100 x = 1 ..< √100 """ assertPrettyPrintEqual(input: input, expected: expected10, linelength: 10) } func testRangeFormationOperatorsAreNotCompactedWhenUnaryOperatorsAreOnEachSide() { let input = """ x = 1++ ... -100 x = 1-- ..< -100 x = 1++ ... √100 x = 1-- ..< √100 """ let expected80 = """ x = 1++ ... -100 x = 1-- ..< -100 x = 1++ ... √100 x = 1-- ..< √100 """ assertPrettyPrintEqual(input: input, expected: expected80, linelength: 80) let expected10 = """ x = 1++ ... -100 x = 1-- ..< -100 x = 1++ ... √100 x = 1-- ..< √100 """ assertPrettyPrintEqual(input: input, expected: expected10, linelength: 10) } func testRangeFormationOperatorsAreNotCompactedWhenPrecedingPrefixDot() { let input = """ x = .first ... .last x = .first ..< .last x = .first ... .last x = .first ..< .last """ let expected80 = """ x = .first ... .last x = .first ..< .last x = .first ... .last x = .first ..< .last """ assertPrettyPrintEqual(input: input, expected: expected80, linelength: 80) let expected10 = """ x = .first ... .last x = .first ..< .last x = .first ... .last x = .first ..< .last """ assertPrettyPrintEqual(input: input, expected: expected10, linelength: 10) } }
f645b956dc651a433738cb7ca580b377
17.300469
84
0.43843
false
false
false
false
squall09s/VegOresto
refs/heads/master
VegoResto/Ressources/Lib/FBAnnotation/FBQuadTreeNode.swift
gpl-3.0
1
// // FBQuadTreeNode.swift // FBAnnotationClusteringSwift // // Created by Robert Chen on 4/2/15. // Copyright (c) 2015 Robert Chen. All rights reserved. // import Foundation import MapKit public class FBQuadTreeNode: NSObject { var boundingBox: FBBoundingBox? var northEast: FBQuadTreeNode? var northWest: FBQuadTreeNode? var southEast: FBQuadTreeNode? var southWest: FBQuadTreeNode? var count = 0 var annotations: [MKAnnotation] = [] // MARK: - Initializers override init() { super.init() } init(boundingBox box: FBBoundingBox) { super.init() boundingBox = box } // MARK: - Instance functions func isLeaf() -> Bool { return (northEast == nil) ? true : false } func subdivide() { northEast = FBQuadTreeNode() northWest = FBQuadTreeNode() southEast = FBQuadTreeNode() southWest = FBQuadTreeNode() let box = boundingBox! let xMid: CGFloat = (box.xf + box.x0) / 2.0 let yMid: CGFloat = (box.yf + box.y0) / 2.0 northEast!.boundingBox = FBQuadTreeNode.FBBoundingBoxMake(x0: xMid, y0:box.y0, xf:box.xf, yf:yMid) northWest!.boundingBox = FBQuadTreeNode.FBBoundingBoxMake(x0: box.x0, y0:box.y0, xf:xMid, yf:yMid) southEast!.boundingBox = FBQuadTreeNode.FBBoundingBoxMake(x0: xMid, y0:yMid, xf:box.xf, yf:box.yf) southWest!.boundingBox = FBQuadTreeNode.FBBoundingBoxMake(x0: box.x0, y0:yMid, xf:xMid, yf:box.yf) } // MARK: - Class functions class func FBBoundingBoxMake(x0: CGFloat, y0: CGFloat, xf: CGFloat, yf: CGFloat) -> FBBoundingBox { let box = FBBoundingBox(x0: x0, y0: y0, xf: xf, yf: yf) return box } class func FBBoundingBoxContainsCoordinate(box: FBBoundingBox, coordinate: CLLocationCoordinate2D) -> Bool { let containsX: Bool = (box.x0 <= CGFloat(coordinate.latitude)) && (CGFloat(coordinate.latitude) <= box.xf) let containsY: Bool = (box.y0 <= CGFloat(coordinate.longitude)) && (CGFloat(coordinate.longitude) <= box.yf) return (containsX && containsY) } class func FBBoundingBoxForMapRect(mapRect: MKMapRect) -> FBBoundingBox { let topLeft: CLLocationCoordinate2D = MKCoordinateForMapPoint(mapRect.origin) let botRight: CLLocationCoordinate2D = MKCoordinateForMapPoint(MKMapPointMake(MKMapRectGetMaxX(mapRect), MKMapRectGetMaxY(mapRect))) let minLat: CLLocationDegrees = botRight.latitude let maxLat: CLLocationDegrees = topLeft.latitude let minLon: CLLocationDegrees = topLeft.longitude let maxLon: CLLocationDegrees = botRight.longitude return FBQuadTreeNode.FBBoundingBoxMake(x0: CGFloat(minLat), y0: CGFloat(minLon), xf: CGFloat(maxLat), yf: CGFloat(maxLon)) } class func FBBoundingBoxIntersectsBoundingBox(box1: FBBoundingBox, box2: FBBoundingBox) -> Bool { return (box1.x0 <= box2.xf && box1.xf >= box2.x0 && box1.y0 <= box2.yf && box1.yf >= box2.y0) } class func FBMapRectForBoundingBox(boundingBox: FBBoundingBox) -> MKMapRect { let topLeft: MKMapPoint = MKMapPointForCoordinate(CLLocationCoordinate2DMake(CLLocationDegrees(boundingBox.x0), CLLocationDegrees(boundingBox.y0))) let botRight: MKMapPoint = MKMapPointForCoordinate(CLLocationCoordinate2DMake(CLLocationDegrees(boundingBox.xf), CLLocationDegrees(boundingBox.yf))) return MKMapRectMake(topLeft.x, botRight.y, fabs(botRight.x - topLeft.x), fabs(botRight.y - topLeft.y)) } }
22f73a48e1ca9fea82d54018410cc6e5
35.153061
157
0.685295
false
false
false
false
elpassion/el-space-ios
refs/heads/master
ELSpace/Commons/Extensions/UIColor/UIColor_Hex.swift
gpl-3.0
1
import UIKit extension UIColor { convenience init?(hexRed red: Int, green: Int, blue: Int, alpha: Int = 255) { guard red >= 0 && red <= 255 else { return nil } guard green >= 0 && green <= 255 else { return nil } guard blue >= 0 && blue <= 255 else { return nil } self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: CGFloat(alpha) / 255.0) } convenience init?(hexString: String) { let hex = hexString.trimmingCharacters(in: CharacterSet.alphanumerics.inverted) var int = UInt32() Scanner(string: hex).scanHexInt32(&int) let red, green, blue, alpha: UInt32 switch hex.count { case 3: // RGB (12-bit) (alpha, red, green, blue) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17) case 6: // RGB (24-bit) (alpha, red, green, blue) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF) case 8: // ARGB (32-bit) (alpha, red, green, blue) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF) default: return nil } self.init(hexRed: Int(red), green: Int(green), blue: Int(blue), alpha: Int(alpha)) } }
2ac43799296228d793da1cd8c8ddc438
37.382353
103
0.520307
false
false
false
false
luizlopezm/ios-Luis-Trucking
refs/heads/master
Pods/Eureka/Source/Rows/Common/GenericMultipleSelectorRow.swift
mit
1
// // GenericMultipleSelectorRow.swift // Eureka // // Created by Martin Barreto on 2/24/16. // Copyright © 2016 Xmartlabs. All rights reserved. // import Foundation /// Generic options selector row that allows multiple selection. public class GenericMultipleSelectorRow<T: Hashable, Cell: CellType, VCType: TypedRowControllerType where Cell: BaseCell, Cell: TypedCellType, Cell.Value == Set<T>, VCType: UIViewController, VCType.RowValue == Set<T>>: Row<Set<T>, Cell>, PresenterRowType { /// Defines how the view controller will be presented, pushed, etc. public var presentationMode: PresentationMode<VCType>? /// Will be called before the presentation occurs. public var onPresentCallback : ((FormViewController, VCType)->())? /// Title to be displayed for the options public var selectorTitle: String? /// Options from which the user will choose public var options: [T] { get { return self.dataProvider?.arrayData?.map({ $0.first! }) ?? [] } set { self.dataProvider = DataProvider(arrayData: newValue.map({ Set<T>(arrayLiteral: $0) })) } } required public init(tag: String?) { super.init(tag: tag) displayValueFor = { if let t = $0 { return t.map({ String($0) }).joinWithSeparator(", ") } return nil } presentationMode = .Show(controllerProvider: ControllerProvider.Callback { return VCType() }, completionCallback: { vc in vc.navigationController?.popViewControllerAnimated(true) }) } /** Extends `didSelect` method */ public override func customDidSelect() { super.customDidSelect() if !isDisabled { if let presentationMode = presentationMode { if let controller = presentationMode.createController(){ controller.row = self if let title = selectorTitle { controller.title = title } onPresentCallback?(cell.formViewController()!, controller) presentationMode.presentViewController(controller, row: self, presentingViewController: self.cell.formViewController()!) } else{ presentationMode.presentViewController(nil, row: self, presentingViewController: self.cell.formViewController()!) } } } } /** Prepares the pushed row setting its title and completion callback. */ public override func prepareForSegue(segue: UIStoryboardSegue) { super.prepareForSegue(segue) guard let rowVC = segue.destinationViewController as? VCType else { return } if let title = selectorTitle { rowVC.title = title } if let callback = self.presentationMode?.completionHandler{ rowVC.completionCallback = callback } onPresentCallback?(cell.formViewController()!, rowVC) rowVC.row = self } }
b89c4bd2e64c7d438da1a14abef49969
36.024096
256
0.61601
false
false
false
false
superk589/CGSSGuide
refs/heads/master
DereGuide/LiveSimulator/LFDistribution.swift
mit
2
// // LFDistribution.swift // DereGuide // // Created by zzk on 2017/3/31. // Copyright © 2017 zzk. All rights reserved. // import Foundation /// only used in live formulator struct LFDistribution { var samples: [LFSamplePoint<LSScoreBonusGroup>] var average: Double { if samples.count == 0 { return Double(LSScoreBonusGroup.basic.bonusValue) } else { return samples.reduce(0.0) { $0 + Double($1.value.bonusValue) * $1.probability } } } var maxValue: Int { let max = samples.max { $0.value.bonusValue < $1.value.bonusValue } if let max = max { return max.value.bonusValue } else { return LSScoreBonusGroup.basic.bonusValue } } var minValue: Int { let min = samples.filter { $0.probability > 0 }.min { $0.value.bonusValue < $1.value.bonusValue } if let min = min { return min.value.bonusValue } else { return LSScoreBonusGroup.basic.bonusValue } } }
6c1ac6705c31a3318820ff1ce31d93c4
23.511111
92
0.556664
false
false
false
false
jcfausto/transit-app
refs/heads/master
TransitApp/TransitApp/RouteSegmentButton.swift
mit
1
// // RouteSegmentButtom.swift // TransitApp // // Created by Julio Cesar Fausto on 27/02/16. // Copyright © 2016 Julio Cesar Fausto. All rights reserved. // import Foundation import UIKit import SVGKit /** This is an UIButton capable of retrieve an SVG from some URL, convert it to an image and assign it as its own image for the normal state. It is dependable on the SVGKit framework */ @IBDesignable class RouteSegmentButton: UIButton { // MARK: Properties /** The shape's icon url. If presente, this icon will be drawed into the button */ @IBInspectable var svgIconUrl: NSURL? /** The shape's color */ @IBInspectable var fillColor: UIColor? /** This button is designed primarily to be placed inside a view that will contain a collection of this buttons. This property can store a index refecence indicating in wich index it resides inside a collection */ @IBInspectable var index: Int = 0 /** The SVG cache manager */ let cache = SVGIconCache() func retrieveSvgFromCache(stringUrl: NSURL) -> NSData? { if let fileName = stringUrl.lastPathComponent { return cache.retrieveSVG(fileName) } else { return nil } } // MARK: Custom Draw override func drawRect(rect: CGRect) { if let svgIconUrl = self.svgIconUrl { //This must be done in background because of the relationship with the SVGCache that sometimes //will perform a file read from the disk and if this occurs in the main thread the UI will block //until the file finishes loading dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) { let svgData = self.retrieveSvgFromCache(svgIconUrl) if let svgData = svgData { self.drawSvg(svgData, rect: rect) } else { self.loadAndDrawSvgForTheFirstTime(svgIconUrl, rect: rect) } } } } // MARK: SVG Drawing func loadAndDrawSvgForTheFirstTime(svgIconUrl: NSURL, rect: CGRect) { if let svgIconUrl: NSURL = svgIconUrl { let request = NSURLRequest(URL: svgIconUrl) //This is asynchronous. When the download completes, the sgv image will be converted and drawed into the button let getSvgResourceTask = NSURLSession.sharedSession().dataTaskWithRequest(request){ data, response, error in if let svgData = data as NSData? { if let fileName = svgIconUrl.lastPathComponent { self.cache.saveSVG(svgData, fileName: fileName) } self.drawSvg(svgData, rect: rect) } } getSvgResourceTask.resume() } } func drawSvg(svgData: NSData, rect: CGRect) { let svgSource = SVGKSource(inputSteam: NSInputStream(data: svgData)) let svgParsed = SVGKParser.parseSourceUsingDefaultSVGKParser(svgSource) let svgImage = SVGKImage(parsedSVG: svgParsed, fromSource: svgSource) //Fill the SVG sublayers with the segment color let svgImageView = SVGKLayeredImageView(SVGKImage: svgImage) let layer = svgImageView.layer self.changeFillColorRecursively(layer.sublayers!, color: self.fillColor!) if let image = svgImage.UIImage { //Creates a context with the same size of the button's frame UIGraphicsBeginImageContextWithOptions(CGSize(width: rect.size.width, height: rect.size.height), false, 0) //Get the contexts that we just created let context = UIGraphicsGetCurrentContext() //Setting the paths and configs. CGContextSetFillColorWithColor(context, UIColor.whiteColor().CGColor) CGContextSetStrokeColorWithColor(context, UIColor.blackColor().CGColor) //Draw the image in the button's rect image.drawInRect(rect) //Tell the context to draw CGContextDrawPath(context, .FillStroke) //Get the image drawed into the context let img = UIGraphicsGetImageFromCurrentImageContext() //Ends the context UIGraphicsEndImageContext() //Sets the image into the buttom asynchronously dispatch_async(dispatch_get_main_queue(), { self.setImage(img, forState: .Normal) }); } } // MARK: SVG color fill //It was necessary to use this workarround to fill the layers with the segment color //https://github.com/SVGKit/SVGKit/issues/98 func changeFillColorRecursively(sublayers: [CALayer], color: UIColor) { for layer in sublayers { if let l = layer as? CAShapeLayer { l.fillColor = color.CGColor } if let l: CALayer = layer, sub = l.sublayers { changeFillColorRecursively(sub, color: color) } } } }
0d40f71819d31041ad44ccbbef12465b
32.170732
123
0.584007
false
false
false
false
SwiftAndroid/swift
refs/heads/master
test/1_stdlib/VarArgs.swift
apache-2.0
5
// RUN: %target-run-stdlib-swift -parse-stdlib %s | FileCheck %s // REQUIRES: executable_test import Swift #if _runtime(_ObjC) import Darwin import CoreGraphics #else import Glibc typealias CGFloat = Double #endif func my_printf(_ format: String, _ arguments: CVarArg...) { withVaList(arguments) { vprintf(format, $0) } } func test_varArgs0() { // CHECK: The answer to life and everything is 42, 42, -42, 3.14 my_printf( "The answer to life and everything is %ld, %u, %d, %f\n", 42, UInt32(42), Int16(-42), 3.14159279) } test_varArgs0() func test_varArgs1() { var args = [CVarArg]() var format = "dig it: " for i in 0..<12 { args.append(Int16(-i)) args.append(Float(i)) format += "%d %2g " } // CHECK: dig it: 0 0 -1 1 -2 2 -3 3 -4 4 -5 5 -6 6 -7 7 -8 8 -9 9 -10 10 -11 11 withVaList(args) { vprintf(format + "\n", $0) } } test_varArgs1() func test_varArgs3() { var args = [CVarArg]() let format = "pointers: '%p' '%p' '%p' '%p' '%p'\n" args.append(OpaquePointer(bitPattern: 0x1234_5670)!) args.append(OpaquePointer(bitPattern: 0x1234_5671)!) args.append(UnsafePointer<Int>(bitPattern: 0x1234_5672)!) args.append(UnsafeMutablePointer<Float>(bitPattern: 0x1234_5673)!) #if _runtime(_ObjC) args.append(AutoreleasingUnsafeMutablePointer<AnyObject>( UnsafeMutablePointer<AnyObject>(bitPattern: 0x1234_5674)!)) #else //Linux does not support AutoreleasingUnsafeMutablePointer; put placeholder. args.append(UnsafeMutablePointer<Float>(bitPattern: 0x1234_5674)!) #endif // CHECK: {{pointers: '(0x)?0*12345670' '(0x)?0*12345671' '(0x)?0*12345672' '(0x)?0*12345673' '(0x)?0*12345674'}} withVaList(args) { vprintf(format, $0) } } test_varArgs3() func test_varArgs4() { // Verify alignment of va_list contents. // On some architectures some types are better- // aligned than Int and must be packaged with care. let i8 = Int8(1) let i16 = Int16(2) let i32 = Int32(3) let i64 = 4444444444444444 as Int64 let u8 = UInt8(10) let u16 = UInt16(20) let u32 = UInt32(30) let u64 = 4040404040404040 as UInt64 let f32 = Float(1.1) let f64 = Double(2.2) let fCG = CGFloat(3.3) my_printf("a %g %d %g %d %g %d a\n", f32, i8, f64, i8, fCG, i8) my_printf("b %d %g %d %g %d %g %d b\n", i8, f32, i8, f64, i8, fCG, i8) my_printf("c %d %d %d %d %d %lld %d c\n", i8, i16, i8, i32, i8, i64, i8) my_printf("d %d %d %d %d %d %d %lld %d d\n",i8, i8, i16, i8, i32, i8, i64, i8) my_printf("e %u %u %u %u %u %llu %u e\n", u8, u16, u8, u32, u8, u64, u8) my_printf("f %u %u %u %u %u %u %llu %u f\n",u8, u8, u16, u8, u32, u8, u64, u8) // CHECK: a 1.1 1 2.2 1 3.3 1 a // CHECK: b 1 1.1 1 2.2 1 3.3 1 b // CHECK: c 1 2 1 3 1 4444444444444444 1 c // CHECK: d 1 1 2 1 3 1 4444444444444444 1 d // CHECK: e 10 20 10 30 10 4040404040404040 10 e // CHECK: f 10 10 20 10 30 10 4040404040404040 10 f } test_varArgs4() // CHECK: done. print("done.")
d2d7eea18082c722718b95801012e836
27.788462
115
0.619906
false
true
false
false
meetkei/KeiSwiftFramework
refs/heads/master
KeiSwiftFramework/Date/NSDate+Format.swift
mit
1
// // NSDate+Format.swift // // Copyright (c) 2016 Keun young Kim <[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 Foundation private let privateFormatter = DateFormatter() public extension NSDate { public func toString(_ format: String = "yyyyMMdd") -> String { privateFormatter.dateFormat = format return privateFormatter.string(from: self as Date) } public func toLocalizedString(_ format: String, locale: Locale = Locale.current, timeZone: TimeZone = TimeZone.current) -> String { let currentLocale = privateFormatter.locale let currentTimeZone = privateFormatter.timeZone privateFormatter.locale = locale privateFormatter.timeZone = timeZone privateFormatter.dateFormat = format let result = privateFormatter.string(from: self as Date) privateFormatter.locale = currentLocale privateFormatter.timeZone = currentTimeZone return result } public func toStyledString(_ style: DateFormatter.Style) -> String { privateFormatter.dateStyle = style return privateFormatter.string(from: self as Date) } public func toStyledString(dateStyle dStyle: DateFormatter.Style, timeStyle tStyle: DateFormatter.Style) -> String { privateFormatter.dateStyle = dStyle privateFormatter.timeStyle = tStyle return privateFormatter.string(from: self as Date) } }
09de039ab14c4464bfddb553be3dec7c
37.606061
135
0.708399
false
false
false
false
CharlesVu/Smart-iPad
refs/heads/master
MKHome/Settings/CityChooserViewController.swift
mit
1
// // CityChooserTableViewController.swift // MKHome // // Created by Charles Vu on 24/12/2016. // Copyright © 2016 charles. All rights reserved. // import Foundation import UIKit import MapKit import Persistance class CityChooserViewController: UIViewController { @IBOutlet var searchBar: UISearchBar? @IBOutlet var tableView: UITableView? @IBOutlet var spinner: UIActivityIndicatorView? fileprivate let appSettings = NationalRail.AppData.sharedInstance fileprivate var searchResults: [CLPlacemark] = [] fileprivate let geocoder = CLGeocoder() func lookup(name: String, completion: @escaping (Error?, [CLPlacemark]?) -> Void) { geocoder.cancelGeocode() spinner?.startAnimating() geocoder.geocodeAddressString(name) { (placemarks, error) in self.spinner?.stopAnimating() if error != nil { completion(error, nil) } else { completion(nil, placemarks) } } } } extension CityChooserViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let placemark = searchResults[indexPath.row] if let name = placemark.name, let coordinate = placemark.location?.coordinate { UserSettings.sharedInstance.weather.addCity(WeatherCity(name: name, longitude: coordinate.longitude, latitude: coordinate.latitude)) } _ = self.navigationController?.popViewController(animated: true) } } extension CityChooserViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return searchResults.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let placemark = searchResults[indexPath.row] let cell = tableView.dequeueReusableCell(withIdentifier: "CityCell")! cell.textLabel?.text = placemark.name! + ", " + placemark.country! if UIDevice.current.userInterfaceIdiom == .pad { cell.preservesSuperviewLayoutMargins = false cell.layoutMargins = .zero cell.separatorInset = .zero } return cell } } extension CityChooserViewController: UISearchBarDelegate { func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { if searchText != "" { lookup(name: searchText, completion: { (_, placemarks) in if let placemarks = placemarks { self.searchResults = placemarks } else { self.searchResults.removeAll() } self.tableView?.reloadData() }) } else { searchResults = [] self.tableView?.reloadData() } } }
514c03fb26aa6022ce5f3d9d6764f6d7
31.847826
100
0.615156
false
false
false
false
jduquennoy/Log4swift
refs/heads/master
Log4swiftTests/RotationPolicy/DateRotationPolicyTest.swift
apache-2.0
1
// // DateRotationPolicyTest.swift // log4swiftTests // // Created by Jérôme Duquennoy on 24/08/2018. // Copyright © 2018 jerome. All rights reserved. // import Foundation import XCTest @testable import Log4swift class DateRotationPolicyTest: XCTestCase { func testRotationIsRequestedWhenAgeExceedsLimit() throws { let filePath = try self.createTemporaryFilePath(fileExtension: "log") let policy = DateRotationPolicy(maxFileAge: 10) let fileCreationInterval = -1 * (policy.maxFileAge + 1) FileManager.default.createFile(atPath: filePath, contents: nil, attributes: [FileAttributeKey.creationDate: Date(timeIntervalSinceNow: fileCreationInterval)]) policy.appenderDidOpenFile(atPath: filePath) // Execute & validate XCTAssertTrue(policy.shouldRotate()) } func testRotationIsNotRequestedWhenFileAgeDoesNotExceedLimit() throws { let filePath = try self.createTemporaryFilePath(fileExtension: "log") let policy = DateRotationPolicy(maxFileAge: 10) let fileCreationInterval = -1 * (policy.maxFileAge - 1) FileManager.default.createFile(atPath: filePath, contents: nil, attributes: [FileAttributeKey.creationDate: Date(timeIntervalSinceNow: fileCreationInterval)]) policy.appenderDidOpenFile(atPath: filePath) // Execute & validate XCTAssertFalse(policy.shouldRotate()) } func testRotationIsNotRequestedIfNoFileWasOpened() { let policy = DateRotationPolicy(maxFileAge: 10) // Execute & validate XCTAssertFalse(policy.shouldRotate()) } func testRotationIsNotRequestedIfNonExistingFileWasOpened() { let policy = DateRotationPolicy(maxFileAge: 10) // Execute & validate policy.appenderDidOpenFile(atPath: "/File/that/does/not/exist.log") XCTAssertFalse(policy.shouldRotate()) } func testFileDateDefaultsToNowIfFileDoesNotExist() { let policy = DateRotationPolicy(maxFileAge: 1) // Execute & validate policy.appenderDidOpenFile(atPath: "/File/that/does/not/exist.log") XCTAssertFalse(policy.shouldRotate()) Thread.sleep(forTimeInterval: 1.5) XCTAssertTrue(policy.shouldRotate()) } }
e4b36d5bbc2c800f1ddd17571da2c32f
33.709677
162
0.745818
false
true
false
false
testpress/ios-app
refs/heads/master
ios-app/Model/ExamQuestion.swift
mit
1
// // ExamQuestion.swift // ios-app // // Created by Karthik on 12/05/20. // Copyright © 2020 Testpress. All rights reserved. // import ObjectMapper class ExamQuestion: DBModel { @objc dynamic var id = 0 @objc dynamic var marks = "" @objc dynamic var negativeMarks = "" @objc dynamic var order = -1 @objc dynamic var examId = 8989 @objc dynamic var question: AttemptQuestion? = nil @objc dynamic var questionId: Int = -1 override func mapping(map: Map) { id <- map["id"] marks <- map["marks"] negativeMarks <- map["negative_marks"] order <- map["order"] examId <- map["exam_id"] questionId <- map["question_id"] } override class func primaryKey() -> String? { return "id" } }
4bcaf41970fc68495837d817998cc4be
23.75
54
0.592172
false
false
false
false
saeta/penguin
refs/heads/main
Sources/PenguinPipeline/Pipeline/PipelineWorkerThread.swift
apache-2.0
1
// Copyright 2020 Penguin Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation class PipelineWorkerThread: Thread { static var startedThreadCount: Int32 = 0 static var runningThreadCount: Int32 = 0 static var lock = NSLock() public init(name: String) { super.init() self.name = name } /// This function must be overridden! func body() { preconditionFailure("No body in thread \(name!).") } override final func main() { PipelineWorkerThread.lock.lock() PipelineWorkerThread.startedThreadCount += 1 PipelineWorkerThread.runningThreadCount += 1 PipelineWorkerThread.lock.unlock() condition.lock() state = .started condition.broadcast() condition.unlock() // Do the work body() PipelineWorkerThread.lock.lock() PipelineWorkerThread.runningThreadCount -= 1 PipelineWorkerThread.lock.unlock() assert(isFinished == false, "isFinished is not false??? \(self)") condition.lock() defer { condition.unlock() } state = .finished condition.broadcast() // Wake up everyone who has tried to join against this thread. } /// Blocks until the worker thread has guaranteed to have started. func waitUntilStarted() { condition.lock() defer { condition.unlock() } while state == .initialized { condition.wait() } } /// Blocks until the body has finished executing. func join() { condition.lock() defer { condition.unlock() } while state != .finished { condition.wait() } } enum State { case initialized case started case finished } private var state: State = .initialized private var condition = NSCondition() } extension PipelineIterator { /// Determines if all worker threads started by Pipeline iterators process-wide have been stopped. /// /// This is used during testing to ensure there are no resource leaks. public static func _allThreadsStopped() -> Bool { // print("Running thread count: \(PipelineWorkerThread.runningThreadCount); started: \(PipelineWorkerThread.startedThreadCount).") PipelineWorkerThread.lock.lock() defer { PipelineWorkerThread.lock.unlock() } return PipelineWorkerThread.runningThreadCount == 0 } }
0ae55d08e9f071280b2eb9c9b56a2fc3
28.37234
134
0.70192
false
false
false
false
google/android-auto-companion-ios
refs/heads/main
Tests/AndroidAutoConnectedDeviceTransportTests/TransportSessionTest.swift
apache-2.0
1
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import AndroidAutoConnectedDeviceTransportFakes import AndroidAutoLogger import XCTest @testable import AndroidAutoConnectedDeviceTransport /// Unit tests for TransportSessionTest. class TransportSessionTest: XCTestCase { private var peripheralProvider: FakePeripheralProvider! private var delegate: FakeTransportSessionDelegate! private var session: TransportSession<FakePeripheralProvider>! override func setUp() { super.setUp() peripheralProvider = FakePeripheralProvider() delegate = FakeTransportSessionDelegate() session = TransportSession(provider: peripheralProvider, delegate: delegate) } override func tearDown() { session = nil delegate = nil peripheralProvider = nil super.tearDown() } func testDiscoversAssociatedPeripherals() { session.scanForPeripherals(mode: .reconnection) { _, _ in } let firstPeripheral = FakePeripheral() peripheralProvider.postPeripheral(firstPeripheral) XCTAssertEqual(session.peripherals.count, 1) let secondPeripheral = FakePeripheral() peripheralProvider.postPeripheral(secondPeripheral) XCTAssertEqual(session.peripherals.count, 2) XCTAssertTrue(session.peripherals.contains(firstPeripheral)) XCTAssertTrue(session.peripherals.contains(secondPeripheral)) XCTAssertEqual(session.discoveredPeripherals.count, 2) XCTAssertTrue(session.discoveredPeripherals.contains(firstPeripheral)) XCTAssertTrue(session.discoveredPeripherals.contains(secondPeripheral)) XCTAssertEqual(delegate.discoveredAssociatedPeripherals.count, 2) XCTAssertTrue( delegate.discoveredAssociatedPeripherals.contains(where: { $0 === firstPeripheral })) XCTAssertTrue( delegate.discoveredAssociatedPeripherals.contains(where: { $0 === secondPeripheral })) XCTAssertEqual(delegate.discoveredUnassociatedPeripherals.count, 0) } func testDiscoversUnassociatedPeripherals() { session.scanForPeripherals(mode: .association) { _, _ in } let firstPeripheral = FakePeripheral() peripheralProvider.postPeripheral(firstPeripheral) XCTAssertEqual(session.peripherals.count, 1) let secondPeripheral = FakePeripheral() peripheralProvider.postPeripheral(secondPeripheral) XCTAssertEqual(session.peripherals.count, 2) XCTAssertTrue(session.peripherals.contains(firstPeripheral)) XCTAssertTrue(session.peripherals.contains(secondPeripheral)) XCTAssertEqual(session.discoveredPeripherals.count, 2) XCTAssertTrue(session.discoveredPeripherals.contains(firstPeripheral)) XCTAssertTrue(session.discoveredPeripherals.contains(secondPeripheral)) XCTAssertEqual(delegate.discoveredUnassociatedPeripherals.count, 2) XCTAssertTrue( delegate.discoveredUnassociatedPeripherals.contains(where: { $0 === firstPeripheral })) XCTAssertTrue( delegate.discoveredUnassociatedPeripherals.contains(where: { $0 === secondPeripheral })) XCTAssertEqual(delegate.discoveredAssociatedPeripherals.count, 0) } func testPropagatesStateChange() { session.scanForPeripherals(mode: .reconnection) { _, _ in } let peripheral = FakePeripheral() peripheralProvider.postPeripheral(peripheral) peripheral.status = .connecting XCTAssertEqual(delegate.connectingPeripherals.count, 1) } } private class FakeTransportSessionDelegate: TransportSessionDelegate { var discoveredAssociatedPeripherals: [AnyTransportPeripheral] = [] var discoveredUnassociatedPeripherals: [AnyTransportPeripheral] = [] var connectingPeripherals: [AnyTransportPeripheral] = [] func session( _: AnyTransportSession, didDiscover peripheral: AnyTransportPeripheral, mode: PeripheralScanMode ) { switch mode { case .association: discoveredUnassociatedPeripherals.append(peripheral) case .reconnection: discoveredAssociatedPeripherals.append(peripheral) } } func session( _: AnyTransportSession, peripheral: AnyTransportPeripheral, didChangeStateTo state: PeripheralStatus ) { if case .connecting = state { connectingPeripherals.append(peripheral) } } }
12a4144c9961e9a88678066fb744490c
33.904412
100
0.765747
false
true
false
false
tlax/GaussSquad
refs/heads/master
GaussSquad/Model/Keyboard/States/MKeyboardStateMultiply.swift
mit
1
import UIKit class MKeyboardStateMultiply:MKeyboardState { private let previousValue:Double private let kNeedsUpdate:Bool = true init(previousValue:Double, editing:String) { self.previousValue = previousValue super.init( editing:editing, needsUpdate:kNeedsUpdate) } override func commitState(model:MKeyboard, view:UITextView) { let currentValue:Double = model.lastNumber() let newValue:Double = previousValue * currentValue editing = model.numberAsString(scalar:newValue) view.text = model.kEmpty view.insertText(editing) let currentString:String = model.numberAsString( scalar:currentValue) commitingDescription = "× \(currentString) = \(editing)" } }
dc00afb4021d207527d626219ed77798
26.7
64
0.638989
false
false
false
false
thatseeyou/iOSSDKExamples
refs/heads/master
Pages/NSData from HTTP.xcplaygroundpage/Contents.swift
mit
1
/*: # HTTP 응답을 Data로 받아오기 */ import Foundation let url = NSURL(string: "https://api.whitehouse.gov/v1/petitions.json?limit=30") let data: NSData! = try? NSData(contentsOfURL: url!, options: []) //print(data) if let dataValue = data { var dataString = NSString(data: dataValue, encoding:NSUTF8StringEncoding) print(dataString) }
f1e5812382c5ffa067fe3f02d6d57a2d
16.35
80
0.694524
false
false
false
false
hathway/JSONRequest
refs/heads/master
JSONRequest/JSONRequestAuthChallengeHandler.swift
mit
1
// // JSONRequestAuthChallengeHandler.swift // JSONRequest // // Created by Yevhenii Hutorov on 04.11.2019. // Copyright © 2019 Hathway. All rights reserved. // import Foundation public struct JSONRequestAuthChallengeResult { public let disposition: URLSession.AuthChallengeDisposition public let credential: URLCredential? public init(disposition: URLSession.AuthChallengeDisposition, credential: URLCredential? = nil) { self.disposition = disposition self.credential = credential } } public protocol JSONRequestAuthChallengeHandler { func handle(_ session: URLSession, challenge: URLAuthenticationChallenge) -> JSONRequestAuthChallengeResult } class JSONRequestSessionDelegate: NSObject, URLSessionDelegate { var authChallengeHandler: JSONRequestAuthChallengeHandler? func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { let result = authChallengeHandler?.handle(session, challenge: challenge) let disposition = result?.disposition ?? .performDefaultHandling completionHandler(disposition, result?.credential) } }
a9fc3433689f5004014f056ca626f64f
37.34375
186
0.774246
false
false
false
false
eflyjason/astro-daily
refs/heads/master
Astro Daily - APP/Astro Daily/AboutViewController.swift
apache-2.0
1
// // AboutViewController.swift // Astro Daily // // Created by Arefly on 22/1/2015. // Copyright (c) 2015年 Arefly. All rights reserved. // import Foundation import UIKit import CoreData class AboutViewController: UIViewController { //设置视图 @IBOutlet var versionLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() var version = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as String var build = NSBundle.mainBundle().objectForInfoDictionaryKey(kCFBundleVersionKey as NSString) as String versionLabel.numberOfLines = 0; // Enable \n break line versionLabel.hidden = false; // Disable Hidden versionLabel.text = "V " + version + " (Build " + build + ")" } }
173dc3e0c24860296d7f21e164ecfe29
29.75
111
0.626744
false
false
false
false
kclowes/HackingWithSwift
refs/heads/master
Project7/Project7/DetailViewController.swift
mit
1
// // DetailViewController.swift // Project7 // // Created by Keri Clowes on 3/25/16. // Copyright © 2016 Keri Clowes. All rights reserved. // import UIKit import WebKit class DetailViewController: UIViewController { var webView: WKWebView! var detailItem: [String: String]! override func loadView() { webView = WKWebView() view = webView } override func viewDidLoad() { super.viewDidLoad() guard detailItem != nil else { return } if let body = detailItem["body"] { var html = "<html>" html += "<head>" html += "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">" html += "<style> body { font-size: 150%; } </style>" html += "</head>" html += "<body>" html += body html += "</body>" html += "</html>" webView.loadHTMLString(html, baseURL: nil) } } }
3b87b6180ffc15475d67bc7b98665b10
22.078947
88
0.596351
false
false
false
false
Ivacker/swift
refs/heads/master
test/1_stdlib/CGGeometry.swift
apache-2.0
12
// RUN: %target-run-simple-swift | FileCheck %s // REQUIRES: executable_test // REQUIRES: objc_interop import CoreGraphics func print_(r: CGPoint, _ prefix: String) { print("\(prefix) \(r.x) \(r.y)") } func print_(r: CGSize, _ prefix: String) { print("\(prefix) \(r.width) \(r.height)") } func print_(r: CGVector, _ prefix: String) { print("\(prefix) \(r.dx) \(r.dy)") } func print_(r: CGRect, _ prefix: String) { print("\(prefix) \(r.origin.x) \(r.origin.y) \(r.size.width) \(r.size.height)") } let int1: Int = 1 let int2: Int = 2 let int3: Int = 3 let int4: Int = 4 let cgfloat1: CGFloat = 1 let cgfloat2: CGFloat = 2 let cgfloat3: CGFloat = 3 let cgfloat4: CGFloat = 4 let double1: Double = 1 let double2: Double = 2 let double3: Double = 3 let double4: Double = 4 print("You may begin.") // CHECK: You may begin. var pt: CGPoint pt = CGPoint(x: 1.25, y: 2.25) print_(pt, "named float literals") pt = CGPoint(x: 1, y: 2) print_(pt, "named int literals") pt = CGPoint(x: cgfloat1, y: cgfloat2) print_(pt, "named cgfloats") pt = CGPoint(x: double1, y: double2) print_(pt, "named doubles") pt = CGPoint(x: int1, y: int2) print_(pt, "named ints") // CHECK-NEXT: named float literals 1.25 2.25 // CHECK-NEXT: named int literals 1.0 2.0 // CHECK-NEXT: named cgfloats 1.0 2.0 // CHECK-NEXT: named doubles 1.0 2.0 // CHECK-NEXT: named ints 1.0 2.0 assert(pt != CGPoint.zero) var size: CGSize size = CGSize(width:-1.25, height:-2.25) print_(size, "named float literals") size = CGSize(width:-1, height:-2) print_(size, "named int literals") size = CGSize(width:cgfloat1, height:cgfloat2) print_(size, "named cgfloats") size = CGSize(width:double1, height:double2) print_(size, "named doubles") size = CGSize(width: int1, height: int2) print_(size, "named ints") // CHECK-NEXT: named float literals -1.25 -2.25 // CHECK-NEXT: named int literals -1.0 -2.0 // CHECK-NEXT: named cgfloats 1.0 2.0 // CHECK-NEXT: named doubles 1.0 2.0 // CHECK-NEXT: named ints 1.0 2.0 assert(size != CGSize.zero) var vector: CGVector vector = CGVector(dx: -111.25, dy: -222.25) print_(vector, "named float literals") vector = CGVector(dx: -111, dy: -222) print_(vector, "named int literals") vector = CGVector(dx: cgfloat1, dy: cgfloat2) print_(vector, "named cgfloats") vector = CGVector(dx: double1, dy: double2) print_(vector, "named doubles") vector = CGVector(dx: int1, dy: int2) print_(vector, "named ints") // CHECK-NEXT: named float literals -111.25 -222.25 // CHECK-NEXT: named int literals -111.0 -222.0 // CHECK-NEXT: named cgfloats 1.0 2.0 // CHECK-NEXT: named doubles 1.0 2.0 // CHECK-NEXT: named ints 1.0 2.0 assert(vector != CGVector.zero) var rect: CGRect pt = CGPoint(x: 10.25, y: 20.25) size = CGSize(width: 30.25, height: 40.25) rect = CGRect(origin: pt, size: size) print_(rect, "point+size") rect = CGRect(origin:pt, size:size) print_(rect, "named point+size") // CHECK-NEXT: point+size 10.25 20.25 30.25 40.25 // CHECK-NEXT: named point+size 10.25 20.25 30.25 40.25 rect = CGRect(x:10.25, y:20.25, width:30.25, height:40.25) print_(rect, "named float literals") rect = CGRect(x:10, y:20, width:30, height:40) print_(rect, "named int literals") rect = CGRect(x:cgfloat1, y:cgfloat2, width:cgfloat3, height:cgfloat4) print_(rect, "named cgfloats") rect = CGRect(x:double1, y:double2, width:double3, height:double4) print_(rect, "named doubles") rect = CGRect(x:int1, y:int2, width:int3, height:int4) print_(rect, "named ints") // CHECK-NEXT: named float literals 10.25 20.25 30.25 40.25 // CHECK-NEXT: named int literals 10.0 20.0 30.0 40.0 // CHECK-NEXT: named cgfloats 1.0 2.0 3.0 4.0 // CHECK-NEXT: named doubles 1.0 2.0 3.0 4.0 // CHECK-NEXT: named ints 1.0 2.0 3.0 4.0 assert(rect == rect) assert(rect != CGRect.zero) assert(!rect.isNull) assert(!rect.isEmpty) assert(!rect.isInfinite) assert(CGRect.null.isNull) assert(CGRect.zero.isEmpty) assert(CGRect.infinite.isInfinite) var unstandard = CGRect(x: 10, y: 20, width: -30, height: -50) var standard = unstandard.standardized print_(unstandard, "unstandard") print_(standard, "standard") // CHECK-NEXT: unstandard 10.0 20.0 -30.0 -50.0 // CHECK-NEXT: standard -20.0 -30.0 30.0 50.0 assert(unstandard.width == 30) assert(unstandard.size.width == -30) assert(standard.width == 30) assert(standard.size.width == 30) assert(unstandard.height == 50) assert(unstandard.size.height == -50) assert(standard.height == 50) assert(standard.size.height == 50) assert(unstandard.minX == -20) assert(unstandard.midX == -5) assert(unstandard.maxX == 10) assert(unstandard.minY == -30) assert(unstandard.midY == -5) assert(unstandard.maxY == 20) assert(unstandard == standard) assert(unstandard.standardized == standard) unstandard.standardizeInPlace() print_(unstandard, "standardized unstandard") // CHECK-NEXT: standardized unstandard -20.0 -30.0 30.0 50.0 rect = CGRect(x: 11.25, y: 22.25, width: 33.25, height: 44.25) print_(rect.insetBy(dx: 1, dy: -2), "insetBy") // CHECK-NEXT: insetBy 12.25 20.25 31.25 48.25 rect.insetInPlace(dx: 1, dy: -2) print_(rect, "insetInPlace") // CHECK-NEXT: insetInPlace 12.25 20.25 31.25 48.25 rect = CGRect(x: 11.25, y: 22.25, width: 33.25, height: 44.25) print_(rect.offsetBy(dx: 3, dy: -4), "offsetBy") // CHECK-NEXT: offsetBy 14.25 18.25 33.25 44.25 rect.offsetInPlace(dx: 3, dy: -4) print_(rect, "offsetInPlace") // CHECK-NEXT: offsetInPlace 14.25 18.25 33.25 44.25 rect = CGRect(x: 11.25, y: 22.25, width: 33.25, height: 44.25) print_(rect.integral, "integral") // CHECK-NEXT: integral 11.0 22.0 34.0 45.0 rect.makeIntegralInPlace() print_(rect, "makeIntegralInPlace") // CHECK-NEXT: makeIntegralInPlace 11.0 22.0 34.0 45.0 let smallRect = CGRect(x: 10, y: 25, width: 5, height: -5) let bigRect = CGRect(x: 1, y: 2, width: 101, height: 102) let distantRect = CGRect(x: 1000, y: 2000, width: 1, height: 1) rect = CGRect(x: 11.25, y: 22.25, width: 33.25, height: 44.25) print_(rect.union(smallRect), "union small") print_(rect.union(bigRect), "union big") print_(rect.union(distantRect), "union distant") // CHECK-NEXT: union small 10.0 20.0 34.5 46.5 // CHECK-NEXT: union big 1.0 2.0 101.0 102.0 // CHECK-NEXT: union distant 11.25 22.25 989.75 1978.75 rect.unionInPlace(smallRect) rect.unionInPlace(bigRect) rect.unionInPlace(distantRect) print_(rect, "unionInPlace") // CHECK-NEXT: unionInPlace 1.0 2.0 1000.0 1999.0 rect = CGRect(x: 11.25, y: 22.25, width: 33.25, height: 44.25) print_(rect.intersect(smallRect), "intersect small") print_(rect.intersect(bigRect), "intersect big") print_(rect.intersect(distantRect), "intersect distant") // CHECK-NEXT: intersect small 11.25 22.25 3.75 2.75 // CHECK-NEXT: intersect big 11.25 22.25 33.25 44.25 // CHECK-NEXT: intersect distant inf inf 0.0 0.0 assert(rect.intersects(smallRect)) rect.intersectInPlace(smallRect) assert(!rect.isEmpty) assert(rect.intersects(bigRect)) rect.intersectInPlace(bigRect) assert(!rect.isEmpty) assert(!rect.intersects(distantRect)) rect.intersectInPlace(distantRect) assert(rect.isEmpty) rect = CGRect(x: 11.25, y: 22.25, width: 33.25, height: 44.25) assert(rect.contains(CGPoint(x: 15, y: 25))) assert(!rect.contains(CGPoint(x: -15, y: 25))) assert(bigRect.contains(rect)) assert(!rect.contains(bigRect)) rect = CGRect(x: 11.25, y: 22.25, width: 33.25, height: 44.25) var (slice, remainder) = rect.divide(5, fromEdge:CGRectEdge.MinXEdge) print_(slice, "slice") print_(remainder, "remainder") // CHECK-NEXT: slice 11.25 22.25 5.0 44.25 // CHECK-NEXT: remainder 16.25 22.25 28.25 44.25
c444f66bbff2679d2e480811b6f6e815
29.946281
81
0.696355
false
false
false
false
devincoughlin/swift
refs/heads/master
test/ClangImporter/optional.swift
apache-2.0
8
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -module-name optional -I %S/Inputs/custom-modules -emit-silgen -o - %s | %FileCheck %s // REQUIRES: objc_interop import ObjectiveC import Foundation import objc_ext import TestProtocols class A { @objc func foo() -> String? { return "" } // CHECK-LABEL: sil hidden [thunk] [ossa] @$s8optional1AC3fooSSSgyFTo : $@convention(objc_method) (A) -> @autoreleased Optional<NSString> // CHECK: bb0([[SELF:%.*]] : @unowned $A): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK: [[T0:%.*]] = function_ref @$s8optional1AC3fooSSSgyF // CHECK-NEXT: [[T1:%.*]] = apply [[T0]]([[BORROWED_SELF_COPY]]) // CHECK-NEXT: end_borrow [[BORROWED_SELF_COPY]] // CHECK-NEXT: destroy_value [[SELF_COPY]] // CHECK-NEXT: switch_enum [[T1]] : $Optional<String>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // // Something branch: project value, translate, inject into result. // CHECK: [[SOME_BB]]([[STR:%.*]] : @owned $String): // CHECK: [[T0:%.*]] = function_ref @$sSS10FoundationE19_bridgeToObjectiveCSo8NSStringCyF // CHECK-NEXT: [[BORROWED_STR:%.*]] = begin_borrow [[STR]] // CHECK-NEXT: [[T1:%.*]] = apply [[T0]]([[BORROWED_STR]]) // CHECK-NEXT: end_borrow [[BORROWED_STR:%.*]] // CHECK-NEXT: enum $Optional<NSString>, #Optional.some!enumelt.1, [[T1]] // CHECK-NEXT: destroy_value [[STR]] // CHECK-NEXT: br // Nothing branch: inject nothing into result. // // CHECK: [[NONE_BB]]: // CHECK-NEXT: enum $Optional<NSString>, #Optional.none!enumelt // CHECK-NEXT: br // Continuation. // CHECK: bb3([[T0:%.*]] : @owned $Optional<NSString>): // CHECK-NEXT: return [[T0]] @objc func bar(x x : String?) {} // CHECK-LABEL: sil hidden [thunk] [ossa] @$s8optional1AC3bar1xySSSg_tFTo : $@convention(objc_method) (Optional<NSString>, A) -> () // CHECK: bb0([[ARG:%.*]] : @unowned $Optional<NSString>, [[SELF:%.*]] : @unowned $A): // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: switch_enum [[ARG_COPY]] : $Optional<NSString>, case #Optional.some!enumelt.1: [[SOME_BB:bb[0-9]+]], case #Optional.none!enumelt: [[NONE_BB:bb[0-9]+]] // // Something branch: project value, translate, inject into result. // CHECK: [[SOME_BB]]([[NSSTR:%.*]] : @owned $NSString): // CHECK: [[T0:%.*]] = function_ref @$sSS10FoundationE36_unconditionallyBridgeFromObjectiveCySSSo8NSStringCSgFZ // Make a temporary initialized string that we're going to clobber as part of the conversion process (?). // CHECK-NEXT: [[NSSTR_BOX:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[NSSTR]] : $NSString // CHECK-NEXT: [[STRING_META:%.*]] = metatype $@thin String.Type // CHECK-NEXT: [[T1:%.*]] = apply [[T0]]([[NSSTR_BOX]], [[STRING_META]]) // CHECK-NEXT: enum $Optional<String>, #Optional.some!enumelt.1, [[T1]] // CHECK-NEXT: destroy_value [[NSSTR_BOX]] // CHECK-NEXT: br // // Nothing branch: inject nothing into result. // CHECK: [[NONE_BB]]: // CHECK: enum $Optional<String>, #Optional.none!enumelt // CHECK-NEXT: br // Continuation. // CHECK: bb3([[T0:%.*]] : @owned $Optional<String>): // CHECK: [[BORROWED_T0:%.*]] = begin_borrow [[T0]] // CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK: [[T1:%.*]] = function_ref @$s8optional1AC3bar1xySSSg_tF // CHECK-NEXT: [[T2:%.*]] = apply [[T1]]([[BORROWED_T0]], [[BORROWED_SELF_COPY]]) // CHECK-NEXT: end_borrow [[BORROWED_SELF_COPY]] // CHECK-NEXT: end_borrow [[BORROWED_T0]] // CHECK-NEXT: destroy_value [[T0]] // CHECK-NEXT: destroy_value [[SELF_COPY]] // CHECK-NEXT: return [[T2]] : $() } // rdar://15144951 class TestWeak : NSObject { weak var b : WeakObject? = nil } class WeakObject : NSObject {}
eee78a2b365946e2641f4b1dfc1534c3
45.927711
165
0.626701
false
false
false
false
CrowdFlower/incubator-openwhisk
refs/heads/master
tests/dat/actions/httpGet.swift
apache-2.0
10
/** * Sample code using the experimental Swift 3 runtime * with links to KituraNet and GCD */ import KituraNet import Dispatch import Foundation import SwiftyJSON func main(args:[String:Any]) -> [String:Any] { // Force KituraNet call to run synchronously on a global queue var str = "No response" dispatch_sync(dispatch_get_global_queue(0, 0)) { HTTP.get("https://httpbin.org/get") { response in do { str = try response!.readString()! } catch { print("Error \(error)") } } } // Assume string is JSON print("Got string \(str)") var result:[String:Any]? // Convert to NSData let data = str.data(using: NSUTF8StringEncoding, allowLossyConversion: true)! // test SwiftyJSON let json = JSON(data: data) if let jsonUrl = json["url"].string { print("Got json url \(jsonUrl)") } else { print("JSON DID NOT PARSE") } // create result object to return do { result = try NSJSONSerialization.jsonObject(with: data, options: []) as? [String: Any] } catch { print("Error \(error)") } // return, which should be a dictionary print("Result is \(result!)") return result! }
a63363d8163f15c5f23ca5ec441d02f6
23.490566
94
0.578582
false
false
false
false
lllyyy/LY
refs/heads/master
GraphView/GraphView/UIColor+colorFromHex.swift
mit
3
import UIKit // An extension to UIColor which adds a class function that returns a UIColor from the provided hex string. The colours are cached. // Parameters: hexString:String, the hex code for the color you want. Leading "#" is optional. Must be 6 hex digts long. (8 bits per color) // Usage: let someColor = UIColor.colorFromHex("#2d34aa") extension UIColor { // Convert a hex string to a UIColor object. class func colorFromHex(hexString:String) -> UIColor { func clean(hexString: String) -> String { var cleanedHexString = String() // Remove the leading "#" if(hexString[hexString.startIndex] == "#") { let index = hexString.index(hexString.startIndex, offsetBy: 1) cleanedHexString = String(hexString[index...]) } // TODO: Other cleanup. Allow for a "short" hex string, i.e., "#fff" return cleanedHexString } let cleanedHexString = clean(hexString: hexString) // If we can get a cached version of the colour, get out early. if let cachedColor = UIColor.getColorFromCache(hexString: cleanedHexString) { return cachedColor } // Else create the color, store it in the cache and return. let scanner = Scanner(string: cleanedHexString) var value:UInt32 = 0 // We have the hex value, grab the red, green, blue and alpha values. // Have to pass value by reference, scanner modifies this directly as the result of scanning the hex string. The return value is the success or fail. if(scanner.scanHexInt32(&value)){ // intValue = 01010101 11110111 11101010 // binary // intValue = 55 F7 EA // hexadecimal // r // 00000000 00000000 01010101 intValue >> 16 // & 00000000 00000000 11111111 mask // ========================== // = 00000000 00000000 01010101 red // r g // 00000000 01010101 11110111 intValue >> 8 // & 00000000 00000000 11111111 mask // ========================== // = 00000000 00000000 11110111 green // r g b // 01010101 11110111 11101010 intValue // & 00000000 00000000 11111111 mask // ========================== // = 00000000 00000000 11101010 blue let intValue = UInt32(value) let mask:UInt32 = 0xFF let red = intValue >> 16 & mask let green = intValue >> 8 & mask let blue = intValue & mask // red, green, blue and alpha are currently between 0 and 255 // We want to normalise these values between 0 and 1 to use with UIColor. let colors:[UInt32] = [red, green, blue] let normalised = normalise(colors: colors) let newColor = UIColor(red: normalised[0], green: normalised[1], blue: normalised[2], alpha: 1) UIColor.storeColorInCache(hexString: cleanedHexString, color: newColor) return newColor } // We couldn't get a value from a valid hex string. else { print("Error: Couldn't convert the hex string to a number, returning UIColor.whiteColor() instead.") return UIColor.white } } // Takes an array of colours in the range of 0-255 and returns a value between 0 and 1. private class func normalise(colors: [UInt32]) -> [CGFloat]{ var normalisedVersions = [CGFloat]() for color in colors{ normalisedVersions.append(CGFloat(color % 256) / 255) } return normalisedVersions } // Caching // Store any colours we've gotten before. Colours don't change. private static var hexColorCache = [String : UIColor]() private class func getColorFromCache(hexString: String) -> UIColor? { guard let color = UIColor.hexColorCache[hexString] else { return nil } return color } private class func storeColorInCache(hexString: String, color: UIColor) { if UIColor.hexColorCache.keys.contains(hexString) { return // No work to do if it is already there. } UIColor.hexColorCache[hexString] = color } private class func clearColorCache() { UIColor.hexColorCache.removeAll() } }
5ef621dcb21ef6942da87b443eb12f67
37.532258
157
0.5473
false
false
false
false
artsy/eidolon
refs/heads/master
KioskTests/Bid Fulfillment/ConfirmYourBidPINViewControllerTests.swift
mit
3
import Quick import Nimble @testable import Kiosk import Moya import RxSwift import Nimble_Snapshots class ConfirmYourBidPINViewControllerTests: QuickSpec { override func spec() { it("looks right by default") { let subject = testConfirmYourBidPINViewController() subject.loadViewProgrammatically() expect(subject) == snapshot() } it("reacts to keypad inputs with the string") { let customKeySubject = PublishSubject<String>() let subject = testConfirmYourBidPINViewController() subject.pin = customKeySubject.asObservable() subject.loadViewProgrammatically() customKeySubject.onNext("2344"); expect(subject.pinTextField.text) == "2344" } it("reacts to keypad inputs with the string") { let customKeySubject = PublishSubject<String>() let subject = testConfirmYourBidPINViewController() subject.pin = customKeySubject subject.loadViewProgrammatically() customKeySubject.onNext("2"); expect(subject.pinTextField.text) == "2" } it("reacts to keypad inputs with the string") { let customKeySubject = PublishSubject<String>() let subject = testConfirmYourBidPINViewController() subject.pin = customKeySubject; subject.loadViewProgrammatically() customKeySubject.onNext("222"); expect(subject.pinTextField.text) == "222" } } } func testConfirmYourBidPINViewController() -> ConfirmYourBidPINViewController { let controller = ConfirmYourBidPINViewController.instantiateFromStoryboard(fulfillmentStoryboard).wrapInFulfillmentNav() as! ConfirmYourBidPINViewController controller.provider = Networking.newStubbingNetworking() return controller }
c64613fd0bc51ccd656584a0c54a895b
31.482759
160
0.667197
false
true
false
false
kristopherjohnson/bitsybasic
refs/heads/master
finchbasic/main.swift
mit
1
/* Copyright (c) 2014, 2015 Kristopher Johnson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import Foundation func runInterpreter() { let io = StandardIO() let interpreter = Interpreter(interpreterIO: io) interpreter.runUntilEndOfInput() } // Put -DUSE_INTERPRETER_THREAD=1 in Build Settings // to run the interpreter in another thread. // // This demonstrates that we get EXC_BAD_ACCESS when // running the interpreter in another thread. Do not // use this for production code. // // See http://www.openradar.me/19353741 #if USE_INTERPRETER_THREAD final class InterpreterThread: NSThread { let completionSemaphore = dispatch_semaphore_create(0) override func main() { runInterpreter() dispatch_semaphore_signal(self.completionSemaphore) } } let thread = InterpreterThread() thread.start() // Main thread waits for the other thread to finish dispatch_semaphore_wait(thread.completionSemaphore, DISPATCH_TIME_FOREVER) #else // Normal case is to run the interpreter in the // main thread runInterpreter() #endif
cfc712ce7a7f18ca432d2c3f66adaac7
32.460317
78
0.748577
false
false
false
false
P0ed/Magikombat
refs/heads/master
Magikombat/Engine/Engine.swift
mit
1
import Foundation class Engine { let world = World() var state = GameState() var hero = Actor() init(level: Level) { setup(level) } func setup(level: Level) { level.forEach { node in let platform = node.platform world.createStaticBody(platform.position.asVector(), size: platform.size.asVector()) } hero.body = world.createDynamicBody(Position(x: 10, y: 10).asVector(), size: Size(width: 1, height: 2).asVector()) } func handleInput(input: Input) { hero.handleInput(input) } func simulatePhysics(input: Input) -> GameState { handleInput(input) world.step() state.hero.position = hero.body!.position return state } }
8ea6727564ba1285d52f3d4bce073edb
16.918919
116
0.686275
false
false
false
false
appnexus/mobile-sdk-ios
refs/heads/master
examples/Swift/SimpleIntegration/SimpleIntegrationSwift/NativeAd/NativeAdViewController.swift
apache-2.0
1
/* Copyright 2020 APPNEXUS INC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import UIKit import AppNexusSDK class NativeAdViewController: UIViewController , ANNativeAdRequestDelegate , ANNativeAdDelegate { var nativeAdRequest: ANNativeAdRequest? var nativeAdResponse: ANNativeAdResponse? var anNativeAdView: ANNativeAdView? var indicator = UIActivityIndicatorView() override func viewDidLoad() { super.viewDidLoad() self.title = "Native Ad" // Do any additional setup after loading the view. nativeAdRequest = ANNativeAdRequest() nativeAdRequest!.placementId = "17058950" nativeAdRequest!.shouldLoadIconImage = true nativeAdRequest!.shouldLoadMainImage = true nativeAdRequest!.delegate = self nativeAdRequest!.loadAd() } func adRequest(_ request: ANNativeAdRequest, didReceive response: ANNativeAdResponse) { self.nativeAdResponse = response let adNib = UINib(nibName: "ANNativeAdView", bundle: Bundle.main) let array = adNib.instantiate(withOwner: self, options: nil) anNativeAdView = array.first as? ANNativeAdView anNativeAdView?.titleLabel.text = nativeAdResponse?.title anNativeAdView?.bodyLabel.text = nativeAdResponse?.body anNativeAdView?.iconImageView.image = nativeAdResponse?.iconImage anNativeAdView?.mainImageView.image = nativeAdResponse?.mainImage anNativeAdView?.sponsoredLabel.text = nativeAdResponse?.sponsoredBy anNativeAdView?.callToActionButton.setTitle(nativeAdResponse?.callToAction, for: .normal) nativeAdResponse?.delegate = self nativeAdResponse?.clickThroughAction = ANClickThroughAction.openSDKBrowser view.addSubview(anNativeAdView!) do { try nativeAdResponse?.registerView(forTracking: anNativeAdView!, withRootViewController: self, clickableViews: [self.anNativeAdView?.callToActionButton! as Any, self.anNativeAdView?.mainImageView! as Any]) } catch { print("Failed to registerView for Tracking") } } func adRequest(_ request: ANNativeAdRequest, didFailToLoadWithError error: Error, with adResponseInfo: ANAdResponseInfo?) { print("Ad request Failed With Error") } // MARK: - ANNativeAdDelegate func adDidLogImpression(_ response: Any) { print("adDidLogImpression") } func adWillExpire(_ response: Any) { print("adWillExpire") } func adDidExpire(_ response: Any) { print("adDidExpire") } func adWasClicked(_ response: Any) { print("adWasClicked") } func adWillPresent(_ response: Any) { print("adWillPresent") } func adDidPresent(_ response: Any) { print("adDidPresent") } func adWillClose(_ response: Any) { print("adWillClose") } func adDidClose(_ response: Any) { print("adDidClose") } func adWillLeaveApplication(_ response: Any) { print("adWillLeaveApplication") } @IBAction func hideAds(_ sender: Any) { self.anNativeAdView?.removeFromSuperview() } }
1c3fee72751a2df450dc13dd18599700
32.5
217
0.677505
false
false
false
false
byu-oit/ios-byuSuite
refs/heads/dev
byuSuite/Apps/DiningLocations/controller/DiningLocationsDatePickerViewController.swift
apache-2.0
1
// // DiningLocationsDatePickerViewController.swift // byuSuite // // Created by Erik Brady on 6/20/17. // Copyright © 2017 Brigham Young University. All rights reserved. // private let SECONDS_IN_WEEK = 604800 as Double private let DEFAULT_LOCATION_KEY = "defaultLocation" private let DAY_FORMATTER = DateFormatter.defaultDateFormat("EEEE") private let SERVE_DATE_FORMATTER = DateFormatter.defaultDateFormat("yyyyMMdd") private let DISCLAIMER_KEY = "hasSeenBYUDiningDisclaimer" private let CANNON_LOCATION = DiningLocationsLocation(locationId: "Cannon", name: "Cannon Commons", externalUrl: "") class DiningLocationsDatePickerViewController: ByuTableDataViewController { //Outlets @IBOutlet private weak var datePicker: UIDatePicker! //Properties private var location: DiningLocationsLocation = CANNON_LOCATION { didSet { //When the location is updated, save into user defaults. UserDefaults.standard.set(try? JSONEncoder().encode(location), forKey: DEFAULT_LOCATION_KEY) DiningLocationsAllergenFilter.clearFilters() reload() } } private var meals: [DiningLocationsMeal]? override func viewDidLoad() { super.viewDidLoad() datePicker.minimumDate = Date() datePicker.maximumDate = Date(timeIntervalSinceNow: SECONDS_IN_WEEK * 2) if !UserDefaults.standard.bool(forKey: DISCLAIMER_KEY) { performSegue(withIdentifier: "toLegalView", sender: self) UserDefaults.standard.set(true, forKey: DISCLAIMER_KEY) } //Get saved location in user defaults, if there is not one saved then it is defaulted to Cannon Commons. if let data = UserDefaults.standard.data(forKey: DEFAULT_LOCATION_KEY), let location = try? JSONDecoder().decode(DiningLocationsLocation.self, from: data) { self.location = location } else { self.location = CANNON_LOCATION } } //MARK: Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if location.id == CANNON_LOCATION.id, segue.identifier == "showStations", let tbc = segue.destination as? UITabBarController, let stationVC = tbc.viewControllers?[0] as? DiningLocationsCannonsStationsViewController, let fullMenuVC = tbc.viewControllers?[1] as? DiningLocationsMenuViewController, let meal = sender as? DiningLocationsMeal { tbc.title = meal.name stationVC.categories = meal.categories fullMenuVC.categories = meal.categories } else if segue.identifier == "fullMenu", let fullMenuVC = segue.destination as? DiningLocationsMenuViewController, let meal = sender as? DiningLocationsMeal { fullMenuVC.title = meal.name fullMenuVC.categories = meal.categories } else if segue.identifier == "showLocations", let vc = segue.destination as? UINavigationController, let tbc = vc.viewControllers.first as? DiningLocationsLocationsTabBarViewController { tbc.selectedLocation = location } } //MARK: Listeners @IBAction func unwindSegue(_ sender: UIStoryboardSegue) { if let vc = sender.source as? DiningLocationsLocationsTabBarViewController, let location = vc.selectedLocation { self.location = location } } @IBAction func datePickerValueChanged(_ sender: Any) { reload() } //MARK: Custom Methods private func reload() { //This method will be called each time the date or the location reloads. title = location.name let day = DAY_FORMATTER.string(from: self.datePicker.date) //Only load meals if there is no external url. if location.externalUrl == "" { //The table is hidden while the data is loaded. tableView.isHidden = true spinner?.startAnimating() let serveDate = SERVE_DATE_FORMATTER.string(from: datePicker.date) DiningLocationsClient.getMeals(locationId: location.id, serveDate: serveDate) { (meals, error) in self.tableView.isHidden = false self.spinner?.stopAnimating() if let meals = meals { self.meals = meals //Load the allergens from all of the menu items into the static filter DiningLocationsAllergenFilter.loadAllPossibleFilters(meals: meals) //Setup table data self.tableData = TableData(sections: [Section(title: meals.count == 0 ? "\(day) - No meals found" : "\(day)", rows: meals.map({ (meal) -> Row in return Row(text: meal.name, action: { if self.location.id == "Cannon" { self.performSegue(withIdentifier: "showStations", sender: meal) } else { self.performSegue(withIdentifier: "fullMenu", sender: meal) } }, object: meal) }))]) self.tableView.reloadData() } else { super.displayAlert(error: error) } } } else { tableData = TableData(sections: [Section(title: "\(day)", rows: [Row(text: "Tap to view \(location.name) menu/nutrition information online.", cellId: "externalUrlCell", action: { self.presentSafariViewController(urlString: self.location.externalUrl)})])]) tableView.reloadData() } } }
22fce7c8f5bb2193547d3422bbed45af
34.543478
181
0.722936
false
false
false
false
parkera/swift-corelibs-foundation
refs/heads/master
Foundation/Operation.swift
apache-2.0
1
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // #if DEPLOYMENT_ENABLE_LIBDISPATCH import Dispatch #endif import CoreFoundation open class Operation : NSObject { let lock = NSLock() internal weak var _queue: OperationQueue? internal var _cancelled = false internal var _executing = false internal var _finished = false internal var _ready = false internal var _dependencies = Set<Operation>() #if DEPLOYMENT_ENABLE_LIBDISPATCH internal var _group = DispatchGroup() internal var _depGroup = DispatchGroup() internal var _groups = [DispatchGroup]() #endif // prioritizedPrevious && prioritizedNext used to traverse in the order in which the operations need to be dequeued fileprivate weak var prioritizedPrevious: Operation? fileprivate var prioritizedNext: Operation? // orderdedPrevious && orderdedNext used to traverse in the order in which the operations added to the queue fileprivate weak var orderdedPrevious: Operation? fileprivate var orderdedNext: Operation? public override init() { super.init() #if DEPLOYMENT_ENABLE_LIBDISPATCH _group.enter() #endif } internal func _leaveGroups() { // assumes lock is taken #if DEPLOYMENT_ENABLE_LIBDISPATCH _groups.forEach() { $0.leave() } _groups.removeAll() _group.leave() #endif } open func start() { if !isCancelled { lock.lock() _executing = true lock.unlock() main() lock.lock() _executing = false lock.unlock() } finish() } internal func finish() { lock.lock() _finished = true _leaveGroups() lock.unlock() if let queue = _queue { queue._operationFinished(self) } #if DEPLOYMENT_ENABLE_LIBDISPATCH // The completion block property is a bit cagey and can not be executed locally on the queue due to thread exhaust potentials. // This sets up for some strange behavior of finishing operations since the handler will be executed on a different queue if let completion = completionBlock { DispatchQueue.global(qos: .background).async { () -> Void in completion() } } #endif } open func main() { } open var isCancelled: Bool { return _cancelled } open func cancel() { // Note that calling cancel() is advisory. It is up to the main() function to // call isCancelled at appropriate points in its execution flow and to do the // actual canceling work. Eventually main() will invoke finish() and this is // where we then leave the groups and unblock other operations that might // depend on us. lock.lock() _cancelled = true lock.unlock() } open var isExecuting: Bool { let wasExecuting: Bool lock.lock() wasExecuting = _executing lock.unlock() return wasExecuting } open var isFinished: Bool { return _finished } // - Note: This property is NEVER used in the objective-c implementation! open var isAsynchronous: Bool { return false } open var isReady: Bool { return _ready } open func addDependency(_ op: Operation) { lock.lock() _dependencies.insert(op) op.lock.lock() #if DEPLOYMENT_ENABLE_LIBDISPATCH _depGroup.enter() op._groups.append(_depGroup) #endif op.lock.unlock() lock.unlock() } open func removeDependency(_ op: Operation) { lock.lock() _dependencies.remove(op) op.lock.lock() #if DEPLOYMENT_ENABLE_LIBDISPATCH let groupIndex = op._groups.firstIndex(where: { $0 === self._depGroup }) if let idx = groupIndex { let group = op._groups.remove(at: idx) group.leave() } #endif op.lock.unlock() lock.unlock() } open var dependencies: [Operation] { lock.lock() let ops = _dependencies.map() { $0 } lock.unlock() return ops } open var queuePriority: QueuePriority = .normal public var completionBlock: (() -> Void)? open func waitUntilFinished() { #if DEPLOYMENT_ENABLE_LIBDISPATCH _group.wait() #endif } open var threadPriority: Double = 0.5 /// - Note: Quality of service is not directly supported here since there are not qos class promotions available outside of darwin targets. open var qualityOfService: QualityOfService = .default open var name: String? internal func _waitUntilReady() { #if DEPLOYMENT_ENABLE_LIBDISPATCH _depGroup.wait() #endif _ready = true } } /// The following two methods are added to provide support for Operations which /// are asynchronous from the execution of the operation queue itself. On Darwin, /// this is supported via KVO notifications. In the absence of KVO on non-Darwin /// platforms, these two methods (which are defined in NSObject on Darwin) are /// temporarily added here. They should be removed once a permanent solution is /// found. extension Operation { public func willChangeValue(forKey key: String) { // do nothing } public func didChangeValue(forKey key: String) { if key == "isFinished" && isFinished { finish() } } public func willChangeValue<Value>(for keyPath: KeyPath<Operation, Value>) { // do nothing } public func didChangeValue<Value>(for keyPath: KeyPath<Operation, Value>) { if keyPath == \Operation.isFinished { finish() } } } extension Operation { public enum QueuePriority : Int { case veryLow case low case normal case high case veryHigh } } open class BlockOperation: Operation { typealias ExecutionBlock = () -> Void internal var _block: () -> Void internal var _executionBlocks = [ExecutionBlock]() public init(block: @escaping () -> Void) { _block = block } override open func main() { lock.lock() let block = _block let executionBlocks = _executionBlocks lock.unlock() block() executionBlocks.forEach { $0() } } open func addExecutionBlock(_ block: @escaping () -> Void) { lock.lock() _executionBlocks.append(block) lock.unlock() } open var executionBlocks: [() -> Void] { lock.lock() let blocks = _executionBlocks lock.unlock() return blocks } } extension OperationQueue { public static let defaultMaxConcurrentOperationCount: Int = Int.max } fileprivate class _IndexedOperationLinkedList { private(set) var root: Operation? = nil private(set) var tail: Operation? = nil func append(_ operation: Operation, inOrderList: Bool = false) { if root == nil { root = operation tail = operation } else { if inOrderList { appendOperationInOrderList(operation) } else { appendOperationInPriorityList(operation) } } } private func appendOperationInPriorityList(_ operation: Operation) { operation.prioritizedPrevious = tail tail?.prioritizedNext = operation tail = operation } private func appendOperationInOrderList(_ operation: Operation) { operation.orderdedPrevious = tail tail?.orderdedNext = operation tail = operation } func remove(_ operation: Operation, fromOrderList: Bool) { if fromOrderList { removeOperationFromOrderList(operation) } else { removeOperationFromPriorityList(operation) } } private func removeOperationFromPriorityList(_ operation: Operation) { guard let unwrappedRoot = root, let unwrappedTail = tail else { return } if operation === unwrappedRoot { let next = operation.prioritizedNext next?.prioritizedPrevious = nil root = next if root == nil { tail = nil } } else if operation === unwrappedTail { tail = operation.prioritizedPrevious tail?.prioritizedNext = nil } else { // Middle Node let previous = operation.prioritizedPrevious let next = operation.prioritizedNext previous?.prioritizedNext = next next?.prioritizedPrevious = previous operation.prioritizedNext = nil operation.prioritizedPrevious = nil } } private func removeOperationFromOrderList(_ operation: Operation) { guard let unwrappedRoot = root, let unwrappedTail = tail else { return } if operation === unwrappedRoot { let next = operation.orderdedNext next?.orderdedPrevious = nil root = next if root == nil { tail = nil } } else if operation === unwrappedTail { tail = operation.orderdedPrevious tail?.orderdedNext = nil } else { // Middle Node let previous = operation.orderdedPrevious let next = operation.orderdedNext previous?.orderdedNext = next next?.orderdedPrevious = previous operation.orderdedNext = nil operation.orderdedPrevious = nil } } func removeFirstInPriority() -> Operation? { guard let operation = root else { return nil } remove(operation, fromOrderList: false) return operation } } fileprivate struct _OperationList { var veryLow = _IndexedOperationLinkedList() var low = _IndexedOperationLinkedList() var normal = _IndexedOperationLinkedList() var high = _IndexedOperationLinkedList() var veryHigh = _IndexedOperationLinkedList() var all = _IndexedOperationLinkedList() var count: Int = 0 mutating func insert(_ operation: Operation) { all.append(operation, inOrderList: true) switch operation.queuePriority { case .veryLow: veryLow.append(operation) case .low: low.append(operation) case .normal: normal.append(operation) case .high: high.append(operation) case .veryHigh: veryHigh.append(operation) } count += 1 } mutating func remove(_ operation: Operation) { all.remove(operation, fromOrderList: true) switch operation.queuePriority { case .veryLow: veryLow.remove(operation, fromOrderList: false) case .low: low.remove(operation, fromOrderList: false) case .normal: normal.remove(operation, fromOrderList: false) case .high: high.remove(operation, fromOrderList: false) case .veryHigh: veryHigh.remove(operation, fromOrderList: false) } count -= 1 } func dequeue() -> Operation? { if let operation = veryHigh.removeFirstInPriority() { return operation } else if let operation = high.removeFirstInPriority() { return operation } else if let operation = normal.removeFirstInPriority() { return operation } else if let operation = low.removeFirstInPriority() { return operation } else if let operation = veryLow.removeFirstInPriority() { return operation } else { return nil } } func map<T>(_ transform: (Operation) throws -> T) rethrows -> [T] { var result: [T] = [] var current = all.root while let node = current { result.append(try transform(node)) current = current?.orderdedNext } return result } } open class OperationQueue: NSObject { let lock = NSLock() #if DEPLOYMENT_ENABLE_LIBDISPATCH var __concurrencyGate: DispatchSemaphore? var __underlyingQueue: DispatchQueue? { didSet { let key = OperationQueue.OperationQueueKey oldValue?.setSpecific(key: key, value: nil) __underlyingQueue?.setSpecific(key: key, value: Unmanaged.passUnretained(self)) } } let queueGroup = DispatchGroup() var unscheduledWorkItems: [DispatchWorkItem] = [] #endif fileprivate var _operations = _OperationList() #if DEPLOYMENT_ENABLE_LIBDISPATCH internal var _concurrencyGate: DispatchSemaphore? { get { lock.lock() let val = __concurrencyGate lock.unlock() return val } } // This is NOT the behavior of the objective-c variant; it will never re-use a queue and instead for every operation it will create a new one. // However this is considerably faster and probably more effecient. internal var _underlyingQueue: DispatchQueue { lock.lock() if let queue = __underlyingQueue { lock.unlock() return queue } else { let effectiveName: String if let requestedName = _name { effectiveName = requestedName } else { effectiveName = "NSOperationQueue::\(Unmanaged.passUnretained(self).toOpaque())" } let attr: DispatchQueue.Attributes if maxConcurrentOperationCount == 1 { attr = [] __concurrencyGate = DispatchSemaphore(value: 1) } else { attr = .concurrent if maxConcurrentOperationCount != OperationQueue.defaultMaxConcurrentOperationCount { __concurrencyGate = DispatchSemaphore(value:maxConcurrentOperationCount) } } let queue = DispatchQueue(label: effectiveName, attributes: attr) __underlyingQueue = queue lock.unlock() return queue } } #endif public override init() { super.init() } #if DEPLOYMENT_ENABLE_LIBDISPATCH internal init(_queue queue: DispatchQueue, maxConcurrentOperations: Int = OperationQueue.defaultMaxConcurrentOperationCount) { __underlyingQueue = queue maxConcurrentOperationCount = maxConcurrentOperations super.init() queue.setSpecific(key: OperationQueue.OperationQueueKey, value: Unmanaged.passUnretained(self)) } #endif internal func _dequeueOperation() -> Operation? { lock.lock() let op = _operations.dequeue() lock.unlock() return op } open func addOperation(_ op: Operation) { addOperations([op], waitUntilFinished: false) } internal func _runOperation() { if let op = _dequeueOperation() { if !op.isCancelled { op._waitUntilReady() if !op.isCancelled { op.start() } } } } open func addOperations(_ ops: [Operation], waitUntilFinished wait: Bool) { #if DEPLOYMENT_ENABLE_LIBDISPATCH var waitGroup: DispatchGroup? if wait { waitGroup = DispatchGroup() } #endif /* If QueuePriority was not supported this could be much faster since it would not need to have the extra book-keeping for managing a priority queue. However this implementation attempts to be similar to the specification. As a consequence this means that the dequeue may NOT necessarily be the same as the enqueued operation in this callout. So once the dispatch_block is created the operation must NOT be touched; since it has nothing to do with the actual execution. The only differential is that the block enqueued to dispatch_async is balanced with the number of Operations enqueued to the OperationQueue. */ lock.lock() ops.forEach { (operation: Operation) -> Void in operation._queue = self _operations.insert(operation) } lock.unlock() #if DEPLOYMENT_ENABLE_LIBDISPATCH let items = ops.map { (operation: Operation) -> DispatchWorkItem in if let group = waitGroup { group.enter() } return DispatchWorkItem(flags: .enforceQoS) { () -> Void in if let sema = self._concurrencyGate { sema.wait() self._runOperation() sema.signal() } else { self._runOperation() } if let group = waitGroup { group.leave() } } } let queue = _underlyingQueue lock.lock() if _suspended { unscheduledWorkItems += items } else { items.forEach { queue.async(group: queueGroup, execute: $0) } } lock.unlock() if let group = waitGroup { group.wait() } #endif } internal func _operationFinished(_ operation: Operation) { lock.lock() _operations.remove(operation) operation._queue = nil lock.unlock() } open func addOperation(_ block: @escaping () -> Swift.Void) { let op = BlockOperation(block: block) op.qualityOfService = qualityOfService addOperation(op) } // WARNING: the return value of this property can never be used to reliably do anything sensible open var operations: [Operation] { lock.lock() let ops = _operations.map() { $0 } lock.unlock() return ops } // WARNING: the return value of this property can never be used to reliably do anything sensible open var operationCount: Int { lock.lock() let count = _operations.count lock.unlock() return count } open var maxConcurrentOperationCount: Int = OperationQueue.defaultMaxConcurrentOperationCount internal var _suspended = false open var isSuspended: Bool { get { return _suspended } set { lock.lock() _suspended = newValue let items = unscheduledWorkItems unscheduledWorkItems.removeAll() lock.unlock() if !newValue { items.forEach { _underlyingQueue.async(group: queueGroup, execute: $0) } } } } internal var _name: String? open var name: String? { get { lock.lock() let val = _name lock.unlock() return val } set { lock.lock() _name = newValue #if DEPLOYMENT_ENABLE_LIBDISPATCH __underlyingQueue = nil #endif lock.unlock() } } open var qualityOfService: QualityOfService = .default #if DEPLOYMENT_ENABLE_LIBDISPATCH // Note: this will return non nil whereas the objective-c version will only return non nil when it has been set. // it uses a target queue assignment instead of returning the actual underlying queue. open var underlyingQueue: DispatchQueue? { get { lock.lock() let queue = __underlyingQueue lock.unlock() return queue } set { lock.lock() __underlyingQueue = newValue lock.unlock() } } #endif open func cancelAllOperations() { lock.lock() let ops = _operations.map() { $0 } lock.unlock() ops.forEach() { $0.cancel() } } open func waitUntilAllOperationsAreFinished() { #if DEPLOYMENT_ENABLE_LIBDISPATCH queueGroup.wait() #endif } #if DEPLOYMENT_ENABLE_LIBDISPATCH static let OperationQueueKey = DispatchSpecificKey<Unmanaged<OperationQueue>>() #endif open class var current: OperationQueue? { #if DEPLOYMENT_ENABLE_LIBDISPATCH guard let specific = DispatchQueue.getSpecific(key: OperationQueue.OperationQueueKey) else { if _CFIsMainThread() { return OperationQueue.main } else { return nil } } return specific.takeUnretainedValue() #else return nil #endif } #if DEPLOYMENT_ENABLE_LIBDISPATCH private static let _main = OperationQueue(_queue: .main, maxConcurrentOperations: 1) #endif open class var main: OperationQueue { #if DEPLOYMENT_ENABLE_LIBDISPATCH return _main #else fatalError("OperationQueue requires libdispatch") #endif } }
1b54a59ffa31bdfa4c9c39dcf8856a18
29.167135
146
0.588016
false
false
false
false
darrinhenein/firefox-ios
refs/heads/master
Storage/Storage/SQL/JoinedHistoryVisitsTable.swift
mpl-2.0
1
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation let HistoryVisits = "history-visits" // This isn't a real table. Its an abstraction around the history and visits table // to simpify queries that should join both tables. It also handles making sure that // inserts/updates/delete update both tables appropriately. i.e. // 1.) Deleteing a history entry here will also remove all visits to it // 2.) Adding a visit here will ensure that a site exists for the visit // 3.) Updates currently only update site information. class JoinedHistoryVisitsTable: Table { typealias Type = (site: Site?, visit: Visit?) var name: String { return HistoryVisits } var version: Int { return 1 } private let visits = VisitsTable<Visit>() private let history = HistoryTable<Site>() private let favicons: FaviconsTable<Favicon> private let faviconSites: JoinedFaviconsHistoryTable<(Site, Favicon)> init(files: FileAccessor) { favicons = FaviconsTable<Favicon>(files: files) faviconSites = JoinedFaviconsHistoryTable<(Site, Favicon)>(files: files) } private func getIDFor(db: SQLiteDBConnection, site: Site) -> Int? { let opts = QueryOptions() opts.filter = site.url let cursor = history.query(db, options: opts) if (cursor.count != 1) { return nil } return (cursor[0] as Site).id } func create(db: SQLiteDBConnection, version: Int) -> Bool { return history.create(db, version: version) && visits.create(db, version: version) && faviconSites.create(db, version: version) } func updateTable(db: SQLiteDBConnection, from: Int, to: Int) -> Bool { return history.updateTable(db, from: from, to: to) && visits.updateTable(db, from: from, to: to) } func exists(db: SQLiteDBConnection) -> Bool { return history.exists(db) && visits.exists(db) } func drop(db: SQLiteDBConnection) -> Bool { return history.drop(db) && visits.drop(db) } private func updateSite(db: SQLiteDBConnection, site: Site, inout err: NSError?) -> Int { // If our site doesn't have an id, we need to find one if site.id == nil { if let id = getIDFor(db, site: site) { site.id = id // Update the page title return history.update(db, item: site, err: &err) } else { // Make sure we have a site in the table first site.id = history.insert(db, item: site, err: &err) return 1 } } // Update the page title return history.update(db, item: site, err: &err) } func insert(db: SQLiteDBConnection, item: Type?, inout err: NSError?) -> Int { if let visit = item?.visit { if updateSite(db, site: visit.site, err: &err) < 0 { return -1; } // Now add a visit return visits.insert(db, item: visit, err: &err) } else if let site = item?.site { if updateSite(db, site: site, err: &err) < 0 { return -1; } // Now add a visit let visit = Visit(site: site, date: NSDate()) return visits.insert(db, item: visit, err: &err) } return -1 } func update(db: SQLiteDBConnection, item: Type?, inout err: NSError?) -> Int { return visits.update(db, item: item?.visit, err: &err); } func delete(db: SQLiteDBConnection, item: Type?, inout err: NSError?) -> Int { if let visit = item?.visit { return visits.delete(db, item: visit, err: &err) } else if let site = item?.site { let v = Visit(site: site, date: NSDate()) visits.delete(db, item: v, err: &err) return history.delete(db, item: site, err: &err) } else if item == nil { let site: Site? = nil let visit: Visit? = nil history.delete(db, item: site, err: &err); return visits.delete(db, item: visit, err: &err); } return -1 } func factory(result: SDRow) -> (site: Site, visit: Visit) { let site = Site(url: result["siteUrl"] as String, title: result["title"] as String) site.guid = result["guid"] as? String site.id = result["historyId"] as? Int let d = NSDate(timeIntervalSince1970: result["visitDate"] as Double) let type = VisitType(rawValue: result["visitType"] as Int) let visit = Visit(site: site, date: d, type: type!) visit.id = result["visitId"] as? Int site.latestVisit = visit if let iconurl = result["iconUrl"] as? String { let icon = Favicon(url: iconurl, date: NSDate(timeIntervalSince1970: result["iconDate"] as Double), type: IconType(rawValue: result["iconType"] as Int)!) icon.id = result["faviconId"] as? Int site.icon = icon } return (site, visit) } func query(db: SQLiteDBConnection, options: QueryOptions?) -> Cursor { var args = [AnyObject?]() var sql = "SELECT \(history.name).id as historyId, \(history.name).url as siteUrl, title, guid, \(visits.name).id as visitId, \(visits.name).date as visitDate, \(visits.name).type as visitType, " + "\(favicons.name).id as faviconId, \(favicons.name).url as iconUrl, \(favicons.name).date as iconDate, \(favicons.name).type as iconType FROM \(visits.name) " + "INNER JOIN \(history.name) ON \(history.name).id = \(visits.name).siteId " + "LEFT JOIN \(faviconSites.name) ON \(faviconSites.name).siteId = \(history.name).id LEFT JOIN \(favicons.name) ON \(faviconSites.name).faviconId = \(favicons.name).id "; if let filter: AnyObject = options?.filter { sql += "WHERE siteUrl LIKE ? " args.append("%\(filter)%") } sql += "GROUP BY historyId"; // Trying to do this in one line (i.e. options?.sort == .LastVisit) breaks the Swift compiler if let sort = options?.sort { if sort == .LastVisit { sql += " ORDER BY visitDate DESC" } } // println("Query \(sql) \(args)") return db.executeQuery(sql, factory: factory, withArgs: args) } }
87b0275b9750d709e47d3d39188126e9
39.385093
205
0.591972
false
false
false
false
congncif/SiFUtilities
refs/heads/master
Example/Pods/Boardy/Boardy/Core/BoardType/DedicatedBoard.swift
mit
1
// // DedicatedBoard.swift // Boardy // // Created by NGUYEN CHI CONG on 3/18/20. // import Foundation // MARK: - AdaptableBoard public protocol AdaptableBoard { associatedtype InputType var inputAdapters: [(Any?) -> InputType?] { get } } extension AdaptableBoard { public func convertOptionToInput(_ option: Any?) -> InputType? { var input: InputType? for adapter in validAdapters { input = adapter(option) if input != nil { break } } return input } public var inputAdapters: [(Any?) -> InputType?] { [] } var validAdapters: [(Any?) -> InputType?] { let defaultAdapter: (Any?) -> InputType? = { $0 as? InputType } return inputAdapters + [defaultAdapter] } } // MARK: - DedicatedBoard public protocol DedicatedBoard: AdaptableBoard, ActivatableBoard { func activate(withInput input: InputType?) } extension DedicatedBoard { public func activate(withOption option: Any?) { activate(withInput: convertOptionToInput(option)) } } // MARK: - GuaranteedBoard public protocol GuaranteedBoard: AdaptableBoard, ActivatableBoard { func activate(withGuaranteedInput input: InputType) var silentInputWhiteList: [(_ input: Any?) -> Bool] { get } } extension GuaranteedBoard { private func isSilent(input: Any?) -> Bool { let listCheckers = [isSilentData] + silentInputWhiteList for checker in listCheckers { if checker(input) { return true } } return false } public var silentInputWhiteList: [(_ input: Any?) -> Bool] { [] } public func activate(withOption option: Any?) { guard let input = convertOptionToInput(option) else { guard isSilent(input: option) else { assertionFailure("\(String(describing: self))\n🔥 Cannot convert input from \(String(describing: option)) to type \(InputType.self)") return } return } activate(withGuaranteedInput: input) } } // MARK: - Board sending a type safe Output data public protocol GuaranteedOutputSendingBoard: IdentifiableBoard { associatedtype OutputType } extension GuaranteedOutputSendingBoard { public func sendOutput(_ data: OutputType) { #if DEBUG if isSilentData(data) { print("\(String(describing: self))\n🔥 Sending a special Data Type might lead unexpected behaviours!\n👉 You should wrap \(data) in custom Output Type.") } #endif sendToMotherboard(data: data) } }
2e739a67019159e795f0757d7ac9e798
26.351064
163
0.641774
false
false
false
false
padawan/smartphone-app
refs/heads/master
MT_iOS/MT_iOS/Classes/ViewController/EntryHTMLEditorViewController.swift
mit
1
// // EntryHTMLEditorViewController.swift // MT_iOS // // Created by CHEEBOW on 2015/06/05. // Copyright (c) 2015年 Six Apart, Ltd. All rights reserved. // import UIKit import ZSSRichTextEditor class EntryHTMLEditorViewController: BaseViewController, UITextViewDelegate, AddAssetDelegate { var sourceView: ZSSTextView! var object: EntryTextAreaItem! var blog: Blog! var entry: BaseEntry! override func viewDidLoad() { super.viewDidLoad() self.title = object.label // Do any additional setup after loading the view. self.sourceView = ZSSTextView(frame: self.view.bounds) self.sourceView.autocapitalizationType = UITextAutocapitalizationType.None self.sourceView.autocorrectionType = UITextAutocorrectionType.No //self.sourceView.font = UIFont.systemFontOfSize(16.0) self.sourceView.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight self.sourceView.autoresizesSubviews = true self.sourceView.delegate = self self.view.addSubview(self.sourceView) self.sourceView.text = object.text self.sourceView.selectedRange = NSRange() let toolBar = UIToolbar(frame: CGRectMake(0.0, 0.0, self.view.frame.size.width, 44.0)) let cameraButton = UIBarButtonItem(image: UIImage(named: "btn_camera"), left: true, target: self, action: "cameraButtonPushed:") let flexibleButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil) var previewButton = UIBarButtonItem(image: UIImage(named: "btn_preview"), style: UIBarButtonItemStyle.Plain, target: self, action: "previewButtonPushed:") let doneButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: self, action: "doneButtonPushed:") if object is BlockTextItem { toolBar.items = [flexibleButton, previewButton, doneButton] } else { toolBar.items = [cameraButton, flexibleButton, previewButton, doneButton] } self.sourceView.inputAccessoryView = toolBar self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: self, action: "saveButtonPushed:") self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "back_arw"), left: true, target: self, action: "backButtonPushed:") self.sourceView.becomeFirstResponder() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillChangeFrameNotification, object: nil) } override func viewDidDisappear(animated: Bool) { NSNotificationCenter.defaultCenter().removeObserver(self) } 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. } */ func keyboardWillShow(notification: NSNotification) { var info = notification.userInfo! var keyboardFrame: CGRect = (info[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue() let duration: NSTimeInterval = (info[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue ?? 0 var insets = self.sourceView.contentInset insets.bottom = keyboardFrame.size.height UIView.animateWithDuration(duration, animations: {_ in self.sourceView.contentInset = insets; } ) } func keyboardWillHide(notification: NSNotification) { var info = notification.userInfo! var keyboardFrame: CGRect = (info[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue() let duration: NSTimeInterval = (info[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue ?? 0 var insets = self.sourceView.contentInset insets.bottom = 0 UIView.animateWithDuration(duration, animations: {_ in self.sourceView.contentInset = insets; } ) } @IBAction func saveButtonPushed(sender: UIBarButtonItem) { object.text = sourceView.text object.isDirty = true self.navigationController?.popViewControllerAnimated(true) } @IBAction func doneButtonPushed(sender: UIBarButtonItem) { self.sourceView.resignFirstResponder() } private func showAssetSelector() { let storyboard: UIStoryboard = UIStoryboard(name: "ImageSelector", bundle: nil) let nav = storyboard.instantiateInitialViewController() as! UINavigationController let vc = nav.topViewController as! ImageSelectorTableViewController vc.blog = blog vc.delegate = self vc.showAlign = true vc.object = EntryImageItem() vc.entry = entry self.presentViewController(nav, animated: true, completion: nil) } @IBAction func cameraButtonPushed(sender: UIBarButtonItem) { self.showAssetSelector() } func AddAssetDone(controller: AddAssetTableViewController, asset: Asset) { self.dismissViewControllerAnimated(true, completion: nil) let vc = controller as! ImageSelectorTableViewController let item = vc.object item.asset = asset let align = controller.imageAlign object.assets.append(asset) self.sourceView.replaceRange(self.sourceView.selectedTextRange!, withText: asset.imageHTML(align)) } @IBAction func backButtonPushed(sender: UIBarButtonItem) { if self.sourceView.text == object.text { self.navigationController?.popViewControllerAnimated(true) return } Utils.confrimSave(self) } @IBAction func previewButtonPushed(sender: UIBarButtonItem) { let vc = PreviewViewController() let nav = UINavigationController(rootViewController: vc) var html = "<!DOCTYPE html><html><head><title>Preview</title><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"></head><body>" html += self.sourceView.text html += "</body></html>" vc.html = html self.presentViewController(nav, animated: true, completion: nil) } }
30adad99282aa3232baa6adf3cd73bf3
40.348837
162
0.686586
false
false
false
false
dPackumar/FlexiCollectionViewLayout
refs/heads/master
Example/swift/FlexiCollectionViewLayout/ViewController.swift
mit
1
// // ViewController.swift // FlexiCollectionViewLayout // // Created by Deepak Kumar on 11/13/16. // Copyright © 2016 Deepak Kumar. All rights reserved. // import UIKit import FlexiCollectionViewLayout internal let cellReuseIdentifier = "HKCellReuseID" /** Example project to get started with FlexiCollectionViewLayout */ final class ViewController: UICollectionViewController { fileprivate let hongKongPhotos = [UIImage(named: "beach"), UIImage(named: "boat"),UIImage(named: "brucelee"),UIImage(named: "dragonboat"),UIImage(named: "icc"),UIImage(named: "icclightshow"),UIImage(named: "ifc"),UIImage(named: "island"),UIImage(named: "lantau"),UIImage(named: "oceanpark"),UIImage(named: "orange"),UIImage(named: "panda"),UIImage(named: "sunset"),UIImage(named: "thepeak"),UIImage(named: "tram")] fileprivate let interItemSpacing: CGFloat = 2 fileprivate let edgeInsets = UIEdgeInsets.zero override func viewDidLoad() { super.viewDidLoad() let layout = FlexiCollectionViewLayout() collectionView?.collectionViewLayout = layout registerSupplementaryViews() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } private func registerSupplementaryViews() { collectionView?.register(UINib(nibName: "HeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "HeaderReuseID") collectionView?.register(UINib(nibName: "FooterView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: "FooterReuseID") } //MARK: Helpers fileprivate func cellWidth() -> CGFloat { return (self.collectionView!.bounds.size.width - (interItemSpacing * 2) - edgeInsets.left - edgeInsets.right ) / 3 } } //MARK: UICollectionViewDatasource extension ViewController { override func numberOfSections(in collectionView: UICollectionView) -> Int { return 3 } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { switch section { case 0: return 28 case 1: return 20 default: return 24 } } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellReuseIdentifier, for: indexPath) as! HKCell cell.imageView.image = hongKongPhotos[indexPath.item % hongKongPhotos.count] cell.infoLabel.text = "Image \(indexPath.row)" return cell } override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { if kind == UICollectionElementKindSectionHeader { let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "HeaderReuseID", for: indexPath) as! HeaderView headerView.headerLabel.text = "Section \(indexPath.section)" return headerView } else if kind == UICollectionElementKindSectionFooter { let footerView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionFooter, withReuseIdentifier: "FooterReuseID", for: indexPath) as! FooterView footerView.footerLabel.text = "Footer \(indexPath.section)" return footerView } return UICollectionReusableView() } } //MARK: FlexiCollectionViewLayoutDelegate extension ViewController: FlexiCollectionViewLayoutDelegate { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: FlexiCollectionViewLayout, sizeForFlexiItemAt indexPath: IndexPath) -> ItemSizeAttributes { let size = CGSize(width: cellWidth(), height: 100) switch indexPath.row { case 0: return ItemSizeAttributes(itemSize: size, layoutSize: .large, widthFactor: 2, heightFactor: 2) case 1: return ItemSizeAttributes(itemSize: size, layoutSize: .regular, widthFactor: 1, heightFactor: 1) case 2: return ItemSizeAttributes(itemSize: size, layoutSize: .regular, widthFactor: 1, heightFactor: 1) case 3: return ItemSizeAttributes(itemSize: size, layoutSize: .large, widthFactor: 3, heightFactor: 1) case 4: return ItemSizeAttributes(itemSize: size, layoutSize: .large, widthFactor: 1, heightFactor: 3) case 5: return ItemSizeAttributes(itemSize: size, layoutSize: .regular, widthFactor: 1, heightFactor: 1) case 6: return ItemSizeAttributes(itemSize: size, layoutSize: .regular, widthFactor: 1, heightFactor: 1) case 7: return ItemSizeAttributes(itemSize: size, layoutSize: .large, widthFactor: 2, heightFactor: 1) case 8: return ItemSizeAttributes(itemSize: size, layoutSize: .regular, widthFactor: 1, heightFactor: 1) case 9: return ItemSizeAttributes(itemSize: size, layoutSize: .regular, widthFactor: 1, heightFactor: 1) case 10: return ItemSizeAttributes(itemSize: size, layoutSize: .large, widthFactor: 1, heightFactor: 2) case 11: return ItemSizeAttributes(itemSize: size, layoutSize: .large, widthFactor: 2, heightFactor: 2) default: return ItemSizeAttributes(itemSize: size, layoutSize: .regular, widthFactor: 1, heightFactor: 1) } /** if indexPath.item % 6 == 0 { return ItemSizeAttributes(itemSize: size, layoutSize: .large, widthFactor: 2, heightFactor: 2) } return ItemSizeAttributes(itemSize: size, layoutSize: .regular, widthFactor: 1, heightFactor: 1) */ } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return edgeInsets } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return interItemSpacing } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, heightForFooterInSection section: Int) -> CGFloat { return 45 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, heightForHeaderInSection section: Int) -> CGFloat { return 45 } }
6931e84b8ff82b2ee6d8dce0017caf46
46.573427
418
0.702631
false
false
false
false
narner/AudioKit
refs/heads/master
Examples/iOS/SongProcessor/SongProcessor/View Controllers/PitchShifterViewController.swift
mit
1
// // PitchShifterViewController.swift // SongProcessor // // Created by Elizabeth Simonian on 10/17/16. // Copyright © 2016 AudioKit. All rights reserved. // import AudioKit import AudioKitUI import UIKit class PitchShifterViewController: UIViewController { @IBOutlet private weak var pitchSlider: AKSlider! @IBOutlet private weak var mixSlider: AKSlider! let songProcessor = SongProcessor.sharedInstance override func viewDidLoad() { super.viewDidLoad() pitchSlider.range = -24 ... 24 pitchSlider.value = songProcessor.pitchShifter.shift mixSlider.value = songProcessor.pitchMixer.balance mixSlider.callback = updateMix pitchSlider.callback = updatePitch } func updatePitch(value: Double) { songProcessor.pitchShifter.shift = value } func updateMix(value: Double) { songProcessor.pitchMixer.balance = value } }
1f6bdd6e0878703674c061220c6c71a0
21.658537
60
0.70183
false
false
false
false
3DprintFIT/octoprint-ios-client
refs/heads/dev
OctoPhone/View Related/Detail/View/JobStateCell.swift
mit
1
// // JobStateCell.swift // OctoPhone // // Created by Josef Dolezal on 01/05/2017. // Copyright © 2017 Josef Dolezal. All rights reserved. // import UIKit import SnapKit import ReactiveSwift /// Cell with job state class JobStateCell: UICollectionViewCell, TypedCell { /// Reuse identifier of cell static let identifier = "JobStateCell" // MARK: Public API /// Label for job state let stateLabel: UILabel = { let label = UILabel() label.font = UIFont.preferredFont(forTextStyle: .headline) label.textAlignment = .center return label }() // MARK: Private properties // MARK: Initializers override init(frame: CGRect) { super.init(frame: frame) contentView.addSubview(stateLabel) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: Cell lifecycle override func layoutSubviews() { super.layoutSubviews() stateLabel.snp.makeConstraints { make in make.edges.equalToSuperview() } } // MARK: Internal logic }
168c3f319c1c4f49cf11514d604434c8
19.25
66
0.637566
false
false
false
false
ps2/rileylink_ios
refs/heads/dev
OmniKitUI/Views/SetupCompleteView.swift
mit
1
// // SetupCompleteView.swift // OmniKit // // Created by Pete Schwamb on 3/2/21. // Copyright © 2021 LoopKit Authors. All rights reserved. // import SwiftUI import LoopKitUI struct SetupCompleteView: View { @Environment(\.verticalSizeClass) var verticalSizeClass @Environment(\.appName) private var appName private var onSaveScheduledExpirationReminder: ((_ selectedDate: Date?, _ completion: @escaping (_ error: Error?) -> Void) -> Void)? private var didFinish: () -> Void private var didRequestDeactivation: () -> Void private var dateFormatter: DateFormatter @State private var scheduledReminderDate: Date? @State private var scheduleReminderDateEditViewIsShown: Bool = false var allowedDates: [Date] init(scheduledReminderDate: Date?, dateFormatter: DateFormatter, allowedDates: [Date], onSaveScheduledExpirationReminder: ((_ selectedDate: Date?, _ completion: @escaping (_ error: Error?) -> Void) -> Void)?, didFinish: @escaping () -> Void, didRequestDeactivation: @escaping () -> Void) { self._scheduledReminderDate = State(initialValue: scheduledReminderDate) self.dateFormatter = dateFormatter self.allowedDates = allowedDates self.onSaveScheduledExpirationReminder = onSaveScheduledExpirationReminder self.didFinish = didFinish self.didRequestDeactivation = didRequestDeactivation } var body: some View { GuidePage(content: { VStack { LeadingImage("Pod") Text(String(format: LocalizedString("Your Pod is ready for use.\n\n%1$@ will remind you to change your pod before it expires. You can change this to a time convenient for you.", comment: "Format string for instructions for setup complete view. (1: app name)"), appName)) .fixedSize(horizontal: false, vertical: true) Divider() VStack(alignment: .leading) { Text("Scheduled Reminder") Divider() NavigationLink( destination: ScheduledExpirationReminderEditView( scheduledExpirationReminderDate: scheduledReminderDate, allowedDates: allowedDates, dateFormatter: dateFormatter, onSave: { (newDate, completion) in onSaveScheduledExpirationReminder?(newDate) { (error) in if error == nil { scheduledReminderDate = newDate } completion(error) } }, onFinish: { scheduleReminderDateEditViewIsShown = false }), isActive: $scheduleReminderDateEditViewIsShown) { RoundedCardValueRow( label: LocalizedString("Time", comment: "Label for expiration reminder row"), value: scheduledReminderDateString(scheduledReminderDate), highlightValue: false ) } } } .padding(.bottom, 8) .accessibility(sortPriority: 1) }) { Button(action: { didFinish() }) { Text(LocalizedString("Finish Setup", comment: "Action button title to continue at Setup Complete")) .actionButtonStyle(.primary) } .padding() .background(Color(UIColor.systemBackground)) .zIndex(1) } .animation(.default) .navigationBarTitle("Setup Complete", displayMode: .automatic) } private func scheduledReminderDateString(_ scheduledDate: Date?) -> String { if let scheduledDate = scheduledDate { return dateFormatter.string(from: scheduledDate) } else { return LocalizedString("No Reminder", comment: "Value text for no expiration reminder") } } } struct SetupCompleteView_Previews: PreviewProvider { static var previews: some View { SetupCompleteView( scheduledReminderDate: Date(), dateFormatter: DateFormatter(), allowedDates: [Date()], onSaveScheduledExpirationReminder: { (date, completion) in }, didFinish: { }, didRequestDeactivation: { } ) } }
5dc7ffc7add5c77c068f47eb6f49c792
40.150442
291
0.563871
false
false
false
false
klesh/cnodejs-swift
refs/heads/master
CNode/Options/MessagesCell.swift
apache-2.0
1
// // MessagesCell.swift // CNode // // Created by Klesh Wong on 1/11/16. // Copyright © 2016 Klesh Wong. All rights reserved. // import UIKit import SwiftyJSON protocol MessagesCellDelegate : class { func avatarTapped(author: String, cell: MessagesCell) } class MessagesCell : UITableViewCell { @IBOutlet weak var theAvatar: UIButton! @IBOutlet weak var theAuthor: UILabel! @IBOutlet weak var theType: UILabel! @IBOutlet weak var theElapse: UILabel! @IBOutlet weak var theReply: UIWebView! @IBOutlet weak var theContent: CNWebView! @IBOutlet weak var theTopic: UILabel! weak var delegate: MessagesCellDelegate? override func awakeFromNib() { super.awakeFromNib() Utils.circleUp(theAvatar) } func bind(message: JSON) { theAvatar.kf_setImageWithURL(Utils.toURL(message["author"]["avatar_url"].string), forState: .Normal) theAuthor.text = message["author"]["loginname"].string theTopic.text = message["topic"]["title"].string let hasReply = nil != message["reply"]["id"].string if message["type"].stringValue == "at" { if hasReply { theType.text = "在回复中@了你" } else { theType.text = "在主题中@了你" } } else { theType.text = "回复了您的话题" } if hasReply { theElapse.text = Utils.relativeTillNow(message["reply"]["create_at"].stringValue.toDateFromISO8601()) theContent.loadHTMLAsPageOnce(message["reply"]["content"].stringValue, baseURL: ApiClient.BASE_URL) } else { theElapse.text = Utils.relativeTillNow(message["topic"]["last_reply_at"].stringValue.toDateFromISO8601()) theContent.hidden = true } let textColor = message["has_read"].boolValue ? UIColor.darkGrayColor() : UIColor.darkTextColor() theAuthor.textColor = textColor theType.textColor = textColor theElapse.textColor = textColor theTopic.textColor = textColor } @IBAction func avatarDidTapped(sender: AnyObject) { if let d = delegate { d.avatarTapped(theAuthor.text!, cell: self) } } }
29ba5134e4e5468df047685de14df765
31.271429
117
0.616202
false
false
false
false
KDE/krita
refs/heads/master
krita/integration/quicklookng/ThumbnailProvider.swift
gpl-3.0
1
/* * This file is part of Krita * * Copyright (c) 2020 L. E. Segovia <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. */ import AppKit import QuickLookThumbnailing class ThumbnailProvider: QLThumbnailProvider { override func provideThumbnail(for request: QLFileThumbnailRequest, _ handler: @escaping (QLThumbnailReply?, Error?) -> Void) { // There are three ways to provide a thumbnail through a QLThumbnailReply. Only one of them should be used. // First way: Draw the thumbnail into the current context, set up with UIKit's coordinate system. /* handler(QLThumbnailReply(contextSize: request.maximumSize, currentContextDrawing: { () -> Bool in // Draw the thumbnail here. // Return true if the thumbnail was successfully drawn inside this block. return true }), nil) */ // Second way: Draw the thumbnail into a context passed to your block, set up with Core Graphics's coordinate system. handler(QLThumbnailReply(contextSize: request.maximumSize, drawing: { (context: CGContext) -> Bool in // Draw the thumbnail here. var appPlist = UnzipTask(request.fileURL.path, "preview.png") // Not made with Krita. Find ORA thumbnail instead. if (appPlist == nil || appPlist!.isEmpty) { appPlist = UnzipTask(request.fileURL.path, "Thumbnails/thumbnail.png"); } if (appPlist != nil && !appPlist!.isEmpty) { let appIcon = NSImage.init(data: appPlist!); let rep = appIcon!.representations.first!; var renderRect = NSMakeRect(0.0, 0.0, CGFloat(rep.pixelsWide), CGFloat(rep.pixelsHigh)); let cgImage = appIcon?.cgImage(forProposedRect: &renderRect, context: nil, hints: nil); context.draw(cgImage!, in: renderRect); } else { return false; } // Return true if the thumbnail was successfully drawn inside this block. return true }), nil) // Third way: Set an image file URL. /* handler(QLThumbnailReply(imageFileURL: Bundle.main.url(forResource: "fileThumbnail", withExtension: "jpg")!), nil) */ } }
e601b942b2f5640e8bdbcd21b7dc7b17
39
131
0.65473
false
false
false
false
chai2010/ptyy
refs/heads/master
ios-app/yjyy-swift/DataEngin.swift
bsd-3-clause
1
// Copyright 2016 <chaishushan{AT}gmail.com>. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. import UIKit extension String { subscript (i: Int) -> Character { return self[self.startIndex.advancedBy(i)] } subscript (i: Int) -> String { return String(self[i] as Character) } subscript (r: Range<Int>) -> String { let start = startIndex.advancedBy(r.startIndex) let end = start.advancedBy(r.endIndex - r.startIndex) return self[Range(start ..< end)] } } // 导入Go语言函数 @_silgen_name("YjyySearch") func GoYjyySearch(query:UnsafePointer<CChar>, limits:Int32) -> UnsafeMutablePointer<CChar> class DataEngin { let cache = LRUCache<String, [String]>(capacity: 16) let cacheV2 = LRUCache<String, [[String]]>(capacity: 16) // 失败的查询(对于非正则只要包含, 则必然是失败的) // 正则的特例: .*?| let failedQueryCache = LRUCache<String, Bool>(capacity: 64) // 判断是非是失败的查询 private func assertFailedQuery(query:String) -> Bool { // 1. 如果完全包含, 则必然是失败的查询 if self.failedQueryCache[query] != nil { return true } // 2. 查看是否是失败集合的子集 for (key, _) in self.failedQueryCache.Map() { if query.rangeOfString(key) != nil{ return true } } // 不确定是否失败 return false } // 注册失败的查询 private func addFailedQuery(query:String) { // 正则的特例: .*?| for c in query.characters { for x in ".*?|。*?|".characters { if c == x { return } } } if self.assertFailedQuery(query) { return } self.failedQueryCache[query] = true } func SearchV2(rawQuery:String) -> [[String]] { // 删除空白 let query = rawQuery.stringByTrimmingCharactersInSet( NSCharacterSet.whitespaceAndNewlineCharacterSet() ) // 已经缓存成功的查询 if let result = self.cacheV2[query] { return result } var resultMap = [String: [String]]() let letters : NSString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ#" for i in 0..<letters.length { let c = letters.characterAtIndex(i) resultMap[String(UnicodeScalar(c))] = [] } // 执行查询 var resultTemp = [String]() // 如果不确定是失败的查询, 则进行查询操作 if !self.assertFailedQuery(query) { resultTemp = self.Search(query) } // 处理查询结果 for s in resultTemp { if !s.isEmpty { let key = self.getFistLetter(s) resultMap[key]!.append(s) } } var resultList = [[String]]() for i in 0..<letters.length { let c = letters.characterAtIndex(i) resultList.append(resultMap[String(UnicodeScalar(c))]!) } // 缓存成功和失败的查询 if resultTemp.isEmpty { self.addFailedQuery(query) } else { self.cacheV2[query] = resultList } return resultList } func Search(query:String) -> [String] { if let result = self.cache[query] { return result } let p = GoYjyySearch(query, limits: 0) let s = String.fromCString(p)! p.dealloc(1) let result = s.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet()) self.cache[query] = result return result } // 拼音首字母, [A-Z]# func getFistLetter(str: String)-> String { if str.isEmpty { return "#" } // 多音字: 长沙/涡阳/厦门 if str[0] == "长" { return "C" } if str[0] == "涡" { return "G" } if str[0] == "厦" { return "X" } let mutStr = NSMutableString(string: str) as CFMutableString // 取得带音调拼音 if CFStringTransform(mutStr, nil,kCFStringTransformMandarinLatin, false) { // 取得不带音调拼音 if CFStringTransform(mutStr, nil, kCFStringTransformStripDiacritics, false) { let pinyin = (mutStr as String).uppercaseString if pinyin.characters.count > 0 { if pinyin[0] >= "A" && pinyin[0] <= "Z"{ return pinyin[0] } } } } return "#" } }
a6feaf5079ca5125597ec78fb27304f7
20.211765
91
0.653078
false
false
false
false
itsaboutcode/WordPress-iOS
refs/heads/develop
WordPress/Classes/ViewRelated/System/AdaptiveNavigationController.swift
gpl-2.0
2
import Foundation import WordPressShared /// This UINavigationController subclass will take care, automatically, of hiding the UINavigationBar /// whenever: /// /// - We're running on an iPad Device /// - The presentation style is not set to fullscreen (AKA "we're in Popover Mode!") /// /// Note that we won't hide the NavigationBar on iPhone devices, since the *Plus* devices, in landscape mode, /// do render the presentedView within a popover, but you cannot actually dismiss it, by tapping over the /// gray area. /// class AdaptiveNavigationController: UINavigationController { /// Insets to be applied on the SourceView's Coordinates, in order to fine tune the Popover's arrow position. /// private let sourceInsets = CGVector(dx: -10, dy: 0) /// This is the main method of this helper: we'll set both, the Presentation Style, Presentation Delegate, /// and SourceView parameters, accordingly. /// /// - Parameter presentingView: UIView instance from which the popover will be shown /// @objc func configurePopoverPresentationStyle(from sourceView: UIView) { modalPresentationStyle = .popover guard let presentationController = popoverPresentationController else { fatalError() } presentationController.sourceRect = sourceView.bounds.insetBy(dx: sourceInsets.dx, dy: sourceInsets.dy) presentationController.sourceView = sourceView presentationController.permittedArrowDirections = .any presentationController.delegate = self } } // MARK: - UIPopoverPresentationControllerDelegate Methods // extension AdaptiveNavigationController: UIPopoverPresentationControllerDelegate { func presentationController(_ presentationController: UIPresentationController, willPresentWithAdaptiveStyle style: UIModalPresentationStyle, transitionCoordinator: UIViewControllerTransitionCoordinator?) { guard let navigationController = presentationController.presentedViewController as? UINavigationController else { return } let hidesNavigationBar = style != .fullScreen && WPDeviceIdentification.isiPad() navigationController.navigationBar.isHidden = hidesNavigationBar } }
09280d686272e8036c445535d86f8eb6
41.169811
210
0.745861
false
false
false
false
wayfindrltd/wayfindr-demo-ios
refs/heads/master
Wayfindr Demo/Classes/Controller/Developer/MissingKeyRoutesTableViewController.swift
mit
1
// // MissingKeyRoutes.swift // Wayfindr Demo // // Created by Wayfindr on 18/11/2015. // Copyright (c) 2016 Wayfindr (http://www.wayfindr.net) // // 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 SwiftGraph import SVProgressHUD /// Table view for displaying any missing key routes (i.e. those between platforms and exits). final class MissingKeyRoutesTableViewController: UITableViewController { // MARK: - Properties /// Reuse identifier for the table cells. fileprivate let reuseIdentifier = "RouteCell" /// Model representation of entire venue. fileprivate let venue: WAYVenue /// Whether the controller is still computing missing routes. fileprivate var parsingData = true /// Array of all the currently missing routes (or a congratulations message if there are none). fileprivate var missingRoutes = [String]() // MARK: - Intiailizers / Deinitializers /** Initializes a `MissingKeyRoutesTableViewController`. - parameter venue: Model representation of entire venue. */ init(venue: WAYVenue) { self.venue = venue super.init(style: .plain) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - View Lifecycle override func viewDidLoad() { super.viewDidLoad() tableView.register(UITableViewCell.self, forCellReuseIdentifier: reuseIdentifier) tableView.estimatedRowHeight = WAYConstants.WAYSizes.EstimatedCellHeight tableView.rowHeight = UITableView.automaticDimension title = WAYStrings.MissingKeyRoutes.MissingRoutes SVProgressHUD.show() DispatchQueue.global(qos: DispatchQoS.QoSClass.background).async(execute: { [weak self] in self?.determineMissingRoutes() self?.parsingData = false DispatchQueue.main.async(execute: { SVProgressHUD.dismiss() self?.tableView.reloadData() }) }) } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) SVProgressHUD.dismiss() } // MARK: - Setup /** Calculates all the missing key routes (those between platforms and exits) and adds them to the `missingRoutes` array. */ fileprivate func determineMissingRoutes() { let venueGraph = venue.destinationGraph // Routes starting at a platform for startPlatform in venue.platforms { let startNode = startPlatform.exitNode for platform in venue.platforms { if startPlatform.name == platform.name { continue } let destinationNode = platform.entranceNode if !venueGraph.canRoute(startNode, toNode: destinationNode) { let newMissingRoute = "Platform \(startPlatform.name) to Platform \(platform.name)" missingRoutes.append(newMissingRoute) } } // Next platform for exit in venue.exits { let destinationNode = exit.entranceNode if !venueGraph.canRoute(startNode, toNode: destinationNode) { let newMissingRoute = "Platform \(startPlatform.name) to Exit \(exit.name)" missingRoutes.append(newMissingRoute) } } // Next exit } // Next startPlatform // Routes starting at an exit for startExit in venue.exits { let startNode = startExit.exitNode for platform in venue.platforms { let destinationNode = platform.entranceNode if !venueGraph.canRoute(startNode, toNode: destinationNode) { let newMissingRoute = "Entrance \(startExit.name) to Platform \(platform.name)" missingRoutes.append(newMissingRoute) } } // Next platform for exit in venue.exits { if startExit.name == exit.name { continue } let destinationNode = exit.entranceNode if !venueGraph.canRoute(startNode, toNode: destinationNode) { let newMissingRoute = "Entrance \(startExit.name) to Exit \(exit.name)" missingRoutes.append(newMissingRoute) } } // Next exit } // Next startExit if missingRoutes.isEmpty { missingRoutes.append(WAYStrings.MissingKeyRoutes.Congratulations) } } // MARK: - UITableViewDatasource override func numberOfSections(in tableView: UITableView) -> Int { return parsingData ? 0 : 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return missingRoutes.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath) cell.textLabel?.text = missingRoutes[indexPath.row] cell.textLabel?.numberOfLines = 0 cell.textLabel?.lineBreakMode = .byWordWrapping return cell } // MARK: - UITableViewDelegate override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) } }
82a72984d49cc7283091c7fd5745fd72
34.671875
123
0.620675
false
false
false
false
Wei-Xia/TVMLKitchen
refs/heads/swift2.2
Sources/Recipes/CatalogRecipe.swift
mit
1
// // CatalogRecipe.swift // TVMLKitchen // // Created by toshi0383 on 3/19/16. // Copyright © 2016 toshi0383. All rights reserved. // import Foundation // MARK: Content and Section public struct Section { struct Content { let title: String let thumbnailURL: String let actionID: String? let templateFileName: String? let width: Int let height: Int } public typealias ContentTuple = (title: String, thumbnailURL: String, actionID: String?, templateFileName: String?, width: Int, height: Int) let title: String let contents: [Content] public init(title: String, args: [ContentTuple]) { self.title = title self.contents = args.map(Content.init) } public init(title: String, args: ContentTuple...) { self.title = title self.contents = args.map(Content.init) } } extension Section: CustomStringConvertible { public var description: String { var xml = "" xml += "<listItemLockup>" xml += "<title class=\"kitchen_highlight_bg\" >\(title)</title>" xml += "<decorationLabel class=\"kitchen_highlight_bg\" >\(contents.count)</decorationLabel>" xml += "<relatedContent>" xml += "<grid>" xml += "<section>" xml += contents.map{ content in var xml = "" if let actionID = content.actionID { xml += "<lockup actionID=\"\(actionID)\" >" } else if let templateFileName = content.templateFileName { xml += "<lockup template=\"\(templateFileName)\" >" } xml += "<img src=\"\(content.thumbnailURL)\" " xml += "width=\"\(content.width)\" height=\"\(content.height)\" />" xml += "<title class=\"kitchen_no_highlight_bg\">\(content.title)</title>" xml += "</lockup>" return xml }.joinWithSeparator("") xml += "</section>" xml += "</grid>" xml += "</relatedContent>" xml += "</listItemLockup>" return xml } } public struct CatalogRecipe: TemplateRecipeType { let banner: String let sections: [Section] public var theme = BlackTheme() public var presentationType: PresentationType public init(banner: String, sections: [Section], presentationType: PresentationType = .Default) { self.banner = banner self.sections = sections self.presentationType = presentationType } public var template: String { var xml = "" xml += "<catalogTemplate>" /// Top Banner xml += "<banner>" xml += "<title>\(banner)</title>" xml += "</banner>" /// Section and Contents xml += "<list>" xml += "<section>" xml += "<header>" xml += "<title></title>" xml += "</header>" xml += sections.map{"\($0)"}.joinWithSeparator("") xml += "</section>" xml += "</list>" xml += "</catalogTemplate>" return xml } }
e724017b155648810eccd9fbe575edef
27.570093
101
0.554792
false
false
false
false
KeepGoing2016/Swift-
refs/heads/master
DUZB_XMJ/DUZB_XMJ/Classes/Home/View/IconCollectionViewCell.swift
apache-2.0
1
// // IconCollectionViewCell.swift // DUZB_XMJ // // Created by user on 16/12/28. // Copyright © 2016年 XMJ. All rights reserved. // import UIKit import Alamofire class IconCollectionViewCell: UICollectionViewCell { @IBOutlet weak var iconImg: UIImageView! @IBOutlet weak var iconL: UILabel! var dataM:CellGroupModel?{ didSet{ iconL.text = dataM?.tag_name // guard let iconUrl = URL(string:(dataM?.icon_url)!) else { // return // } // iconImg.kf.setImage(with: iconUrl, placeholder: UIImage(named: "home_more_btn")) if let iconUrl = URL(string: dataM?.icon_url ?? "") { iconImg.kf.setImage(with: iconUrl, placeholder: UIImage(named: "home_more_btn")) }else{ iconImg.image = UIImage(named: "home_more_btn") } } } override func layoutSubviews() { super.layoutSubviews() iconImg.layer.cornerRadius = 22 iconImg.layer.masksToBounds = true } override func awakeFromNib() { super.awakeFromNib() } }
5e876ae4441ac865d7f6a90ef0ca12f2
26.365854
96
0.582888
false
false
false
false
nutletor/Start_Swift
refs/heads/master
SwiftNotesPlayground/2_02 Basic Operators.playground/Contents.swift
mit
2
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" //基本运算符(Basic Operators) //术语 //运算符有一元、二元和三元运算符。 //• 一元运算符对单一操作对象操作(如 -a )。一元运算符分前置运算符和后置运算符,前置运算符需紧跟在操 作对象之前(如 !b ),后置运算符需紧跟在操作对象之后(如 i++ )。 //• 二元运算符操作两个操作对象(如 2 + 3 ),是中置的,因为它们出现在两个操作对象之间。 //• 三元运算符操作三个操作对象,和 C 语言一样,Swift 只有一个三元运算符,就是三目运算符( a ? b : c)。 //受运算符影响的值叫操作数,在表达式 1 + 2 中,加号 + 是二元运算符,它的两个操作数是值 1 和 2 。 //赋值运算符 //如果赋值的右边是一个多元组,它的元素可以马上被分解成多个常量或变量: let (x, y) = (1, 2) // 现在 x 等于 1, y 等于 2 //与 C 和 OC 不同,Swift 的赋值操作并不返回任何值。 // if x = y { // 此句错误, 因为 x = y 并不返回任何值 // } //这个特性使你无法把( == )错写成( = ),由于 if x = y 是错误代码,Swift帮你避免此类错误的的发生。 //算术运算符 //Swift 中所有数值类型都支持了基本的四则运算: //• 加法(+) //• 减法(-) //• 乘法(*) //• 除法(/) //与 C 语言和 OC 不同的是,Swift 中算术运算符( + , - , * , / , % 等)会 检测并不允许值溢出,以此来避免保存变量时由于变量大于或小于其类型所能承载的范围时导致的异常结果。但是你可以使用 Swift 的溢出运算符来实现溢出运算(如 a &+ b ) //加法运算符也可用于 String 的拼接: "hello, " + "world" //求余运算符 //求余运算( a % b )是计算 b 的多少倍刚刚好可以容入 a ,返回多出来的那部分(余数)。 //注意:求余运算( % )在其他语言也叫取模运算。然而严格说来,我们看该运算符对负数的操作结果,"求余"比"取 模"更合适些。 9 % 4 -9 % 4 9 % -4 //在对负数 b 求余时, b 的符号会被忽略。这意味着 a % b 和 a % -b 的结果是相同的。 //浮点数求余计算 //不同于 C 和 OC,Swift 中是可以对浮点数进行求余的。 8 % 2.5 //结果是一个 Double 值 0.5 //自增和自减运算 //对变量本身加1或减1的自增( ++ )和自减( -- )的缩略算符,操作对象可以是整形和浮点型。 //++i是i = i + 1的简写;--i是i = i - 1的简写 //运算符即可修改了i的值也可以返回i的值 //当 ++ 前置的时候,先自増再返回;当 ++ 后置的时候,先返回再自增。 //一元负号运算符 //数值的正负号可以使用前缀 - (即一元负号)来切换: let three = 3 let minusThree = -three // minusThree 等于 -3 let plusThree = -minusThree // plusThree 等于 3, 或 "负负3" //一元正号运算符 //一元正号( + )不做任何改变地返回操作数的值: let minusSix = -6 let alsoMinusSix = +minusSix // alsoMinusSix 等于 -6 //组合赋值运算符(Compound Assignment Operators) var a = 1 a += 2 // a 现在是 3 //注意:复合赋值运算没有返回值, let b = a += 2 这类代码是错误 //比较运算符 //所有标准 C 语言中的比较运算都可以在 Swift 中使用: //• 等于( a == b ) //• 不等于( a != b ) //• 大于( a > b ) //• 小于( a < b ) //• 大于等于( a >= b ) //• 小于等于( a <= b ) //注意: Swift 也提供恒等 === 和不恒等 !== 来判断两个对象是否引用同一个对象实例。 //每个比较运算都返回了一个标识表达式是否成立的布尔值 //三目运算符(Ternary Conditional Operator) //三目运算符的特殊在于它是有三个操作数的运算符,它的原型是 问题 ? 答案1 : 答案2 //如果 问题 成立,返回 答案1 的结果; 如果不成立,返回 答案2 的结果。 //空合运算符(Nil Coalescing Operator) //空合运算符(a ?? b)将对可选类型 a 进行空判断,如果 a 包含一个值就进行解封,否则就返回一个默认值 b //该运算符有两个条件: //• 表达式 a 必须是Optional类型 //• 默认值 b 的类型必须要和 a 存储值的类型保持一致 //空合运算符是对以下代码的简短表达方法: //a != nil ? a! : b //注意: 如果 a 为非空值( non-nil ),那么值 b 将不会被估值。这也就是所谓的短路求值。 //区间运算符 //闭区间运算符 //闭区间运算符( a...b )定义一个包含从 a 到 b (包括 a 和 b )的所有值的区间, b 必须大于等于 a for index in 1...5 { print("\(index) * 5 = \(index * 5)") } // 1 * 5 = 5 // 2 * 5 = 10 // 3 * 5 = 15 // 4 * 5 = 20 // 5 * 5 = 25 //半开区间运算符 //半开区间( a..<b )定义一个从 a 到 b 但不包括 b 的区间 let names = ["Anna", "Alex", "Brian", "Jack"] let count = names.count for i in 0..<count { print("第 \(i + 1) 个人叫 \(names[i])") } // 第 1 个人叫 Anna // 第 2 个人叫 Alex // 第 3 个人叫 Brian // 第 4 个人叫 Jack //逻辑运算 //逻辑运算的操作对象是逻辑布尔值。Swift 支持基于 C 语言的三个标准逻辑运算。 // • 逻辑非(!a) // • 逻辑与( a && b ) // • 逻辑或( a || b ) //注意:逻辑或、逻辑与的短路计算 //逻辑运算符组合计算 // if enteredDoorCode && passedRetinaScan || hasDoorKey || knowsOverridePassword { // print("Welcome!") //} else { // print("ACCESS DENIED") //} //无论怎样, && 和 || 始终只能操作两个值。所以这实际是三个简单逻辑连续操作的结果。 //注意: Swift 逻辑操作符 && 和 || 是左结合的,这意味着拥有多元逻辑操作符的复合表达式优先计算最左边的子表达式。 //为了一个复杂表达式更容易读懂,在合适的地方使用括号()来明确优先级是很有效的
9f992d6af604c42ead71ef2fa123f9a8
21.328767
140
0.621166
false
false
false
false
Chriskuei/Bon-for-Mac
refs/heads/master
Bon/BonConfig.swift
mit
1
// // BonConfig.swift // Bon // // Created by Chris on 16/4/19. // Copyright © 2016年 Chris. All rights reserved. // import Cocoa import Foundation class BonConfig { static let appGroupID: String = "group.chriskuei.Bon" static let BonFont: String = "Avenir Book" //static let ScreenWidth: CGFloat = UIScreen.mainScreen().bounds.width //static let ScreenHeight: CGFloat = UIScreen.mainScreen().bounds.height struct BonNotification { static let GetOnlineInfo = "GetOnlineInfo" static let ShowLoginView = "ShowLoginView" static let HideLoginView = "ShowLoginView" } }
bdafa166f33eb47866d5325b1fb0ea6e
23.538462
76
0.673469
false
true
false
false
bm842/Brokers
refs/heads/master
Sources/PlaybackOrder.swift
mit
2
/* The MIT License (MIT) Copyright (c) 2016 Bertrand Marlier Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE */ import Foundation public class PlaybackOrder: GenericOrder, Order { public func modify(change parameters: [OrderParameter], completion: @escaping (RequestStatus) -> ()) { let playbackInstrument = instrument as! PlaybackInstrument guard let tick = playbackInstrument.currentTick else { completion(PlaybackStatus.noTick) return } for param in parameters { switch param { case .stopLoss(let price): self.stopLoss = price case .takeProfit(let price): self.takeProfit = price case .entry(let price): self.entry = price! case .expiry(let time): self.expiry = time! // expiry is mandatory in working orders } } modify(atTime: tick.time, parameters: parameters) completion(PlaybackStatus.success) } public override func cancel(_ completion: @escaping (RequestStatus) -> ()) { let playbackInstrument = instrument as! PlaybackInstrument guard let tick = playbackInstrument.currentTick else { completion(PlaybackStatus.noTick) return } super.cancel(completion) genericInstrument.notify(tradeEvent: .orderClosed(info: OrderClosure(orderId: id, time: tick.time, reason: .cancelled))) completion(PlaybackStatus.success) } }
b2768a1a33fec95219248b355953606a
34.739726
128
0.669222
false
false
false
false
Shun87/OpenAdblock
refs/heads/master
Open Adblock/Open Adblock/RulesViewController.swift
apache-2.0
5
// // RulesViewController.swift // Open Adblock // // Created by Saagar Jha on 8/14/15. // Copyright © 2015 OpenAdblock. All rights reserved. // import UIKit class RulesViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { let cellIdentifer = "rule" @IBOutlet weak var rulesTableView: UITableView! { didSet { rulesTableView.delegate = self } } var rules: [String]! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. rules = Adblocker.sharedInstance.ruleNames navigationController?.setToolbarHidden(false, animated: false) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { //print(rules) //return 0 return rules.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifer) as UITableViewCell! cell.textLabel?.text = rules[indexPath.row] return cell } /* // 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. } */ }
b5a47be562f58559a5fa43055aea9745
27.983871
109
0.670006
false
false
false
false
MadArkitekt/Swift_Tutorials_And_Demos
refs/heads/master
CustomSwiftUI/techEdGradientPreview/GradientView.swift
gpl-2.0
1
// // GradientView.swift // CustomSwiftUI // // Created by Edward Salter on 9/19/14. // Copyright (c) 2014 Edward Salter. All rights reserved. // import UIKit import QuartzCore @IBDesignable class GradientView: UIView { @IBInspectable var startColor: UIColor = UIColor.whiteColor() { didSet{ setupView() } } @IBInspectable var endColor: UIColor = UIColor.blackColor() { didSet{ setupView() } } @IBInspectable var isHorizontal: Bool = false { didSet{ setupView() } } @IBInspectable var roundness: CGFloat = 0.0 { didSet{ setupView() } } //MARK: Overrides override class func layerClass()->AnyClass { return CAGradientLayer.self } override init(frame: CGRect) { super.init(frame: frame) setupView() } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupView() } //MARK: Framework Funcs private func setupView() { let colors:Array<AnyObject> = [startColor.CGColor, endColor.CGColor] gradientLayer.colors = colors gradientLayer.cornerRadius = roundness gradientLayer.startPoint = CGPoint(x:0, y:0) if (isHorizontal) { gradientLayer.endPoint = CGPoint(x:1, y:0) }else{ gradientLayer.endPoint = CGPoint(x:0, y:1) } self.setNeedsDisplay() } //MARK: Main Layer = CAGradientLayer var gradientLayer: CAGradientLayer { return layer as CAGradientLayer } }
3d1069cdff47ae99fcd82ee27818f46c
22.428571
76
0.581098
false
false
false
false
cuappdev/podcast-ios
refs/heads/master
Recast/iTunesPodcasts/Models/RSS/Episode.swift
mit
1
// // RSSFeedItem.swift // // Copyright (c) 2016 - 2018 Nuno Manuel Dias // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Foundation // MARK: - Equatable extension Episode { public static func == (lhs: Episode, rhs: Episode) -> Bool { return lhs.author == rhs.author && lhs.categories == rhs.categories && lhs.comments == rhs.comments && lhs.content == rhs.content && lhs.descriptionText == rhs.descriptionText && lhs.enclosure == rhs.enclosure && lhs.guid == rhs.guid && lhs.iTunes == rhs.iTunes && lhs.pubDate == rhs.pubDate && lhs.source == rhs.source && lhs.title == rhs.title } }
a4f40a5d6bda24be14b7914c0d113aaa
37.934783
82
0.668342
false
false
false
false
hovansuit/FoodAndFitness
refs/heads/master
FoodAndFitness/Controllers/TrackingDetail/TrackingDetailController.swift
mit
1
// // TrackingDetailController.swift // FoodAndFitness // // Created by Mylo Ho on 5/29/17. // Copyright © 2017 SuHoVan. All rights reserved. // import MapKit import UIKit import CoreLocation class TrackingDetailController: BaseViewController { @IBOutlet fileprivate(set) weak var mapView: MKMapView! @IBOutlet fileprivate(set) weak var activeLabel: UILabel! @IBOutlet fileprivate(set) weak var durationLabel: UILabel! @IBOutlet fileprivate(set) weak var distanceLabel: UILabel! var viewModel: TrackingDetailViewModel! struct Data { var active: String var duration: String var distance: String } var data: Data? { didSet { guard let data = data else { return } activeLabel.text = data.active durationLabel.text = data.duration distanceLabel.text = data.distance } } override func setupUI() { super.setupUI() title = Strings.tracking configureMapView() configInfor() } private func configureMapView() { mapView.delegate = self mapView.add(MKPolyline(coordinates: viewModel.coordinatesForMap(), count: viewModel.coordinatesForMap().count)) } private func configInfor() { data = viewModel.data() } @IBAction func save(_ sender: Any) { self.viewModel.save(completion: { [weak self](result) in guard let this = self else { return } switch result { case .success(_): this.navigationController?.popViewController(animated: true) case .failure(let error): error.show() } }) } @IBAction func cancel(_ sender: Any) { navigationController?.popViewController(animated: true) } } // MARK: - MKMapViewDelegate extension TrackingDetailController: MKMapViewDelegate { func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer { let renderer = MKPolylineRenderer(overlay: overlay) renderer.strokeColor = UIColor.blue renderer.lineWidth = 2 return renderer } }
24c1d84bb4f33cbe9f9084371ac7dcc6
27.103896
119
0.636322
false
true
false
false
atrick/swift
refs/heads/main
test/Generics/sr14510.swift
apache-2.0
2
// RUN: %target-typecheck-verify-swift -requirement-machine-protocol-signatures=on // RUN: %target-swift-frontend -debug-generic-signatures -typecheck %s -requirement-machine-protocol-signatures=on 2>&1 | %FileCheck %s // CHECK-LABEL: Requirement signature: <Self where Self == Self.[Adjoint]Dual.[Adjoint]Dual, Self.[Adjoint]Dual : Adjoint> public protocol Adjoint { associatedtype Dual: Adjoint where Self.Dual.Dual == Self } // CHECK-LABEL: Requirement signature: <Self> public protocol Diffable { associatedtype Patch } // CHECK-LABEL: Requirement signature: <Self where Self : Adjoint, Self : Diffable, Self.[Adjoint]Dual : AdjointDiffable, Self.[Diffable]Patch : Adjoint, Self.[Adjoint]Dual.[Diffable]Patch == Self.[Diffable]Patch.[Adjoint]Dual> public protocol AdjointDiffable: Adjoint & Diffable where Self.Patch: Adjoint, Self.Dual: AdjointDiffable, Self.Patch.Dual == Self.Dual.Patch { } // This is another example used to hit the same problem. Any one of the three // conformance requirements 'A : P', 'B : P' or 'C : P' can be dropped and // proven from the other two, but dropping two or more conformance requirements // leaves us with an invalid signature. // CHECK-LABEL: Requirement signature: <Self where Self.[P]A : P, Self.[P]A == Self.[P]B.[P]C, Self.[P]B : P, Self.[P]B == Self.[P]A.[P]C, Self.[P]C == Self.[P]A.[P]B> protocol P { associatedtype A : P where A == B.C associatedtype B : P where B == A.C associatedtype C : P where C == A.B // expected-warning@-1 {{redundant conformance constraint 'Self.C' : 'P'}} }
5c6ba0a5c15f23504bda2da0e7dcf469
49.322581
227
0.716026
false
false
false
false
ReactorKit/ReactorKit
refs/heads/master
Sources/ReactorKit/IdentityEquatable.swift
mit
1
// // IdentityEquatable.swift // ReactorKit // // Created by Suyeol Jeon on 2019/10/17. // public protocol IdentityEquatable: AnyObject, Equatable {} extension IdentityEquatable { public static func == (lhs: Self, rhs: Self) -> Bool { lhs === rhs } }
8c7d492f5532e9544e6ebbe88d0f457c
17.857143
58
0.666667
false
false
false
false
EclipseSoundscapes/EclipseSoundscapes
refs/heads/master
Example/Pods/RxSwift/RxSwift/Observables/ShareReplayScope.swift
apache-2.0
6
// // ShareReplayScope.swift // RxSwift // // Created by Krunoslav Zaher on 5/28/17. // Copyright © 2017 Krunoslav Zaher. All rights reserved. // /// Subject lifetime scope public enum SubjectLifetimeScope { /** **Each connection will have it's own subject instance to store replay events.** **Connections will be isolated from each another.** Configures the underlying implementation to behave equivalent to. ``` source.multicast(makeSubject: { MySubject() }).refCount() ``` **This is the recommended default.** This has the following consequences: * `retry` or `concat` operators will function as expected because terminating the sequence will clear internal state. * Each connection to source observable sequence will use it's own subject. * When the number of subscribers drops from 1 to 0 and connection to source sequence is disposed, subject will be cleared. ``` let xs = Observable.deferred { () -> Observable<TimeInterval> in print("Performing work ...") return Observable.just(Date().timeIntervalSince1970) } .share(replay: 1, scope: .whileConnected) _ = xs.subscribe(onNext: { print("next \($0)") }, onCompleted: { print("completed\n") }) _ = xs.subscribe(onNext: { print("next \($0)") }, onCompleted: { print("completed\n") }) _ = xs.subscribe(onNext: { print("next \($0)") }, onCompleted: { print("completed\n") }) ``` Notice how time interval is different and `Performing work ...` is printed each time) ``` Performing work ... next 1495998900.82141 completed Performing work ... next 1495998900.82359 completed Performing work ... next 1495998900.82444 completed ``` */ case whileConnected /** **One subject will store replay events for all connections to source.** **Connections won't be isolated from each another.** Configures the underlying implementation behave equivalent to. ``` source.multicast(MySubject()).refCount() ``` This has the following consequences: * Using `retry` or `concat` operators after this operator usually isn't advised. * Each connection to source observable sequence will share the same subject. * After number of subscribers drops from 1 to 0 and connection to source observable sequence is dispose, this operator will continue holding a reference to the same subject. If at some later moment a new observer initiates a new connection to source it can potentially receive some of the stale events received during previous connection. * After source sequence terminates any new observer will always immediately receive replayed elements and terminal event. No new subscriptions to source observable sequence will be attempted. ``` let xs = Observable.deferred { () -> Observable<TimeInterval> in print("Performing work ...") return Observable.just(Date().timeIntervalSince1970) } .share(replay: 1, scope: .forever) _ = xs.subscribe(onNext: { print("next \($0)") }, onCompleted: { print("completed\n") }) _ = xs.subscribe(onNext: { print("next \($0)") }, onCompleted: { print("completed\n") }) _ = xs.subscribe(onNext: { print("next \($0)") }, onCompleted: { print("completed\n") }) ``` Notice how time interval is the same, replayed, and `Performing work ...` is printed only once ``` Performing work ... next 1495999013.76356 completed next 1495999013.76356 completed next 1495999013.76356 completed ``` */ case forever } extension ObservableType { /** Returns an observable sequence that **shares a single subscription to the underlying sequence**, and immediately upon subscription replays elements in buffer. This operator is equivalent to: * `.whileConnected` ``` // Each connection will have it's own subject instance to store replay events. // Connections will be isolated from each another. source.multicast(makeSubject: { Replay.create(bufferSize: replay) }).refCount() ``` * `.forever` ``` // One subject will store replay events for all connections to source. // Connections won't be isolated from each another. source.multicast(Replay.create(bufferSize: replay)).refCount() ``` It uses optimized versions of the operators for most common operations. - parameter replay: Maximum element count of the replay buffer. - parameter scope: Lifetime scope of sharing subject. For more information see `SubjectLifetimeScope` enum. - seealso: [shareReplay operator on reactivex.io](http://reactivex.io/documentation/operators/replay.html) - returns: An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ public func share(replay: Int = 0, scope: SubjectLifetimeScope = .whileConnected) -> Observable<Element> { switch scope { case .forever: switch replay { case 0: return self.multicast(PublishSubject()).refCount() default: return self.multicast(ReplaySubject.create(bufferSize: replay)).refCount() } case .whileConnected: switch replay { case 0: return ShareWhileConnected(source: self.asObservable()) case 1: return ShareReplay1WhileConnected(source: self.asObservable()) default: return self.multicast(makeSubject: { ReplaySubject.create(bufferSize: replay) }).refCount() } } } } private final class ShareReplay1WhileConnectedConnection<Element> : ObserverType , SynchronizedUnsubscribeType { typealias Observers = AnyObserver<Element>.s typealias DisposeKey = Observers.KeyType typealias Parent = ShareReplay1WhileConnected<Element> private let _parent: Parent private let _subscription = SingleAssignmentDisposable() private let _lock: RecursiveLock private var _disposed: Bool = false fileprivate var _observers = Observers() private var _element: Element? init(parent: Parent, lock: RecursiveLock) { self._parent = parent self._lock = lock #if TRACE_RESOURCES _ = Resources.incrementTotal() #endif } final func on(_ event: Event<Element>) { self._lock.lock() let observers = self._synchronized_on(event) self._lock.unlock() dispatch(observers, event) } final private func _synchronized_on(_ event: Event<Element>) -> Observers { if self._disposed { return Observers() } switch event { case .next(let element): self._element = element return self._observers case .error, .completed: let observers = self._observers self._synchronized_dispose() return observers } } final func connect() { self._subscription.setDisposable(self._parent._source.subscribe(self)) } final func _synchronized_subscribe<Observer: ObserverType>(_ observer: Observer) -> Disposable where Observer.Element == Element { self._lock.lock(); defer { self._lock.unlock() } if let element = self._element { observer.on(.next(element)) } let disposeKey = self._observers.insert(observer.on) return SubscriptionDisposable(owner: self, key: disposeKey) } final private func _synchronized_dispose() { self._disposed = true if self._parent._connection === self { self._parent._connection = nil } self._observers = Observers() } final func synchronizedUnsubscribe(_ disposeKey: DisposeKey) { self._lock.lock() let shouldDisconnect = self._synchronized_unsubscribe(disposeKey) self._lock.unlock() if shouldDisconnect { self._subscription.dispose() } } @inline(__always) final private func _synchronized_unsubscribe(_ disposeKey: DisposeKey) -> Bool { // if already unsubscribed, just return if self._observers.removeKey(disposeKey) == nil { return false } if self._observers.count == 0 { self._synchronized_dispose() return true } return false } #if TRACE_RESOURCES deinit { _ = Resources.decrementTotal() } #endif } // optimized version of share replay for most common case final private class ShareReplay1WhileConnected<Element> : Observable<Element> { fileprivate typealias Connection = ShareReplay1WhileConnectedConnection<Element> fileprivate let _source: Observable<Element> private let _lock = RecursiveLock() fileprivate var _connection: Connection? init(source: Observable<Element>) { self._source = source } override func subscribe<Observer: ObserverType>(_ observer: Observer) -> Disposable where Observer.Element == Element { self._lock.lock() let connection = self._synchronized_subscribe(observer) let count = connection._observers.count let disposable = connection._synchronized_subscribe(observer) self._lock.unlock() if count == 0 { connection.connect() } return disposable } @inline(__always) private func _synchronized_subscribe<Observer: ObserverType>(_ observer: Observer) -> Connection where Observer.Element == Element { let connection: Connection if let existingConnection = self._connection { connection = existingConnection } else { connection = ShareReplay1WhileConnectedConnection<Element>( parent: self, lock: self._lock) self._connection = connection } return connection } } private final class ShareWhileConnectedConnection<Element> : ObserverType , SynchronizedUnsubscribeType { typealias Observers = AnyObserver<Element>.s typealias DisposeKey = Observers.KeyType typealias Parent = ShareWhileConnected<Element> private let _parent: Parent private let _subscription = SingleAssignmentDisposable() private let _lock: RecursiveLock private var _disposed: Bool = false fileprivate var _observers = Observers() init(parent: Parent, lock: RecursiveLock) { self._parent = parent self._lock = lock #if TRACE_RESOURCES _ = Resources.incrementTotal() #endif } final func on(_ event: Event<Element>) { self._lock.lock() let observers = self._synchronized_on(event) self._lock.unlock() dispatch(observers, event) } final private func _synchronized_on(_ event: Event<Element>) -> Observers { if self._disposed { return Observers() } switch event { case .next: return self._observers case .error, .completed: let observers = self._observers self._synchronized_dispose() return observers } } final func connect() { self._subscription.setDisposable(self._parent._source.subscribe(self)) } final func _synchronized_subscribe<Observer: ObserverType>(_ observer: Observer) -> Disposable where Observer.Element == Element { self._lock.lock(); defer { self._lock.unlock() } let disposeKey = self._observers.insert(observer.on) return SubscriptionDisposable(owner: self, key: disposeKey) } final private func _synchronized_dispose() { self._disposed = true if self._parent._connection === self { self._parent._connection = nil } self._observers = Observers() } final func synchronizedUnsubscribe(_ disposeKey: DisposeKey) { self._lock.lock() let shouldDisconnect = self._synchronized_unsubscribe(disposeKey) self._lock.unlock() if shouldDisconnect { self._subscription.dispose() } } @inline(__always) final private func _synchronized_unsubscribe(_ disposeKey: DisposeKey) -> Bool { // if already unsubscribed, just return if self._observers.removeKey(disposeKey) == nil { return false } if self._observers.count == 0 { self._synchronized_dispose() return true } return false } #if TRACE_RESOURCES deinit { _ = Resources.decrementTotal() } #endif } // optimized version of share replay for most common case final private class ShareWhileConnected<Element> : Observable<Element> { fileprivate typealias Connection = ShareWhileConnectedConnection<Element> fileprivate let _source: Observable<Element> private let _lock = RecursiveLock() fileprivate var _connection: Connection? init(source: Observable<Element>) { self._source = source } override func subscribe<Observer: ObserverType>(_ observer: Observer) -> Disposable where Observer.Element == Element { self._lock.lock() let connection = self._synchronized_subscribe(observer) let count = connection._observers.count let disposable = connection._synchronized_subscribe(observer) self._lock.unlock() if count == 0 { connection.connect() } return disposable } @inline(__always) private func _synchronized_subscribe<Observer: ObserverType>(_ observer: Observer) -> Connection where Observer.Element == Element { let connection: Connection if let existingConnection = self._connection { connection = existingConnection } else { connection = ShareWhileConnectedConnection<Element>( parent: self, lock: self._lock) self._connection = connection } return connection } }
fba516958e9914031149ae6bd79b35a8
30.274123
164
0.634387
false
false
false
false
ArchimboldiMao/remotex-iOS
refs/heads/master
remotex-iOS/Constants.swift
apache-2.0
2
// // Constants.swift // remotex-iOS // // Created by archimboldi on 10/05/2017. // Copyright © 2017 me.archimboldi. All rights reserved. // import UIKit struct Constants { struct AppLayout { static let LogoForegroundColor: UIColor = UIColor.init(red: 0.31, green: 0.74, blue: 1.0, alpha: 1.0) } struct NavigationBarLayout { static let StatusBarBackgroundColor: UIColor = UIColor.init(red: 0.98, green: 0.98, blue: 0.98, alpha: 0.95) } struct TableLayout { static let BackgroundColor: UIColor = UIColor.init(red: 0.98, green: 0.98, blue: 0.98, alpha: 1.0) } struct CellLayout { static let TitleFontSize: CGFloat = 18.0 static let TitleForegroundColor: UIColor = UIColor.init(red: 0.2, green: 0.2, blue: 0.2, alpha: 1.0) static let PriceFontSize: CGFloat = 16.0 static let TagFontSize: CGFloat = 14.0 static let TagForegroundColor: UIColor = UIColor.init(red: 0.4, green: 0.4, blue: 0.4, alpha: 1.0) static let TagBackgroundColor: UIColor = UIColor.init(red: 0.96, green: 0.96, blue: 0.96, alpha: 1.0) static let AbstractFontSize: CGFloat = 16.0 static let AbstractForegroundColor: UIColor = TitleForegroundColor static let DateFontSize: CGFloat = 14.0 static let DateForegroundColor: UIColor = UIColor.init(red: 0.4, green: 0.4, blue: 0.4, alpha: 1.0) static let PriceForegroundColor: UIColor = UIColor.init(red: 0.4, green: 0.4, blue: 0.4, alpha: 1.0) } struct AboutLayout { static let TitleFontSize: CGFloat = 25.0 static let SloganFontSize: CGFloat = 19.0 static let DescriptionFontSize: CGFloat = 16.0 static let VersionFontSize: CGFloat = 12.0 } struct ShareContext { static let TitleText = "RemoteX 远程工作空间 -- 快乐工作 认真生活" static let AppStoreLinkURL = NSURL.init(string: "https://itunes.apple.com/app/id1236035785")! static let LogoImage = UIImage(named: "logo")! } struct AppStore { static let TitleText = "App Store" static let ReviewURL = URL(string: "itms-apps://itunes.apple.com/app/id1236035785?action=write-review")! } struct MessageDescription { static let NoInternetConnection = "网络连接超时。" } }
467ca499653945bfc14db7b4cf024db2
35.484375
116
0.639829
false
false
false
false
bencochran/KaleidoscopeLang
refs/heads/master
KaleidoscopeLang/Parser.swift
bsd-3-clause
1
// // Parser.swift // KaleidoscopeLang // // Created by Ben Cochran on 11/8/15. // Copyright © 2015 Ben Cochran. All rights reserved. // import Madness import Prelude import Either internal typealias ValueExpressionParser = Parser<[Token], ValueExpression>.Function internal typealias TopLevelExpressionParser = Parser<[Token], TopLevelExpression>.Function internal typealias ExpressionParser = Parser<[Token], Expression>.Function // MARK: Token unwrappers private let identifier: Parser<[Token], String>.Function = attempt { $0.identifier } private let double: Parser<[Token], Double>.Function = attempt { $0.number } // MARK: Value expressions private let valueExpression: ValueExpressionParser = fix { valueExpression in /// variable ::= Identifier let variable: ValueExpressionParser = VariableExpression.init <^> identifier /// number ::= Number let number: ValueExpressionParser = NumberExpression.init <^> double /// parenExpression ::= "(" valueExpression ")" let parenExpression = %(.Character("(")) *> valueExpression <* %(.Character(")")) /// callargs ::= "(" valueExpression* ")" let callargs = %(.Character("(")) *> many(valueExpression) <* %(.Character(")")) /// call ::= Identifier callargs let call: ValueExpressionParser = curry(CallExpression.init) <^> identifier <*> callargs /// primary /// ::= call /// ::= variable /// ::= number /// ::= parenExpression let primary = call <|> variable <|> number <|> parenExpression /// infixOperator /// ::= "+" /// ::= "-" /// ::= "*" /// ::= "/" let infixOperator: Parser<[Token], Token>.Function = oneOf([ .Character("+"), .Character("-"), .Character("*"), .Character("/") ]) /// infixRight ::= infixOperator primary let infixRight = curry(pair) <^> infixOperator <*> primary /// infix ::= primary infixRight* let repackedInfix = curry(map(id, ArraySlice.init)) <^> primary <*> many(infixRight) let infix: ValueExpressionParser = collapsePackedInfix <^> repackedInfix /// valueExpression /// ::= infix /// ::= primary return infix <|> primary } // MARK: Top-level expressions /// prototypeArgs ::= "(" Identifier* ")" private let prototypeArgs = %(.Character("(")) *> many(identifier) <* %(.Character(")")) /// prototype ::= Identifier prototypeArgs private let prototype = curry(PrototypeExpression.init) <^> identifier <*> prototypeArgs /// definition ::= "def" prototype expression private let definition: TopLevelExpressionParser = %(Token.Def) *> (curry(FunctionExpression.init) <^> prototype <*> valueExpression) /// external ::= "extern" prototype private let external: TopLevelExpressionParser = id <^> ( %(Token.Extern) *> prototype ) /// top /// ::= definition /// ::= external private let top = definition <|> external /// topLevelExpression ::= top EndOfStatement internal let topLevelExpression = top <* %(.EndOfStatement) /// expression /// ::= topLevelExpression /// ::= valueExpression internal let expression = topLevelExpression <|> valueExpression // MARK: Public /// Parse a series of tokens into a value expression public func parseValueExpression(tokens: [Token]) -> Either<Error, ValueExpression> { return parse(valueExpression, input: tokens).mapLeft(Error.treeError(tokens)) } /// Lex and parse a string into a value expression public func parseValueExpression(string: String) -> Either<Error, ValueExpression> { return lex(string) >>- parseValueExpression } /// Parse a series of tokens into a top-level expression public func parseTopLevelExpression(tokens: [Token]) -> Either<Error, TopLevelExpression> { return parse(topLevelExpression, input: tokens).mapLeft(Error.treeError(tokens)) } /// Lex and parse a string into a top-level expression public func parseTopLevelExpression(string: String) -> Either<Error, TopLevelExpression> { return lex(string) >>- parseTopLevelExpression } /// Parse a series of tokens into a value or top-level expression public func parse(tokens: [Token]) -> Either<Error, Expression> { return parse(expression, input: tokens).mapLeft(Error.treeError(tokens)).map(collapseExpression) } /// Lex and parse a string into a value or top-level expression public func parse(string: String) -> Either<Error, Expression> { return lex(string) >>- parse } // MARK: Private private func collapseExpression(expression: Either<TopLevelExpression, ValueExpression>) -> Expression { return expression.either(ifLeft: id, ifRight: id) } // MARK: Infix Helpers private func collapsePackedInfix(binop: (ValueExpression, ArraySlice<(Token, ValueExpression)>)) -> ValueExpression { // Recursion base guard let rightHalf = binop.1.first else { return binop.0 } let code = rightHalf.0.character! let rest = (rightHalf.1, binop.1.dropFirst()) let left = binop.0 return BinaryOperatorExpression(code: code, left: left, right: collapsePackedInfix(rest)) }
f7b3b558ca2ec0c1d501569917530671
33.653061
133
0.678053
false
false
false
false
fdanise/loadingButton
refs/heads/master
ExtensionUIButton.swift
mit
1
// // ExtensionUIButton.swift // // Created by Ferdinando Danise on 07/09/17. // Copyright © 2017 Ferdinando Danise. All rights reserved. // import UIKit extension UIButton { func startLoading(color: UIColor) { let shapeOuter = shapeLayerOuter(color: color) let shapeInner = shapeLayerInner(color: color) shapeOuter.add(animationOuter(), forKey: nil) shapeInner.add(animationInner(), forKey: nil) self.layer.addSublayer(shapeOuter) self.layer.addSublayer(shapeInner) } func stopLoading(){ UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseOut, animations: { self.alpha = 0 }) { (true) in self.layer.removeFromSuperlayer() } } private func shapeLayerOuter(color: UIColor) -> CAShapeLayer{ let circleOut = UIBezierPath(arcCenter: CGPoint(x: self.bounds.midX, y: self.bounds.midY), radius: CGFloat(self.bounds.height * 0.4), startAngle: CGFloat(0), endAngle:CGFloat(Double.pi * 2), clockwise: true) let shapeLayerOut = CAShapeLayer() shapeLayerOut.path = circleOut.cgPath shapeLayerOut.fillColor = UIColor.clear.cgColor shapeLayerOut.strokeColor = color.cgColor shapeLayerOut.strokeStart = 0.1 shapeLayerOut.strokeEnd = 1 shapeLayerOut.lineWidth = 3.5 shapeLayerOut.lineCap = "round" shapeLayerOut.frame = self.bounds return shapeLayerOut } private func shapeLayerInner(color: UIColor) -> CAShapeLayer{ let circleIn = UIBezierPath(arcCenter: CGPoint(x: self.bounds.midX, y: self.bounds.midY), radius: CGFloat(self.bounds.height * 0.2), startAngle: CGFloat(0), endAngle: CGFloat(Double.pi * 2), clockwise: false) let shapeLayerIn = CAShapeLayer() shapeLayerIn.path = circleIn.cgPath shapeLayerIn.fillColor = UIColor.clear.cgColor shapeLayerIn.strokeColor = color.cgColor shapeLayerIn.strokeStart = 0.1 shapeLayerIn.strokeEnd = 1 shapeLayerIn.lineWidth = 3.2 shapeLayerIn.lineCap = "round" shapeLayerIn.frame = self.bounds return shapeLayerIn } private func animationOuter() -> CABasicAnimation{ let animationOut = CABasicAnimation(keyPath: "transform.rotation") animationOut.fromValue = 0 animationOut.toValue = Double.pi * 2 animationOut.duration = 1 animationOut.repeatCount = Float.infinity return animationOut } private func animationInner() -> CABasicAnimation { let animationIn = CABasicAnimation(keyPath: "transform.rotation") animationIn.fromValue = 0 animationIn.toValue = -(Double.pi * 2) animationIn.duration = 1 animationIn.repeatCount = Float.infinity return animationIn } }
c16dd1a2138d63731d53995964620237
31.782178
98
0.57022
false
false
false
false
tjw/swift
refs/heads/master
test/SILGen/opaque_values_silgen_lib.swift
apache-2.0
1
// RUN: %target-swift-frontend -enable-sil-ownership -enable-sil-opaque-values -emit-sorted-sil -Xllvm -sil-full-demangle -parse-stdlib -parse-as-library -emit-silgen -module-name Swift %s | %FileCheck %s precedencegroup AssignmentPrecedence { assignment: true } enum Optional<Wrapped> { case none case some(Wrapped) } protocol EmptyP {} struct String { var ptr: Builtin.NativeObject } // Tests Empty protocol + Builtin.NativeObject enum (including opaque tuples as a return value) // --- // CHECK-LABEL: sil hidden @$Ss21s010______PAndS_casesyyF : $@convention(thin) () -> () { // CHECK: bb0: // CHECK: [[MTYPE:%.*]] = metatype $@thin PAndSEnum.Type // CHECK: [[EAPPLY:%.*]] = apply {{.*}}([[MTYPE]]) : $@convention(thin) (@thin PAndSEnum.Type) -> @owned @callee_guaranteed (@in_guaranteed EmptyP, @guaranteed String) -> @out PAndSEnum // CHECK: destroy_value [[EAPPLY]] // CHECK: return %{{.*}} : $() // CHECK-LABEL: } // end sil function '$Ss21s010______PAndS_casesyyF' func s010______PAndS_cases() { _ = PAndSEnum.A } // Test emitBuiltinReinterpretCast. // --- // CHECK-LABEL: sil hidden @$Ss21s020__________bitCast_2toq_x_q_mtr0_lF : $@convention(thin) <T, U> (@in_guaranteed T, @thick U.Type) -> @out U { // CHECK: bb0([[ARG:%.*]] : @guaranteed $T, // CHECK: [[CAST:%.*]] = unchecked_bitwise_cast [[ARG]] : $T to $U // CHECK: [[RET:%.*]] = copy_value [[CAST]] : $U // CHECK-NOT: destroy_value [[COPY]] : $T // CHECK: return [[RET]] : $U // CHECK-LABEL: } // end sil function '$Ss21s020__________bitCast_2toq_x_q_mtr0_lF' func s020__________bitCast<T, U>(_ x: T, to type: U.Type) -> U { return Builtin.reinterpretCast(x) } // Test emitBuiltinCastReference // --- // CHECK-LABEL: sil hidden @$Ss21s030__________refCast_2toq_x_q_mtr0_lF : $@convention(thin) <T, U> (@in_guaranteed T, @thick U.Type) -> @out U { // CHECK: bb0([[ARG:%.*]] : @guaranteed $T, %1 : @trivial $@thick U.Type): // CHECK: [[COPY:%.*]] = copy_value [[ARG]] : $T // CHECK: [[SRC:%.*]] = alloc_stack $T // CHECK: store [[COPY]] to [init] [[SRC]] : $*T // CHECK: [[DEST:%.*]] = alloc_stack $U // CHECK: unchecked_ref_cast_addr T in [[SRC]] : $*T to U in [[DEST]] : $*U // CHECK: [[LOAD:%.*]] = load [take] [[DEST]] : $*U // CHECK: dealloc_stack [[DEST]] : $*U // CHECK: dealloc_stack [[SRC]] : $*T // CHECK-NOT: destroy_value [[ARG]] : $T // CHECK: return [[LOAD]] : $U // CHECK-LABEL: } // end sil function '$Ss21s030__________refCast_2toq_x_q_mtr0_lF' func s030__________refCast<T, U>(_ x: T, to: U.Type) -> U { return Builtin.castReference(x) } // Init of Empty protocol + Builtin.NativeObject enum (including opaque tuples as a return value) // --- // CHECK-LABEL: sil shared [transparent] @$Ss9PAndSEnumO1AyABs6EmptyP_p_SStcABmF : $@convention(method) (@in EmptyP, @owned String, @thin PAndSEnum.Type) -> @out PAndSEnum { // CHECK: bb0([[ARG0:%.*]] : @owned $EmptyP, [[ARG1:%.*]] : @owned $String, [[ARG2:%.*]] : @trivial $@thin PAndSEnum.Type): // CHECK: [[RTUPLE:%.*]] = tuple ([[ARG0]] : $EmptyP, [[ARG1]] : $String) // CHECK: [[RETVAL:%.*]] = enum $PAndSEnum, #PAndSEnum.A!enumelt.1, [[RTUPLE]] : $(EmptyP, String) // CHECK: return [[RETVAL]] : $PAndSEnum // CHECK-LABEL: } // end sil function '$Ss9PAndSEnumO1AyABs6EmptyP_p_SStcABmF' // CHECK-LABEL: sil shared [transparent] [thunk] @$Ss9PAndSEnumO1AyABs6EmptyP_p_SStcABmFTc : $@convention(thin) (@thin PAndSEnum.Type) -> @owned @callee_guaranteed (@in_guaranteed EmptyP, @guaranteed String) -> @out PAndSEnum { // CHECK: bb0([[ARG:%.*]] : @trivial $@thin PAndSEnum.Type): // CHECK: [[RETVAL:%.*]] = partial_apply [callee_guaranteed] {{.*}}([[ARG]]) : $@convention(method) (@in EmptyP, @owned String, @thin PAndSEnum.Type) -> @out PAndSEnum // CHECK: [[CANONICAL_THUNK_FN:%.*]] = function_ref @$Ss6EmptyP_pSSs9PAndSEnumOIegixr_sAA_pSSACIegngr_TR : $@convention(thin) (@in_guaranteed EmptyP, @guaranteed String, @guaranteed @callee_guaranteed (@in EmptyP, @owned String) -> @out PAndSEnum) -> @out PAndSEnum // CHECK: [[CANONICAL_THUNK:%.*]] = partial_apply [callee_guaranteed] [[CANONICAL_THUNK_FN]]([[RETVAL]]) // CHECK: return [[CANONICAL_THUNK]] : $@callee_guaranteed (@in_guaranteed EmptyP, @guaranteed String) -> @out PAndSEnum // CHECK-LABEL: } // end sil function '$Ss9PAndSEnumO1AyABs6EmptyP_p_SStcABmFTc' enum PAndSEnum { case A(EmptyP, String) }
b737fda997c0230186b288c02345a80c
56.013158
267
0.633741
false
false
false
false
the-blue-alliance/the-blue-alliance-ios
refs/heads/master
the-blue-alliance-ios/View Elements/Settings/Notifications/NotificationStatusTableViewCell.swift
mit
1
import Foundation import UIKit class NotificationStatusTableViewCell: UITableViewCell { var viewModel: NotificationStatusCellViewModel? { didSet { configureCell() } } // MARK: - Reusable static var nib: UINib? { return UINib(nibName: String(describing: self), bundle: nil) } // MARK: - Interface Builder @IBOutlet private weak var activityIndicator: UIActivityIndicatorView! @IBOutlet private weak var statusImageView: UIImageView! @IBOutlet private weak var titleLabel: UILabel! // MARK: - Private Methods private func configureCell() { guard let viewModel = viewModel else { return } titleLabel.alpha = 1.0 titleLabel.text = viewModel.title statusImageView.image = nil activityIndicator.isHidden = true selectionStyle = .none isUserInteractionEnabled = false accessoryType = .none switch viewModel.notificationStatus { case .unknown: titleLabel.alpha = 0.5 case .loading: activityIndicator.isHidden = false activityIndicator.startAnimating() case .valid: statusImageView.image = UIImage(systemName: "checkmark.circle.fill") statusImageView.tintColor = UIColor.primaryBlue case .invalid: selectionStyle = .default accessoryType = .disclosureIndicator isUserInteractionEnabled = true statusImageView.image = UIImage(systemName: "xmark.circle.fill") statusImageView.tintColor = UIColor.systemRed } } }
21098f50f30b79a627d4f5531faa38c0
27.431034
80
0.635537
false
false
false
false
Authman2/Pix
refs/heads/master
Pix/ProfilePage.swift
gpl-3.0
1
// // ProfilePage.swift // Pix // // Created by Adeola Uthman on 12/23/16. // Copyright © 2016 Adeola Uthman. All rights reserved. // import UIKit import Foundation import SnapKit import Firebase import PullToRefreshSwift import OneSignal import IGListKit class ProfilePage: ProfileDisplayPage, IGListAdapterDataSource, UIImagePickerControllerDelegate, UINavigationControllerDelegate { /******************************** * * VARIABLES * ********************************/ /* The adapter. */ lazy var adapter: IGListAdapter = { return IGListAdapter(updater: IGListAdapterUpdater(), viewController: self, workingRangeSize: 1); }(); /* The collection view. */ let collectionView: IGListCollectionView = { let layout = IGListGridCollectionViewLayout(); let view = IGListCollectionView(frame: CGRect.zero, collectionViewLayout: layout); view.alwaysBounceVertical = true; return view; }(); /* The image view that displays the profile picture. */ let profilePicture: CircleImageView = { let i = CircleImageView(); i.translatesAutoresizingMaskIntoConstraints = false; i.isUserInteractionEnabled = true; i.backgroundColor = UIColor.gray; return i; }(); /* A label to display whether or not this user is private. */ let privateLabel: UILabel = { let a = UILabel(); a.translatesAutoresizingMaskIntoConstraints = false; a.isUserInteractionEnabled = false; a.font = UIFont(name: a.font.fontName, size: 15); a.numberOfLines = 0; a.textColor = UIColor(red: 21/255, green: 180/255, blue: 133/255, alpha: 1).lighter(); a.textAlignment = .center; a.isHidden = true; return a; }(); /* Label that shows the user's name. */ let nameLabel: UILabel = { let n = UILabel(); n.translatesAutoresizingMaskIntoConstraints = false; n.isUserInteractionEnabled = false; n.font = UIFont(name: n.font.fontName, size: 20); n.textColor = UIColor.black; n.textAlignment = .center; return n; }(); /* Label that shows the number of followers this user has. */ let followersLabel: UILabel = { let n = UILabel(); n.translatesAutoresizingMaskIntoConstraints = false; n.isUserInteractionEnabled = false; n.font = UIFont(name: n.font.fontName, size: 15); n.textColor = UIColor.black; n.textAlignment = .center; return n; }(); /* Label that shows the number of people this user is following. */ let followingLabel: UILabel = { let n = UILabel(); n.translatesAutoresizingMaskIntoConstraints = false; n.isUserInteractionEnabled = false; n.font = UIFont(name: n.font.fontName, size: 15); n.textColor = UIColor.black; n.textAlignment = .center; return n; }(); /* The button used for editing the profile. */ var editProfileButton: UIBarButtonItem!; /* Image picker */ let imgPicker = UIImagePickerController(); var canChangeProfilePic = false; var tap: UITapGestureRecognizer!; /* Firebase reference. */ let fireRef: FIRDatabaseReference = FIRDatabase.database().reference(); /******************************** * * METHODS * ********************************/ override func viewDidLoad() { super.viewDidLoad(); view.backgroundColor = UIColor(red: 239/255, green: 255/255, blue:245/255, alpha: 1); navigationController?.navigationBar.isHidden = false; navigationItem.hidesBackButton = true; navigationItem.title = "Profile"; viewcontrollerName = "Profile"; setupCollectionView(); view.addSubview(collectionView) /* Setup/Layout the view. */ view.addSubview(privateLabel); view.addSubview(profilePicture); view.addSubview(nameLabel); view.addSubview(followersLabel); view.addSubview(followingLabel); profilePicture.snp.makeConstraints { (maker: ConstraintMaker) in maker.centerX.equalTo(view.snp.centerX); maker.bottom.equalTo(view.snp.centerY).offset(-100); maker.width.equalTo(90); maker.height.equalTo(90); } privateLabel.snp.makeConstraints { (maker: ConstraintMaker) in maker.centerX.equalTo(view.snp.centerX); maker.bottom.equalTo(profilePicture.snp.top).offset(-10); maker.width.equalTo(view.width); maker.height.equalTo(50); } nameLabel.snp.makeConstraints { (maker: ConstraintMaker) in maker.centerX.equalTo(view.snp.centerX); maker.width.equalTo(view.width); maker.height.equalTo(25); maker.top.equalTo(profilePicture.snp.bottom).offset(20); } followersLabel.snp.makeConstraints { (maker: ConstraintMaker) in maker.centerX.equalTo(view.snp.centerX); maker.width.equalTo(view.width); maker.height.equalTo(20); maker.top.equalTo(nameLabel.snp.bottom).offset(10); } followingLabel.snp.makeConstraints { (maker: ConstraintMaker) in maker.centerX.equalTo(view.snp.centerX); maker.width.equalTo(view.width); maker.height.equalTo(20); maker.top.equalTo(followersLabel.snp.bottom).offset(5); } collectionView.snp.makeConstraints({ (maker: ConstraintMaker) in maker.width.equalTo(view.frame.width); maker.centerX.equalTo(view); maker.top.equalTo(followingLabel.snp.bottom).offset(10); maker.bottom.equalTo(view.snp.bottom); }) /* Add the pull to refresh function. */ var options = PullToRefreshOption(); options.fixedSectionHeader = false; collectionView.addPullRefresh(options: options, refreshCompletion: { (Void) in //self.adapter.performUpdates(animated: true, completion: nil); self.adapter.reloadData(completion: { (b: Bool) in self.reloadLabels(); self.collectionView.stopPullRefreshEver(); }) }); /* Bar button item. */ editProfileButton = UIBarButtonItem(title: "Edit", style: .plain, target: self, action: #selector(editProfile)); editProfileButton.tintColor = .white; navigationItem.rightBarButtonItem = editProfileButton; /* Profile pic image picker. */ imgPicker.delegate = self; imgPicker.sourceType = .photoLibrary; tap = UITapGestureRecognizer(target: self, action: #selector(uploadProfilePic)); profilePicture.addGestureRecognizer(tap); } // End of viewDidLoad(). override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated); lastProfile = self; self.adapter.reloadData(completion: nil); editProfileButton.isEnabled = true; editProfileButton.tintColor = .white; self.reloadLabels(); profilePicture.addGestureRecognizer(tap); } // End of viewDidAppear(). func reloadLabels() { if let cUser = Networking.currentUser { nameLabel.text = "\(cUser.firstName) \(cUser.lastName)"; followersLabel.text = "Followers: \(cUser.followers.count)"; followingLabel.text = "Following: \(cUser.following.count)"; profilePicture.image = cUser.profilepic; privateLabel.text = "\(cUser.username) is private. Send a follow request to see their photos."; privateLabel.isHidden = true; collectionView.isHidden = false; profilePicture.image = cUser.profilepic; } } @objc func logout() { do { try FIRAuth.auth()?.signOut(); Networking.currentUser = nil; feedPage.followingUsers.removeAll(); feedPage.postFeed.removeAll(); explorePage.listOfUsers.removeAll(); explorePage.listOfUsers_fb.removeAllObjects(); let _ = navigationController?.popToRootViewController(animated: true); self.debug(message: "Signed out!"); self.debug(message: "Logged out!"); } catch { self.debug(message: "There was a problem signing out."); } } @objc func editProfile() { navigationController?.pushViewController(EditProfilePage(), animated: true); } /******************************** * * IMAGE PICKER * ********************************/ @objc func uploadProfilePic() { show(imgPicker, sender: self); } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { if let photo = info[UIImagePickerControllerOriginalImage] as? UIImage { // Set the picture on the image view and also on the actual user object. profilePicture.image = photo; let id = Networking.currentUser!.profilePicName; Networking.currentUser!.profilepic = photo; // Delete the old picture from firebase, and replace it with the new one, but keep the same id. let storageRef = FIRStorageReference().child("\(Networking.currentUser!.uid)/\(id!).jpg"); storageRef.delete { error in // If there's an error. if let error = error { self.debug(message: "There was an error deleting the image: \(error)"); } else { // Save the new image. let data = UIImageJPEGRepresentation(photo, 100) as NSData?; let _ = storageRef.put(data! as Data, metadata: nil) { (metaData, error) in if (error == nil) { let post = Post(photo: photo, caption: "", Uploader: Networking.currentUser!, ID: id!); post.isProfilePicture = true; let postObj = post.toDictionary(); Networking.saveObject(object: postObj, path: "Photos/\(Networking.currentUser!.uid)/\(id!)", success: { }, failure: { (err: Error) in }); // self.fireRef.child("Photos").child("\(Networking.currentUser!.uid)").child("\(id!)").setValue(postObj); self.debug(message: "Old profile picture was removed; replace with new one."); } else { print(error.debugDescription); } } } } // Dismiss view controller. imgPicker.dismiss(animated: true, completion: nil); } } /******************************** * * COLLECTION VIEW * ********************************/ func setupCollectionView() { collectionView.register(ProfilePageCell.self, forCellWithReuseIdentifier: "Cell"); collectionView.backgroundColor = view.backgroundColor; adapter.collectionView = collectionView; adapter.dataSource = self; } func objects(for listAdapter: IGListAdapter) -> [IGListDiffable] { if let cUser = Networking.currentUser { return cUser.posts; } else { return []; } } func listAdapter(_ listAdapter: IGListAdapter, sectionControllerFor object: Any) -> IGListSectionController { return ProfileSectionController(vc: self); } func emptyView(for listAdapter: IGListAdapter) -> UIView? { return EmptyPhotoView(place: .top); } }
101c46d6bb716e603e60ad8774779c74
31.551282
133
0.549508
false
false
false
false
LoopKit/LoopKit
refs/heads/dev
LoopKit/SettingsStore.swift
mit
1
// // SettingsStore.swift // LoopKit // // Created by Darin Krauss on 10/14/19. // Copyright © 2019 LoopKit Authors. All rights reserved. // import os.log import Foundation import CoreData import HealthKit public protocol SettingsStoreDelegate: AnyObject { /** Informs the delegate that the settings store has updated settings data. - Parameter settingsStore: The settings store that has updated settings data. */ func settingsStoreHasUpdatedSettingsData(_ settingsStore: SettingsStore) } public class SettingsStore { public weak var delegate: SettingsStoreDelegate? public private(set) var latestSettings: StoredSettings? { get { return lockedLatestSettings.value } set { lockedLatestSettings.value = newValue } } private let lockedLatestSettings: Locked<StoredSettings?> private let store: PersistenceController private let expireAfter: TimeInterval private let dataAccessQueue = DispatchQueue(label: "com.loopkit.SettingsStore.dataAccessQueue", qos: .utility) private let log = OSLog(category: "SettingsStore") public init(store: PersistenceController, expireAfter: TimeInterval) { self.store = store self.expireAfter = expireAfter self.lockedLatestSettings = Locked(nil) dataAccessQueue.sync { self.store.managedObjectContext.performAndWait { let storedRequest: NSFetchRequest<SettingsObject> = SettingsObject.fetchRequest() storedRequest.sortDescriptors = [NSSortDescriptor(key: "modificationCounter", ascending: false)] storedRequest.fetchLimit = 1 do { let stored = try self.store.managedObjectContext.fetch(storedRequest) self.latestSettings = stored.first.flatMap { self.decodeSettings(fromData: $0.data) } } catch let error { self.log.error("Error fetching latest settings: %@", String(describing: error)) return } } } } func storeSettings(_ settings: StoredSettings) async { await withCheckedContinuation { continuation in storeSettings(settings) { (_) in continuation.resume() } } } public func storeSettings(_ settings: StoredSettings, completion: @escaping (Error?) -> Void) { dataAccessQueue.async { var error: Error? if let data = self.encodeSettings(settings) { self.store.managedObjectContext.performAndWait { let object = SettingsObject(context: self.store.managedObjectContext) object.data = data object.date = settings.date error = self.store.save() } } self.latestSettings = settings self.purgeExpiredSettings() completion(error) } } public var expireDate: Date { return Date(timeIntervalSinceNow: -expireAfter) } private func purgeExpiredSettings() { guard let latestSettings = latestSettings else { return } guard expireDate < latestSettings.date else { return } purgeSettingsObjects(before: expireDate) } public func purgeSettings(before date: Date, completion: @escaping (Error?) -> Void) { dataAccessQueue.async { self.purgeSettingsObjects(before: date, completion: completion) } } private func purgeSettingsObjects(before date: Date, completion: ((Error?) -> Void)? = nil) { dispatchPrecondition(condition: .onQueue(dataAccessQueue)) var purgeError: Error? store.managedObjectContext.performAndWait { do { let count = try self.store.managedObjectContext.purgeObjects(of: SettingsObject.self, matching: NSPredicate(format: "date < %@", date as NSDate)) if count > 0 { self.log.default("Purged %d SettingsObjects", count) } } catch let error { self.log.error("Unable to purge SettingsObjects: %{public}@", String(describing: error)) purgeError = error } } if let purgeError = purgeError { completion?(purgeError) return } delegate?.settingsStoreHasUpdatedSettingsData(self) completion?(nil) } private static var encoder: PropertyListEncoder = { let encoder = PropertyListEncoder() encoder.outputFormat = .binary return encoder }() private func encodeSettings(_ settings: StoredSettings) -> Data? { do { return try Self.encoder.encode(settings) } catch let error { self.log.error("Error encoding StoredSettings: %@", String(describing: error)) return nil } } private static var decoder = PropertyListDecoder() private func decodeSettings(fromData data: Data) -> StoredSettings? { do { return try Self.decoder.decode(StoredSettings.self, from: data) } catch let error { self.log.error("Error decoding StoredSettings: %@", String(describing: error)) return nil } } } extension SettingsStore { public struct QueryAnchor: Equatable, RawRepresentable { public typealias RawValue = [String: Any] internal var modificationCounter: Int64 public init() { self.modificationCounter = 0 } public init?(rawValue: RawValue) { guard let modificationCounter = rawValue["modificationCounter"] as? Int64 else { return nil } self.modificationCounter = modificationCounter } public var rawValue: RawValue { var rawValue: RawValue = [:] rawValue["modificationCounter"] = modificationCounter return rawValue } } public enum SettingsQueryResult { case success(QueryAnchor, [StoredSettings]) case failure(Error) } public func executeSettingsQuery(fromQueryAnchor queryAnchor: QueryAnchor?, limit: Int, completion: @escaping (SettingsQueryResult) -> Void) { dataAccessQueue.async { var queryAnchor = queryAnchor ?? QueryAnchor() var queryResult = [StoredSettingsData]() var queryError: Error? guard limit > 0 else { completion(.success(queryAnchor, [])) return } self.store.managedObjectContext.performAndWait { let storedRequest: NSFetchRequest<SettingsObject> = SettingsObject.fetchRequest() storedRequest.predicate = NSPredicate(format: "modificationCounter > %d", queryAnchor.modificationCounter) storedRequest.sortDescriptors = [NSSortDescriptor(key: "modificationCounter", ascending: true)] storedRequest.fetchLimit = limit do { let stored = try self.store.managedObjectContext.fetch(storedRequest) if let modificationCounter = stored.max(by: { $0.modificationCounter < $1.modificationCounter })?.modificationCounter { queryAnchor.modificationCounter = modificationCounter } queryResult.append(contentsOf: stored.compactMap { StoredSettingsData(date: $0.date, data: $0.data) }) } catch let error { queryError = error return } } if let queryError = queryError { completion(.failure(queryError)) return } // Decoding a large number of settings can be very CPU intensive and may take considerable wall clock time. // Do not block SettingsStore dataAccessQueue. Perform work and callback in global utility queue. DispatchQueue.global(qos: .utility).async { completion(.success(queryAnchor, queryResult.compactMap { self.decodeSettings(fromData: $0.data) })) } } } } public struct StoredSettingsData { public let date: Date public let data: Data public init(date: Date, data: Data) { self.date = date self.data = data } } public struct StoredSettings: Equatable { public let date: Date public var controllerTimeZone: TimeZone public let dosingEnabled: Bool public let glucoseTargetRangeSchedule: GlucoseRangeSchedule? public let preMealTargetRange: ClosedRange<HKQuantity>? public let workoutTargetRange: ClosedRange<HKQuantity>? public let overridePresets: [TemporaryScheduleOverridePreset]? public let scheduleOverride: TemporaryScheduleOverride? public let preMealOverride: TemporaryScheduleOverride? public let maximumBasalRatePerHour: Double? public let maximumBolus: Double? public let suspendThreshold: GlucoseThreshold? public let deviceToken: String? public let insulinType: InsulinType? public let defaultRapidActingModel: StoredInsulinModel? public let basalRateSchedule: BasalRateSchedule? public let insulinSensitivitySchedule: InsulinSensitivitySchedule? public let carbRatioSchedule: CarbRatioSchedule? public var notificationSettings: NotificationSettings? public let controllerDevice: ControllerDevice? public let cgmDevice: HKDevice? public let pumpDevice: HKDevice? // This is the user's display preference glucose unit. TODO: Rename? public let bloodGlucoseUnit: HKUnit? public let automaticDosingStrategy: AutomaticDosingStrategy public let syncIdentifier: UUID public init(date: Date = Date(), controllerTimeZone: TimeZone = TimeZone.current, dosingEnabled: Bool = false, glucoseTargetRangeSchedule: GlucoseRangeSchedule? = nil, preMealTargetRange: ClosedRange<HKQuantity>? = nil, workoutTargetRange: ClosedRange<HKQuantity>? = nil, overridePresets: [TemporaryScheduleOverridePreset]? = nil, scheduleOverride: TemporaryScheduleOverride? = nil, preMealOverride: TemporaryScheduleOverride? = nil, maximumBasalRatePerHour: Double? = nil, maximumBolus: Double? = nil, suspendThreshold: GlucoseThreshold? = nil, deviceToken: String? = nil, insulinType: InsulinType? = nil, defaultRapidActingModel: StoredInsulinModel? = nil, basalRateSchedule: BasalRateSchedule? = nil, insulinSensitivitySchedule: InsulinSensitivitySchedule? = nil, carbRatioSchedule: CarbRatioSchedule? = nil, notificationSettings: NotificationSettings? = nil, controllerDevice: ControllerDevice? = nil, cgmDevice: HKDevice? = nil, pumpDevice: HKDevice? = nil, bloodGlucoseUnit: HKUnit? = nil, automaticDosingStrategy: AutomaticDosingStrategy = .tempBasalOnly, syncIdentifier: UUID = UUID()) { self.date = date self.controllerTimeZone = controllerTimeZone self.dosingEnabled = dosingEnabled self.glucoseTargetRangeSchedule = glucoseTargetRangeSchedule self.preMealTargetRange = preMealTargetRange self.workoutTargetRange = workoutTargetRange self.overridePresets = overridePresets self.scheduleOverride = scheduleOverride self.preMealOverride = preMealOverride self.maximumBasalRatePerHour = maximumBasalRatePerHour self.maximumBolus = maximumBolus self.suspendThreshold = suspendThreshold self.deviceToken = deviceToken self.insulinType = insulinType self.defaultRapidActingModel = defaultRapidActingModel self.basalRateSchedule = basalRateSchedule self.insulinSensitivitySchedule = insulinSensitivitySchedule self.carbRatioSchedule = carbRatioSchedule self.notificationSettings = notificationSettings self.controllerDevice = controllerDevice self.cgmDevice = cgmDevice self.pumpDevice = pumpDevice self.bloodGlucoseUnit = bloodGlucoseUnit self.automaticDosingStrategy = automaticDosingStrategy self.syncIdentifier = syncIdentifier } } extension StoredSettings: Codable { fileprivate static let codingGlucoseUnit = HKUnit.milligramsPerDeciliter public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let bloodGlucoseUnit = HKUnit(from: try container.decode(String.self, forKey: .bloodGlucoseUnit)) self.init(date: try container.decode(Date.self, forKey: .date), controllerTimeZone: try container.decode(TimeZone.self, forKey: .controllerTimeZone), dosingEnabled: try container.decode(Bool.self, forKey: .dosingEnabled), glucoseTargetRangeSchedule: try container.decodeIfPresent(GlucoseRangeSchedule.self, forKey: .glucoseTargetRangeSchedule), preMealTargetRange: try container.decodeIfPresent(DoubleRange.self, forKey: .preMealTargetRange)?.quantityRange(for: bloodGlucoseUnit), workoutTargetRange: try container.decodeIfPresent(DoubleRange.self, forKey: .workoutTargetRange)?.quantityRange(for: bloodGlucoseUnit), overridePresets: try container.decodeIfPresent([TemporaryScheduleOverridePreset].self, forKey: .overridePresets), scheduleOverride: try container.decodeIfPresent(TemporaryScheduleOverride.self, forKey: .scheduleOverride), preMealOverride: try container.decodeIfPresent(TemporaryScheduleOverride.self, forKey: .preMealOverride), maximumBasalRatePerHour: try container.decodeIfPresent(Double.self, forKey: .maximumBasalRatePerHour), maximumBolus: try container.decodeIfPresent(Double.self, forKey: .maximumBolus), suspendThreshold: try container.decodeIfPresent(GlucoseThreshold.self, forKey: .suspendThreshold), deviceToken: try container.decodeIfPresent(String.self, forKey: .deviceToken), insulinType: try container.decodeIfPresent(InsulinType.self, forKey: .insulinType), defaultRapidActingModel: try container.decodeIfPresent(StoredInsulinModel.self, forKey: .defaultRapidActingModel), basalRateSchedule: try container.decodeIfPresent(BasalRateSchedule.self, forKey: .basalRateSchedule), insulinSensitivitySchedule: try container.decodeIfPresent(InsulinSensitivitySchedule.self, forKey: .insulinSensitivitySchedule), carbRatioSchedule: try container.decodeIfPresent(CarbRatioSchedule.self, forKey: .carbRatioSchedule), notificationSettings: try container.decodeIfPresent(NotificationSettings.self, forKey: .notificationSettings), controllerDevice: try container.decodeIfPresent(ControllerDevice.self, forKey: .controllerDevice), cgmDevice: try container.decodeIfPresent(CodableDevice.self, forKey: .cgmDevice)?.device, pumpDevice: try container.decodeIfPresent(CodableDevice.self, forKey: .pumpDevice)?.device, bloodGlucoseUnit: bloodGlucoseUnit, automaticDosingStrategy: try container.decodeIfPresent(AutomaticDosingStrategy.self, forKey: .automaticDosingStrategy) ?? .tempBasalOnly, syncIdentifier: try container.decode(UUID.self, forKey: .syncIdentifier)) } public func encode(to encoder: Encoder) throws { let bloodGlucoseUnit = self.bloodGlucoseUnit ?? StoredSettings.codingGlucoseUnit var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(date, forKey: .date) try container.encode(controllerTimeZone, forKey: .controllerTimeZone) try container.encode(dosingEnabled, forKey: .dosingEnabled) try container.encodeIfPresent(glucoseTargetRangeSchedule, forKey: .glucoseTargetRangeSchedule) try container.encodeIfPresent(preMealTargetRange?.doubleRange(for: bloodGlucoseUnit), forKey: .preMealTargetRange) try container.encodeIfPresent(workoutTargetRange?.doubleRange(for: bloodGlucoseUnit), forKey: .workoutTargetRange) try container.encodeIfPresent(overridePresets, forKey: .overridePresets) try container.encodeIfPresent(scheduleOverride, forKey: .scheduleOverride) try container.encodeIfPresent(preMealOverride, forKey: .preMealOverride) try container.encodeIfPresent(maximumBasalRatePerHour, forKey: .maximumBasalRatePerHour) try container.encodeIfPresent(maximumBolus, forKey: .maximumBolus) try container.encodeIfPresent(suspendThreshold, forKey: .suspendThreshold) try container.encodeIfPresent(insulinType, forKey: .insulinType) try container.encodeIfPresent(deviceToken, forKey: .deviceToken) try container.encodeIfPresent(defaultRapidActingModel, forKey: .defaultRapidActingModel) try container.encodeIfPresent(basalRateSchedule, forKey: .basalRateSchedule) try container.encodeIfPresent(insulinSensitivitySchedule, forKey: .insulinSensitivitySchedule) try container.encodeIfPresent(carbRatioSchedule, forKey: .carbRatioSchedule) try container.encodeIfPresent(notificationSettings, forKey: .notificationSettings) try container.encodeIfPresent(controllerDevice, forKey: .controllerDevice) try container.encodeIfPresent(cgmDevice.map { CodableDevice($0) }, forKey: .cgmDevice) try container.encodeIfPresent(pumpDevice.map { CodableDevice($0) }, forKey: .pumpDevice) try container.encode(bloodGlucoseUnit.unitString, forKey: .bloodGlucoseUnit) try container.encode(automaticDosingStrategy, forKey: .automaticDosingStrategy) try container.encode(syncIdentifier, forKey: .syncIdentifier) } public struct ControllerDevice: Codable, Equatable { public let name: String public let systemName: String public let systemVersion: String public let model: String public let modelIdentifier: String public init(name: String, systemName: String, systemVersion: String, model: String, modelIdentifier: String) { self.name = name self.systemName = systemName self.systemVersion = systemVersion self.model = model self.modelIdentifier = modelIdentifier } } private enum CodingKeys: String, CodingKey { case date case controllerTimeZone case dosingEnabled case glucoseTargetRangeSchedule case preMealTargetRange case workoutTargetRange case overridePresets case scheduleOverride case preMealOverride case maximumBasalRatePerHour case maximumBolus case suspendThreshold case deviceToken case insulinType case defaultRapidActingModel case basalRateSchedule case insulinSensitivitySchedule case carbRatioSchedule case notificationSettings case controllerDevice case cgmDevice case pumpDevice case bloodGlucoseUnit case automaticDosingStrategy case syncIdentifier } } // MARK: - Critical Event Log Export extension SettingsStore: CriticalEventLog { private var exportProgressUnitCountPerObject: Int64 { 11 } private var exportFetchLimit: Int { Int(criticalEventLogExportProgressUnitCountPerFetch / exportProgressUnitCountPerObject) } public var exportName: String { "Settings.json" } public func exportProgressTotalUnitCount(startDate: Date, endDate: Date? = nil) -> Result<Int64, Error> { var result: Result<Int64, Error>? self.store.managedObjectContext.performAndWait { do { let request: NSFetchRequest<SettingsObject> = SettingsObject.fetchRequest() request.predicate = self.exportDatePredicate(startDate: startDate, endDate: endDate) let objectCount = try self.store.managedObjectContext.count(for: request) result = .success(Int64(objectCount) * exportProgressUnitCountPerObject) } catch let error { result = .failure(error) } } return result! } public func export(startDate: Date, endDate: Date, to stream: OutputStream, progress: Progress) -> Error? { let encoder = JSONStreamEncoder(stream: stream) var modificationCounter: Int64 = 0 var fetching = true var error: Error? while fetching && error == nil { self.store.managedObjectContext.performAndWait { do { guard !progress.isCancelled else { throw CriticalEventLogError.cancelled } let request: NSFetchRequest<SettingsObject> = SettingsObject.fetchRequest() request.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [NSPredicate(format: "modificationCounter > %d", modificationCounter), self.exportDatePredicate(startDate: startDate, endDate: endDate)]) request.sortDescriptors = [NSSortDescriptor(key: "modificationCounter", ascending: true)] request.fetchLimit = self.exportFetchLimit let objects = try self.store.managedObjectContext.fetch(request) if objects.isEmpty { fetching = false return } try encoder.encode(objects) modificationCounter = objects.last!.modificationCounter progress.completedUnitCount += Int64(objects.count) * exportProgressUnitCountPerObject } catch let fetchError { error = fetchError } } } if let closeError = encoder.close(), error == nil { error = closeError } return error } private func exportDatePredicate(startDate: Date, endDate: Date? = nil) -> NSPredicate { var predicate = NSPredicate(format: "date >= %@", startDate as NSDate) if let endDate = endDate { predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [predicate, NSPredicate(format: "date < %@", endDate as NSDate)]) } return predicate } } // MARK: - Core Data (Bulk) - TEST ONLY extension SettingsStore { public func addStoredSettings(settings: [StoredSettings], completion: @escaping (Error?) -> Void) { guard !settings.isEmpty else { completion(nil) return } dataAccessQueue.async { var error: Error? self.store.managedObjectContext.performAndWait { for setting in settings { guard let data = self.encodeSettings(setting) else { continue } let object = SettingsObject(context: self.store.managedObjectContext) object.data = data object.date = setting.date } error = self.store.save() } guard error == nil else { completion(error) return } self.log.info("Added %d SettingsObjects", settings.count) self.delegate?.settingsStoreHasUpdatedSettingsData(self) completion(nil) } } }
de25e05aa567b4dacad26e750aef2be6
42.658802
161
0.651646
false
false
false
false
r14r-work/fork_swift_intro-playgrounds
refs/heads/master
ScratchPad.playground/section-1.swift
mit
2
// Playground - noun: a place where people can play import UIKit var str: String = "Hello, playground" // Empty Strings var emptyString = "" var anotherEmptyString = String() emptyString.isEmpty // Mutability var catName = "Kaydee" var greeting = "Hello" var message = "" message = greeting message += " " + catName // Immutable Strings let constantMessage = message // ,constantMessage += " " + catName struct Point { var x: Double = 0.0 var y: Double = 0.0 } class Polyline { var points = Array<Point>() } let origin = Point(x: 0.0, y: 0.0) let line = Polyline() class Person { var name: String = "" init(var name: String) { self.name = name } } let pHenryFord = Person(name: "Henry Ford") let pHenryFonda = Person(name: "Henry Fonda") let pInventor = pHenryFord pInventor === pHenryFord pInventor !== pHenryFord pInventor === pHenryFonda pInventor.name = "Albert Einstein" pInventor === pHenryFord pInventor !== pHenryFord var a1 = [1, 2, 3] var a2 = Int[]([1, 2, 3]) var a3 = Array<Int>([1, 2, 3]) a1 === a2 a1 == a2 a1 === a3 a1 == a3 var b1 = a1 b1 a1 === b1 a1[0] = -1 a1 b1 a1.append(4) b1.append(4) a1 === b1 a1 == b1 a1 b1 var c = [1, 2, 3] let d = c.unshare() var v = c.unshare()
367c99db4d9b86d61cd3d0d6b707d68d
11.969072
51
0.627981
false
false
false
false
gdamron/PaulaSynth
refs/heads/master
PaulaSynth/UserSettings.swift
apache-2.0
1
// // UserSettings.swift // AudioEngine2 // // Created by Grant Damron on 10/4/16. // Copyright © 2016 Grant Damron. All rights reserved. // import UIKit import Foundation class UserSettings: NSObject { static let sharedInstance = UserSettings() fileprivate enum Keys: String { case LowNote = "lowNote" case PolyOn = "polyphonyOn" case Scale = "scale" case Sound = "sound" case TabHidden = "tabHidden" } let tabHiddenThresh = 3 var lowNote = 48 { didSet { dirty = true } } var polyphonyOn = false { didSet { dirty = true } } var scale = Scale.Blues { didSet { dirty = true } } var tabHiddenCount = 0 { didSet { dirty = true tabHiddenCount = min(tabHiddenCount, tabHiddenThresh) } } var hideSettingsTab: Bool { return tabHiddenCount >= tabHiddenThresh } var sound = SynthSound.Square fileprivate var dirty = false open func save() { if (dirty) { let defaults = UserDefaults.standard defaults.set(lowNote, forKey: Keys.LowNote.rawValue) defaults.set(polyphonyOn, forKey: Keys.PolyOn.rawValue) defaults.set(scale.rawValue, forKey: Keys.Scale.rawValue) defaults.set(sound.name, forKey: Keys.Sound.rawValue) defaults.set(tabHiddenCount, forKey: Keys.TabHidden.rawValue) defaults.synchronize() dirty = false } } open func load() { let defaults = UserDefaults.standard if defaults.object(forKey: Keys.LowNote.rawValue) != nil { lowNote = defaults.integer(forKey: Keys.LowNote.rawValue) } // default value of false is acceptable polyphonyOn = defaults.bool(forKey: Keys.PolyOn.rawValue) // default vale of 0 is fine tabHiddenCount = defaults.integer(forKey: Keys.TabHidden.rawValue) if let val = defaults.string(forKey: Keys.Scale.rawValue), let s = Scale(rawValue: val) { scale = s } if let soundVal = defaults.string(forKey: Keys.Sound.rawValue) { sound = SynthSound(key: soundVal) } } }
65b0d5826722bdd581c7e0d61a255fbb
25.087912
74
0.564448
false
false
false
false
barbosa/clappr-ios
refs/heads/master
Pod/Classes/View/BorderView.swift
bsd-3-clause
1
import UIKit @IBDesignable class BorderView: UIView { @IBInspectable var cornerRadius: CGFloat = 0 { didSet { layer.cornerRadius = cornerRadius layer.masksToBounds = cornerRadius > 0 } } @IBInspectable var borderWidth: CGFloat = 0 { didSet { layer.borderWidth = borderWidth } } @IBInspectable var borderColor: UIColor? { didSet { layer.borderColor = borderColor?.CGColor } } }
67c60ab333c65a7d2abcc44b3cc38d48
20.782609
52
0.57485
false
false
false
false
material-components/material-components-ios
refs/heads/develop
components/Ripple/examples/UICollectionViewWithRippleExample.swift
apache-2.0
2
// Copyright 2020-present the Material Components for iOS authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import UIKit import MaterialComponents.MaterialRipple import MaterialComponents.MaterialContainerScheme class RippleCell: UICollectionViewCell { var rippleView: MDCRippleView! override init(frame: CGRect) { super.init(frame: frame) rippleView = MDCRippleView(frame: self.contentView.bounds) self.contentView.addSubview(rippleView) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class UICollectionViewWithRippleExample: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, MDCRippleTouchControllerDelegate { let collectionView = UICollectionView( frame: .zero, collectionViewLayout: UICollectionViewFlowLayout()) var rippleTouchController: MDCRippleTouchController? @objc var containerScheme: MDCContainerScheming! override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { containerScheme = MDCContainerScheme() super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = containerScheme.colorScheme.backgroundColor collectionView.backgroundColor = containerScheme.colorScheme.backgroundColor collectionView.frame = view.bounds collectionView.dataSource = self collectionView.delegate = self collectionView.backgroundColor = .white collectionView.alwaysBounceVertical = true collectionView.register(RippleCell.self, forCellWithReuseIdentifier: "Cell") collectionView.translatesAutoresizingMaskIntoConstraints = false collectionView.allowsMultipleSelection = true view.addSubview(collectionView) rippleTouchController = MDCRippleTouchController(view: collectionView) rippleTouchController?.delegate = self let guide = view.safeAreaLayoutGuide NSLayoutConstraint.activate([ collectionView.leftAnchor.constraint(equalTo: guide.leftAnchor), collectionView.rightAnchor.constraint(equalTo: guide.rightAnchor), collectionView.topAnchor.constraint(equalTo: view.topAnchor), collectionView.bottomAnchor.constraint(equalTo: guide.bottomAnchor), ]) collectionView.contentInsetAdjustmentBehavior = .always } func preiOS11Constraints() { self.view.addConstraints( NSLayoutConstraint.constraints( withVisualFormat: "H:|[view]|", options: [], metrics: nil, views: ["view": collectionView])) self.view.addConstraints( NSLayoutConstraint.constraints( withVisualFormat: "V:|[view]|", options: [], metrics: nil, views: ["view": collectionView])) } func collectionView( _ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath ) -> UICollectionViewCell { guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as? RippleCell else { fatalError() } cell.layer.borderWidth = 1 cell.layer.borderColor = UIColor.lightGray.cgColor cell.backgroundColor = containerScheme.colorScheme.surfaceColor return cell } func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView( _ collectionView: UICollectionView, numberOfItemsInSection section: Int ) -> Int { return 30 } func collectionView( _ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath ) -> CGSize { let size = collectionView.bounds.size.width - 12 return CGSize(width: size, height: 60) } func collectionView( _ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int ) -> UIEdgeInsets { return UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8) } func collectionView( _ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int ) -> CGFloat { return 8 } func collectionView( _ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int ) -> CGFloat { return 8 } func rippleTouchController( _ rippleTouchController: MDCRippleTouchController, rippleViewAtTouchLocation location: CGPoint ) -> MDCRippleView? { guard let indexPath = self.collectionView.indexPathForItem(at: location) else { return nil } let cell = self.collectionView.cellForItem(at: indexPath) as? RippleCell if let cell = cell { return cell.rippleView } return nil } } extension UICollectionViewWithRippleExample { @objc class func catalogMetadata() -> [String: Any] { return [ "breadcrumbs": ["Ripple", "UICollectionView with Ripple"], "primaryDemo": false, "presentable": false, ] } }
81656823eb152b9e803d61f67bda140d
29.935135
96
0.73755
false
false
false
false
Wolox/wolmo-core-ios
refs/heads/master
WolmoCoreTests/Extensions/Foundation/RawRepresentableSpec.swift
mit
1
// // RawRepresentable.swift // WolmoCore // // Created by Francisco Depascuali on 7/18/16. // Copyright © 2016 Wolox. All rights reserved. // import Foundation import Quick import Nimble import WolmoCore private enum IntRepresentable: Int { case zero case one case two case three } public class RawRepresentableSpec: QuickSpec { override public func spec() { describe("#allValues") { context("When specifying an existent initial value") { it("should return all values starting at the initial value") { let values = Array(IntRepresentable.allValues(startingAt: .one)) expect(values).to(equal([.one, .two, .three])) } context("When the value is the first one") { it("should return all values") { let values = Array(IntRepresentable.allValues(startingAt: .zero)) expect(values).to(equal([.zero, .one, .two, .three])) } } context("When the value is the last one") { it("should return the last value") { let values = Array(IntRepresentable.allValues(startingAt: .three)) expect(values).to(equal([.three])) } } } } describe("#count") { context("When specifying an initial value") { it("should return the count of all the values starting at the initial value") { expect(IntRepresentable.count(startingAt: .one)).to(equal(3)) } context("When the value is the first one") { it("should return the count of all the values") { expect(IntRepresentable.count(startingAt: .zero)).to(equal(4)) } } context("When the value is the last one") { it("should return one") { expect(IntRepresentable.count(startingAt: .three)).to(equal(1)) } } } } } } public class RawRepresentableGeneratorSpec: QuickSpec { override public func spec() { var generator: RawRepresentableGenerator<Int, IntRepresentable>! beforeEach { generator = RawRepresentableGenerator(startingAt: .zero) { $0 } } describe("#next") { context("When using the identity function as generator") { it("should return always the same element") { expect(generator.next()).to(equal(IntRepresentable.zero)) expect(generator.next()).to(equal(IntRepresentable.zero)) } } context("When adding one in the generator") { beforeEach { generator = RawRepresentableGenerator(startingAt: .zero) { IntRepresentable(rawValue: $0.rawValue + 1) } } it("should return the following element until there is no following") { expect(generator.next()).to(equal(IntRepresentable.zero)) expect(generator.next()).to(equal(IntRepresentable.one)) expect(generator.next()).to(equal(IntRepresentable.two)) expect(generator.next()).to(equal(IntRepresentable.three)) expect(generator.next()).to(beNil()) expect(generator.next()).to(beNil()) } } } } }
41e5033f6882ff03b0f0c56e0c948335
37.229167
124
0.518529
false
false
false
false
spothero/SHEmailValidator
refs/heads/master
Sources/SpotHeroEmailValidator/SpotHeroEmailValidator.swift
apache-2.0
1
// Copyright © 2021 SpotHero, Inc. All rights reserved. import Foundation // TODO: Remove NSObject when entirely converted into Swift public class SpotHeroEmailValidator: NSObject { private typealias EmailParts = (username: String, hostname: String, tld: String) public static let shared = SpotHeroEmailValidator() private let commonTLDs: [String] private let commonDomains: [String] private let ianaRegisteredTLDs: [String] override private init() { var dataDictionary: NSDictionary? // All TLDs registered with IANA as of October 8th, 2019 at 11:28 AM CST (latest list at: http://data.iana.org/TLD/tlds-alpha-by-domain.txt) if let plistPath = Bundle.module.path(forResource: "DomainData", ofType: "plist") { dataDictionary = NSDictionary(contentsOfFile: plistPath) } self.commonDomains = dataDictionary?["CommonDomains"] as? [String] ?? [] self.commonTLDs = dataDictionary?["CommonTLDs"] as? [String] ?? [] self.ianaRegisteredTLDs = dataDictionary?["IANARegisteredTLDs"] as? [String] ?? [] } public func validateAndAutocorrect(emailAddress: String) throws -> SHValidationResult { do { // Attempt to get an autocorrect suggestion // As long as no error is thrown, we can consider the email address to have passed validation let autocorrectSuggestion = try self.autocorrectSuggestion(for: emailAddress) return SHValidationResult(passedValidation: true, autocorrectSuggestion: autocorrectSuggestion) } catch { return SHValidationResult(passedValidation: false, autocorrectSuggestion: nil) } } public func autocorrectSuggestion(for emailAddress: String) throws -> String? { // Attempt to validate the syntax of the email address // If the email address has incorrect format or syntax, an error will be thrown try self.validateSyntax(of: emailAddress) // Split the email address into its component parts let emailParts = try self.splitEmailAddress(emailAddress) var suggestedTLD = emailParts.tld if !self.ianaRegisteredTLDs.contains(emailParts.tld), let closestTLD = self.closestString(for: emailParts.tld, fromArray: self.commonTLDs, withTolerance: 0.5) { suggestedTLD = closestTLD } var suggestedDomain = "\(emailParts.hostname).\(suggestedTLD)" if !self.commonDomains.contains(suggestedDomain), let closestDomain = self.closestString(for: suggestedDomain, fromArray: self.commonDomains, withTolerance: 0.25) { suggestedDomain = closestDomain } let suggestedEmailAddress = "\(emailParts.username)@\(suggestedDomain)" guard suggestedEmailAddress != emailAddress else { return nil } return suggestedEmailAddress } @discardableResult public func validateSyntax(of emailAddress: String) throws -> Bool { // Split the email address into parts let emailParts = try self.splitEmailAddress(emailAddress) // Ensure the username is valid by itself guard emailParts.username.isValidEmailUsername() else { throw Error.invalidUsername } // Combine the hostname and TLD into the domain" let domain = "\(emailParts.hostname).\(emailParts.tld)" // Ensure the domain is valid guard domain.isValidEmailDomain() else { throw Error.invalidDomain } // Ensure that the entire email forms a syntactically valid email guard emailAddress.isValidEmail() else { throw Error.invalidSyntax } return true } // TODO: Use better name for array parameter private func closestString(for string: String, fromArray array: [String], withTolerance tolerance: Float) -> String? { guard !array.contains(string) else { return nil } var closestString: String? var closestDistance = Int.max // TODO: Use better name for arrayString parameter for arrayString in array { let distance = Int(string.levenshteinDistance(from: arrayString)) if distance < closestDistance, Float(distance) / Float(string.count) < tolerance { closestDistance = distance closestString = arrayString } } return closestString } private func splitEmailAddress(_ emailAddress: String) throws -> EmailParts { let emailAddressParts = emailAddress.split(separator: "@") guard emailAddressParts.count == 2 else { // There are either no @ symbols or more than one @ symbol, throw an error throw Error.invalidSyntax } // Extract the username from the email address parts let username = String(emailAddressParts.first ?? "") // Extract the full domain (including TLD) from the email address parts let fullDomain = String(emailAddressParts.last ?? "") // Split the domain parts for evaluation let domainParts = fullDomain.split(separator: ".") guard domainParts.count >= 2 else { // There are no periods found in the domain, throw an error throw Error.invalidDomain } // TODO: This logic is wrong and doesn't take subdomains into account. We should compare TLDs against the commonTLDs list." // Extract the domain from the domain parts let domain = domainParts.first?.lowercased() ?? "" // Extract the TLD from the domain parts, which are all the remaining parts joined with a period again let tld = domainParts.dropFirst().joined(separator: ".") return (username, domain, tld) } } // MARK: - Extensions public extension SpotHeroEmailValidator { enum Error: Int, LocalizedError { case blankAddress = 1000 case invalidSyntax = 1001 case invalidUsername = 1002 case invalidDomain = 1003 public var errorDescription: String? { switch self { case .blankAddress: return "The entered email address is blank." case .invalidDomain: return "The domain name section of the entered email address is invalid." case .invalidSyntax: return "The syntax of the entered email address is invalid." case .invalidUsername: return "The username section of the entered email address is invalid." } } } } private extension String { /// RFC 5322 Official Standard Email Regex Pattern /// /// Sources: /// - [How to validate an email address using a regular expression? (Stack Overflow)](https://stackoverflow.com/questions/201323/how-to-validate-an-email-address-using-a-regular-expression) /// - [What characters are allowed in an email address? (Stack Overflow](https://stackoverflow.com/questions/2049502/what-characters-are-allowed-in-an-email-address) private static let emailRegexPattern = "\(Self.emailUsernameRegexPattern)@\(Self.emailDomainRegexPattern)" // swiftlint:disable:next line_length private static let emailUsernameRegexPattern = #"(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")"# // swiftlint:disable:next line_length private static let emailDomainRegexPattern = #"(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])"# func isValidEmail() -> Bool { return self.range(of: Self.emailRegexPattern, options: .regularExpression) != nil } func isValidEmailUsername() -> Bool { return !self.hasPrefix(".") && !self.hasSuffix(".") && (self as NSString).range(of: "..").location == NSNotFound && self.range(of: Self.emailUsernameRegexPattern, options: .regularExpression) != nil } func isValidEmailDomain() -> Bool { return self.range(of: Self.emailDomainRegexPattern, options: .regularExpression) != nil } }
d7ed6f1e0621236945bcfce55a0a7403
41.627451
342
0.62247
false
false
false
false
iRoxx/WordPress-iOS
refs/heads/develop
WordPress/WordPressTest/ContextManagerTests.swift
gpl-2.0
1
import Foundation import XCTest import CoreData class ContextManagerTests: XCTestCase { var contextManager:TestContextManager! override func setUp() { super.setUp() contextManager = TestContextManager() } override func tearDown() { super.tearDown() } func testIterativeMigration() { let model19Name = "WordPress 19" // Instantiate a Model 19 Stack startupCoredataStack(model19Name) let mocOriginal = contextManager.mainContext let psc = contextManager.persistentStoreCoordinator // Insert a Theme Entity let objectOriginal = NSEntityDescription.insertNewObjectForEntityForName("Theme", inManagedObjectContext: mocOriginal) as NSManagedObject mocOriginal.obtainPermanentIDsForObjects([objectOriginal], error: nil) var error: NSError? mocOriginal.save(&error) let objectID = objectOriginal.objectID XCTAssertFalse(objectID.temporaryID, "Should be a permanent object") // Migrate to the latest let persistentStore = psc.persistentStores.first as? NSPersistentStore psc.removePersistentStore(persistentStore!, error: nil); let standardPSC = contextManager.standardPSC XCTAssertNotNil(standardPSC, "New store should exist") XCTAssertTrue(standardPSC.persistentStores.count == 1, "Should be one persistent store.") // Verify if the Theme Entity is there let mocSecond = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.MainQueueConcurrencyType) mocSecond.persistentStoreCoordinator = standardPSC let object = mocSecond.existingObjectWithID(objectID, error: nil) XCTAssertNotNil(object, "Object should exist in new PSC") } func testMigrate20to21PreservingDefaultAccount() { let model20Name = "WordPress 20" let model21Name = "WordPress 21" // Instantiate a Model 20 Stack startupCoredataStack(model20Name) let mainContext = contextManager.mainContext let psc = contextManager.persistentStoreCoordinator // Insert a WordPress.com account with a Jetpack blog let wrongAccount = newAccountInContext(mainContext) let wrongBlog = newBlogInAccount(wrongAccount) wrongAccount.addJetpackBlogsObject(wrongBlog) // Insert a WordPress.com account with a Dotcom blog let rightAccount = newAccountInContext(mainContext) let rightBlog = newBlogInAccount(rightAccount) rightAccount.addBlogsObject(rightBlog) rightAccount.username = "Right" // Insert an offsite WordPress account let offsiteAccount = newAccountInContext(mainContext) offsiteAccount.isWpcom = false mainContext.obtainPermanentIDsForObjects([wrongAccount, rightAccount, offsiteAccount], error: nil) mainContext.save(nil) // Set the DefaultDotCom let oldRightAccountURL = rightAccount.objectID.URIRepresentation() NSUserDefaults.standardUserDefaults().setURL(oldRightAccountURL, forKey: "AccountDefaultDotcom") NSUserDefaults.standardUserDefaults().synchronize() // Initialize 20 > 21 Migration let secondContext = performCoredataMigration(model21Name) // Verify that the three accounts made it through let allAccountsRequest = NSFetchRequest(entityName: "Account") let numberOfAccounts = secondContext.countForFetchRequest(allAccountsRequest, error: nil) XCTAssertTrue(numberOfAccounts == 3, "Should have three accounts") // Verify if the Default Account is the right one let newRightAccountURL = NSUserDefaults.standardUserDefaults().URLForKey("AccountDefaultDotcom") XCTAssert(newRightAccountURL != nil, "Default Account's URL is missing") let objectID = secondContext.persistentStoreCoordinator?.managedObjectIDForURIRepresentation(newRightAccountURL!) XCTAssert(objectID != nil, "Invalid newRightAccount URL") let reloadedRightAccount = secondContext.existingObjectWithID(objectID!, error: nil) as? WPAccount XCTAssert(reloadedRightAccount != nil, "Couldn't load the right default account") XCTAssert(reloadedRightAccount!.username! == "Right", "Invalid default account") } func testMigrate21to23WithoutRunningAccountsFix() { let model21Name = "WordPress 21" let model23Name = "WordPress 23" // Instantiate a Model 21 Stack startupCoredataStack(model21Name) let mainContext = contextManager.mainContext let psc = contextManager.persistentStoreCoordinator // Insert a WPAccount entity let dotcomAccount = newAccountInContext(mainContext) let offsiteAccount = newAccountInContext(mainContext) offsiteAccount.isWpcom = false offsiteAccount.username = "OffsiteUsername" mainContext.obtainPermanentIDsForObjects([dotcomAccount, offsiteAccount], error: nil) mainContext.save(nil) // Set the DefaultDotCom let dotcomAccountURL = dotcomAccount.objectID.URIRepresentation() NSUserDefaults.standardUserDefaults().setURL(dotcomAccountURL, forKey: "AccountDefaultDotcom") NSUserDefaults.standardUserDefaults().synchronize() // Initialize 21 > 23 Migration let secondContext = performCoredataMigration(model23Name) // Verify that the two accounts have been migrated let fetchRequest = NSFetchRequest(entityName: "Account") let numberOfAccounts = secondContext.countForFetchRequest(fetchRequest, error: nil) XCTAssertTrue(numberOfAccounts == 2, "Should have two account") // Verify if the Default Account is the right one let defaultAccountUUID = NSUserDefaults.standardUserDefaults().stringForKey("AccountDefaultDotcomUUID") XCTAssert(defaultAccountUUID != nil, "Missing UUID") let request = NSFetchRequest(entityName: "Account") request.predicate = NSPredicate(format: "uuid == %@", defaultAccountUUID!) let results = secondContext.executeFetchRequest(request, error: nil) as? [WPAccount] XCTAssert(results!.count == 1, "Default account not found") let defaultAccount = results!.first! XCTAssert(defaultAccount.username == "username", "Invalid Default Account") } func testMigrate21to23RunningAccountsFix() { let model21Name = "WordPress 21" let model23Name = "WordPress 23" // Instantiate a Model 21 Stack startupCoredataStack(model21Name) let mainContext = contextManager.mainContext let psc = contextManager.persistentStoreCoordinator // Insert a WordPress.com account with a Jetpack blog let wrongAccount = newAccountInContext(mainContext) let wrongBlog = newBlogInAccount(wrongAccount) wrongAccount.addJetpackBlogsObject(wrongBlog) // Insert a WordPress.com account with a Dotcom blog let rightAccount = newAccountInContext(mainContext) let rightBlog = newBlogInAccount(rightAccount) rightAccount.addBlogsObject(rightBlog) rightAccount.username = "Right" // Insert an offsite WordPress account let offsiteAccount = newAccountInContext(mainContext) offsiteAccount.isWpcom = false mainContext.obtainPermanentIDsForObjects([wrongAccount, rightAccount, offsiteAccount], error: nil) mainContext.save(nil) // Set the DefaultDotCom let offsiteAccountURL = offsiteAccount.objectID.URIRepresentation() NSUserDefaults.standardUserDefaults().setURL(offsiteAccountURL, forKey: "AccountDefaultDotcom") NSUserDefaults.standardUserDefaults().synchronize() // Initialize 21 > 23 Migration let secondContext = performCoredataMigration(model23Name) // Verify that the three accounts made it through let allAccountsRequest = NSFetchRequest(entityName: "Account") let numberOfAccounts = secondContext.countForFetchRequest(allAccountsRequest, error: nil) XCTAssertTrue(numberOfAccounts == 3, "Should have three accounts") // Verify if the Default Account is the right one let accountUUID = NSUserDefaults.standardUserDefaults().stringForKey("AccountDefaultDotcomUUID") XCTAssert(accountUUID != nil, "Default Account's UUID is missing") let request = NSFetchRequest(entityName: "Account") request.predicate = NSPredicate(format: "uuid == %@", accountUUID!) let results = secondContext.executeFetchRequest(request, error: nil) as? [WPAccount] XCTAssert(results != nil, "Default Account has been lost") XCTAssert(results?.count == 1, "UUID is not unique!") let username = results?.first?.username XCTAssert(username! == "Right", "Invalid default account") } // MARK: - Helper Methods private func startupCoredataStack(modelName: String) { let modelURL = urlForModelName(modelName) let model = NSManagedObjectModel(contentsOfURL: modelURL!) let persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: model!) let storeUrl = contextManager.storeURL() removeStoresBasedOnStoreURL(storeUrl) let persistentStore = persistentStoreCoordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeUrl, options: nil, error: nil) XCTAssertNotNil(persistentStore, "Store should exist") let mainContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.MainQueueConcurrencyType) mainContext.persistentStoreCoordinator = persistentStoreCoordinator contextManager.managedObjectModel = model contextManager.mainContext = mainContext contextManager.persistentStoreCoordinator = persistentStoreCoordinator } private func performCoredataMigration(newModelName: String) -> NSManagedObjectContext { let psc = contextManager.persistentStoreCoordinator let mainContext = contextManager.mainContext let persistentStore = psc.persistentStores.first as? NSPersistentStore psc.removePersistentStore(persistentStore!, error: nil); let newModelURL = urlForModelName(newModelName) contextManager.managedObjectModel = NSManagedObjectModel(contentsOfURL: newModelURL!) let standardPSC = contextManager.standardPSC XCTAssertNotNil(standardPSC, "New store should exist") XCTAssertTrue(standardPSC.persistentStores.count == 1, "Should be one persistent store.") let secondContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.MainQueueConcurrencyType) secondContext.persistentStoreCoordinator = standardPSC return secondContext } private func urlForModelName(name: NSString!) -> NSURL? { var bundle = NSBundle.mainBundle() var url = bundle.URLForResource(name, withExtension: "mom") if url == nil { var momdPaths = bundle.pathsForResourcesOfType("momd", inDirectory: nil); for momdPath in momdPaths { url = bundle.URLForResource(name, withExtension: "mom", subdirectory: momdPath.lastPathComponent) } } return url } private func removeStoresBasedOnStoreURL(storeURL: NSURL) { let fileManager = NSFileManager.defaultManager() let directoryUrl = storeURL.URLByDeletingLastPathComponent let files = fileManager.contentsOfDirectoryAtURL(directoryUrl!, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions.SkipsSubdirectoryDescendants, error: nil) as Array<NSURL> for file in files { let range = file.lastPathComponent.rangeOfString(storeURL.lastPathComponent, options: nil, range: nil, locale: nil) if range?.startIndex != range?.endIndex { fileManager.removeItemAtURL(file, error: nil) } } } private func newAccountInContext(context: NSManagedObjectContext) -> WPAccount { let account = NSEntityDescription.insertNewObjectForEntityForName("Account", inManagedObjectContext: context) as WPAccount account.username = "username" account.isWpcom = true account.authToken = "authtoken" account.xmlrpc = "http://example.com/xmlrpc.php" return account } private func newBlogInAccount(account: WPAccount) -> Blog { let blog = NSEntityDescription.insertNewObjectForEntityForName("Blog", inManagedObjectContext: account.managedObjectContext!) as Blog blog.xmlrpc = "http://test.blog/xmlrpc.php"; blog.url = "http://test.blog/"; blog.account = account return blog; } }
d6a47537d61bd00ad702442f4b8acd17
44.539519
201
0.693103
false
false
false
false
mattjgalloway/emoncms-ios
refs/heads/master
EmonCMSiOS/UI/View Controllers/FeedListViewController.swift
mit
1
// // ViewController.swift // EmonCMSiOS // // Created by Matt Galloway on 11/09/2016. // Copyright © 2016 Matt Galloway. All rights reserved. // import UIKit import RxSwift import RxCocoa import RxDataSources final class FeedListViewController: UITableViewController { var viewModel: FeedListViewModel! fileprivate let dataSource = RxTableViewSectionedReloadDataSource<FeedListViewModel.Section>() fileprivate let disposeBag = DisposeBag() fileprivate enum Segues: String { case showFeed } override func viewDidLoad() { super.viewDidLoad() self.title = "Feeds" self.setupDataSource() self.setupBindings() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.viewModel.active.value = true } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) self.viewModel.active.value = false } private func setupDataSource() { self.dataSource.configureCell = { (ds, tableView, indexPath, item) in let cell = tableView.dequeueReusableCell(withIdentifier: "FeedCell", for: indexPath) cell.textLabel?.text = item.name cell.detailTextLabel?.text = item.value return cell } self.dataSource.titleForHeaderInSection = { (ds, index) in return ds.sectionModels[index].model } self.tableView.delegate = nil self.tableView.dataSource = nil self.viewModel.feeds .drive(self.tableView.rx.items(dataSource: self.dataSource)) .addDisposableTo(self.disposeBag) } private func setupBindings() { let refreshControl = self.tableView.refreshControl! refreshControl.rx.controlEvent(.valueChanged) .bindTo(self.viewModel.refresh) .addDisposableTo(self.disposeBag) self.viewModel.isRefreshing .drive(refreshControl.rx.refreshing) .addDisposableTo(self.disposeBag) } } extension FeedListViewController { override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == Segues.showFeed.rawValue { let feedViewController = segue.destination as! FeedChartViewController let selectedIndexPath = self.tableView.indexPathForSelectedRow! let item = self.dataSource[selectedIndexPath] let viewModel = self.viewModel.feedChartViewModel(forItem: item) feedViewController.viewModel = viewModel } } }
e94c420ff33d72f362e123e84c9907ce
25.197802
96
0.72651
false
false
false
false
HighBay/PageMenu
refs/heads/master
Demos/Demo 4/PageMenuDemoTabbar/PageMenuDemoTabbar/PageMenuTwoViewController.swift
bsd-3-clause
4
// // PageMenuTwoViewController.swift // PageMenuDemoTabbar // // Created by Niklas Fahl on 1/9/15. // Copyright (c) 2015 Niklas Fahl. All rights reserved. // import UIKit import PageMenu class PageMenuTwoViewController: UIViewController { var pageMenu : CAPSPageMenu? override func viewDidLoad() { super.viewDidLoad() // MARK: - Scroll menu setup // Initialize view controllers to display and place in array var controllerArray : [UIViewController] = [] let controller1 : TestTableViewController = TestTableViewController(nibName: "TestTableViewController", bundle: nil) controller1.title = "friends" controllerArray.append(controller1) let controller2 : TestCollectionViewController = TestCollectionViewController(nibName: "TestCollectionViewController", bundle: nil) controller2.title = "mood" controllerArray.append(controller2) let controller3 : TestCollectionViewController = TestCollectionViewController(nibName: "TestCollectionViewController", bundle: nil) controller3.title = "favorites" controllerArray.append(controller3) let controller4 : TestTableViewController = TestTableViewController(nibName: "TestTableViewController", bundle: nil) controller4.title = "music" controllerArray.append(controller4) // Customize menu (Optional) let parameters: [CAPSPageMenuOption] = [ .scrollMenuBackgroundColor(UIColor(red: 20.0/255.0, green: 20.0/255.0, blue: 20.0/255.0, alpha: 1.0)), .viewBackgroundColor(UIColor(red: 20.0/255.0, green: 20.0/255.0, blue: 20.0/255.0, alpha: 1.0)), .selectionIndicatorColor(UIColor.orange), .addBottomMenuHairline(false), .menuItemFont(UIFont(name: "HelveticaNeue", size: 35.0)!), .menuHeight(50.0), .selectionIndicatorHeight(0.0), .menuItemWidthBasedOnTitleTextWidth(true), .selectedMenuItemLabelColor(UIColor.orange) ] // Initialize scroll menu pageMenu = CAPSPageMenu(viewControllers: controllerArray, frame: CGRect(x: 0.0, y: 60.0, width: self.view.frame.width, height: self.view.frame.height - 60.0), pageMenuOptions: parameters) self.view.addSubview(pageMenu!.view) } }
bfb317474846dcff544e095ca8ab5d31
42.851852
195
0.673986
false
true
false
false
lanstonpeng/Focord2
refs/heads/master
Focord2/GameCountingCircleView.swift
mit
1
// // GameCountingCircleView.swift // Focord2 // // Created by Lanston Peng on 8/20/14. // Copyright (c) 2014 Vtm. All rights reserved. // import UIKit import CoreMotion protocol GameCountingCircleDelegate:NSObjectProtocol { func GameCountingCircleDidEndCount(circleKey:NSString) func GameCountingCircleDidChange(circleKey:NSString) } class GameCountingCircleView: UIView,NSCopying { var indicatorLabel:UILabel? var pieCapacity:CGFloat{ didSet{ self.setNeedsDisplay() } } var clockWise:Int32!//0=逆时针,1=顺时针 var currentCount:Int var deltaCount:Int! var destinationCount:Int var circleKey:NSString! var frontColor:UIColor! var circleColor:UIColor! var delegate:GameCountingCircleDelegate? let frontLayer:CALayer! let frontBgLayer:CALayer! let circleLayer:CAShapeLayer! var timer:NSTimer? var startX:CGFloat! var startY:CGFloat! var radius:CGFloat! var pieStart:CGFloat! // func addCount(deltaNum:Int) // func addCount(deltaNum:Int isReverse:Bool) // func initShapeLayer() internal var f:CGRect! internal var addCountCurrentNumber:CGFloat var animator:UIDynamicAnimator! var gravity:UIGravityBehavior! var collision:UICollisionBehavior! var totalCount: Int { didSet { self.indicatorLabel?.text = "\(totalCount)" } } override init(frame: CGRect) { f = frame addCountCurrentNumber = 0 pieStart = 270 pieCapacity = 360 clockWise = 0 currentCount = 0 deltaCount = 0 destinationCount = 0 circleKey = "timeCount" frontLayer = CALayer() frontBgLayer = CALayer() circleLayer = CAShapeLayer() totalCount = 0 super.init(frame: frame) let smallerFrame:CGRect = CGRectInset(self.bounds, 10, 10) radius = smallerFrame.size.width/2 + 1 startX = self.bounds.size.width/2 startY = self.bounds.size.height/2 self.backgroundColor = UIColor.clearColor() self.clipsToBounds = false self.layer.masksToBounds = false frontLayer.frame = smallerFrame frontLayer.backgroundColor = UIColor(red: 0.0/255, green: 206.0/255, blue: 97.0/255, alpha: 1.0).CGColor frontLayer.cornerRadius = smallerFrame.size.width / 2; circleLayer.fillColor = UIColor.clearColor().CGColor circleLayer.strokeStart = 0; circleLayer.strokeEnd = 1; circleLayer.lineWidth = 5; circleLayer.lineCap = "round"; self.layer.addSublayer(frontLayer) self.layer.insertSublayer(circleLayer, below:frontLayer) } required init(coder aDecoder: NSCoder) { f = CGRectZero currentCount = 0 addCountCurrentNumber = 0 destinationCount = 0 pieCapacity = 360 totalCount = 0 //super.init() super.init(coder: aDecoder) } func startCounting() { if timer == nil { timer = NSTimer.scheduledTimerWithTimeInterval(1.0/30, target: self, selector: "updateSector", userInfo: nil, repeats: true) } } func stopCounting(){ timer?.invalidate() timer = nil } func initData(toCount desCount:Int,withStart startCount:Int) { indicatorLabel = UILabel(frame:self.bounds) self.currentCount = startCount; destinationCount = desCount; deltaCount = abs(destinationCount - startCount) indicatorLabel?.textAlignment = NSTextAlignment.Center //indicatorLabel?.textColor = UIColor(red: 254.0/255, green: 213.0/255, blue: 49.0/255, alpha: 1) indicatorLabel?.textColor = UIColor.whiteColor() indicatorLabel?.font = UIFont(name: "AppleSDGothicNeo-Thin", size: 40.0) indicatorLabel?.adjustsFontSizeToFitWidth = true indicatorLabel?.layer.shadowOpacity = 0.5 indicatorLabel?.layer.shadowOffset = CGSizeMake(0,2) indicatorLabel?.layer.shadowColor = UIColor.blackColor().CGColor indicatorLabel?.layer.shadowRadius = 1.5 indicatorLabel?.layer.masksToBounds = false indicatorLabel?.text = "0" self.addSubview(indicatorLabel!) } func copyWithZone(zone: NSZone) -> AnyObject! { let c:GameCountingCircleView = GameCountingCircleView(frame: self.f) c.initData(toCount: self.destinationCount, withStart: self.currentCount) c.indicatorLabel?.text = self.indicatorLabel?.text return c } func bigifyCircleByUnit() { frontLayer.frame = CGRectInset(frontLayer.frame, -1, -1) self.bounds = CGRectInset(self.bounds, -1, -1) frontLayer.cornerRadius = frontLayer.frame.size.width / 2; radius = frontLayer.frame.size.width/2 + 1 } func dropCicleView() { if animator == nil { animator = UIDynamicAnimator(referenceView: self.superview) collision = UICollisionBehavior(items: [self]) collision.translatesReferenceBoundsIntoBoundary = true gravity = UIGravityBehavior(items: [self]) animator.addBehavior(collision) MotionManager.instance.startListenDeviceMotion({ (deviceMotion:CMDeviceMotion!, error:NSError!) -> Void in let gravityVector:CMAcceleration = deviceMotion.gravity self.gravity.gravityDirection = CGVectorMake(CGFloat(gravityVector.x), CGFloat(-gravityVector.y)) }) } animator.addBehavior(gravity) } func updateSector() { //pieCapacity += 360.0 / CGFloat(destinationCount / (1.0) / 30.0 ) pieCapacity -= 18 * 1/30 addCountCurrentNumber += 1 if addCountCurrentNumber >= 30 { addCountCurrentNumber = 0 currentCount -= 1 if currentCount == destinationCount { self.delegate?.GameCountingCircleDidEndCount(self.circleKey) } else { self.delegate?.GameCountingCircleDidChange(self.circleKey) } } //self.setNeedsDisplay() } func DEG2RAD(angle:CGFloat) -> CGFloat { return ( angle ) * 3.1415926 / 180.0 } override func drawRect(rect: CGRect) { let context:CGContextRef = UIGraphicsGetCurrentContext(); //CGContextSetRGBStrokeColor(context, 0, 1, 1, 1); CGContextSetStrokeColorWithColor(context, UIColor(red: 254.0/255, green: 213.0/255, blue: 49.0/255, alpha: 1).CGColor); CGContextSetLineWidth(context, 5); CGContextSetLineCap(context, kCGLineCapRound); CGContextAddArc(context, startX, startY, radius, self.DEG2RAD(pieStart), self.DEG2RAD(pieStart + pieCapacity), clockWise); CGContextStrokePath(context); } }
5aaddd2cd1708f82924884d8d2d28774
29.679654
136
0.621561
false
false
false
false
asynchrony/Re-Lax
refs/heads/master
ReLax/ReLax/ReLaxResource.swift
mit
1
import Foundation struct ReLaxResource { private final class BundleClass { } static let bundle = Bundle(for: BundleClass.self) static let radiosityURL = bundle.url(forResource: "blue-radiosity", withExtension: nil)! static let tmfkPrefixData = bundle.url(forResource: "tmfkPrefixData", withExtension: nil)! static let tmfkLayerData = bundle.url(forResource: "tmfkLayerData", withExtension: nil)! static let bomTableStart = bundle.url(forResource: "bomTableStart", withExtension: nil)! }
6788ce097859c9c2ecdee36977bcf1f6
44.090909
91
0.780242
false
false
false
false
wireapp/wire-ios
refs/heads/develop
Wire-iOS/Sources/UserInterface/Settings/ChangingDetails/ChangeHandleViewController.swift
gpl-3.0
1
// // Wire // Copyright (C) 2016 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation import UIKit import WireSyncEngine fileprivate extension UIView { func wiggle() { let animation = CAKeyframeAnimation() animation.keyPath = "position.x" animation.duration = 0.3 animation.isAdditive = true animation.values = [0, 4, -4, 2, 0] animation.keyTimes = [0, 0.166, 0.5, 0.833, 1] layer.add(animation, forKey: "wiggle-animation") } } protocol ChangeHandleTableViewCellDelegate: AnyObject { func tableViewCell(cell: ChangeHandleTableViewCell, shouldAllowEditingText text: String) -> Bool func tableViewCellDidChangeText(cell: ChangeHandleTableViewCell, text: String) } final class ChangeHandleTableViewCell: UITableViewCell, UITextFieldDelegate { weak var delegate: ChangeHandleTableViewCellDelegate? let prefixLabel: UILabel = { let label = UILabel() label.font = .normalSemiboldFont label.textColor = SemanticColors.Label.textDefault return label }() let handleTextField: UITextField = { let textField = UITextField() textField.font = .normalFont textField.textColor = SemanticColors.Label.textDefault return textField }() let domainLabel: UILabel = { let label = UILabel() label.font = .normalSemiboldFont label.textColor = .gray label.setContentCompressionResistancePriority(.required, for: .horizontal) return label }() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setupViews() createConstraints() setupStyle() } func setupStyle() { backgroundColor = .clear } @available(*, unavailable) required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setupViews() { handleTextField.delegate = self handleTextField.addTarget(self, action: #selector(editingChanged), for: .editingChanged) handleTextField.autocapitalizationType = .none handleTextField.accessibilityLabel = "handleTextField" handleTextField.autocorrectionType = .no handleTextField.spellCheckingType = .no handleTextField.textAlignment = .right prefixLabel.text = "@" [prefixLabel, handleTextField, domainLabel].forEach(addSubview) } private func createConstraints() { [prefixLabel, handleTextField, domainLabel].prepareForLayout() NSLayoutConstraint.activate([ prefixLabel.topAnchor.constraint(equalTo: topAnchor), prefixLabel.widthAnchor.constraint(equalToConstant: 16), prefixLabel.bottomAnchor.constraint(equalTo: bottomAnchor), prefixLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 16), prefixLabel.trailingAnchor.constraint(equalTo: handleTextField.leadingAnchor, constant: -4), handleTextField.topAnchor.constraint(equalTo: topAnchor), handleTextField.bottomAnchor.constraint(equalTo: bottomAnchor), handleTextField.trailingAnchor.constraint(equalTo: domainLabel.leadingAnchor, constant: -4), domainLabel.topAnchor.constraint(equalTo: topAnchor), domainLabel.bottomAnchor.constraint(equalTo: bottomAnchor), domainLabel.trailingAnchor.constraint(lessThanOrEqualTo: trailingAnchor, constant: -16) ]) } func performWiggleAnimation() { [handleTextField, prefixLabel].forEach { $0.wiggle() } } // MARK: - UITextField @objc func editingChanged(textField: UITextField) { let lowercase = textField.text?.lowercased() ?? "" textField.text = lowercase delegate?.tableViewCellDidChangeText(cell: self, text: lowercase) } func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { guard let delegate = delegate else { return false } let current = (textField.text ?? "") as NSString let replacement = current.replacingCharacters(in: range, with: string) if delegate.tableViewCell(cell: self, shouldAllowEditingText: replacement) { return true } performWiggleAnimation() return false } } /// This struct represents the current state of a handle /// change operation and performs necessary validation steps of /// a new handle. The `ChangeHandleViewController` uses this state /// to layout its interface. struct HandleChangeState { enum ValidationError: Error { case tooShort, tooLong, invalidCharacter, sameAsPrevious } enum HandleAvailability { case unknown, available, taken } let currentHandle: String? private(set) var newHandle: String? var availability: HandleAvailability var displayHandle: String? { return newHandle ?? currentHandle } init(currentHandle: String?, newHandle: String?, availability: HandleAvailability) { self.currentHandle = currentHandle self.newHandle = newHandle self.availability = availability } private static var allowedCharacters: CharacterSet = { return CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyz_-.").union(.decimalDigits) }() private static var allowedLength: CountableClosedRange<Int> { return 2...256 } /// Validates the passed in handle and updates the state if /// no error occurs, otherwise a `ValidationError` will be thrown. mutating func update(_ handle: String) throws { availability = .unknown try validate(handle) newHandle = handle } /// Validation a new handle, if passed in handle /// is invalid, an error will be thrown. /// This function does not update the `HandleChangeState` itself. func validate(_ handle: String) throws { let subset = CharacterSet(charactersIn: handle).isSubset(of: HandleChangeState.allowedCharacters) guard subset && handle.isEqualToUnicodeName else { throw ValidationError.invalidCharacter } guard handle.count >= HandleChangeState.allowedLength.lowerBound else { throw ValidationError.tooShort } guard handle.count <= HandleChangeState.allowedLength.upperBound else { throw ValidationError.tooLong } guard handle != currentHandle else { throw ValidationError.sameAsPrevious } } } final class ChangeHandleViewController: SettingsBaseTableViewController { private typealias HandleChange = L10n.Localizable.Self.Settings.AccountSection.Handle.Change var footerFont: UIFont = .smallFont var state: HandleChangeState private var footerLabel = UILabel() fileprivate weak var userProfile = ZMUserSession.shared()?.userProfile private var observerToken: Any? var popOnSuccess = true private var federationEnabled: Bool convenience init() { self.init(state: HandleChangeState(currentHandle: SelfUser.current.handle ?? nil, newHandle: nil, availability: .unknown)) } convenience init(suggestedHandle handle: String) { self.init(state: .init(currentHandle: nil, newHandle: handle, availability: .unknown)) setupViews() checkAvailability(of: handle) } /// Used to inject a specific `HandleChangeState` in tests. See `ChangeHandleViewControllerTests`. init(state: HandleChangeState, federationEnabled: Bool = BackendInfo.isFederationEnabled) { self.state = state self.federationEnabled = federationEnabled super.init(style: .grouped) setupViews() } @available(*, unavailable) required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewWillAppear(_ animated: Bool) { super.viewDidAppear(animated) updateUI() observerToken = userProfile?.add(observer: self) } override func viewWillDisappear(_ animated: Bool) { super.viewWillAppear(animated) observerToken = nil } private func setupViews() { navigationItem.setupNavigationBarTitle(title: HandleChange.title.capitalized) view.backgroundColor = .clear ChangeHandleTableViewCell.register(in: tableView) tableView.allowsSelection = false tableView.isScrollEnabled = false tableView.separatorStyle = .singleLine tableView.separatorColor = SemanticColors.View.backgroundSeparatorCell footerLabel.numberOfLines = 0 updateUI() navigationItem.rightBarButtonItem = UIBarButtonItem( title: HandleChange.save.capitalized, style: .plain, target: self, action: #selector(saveButtonTapped) ) navigationItem.rightBarButtonItem?.tintColor = SemanticColors.Label.textDefault } @objc func saveButtonTapped(sender: UIBarButtonItem) { guard let handleToSet = state.newHandle else { return } userProfile?.requestSettingHandle(handle: handleToSet) isLoadingViewVisible = true } fileprivate var attributedFooterTitle: NSAttributedString? { let infoText = HandleChange.footer.attributedString && SemanticColors.Label.textSectionFooter let alreadyTakenText = HandleChange.Footer.unavailable && SemanticColors.LegacyColors.vividRed let prefix = state.availability == .taken ? alreadyTakenText + "\n\n" : "\n\n".attributedString return (prefix + infoText) && footerFont } private func updateFooter() { footerLabel.attributedText = attributedFooterTitle let size = footerLabel.sizeThatFits(CGSize(width: view.frame.width - 32, height: UIView.noIntrinsicMetric)) footerLabel.frame = CGRect(origin: CGPoint(x: 16, y: 0), size: size) tableView.tableFooterView = footerLabel } private func updateNavigationItem() { navigationItem.rightBarButtonItem?.isEnabled = state.availability == .available } fileprivate func updateUI() { updateNavigationItem() updateFooter() } // MARK: - UITableView override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return section == 0 ? 1 : 0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: ChangeHandleTableViewCell.zm_reuseIdentifier, for: indexPath) as! ChangeHandleTableViewCell cell.delegate = self cell.handleTextField.text = state.displayHandle cell.handleTextField.becomeFirstResponder() cell.domainLabel.isHidden = !federationEnabled cell.domainLabel.text = federationEnabled ? SelfUser.current.domainString : "" return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 56 } } extension ChangeHandleViewController: ChangeHandleTableViewCellDelegate { func tableViewCell(cell: ChangeHandleTableViewCell, shouldAllowEditingText text: String) -> Bool { do { /// We validate the new handle and only allow the edit if /// the new handle neither contains invalid characters nor is too long. try state.validate(text) return true } catch HandleChangeState.ValidationError.invalidCharacter { return false } catch HandleChangeState.ValidationError.tooLong { return false } catch { return true } } func tableViewCellDidChangeText(cell: ChangeHandleTableViewCell, text: String) { do { NSObject.cancelPreviousPerformRequests(withTarget: self) try state.update(text) perform(#selector(checkAvailability), with: text, afterDelay: 0.2) } catch { // no-op } updateUI() } @objc fileprivate func checkAvailability(of handle: String) { userProfile?.requestCheckHandleAvailability(handle: handle) } } extension ChangeHandleViewController: UserProfileUpdateObserver { func didCheckAvailiabilityOfHandle(handle: String, available: Bool) { guard handle == state.newHandle else { return } state.availability = available ? .available : .taken updateUI() } func didFailToCheckAvailabilityOfHandle(handle: String) { guard handle == state.newHandle else { return } // If we fail to check we let the user check again by tapping the save button state.availability = .available updateUI() } func didSetHandle() { isLoadingViewVisible = false state.availability = .taken guard popOnSuccess else { return } _ = navigationController?.popViewController(animated: true) } func didFailToSetHandle() { presentFailureAlert() isLoadingViewVisible = false } func didFailToSetHandleBecauseExisting() { state.availability = .taken updateUI() isLoadingViewVisible = false } private func presentFailureAlert() { let alert = UIAlertController( title: HandleChange.FailureAlert.title, message: HandleChange.FailureAlert.message, preferredStyle: .alert ) alert.addAction(.init(title: L10n.Localizable.General.ok, style: .cancel, handler: nil)) present(alert, animated: true, completion: nil) } } fileprivate extension String { var isEqualToUnicodeName: Bool { return applyingTransform(.toUnicodeName, reverse: false) == self } }
16b90ee56be12973232cd9a49e157b02
34.719902
156
0.686408
false
false
false
false
J3D1-WARR10R/WikiRaces
refs/heads/master
WikiRaces/Shared/Race View Controllers/HistoryViewController/HistoryTableViewStatsCell.swift
mit
2
// // HistoryTableViewStatsCell.swift // WikiRaces // // Created by Andrew Finke on 2/28/19. // Copyright © 2019 Andrew Finke. All rights reserved. // import UIKit final internal class HistoryTableViewStatsCell: UITableViewCell { // MARK: - Properties - static let reuseIdentifier = "statsReuseIdentifier" var stat: (key: String, value: String)? { didSet { statLabel.text = stat?.key detailLabel.text = stat?.value } } let statLabel = UILabel() let detailLabel = UILabel() // MARK: - Initialization - override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) statLabel.textAlignment = .left statLabel.font = UIFont.systemFont(ofSize: 17, weight: .regular) statLabel.numberOfLines = 0 statLabel.translatesAutoresizingMaskIntoConstraints = false addSubview(statLabel) detailLabel.font = UIFont.systemFont(ofSize: 17, weight: .medium) detailLabel.textAlignment = .right detailLabel.setContentCompressionResistancePriority(.required, for: .horizontal) detailLabel.translatesAutoresizingMaskIntoConstraints = false addSubview(detailLabel) setupConstraints() isUserInteractionEnabled = false } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - View Life Cycle - public override func layoutSubviews() { super.layoutSubviews() let textColor = UIColor.wkrTextColor(for: traitCollection) tintColor = textColor statLabel.textColor = textColor detailLabel.textColor = textColor } // MARK: - Constraints - private func setupConstraints() { let leftMarginConstraint = NSLayoutConstraint(item: statLabel, attribute: .left, relatedBy: .equal, toItem: self, attribute: .leftMargin, multiplier: 1.0, constant: 0.0) let rightMarginConstraint = NSLayoutConstraint(item: detailLabel, attribute: .right, relatedBy: .equal, toItem: self, attribute: .rightMargin, multiplier: 1.0, constant: 0.0) let constraints = [ leftMarginConstraint, statLabel.topAnchor.constraint(equalTo: topAnchor, constant: 10), statLabel.heightAnchor.constraint(greaterThanOrEqualToConstant: 15), statLabel.rightAnchor.constraint(lessThanOrEqualTo: detailLabel.leftAnchor, constant: -15), rightMarginConstraint, detailLabel.centerYAnchor.constraint(equalTo: centerYAnchor) ] NSLayoutConstraint.activate(constraints) } }
851ed0b40d3a8f5047e82fb7b291c7e0
35.086022
103
0.548272
false
false
false
false
phimage/MomXML
refs/heads/master
Sources/Model/MomElement.swift
mit
1
// Created by Eric Marchand on 07/06/2017. // Copyright © 2017 Eric Marchand. All rights reserved. // import Foundation public struct MomElement { public var name: String public var positionX: Int = 0 public var positionY: Int = 0 public var width: Int = 128 public var height: Int = 128 public init(name: String, positionX: Int = 0, positionY: Int = 0, width: Int = 0, height: Int = 0) { self.name = name self.positionX = positionX self.positionY = positionY self.width = width self.height = height } }
06f5e9af6f0714b4b99304cc674e6fbb
24.173913
104
0.632124
false
false
false
false
WSDOT/wsdot-ios-app
refs/heads/master
wsdot/AmtrakCascadesServiceStopItem.swift
gpl-3.0
2
// // AmtrakCascadesServiceItem.swift // WSDOT // // Copyright (c) 2016 Washington State Department of Transportation // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/> // import Foundation // Stop item represents an item from the Amtrak API. It is eitehr an arriavl or desprature. class AmtrakCascadesServiceStopItem{ var stationId: String = "" var stationName: String = "" var trainNumber: Int = -1 var tripNumer: Int = -1 var sortOrder: Int = -1 var arrivalComment: String? = nil var departureComment: String? = nil var scheduledArrivalTime: Date? = nil var scheduledDepartureTime: Date? = nil var updated = Date(timeIntervalSince1970: 0) }
4fb9b8298f02c3eebedf945034163066
31.365854
92
0.706104
false
false
false
false
totomo/SSLogger
refs/heads/master
Source/Printer.swift
mit
1
// // Printer.swift // SSLogger // // Created by Kenta Tokumoto on 2015/09/19. // Copyright © 2015年 Kenta Tokumoto. All rights reserved. // public func print(value:Any...){ #if DEBUG var message = "" for element in value { var eachMessage = "\(element)" let pattern = "Optional\\((.+)\\)" eachMessage = eachMessage .stringByReplacingOccurrencesOfString(pattern, withString:"$1", options:.RegularExpressionSearch, range: nil) message += eachMessage } Swift.print(message) #endif }
d4af47f1e46144c65b59cb227db4c921
23.708333
58
0.584459
false
false
false
false
robotwholearned/GettingStarted
refs/heads/master
FoodTracker/MealTableViewController.swift
mit
1
// // MealTableViewController.swift // FoodTracker // // Created by Sandquist, Cassandra - Cassandra on 3/12/16. // Copyright © 2016 robotwholearned. All rights reserved. // import UIKit enum RatingLevels: Int { case One = 1, Two, Three, Four, Five } struct MealNames { static let capreseSalad = "Caprese Salad" static let chickenAndPotatoes = "Chicken and Potatoes" static let pastaAndMeatballs = "Pasta with Meatballs" } class MealTableViewController: UITableViewController { //MARK: Properties var meals = [Meal]() override func viewDidLoad() { super.viewDidLoad() navigationItem.leftBarButtonItem = editButtonItem() if let loadedMeals = loadMeals() { meals += loadedMeals } else { loadSampleMeals() } } func loadSampleMeals() { let photo1 = R.image.meal1() let meal1 = Meal(name: MealNames.capreseSalad, photo: photo1, rating: RatingLevels.Four.rawValue)! let photo2 = R.image.meal2() let meal2 = Meal(name: MealNames.chickenAndPotatoes, photo: photo2, rating: RatingLevels.Five.rawValue)! let photo3 = R.image.meal3() let meal3 = Meal(name: MealNames.pastaAndMeatballs, photo: photo3, rating: RatingLevels.Three.rawValue)! meals += [meal1, meal2, meal3] } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return meals.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(R.reuseIdentifier.mealTableViewCell.identifier, forIndexPath: indexPath) as! MealTableViewCell // Fetches the appropriate meal for the data source layout. let meal = meals[indexPath.row] cell.nameLabel.text = meal.name cell.photoImageView?.image = meal.photo cell.ratingControl.rating = meal.rating return cell } @IBAction func unwindToMealList (segue: UIStoryboardSegue) { if let sourceViewController = segue.sourceViewController as? MealViewController, meal = sourceViewController.meal { if let selectedIndexPath = tableView.indexPathForSelectedRow { meals[selectedIndexPath.row] = meal tableView.reloadRowsAtIndexPaths([selectedIndexPath], withRowAnimation: .None) } else { // Add a new meal. let newIndexPath = NSIndexPath(forRow: meals.count, inSection: 0) meals.append(meal) tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Bottom) } saveMeals() } } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { meals.removeAtIndex(indexPath.row) saveMeals() 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 func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { 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?) { if segue.identifier == R.segue.mealTableViewController.showDetail.identifier { let mealDetailViewController = segue.destinationViewController as! MealViewController if let selectedMealCell = sender as? MealTableViewCell { let indexPath = tableView.indexPathForCell(selectedMealCell)! let selectedMeal = meals[indexPath.row] mealDetailViewController.meal = selectedMeal } } else if segue.identifier == R.segue.mealTableViewController.addItem.identifier { print("Adding new meal.") } } // MARK: NSCoding func saveMeals() { let isSuccessfulSave = NSKeyedArchiver.archiveRootObject(meals, toFile: Meal.ArchiveURL.path!) if !isSuccessfulSave { print("Failed to save meals...") } } func loadMeals() -> [Meal]? { return NSKeyedUnarchiver.unarchiveObjectWithFile(Meal.ArchiveURL.path!) as? [Meal] } }
8713f956f550ceebaaf514ad99771e0d
34.381295
157
0.665718
false
false
false
false
digice/ios-dvm-boilerplate
refs/heads/master
Location/LocationData.swift
mit
1
// // Location.swift // DVM-Boilerplate // // Created by Digices LLC on 3/30/17. // Copyright © 2017 Digices LLC. All rights reserved. // import Foundation import CoreLocation class LocationData : NSObject, NSCoding { // MARK: - Optional Properties var latitude : Double? var longitude : Double? var region : CLRegion? // MARK: - NSObject Methods override init() { super.init() } // MARK: - NSCoder Methods required init?(coder aDecoder: NSCoder) { // decode latitude let x = aDecoder.decodeDouble(forKey: "latitude") if x < 200 { self.latitude = x } // decode longitude let y = aDecoder.decodeDouble(forKey: "longitude") if y < 200 { self.longitude = y } // decode region let r = aDecoder.decodeObject(forKey: "region") if r as? String == "nil" { // do nothing } else { self.region = r as? CLRegion } } func encode(with aCoder: NSCoder) { // encode latitude if let x = self.latitude { aCoder.encode(x, forKey: "latitude") } else { aCoder.encode(999.9, forKey: "latitude") } // encode longitiude if let y = self.longitude { aCoder.encode(y, forKey: "longitude") } else { aCoder.encode(999.9, forKey: "longitude") } if let r = self.region { aCoder.encode(r, forKey: "region") } else { aCoder.encode("nil", forKey: "region") } } // MARK: - Custom Methods func httpBody() -> String { // make sure we have longitude and latitude if let x = self.latitude { if let y = self.longitude { if let r = self.region { // optionally include region identifier return "x=\(x)&y=\(y)&r=\(r.identifier)" } else { // return "x=\(x)&y=\(y)&r=unknown" } } } // return default string with recognizably invalid parameters return "x=999.9&y=999.9&r=unknown" } }
af138f5e17737bb9e09bafa5ba7ddd45
18.465347
65
0.574771
false
false
false
false
JGiola/swift-corelibs-foundation
refs/heads/main
Foundation/NSValue.swift
apache-2.0
14
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // open class NSValue : NSObject, NSCopying, NSSecureCoding, NSCoding { private static var SideTable = [ObjectIdentifier : NSValue]() private static var SideTableLock = NSLock() internal override init() { super.init() // on Darwin [NSValue new] returns nil } // because we cannot support the class cluster pattern owing to a lack of // factory initialization methods, we maintain a sidetable mapping instances // of NSValue to NSConcreteValue internal var _concreteValue: NSValue { get { return NSValue.SideTableLock.synchronized { return NSValue.SideTable[ObjectIdentifier(self)]! } } set { NSValue.SideTableLock.synchronized { NSValue.SideTable[ObjectIdentifier(self)] = newValue } } } deinit { if type(of: self) == NSValue.self { NSValue.SideTableLock.synchronized { NSValue.SideTable[ObjectIdentifier(self)] = nil } } } open override var hash: Int { get { if type(of: self) == NSValue.self { return _concreteValue.hash } else { return super.hash } } } open override func isEqual(_ value: Any?) -> Bool { guard let object = value as? NSValue else { return false } if self === object { return true } else { // bypass _concreteValue accessor in order to avoid acquiring lock twice let (lhs, rhs) = NSValue.SideTableLock.synchronized { return (NSValue.SideTable[ObjectIdentifier(self)], NSValue.SideTable[ObjectIdentifier(object)]) } guard let left = lhs, let right = rhs else { return false } return left.isEqual(right) } } open override var description : String { get { if type(of: self) == NSValue.self { return _concreteValue.description } else { return super.description } } } open func getValue(_ value: UnsafeMutableRawPointer) { if type(of: self) == NSValue.self { return _concreteValue.getValue(value) } else { NSRequiresConcreteImplementation() } } open var objCType: UnsafePointer<Int8> { if type(of: self) == NSValue.self { return _concreteValue.objCType } else { NSRequiresConcreteImplementation() } } private static func _isSpecialObjCType(_ type: UnsafePointer<Int8>) -> Bool { return NSSpecialValue._typeFromObjCType(type) != nil } public convenience required init(bytes value: UnsafeRawPointer, objCType type: UnsafePointer<Int8>) { if Swift.type(of: self) == NSValue.self { self.init() if NSValue._isSpecialObjCType(type) { self._concreteValue = NSSpecialValue(bytes: value.assumingMemoryBound(to: UInt8.self), objCType: type) } else { self._concreteValue = NSConcreteValue(bytes: value.assumingMemoryBound(to: UInt8.self), objCType: type) } } else { NSRequiresConcreteImplementation() } } public convenience required init?(coder aDecoder: NSCoder) { if type(of: self) == NSValue.self { self.init() var concreteValue : NSValue? = nil if aDecoder.containsValue(forKey: "NS.special") { // It's unfortunate that we can't specialise types at runtime concreteValue = NSSpecialValue(coder: aDecoder) } else { concreteValue = NSConcreteValue(coder: aDecoder) } guard concreteValue != nil else { return nil } self._concreteValue = concreteValue! } else { NSRequiresConcreteImplementation() } } open func encode(with aCoder: NSCoder) { if type(of: self) == NSValue.self { _concreteValue.encode(with: aCoder) } else { NSRequiresConcreteImplementation() } } open class var supportsSecureCoding: Bool { return true } open override func copy() -> Any { return copy(with: nil) } open func copy(with zone: NSZone? = nil) -> Any { return self } } extension NSValue : _Factory {} internal protocol _Factory { init(factory: () -> Self) } extension _Factory { init(factory: () -> Self) { self = factory() } }
8a8b066cefac0d7870487bab71210ecd
29.790419
119
0.562038
false
false
false
false
mlibai/OMKit
refs/heads/master
Example/OMKit/NewsDetailMessageHandler.swift
mit
1
// // NewsDetailMessageHandler.swift // OMKit // // Created by mlibai on 2017/9/4. // Copyright © 2017年 CocoaPods. All rights reserved. // import UIKit import WebKit import OMKit enum NewsDetailList: String { case more = "More List" case hots = "Hot Comments List" case comments = "Comments List" case floor = "Floor Comments List" } protocol NewsDetailMessageHandlerDelegate: class { func ready(_ completion: () -> Void) func numberOfRowsInList(_ list: NewsDetailList) -> Int func list(_ list: NewsDetailList, dataForRowAt index: Int) -> [String: Any] func list(_ list: NewsDetailList, didSelectRowAt index: Int) func followButtonWasClicked(_ isSelected: Bool, completion: (Bool) -> Void) func conentLinkWasClicked() func likeButtonWasClicked(_ isSelected: Bool, completion: (_ isSelected: Bool) -> Void) func dislikeButtonWasClicked(_ isSelected: Bool, completion: (_ isSelected: Bool) -> Void) func sharePathWasClicked(_ sharePath: String) func navigationBarInfoButtonWasClicked() func toolBarShareButtonClicked() func toolBarCollectButtonClicked(_ isSelected: Bool, completion:(Bool) -> Void) // 加载评论 func loadComments() // 加载叠楼回复 func loadReplies() /// 评论点赞按钮被点击时。 /// /// - Parameters: /// - commentsList: 评论列表。 /// - index: 被点击的按钮所在列表的行索引。叠楼时,index = -1 表示楼主的评论被点击。 /// - isSelected: 按钮的当前状态。 /// - completion: 按钮被点击后的状态。 func commentsList(_ commentsList: NewsDetailList, likeButtonAt index: Int, wasClicked isSelected: Bool, completion: (Bool)->Void) } class NewsDetailMessageHandler: WebViewMessageHandler { unowned let delegate: NewsDetailMessageHandlerDelegate init(delegate: NewsDetailMessageHandlerDelegate, webView: WKWebView, viewController: UIViewController) { self.delegate = delegate super.init(webView: webView, viewController: viewController) } override func ready(_ completion: @escaping () -> Void) { delegate.ready(completion) } override func document(_ document: String, numberOfRowsInList list: String, completion: @escaping (Int) -> Void) { if let list = NewsDetailList.init(rawValue: list) { completion(delegate.numberOfRowsInList(list)); } else { super.document(document, numberOfRowsInList: list, completion: completion) } } override func document(_ document: String, list: String, dataForRowAt index: Int, completion: @escaping ([String : Any]) -> Void) { if let list = NewsDetailList.init(rawValue: list) { completion(delegate.list(list, dataForRowAt: index)) } else { super.document(document, list: list, dataForRowAt: index, completion: completion) } } override func document(_ document: String, list: String, didSelectRowAt index: Int, completion: @escaping () -> Void) { if let list = NewsDetailList.init(rawValue: list) { delegate.list(list, didSelectRowAt: index) completion() } else { super.document(document, list: list, didSelectRowAt: index, completion: completion) } } override func document(_ document: String, element: String, wasClicked data: Any, completion: @escaping (Bool) -> Void) { switch element { case "Follow Button": delegate.followButtonWasClicked(data as? Bool ?? false, completion: completion) case "Content Link": delegate.conentLinkWasClicked() case "Action Like": guard let isSelected = data as? Bool else { return } delegate.likeButtonWasClicked(isSelected, completion: completion) case "Action Dislike": guard let isSelected = data as? Bool else { return } delegate.dislikeButtonWasClicked(isSelected, completion: completion) case "Comments Load More": delegate.loadComments() case "Share Button": guard let sharePath = data as? String else { return } delegate.sharePathWasClicked(sharePath) case "Floor Load More": delegate.loadReplies() case "Hots Comments List Like Action": guard let dict = data as? [String: Any] else { return } guard let index = dict["index"] as? Int else { return } guard let isSelected = dict["isSelected"] as? Bool else { return } delegate.commentsList(.hots, likeButtonAt: index, wasClicked: isSelected, completion: completion) case "Comments List Like Action": guard let dict = data as? [String: Any] else { return } guard let index = dict["index"] as? Int else { return } guard let isSelected = dict["isSelected"] as? Bool else { return } delegate.commentsList(.comments, likeButtonAt: index, wasClicked: isSelected, completion: completion) case "Floor List Like Action": guard let dict = data as? [String: Any] else { return } guard let index = dict["index"] as? Int else { return } guard let isSelected = dict["isSelected"] as? Bool else { return } delegate.commentsList(.floor, likeButtonAt: index, wasClicked: isSelected, completion: completion) case "Floor Host Like Action": guard let dict = data as? [String: Any] else { return } guard let isSelected = dict["isSelected"] as? Bool else { return } delegate.commentsList(.floor, likeButtonAt: -1, wasClicked: isSelected, completion: { (isSelected) in completion(isSelected) }) case "Navigation Bar Info": delegate.navigationBarInfoButtonWasClicked() case "Tool Bar Share": delegate.toolBarShareButtonClicked() case "Tool Bar Collect": guard let isSelected = data as? Bool else { return } delegate.toolBarCollectButtonClicked(isSelected, completion: completion) default: super.document(document, element: element, wasClicked: data, completion: completion) } } }
33c8eb506bcae50a631c6436f117c142
34.524862
135
0.617729
false
false
false
false
weiss19ja/LocalizableUI
refs/heads/master
LocalizableUI/LocalizedItems/UITextField+LocalizableUI.swift
mit
1
// // UITextField+LocalizableUI.swift // Pods // // Created by Jan Weiß on 01.08.17. // // import Foundation import UIKit private var AssociatedObjectPointer: UInt8 = 0 extension UITextField: Localizable { // Stores the property of the localized placeholder key @IBInspectable public var localizedPlaceholderKey: String? { get { return objc_getAssociatedObject(self, &AssociatedObjectPointer) as? String } set { objc_setAssociatedObject(self, &AssociatedObjectPointer, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) // Add the Element to the LocalizationManager addToManager() } } public convenience init(frame: CGRect, localizedKey: String?, localizedPlaceholderKey: String?) { self.init(frame: frame) self.localizedKey = localizedKey self.localizedPlaceholderKey = localizedPlaceholderKey } /// Updates all subviews with their given localizedKeys public func updateLocalizedStrings() { if let localizedKey = localizedKey { text = LocalizationManager.localizedStringFor(localizedKey) } if let localizedPlaceHolderKey = localizedPlaceholderKey { placeholder = LocalizationManager.localizedStringFor(localizedPlaceHolderKey) } } }
976bebbdd624b6c86c29d3669142a974
28.319149
114
0.662554
false
false
false
false
flodolo/firefox-ios
refs/heads/main
Shared/TimeConstants.swift
mpl-2.0
2
// 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 public typealias Timestamp = UInt64 public typealias MicrosecondTimestamp = UInt64 public let ThreeWeeksInSeconds = 3 * 7 * 24 * 60 * 60 public let OneYearInMilliseconds = 12 * OneMonthInMilliseconds public let OneMonthInMilliseconds = 30 * OneDayInMilliseconds public let OneWeekInMilliseconds = 7 * OneDayInMilliseconds public let OneDayInMilliseconds = 24 * OneHourInMilliseconds public let OneHourInMilliseconds = 60 * OneMinuteInMilliseconds public let OneMinuteInMilliseconds = 60 * OneSecondInMilliseconds public let OneSecondInMilliseconds: UInt64 = 1000 private let rfc822DateFormatter: DateFormatter = { let dateFormatter = DateFormatter() dateFormatter.timeZone = TimeZone(abbreviation: "GMT") dateFormatter.dateFormat = "EEE',' dd MMM yyyy HH':'mm':'ss 'GMT'" dateFormatter.locale = Locale(identifier: "en_US") return dateFormatter }() public struct DateDifference { public var month: Int? public var day: Int? public var hour: Int? public var minute: Int? public var second: Int? } extension TimeInterval { public static func fromMicrosecondTimestamp(_ microsecondTimestamp: MicrosecondTimestamp) -> TimeInterval { return Double(microsecondTimestamp) / 1000000 } public static func timeIntervalSince1970ToDate(timeInterval: TimeInterval) -> Date { Date(timeIntervalSince1970: timeInterval) } } extension Timestamp { public static func uptimeInMilliseconds() -> Timestamp { return Timestamp(DispatchTime.now().uptimeNanoseconds) / 1000000 } } extension Date { public static func now() -> Timestamp { return UInt64(1000 * Date().timeIntervalSince1970) } public static func nowNumber() -> NSNumber { return NSNumber(value: now() as UInt64) } public func toMillisecondsSince1970() -> Int64 { return Int64((self.timeIntervalSince1970 * 1000.0).rounded()) } public func toMicrosecondsSince1970() -> MicrosecondTimestamp { return UInt64(1_000_000 * self.timeIntervalSince1970) } public static func fromTimestamp(_ timestamp: Timestamp) -> Date { return Date(timeIntervalSince1970: Double(timestamp) / 1000) } public func toTimestamp() -> Timestamp { return UInt64(1000 * timeIntervalSince1970) } public static func fromMicrosecondTimestamp(_ microsecondTimestamp: MicrosecondTimestamp) -> Date { return Date(timeIntervalSince1970: Double(microsecondTimestamp) / 1000000) } public func toRelativeTimeString(dateStyle: DateFormatter.Style = .short, timeStyle: DateFormatter.Style = .short) -> String { let now = Date() let units: Set<Calendar.Component> = [.second, .minute, .day, .weekOfYear, .month, .year, .hour] let components = Calendar.current.dateComponents(units, from: self, to: now) if components.year ?? 0 > 0 { return String(format: DateFormatter.localizedString(from: self, dateStyle: dateStyle, timeStyle: timeStyle)) } if components.month == 1 { return String(format: .TimeConstantMoreThanAMonth) } if components.month ?? 0 > 1 { return String(format: DateFormatter.localizedString(from: self, dateStyle: dateStyle, timeStyle: timeStyle)) } if components.weekOfYear ?? 0 > 0 { return String(format: .TimeConstantMoreThanAWeek) } if components.day == 1 { return String(format: .TimeConstantYesterday) } if components.day ?? 0 > 1 { return String(format: .TimeConstantThisWeek, String(describing: components.day)) } if components.hour ?? 0 > 0 || components.minute ?? 0 > 0 { // Can't have no time specified for this formatting case. let timeStyle = timeStyle != .none ? timeStyle : .short let absoluteTime = DateFormatter.localizedString(from: self, dateStyle: .none, timeStyle: timeStyle) return String(format: .TimeConstantRelativeToday, absoluteTime) } return String(format: .TimeConstantJustNow) } public func toRFC822String() -> String { return rfc822DateFormatter.string(from: self) } public static func differenceBetween(_ firstDate: Date, and previousDate: Date) -> DateDifference { let day = Calendar.current.dateComponents([.day], from: previousDate, to: firstDate).day let month = Calendar.current.dateComponents([.month], from: previousDate, to: firstDate).month let hour = Calendar.current.dateComponents([.hour], from: previousDate, to: firstDate).hour let minute = Calendar.current.dateComponents([.minute], from: previousDate, to: firstDate).minute let second = Calendar.current.dateComponents([.second], from: previousDate, to: firstDate).second return DateDifference(month: month, day: day, hour: hour, minute: minute, second: second) } static func - (lhs: Date, rhs: Date) -> TimeInterval { return lhs.timeIntervalSinceReferenceDate - rhs.timeIntervalSinceReferenceDate } } extension Date { public static var yesterday: Date { return Date().dayBefore } public static var tomorrow: Date { return Date().dayAfter } public var lastTwoWeek: Date { return Calendar.current.date(byAdding: .day, value: -14, to: noon) ?? Date() } public var lastWeek: Date { return Calendar.current.date(byAdding: .day, value: -8, to: noon) ?? Date() } public var older: Date { return Calendar.current.date(byAdding: .day, value: -20, to: noon) ?? Date() } public var dayBefore: Date { return Calendar.current.date(byAdding: .day, value: -1, to: noon) ?? Date() } public var dayAfter: Date { return Calendar.current.date(byAdding: .day, value: 1, to: noon) ?? Date() } public var noon: Date { return Calendar.current.date(bySettingHour: 12, minute: 0, second: 0, of: self) ?? Date() } public func isToday() -> Bool { return Calendar.current.isDateInToday(self) } public func isYesterday() -> Bool { return Calendar.current.isDateInYesterday(self) } public func isWithinLast7Days() -> Bool { return (Date().lastWeek ... Date()).contains(self) } public func isWithinLast14Days() -> Bool { return (Date().lastTwoWeek ... Date()).contains(self) } } let MaxTimestampAsDouble = Double(UInt64.max) /** This is just like decimalSecondsStringToTimestamp, but it looks for values that seem to be * milliseconds and fixes them. That's necessary because Firefox for iOS <= 7.3 uploaded millis * when seconds were expected. */ public func someKindOfTimestampStringToTimestamp(_ input: String) -> Timestamp? { if let double = Scanner(string: input).scanDouble() { // This should never happen. Hah! if double.isNaN || double.isInfinite { return nil } // `double` will be either huge or negatively huge on overflow, and 0 on underflow. // We clamp to reasonable ranges. if double < 0 { return nil } if double >= MaxTimestampAsDouble { // Definitely not representable as a timestamp if the seconds are this large! return nil } if double > 1000000000000 { // Oh, this was in milliseconds. return Timestamp(double) } let millis = double * 1000 if millis >= MaxTimestampAsDouble { // Not representable as a timestamp. return nil } return Timestamp(millis) } return nil } public func decimalSecondsStringToTimestamp(_ input: String) -> Timestamp? { if let double = Scanner(string: input).scanDouble() { // This should never happen. Hah! if double.isNaN || double.isInfinite { return nil } // `double` will be either huge or negatively huge on overflow, and 0 on underflow. // We clamp to reasonable ranges. if double < 0 { return nil } let millis = double * 1000 if millis >= MaxTimestampAsDouble { // Not representable as a timestamp. return nil } return Timestamp(millis) } return nil } public func millisecondsToDecimalSeconds(_ input: Timestamp) -> String { let val = Double(input) / 1000 return String(format: "%.2F", val) } public func millisecondsToSeconds(_ input: Timestamp) -> UInt64 { let val = input / 1000 return val }
943aacf151cbe9ae3fd64f7ebf66e1df
34.039216
130
0.651371
false
false
false
false
jaouahbi/OMCircularProgress
refs/heads/master
OMCircularProgress/Classes/Extensions/Interpolation.swift
apache-2.0
2
// // Copyright 2015 - Jorge Ouahbi // // 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. // // // Interpolation.swift // // Created by Jorge Ouahbi on 13/5/16. // Copyright © 2016 Jorge Ouahbi. All rights reserved. // import UIKit /// Interpolation type /// /// - linear: <#linear description#> /// - exponential: <#exponential description#> /// - cosine: <#cosine description#> /// - cubic: <#cubic description#> /// - bilinear: <#bilinear description#> enum InterpolationType { case linear case exponential case cosine case cubic case bilinear } class Interpolation { /// Cubic Interpolation /// /// - Parameters: /// - y0: element 0 /// - y1: element 1 /// - y2: element 2 /// - y3: element 3 /// - t: alpha /// - Returns: the interpolate value /// - Note: /// Paul Breeuwsma proposes the following coefficients for a smoother interpolated curve, /// which uses the slope between the previous point and the next as the derivative at the current point. /// This results in what are generally referred to as Catmull-Rom splines. /// a0 = -0.5*y0 + 1.5*y1 - 1.5*y2 + 0.5*y3; /// a1 = y0 - 2.5*y1 + 2*y2 - 0.5*y3; /// a2 = -0.5*y0 + 0.5*y2; /// a3 = y1; class func cubicerp(_ y0:CGFloat,y1:CGFloat,y2:CGFloat,y3:CGFloat,t:CGFloat) -> CGFloat { var a0:CGFloat var a1:CGFloat var a2:CGFloat var a3:CGFloat var t2:CGFloat assert(t >= 0.0 && t <= 1.0); t2 = t*t; a0 = y3 - y2 - y0 + y1; a1 = y0 - y1 - a0; a2 = y2 - y0; a3 = y1; return(a0*t*t2+a1*t2+a2*t+a3); } /// Exponential Interpolation /// /// - Parameters: /// - y0: element 0 /// - y1: element 1 /// - t: alpha /// - Returns: the interpolate value class func eerp(_ y0:CGFloat,y1:CGFloat,t:CGFloat) -> CGFloat { assert(t >= 0.0 && t <= 1.0); let end = log(max(Double(y0), 0.01)) let start = log(max(Double(y1), 0.01)) return CGFloat(exp(start - (end + start) * Double(t))) } /// Linear Interpolation /// /// - Parameters: /// - y0: element 0 /// - y1: element 1 /// - t: alpha /// - Returns: the interpolate value /// - Note: /// Imprecise method which does not guarantee v = v1 when t = 1, due to floating-point arithmetic error. /// This form may be used when the hardware has a native Fused Multiply-Add instruction. /// return v0 + t*(v1-v0); /// /// Precise method which guarantees v = v1 when t = 1. /// (1-t)*v0 + t*v1; class func lerp(_ y0:CGFloat,y1:CGFloat,t:CGFloat) -> CGFloat { assert(t >= 0.0 && t <= 1.0); let inverse = 1.0 - t; return inverse * y0 + t * y1 } /// Bilinear Interpolation /// /// - Parameters: /// - y0: element 0 /// - y1: element 1 /// - t1: alpha /// - y2: element 2 /// - y3: element 3 /// - t2: alpha /// - Returns: the interpolate value class func bilerp(_ y0:CGFloat,y1:CGFloat,t1:CGFloat,y2:CGFloat,y3:CGFloat,t2:CGFloat) -> CGFloat { assert(t1 >= 0.0 && t1 <= 1.0); assert(t2 >= 0.0 && t2 <= 1.0); let x = lerp(y0, y1: y1, t: t1) let y = lerp(y2, y1: y3, t: t2) return lerp(x, y1: y, t: 0.5) } /// Cosine Interpolation /// /// - Parameters: /// - y0: element 0 /// - y1: element 1 /// - t: alpha /// - Returns: the interpolate value class func coserp(_ y0:CGFloat,y1:CGFloat,t:CGFloat) -> CGFloat { assert(t >= 0.0 && t <= 1.0); let mu2 = CGFloat(1.0-cos(Double(t) * .pi))/2; return (y0*(1.0-mu2)+y1*mu2); } }
838ad531c4a543051055ddddbbf02734
27.54902
109
0.547619
false
false
false
false
SmallElephant/FEAlgorithm-Swift
refs/heads/master
3-Fibonacci/3-Fibonacci/SearchArray.swift
mit
1
// // SearchArray.swift // 3-Array // // Created by keso on 2016/12/18. // Copyright © 2016年 FlyElephant. All rights reserved. // import Foundation class SearchArray { //数组中出现次数超过一半的数字 // 题目:数组中有一个数字出现的次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,5,4,2}。由于数字2在数组中出现了5词,超过数组长度的一半,因此输出2. func moreThanHalfNum(arr:[Int]) -> Int? { if arr.count == 0 { return nil } var num:Int = arr[0] var times:Int = 1 for i in 1..<arr.count { if times == 0 { num = arr[i] times = 1 } else { if arr[i] == num { times += 1 } else { times -= 1 } } } return num } }
5fd6147fc824745534ddccb15fdc25e4
21.166667
102
0.451128
false
false
false
false