repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
blockchain/My-Wallet-V3-iOS
Modules/FeatureAuthentication/Sources/FeatureAuthenticationUI/Support/SupportReducer.swift
1
4033
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import AnalyticsKit import Combine import ComposableArchitecture import ComposableNavigation import DIKit import FeatureAuthenticationDomain import ToolKit public enum SupportViewAction: Equatable { public enum URLContent { case contactUs case viewFAQ } case loadAppStoreVersionInformation case failedToRetrieveAppStoreInfo case appStoreVersionInformationReceived(AppStoreApplicationInfo) case openURL(URLContent) } struct SupportViewState: Equatable { let applicationVersion: String let bundleIdentifier: String var appStoreVersion: String? var isApplicationUpdated: Bool init( applicationVersion: String, bundleIdentifier: String ) { self.applicationVersion = applicationVersion self.bundleIdentifier = bundleIdentifier appStoreVersion = nil isApplicationUpdated = true } } let supportViewReducer = Reducer< SupportViewState, SupportViewAction, SupportViewEnvironment > { state, action, environment in switch action { case .loadAppStoreVersionInformation: return environment .appStoreInformationRepository .verifyTheCurrentAppVersionIsTheLatestVersion( state.applicationVersion, bundleId: "com.rainydayapps.Blockchain" ) .receive(on: environment.mainQueue) .catchToEffect() .map { result -> SupportViewAction in guard let applicationInfo = result.success else { return .failedToRetrieveAppStoreInfo } return .appStoreVersionInformationReceived(applicationInfo) } case .appStoreVersionInformationReceived(let applicationInfo): state.isApplicationUpdated = applicationInfo.isApplicationUpToDate state.appStoreVersion = applicationInfo.version return .none case .failedToRetrieveAppStoreInfo: return .none case .openURL(let content): switch content { case .contactUs: environment.externalAppOpener.open(URL(string: Constants.SupportURL.PIN.contactUs)!) case .viewFAQ: environment.externalAppOpener.open(URL(string: Constants.SupportURL.PIN.viewFAQ)!) } return .none } } .analytics() struct SupportViewEnvironment { let mainQueue: AnySchedulerOf<DispatchQueue> let appStoreInformationRepository: AppStoreInformationRepositoryAPI let analyticsRecorder: AnalyticsEventRecorderAPI let externalAppOpener: ExternalAppOpener } extension SupportViewEnvironment { static let `default`: SupportViewEnvironment = .init( mainQueue: .main, appStoreInformationRepository: resolve(), analyticsRecorder: resolve(), externalAppOpener: resolve() ) } // MARK: - Private extension Reducer where Action == SupportViewAction, State == SupportViewState, Environment == SupportViewEnvironment { /// Helper reducer for analytics tracking fileprivate func analytics() -> Self { combined( with: Reducer< SupportViewState, SupportViewAction, SupportViewEnvironment > { _, action, environment in switch action { case .loadAppStoreVersionInformation: environment.analyticsRecorder.record(event: .customerSupportClicked) return .none case .openURL(let content): switch content { case .contactUs: environment.analyticsRecorder.record(event: .contactUsClicked) case .viewFAQ: environment.analyticsRecorder.record(event: .viewFAQsClicked) } return .none default: return .none } } ) } }
lgpl-3.0
bfcb1ecebf46ac68628b9c1ff0cd87ec
30.5
96
0.646081
5.964497
false
false
false
false
ngageoint/fog-machine
Demo/FogViewshed/FogViewshed/Models/Observer.swift
1
2277
import Foundation import MapKit public class Observer : NSObject, NSCoding { public var uniqueId:String = NSUUID().UUIDString public var elevationInMeters:Double = 1.6 public var radiusInMeters:Double = 30000.0 public var position:CLLocationCoordinate2D = CLLocationCoordinate2DMake(0.0, 0.0) override init() { } init(elevationInMeters: Double, radiusInMeters: Double, position: CLLocationCoordinate2D) { self.elevationInMeters = elevationInMeters self.radiusInMeters = radiusInMeters self.position = position } // MARK: FMCoding required public init(coder decoder: NSCoder) { self.uniqueId = decoder.decodeObjectForKey("uniqueId") as! String self.elevationInMeters = decoder.decodeDoubleForKey("elevationInMeters") self.radiusInMeters = decoder.decodeDoubleForKey("radiusInMeters") self.position = CLLocationCoordinate2DMake(decoder.decodeDoubleForKey("latitude"), decoder.decodeDoubleForKey("longitude")) } public func encodeWithCoder(coder: NSCoder) { coder.encodeObject(uniqueId, forKey: "uniqueId") coder.encodeDouble(elevationInMeters, forKey: "elevationInMeters") coder.encodeDouble(radiusInMeters, forKey: "radiusInMeters") coder.encodeDouble(position.latitude, forKey: "latitude") coder.encodeDouble(position.longitude, forKey: "longitude") } // MARK: CustomStringConvertible /// lat, lon fo the observer override public var description: String { return String(format: "%.4f", position.latitude) + ", " + String(format: "%.4f", position.longitude) } override public func isEqual(object: AnyObject?) -> Bool { if let object = object as? Observer { return uniqueId == object.uniqueId } else { return false } } override public var hash: Int { return uniqueId.hashValue } } /** Determines if two Observers are equivalent - parameter lhs: left-hand Observer - parameter rhs: right-hand Observer - returns: true iff the lhs.uniqueId == rhs.uniqueId, false otherwise */ public func ==(lhs: Observer, rhs: Observer) -> Bool { return lhs.uniqueId == rhs.uniqueId }
mit
a3da2fd85d5358371263326a24984796
33
131
0.678524
5.037611
false
false
false
false
jjacobson93/RethinkDBSwift
Sources/RethinkDB/AST/ReqlQueryLambda.swift
1
2393
// // ReqlQueryLambda.swift // RethinkDBSwift // // Created by Jeremy Jacobson on 10/17/16. // // import Foundation import Dispatch public typealias ReqlModification = (ReqlSerializable) -> [String: ReqlQuery] public typealias ReqlPredicate1 = (ReqlExpr) -> ReqlExpr public typealias ReqlPredicate2 = (ReqlExpr, ReqlExpr) -> ReqlExpr public typealias ReqlPredicate = ReqlPredicate1 public class ReqlQueryLambda: ReqlQuery { public let json: Any private static var parameterLock = DispatchQueue(label: "io.jjacobson.RethinkDBSwift") private static var parameterCounter = 0 init(_ block: ReqlPredicate1) { let parameter = ReqlExpr(json: ReqlQueryLambda.nextParameter()) let parameterAccess = ReqlExpr(json: [ReqlTerm.var.rawValue, [parameter.json]]) self.json = [ ReqlTerm.func.rawValue, [ [ReqlTerm.makeArray.rawValue, [parameter.json]], block(parameterAccess).json ] ] } init(_ block: ReqlPredicate2) { let parameter1 = ReqlExpr(json: ReqlQueryLambda.nextParameter()) let parameter2 = ReqlExpr(json: ReqlQueryLambda.nextParameter()) let parameterAccess1 = ReqlExpr(json: [ReqlTerm.var.rawValue, [parameter1.json]]) let parameterAccess2 = ReqlExpr(json: [ReqlTerm.var.rawValue, [parameter2.json]]) self.json = [ ReqlTerm.func.rawValue, [ [ReqlTerm.makeArray.rawValue, [parameter1.json, parameter2.json]], block(parameterAccess1, parameterAccess2).json ] ] } init(_ block: ReqlModification) { let p = ReqlQueryLambda.nextParameter() let parameter = ReqlExpr(json: p) let parameterAccess = ReqlExpr(json: [ReqlTerm.var.rawValue, [parameter.json]]) let changes = block(parameterAccess) var serializedChanges: [String: Any] = [:] for (k, v) in changes { serializedChanges[k] = v.json } self.json = [ ReqlTerm.func.rawValue, [ [ReqlTerm.makeArray.rawValue, [parameter.json]], serializedChanges ] ] } private static func nextParameter() -> Int { self.parameterLock.sync { self.parameterCounter += 1 } return self.parameterCounter } }
mit
667bd385e0e38fd5670b986872efe38a
31.780822
90
0.619724
4.664717
false
false
false
false
madcato/OSFramework
Sources/OSFramework/UIViewController+imageBackground.swift
1
754
// // UIViewController+imageBackground.swift // OSFramework // // Created by Daniel Vela on 27/04/2017. // Copyright © 2017 Daniel Vela. All rights reserved. // import Foundation public extension UIViewController { @objc func setAppBackground(imageName: String) { let backgroundImage = UIImageView(frame: UIScreen.main.bounds) backgroundImage.image = UIImage(named: imageName) view.insertSubview(backgroundImage, at: 0) } } public extension UITableViewController { override func setAppBackground(imageName: String) { let backgroundImage = UIImageView(frame: UIScreen.main.bounds) backgroundImage.image = UIImage(named: imageName) self.tableView.backgroundView = backgroundImage } }
mit
f77d79eac427bc494506517ac1534eec
29.12
70
0.722444
4.648148
false
false
false
false
sahandnayebaziz/Dana-Hills
Pods/RSBarcodes_Swift/Source/RSCode93Generator.swift
2
3896
// // RSCode93Generator.swift // RSBarcodesSample // // Created by R0CKSTAR on 6/11/14. // Copyright (c) 2014 P.D.Q. All rights reserved. // import UIKit // http://www.barcodeisland.com/code93.phtml open class RSCode93Generator: RSAbstractCodeGenerator, RSCheckDigitGenerator { let CODE93_ALPHABET_STRING = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. $/+%abcd*" let CODE93_PLACEHOLDER_STRING = "abcd"; let CODE93_CHARACTER_ENCODINGS = [ "100010100", "101001000", "101000100", "101000010", "100101000", "100100100", "100100010", "101010000", "100010010", "100001010", "110101000", "110100100", "110100010", "110010100", "110010010", "110001010", "101101000", "101100100", "101100010", "100110100", "100011010", "101011000", "101001100", "101000110", "100101100", "100010110", "110110100", "110110010", "110101100", "110100110", "110010110", "110011010", "101101100", "101100110", "100110110", "100111010", "100101110", "111010100", "111010010", "111001010", "101101110", "101110110", "110101110", "100100110", "111011010", "111010110", "100110010", "101011110" ] func encodeCharacterString(_ characterString:String) -> String { return CODE93_CHARACTER_ENCODINGS[CODE93_ALPHABET_STRING.location(characterString)] } override open func isValid(_ contents: String) -> Bool { if contents.length() > 0 && contents == contents.uppercased() { for i in 0..<contents.length() { if CODE93_ALPHABET_STRING.location(contents[i]) == NSNotFound { return false } if CODE93_PLACEHOLDER_STRING.location(contents[i]) != NSNotFound { return false } } return true } return false } override open func initiator() -> String { return self.encodeCharacterString("*") } override open func terminator() -> String { // With the termination bar: 1 return self.encodeCharacterString("*") + "1" } override open func barcode(_ contents: String) -> String { var barcode = "" for character in contents.characters { barcode += self.encodeCharacterString(String(character)) } let checkDigits = self.checkDigit(contents) for character in checkDigits.characters { barcode += self.encodeCharacterString(String(character)) } return barcode } // MARK: RSCheckDigitGenerator open func checkDigit(_ contents: String) -> String { // Weighted sum += value * weight // The first character var sum = 0 for i in 0..<contents.length() { if let character = contents[contents.length() - i - 1] { let characterValue = CODE93_ALPHABET_STRING.location(character) sum += characterValue * (i % 20 + 1) } } var checkDigits = "" checkDigits += CODE93_ALPHABET_STRING[sum % 47] // The second character sum = 0 let newContents = contents + checkDigits for i in 0..<newContents.length() { if let character = newContents[newContents.length() - i - 1] { let characterValue = CODE93_ALPHABET_STRING.location(character) sum += characterValue * (i % 15 + 1) } } checkDigits += CODE93_ALPHABET_STRING[sum % 47] return checkDigits } }
mit
7513479416c1dc86f001faa053ee6ba6
27.231884
91
0.536961
4.442417
false
false
false
false
cwwise/CWWeChat
CWWeChat/ChatModule/CWChatKit/Message/View/VoiceMessageContentView.swift
2
3682
// // VoiceMessageContentView.swift // CWWeChat // // Created by chenwei on 2017/9/15. // Copyright © 2017年 cwwise. All rights reserved. // import UIKit private let kReddotWidth: CGFloat = 6 class VoiceMessageContentView: MessageContentView { /// voice图标的imageView lazy var voiceImageView:UIImageView = { let voiceImageView = UIImageView() voiceImageView.size = CGSize(width: 12.5, height: 17) voiceImageView.contentMode = .scaleAspectFit return voiceImageView }() lazy var redTipImageView:UIImageView = { let redTipImageView = UIImageView() redTipImageView.clipsToBounds = true redTipImageView.backgroundColor = UIColor.redTipColor() redTipImageView.layer.cornerRadius = kReddotWidth/2 return redTipImageView }() lazy var voiceLengthLable: UILabel = { let voiceLengthLable = UILabel() return voiceLengthLable }() override init(frame: CGRect) { super.init(frame: frame) self.addSubview(voiceImageView) } override func refresh(message: CWMessageModel) { super.refresh(message: message) if message.isSend { setupVoicePlayIndicatorImageView(true) } else { setupVoicePlayIndicatorImageView(false) } } override func layoutSubviews() { super.layoutSubviews() guard let message = message else { voiceImageView.frame = self.bounds return } if message.isSend { let edge = ChatCellUI.right_edge_insets let size = CGSize(width: 13, height: 17) let origin = CGPoint(x: self.bounds.maxX-edge.right-size.width, y: edge.top) voiceImageView.frame = CGRect(origin: origin, size: size) } else { let edge = ChatCellUI.left_edge_insets let size = CGSize(width: 13, height: 17) let origin = CGPoint(x: edge.left, y: edge.top) voiceImageView.frame = CGRect(origin: origin, size: size) } } /// 设置播放 func setupVoicePlayIndicatorImageView(_ send: Bool) { let images: [UIImage] if send { images = [UIImage(named: "SenderVoiceNodePlaying001")!, UIImage(named: "SenderVoiceNodePlaying002")!, UIImage(named: "SenderVoiceNodePlaying003")!] voiceImageView.image = images.last } else { images = [UIImage(named: "ReceiverVoiceNodePlaying001")!, UIImage(named: "ReceiverVoiceNodePlaying002")!, UIImage(named: "ReceiverVoiceNodePlaying003")!] voiceImageView.image = images.last } voiceImageView.animationDuration = 1 voiceImageView.animationImages = images } func updateState() { // 如果正在播放 播放动画 if message?.playStatus == .playing { startAnimating() redTipImageView.isHidden = true } else if message?.playStatus == .none && message?.isSend == false { redTipImageView.isHidden = false stopAnimating() } else { redTipImageView.isHidden = true stopAnimating() } } /// 结束动画 func startAnimating() { voiceImageView.startAnimating() } /// 开始动画 func stopAnimating() { voiceImageView.stopAnimating() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
7a292614438851a8a980cfc00f29e279
28.745902
88
0.586939
5.162162
false
false
false
false
bloglucas/CoreData-Swift
CoreData/AbstractEntity.swift
1
1198
// // AbstractEntity.swift // CoreData // // Created by Lucas Conceição on 01/09/14. // Copyright (c) 2014 Lucas Conceicao. All rights reserved. // import Foundation import CoreData class AbstractEntity: NSManagedObject{ override init(entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?) { super.init(entity: entity, insertIntoManagedObjectContext: nil) } class func entityDescription() -> (NSEntityDescription) { fatalError("Must Override") } func delete(){ let context:NSManagedObjectContext = DataManager.getContext() var error:NSError? context.deleteObject(self) context.save(&error) if (error != nil){ NSLog(error!.description) } } func salvar(){ let context:NSManagedObjectContext = DataManager.getContext() var error:NSError? if (self.managedObjectContext == nil) { context.insertObject(self) } context.save(&error) if (error != nil){ NSLog(error!.description) } } }
gpl-2.0
33000e97f0621cd5a04c484fcba82e8c
22.470588
113
0.592809
5.133047
false
false
false
false
rahulsend89/MemoryGame
MemoryGame/JsonParsor.swift
1
3693
// // JsonParsor.swift // MemoryGame // // Created by Rahul Malik on 7/15/17. // Copyright © 2017 aceenvisage. All rights reserved. // import UIKit import UIKit class JsonParser: NSObject { func parseJson(_ json: AnyObject!, inToClass parseClass: ModelClass.Type!, keypath: String!) -> AnyObject { var paraResponseJson: AnyObject! = json if parseClass == nil { return json } if keypath != nil { if json.isKind(of: NSDictionary.self) && json[keypath] != nil { paraResponseJson = json[keypath]! as AnyObject } } if let paraResponseJsonDic = paraResponseJson as? NSDictionary { return parseDictionary(paraResponseJsonDic, intoClass: parseClass) } else { if let paraResponseJsonArray = paraResponseJson as? [NSDictionary] { let list: NSMutableArray! = NSMutableArray() for dict: NSDictionary in paraResponseJsonArray { list.add(self.parseDictionary(dict, intoClass: parseClass)) } return list } } return paraResponseJson } func parseDictionary(_ dictionary: NSDictionary, intoClass classObject: ModelClass.Type) -> AnyObject { let returnObject: AnyObject = classObject.init(dictionary: dictionary) return returnObject } func parseResponse(intoClass parseClass: ModelClass.Type, data: Data!, handlerError:(_ error: NSError?) -> Void, handlerResponse:(_ returnObject: AnyObject?) -> Void) { let jsonResponse: AnyObject! = self.parseToJSON(data) LogHelper.sharedInstance.log("JsonParser->parseResponse() JsonResponse: \(jsonResponse)") if (jsonResponse == nil) || jsonResponse.isKind(of: NSError.self) { handlerError(makeErrorWithDifferentCode("jsonResponseError")) LogHelper.sharedInstance.log("JsonParser->parseResponse() Error: Json Response Error : \(NSString(data: data, encoding: 4)!)") return } let returnObj: AnyObject = self.parseJson(jsonResponse, inToClass: parseClass, keypath: "photos") handlerResponse(returnObj) } func parseToJSON(_ data: Data) -> AnyObject? { var jsonResponse: AnyObject do { jsonResponse = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject return jsonResponse } catch let jsonError { LogHelper.sharedInstance.log("JsonParser->parseToJSON() Error: \(jsonError)") return nil } } func iterateJsonObject(_ json: AnyObject?, intoClass classObject: ModelClass.Type) -> AnyObject! { if json != nil { if let jsonArray = json as? [NSDictionary] { return self.parserJsonArray(jsonArray, intoClass: classObject) as AnyObject! } else { if let jsonDic = json as? NSDictionary { let tempDic: NSDictionary = jsonDic return self.parseDictionary(tempDic, intoClass: classObject) } } } return nil } func parserJsonArray(_ jsonArray: [NSDictionary], intoClass classObject: ModelClass.Type) -> [AnyObject] { var array: [AnyObject] = [AnyObject]() for (_, item) in jsonArray.enumerated() { if item.isKind(of: NSDictionary.self) { let instanceObject: AnyObject = self.parseDictionary(item as NSDictionary, intoClass: classObject) array.append(instanceObject) } } return array as [AnyObject] } }
mit
4e8201b080778a308b57f7c9d8691e3a
39.571429
172
0.621073
5.127778
false
false
false
false
JarlRyan/IOSNote
Swift/EmptyNavigation/EmptyNavigation/SecondViewController.swift
1
1467
// // SecondViewController.swift // EmptyNavigation // // Created by bingoogol on 14-6-17. // Copyright (c) 2014年 bingoogol. All rights reserved. // import UIKit protocol FontSizeChangeDelegate : NSObjectProtocol { func fontSizeDidChange(controller:SecondViewController,fontSize:Int) } class SecondViewController : UIViewController { var fontSize = 20 var delegate:FontSizeChangeDelegate? override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.greenColor() self.title = "第二页" let preButton = UIButton.buttonWithType(.System) as UIButton preButton.frame = CGRect(x:100,y:100,width:100,height:50) preButton.setTitle("返回上一页", forState:.Normal) preButton.addTarget(self,action:"prePage:",forControlEvents:.TouchUpInside) self.view.addSubview(preButton) let fontButton = UIButton.buttonWithType(.System) as UIButton fontButton.frame = CGRect(x:100,y:200,width:100,height:50) fontButton.setTitle("增大字体", forState:.Normal) fontButton.addTarget(self,action:"addFontSize",forControlEvents:.TouchUpInside) self.view.addSubview(fontButton) } func prePage(sender:UIButton) { self.navigationController.popViewControllerAnimated(true) } func addFontSize() { fontSize++ delegate!.fontSizeDidChange(self,fontSize:fontSize) } }
apache-2.0
834c140f42a08b06af67f09aead239bb
31.75
87
0.693269
4.420245
false
false
false
false
alecgorge/AGAudioPlayer
AGAudioPlayer/UI/Transition/AGAudioPlayerTransition.swift
1
4370
// // AGAudioPlayerViewControllerTransitioningDelegate.swift // AGAudioPlayer // // Created by Alec Gorge on 1/20/17. // Copyright © 2017 Alec Gorge. All rights reserved. // import UIKit import UIKit.UIGestureRecognizerSubclass public enum PanDirection { case vertical case horizontal } public class PanDirectionGestureRecognizer: UIPanGestureRecognizer { let direction: PanDirection init(direction: PanDirection, target: Any?, action: Selector?) { self.direction = direction super.init(target: target, action: action) } override public func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent) { super.touchesMoved(touches, with: event) if state == .began { let vel = velocity(in: view) switch direction { case .horizontal where abs(vel.y) > abs(vel.x): state = .cancelled case .vertical where abs(vel.x) > abs(vel.y): state = .cancelled default: break } } } } public class VerticalPanDirectionGestureRecognizer: PanDirectionGestureRecognizer { init(target: Any?, action: Selector?) { super.init(direction: .vertical, target: target, action: action) } } class AGAudioPlayerViewControllerTransitioningDelegate: NSObject, UIViewControllerTransitioningDelegate { public let interactor = Interactor() func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { return DismissAnimator() } func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { return interactor.hasStarted ? interactor : nil } func handleGesture(_ vc: UIViewController, inView: UIView, sender: UIPanGestureRecognizer) { let percentThreshold:CGFloat = 0.3 // convert y-position to downward pull progress (percentage) let translation = sender.translation(in: inView) let verticalMovement = translation.y / vc.view.bounds.height let downwardMovement = fmaxf(Float(verticalMovement), 0.0) let downwardMovementPercent = fminf(downwardMovement, 1.0) let progress = CGFloat(downwardMovementPercent) switch sender.state { case .began: interactor.hasStarted = true vc.dismiss(animated: true, completion: nil) case .changed: interactor.shouldFinish = progress > percentThreshold interactor.update(progress) case .cancelled: interactor.hasStarted = false interactor.cancel() case .ended: interactor.hasStarted = false interactor.shouldFinish ? interactor.finish() : interactor.cancel() default: break } } } class DismissAnimator : NSObject, UIViewControllerAnimatedTransitioning { func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.6 } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { let containerView = transitionContext.containerView guard let fromVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from), let toVC = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) else { return } containerView.insertSubview(toVC.view, belowSubview: fromVC.view) let screenBounds = UIScreen.main.bounds let bottomLeftCorner = CGPoint(x: 0, y: screenBounds.height) let finalFrame = CGRect(origin: bottomLeftCorner, size: screenBounds.size) UIView.animate( withDuration: transitionDuration(using: transitionContext), animations: { fromVC.view.frame = finalFrame }, completion: { _ in transitionContext.completeTransition(!transitionContext.transitionWasCancelled) } ) } } class Interactor: UIPercentDrivenInteractiveTransition { var hasStarted = false var shouldFinish = false }
mit
199dfd32f31af677b6ec6bcaa2edba13
33.401575
144
0.656443
5.666667
false
false
false
false
WhisperSystems/Signal-iOS
SignalMessaging/profiles/ProfileFetcherJob.swift
1
11045
// // Copyright (c) 2019 Open Whisper Systems. All rights reserved. // import Foundation import PromiseKit import SignalServiceKit import SignalMetadataKit @objc public class ProfileFetcherJob: NSObject { // This property is only accessed on the serial queue. static var fetchDateMap = [SignalServiceAddress: Date]() static let serialQueue = DispatchQueue(label: "org.signal.profileFetcherJob") let ignoreThrottling: Bool var backgroundTask: OWSBackgroundTask? @objc public class func run(thread: TSThread) { guard CurrentAppContext().isMainApp else { return } ProfileFetcherJob().run(addresses: thread.recipientAddresses) } @objc public class func run(address: SignalServiceAddress, ignoreThrottling: Bool) { guard CurrentAppContext().isMainApp else { return } ProfileFetcherJob(ignoreThrottling: ignoreThrottling).run(addresses: [address]) } @objc public class func run(username: String, completion: @escaping (_ address: SignalServiceAddress?, _ notFound: Bool, _ error: Error?) -> Void) { guard CurrentAppContext().isMainApp else { return } ProfileFetcherJob(ignoreThrottling: true).run(username: username, completion: completion) } public init(ignoreThrottling: Bool = false) { self.ignoreThrottling = ignoreThrottling } // MARK: - Dependencies private var networkManager: TSNetworkManager { return SSKEnvironment.shared.networkManager } private var socketManager: TSSocketManager { return TSSocketManager.shared } private var udManager: OWSUDManager { return SSKEnvironment.shared.udManager } private var profileManager: OWSProfileManager { return OWSProfileManager.shared() } private var identityManager: OWSIdentityManager { return SSKEnvironment.shared.identityManager } private var signalServiceClient: SignalServiceClient { // TODO hang on SSKEnvironment return SignalServiceRestClient() } private var tsAccountManager: TSAccountManager { return SSKEnvironment.shared.tsAccountManager } private var sessionStore: SSKSessionStore { return SSKSessionStore() } private var databaseStorage: SDSDatabaseStorage { return SDSDatabaseStorage.shared } // MARK: - public func run(addresses: [SignalServiceAddress]) { AssertIsOnMainThread() run { for address in addresses { self.getAndUpdateProfile(address: address) } } } public func run(username: String, completion: @escaping (_ address: SignalServiceAddress?, _ notFound: Bool, _ error: Error?) -> Void) { run { let request = OWSRequestFactory.getProfileRequest(withUsername: username) self.networkManager.makePromise(request: request) .map(on: DispatchQueue.global()) { try SignalServiceProfile(address: nil, responseObject: $1) } .done(on: DispatchQueue.global()) { serviceProfile in self.updateProfile(signalServiceProfile: serviceProfile) completion(serviceProfile.address, false, nil) }.catch(on: DispatchQueue.global()) { error in if case .taskError(let task, _)? = error as? NetworkManagerError, task.statusCode() == 404 { completion(nil, true, nil) return } completion(nil, false, error) }.retainUntilComplete() } } public func run(runBlock: @escaping () -> Void) { guard CurrentAppContext().isMainApp else { // Only refresh profiles in the MainApp to decrease the chance of missed SN notifications // in the AppExtension for our users who choose not to verify contacts. owsFailDebug("Should only fetch profiles in the main app") return } backgroundTask = OWSBackgroundTask(label: "\(#function)", completionBlock: { [weak self] status in AssertIsOnMainThread() guard status == .expired else { return } guard let _ = self else { return } Logger.error("background task time ran out before profile fetch completed.") }) DispatchQueue.global().async(execute: runBlock) } enum ProfileFetcherJobError: Error { case throttled(lastTimeInterval: TimeInterval) } public func getAndUpdateProfile(address: SignalServiceAddress, remainingRetries: Int = 3) { self.getProfile(address: address).map(on: DispatchQueue.global()) { profile in self.updateProfile(signalServiceProfile: profile) }.catch(on: DispatchQueue.global()) { error in switch error { case ProfileFetcherJobError.throttled: // skipping break case let error as SignalServiceProfile.ValidationError: Logger.warn("skipping updateProfile retry. Invalid profile for: \(address) error: \(error)") default: if remainingRetries > 0 { self.getAndUpdateProfile(address: address, remainingRetries: remainingRetries - 1) } else { Logger.warn("failed to get profile with error: \(error)") } } }.retainUntilComplete() } public func getProfile(address: SignalServiceAddress) -> Promise<SignalServiceProfile> { if !ignoreThrottling { if let lastDate = lastFetchDate(for: address) { let lastTimeInterval = fabs(lastDate.timeIntervalSinceNow) // Don't check a profile more often than every N seconds. // // Throttle less in debug to make it easier to test problems // with our fetching logic. let kGetProfileMaxFrequencySeconds = _isDebugAssertConfiguration() ? 60 : 60.0 * 5.0 guard lastTimeInterval > kGetProfileMaxFrequencySeconds else { return Promise(error: ProfileFetcherJobError.throttled(lastTimeInterval: lastTimeInterval)) } } } recordLastFetchDate(for: address) Logger.info("getProfile: \(address)") // Don't use UD for "self" profile fetches. var udAccess: OWSUDAccess? if !address.isLocalAddress { udAccess = udManager.udAccess(forAddress: address, requireSyncAccess: false) } return requestProfile(address: address, udAccess: udAccess, canFailoverUDAuth: true) } private func requestProfile(address: SignalServiceAddress, udAccess: OWSUDAccess?, canFailoverUDAuth: Bool) -> Promise<SignalServiceProfile> { let requestMaker = RequestMaker(label: "Profile Fetch", requestFactoryBlock: { (udAccessKeyForRequest) -> TSRequest in return OWSRequestFactory.getProfileRequest(address: address, udAccessKey: udAccessKeyForRequest) }, udAuthFailureBlock: { // Do nothing }, websocketFailureBlock: { // Do nothing }, address: address, udAccess: udAccess, canFailoverUDAuth: canFailoverUDAuth) return requestMaker.makeRequest() .map(on: DispatchQueue.global()) { (result: RequestMakerResult) -> SignalServiceProfile in try SignalServiceProfile(address: address, responseObject: result.responseObject) } } private func updateProfile(signalServiceProfile: SignalServiceProfile) { let address = signalServiceProfile.address verifyIdentityUpToDateAsync(address: address, latestIdentityKey: signalServiceProfile.identityKey) profileManager.updateProfile(for: address, profileNameEncrypted: signalServiceProfile.profileNameEncrypted, username: signalServiceProfile.username, avatarUrlPath: signalServiceProfile.avatarUrlPath) updateUnidentifiedAccess(address: address, verifier: signalServiceProfile.unidentifiedAccessVerifier, hasUnrestrictedAccess: signalServiceProfile.hasUnrestrictedUnidentifiedAccess) } private func updateUnidentifiedAccess(address: SignalServiceAddress, verifier: Data?, hasUnrestrictedAccess: Bool) { guard let verifier = verifier else { // If there is no verifier, at least one of this user's devices // do not support UD. udManager.setUnidentifiedAccessMode(.disabled, address: address) return } if hasUnrestrictedAccess { udManager.setUnidentifiedAccessMode(.unrestricted, address: address) return } guard let udAccessKey = udManager.udAccessKey(forAddress: address) else { udManager.setUnidentifiedAccessMode(.disabled, address: address) return } let dataToVerify = Data(count: 32) guard let expectedVerifier = Cryptography.computeSHA256HMAC(dataToVerify, withHMACKey: udAccessKey.keyData) else { owsFailDebug("could not compute verification") udManager.setUnidentifiedAccessMode(.disabled, address: address) return } guard expectedVerifier.ows_constantTimeIsEqual(to: verifier) else { Logger.verbose("verifier mismatch, new profile key?") udManager.setUnidentifiedAccessMode(.disabled, address: address) return } udManager.setUnidentifiedAccessMode(.enabled, address: address) } private func verifyIdentityUpToDateAsync(address: SignalServiceAddress, latestIdentityKey: Data) { databaseStorage.asyncWrite { (transaction) in if self.identityManager.saveRemoteIdentity(latestIdentityKey, address: address, transaction: transaction) { Logger.info("updated identity key with fetched profile for recipient: \(address)") self.sessionStore.archiveAllSessions(for: address, transaction: transaction) } else { // no change in identity. } } } private func lastFetchDate(for address: SignalServiceAddress) -> Date? { return ProfileFetcherJob.serialQueue.sync { return ProfileFetcherJob.fetchDateMap[address] } } private func recordLastFetchDate(for address: SignalServiceAddress) { ProfileFetcherJob.serialQueue.sync { ProfileFetcherJob.fetchDateMap[address] = Date() } } }
gpl-3.0
768a24a08c9fca3b72c541dfa9ceaa05
37.217993
146
0.626799
5.819283
false
false
false
false
zjjzmw1/speedxSwift
speedxSwift/Pods/RealmSwift/RealmSwift/Util.swift
34
1821
//////////////////////////////////////////////////////////////////////////// // // Copyright 2015 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import Foundation import Realm // MARK: Internal Helpers internal func notFoundToNil(index: UInt) -> Int? { if index == UInt(NSNotFound) { return nil } return Int(index) } internal func throwRealmException(message: String, userInfo: [String:AnyObject] = [:]) { NSException(name: RLMExceptionName, reason: message, userInfo: userInfo).raise() } internal func throwForNegativeIndex(int: Int, parameterName: String = "index") { if int < 0 { throwRealmException("Cannot pass a negative value for '\(parameterName)'.") } } internal func gsub(pattern: String, template: String, string: String, error: NSErrorPointer = nil) -> String? { do { let regex = try NSRegularExpression(pattern: pattern, options: []) return regex.stringByReplacingMatchesInString(string, options: [], range: NSRange(location: 0, length: string.utf16.count), withTemplate: template) } catch { // no-op } return nil }
mit
2d7282e49208ec876cec16a7152706ac
34.705882
111
0.602416
4.895161
false
false
false
false
svenbacia/TraktKit
TraktKit/Sources/Model/Season.swift
1
1546
// // Season.swift // TraktKit // // Created by Sven Bacia on 05.11.17. // Copyright © 2017 Sven Bacia. All rights reserved. // import Foundation public struct Season: Codable { // MARK: Codable private enum CodingKeys: String, CodingKey { case number case ids case rating case votes case episodesCount = "episode_count" case airedEpisodes = "aired_episodes" case title case overview case firstAired = "first_aired" case network case episodes } // MARK: - Properties public let number: Int public let ids: Ids public let rating: Double public let votes: Int public let episodesCount: Int public let airedEpisodes: Int public let title: String? public let overview: String? public let firstAired: Date? public let network: String? public let episodes: [Episode]? // MARK: - Init public init(number: Int, ids: Ids, rating: Double, votes: Int, episodesCount: Int, airedEpisodes: Int, title: String?, overview: String?, firstAired: Date?, network: String?, episodes: [Episode]?) { //swiftlint:disable:this line_length self.number = number self.ids = ids self.rating = rating self.votes = votes self.episodesCount = episodesCount self.airedEpisodes = airedEpisodes self.title = title self.overview = overview self.firstAired = firstAired self.network = network self.episodes = episodes } }
mit
1cf359012c715f0cf4080873602f6001
25.637931
239
0.631715
4.517544
false
false
false
false
ZeroFengLee/PieceStore
PieceStore/CodingSupport.swift
1
1222
// // CodingSupport.swift // CodingSupport // // Created by Zero on 16/7/2. // Copyright © 2016年 Zero. All rights reserved. // import Foundation open class CodingSupport: NSObject, NSCoding { public func encode(with aCoder: NSCoder) { var count: UInt32 = 0 let ivars = class_copyIvarList(self.classForCoder, &count) for i in 0..<Int(count) { let ivar = ivars?[i] let key = NSString(cString: ivar_getName(ivar!)!, encoding: String.Encoding.utf8.rawValue)! as String let value = self.value(forKey: key) aCoder.encode(value, forKey: key) } free(ivars) } public required init?(coder aDecoder: NSCoder) { super.init() var count: UInt32 = 0 let ivars = class_copyIvarList(self.classForCoder, &count) for i in 0..<Int(count) { let ivar = ivars?[i] let key = NSString(cString: ivar_getName(ivar!)!, encoding: String.Encoding.utf8.rawValue)! as String let value = aDecoder.decodeObject(forKey: key) self.setValue(value, forKey: key) } free(ivars) } public override init() { super.init() } }
mit
055d8c8c6804f359dad462faa20d5a84
28.731707
113
0.586546
3.996721
false
false
false
false
suzp1984/IOS-ApiDemo
ApiDemo-Swift/ApiDemo-Swift/ManualThreadedMandelbrotView.swift
1
3622
// // ManualThreadedMandelbrotView.swift // ApiDemo-Swift // // Created by Jacob su on 8/3/16. // Copyright © 2016 [email protected]. All rights reserved. // import UIKit class ManualThreadedMandelbrotView: UIView { let MANDELBROT_STEPS = 200 var bitmapContext: CGContext! var odd = false // jumping-off point: draw the Mandelbrot set func drawThatPuppy () { UIApplication.shared.beginIgnoringInteractionEvents() self.makeBitmapContext(self.bounds.size) let center = CGPoint(x: self.bounds.midX, y: self.bounds.midY) let d = ["center":NSValue(cgPoint: center), "zoom":CGFloat(1)] as [String : Any] self.performSelector(inBackground: #selector(reallyDraw), with: d) } // trampoline, background thread entry point func reallyDraw(_ d:[AnyHashable: Any]) { autoreleasepool { self.drawAtCenter((d["center"] as! NSValue).cgPointValue, zoom: d["zoom"] as! CGFloat) self.performSelector(onMainThread: #selector(allDone), with: nil, waitUntilDone: false) } } // called on main thread! background thread exit point func allDone() { self.setNeedsDisplay() UIApplication.shared.endIgnoringInteractionEvents() } // create bitmap context func makeBitmapContext(_ size:CGSize) { var bitmapBytesPerRow = Int(size.width * 4) bitmapBytesPerRow += (16 - (bitmapBytesPerRow % 16)) % 16 let colorSpace = CGColorSpaceCreateDeviceRGB() let prem = CGImageAlphaInfo.premultipliedLast.rawValue let context = CGContext(data: nil, width: Int(size.width), height: Int(size.height), bitsPerComponent: 8, bytesPerRow: bitmapBytesPerRow, space: colorSpace, bitmapInfo: prem) self.bitmapContext = context } // draw pixels of bitmap context func drawAtCenter(_ center:CGPoint, zoom:CGFloat) { func isInMandelbrotSet(_ re:Float, _ im:Float) -> Bool { var fl = true var (x, y, nx, ny) : (Float,Float,Float,Float) = (0,0,0,0) for _ in 0 ..< MANDELBROT_STEPS { nx = x*x - y*y + re ny = 2*x*y + im if nx*nx + ny*ny > 4 { fl = false break } x = nx y = ny } return fl } self.bitmapContext.setAllowsAntialiasing(false) self.bitmapContext.setFillColor(red: 0, green: 0, blue: 0, alpha: 1) var re : CGFloat var im : CGFloat let maxi = Int(self.bounds.size.width) let maxj = Int(self.bounds.size.height) for i in 0 ..< maxi { for j in 0 ..< maxj { re = (CGFloat(i) - 1.33 * center.x) / 160 im = (CGFloat(j) - 1.0 * center.y) / 160 re /= zoom im /= zoom if (isInMandelbrotSet(Float(re), Float(im))) { self.bitmapContext.fill (CGRect(x: CGFloat(i), y: CGFloat(j), width: 1.0, height: 1.0)) } } } } // ==== end of material called on background thread // turn pixels of bitmap context into CGImage, draw into ourselves override func draw(_ rect: CGRect) { if self.bitmapContext != nil { let context = UIGraphicsGetCurrentContext()! let im = self.bitmapContext.makeImage() context.draw(im!, in: self.bounds) self.odd = !self.odd self.backgroundColor = self.odd ? UIColor.green : UIColor.red } } }
apache-2.0
433e15ec93e315c8622d8cabccafc5eb
35.21
182
0.572494
4.26
false
false
false
false
techgrains/TGFramework-iOS
TGFrameworkExample/TGFrameworkExample/Classes/Service/EmployeeCreateService.swift
1
4523
import Foundation import TGFramework class EmployeeCreateService: TGService { static var instance:EmployeeCreateService? //Initialization service class instance class func getInstance() -> EmployeeCreateService { if instance == nil { instance = EmployeeCreateService() } return instance! } override init() { super.init() // Initialization code here. } func serviceParams(_ request: EmployeeCreateRequest) -> [AnyHashable: Any] { var dictionary = [AnyHashable: Any]() // Set MobileNumber if TGUtil.stringHasValue(request.name) { dictionary["name"] = request.name } else { dictionary["name"] = "" } // Set Live if TGUtil.stringHasValue(request.designation) { dictionary["designation"] = request.designation } else { dictionary["designation"] = "" } return dictionary } func generateResponseModal(_ json: [AnyHashable: Any]) -> EmployeeCreateResponse { let response = EmployeeCreateResponse() // Get Response Object if TGUtil.dictionaryHasValue((json as [AnyHashable : Any])) { if(json["status"] != nil) { response.status = json["status"] as! String // Get timestamp let timestamp: Float = (json["timestamp"] as! Float) response.timestamp = timestamp // Get error let error: String = (json["error"] as! String) if TGUtil.stringHasValue(error) { response.error = error } // Get message let message: String = (json["message"] as! String) if TGUtil.stringHasValue(message) { response.message = message } } else { let employee = Employee() // Get id let id: Int = (json["id"] as! Int) employee.id = id //response.id = id // Get name let name: String = (json["name"] as! String) if TGUtil.stringHasValue(name) { employee.name = name } // Get designation let designation: String = (json["designation"] as! String) if TGUtil.stringHasValue(designation) { employee.designation = designation } // Get created let created: Float = (json["created"] as! Float) employee.created = created // Get modified let modified: Float = (json["modified"] as! Float) employee.modified = modified let departments:[AnyObject] = (json["departments"] as! Array) if TGUtil.arrayHasValue(departments) { for j in 0..<departments.count { let departmentDic:[String: Any] = departments[j] as! [String : Any] let department = Department() department.code = departmentDic["code"] as! Int department.name = departmentDic["name"] as! String employee.departments.append(department) } } response.employee = employee } } return response } func serviceResponse(forURL requestUrl: String, with request: EmployeeCreateRequest) -> String { var response: String = "" switch REGISTER_SERVICE { case LIVE_SERVICE: let dictionary: [AnyHashable: Any] = self.serviceParams(request) response = self.serviceResponseByPostDictionary(requestUrl, dictionary) default: break } return response } func createEmployee(with request: EmployeeCreateRequest) -> EmployeeCreateResponse { let serviceResponse: String = self.serviceResponse(forURL: request.url(), with: request) let json: [AnyHashable: Any] = self.dictionaryfromJSON(serviceResponse) let response: EmployeeCreateResponse? = self.generateResponseModal(json) return response! } }
apache-2.0
cd28590cf145cf9f41b4b713526ef554
35.184
100
0.512492
5.725316
false
false
false
false
yangligeryang/codepath
labs/TableViewDemo/MovieData.playground/Contents.swift
1
1375
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" // Arrays let integers = [1,2,3,4,5,6,7,8,9] let firstItem = integers[0] let thirdItem = integers[2] let anotherFirstItem = integers.first let lastInt = integers.last let numberofInts = integers.count let reversedArray = integers.reversed() for integer in integers { // print(integer) } var colors = ["red", "blue", "green", "yellow"] for (index, color) in colors.enumerated() { // print("the color \(color) is at index \(index)") } colors[1] = "purple" colors let removedColor = colors.remove(at: 2) colors removedColor // Dictionaries let movie1 = ["title": "Wayne's World", "overview": "Wayne and Garth go on a crazy adventure"] let movie2 = ["overview": "Maverick and Goose try to outfly Iceman", "title": "Top Gun"] let movie3 = ["overview": "Airel wants to be a real woman", "title": "The Litte Mermaid"] let movies = [movie1, movie2, movie3] let title = movie1["title"] let title2 = movie2["title"] let overView = movie1["overview"] for movie in movies { print("in \(movie["title"]!), \(movie["overview"]!)") } let response: [String: Any] = ["dates": "someStuff", "pages": "moreStuff", "results": movies] let results = response["results"] as! [NSDictionary] let result = results[1] let resultTitle = result["title"]! print("\(resultTitle)")
apache-2.0
62e92701f0c5a88f03fa07a7f8e91d2f
24.462963
93
0.68
3.2277
false
false
false
false
gaowanli/PinGo
PinGo/PinGo/Home/FamousType.swift
1
879
// // FamousType.swift // PinGo // // Created by GaoWanli on 16/1/16. // Copyright © 2016年 GWL. All rights reserved. // import UIKit class FamousType: NSObject { var typeID = 0 var typeName: String? var isPrimary = 0 var isOfficial = 0 init(dict: [String: AnyObject]?) { super.init() guard let `dict` = dict, `dict`.keys.count > 0 else { return } for (key, value) in `dict` { let keyName = key as String if keyName == "typeID" { if let t = value as? String { setValue(Int(t), forKey: "typeID") }else if let t = value as? Int { setValue(t, forKey: "typeID") } continue } self.setValue(value, forKey: keyName) } } }
mit
851a56e65e6a3dc908f057ba9b76462b
22.052632
61
0.471461
4.036866
false
false
false
false
IdrissPiard/UnikornTube_Client
UnikornTube/User.swift
1
769
// // User.swift // UnikornTube // // Created by Damien Serin on 27/04/2015. // Copyright (c) 2015 SimpleAndNew. All rights reserved. // import UIKit class User: NSObject { var id : Int var username : String var email : String var channelName : String var profilImgUrl : String var subscriptions : [User] var playlist : [Playlist] init(id: Int, username: String, email: String, channelName : String, profilImgUrl: String, subscriptions : [User], playlist : [Playlist]) { self.id = id self.username = username self.email = email self.channelName = channelName self.profilImgUrl = profilImgUrl self.subscriptions = subscriptions self.playlist = playlist } }
mit
4b07bbf92f13299e13ca44a9be5a5c8d
23.806452
143
0.63459
4.068783
false
false
false
false
P0ed/FireTek
Source/SpaceEngine/Fabrics/SoundsFabric.swift
1
539
import SpriteKit enum SoundsFabric { static func preheat() { _ = [cannon, explosion, vehicleExplosion, crystalCollected] } static let crystalCollected: SKAction = .playSoundFileNamed("CrystalCollected.wav", waitForCompletion: false) static let cannon: SKAction = .playSoundFileNamed("Cannon0.wav", waitForCompletion: false) static let explosion: SKAction = .playSoundFileNamed("Boom1.wav", waitForCompletion: false) static let vehicleExplosion: SKAction = .playSoundFileNamed("Boom2.wav", waitForCompletion: false) }
mit
61305adce6ce48ce5b14d71cde49855d
25.95
73
0.769944
4.210938
false
false
false
false
sublimter/Meijiabang
KickYourAss/KickYourAss/SettingViewController.swift
3
6078
// // SettingViewController.swift // KickYourAss // // Created by eagle on 15/2/9. // Copyright (c) 2015年 多思科技. All rights reserved. // import UIKit class SettingViewController: UITableViewController { var userInfo: CYMJUserInfoData! override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() let flexLeft = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil) let logout = UIBarButtonItem(title: "退出账户", style: UIBarButtonItemStyle.Plain, target: self, action: "logoutButtonPressed:") let flexRight = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil) // navigationController?.toolbarItems = [flexLeft, logout, flexRight] setToolbarItems([flexLeft, logout, flexRight], animated: false) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) navigationController?.toolbarHidden = false } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) navigationController?.toolbarHidden = true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Action func logoutButtonPressed(sender: AnyObject) { LCYCommon.sharedInstance.logout() (navigationController?.viewControllers.first as? AboutMeViewController)?.refreshHeader() navigationController?.popToRootViewControllerAnimated(true) } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Potentially incomplete method implementation. // Return the number of sections. return 2 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete method implementation. // Return the number of rows in the section. switch section { case 0: return 2 case 1: return userInfo.role == "1" ? 2 : 3 default: return 0 } } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(SettingCell.identifier, forIndexPath: indexPath) as SettingCell // Configure the cell... switch indexPath.section { case 0: switch indexPath.row { case 0: cell.textLabel?.text = "消息设置" case 1: cell.textLabel?.text = "修改密码" default: break } case 1: switch indexPath.row { case 0: cell.textLabel?.text = "关于我们" case 1: cell.textLabel?.text = "注册协议" case 2: cell.textLabel?.text = "身份验证" default: break } default: break } return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { switch indexPath.section { case 0: switch indexPath.row { case 0: break case 1: performSegueWithIdentifier("modifyPassword", sender: nil) default: break } case 1: switch indexPath.row { case 0: performSegueWithIdentifier("showVersion", sender: nil) case 1: performSegueWithIdentifier("showWeb", sender: nil) case 2: break default: break } default: break } } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ }
mit
1c9bd422c536f345d73c252d3c4fcabd
32.631285
157
0.624751
5.605214
false
false
false
false
rcobelli/GameOfficials
Game Officials/GameCustomCell.swift
1
834
// // GameCustomCell.swift // Game Officials // // Created by Ryan Cobelli on 11/29/15. // Copyright © 2015 Rybel LLC. All rights reserved. // import UIKit class GameCustomCell: UITableViewCell { @IBOutlet weak var dateAndTimeLabel: UILabel! @IBOutlet weak var homeTeamLabel: UILabel! @IBOutlet weak var awayTeamLabel: UILabel! @IBOutlet weak var venueLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() self.selectionStyle = .none } func loadItem(_ homeTeam: String, awayTeam: String, dateAndTime: String, field: String) { dateAndTimeLabel.text = dateAndTime homeTeamLabel.text = homeTeam awayTeamLabel.text = awayTeam venueLabel.text = field } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } }
mit
3b7707bcaf3f72ad1218b4fb15597222
24.242424
90
0.721489
3.83871
false
false
false
false
magnetsystems/message-ios
Source/Poll/MMXPoll.swift
1
17290
/* * Copyright (c) 2015 Magnet Systems, Inc. * 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 MagnetMaxCore enum MMXPollErrorType : ErrorType { case IdEmpty case NameEmpty case OptionsEmpty case QuestionEmpty } extension Array where Element : Hashable { func exclude(A:Array<Element>) -> Array<Element> { var hash = [Int : Element]() for val in self { hash[val.hashValue] = val } var excluded = [Element]() for val in A { if let hashVal = hash[val.hashValue] { excluded.append(hashVal) } } return excluded } func union(A:Array<Element>) -> Array<Element> { var hash = [Int : Element]() for val in self { hash[val.hashValue] = val } var union = [Element]() for val in A { if let hashVal = hash[val.hashValue] { union.append(hashVal) } } return union } } @objc public class MMXPoll: NSObject { //MARK: Public Properties public private(set) var allowMultiChoice = false public private(set) var channel : MMXChannel? public let endDate: NSDate? public var extras: [String:String]? public let hideResultsFromOthers: Bool public private(set) var isPublished = false public private(set) var myVotes: [MMXPollOption]? public let name: String public var options: [MMXPollOption] public private(set) var ownerID: String? public private(set) var pollID: String? public let question: String //MARK: Private Properties private var underlyingSurvey: MMXSurvey? //MARK: Init public convenience init(name: String, question: String, options: [String], hideResultsFromOthers: Bool, endDate: NSDate? = nil, extras: [String:String]? = nil, allowMultiChoice: Bool = false) { var opts = [MMXPollOption]() for option in options { let mmxOption = MMXPollOption(text: option, count: 0) opts.append(mmxOption) } self.init(name : name, question: question, mmxPollOptions: opts, hideResultsFromOthers: hideResultsFromOthers, endDate: endDate, extras: extras, allowMultiChoice: allowMultiChoice) } //MARK: Creation public static func createPoll(name : String, question: String, options: [String], hideResultsFromOthers: Bool, endDate: NSDate? = nil, extras : [String:String]? = nil, allowMultiChoice : Bool = false) -> MMXPoll { return MMXPoll(name: name, question: question, options: options, hideResultsFromOthers: hideResultsFromOthers, endDate: endDate, extras: extras, allowMultiChoice: allowMultiChoice) } public static func createPoll(name : String, question: String, options: [String], hideResultsFromOthers: Bool, endDate: NSDate? = nil, extras : [String:String]? = nil) -> MMXPoll { return MMXPoll(name: name, question: question, options: options, hideResultsFromOthers: hideResultsFromOthers, endDate: endDate, extras: extras) } public static func createPoll(name : String, question: String, options: [String], hideResultsFromOthers: Bool, endDate: NSDate? = nil) -> MMXPoll { return MMXPoll(name: name, question: question, options: options, hideResultsFromOthers: hideResultsFromOthers, endDate: endDate) } public static func createPoll(name : String, question: String, options: [String], hideResultsFromOthers: Bool) -> MMXPoll { return MMXPoll(name: name, question: question, options: options, hideResultsFromOthers: hideResultsFromOthers) } //MARK: Private Init private init(name : String, question: String, mmxPollOptions options: [MMXPollOption], hideResultsFromOthers: Bool, endDate: NSDate?, extras: [String:String]?, allowMultiChoice: Bool) { self.question = question self.options = options self.name = name self.hideResultsFromOthers = hideResultsFromOthers self.endDate = endDate self.ownerID = MMUser.currentUser()?.userID self.extras = extras self.allowMultiChoice = allowMultiChoice } //MARK: Public Methods public func choose(option: MMXPollOption, success: ((MMXMessage?) -> Void)?, failure: ((error: NSError) -> Void)?) { choose(options: [option], success: success, failure: failure) } public func choose(options option: [MMXPollOption], success: ((MMXMessage?) -> Void)?, failure: ((error: NSError) -> Void)?) { guard let channel = self.channel else { assert(false, "Poll not related to a channel, please submit poll first.") return } guard option.count <= 1 || (option.count > 1 && self.allowMultiChoice) else { assert(false, "Only one option is allowed") return } var answers = [MMXSurveyAnswer]() let previousSelection = myVotes for opt in option { let answer = MMXSurveyAnswer() answer.selectedOptionId = opt.optionID answer.text = opt.text answer.questionId = self.underlyingSurvey?.surveyDefinition.questions.first?.questionId answers.append(answer) } let surveyAnswerRequest = MMXSurveyAnswerRequest() surveyAnswerRequest.answers = answers let call = MMXSurveyService().submitSurveyAnswers(self.pollID, body: surveyAnswerRequest, success: { let msg = MMXMessage(toChannel: channel, messageContent: [kQuestionKey: self.question], pushConfigName: kDefaultPollAnswerPushConfigNameKey) let result = MMXPollAnswer(self, selectedOptions: option, previousSelection: previousSelection) result.userID = MMUser.currentUser()?.userID ?? "" msg.payload = result self.myVotes = option if self.hideResultsFromOthers { success?(nil) } else { msg.sendWithSuccess({ [weak msg] users in if let weakMessage = msg { success?(weakMessage) } }, failure: { error in failure?(error: error) }) } }, failure: { error in failure?(error: error) }) call.executeInBackground(nil) } public func mmxPayload() -> MMXPollIdentifier? { return self.pollID != nil ? MMXPollIdentifier(self.pollID!) : nil } public func refreshResults(answer answer: MMXPollAnswer) { if let previous = answer.previousSelection { for option in self.options.union(previous) { if let count = option.count { option.count = count.integerValue - 1 } } } for option in self.options.union(answer.currentSelection) { if let count = option.count { option.count = count.integerValue + 1 } } if answer.userID == MMUser.currentUser()?.userID { self.myVotes = answer.currentSelection } } public func refreshResults(completion completion:((poll : MMXPoll?) -> Void)) { guard let pollID = self.pollID else { completion(poll: nil) return } MMXPoll.pollWithID(pollID, success: { (poll) in var hashMap = [Int: MMXPollOption]() for option in poll.options { hashMap[option.hashValue] = option } for option in self.options { option.count = hashMap[option.hashValue]?.count ?? 0 } let comp = {[weak self] in completion(poll: self) } comp() }) { (error) in completion(poll: nil) } } //MARK: Public Static Methods //MARK: Publish public func publish(channel channel: MMXChannel,success: ((MMXMessage) -> Void)?, failure: ((error: NSError) -> Void)?) { let msg = MMXMessage(toChannel: channel, messageContent: [kQuestionKey: question], pushConfigName: kDefaultPollPushConfigNameKey) publish(message: msg, success: success, failure: failure) } private func publish(message message: MMXMessage, success: ((MMXMessage) -> Void)?, failure: ((error: NSError) -> Void)?) { guard let channel = message.channel as MMXChannel? else { assert(false, "Channel must be set on message for poll") return } createPoll(channel, success: { message.payload = self.mmxPayload(); message.sendWithSuccess({ [weak message] users in self.isPublished = true if let weakMessage = message { success?(weakMessage) } }, failure: { error in failure?(error: error) }) }, failure: { error in failure?(error: error) }) } //MARK: Poll retrieval static public func pollFromMessage(message: MMXMessage, success: ((MMXPoll) -> Void), failure: ((error: NSError) -> Void)?) { if let payload = message.payload as? MMXPayload, let channel = message.channel { pollFromMMXPayload(payload, success: success, failure: failure) } else { let error = MMXClient.errorWithTitle("Poll", message: "Incompatible Message", code: 500) failure?(error : error) } } static private func pollWithID(pollID: String, success: ((MMXPoll) -> Void), failure: ((error: NSError) -> Void)?) { let service = MMXSurveyService() let call = service.getSurvey(pollID, success: {[weak service] survey in let call = service?.getResults(survey.surveyId, success: { surveyResults in MMXChannel.channelForID(survey.surveyDefinition.notificationChannelId, success: { (channel) in do { let poll = try self.pollFromSurveyResults(surveyResults, channel: channel) success(poll) } catch { let error = MMXClient.errorWithTitle("Poll", message: "Error Parsing Poll", code: 400) failure?(error : error) } }, failure: { (error) in failure?(error : error) }) }, failure: { error in failure?(error : error) }) call?.executeInBackground(nil) }, failure: { error in failure?(error : error) }) call.executeInBackground(nil) } //MARK Private Static Methods private func createPoll(channel: MMXChannel, success: (() -> Void), failure: ((error: NSError) -> Void)) { guard let user = MMUser.currentUser() else { let error = MMXClient.errorWithTitle("Login", message: "Must be logged in to use this API", code: 401) failure(error: error) return } let survey = MMXPoll.generateSurvey(channel: channel, owner: user, name: self.name, question: self.question, options: self.options, hideResultsFromOthers: self.hideResultsFromOthers, endDate: self.endDate, extras: self.extras, allowMultiChoice: self.allowMultiChoice) let call = MMXSurveyService().createSurvey(survey, success: { survey in let error = MMXClient.errorWithTitle("Poll", message: "Error Parsing Poll", code: 400) guard survey.surveyId != nil else { failure(error: error) return } self.pollID = survey.surveyId success() }, failure: { error in failure(error: error) }) call.executeInBackground(nil) } private static func generateSurvey(channel channel: MMXChannel, owner: MMUser,name: String, question: String, options: [MMXPollOption], hideResultsFromOthers: Bool, endDate: NSDate?, extras: [String : String]?, allowMultiChoice: Bool) -> MMXSurvey { let survey = MMXSurvey() survey.owners = [owner.userID] survey.name = name survey.metaData = extras let surveyDefinition = MMXSurveyDefinition() surveyDefinition.startDate = NSDate() surveyDefinition.endDate = endDate surveyDefinition.type = .POLL surveyDefinition.resultAccessModel = hideResultsFromOthers ? .PRIVATE : .PUBLIC surveyDefinition.participantModel = .PUBLIC survey.surveyDefinition = surveyDefinition let surveyQuestion = MMXSurveyQuestion() surveyQuestion.text = question surveyDefinition.notificationChannelId = channel.channelID var index = 0 let surveyOptions : [MMXSurveyOption] = options.map({ let option = MMXSurveyOption() option.displayOder = Int32(index) index += 1 option.value = $0.text option.metaData = $0.extras return option }) surveyQuestion.choices = surveyOptions surveyQuestion.displayOrder = 0 surveyQuestion.type = allowMultiChoice ? .MULTI_CHOICE : .SINGLE_CHOICE surveyDefinition.questions = [surveyQuestion] return survey } private static func pollFromSurveyResults(results : MMXSurveyResults, channel : MMXChannel) throws -> MMXPoll { let survey = results.survey guard let sid = survey.surveyId else { throw MMXPollErrorType.IdEmpty } guard let name = survey.name else { throw MMXPollErrorType.NameEmpty } guard let question = survey.surveyDefinition.questions.first else { throw MMXPollErrorType.QuestionEmpty } guard let options = survey.surveyDefinition.questions.first?.choices else { throw MMXPollErrorType.OptionsEmpty } let hideResultsFromOthers = survey.surveyDefinition.resultAccessModel == .PRIVATE let endDate = survey.surveyDefinition.endDate var choiceMap = [String : MMXSurveyChoiceResult]() for choiceResult in results.summary { choiceMap[choiceResult.selectedChoiceId] = choiceResult } var pollOptions: [MMXPollOption] = [] var myAnswers : [MMXPollOption] = [] for option in options { let count : NSNumber? = choiceMap[option.optionId] != nil ? NSNumber(longLong: choiceMap[option.optionId]!.count) : nil let pollOption = MMXPollOption(text: option.value, count: count) pollOption.pollID = survey.surveyId pollOption.optionID = option.optionId pollOption.extras = option.metaData if results.myAnswers.map({$0.selectedOptionId}).contains(option.optionId) { myAnswers.append(pollOption) } pollOptions.append(pollOption) } let poll = MMXPoll.init(name: name, question: question.text, mmxPollOptions: pollOptions, hideResultsFromOthers: hideResultsFromOthers, endDate: endDate, extras: survey.metaData, allowMultiChoice: question.type == .MULTI_CHOICE) poll.underlyingSurvey = survey poll.myVotes = myAnswers poll.ownerID = survey.owners.first poll.pollID = sid poll.channel = channel poll.isPublished = true return poll } static private func pollFromMMXPayload(payload : MMXPayload?, success: ((MMXPoll) -> Void), failure: ((error: NSError) -> Void)?) { if let pollIdentifier = payload as? MMXPollIdentifier { self.pollWithID(pollIdentifier.pollID, success: success, failure: failure) } else if let pollID = (payload as? MMXPollAnswer)?.pollID { self.pollWithID(pollID, success: success, failure: failure) } else { let error = MMXClient.errorWithTitle("Poll", message: "Incompatible Object Type", code: 500) failure?(error : error) } } } // MARK: MMXPoll Equality extension MMXPoll { override public var hash: Int { return pollID?.hashValue ?? 0 } override public func isEqual(object: AnyObject?) -> Bool { if let rhs = object as? MMXPoll { return pollID == rhs.pollID } return false } }
apache-2.0
56ac7c551a45ca876684a37b5d327159
38.565217
275
0.601215
5.00579
false
false
false
false
SpiciedCrab/CodingForP
CodingForP_Sample/CodingForP_Sample/SampleViewModel.swift
1
2246
// // SampleViewModel.swift // CodingForP_Sample // // Created by Harly on 2017/2/6. // Copyright © 2017年 MogoOrg. All rights reserved. // import UIKit class SampleViewModel: NSObject { func samplePlist() { let sampleSource = ["userName" : "harly", "userId" : "123", "price" : "99222"] guard let plistPath = Bundle.main.path(forResource: "sampleCodingP", ofType: "plist") else { return } guard let value = NSArray(contentsOfFile: plistPath)!.firstObject as? String else { return } print("\(smartTranslate(value, fromLazyServerJson: sampleSource))") } func setupData() -> [String : Any] { let sampleSource = ["id" : "10000", "name" : "Fish", "salary" : 5000 , "summary" : "fff", "description" : "sss"] as [String : Any] let person = Person(json : sampleSource) return ["Name" : person.name, "price" : person.displayedSalary , "Summary" : person.summary , "Desciprtion" : person.displayedDiscription] } } func setupData() -> [String : Any] { let sampleSource = ["id" : "10000", "name" : "Fish", "salary" : 5000 , "summary" : "fff", "description" : "sss"] as [String : Any] let person = Person(json : sampleSource) return ["Name" : person.name, "Salary" : person.displayedSalary , "Summary" : person.summary , "Desciprtion" : person.displayedDiscription] } struct Person { var id : String! var name : String! var salary : Double = 0 var summary : String! var description : String! var displayedDiscription : String { return "PersonId : \(id) \n Description : \(description)" } var displayedSalary : String { return currencyGenerator(currencyDoubleValue: salary) } func currencyGenerator(currencyDoubleValue : Double) -> String { return "" } init(json : [String : Any]) { } } struct ConfigRow { // left title var key : String! // right title var value : String! // json中对应的key值 var valuePath : String! var sortOrder : Int = 0 var color : String = "" }
mit
d0195bfacb5e70414848a65117122cba
24.965116
138
0.575459
3.952212
false
false
false
false
laurentVeliscek/AudioKit
AudioKit/Common/Nodes/Generators/Oscillators/PWM Oscillator/AKPWMOscillator.swift
1
7329
// // AKPWMOscillator.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright (c) 2016 Aurelius Prochazka. All rights reserved. // import AVFoundation /// Pulse-Width Modulating Oscillator /// /// - Parameters: /// - frequency: In cycles per second, or Hz. /// - amplitude: Output amplitude /// - pulseWidth: Duty cycle width (range 0-1). /// - detuningOffset: Frequency offset in Hz. /// - detuningMultiplier: Frequency detuning multiplier /// public class AKPWMOscillator: AKNode, AKToggleable { // MARK: - Properties internal var internalAU: AKPWMOscillatorAudioUnit? internal var token: AUParameterObserverToken? private var frequencyParameter: AUParameter? private var amplitudeParameter: AUParameter? private var pulseWidthParameter: AUParameter? private var detuningOffsetParameter: AUParameter? private var detuningMultiplierParameter: AUParameter? /// Ramp Time represents the speed at which parameters are allowed to change public var rampTime: Double = AKSettings.rampTime { willSet { if rampTime != newValue { internalAU?.rampTime = newValue internalAU?.setUpParameterRamp() } } } /// In cycles per second, or Hz. public var frequency: Double = 440 { willSet { if frequency != newValue { if internalAU!.isSetUp() { frequencyParameter?.setValue(Float(newValue), originator: token!) } else { internalAU?.frequency = Float(newValue) } } } } /// Output amplitude public var amplitude: Double = 1.0 { willSet { if amplitude != newValue { if internalAU!.isSetUp() { amplitudeParameter?.setValue(Float(newValue), originator: token!) } else { internalAU?.amplitude = Float(newValue) } } } } /// Frequency offset in Hz. public var detuningOffset: Double = 0 { willSet { if detuningOffset != newValue { if internalAU!.isSetUp() { detuningOffsetParameter?.setValue(Float(newValue), originator: token!) } else { internalAU?.detuningOffset = Float(newValue) } } } } /// Frequency detuning multiplier public var detuningMultiplier: Double = 1 { willSet { if detuningMultiplier != newValue { if internalAU!.isSetUp() { detuningMultiplierParameter?.setValue(Float(newValue), originator: token!) } else { internalAU?.detuningMultiplier = Float(newValue) } } } } /// Duty cycle width (range 0-1). public var pulseWidth: Double = 0.5 { willSet { if pulseWidth != newValue { if internalAU!.isSetUp() { pulseWidthParameter?.setValue(Float(newValue), originator: token!) } else { internalAU?.pulseWidth = Float(newValue) } } } } /// Tells whether the node is processing (ie. started, playing, or active) public var isStarted: Bool { return internalAU!.isPlaying() } // MARK: - Initialization /// Initialize the oscillator with defaults /// /// - parameter frequency: In cycles per second, or Hz. /// public convenience override init() { self.init(frequency: 440) } /// Initialize this oscillator node /// /// - Parameters: /// - frequency: In cycles per second, or Hz. /// - amplitude: Output amplitude /// - pulseWidth: Duty cycle width (range 0-1). /// - detuningOffset: Frequency offset in Hz. /// - detuningMultiplier: Frequency detuning multiplier /// public init( frequency: Double, amplitude: Double = 1.0, pulseWidth: Double = 0.5, detuningOffset: Double = 0, detuningMultiplier: Double = 1) { self.frequency = frequency self.amplitude = amplitude self.pulseWidth = pulseWidth self.detuningOffset = detuningOffset self.detuningMultiplier = detuningMultiplier var description = AudioComponentDescription() description.componentType = kAudioUnitType_Generator description.componentSubType = 0x70776d6f /*'pwmo'*/ description.componentManufacturer = 0x41754b74 /*'AuKt'*/ description.componentFlags = 0 description.componentFlagsMask = 0 AUAudioUnit.registerSubclass( AKPWMOscillatorAudioUnit.self, asComponentDescription: description, name: "Local AKPWMOscillator", version: UInt32.max) super.init() AVAudioUnit.instantiateWithComponentDescription(description, options: []) { avAudioUnit, error in guard let avAudioUnitGenerator = avAudioUnit else { return } self.avAudioNode = avAudioUnitGenerator self.internalAU = avAudioUnitGenerator.AUAudioUnit as? AKPWMOscillatorAudioUnit AudioKit.engine.attachNode(self.avAudioNode) } guard let tree = internalAU?.parameterTree else { return } frequencyParameter = tree.valueForKey("frequency") as? AUParameter amplitudeParameter = tree.valueForKey("amplitude") as? AUParameter pulseWidthParameter = tree.valueForKey("pulseWidth") as? AUParameter detuningOffsetParameter = tree.valueForKey("detuningOffset") as? AUParameter detuningMultiplierParameter = tree.valueForKey("detuningMultiplier") as? AUParameter token = tree.tokenByAddingParameterObserver { address, value in dispatch_async(dispatch_get_main_queue()) { if address == self.frequencyParameter!.address { self.frequency = Double(value) } else if address == self.amplitudeParameter!.address { self.amplitude = Double(value) } else if address == self.pulseWidthParameter!.address { self.pulseWidth = Double(value) } else if address == self.detuningOffsetParameter!.address { self.detuningOffset = Double(value) } else if address == self.detuningMultiplierParameter!.address { self.detuningMultiplier = Double(value) } } } internalAU?.frequency = Float(frequency) internalAU?.amplitude = Float(amplitude) internalAU?.pulseWidth = Float(pulseWidth) internalAU?.detuningOffset = Float(detuningOffset) internalAU?.detuningMultiplier = Float(detuningMultiplier) } /// Function to start, play, or activate the node, all do the same thing public func start() { self.internalAU!.start() } /// Function to stop or bypass the node, both are equivalent public func stop() { self.internalAU!.stop() } }
mit
cddd71d014c5dd8642025ecf3439ce8d
33.247664
94
0.59094
5.716849
false
false
false
false
loudnate/Loop
Loop/AppDelegate.swift
1
7004
// // AppDelegate.swift // Naterade // // Created by Nathan Racklyeft on 8/15/15. // Copyright © 2015 Nathan Racklyeft. All rights reserved. // import UIKit import Intents import LoopKit import UserNotifications @UIApplicationMain final class AppDelegate: UIResponder, UIApplicationDelegate { private lazy var log = DiagnosticLogger.shared.forCategory("AppDelegate") var window: UIWindow? private var deviceManager: DeviceDataManager? private var rootViewController: RootNavigationController! { return window?.rootViewController as? RootNavigationController } private var isAfterFirstUnlock: Bool { let fileManager = FileManager.default do { let documentDirectory = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor:nil, create:false) let fileURL = documentDirectory.appendingPathComponent("protection.test") guard fileManager.fileExists(atPath: fileURL.path) else { let contents = Data("unimportant".utf8) try? contents.write(to: fileURL, options: .completeFileProtectionUntilFirstUserAuthentication) // If file doesn't exist, we're at first start, which will be user directed. return true } let contents = try? Data(contentsOf: fileURL) return contents != nil } catch { log.error(error) } return false } private func finishLaunch() { log.default("Finishing launching") deviceManager = DeviceDataManager() NotificationManager.authorize(delegate: self) let mainStatusViewController = UIStoryboard(name: "Main", bundle: Bundle(for: AppDelegate.self)).instantiateViewController(withIdentifier: "MainStatusViewController") as! StatusTableViewController mainStatusViewController.deviceManager = deviceManager rootViewController.pushViewController(mainStatusViewController, animated: false) } func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { log.default("didFinishLaunchingWithOptions \(String(describing: launchOptions))") AnalyticsManager.shared.application(application, didFinishLaunchingWithOptions: launchOptions) guard isAfterFirstUnlock else { log.default("Launching before first unlock; pausing launch...") return false } finishLaunch() let notificationOption = launchOptions?[.remoteNotification] if let notification = notificationOption as? [String: AnyObject] { deviceManager?.handleRemoteNotification(notification) } return true } func applicationWillResignActive(_ application: UIApplication) { log.default(#function) } func applicationDidEnterBackground(_ application: UIApplication) { log.default(#function) } func applicationWillEnterForeground(_ application: UIApplication) { log.default(#function) } func applicationDidBecomeActive(_ application: UIApplication) { deviceManager?.updatePumpManagerBLEHeartbeatPreference() } func applicationWillTerminate(_ application: UIApplication) { log.default(#function) } // MARK: - Continuity func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool { log.default(#function) if #available(iOS 12.0, *) { if userActivity.activityType == NewCarbEntryIntent.className { log.default("Restoring \(userActivity.activityType) intent") rootViewController.restoreUserActivityState(.forNewCarbEntry()) return true } } switch userActivity.activityType { case NSUserActivity.newCarbEntryActivityType, NSUserActivity.viewLoopStatusActivityType: log.default("Restoring \(userActivity.activityType) activity") restorationHandler([rootViewController]) return true default: return false } } // MARK: - Remote notifications func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { let tokenParts = deviceToken.map { data in String(format: "%02.2hhx", data) } let token = tokenParts.joined() log.default("RemoteNotifications device token: \(token)") deviceManager?.loopManager.settings.deviceToken = deviceToken } func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { log.error("Failed to register: \(error)") } func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void ) { guard let notification = userInfo as? [String: AnyObject] else { completionHandler(.failed) return } deviceManager?.handleRemoteNotification(notification) completionHandler(.noData) } func applicationProtectedDataDidBecomeAvailable(_ application: UIApplication) { log.default("applicationProtectedDataDidBecomeAvailable") if deviceManager == nil { finishLaunch() } } } extension AppDelegate: UNUserNotificationCenterDelegate { func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { switch response.actionIdentifier { case NotificationManager.Action.retryBolus.rawValue: if let units = response.notification.request.content.userInfo[NotificationManager.UserInfoKey.bolusAmount.rawValue] as? Double, let startDate = response.notification.request.content.userInfo[NotificationManager.UserInfoKey.bolusStartDate.rawValue] as? Date, startDate.timeIntervalSinceNow >= TimeInterval(minutes: -5) { AnalyticsManager.shared.didRetryBolus() deviceManager?.enactBolus(units: units, at: startDate) { (_) in completionHandler() } return } default: break } completionHandler() } func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { completionHandler([.badge, .sound, .alert]) } }
apache-2.0
49b55f22bb33a2d79d5da7776f023d95
36.05291
207
0.669856
6.170044
false
false
false
false
PureSwift/Cacao
Sources/Cacao/UIPressesEvent.swift
1
1534
// // UIPressesEvent.swift // Cacao // // Created by Alsey Coleman Miller on 11/26/17. // import Foundation /// An event that describes the state of a set of physical buttons that are available to the device, /// such as those on an associated remote or game controller. public class UIPressesEvent: UIEvent { /// Returns the state of all physical buttons in the event. public internal(set) var allPresses: Set<UIPress> = [] public private(set) var triggeringPhysicalButton: UIPress? /// Returns the state of all physical buttons in the event that are associated with a particular gesture recognizer. public func presses(for gesture: UIGestureRecognizer) -> Set<UIPress> { return Set(allPresses.filter({ ($0.gestureRecognizers ?? []).contains(where: { $0 === gesture }) })) } internal func physicalButtons(for window: UIWindow) -> Set<UIPress> { return Set(allPresses.filter({ $0.window === window })) } internal func responders(for window: UIWindow) -> Set<UIResponder> { return Set(allPresses.flatMap({ $0.responder })) } internal func physicalButtons(for responder: UIResponder) -> Set<UIPress> { return Set(allPresses.filter({ $0.responder === responder })) } internal func physicalButtons(for responder: UIResponder, with phase: UIPressPhase) -> Set<UIPress> { return Set(allPresses.filter({ $0.responder === responder && $0.phase == phase })) } }
mit
f5f476fc1c1f88199269bf97a64aed55
33.863636
120
0.653846
4.620482
false
false
false
false
bitjammer/swift
test/Interpreter/generic_objc_subclass.swift
15
4939
// RUN: rm -rf %t // RUN: mkdir -p %t // // RUN: %target-clang -fobjc-arc %S/Inputs/ObjCClasses/ObjCClasses.m -c -o %t/ObjCClasses.o // RUN: %target-build-swift -I %S/Inputs/ObjCClasses/ -Xlinker %t/ObjCClasses.o %s -o %t/a.out // RUN: %target-run %t/a.out | %FileCheck %s // REQUIRES: executable_test // REQUIRES: objc_interop import Foundation import ObjCClasses @objc protocol P { func calculatePrice() -> Int } protocol PP { func calculateTaxes() -> Int } // // Generic subclass of an @objc class // class A<T> : HasHiddenIvars, P { var first: Int = 16 var second: T? var third: Int = 61 override var description: String { return "Grilled artichokes" } func calculatePrice() -> Int { return 400 } } let a = A<Int>() // CHECK: Grilled artichokes // CHECK: Grilled artichokes print(a.description) print((a as NSObject).description) let f = { (a.x, a.y, a.z, a.t, a.first, a.second, a.third) } // CHECK: (0, 0, 0, 0, 16, nil, 61) print(f()) // CHECK: (25, 225, 255, 2255, 16, nil, 61) a.x = 25 a.y = 225 a.z = 255 a.t = 2255 print(f()) // CHECK: (36, 225, 255, 2255, 16, nil, 61) a.x = 36 print(f()) // CHECK: (36, 225, 255, 2255, 16, Optional(121), 61) a.second = 121 print(f()) // // Instantiate the class with a different set of generic parameters // let aa = A<(Int, Int)>() let ff = { (aa.x, aa.y, aa.z, aa.t, aa.first, aa.second, aa.third) } // CHECK: (0, 0, 0, 0, 16, nil, 61) print(ff()) aa.x = 101 aa.second = (19, 84) aa.third = 17 // CHECK: (101, 0, 0, 0, 16, Optional((19, 84)), 17) print(ff()) // // Concrete subclass of generic subclass of @objc class // class B : A<(Int, Int)> { override var description: String { return "Salmon" } @nonobjc override func calculatePrice() -> Int { return 1675 } } class BB : B {} class C : A<(Int, Int)>, PP { @nonobjc override var description: String { return "Invisible Chicken" } override func calculatePrice() -> Int { return 650 } func calculateTaxes() -> Int { return 110 } } // CHECK: 400 // CHECK: 400 // CHECK: 650 // CHECK: 110 print((BB() as P).calculatePrice()) print((B() as P).calculatePrice()) print((C() as P).calculatePrice()) print((C() as PP).calculateTaxes()) // CHECK: Salmon // CHECK: Grilled artichokes print((B() as NSObject).description) print((C() as NSObject).description) let b = B() let g = { (b.x, b.y, b.z, b.t, b.first, b.second, b.third) } // CHECK: (0, 0, 0, 0, 16, nil, 61) print(g()) b.x = 101 b.second = (19, 84) b.third = 17 // CHECK: (101, 0, 0, 0, 16, Optional((19, 84)), 17) print(g()) // // Generic subclass of @objc class without any generically-sized members // class FixedA<T> : HasHiddenIvars, P { var first: Int = 16 var second: [T] = [] var third: Int = 61 override var description: String { return "Grilled artichokes" } func calculatePrice() -> Int { return 400 } } let fixedA = FixedA<Int>() // CHECK: Grilled artichokes // CHECK: Grilled artichokes print(fixedA.description) print((fixedA as NSObject).description) let fixedF = { (fixedA.x, fixedA.y, fixedA.z, fixedA.t, fixedA.first, fixedA.second, fixedA.third) } // CHECK: (0, 0, 0, 0, 16, [], 61) print(fixedF()) // CHECK: (25, 225, 255, 2255, 16, [], 61) fixedA.x = 25 fixedA.y = 225 fixedA.z = 255 fixedA.t = 2255 print(fixedF()) // CHECK: (36, 225, 255, 2255, 16, [], 61) fixedA.x = 36 print(fixedF()) // CHECK: (36, 225, 255, 2255, 16, [121], 61) fixedA.second = [121] print(fixedF()) // // Instantiate the class with a different set of generic parameters // let fixedAA = FixedA<(Int, Int)>() let fixedFF = { (fixedAA.x, fixedAA.y, fixedAA.z, fixedAA.t, fixedAA.first, fixedAA.second, fixedAA.third) } // CHECK: (0, 0, 0, 0, 16, [], 61) print(fixedFF()) fixedAA.x = 101 fixedAA.second = [(19, 84)] fixedAA.third = 17 // CHECK: (101, 0, 0, 0, 16, [(19, 84)], 17) print(fixedFF()) // // Concrete subclass of generic subclass of @objc class // without any generically-sized members // class FixedB : FixedA<Int> { override var description: String { return "Salmon" } override func calculatePrice() -> Int { return 1675 } } // CHECK: 675 print((FixedB() as P).calculatePrice()) // CHECK: Salmon print((FixedB() as NSObject).description) let fixedB = FixedB() let fixedG = { (fixedB.x, fixedB.y, fixedB.z, fixedB.t, fixedB.first, fixedB.second, fixedB.third) } // CHECK: (0, 0, 0, 0, 16, [], 61) print(fixedG()) fixedB.x = 101 fixedB.second = [19, 84] fixedB.third = 17 // CHECK: (101, 0, 0, 0, 16, [19, 84], 17) print(fixedG()) // Problem with field alignment in direct generic subclass of NSObject - // <https://bugs.swift.org/browse/SR-2586> public class PandorasBox<T>: NSObject { final public var value: T public init(_ value: T) { // Uses ConstantIndirect access pattern self.value = value } } let c = PandorasBox(30) // CHECK: 30 // Uses ConstantDirect access pattern print(c.value)
apache-2.0
99cc4ab512d83c0ff38f0fefa20bdd0d
18.677291
108
0.62867
2.922485
false
false
false
false
JadenGeller/Helium
Helium/Helium/Window/Toolbar/Items/DirectionalNavigationButtonsToolbarItem.swift
1
3131
// // DirectionalNavigationButtonsToolbarItem.swift // Helium // // Created by Jaden Geller on 5/14/20. // Copyright © 2020 Jaden Geller. All rights reserved. // import Cocoa import OpenCombine import OpenCombineFoundation import WebKit class DirectionalNavigationButtonsToolbarItem: NSToolbarItem { struct Model { var observeCanGoBack: (@escaping (Bool) -> Void) -> NSKeyValueObservation var observeCanGoForward: (@escaping (Bool) -> Void) -> NSKeyValueObservation var backForwardList: WKBackForwardList var navigateToBackForwardListItem: (WKBackForwardListItem) -> Void } enum Segment: Int { case back = 0 case forward = 1 } let model: Model var tokens: [NSKeyValueObservation] = [] init(model: Model) { self.model = model super.init(itemIdentifier: .directionalNavigationButtons) let control = NSSegmentedControl() control.segmentStyle = .separated control.trackingMode = .momentary control.isContinuous = false control.segmentCount = 2 control.target = self control.action = #selector(navigate) control.setImage(NSImage(named: NSImage.goBackTemplateName), forSegment: 0) control.setImage(NSImage(named: NSImage.goForwardTemplateName), forSegment: 1) view = control // FIXME: Memory leaks? tokens.append(model.observeCanGoBack { canGoBack in control.setEnabled(canGoBack, forSegment: Segment.back.rawValue) control.setMenu(HostingMenu(rootMenu: { ForEach(self.model.backForwardList.backList.reversed()) { backItem in // FIXME: Add icons to buttons Button(backItem.title ?? backItem.url.absoluteString, action: { self.model.navigateToBackForwardListItem(backItem) }) } }), forSegment: Segment.back.rawValue) }) tokens.append(model.observeCanGoForward { canGoForward in control.setEnabled(canGoForward, forSegment: Segment.forward.rawValue) control.setMenu(HostingMenu(rootMenu: { ForEach(self.model.backForwardList.forwardList) { forwardItem in Button(forwardItem.title ?? forwardItem.url.absoluteString, action: { self.model.navigateToBackForwardListItem(forwardItem) }) } }), forSegment: Segment.forward.rawValue) }) } var control: NSSegmentedControl { view as! NSSegmentedControl } @objc func navigate(_ control: NSSegmentedControl) { switch Segment(rawValue: control.selectedSegment)! { case .back: model.navigateToBackForwardListItem(model.backForwardList.backItem!) case .forward: model.navigateToBackForwardListItem(model.backForwardList.forwardItem!) } } } extension NSToolbarItem.Identifier { static var directionalNavigationButtons = NSToolbarItem.Identifier("directionalNavigationButtons") }
mit
fe6d6fc9d33b21446e3805b82f055600
36.261905
102
0.645687
5.234114
false
false
false
false
gregomni/swift
stdlib/public/Concurrency/AsyncFilterSequence.swift
3
4305
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2021 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import Swift @available(SwiftStdlib 5.1, *) extension AsyncSequence { /// Creates an asynchronous sequence that contains, in order, the elements of /// the base sequence that satisfy the given predicate. /// /// In this example, an asynchronous sequence called `Counter` produces `Int` /// values from `1` to `10`. The `filter(_:)` method returns `true` for even /// values and `false` for odd values, thereby filtering out the odd values: /// /// let stream = Counter(howHigh: 10) /// .filter { $0 % 2 == 0 } /// for await number in stream { /// print("\(number) ", terminator: " ") /// } /// // Prints: 2 4 6 8 10 /// /// - Parameter isIncluded: A closure that takes an element of the /// asynchronous sequence as its argument and returns a Boolean value /// that indicates whether to include the element in the filtered sequence. /// - Returns: An asynchronous sequence that contains, in order, the elements /// of the base sequence that satisfy the given predicate. @preconcurrency @inlinable public __consuming func filter( _ isIncluded: @Sendable @escaping (Element) async -> Bool ) -> AsyncFilterSequence<Self> { return AsyncFilterSequence(self, isIncluded: isIncluded) } } /// An asynchronous sequence that contains, in order, the elements of /// the base sequence that satisfy a given predicate. @available(SwiftStdlib 5.1, *) public struct AsyncFilterSequence<Base: AsyncSequence> { @usableFromInline let base: Base @usableFromInline let isIncluded: (Element) async -> Bool @usableFromInline init( _ base: Base, isIncluded: @escaping (Base.Element) async -> Bool ) { self.base = base self.isIncluded = isIncluded } } @available(SwiftStdlib 5.1, *) extension AsyncFilterSequence: AsyncSequence { /// The type of element produced by this asynchronous sequence. /// /// The filter sequence produces whatever type of element its base /// sequence produces. public typealias Element = Base.Element /// The type of iterator that produces elements of the sequence. public typealias AsyncIterator = Iterator /// The iterator that produces elements of the filter sequence. public struct Iterator: AsyncIteratorProtocol { @usableFromInline var baseIterator: Base.AsyncIterator @usableFromInline let isIncluded: (Base.Element) async -> Bool @usableFromInline init( _ baseIterator: Base.AsyncIterator, isIncluded: @escaping (Base.Element) async -> Bool ) { self.baseIterator = baseIterator self.isIncluded = isIncluded } /// Produces the next element in the filter sequence. /// /// This iterator calls `next()` on its base iterator; if this call returns /// `nil`, `next()` returns nil. Otherwise, `next()` evaluates the /// result with the `predicate` closure. If the closure returns `true`, /// `next()` returns the received element; otherwise it awaits the next /// element from the base iterator. @inlinable public mutating func next() async rethrows -> Base.Element? { while true { guard let element = try await baseIterator.next() else { return nil } if await isIncluded(element) { return element } } } } @inlinable public __consuming func makeAsyncIterator() -> Iterator { return Iterator(base.makeAsyncIterator(), isIncluded: isIncluded) } } @available(SwiftStdlib 5.1, *) extension AsyncFilterSequence: @unchecked Sendable where Base: Sendable, Base.Element: Sendable { } @available(SwiftStdlib 5.1, *) extension AsyncFilterSequence.Iterator: @unchecked Sendable where Base.AsyncIterator: Sendable, Base.Element: Sendable { }
apache-2.0
de5cd41bd2e764545e17a11b4f68b84a
33.166667
80
0.657375
4.772727
false
false
false
false
mcberros/memeMe
memePickingImages/ViewController.swift
1
6181
// // ViewController.swift // memePickingImages // // Created by Carmen Berros on 27/11/15. // Copyright © 2015 mcberros. All rights reserved. // import UIKit class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate { @IBOutlet weak var imagePickerView: UIImageView! @IBOutlet weak var cameraButton: UIBarButtonItem! @IBOutlet weak var topText: UITextField! @IBOutlet weak var bottonText: UITextField! @IBOutlet weak var shareAction: UIBarButtonItem! private let memeTextAttributes = [ NSStrokeColorAttributeName: UIColor.blackColor(), NSForegroundColorAttributeName: UIColor.whiteColor(), NSFontAttributeName: UIFont(name: "HelveticaNeue-CondensedBlack", size: 40)!, NSStrokeWidthAttributeName: -4 ] // Text Field Delegate object private let memeTextDelegate = MemeTextFieldDelegate() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. setTextField(topText, initialText: "TOP") setTextField(bottonText, initialText: "BOTTOM") } override func viewWillAppear(animated: Bool) { cameraButton.enabled = UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera) subscribeToKeyboardNotifications() UIApplication.sharedApplication().statusBarHidden = true shareAction.enabled = false } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) unsubscribeFromKeyboardNotifications() } @IBAction func pickAnImageFromAlbum(sender: AnyObject) { pickAnImageFromSource(UIImagePickerControllerSourceType.PhotoLibrary) } @IBAction func pickAnImageFromCamera(sender: AnyObject) { pickAnImageFromSource(UIImagePickerControllerSourceType.Camera) } @IBAction func startActivityView(sender: AnyObject) { let image = generateMemedImage() let controller = UIActivityViewController(activityItems: [image], applicationActivities: nil) controller.completionWithItemsHandler = saveMemeAfterSharing presentViewController(controller, animated: true, completion: nil) } @IBAction func cancelAction(sender: AnyObject) { dismissViewControllerAnimated(true, completion: nil) } func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String: AnyObject]) { if let image = info[UIImagePickerControllerOriginalImage] as? UIImage { imagePickerView.image = image dismissViewControllerAnimated(true, completion: { () -> Void in self.shareAction.enabled = true }); } } func imagePickerControllerDidCancel(picker: UIImagePickerController) { dismissViewControllerAnimated(true, completion: {}); } // Move view frame up func keyboardWillShow(notification: NSNotification) { if bottonText.isFirstResponder() && view.frame.origin.y == 0 { view.frame.origin.y -= getKeyboardHeight(notification) } } // Move view frame down func keyboardWillHide(notification: NSNotification) { if bottonText.isFirstResponder() { view.frame.origin.y += getKeyboardHeight(notification) } } private func setTextField(textField: UITextField, initialText: String) { textField.text = initialText textField.delegate = memeTextDelegate textField.defaultTextAttributes = memeTextAttributes textField.textAlignment = .Center } private func pickAnImageFromSource(sourceType: UIImagePickerControllerSourceType){ let imagePicker = UIImagePickerController() imagePicker.delegate = self imagePicker.sourceType = sourceType presentViewController(imagePicker, animated: true, completion: nil) } private func saveMemeAfterSharing(activity: String?, completed: Bool, items: [AnyObject]?, err: NSError?) -> Void { if completed { save() dismissViewControllerAnimated(true, completion: nil) } } private func getKeyboardHeight(notification: NSNotification) -> CGFloat{ let userInfo = notification.userInfo let keyboardSize = userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue return keyboardSize.CGRectValue().height } private func subscribeToKeyboardNotifications() { NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil) } private func unsubscribeFromKeyboardNotifications() { NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil) } private func generateMemedImage() -> UIImage { navigationController?.setToolbarHidden(true, animated: true) navigationController?.setNavigationBarHidden(true, animated: true) // Render view to an image UIGraphicsBeginImageContext(view.frame.size) view.drawViewHierarchyInRect(view.frame, afterScreenUpdates: true) let memedImage: UIImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() navigationController?.setToolbarHidden(false, animated: true) navigationController?.setNavigationBarHidden(false, animated: true) return memedImage } private func save() { //Create the meme let meme = Meme(topText: topText.text!, bottonText: bottonText.text!, originalImage: imagePickerView.image!, memedImage: generateMemedImage()) let object = UIApplication.sharedApplication().delegate let appDelegate = object as! AppDelegate appDelegate.memes.append(meme) } }
mit
9e775de863422b75bf7b14f298e7cc92
36.454545
150
0.71246
6.041056
false
false
false
false
ByteriX/BxInputController
BxInputController/Sources/Rows/Date/BxInputDateRow.swift
1
1872
/** * @file BxInputDateRow.swift * @namespace BxInputController * * @details Row for choosing date from selector with keyboard frame * @date 10.01.2017 * @author Sergey Balalaev * * @version last in https://github.com/ByteriX/BxInputController.git * @copyright The MIT License (MIT) https://opensource.org/licenses/MIT * Copyright (c) 2017 ByteriX. See http://byterix.com */ import UIKit /// Row for choosing date from selector with keyboard frame open class BxInputDateRow : BxInputValueRow { /// Make and return Binder for binding row with cell. open var binder : BxInputRowBinder { return BxInputDateRowBinder<BxInputDateRow, BxInputStandartTextCell>(row: self) } open var resourceId : String { get { return "BxInputStandartTextCell" } } open var estimatedHeight : CGFloat { get { return 60 } } open var title : String? open var subtitle: String? open var placeholder : String? open var isEnabled : Bool = true open var value: Date? = nil open var minimumDate: Date? = nil open var maximumDate: Date? = nil /// Default date for first selection time. If is nil then will be selected now date open var defaultDate: Date? = nil /// Return true if value for the row is empty open var hasEmptyValue: Bool { return value == nil } public init(title: String? = nil, subtitle: String? = nil, placeholder: String? = nil, value: Date? = nil) { self.title = title self.subtitle = subtitle self.placeholder = placeholder self.value = value } /// event when value of current row was changed open func didChangeValue(){ // } /// Date for first selection time. var firstSelectionDate : Date { return defaultDate ?? Date() } }
mit
d49381ee56bd5c543d364efeeeea46d2
26.940299
87
0.642628
4.363636
false
false
false
false
weirenxin/Swift30day
9-ImageScroller/9-ImageScroller/ViewController.swift
1
2854
// // ViewController.swift // 9-ImageScroller // // Created by weirenxin on 2016/12/29. // Copyright © 2016年 广西家饰宝科技有限公司. All rights reserved. // import UIKit class ViewController: UIViewController, UIScrollViewDelegate { private lazy var imageView: UIImageView = { return UIImageView(image: UIImage(named: "steve")) }() private lazy var scrollView: UIScrollView = {[weak self] in let scrollView = UIScrollView(frame: (self?.view.bounds)!) scrollView.autoresizingMask = [.flexibleWidth, .flexibleHeight] scrollView.backgroundColor = UIColor.clear scrollView.contentSize = (self?.imageView.bounds.size)! scrollView.delegate = self return scrollView }() override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } override func viewDidLoad() { super.viewDidLoad() scrollView.addSubview(imageView) view.addSubview(scrollView) setZoomScaleFor(scrollViewSize: scrollView.bounds.size) scrollView.zoomScale = scrollView.minimumZoomScale recenterImage() } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() setZoomScaleFor(scrollViewSize: scrollView.bounds.size) if scrollView.zoomScale < scrollView.minimumZoomScale { scrollView.zoomScale = scrollView.minimumZoomScale } recenterImage() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } private func setZoomScaleFor(scrollViewSize: CGSize) { let imageSize = imageView.bounds.size let widthScale = scrollViewSize.width / imageSize.width let heightScale = scrollViewSize.height / imageSize.height let minimunScale = min(widthScale, heightScale) scrollView.minimumZoomScale = minimunScale scrollView.maximumZoomScale = 3.0 } private func recenterImage() { let scrollViewSize = scrollView.bounds.size let imageViewSize = imageView.bounds.size let horizontalSpace = imageViewSize.width < scrollViewSize.width ? (scrollViewSize.width - imageViewSize.width) / 2.0 : 0 let verticalSpace = imageViewSize.height < scrollViewSize.height ? (scrollViewSize.height - imageViewSize.width) / 2.0 : 0 scrollView.contentInset = UIEdgeInsetsMake(verticalSpace, horizontalSpace, verticalSpace, horizontalSpace) } func viewForZooming(in scrollView: UIScrollView) -> UIView? { return imageView } func scrollViewDidZoom(_ scrollView: UIScrollView) { recenterImage() } }
apache-2.0
5c2312d7d24ade3ea046aa75a43e444d
30.433333
130
0.659244
5.613095
false
false
false
false
Sergey-Lomov/SSPPullToRefresh
SSPPullToRefresh/SSPLayerSpeedActivityView.swift
1
1129
// // SSPLayerSpeedActivityView.swift // BezierAnimation // // Created by Sergey Lomov on 4/24/17. // Copyright © 2017 Rozdoum. All rights reserved. // import UIKit open class SSPLayerSpeedActivityView: SSPActivityIndicatorView { private var animationAddingTime:CFTimeInterval? // Should be called in subclass at animation adding public final func setAnimationAddingTime () { animationAddingTime = CACurrentMediaTime() } public final override func reset() { layer.speed = 0.0 layer.timeOffset = animationAddingTime! } public final override func startAnimating() { let stopedLayerTime = layer.convertTime(CACurrentMediaTime(), from: nil) layer.speed = 1.0 layer.timeOffset = 0.0 let runedLayerTime = layer.convertTime(CACurrentMediaTime(), from: nil) layer.timeOffset = -1 * (runedLayerTime - stopedLayerTime) } public final override func stopAnimating() { let layerTime = layer.convertTime(CACurrentMediaTime(), from: nil) layer.speed = 0 layer.timeOffset = layerTime } }
mit
2b04ed246a0faebe3249ecc47d88dbdf
27.923077
80
0.675532
4.458498
false
false
false
false
bgerstle/wikipedia-ios
Wikipedia/Code/WMFTableOfContentsPresentationController.swift
1
8173
import UIKit // MARK: - Delegate @objc public protocol WMFTableOfContentsPresentationControllerTapDelegate { func tableOfContentsPresentationControllerDidTapBackground(controller: WMFTableOfContentsPresentationController) } public class WMFTableOfContentsPresentationController: UIPresentationController { // MARK: - init public required init(presentedViewController: UIViewController, presentingViewController: UIViewController, tapDelegate: WMFTableOfContentsPresentationControllerTapDelegate) { self.tapDelegate = tapDelegate super.init(presentedViewController: presentedViewController, presentingViewController: presentedViewController) } weak public var tapDelegate: WMFTableOfContentsPresentationControllerTapDelegate? public var minimumVisibleBackgroundWidth: CGFloat = 60.0 public var maximumTableOfContentsWidth: CGFloat = 300.0 public var closeButtonPadding: CGFloat = 10.0 public var statusBarEstimatedHeight: CGFloat = 20.0 // MARK: - Views lazy var statusBarBackground: UIView = { let view = UIView(frame: CGRect(x: CGRectGetMinX(self.containerView!.bounds), y: CGRectGetMinY(self.containerView!.bounds), width: CGRectGetWidth(self.containerView!.bounds), height: self.statusBarEstimatedHeight)) view.autoresizingMask = .FlexibleWidth let statusBarBackgroundBottomBorder = UIView(frame: CGRectMake(CGRectGetMinX(view.bounds), CGRectGetMaxY(view.bounds), CGRectGetWidth(view.bounds), 0.5)) statusBarBackgroundBottomBorder.autoresizingMask = .FlexibleWidth view.backgroundColor = UIColor.whiteColor() statusBarBackgroundBottomBorder.backgroundColor = UIColor.lightGrayColor() view.addSubview(statusBarBackgroundBottomBorder) return view }() lazy var closeButton:UIButton = { let button = UIButton(frame: CGRectZero) button.setImage(UIImage(named: "close"), forState: UIControlState.Normal) button.tintColor = UIColor.whiteColor() button.addTarget(self, action: "didTap:", forControlEvents: .TouchUpInside) button.accessibilityHint = localizedStringForKeyFallingBackOnEnglish("table-of-contents-close-accessibility-hint") button.accessibilityLabel = localizedStringForKeyFallingBackOnEnglish("table-of-contents-close-accessibility-label") return button }() lazy var backgroundView :UIVisualEffectView = { let view = UIVisualEffectView(frame: CGRectZero) view.autoresizingMask = .FlexibleWidth view.effect = UIBlurEffect(style: .Dark) view.alpha = 0.0 let tap = UITapGestureRecognizer.init() tap.addTarget(self, action: Selector("didTap:")) view.addGestureRecognizer(tap) view.addSubview(self.statusBarBackground) view.addSubview(self.closeButton) return view }() func updateButtonConstraints() { self.closeButton.mas_remakeConstraints({ make in make.width.equalTo()(44) make.height.equalTo()(44) make.leading.equalTo()(self.closeButton.superview!.mas_leading).offset()(10) if(self.traitCollection.verticalSizeClass == .Compact){ make.top.equalTo()(self.closeButtonPadding) }else{ make.top.equalTo()(self.closeButtonPadding + self.statusBarEstimatedHeight) } return () }) } func didTap(tap: UITapGestureRecognizer) { self.tapDelegate?.tableOfContentsPresentationControllerDidTapBackground(self); } // MARK: - Accessibility func togglePresentingViewControllerAccessibility(accessible: Bool) { self.presentingViewController.view.accessibilityElementsHidden = !accessible } // MARK: - UIPresentationController override public func presentationTransitionWillBegin() { // Add the dimming view and the presented view to the heirarchy self.backgroundView.frame = self.containerView!.bounds self.containerView!.addSubview(self.backgroundView) if(self.traitCollection.verticalSizeClass == .Compact){ self.statusBarBackground.hidden = true } updateButtonConstraints() self.containerView!.addSubview(self.presentedView()!) // Hide the presenting view controller for accessibility self.togglePresentingViewControllerAccessibility(false) //Add shadow to the presented view self.presentedView()?.layer.shadowOpacity = 0.5 self.presentedView()?.layer.shadowOffset = CGSize(width: 3, height: 5) self.presentedView()?.clipsToBounds = false // Fade in the dimming view alongside the transition if let transitionCoordinator = self.presentingViewController.transitionCoordinator() { transitionCoordinator.animateAlongsideTransition({(context: UIViewControllerTransitionCoordinatorContext!) -> Void in self.backgroundView.alpha = 1.0 }, completion:nil) } } override public func presentationTransitionDidEnd(completed: Bool) { if !completed { self.backgroundView.removeFromSuperview() } } override public func dismissalTransitionWillBegin() { if let transitionCoordinator = self.presentingViewController.transitionCoordinator() { transitionCoordinator.animateAlongsideTransition({(context: UIViewControllerTransitionCoordinatorContext!) -> Void in self.backgroundView.alpha = 0.0 }, completion:nil) } } override public func dismissalTransitionDidEnd(completed: Bool) { if completed { self.backgroundView.removeFromSuperview() self.togglePresentingViewControllerAccessibility(true) //Remove shadow from the presented View self.presentedView()?.layer.shadowOpacity = 0.0 self.presentedView()?.clipsToBounds = true } } override public func frameOfPresentedViewInContainerView() -> CGRect { var frame = self.containerView!.bounds; var bgWidth = self.minimumVisibleBackgroundWidth var tocWidth = frame.size.width - bgWidth if(tocWidth > self.maximumTableOfContentsWidth){ tocWidth = self.maximumTableOfContentsWidth bgWidth = frame.size.width - tocWidth } if !UIApplication.sharedApplication().wmf_tocShouldBeOnLeft{ frame.origin.x += bgWidth } frame.origin.y = UIApplication.sharedApplication().statusBarFrame.size.height + 0.5; frame.size.width = tocWidth return frame } override public func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator transitionCoordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransitionToSize(size, withTransitionCoordinator: transitionCoordinator) transitionCoordinator.animateAlongsideTransition({(context: UIViewControllerTransitionCoordinatorContext!) -> Void in self.backgroundView.frame = self.containerView!.bounds let frame = self.frameOfPresentedViewInContainerView() self.presentedView()!.frame = frame }, completion:nil) } override public func willTransitionToTraitCollection(newCollection: UITraitCollection, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { super.willTransitionToTraitCollection(newCollection, withTransitionCoordinator: coordinator) if newCollection.verticalSizeClass == .Compact { self.statusBarBackground.hidden = true; } if newCollection.verticalSizeClass == .Regular { self.statusBarBackground.hidden = false; } coordinator.animateAlongsideTransition({(context: UIViewControllerTransitionCoordinatorContext!) -> Void in self.updateButtonConstraints() }, completion:nil) } }
mit
06fdeb8320434bb1c901956487bc2a2e
39.661692
222
0.691301
6.345497
false
false
false
false
Instagram/IGListKit
Examples/Examples-iOS/IGListKitExamples/Views/CenterLabelCell.swift
1
818
/* * Copyright (c) Meta Platforms, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import UIKit final class CenterLabelCell: UICollectionViewCell { lazy private var label: UILabel = { let view = UILabel() view.backgroundColor = .clear view.textAlignment = .center view.textColor = .white view.font = .boldSystemFont(ofSize: 18) self.contentView.addSubview(view) return view }() var text: String? { get { return label.text } set { label.text = newValue } } override func layoutSubviews() { super.layoutSubviews() label.frame = contentView.bounds } }
mit
d3298c48baaa38cad091f72a25256ece
21.722222
66
0.601467
4.595506
false
false
false
false
anas10/AASquaresLoading
Source/AASquaresLoading.swift
2
8842
// // AASquaresLoading.swift // Etix Mobile // // Created by Anas Ait Ali on 18/02/15. // Copyright (c) 2015 Etix. All rights reserved. // import UIKit //MARK: AASquareLoadingInterface /** Interface for the AASquareLoading class */ public protocol AASquareLoadingInterface: class { var color : UIColor { get set } var backgroundColor : UIColor? { get set } func start(_ delay : TimeInterval) func stop(_ delay : TimeInterval) func setSquareSize(_ size: Float) } private var AASLAssociationKey: UInt8 = 0 //MARK: UIView extension public extension UIView { /** Variable to allow access to the class AASquareLoading */ public var squareLoading: AASquareLoadingInterface { get { if let value = objc_getAssociatedObject(self, &AASLAssociationKey) as? AASquareLoadingInterface { return value } else { let squareLoading = AASquaresLoading(target: self) objc_setAssociatedObject(self, &AASLAssociationKey, squareLoading, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) return squareLoading } } set { objc_setAssociatedObject(self, &AASLAssociationKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) } } } //MARK: AASquareLoading class /** Main class AASquareLoading */ open class AASquaresLoading : UIView, AASquareLoadingInterface, CAAnimationDelegate { open var view : UIView = UIView() fileprivate(set) open var size : Float = 0 open var color : UIColor = UIColor(red: 0, green: 0.48, blue: 1, alpha: 1) { didSet { for layer in squares { layer.backgroundColor = color.cgColor } } } open var parentView : UIView? fileprivate var squareSize: Float? fileprivate var gapSize: Float? fileprivate var moveTime: Float? fileprivate var squareStartX: Float? fileprivate var squareStartY: Float? fileprivate var squareStartOpacity: Float? fileprivate var squareEndX: Float? fileprivate var squareEndY: Float? fileprivate var squareEndOpacity: Float? fileprivate var squareOffsetX: [Float] = [Float](repeating: 0, count: 9) fileprivate var squareOffsetY: [Float] = [Float](repeating: 0, count: 9) fileprivate var squareOpacity: [Float] = [Float](repeating: 0, count: 9) fileprivate var squares : [CALayer] = [CALayer]() public init(target: UIView) { super.init(frame: target.frame) parentView = target setup(self.size) } public init(target: UIView, size: Float) { super.init(frame: target.frame) parentView = target setup(size) } override init(frame: CGRect) { super.init(frame: frame) setup(0) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup(0) } open override func layoutSubviews() { updateFrame() super.layoutSubviews() } fileprivate func setup(_ size: Float) { self.size = size updateFrame() self.initialize() } fileprivate func updateFrame() { if parentView != nil { self.frame = CGRect(x: 0, y: 0, width: parentView!.frame.width, height: parentView!.frame.height) } if size == 0 { let width = frame.size.width let height = frame.size.height size = width > height ? Float(height/8) : Float(width/8) } self.view.frame = CGRect(x: frame.width / 2 - CGFloat(size) / 2, y: frame.height / 2 - CGFloat(size) / 2, width: CGFloat(size), height: CGFloat(size)) } /** Function to start the loading animation - Parameter delay : The delay before the loading start */ open func start(_ delay : TimeInterval = 0.0) { if (parentView != nil) { self.layer.opacity = 0 self.parentView!.addSubview(self) UIView.animate(withDuration: 0.6, delay: delay, options: UIViewAnimationOptions(), animations: { () -> Void in self.layer.opacity = 1 }, completion: nil) } } /** Function to start the loading animation - Parameter delay : The delay before the loading start */ open func stop(_ delay : TimeInterval = 0.0) { if (parentView != nil) { self.layer.opacity = 1 UIView.animate(withDuration: 0.6, delay: delay, options: UIViewAnimationOptions(), animations: { () -> Void in self.layer.opacity = 0 }, completion: { (success: Bool) -> Void in self.removeFromSuperview() }) } } open func setSquareSize(_ size: Float) { self.view.layer.sublayers = nil setup(size) } fileprivate func initialize() { let gap : Float = 0.04 gapSize = size * gap squareSize = size * (1.0 - 2 * gap) / 3 moveTime = 0.15 squares = [CALayer]() self.addSubview(view) if (self.backgroundColor == nil) { self.backgroundColor = UIColor.white.withAlphaComponent(0.9) } for i : Int in 0 ..< 3 { for j : Int in 0 ..< 3 { var offsetX, offsetY : Float let idx : Int = 3 * i + j if i == 1 { offsetX = squareSize! * (2 - Float(j)) + gapSize! * (2 - Float(j)) offsetY = squareSize! * Float(i) + gapSize! * Float(i) } else { offsetX = squareSize! * Float(j) + gapSize! * Float(j) offsetY = squareSize! * Float(i) + gapSize! * Float(i) } squareOffsetX[idx] = offsetX squareOffsetY[idx] = offsetY squareOpacity[idx] = 0.1 * (Float(idx) + 1) } } squareStartX = squareOffsetX[0] squareStartY = squareOffsetY[0] - 2 * squareSize! - 2 * gapSize! squareStartOpacity = 0.0 squareEndX = squareOffsetX[8] squareEndY = squareOffsetY[8] + 2 * squareSize! + 2 * gapSize! squareEndOpacity = 0.0 for i in -1 ..< 9 { self.addSquareAnimation(i) } } fileprivate func addSquareAnimation(_ position: Int) { let square : CALayer = CALayer() if position == -1 { square.frame = CGRect(x: CGFloat(squareStartX!), y: CGFloat(squareStartY!), width: CGFloat(squareSize!), height: CGFloat(squareSize!)) square.opacity = squareStartOpacity! } else { square.frame = CGRect(x: CGFloat(squareOffsetX[position]), y: CGFloat(squareOffsetY[position]), width: CGFloat(squareSize!), height: CGFloat(squareSize!)) square.opacity = squareOpacity[position] } square.backgroundColor = self.color.cgColor squares.append(square) self.view.layer.addSublayer(square) var keyTimes = [Float]() var alphas = [Float]() keyTimes.append(0.0) if position == -1 { alphas.append(0.0) } else { alphas.append(squareOpacity[position]) } if position == 0 { square.opacity = 0.0 } let sp : CGPoint = square.position let path : CGMutablePath = CGMutablePath() path.move(to: CGPoint(x: sp.x, y: sp.y)) var x, y, a : Float if position == -1 { x = squareOffsetX[0] - squareStartX! y = squareOffsetY[0] - squareStartY! a = squareOpacity[0] } else if position == 8 { x = squareEndX! - squareOffsetX[position] y = squareEndY! - squareOffsetY[position] a = squareEndOpacity! } else { x = squareOffsetX[position + 1] - squareOffsetX[position] y = squareOffsetY[position + 1] - squareOffsetY[position] a = squareOpacity[position + 1] } path.addLine(to: CGPoint(x: sp.x + CGFloat(x), y: sp.y + CGFloat(y))) keyTimes.append(1.0 / 8.0) alphas.append(a) path.addLine(to: CGPoint(x: sp.x + CGFloat(x), y: sp.y + CGFloat(y))) keyTimes.append(1.0) alphas.append(a) let posAnim : CAKeyframeAnimation = CAKeyframeAnimation(keyPath: "position") posAnim.isRemovedOnCompletion = false posAnim.duration = Double(moveTime! * 8) posAnim.path = path posAnim.keyTimes = keyTimes as [NSNumber]? let alphaAnim : CAKeyframeAnimation = CAKeyframeAnimation(keyPath: "opacity") alphaAnim.isRemovedOnCompletion = false alphaAnim.duration = Double(moveTime! * 8) alphaAnim.values = alphas alphaAnim.keyTimes = keyTimes as [NSNumber]? let blankAnim : CAKeyframeAnimation = CAKeyframeAnimation(keyPath: "opacity") blankAnim.isRemovedOnCompletion = false blankAnim.beginTime = Double(moveTime! * 8) blankAnim.duration = Double(moveTime!) blankAnim.values = [0.0, 0.0] blankAnim.keyTimes = [0.0, 1.0] var beginTime : Float if position == -1 { beginTime = 0 } else { beginTime = moveTime! * Float(8 - position) } let group : CAAnimationGroup = CAAnimationGroup() group.animations = [posAnim, alphaAnim, blankAnim] group.beginTime = CACurrentMediaTime() + Double(beginTime) group.repeatCount = HUGE group.isRemovedOnCompletion = false group.delegate = self group.duration = Double(9 * moveTime!) square.add(group, forKey: "square-\(position)") } }
mit
2ec71696901a8cadc9f1dcd80224c7cf
28.473333
103
0.641031
4.041133
false
false
false
false
jkolb/ModestProposal
ModestProposal/NSURLComponents+HTTP.swift
2
2126
// Copyright (c) 2016 Justin Kolb - http://franticapparatus.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 Foundation public extension NSURLComponents { public var parameters: [String:String] { get { // Assumes query string does not have duplicate names! Last duplicate processed will overwrite any prior values. if let items = queryItems { var parameters = [String:String](minimumCapacity: items.count) for item in items { parameters[item.name] = item.value } return parameters } else { return [:] } } set { if newValue.count == 0 { queryItems = nil } else { var items = [NSURLQueryItem]() items.reserveCapacity(newValue.count) for (name, value) in newValue { items.append(NSURLQueryItem(name: name, value: value)) } queryItems = items } } } }
mit
a5877f0e47c2cf1f698a7aea20bdf3f5
41.52
124
0.636406
5.098321
false
false
false
false
RMizin/PigeonMessenger-project
FalconMessenger/Supporting Files/CoreManagers/ThemeManager.swift
1
15758
// // ThemeManager.swift // Pigeon-project // // Created by Roman Mizin on 8/2/17. // Copyright © 2017 Roman Mizin. All rights reserved. // import UIKit import SDWebImage import AVKit import ARSLineProgress extension NSNotification.Name { static let themeUpdated = NSNotification.Name(Bundle.main.bundleIdentifier! + ".themeUpdated") } struct ThemeManager { static func applyTheme(theme: Theme) { userDefaults.updateObject(for: userDefaults.selectedTheme, with: theme.rawValue) ARSLineProgressConfiguration.backgroundViewColor = ThemeManager.currentTheme().inputTextViewColor.withAlphaComponent(0.5).cgColor ARSLineProgressConfiguration.blurStyle = ThemeManager.currentTheme().arsLineProgressBlurStyle ARSLineProgressConfiguration.circleColorMiddle = ThemeManager.currentTheme().tintColor.cgColor ARSLineProgressConfiguration.circleColorInner = ThemeManager.currentTheme().tintColor.cgColor UITabBar.appearance().barStyle = theme.barStyle UINavigationBar.appearance().isTranslucent = false UINavigationBar.appearance().barStyle = theme.barStyle UINavigationBar.appearance().barTintColor = theme.barBackgroundColor if #available(iOS 13.0, *) { let coloredAppearance = UINavigationBarAppearance() coloredAppearance.configureWithOpaqueBackground() coloredAppearance.backgroundColor = ThemeManager.currentTheme().generalBackgroundColor coloredAppearance.titleTextAttributes = [.foregroundColor: ThemeManager.currentTheme().generalTitleColor] coloredAppearance.largeTitleTextAttributes = [.foregroundColor: ThemeManager.currentTheme().generalTitleColor] UINavigationBar.appearance().standardAppearance = coloredAppearance UINavigationBar.appearance().scrollEdgeAppearance = coloredAppearance UINavigationBar.appearance().compactAppearance = coloredAppearance } UITabBar.appearance().tintColor = theme.tabBarTintColor UITabBar.appearance().barTintColor = theme.barBackgroundColor UITableViewCell.appearance().selectionColor = ThemeManager.currentTheme().cellSelectionColor UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).defaultTextAttributes = [NSAttributedString.Key.foregroundColor: theme.generalTitleColor] UIView.appearance().tintColor = theme.tintColor UIView.appearance(whenContainedInInstancesOf: [INSPhotosViewController.self]).tintColor = .white UIView.appearance(whenContainedInInstancesOf: [UINavigationBar.self]).tintColor = theme.barTintColor NotificationCenter.default.post(name: .themeUpdated, object: nil) } static func currentTheme() -> Theme { if UserDefaults.standard.object(forKey: userDefaults.selectedTheme) == nil { return .Dark } if let storedTheme = userDefaults.currentIntObjectState(for: userDefaults.selectedTheme) { return Theme(rawValue: storedTheme)! } else { return .Default } } static func setNavigationBarAppearance(_ naviationBar: UINavigationBar) { if #available(iOS 13.0, *) { let coloredAppearance = UINavigationBarAppearance() coloredAppearance.configureWithOpaqueBackground() coloredAppearance.backgroundColor = ThemeManager.currentTheme().generalBackgroundColor coloredAppearance.titleTextAttributes = [.foregroundColor: ThemeManager.currentTheme().generalTitleColor] coloredAppearance.largeTitleTextAttributes = [.foregroundColor: ThemeManager.currentTheme().generalTitleColor] naviationBar.standardAppearance = coloredAppearance naviationBar.scrollEdgeAppearance = coloredAppearance naviationBar.compactAppearance = coloredAppearance } } } enum Theme: Int { case Default, Dark, LivingCoral var tintColor: UIColor { switch self { case .Default: return TintPalette.blue case .Dark: return TintPalette.blue case .LivingCoral: return TintPalette.livingCoral } } var generalBackgroundColor: UIColor { switch self { case .Default: return .white case .Dark: return .black case .LivingCoral: return .white } } var barTintColor: UIColor { switch self { case .Default: return tintColor case .Dark: return tintColor case .LivingCoral: return tintColor } } var tabBarTintColor: UIColor { switch self { case .Default: return tintColor case .Dark: return tintColor case .LivingCoral: return tintColor } } var unselectedButtonTintColor: UIColor { switch self { case .Default: return UIColor(red: 0.67, green: 0.67, blue: 0.67, alpha: 1.0) case .Dark: return UIColor(red: 0.67, green: 0.67, blue: 0.67, alpha: 1.0) case .LivingCoral: return TintPalette.livingCoralExtraLight } } var selectedButtonTintColor: UIColor { switch self { case .Default: return tintColor case .Dark: return tintColor case .LivingCoral: return tintColor } } var barBackgroundColor: UIColor { switch self { case .Default: return .white case .Dark: return .black case .LivingCoral: return .white } } var barTextColor: UIColor { switch self { case .Default: return UIColor(red: 0.67, green: 0.67, blue: 0.67, alpha: 1.0) case .Dark: return UIColor(red: 0.67, green: 0.67, blue: 0.67, alpha: 1.0) case .LivingCoral: return tintColor } } var controlButtonTintColor: UIColor { switch self { case .Default: return tintColor case .Dark: return tintColor case .LivingCoral: return tintColor } } var generalTitleColor: UIColor { switch self { case .Default: return UIColor.black case .Dark: return UIColor.white case .LivingCoral: return UIColor.black } } var chatLogTitleColor: UIColor { switch self { case .Default: return .black case .Dark: return .white case .LivingCoral: return .black } } var generalSubtitleColor: UIColor { switch self { case .Default: return UIColor(red: 0.67, green: 0.67, blue: 0.67, alpha: 1.0) case .Dark: return UIColor(red: 0.67, green: 0.67, blue: 0.67, alpha: 1.0) case .LivingCoral: return UIColor(red: 0.67, green: 0.67, blue: 0.67, alpha: 1.0) } } var cellSelectionColor: UIColor { switch self { case .Default: return UIColor(red: 0.95, green: 0.95, blue: 0.95, alpha: 1.0) //F1F1F1 case .Dark: return UIColor(red: 0.10, green: 0.10, blue: 0.10, alpha: 1.0) //191919 case .LivingCoral: return UIColor(red: 0.95, green: 0.95, blue: 0.95, alpha: 1.0) //F1F1F1 } } var inputTextViewColor: UIColor { switch self { case .Default: return UIColor(red: 0.95, green: 0.95, blue: 0.95, alpha: 1.0) case .Dark: return UIColor(red: 0.11, green: 0.11, blue: 0.11, alpha: 1.0) case .LivingCoral: return UIColor(red: 0.95, green: 0.95, blue: 0.95, alpha: 1.0) } } var supplementaryViewTextColor: UIColor { switch self { case .Default: return .gray case .Dark: return .lightGray case .LivingCoral: return .gray } } var sdWebImageActivityIndicator: SDWebImageActivityIndicator { switch self { case .Default: return SDWebImageActivityIndicator.gray case .Dark: return SDWebImageActivityIndicator.white case .LivingCoral: return SDWebImageActivityIndicator.gray } } var controlButtonColor: UIColor { switch self { case .Default: return UIColor(red: 0.94, green: 0.94, blue: 0.96, alpha: 1.0) case .Dark: return UIColor(red: 0.11, green: 0.11, blue: 0.11, alpha: 1.0) case .LivingCoral: return UIColor(red: 0.94, green: 0.94, blue: 0.96, alpha: 1.0) } } var controlButtonHighlightingColor: UIColor { switch self { case .Default: return UIColor(red: 0.85, green: 0.85, blue: 0.85, alpha: 1.0) //F1F1F1 case .Dark: return UIColor(red: 0.07, green: 0.07, blue: 0.07, alpha: 1.0) //191919 case .LivingCoral: return UIColor(red: 0.85, green: 0.85, blue: 0.85, alpha: 1.0) //F1F1F1 } } var muteRowActionBackgroundColor: UIColor { switch self { case .Default: return TintPalette.lightBlue case .Dark: return controlButtonHighlightingColor case .LivingCoral: return TintPalette.livingCoralLight } } var pinRowActionBackgroundColor: UIColor { switch self { case .Default: return TintPalette.blue case .Dark: return controlButtonColor case .LivingCoral: return TintPalette.livingCoral } } var searchBarColor: UIColor { switch self { case .Default: return UIColor(red: 0.99, green: 0.99, blue: 0.99, alpha: 0.5) case .Dark: return UIColor(red: 0.11, green: 0.11, blue: 0.11, alpha: 0.8) case .LivingCoral: return UIColor(red: 0.99, green: 0.99, blue: 0.99, alpha: 0.5) } } var mediaPickerControllerBackgroundColor: UIColor { switch self { case .Default: return UIColor(red: 209.0/255.0, green: 213.0/255.0, blue: 218.0/255.0, alpha: 1.0) case .Dark: return UIColor(red: 0.10, green: 0.10, blue: 0.10, alpha: 1.0) case .LivingCoral: return UIColor(red: 209.0/255.0, green: 213.0/255.0, blue: 218.0/255.0, alpha: 1.0) } } var scrollDownImage: UIImage { switch self { case .Default: return UIImage(named: "arrowDownBlack")! case .Dark: return UIImage(named: "arrowDownWhite")! case .LivingCoral: return UIImage(named: "arrowDownBlack")! } } var personalStorageImage: UIImage { switch self { case .Default: return UIImage(named: "PersonalStorage")! case .Dark: return UIImage(named: "PersonalStorage")! case .LivingCoral: return UIImage(named: "PersonalStorage")! } } var incomingBubble: UIImage { switch self { case .Default: return UIImage(named: "FMIncomingFull")!.stretchableImage(withLeftCapWidth: 23, topCapHeight: 16).withRenderingMode(.alwaysTemplate) case .Dark: return UIImage(named: "FMIncomingFull")!.stretchableImage(withLeftCapWidth: 23, topCapHeight: 16).withRenderingMode(.alwaysTemplate) case .LivingCoral: return UIImage(named: "FMIncomingFull")!.stretchableImage(withLeftCapWidth: 23, topCapHeight: 16).withRenderingMode(.alwaysTemplate) } } var incomingPartialBubble: UIImage { switch self { case .Default: return UIImage(named: "partialDefaultIncoming")!.stretchableImage(withLeftCapWidth: 23, topCapHeight: 16).withRenderingMode(.alwaysTemplate) case .Dark: return UIImage(named: "partialDefaultIncoming")!.stretchableImage(withLeftCapWidth: 23, topCapHeight: 16).withRenderingMode(.alwaysTemplate) case .LivingCoral: return UIImage(named: "partialDefaultIncoming")!.stretchableImage(withLeftCapWidth: 23, topCapHeight: 16).withRenderingMode(.alwaysTemplate) } } var outgoingBubble: UIImage { switch self { case .Default: return UIImage(named: "FMOutgoingFull")!.stretchableImage(withLeftCapWidth: 17, topCapHeight: 16).withRenderingMode(.alwaysTemplate) case .Dark: return UIImage(named: "FMOutgoingFull")!.stretchableImage(withLeftCapWidth: 17, topCapHeight: 16).withRenderingMode(.alwaysTemplate) case .LivingCoral: return UIImage(named: "FMOutgoingFull")!.stretchableImage(withLeftCapWidth: 17, topCapHeight: 16).withRenderingMode(.alwaysTemplate) } } var outgoingPartialBubble: UIImage { switch self { case .Default: return UIImage(named: "partialDefaultOutgoing")!.stretchableImage(withLeftCapWidth: 17, topCapHeight: 16).withRenderingMode(.alwaysTemplate) case .Dark: return UIImage(named: "partialDefaultOutgoing")!.stretchableImage(withLeftCapWidth: 17, topCapHeight: 16).withRenderingMode(.alwaysTemplate) case .LivingCoral: return UIImage(named: "partialDefaultOutgoing")!.stretchableImage(withLeftCapWidth: 17, topCapHeight: 16).withRenderingMode(.alwaysTemplate) } } var outgoingBubbleTintColor: UIColor { switch self { case .Default: return tintColor case .Dark: return UIColor(red: 0.15, green: 0.15, blue: 0.15, alpha: 1.0) case .LivingCoral: return tintColor } } var incomingBubbleTintColor: UIColor { switch self { case .Default: return UIColor(red: 0.95, green: 0.95, blue: 0.95, alpha: 1.0) case .Dark: return UIColor(red: 0.11, green: 0.11, blue: 0.11, alpha: 1.0) case .LivingCoral: return UIColor(red: 0.95, green: 0.95, blue: 0.95, alpha: 1.0) } } var selectedOutgoingBubbleTintColor: UIColor { switch self { case .Default: return UIColor(red: 0.00, green: 0.50, blue: 0.80, alpha: 1.0) case .Dark: return UIColor(red: 0.30, green: 0.30, blue: 0.30, alpha: 1.0) case .LivingCoral: return TintPalette.livingCoralExtraLight } } var selectedIncomingBubbleTintColor: UIColor { switch self { case .Default: return UIColor(red: 0.70, green: 0.70, blue: 0.70, alpha: 1.0) case .Dark: return UIColor(red: 0.20, green: 0.20, blue: 0.20, alpha: 1.0) case .LivingCoral: return UIColor(red: 0.70, green: 0.70, blue: 0.70, alpha: 1.0) } } var incomingBubbleTextColor: UIColor { switch self { case .Default: return .black case .Dark: return .white case .LivingCoral: return .black } } var outgoingBubbleTextColor: UIColor { switch self { case .Default: return .white case .Dark: return .white case .LivingCoral: return .white } } var authorNameTextColor: UIColor { switch self { case .Default: return tintColor case .Dark: return UIColor(red: 0.55, green: 0.77, blue: 1.0, alpha: 1.0) case .LivingCoral: return tintColor } } var outgoingProgressStrokeColor: UIColor { switch self { case .Default: return .white case .Dark: return .white case .LivingCoral: return .white } } var incomingProgressStrokeColor: UIColor { switch self { case .Default: return .black case .Dark: return .white case .LivingCoral: return .black } } var keyboardAppearance: UIKeyboardAppearance { switch self { case .Default: return .default case .Dark: return .dark case .LivingCoral: return .default } } var barStyle: UIBarStyle { switch self { case .Default: return .default case .Dark: return .black case .LivingCoral: return .default } } var statusBarStyle: UIStatusBarStyle { switch self { case .Default: return .default case .Dark: return .lightContent case .LivingCoral: return .default } } var scrollBarStyle: UIScrollView.IndicatorStyle { switch self { case .Default: return .default case .Dark: return .white case .LivingCoral: return .default } } var arsLineProgressBlurStyle: UIBlurEffect.Style { switch self { case .Default: return .light case .Dark: return .dark case .LivingCoral: return .light } } } struct TintPalette { static let blue = UIColor(red: 0.00, green: 0.55, blue: 1.00, alpha: 1.0) static let lightBlue = UIColor(red: 0.13, green: 0.61, blue: 1.00, alpha: 1.0) static let grey = UIColor(red: 0.15, green: 0.15, blue: 0.15, alpha: 1.0) static let red = UIColor.red static let livingCoral = UIColor(red: 0.98, green: 0.45, blue: 0.41, alpha: 1.0) static let livingCoralLight = UIColor(red: 0.99, green: 0.69, blue: 0.67, alpha: 1.0) static let livingCoralExtraLight = UIColor(red: 0.99, green: 0.81, blue: 0.80, alpha: 1.0) } struct FalconPalette { static let dismissRed = UIColor(red: 1.00, green: 0.23, blue: 0.19, alpha: 1.0) static let appStoreGrey = UIColor(red: 0.94, green: 0.94, blue: 0.96, alpha: 1.0) }
gpl-3.0
5a5d029c3e0c272fe566a1bb57cf8a7a
27.087344
162
0.690487
3.837555
false
false
false
false
argon/mas
MasKit/Network/NetworkManager.swift
1
1628
// // NetworkManager.swift // MasKit // // Created by Ben Chatelain on 1/5/19. // Copyright © 2019 mas-cli. All rights reserved. // import Foundation /// Network abstraction public class NetworkManager { enum NetworkError: Error { case timeout } private let session: NetworkSession /// Designated initializer /// /// - Parameter session: A networking session. public init(session: NetworkSession = URLSession.shared) { self.session = session } /// Loads data asynchronously. /// /// - Parameters: /// - url: URL to load data from. /// - completionHandler: Closure where result is delivered. func loadData(from url: URL, completionHandler: @escaping (NetworkResult) -> Void) { session.loadData(from: url) { (data: Data?, error: Error?) in let result: NetworkResult = data != nil ? .success(data!) : .failure(error!) completionHandler(result) } } /// Loads data synchronously. /// /// - Parameter url: URL to load data from. /// - Returns: Network result containing either Data or an Error. func loadDataSync(from url: URL) -> NetworkResult { var syncResult: NetworkResult? let semaphore = DispatchSemaphore(value: 0) loadData(from: url) { asyncResult in syncResult = asyncResult semaphore.signal() } _ = semaphore.wait(timeout: .distantFuture) guard let result = syncResult else { return .failure(NetworkError.timeout) } return result } }
mit
a670c65d0599f3de819c28dc2fdf79ae
26.116667
88
0.601721
4.688761
false
false
false
false
yuxiuyu/TrendBet
TrendBetting_0531换首页/Pods/Charts/Source/Charts/Charts/ChartViewBase.swift
4
35772
// // ChartViewBase.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // // Based on https://github.com/PhilJay/MPAndroidChart/commit/c42b880 import Foundation import CoreGraphics #if !os(OSX) import UIKit #endif @objc public protocol ChartViewDelegate { /// Called when a value has been selected inside the chart. /// - parameter entry: The selected Entry. /// - parameter highlight: The corresponding highlight object that contains information about the highlighted position such as dataSetIndex etc. @objc optional func chartValueSelected(_ chartView: ChartViewBase, entry: ChartDataEntry, highlight: Highlight) // Called when nothing has been selected or an "un-select" has been made. @objc optional func chartValueNothingSelected(_ chartView: ChartViewBase) // Callbacks when the chart is scaled / zoomed via pinch zoom gesture. @objc optional func chartScaled(_ chartView: ChartViewBase, scaleX: CGFloat, scaleY: CGFloat) // Callbacks when the chart is moved / translated via drag gesture. @objc optional func chartTranslated(_ chartView: ChartViewBase, dX: CGFloat, dY: CGFloat) } open class ChartViewBase: NSUIView, ChartDataProvider, AnimatorDelegate { // MARK: - Properties /// - returns: The object representing all x-labels, this method can be used to /// acquire the XAxis object and modify it (e.g. change the position of the /// labels) @objc open var xAxis: XAxis { return _xAxis } /// The default IValueFormatter that has been determined by the chart considering the provided minimum and maximum values. internal var _defaultValueFormatter: IValueFormatter? = DefaultValueFormatter(decimals: 0) /// object that holds all data that was originally set for the chart, before it was modified or any filtering algorithms had been applied internal var _data: ChartData? /// Flag that indicates if highlighting per tap (touch) is enabled private var _highlightPerTapEnabled = true /// If set to true, chart continues to scroll after touch up @objc open var dragDecelerationEnabled = true /// Deceleration friction coefficient in [0 ; 1] interval, higher values indicate that speed will decrease slowly, for example if it set to 0, it will stop immediately. /// 1 is an invalid value, and will be converted to 0.999 automatically. private var _dragDecelerationFrictionCoef: CGFloat = 0.9 /// if true, units are drawn next to the values in the chart internal var _drawUnitInChart = false /// The object representing the labels on the x-axis internal var _xAxis: XAxis! /// The `Description` object of the chart. /// This should have been called just "description", but @objc open var chartDescription: Description? /// The legend object containing all data associated with the legend internal var _legend: Legend! /// delegate to receive chart events @objc open weak var delegate: ChartViewDelegate? /// text that is displayed when the chart is empty @objc open var noDataText = "No chart data available." /// Font to be used for the no data text. @objc open var noDataFont: NSUIFont! = NSUIFont(name: "HelveticaNeue", size: 12.0) /// color of the no data text @objc open var noDataTextColor: NSUIColor = NSUIColor.black internal var _legendRenderer: LegendRenderer! /// object responsible for rendering the data @objc open var renderer: DataRenderer? @objc open var highlighter: IHighlighter? /// object that manages the bounds and drawing constraints of the chart internal var _viewPortHandler: ViewPortHandler! /// object responsible for animations internal var _animator: Animator! /// flag that indicates if offsets calculation has already been done or not private var _offsetsCalculated = false /// array of Highlight objects that reference the highlighted slices in the chart internal var _indicesToHighlight = [Highlight]() /// `true` if drawing the marker is enabled when tapping on values /// (use the `marker` property to specify a marker) @objc open var drawMarkers = true /// - returns: `true` if drawing the marker is enabled when tapping on values /// (use the `marker` property to specify a marker) @objc open var isDrawMarkersEnabled: Bool { return drawMarkers } /// The marker that is displayed when a value is clicked on the chart @objc open var marker: IMarker? private var _interceptTouchEvents = false /// An extra offset to be appended to the viewport's top @objc open var extraTopOffset: CGFloat = 0.0 /// An extra offset to be appended to the viewport's right @objc open var extraRightOffset: CGFloat = 0.0 /// An extra offset to be appended to the viewport's bottom @objc open var extraBottomOffset: CGFloat = 0.0 /// An extra offset to be appended to the viewport's left @objc open var extraLeftOffset: CGFloat = 0.0 @objc open func setExtraOffsets(left: CGFloat, top: CGFloat, right: CGFloat, bottom: CGFloat) { extraLeftOffset = left extraTopOffset = top extraRightOffset = right extraBottomOffset = bottom } // MARK: - Initializers public override init(frame: CGRect) { super.init(frame: frame) initialize() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initialize() } deinit { self.removeObserver(self, forKeyPath: "bounds") self.removeObserver(self, forKeyPath: "frame") } internal func initialize() { #if os(iOS) self.backgroundColor = NSUIColor.clear #endif _animator = Animator() _animator.delegate = self _viewPortHandler = ViewPortHandler(width: bounds.size.width, height: bounds.size.height) chartDescription = Description() _legend = Legend() _legendRenderer = LegendRenderer(viewPortHandler: _viewPortHandler, legend: _legend) _xAxis = XAxis() self.addObserver(self, forKeyPath: "bounds", options: .new, context: nil) self.addObserver(self, forKeyPath: "frame", options: .new, context: nil) } // MARK: - ChartViewBase /// The data for the chart open var data: ChartData? { get { return _data } set { _data = newValue _offsetsCalculated = false guard let _data = _data else { return } // calculate how many digits are needed setupDefaultFormatter(min: _data.getYMin(), max: _data.getYMax()) for set in _data.dataSets { if set.needsFormatter || set.valueFormatter === _defaultValueFormatter { set.valueFormatter = _defaultValueFormatter } } // let the chart know there is new data notifyDataSetChanged() } } /// Clears the chart from all data (sets it to null) and refreshes it (by calling setNeedsDisplay()). @objc open func clear() { _data = nil _offsetsCalculated = false _indicesToHighlight.removeAll() lastHighlighted = nil setNeedsDisplay() } /// Removes all DataSets (and thereby Entries) from the chart. Does not set the data object to nil. Also refreshes the chart by calling setNeedsDisplay(). @objc open func clearValues() { _data?.clearValues() setNeedsDisplay() } /// - returns: `true` if the chart is empty (meaning it's data object is either null or contains no entries). @objc open func isEmpty() -> Bool { guard let data = _data else { return true } if data.entryCount <= 0 { return true } else { return false } } /// Lets the chart know its underlying data has changed and should perform all necessary recalculations. /// It is crucial that this method is called everytime data is changed dynamically. Not calling this method can lead to crashes or unexpected behaviour. @objc open func notifyDataSetChanged() { fatalError("notifyDataSetChanged() cannot be called on ChartViewBase") } /// Calculates the offsets of the chart to the border depending on the position of an eventual legend or depending on the length of the y-axis and x-axis labels and their position internal func calculateOffsets() { fatalError("calculateOffsets() cannot be called on ChartViewBase") } /// calcualtes the y-min and y-max value and the y-delta and x-delta value internal func calcMinMax() { fatalError("calcMinMax() cannot be called on ChartViewBase") } /// calculates the required number of digits for the values that might be drawn in the chart (if enabled), and creates the default value formatter internal func setupDefaultFormatter(min: Double, max: Double) { // check if a custom formatter is set or not var reference = Double(0.0) if let data = _data , data.entryCount >= 2 { reference = fabs(max - min) } else { let absMin = fabs(min) let absMax = fabs(max) reference = absMin > absMax ? absMin : absMax } if _defaultValueFormatter is DefaultValueFormatter { // setup the formatter with a new number of digits let digits = reference.decimalPlaces (_defaultValueFormatter as? DefaultValueFormatter)?.decimals = digits } } open override func draw(_ rect: CGRect) { let optionalContext = NSUIGraphicsGetCurrentContext() guard let context = optionalContext else { return } let frame = self.bounds if _data === nil && noDataText.count > 0 { context.saveGState() defer { context.restoreGState() } ChartUtils.drawMultilineText( context: context, text: noDataText, point: CGPoint(x: frame.width / 2.0, y: frame.height / 2.0), attributes: [NSAttributedStringKey.font: noDataFont, NSAttributedStringKey.foregroundColor: noDataTextColor], constrainedToSize: self.bounds.size, anchor: CGPoint(x: 0.5, y: 0.5), angleRadians: 0.0) return } if !_offsetsCalculated { calculateOffsets() _offsetsCalculated = true } } /// Draws the description text in the bottom right corner of the chart (per default) internal func drawDescription(context: CGContext) { // check if description should be drawn guard let description = chartDescription, description.isEnabled, let descriptionText = description.text, descriptionText.count > 0 else { return } let position = description.position ?? CGPoint(x: bounds.width - _viewPortHandler.offsetRight - description.xOffset, y: bounds.height - _viewPortHandler.offsetBottom - description.yOffset - description.font.lineHeight) var attrs = [NSAttributedStringKey : Any]() attrs[NSAttributedStringKey.font] = description.font attrs[NSAttributedStringKey.foregroundColor] = description.textColor ChartUtils.drawText( context: context, text: descriptionText, point: position, align: description.textAlign, attributes: attrs) } // MARK: - Highlighting /// - returns: The array of currently highlighted values. This might an empty if nothing is highlighted. @objc open var highlighted: [Highlight] { return _indicesToHighlight } /// Set this to false to prevent values from being highlighted by tap gesture. /// Values can still be highlighted via drag or programmatically. /// **default**: true @objc open var highlightPerTapEnabled: Bool { get { return _highlightPerTapEnabled } set { _highlightPerTapEnabled = newValue } } /// - returns: `true` if values can be highlighted via tap gesture, `false` ifnot. @objc open var isHighLightPerTapEnabled: Bool { return highlightPerTapEnabled } /// Checks if the highlight array is null, has a length of zero or if the first object is null. /// - returns: `true` if there are values to highlight, `false` ifthere are no values to highlight. @objc open func valuesToHighlight() -> Bool { return _indicesToHighlight.count > 0 } /// Highlights the values at the given indices in the given DataSets. Provide /// null or an empty array to undo all highlighting. /// This should be used to programmatically highlight values. /// This method *will not* call the delegate. @objc open func highlightValues(_ highs: [Highlight]?) { // set the indices to highlight _indicesToHighlight = highs ?? [Highlight]() if _indicesToHighlight.isEmpty { self.lastHighlighted = nil } else { self.lastHighlighted = _indicesToHighlight[0] } // redraw the chart setNeedsDisplay() } /// Highlights any y-value at the given x-value in the given DataSet. /// Provide -1 as the dataSetIndex to undo all highlighting. /// This method will call the delegate. /// - parameter x: The x-value to highlight /// - parameter dataSetIndex: The dataset index to search in @objc open func highlightValue(x: Double, dataSetIndex: Int) { highlightValue(x: x, dataSetIndex: dataSetIndex, callDelegate: true) } /// Highlights the value at the given x-value and y-value in the given DataSet. /// Provide -1 as the dataSetIndex to undo all highlighting. /// This method will call the delegate. /// - parameter x: The x-value to highlight /// - parameter y: The y-value to highlight. Supply `NaN` for "any" /// - parameter dataSetIndex: The dataset index to search in @objc open func highlightValue(x: Double, y: Double, dataSetIndex: Int) { highlightValue(x: x, y: y, dataSetIndex: dataSetIndex, callDelegate: true) } /// Highlights any y-value at the given x-value in the given DataSet. /// Provide -1 as the dataSetIndex to undo all highlighting. /// - parameter x: The x-value to highlight /// - parameter dataSetIndex: The dataset index to search in /// - parameter callDelegate: Should the delegate be called for this change @objc open func highlightValue(x: Double, dataSetIndex: Int, callDelegate: Bool) { highlightValue(x: x, y: Double.nan, dataSetIndex: dataSetIndex, callDelegate: callDelegate) } /// Highlights the value at the given x-value and y-value in the given DataSet. /// Provide -1 as the dataSetIndex to undo all highlighting. /// - parameter x: The x-value to highlight /// - parameter y: The y-value to highlight. Supply `NaN` for "any" /// - parameter dataSetIndex: The dataset index to search in /// - parameter callDelegate: Should the delegate be called for this change @objc open func highlightValue(x: Double, y: Double, dataSetIndex: Int, callDelegate: Bool) { guard let data = _data else { Swift.print("Value not highlighted because data is nil") return } if dataSetIndex < 0 || dataSetIndex >= data.dataSetCount { highlightValue(nil, callDelegate: callDelegate) } else { highlightValue(Highlight(x: x, y: y, dataSetIndex: dataSetIndex), callDelegate: callDelegate) } } /// Highlights the values represented by the provided Highlight object /// This method *will not* call the delegate. /// - parameter highlight: contains information about which entry should be highlighted @objc open func highlightValue(_ highlight: Highlight?) { highlightValue(highlight, callDelegate: false) } /// Highlights the value selected by touch gesture. @objc open func highlightValue(_ highlight: Highlight?, callDelegate: Bool) { var entry: ChartDataEntry? var h = highlight if h == nil { _indicesToHighlight.removeAll(keepingCapacity: false) } else { // set the indices to highlight entry = _data?.entryForHighlight(h!) if entry == nil { h = nil _indicesToHighlight.removeAll(keepingCapacity: false) } else { _indicesToHighlight = [h!] } } if callDelegate, let delegate = delegate { if let h = h { // notify the listener delegate.chartValueSelected?(self, entry: entry!, highlight: h) } else { delegate.chartValueNothingSelected?(self) } } // redraw the chart setNeedsDisplay() } /// - returns: The Highlight object (contains x-index and DataSet index) of the /// selected value at the given touch point inside the Line-, Scatter-, or /// CandleStick-Chart. @objc open func getHighlightByTouchPoint(_ pt: CGPoint) -> Highlight? { if _data === nil { Swift.print("Can't select by touch. No data set.") return nil } return self.highlighter?.getHighlight(x: pt.x, y: pt.y) } /// The last value that was highlighted via touch. @objc open var lastHighlighted: Highlight? // MARK: - Markers /// draws all MarkerViews on the highlighted positions internal func drawMarkers(context: CGContext) { // if there is no marker view or drawing marker is disabled guard let marker = marker , isDrawMarkersEnabled && valuesToHighlight() else { return } for i in 0 ..< _indicesToHighlight.count { let highlight = _indicesToHighlight[i] guard let set = data?.getDataSetByIndex(highlight.dataSetIndex), let e = _data?.entryForHighlight(highlight) else { continue } let entryIndex = set.entryIndex(entry: e) if entryIndex > Int(Double(set.entryCount) * _animator.phaseX) { continue } let pos = getMarkerPosition(highlight: highlight) // check bounds if !_viewPortHandler.isInBounds(x: pos.x, y: pos.y) { continue } // callbacks to update the content marker.refreshContent(entry: e, highlight: highlight) // draw the marker marker.draw(context: context, point: pos) } } /// - returns: The actual position in pixels of the MarkerView for the given Entry in the given DataSet. @objc open func getMarkerPosition(highlight: Highlight) -> CGPoint { return CGPoint(x: highlight.drawX, y: highlight.drawY) } // MARK: - Animation /// - returns: The animator responsible for animating chart values. @objc open var chartAnimator: Animator! { return _animator } /// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time. /// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart. /// - parameter xAxisDuration: duration for animating the x axis /// - parameter yAxisDuration: duration for animating the y axis /// - parameter easingX: an easing function for the animation on the x axis /// - parameter easingY: an easing function for the animation on the y axis @objc open func animate(xAxisDuration: TimeInterval, yAxisDuration: TimeInterval, easingX: ChartEasingFunctionBlock?, easingY: ChartEasingFunctionBlock?) { _animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easingX: easingX, easingY: easingY) } /// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time. /// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart. /// - parameter xAxisDuration: duration for animating the x axis /// - parameter yAxisDuration: duration for animating the y axis /// - parameter easingOptionX: the easing function for the animation on the x axis /// - parameter easingOptionY: the easing function for the animation on the y axis @objc open func animate(xAxisDuration: TimeInterval, yAxisDuration: TimeInterval, easingOptionX: ChartEasingOption, easingOptionY: ChartEasingOption) { _animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easingOptionX: easingOptionX, easingOptionY: easingOptionY) } /// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time. /// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart. /// - parameter xAxisDuration: duration for animating the x axis /// - parameter yAxisDuration: duration for animating the y axis /// - parameter easing: an easing function for the animation @objc open func animate(xAxisDuration: TimeInterval, yAxisDuration: TimeInterval, easing: ChartEasingFunctionBlock?) { _animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easing: easing) } /// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time. /// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart. /// - parameter xAxisDuration: duration for animating the x axis /// - parameter yAxisDuration: duration for animating the y axis /// - parameter easingOption: the easing function for the animation @objc open func animate(xAxisDuration: TimeInterval, yAxisDuration: TimeInterval, easingOption: ChartEasingOption) { _animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration, easingOption: easingOption) } /// Animates the drawing / rendering of the chart on both x- and y-axis with the specified animation time. /// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart. /// - parameter xAxisDuration: duration for animating the x axis /// - parameter yAxisDuration: duration for animating the y axis @objc open func animate(xAxisDuration: TimeInterval, yAxisDuration: TimeInterval) { _animator.animate(xAxisDuration: xAxisDuration, yAxisDuration: yAxisDuration) } /// Animates the drawing / rendering of the chart the x-axis with the specified animation time. /// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart. /// - parameter xAxisDuration: duration for animating the x axis /// - parameter easing: an easing function for the animation @objc open func animate(xAxisDuration: TimeInterval, easing: ChartEasingFunctionBlock?) { _animator.animate(xAxisDuration: xAxisDuration, easing: easing) } /// Animates the drawing / rendering of the chart the x-axis with the specified animation time. /// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart. /// - parameter xAxisDuration: duration for animating the x axis /// - parameter easingOption: the easing function for the animation @objc open func animate(xAxisDuration: TimeInterval, easingOption: ChartEasingOption) { _animator.animate(xAxisDuration: xAxisDuration, easingOption: easingOption) } /// Animates the drawing / rendering of the chart the x-axis with the specified animation time. /// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart. /// - parameter xAxisDuration: duration for animating the x axis @objc open func animate(xAxisDuration: TimeInterval) { _animator.animate(xAxisDuration: xAxisDuration) } /// Animates the drawing / rendering of the chart the y-axis with the specified animation time. /// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart. /// - parameter yAxisDuration: duration for animating the y axis /// - parameter easing: an easing function for the animation @objc open func animate(yAxisDuration: TimeInterval, easing: ChartEasingFunctionBlock?) { _animator.animate(yAxisDuration: yAxisDuration, easing: easing) } /// Animates the drawing / rendering of the chart the y-axis with the specified animation time. /// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart. /// - parameter yAxisDuration: duration for animating the y axis /// - parameter easingOption: the easing function for the animation @objc open func animate(yAxisDuration: TimeInterval, easingOption: ChartEasingOption) { _animator.animate(yAxisDuration: yAxisDuration, easingOption: easingOption) } /// Animates the drawing / rendering of the chart the y-axis with the specified animation time. /// If `animate(...)` is called, no further calling of `invalidate()` is necessary to refresh the chart. /// - parameter yAxisDuration: duration for animating the y axis @objc open func animate(yAxisDuration: TimeInterval) { _animator.animate(yAxisDuration: yAxisDuration) } // MARK: - Accessors /// - returns: The current y-max value across all DataSets open var chartYMax: Double { return _data?.yMax ?? 0.0 } /// - returns: The current y-min value across all DataSets open var chartYMin: Double { return _data?.yMin ?? 0.0 } open var chartXMax: Double { return _xAxis._axisMaximum } open var chartXMin: Double { return _xAxis._axisMinimum } open var xRange: Double { return _xAxis.axisRange } /// * /// - note: (Equivalent of getCenter() in MPAndroidChart, as center is already a standard in iOS that returns the center point relative to superview, and MPAndroidChart returns relative to self)* /// - returns: The center point of the chart (the whole View) in pixels. @objc open var midPoint: CGPoint { let bounds = self.bounds return CGPoint(x: bounds.origin.x + bounds.size.width / 2.0, y: bounds.origin.y + bounds.size.height / 2.0) } /// - returns: The center of the chart taking offsets under consideration. (returns the center of the content rectangle) open var centerOffsets: CGPoint { return _viewPortHandler.contentCenter } /// - returns: The Legend object of the chart. This method can be used to get an instance of the legend in order to customize the automatically generated Legend. @objc open var legend: Legend { return _legend } /// - returns: The renderer object responsible for rendering / drawing the Legend. @objc open var legendRenderer: LegendRenderer! { return _legendRenderer } /// - returns: The rectangle that defines the borders of the chart-value surface (into which the actual values are drawn). @objc open var contentRect: CGRect { return _viewPortHandler.contentRect } /// - returns: The ViewPortHandler of the chart that is responsible for the /// content area of the chart and its offsets and dimensions. @objc open var viewPortHandler: ViewPortHandler! { return _viewPortHandler } /// - returns: The bitmap that represents the chart. @objc open func getChartImage(transparent: Bool) -> NSUIImage? { NSUIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque || !transparent, NSUIMainScreen()?.nsuiScale ?? 1.0) guard let context = NSUIGraphicsGetCurrentContext() else { return nil } let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: bounds.size) if isOpaque || !transparent { // Background color may be partially transparent, we must fill with white if we want to output an opaque image context.setFillColor(NSUIColor.white.cgColor) context.fill(rect) if let backgroundColor = self.backgroundColor { context.setFillColor(backgroundColor.cgColor) context.fill(rect) } } nsuiLayer?.render(in: context) let image = NSUIGraphicsGetImageFromCurrentImageContext() NSUIGraphicsEndImageContext() return image } public enum ImageFormat { case jpeg case png } /// Saves the current chart state with the given name to the given path on /// the sdcard leaving the path empty "" will put the saved file directly on /// the SD card chart is saved as a PNG image, example: /// saveToPath("myfilename", "foldername1/foldername2") /// /// - parameter to: path to the image to save /// - parameter format: the format to save /// - parameter compressionQuality: compression quality for lossless formats (JPEG) /// /// - returns: `true` if the image was saved successfully open func save(to path: String, format: ImageFormat, compressionQuality: Double) -> Bool { guard let image = getChartImage(transparent: format != .jpeg) else { return false } let imageData: Data? switch (format) { case .png: imageData = NSUIImagePNGRepresentation(image) case .jpeg: imageData = NSUIImageJPEGRepresentation(image, CGFloat(compressionQuality)) } guard let data = imageData else { return false } do { try data.write(to: URL(fileURLWithPath: path), options: .atomic) } catch { return false } return true } internal var _viewportJobs = [ViewPortJob]() open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if keyPath == "bounds" || keyPath == "frame" { let bounds = self.bounds if (_viewPortHandler !== nil && (bounds.size.width != _viewPortHandler.chartWidth || bounds.size.height != _viewPortHandler.chartHeight)) { _viewPortHandler.setChartDimens(width: bounds.size.width, height: bounds.size.height) // This may cause the chart view to mutate properties affecting the view port -- lets do this // before we try to run any pending jobs on the view port itself notifyDataSetChanged() // Finish any pending viewport changes while (!_viewportJobs.isEmpty) { let job = _viewportJobs.remove(at: 0) job.doJob() } } } } @objc open func removeViewportJob(_ job: ViewPortJob) { if let index = _viewportJobs.index(where: { $0 === job }) { _viewportJobs.remove(at: index) } } @objc open func clearAllViewportJobs() { _viewportJobs.removeAll(keepingCapacity: false) } @objc open func addViewportJob(_ job: ViewPortJob) { if _viewPortHandler.hasChartDimens { job.doJob() } else { _viewportJobs.append(job) } } /// **default**: true /// - returns: `true` if chart continues to scroll after touch up, `false` ifnot. @objc open var isDragDecelerationEnabled: Bool { return dragDecelerationEnabled } /// Deceleration friction coefficient in [0 ; 1] interval, higher values indicate that speed will decrease slowly, for example if it set to 0, it will stop immediately. /// 1 is an invalid value, and will be converted to 0.999 automatically. /// /// **default**: true @objc open var dragDecelerationFrictionCoef: CGFloat { get { return _dragDecelerationFrictionCoef } set { var val = newValue if val < 0.0 { val = 0.0 } if val >= 1.0 { val = 0.999 } _dragDecelerationFrictionCoef = val } } /// The maximum distance in screen pixels away from an entry causing it to highlight. /// **default**: 500.0 open var maxHighlightDistance: CGFloat = 500.0 /// the number of maximum visible drawn values on the chart only active when `drawValuesEnabled` is enabled open var maxVisibleCount: Int { return Int(INT_MAX) } // MARK: - AnimatorDelegate open func animatorUpdated(_ chartAnimator: Animator) { setNeedsDisplay() } open func animatorStopped(_ chartAnimator: Animator) { } // MARK: - Touches open override func nsuiTouchesBegan(_ touches: Set<NSUITouch>, withEvent event: NSUIEvent?) { if !_interceptTouchEvents { super.nsuiTouchesBegan(touches, withEvent: event) } } open override func nsuiTouchesMoved(_ touches: Set<NSUITouch>, withEvent event: NSUIEvent?) { if !_interceptTouchEvents { super.nsuiTouchesMoved(touches, withEvent: event) } } open override func nsuiTouchesEnded(_ touches: Set<NSUITouch>, withEvent event: NSUIEvent?) { if !_interceptTouchEvents { super.nsuiTouchesEnded(touches, withEvent: event) } } open override func nsuiTouchesCancelled(_ touches: Set<NSUITouch>?, withEvent event: NSUIEvent?) { if !_interceptTouchEvents { super.nsuiTouchesCancelled(touches, withEvent: event) } } }
apache-2.0
20e3c9b9da4fa374b1552fb6d36a7b76
35.614125
199
0.625042
5.257496
false
false
false
false
icapps/ios-air-rivet
Example/Pods/Stella/Sources/Defaults/Defaults.swift
3
4693
// // DefaultKeys.swift // Pods // // Created by Jelle Vandebeeck on 08/06/16. // // /// `Defaults` is a wrapper for the UserDefaults standard defaults instance. public let Defaults = UserDefaults.standard /// `DefaultsKeys` is a wrapper we can extend to define all the different default keys available. /// /// ``` /// extension DefaultsKeys { /// static let string = DefaultsKey<String?>("the string defaults key") /// } /// ``` open class DefaultsKeys {} /// The `DefaulesKey` defines the key and the value type for a certain user default value. open class DefaultsKey<ValueType>: DefaultsKeys { fileprivate let key: String /// Initialize the key in your `DefaultsKeys` extension. /// /// ``` /// static let string = DefaultsKey<String?>("the string defaults key") /// ``` public init(_ key: String) { self.key = key } } public extension UserDefaults { /// Get the defaults String value for the given `DefaultsKey`. The preferred way to do this is to pass the static key variable defined in the `DefaultsKeys` extension. /// /// ``` /// static let string = DefaultsKey<String?>("the string defaults key") /// ``` public subscript(key: DefaultsKey<String?>) -> String? { get { return string(forKey: key.key) } set { set(newValue, forKey: key.key) } } /// Get the defaults Int value for the given `DefaultsKey`. The preferred way to do this is to pass the static key variable defined in the `DefaultsKeys` extension. /// /// ``` /// static let integer = DefaultsKey<Int?>("the integer defaults key") /// ``` public subscript(key: DefaultsKey<Int?>) -> Int? { get { return integer(forKey: key.key) } set { if let newValue = newValue { set(newValue, forKey: key.key) } else { removeObject(forKey: key.key) } } } /// Get the defaults Float value for the given `DefaultsKey`. The preferred way to do this is to pass the static key variable defined in the `DefaultsKeys` extension. /// /// ``` /// static let float = DefaultsKey<Float?>("the float defaults key") /// ``` public subscript(key: DefaultsKey<Float?>) -> Float? { get { return float(forKey: key.key) } set { if let newValue = newValue { set(newValue, forKey: key.key) } else { removeObject(forKey: key.key) } } } /// Get the defaults Double value for the given `DefaultsKey`. The preferred way to do this is to pass the static key variable defined in the `DefaultsKeys` extension. /// /// ``` /// static let double = DefaultsKey<Double?>("the double defaults key") /// ``` public subscript(key: DefaultsKey<Double?>) -> Double? { get { return double(forKey: key.key) } set { if let newValue = newValue { set(newValue, forKey: key.key) } else { removeObject(forKey: key.key) } } } /// Get the defaults Bool value for the given `DefaultsKey`. The preferred way to do this is to pass the static key variable defined in the `DefaultsKeys` extension. /// /// ``` /// static let boolean = DefaultsKey<Bool?>("the boolean defaults key") /// ``` public subscript(key: DefaultsKey<Bool?>) -> Bool { get { return bool(forKey: key.key) } set { set(newValue, forKey: key.key) } } /// Get the defaults NSDate value for the given `DefaultsKey`. The preferred way to do this is to pass the static key variable defined in the `DefaultsKeys` extension. /// /// ``` /// static let date = DefaultsKey<NSDate?>("the date defaults key") /// ``` public subscript(key: DefaultsKey<Date?>) -> Date? { get { return object(forKey: key.key) as? Date } set { set(newValue, forKey: key.key) } } /// Get the defaults [String] value for the given `DefaultsKey`. The preferred way to do this is to pass the static key variable defined in the `DefaultsKeys` extension. /// /// ``` /// static let strings = DefaultsKey<[String]?>("the strings defaults key") /// ``` public subscript(key: DefaultsKey<[String]?>) -> [String]? { get { return object(forKey: key.key) as? [String] } set { set(newValue, forKey: key.key) } } }
mit
1ac678971320a9a4e78c968e8685f888
31.143836
173
0.569572
4.60098
false
false
false
false
DiegoSan1895/Smartisan-Notes
Smartisan-Notes/UIButton+Notes.swift
1
1438
// // UIButton+Notes.swift // Smartisan-Notes // // Created by DiegoSan on 3/17/16. // Copyright © 2016 DiegoSan. All rights reserved. // import UIKit /* extension UIButton { class func xxx_swizzleSendAction() { struct xxx_swizzleToken { static var onceToken : dispatch_once_t = 0 } dispatch_once(&xxx_swizzleToken.onceToken) { let cls: AnyClass! = UIButton.self let originalSelector = Selector("sendAction:to:forEvent:") let swizzledSelector = Selector("xxx_sendAction:to:forEvent:") let originalMethod = class_getInstanceMethod(cls, originalSelector) let swizzledMethod = class_getInstanceMethod(cls, swizzledSelector) method_exchangeImplementations(originalMethod, swizzledMethod) } } public func xxx_sendAction(action: Selector, to target: AnyObject?, forEvent event: UIEvent?) { struct xxx_buttonTapCounter { static var count: Int = 0 } xxx_buttonTapCounter.count += 1 print(xxx_buttonTapCounter.count) xxx_sendAction(action, to: target, forEvent: event) } } extension UIButton { override public class func initialize() { if self != UIButton.self { return } UIButton.xxx_swizzleSendAction() } } */
mit
7080e92da6ede9f1b93d024e8c083a99
24.660714
74
0.590814
4.921233
false
false
false
false
takebayashi/http4swift
Sources/HTTPResponseWriter.swift
1
2654
/* The MIT License (MIT) Copyright (c) 2015 Shun Takebayashi 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 Nest #if os(OSX) import Darwin #elseif os(Linux) import Glibc #endif enum WriterError: ErrorProtocol { case GenericError(error: Int32) } public class HTTPResponseWriter { let socket: Int32 init(socket: Int32) { self.socket = socket } public func write(bytes: UnsafePointer<Int8>, length: Int? = nil) throws { #if os(Linux) let flags = Int32(MSG_NOSIGNAL) #else let flags = Int32(0) #endif var rest = length ?? Int(strlen(bytes)) while rest > 0 { let sent = send(socket, bytes, rest, flags) if sent < 0 { throw WriterError.GenericError(error: errno) } rest -= sent } } public func write(response: ResponseType) throws { try write("HTTP/1.0 \(response.statusLine)\r\n") var lengthWrote = false for header in response.headers { try write("\(header.0): \(header.1)\r\n") if header.0 == "Content-Length" { lengthWrote = true } } var body = [UInt8]() if var payload = response.body { while let chunk = payload.next() { body.append(contentsOf: chunk) } } if !lengthWrote { try write("Content-Length: \(body.count)\r\n") } try write("\r\n") try body.map({ return Int8($0) }).withUnsafeBufferPointer { buffer in try self.write(buffer.baseAddress, length: buffer.count) } } }
mit
24c85944079bf09071a60d84ff4061fa
29.505747
79
0.643557
4.294498
false
false
false
false
ColinConduff/BlocFit
BlocFit/Main Components/MainViewC.swift
1
11372
// // MainViewC.swift // BlocFit // // Created by Colin Conduff on 10/1/16. // Copyright © 2016 Colin Conduff. All rights reserved. // import UIKit import CoreData import CoreLocation import MultipeerConnectivity import GameKit /** Used by the sideMenu to notify the MainViewC that the user would like to segue to an auxiliary view. */ internal protocol SegueCoordinationDelegate: class { func transition(withSegueIdentifier identifier: String) } /** Used by the topMenu to notify the MainViewC that the user would like to either open the sideMenu or segue to the current bloc table view or the multipeer browser view. */ internal protocol TopMenuDelegate: class { func toggleSideMenu() func segueToCurrentBlocTable() func presentMCBrowserAndStartMCAssistant() } /** Used by the MultipeerManager to notify the MainViewC that the user has connected with a nearby peer. */ internal protocol MultipeerViewHandlerProtocol: class { func addToCurrentBloc(blocMember: BlocMember) func blocMembersContains(blocMember: BlocMember) -> Bool } /** Used by the Run History Table to notify the MainViewC that the user would like to display a past run path on the map and its values on the dashboard. */ internal protocol LoadRunDelegate: class { func tellMapToLoadRun(run: Run) } /** Used by the MapController to request the current bloc members from the MainViewC. */ internal protocol RequestMainDataDelegate: class { func getCurrentBlocMembers() -> [BlocMember] } /** Used by the GameKitManager to request that the MainViewC present GameKit-related view controller. */ internal protocol GameViewPresenterDelegate: class { func presentGameVC(_ viewController: UIViewController) } /** The initial view controller for the application. The MainViewC is responsible for controlling most of the communication and navigation between child view controllers. It also controls the opening and closing of the side menu view. */ final class MainViewC: UIViewController, LoadRunDelegate, RequestMainDataDelegate, SegueCoordinationDelegate, TopMenuDelegate, MultipeerViewHandlerProtocol, GameViewPresenterDelegate { // MARK: - Properties private weak var multipeerManagerDelegate: MultipeerManagerDelegate! private weak var dashboardUpdateDelegate: DashboardControllerProtocol! private weak var mapNotificationDelegate: MapNotificationDelegate! private weak var gameKitManagerDelegate: GameKitManagerDelegate! // used to set the dashboard's delegate in the prepare for segue method // need to find a way to do so without keeping this reference private weak var mapViewC: MapViewC? @IBOutlet weak var sideMenuContainerView: UIView! @IBOutlet weak var sideMenuContainerWidthConstraint: NSLayoutConstraint! // Created when the side menu is openned // Destroyed when the side menu is closed private weak var dismissSideMenuView: DismissSideMenuView? // Can be edited by CurrentBlocTableViewC // need a better way to synchronize blocMembers array across multiple classes private var blocMembers = [BlocMember]() { didSet { // Notify map and dashboard of change mapNotificationDelegate.blocMembersDidChange(blocMembers) dashboardUpdateDelegate.update(blocMembersCount: blocMembers.count) } } // MARK: - View Controller Lifecycle methods override func viewDidLoad() { super.viewDidLoad() hideSideMenu() } override func viewWillAppear(_ animated: Bool) { self.navigationController?.setNavigationBarHidden(true, animated: animated) super.viewWillAppear(animated) GameKitManager.sharedInstance.gameViewPresenterDelegate = self gameKitManagerDelegate = GameKitManager.sharedInstance multipeerManagerDelegate = MultipeerManager.sharedInstance MultipeerManager.sharedInstance.multipeerViewHandlerDelegate = self } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) gameKitManagerDelegate.authenticatePlayer() } override func viewWillDisappear(_ animated: Bool) { self.navigationController?.setNavigationBarHidden(false, animated: animated) super.viewWillDisappear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // MARK: - Orientation Transition method override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) coordinator.animate(alongsideTransition: nil) { coordinatorContext in self.tapHideSideMenu() } } // MARK: - Side Menu Methods // should be moved to a separate controller? private func hideSideMenu() { sideMenuContainerWidthConstraint.constant = 20 sideMenuContainerView.isHidden = true } // Used by dismiss side menu view UITapGestureRecognizer internal func tapHideSideMenu() { hideSideMenu() sideMenuAnimation() dismissSideMenuView?.removeFromSuperview() } private func showSideMenu() { let newWidth = view.bounds.width * 2 / 3 sideMenuContainerWidthConstraint.constant = newWidth sideMenuContainerView.isHidden = false dismissSideMenuView = DismissSideMenuView(mainVC: self, sideMenuWidth: newWidth) sideMenuAnimation() } private func sideMenuAnimation() { UIView.animate(withDuration: 0.5) { self.view.layoutIfNeeded() } } // MARK: - Action Button IBAction Method private var actionButtonImageIsStartButton = true @IBAction func actionButtonPressed(_ sender: UIButton) { let authorizedToProceed = mapNotificationDelegate.didPressActionButton() if authorizedToProceed { if actionButtonImageIsStartButton { sender.setImage(#imageLiteral(resourceName: "StopRunButton"), for: .normal) } else { sender.setImage(#imageLiteral(resourceName: "StartRunButton"), for: .normal) } actionButtonImageIsStartButton = !actionButtonImageIsStartButton } } // MARK: - Navigation // TODO: - Create a Navigator class for managing navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == SegueIdentifier.dashboardEmbedSegue { if let dashboardViewC = segue.destination as? DashboardViewC { prepareForDashboard(dashboardViewC) } } else if segue.identifier == SegueIdentifier.mapEmbedSegue { mapViewC = segue.destination as? MapViewC prepareForMap(mapViewC!) } else if segue.identifier == SegueIdentifier.runHistoryTableSegue { if let runHistoryTableViewC = segue.destination as? RunHistoryTableViewC { runHistoryTableViewC.loadRunDelegate = self } } else if segue.identifier == SegueIdentifier.currentBlocTableSegue { if let currentBlocTableViewC = segue.destination as? CurrentBlocTableViewC { currentBlocTableViewC.currentBlocTableDataSource = CurrentBlocTableDataSource(blocMembers: blocMembers) } } else if segue.identifier == SegueIdentifier.sideMenuTableEmbedSegue { if let sideMenuTableViewC = segue.destination as? SideMenuTableViewC { sideMenuTableViewC.tableDelegate = SideMenuTableDelegate(segueCoordinator: self) } } else if segue.identifier == SegueIdentifier.topMenuEmbedSegue { if let topMenuViewC = segue.destination as? TopMenuViewC { topMenuViewC.topMenuDelegate = self } } } private func prepareForDashboard(_ dashboardViewC: DashboardViewC) { let dashboardController = DashboardController() dashboardViewC.controller = dashboardController dashboardUpdateDelegate = dashboardController mapViewC?.dashboardUpdateDelegate = dashboardUpdateDelegate } private func prepareForMap(_ mapViewC: MapViewC) { let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext mapViewC.controller = MapController(requestMainDataDelegate: self, scoreReporterDelegate: GameKitManager.sharedInstance, context: context) mapNotificationDelegate = mapViewC.controller as! MapNotificationDelegate! mapViewC.dashboardUpdateDelegate = dashboardUpdateDelegate } // Updates the current blocMembers array if the user removes any // using the current bloc table view @IBAction func undwindToMainViewC(_ sender: UIStoryboardSegue) { if sender.identifier == SegueIdentifier.unwindFromCurrentBlocTable { if let currentBlocTableVC = sender.source as? CurrentBlocTableViewC, let currentBlocTableDataSource = currentBlocTableVC.currentBlocTableDataSource { blocMembers = currentBlocTableDataSource.blocMembers } } } // MARK: - LoadRunDelegate method internal func tellMapToLoadRun(run: Run) { mapNotificationDelegate.loadSavedRun(run: run) } // MARK: - RequestMainDataDelegate method // used by the map to get current bloc members internal func getCurrentBlocMembers() -> [BlocMember] { return blocMembers } // MARK: - SegueCoordinationDelegate method // (for the side menu) internal func transition(withSegueIdentifier identifier: String) { if identifier == SegueIdentifier.gameCenterSegue { gameKitManagerDelegate.showLeaderboard() } else { performSegue(withIdentifier: identifier, sender: self) } } // MARK: - TopMenuProtocol methods internal func segueToCurrentBlocTable() { performSegue(withIdentifier: SegueIdentifier.currentBlocTableSegue, sender: self) } internal func toggleSideMenu() { sideMenuContainerView.isHidden ? showSideMenu() : hideSideMenu() } // Called from TopMenuViewC when user clicks multipeer button internal func presentMCBrowserAndStartMCAssistant() { let mcBrowserVC = multipeerManagerDelegate.prepareMCBrowser() self.present(mcBrowserVC, animated: true, completion: nil) } // MARK: - MultipeerViewHandlerDelegate methods internal func blocMembersContains(blocMember: BlocMember) -> Bool { // should be in view model not view return blocMembers.contains(blocMember) } internal func addToCurrentBloc(blocMember: BlocMember) { // should not be handled by view DispatchQueue.main.sync { blocMembers.append(blocMember) } } // MARK: - GameKitManagerDelegate methods internal func presentGameVC(_ viewController: UIViewController) { present(viewController, animated: true, completion: nil) } }
mit
796d958cad2f2051b9fb1f9e280dea45
36.528053
184
0.693167
5.65159
false
false
false
false
VadimPavlov/Swifty
Sources/Swifty/ios/Permissions/Location.swift
1
2121
// // Location.swift // Swifty // // Created by Vadim Pavlov on 8/17/18. // Copyright © 2018 Vadym Pavlov. All rights reserved. // import UIKit import CoreLocation public extension Permissions { final class Location: NSObject, CLLocationManagerDelegate, Permission { public var nameInUse = "Location In Use" public var nameAlways = "Location Always" public lazy var status = Observable<CLAuthorizationStatus>(CLLocationManager.authorizationStatus()) private let manager = CLLocationManager() private var completion: RequestCompletion? override init() { super.init() manager.delegate = self } public func requestAlways(from vc: UIViewController, completion: RequestCompletion? = nil) { guard validate(usageKey: "NSLocationAlwaysUsageDescription") else { return } switch status.value { case .authorizedAlways: completion?() case .notDetermined: self.completion = completion self.manager.requestAlwaysAuthorization() default: self.showSettingsAlert(permission: nameAlways, in: vc) } } public func requestWhenInUse(from vc: UIViewController, completion: RequestCompletion? = nil) { guard validate(usageKey: "NSLocationWhenInUseUsageDescription") else { return } switch status.value { case .authorizedWhenInUse, .authorizedAlways: completion?() case .notDetermined: self.completion = completion self.manager.requestWhenInUseAuthorization() default: self.showSettingsAlert(permission: nameInUse, in: vc) completion?() } } public func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { if status == .notDetermined { return } self.status.value = status completion?() completion = nil } } }
mit
5474faeea8a909157cd283bbd51d9271
32.125
121
0.613208
5.79235
false
false
false
false
justinvyu/SwiftyDictionary
Pod/Classes/DictionaryRequest.swift
1
1392
// // File.swift // Pods // // Created by Justin Yu on 11/25/15. // // import Foundation import Alamofire import AEXML public class DictionaryRequest { // MARK: - Properties var word: String? var action: SwiftyDictionaryType? var apiKey: String? // MARK: - Lifecycle public init(word: String, action: SwiftyDictionaryType, key: String) { self.word = word self.action = action self.apiKey = key } // MARK: - Request Functions func makeAPIRequest(callback: DictionaryRequestCallback) { let url = getRequestUrl() Alamofire.request(.GET, url) .responseData { response in do { if let data = response.data { let formattedData = try AEXMLDocument(xmlData: data) callback(formattedData) } } catch { print("\(error)") } } } func getRequestUrl() -> NSURL { var urlString = "" if let word = word, action = action, key = apiKey { urlString += "\(action == .Dictionary ? "collegiate" : "thesaurus")/xml/\(word)?key=\(key)" } return NSURL(string: urlString, relativeToURL: SwiftyDictionaryConstants.API_ROOT_PATH)! } }
mit
02535a6c57fc5addd74cd6981dac0a16
23.875
103
0.520115
4.8
false
false
false
false
dbaldwin/DronePan
DronePan/Controllers/ConnectionController.swift
1
7256
/* 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 DJISDK import CocoaLumberjackSwift enum ProductType { case Aircraft case Handheld case Unknown } protocol ConnectionControllerDelegate { func sdkRegistered() func failedToRegister(reason: String) func connectedToProduct(product: DJIBaseProduct) func disconnected() func connectedToBattery(battery: DJIBattery) func connectedToCamera(camera: DJICamera) func connectedToGimbal(gimbal: DJIGimbal) func connectedToRemote(remote: DJIRemoteController) func connectedToFlightController(flightController: DJIFlightController) func disconnectedFromBattery() func disconnectedFromCamera() func disconnectedFromGimbal() func disconnectedFromRemote() func disconnectedFromFlightController() func firmwareVersion(version: String) } protocol ConnectionControllerDiagnosticsDelegate { func diagnosticsSeen(code code: Int, reason: String, solution: String?) } @objc class ConnectionController: NSObject, DJISDKManagerDelegate, DJIBaseProductDelegate, Analytics { var runInBridgeMode = false let bridgeAddress = "10.0.1.18" let appKey = "d6b78c9337f72fadd85d88e2" var delegate: ConnectionControllerDelegate? var diagnosticsDelegate: ConnectionControllerDiagnosticsDelegate? var model: String? var firmwareVersion: String? func start() { DJISDKManager.registerApp(appKey, withDelegate: self) } @objc func sdkManagerDidRegisterAppWithError(error: NSError?) { if let error = error { DDLogWarn("Registration failed with \(error)") self.delegate?.failedToRegister("Unable to register application - make sure you run at least once with internet access") } else { DDLogDebug("Connecting to product") self.delegate?.sdkRegistered() if (runInBridgeMode) { DDLogDebug("Connecting to debug bridge") DJISDKManager.enterDebugModeWithDebugId(bridgeAddress) } else { DDLogDebug("Connecting to real product") DJISDKManager.startConnectionToProduct() } } } func sdkManagerProductDidChangeFrom(oldProduct: DJIBaseProduct?, to newProduct: DJIBaseProduct?) { self.model = newProduct?.model if let product = newProduct { DDLogInfo("Connected to \(self.model)") if let model = product.model { trackEvent(category: "Connection", action: "New Product", label: model) } product.delegate = self self.delegate?.connectedToProduct(product) if let components = product.components { for (key, component) in components { for c in component { self.componentWithKey(key, changedFrom: nil, to: c) } } } // Grab the product firmware version to display in settings product.getFirmwarePackageVersionWithCompletion{ (version:String?, error:NSError?) -> Void in if let firmware = version { DDLogInfo("Firmware \(firmware)") self.trackEvent(category: "Connection", action: "Firmware Version", label: firmware) } self.delegate?.firmwareVersion(version ?? "Unknown") } } else { DDLogInfo("Disconnected") self.delegate?.disconnected() } } func product(product: DJIBaseProduct, didUpdateDiagnosticsInformation info: [AnyObject]) { for diagnostic in info { if let d = diagnostic as? DJIDiagnostics { DDLogDebug("Diagnostic for \(model): Code: \(d.code), Reason: \(d.reason), Solution: \(d.solution)") self.diagnosticsDelegate?.diagnosticsSeen(code: d.code, reason: d.reason, solution: d.solution) } } } func componentWithKey(key: String, changedFrom oldComponent: DJIBaseComponent?, to newComponent: DJIBaseComponent?) { switch key { case DJIBatteryComponent: if let battery = newComponent as? DJIBattery { DDLogDebug("New battery") self.delegate?.connectedToBattery(battery) } else { DDLogDebug("No battery") self.delegate?.disconnectedFromBattery() } case DJICameraComponent: if let camera = newComponent as? DJICamera { DDLogDebug("New camera") trackEvent(category: "Connection", action: "New Camera", label: camera.displayName) if (camera.isChangeableLensSupported()) { camera.getLensInformationWithCompletion({ (info, error) in if let error = error { DDLogError("Unable to get lens information \(error)") } else { if let info = info { self.trackEvent(category: "Connection", action: "New Lens", label: info) } } }) } self.delegate?.connectedToCamera(camera) } else { DDLogDebug("No camera") self.delegate?.disconnectedFromCamera() } case DJIGimbalComponent: if let gimbal = newComponent as? DJIGimbal { DDLogDebug("New gimbal") self.delegate?.connectedToGimbal(gimbal) } else { DDLogDebug("No gimbal") self.delegate?.disconnectedFromGimbal() } case DJIRemoteControllerComponent: if let remote = newComponent as? DJIRemoteController { DDLogDebug("New remote") self.delegate?.connectedToRemote(remote) } else { DDLogDebug("No remote") self.delegate?.disconnectedFromRemote() } case DJIFlightControllerComponent: if let fc = newComponent as? DJIFlightController { DDLogDebug("New flight controller") self.delegate?.connectedToFlightController(fc) } else { DDLogDebug("No flight controller") self.delegate?.disconnectedFromFlightController() } default: DDLogDebug("Not handling \(key)") } } }
gpl-3.0
c2293cbd70e3967251fd62be903b4822
33.552381
132
0.599779
5.526276
false
false
false
false
lrosa007/ghoul
gool/DSP.swift
2
15507
// // DSP.swift // gool // // Digital Signal Processing module // // Copyright © 2016 Dead Squad. All rights reserved. // import Foundation import Accelerate class DSP { // relative dielectric permittivity (RDP) of various soils in approx 100 MHz to 1 GHz range // taken from http://home.earthlink.net/~w6rmk/soildiel.htm // and http://ntrs.nasa.gov/archive/nasa/casi.ntrs.nasa.gov/19750018483.pdf enum SoilType: Double, CustomStringConvertible { case Sandy_dry = 2.25 case Sandy_5_water = 5.5 case Sandy_10_water = 8.0 case Sandy_15_water = 11.9 case Sandy_20_water = 18.1 case Loamy_dry = 3.5 case Loamy_5_water = 5.0 case Loamy_12_water = 10.0 case Loamy_20_water = 22.0 case Clay_dry = 2.38 case Clay_10_water = 8.5 case Clay_20_water = 12.0 var description: String { switch self { case .Sandy_dry: return "Sandy soil (very dry)" case .Sandy_5_water: return "Sandy soil (dry)" case .Sandy_10_water: return "Sandy soil (damp)" case .Sandy_15_water: return "Sandy soil (wet)" case .Sandy_20_water: return "Sandy soil (very wet)" case .Loamy_dry: return "Loamy soil (very dry)" case .Loamy_5_water: return "Loamy soil (dry)" case .Loamy_12_water: return "Loamy soil (damp)" case .Loamy_20_water: return "Loamy soil (wet)" case .Clay_dry: return "Clay (dry)" case .Clay_10_water: return "Clay (damp)" case .Clay_20_water: return "Clay (wet)" } } } static let FWHM = 2.35482 static let C_m_s = 299_792_458.0 // speed of light in m/s static let C_nm_s = C_m_s/1e9 // speed of light in nm/s static let max8Bit = Double(UInt8.max) static let max16Bit = Double(UInt16.max) static func repack(bytes: [UInt8], is8Bit: Bool) -> [UInt16] { var repacked: [UInt16] if is8Bit { repacked = [UInt16](count: bytes.count, repeatedValue: 0) for i in 0...bytes.count-1 { let val = UInt16(bytes[i]) repacked.append(val + (val<<8)) // Each 8-bit val could come from 128 distinct 16-bit values // scaled so 0->0, 128->32896, 255->65535 // Could also randomly select one of the 128 } } else { // may be efficient way to recast in Objective-C let n = bytes.count / 2 repacked = [UInt16](count: n, repeatedValue: 0) for i in 0...n { repacked[i] = UInt16(bytes[2*i]) << 8 repacked[i] += UInt16(bytes[2*i + 1]) } } return repacked } class func dataAsDoubles(trace: GPRTrace) -> [Double] { return trace.data.map({(val: UInt16) -> Double in Double(val)}) } // Assuming constant material RDP and ignoring attenuation, determines // change in reflection depth between successive samples class internal func dDepth(trace: GPRTrace, settings: GPRSettings) -> Double { return estDepth_s(settings.𝚫T, avgRDP: settings.baseRdp) } //TODO: stubbed class internal func filter(signal: GPRTrace, settings: GPRSettings) -> [UInt16] { // plan: select transforms and/or filters based on mode return signal.data } // does not check that traces match each other; just stacks their data static func stackData(traces : [GPRTrace]) -> [UInt16] { // consider using vDSP_vavlin or _vavlinD let n = UInt16(traces.count), len = traces[0].data.count var stackedData = [UInt16](count: len, repeatedValue: 0) var remainder = [UInt16](count: len, repeatedValue: 0) for trace in traces { for (index, value) in trace.data.enumerate() { stackedData[index] += value/n remainder[index] += value%n } } for (index, value) in remainder.enumerate() { //currently just tries to round appropriately; // perhaps 2 or 4 bytes could be averaged at a time stackedData[index] += (value + n/2)/n } return stackedData } static func findPeaks(vector: [Double], dx: Double, minSlope: Double, minAmplitude: Double) -> [Peak] { // 1) Find derivative // 2) Smooth derivative // 3) Find zero crossings in smoothed derivative // TODO: update to determine (or be passed) values for optimal smoothing ratio let smoothedDeriv = smooth(deriv(vector, dx: dx), width: 3) let n = vector.count var peaks = [Peak]() for i in 1 ... n-2 { // zero crossing if smoothedDeriv[i-1] >= 0 && smoothedDeriv[i] <= 0 && smoothedDeriv[i-1] != smoothedDeriv[i] { // meets amplitude threshold if vector[i] > minAmplitude || vector[i+1] > minAmplitude { // meets slope threshold let slope = max(abs(smoothedDeriv[i+1]-smoothedDeriv[i]), abs(smoothedDeriv[i]-smoothedDeriv[i-1])) // use dx? if slope >= minSlope { // not sure the best way to determine range let from = max(0, i-10), to = min(n-1, i+10) peaks.append(getPeak(vector, dx: dx, from: from, to: to)) } } } } return peaks } // Uses quadratic least-squares regression to estimate peak attributes static private func getPeak(vector: [Double], dx: Double, from: Int, to: Int) -> Peak { let n = from+1-to var sumX = 0.0, sumY = 0.0, sumXY = 0.0, sumX2 = 0.0, sumX3 = 0.0, sumX4 = 0.0, sumX2Y = 0.0 for i in from...to { let x = Double(i) * dx, y = vector[i] sumY += y sumX += x sumXY += x*y sumX2 += x*x sumX2Y += x*x*y sumX3 += x*x*x sumX4 += x*x*x*x } let nd = Double(n) var D = (nd*sumX2*sumX4) D += (2*sumX*sumX2*sumX3) D -= (sumX2*sumX2*sumX2*sumX4) D -= (nd*sumX3*sumX3) var a = nd*sumX2*sumX2Y a += sumX*sumX3*sumY a += sumX*sumX2*sumXY a -= sumX2*sumX2*sumY a -= sumX*sumX*sumX2Y a -= nd*sumX3*sumXY a /= D var b = nd*sumX4*sumXY b += sumX*sumX2*sumX2Y b += sumX2*sumX3*sumY b -= sumX2*sumX2*sumXY b -= sumX*sumX4*sumY b -= nd*sumX3*sumX2Y b /= D var c = sumX2*sumX4*sumY c += sumX2*sumX3*sumXY c += sumX*sumX3*sumX2Y c -= sumX2*sumX2*sumX2Y c -= sumX*sumX4*sumXY c -= sumX3*sumX3*sumY c /= D let position = -b/(2*c) let sample = Int(round(position/dx)) let height = a - c*position*position let width = FWHM/sqrt(-2*c) return Peak(sample: sample, pos: position, h: height, w: width) } // Returns a list of possible materials for this item static func guessMaterials(peak: Peak, settings: GPRSettings, base: Double, reflection: Double) -> [Material] { var guesses = [Material]() let rdp = estimateRDP(settings.baseRdp, baseIntensity: base, reflectedIntensity: reflection) for material in Material.MaterialList { if rdp >= material.minRDP && rdp <= material.maxRDP { guesses.append(material) } } return guesses } // linearly approximates first derivative of signal static func deriv(vector: [Double], dx: Double) -> [Double] { let n = vector.count var deriv = [Double].init(count: n, repeatedValue: 0.0) for i in 1 ... n-2 { deriv[i] = (vector[i+1]-vector[i-1])/(2*dx) } return deriv } // smooth signal with variable signal width (width must be odd) static func smooth(vector: [Double], width: Int) -> [Double] { let w: Int if width < 1 { w = 1 } else if width % 2 == 0 { w = 3 } else { w = width } let wf = Double(w), div = wf*wf let n = vector.count var res = [Double].init(count: n, repeatedValue: 0.0) var sum:Double = wf * vector[w-1] //initial sum value for i in 1 ... w-1 { sum += (wf-Double(i)) * (vector[w-1-i] + vector[w-1+i]) } res[w-1] = sum/div if w <= n-w { for i in w ... n-w { for j in -w ... w-1 { sum += j < 0 ? -vector[i+j] : vector[i+j] } res[i] = sum/div } } return res } // in-place triangular smooth static func smooth(inout vector: [Double]) { let n = vector.count var vim2 = vector[0], vim1 = vector[1], vi = vector[2], vip1 = vector[3], vip2 = vector[4], sum = vim2 + 2*vim1 + 3*vi + 2*vip1 + vip2, i = 2 vector[i] = sum while i+3 < n { i += 1 let next = sum/9.0 sum -= vim2; vim2 = vim1 sum -= vim1; vim1 = vi sum -= vi; vi = vip1 sum += vip1; vip1 = vip2 sum += vip2; vip2 = vector[i+2] vector[i] = next } } // Smooths a signal via Fourier Transform. portion of highest frequencies are eliminated static func smoothFourier(vector: [Double], portion: Float) -> [Double] { // FFT setup let n = vector.count var real = [Double](vector) if portion >= 1.0 { return real } var imaginary = [Double](count: n, repeatedValue: 0.0) var splitComplex = DSPDoubleSplitComplex(realp: &real, imagp: &imaginary) let log2n = vDSP_Length(ceil(log2(Float(n)))) let radix = FFTRadix(kFFTRadix2) let weights = vDSP_create_fftsetupD(log2n, radix) vDSP_fft_zipD(weights, &splitComplex, 1, log2n, FFTDirection(FFT_FORWARD)) // note that vDSP implementation of real FFT yields doubled values. No fix needed for complex // splitComplex now holds the Fourier transform of signal // zero out high frequencies to remove noise let clearInd = Int(ceil(Float(n)*portion)) for i in clearInd...n-1 { real[i] = 0.0 imaginary[i] = 0.0 } // inverse FFT vDSP_fft_zipD(weights, &splitComplex, 1, log2n, FFTDirection(FFT_INVERSE)) // cleanup vDSP_destroy_fftsetupD(weights) // vDSP complex inverse FFT yields actual values times n let nd = Double(n) return real.map({(x: Double) -> Double in return x/nd}) } // Given expected average RDP of medium, what reflection depth is indicated by a sample at time t? static func estDepth_s(t: Double, avgRDP: Double) -> Double { return C_m_s * t / (2.0 * sqrt(avgRDP)) } // same as estDepth_s but with time in nanoseconds instead of seconds static func estDepth_ns(t: Double, avgRDP: Double) -> Double { return C_nm_s * t / (2.0 * sqrt(avgRDP)) } // Electromagnetic waves are reflected at interface of two materials based on their relative // dielectric permittivities (RDPs). Given expected RDP of first material, expected wave intensity // at interface, and measured reflected intensity, this yields the expected RDP of second material. // This function does not account for attenuation/loss; all such adjustments must be made before calling. // Returned value of > ~80 indicates second material is a conductor. static func estimateRDP(baseRDP: Double, baseIntensity: Double, reflectedIntensity: Double) -> Double { let plus = baseIntensity + reflectedIntensity let diff = baseIntensity - reflectedIntensity return baseRDP * (plus*plus) / (diff*diff) } // Cubic spline function. results of interpolation are stored in yNew // based on JL_UTIL.C Spline() by Jeff Lucius, USGS Crustal Imaging and Characterization Team static func spline(xNew: [Double], yNewValues: [Double], xValues: [Double], yValues: [Double]) { let n = xValues.count var x = [Double].init(count: n, repeatedValue: 0.0), y = [Double].init(count: n, repeatedValue: 0.0), yNew = [Double].init(count: n, repeatedValue: 0.0) for i in 0...n-1 { x[i] = xValues[i] y[i] = yValues[i] yNew[i] = yNewValues[i] } // reverse sequence if necessary if(x[n-1] < x[0]) { var temp = 0.0 for i in 0...n/2-1 { temp = x[i] x[i] = x[n-1-i] x[n-1-i] = temp temp = y[i] y[i] = y[n-1-i] y[n-1-i] = temp } } var s = [Double](), g = [Double](), work = [Double](count: n, repeatedValue: 0.0) s.append(0.0) g.append(0.0) for i in 1...n-2 { var dx, dx2: Double dx = x[i]-x[i-1] dx2 = x[i+1]-x[i-1] work[i] = (dx)/(dx2)/2 let t = ((y[i+1]-y[i])/(dx) - (y[i]-y[i-1])/(dx))/(dx2) s.append(2.0*t) g.append(3.0*t) } s.append(0.0) g.append(0.0) let w = 8.0 - 4.0*sqrt(3.0), epsilon = 1.0e-6 var u = 0.0 repeat { u = 0.0 for i in 1...n-2 { let xx = work[i] let t = w*(g[i]-s[i] - xx*s[i] - (0.5-xx)*s[i+1]) u = max(u, abs(t)) s[i] += t } } while(u >= epsilon) for i in 0...n-1 { g[i] = (s[i+1] - x[i]) / (x[i+1] - x[i]) } // interpolation var i = 0 for j in 0...n-1 { let t = xNew[j] repeat {i += 1} while (i < n-1 && t > x[i]) i -= 1 let h = xNew[j] - x[i] var temp: Double = (xNew[j]-x[i+1])/6.0 temp *= (2*s[i] + s[i+1] + h*g[i]) temp += (y[i+1]-y[i])/(x[i+1]-x[i]) + y[i] yNew[j] = h * temp } } class Peak { var position, height, width: Double var sampleNumber: Int init(sample: Int, pos: Double, h: Double, w: Double) { sampleNumber = sample position = pos height = h width = w } }}
gpl-2.0
b5473231e8b6f8cf802bb6bf7f107721
32.341935
130
0.497001
3.799755
false
false
false
false
qds-hoi/suracare
suracare/suracare/Core/CommonUI/AudioVisualization/KMCircularProgressView.swift
6
5606
// // KMCircularProgressView.swift // VoiceMemos // // Created by Zhouqi Mo on 2/21/15. // Copyright (c) 2015 Zhouqi Mo. All rights reserved. // import UIKit @IBDesignable public class KMCircularProgressView: UIView { @IBInspectable public var progress: CGFloat = 0.0 { didSet { progressLayer.strokeEnd = progress } } public var iconStyle: KMIconStyle = .Empty { didSet { iconLayer.path = iconStyle.path(iconLayerBounds) } } @IBInspectable public var lineWidth: CGFloat = 3.0 { didSet { backgroundLayer.lineWidth = lineWidth progressLayer.lineWidth = lineWidth } } @IBInspectable public var backgroundLayerStrokeColor: UIColor = UIColor(white: 0.90, alpha: 1.0) { didSet { backgroundLayer.strokeColor = backgroundLayerStrokeColor.CGColor } } @IBInspectable public var iconLayerFrameRatio: CGFloat = 0.4 { didSet { iconLayer.frame = iconLayerFrame(iconLayerBounds, ratio: iconLayerFrameRatio) iconLayer.path = iconStyle.path(iconLayerBounds) } } public var iconLayerBounds: CGRect { return iconLayer.bounds } public func setProgress(progress: CGFloat, animated: Bool = true) { if animated { self.progress = progress } else { self.progress = progress let animation = CABasicAnimation(keyPath: "strokeEnd") animation.fromValue = progress animation.duration = 0.0 progressLayer.addAnimation(animation, forKey: nil) } } public enum KMIconStyle { case Play case Pause case Stop case Empty case Custom(UIBezierPath) func path(layerBounds: CGRect) -> CGPath { switch self { case .Play: let path = UIBezierPath() path.moveToPoint(CGPoint(x: layerBounds.width / 5, y: 0)) path.addLineToPoint(CGPoint(x: layerBounds.width, y: layerBounds.height / 2)) path.addLineToPoint(CGPoint(x: layerBounds.width / 5, y: layerBounds.height)) path.closePath() return path.CGPath case .Pause: var rect = CGRect(origin: CGPoint(x: layerBounds.width * 0.1, y: 0), size: CGSize(width: layerBounds.width * 0.2, height: layerBounds.height)) let path = UIBezierPath(rect: rect) rect.offsetInPlace(dx: layerBounds.width * 0.6, dy: 0) path.appendPath(UIBezierPath(rect: rect)) return path.CGPath case .Stop: let insetBounds = CGRectInset(layerBounds, layerBounds.width / 6, layerBounds.width / 6) let path = UIBezierPath(rect: insetBounds) return path.CGPath case .Empty: return UIBezierPath().CGPath case .Custom(let path): return path.CGPath } } } lazy var backgroundLayer: CAShapeLayer = { let backgroundLayer = CAShapeLayer() backgroundLayer.fillColor = nil backgroundLayer.lineWidth = self.lineWidth backgroundLayer.strokeColor = self.backgroundLayerStrokeColor.CGColor self.layer.addSublayer(backgroundLayer) return backgroundLayer }() lazy var progressLayer: CAShapeLayer = { let progressLayer = CAShapeLayer() progressLayer.fillColor = nil progressLayer.lineWidth = self.lineWidth progressLayer.strokeColor = self.tintColor.CGColor self.layer.insertSublayer(progressLayer, above: self.backgroundLayer) return progressLayer }() lazy var iconLayer: CAShapeLayer = { let iconLayer = CAShapeLayer() iconLayer.fillColor = self.tintColor.CGColor self.layer.addSublayer(iconLayer) return iconLayer }() func iconLayerFrame(rect: CGRect, ratio: CGFloat) -> CGRect { let insetRatio = (1 - ratio) / 2.0 return CGRectInset(rect, CGRectGetWidth(rect) * insetRatio, CGRectGetHeight (rect) * insetRatio) } func getSquareLayerFrame(rect: CGRect) -> CGRect { if rect.width != rect.height { let width = min(rect.width, rect.height) let originX = (rect.width - width) / 2 let originY = (rect.height - width) / 2 return CGRectMake(originX, originY, width, width) } return rect } override public func layoutSubviews() { super.layoutSubviews() let squareRect = getSquareLayerFrame(layer.bounds) backgroundLayer.frame = squareRect progressLayer.frame = squareRect let innerRect = CGRectInset(squareRect, lineWidth / 2.0, lineWidth / 2.0) iconLayer.frame = iconLayerFrame(innerRect, ratio: iconLayerFrameRatio) let center = CGPointMake(squareRect.width / 2.0, squareRect.height / 2.0) let path = UIBezierPath(arcCenter: center, radius: innerRect.width / 2.0, startAngle: CGFloat(-M_PI_2), endAngle: CGFloat(-M_PI_2 + 2.0 * M_PI), clockwise: true) backgroundLayer.path = path.CGPath progressLayer.path = path.CGPath iconLayer.path = iconStyle.path(iconLayerBounds) } override public func prepareForInterfaceBuilder() { super.prepareForInterfaceBuilder() iconStyle = .Play } }
mit
2ee147647552864fe96acbbd812f993f
33.611111
169
0.600428
5.087114
false
false
false
false
radazzouz/firefox-ios
Storage/PageMetadata.swift
1
3129
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import UIKit import WebImage enum MetadataKeys: String { case imageURL = "image_url" case imageDataURI = "image_data_uri" case pageURL = "url" case title = "title" case description = "description" case type = "type" case provider = "provider" } /* * Value types representing a page's metadata */ public struct PageMetadata { public let id: Int? public let siteURL: String public let mediaURL: String? public let title: String? public let description: String? public let type: String? public let providerName: String? public init(id: Int?, siteURL: String, mediaURL: String?, title: String?, description: String?, type: String?, providerName: String?, mediaDataURI: String?) { self.id = id self.siteURL = siteURL self.mediaURL = mediaURL self.title = title self.description = description self.type = type self.providerName = providerName self.cacheImage(fromDataURI: mediaDataURI, forURL: mediaURL) } public static func fromDictionary(_ dict: [String: Any]) -> PageMetadata? { guard let siteURL = dict[MetadataKeys.pageURL.rawValue] as? String else { return nil } return PageMetadata(id: nil, siteURL: siteURL, mediaURL: dict[MetadataKeys.imageURL.rawValue] as? String, title: dict[MetadataKeys.title.rawValue] as? String, description: dict[MetadataKeys.description.rawValue] as? String, type: dict[MetadataKeys.type.rawValue] as? String, providerName: dict[MetadataKeys.provider.rawValue] as? String, mediaDataURI: dict[MetadataKeys.imageDataURI.rawValue] as? String) } fileprivate func cacheImage(fromDataURI dataURI: String?, forURL urlString: String?) { if let urlString = urlString, let url = URL(string: urlString) { if let dataURI = dataURI, let dataURL = URL(string: dataURI), let data = try? Data(contentsOf: dataURL), let image = UIImage(data: data) { self.cache(image: image, forURL: url) } else { // download image direct from URL self.downloadAndCache(fromURL: url) } } } fileprivate func downloadAndCache(fromURL webUrl: URL) { let imageManager = SDWebImageManager.shared() let _ = imageManager?.downloadImage(with: webUrl, options: SDWebImageOptions.continueInBackground, progress: nil) { (image, error, cacheType, success, url) in guard let image = image else { return } self.cache(image: image, forURL: webUrl) } } fileprivate func cache(image: UIImage, forURL url: URL) { let imageManager = SDWebImageManager.shared() imageManager?.saveImage(toCache: image, for: url) } }
mpl-2.0
781a535d803b92ed4b9a3f36cd0944b1
36.698795
208
0.635986
4.587977
false
false
false
false
klaus01/Centipede
Centipede/MediaPlayer/CE_MPMediaPickerController.swift
1
2854
// // CE_MPMediaPickerController.swift // Centipede // // Created by kelei on 2016/9/15. // Copyright (c) 2016年 kelei. All rights reserved. // import MediaPlayer extension MPMediaPickerController { private struct Static { static var AssociationKey: UInt8 = 0 } private var _delegate: MPMediaPickerController_Delegate? { get { return objc_getAssociatedObject(self, &Static.AssociationKey) as? MPMediaPickerController_Delegate } set { objc_setAssociatedObject(self, &Static.AssociationKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) } } private var ce: MPMediaPickerController_Delegate { if let obj = _delegate { return obj } if let obj: AnyObject = self.delegate { if obj is MPMediaPickerController_Delegate { return obj as! MPMediaPickerController_Delegate } } let obj = getDelegateInstance() _delegate = obj return obj } private func rebindingDelegate() { let delegate = ce self.delegate = nil self.delegate = delegate } internal override func getDelegateInstance() -> MPMediaPickerController_Delegate { return MPMediaPickerController_Delegate() } @discardableResult public func ce_mediaPicker_didPickMediaItems(handle: @escaping (MPMediaPickerController, MPMediaItemCollection) -> Void) -> Self { ce._mediaPicker_didPickMediaItems = handle rebindingDelegate() return self } @discardableResult public func ce_mediaPickerDidCancel(handle: @escaping (MPMediaPickerController) -> Void) -> Self { ce._mediaPickerDidCancel = handle rebindingDelegate() return self } } internal class MPMediaPickerController_Delegate: UIViewController_Delegate, MPMediaPickerControllerDelegate { var _mediaPicker_didPickMediaItems: ((MPMediaPickerController, MPMediaItemCollection) -> Void)? var _mediaPickerDidCancel: ((MPMediaPickerController) -> Void)? override func responds(to aSelector: Selector!) -> Bool { let funcDic1: [Selector : Any?] = [ #selector(mediaPicker(_:didPickMediaItems:)) : _mediaPicker_didPickMediaItems, #selector(mediaPickerDidCancel(_:)) : _mediaPickerDidCancel, ] if let f = funcDic1[aSelector] { return f != nil } return super.responds(to: aSelector) } @objc func mediaPicker(_ mediaPicker: MPMediaPickerController, didPickMediaItems mediaItemCollection: MPMediaItemCollection) { _mediaPicker_didPickMediaItems!(mediaPicker, mediaItemCollection) } @objc func mediaPickerDidCancel(_ mediaPicker: MPMediaPickerController) { _mediaPickerDidCancel!(mediaPicker) } }
mit
644e5eb9051dc835e3f8f3751f827c32
32.952381
134
0.667251
5.548638
false
false
false
false
yanyuqingshi/ios-charts
Charts/Classes/Renderers/BarChartRenderer.swift
1
23406
// // BarChartRenderer.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics.CGBase import UIKit.UIFont @objc public protocol BarChartRendererDelegate { func barChartRendererData(renderer: BarChartRenderer) -> BarChartData!; func barChartRenderer(renderer: BarChartRenderer, transformerForAxis which: ChartYAxis.AxisDependency) -> ChartTransformer!; func barChartRendererMaxVisibleValueCount(renderer: BarChartRenderer) -> Int; func barChartDefaultRendererValueFormatter(renderer: BarChartRenderer) -> NSNumberFormatter!; func barChartRendererChartYMax(renderer: BarChartRenderer) -> Double; func barChartRendererChartYMin(renderer: BarChartRenderer) -> Double; func barChartRendererChartXMax(renderer: BarChartRenderer) -> Double; func barChartRendererChartXMin(renderer: BarChartRenderer) -> Double; func barChartIsDrawHighlightArrowEnabled(renderer: BarChartRenderer) -> Bool; func barChartIsDrawValueAboveBarEnabled(renderer: BarChartRenderer) -> Bool; func barChartIsDrawValuesForWholeStackEnabled(renderer: BarChartRenderer) -> Bool; func barChartIsDrawBarShadowEnabled(renderer: BarChartRenderer) -> Bool; func barChartIsInverted(renderer: BarChartRenderer, axis: ChartYAxis.AxisDependency) -> Bool; } public class BarChartRenderer: ChartDataRendererBase { public weak var delegate: BarChartRendererDelegate?; public init(delegate: BarChartRendererDelegate?, animator: ChartAnimator?, viewPortHandler: ChartViewPortHandler) { super.init(animator: animator, viewPortHandler: viewPortHandler); self.delegate = delegate; } public override func drawData(#context: CGContext) { var barData = delegate!.barChartRendererData(self); if (barData === nil) { return; } for (var i = 0; i < barData.dataSetCount; i++) { var set = barData.getDataSetByIndex(i); if (set !== nil && set!.isVisible) { drawDataSet(context: context, dataSet: set as! BarChartDataSet, index: i); } } } internal func drawDataSet(#context: CGContext, dataSet: BarChartDataSet, index: Int) { CGContextSaveGState(context); var barData = delegate!.barChartRendererData(self); var trans = delegate!.barChartRenderer(self, transformerForAxis: dataSet.axisDependency); var drawBarShadowEnabled: Bool = delegate!.barChartIsDrawBarShadowEnabled(self); var dataSetOffset = (barData.dataSetCount - 1); var groupSpace = barData.groupSpace; var groupSpaceHalf = groupSpace / 2.0; var barSpace = dataSet.barSpace; var barSpaceHalf = barSpace / 2.0; var containsStacks = dataSet.isStacked; var isInverted = delegate!.barChartIsInverted(self, axis: dataSet.axisDependency); var entries = dataSet.yVals as! [BarChartDataEntry]; var barWidth: CGFloat = 0.5; var phaseY = _animator.phaseY; var barRect = CGRect(); var barShadow = CGRect(); var y: Double; // do the drawing for (var j = 0, count = Int(ceil(CGFloat(dataSet.entryCount) * _animator.phaseX)); j < count; j++) { var e = entries[j]; // calculate the x-position, depending on datasetcount var x = CGFloat(e.xIndex + j * dataSetOffset) + CGFloat(index) + groupSpace * CGFloat(j) + groupSpaceHalf; var vals = e.values; if (!containsStacks || vals == nil) { y = e.value; var left = x - barWidth + barSpaceHalf; var right = x + barWidth - barSpaceHalf; var top = isInverted ? (y <= 0.0 ? CGFloat(y) : 0) : (y >= 0.0 ? CGFloat(y) : 0); var bottom = isInverted ? (y >= 0.0 ? CGFloat(y) : 0) : (y <= 0.0 ? CGFloat(y) : 0); // multiply the height of the rect with the phase if (top > 0) { top *= phaseY; } else { bottom *= phaseY; } barRect.origin.x = left; barRect.size.width = right - left; barRect.origin.y = top; barRect.size.height = bottom - top; trans.rectValueToPixel(&barRect); if (!viewPortHandler.isInBoundsLeft(barRect.origin.x + barRect.size.width)) { continue; } if (!viewPortHandler.isInBoundsRight(barRect.origin.x)) { break; } // if drawing the bar shadow is enabled if (drawBarShadowEnabled) { barShadow.origin.x = barRect.origin.x; barShadow.origin.y = viewPortHandler.contentTop; barShadow.size.width = barRect.size.width; barShadow.size.height = viewPortHandler.contentHeight; CGContextSetFillColorWithColor(context, dataSet.barShadowColor.CGColor); CGContextFillRect(context, barShadow); } // Set the color for the currently drawn value. If the index is out of bounds, reuse colors. CGContextSetFillColorWithColor(context, dataSet.colorAt(j).CGColor); CGContextFillRect(context, barRect); } else { var all = e.value; // if drawing the bar shadow is enabled if (drawBarShadowEnabled) { y = e.value; var left = x - barWidth + barSpaceHalf; var right = x + barWidth - barSpaceHalf; var top = isInverted ? (y <= 0.0 ? CGFloat(y) : 0) : (y >= 0.0 ? CGFloat(y) : 0); var bottom = isInverted ? (y >= 0.0 ? CGFloat(y) : 0) : (y <= 0.0 ? CGFloat(y) : 0); // multiply the height of the rect with the phase if (top > 0) { top *= phaseY; } else { bottom *= phaseY; } barRect.origin.x = left; barRect.size.width = right - left; barRect.origin.y = top; barRect.size.height = bottom - top; trans.rectValueToPixel(&barRect); barShadow.origin.x = barRect.origin.x; barShadow.origin.y = viewPortHandler.contentTop; barShadow.size.width = barRect.size.width; barShadow.size.height = viewPortHandler.contentHeight; CGContextSetFillColorWithColor(context, dataSet.barShadowColor.CGColor); CGContextFillRect(context, barShadow); } // fill the stack for (var k = 0; k < vals.count; k++) { all -= vals[k]; y = vals[k] + all; var left = x - barWidth + barSpaceHalf; var right = x + barWidth - barSpaceHalf; var top = y >= 0.0 ? CGFloat(y) : 0; var bottom = y <= 0.0 ? CGFloat(y) : 0; // multiply the height of the rect with the phase if (top > 0) { top *= phaseY; } else { bottom *= phaseY; } barRect.origin.x = left; barRect.size.width = right - left; barRect.origin.y = top; barRect.size.height = bottom - top; trans.rectValueToPixel(&barRect); if (k == 0 && !viewPortHandler.isInBoundsLeft(barRect.origin.x + barRect.size.width)) { // Skip to next bar break; } // avoid drawing outofbounds values if (!viewPortHandler.isInBoundsRight(barRect.origin.x)) { break; } // Set the color for the currently drawn value. If the index is out of bounds, reuse colors. CGContextSetFillColorWithColor(context, dataSet.colorAt(k).CGColor); CGContextFillRect(context, barRect); } } } CGContextRestoreGState(context); } /// Prepares a bar for being highlighted. internal func prepareBarHighlight(#x: CGFloat, y: Double, barspacehalf: CGFloat, from: Double, trans: ChartTransformer, inout rect: CGRect) { let barWidth: CGFloat = 0.5; var left = x - barWidth + barspacehalf; var right = x + barWidth - barspacehalf; var top = y >= from ? CGFloat(y) : CGFloat(from); var bottom = y <= from ? CGFloat(y) : CGFloat(from); rect.origin.x = left; rect.origin.y = top; rect.size.width = right - left; rect.size.height = bottom - top; trans.rectValueToPixel(&rect, phaseY: _animator.phaseY); } public override func drawValues(#context: CGContext) { // if values are drawn if (passesCheck()) { var barData = delegate!.barChartRendererData(self); var defaultValueFormatter = delegate!.barChartDefaultRendererValueFormatter(self); var dataSets = barData.dataSets; var drawValueAboveBar = delegate!.barChartIsDrawValueAboveBarEnabled(self); var drawValuesForWholeStackEnabled = delegate!.barChartIsDrawValuesForWholeStackEnabled(self); var valueTextHeight: CGFloat; var posOffset: CGFloat; var negOffset: CGFloat; for (var i = 0, count = barData.dataSetCount; i < count; i++) { var dataSet = dataSets[i]; if (!dataSet.isDrawValuesEnabled) { continue; } var isInverted = delegate!.barChartIsInverted(self, axis: dataSet.axisDependency); // calculate the correct offset depending on the draw position of the value let valueOffsetPlus: CGFloat = 5.0; var valueFont = dataSet.valueFont; var valueTextHeight = valueFont.lineHeight; posOffset = (drawValueAboveBar ? -(valueTextHeight + valueOffsetPlus) : valueOffsetPlus); negOffset = (drawValueAboveBar ? valueOffsetPlus : -(valueTextHeight + valueOffsetPlus)); if (isInverted) { posOffset = -posOffset - valueTextHeight; negOffset = -negOffset - valueTextHeight; } var valueTextColor = dataSet.valueTextColor; var formatter = dataSet.valueFormatter; if (formatter === nil) { formatter = defaultValueFormatter; } var trans = delegate!.barChartRenderer(self, transformerForAxis: dataSet.axisDependency); var entries = dataSet.yVals as! [BarChartDataEntry]; var valuePoints = getTransformedValues(trans: trans, entries: entries, dataSetIndex: i); // if only single values are drawn (sum) if (!drawValuesForWholeStackEnabled) { for (var j = 0, count = Int(ceil(CGFloat(valuePoints.count) * _animator.phaseX)); j < count; j++) { if (!viewPortHandler.isInBoundsRight(valuePoints[j].x)) { break; } if (!viewPortHandler.isInBoundsY(valuePoints[j].y) || !viewPortHandler.isInBoundsLeft(valuePoints[j].x)) { continue; } var val = entries[j].value; drawValue(context: context, value: formatter!.stringFromNumber(val)!, xPos: valuePoints[j].x, yPos: valuePoints[j].y + (val >= 0.0 ? posOffset : negOffset), font: valueFont, align: .Center, color: valueTextColor); } } else { // if each value of a potential stack should be drawn for (var j = 0, count = Int(ceil(CGFloat(valuePoints.count) * _animator.phaseX)); j < count; j++) { var e = entries[j]; var vals = e.values; // we still draw stacked bars, but there is one non-stacked in between if (vals == nil) { if (!viewPortHandler.isInBoundsRight(valuePoints[j].x)) { break; } if (!viewPortHandler.isInBoundsY(valuePoints[j].y) || !viewPortHandler.isInBoundsLeft(valuePoints[j].x)) { continue; } drawValue(context: context, value: formatter!.stringFromNumber(e.value)!, xPos: valuePoints[j].x, yPos: valuePoints[j].y + (e.value >= 0.0 ? posOffset : negOffset), font: valueFont, align: .Center, color: valueTextColor); } else { var transformed = [CGPoint](); var cnt = 0; var add = e.value; for (var k = 0; k < vals.count; k++) { add -= vals[cnt]; transformed.append(CGPoint(x: 0.0, y: (CGFloat(vals[cnt]) + CGFloat(add)) * _animator.phaseY)); cnt++; } trans.pointValuesToPixel(&transformed); for (var k = 0; k < transformed.count; k++) { var x = valuePoints[j].x; var y = transformed[k].y + (vals[k] >= 0 ? posOffset : negOffset); if (!viewPortHandler.isInBoundsRight(x)) { break; } if (!viewPortHandler.isInBoundsY(y) || !viewPortHandler.isInBoundsLeft(x)) { continue; } drawValue(context: context, value: formatter!.stringFromNumber(vals[k])!, xPos: x, yPos: y, font: valueFont, align: .Center, color: valueTextColor); } } } } } } } /// Draws a value at the specified x and y position. internal func drawValue(#context: CGContext, value: String, xPos: CGFloat, yPos: CGFloat, font: UIFont, align: NSTextAlignment, color: UIColor) { ChartUtils.drawText(context: context, text: value, point: CGPoint(x: xPos, y: yPos), align: align, attributes: [NSFontAttributeName: font, NSForegroundColorAttributeName: color]); } public override func drawExtras(#context: CGContext) { } private var _highlightArrowPtsBuffer = [CGPoint](count: 3, repeatedValue: CGPoint()); public override func drawHighlighted(#context: CGContext, indices: [ChartHighlight]) { var barData = delegate!.barChartRendererData(self); if (barData === nil) { return; } CGContextSaveGState(context); var setCount = barData.dataSetCount; var drawHighlightArrowEnabled = delegate!.barChartIsDrawHighlightArrowEnabled(self); var barRect = CGRect(); for (var i = 0; i < indices.count; i++) { var h = indices[i]; var index = h.xIndex; var dataSetIndex = h.dataSetIndex; var set = barData.getDataSetByIndex(dataSetIndex) as! BarChartDataSet!; if (set === nil || !set.highlightEnabled) { continue; } var barspaceHalf = set.barSpace / 2.0; var trans = delegate!.barChartRenderer(self, transformerForAxis: set.axisDependency); CGContextSetFillColorWithColor(context, set.highlightColor.CGColor); CGContextSetAlpha(context, set.highLightAlpha); // check outofbounds if (index < barData.yValCount && index >= 0 && CGFloat(index) < (CGFloat(delegate!.barChartRendererChartXMax(self)) * _animator.phaseX) / CGFloat(setCount)) { var e = barData.getDataSetByIndex(dataSetIndex)!.entryForXIndex(index) as! BarChartDataEntry!; if (e === nil) { continue; } var groupspace = barData.groupSpace; var isStack = h.stackIndex < 0 ? false : true; // calculate the correct x-position var x = CGFloat(index * setCount + dataSetIndex) + groupspace / 2.0 + groupspace * CGFloat(index); var y = isStack ? e.values[h.stackIndex] + e.getBelowSum(h.stackIndex) : e.value; // this is where the bar starts var from = isStack ? e.getBelowSum(h.stackIndex) : 0.0; prepareBarHighlight(x: x, y: y, barspacehalf: barspaceHalf, from: from, trans: trans, rect: &barRect); CGContextFillRect(context, barRect); if (drawHighlightArrowEnabled) { CGContextSetAlpha(context, 1.0); // distance between highlight arrow and bar var offsetY = _animator.phaseY * 0.07; CGContextSaveGState(context); var pixelToValueMatrix = trans.pixelToValueMatrix; var onePoint = CGPoint(x: 100.0, y: 100.0); onePoint.x = onePoint.x * sqrt(pixelToValueMatrix.a * pixelToValueMatrix.a + pixelToValueMatrix.c * pixelToValueMatrix.c); onePoint.y = onePoint.y * sqrt(pixelToValueMatrix.b * pixelToValueMatrix.b + pixelToValueMatrix.d * pixelToValueMatrix.d); var xToYRel = abs(onePoint.y / onePoint.x); var arrowWidth = set.barSpace / 2.0; var arrowHeight = arrowWidth * xToYRel; _highlightArrowPtsBuffer[0].x = CGFloat(x) + 0.4; _highlightArrowPtsBuffer[0].y = CGFloat(y) + offsetY; _highlightArrowPtsBuffer[1].x = CGFloat(x) + 0.4 + arrowWidth; _highlightArrowPtsBuffer[1].y = CGFloat(y) + offsetY - arrowHeight; _highlightArrowPtsBuffer[2].x = CGFloat(x) + 0.4 + arrowWidth; _highlightArrowPtsBuffer[2].y = CGFloat(y) + offsetY + arrowHeight; trans.pointValuesToPixel(&_highlightArrowPtsBuffer); CGContextBeginPath(context); CGContextMoveToPoint(context, _highlightArrowPtsBuffer[0].x, _highlightArrowPtsBuffer[0].y); CGContextAddLineToPoint(context, _highlightArrowPtsBuffer[1].x, _highlightArrowPtsBuffer[1].y); CGContextAddLineToPoint(context, _highlightArrowPtsBuffer[2].x, _highlightArrowPtsBuffer[2].y); CGContextClosePath(context); CGContextFillPath(context); CGContextRestoreGState(context); } } } CGContextRestoreGState(context); } public func getTransformedValues(#trans: ChartTransformer, entries: [BarChartDataEntry], dataSetIndex: Int) -> [CGPoint] { return trans.generateTransformedValuesBarChart(entries, dataSet: dataSetIndex, barData: delegate!.barChartRendererData(self)!, phaseY: _animator.phaseY); } internal func passesCheck() -> Bool { var barData = delegate!.barChartRendererData(self); if (barData === nil) { return false; } return CGFloat(barData.yValCount) < CGFloat(delegate!.barChartRendererMaxVisibleValueCount(self)) * viewPortHandler.scaleX; } }
apache-2.0
01ff7e087dbf5370af917eaece67d2a0
41.480944
187
0.477399
6.172468
false
false
false
false
AndyQ/C64Emulator
C64Emulator/Views/MonitorViewController.swift
1
2042
// // MonitorViewController.swift // C64Emulator // // Created by Andy Qua on 28/12/2021. // import UIKit extension UITextView { func scrollToBottom() { let textCount: Int = text.count guard textCount >= 1 else { return } scrollRangeToVisible(NSRange(location: textCount - 1, length: 1)) } } class MonitorViewController: UIViewController { @IBOutlet weak var txtOutput : UITextView! @IBOutlet weak var txtCommand : UITextField! override func viewDidLoad() { super.viewDidLoad() txtOutput.font = UIFont.monospacedSystemFont(ofSize: 16, weight: .regular) txtOutput.text = "" txtOutput.isEditable = false } @IBAction func activateMonitorPressed( _ sender : Any ) { theVICEMachine.machineController().activateMonitor() txtOutput.text = "" } @IBAction func sendCommandPressed( _ sender : Any ) { guard let line = txtCommand.text else { return } theVICEMachine.submitLineInput(line) setOutput( "\(line)\n" ) (self.parent as!EmulatorViewController).viceView().becomeFirstResponder() } func startMonitor() { theVICEMachine.machineController().activateMonitor() txtCommand.becomeFirstResponder() } func stopMonitor() { theVICEMachine.submitLineInput("x") txtCommand.resignFirstResponder() } func showPrompt( _ prompt : String ) { if txtOutput.text != "" { setOutput( "\n" ) } setOutput( "\(prompt)" ) txtCommand.becomeFirstResponder() } func setOutput( _ text: String ) { txtOutput.text += text txtOutput.scrollToBottom() } } extension MonitorViewController : UITextFieldDelegate { func textFieldDidBeginEditing(_ textField: UITextField) { txtCommand.selectAll(nil) } func textFieldShouldReturn(_ textField: UITextField) -> Bool { sendCommandPressed( textField ) return false } }
gpl-2.0
416eebea274c47cd691c5d1349c50ecc
25.179487
82
0.625857
4.896882
false
false
false
false
dukehealth/DukeCore-iOS
HealthKit/HKQuantitySample+Utility.swift
1
2148
// // HKQuantitySample+Utility.swift // DukeCore-iOS // // Created by Mike Revoir on 3/2/16. // Copyright © 2016 Duke Institute for Health Innovation. All rights reserved. // import Foundation import HealthKit extension HKQuantitySample { /** * Returns the count unit value for an `HKQuantitySample`. * This method assumes that the default unit type was used when constructing the sample. */ func countValue() -> Double { let unit = HKUnit.defaultCountUnit() return self.quantity.doubleValueForUnit(unit) } /** * Returns the energy unit value for an `HKQuantitySample`. * This method assumes that the default unit type was used when constructing the sample. */ func energyValue() -> Double { let unit = HKUnit.defaultEnergyUnit() return self.quantity.doubleValueForUnit(unit) } /** * Returns the length unit value for an `HKQuantitySample`. * This method assumes that the default unit type was used when constructing the sample. */ func lengthValue() -> Double { let unit = HKUnit.defaultLengthUnit() return self.quantity.doubleValueForUnit(unit) } /** * Returns the mass unit value for an `HKQuantitySample`. * This method assumes that the default unit type was used when constructing the sample. */ func massValue() -> Double { let unit = HKUnit.defaultMassUnit() return self.quantity.doubleValueForUnit(unit) } /** * Returns the time unit value for an `HKQuantitySample`. * This method assumes that the default unit type was used when constructing the sample. */ func timeValue() -> Double { let unit = HKUnit.defaultTimeUnit() return self.quantity.doubleValueForUnit(unit) } /** * Returns the count/time unit value for an `HKQuantitySample`. * This method assumes that the default unit type was used when constructing the sample. */ func countsPerTimeValue() -> Double { let unit = HKUnit.defaultCountsPerTimeUnit() return self.quantity.doubleValueForUnit(unit) } }
bsd-3-clause
1cf48e4d5d8b16b839004488057966b1
31.530303
92
0.666977
4.781737
false
false
false
false
ivygulch/IVGRouter
IVGRouterTests/tests/presenters/RootRouteSegmentPresenterSpec.swift
1
2510
// // RootRouteSegmentPresenterSpec.swift // IVGRouter // // Created by Douglas Sjoquist on 4/6/16. // Copyright © 2016 Ivy Gulch LLC. All rights reserved. // import UIKit import Quick import Nimble import IVGRouter class RootRouteSegmentPresenterSpec: QuickSpec { override func spec() { let mockViewControllerA = MockViewController("A") let mockViewControllerB = MockViewController("B") var mockWindow: MockWindow! var mockCompletionBlock: MockCompletionBlock! beforeEach { mockWindow = MockWindow() mockCompletionBlock = MockCompletionBlock() } describe("class definition") { it("should have default identifier") { expect(RootRouteSegmentPresenter.defaultPresenterIdentifier).to(equal(Identifier(name: String(describing: RootRouteSegmentPresenter.self)))) } } describe("presentViewController") { it("should fail when window is nil") { let presenter = RootRouteSegmentPresenter() presenter.present(viewController: mockViewControllerB, from: nil, options: [: ], window: nil, completion: mockCompletionBlock.completion) expect(mockCompletionBlock.trackerKeyValuesDifferences(["completion": [["false","nil"]]])).to(beEmpty()) } it("should fail when presentingViewController is not nil") { let presenter = RootRouteSegmentPresenter() presenter.present(viewController: mockViewControllerB, from: mockViewControllerA, options: [: ], window: mockWindow, completion: mockCompletionBlock.completion) expect(mockCompletionBlock.trackerKeyValuesDifferences(["completion": [["false","nil"]]])).to(beEmpty()) expect(mockWindow.trackerKeyValues).to(beEmpty()) } it("should pass when window is not nil") { let presenter = RootRouteSegmentPresenter() presenter.present(viewController: mockViewControllerB, from: nil, options: [: ], window: mockWindow, completion: mockCompletionBlock.completion) expect(mockCompletionBlock.trackerKeyValuesDifferences(["completion": [["true",String(describing: mockViewControllerB)]]])).to(beEmpty()) expect(mockWindow.trackerKeyValuesDifferences(["makeKeyAndVisible": [[]],"setRootViewController": [[mockViewControllerB.description]]])).to(beEmpty()) } } } }
mit
baf9e3b0bf2ed5610a2d4c70d19a3cfa
39.467742
176
0.656835
5.676471
false
false
false
false
SlaunchaMan/Advent-of-Code-2016
Advent of Code 2016 Day 3.playground/Contents.swift
1
1679
import Foundation func validTriangle(a: Int, b: Int, c: Int) -> Bool { return (a + b > c && a + c > b && b + c > a) } validTriangle(a: 5, b: 10, c: 25) guard let input = try? String(contentsOf: #fileLiteral(resourceName: "4 21 894.txt")) else { fatalError() } // Part 1 var part1Count = 0 input.enumerateLines { (line, _) in let numbers = line .components(separatedBy: CharacterSet.whitespaces) .filter { component in component.rangeOfCharacter(from: CharacterSet.whitespaces.inverted) != nil } .flatMap { Int($0) } guard numbers.count == 3 else { return } if validTriangle(a: numbers[0], b: numbers[1], c: numbers[2]) { part1Count += 1 } } part1Count // Part 2 var part2Count = 0 var lineBuffer: [String] = [] input.enumerateLines { (line, _) in lineBuffer.append(line) if (lineBuffer.count == 3) { defer { lineBuffer.removeAll() } let numbers = lineBuffer.map { $0.components(separatedBy: CharacterSet.whitespaces) .filter { component in component.rangeOfCharacter(from: CharacterSet.whitespaces.inverted) != nil } .flatMap { Int($0) } } for i in 0 ..< 3 { if validTriangle(a: numbers[0][i], b: numbers[1][i], c: numbers[2][i]) { part2Count += 1 } } } } part2Count
mit
5578e06ebdacadd2bc3363db760a2c42
22.647887
98
0.479452
4.229219
false
false
false
false
abeintopalo/AppIconSetGen
Sources/AppIconSetGenCore/NSImage+Extensions.swift
1
1477
// // NSImage+Extensions.swift // AppIconSetGenCore // // Created by Attila Bencze on 11/05/2017. // // import Cocoa import Foundation extension NSImage { func imagePNGRepresentation(widthInPixels: CGFloat, heightInPixels: CGFloat) -> NSData? { let imageRep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: Int(widthInPixels), pixelsHigh: Int(heightInPixels), bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: NSColorSpaceName.calibratedRGB, bytesPerRow: 0, bitsPerPixel: 0) imageRep?.size = NSMakeSize(widthInPixels, heightInPixels) NSGraphicsContext.saveGraphicsState() NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep: imageRep!) draw(in: NSMakeRect(0, 0, widthInPixels, heightInPixels), from: NSZeroRect, operation: .copy, fraction: 1.0) NSGraphicsContext.restoreGraphicsState() let imageProps: [NSBitmapImageRep.PropertyKey: Any] = [:] let imageData = imageRep?.representation(using: NSBitmapImageRep.FileType.png, properties: imageProps) as NSData? return imageData } }
mit
02ac952b674a75fa3a7f6bb9e92506e4
41.2
121
0.558565
6.004065
false
false
false
false
ehtd/HackerNews
Hackyto/hackytoTests/FetcherTests.swift
1
1511
// // FetcherTests.swift // Hackyto // // Created by Ernesto Torres on 5/28/17. // Copyright © 2017 ehtd. All rights reserved. // import XCTest import Hermes class FetcherTests: XCTestCase { fileprivate let apiEndPoint = "https://hacker-news.firebaseio.com/v0/" fileprivate let session = URLSession(configuration: URLSessionConfiguration.default) fileprivate var fetcher: ListFetcher? fileprivate var itemFetcher: ItemFetcher? fileprivate let topStories = "topstories.json" fileprivate let storyId = "10483024" override func setUp() { super.setUp() fetcher = ListFetcher(with: session, apiEndPoint: apiEndPoint) itemFetcher = ItemFetcher(with: session, apiEndPoint: apiEndPoint) } func testFetchingIDList() { let exp = expectation(description: "Fetch Top Stories List") fetcher?.fetch(topStories, success: { (response) in print(response) exp.fulfill() }, error: { (_) in XCTFail() }) waitForExpectations(timeout: 3.0) { (error) in XCTAssertNil(error) } } func testFetchItem() { let exp = expectation(description: "Fetch item") itemFetcher?.fetch( "item/\(storyId).json", success: { (response) in print(response) exp.fulfill() }, error: { (_) in XCTFail() }) waitForExpectations(timeout: 3.0) { (error) in XCTAssertNil(error) } } }
gpl-3.0
40e4462259cf1183b739330bc61570f3
25.491228
88
0.611258
4.415205
false
true
false
false
jinseokpark6/u-team
Code/Controllers/TeamNotificationVC.swift
1
5033
// // TeamNotificationVC.swift // // // Created by Jin Seok Park on 2015. 9. 3.. // // import UIKit class TeamNotificationVC: UIViewController, UITableViewDelegate, UITableViewDataSource { var announcements = [PFObject]() @IBOutlet weak var resultsTable: UITableView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func viewDidAppear(animated: Bool) { announcements.removeAll(keepCapacity: false) self.fetchInfo() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! teamNotificationCell let name = self.announcements[indexPath.row].objectForKey("name") as! String let title = self.announcements[indexPath.row].objectForKey("title") as! String let date = self.announcements[indexPath.row].objectForKey("date") as! NSDate let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "EEE, MMM d, h:mm a" let selectedDate = dateFormatter.stringFromDate(date) let color1 = UIColor(red: 174/256.0, green: 187/256.0, blue: 199/256.0, alpha: 0.5) let color2 = UIColor(red: 155/256.0, green: 175/256.0, blue: 142/256.0, alpha: 0.5) let color3 = UIColor(red: 219/256.0, green: 173/256.0, blue: 114/256.0, alpha: 0.5) if self.announcements[indexPath.row].objectForKey("type") as! String == "Add Event" { cell.descriptionLabel.text = "New Event: '\(title)'" + "\n" + "by \(name)" cell.backgroundColor = color1 print(color1) } else if self.announcements[indexPath.row].objectForKey("type") as! String == "Update Event" { cell.descriptionLabel.text = "Update: '\(title)'" + "\n" + "by \(name)" cell.backgroundColor = color2 } else if self.announcements[indexPath.row].objectForKey("type") as! String == "Add Note" { cell.descriptionLabel.text = "New Note: '\(title)'" + "\n" + "by \(name)" cell.backgroundColor = color3 } let dateFormatter1 = NSDateFormatter() dateFormatter1.dateStyle = NSDateFormatterStyle.ShortStyle dateFormatter1.timeStyle = NSDateFormatterStyle.ShortStyle let date1 = dateFormatter1.stringFromDate(self.announcements[indexPath.row].createdAt!) cell.timeLabel.text = date1 return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) let query = PFQuery(className:"Schedule") query.whereKey("objectId", equalTo: self.announcements[indexPath.row].objectForKey("eventId")!) query.getFirstObjectInBackgroundWithBlock { (object, error) -> Void in if object != nil { selectedEvent.removeAll(keepCapacity: false) selectedEvent.append(object!) let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle()) let controller = storyboard.instantiateViewControllerWithIdentifier("ExistingEventViewController") as! ExistingEventViewController let nav = UINavigationController(rootViewController: controller) self.presentViewController(nav, animated: true, completion: nil) } else { let infoAlert = UIAlertController(title: "Notification", message: "The selected event does not exist anymore", preferredStyle: UIAlertControllerStyle.Alert) infoAlert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { (action:UIAlertAction!) -> Void in })) self.presentViewController(infoAlert, animated: true, completion: nil) } } } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { // return UITableViewAutomaticDimension return 90 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.announcements.count } func fetchInfo() { let query = PFQuery(className:"Team_Announcement") query.whereKey("teamId", equalTo:selectedTeamId) query.addDescendingOrder("createdAt") query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in if error == nil { for object in objects! { self.announcements.append(object as! PFObject) } self.resultsTable.reloadData() } } } @IBAction func cancelBtn_click(sender: AnyObject) { self.dismissViewControllerAnimated(true, completion: nil) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
apache-2.0
3a0d60b9a7f3d2a7d1604acb0ccc5d82
31.262821
160
0.703358
4.323883
false
false
false
false
tgyhlsb/RxSwiftExt
Tests/RxSwift/ignoreErrorsTests.swift
2
4958
// // ignoreErrorsTests.swift // RxSwiftExtDemo // // Created by Florent Pillet on 18/05/16. // Copyright © 2016 RxSwift Community. All rights reserved. // import XCTest import RxSwift import RxSwiftExt import RxTest // credits: // tests for ignoreErrors() are the tests for retry() retargeted to the ignoreErrors() operator // tests for ignoreWhen() are the tests for retry(count) adapted to the ignoreWhen() operator class IgnoreErrorsTests: XCTestCase { let testError = NSError(domain: "dummyError", code: -232, userInfo: nil) func testIgnoreErrors_Basic() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createColdObservable([ next(100, 1), next(150, 2), next(200, 3), completed(250) ]) let res = scheduler.start { xs.ignoreErrors() } XCTAssertEqual(res.events, [ next(300, 1), next(350, 2), next(400, 3), completed(450) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 450) ]) } func testIgnoreErrors_Infinite() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createColdObservable([ next(100, 1), next(150, 2), next(200, 3), ]) let res = scheduler.start { xs.ignoreErrors() } XCTAssertEqual(res.events, [ next(300, 1), next(350, 2), next(400, 3), ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 1000) ]) } func testIgnoreErrors_Observable_Error() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createColdObservable([ next(100, 1), next(150, 2), next(200, 3), error(250, testError), ]) let res = scheduler.start(1100) { xs.ignoreErrors() } XCTAssertEqual(res.events, [ next(300, 1), next(350, 2), next(400, 3), next(550, 1), next(600, 2), next(650, 3), next(800, 1), next(850, 2), next(900, 3), next(1050, 1) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 450), Subscription(450, 700), Subscription(700, 950), Subscription(950, 1100) ]) } func testIgnoreErrors_PredicateBasic() { let scheduler = TestScheduler(initialClock: 0) var counter = 0 let xs = scheduler.createColdObservable([ next(5, 1), next(10, 2), next(15, 3), error(20, testError) ]) let res = scheduler.start { xs.ignoreErrors { error -> Bool in counter += 1 return counter < 3 } } XCTAssertEqual(res.events, [ next(205, 1), next(210, 2), next(215, 3), next(225, 1), next(230, 2), next(235, 3), next(245, 1), next(250, 2), next(255, 3), error(260, testError) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 220), Subscription(220, 240), Subscription(240, 260) ]) } func testIgnoreErrors_PredicateInfinite() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createColdObservable([ next(5, 1), next(10, 2), next(15, 3), error(20, testError) ]) let res = scheduler.start(231) { xs.ignoreErrors { error -> Bool in return true } } XCTAssertEqual(res.events, [ next(205, 1), next(210, 2), next(215, 3), next(225, 1), next(230, 2), ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 220), Subscription(220, 231), ]) } func testIgnoreErrors_PredicateCompleted() { let scheduler = TestScheduler(initialClock: 0) let xs = scheduler.createColdObservable([ next(100, 1), next(150, 2), next(200, 3), completed(250) ]) let res = scheduler.start { xs.ignoreErrors { error -> Bool in return true } } XCTAssertEqual(res.events, [ next(300, 1), next(350, 2), next(400, 3), completed(450) ]) XCTAssertEqual(xs.subscriptions, [ Subscription(200, 450), ]) } }
mit
9490e4813913f5e86e507cc9dd94ec4a
23.539604
95
0.478919
4.658835
false
true
false
false
vapor/node
Sources/Node/Convertibles/Date+Convertible.swift
1
3979
import Foundation extension Date: NodeConvertible { internal static let lock = NSLock() /** If a date receives a numbered node, it will use this closure to convert that number into a Date as a timestamp By default, this timestamp uses seconds via timeIntervalSince1970. Override for custom implementations */ public static var incomingTimestamp: (Node.Number) throws -> Date = { return Date(timeIntervalSince1970: $0.double) } /** In default scenarios where a timestamp should be represented as a Number, this closure will be used. By default, uses seconds via timeIntervalSince1970. Override for custom implementations. */ public static var outgoingTimestamp: (Date) throws -> Node.Number = { return Node.Number($0.timeIntervalSince1970) } /** A prioritized list of date formatters to use when attempting to parse a String into a Date. Override for custom implementations, or to remove supported formats */ public static var incomingDateFormatters: [DateFormatter] = [ .iso8601, .mysql, .rfc1123 ] /** A default formatter to use when serializing a Date object to a String. Defaults to ISO 8601 Override for custom implementations. For complex scenarios where various string representations must be used, the user is responsible for handling their date formatting manually. */ public static var outgoingDateFormatter: DateFormatter = .iso8601 /** Initializes a Date object with another Node.date, a number representing a timestamp, or a formatted date string corresponding to one of the `incomingDateFormatters`. */ public init(node: Node) throws { switch node.wrapped { case let .date(date): self = date case let .number(number): self = try Date.incomingTimestamp(number) case let .string(string): Date.lock.lock() defer { Date.lock.unlock() } guard let date = Date.incomingDateFormatters .lazy .flatMap({ $0.date(from: string) }) .first else { fallthrough } self = date default: throw NodeError.unableToConvert( input: node, expectation: "\(Date.self), formatted time string, or timestamp", path: [] ) } } /// Creates a node representation of the date public func makeNode(in context: Context?) throws -> Node { return .date(self, in: context) } } extension StructuredData { public var date: Date? { return try? Date(node: self, in: nil) } } extension DateFormatter { /** ISO8601 Date Formatter -- preferred in JSON http://stackoverflow.com/a/28016692/2611971 */ @nonobjc public static let iso8601: DateFormatter = { let formatter = DateFormatter() formatter.locale = Locale(identifier: "en_US_POSIX") formatter.timeZone = TimeZone(secondsFromGMT: 0) formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX" return formatter }() } extension DateFormatter { /** A date formatter for mysql formatted types */ @nonobjc public static let mysql: DateFormatter = { let formatter = DateFormatter() formatter.timeZone = TimeZone(secondsFromGMT: 0) formatter.dateFormat = "yyyy-MM-dd HH:mm:ss" return formatter }() } extension DateFormatter { /** A date formatter conforming to RFC 1123 spec */ @nonobjc public static let rfc1123: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss z" return formatter }() }
mit
f6203330a3958abdbaecbbbcab54060a
29.143939
92
0.60769
5.030341
false
false
false
false
0x51/PrettyText
Example/Tests/Tests.swift
1
1177
// https://github.com/Quick/Quick import Quick import Nimble import PrettyText class TableOfContentsSpec: QuickSpec { override func spec() { describe("these will fail") { it("can do maths") { expect(1) == 2 } it("can read") { expect("number") == "string" } it("will eventually fail") { expect("time").toEventually( equal("done") ) } context("these will pass") { it("can do maths") { expect(23) == 23 } it("can read") { expect("🐮") == "🐮" } it("will eventually pass") { var time = "passing" dispatch_async(dispatch_get_main_queue()) { time = "done" } waitUntil { done in NSThread.sleepForTimeInterval(0.5) expect(time) == "done" done() } } } } } }
mit
3748f13b9cd84aec62331ebe57c2fa70
22.42
63
0.363792
5.471963
false
false
false
false
jacksonic/vjlofvhjfgm
swift_src/FOAMSupport.swift
3
19039
/** * @license * Copyright 2017 The FOAM Authors. All Rights Reserved. * http://www.apache.org/licenses/LICENSE-2.0 */ import Foundation public typealias Listener = (Subscription, [Any?]) -> Void public typealias MethodSlotClosure = ([Any?]) throws -> Any? public protocol ContextAware { var __context__: Context { get set } var __subContext__: Context { get } } public protocol Axiom { var name: String { get } } public protocol GetterAxiom { func get(_ obj: foam_core_FObject?) -> Any? } public protocol SetterAxiom { func set(_ obj: foam_core_FObject?, value: Any?) } public protocol SlotGetterAxiom { func getSlot(_ obj: foam_core_FObject?) -> foam_swift_core_Slot? } public protocol SlotSetterAxiom { func setSlot(_ obj: foam_core_FObject?, value: foam_swift_core_Slot?) } class ListenerList { var next: ListenerList? var prev: ListenerList? lazy var children: [String:ListenerList] = [:] var listener: Listener? var sub: Subscription? } public protocol PropertyInfo: Axiom, SlotGetterAxiom, SlotSetterAxiom, GetterAxiom, SetterAxiom, foam_mlang_Expr, foam_mlang_order_Comparator { var classInfo: ClassInfo { get } var transient: Bool { get } var storageTransient: Bool { get } var networkTransient: Bool { get } var label: String { get } var visibility: foam_u2_Visibility { get } var jsonParser: foam_swift_parse_parser_Parser? { get } func viewFactory(x: Context) -> foam_core_FObject? func hasOwnProperty(_ o: foam_core_FObject?) -> Bool func clearProperty(_ o: foam_core_FObject?) func toJSON(outputter: foam_swift_parse_json_output_Outputter?, out: foam_json2_Outputter?, value: Any?) } extension PropertyInfo { public func f(_ obj: Any?) -> Any? { if let obj = obj as? foam_core_FObject { return get(obj) } return nil } func `partialEval`() -> foam_mlang_Expr? { return self } func `compare`(_ o1: Any?, _ o2: Any?) -> Int { guard let fo1 = o1 as? foam_core_FObject, let fo2 = o2 as? foam_core_FObject else { return FOAM_utils.compare(o1, o2) } return FOAM_utils.compare(get(fo1), get(fo2)) } public func createStatement() -> String? { return "" } public func prepareStatement(_ stmt: Any?) { } } public protocol JSONOutputter { func toJSON(outputter: foam_swift_parse_json_output_Outputter?, out: foam_json2_Outputter?) } public class MethodArg { public var name: String = "" } public protocol MethodInfo: Axiom, GetterAxiom, SlotGetterAxiom { var args: [MethodArg] { get } } extension MethodInfo { public func call(_ obj: foam_core_FObject?, args: [Any?] = []) throws -> Any? { let callback = obj!.getSlot(key: name)!.swiftGet() as! ([Any?]) throws -> Any? return try callback(args) } public func get(_ obj: foam_core_FObject?) -> Any? { return obj?.getSlot(key: name)!.swiftGet() } } public protocol ActionInfo: MethodInfo { var label: String { get } } public class Context { public static let GLOBAL: Context = { let x = Context() FOAM_utils.registerClasses(x) return x }() var parent: Context? private lazy var classIdMap: [String:ClassInfo] = [:] private lazy var classNameMap: [String:String] = [:] public func registerClass(cls: ClassInfo) { classIdMap[cls.id] = cls classNameMap[NSStringFromClass(cls.cls)] = cls.id _ = cls.ownAxioms } public func lookup(_ id: String?) -> ClassInfo? { return classIdMap[id!] ?? parent?.lookup(id) } func lookup_(_ cls: AnyClass) -> ClassInfo? { let str = NSStringFromClass(cls) if let id = classNameMap[str] { return lookup(id) } return parent?.lookup_(cls) } public func create<T>(_ type: T.Type, args: [String:Any?] = [:]) -> T? { if let type = type as? AnyClass, let cls = lookup_(type) { return cls.create(args: args, x: self) as? T } return nil } private var slotMap: [String:foam_swift_core_Slot] = [:] public subscript(key: String) -> Any? { if let slot = slotMap[key] { return slot } else if let slot = slotMap[toSlotName(name: key)] { return slot.swiftGet() } return parent?[key] } private func toSlotName(name: String) -> String { return name + "$" } public func createSubContext(args: [String:Any?] = [:]) -> Context { var slotMap: [String:foam_swift_core_Slot] = [:] for (key, value) in args { let slotName = toSlotName(name: key) if let slot = value as AnyObject as? foam_swift_core_Slot { slotMap[slotName] = slot } else { slotMap[slotName] = foam_swift_core_ConstantSlot(["value": value]) } } let subContext = Context() subContext.slotMap = slotMap subContext.parent = self return subContext } } public protocol ClassInfo { var id: String { get } var label: String { get } var parent: ClassInfo? { get } var ownAxioms: [Axiom] { get } var cls: AnyClass { get } var axioms: [Axiom] { get } func axiom(byName name: String) -> Axiom? func create(args: [String:Any?], x: Context) -> Any func instanceOf(_ o: Any?) -> Bool } extension ClassInfo { func create() -> Any { return create(args: [:], x: Context.GLOBAL) } func create(x: Context) -> Any { return create(args: [:], x: x) } func create(args: [String:Any?]) -> Any { return create(args: args, x: Context.GLOBAL) } func ownAxioms<T>(byType type: T.Type) -> [T] { var axs: [T] = [] for axiom in ownAxioms { if let axiom = axiom as? T { axs.append(axiom) } } return axs } func axioms<T>(byType type: T.Type) -> [T] { var axs: [T] = [] for axiom in axioms { if let axiom = axiom as? T { axs.append(axiom) } } return axs } } public class Subscription: foam_core_Detachable { private var detach_: (() -> Void)? init(detach: @escaping () ->Void) { self.detach_ = detach } public func detach() { detach_?() detach_ = nil } } public protocol foam_core_FObject: foam_core_Detachable, Topic, JSONOutputter { func ownClassInfo() -> ClassInfo func set(key: String, value: Any?) func get(key: String) -> Any? func getSlot(key: String) -> foam_swift_core_Slot? func hasOwnProperty(_ key: String) -> Bool func clearProperty(_ key: String) func compareTo(_ data: foam_core_FObject?) -> Int func onDetach(_ sub: foam_core_Detachable?) func toString() -> String func copyFrom(_ o: foam_core_FObject) init(_ args: [String:Any?]) } public class AbstractFObject: NSObject, foam_core_FObject, ContextAware { public var __context__: Context = Context.GLOBAL private var ___subContext___: Context! public var __subContext__: Context { get { return self.___subContext___ } } func _createExports_() -> [String:Any?] { return [:] } lazy var listeners: ListenerList = ListenerList() lazy var __foamInit__$: foam_swift_core_Slot = { return foam_swift_core_ConstantSlot([ "value": { [weak self] (args: [Any?]) throws -> Any? in if self == nil { fatalError() } return self!.__foamInit__() } ]) }() public class func classInfo() -> ClassInfo { fatalError() } public func ownClassInfo() -> ClassInfo { fatalError() } public func set(key: String, value: Any?) { if key.last == "$" && value is foam_swift_core_Slot { let slot = String(key[..<(key.index(before: key.endIndex))]) (self.ownClassInfo().axiom(byName: slot) as? SlotSetterAxiom)?.setSlot(self, value: value as? foam_swift_core_Slot) } else { (self.ownClassInfo().axiom(byName: key) as? SetterAxiom)?.set(self, value: value) } } public func get(key: String) -> Any? { return (self.ownClassInfo().axiom(byName: key) as? GetterAxiom)?.get(self) ?? nil } public func getSlot(key: String) -> foam_swift_core_Slot? { return (self.ownClassInfo().axiom(byName: key) as? SlotGetterAxiom)?.getSlot(self) ?? nil } public func hasOwnProperty(_ key: String) -> Bool { return (self.ownClassInfo().axiom(byName: key) as? PropertyInfo)?.hasOwnProperty(self) ?? false } public func clearProperty(_ key: String) { (self.ownClassInfo().axiom(byName: key) as? PropertyInfo)?.clearProperty(self) } public func onDetach(_ sub: foam_core_Detachable?) { guard let sub = sub else { return } _ = self.sub(topics: ["detach"]) { (s, _) in s.detach() sub.detach() } } public func detach() { _ = pub(["detach"]) detachListeners(listeners: listeners) } public func sub( topics: [String] = [], listener l: @escaping Listener) -> Subscription { var listeners = self.listeners for topic in topics { if listeners.children[topic] == nil { listeners.children[topic] = ListenerList() } listeners = listeners.children[topic]! } let node = ListenerList() node.next = listeners.next node.prev = listeners node.listener = l node.sub = Subscription(detach: { node.next?.prev = node.prev node.prev?.next = node.next node.listener = nil node.next = nil node.prev = nil node.sub = nil }) listeners.next?.prev = node listeners.next = node return node.sub! } public func hasListeners(_ args: [Any]) -> Bool { var listeners: ListenerList? = self.listeners var i = 0 while listeners != nil { if listeners?.next != nil { return true } if i == args.count { return false } if let p = args[i] as? String { listeners = listeners?.children[p] i += 1 } else { break } } return false } private func notify(listeners: ListenerList?, args: [Any?]) -> Int { var count = 0 var l = listeners while l != nil { let listener = l!.listener! let sub = l!.sub! l = l!.next listener(sub, args) count += 1 } return count } public func pub(_ args: [Any?]) -> Int { var listeners: ListenerList = self.listeners var count = notify(listeners: listeners.next, args: args) for arg in args { guard let key = arg as? String else { break } if listeners.children[key] == nil { break } listeners = listeners.children[key]! count += notify(listeners: listeners.next, args: args) } return count } public func compareTo(_ data: foam_core_FObject?) -> Int { if self === data { return 0 } if data == nil { return 1 } let data = data! if ownClassInfo().id != data.ownClassInfo().id { return ownClassInfo().id > data.ownClassInfo().id ? 1 : -1 } for props in data.ownClassInfo().axioms(byType: PropertyInfo.self) { let diff = props.compare(self, data) if diff != 0 { return diff } } return 0 } public override required init() { super.init() ___subContext___ = __context__.createSubContext(args: self._createExports_()) __foamInit__() } public required init(_ args: [String:Any?]) { super.init() ___subContext___ = __context__.createSubContext(args: self._createExports_()) for (key, value) in args { self.set(key: key, value: value) } __foamInit__() } public required init(X x: Context) { super.init() __context__ = x ___subContext___ = __context__.createSubContext(args: self._createExports_()) __foamInit__() } public required init(_ args: [String:Any?], _ x: Context) { super.init() __context__ = x ___subContext___ = __context__.createSubContext(args: self._createExports_()) for (key, value) in args { self.set(key: key, value: value) } __foamInit__() } func __foamInit__() {} private func detachListeners(listeners: ListenerList?) { var l = listeners while l != nil { l!.sub?.detach() for child in l!.children.values { detachListeners(listeners: child) } l = l!.next } } deinit { detach() } public func toString() -> String { return foam_swift_parse_json_output_Outputter.DEFAULT.swiftStringify(self)! } public func copyFrom(_ o: foam_core_FObject) { if ownClassInfo().id == o.ownClassInfo().id { ownClassInfo().axioms(byType: PropertyInfo.self).forEach { (p) in if o.hasOwnProperty(p.name) { p.set(self, value: p.get(o)) } } } else { ownClassInfo().axioms(byType: PropertyInfo.self).forEach { (p) in if let p2 = o.ownClassInfo().axiom(byName: p.name) as? PropertyInfo { p.set(self, value: p2.get(o)) } } } } public override func isEqual(_ object: Any?) -> Bool { if let o = object as? foam_core_FObject { return compareTo(o) == 0 } return super.isEqual(object) } public func toJSON(outputter: foam_swift_parse_json_output_Outputter?, out: foam_json2_Outputter?) { outputter?.outputFObject(out, self) } } struct FOAM_utils { public static func equals(_ o1: Any?, _ o2: Any?) -> Bool { return FOAM_utils.compare(o1, o2) == 0 } public static func compare(_ o1: Any?, _ o2: Any?) -> Int { return foam_swift_type_Util().compare(o1, o2) } } public class Reference<T> { var value: T init(value: T) { self.value = value } } extension String { func char(at: Int) -> Character { return self[index(startIndex, offsetBy: at)] } func index(of: Character) -> Int { if let r = range(of: of.description) { return distance(from: startIndex, to: r.lowerBound) } return -1 } } extension Character { func isDigit() -> Bool { return "0"..."9" ~= self } } public class ModelParserFactory { private static var parsers: [String:foam_swift_parse_parser_Parser] = [:] public static func getInstance(_ cls: ClassInfo) -> foam_swift_parse_parser_Parser { if let p = parsers[cls.id] { return p } let parser = buildInstance(cls) parsers[cls.id] = parser return parser } private static func buildInstance(_ info: ClassInfo) -> foam_swift_parse_parser_Parser { var parsers = [foam_swift_parse_parser_Parser]() for p in info.axioms(byType: PropertyInfo.self) { if p.jsonParser != nil { parsers.append(foam_swift_parse_json_PropertyParser(["property": p])) } } parsers.append(foam_swift_parse_json_UnknownPropertyParser()) return foam_swift_parse_parser_Repeat0([ "delegate": foam_swift_parse_parser_Seq0(["parsers": [ foam_swift_parse_json_Whitespace(), foam_swift_parse_parser_Alt(["parsers": parsers]) ]]), "delim": foam_swift_parse_parser_Literal(["string": ","]), ]) } } public class FoamError: Error { var obj: Any? init(_ obj: Any?) { self.obj = obj } public func toString() -> String { if let obj = self.obj as? foam_core_FObject { return foam_swift_parse_json_output_Outputter.DEFAULT.swiftStringify(obj)! } else if let obj = self.obj as? FoamError { return "FoamError(" + obj.toString() + ")" } return String(describing: self.obj as AnyObject) } } public typealias AFunc = (@escaping (Any?) -> Void, @escaping (Any?) -> Void, Any?) -> Void public struct Async { public static func aPar(_ funcs: [AFunc]) -> AFunc { return { (aRet: @escaping (Any?) -> Void, aThrow: @escaping (Any?) -> Void, args: Any?) in var numCompleted = 0 var returnValues = Array<Any?>(repeating: nil, count: funcs.count) for i in 0...funcs.count-1 { returnValues[i] = 0 let f = funcs[i] f({ data in if let data = data as Any? { returnValues[i] = data } numCompleted += 1 if numCompleted == funcs.count { aRet(returnValues) } }, aThrow, args) } } } public static func aSeq(_ funcs: [AFunc]) -> AFunc { return { (aRet: @escaping (Any?) -> Void, aThrow: @escaping (Any?) -> Void, args: Any?) in var i = 0 var next: ((Any?) -> Void)! next = { d in let f = funcs[i] f({ d2 in i += 1 if i == funcs.count { aRet(d2) } else { next(d2) } }, aThrow, d) } next(args) } } public static func aWhile(_ cond: @escaping () -> Bool, afunc: @escaping AFunc) -> AFunc { return { (aRet: @escaping (Any?) -> Void, aThrow: @escaping (Any?) -> Void, args: Any?) in var next: ((Any?) -> Void)! next = { d in if !cond() { aRet(args) return } afunc(next, aThrow, args) } next(args) } } public static func aWait(delay: TimeInterval = 0, queue: DispatchQueue = DispatchQueue.main, afunc: @escaping AFunc = { aRet, _, _ in aRet(nil) }) -> AFunc { return { (aRet: @escaping (Any?) -> Void, aThrow: @escaping (Any?) -> Void, args: Any?) in queue.asyncAfter( deadline: DispatchTime.now() + Double(Int64(UInt64(delay * 1000.0) * NSEC_PER_MSEC)) / Double(NSEC_PER_SEC), execute: { () -> Void in afunc(aRet, aThrow, args) }) } } } public class Future<T> { private var set: Bool = false private var value: T! private var error: Error? private var semaphore = DispatchSemaphore(value: 0) private var numWaiting = 0 public func get() throws -> T { if !set { numWaiting += 1 semaphore.wait() } if error != nil { throw error! } return value } public func set(_ value: T) { self.value = value set = true for _ in 0...numWaiting { semaphore.signal() } } public func error(_ value: Error?) { self.error = value set = true for _ in 0...numWaiting { semaphore.signal() } } } // TODO: Model! public class ParserContext { private lazy var map_: [String:Any] = [:] private var parent_: ParserContext? public func get(_ key: String) -> Any? { return map_[key] ?? parent_?.get(key) } public func set(_ key: String, _ value: Any) { map_[key] = value } public func sub() -> ParserContext { let child = ParserContext() child.parent_ = self return child } } extension foam_dao_DAO { public func select() throws -> foam_dao_ArraySink { return try select(Context.GLOBAL.create(foam_dao_ArraySink.self)!) as! foam_dao_ArraySink } } public protocol Topic { func hasListeners(_ args: [Any]) -> Bool func sub(topics: [String], listener l: @escaping Listener) -> Subscription func pub(_ args: [Any?]) -> Int } extension Topic { func pub() -> Int { return pub([]) } } public class BasicTopic: Topic { var name_: String! var parent_: Topic! var map_: [String:Topic] = [:] public func hasListeners(_ args: [Any] = []) -> Bool { return parent_.hasListeners([name_!] + args) } public func sub(topics: [String] = [], listener l: @escaping Listener) -> Subscription { return parent_.sub(topics: [name_!] + topics, listener: l) } public func pub(_ args: [Any?]) -> Int { return parent_.pub([name_!] + args) } subscript(key: String) -> Topic { return map_[key]! } }
apache-2.0
e883ee6c614e016ed11bd58116b4ed01
27.081121
143
0.608383
3.617519
false
false
false
false
BrianCorbin/SwiftRangeSlider
Examples/SwiftRangeSliderExample/Pods/SwiftRangeSlider/SwiftRangeSlider/RangeSlider.swift
1
5345
// // RangeSlider.swift // SwiftRangeSlider // // Created by Brian Corbin on 5/22/16. // Copyright © 2016 Caramel Apps. All rights reserved. // import UIKit import QuartzCore @IBDesignable open class RangeSlider: UIControl { @IBInspectable open var minimumValue: Double = 0.0 { didSet { updateLayerFrames() } } @IBInspectable open var maximumValue: Double = 1.0 { didSet { updateLayerFrames() } } @IBInspectable open var lowerValue: Double = 0.2 { didSet { updateLayerFrames() } } @IBInspectable open var upperValue: Double = 0.8 { didSet { updateLayerFrames() } } @IBInspectable open var trackTintColor: UIColor = UIColor(white: 0.9, alpha: 1.0) { didSet { trackLayer.setNeedsDisplay() } } @IBInspectable open var trackHighlightTintColor: UIColor = UIColor(red: 0.0, green: 0.45, blue: 0.94, alpha: 1.0) { didSet { trackLayer.setNeedsDisplay() } } @IBInspectable open var trackThickness: CGFloat = 0.1 { didSet { updateLayerFrames() } } @IBInspectable open var thumbTintColor: UIColor = UIColor.white { didSet { lowerThumbLayer.setNeedsDisplay() upperThumbLayer.setNeedsDisplay() } } @IBInspectable open var thumbBorderThickness: CGFloat = 0.1 { didSet { lowerThumbLayer.setNeedsDisplay() upperThumbLayer.setNeedsDisplay() } } @IBInspectable open var thumbHasShadow: Bool = true { didSet{ lowerThumbLayer.setNeedsDisplay() upperThumbLayer.setNeedsDisplay() } } @IBInspectable open var curvaceousness: CGFloat = 1.0 { didSet { trackLayer.setNeedsDisplay() lowerThumbLayer.setNeedsDisplay() upperThumbLayer.setNeedsDisplay() } } var previousLocation = CGPoint() let trackLayer = RangeSliderTrackLayer() let lowerThumbLayer = RangeSliderThumbLayer() let upperThumbLayer = RangeSliderThumbLayer() var thumbWidth: CGFloat { return CGFloat(bounds.height) } override open var frame: CGRect { didSet { updateLayerFrames() } } override init(frame: CGRect) { super.init(frame: frame) addContentViews() } required public init(coder: NSCoder) { super.init(coder: coder)! addContentViews() } func addContentViews(){ trackLayer.rangeSlider = self trackLayer.contentsScale = UIScreen.main.scale layer.addSublayer(trackLayer) lowerThumbLayer.rangeSlider = self lowerThumbLayer.contentsScale = UIScreen.main.scale layer.addSublayer(lowerThumbLayer) upperThumbLayer.rangeSlider = self upperThumbLayer.contentsScale = UIScreen.main.scale layer.addSublayer(upperThumbLayer) } open func updateLayerFrames() { CATransaction.begin() CATransaction.setDisableActions(true) let newTrackDy = (frame.height - frame.height * trackThickness) / 2 trackLayer.frame = CGRect(x: 0, y: newTrackDy, width: frame.width, height: frame.height * trackThickness) trackLayer.setNeedsDisplay() let lowerThumbCenter = CGFloat(positionForValue(lowerValue)) lowerThumbLayer.frame = CGRect(x: lowerThumbCenter - thumbWidth / 2.0, y: 0.0, width: thumbWidth, height: thumbWidth) lowerThumbLayer.setNeedsDisplay() let upperThumbCenter = CGFloat(positionForValue(upperValue)) upperThumbLayer.frame = CGRect(x: upperThumbCenter - thumbWidth / 2.0, y: 0.0, width: thumbWidth, height: thumbWidth) upperThumbLayer.setNeedsDisplay() CATransaction.commit() } func positionForValue(_ value: Double) -> Double { return Double(bounds.width - thumbWidth) * (value - minimumValue) / (maximumValue - minimumValue) + Double(thumbWidth / 2.0) } func boundValue(_ value: Double, toLowerValue lowerValue: Double, upperValue: Double) -> Double { return min(max(value, lowerValue), upperValue) } override open func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool { previousLocation = touch.location(in: self) if lowerThumbLayer.frame.contains(previousLocation) { lowerThumbLayer.highlighted = true } else if upperThumbLayer.frame.contains(previousLocation) { upperThumbLayer.highlighted = true } return lowerThumbLayer.highlighted || upperThumbLayer.highlighted } override open func continueTracking(_ touch: UITouch, with event: UIEvent?) -> Bool { let location = touch.location(in: self) let deltaLocation = Double(location.x - previousLocation.x) let deltaValue = (maximumValue - minimumValue) * deltaLocation / Double(bounds.width - thumbWidth) previousLocation = location if lowerThumbLayer.highlighted { lowerValue += deltaValue lowerValue = boundValue(lowerValue, toLowerValue: minimumValue, upperValue: upperValue) } else if upperThumbLayer.highlighted { upperValue += deltaValue upperValue = boundValue(upperValue, toLowerValue: lowerValue, upperValue: maximumValue) } sendActions(for: .valueChanged) return true } override open func endTracking(_ touch: UITouch?, with event: UIEvent?) { lowerThumbLayer.highlighted = false upperThumbLayer.highlighted = false } }
mit
1b3962aaf71fcde4d5ce20da1b681c05
26.979058
117
0.679079
4.889296
false
false
false
false
PrestonV/ios-cannonball
Cannonball/AboutViewController.swift
1
2808
// // Copyright (C) 2014 Twitter, Inc. and other contributors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import UIKit import TwitterKit class AboutViewController: UIViewController { // MARK: References @IBOutlet weak var signOutButton: UIButton! var logoView: UIImageView! // MARK: View Life Cycle override func viewDidLoad() { // Add the logo view to the top (not in the navigation bar title to have it bigger). logoView = UIImageView(frame: CGRectMake(0, 0, 40, 40)) logoView.image = UIImage(named: "Logo")?.imageWithRenderingMode(.AlwaysTemplate) logoView.tintColor = UIColor.cannonballGreenColor() logoView.frame.origin.x = (self.view.frame.size.width - logoView.frame.size.width) / 2 logoView.frame.origin.y = 8 // Add the logo view to the navigation controller. self.navigationController?.view.addSubview(logoView) // Bring the logo view to the front. self.navigationController?.view.bringSubviewToFront(logoView) // Customize the navigation bar. let titleDict: NSDictionary = [NSForegroundColorAttributeName: UIColor.cannonballGreenColor()] self.navigationController?.navigationBar.titleTextAttributes = titleDict self.navigationController?.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: .Default) self.navigationController?.navigationBar.shadowImage = UIImage() } // MARK: IBActions @IBAction func dismiss(sender: AnyObject) { self.dismissViewControllerAnimated(true, completion: nil) } @IBAction func learnMore(sender: AnyObject) { UIApplication.sharedApplication().openURL(NSURL(string: "http://t.co/cannonball")!) } @IBAction func signOut(sender: AnyObject) { // Remove any Twitter or Digits local sessions for this app. Twitter.sharedInstance().logOut() Digits.sharedInstance().logOut() // Present the Sign In again. let storyboard = UIStoryboard(name: "Main", bundle: nil) let signInViewController: UIViewController! = storyboard.instantiateViewControllerWithIdentifier("SignInViewController") as UIViewController self.presentViewController(signInViewController, animated: true, completion: nil) } }
apache-2.0
1d63c573a8058cccc32e244a461f4139
38
148
0.712607
4.987567
false
false
false
false
mattrajca/swift-corelibs-foundation
TestFoundation/TestURL.swift
3
31394
// 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_RUNTIME_OBJC || os(Linux) import Foundation import XCTest #else import SwiftFoundation import SwiftXCTest #endif let kURLTestParsingTestsKey = "ParsingTests" let kURLTestTitleKey = "In-Title" let kURLTestUrlKey = "In-Url" let kURLTestBaseKey = "In-Base" let kURLTestURLCreatorKey = "In-URLCreator" let kURLTestPathComponentKey = "In-PathComponent" let kURLTestPathExtensionKey = "In-PathExtension" let kURLTestCFResultsKey = "Out-CFResults" let kURLTestNSResultsKey = "Out-NSResults" let kNSURLWithStringCreator = "NSURLWithString" let kCFURLCreateWithStringCreator = "CFURLCreateWithString" let kCFURLCreateWithBytesCreator = "CFURLCreateWithBytes" let kCFURLCreateAbsoluteURLWithBytesCreator = "CFURLCreateAbsoluteURLWithBytes" let kNullURLString = "<null url>" let kNullString = "<null>" /// Reads the test data plist file and returns the list of objects private func getTestData() -> [Any]? { let testFilePath = testBundle().url(forResource: "NSURLTestData", withExtension: "plist") let data = try! Data(contentsOf: testFilePath!) guard let testRoot = try? PropertyListSerialization.propertyList(from: data, options: [], format: nil) as? [String : Any] else { XCTFail("Unable to deserialize property list data") return nil } guard let parsingTests = testRoot![kURLTestParsingTestsKey] as? [Any] else { XCTFail("Unable to create the parsingTests dictionary") return nil } return parsingTests } class TestURL : XCTestCase { static var allTests: [(String, (TestURL) -> () throws -> Void)] { return [ ("test_URLStrings", test_URLStrings), ("test_fileURLWithPath_relativeTo", test_fileURLWithPath_relativeTo ), // TODO: these tests fail on linux, more investigation is needed ("test_fileURLWithPath", test_fileURLWithPath), ("test_fileURLWithPath_isDirectory", test_fileURLWithPath_isDirectory), ("test_URLByResolvingSymlinksInPath", test_URLByResolvingSymlinksInPath), ("test_reachable", test_reachable), ("test_copy", test_copy), ("test_itemNSCoding", test_itemNSCoding), ("test_dataRepresentation", test_dataRepresentation), ("test_description", test_description), ] } func test_fileURLWithPath_relativeTo() { let homeDirectory = NSHomeDirectory() XCTAssertNotNil(homeDirectory, "Failed to find home directory") let homeURL = URL(fileURLWithPath: homeDirectory, isDirectory: true) XCTAssertNotNil(homeURL, "fileURLWithPath:isDirectory: failed") XCTAssertEqual(homeDirectory, homeURL.path) #if os(OSX) let baseURL = URL(fileURLWithPath: homeDirectory, isDirectory: true) let relativePath = "Documents" #elseif os(Android) let baseURL = URL(fileURLWithPath: "/data", isDirectory: true) let relativePath = "local" #elseif os(Linux) let baseURL = URL(fileURLWithPath: "/usr", isDirectory: true) let relativePath = "include" #endif // we're telling fileURLWithPath:isDirectory:relativeTo: Documents is a directory let url1 = URL(fileURLWithFileSystemRepresentation: relativePath, isDirectory: true, relativeTo: baseURL) XCTAssertNotNil(url1, "fileURLWithPath:isDirectory:relativeTo: failed") // we're letting fileURLWithPath:relativeTo: determine Documents is a directory with I/O let url2 = URL(fileURLWithPath: relativePath, relativeTo: baseURL) XCTAssertNotNil(url2, "fileURLWithPath:relativeTo: failed") XCTAssertEqual(url1, url2, "\(url1) was not equal to \(url2)") // we're telling fileURLWithPath:relativeTo: Documents is a directory with a trailing slash let url3 = URL(fileURLWithPath: relativePath + "/", relativeTo: baseURL) XCTAssertNotNil(url3, "fileURLWithPath:relativeTo: failed") XCTAssertEqual(url1, url3, "\(url1) was not equal to \(url3)") } /// Returns a URL from the given url string and base private func URLWithString(_ urlString : String, baseString : String?) -> URL? { if let baseString = baseString { let baseURL = URL(string: baseString) return URL(string: urlString, relativeTo: baseURL) } else { return URL(string: urlString) } } internal func generateResults(_ url: URL, pathComponent: String?, pathExtension : String?) -> [String : Any] { var result = [String : Any]() if let pathComponent = pathComponent { let newFileURL = url.appendingPathComponent(pathComponent, isDirectory: false) result["appendingPathComponent-File"] = newFileURL.relativeString result["appendingPathComponent-File-BaseURL"] = newFileURL.baseURL?.relativeString ?? kNullString let newDirURL = url.appendingPathComponent(pathComponent, isDirectory: true) result["appendingPathComponent-Directory"] = newDirURL.relativeString result["appendingPathComponent-Directory-BaseURL"] = newDirURL.baseURL?.relativeString ?? kNullString } else if let pathExtension = pathExtension { let newURL = url.appendingPathExtension(pathExtension) result["appendingPathExtension"] = newURL.relativeString result["appendingPathExtension-BaseURL"] = newURL.baseURL?.relativeString ?? kNullString } else { result["relativeString"] = url.relativeString result["baseURLString"] = url.baseURL?.relativeString ?? kNullString result["absoluteString"] = url.absoluteString result["absoluteURLString"] = url.absoluteURL.relativeString result["scheme"] = url.scheme ?? kNullString result["host"] = url.host ?? kNullString result["port"] = url.port ?? kNullString result["user"] = url.user ?? kNullString result["password"] = url.password ?? kNullString result["path"] = url.path result["query"] = url.query ?? kNullString result["fragment"] = url.fragment ?? kNullString result["relativePath"] = url.relativePath result["isFileURL"] = url.isFileURL ? "YES" : "NO" result["standardizedURL"] = url.standardized.relativeString result["pathComponents"] = url.pathComponents result["lastPathComponent"] = url.lastPathComponent result["pathExtension"] = url.pathExtension result["deletingLastPathComponent"] = url.deletingLastPathComponent().relativeString result["deletingLastPathExtension"] = url.deletingPathExtension().relativeString } return result } internal func compareResults(_ url : URL, expected : [String : Any], got : [String : Any]) -> (Bool, [String]) { var differences = [String]() for (key, obj) in expected { // Skip non-string expected results if ["port", "standardizedURL", "pathComponents"].contains(key) { continue } if let expectedValue = obj as? String { if let testedValue = got[key] as? String { if expectedValue != testedValue { differences.append(" \(key) Expected = '\(expectedValue)', Got = '\(testedValue)'") } } else { differences.append(" \(key) Expected = '\(expectedValue)', Got = '\(String(describing: got[key]))'") } } else if let expectedValue = obj as? [String] { if let testedValue = got[key] as? [String] { if expectedValue != testedValue { differences.append(" \(key) Expected = '\(expectedValue)', Got = '\(testedValue)'") } } else { differences.append(" \(key) Expected = '\(expectedValue)', Got = '\(String(describing: got[key]))'") } } else if let expectedValue = obj as? Int { if let testedValue = got[key] as? Int { if expectedValue != testedValue { differences.append(" \(key) Expected = '\(expectedValue)', Got = '\(testedValue)'") } } else { differences.append(" \(key) Expected = '\(expectedValue)', Got = '\(String(describing: got[key]))'") } } } for (key, obj) in got { if expected[key] == nil { differences.append(" \(key) Expected = 'nil', Got = '\(obj)'") } } if differences.count > 0 { differences.sort() differences.insert(" url: '\(url)' ", at: 0) return (false, differences) } else { return (true, []) } } func test_URLStrings() { for obj in getTestData()! { let testDict = obj as! [String: Any] let title = testDict[kURLTestTitleKey] as! String let inURL = testDict[kURLTestUrlKey]! as! String let inBase = testDict[kURLTestBaseKey] as! String? let inPathComponent = testDict[kURLTestPathComponentKey] as! String? let inPathExtension = testDict[kURLTestPathExtensionKey] as! String? let expectedNSResult = testDict[kURLTestNSResultsKey]! var url : URL? = nil switch (testDict[kURLTestURLCreatorKey]! as! String) { case kNSURLWithStringCreator: url = URLWithString(inURL, baseString: inBase) case kCFURLCreateWithStringCreator, kCFURLCreateWithBytesCreator, kCFURLCreateAbsoluteURLWithBytesCreator: // TODO: Not supported right now continue default: XCTFail() } if title == "NSURLWithString-parse-ambiguous-url-001" { // TODO: Fix this test } else { if let url = url { let results = generateResults(url, pathComponent: inPathComponent, pathExtension: inPathExtension) let (isEqual, differences) = compareResults(url, expected: expectedNSResult as! [String: Any], got: results) XCTAssertTrue(isEqual, "\(title): \(differences.joined(separator: "\n"))") } else { XCTAssertEqual(expectedNSResult as? String, kNullURLString) } } } } static let gBaseTemporaryDirectoryPath = NSTemporaryDirectory() static var gBaseCurrentWorkingDirectoryPath : String { let count = Int(1024) // MAXPATHLEN is platform specific; this is the lowest common denominator for darwin and most linuxes var buf : [Int8] = Array(repeating: 0, count: count) getcwd(&buf, count) return String(cString: buf) } static var gRelativeOffsetFromBaseCurrentWorkingDirectory: UInt = 0 static let gFileExistsName = "TestCFURL_file_exists\(ProcessInfo.processInfo.globallyUniqueString)" static let gFileDoesNotExistName = "TestCFURL_file_does_not_exist" static let gDirectoryExistsName = "TestCFURL_directory_exists\(ProcessInfo.processInfo.globallyUniqueString)" static let gDirectoryDoesNotExistName = "TestCFURL_directory_does_not_exist" static let gFileExistsPath = gBaseTemporaryDirectoryPath + gFileExistsName static let gFileDoesNotExistPath = gBaseTemporaryDirectoryPath + gFileDoesNotExistName static let gDirectoryExistsPath = gBaseTemporaryDirectoryPath + gDirectoryExistsName static let gDirectoryDoesNotExistPath = gBaseTemporaryDirectoryPath + gDirectoryDoesNotExistName static func setup_test_paths() -> Bool { if creat(gFileExistsPath, S_IRWXU) < 0 && errno != EEXIST { return false } if unlink(gFileDoesNotExistPath) != 0 && errno != ENOENT { return false } if mkdir(gDirectoryExistsPath, S_IRWXU) != 0 && errno != EEXIST { return false } if rmdir(gDirectoryDoesNotExistPath) != 0 && errno != ENOENT { return false } #if os(Android) chdir("/data/local/tmp") #endif let cwd = FileManager.default.currentDirectoryPath let cwdURL = URL(fileURLWithPath: cwd, isDirectory: true) // 1 for path separator cwdURL.withUnsafeFileSystemRepresentation { gRelativeOffsetFromBaseCurrentWorkingDirectory = UInt(strlen($0!) + 1) } return true } func test_fileURLWithPath() { if !TestURL.setup_test_paths() { let error = strerror(errno)! XCTFail("Failed to set up test paths: \(String(cString: error))") } // test with file that exists var path = TestURL.gFileExistsPath var url = NSURL(fileURLWithPath: path) XCTAssertFalse(url.hasDirectoryPath, "did not expect URL with directory path: \(url)") XCTAssertEqual(path, url.path, "path from file path URL is wrong") // test with file that doesn't exist path = TestURL.gFileDoesNotExistPath url = NSURL(fileURLWithPath: path) XCTAssertFalse(url.hasDirectoryPath, "did not expect URL with directory path: \(url)") XCTAssertEqual(path, url.path, "path from file path URL is wrong") // test with directory that exists path = TestURL.gDirectoryExistsPath url = NSURL(fileURLWithPath: path) XCTAssertTrue(url.hasDirectoryPath, "expected URL with directory path: \(url)") XCTAssertEqual(path, url.path, "path from file path URL is wrong") // test with directory that doesn't exist path = TestURL.gDirectoryDoesNotExistPath url = NSURL(fileURLWithPath: path) XCTAssertFalse(url.hasDirectoryPath, "did not expect URL with directory path: \(url)") XCTAssertEqual(path, url.path, "path from file path URL is wrong") // test with name relative to current working directory path = TestURL.gFileDoesNotExistName url = NSURL(fileURLWithPath: path) XCTAssertFalse(url.hasDirectoryPath, "did not expect URL with directory path: \(url)") let fileSystemRep = url.fileSystemRepresentation let actualLength = strlen(fileSystemRep) // 1 for path separator let expectedLength = UInt(strlen(TestURL.gFileDoesNotExistName)) + TestURL.gRelativeOffsetFromBaseCurrentWorkingDirectory XCTAssertEqual(UInt(actualLength), expectedLength, "fileSystemRepresentation was too short") XCTAssertTrue(strncmp(TestURL.gBaseCurrentWorkingDirectoryPath, fileSystemRep, Int(strlen(TestURL.gBaseCurrentWorkingDirectoryPath))) == 0, "fileSystemRepresentation of base path is wrong") let lengthOfRelativePath = Int(strlen(TestURL.gFileDoesNotExistName)) let relativePath = fileSystemRep.advanced(by: Int(TestURL.gRelativeOffsetFromBaseCurrentWorkingDirectory)) XCTAssertTrue(strncmp(TestURL.gFileDoesNotExistName, relativePath, lengthOfRelativePath) == 0, "fileSystemRepresentation of file path is wrong") } func test_fileURLWithPath_isDirectory() { if !TestURL.setup_test_paths() { let error = strerror(errno)! XCTFail("Failed to set up test paths: \(String(cString: error))") } // test with file that exists var path = TestURL.gFileExistsPath var url = NSURL(fileURLWithPath: path, isDirectory: true) XCTAssertTrue(url.hasDirectoryPath, "expected URL with directory path: \(url)") url = NSURL(fileURLWithPath: path, isDirectory: false) XCTAssertFalse(url.hasDirectoryPath, "did not expect URL with directory path: \(url)") XCTAssertEqual(path, url.path, "path from file path URL is wrong") // test with file that doesn't exist path = TestURL.gFileDoesNotExistPath url = NSURL(fileURLWithPath: path, isDirectory: true) XCTAssertTrue(url.hasDirectoryPath, "expected URL with directory path: \(url)") url = NSURL(fileURLWithPath: path, isDirectory: false) XCTAssertFalse(url.hasDirectoryPath, "did not expect URL with directory path: \(url)") XCTAssertEqual(path, url.path, "path from file path URL is wrong") // test with directory that exists path = TestURL.gDirectoryExistsPath url = NSURL(fileURLWithPath: path, isDirectory: false) XCTAssertFalse(url.hasDirectoryPath, "did not expect URL with directory path: \(url)") url = NSURL(fileURLWithPath: path, isDirectory: true) XCTAssertTrue(url.hasDirectoryPath, "expected URL with directory path: \(url)") XCTAssertEqual(path, url.path, "path from file path URL is wrong") // test with directory that doesn't exist path = TestURL.gDirectoryDoesNotExistPath url = NSURL(fileURLWithPath: path, isDirectory: false) XCTAssertFalse(url.hasDirectoryPath, "did not expect URL with directory path: \(url)") url = NSURL(fileURLWithPath: path, isDirectory: true) XCTAssertTrue(url.hasDirectoryPath, "expected URL with directory path: \(url)") XCTAssertEqual(path, url.path, "path from file path URL is wrong") // test with name relative to current working directory path = TestURL.gFileDoesNotExistName url = NSURL(fileURLWithPath: path, isDirectory: false) XCTAssertFalse(url.hasDirectoryPath, "did not expect URL with directory path: \(url)") url = NSURL(fileURLWithPath: path, isDirectory: true) XCTAssertTrue(url.hasDirectoryPath, "expected URL with directory path: \(url)") let fileSystemRep = url.fileSystemRepresentation let actualLength = UInt(strlen(fileSystemRep)) // 1 for path separator let expectedLength = UInt(strlen(TestURL.gFileDoesNotExistName)) + TestURL.gRelativeOffsetFromBaseCurrentWorkingDirectory XCTAssertEqual(actualLength, expectedLength, "fileSystemRepresentation was too short") XCTAssertTrue(strncmp(TestURL.gBaseCurrentWorkingDirectoryPath, fileSystemRep, Int(strlen(TestURL.gBaseCurrentWorkingDirectoryPath))) == 0, "fileSystemRepresentation of base path is wrong") let lengthOfRelativePath = Int(strlen(TestURL.gFileDoesNotExistName)) let relativePath = fileSystemRep.advanced(by: Int(TestURL.gRelativeOffsetFromBaseCurrentWorkingDirectory)) XCTAssertTrue(strncmp(TestURL.gFileDoesNotExistName, relativePath, lengthOfRelativePath) == 0, "fileSystemRepresentation of file path is wrong") } func test_URLByResolvingSymlinksInPath() { let files = [ NSTemporaryDirectory() + "ABC/test_URLByResolvingSymlinksInPath" ] guard ensureFiles(files) else { XCTAssert(false, "Could create files for testing.") return } // tmp is special because it is symlinked to /private/tmp and this /private prefix should be dropped, // so tmp is tmp. On Linux tmp is not symlinked so it would be the same. do { let url = URL(fileURLWithPath: "/.//tmp/ABC/..") let result = url.resolvingSymlinksInPath().absoluteString XCTAssertEqual(result, "file:///tmp/", "URLByResolvingSymlinksInPath removes extraneous path components and resolve symlinks.") } do { let url = URL(fileURLWithPath: "~") let result = url.resolvingSymlinksInPath().absoluteString let expected = "file://" + FileManager.default.currentDirectoryPath + "/~" XCTAssertEqual(result, expected, "URLByResolvingSymlinksInPath resolves relative paths using current working directory.") } do { let url = URL(fileURLWithPath: "anysite.com/search") let result = url.resolvingSymlinksInPath().absoluteString let expected = "file://" + FileManager.default.currentDirectoryPath + "/anysite.com/search" XCTAssertEqual(result, expected) } // tmp is symlinked on OS X only #if os(OSX) do { let url = URL(fileURLWithPath: "/tmp/..") let result = url.resolvingSymlinksInPath().absoluteString XCTAssertEqual(result, "file:///private/") } #else do { let url = URL(fileURLWithPath: "/tmp/ABC/test_URLByResolvingSymlinksInPath") let result = url.resolvingSymlinksInPath().absoluteString XCTAssertEqual(result, "file:///tmp/ABC/test_URLByResolvingSymlinksInPath", "URLByResolvingSymlinksInPath appends trailing slash for existing directories only") } #endif do { let url = URL(fileURLWithPath: "/tmp/ABC/..") let result = url.resolvingSymlinksInPath().absoluteString XCTAssertEqual(result, "file:///tmp/") } } func test_reachable() { #if os(Android) var url = URL(fileURLWithPath: "/data") #else var url = URL(fileURLWithPath: "/usr") #endif XCTAssertEqual(true, try? url.checkResourceIsReachable()) url = URL(string: "https://www.swift.org")! do { _ = try url.checkResourceIsReachable() XCTFail() } catch let error as NSError { XCTAssertEqual(NSCocoaErrorDomain, error.domain) XCTAssertEqual(CocoaError.Code.fileNoSuchFile.rawValue, error.code) } catch { XCTFail() } url = URL(fileURLWithPath: "/some_random_path") do { _ = try url.checkResourceIsReachable() XCTFail() } catch let error as NSError { XCTAssertEqual(NSCocoaErrorDomain, error.domain) XCTAssertEqual(CocoaError.Code.fileReadNoSuchFile.rawValue, error.code) } catch { XCTFail() } #if os(Android) var nsURL = NSURL(fileURLWithPath: "/data") #else var nsURL = NSURL(fileURLWithPath: "/usr") #endif XCTAssertEqual(true, try? nsURL.checkResourceIsReachable()) nsURL = NSURL(string: "https://www.swift.org")! do { _ = try nsURL.checkResourceIsReachable() XCTFail() } catch let error as NSError { XCTAssertEqual(NSCocoaErrorDomain, error.domain) XCTAssertEqual(CocoaError.Code.fileNoSuchFile.rawValue, error.code) } catch { XCTFail() } nsURL = NSURL(fileURLWithPath: "/some_random_path") do { _ = try nsURL.checkResourceIsReachable() XCTFail() } catch let error as NSError { XCTAssertEqual(NSCocoaErrorDomain, error.domain) XCTAssertEqual(CocoaError.Code.fileReadNoSuchFile.rawValue, error.code) } catch { XCTFail() } } func test_copy() { let url = NSURL(string: "https://www.swift.org") let urlCopy = url!.copy() as! NSURL XCTAssertTrue(url!.isEqual(urlCopy)) let queryItem = NSURLQueryItem(name: "id", value: "23") let queryItemCopy = queryItem.copy() as! NSURLQueryItem XCTAssertTrue(queryItem.isEqual(queryItemCopy)) } func test_itemNSCoding() { let queryItemA = NSURLQueryItem(name: "id", value: "23") let queryItemB = NSKeyedUnarchiver.unarchiveObject(with: NSKeyedArchiver.archivedData(withRootObject: queryItemA)) as! NSURLQueryItem XCTAssertEqual(queryItemA, queryItemB, "Archived then unarchived query item must be equal.") } func test_dataRepresentation() { let url = NSURL(fileURLWithPath: "/tmp/foo") let url2 = NSURL(dataRepresentation: url.dataRepresentation, relativeTo: nil) XCTAssertEqual(url, url2) } func test_description() { let url = URL(string: "http://amazon.in")! XCTAssertEqual(url.description, "http://amazon.in") } } class TestURLComponents : XCTestCase { static var allTests: [(String, (TestURLComponents) -> () throws -> Void)] { return [ ("test_queryItems", test_queryItems), ("test_string", test_string), ("test_port", test_portSetter), ("test_url", test_url), ("test_copy", test_copy), ("test_createURLWithComponents", test_createURLWithComponents), ("test_path", test_path), ("test_percentEncodedPath", test_percentEncodedPath), ] } func test_queryItems() { let urlString = "http://localhost:8080/foo?bar=&bar=baz" let url = URL(string: urlString)! let components = URLComponents(url: url, resolvingAgainstBaseURL: false) var query = [String: String]() components?.queryItems?.forEach { query[$0.name] = $0.value ?? "" } XCTAssertEqual(["bar": "baz"], query) } func test_string() { for obj in getTestData()! { let testDict = obj as! [String: Any] let unencodedString = testDict[kURLTestUrlKey] as! String let expectedString = NSString(string: unencodedString).addingPercentEncoding(withAllowedCharacters: .urlPathAllowed)! guard let components = URLComponents(string: expectedString) else { continue } XCTAssertEqual(components.string!, expectedString, "should be the expected string (\(components.string!) != \(expectedString))") } } func test_portSetter() { let urlString = "http://myhost.mydomain.com" let port: Int = 8080 let expectedString = "http://myhost.mydomain.com:8080" var url = URLComponents(string: urlString) url!.port = port let receivedString = url!.string XCTAssertEqual(receivedString, expectedString, "expected \(expectedString) but received \(receivedString as Optional)") } func test_url() { let baseURL = URL(string: "https://www.example.com") /* test NSURLComponents without authority */ var compWithAuthority = URLComponents(string: "https://www.swift.org") compWithAuthority!.path = "/path/to/file with space.html" compWithAuthority!.query = "id=23&search=Foo Bar" var expectedString = "https://www.swift.org/path/to/file%20with%20space.html?id=23&search=Foo%20Bar" XCTAssertEqual(compWithAuthority!.string, expectedString, "expected \(expectedString) but received \(compWithAuthority!.string as Optional)") var aURL = compWithAuthority!.url(relativeTo: baseURL) XCTAssertNotNil(aURL) XCTAssertNil(aURL!.baseURL) XCTAssertEqual(aURL!.absoluteString, expectedString, "expected \(expectedString) but received \(aURL!.absoluteString)") compWithAuthority!.path = "path/to/file with space.html" //must start with / XCTAssertNil(compWithAuthority!.string) // must be nil aURL = compWithAuthority!.url(relativeTo: baseURL) XCTAssertNil(aURL) //must be nil /* test NSURLComponents without authority */ var compWithoutAuthority = URLComponents() compWithoutAuthority.path = "path/to/file with space.html" compWithoutAuthority.query = "id=23&search=Foo Bar" expectedString = "path/to/file%20with%20space.html?id=23&search=Foo%20Bar" XCTAssertEqual(compWithoutAuthority.string, expectedString, "expected \(expectedString) but received \(compWithoutAuthority.string as Optional)") aURL = compWithoutAuthority.url(relativeTo: baseURL) XCTAssertNotNil(aURL) expectedString = "https://www.example.com/path/to/file%20with%20space.html?id=23&search=Foo%20Bar" XCTAssertEqual(aURL!.absoluteString, expectedString, "expected \(expectedString) but received \(aURL!.absoluteString)") compWithoutAuthority.path = "//path/to/file with space.html" //shouldn't start with // XCTAssertNil(compWithoutAuthority.string) // must be nil aURL = compWithoutAuthority.url(relativeTo: baseURL) XCTAssertNil(aURL) //must be nil } func test_copy() { let urlString = "https://www.swift.org/path/to/file.html?id=name" let urlComponent = NSURLComponents(string: urlString)! let copy = urlComponent.copy() as! NSURLComponents /* Assert that NSURLComponents.copy did not return self */ XCTAssertFalse(copy === urlComponent) /* Assert that NSURLComponents.copy is actually a copy of NSURLComponents */ XCTAssertTrue(copy.isEqual(urlComponent)) } func test_createURLWithComponents() { let urlComponents = NSURLComponents() urlComponents.scheme = "https"; urlComponents.host = "com.test.swift"; urlComponents.path = "/test/path"; let date = Date() let query1 = URLQueryItem(name: "date", value: date.description) let query2 = URLQueryItem(name: "simpleDict", value: "false") let query3 = URLQueryItem(name: "checkTest", value: "false") let query4 = URLQueryItem(name: "someKey", value: "afsdjhfgsdkf^fhdjgf") urlComponents.queryItems = [query1, query2, query3, query4] XCTAssertNotNil(urlComponents.url?.query) XCTAssertEqual(urlComponents.queryItems?.count, 4) } func test_path() { let c1 = URLComponents() XCTAssertEqual(c1.path, "") let c2 = URLComponents(string: "http://swift.org") XCTAssertEqual(c2?.path, "") let c3 = URLComponents(string: "http://swift.org/") XCTAssertEqual(c3?.path, "/") let c4 = URLComponents(string: "http://swift.org/foo/bar") XCTAssertEqual(c4?.path, "/foo/bar") let c5 = URLComponents(string: "http://swift.org:80/foo/bar") XCTAssertEqual(c5?.path, "/foo/bar") let c6 = URLComponents(string: "http://swift.org:80/foo/b%20r") XCTAssertEqual(c6?.path, "/foo/b r") } func test_percentEncodedPath() { let c1 = URLComponents() XCTAssertEqual(c1.percentEncodedPath, "") let c2 = URLComponents(string: "http://swift.org") XCTAssertEqual(c2?.percentEncodedPath, "") let c3 = URLComponents(string: "http://swift.org/") XCTAssertEqual(c3?.percentEncodedPath, "/") let c4 = URLComponents(string: "http://swift.org/foo/bar") XCTAssertEqual(c4?.percentEncodedPath, "/foo/bar") let c5 = URLComponents(string: "http://swift.org:80/foo/bar") XCTAssertEqual(c5?.percentEncodedPath, "/foo/bar") let c6 = URLComponents(string: "http://swift.org:80/foo/b%20r") XCTAssertEqual(c6?.percentEncodedPath, "/foo/b%20r") } }
apache-2.0
e69fd0a53f378ca58a6a711cdb200b26
45.099853
197
0.638944
5.035124
false
true
false
false
SanctionCo/pilot-ios
Pods/Gallery/Sources/Camera/CameraView.swift
1
7720
import UIKit import AVFoundation protocol CameraViewDelegate: class { func cameraView(_ cameraView: CameraView, didTouch point: CGPoint) } class CameraView: UIView, UIGestureRecognizerDelegate { lazy var closeButton: UIButton = self.makeCloseButton() lazy var flashButton: TripleButton = self.makeFlashButton() lazy var rotateButton: UIButton = self.makeRotateButton() fileprivate lazy var bottomContainer: UIView = self.makeBottomContainer() lazy var bottomView: UIView = self.makeBottomView() lazy var stackView: StackView = self.makeStackView() lazy var shutterButton: ShutterButton = self.makeShutterButton() lazy var doneButton: UIButton = self.makeDoneButton() lazy var focusImageView: UIImageView = self.makeFocusImageView() lazy var tapGR: UITapGestureRecognizer = self.makeTapGR() lazy var rotateOverlayView: UIView = self.makeRotateOverlayView() lazy var shutterOverlayView: UIView = self.makeShutterOverlayView() lazy var blurView: UIVisualEffectView = self.makeBlurView() var timer: Timer? var previewLayer: AVCaptureVideoPreviewLayer? weak var delegate: CameraViewDelegate? // MARK: - Initialization override init(frame: CGRect) { super.init(frame: frame) backgroundColor = UIColor.black setup() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Setup func setup() { addGestureRecognizer(tapGR) [closeButton, flashButton, rotateButton, bottomContainer].forEach { addSubview($0) } [bottomView, shutterButton].forEach { bottomContainer.addSubview($0) } [stackView, doneButton].forEach { bottomView.addSubview($0 as! UIView) } [closeButton, flashButton, rotateButton].forEach { $0.g_addShadow() } rotateOverlayView.addSubview(blurView) insertSubview(rotateOverlayView, belowSubview: rotateButton) insertSubview(focusImageView, belowSubview: bottomContainer) insertSubview(shutterOverlayView, belowSubview: bottomContainer) closeButton.g_pin(on: .left) closeButton.g_pin(size: CGSize(width: 44, height: 44)) flashButton.g_pin(on: .centerY, view: closeButton) flashButton.g_pin(on: .centerX) flashButton.g_pin(size: CGSize(width: 60, height: 44)) rotateButton.g_pin(on: .right) rotateButton.g_pin(size: CGSize(width: 44, height: 44)) if #available(iOS 11, *) { Constraint.on( closeButton.topAnchor.constraint(equalTo: safeAreaLayoutGuide.topAnchor), rotateButton.topAnchor.constraint(equalTo: safeAreaLayoutGuide.topAnchor) ) } else { Constraint.on( closeButton.topAnchor.constraint(equalTo: superview!.topAnchor), rotateButton.topAnchor.constraint(equalTo: superview!.topAnchor) ) } bottomContainer.g_pinDownward() bottomContainer.g_pin(height: 80) bottomView.g_pinEdges() stackView.g_pin(on: .centerY, constant: -4) stackView.g_pin(on: .left, constant: 38) stackView.g_pin(size: CGSize(width: 56, height: 56)) shutterButton.g_pinCenter() shutterButton.g_pin(size: CGSize(width: 60, height: 60)) doneButton.g_pin(on: .centerY) doneButton.g_pin(on: .right, constant: -38) rotateOverlayView.g_pinEdges() blurView.g_pinEdges() shutterOverlayView.g_pinEdges() } func setupPreviewLayer(_ session: AVCaptureSession) { guard previewLayer == nil else { return } let layer = AVCaptureVideoPreviewLayer(session: session) layer.autoreverses = true layer.videoGravity = .resizeAspectFill self.layer.insertSublayer(layer, at: 0) layer.frame = self.layer.bounds previewLayer = layer } override func layoutSubviews() { super.layoutSubviews() previewLayer?.frame = self.layer.bounds } // MARK: - Action @objc func viewTapped(_ gr: UITapGestureRecognizer) { let point = gr.location(in: self) focusImageView.transform = CGAffineTransform.identity timer?.invalidate() delegate?.cameraView(self, didTouch: point) focusImageView.center = point UIView.animate(withDuration: 0.5, animations: { self.focusImageView.alpha = 1 self.focusImageView.transform = CGAffineTransform(scaleX: 0.6, y: 0.6) }, completion: { _ in self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(CameraView.timerFired(_:)), userInfo: nil, repeats: false) }) } // MARK: - Timer @objc func timerFired(_ timer: Timer) { UIView.animate(withDuration: 0.3, animations: { self.focusImageView.alpha = 0 }, completion: { _ in self.focusImageView.transform = CGAffineTransform.identity }) } // MARK: - UIGestureRecognizerDelegate override func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { let point = gestureRecognizer.location(in: self) return point.y > closeButton.frame.maxY && point.y < bottomContainer.frame.origin.y } // MARK: - Controls func makeCloseButton() -> UIButton { let button = UIButton(type: .custom) button.setImage(GalleryBundle.image("gallery_close"), for: UIControlState()) return button } func makeFlashButton() -> TripleButton { let states: [TripleButton.State] = [ TripleButton.State(title: "Gallery.Camera.Flash.Off".g_localize(fallback: "OFF"), image: GalleryBundle.image("gallery_camera_flash_off")!), TripleButton.State(title: "Gallery.Camera.Flash.On".g_localize(fallback: "ON"), image: GalleryBundle.image("gallery_camera_flash_on")!), TripleButton.State(title: "Gallery.Camera.Flash.Auto".g_localize(fallback: "AUTO"), image: GalleryBundle.image("gallery_camera_flash_auto")!) ] let button = TripleButton(states: states) return button } func makeRotateButton() -> UIButton { let button = UIButton(type: .custom) button.setImage(GalleryBundle.image("gallery_camera_rotate"), for: UIControlState()) return button } func makeBottomContainer() -> UIView { let view = UIView() return view } func makeBottomView() -> UIView { let view = UIView() view.backgroundColor = Config.Camera.BottomContainer.backgroundColor view.alpha = 0 return view } func makeStackView() -> StackView { let view = StackView() return view } func makeShutterButton() -> ShutterButton { let button = ShutterButton() button.g_addShadow() return button } func makeDoneButton() -> UIButton { let button = UIButton(type: .system) button.setTitleColor(UIColor.white, for: UIControlState()) button.setTitleColor(UIColor.lightGray, for: .disabled) button.titleLabel?.font = Config.Font.Text.regular.withSize(16) button.setTitle("Gallery.Done".g_localize(fallback: "Done"), for: UIControlState()) return button } func makeFocusImageView() -> UIImageView { let view = UIImageView() view.frame.size = CGSize(width: 110, height: 110) view.image = GalleryBundle.image("gallery_camera_focus") view.backgroundColor = .clear view.alpha = 0 return view } func makeTapGR() -> UITapGestureRecognizer { let gr = UITapGestureRecognizer(target: self, action: #selector(viewTapped(_:))) gr.delegate = self return gr } func makeRotateOverlayView() -> UIView { let view = UIView() view.alpha = 0 return view } func makeShutterOverlayView() -> UIView { let view = UIView() view.alpha = 0 view.backgroundColor = UIColor.black return view } func makeBlurView() -> UIVisualEffectView { let effect = UIBlurEffect(style: .dark) let blurView = UIVisualEffectView(effect: effect) return blurView } }
mit
87a34f580685e6cad1583447ccd7955f
27.698885
147
0.698834
4.341957
false
false
false
false
paulatwilson/HtmlStrings
Sources/HtmlStrings.swift
1
604
import Foundation public class HtmlStrings { public static func escape(html: String) -> String{ var result = html.replacingOccurrences(of: "&", with: "&amp;") result = result.replacingOccurrences(of: "\"", with: "&quot;") result = result.replacingOccurrences(of: "'", with: "&#x27;") result = result.replacingOccurrences(of: "<", with: "&lt;") result = result.replacingOccurrences(of: ">", with: "&gt;") result = result.replacingOccurrences(of: "/", with: "&#x2F;") result = result.replacingOccurrences(of: "\\", with: "&#x5C;") return result } }
mit
02a532dea0f02d2b646bf4cfba8c90ad
36.75
68
0.620861
4.253521
false
false
false
false
rymcol/Linux-Server-Side-Swift-Benchmarking
VaporPress/App/IndexHandler.swift
1
1854
#if os(Linux) import Glibc #else import Darwin #endif import Core struct IndexHandler { func loadPageContent() -> Bytes { var post = "No matching post was found".bytes let randomContent = ContentGenerator().generate() if let firstPost = randomContent["Test Post 1"] { post = firstPost } let imageNumber = Int(arc4random_uniform(25) + 1) var finalContent = "<section id=\"content\"><div class=\"container\"><div class=\"row\"><div class=\"banner center-block\"><div><img src=\"/img/[email protected]\" alt=\"Swift Based Blog\" class=\"img-responsive banner center-block\" /></div> <div><img src=\"/img/random/random-1.jpg\" alt=\"Swift Based Blog\" class=\"img-responsive banner center-block\" /></div> <div><img src=\"/img/random/random-2.jpg\" alt=\"Swift Based Blog\" class=\"img-responsive banner center-block\" /></div> <div><img src=\"/img/random/random-3.jpg\" alt=\"Swift Based Blog\" class=\"img-responsive banner center-block\" /></div> <div><img src=\"/img/random/random-4.jpg\" alt=\"Swift Based Blog\" class=\"img-responsive banner center-block\" /></div> <div><img src=\"/img/random/random-5.jpg\" alt=\"Swift Based Blog\" class=\"img-responsive banner center-block\" /></div></div></div><div class=\"row\"><div class=\"col-xs-12\"><h1>".bytes finalContent += "Test Post 1".bytes finalContent += "</h1><img src=\"".bytes finalContent += "/img/random/random-\(imageNumber).jpg\" alt=\"Random Image \(imageNumber)\" class=\"alignleft feature-image img-responsive\" />".bytes finalContent += "<div class=\"content\">".bytes finalContent += post finalContent += "</div>".bytes finalContent += "</div></div</div></section>".bytes return finalContent } }
apache-2.0
0d681c32d940a2ee8b19a7aba87e129a
55.181818
923
0.619741
4.138393
false
true
false
false
Driftt/drift-sdk-ios
Drift/Models/MessageRequest.swift
2
3554
// // MessageRequest.swift // Drift-SDK // // Created by Eoin O'Connell on 06/02/2018. // Copyright © 2018 Drift. All rights reserved. // class MessageRequest { var body: String = "" var type:ContentType = .Chat var attachments: [Int64] = [] var requestId: Double = Date().timeIntervalSince1970 var googleMeeting: GoogleMeeting? var userAvailability: UserAvailability? var conversationId: Int64? var meetingUserId: Int64? var meetingTimeSlot:Date? init (body: String, contentType: ContentType = .Chat, attachmentIds: [Int64] = []) { self.body = TextHelper.wrapTextInHTML(text: body) self.type = contentType self.attachments = attachmentIds } init(googleMeeting: GoogleMeeting, userAvailability: UserAvailability, meetingUserId: Int64, conversationId: Int64, timeSlot: Date) { self.body = "" self.type = .Chat self.googleMeeting = googleMeeting self.userAvailability = userAvailability self.conversationId = conversationId self.meetingUserId = meetingUserId self.meetingTimeSlot = timeSlot } func getContextUserAgent() -> String { var userAgent = "Mobile App / \(UIDevice.current.drift_modelName) / \(UIDevice.current.systemName) \(UIDevice.current.systemVersion)" if let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] { userAgent.append(" / App Version: \(version)") } return userAgent } func toJSON() -> [String: Any]{ var json:[String : Any] = [ "body": body, "type": type.rawValue, "attachments": attachments, "context": ["userAgent": getContextUserAgent()] ] if let googleMeetingId = googleMeeting?.meetingId, let googleMeetingURL = googleMeeting?.meetingURL, let meetingDuration = userAvailability?.duration, let meetingUserId = meetingUserId, let meetingTimeSlot = meetingTimeSlot, let conversationId = conversationId, let agentTimeZone = userAvailability?.timezone{ let apointment: [String: Any] = [ "id":googleMeetingId, "url": googleMeetingURL, "availabilitySlot": meetingTimeSlot.timeIntervalSince1970*1000, "slotDuration": meetingDuration, "agentId": meetingUserId, "conversationId": conversationId, "endUserTimeZone": TimeZone.current.identifier, "agentTimeZone": agentTimeZone ] let attributes: [String: Any] = [ "scheduleMeetingFlow": true, "scheduleMeetingWith":meetingUserId, "appointmentInfo":apointment] json["attributes"] = attributes } return json } func generateFakeMessage(conversationId:Int64, userId: Int64) -> Message { let message = Message(uuid: UUID().uuidString, body: body, contentType: type, createdAt: Date(), authorId: userId, authorType: .EndUser, conversationId: conversationId, requestId: requestId, fakeMessage: true) message.formattedBody = TextHelper.attributedTextForString(text: body) message.sendStatus = .Pending return message } }
mit
634fb8c729fa040c8c32e680fdfc0f4e
33.163462
141
0.590205
5.225
false
false
false
false
hjw6160602/JourneyNotes
JourneyNotes/Classes/Common/NetworkManager/NetworkTools/AnalyzingTool.swift
1
1485
// // AnalyzingTool.swift // LvmmModel // // Created by 贺嘉炜 on 2017/1/4. // Copyright © 2017年 Nee. All rights reserved. // import Foundation struct AnalyzingTool { static let Directory = "RequestBundle.bundle" /// paramsFromPlist /// 根据传入的资源文件名称引找到请求数据字典 /// - Parameters: /// - resource: 资源文件名称 /// - Returns: 返回需要请求的url,请求方法method,请求参数params static func paramsFromPlist(resource:String) -> (host:String, page:String, method:String, params:[String: String]?){ let path = Bundle.main.path(forResource: resource, ofType: "plist", inDirectory: Directory) let dict = NSMutableDictionary(contentsOfFile: path!)! let host = dict["host"] as! String let page = dict["page"] as! String let method = dict["method"] as! String // let version = dict["version"] as! String let originParams = dict["params"] as! [String:String] var params:[String: String]? if let version = dict["version"] { params = ["version":version as! String] } for (key, value) in originParams { let valueString = value let length = valueString.lengthOfBytes(using: String.Encoding.utf8) if length > 0 { params?[key] = value } } return (host, page, method, params) } }
mit
028a798bef7d23c46e0557351d1738ed
29.888889
120
0.586331
4.076246
false
false
false
false
xipengyang/SwiftApp1
we sale assistant/we sale assistant/MKLayer.swift
1
8037
// // MKLayer.swift // MaterialKit // // Created by Le Van Nghia on 11/15/14. // Copyright (c) 2014 Le Van Nghia. All rights reserved. // import UIKit import QuartzCore public enum MKTimingFunction { case Linear case EaseIn case EaseOut case Custom(Float, Float, Float, Float) public var function: CAMediaTimingFunction { switch self { case .Linear: return CAMediaTimingFunction(name: "linear") case .EaseIn: return CAMediaTimingFunction(name: "easeIn") case .EaseOut: return CAMediaTimingFunction(name: "easeOut") case .Custom(let cpx1, let cpy1, let cpx2, let cpy2): return CAMediaTimingFunction(controlPoints: cpx1, cpy1, cpx2, cpy2) } } } public enum MKRippleLocation { case Center case Left case Right case TapLocation } public class MKLayer { private var superLayer: CALayer! private let rippleLayer = CALayer() private let backgroundLayer = CALayer() private let maskLayer = CAShapeLayer() public var rippleLocation: MKRippleLocation = .TapLocation { didSet { let origin: CGPoint? let sw = CGRectGetWidth(superLayer.bounds) let sh = CGRectGetHeight(superLayer.bounds) switch rippleLocation { case .Center: origin = CGPoint(x: sw/2, y: sh/2) case .Left: origin = CGPoint(x: sw*0.25, y: sh/2) case .Right: origin = CGPoint(x: sw*0.75, y: sh/2) default: origin = nil } if let origin = origin { setCircleLayerLocationAt(origin) } } } public var ripplePercent: Float = 0.9 { didSet { if ripplePercent > 0 { let sw = CGRectGetWidth(superLayer.bounds) let sh = CGRectGetHeight(superLayer.bounds) let circleSize = CGFloat(max(sw, sh)) * CGFloat(ripplePercent) let circleCornerRadius = circleSize/2 rippleLayer.cornerRadius = circleCornerRadius setCircleLayerLocationAt(CGPoint(x: sw/2, y: sh/2)) } } } public init(superLayer: CALayer) { self.superLayer = superLayer let sw = CGRectGetWidth(superLayer.bounds) let sh = CGRectGetHeight(superLayer.bounds) // background layer backgroundLayer.frame = superLayer.bounds backgroundLayer.opacity = 0.0 superLayer.addSublayer(backgroundLayer) // ripple layer let circleSize = CGFloat(max(sw, sh)) * CGFloat(ripplePercent) let rippleCornerRadius = circleSize/2 rippleLayer.opacity = 0.0 rippleLayer.cornerRadius = rippleCornerRadius setCircleLayerLocationAt(CGPoint(x: sw/2, y: sh/2)) backgroundLayer.addSublayer(rippleLayer) // mask layer setMaskLayerCornerRadius(superLayer.cornerRadius) backgroundLayer.mask = maskLayer } public func superLayerDidResize() { CATransaction.begin() CATransaction.setDisableActions(true) backgroundLayer.frame = superLayer.bounds setMaskLayerCornerRadius(superLayer.cornerRadius) CATransaction.commit() setCircleLayerLocationAt(CGPoint(x: superLayer.bounds.width/2, y: superLayer.bounds.height/2)) } public func enableOnlyCircleLayer() { backgroundLayer.removeFromSuperlayer() superLayer.addSublayer(rippleLayer) } public func setBackgroundLayerColor(color: UIColor) { backgroundLayer.backgroundColor = color.CGColor } public func setCircleLayerColor(color: UIColor) { rippleLayer.backgroundColor = color.CGColor } public func didChangeTapLocation(location: CGPoint) { if rippleLocation == .TapLocation { setCircleLayerLocationAt(location) } } public func setMaskLayerCornerRadius(cornerRadius: CGFloat) { maskLayer.path = UIBezierPath(roundedRect: backgroundLayer.bounds, cornerRadius: cornerRadius).CGPath } public func enableMask(enable: Bool = true) { backgroundLayer.mask = enable ? maskLayer : nil } public func setBackgroundLayerCornerRadius(cornerRadius: CGFloat) { backgroundLayer.cornerRadius = cornerRadius } private func setCircleLayerLocationAt(center: CGPoint) { let bounds = superLayer.bounds let width = CGRectGetWidth(bounds) let height = CGRectGetHeight(bounds) let subSize = CGFloat(max(width, height)) * CGFloat(ripplePercent) let subX = center.x - subSize/2 let subY = center.y - subSize/2 // disable animation when changing layer frame CATransaction.begin() CATransaction.setDisableActions(true) rippleLayer.cornerRadius = subSize / 2 rippleLayer.frame = CGRect(x: subX, y: subY, width: subSize, height: subSize) CATransaction.commit() } // MARK - Animation public func animateScaleForCircleLayer(fromScale: Float, toScale: Float, timingFunction: MKTimingFunction, duration: CFTimeInterval) { let rippleLayerAnim = CABasicAnimation(keyPath: "transform.scale") rippleLayerAnim.fromValue = fromScale rippleLayerAnim.toValue = toScale let opacityAnim = CABasicAnimation(keyPath: "opacity") opacityAnim.fromValue = 1.0 opacityAnim.toValue = 0.0 let groupAnim = CAAnimationGroup() groupAnim.duration = duration groupAnim.timingFunction = timingFunction.function groupAnim.removedOnCompletion = false groupAnim.fillMode = kCAFillModeForwards groupAnim.animations = [rippleLayerAnim, opacityAnim] rippleLayer.addAnimation(groupAnim, forKey: nil) } public func animateAlphaForBackgroundLayer(timingFunction: MKTimingFunction, duration: CFTimeInterval) { let backgroundLayerAnim = CABasicAnimation(keyPath: "opacity") backgroundLayerAnim.fromValue = 1.0 backgroundLayerAnim.toValue = 0.0 backgroundLayerAnim.duration = duration backgroundLayerAnim.timingFunction = timingFunction.function backgroundLayer.addAnimation(backgroundLayerAnim, forKey: nil) } public func animateSuperLayerShadow(fromRadius: CGFloat, toRadius: CGFloat, fromOpacity: Float, toOpacity: Float, timingFunction: MKTimingFunction, duration: CFTimeInterval) { animateShadowForLayer(superLayer, fromRadius: fromRadius, toRadius: toRadius, fromOpacity: fromOpacity, toOpacity: toOpacity, timingFunction: timingFunction, duration: duration) } public func animateMaskLayerShadow() { } private func animateShadowForLayer(layer: CALayer, fromRadius: CGFloat, toRadius: CGFloat, fromOpacity: Float, toOpacity: Float, timingFunction: MKTimingFunction, duration: CFTimeInterval) { let radiusAnimation = CABasicAnimation(keyPath: "shadowRadius") radiusAnimation.fromValue = fromRadius radiusAnimation.toValue = toRadius let opacityAnimation = CABasicAnimation(keyPath: "shadowOpacity") opacityAnimation.fromValue = fromOpacity opacityAnimation.toValue = toOpacity let groupAnimation = CAAnimationGroup() groupAnimation.duration = duration groupAnimation.timingFunction = timingFunction.function groupAnimation.removedOnCompletion = false groupAnimation.fillMode = kCAFillModeForwards groupAnimation.animations = [radiusAnimation, opacityAnimation] layer.addAnimation(groupAnimation, forKey: nil) } public func removeAllAnimations() { self.backgroundLayer.removeAllAnimations() self.rippleLayer.removeAllAnimations() } }
mit
61ff94a6ae2909ee55bd0fb599f7a615
34.883929
194
0.652482
5.659859
false
false
false
false
ai260697793/weibo
新浪微博/新浪微博/UIs/Login/MHOAuthViewController.swift
1
3981
// // MHOAuthViewController.swift // 新浪微博 // // Created by 莫煌 on 16/5/6. // Copyright © 2016年 MH. All rights reserved. // import UIKit import SVProgressHUD class MHOAuthViewController: UIViewController, UIWebViewDelegate { let webView = UIWebView() override func loadView() { view = webView webView.delegate = self setupNav() } /// App Key:2990485310 /// App Secret:c0e78554e15a9f441a9f59dac7d6a772 /// https://api.weibo.com/oauth2/authorize?client_id=2990485310&redirect_uri=http://www.baidu.com override func viewDidLoad() { super.viewDidLoad() let request = NSURLRequest(URL: NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=2990485310&redirect_uri=http://www.baidu.com")!) webView.loadRequest(request) // Do any additional setup after loading the view. } // MARK: - 设置NAV private func setupNav(){ navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(MHOAuthViewController.dismiss)) navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(MHOAuthViewController.autoFill)) } // MARK: - 按钮点击方法 @objc private func dismiss() { self.dismissViewControllerAnimated(true, completion: nil) } @objc private func autoFill() { let jsString = "document.getElementById('userId').value='18373280031';document.getElementById('passwd').value='woAIya'" webView.stringByEvaluatingJavaScriptFromString(jsString) } } extension MHOAuthViewController { // MARK: - webView代理方法 func webViewDidStartLoad(webView: UIWebView) { SVProgressHUD.show() } func webViewDidFinishLoad(webView: UIWebView) { SVProgressHUD.dismiss() } func webView(webView: UIWebView, didFailLoadWithError error: NSError?) { SVProgressHUD.showErrorWithStatus(error?.description) } func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool { // print(request) /* <NSMutableURLRequest: 0x7fd63b9cfca0> { URL: https://api.weibo.com/oauth2/authorize?client_id=2990485310&redirect_uri=http://www.baidu.com# } <NSMutableURLRequest: 0x7fd63ba1ae20> { URL: https://api.weibo.com/oauth2/authorize } <NSMutableURLRequest: 0x7fd639541e80> { URL: http://www.baidu.com/?code=1c2f67b2f70fb30755aca6963c1763f7 } <NSMutableURLRequest: 0x7fd63ba00290> { URL: https://m.baidu.com/?code=1c2f67b2f70fb30755aca6963c1763f7&from=844b&vit=fps } */ if let absoluteString = request.URL?.absoluteString { if absoluteString.hasPrefix(AppRedictUrl) { // print(absoluteString) if let query = request.URL?.query { // 截取到 code=d51f8c7887d8abe18a202a3e5c8f38fc // print(query) let code = query.substringFromIndex("code=".endIndex) // print(code) // 调用afn请求,用code来换取token // 调用成功,切换视图控制器,失败,显示失败信息 MHOauthViewModel.sharedInstance.loadToken(code, success: { // self.dismiss() // 发送通知 NSNotificationCenter.defaultCenter().postNotificationName(kNotificationChangeViewController, object: self) // SVProgressHUD.dismiss() }, failed: { //处理失败信息 }) } } } return true } }
mit
e2957e2846e77c460b3aa502bd123429
34.611111
174
0.616225
4.355606
false
false
false
false
Alua-Kinzhebayeva/iOS-PDF-Reader
Sources/Classes/PDFThumbnailCollectionViewController.swift
2
2899
// // PDFThumbnailCollectionViewController.swift // PDFReader // // Created by Ricardo Nunez on 7/9/16. // Copyright © 2016 AK. All rights reserved. // import UIKit /// Delegate that is informed of important interaction events with the current thumbnail collection view protocol PDFThumbnailControllerDelegate: class { /// User has tapped on thumbnail func didSelectIndexPath(_ indexPath: IndexPath) } /// Bottom collection of thumbnails that the user can interact with internal final class PDFThumbnailCollectionViewController: UICollectionViewController { /// Current document being displayed var document: PDFDocument! /// Current page index being displayed var currentPageIndex: Int = 0 { didSet { guard let collectionView = collectionView else { return } guard let pageImages = pageImages else { return } guard pageImages.count > 0 else { return } let curentPageIndexPath = IndexPath(row: currentPageIndex, section: 0) if !collectionView.indexPathsForVisibleItems.contains(curentPageIndexPath) { collectionView.scrollToItem(at: curentPageIndexPath, at: .centeredHorizontally, animated: true) } collectionView.reloadData() } } /// Calls actions when certain cells have been interacted with weak var delegate: PDFThumbnailControllerDelegate? /// Small thumbnail image representations of the pdf pages private var pageImages: [UIImage]? { didSet { collectionView?.reloadData() } } override func viewDidLoad() { super.viewDidLoad() DispatchQueue.global(qos: .background).async { self.document.allPageImages(callback: { (images) in DispatchQueue.main.async { self.pageImages = images } }) } } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return pageImages?.count ?? 0 } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! PDFThumbnailCell cell.imageView?.image = pageImages?[indexPath.row] cell.alpha = currentPageIndex == indexPath.row ? 1 : 0.2 return cell } @objc func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize { return PDFThumbnailCell.cellSize } override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { delegate?.didSelectIndexPath(indexPath) } }
mit
2df3d36c556ab393fb9ea62e8a6a2385
36.636364
175
0.678054
5.704724
false
false
false
false
yasuoza/SAHistoryNavigationViewController
SAHistoryNavigationViewControllerSample/Pods/SAHistoryNavigationViewController/SAHistoryNavigationViewController/SAHistoryViewController.swift
7
3675
// // SAHistoryViewController.swift // SAHistoryNavigationViewControllerSample // // Created by 鈴木大貴 on 2015/03/26. // Copyright (c) 2015年 鈴木大貴. All rights reserved. // import UIKit protocol SAHistoryViewControllerDelegate: class { func didSelectIndex(index: Int) } class SAHistoryViewController: UIViewController { let collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: UICollectionViewFlowLayout()) var images: [UIImage]? var currentIndex: Int = 0 weak var delegate: SAHistoryViewControllerDelegate? private let kLineSpace: CGFloat = 20.0 override init() { super.init() } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. let size = UIScreen.mainScreen().bounds.size if let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout { layout.itemSize = size layout.minimumInteritemSpacing = 0.0 layout.minimumLineSpacing = 20.0 layout.sectionInset = UIEdgeInsets(top: 0.0, left: size.width, bottom: 0.0, right: size.width) layout.scrollDirection = .Horizontal } collectionView.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "Cell") collectionView.delegate = self collectionView.dataSource = self collectionView.backgroundColor = .clearColor() collectionView.showsHorizontalScrollIndicator = false NSLayoutConstraint.applyAutoLayout(view, target: collectionView, index: nil, top: 0.0, left: 0.0, right: 0.0, bottom: 0.0, height: nil, width: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func reload() { collectionView.reloadData() scrollToIndex(currentIndex, animated: false) } func scrollToIndex(index: Int, animated: Bool) { let width = UIScreen.mainScreen().bounds.size.width collectionView.setContentOffset(CGPoint(x: (width + kLineSpace) * CGFloat(index), y: 0), animated: animated) } } extension SAHistoryViewController: UICollectionViewDataSource { func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if let count = images?.count { return count } return 0 } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as UICollectionViewCell for view in cell.subviews { if let view = view as? UIImageView { view.removeFromSuperview() } } let imageView = UIImageView(frame: cell.bounds) imageView.image = images?[indexPath.row] cell.addSubview(imageView) return cell } } extension SAHistoryViewController: UICollectionViewDelegate { func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { collectionView.deselectItemAtIndexPath(indexPath, animated: false) delegate?.didSelectIndex(indexPath.row) } }
mit
7c2464e7d6584e11ebf0f1015a6282f8
33.509434
155
0.678972
5.401773
false
false
false
false
MellongLau/LiteAutoLayout
LiteAutoLayout.swift
1
19825
// // Copyright (c) 2016 Mellong Lau // https://github.com/MellongLau/LiteAutoLayout // // 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 // MARK: - Public API prefix operator ~> public extension UIView { /// Set layout constraints between two views /// /// - parameter left: the subview, or the view is at the right or bottom. /// - parameter right: the superview, or the view is at the top or left. /// /// - returns: RelationLiteAutoLayout instance public static func ~> (left: UIView, right: UIView) -> RelationLiteAutoLayout { return RelationLiteAutoLayout(left: left, right: right) } /// Set view's layout attribute /// /// - parameter left: which view's layout constraints to be set /// /// - returns: ItemLiteAutoLayout instance public static prefix func ~> (view: UIView) -> ItemLiteAutoLayout { return ItemLiteAutoLayout(left: view, right: nil) } /// Set the view's layout attribute /// /// - returns: ItemLiteAutoLayout instance @objc public func startLayout() -> ItemLiteAutoLayout { return ItemLiteAutoLayout(left: self, right: nil) } /// Set layout constraints between two views /// /// - parameter toView: the view's superview, or at the top or left of the view. /// /// - returns: RelationLiteAutoLayout instance @objc public func startLayout(toView: UIView) -> RelationLiteAutoLayout { return RelationLiteAutoLayout(left: self, right: toView) } } fileprivate enum ContraintType { case equalHeights case equalWidths case leading case trailing case baseline case aspectRatio case centerHorizontally case centerVertically case top case bottom case horizontalSpacing case verticalSpacing } fileprivate class ContraintModel { var type: ContraintType var constant: Float = 0.0 var multiplier: Float = 1.0 var priority: UILayoutPriority = UILayoutPriority.required var relatedBy: NSLayoutConstraint.Relation = .equal init(contraintType: ContraintType, constants: Float) { self.type = contraintType self.constant = constants } init(contraintType: ContraintType, constants: Float, relatedBy: (Int, Int) -> Bool, multiplier: Float, priority: UILayoutPriority) { self.multiplier = multiplier self.priority = priority self.type = contraintType self.constant = constants self.relatedBy = checkOperator(relatedBy) } private func checkOperator(_ test: (Int, Int) -> Bool) -> NSLayoutConstraint.Relation{ let lessThan = test(0, 1) let equal = test(0, 0) let greaterThan = test(1, 0) let lessThanOrEqual = lessThan && equal let greaterThanOrEqual = greaterThan && equal if greaterThanOrEqual { return .greaterThanOrEqual } if lessThanOrEqual { return .lessThanOrEqual } assert(!lessThan, "Only <=, >= and == operators allow!") assert(!greaterThan, "Only <=, >= and == operators allow!") return .equal } } @objc public class ItemLiteAutoLayout: LiteAutoLayout { @objc @discardableResult public func marginTopToSafeArea(_ constant: Float = 0) -> ItemLiteAutoLayout { let superview = firstItem.superview! firstItem.topAnchor.constraint(equalTo: superview.safeAreaLayoutGuide.topAnchor, constant: constant.cgFloat).isActive = true return self } @objc @discardableResult public func marginBottomToSafeArea(_ constant: Float = 0) -> ItemLiteAutoLayout { let superview = firstItem.superview! firstItem.bottomAnchor.constraint(equalTo: superview.safeAreaLayoutGuide.bottomAnchor, constant: constant.cgFloat).isActive = true return self } @objc @discardableResult public func marginTop(_ constant: Float = 0, relatedBy: ((Int, Int) -> Bool) = (==), multiplier: Float = 1.0, priority: UILayoutPriority = UILayoutPriority.required) -> ItemLiteAutoLayout { let item = ContraintModel(contraintType: .top, constants: constant, relatedBy: relatedBy, multiplier: multiplier, priority: priority) constraints.append(item) secondItem = firstItem.superview addContraint(contraintModel: item) secondItem = nil return self } @objc @discardableResult public func marginBottom(_ constant: Float = 0, relatedBy: ((Int, Int) -> Bool) = (==), multiplier: Float = 1.0, priority: UILayoutPriority = UILayoutPriority.required) -> ItemLiteAutoLayout { let item = ContraintModel(contraintType: .bottom, constants: -constant, relatedBy: relatedBy, multiplier: multiplier, priority: priority) constraints.append(item) secondItem = firstItem.superview addContraint(contraintModel: item) secondItem = nil return self } @objc @discardableResult public func marginLeft(_ constant: Float = 0, relatedBy: ((Int, Int) -> Bool) = (==), multiplier: Float = 1.0, priority: UILayoutPriority = UILayoutPriority.required) -> ItemLiteAutoLayout { let item = ContraintModel(contraintType: .leading, constants: constant, relatedBy: relatedBy, multiplier: multiplier, priority: priority) constraints.append(item) secondItem = firstItem.superview addContraint(contraintModel: item) secondItem = nil return self } @objc @discardableResult public func marginRight(_ constant: Float = 0, relatedBy: ((Int, Int) -> Bool) = (==), multiplier: Float = 1.0, priority: UILayoutPriority = UILayoutPriority.required) -> ItemLiteAutoLayout { let item = ContraintModel(contraintType: .trailing, constants: -constant, relatedBy: relatedBy, multiplier: multiplier, priority: priority) constraints.append(item) secondItem = firstItem.superview addContraint(contraintModel: item) secondItem = nil return self } @objc @discardableResult public func height(_ constant: Float = 0, relatedBy: ((Int, Int) -> Bool) = (==), multiplier: Float = 1.0, priority: UILayoutPriority = UILayoutPriority.required) -> ItemLiteAutoLayout { let item = ContraintModel(contraintType: .equalHeights, constants: constant, relatedBy: relatedBy, multiplier: multiplier, priority: priority) constraints.append(item) addContraint(contraintModel: item) return self } @objc @discardableResult public func width(_ constant: Float = 0, relatedBy: ((Int, Int) -> Bool) = (==), multiplier: Float = 1.0, priority: UILayoutPriority = UILayoutPriority.required) -> ItemLiteAutoLayout { let item = ContraintModel(contraintType: .equalWidths, constants: constant, relatedBy: relatedBy, multiplier: multiplier, priority: priority) constraints.append(item) addContraint(contraintModel: item) return self } @objc @discardableResult public func centerVertically(_ constant: Float = 0, relatedBy: ((Int, Int) -> Bool) = (==), multiplier: Float = 1.0, priority: UILayoutPriority = UILayoutPriority.required) -> ItemLiteAutoLayout { let item = ContraintModel(contraintType: .centerVertically, constants: constant, relatedBy: relatedBy, multiplier: multiplier, priority: priority) constraints.append(item) secondItem = firstItem.superview addContraint(contraintModel: item) secondItem = nil return self } @objc @discardableResult public func centerHorizontally(_ constant: Float = 0, relatedBy: ((Int, Int) -> Bool) = (==), multiplier: Float = 1.0, priority: UILayoutPriority = UILayoutPriority.required) -> ItemLiteAutoLayout { let item = ContraintModel(contraintType: .centerHorizontally, constants: constant, relatedBy: relatedBy, multiplier: multiplier, priority: priority) constraints.append(item) secondItem = firstItem.superview addContraint(contraintModel: item) secondItem = nil return self } @objc @discardableResult public func aspectRatio(width: Float, height: Float, relatedBy: ((Int, Int) -> Bool) = (==), priority: UILayoutPriority = UILayoutPriority.required) -> ItemLiteAutoLayout { let item = ContraintModel(contraintType: .aspectRatio, constants: 0, relatedBy: relatedBy, multiplier: width/height, priority: priority) constraints.append(item) addContraint(contraintModel: item) return self } } @objc public class RelationLiteAutoLayout: LiteAutoLayout { @objc @discardableResult public func baseline(_ constant: Float = 0, relatedBy: ((Int, Int) -> Bool) = (==), multiplier: Float = 1.0, priority: UILayoutPriority = UILayoutPriority.required) -> RelationLiteAutoLayout { guard let _ = secondItem else { return self } let item = ContraintModel(contraintType: .baseline, constants: constant, relatedBy: relatedBy, multiplier: multiplier, priority: priority) constraints.append(item) addContraint(contraintModel: item) return self } @objc @discardableResult public func leading(_ constant: Float = 0, relatedBy: ((Int, Int) -> Bool) = (==), multiplier: Float = 1.0, priority: UILayoutPriority = UILayoutPriority.required) -> RelationLiteAutoLayout { guard let _ = secondItem else { return self } let item = ContraintModel(contraintType: .leading, constants: constant, relatedBy: relatedBy, multiplier: multiplier, priority: priority) constraints.append(item) addContraint(contraintModel: item) return self } @objc @discardableResult public func bottom(_ constant: Float = 0, relatedBy: ((Int, Int) -> Bool) = (==), multiplier: Float = 1.0, priority: UILayoutPriority = UILayoutPriority.required) -> RelationLiteAutoLayout { guard let _ = secondItem else { return self } let item = ContraintModel(contraintType: .bottom, constants: constant, relatedBy: relatedBy, multiplier: multiplier, priority: priority) constraints.append(item) addContraint(contraintModel: item) return self } @objc @discardableResult public func top(_ constant: Float = 0, relatedBy: ((Int, Int) -> Bool) = (==), multiplier: Float = 1.0, priority: UILayoutPriority = UILayoutPriority.required) -> RelationLiteAutoLayout { guard let _ = secondItem else { return self } let item = ContraintModel(contraintType: .top, constants: constant, relatedBy: relatedBy, multiplier: multiplier, priority: priority) constraints.append(item) addContraint(contraintModel: item) return self } @objc @discardableResult public func trailing(_ constant: Float = 0, relatedBy: ((Int, Int) -> Bool) = (==), multiplier: Float = 1.0, priority: UILayoutPriority = UILayoutPriority.required) -> RelationLiteAutoLayout { guard let _ = secondItem else { return self } let item = ContraintModel(contraintType: .trailing, constants: constant, relatedBy: relatedBy, multiplier: multiplier, priority: priority) constraints.append(item) addContraint(contraintModel: item) return self } @objc @discardableResult public func horizontalSpacing(_ constant: Float = 0, relatedBy: ((Int, Int) -> Bool) = (==), multiplier: Float = 1.0, priority: UILayoutPriority = UILayoutPriority.required) -> RelationLiteAutoLayout { guard let _ = secondItem else { return self } let item = ContraintModel(contraintType: .horizontalSpacing, constants: constant, relatedBy: relatedBy, multiplier: multiplier, priority: priority) constraints.append(item) addContraint(contraintModel: item) return self } @objc @discardableResult public func verticalSpacing(_ constant: Float = 0, relatedBy: ((Int, Int) -> Bool) = (==), multiplier: Float = 1.0, priority: UILayoutPriority = UILayoutPriority.required) -> RelationLiteAutoLayout { guard let _ = secondItem else { return self } let item = ContraintModel(contraintType: .verticalSpacing, constants: constant, relatedBy: relatedBy, multiplier: multiplier, priority: priority) constraints.append(item) addContraint(contraintModel: item) return self } @objc @discardableResult public func equalHeights(_ constant: Float = 0, relatedBy: ((Int, Int) -> Bool) = (==), multiplier: Float = 1.0, priority: UILayoutPriority = UILayoutPriority.required) -> RelationLiteAutoLayout { let item = ContraintModel(contraintType: .equalHeights, constants: constant, relatedBy: relatedBy, multiplier: multiplier, priority: priority) constraints.append(item) addContraint(contraintModel: item) return self } @objc @discardableResult public func equalWidths(_ constant: Float = 0, relatedBy: ((Int, Int) -> Bool) = (==), multiplier: Float = 1.0, priority: UILayoutPriority = UILayoutPriority.required) -> RelationLiteAutoLayout { let item = ContraintModel(contraintType: .equalWidths, constants: constant, relatedBy: relatedBy, multiplier: multiplier, priority: priority) constraints.append(item) addContraint(contraintModel: item) return self } @objc @discardableResult public func centerVertically(_ constant: Float = 0, relatedBy: ((Int, Int) -> Bool) = (==), multiplier: Float = 1.0, priority: UILayoutPriority = UILayoutPriority.required) -> RelationLiteAutoLayout { let item = ContraintModel(contraintType: .centerVertically, constants: constant, relatedBy: relatedBy, multiplier: multiplier, priority: priority) constraints.append(item) addContraint(contraintModel: item) return self } @objc @discardableResult public func centerHorizontally(_ constant: Float = 0, relatedBy: ((Int, Int) -> Bool) = (==), multiplier: Float = 1.0, priority: UILayoutPriority = UILayoutPriority.required) -> RelationLiteAutoLayout { let item = ContraintModel(contraintType: .centerHorizontally, constants: constant, relatedBy: relatedBy, multiplier: multiplier, priority: priority) constraints.append(item) addContraint(contraintModel: item) return self } } @objc public class LiteAutoLayout: NSObject { fileprivate var constraints: [ContraintModel] = [] fileprivate var firstItem: UIView! fileprivate var secondItem: UIView? public init(left: UIView, right: UIView?) { left.translatesAutoresizingMaskIntoConstraints = false firstItem = left secondItem = right } fileprivate func addContraint(contraintModel: ContraintModel) -> Void { let item = contraintModel var layoutConstraint: NSLayoutConstraint! var layoutAttributes: (fistAttribute: NSLayoutConstraint.Attribute, secondAttibute: NSLayoutConstraint.Attribute) switch item.type { case .baseline: layoutAttributes = (.lastBaseline, .lastBaseline) case .bottom: layoutAttributes = (.bottom, .bottom) case .top: layoutAttributes = (.top, .top) case .centerVertically: layoutAttributes = (.centerY, .centerY) case .centerHorizontally: layoutAttributes = (.centerX, .centerX) case .equalHeights: layoutAttributes = (.height, .height) case .equalWidths: layoutAttributes = (.width, .width) case .leading: layoutAttributes = (.leading, .leading) case .trailing: layoutAttributes = (.trailing, .trailing) case .horizontalSpacing: layoutAttributes = (.leading, .trailing) case .verticalSpacing: layoutAttributes = (.top, .bottom) case .aspectRatio: layoutAttributes = (.width, .height) layoutConstraint = NSLayoutConstraint(item: firstItem, attribute: .width, relatedBy: item.relatedBy, toItem: firstItem, attribute: .height, multiplier: CGFloat(item.multiplier), constant: CGFloat(item.constant)) } if item.type != .aspectRatio { layoutConstraint = NSLayoutConstraint(item: firstItem, attribute: layoutAttributes.fistAttribute, relatedBy: item.relatedBy, toItem: secondItem, attribute: layoutAttributes.secondAttibute, multiplier: CGFloat(item.multiplier), constant: CGFloat(item.constant)) } layoutConstraint.priority = item.priority // if second item is nil, add constraint to the first item and return. guard let _ = secondItem else { firstItem.addConstraint(layoutConstraint) return; } // find the parent view to add layout constraint if exist. if firstItem === secondItem?.superview { // firstItem.constraints firstItem.addConstraint(layoutConstraint) }else if firstItem.superview === secondItem { let constraints = secondItem?.constraints.filter { $0.firstItem === firstItem && $0.secondItem === secondItem && layoutAttributes.fistAttribute == $0.firstAttribute && layoutAttributes.secondAttibute == $0.secondAttribute } if let safeConstraints = constraints { secondItem?.removeConstraints(safeConstraints) } secondItem?.addConstraint(layoutConstraint) }else if firstItem.superview === secondItem?.superview { firstItem.superview?.addConstraint(layoutConstraint) } else { firstItem.addConstraint(layoutConstraint) } } }
mit
152fcb17430c8e28c1307a6483e0c275
44.159453
231
0.643279
5.48713
false
false
false
false
devnikor/mpvx
mpvx/Core/Player.swift
1
2307
// // Player.swift // mpvx // // Created by Игорь Никитин on 16.02.16. // Copyright © 2016 Coder's Cake. All rights reserved. // import Cocoa import CleanroomLogger class Player { // // MARK: - Properties // // private let core: Core // // // MARK: Initialization // // // init() throws { // // } // // /** // Initializes mpv handle with default options and given output view // // - parameter view: video output view // // - throws: `Player.Error` on error // */ // private func initializeWithView(view: UnsafeMutablePointer<Void>) throws { // if let error = errorWithCode(mpv_set_option(context, "wid", MPV_FORMAT_INT64, view)) { // Log.error?.message("Failed to set window \(error.description)") // throw error // } // // // // setDefaultOptions() // observeNeededValues() // // Log.verbose?.message("Trying to initialize mpv handle") // // if let error = errorWithCode(mpv_initialize(context)) { // Log.error?.message("Failed to initialize mpv handle: \(error.description)") // throw error // } // // // Initialization done. Deal with events in background // dispatch_async(queue) { // func wakeup(data: UnsafeMutablePointer<Void>) -> Void { // let me = Unmanaged<Player>.fromOpaque(COpaquePointer(data)).takeUnretainedValue() // me.readEvents() // } // // let pointer = UnsafeMutablePointer<Void>(Unmanaged.passUnretained(self).toOpaque()) // mpv_set_wakeup_callback(self.context, wakeup, pointer) // } // } // // private func setDefaultOptions() { // // TODO: Should not hardcode options // Log.verbose?.message("Setting default options") // let _ = try? setOption("audio-client-name", to: "mpvx") // let _ = try? setOption("vo", to: "opengl-hq:icc-profile-auto") // let _ = try? setOption("hwdec", to: "auto") // let _ = try? setOption("hwdec-codecs", to: "all") // } // // private func observeNeededValues() { // mpv_observe_property(context, 0, "time-pos", mpv_format) // } }
gpl-2.0
6cf14783a6b72f35b5afce110994b1b0
28.792208
99
0.551874
3.730081
false
false
false
false
yaslab/KanaDouble
AutoLaunchHelper/Application/AppDelegate.swift
1
906
// // AppDelegate.swift // AutoLaunchHelper // // Created by Yasuhiro Hatta on 2017/10/14. // Copyright © 2017 yaslab. All rights reserved. // import Cocoa private let kMainAppName = "KanaDouble" private let kMainAppBundleIdentifier = "net.yaslab.\(kMainAppName)" private let kMainAppURLScheme: URL = { var builder = URLComponents() builder.scheme = kMainAppName return builder.url! }() @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(_ notification: Notification) { let apps = NSRunningApplication.runningApplications(withBundleIdentifier: kMainAppBundleIdentifier) if apps.count == 0 || apps[0].isActive == false { NSWorkspace.shared.open(kMainAppURLScheme) } // Quit NSApp.perform(#selector(NSApplication.terminate(_:)), with: nil, afterDelay: 0.0) } }
mit
1cbe17f925257c96b6249aae1c8e508e
27.28125
107
0.700552
4.480198
false
false
false
false
m4rr/MosCoding
Flashcards/Flashcards/Flashcard.swift
1
698
// // Flashcard.swift // Flashcards // // Created by Marat S. on 19/11/2016. // Copyright © 2016 m4rr. All rights reserved. // import Foundation import UIKit class Flashcard { let term: String let definition: String let color: UIColor convenience init(term: String, definition: String) { self.init(term: term, definition: definition, color: .black) } init(term: String, definition: String, color: UIColor) { self.term = term self.definition = definition self.color = color } convenience init() { // self.term = "Default term" // self.definition = "Default definiton." self.init(term: "Default term", definition: "Default definiton.") } }
mit
24d69ba5b6838c7475afe943566af9b3
17.837838
69
0.664275
3.611399
false
false
false
false
KinoAndWorld/PinballLoadingView
PinballLoadingViewDemo/ViewController2.swift
1
1902
// // ViewController2.swift // PinballLoadingViewDemo // // Created by kino on 15/5/5. // // import UIKit class ViewController2: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) let loadingView = PinballLoadingView() loadingView.configureBackView = { (frame:CGRect) -> UIView in let contentView = UIView(frame: frame) let imageView = UIImageView(image: UIImage(named: "loadingBack")) imageView.frame = contentView.bounds let blurLayer = UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffectStyle.Light)) blurLayer.frame = contentView.bounds contentView.addSubview(imageView) contentView.addSubview(blurLayer) return contentView } loadingView.showInView(self.view) dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64( UInt64(5.0) * NSEC_PER_SEC)) , dispatch_get_main_queue(), { [weak self] () -> Void in loadingView.stopAnimateAndDismiss() self?.navigationController?.popViewControllerAnimated(true) }) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
0aaa11515764f8f9937db3437afdee0a
30.180328
120
0.629863
5.154472
false
false
false
false
VernonVan/SmartClass
SmartClass/Paper/Create Paper/View/QuestionListViewController.swift
1
3403
// // QuestionListViewController.swift // SmartClass // // Created by Vernon on 16/4/4. // Copyright © 2016年 Vernon. All rights reserved. // import UIKit class QuestionListViewController: UITableViewController { var viewModel: QuestionListViewModel? var intentResultDelegate: IntentResultDelegate? fileprivate var isChanged = false { didSet { if isChanged { navigationItem.leftBarButtonItem = doneBarButton } } } fileprivate let reuseIdentifier = "QuestionCell" fileprivate lazy var doneBarButton: UIBarButtonItem = { let doneBarButton = UIBarButtonItem(title: NSLocalizedString("确定", comment: ""), style: .plain, target: self, action: #selector(doneAction)) doneBarButton.tintColor = ThemeBlueColor return doneBarButton }() override func viewDidLoad() { super.viewDidLoad() tableView.tableFooterView = UIView() tableView.estimatedRowHeight = 60 tableView.rowHeight = UITableViewAutomaticDimension } func doneAction() { intentResultDelegate?.selectQuestionAtIndex(0) _ = navigationController?.popViewController(animated: true) } @IBAction func backAction(_ sender: UIBarButtonItem) { if isChanged == true { intentResultDelegate?.selectQuestionAtIndex(0) } _ = navigationController?.popViewController(animated: true) } @IBAction func editAction(_ sender: UIBarButtonItem) { tableView.setEditing(!tableView.isEditing, animated: true) } // MARK: - Table view override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return viewModel!.numberOfQuestions() } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath) as! QuestionCell let question = viewModel?.questionAtIndexPath((indexPath as NSIndexPath).row) cell.configurForQuestion(question) return cell } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { if tableView.numberOfRows(inSection: 0) == 1 { return false } return true } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if tableView.numberOfRows(inSection: 0) == 1 { setEditing(false, animated: true) } if editingStyle == .delete { isChanged = true viewModel?.deleteItemAtIndex((indexPath as NSIndexPath).row) tableView.deleteRows(at: [indexPath], with: .fade) } } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { intentResultDelegate?.selectQuestionAtIndex((indexPath as NSIndexPath).row) _ = navigationController?.popViewController(animated: true) } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 54.0 } } protocol IntentResultDelegate { func selectQuestionAtIndex(_ index: Int) }
mit
220782a32fe64f11205ae1b9899e8d1f
27.779661
148
0.656655
5.567213
false
false
false
false
red-spotted-newts-2014/Im-In
im-in-ios/im-in-ios/untitled folder/AddFriendsViewController.swift
1
2406
// // ViewController.swift // Im_in // // Created by fahia mohamed on 2014-08-14. // Copyright (c) 2014 fahia mohamed. All rights reserved. // import UIKit // //, APIControllerProtocol class AddFriendsViewController: UIViewController, APIAddFriendsControllerProtocol, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var button: UIButton! var apiCtrl = APIAddFriendsController() var attending: NSArray! func didReceiveAPIResults(results: NSDictionary) { println("AddFriendsViewController#didReceiveAPIResults") println(results) attending = results.objectForKey("following") as? NSArray // println("****") println(attending) self.tableView.reloadData() } @IBAction func buttonPressed(sender: AnyObject) { //apiCtrl.loadAllEvents() } func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int { println("AddFriendsViewController#tableView (count)") if attending == nil { return 0 } return attending.count; } // Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier: // Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls) func tableView(tableView:UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! { println("AddFriendsViewController#tableView") let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Value1, reuseIdentifier: "MyTestCell") // println("***") // cell.textLabel.text = "Row #\(indexPath.row)" cell.textLabel.text = attending[indexPath.row].objectForKey("username") as? String return cell } override func viewDidLoad() { super.viewDidLoad() println("AddFriendsViewController#viewDidLoad") apiCtrl.delegate = self apiCtrl.loadAllEvents() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
464ebac14f611456dc1bd5ffb39735e3
31.513514
188
0.662095
5.443439
false
false
false
false
material-motion/material-motion-components-swift
examples/supplemental/ExampleViews.swift
2
1009
/* Copyright 2016-present The Material Motion 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 func createExampleView() -> UIView { let view = UIView(frame: .init(x: 0, y: 0, width: 128, height: 128)) view.backgroundColor = .primaryColor view.layer.cornerRadius = view.bounds.width / 2 return view } func createExampleSquareView() -> UIView { let view = UIView(frame: .init(x: 0, y: 0, width: 128, height: 128)) view.backgroundColor = .primaryColor return view }
apache-2.0
e2beb425277d8892d71012c1de5b173b
32.633333
73
0.746283
4.068548
false
false
false
false
qvacua/vimr
VimR/VimR/HtmlPreviewTool.swift
1
5446
/** * Tae Won Ha - http://taewon.de - @hataewon * See LICENSE */ import Cocoa import EonilFSEvents import MaterialIcons import os import PureLayout import RxSwift import WebKit import Workspace private let fileSystemEventsLatency = 1.0 final class HtmlPreviewTool: NSView, UiComponent, WKNavigationDelegate { enum Action { case selectHtmlFile(URL) } typealias StateType = MainWindow.State let innerCustomToolbar = InnerCustomToolbar() required init(source: Observable<StateType>, emitter: ActionEmitter, state: StateType) { self.emit = emitter.typedEmit() self.uuid = state.uuid let configuration = WKWebViewConfiguration() configuration.processPool = Defs.webViewProcessPool self.webview = WKWebView(frame: CGRect.zero, configuration: configuration) self.queue = DispatchQueue( label: String(reflecting: HtmlPreviewTool.self) + "-\(self.uuid)", qos: .userInitiated, target: .global(qos: .userInitiated) ) super.init(frame: .zero) self.configureForAutoLayout() self.webview.navigationDelegate = self self.innerCustomToolbar.htmlPreviewTool = self self.addViews() if let serverUrl = state.htmlPreview.server?.payload { self.webview.load(URLRequest(url: serverUrl)) } source .observe(on: MainScheduler.instance) .subscribe(onNext: { state in if state.viewToBeFocused != nil, case .htmlPreview = state.viewToBeFocused! { self.beFirstResponder() } guard let serverUrl = state.htmlPreview.server else { self.monitor = nil return } if serverUrl.mark == self.mark { return } self.mark = serverUrl.mark self.reloadWebview(with: serverUrl.payload) guard let htmlFileUrl = state.htmlPreview.htmlFile else { return } do { self.monitor = try EonilFSEventStream( pathsToWatch: [htmlFileUrl.path], sinceWhen: EonilFSEventsEventID.getCurrentEventId(), latency: fileSystemEventsLatency, flags: [.fileEvents], handler: { [weak self] _ in self?.reloadWebview(with: serverUrl.payload) } ) self.monitor?.setDispatchQueue(self.queue) try self.monitor?.start() } catch { self.log.error("Could not start file monitor for \(htmlFileUrl): \(error)") } self.innerCustomToolbar .selectHtmlFile.toolTip = (htmlFileUrl.path as NSString).abbreviatingWithTildeInPath }) .disposed(by: self.disposeBag) } deinit { self.monitor?.stop() self.monitor?.invalidate() } private func reloadWebview(with url: URL) { DispatchQueue.main.async { self.webview.evaluateJavaScript("document.body.scrollTop") { result, _ in self.scrollTop = result as? Int ?? 0 } } self.webview.load(URLRequest(url: url)) } private func addViews() { self.webview.configureForAutoLayout() self.addSubview(self.webview) self.webview.autoPinEdgesToSuperviewEdges() } private let emit: (UuidAction<Action>) -> Void private let uuid: UUID private var mark = Token() private var scrollTop = 0 private let webview: WKWebView private var monitor: EonilFSEventStream? private let disposeBag = DisposeBag() private let log = OSLog(subsystem: Defs.loggerSubsystem, category: Defs.LoggerCategory.ui) private let queue: DispatchQueue @available(*, unavailable) required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } @objc func selectHtmlFile(sender _: Any?) { let panel = NSOpenPanel() panel.canChooseDirectories = false panel.allowsMultipleSelection = false panel.beginSheetModal(for: self.window!) { result in guard result == .OK else { return } let urls = panel.urls guard urls.count == 1 else { return } self.emit(UuidAction(uuid: self.uuid, action: .selectHtmlFile(urls[0]))) } } func webView(_: WKWebView, didFinish _: WKNavigation!) { self.webview.evaluateJavaScript("document.body.scrollTop = \(self.scrollTop)") } } extension HtmlPreviewTool { class InnerCustomToolbar: CustomToolBar { fileprivate weak var htmlPreviewTool: HtmlPreviewTool? { didSet { self.selectHtmlFile.target = self.htmlPreviewTool } } let selectHtmlFile = NSButton(forAutoLayout: ()) init() { super.init(frame: .zero) self.configureForAutoLayout() self.addViews() } override func repaint(with theme: Workspace.Theme) { self.selectHtmlFile.image = Icon.description.asImage( dimension: InnerToolBar.iconDimension, style: .outlined, color: theme.toolbarForeground ) } private func addViews() { let selectHtmlFile = self.selectHtmlFile InnerToolBar.configureToStandardIconButton( button: selectHtmlFile, iconName: Icon.description, style: .outlined ) selectHtmlFile.toolTip = "Select the HTML file" selectHtmlFile.action = #selector(HtmlPreviewTool.selectHtmlFile) self.addSubview(selectHtmlFile) selectHtmlFile.autoPinEdge(toSuperviewEdge: .top) selectHtmlFile.autoPinEdge(toSuperviewEdge: .right, withInset: InnerToolBar.itemPadding) } @available(*, unavailable) required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } } }
mit
526ca3b5329483877c647d27a287c3d2
27.513089
94
0.675725
4.634894
false
false
false
false
ukitaka/UILifeCycleClosure
Example/UITests/UITests.swift
1
2583
// // UITests.swift // UITests // // Created by Yuki Takahashi on 2015/10/13. // Copyright © 2015年 CocoaPods. All rights reserved. // import XCTest class UITests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. continueAfterFailure = false // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. XCUIApplication().launch() // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample1() { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. let app = XCUIApplication() // Select cell. app.tables.element.cells.elementBoundByIndex(0).tap() // Input text and submit. app.textFields.element.tap() app.textFields.element.typeText("ABCDEFG") app.buttons["Go"].tap() // Check text. XCTAssert(app.staticTexts["ABCDEFG"].exists) // lower case. app.buttons["lower"].tap() XCTAssert(app.staticTexts["abcdefg"].exists) // next. app.buttons["next"].tap() // Check text. XCTAssert(app.staticTexts["abcdefg"].exists) } func testExample2() { let app = XCUIApplication() // show example2 vc app.tables.element.cells.elementBoundByIndex(1).tap() // and transition to detail vc automatically. // detail vc has 'OK' label XCTAssert(app.staticTexts["OK"].exists) let label = app.staticTexts["afterViewDidAppear2"] let exists = NSPredicate(format: "exists == 1") expectationForPredicate(exists, evaluatedWithObject: label, handler: nil) waitForExpectationsWithTimeout(5, handler: nil) // invoke blocks in order. XCTAssert(app.staticTexts["afterViewDidAppear2"].exists) } }
mit
3bb7fd6a66a81aead68cb13cc9a403a1
31.632911
182
0.609775
4.948177
false
true
false
false
acsalu/Keymochi
Keymochi/DataChunkViewController.swift
2
2737
// // DataChunkViewController.swift // Keymochi // // Created by Huai-Che Lu on 4/7/16. // Copyright © 2016 Cornell Tech. All rights reserved. // import Foundation import UIKit import Firebase import FirebaseAnalytics import FirebaseDatabase import PAM import RealmSwift class DataChunkViewController: UITableViewController { var dataChunk: DataChunk! var uid: String! @IBOutlet weak var emotionContainer: UIView! override func viewDidLoad() { super.viewDidLoad() } func alertSetupUserId() { let alert = UIAlertController.init(title: "Error", message: "Please set your userId by going to Settings --> Keymochi --> And Enter a Value in the UserID field", preferredStyle: .alert) alert.addAction(UIAlertAction.init(title: "OK", style: .default, handler: nil)) self.present(alert, animated: true, completion: nil) } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard let identifier = segue.identifier else { return } let vc = segue.destination as! DataChunkDetailsTableViewController func bindData(_ data: [String], andTimestamps timeStamps: [String]?, withTitle title: String) { vc.data = data vc.timestamps = timeStamps vc.title = "\(title) (\(data.count))" } switch identifier { case "ShowKey": bindData(dataChunk.keyEvents?.map { $0.description } ?? [], andTimestamps: dataChunk.keyEvents?.map { $0.timestamp } ?? [], withTitle: "Key") case "ShowITD": bindData(dataChunk.interTapDistances?.map(String.init) ?? [], andTimestamps: nil, withTitle: "Inter-Tap Distance") case "ShowAcceleration": bindData(dataChunk.accelerationDataPoints?.map { $0.description } ?? [], andTimestamps: dataChunk.accelerationDataSequence?.timestamps ?? [], withTitle: "Acceleration") case "ShowGyro": bindData(dataChunk.gyroDataPoints?.map { $0.description } ?? [], andTimestamps: dataChunk.gyroDataSequence?.timestamps ?? [], withTitle: "Gyro") case "ShowSentiment": bindData(dataChunk.gyroDataPoints?.map { $0.description } ?? [], andTimestamps: dataChunk.gyroDataSequence?.timestamps ?? [], withTitle: "Gyro") default: break } } }
bsd-3-clause
81abcb95b9e9f32c591979d5f1135893
34.076923
193
0.597222
4.965517
false
false
false
false
brentdax/swift
stdlib/private/StdlibUnittest/OpaqueIdentityFunctions.swift
9
2413
//===--- OpaqueIdentityFunctions.swift ------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// @_silgen_name("getPointer") func _getPointer(_ x: OpaquePointer) -> OpaquePointer public func _opaqueIdentity<T>(_ x: T) -> T { let ptr = UnsafeMutablePointer<T>.allocate(capacity: 1) ptr.initialize(to: x) let result = UnsafeMutablePointer<T>(_getPointer(OpaquePointer(ptr))).pointee ptr.deinitialize(count: 1) ptr.deallocate() return result } func _blackHolePtr<T>(_ x: UnsafePointer<T>) { _ = _getPointer(OpaquePointer(x)) } public func _blackHole<T>(_ x: T) { var x = x _blackHolePtr(&x) } @inline(never) public func getBool(_ x: Bool) -> Bool { return _opaqueIdentity(x) } @inline(never) public func getInt8(_ x: Int8) -> Int8 { return _opaqueIdentity(x) } @inline(never) public func getInt16(_ x: Int16) -> Int16 { return _opaqueIdentity(x) } @inline(never) public func getInt32(_ x: Int32) -> Int32 { return _opaqueIdentity(x) } @inline(never) public func getInt64(_ x: Int64) -> Int64 { return _opaqueIdentity(x) } @inline(never) public func getInt(_ x: Int) -> Int { return _opaqueIdentity(x) } @inline(never) public func getUInt8(_ x: UInt8) -> UInt8 { return _opaqueIdentity(x) } @inline(never) public func getUInt16(_ x: UInt16) -> UInt16 { return _opaqueIdentity(x) } @inline(never) public func getUInt32(_ x: UInt32) -> UInt32 { return _opaqueIdentity(x) } @inline(never) public func getUInt64(_ x: UInt64) -> UInt64 { return _opaqueIdentity(x) } @inline(never) public func getUInt(_ x: UInt) -> UInt { return _opaqueIdentity(x) } @inline(never) public func getFloat32(_ x: Float32) -> Float32 { return _opaqueIdentity(x) } @inline(never) public func getFloat64(_ x: Float64) -> Float64 { return _opaqueIdentity(x) } #if arch(i386) || arch(x86_64) @inline(never) public func getFloat80(_ x: Float80) -> Float80 { return _opaqueIdentity(x) } #endif public func getPointer(_ x: OpaquePointer) -> OpaquePointer { return _opaqueIdentity(x) }
apache-2.0
fcd5bef4eee4a8212a0d7a5424b3d8dd
28.790123
80
0.665562
3.512373
false
false
false
false
Zewo/Examples
HTTP/Source/ServerMiddleware/main.swift
1
792
import Zewo let log = Log() let logger = LogMiddleware(log: log) let parsers = MediaTypeParserCollection() parsers.add(JSONMediaType, parser: JSONInterchangeDataParser()) parsers.add(URLEncodedFormMediaType, parser: URLEncodedFormInterchangeDataParser()) let serializers = MediaTypeSerializerCollection() serializers.add(JSONMediaType, serializer: JSONInterchangeDataSerializer()) serializers.add(URLEncodedFormMediaType, serializer: URLEncodedFormInterchangeDataSerializer()) let contentNegotiation = ServerContentNegotiationMiddleware( parsers: parsers, serializers: serializers ) try Server(middleware: logger, contentNegotiation) { _ in let content: InterchangeData = [ "foo": "bar", "hello": "world" ] return Response(content: content) }.start()
mit
3c3b27cb2f42c3f2af1ca0b72ada0576
29.5
95
0.776515
4.631579
false
false
false
false
twtstudio/WePeiYang-iOS
WePeiYang/Bicycle/Model/NotificationItem.swift
1
763
// // NotificationItem.swift // WePeiYang // // Created by JinHongxu on 16/8/7. // Copyright © 2016年 Qin Yubo. All rights reserved. // import Foundation class NotificationItem: NSObject { var id: String = "" //坑:类型 var title: String = "" var content: String = "" var timeStamp: NSDate = NSDate() var second: Int = 0 init(dict: NSDictionary) { id = dict.objectForKey("id") as! String title = dict.objectForKey("title") as! String content = dict.objectForKey("content") as! String let timeStampString = dict.objectForKey("timestamp") as? String second = Int(timeStampString!)! timeStamp = NSDate(timeIntervalSince1970: Double(second)) } }
mit
be836dfb4985d63a8d36394b8b63f70e
24.066667
71
0.613032
4.201117
false
false
false
false
softmaxsg/trakt.tv-searcher
TraktSearcher/AppDelegate.swift
1
776
// // AppDelegate.swift // TraktSearcher // // Copyright © 2016 Vitaly Chupryk. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var moviesAssembly: MoviesAssembly? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { application.statusBarHidden = false self.moviesAssembly = MoviesAssembly() let window = UIWindow(frame: UIScreen.mainScreen().bounds) window.rootViewController = UINavigationController(rootViewController: moviesAssembly!.createMoviesViewController()) window.makeKeyAndVisible() self.window = window return true } }
mit
e470b46c5fc5c8ff7bc655ab547a328c
24.833333
125
0.722581
5.272109
false
false
false
false
Jamnitzer/MBJ_BasicTexturing
MBJ_BasicTexturing/MBJ_BasicTexturing/Renderer.swift
1
14410
// // Renderer.m // BasicTexturing // // Created by Warren Moore on 9/25/14. // Copyright (c) 2014 Metal By Example. All rights reserved. //------------------------------------------------------------------------ // converted to Swift by Jamnitzer (Jim Wrenholt) //------------------------------------------------------------------------ import UIKit import Metal import simd import Accelerate //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ class Renderer { var view:UIView! = nil var layer:CAMetalLayer! = nil var device:MTLDevice! = nil var library:MTLLibrary! = nil var pipeline:MTLRenderPipelineState! = nil var commandQueue:MTLCommandQueue! = nil var pipelineDirty:Bool = false var uniformBuffer:MTLBuffer! = nil var depthTexture:MTLTexture! = nil var sampler:MTLSamplerState! = nil var currentRenderPass:MTLRenderPassDescriptor! = nil var currentDrawable:CAMetalDrawable! = nil var clearColor = UIColor(white: 0.95, alpha: 1.0) var modelViewProjectionMatrix:float4x4 = float4x4(1.0) var modelViewMatrix:float4x4 = float4x4(1.0) var normalMatrix:float4x4 = float4x4(1.0) //------------------------------------------------------------------------------ init(view:UIView) { self.view = view if let metal_layer = view.layer as? CAMetalLayer { self.layer = metal_layer } else { print("Layer type of view used for rendering must be CAMetalLayer") assert(false) } self.clearColor = UIColor(white: 0.95, alpha: 1.0) self.pipelineDirty = true self.device = MTLCreateSystemDefaultDevice() initializeDeviceDependentObjects() } //------------------------------------------------------------------------------ func initializeDeviceDependentObjects() { self.library = self.device!.newDefaultLibrary() commandQueue = device!.newCommandQueue() let samplerDescriptor = MTLSamplerDescriptor() samplerDescriptor.minFilter = MTLSamplerMinMagFilter.Nearest samplerDescriptor.magFilter = MTLSamplerMinMagFilter.Linear self.sampler = self.device!.newSamplerStateWithDescriptor(samplerDescriptor) } //------------------------------------------------------------------------------ func configurePipelineWithMaterial(material:Material) { let pos_offset = 0 let norm_offset = pos_offset + sizeof(float4) let tc_offset = norm_offset + sizeof(float3) let vertexDescriptor = MTLVertexDescriptor() vertexDescriptor.attributes[0].format = MTLVertexFormat.Float4 vertexDescriptor.attributes[0].bufferIndex = 0 vertexDescriptor.attributes[0].offset = pos_offset // offsetof(Vertex, position) vertexDescriptor.attributes[1].format = MTLVertexFormat.Float3 vertexDescriptor.attributes[1].bufferIndex = 0 vertexDescriptor.attributes[1].offset = norm_offset // offsetof(Vertex, normal) vertexDescriptor.attributes[2].format = MTLVertexFormat.Float2 vertexDescriptor.attributes[2].bufferIndex = 0 vertexDescriptor.attributes[2].offset = tc_offset // offsetof(Vertex, texCoords) vertexDescriptor.layouts[0].stride = sizeof(Vertex) vertexDescriptor.layouts[0].stepFunction = MTLVertexStepFunction.PerVertex let pipelineDescriptor = MTLRenderPipelineDescriptor() pipelineDescriptor.vertexFunction = material.vertexFunction pipelineDescriptor.fragmentFunction = material.fragmentFunction pipelineDescriptor.vertexDescriptor = vertexDescriptor pipelineDescriptor.colorAttachments[0].pixelFormat = MTLPixelFormat.BGRA8Unorm pipelineDescriptor.depthAttachmentPixelFormat = MTLPixelFormat.Depth32Float do { self.pipeline = try device.newRenderPipelineStateWithDescriptor(pipelineDescriptor) } catch let pipelineError as NSError { self.pipeline = nil print("Error occurred when creating render pipeline state \(pipelineError)") assert(false) } } //------------------------------------------------------------------------------ func textureForImage(image:UIImage) -> MTLTexture? { let imageRef = image.CGImage // Create a suitable bitmap context for extracting the bits of the image let width = CGImageGetWidth(imageRef) let height = CGImageGetHeight(imageRef) let colorSpace = CGColorSpaceCreateDeviceRGB() let rawData = calloc(height * width * 4, Int(sizeof(UInt8))) let bytesPerPixel: Int = 4 let bytesPerRow: Int = bytesPerPixel * width let bitsPerComponent: Int = 8 let options = CGImageAlphaInfo.PremultipliedLast.rawValue | CGBitmapInfo.ByteOrder32Big.rawValue let context = CGBitmapContextCreate(rawData, width, height, bitsPerComponent, bytesPerRow, colorSpace, options) // CGColorSpaceRelease(colorSpace) // Flip the context so the positive Y axis points down CGContextTranslateCTM(context, 0.0, CGFloat(height)); CGContextScaleCTM(context, 1.0, -1.0); CGContextDrawImage(context, CGRectMake(0, 0, CGFloat(width), CGFloat(height)), imageRef) // CGContextRelease(context) let textureDescriptor = MTLTextureDescriptor.texture2DDescriptorWithPixelFormat( .RGBA8Unorm, width: Int(width), height: Int(height), mipmapped: true) let texture = device.newTextureWithDescriptor(textureDescriptor) texture.label = "textureForImage" let region = MTLRegionMake2D(0, 0, Int(width), Int(height)) texture.replaceRegion(region, mipmapLevel: 0, withBytes: rawData, bytesPerRow: Int(bytesPerRow)) free(rawData) return texture } //------------------------------------------------------------------------------ func newMaterialWithVertexFunctionNamed( vertexFunctionName:String, fragmentFunctionName:String, diffuseTextureName:String) -> Material? { //------------------------------------------------------------------------ // Creates a new material with the specified pair of vertex/fragment // functions and the specified diffuse texture name. // The texture name must refer to a PNG resource // in the main bundle in order to be loaded successfully. //------------------------------------------------------------------------ let vertexFunction = library!.newFunctionWithName(vertexFunctionName) if (vertexFunction == nil) { print("Could not load vertex function named \(vertexFunctionName) from default library") return nil } //------------------------------------------------------------------------ let fragmentFunction = library!.newFunctionWithName(fragmentFunctionName) if (fragmentFunction == nil) { print("Could not load fragment function named \(fragmentFunctionName) from default library") return nil } //------------------------------------------------------------------------ let diffuseTextureImage = UIImage(named: diffuseTextureName) if (diffuseTextureImage == nil) { print("Unable to find PNG image named \(diffuseTextureName) in main bundle") return nil } //------------------------------------------------------------------------ let diffuseTexture = textureForImage(diffuseTextureImage!) if (diffuseTexture == nil) { print("Could not create a texture from an image") } //------------------------------------------------------------------------ let material:Material = Material( vertexFunction:vertexFunction!, fragmentFunction:fragmentFunction!, diffuseTexture:diffuseTexture!) return material } //------------------------------------------------------------------------------ func newMeshWithOBJGroup(group:OBJGroup) -> Mesh { let vertexBuffer:MTLBuffer = device!.newBufferWithBytes( group.vertexData.bytes, length: group.vertexData.length, options: .CPUCacheModeDefaultCache) let indexBuffer:MTLBuffer = device!.newBufferWithBytes( group.indexData.bytes, length: group.indexData.length, options: .CPUCacheModeDefaultCache) let mesh:Mesh = Mesh(vertexBuffer:vertexBuffer, indexBuffer:indexBuffer) return mesh } //------------------------------------------------------------------------------ func createDepthBuffer() { let drawableSize:CGSize = layer.drawableSize let depthTexDesc = MTLTextureDescriptor.texture2DDescriptorWithPixelFormat( MTLPixelFormat.Depth32Float, width: Int(drawableSize.width), height: Int(drawableSize.height), mipmapped: false ) self.depthTexture = device!.newTextureWithDescriptor(depthTexDesc) } //------------------------------------------------------------------------------ func updateUniforms() { if (uniformBuffer == nil) { self.uniformBuffer = device!.newBufferWithLength( sizeof(Uniforms), options: .CPUCacheModeDefaultCache) } var uniforms = Uniforms() uniforms.modelViewMatrix = self.modelViewMatrix uniforms.modelViewProjectionMatrix = self.modelViewProjectionMatrix let upleft3x3:float3x3 = UpperLeft3x3(self.modelViewMatrix) let trans_upleft:float3x3 = upleft3x3.transpose let inv_m:float3x3 = trans_upleft.inverse uniforms.normalMatrix = inv_m let bufferPointer:UnsafeMutablePointer<Void>? = uniformBuffer.contents() memcpy(bufferPointer!, &uniforms, // the data. sizeof(Uniforms)) // num of bytes } //------------------------------------------------------------------------------ func startFrame() { let drawableSize:CGSize = layer.drawableSize if ( (self.depthTexture == nil) || CGFloat(depthTexture.width) != drawableSize.width || CGFloat(depthTexture.height) != drawableSize.height) { createDepthBuffer() } let drawable:CAMetalDrawable? = self.layer.nextDrawable() if (drawable == nil) { print("Could not retrieve drawable from Metal layer") assert(false) } var r:CGFloat = 0.0 var g:CGFloat = 0.0 var b:CGFloat = 0.0 var a:CGFloat = 0.0 clearColor.getRed(&r, green:&g, blue:&b, alpha:&a) let renderPass = MTLRenderPassDescriptor() renderPass.colorAttachments[0].texture = drawable!.texture renderPass.colorAttachments[0].loadAction = MTLLoadAction.Clear renderPass.colorAttachments[0].storeAction = MTLStoreAction.Store renderPass.colorAttachments[0].clearColor = MTLClearColorMake( Double(r), Double(g), Double(b), Double(a)) renderPass.depthAttachment.texture = self.depthTexture renderPass.depthAttachment.loadAction = MTLLoadAction.Clear renderPass.depthAttachment.storeAction = MTLStoreAction.Store renderPass.depthAttachment.clearDepth = 1 self.currentDrawable = drawable self.currentRenderPass = renderPass } //------------------------------------------------------------------------------ func drawMesh(mesh:Mesh, material:Material) { configurePipelineWithMaterial(material) updateUniforms() let commandBuffer:MTLCommandBuffer = commandQueue.commandBuffer() let commandEncoder:MTLRenderCommandEncoder = commandBuffer.renderCommandEncoderWithDescriptor(currentRenderPass) commandEncoder.setVertexBuffer( mesh.vertexBuffer, offset: 0, atIndex: 0) commandEncoder.setVertexBuffer( self.uniformBuffer, offset: 0, atIndex: 1) commandEncoder.setFragmentBuffer( self.uniformBuffer, offset: 0, atIndex: 0) commandEncoder.setFragmentTexture(material.diffuseTexture, atIndex: 0) commandEncoder.setFragmentSamplerState(self.sampler, atIndex: 0) commandEncoder.setRenderPipelineState(self.pipeline) commandEncoder.setCullMode( MTLCullMode.Back) commandEncoder.setFrontFacingWinding(MTLWinding.CounterClockwise) let depthStencilDescriptor = MTLDepthStencilDescriptor() depthStencilDescriptor.depthCompareFunction = MTLCompareFunction.Less depthStencilDescriptor.depthWriteEnabled = true let depthStencilState = device!.newDepthStencilStateWithDescriptor(depthStencilDescriptor) commandEncoder.setDepthStencilState( depthStencilState) commandEncoder.drawIndexedPrimitives(MTLPrimitiveType.Triangle, indexCount: mesh.indexBuffer.length / sizeof(UInt16), indexType: MTLIndexType.UInt16, indexBuffer: mesh.indexBuffer, indexBufferOffset: 0) commandEncoder.endEncoding() commandBuffer.commit() } //------------------------------------------------------------------------------ func endFrame() { let commandBuffer:MTLCommandBuffer = commandQueue.commandBuffer() commandBuffer.presentDrawable(currentDrawable) commandBuffer.commit() } //------------------------------------------------------------------------------ } //----------------------------------------------------------------------------------- //-----------------------------------------------------------------------------------
mit
e18a16d4f12c73e27dc0483ed907a9e8
41.759644
104
0.561832
6.113704
false
false
false
false
weissmar/CharacterSheet
iOS_Files/characterSheet/CharacterViewController.swift
1
2543
// // CharacterViewController.swift // characterSheet // // Created by Rachel Weissman-Hohler on 8/12/16. // Copyright © 2016 Rachel Weissman-Hohler. All rights reserved. // import UIKit class CharacterViewController: UIViewController { // MARK: Properties var userToken: String? var character: Character? @IBOutlet weak var editButton: UIBarButtonItem! @IBOutlet weak var imageViewMed: UIImageView! @IBOutlet weak var xpLabel: UILabel! @IBOutlet weak var strLabel: UILabel! @IBOutlet weak var iqLabel: UILabel! @IBOutlet weak var dexLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() updateLabels() } func updateLabels(){ if character != nil { navigationItem.title = character?.name xpLabel.text = String(character!.XP!) iqLabel.text = String(character!.IQ!) strLabel.text = String(character!.STR!) dexLabel.text = String(character!.DEX!) if character?.charImage != nil { imageViewMed.image = character!.charImage! } } } 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?) { if editButton === sender { let navView = segue.destinationViewController as! UINavigationController let destinationView = navView.topViewController as! EditCharacterViewController destinationView.userToken = self.userToken destinationView.character = self.character } else if segue.identifier == "inventoryEmbedSegue" { //let navViewEmbed = segue.destinationViewController as! UINavigationController //let destinationViewEmbed = navViewEmbed.topViewController as! CharacterTableViewController //destinationViewEmbed.userToken = userToken //destinationViewEmbed.partyID = currParty?.id } } @IBAction func unwindToCharacterView(sender: UIStoryboardSegue) { if sender.sourceViewController is EditCharacterViewController { self.updateLabels() } } @IBAction func done(sender: UIBarButtonItem) { dismissViewControllerAnimated(true, completion: nil) } }
mit
8d0053171d453d9ca9bedd15f17f0df8
33.821918
106
0.664044
5.284823
false
false
false
false
modocache/Gift
Gift/Commit/Commit+Branch.swift
1
1253
import Foundation import LlamaKit public extension Commit { /** Creates a branch that refers to this commit. :param: name The name of the new branch. This name must be unique, unless the `force` parameter is specified. :param: signature The identity that will be used to popular the reflog entry. By default, this will be recorded as "com.libgit2.Gift". :param: force If true, attempts to create branches with a name that already exists will overwrite the previous branch. :returns: The result of the operation: either a reference to the newly created branch, or an error indicating what went wrong. */ public func createBranch(name: String, signature: Signature = giftSignature, force: Bool = false) -> Result<Reference, NSError> { var out = COpaquePointer.null() var cSignature = signature.cSignature let cForce: Int32 = force ? 1 : 0 let errorCode = git_branch_create(&out, cRepository, name, cCommit, cForce, &cSignature, nil) if errorCode == GIT_OK.value { return success(Reference(cReference: out)) } else { return failure(NSError.libGit2Error(errorCode, libGit2PointOfFailure: "git_branch_create")) } } }
mit
b9ef75d6331173fad3e59e08b2a2b329
43.75
131
0.683958
4.33564
false
false
false
false
lorentey/swift
test/IRGen/opaque_result_type_debug.swift
12
2799
// RUN: %target-swift-frontend -enable-library-evolution -disable-availability-checking -g -emit-ir -enable-anonymous-context-mangled-names %s | %FileCheck %s public protocol P {} extension Int: P {} // CHECK: [[DEFINER_NAME:@.*]] = {{.*}}constant [{{[0-9]+}} x i8] c"$s24opaque_result_type_debug3fooQryF\00" // CHECK: @"$s24opaque_result_type_debug3fooQryFMXX" = {{.*}}constant{{.*}} [[DEFINER_NAME]] // CHECK: @"$s24opaque_result_type_debug3fooQryFQOMQ" = {{.*}}constant{{.*}} @"$s24opaque_result_type_debug3fooQryFMXX" public func foo() -> some P { return 0 } // CHECK: [[DEFINER_NAME:@.*]] = {{.*}}constant [{{[0-9]+}} x i8] c"$s24opaque_result_type_debug4propQrvp\00" // CHECK: @"$s24opaque_result_type_debug4propQrvpMXX" = {{.*}}constant{{.*}} [[DEFINER_NAME]] // CHECK: @"$s24opaque_result_type_debug4propQrvpQOMQ" = {{.*}}constant{{.*}} @"$s24opaque_result_type_debug4propQrvpMXX" public var prop: some P { return 0 } // CHECK: [[DEFINER_NAME:@.*]] = {{.*}}constant [{{[0-9]+}} x i8] c"$s24opaque_result_type_debug3FooVQrycip\00" // CHECK: @"$s24opaque_result_type_debug3FooVQrycipMXX" = {{.*}}constant{{.*}} [[DEFINER_NAME]] // CHECK: @"$s24opaque_result_type_debug3FooVQrycipQOMQ" = {{.*}}constant{{.*}} @"$s24opaque_result_type_debug3FooVQrycipMXX" public struct Foo { public init() {} public subscript() -> some P { return 0 } } // CHECK: @"\01l_type_metadata_table" = {{.*}} @"$s24opaque_result_type_debug3fooQryFQOMQ" @_silgen_name("use") public func use<T: P>(_: T) @inlinable public func bar<T: P>(genericValue: T) { use(genericValue) let intValue = 0 use(intValue) let opaqueValue = foo() use(opaqueValue) let opaquePropValue = prop use(opaquePropValue) let opaqueSubValue = Foo()[] use(opaqueSubValue) } // CHECK-DAG: ![[OPAQUE_TYPE:[0-9]+]] = !DICompositeType({{.*}} name: "$s24opaque_result_type_debug3fooQryFQOyQo_D" // CHECK-DAG: ![[LET_OPAQUE_TYPE:[0-9]+]] = !DIDerivedType(tag: DW_TAG_const_type, baseType: ![[OPAQUE_TYPE]]) // CHECK-DAG: ![[OPAQUE_PROP_TYPE:[0-9]+]] = !DICompositeType({{.*}} name: "$s24opaque_result_type_debug4propQrvpQOyQo_D" // CHECK-DAG: ![[LET_OPAQUE_PROP_TYPE:[0-9]+]] = !DIDerivedType(tag: DW_TAG_const_type, baseType: ![[OPAQUE_PROP_TYPE]]) // CHECK-DAG: ![[OPAQUE_SUB_TYPE:[0-9]+]] = !DICompositeType({{.*}} name: "$s24opaque_result_type_debug3FooVQrycipQOy_Qo_D" // CHECK-DAG: ![[LET_OPAQUE_SUB_TYPE:[0-9]+]] = !DIDerivedType(tag: DW_TAG_const_type, baseType: ![[OPAQUE_SUB_TYPE]]) // CHECK-DAG: {{![0-9]+}} = !DILocalVariable(name: "opaqueValue",{{.*}} type: ![[LET_OPAQUE_TYPE]]) // CHECK-DAG: {{![0-9]+}} = !DILocalVariable(name: "opaquePropValue",{{.*}} type: ![[LET_OPAQUE_PROP_TYPE]]) // CHECK-DAG: {{![0-9]+}} = !DILocalVariable(name: "opaqueSubValue",{{.*}} type: ![[LET_OPAQUE_SUB_TYPE]])
apache-2.0
0f367e904fc6f5d0d0949cec54c83906
44.145161
158
0.64916
3.055677
false
false
false
false
indragiek/SwiftTableViews
SwiftTableViews/TableViewDataSource.swift
1
2606
// // TableViewDataSource.swift // // Created by Indragie on 10/6/14. // Copyright (c) 2014 Indragie Karunaratne. All rights reserved. // import UIKit public struct TableViewDataSource<T: AnyObject, U: UITableViewCell where U: ReusableCell> { public typealias CellConfigurator = (T, U) -> Void let dataSource: SectionedDataSource<T> let configurator: CellConfigurator public init(sections: [Section<T>], configurator: CellConfigurator) { self.dataSource = SectionedDataSource(sections: sections) self.configurator = configurator } public func numberOfSections() -> Int { return dataSource.sections.count } public func numberOfRowsInSection(section: Int) -> Int { return dataSource.numberOfItemsInSection(section) } public func itemAtIndexPath(indexPath: NSIndexPath) -> T { return dataSource.itemAtIndexPath(indexPath) } public func toObjC() -> TableViewDataSourceObjC { let sections = dataSource.sections.map { section in section.toObjC() } let configurator = self.configurator return TableViewDataSourceObjC(sections: sections, reuseIdentifier: U.reuseIdentifier()) { (object, cell) in configurator(object as T, cell as U) } } } public class TableViewDataSourceObjC: NSObject, UITableViewDataSource { typealias ObjCCellConfigurator = (AnyObject, AnyObject) -> Void let sections: [SectionObjC] let reuseIdentifier: String let configurator: ObjCCellConfigurator init(sections: [SectionObjC], reuseIdentifier: String, configurator: ObjCCellConfigurator) { self.sections = sections self.reuseIdentifier = reuseIdentifier self.configurator = configurator } // MARK: UITableViewDataSource public func numberOfSectionsInTableView(tableView: UITableView) -> Int { return sections.count } public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return sections[section].items.count } public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if let cell = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier) as? UITableViewCell { let object: AnyObject = sections[indexPath.section].items[indexPath.row] self.configurator(object, cell) return cell } else { assert(false, "Unable to create table view cell for reuse identifier \(reuseIdentifier)") } } }
mit
9832936e5a2d39377bb06e94b49b9381
34.216216
116
0.689946
5.351129
false
true
false
false
rene-dohan/CS-IOS
Renetik/Renetik/Classes/Core/Classes/Controller/CSTextInputPhoneLandscapeController.swift
1
7368
// // Created by Rene Dohan on 12/22/19. // Copyright (c) 2019 Renetik Software. All rights reserved. // import Foundation import UIKit import RenetikObjc import UITextView_Placeholder public protocol CSHasInputAccessory: NSObjectProtocol { var inputAccessoryView: UIView? { get set } } public protocol CSHasUIResponder: NSObjectProtocol { var responder: UIResponder { get } } public protocol CSHasTextInput: NSObjectProtocol { var textInput: UITextInput? { get set } } extension UITextView: CSHasInputAccessory {} public class CSTextInputPhoneLandscapeController: CSViewController { public let defaultAccessoryView = CSInputAccessoryDone() private let keyboardManager = CSKeyboardObserverController() public let container = CSView.construct(width: 100, height: 50).background(.white) public let textView = UITextView.construct().background(.white) public let actionButton = UIButton.construct().text(color: .blue) private var parentTextInput: (CSHasTextProtocol & CSHasUIResponder)! private var hasAccessory: CSHasInputAccessory? private var accessoryTextInput: UITextInput? @discardableResult func construct(by parent: CSViewController, textInput: CSHasTextProtocol & CSHasUIResponder, hasAccessory: CSHasInputAccessory? = nil, placeHolder: String, hideImage: UIImage, action: (title: String?, image: UIImage?, function: Func)?) -> Self { super.construct(parent).asViewLess() parentTextInput = textInput self.hasAccessory = hasAccessory accessoryTextInput = (hasAccessory?.inputAccessoryView as? CSHasTextInput)?.textInput textView.placeholder = placeHolder textView.inputAccessoryView = defaultAccessoryView.construct(hideImage) keyboardManager.construct(self) { [unowned self] _ in onKeyboardChange() } action.notNil { [unowned self] action in action.title.notNil { actionButton.text($0).resizeToFit() } action.image.notNil { actionButton.image($0).size(40) } actionButton.onClick { parentTextInput.text = textView.text action.function() } }.elseDo { actionButton.size(0) } return self } override public func onCreateLayout() { layout(container.add(view: actionButton).centeredVertical()) { [unowned self] in $0.from(right: safeArea.right) } layout(container.add(view: textView).matchParentHeight(margin: 5)) { [unowned self] in $0.from(left: safeArea.left).margin(right: 5, from: actionButton) } } override public func onViewDidLayout() { updateVisibility() } private func onKeyboardChange() { if parentTextInput.responder.isFirstResponder && UIScreen.isShort { textView.text = parentTextInput.text changeAccessory(from: hasAccessory, to: textView, textInput: textView) delegate.window!.add(view: container).matchParent() textView.becomeFirstResponder() runLayoutFunctions() return } if textView.isFirstResponder && UIScreen.isShort { container.margin(bottom: keyboardManager.keyboardHeight) runLayoutFunctions() return } updateVisibility() } private func updateVisibility() { if !UIScreen.isShort && isActive { hide() } if !textView.isFirstResponder && isActive { hide() } } private func hide() { container.removeFromSuperview() // Have to be here so isActive returns false and cycle is prevented parentTextInput.text = textView.text changeAccessory(from: textView, to: hasAccessory, textInput: accessoryTextInput) textView.resignFirstResponder() } private func changeAccessory(from hasAccessory1: CSHasInputAccessory?, to hasAccessory2: CSHasInputAccessory?, textInput: UITextInput?) { let accessoryView = hasAccessory1?.inputAccessoryView textInput.notNil { input in (accessoryView as? CSHasTextInput)?.textInput = input } accessoryView.notNil { hasAccessory2?.inputAccessoryView = $0 } } private var isActive: Bool { container.superview.notNil } } extension CSTextInputPhoneLandscapeController { @discardableResult public func construct(by parent: CSViewController, textInput: CSHasTextProtocol & CSHasUIResponder & CSHasInputAccessory, placeHolder: String = "Enter text", hideImage: UIImage, doneTitle: String = "Done") -> Self { construct(by: parent, textInput: textInput, hasAccessory: textInput, placeHolder: placeHolder, hideImage: hideImage, doneTitle: doneTitle) } @discardableResult public func construct(by parent: CSViewController, textInput: CSHasTextProtocol & CSHasUIResponder, hasAccessory: CSHasInputAccessory? = nil, placeHolder: String = "Enter text", hideImage: UIImage, doneTitle: String = "Done") -> Self { construct(by: parent, textInput: textInput, hasAccessory: hasAccessory, placeHolder: placeHolder, hideImage: hideImage, action: (title: doneTitle, image: nil, function: { self.textView.resignFirstResponder() })) } @discardableResult public func construct(by parent: CSViewController, textInput: CSHasTextProtocol & CSHasUIResponder & CSHasInputAccessory, placeHolder: String, hideImage: UIImage, action: CSImageAction) -> Self { construct(by: parent, textInput: textInput, hasAccessory: textInput, placeHolder: placeHolder, hideImage: hideImage, action: (title: nil, image: action.image, function: action.function)) } @discardableResult public func construct(by parent: CSViewController, textInput: CSHasTextProtocol & CSHasUIResponder & CSHasInputAccessory, placeHolder: String, hideImage: UIImage, action: CSTextAction) -> Self { construct(by: parent, textInput: textInput, hasAccessory: textInput, placeHolder: placeHolder, hideImage: hideImage, action: (title: action.title, image: nil, function: action.function)) } @discardableResult public func construct(by parent: CSViewController, textInput: CSHasTextProtocol & CSHasUIResponder, hasAccessory: CSHasInputAccessory? = nil, placeHolder: String = "Enter text", hideImage: UIImage) -> Self { construct(by: parent, textInput: textInput, hasAccessory: hasAccessory, placeHolder: placeHolder, hideImage: hideImage, action: nil) } } public class CSInputAccessoryDone: UIView { let hideKeyboardButton = UIButton.construct() .tint(color: .darkText).onClick { UIApplication.resignFirstResponder() } func construct(_ keyboardHide: UIImage) -> Self { super.construct().width(400, height: 40).background(.white) add(view: hideKeyboardButton.image(keyboardHide.template)) { $0.matchParentHeight().widthAsHeight().from(left: self.safeArea.left) } return self } }
mit
07d04f674a62e7ace540127e8fb9f12a
42.857143
108
0.665717
5.457778
false
false
false
false
firebase/firebase-ios-sdk
FirebaseCombineSwift/Sources/Functions/HTTPSCallable+Combine.swift
1
3749
// 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. #if canImport(Combine) && swift(>=5.0) import Combine import FirebaseFunctions @available(swift 5.0) @available(iOS 13.0, macOS 10.15, macCatalyst 13.0, tvOS 13.0, *) public extension HTTPSCallable { // MARK: - HTTPS Callable Functions /// Executes this Callable HTTPS trigger asynchronously without any parameters. /// /// The publisher will emit on the **main** thread. /// /// The request to the Cloud Functions backend made by this method automatically includes a /// Firebase Instance ID token to identify the app instance. If a user is logged in with Firebase /// Auth, an auth ID token for the user is also automatically included. /// /// Firebase Installations ID sends data to the Firebase backend periodically to collect information /// regarding the app instance. To stop this, see `[FIRInstallations delete]`. It /// resumes with a new Instance ID the next time you call this method. /// /// - Returns: A publisher emitting a `HTTPSCallableResult` instance. The publisher will emit on the *main* thread. @discardableResult func call() -> Future<HTTPSCallableResult, Error> { Future<HTTPSCallableResult, Error> { promise in self.call { callableResult, error in if let error = error { promise(.failure(error)) } else if let callableResult = callableResult { promise(.success(callableResult)) } } } } /// Executes this Callable HTTPS trigger asynchronously. /// /// The publisher will emit on the **main** thread. /// /// The data passed into the trigger can be any of the following types: /// - `nil` /// - `String` /// - `Number` /// - `Array<Any>`, where the contained objects are also one of these types. /// - `Dictionary<String, Any>`, where the contained objects are also one of these types. /// /// The request to the Cloud Functions backend made by this method automatically includes a /// Firebase Instance ID token to identify the app instance. If a user is logged in with Firebase /// Auth, an auth ID token for the user is also automatically included. /// /// Firebase Instance ID sends data to the Firebase backend periodically to collect information /// regarding the app instance. To stop this, see `[FIRInstanceID deleteIDWithHandler:]`. It /// resumes with a new Instance ID the next time you call this method. /// /// - Parameter data: The data passed into the Callable Function. /// - Returns: A publisher emitting a `HTTPSCallableResult` instance. The publisher will emit on the *main* thread. @discardableResult func call(_ data: Any?) -> Future<HTTPSCallableResult, Error> { Future<HTTPSCallableResult, Error> { promise in self.call(data) { callableResult, error in if let error = error { promise(.failure(error)) } else if let callableResult = callableResult { promise(.success(callableResult)) } } } } } #endif // canImport(Combine) && swift(>=5.0) && canImport(FirebaseFunctions)
apache-2.0
225c0d6d37970dcb6cfbc12bb1c06778
42.593023
119
0.673513
4.727617
false
false
false
false
tamanyan/SwiftPageMenu
Sources/PageMenuController.swift
1
18375
// // PageMenuController.swift // SwiftPageMenu // // Created by Tamanyan on 3/9/17. // Copyright © 2017 Tamanyan. All rights reserved. // import UIKit open class PageMenuController: UIViewController { /// SwiftPageMenu configurations public let options: PageMenuOptions /// PageMenuController data source. open weak var dataSource: PageMenuControllerDataSource? { didSet { self.reloadPages(reloadViewControllers: true) } } /// PageMenuController delegate. open weak var delegate: PageMenuControllerDelegate? /// The view controllers that are displayed in the page view controller. open internal(set) var viewControllers = [UIViewController]() /// The tab menu titles that are displayed in the page view controller. open internal(set) var menuTitles = [String]() /// Current page index var currentIndex: Int? { guard let viewController = self.pageViewController.selectedViewController else { return nil } return self.viewControllers.firstIndex(of: viewController) } fileprivate lazy var pageViewController: EMPageViewController = { let vc = EMPageViewController(navigationOrientation: .horizontal) vc.view.backgroundColor = .clear vc.dataSource = self vc.delegate = self vc.scrollView.backgroundColor = .clear if #available(iOS 11.0, *) { vc.scrollView.contentInsetAdjustmentBehavior = .never } else { vc.automaticallyAdjustsScrollViewInsets = false } return vc }() /// TabView fileprivate(set) lazy var tabView: TabMenuView = { let tabView = TabMenuView(options: self.options) tabView.pageItemPressedBlock = { [weak self] (index: Int, direction: EMPageViewControllerNavigationDirection) in guard let `self` = self else { return } self.displayController(with: index, direction: direction, animated: true) self.delegate?.pageMenuController?(self, didSelectMenuItem: index, direction: direction.toPageMenuNavigationDirection) } return tabView }() fileprivate var beforeIndex: Int? /// TabMenuView for custom layout public var tabMenuView: UIView { return self.tabView } /// Check options have infinite mode public var isInfinite: Bool { return self.options.isInfinite } /// Get page count public var pageCount: Int { return self.viewControllers.count } /// The number of tab items fileprivate var tabItemCount: Int { return self.menuTitles.count } public init(options: PageMenuOptions? = nil) { self.options = options ?? DefaultPageMenuOption() super.init(nibName: nil, bundle: nil) } required public init?(coder: NSCoder) { self.options = DefaultPageMenuOption() super.init(coder: coder) } public init?(coder: NSCoder, options: PageMenuOptions? = nil) { self.options = options ?? DefaultPageMenuOption() super.init(coder: coder) } override open func viewDidLoad() { super.viewDidLoad() self.setup() } override open func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if let currentIndex = self.currentIndex, self.isInfinite { self.tabView.updateCurrentIndex(currentIndex, shouldScroll: true) } } override open func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.tabView.layouted = true } /** Reload the view controllers in the page view controller. This reloads the dataSource entirely, calling viewControllers(forPageMenuViewController:) and defaultPageIndex(forPageMenuViewController:). */ public func reloadPages() { self.reloadPages(reloadViewControllers: true) } /** Transitions to the next page. - parameter animated: A Boolean whether or not to animate the transition - parameter completion: A block that's called after the transition is finished. The block parameter `transitionSuccessful` is `true` if the transition to the selected view controller was completed successfully. */ public func scrollToNext(animated: Bool, completion: ((Bool) -> Void)?) { self.pageViewController.scrollForward(animated: animated, completion: completion) } /** Transitions to the previous page. - parameter animated: A Boolean whether or not to animate the transition - parameter completion: A block that's called after the transition is finished. The block parameter `transitionSuccessful` is `true` if the transition to the selected view controller was completed successfully. */ public func scrollToPrevious(animated: Bool, completion: ((Bool) -> Void)?) { self.pageViewController.scrollReverse(animated: animated, completion: completion) } /** Show page controller with index - parameter index: Index that you want to show - parameter direction: The direction of the navigation and animation - parameter animated: A Boolean whether or not to animate the transition */ fileprivate func displayController(with index: Int, direction: EMPageViewControllerNavigationDirection, animated: Bool) { if self.pageViewController.scrolling { return } if self.pageViewController.selectedViewController == viewControllers[index] { self.tabView.updateCollectionViewUserInteractionEnabled(true) return } self.beforeIndex = index self.pageViewController.delegate = nil self.tabView.updateCollectionViewUserInteractionEnabled(false) let completion: ((Bool) -> Void) = { [weak self] _ in guard let `self` = self else { return } self.beforeIndex = index self.pageViewController.delegate = self self.tabView.updateCollectionViewUserInteractionEnabled(true) self.delegate?.pageMenuController?(self, didScrollToPageAtIndex: index, direction: direction.toPageMenuNavigationDirection) } self.delegate?.pageMenuController?(self, willScrollToPageAtIndex: self.currentIndex ?? 0, direction: direction.toPageMenuNavigationDirection) self.pageViewController.selectViewController(viewControllers[index], direction: direction, animated: animated, completion: completion) guard self.isViewLoaded else { return } self.tabView.updateCurrentIndex(index, shouldScroll: true) } /** Reload all pages - parameter reloadViewControllers: A Boolean whether or not to reload each page view controller */ fileprivate func reloadPages(reloadViewControllers: Bool) { guard let defaultIndex = self.dataSource?.defaultPageIndex(forPageMenuController: self) else { self.tabView.pageTabItems = [] return } if self.tabView.superview == nil { assertionFailure("TabMenuView needs to add subview before setting dataSource when you use custom menu position") } if self.beforeIndex == nil { self.beforeIndex = 0 } guard let titles = self.dataSource?.menuTitles(forPageMenuController: self), let viewControllers = self.dataSource?.viewControllers(forPageMenuController: self) else { return } if defaultIndex < 0 || defaultIndex >= titles.count || defaultIndex >= viewControllers.count { // error index return } if reloadViewControllers || self.viewControllers.count == 0 || self.menuTitles.count == 0 { self.viewControllers = viewControllers self.menuTitles = titles } if let beforeIndex = self.beforeIndex { self.tabView.pageTabItems = titles self.tabView.updateCurrentIndex(beforeIndex, shouldScroll: false, animated: false) } guard defaultIndex < self.viewControllers.count else { return } self.pageViewController.selectViewController(self.viewControllers[defaultIndex], direction: .forward, animated: false, completion: nil) } fileprivate func setup() { self.addChild(self.pageViewController) self.view.addSubview(self.pageViewController.view) switch self.options.tabMenuPosition { case .top: // add tab view self.view.addSubview(self.tabView) // setup page view controller layout self.pageViewController.view.translatesAutoresizingMaskIntoConstraints = false self.pageViewController.view.topAnchor.constraint(equalTo: self.tabView.bottomAnchor).isActive = true self.pageViewController.view.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true self.pageViewController.view.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true // setup tab view layout self.tabView.translatesAutoresizingMaskIntoConstraints = false self.tabView.heightAnchor.constraint(equalToConstant: options.menuItemSize.height).isActive = true self.tabView.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true self.tabView.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true // use layout guide or edge switch self.options.layout { case .layoutGuide: if #available(iOS 11.0, *) { self.pageViewController.view.bottomAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.bottomAnchor).isActive = true self.tabView.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor).isActive = true } else { self.pageViewController.view.bottomAnchor.constraint(equalTo: self.bottomLayoutGuide.bottomAnchor).isActive = true self.tabView.topAnchor.constraint(equalTo: self.topLayoutGuide.bottomAnchor).isActive = true } case .edge: self.pageViewController.view.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true self.tabView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true } case .bottom: // add tab view self.view.addSubview(self.tabView) // setup page view controller layout self.pageViewController.view.translatesAutoresizingMaskIntoConstraints = false self.pageViewController.view.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true self.pageViewController.view.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true self.pageViewController.view.bottomAnchor.constraint(equalTo: self.tabView.topAnchor).isActive = true // setup tab view layout self.tabView.translatesAutoresizingMaskIntoConstraints = false self.tabView.heightAnchor.constraint(equalToConstant: options.menuItemSize.height).isActive = true self.tabView.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true self.tabView.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true // use layout guide or edge switch self.options.layout { case .layoutGuide: if #available(iOS 11.0, *) { self.pageViewController.view.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor).isActive = true self.tabView.bottomAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.bottomAnchor).isActive = true } else { self.pageViewController.view.topAnchor.constraint(equalTo: self.topLayoutGuide.bottomAnchor).isActive = true self.tabView.bottomAnchor.constraint(equalTo: self.bottomLayoutGuide.topAnchor).isActive = true } case .edge: self.pageViewController.view.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true self.tabView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true } case .custom: // setup page view controller layout self.pageViewController.view.translatesAutoresizingMaskIntoConstraints = false self.pageViewController.view.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true self.pageViewController.view.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true // use layout guide or edge switch self.options.layout { case .layoutGuide: if #available(iOS 11.0, *) { self.pageViewController.view.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor).isActive = true self.pageViewController.view.bottomAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.bottomAnchor).isActive = true } else { self.pageViewController.view.topAnchor.constraint(equalTo: self.topLayoutGuide.bottomAnchor).isActive = true self.pageViewController.view.bottomAnchor.constraint(equalTo: self.bottomLayoutGuide.topAnchor).isActive = true } case .edge: self.pageViewController.view.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true self.pageViewController.view.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true } } self.view.sendSubviewToBack(self.pageViewController.view) self.pageViewController.didMove(toParent: self) } } // MARK:- EMPageViewControllerDelegate extension PageMenuController: EMPageViewControllerDelegate { func em_pageViewController(_ pageViewController: EMPageViewController, willStartScrollingFrom startingViewController: UIViewController, destinationViewController: UIViewController, direction: EMPageViewControllerNavigationDirection) { // Order to prevent the the hit repeatedly during animation self.tabView.updateCollectionViewUserInteractionEnabled(false) self.delegate?.pageMenuController?(self, willScrollToPageAtIndex: self.currentIndex ?? 0, direction: direction.toPageMenuNavigationDirection) } func em_pageViewController(_ pageViewController: EMPageViewController, didFinishScrollingFrom startingViewController: UIViewController?, destinationViewController: UIViewController, direction: EMPageViewControllerNavigationDirection, transitionSuccessful: Bool) { if let currentIndex = self.currentIndex, currentIndex < self.tabItemCount { self.tabView.updateCurrentIndex(currentIndex, shouldScroll: true) self.beforeIndex = currentIndex self.delegate?.pageMenuController?(self, didScrollToPageAtIndex: currentIndex, direction: direction.toPageMenuNavigationDirection) } self.tabView.updateCollectionViewUserInteractionEnabled(true) } func em_pageViewController(_ pageViewController: EMPageViewController, isScrollingFrom startingViewController: UIViewController, destinationViewController: UIViewController?, direction: EMPageViewControllerNavigationDirection, progress: CGFloat) { guard let beforeIndex = self.beforeIndex else { return } var index: Int if progress > 0 { index = beforeIndex + 1 } else { index = beforeIndex - 1 } if index == self.tabItemCount { index = 0 } else if index < 0 { index = self.tabItemCount - 1 } let scrollOffsetX = self.view.frame.width * progress self.tabView.scrollCurrentBarView(index, contentOffsetX: scrollOffsetX, progress: progress) self.delegate?.pageMenuController?(self, scrollingProgress: progress, direction: direction.toPageMenuNavigationDirection) } } // MARK:- EMPageViewControllerDataSource extension PageMenuController: EMPageViewControllerDataSource { private func nextViewController(_ viewController: UIViewController, isAfter: Bool) -> UIViewController? { guard var index = viewControllers.firstIndex(of: viewController) else { return nil } if isAfter { index += 1 } else { index -= 1 } if self.isInfinite { if index < 0 { index = viewControllers.count - 1 } else if index == viewControllers.count { index = 0 } } if index >= 0 && index < viewControllers.count { return viewControllers[index] } return nil } func em_pageViewController(_ pageViewController: EMPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? { return nextViewController(viewController, isAfter: true) } func em_pageViewController(_ pageViewController: EMPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? { return nextViewController(viewController, isAfter: false) } }
mit
6a1279eb5eb21f8fd659309ee06e4011
41.045767
215
0.645205
5.866539
false
false
false
false
gregomni/swift
test/Generics/rdar83848546.swift
3
1692
// RUN: %target-typecheck-verify-swift -debug-generic-signatures -requirement-machine-protocol-signatures=on 2>&1 | %FileCheck %s // CHECK: 83848546.(file).Reporter@ // CHECK-NEXT: Requirement signature: <Self where Self.[Reporter]SubReporterType : SubReporter> protocol Reporter { associatedtype SubReporterType: SubReporter func makeSubReporter() -> SubReporterType } // CHECK: 83848546.(file).SubReporter@ // CHECK-NEXT: Requirement signature: <Self where Self.[SubReporter]SubReporterType : SubReporter> protocol SubReporter { associatedtype SubReporterType: SubReporter func makeSubReporter() -> SubReporterType } // CHECK: 83848546.(file).CausesCompilerCrash@ // CHECK-NEXT: Requirement signature: <Self where Self.[CausesCompilerCrash]ReporterType : Reporter, Self.[CausesCompilerCrash]SubReporterType == Self.[CausesCompilerCrash]ReporterType.[Reporter]SubReporterType, Self.[CausesCompilerCrash]ReporterType.[Reporter]SubReporterType == Self.[CausesCompilerCrash]SubReporterType.[SubReporter]SubReporterType> protocol CausesCompilerCrash { associatedtype ReporterType: Reporter associatedtype SubReporterType where ReporterType.SubReporterType == SubReporterType, SubReporterType.SubReporterType == SubReporterType } // CHECK: 83848546.(file).DoesNotCrash@ // CHECK-NEXT: Requirement signature: <Self where Self.[DoesNotCrash]ReporterType : Reporter, Self.[DoesNotCrash]ReporterType.[Reporter]SubReporterType == Self.[DoesNotCrash]ReporterType.[Reporter]SubReporterType.[SubReporter]SubReporterType> protocol DoesNotCrash { associatedtype ReporterType: Reporter where ReporterType.SubReporterType == ReporterType.SubReporterType.SubReporterType }
apache-2.0
addf80e6c3afcd02e7afaeedba5c29a6
53.580645
351
0.808511
5.190184
false
false
false
false