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
zach-freeman/swift-localview
localview/PopViewTransitionAnimator.swift
1
2384
// // PopViewTransitionAnimator.swift // localview // // Created by Zach Freeman on 10/8/15. // Copyright © 2021 sparkwing. All rights reserved. // import UIKit class PopViewTransitionAnimator: NSObject, UIViewControllerAnimatedTransitioning { let duration = 0.75 var presenting = true var originFrame = CGRect.zero func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return duration } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { let containerView = transitionContext.containerView let fromViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from) let toViewController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) toViewController!.view.frame = fromViewController!.view.frame if self.presenting == true { toViewController!.view.alpha = 0 toViewController!.view.transform = CGAffineTransform(scaleX: 0, y: 0) UIView.animate(withDuration: duration, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.3, options: [], animations: { () -> Void in toViewController!.view.alpha = 1 toViewController!.view.transform = CGAffineTransform(scaleX: 1, y: 1) containerView.addSubview(toViewController!.view) }, completion: { (completed) -> Void in transitionContext.completeTransition(completed) }) } else { UIView.animate(withDuration: duration, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.3, options: [], animations: { () -> Void in fromViewController!.view.alpha = 0 fromViewController!.view.transform = CGAffineTransform(scaleX: 0.001, y: 0.0001) }, completion: { (completed) -> Void in fromViewController?.view.removeFromSuperview() transitionContext.completeTransition(completed) }) } } }
mit
fd31c55ca7e70ef829b909b654ca3d1c
44.826923
116
0.603861
6.157623
false
false
false
false
berishaerblin/Attendance
Attendance/Subjects.swift
1
2170
// // Subjects.swift // Attendance // // Created by Erblin Berisha on 8/9/17. // Copyright © 2017 Erblin Berisha. All rights reserved. // import UIKit import CoreData class Subjects: NSManagedObject { class func insertIntoSubjects(theSubject: CreateSubject, in context: NSManagedObjectContext) -> Subjects { let subject = Subjects(context: context) subject.subjectName = theSubject.subjectName // subject.subjectProfessor = Professor.insertIntoProfessor(theProfessor: thisProfessor, in: context) return subject } class func insertNewSubjectIntoProfessor(theSubject: CreateSubject, into theProfessor: CreateNewSubjectIntoProfessor, in context: NSManagedObjectContext) { let subject = Subjects(context: context) subject.subjectName = theSubject.subjectName subject.subjectProfessor = Professor.insertNewSubject(into: theProfessor, in: context) } class func insertNewStudent(theStudent: StudentsAttendance, in context: NSManagedObjectContext) -> Subjects { let request: NSFetchRequest<Subjects> = Subjects.fetchRequest() request.predicate = NSPredicate(format: "subjectName = %@", theStudent.subject) do { let matches = try context.fetch(request) if matches.count > 0{ assert (matches.count >= 1, "Subjects -- database inconsistency!") return matches[0] } } catch { print("unable to find") } return Subjects() } class func find(theSubject: String, in context: NSManagedObjectContext) -> Subjects { let request: NSFetchRequest<Subjects> = Subjects.fetchRequest() request.predicate = NSPredicate(format: "subjectName = %@", theSubject) do { let matches = try context.fetch(request) if matches.count > 0{ assert (matches.count >= 1, "Subjects -- database inconsistency!") return matches[0] } } catch { print("unable to find") } return Subjects() } }
gpl-3.0
c5dcb8e93e3b25f8c0e20b3e0504bc79
32.890625
162
0.626556
5.009238
false
false
false
false
MaartenBrijker/project
project/External/AudioKit-master/AudioKit/OSX/AudioKit/AudioKit for OSX.playground/Pages/Sequencer - Multiple output.xcplaygroundpage/Contents.swift
1
1469
//: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next) //: //: --- //: //: ## Sequencer - Multiple output //: import XCPlayground import AudioKit //: Create the sequencer, but we can't init it until we do some basic setup var sequencer: AKSequencer //: Create some samplers, load different sounds, and connect it to a mixer and the output var sampler1 = AKSampler() var sampler2 = AKSampler() sampler1.loadEXS24("Sounds/sawPiano1") sampler2.loadEXS24("Sounds/sqrTone1") var mixer = AKMixer() mixer.connect(sampler1) mixer.connect(sampler2) let reverb = AKCostelloReverb(mixer) AudioKit.output = reverb //: Load in a midi file, and set the sequencer to the main audiokit engine sequencer = AKSequencer(filename: "4tracks", engine: AudioKit.engine) //: Do some basic setup to make the sequence loop correctly sequencer.setLength(4) sequencer.loopOn() //: Here we set each alternating track to a different instrument //: (Note that track 0 in our case is just meta information...not actual notes) sequencer.avTracks[1].destinationAudioUnit = sampler1.samplerUnit sequencer.avTracks[2].destinationAudioUnit = sampler2.samplerUnit sequencer.avTracks[3].destinationAudioUnit = sampler1.samplerUnit sequencer.avTracks[4].destinationAudioUnit = sampler2.samplerUnit //: Hear it go AudioKit.start() sequencer.play() XCPlaygroundPage.currentPage.needsIndefiniteExecution = true //: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
apache-2.0
9acab1966c7d4658492076c00ef18372
30.934783
89
0.762423
3.654229
false
false
false
false
williamFalcon/Bolt_Swift
Source/MKMapView/MKMapView.swift
2
3042
// // MKMapView.swift // Pokecast // // Created by William Falcon on 7/17/16. // Copyright © 2016 William Falcon. All rights reserved. // import UIKit import MapKit public extension MKMapView { func _mapWidthInMeters() -> CLLocationDistance { let deltaLon = self.region.span.longitudeDelta let latCircumference = 40075160 * cos(self.region.center.latitude * M_PI / 180) return deltaLon * latCircumference / 360 } func _getZoom() -> Double { // function returns current zoom of the map var angleCamera = self.camera.heading if angleCamera > 270 { angleCamera = 360 - angleCamera } else if angleCamera > 90 { angleCamera = fabs(angleCamera - 180) } let angleRad = M_PI * angleCamera / 180 // camera heading in radians let width = Double(self.frame.size.width) let height = Double(self.frame.size.height) let heightOffset : Double = 20 // the offset (status bar height) which is taken by MapKit into consideration to calculate visible area height // calculating Longitude span corresponding to normal (non-rotated) width let spanStraight = width * self.region.span.longitudeDelta / (width * cos(angleRad) + (height - heightOffset) * sin(angleRad)) return (log2(360 * ((width / 256) / spanStraight)) + 1) - 2 } func _scaleAnnotations(maxZoomScale:Double, maxAnnotationSize: CGFloat, minAnnotationSize: CGFloat) { for annotation in self.annotations { if !(annotation is MKUserLocation) { if let annotationView = self.viewForAnnotation(annotation){ self._scaleAnnotation(annotationView, maxZoomScale: maxZoomScale, maxAnnotationSize: maxAnnotationSize, minAnnotationSize: minAnnotationSize, onComplete: nil) } } } } func _widthInMeters() -> Double { let mRect: MKMapRect = self.visibleMapRect let eastMapPoint = MKMapPointMake(MKMapRectGetMinX(mRect), MKMapRectGetMidY(mRect)) let westMapPoint = MKMapPointMake(MKMapRectGetMaxX(mRect), MKMapRectGetMidY(mRect)) let currentDistWideInMeters = MKMetersBetweenMapPoints(eastMapPoint, westMapPoint) return currentDistWideInMeters } func _scaleAnnotation(annotationView: MKAnnotationView , maxZoomScale:Double, maxAnnotationSize: CGFloat, minAnnotationSize: CGFloat, onComplete:(()->())?) { let scale = _getZoom() / maxZoomScale let newWidth : CGFloat = minAnnotationSize + CGFloat(scale) * (maxAnnotationSize - minAnnotationSize) var frame = annotationView.frame let center = annotationView.center frame.size.width = newWidth frame.size.height = newWidth GCD._dispatchMainQueue { annotationView.frame = frame annotationView.center = center onComplete?() } } }
mit
d764179bcdfd07f4fbc8156b040ccd3a
37.493671
178
0.64025
4.788976
false
false
false
false
saasquatch/mobile-sdk-ios-sample
SampleApp/User.swift
1
1077
// // User.swift // SampleApp // // Created by Brendan Crawford on 2016-03-18. // Copyright © 2016 Brendan Crawford. All rights reserved. // Updated by Trevor Lee on 2017-03-21 // import Foundation class User: NSObject { static let sharedUser = User() var token: String? var token_raw: String? var id: String! var accountId: String! var firstName: String! var lastName: String! var email: String! var referralCode: String! var tenant: String! var shareLinks: [String: String]! func login(token: String?, token_raw: String?, id: String, accountId: String, firstName: String, lastName: String, email: String, referralCode: String, tenant: String, shareLinks: [String: String]?) { self.token = token self.token_raw = token_raw self.id = id self.accountId = accountId self.firstName = firstName self.lastName = lastName self.email = email self.referralCode = referralCode self.tenant = tenant self.shareLinks = shareLinks } }
mit
46e4f5b259cd3604732f5210ce2c4df3
26.589744
204
0.639405
3.985185
false
false
false
false
lpniuniu/bookmark
bookmark/bookmark/BookBusiness/NotificationManager.swift
1
2012
// // NotificationManager.swift // bookmark // // Created by familymrfan on 17/1/17. // Copyright © 2017年 niuniu. All rights reserved. // import UserNotifications import Bulb import RealmSwift class AuthNotiSignal : BulbBoolSignal { } class NotificationManager { class func registerNotification() { let un = UNUserNotificationCenter.current() un.requestAuthorization(options: [.sound, .alert], completionHandler: { (b:Bool, error:Error?) in if b == true { Bulb.bulbGlobal().hungUp(AuthNotiSignal.signalDefault(), data: nil) } else { print("notification not open !") } }) } class func sendUrge() { let identifier = "BookSendUrgeNotiIdentifier" let un = UNUserNotificationCenter.current() un.removePendingNotificationRequests(withIdentifiers: [identifier]) let content = UNMutableNotificationContent() content.title = "该读书了" content.body = "记得保持每天阅读的习惯哦!" content.sound = UNNotificationSound.default() let realm = try! Realm() let results = realm.objects(BookSettingData.self); var dict = [String:BookSettingData]() for result in results { dict[result.key!] = result } if dict["urge_switch"]!.value == "1" { let dateFormatter = DateFormatter() let initialString = dict["urge_time"]!.value! dateFormatter.dateFormat = "HH:mm" let date = dateFormatter.date(from: initialString)! let triggerDaily = Calendar.current.dateComponents([.hour,.minute], from: date) let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDaily, repeats: true) let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger) un.add(request, withCompletionHandler:nil) } } }
mit
b80e1729d14ff310402312e6193543f6
32.508475
107
0.617602
4.629977
false
false
false
false
johnmyqin/SlidingContainerViewController
SlidingContainerViewController/DemoViewController.swift
1
2862
// // DemoViewController.swift // SlidingContainerViewController // // Created by Cem Olcay on 10/04/15. // Copyright (c) 2015 Cem Olcay. All rights reserved. // import UIKit class DemoViewController: UIViewController, SlidingContainerViewControllerDelegate { override func viewDidLoad() { super.viewDidLoad() navigationItem.title = "Demo" navigationController?.navigationBar.titleTextAttributes = [ NSFontAttributeName: UIFont(name: "HelveticaNeue-Light", size: 20)! ] } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) let vc1 = viewControllerWithColorAndTitle(UIColor.whiteColor(), title: "First View Controller") let vc2 = viewControllerWithColorAndTitle(UIColor.whiteColor(), title: "Second View Controller") let vc3 = viewControllerWithColorAndTitle(UIColor.whiteColor(), title: "Third View Controller") let vc4 = viewControllerWithColorAndTitle(UIColor.whiteColor(), title: "Forth View Controller") let slidingContainerViewController = SlidingContainerViewController ( parent: self, contentViewControllers: [vc1, vc2, vc3, vc4], titles: ["First", "Second", "Third", "Forth"]) view.addSubview(slidingContainerViewController.view) slidingContainerViewController.sliderView.appearance.outerPadding = 0 slidingContainerViewController.sliderView.appearance.innerPadding = 50 slidingContainerViewController.setCurrentViewControllerAtIndex(0) } func viewControllerWithColorAndTitle (color: UIColor, title: String) -> UIViewController { let vc = UIViewController () vc.view.backgroundColor = color let label = UILabel (frame: vc.view.frame) label.textColor = UIColor.blackColor() label.textAlignment = .Center label.font = UIFont (name: "HelveticaNeue-Light", size: 25) label.text = title label.sizeToFit() label.center = view.center vc.view.addSubview(label) return vc } // MARK: SlidingContainerViewControllerDelegate func slidingContainerViewControllerDidShowSliderView(slidingContainerViewController: SlidingContainerViewController) { } func slidingContainerViewControllerDidHideSliderView(slidingContainerViewController: SlidingContainerViewController) { } func slidingContainerViewControllerDidMoveToViewController(slidingContainerViewController: SlidingContainerViewController, viewController: UIViewController) { } func slidingContainerViewControllerDidMoveToViewControllerAtIndex(slidingContainerViewController: SlidingContainerViewController, index: Int) { } }
mit
0779833f24031c45fb729ed6f7f842df
35.227848
162
0.695318
5.712575
false
false
false
false
lieonCX/Live
Live/View/User/Cells/RealInfoCommitCell.swift
1
2314
// // RealInfoCommitCell.swift // Live // // Created by fanfans on 2017/7/5. // Copyright © 2017年 ChengDuHuanLeHui. All rights reserved. // import UIKit class RealInfoCommitCell: UITableViewCell, ViewNameReusable { fileprivate lazy var bgView: UIView = { let view: UIView = UIView() view.backgroundColor = .white return view }() lazy var tipLable: UILabel = { let tipLable: UILabel = UILabel() tipLable.textAlignment = .left tipLable.textColor = UIColor(hex: 0x222222) tipLable.font = UIFont.systemFont(ofSize: 14) return tipLable }() lazy var inputTextFiled: UITextField = { let inputTextFiled: UITextField = UITextField() inputTextFiled.textColor = UIColor(hex: 0x222222) inputTextFiled.font = UIFont.systemFont(ofSize: 14) inputTextFiled.textAlignment = .left return inputTextFiled }() fileprivate lazy var line: UIView = { let line: UIView = UIView() line.backgroundColor = UIColor(hex: 0xe5e5e5) return line }() override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) contentView.addSubview(bgView) bgView.addSubview(tipLable) bgView.addSubview(inputTextFiled) bgView.addSubview(line) bgView.snp.makeConstraints { (maker) in maker.top.equalTo(0) maker.left.equalTo(0) maker.right.equalTo(0) maker.bottom.equalTo(0) } tipLable.snp.makeConstraints { (maker) in maker.left.equalTo(12) maker.width.equalTo(80) maker.centerY.equalTo(bgView.snp.centerY) } inputTextFiled.snp.makeConstraints { (maker) in maker.right.equalTo(-12) maker.left.equalTo(tipLable.snp.right) maker.top.equalTo(0) maker.bottom.equalTo(0) } line.snp.makeConstraints { (maker) in maker.left.equalTo(0) maker.height.equalTo(0.5) maker.bottom.equalTo(0) maker.right.equalTo(0) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
22ef3e8dfb9cf8b0acb06e5a52b4c07e
31.549296
74
0.612722
4.343985
false
false
false
false
lieonCX/Live
Live/View/User/Cells/UserInfoManagerBaseInfoCell.swift
1
2807
// // UserInfoManagerBaseInfoCell.swift // Live // // Created by fanfans on 2017/7/4. // Copyright © 2017年 ChengDuHuanLeHui. All rights reserved. // import UIKit class UserInfoManagerBaseInfoCell: UITableViewCell, ViewNameReusable { fileprivate lazy var bgView: UIView = { let view: UIView = UIView() view.backgroundColor = .white return view }() lazy var tipLable: UILabel = { let tipLable: UILabel = UILabel() tipLable.textAlignment = .left tipLable.textColor = UIColor(hex: 0x222222) tipLable.font = UIFont.systemFont(ofSize: 14) return tipLable }() lazy var inputTextFiled: UITextField = { let inputTextFiled: UITextField = UITextField() inputTextFiled.textColor = UIColor(hex: 0x222222) inputTextFiled.font = UIFont.systemFont(ofSize: 14) inputTextFiled.textAlignment = .right return inputTextFiled }() lazy var rightArrow: UIImageView = { let rightArrow: UIImageView = UIImageView() rightArrow.image = UIImage(named:"right_arrow") rightArrow.contentMode = .center return rightArrow }() lazy var line: UIView = { let line: UIView = UIView() line.backgroundColor = UIColor(hex: 0xe5e5e5) return line }() override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) contentView.backgroundColor = UIColor(hex: CustomKey.Color.mainBackgroundColor) contentView.addSubview(bgView) bgView.addSubview(tipLable) bgView.addSubview(inputTextFiled) bgView.addSubview(rightArrow) bgView.addSubview(line) bgView.snp.makeConstraints { (maker) in maker.top.equalTo(0) maker.left.equalTo(0) maker.right.equalTo(0) maker.bottom.equalTo(0) } tipLable.snp.makeConstraints { (maker) in maker.left.equalTo(12) maker.centerY.equalTo(bgView.snp.centerY) } rightArrow.snp.makeConstraints { (maker) in maker.top.equalTo(0) maker.right.equalTo(0) maker.bottom.equalTo(0) maker.width.equalTo(50) } inputTextFiled.snp.makeConstraints { (maker) in maker.right.equalTo(-50) maker.left.equalTo(12) maker.centerY.equalTo(bgView.snp.centerY) } line.snp.makeConstraints { (maker) in maker.left.equalTo(0) maker.height.equalTo(0.5) maker.bottom.equalTo(0) maker.right.equalTo(0) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
b4bd62dd4d0e6d7a349c7d45846c9bac
32.783133
87
0.619116
4.4864
false
false
false
false
yaslab/ZipArchive.swift
Sources/ZipIO/MemoryStream.swift
1
2877
// // MemoryStream.swift // ZipArchive // // Created by Yasuhiro Hatta on 2017/06/17. // Copyright © 2017 yaslab. All rights reserved. // import Foundation public class ReadOnlyMemoryStream: RandomAccessInputStream { fileprivate var _buffer: UnsafeMutableRawPointer fileprivate var _count: Int fileprivate var _position: Int = 0 fileprivate typealias Deallocator = (UnsafeMutableRawPointer, Int) -> Void fileprivate let _deallocator: Deallocator fileprivate init(bytesNoCopy bytes: UnsafeMutableRawPointer, count: Int, deallocator: @escaping Deallocator) { _buffer = bytes _count = count _deallocator = deallocator } public convenience init(data: Data) { let copied: UnsafeMutableRawPointer = malloc(data.count) data.withUnsafeBytes { copied.copyMemory(from: $0, byteCount: data.count) } self.init(bytesNoCopy: copied, count: data.count, deallocator: { p, _ in free(p) }) } deinit { _deallocator(_buffer, _count) } public func close() -> Bool { return true } public func read(buffer: UnsafeMutableRawPointer, count: Int) -> Int { let length = min(count, _count - _position) buffer.copyMemory(from: _buffer + _position, byteCount: length) _position += length return length } public func seek(offset: Int64, origin: SeekOrigin) -> Bool { switch origin { case .begin: if offset < 0 || _count < offset { return false } _position = Int(offset) case .current: return self.seek(offset: Int64(_position) + offset, origin: .begin) case .end: return self.seek(offset: Int64(_count) + offset, origin: .begin) } return true } public func tell() -> Int64 { return Int64(_position) } } public final class MemoryStream: ReadOnlyMemoryStream, OutputStream { private var _capacity: Int public init(capacity: Int = 0) { assert(capacity >= 0) _capacity = capacity > 8 ? capacity : 8 super.init(bytesNoCopy: malloc(_capacity), count: 0, deallocator: { p, _ in free(p) }) } public func write(buffer: UnsafeRawPointer, count: Int) -> Int { let position = _position + count if _capacity < position { var capacity = (_capacity == 0) ? 1 : _capacity while capacity < position { capacity *= 2 } guard let new = realloc(_buffer, capacity) else { fatalError() } _buffer = new _capacity = capacity } memcpy(_buffer + _position, buffer, count) _position = position _count = max(_count, position) return count } }
mit
2dd343b26cd9b023f010afdc3428bc6c
27.475248
114
0.582406
4.586922
false
false
false
false
HarveyHu/BLEHelper
BLEHelperExample/BLEHelperExample/BLE.swift
1
3770
// // BLE.swift // BLEHelperExample // // Created by HarveyHu on 3/21/16. // Copyright © 2016 HarveyHu. All rights reserved. // import Foundation import BLEHelper import CoreBluetooth protocol BLEDelegate { func didReceivedData(dataString: String) } func prettyLog(message: String = "", file:String = #file, function:String = #function, line:Int = #line) { print("\((file as NSString).lastPathComponent)(\(line)) \(function) \(message)") } class BLE: BLECentralHelperDelegate { let bleHelper = BLECentralHelper() static let sharedInstance = BLE() var targetDeviceUUID: String? var delegate: BLEDelegate? var judgeInitSet = Set<String>() var bufferString = "" private init () { bleHelper.delegate = self } //MARK: - BLECentralHelperDelegate func bleDidDisconnectFromPeripheral(peripheral: CBPeripheral) { prettyLog("didDisconnectFromPeripheral:\(peripheral.identifier.UUIDString)") } func bleCentralDidReceiveData(data: NSData?, peripheral: CBPeripheral, characteristic: CBCharacteristic) { prettyLog("ReceiveData:\(String(data: data!, encoding: NSUTF8StringEncoding))") guard let string = String(data: data!, encoding: NSUTF8StringEncoding) else { return } self.delegate?.didReceivedData(string) } //MARK: - Operation func scan(completion: (peripheralList: [CBPeripheral]) -> (Void)) { bleHelper.scan(1.0, serviceUUID: nil, handler: completion) } func connect(deviceUUID: String, completion: ((success: Bool) -> (Void))?) { self.targetDeviceUUID = deviceUUID self.bleHelper.retrieve(deviceUUIDs: [self.targetDeviceUUID!], completion: {(peripheral, error) -> (Void) in if error != nil { prettyLog("error: \(error?.description)") completion?(success: false) return } /* case Disconnected = 0 case Connecting case Connected case Disconnecting */ prettyLog("pheripheral.state: \(peripheral.state)") completion?(success: true) }) return } func disconnect(uuid: String?) { bleHelper.disconnect(uuid) } func read(sUUID: String, cUUID: String) { if !bleHelper.isConnected(targetDeviceUUID!) { prettyLog("device is not conncted.") return } bleHelper.readValue(targetDeviceUUID!, serviceUUID: sUUID, characteristicUUID: cUUID) { (success) -> (Void) in prettyLog("is read success: \(success)") } } func enableNotification(sUUID: String, cUUID: String, completion: ((success: Bool) -> (Void))?) { if !bleHelper.isConnected(targetDeviceUUID!) { prettyLog("device is not conncted.") return } prettyLog("targetDeviceUUID: \(targetDeviceUUID!)") bleHelper.enableNotification(true, deviceUUID: targetDeviceUUID!, serviceUUID: sUUID, characteristicUUID: cUUID) { (success) -> (Void) in prettyLog("set notify success: \(success)") completion?(success: success) } } func write(command: String, sUUID: String, cUUID: String) { if !bleHelper.isConnected(targetDeviceUUID!) { prettyLog("device is not conncted.") return } if let data = command.dataUsingEncoding(NSUTF8StringEncoding) { bleHelper.writeValue(data, deviceUUID: targetDeviceUUID!, serviceUUID: sUUID, characteristicUUID: cUUID) { (success) -> (Void) in prettyLog("is write success: \(success)") } } } }
mit
08f7e2f498338aea160d8467d0cea40f
32.070175
145
0.610772
4.647349
false
false
false
false
wantedly/Cerberus
Cerberus/Time.swift
1
1374
import Foundation struct Time { let hour: Int let minute: Int } extension Time { init(_ date: Date) { hour = Calendar.current.component(.hour, from: date) minute = Calendar.current.component(.minute, from: date) } static func now() -> Time { let now = Date() return Time(now) } var isCurrent: Bool { let now = Date() if let addingDate = Calendar.current.date(byAdding: .minute, value: -Time.strideTime.minute, to: now) { return Time(addingDate) < self && self <= Time(now) } return false } static let strideTime = Time(hour: 0, minute: 30) static let timesOfDay: [Time] = { let step = Double(strideTime.hour) + Double(strideTime.minute) / 60 return stride(from: 0.0, to: 24.0, by: step).map { let hour = Int($0) let minute = Int(60 * ($0 - Double(hour))) return Time(hour: hour, minute: minute) } }() } extension Time: Equatable { static func == (lhs: Time, rhs: Time) -> Bool { return lhs.hour == rhs.hour && lhs.minute == rhs.minute } } extension Time: Comparable { static func < (lhs: Time, rhs: Time) -> Bool { if lhs.hour != rhs.hour { return lhs.hour < rhs.hour } else { return lhs.minute < rhs.minute } } }
mit
bc31f7bed829d2842e5f27d71bc56b8b
24.924528
111
0.551674
3.713514
false
false
false
false
lhc70000/iina
iina/MPVController.swift
1
39352
// // MPVController.swift // iina // // Created by lhc on 8/7/16. // Copyright © 2016 lhc. All rights reserved. // import Cocoa import Foundation fileprivate typealias PK = Preference.Key fileprivate let yes_str = "yes" fileprivate let no_str = "no" /** Change this variable to adjust mpv log level */ /* "no" - disable absolutely all messages "fatal" - critical/aborting errors "error" - simple errors "warn" - possible problems "info" - informational message "v" - noisy informational message "debug" - very noisy technical information "trace" - extremely noisy */ fileprivate let MPVLogLevel = "warn" // Global functions protocol MPVEventDelegate { func onMPVEvent(_ event: MPVEvent) } class MPVController: NSObject { // The mpv_handle var mpv: OpaquePointer! var mpvRenderContext: OpaquePointer? var mpvClientName: UnsafePointer<CChar>! var mpvVersion: String! lazy var queue = DispatchQueue(label: "com.colliderli.iina.controller", qos: .userInitiated) unowned let player: PlayerCore var needRecordSeekTime: Bool = false var recordedSeekStartTime: CFTimeInterval = 0 var recordedSeekTimeListener: ((Double) -> Void)? var receivedEndFileWhileLoading: Bool = false var fileLoaded: Bool = false private var hooks: [UInt64: () -> Void] = [:] private var hookCounter: UInt64 = 1 let observeProperties: [String: mpv_format] = [ MPVProperty.trackList: MPV_FORMAT_NONE, MPVProperty.vf: MPV_FORMAT_NONE, MPVProperty.af: MPV_FORMAT_NONE, MPVOption.TrackSelection.vid: MPV_FORMAT_INT64, MPVOption.TrackSelection.aid: MPV_FORMAT_INT64, MPVOption.TrackSelection.sid: MPV_FORMAT_INT64, MPVOption.Subtitles.secondarySid: MPV_FORMAT_INT64, MPVOption.PlaybackControl.pause: MPV_FORMAT_FLAG, MPVProperty.chapter: MPV_FORMAT_INT64, MPVOption.Video.deinterlace: MPV_FORMAT_FLAG, MPVOption.Audio.mute: MPV_FORMAT_FLAG, MPVOption.Audio.volume: MPV_FORMAT_DOUBLE, MPVOption.Audio.audioDelay: MPV_FORMAT_DOUBLE, MPVOption.PlaybackControl.speed: MPV_FORMAT_DOUBLE, MPVOption.Subtitles.subDelay: MPV_FORMAT_DOUBLE, MPVOption.Subtitles.subScale: MPV_FORMAT_DOUBLE, MPVOption.Subtitles.subPos: MPV_FORMAT_DOUBLE, MPVOption.Equalizer.contrast: MPV_FORMAT_INT64, MPVOption.Equalizer.brightness: MPV_FORMAT_INT64, MPVOption.Equalizer.gamma: MPV_FORMAT_INT64, MPVOption.Equalizer.hue: MPV_FORMAT_INT64, MPVOption.Equalizer.saturation: MPV_FORMAT_INT64, MPVOption.Window.fullscreen: MPV_FORMAT_FLAG, MPVOption.Window.ontop: MPV_FORMAT_FLAG, MPVOption.Window.windowScale: MPV_FORMAT_DOUBLE, MPVProperty.mediaTitle: MPV_FORMAT_STRING ] init(playerCore: PlayerCore) { self.player = playerCore super.init() } deinit { ObjcUtils.silenced { self.optionObservers.forEach { (k, _) in UserDefaults.standard.removeObserver(self, forKeyPath: k) } } } /** Init the mpv context, set options */ func mpvInit() { // Create a new mpv instance and an associated client API handle to control the mpv instance. mpv = mpv_create() // Get the name of this client handle. mpvClientName = mpv_client_name(mpv) // User default settings if Preference.bool(for: .enableInitialVolume) { setUserOption(PK.initialVolume, type: .int, forName: MPVOption.Audio.volume, sync: false) } else { setUserOption(PK.softVolume, type: .int, forName: MPVOption.Audio.volume, sync: false) } // - Advanced // disable internal OSD let useMpvOsd = Preference.bool(for: .useMpvOsd) if !useMpvOsd { chkErr(mpv_set_option_string(mpv, MPVOption.OSD.osdLevel, "0")) } else { player.displayOSD = false } // log if Logger.enabled { let path = Logger.logDirectory.appendingPathComponent("mpv.log").path chkErr(mpv_set_option_string(mpv, MPVOption.ProgramBehavior.logFile, path)) } // - General setUserOption(PK.screenshotFolder, type: .other, forName: MPVOption.Screenshot.screenshotDirectory) { key in let screenshotPath = Preference.string(for: key)! return NSString(string: screenshotPath).expandingTildeInPath } setUserOption(PK.screenshotFormat, type: .other, forName: MPVOption.Screenshot.screenshotFormat) { key in let v = Preference.integer(for: key) return Preference.ScreenshotFormat(rawValue: v)?.string } setUserOption(PK.screenshotTemplate, type: .string, forName: MPVOption.Screenshot.screenshotTemplate) if #available(macOS 10.13, *) { chkErr(mpv_set_option_string(mpv, MPVOption.Input.inputMediaKeys, no_str)) } else { setUserOption(PK.useMediaKeys, type: .bool, forName: MPVOption.Input.inputMediaKeys) } setUserOption(PK.useAppleRemote, type: .bool, forName: MPVOption.Input.inputAppleremote) setUserOption(PK.keepOpenOnFileEnd, type: .other, forName: MPVOption.Window.keepOpen) { key in let keepOpen = Preference.bool(for: PK.keepOpenOnFileEnd) let keepOpenPl = !Preference.bool(for: PK.playlistAutoPlayNext) return keepOpenPl ? "always" : (keepOpen ? "yes" : "no") } setUserOption(PK.playlistAutoPlayNext, type: .other, forName: MPVOption.Window.keepOpen) { key in let keepOpen = Preference.bool(for: PK.keepOpenOnFileEnd) let keepOpenPl = !Preference.bool(for: PK.playlistAutoPlayNext) return keepOpenPl ? "always" : (keepOpen ? "yes" : "no") } chkErr(mpv_set_option_string(mpv, "watch-later-directory", Utility.watchLaterURL.path)) setUserOption(PK.resumeLastPosition, type: .bool, forName: MPVOption.ProgramBehavior.savePositionOnQuit) setUserOption(PK.resumeLastPosition, type: .bool, forName: "resume-playback") setUserOption(.initialWindowSizePosition, type: .string, forName: MPVOption.Window.geometry) // - Codec setUserOption(PK.videoThreads, type: .int, forName: MPVOption.Video.vdLavcThreads) setUserOption(PK.audioThreads, type: .int, forName: MPVOption.Audio.adLavcThreads) setUserOption(PK.hardwareDecoder, type: .other, forName: MPVOption.Video.hwdec) { key in let value = Preference.integer(for: key) return Preference.HardwareDecoderOption(rawValue: value)?.mpvString ?? "auto" } setUserOption(PK.audioLanguage, type: .string, forName: MPVOption.TrackSelection.alang) setUserOption(PK.maxVolume, type: .int, forName: MPVOption.Audio.volumeMax) var spdif: [String] = [] if Preference.bool(for: PK.spdifAC3) { spdif.append("ac3") } if Preference.bool(for: PK.spdifDTS){ spdif.append("dts") } if Preference.bool(for: PK.spdifDTSHD) { spdif.append("dts-hd") } setString(MPVOption.Audio.audioSpdif, spdif.joined(separator: ",")) setUserOption(PK.audioDevice, type: .string, forName: MPVOption.Audio.audioDevice) // - Sub chkErr(mpv_set_option_string(mpv, MPVOption.Subtitles.subAuto, "no")) chkErr(mpv_set_option_string(mpv, MPVOption.Subtitles.subCodepage, Preference.string(for: .defaultEncoding))) player.info.subEncoding = Preference.string(for: .defaultEncoding) let subOverrideHandler: OptionObserverInfo.Transformer = { key in let v = Preference.bool(for: .ignoreAssStyles) let level: Preference.SubOverrideLevel = Preference.enum(for: .subOverrideLevel) return v ? level.string : "yes" } setUserOption(PK.ignoreAssStyles, type: .other, forName: MPVOption.Subtitles.subAssOverride, transformer: subOverrideHandler) setUserOption(PK.subOverrideLevel, type: .other, forName: MPVOption.Subtitles.subAssOverride, transformer: subOverrideHandler) setUserOption(PK.subTextFont, type: .string, forName: MPVOption.Subtitles.subFont) setUserOption(PK.subTextSize, type: .int, forName: MPVOption.Subtitles.subFontSize) setUserOption(PK.subTextColor, type: .color, forName: MPVOption.Subtitles.subColor) setUserOption(PK.subBgColor, type: .color, forName: MPVOption.Subtitles.subBackColor) setUserOption(PK.subBold, type: .bool, forName: MPVOption.Subtitles.subBold) setUserOption(PK.subItalic, type: .bool, forName: MPVOption.Subtitles.subItalic) setUserOption(PK.subBlur, type: .float, forName: MPVOption.Subtitles.subBlur) setUserOption(PK.subSpacing, type: .float, forName: MPVOption.Subtitles.subSpacing) setUserOption(PK.subBorderSize, type: .int, forName: MPVOption.Subtitles.subBorderSize) setUserOption(PK.subBorderColor, type: .color, forName: MPVOption.Subtitles.subBorderColor) setUserOption(PK.subShadowSize, type: .int, forName: MPVOption.Subtitles.subShadowOffset) setUserOption(PK.subShadowColor, type: .color, forName: MPVOption.Subtitles.subShadowColor) setUserOption(PK.subAlignX, type: .other, forName: MPVOption.Subtitles.subAlignX) { key in let v = Preference.integer(for: key) return Preference.SubAlign(rawValue: v)?.stringForX } setUserOption(PK.subAlignY, type: .other, forName: MPVOption.Subtitles.subAlignY) { key in let v = Preference.integer(for: key) return Preference.SubAlign(rawValue: v)?.stringForY } setUserOption(PK.subMarginX, type: .int, forName: MPVOption.Subtitles.subMarginX) setUserOption(PK.subMarginY, type: .int, forName: MPVOption.Subtitles.subMarginY) setUserOption(PK.subPos, type: .int, forName: MPVOption.Subtitles.subPos) setUserOption(PK.subLang, type: .string, forName: MPVOption.TrackSelection.slang) setUserOption(PK.displayInLetterBox, type: .bool, forName: MPVOption.Subtitles.subUseMargins) setUserOption(PK.displayInLetterBox, type: .bool, forName: MPVOption.Subtitles.subAssForceMargins) setUserOption(PK.subScaleWithWindow, type: .bool, forName: MPVOption.Subtitles.subScaleByWindow) // - Network / cache settings setUserOption(PK.enableCache, type: .other, forName: MPVOption.Cache.cache) { key in return Preference.bool(for: key) ? nil : "no" } setUserOption(PK.defaultCacheSize, type: .int, forName: MPVOption.Cache.cacheDefault) setUserOption(PK.cacheBufferSize, type: .int, forName: MPVOption.Cache.cacheBackbuffer) setUserOption(PK.secPrefech, type: .int, forName: MPVOption.Cache.cacheSecs) setUserOption(PK.userAgent, type: .other, forName: MPVOption.Network.userAgent) { key in let ua = Preference.string(for: key)! return ua.isEmpty ? nil : ua } setUserOption(PK.transportRTSPThrough, type: .other, forName: MPVOption.Network.rtspTransport) { key in let v: Preference.RTSPTransportation = Preference.enum(for: .transportRTSPThrough) return v.string } setUserOption(PK.ytdlEnabled, type: .bool, forName: MPVOption.ProgramBehavior.ytdl) setUserOption(PK.ytdlRawOptions, type: .string, forName: MPVOption.ProgramBehavior.ytdlRawOptions) chkErr(mpv_set_option_string(mpv, MPVOption.ProgramBehavior.resetOnNextFile, "\(MPVOption.PlaybackControl.abLoopA),\(MPVOption.PlaybackControl.abLoopB)")) // Set user defined conf dir. if Preference.bool(for: .useUserDefinedConfDir) { if var userConfDir = Preference.string(for: .userDefinedConfDir) { userConfDir = NSString(string: userConfDir).standardizingPath mpv_set_option_string(mpv, "config", "yes") let status = mpv_set_option_string(mpv, MPVOption.ProgramBehavior.configDir, userConfDir) if status < 0 { Utility.showAlert("extra_option.config_folder", arguments: [userConfDir]) } } } // Set user defined options. if let userOptions = Preference.value(for: .userOptions) as? [[String]] { userOptions.forEach { op in let status = mpv_set_option_string(mpv, op[0], op[1]) if status < 0 { Utility.showAlert("extra_option.error", arguments: [op[0], op[1], status]) } } } else { Utility.showAlert("extra_option.cannot_read") } // Load external scripts // Load keybindings. This is still required for mpv to handle media keys or apple remote. let userConfigs = Preference.dictionary(for: .inputConfigs) var inputConfPath = PrefKeyBindingViewController.defaultConfigs["IINA Default"] if let confFromUd = Preference.string(for: .currentInputConfigName) { if let currentConfigFilePath = Utility.getFilePath(Configs: userConfigs, forConfig: confFromUd, showAlert: false) { inputConfPath = currentConfigFilePath } } chkErr(mpv_set_option_string(mpv, MPVOption.Input.inputConf, inputConfPath)) // Receive log messages at warn level. chkErr(mpv_request_log_messages(mpv, MPVLogLevel)) // Request tick event. // chkErr(mpv_request_event(mpv, MPV_EVENT_TICK, 1)) // Set a custom function that should be called when there are new events. mpv_set_wakeup_callback(self.mpv, { (ctx) in let mpvController = unsafeBitCast(ctx, to: MPVController.self) mpvController.readEvents() }, mutableRawPointerOf(obj: self)) // Observe propoties. observeProperties.forEach { (k, v) in mpv_observe_property(mpv, 0, k, v) } // Initialize an uninitialized mpv instance. If the mpv instance is already running, an error is retuned. chkErr(mpv_initialize(mpv)) // Set options that can be override by user's config. mpv will log user config when initialize, // so we put them here. chkErr(mpv_set_property_string(mpv, MPVOption.Video.vo, "libmpv")) chkErr(mpv_set_property_string(mpv, MPVOption.Window.keepaspect, "no")) chkErr(mpv_set_property_string(mpv, MPVOption.Video.gpuHwdecInterop, "auto")) // get version mpvVersion = getString(MPVProperty.mpvVersion) } func mpvInitRendering() { guard let mpv = mpv else { fatalError("mpvInitRendering() should be called after mpv handle being initialized!") } let apiType = UnsafeMutableRawPointer(mutating: (MPV_RENDER_API_TYPE_OPENGL as NSString).utf8String) var openGLInitParams = mpv_opengl_init_params(get_proc_address: mpvGetOpenGLFunc, get_proc_address_ctx: nil, extra_exts: nil) var advanced: CInt = 1 var params = [ mpv_render_param(type: MPV_RENDER_PARAM_API_TYPE, data: apiType), mpv_render_param(type: MPV_RENDER_PARAM_OPENGL_INIT_PARAMS, data: &openGLInitParams), mpv_render_param(type: MPV_RENDER_PARAM_ADVANCED_CONTROL, data: &advanced), mpv_render_param() ] mpv_render_context_create(&mpvRenderContext, mpv, &params) mpv_render_context_set_update_callback(mpvRenderContext!, mpvUpdateCallback, mutableRawPointerOf(obj: player.mainWindow.videoView.videoLayer)) } func mpvUninitRendering() { guard let mpvRenderContext = mpvRenderContext else { return } mpv_render_context_set_update_callback(mpvRenderContext, nil, nil) mpv_render_context_free(mpvRenderContext) } func mpvReportSwap() { guard let mpvRenderContext = mpvRenderContext else { return } mpv_render_context_report_swap(mpvRenderContext) } func shouldRenderUpdateFrame() -> Bool { guard let mpvRenderContext = mpvRenderContext else { return false } let flags: UInt64 = mpv_render_context_update(mpvRenderContext) return flags & UInt64(MPV_RENDER_UPDATE_FRAME.rawValue) > 0 } // Basically send quit to mpv func mpvQuit() { command(.quit) } // MARK: - Command & property // Send arbitrary mpv command. func command(_ command: MPVCommand, args: [String?] = [], checkError: Bool = true, returnValueCallback: ((Int32) -> Void)? = nil) { guard mpv != nil else { return } if args.count > 0 && args.last == nil { Logger.fatal("Command do not need a nil suffix") } var strArgs = args strArgs.insert(command.rawValue, at: 0) strArgs.append(nil) var cargs = strArgs.map { $0.flatMap { UnsafePointer<CChar>(strdup($0)) } } let returnValue = mpv_command(self.mpv, &cargs) for ptr in cargs { free(UnsafeMutablePointer(mutating: ptr)) } if checkError { chkErr(returnValue) } else if let cb = returnValueCallback { cb(returnValue) } } func command(rawString: String) -> Int32 { return mpv_command_string(mpv, rawString) } // Set property func setFlag(_ name: String, _ flag: Bool) { var data: Int = flag ? 1 : 0 mpv_set_property(mpv, name, MPV_FORMAT_FLAG, &data) } func setInt(_ name: String, _ value: Int) { var data = Int64(value) mpv_set_property(mpv, name, MPV_FORMAT_INT64, &data) } func setDouble(_ name: String, _ value: Double) { var data = value mpv_set_property(mpv, name, MPV_FORMAT_DOUBLE, &data) } func setFlagAsync(_ name: String, _ flag: Bool) { var data: Int = flag ? 1 : 0 mpv_set_property_async(mpv, 0, name, MPV_FORMAT_FLAG, &data) } func setIntAsync(_ name: String, _ value: Int) { var data = Int64(value) mpv_set_property_async(mpv, 0, name, MPV_FORMAT_INT64, &data) } func setDoubleAsync(_ name: String, _ value: Double) { var data = value mpv_set_property_async(mpv, 0, name, MPV_FORMAT_DOUBLE, &data) } func setString(_ name: String, _ value: String) { mpv_set_property_string(mpv, name, value) } func getInt(_ name: String) -> Int { var data = Int64() mpv_get_property(mpv, name, MPV_FORMAT_INT64, &data) return Int(data) } func getDouble(_ name: String) -> Double { var data = Double() mpv_get_property(mpv, name, MPV_FORMAT_DOUBLE, &data) return data } func getFlag(_ name: String) -> Bool { var data = Int64() mpv_get_property(mpv, name, MPV_FORMAT_FLAG, &data) return data > 0 } func getString(_ name: String) -> String? { let cstr = mpv_get_property_string(mpv, name) let str: String? = cstr == nil ? nil : String(cString: cstr!) mpv_free(cstr) return str } func getScreenshot(_ arg: String) -> NSImage { var args = try! MPVNode.create(["screenshot-raw", arg]) defer { MPVNode.free(args) } var result = mpv_node() mpv_command_node(self.mpv, &args, &result) let rawImage = try! MPVNode.parse(result) as! [String: Any] mpv_free_node_contents(&result) var pixelArray = rawImage["data"] as! [UInt8] // According to mpv's client.h, the pixel array mpv returns arrange // color data as "B8G8R8X8", whereas CGImages's data provider needs // RGBA, so swap each pixel at index 0 and 2. for i in 0 ..< pixelArray.count >> 2 { pixelArray.swapAt(i << 2, i << 2 | 2) } let width = Int(truncatingIfNeeded: rawImage["w"] as! Int64) let height = Int(truncatingIfNeeded: rawImage["h"] as! Int64) let rgbColorSpace = CGColorSpaceCreateDeviceRGB() let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue) let providerRef = CGDataProvider(data: NSData(bytes: pixelArray, length: pixelArray.count))! let cgImage = CGImage(width: width, height: height, bitsPerComponent: 8, bitsPerPixel: 4 * 8, bytesPerRow: width * 4, space: rgbColorSpace, bitmapInfo: bitmapInfo, provider: providerRef, decode: nil, shouldInterpolate: true, intent: .defaultIntent) return NSImage(cgImage: cgImage!, size: NSSize(width: width, height: height)) } /** Get filter. only "af" or "vf" is supported for name */ func getFilters(_ name: String) -> [MPVFilter] { Logger.ensure(name == MPVProperty.vf || name == MPVProperty.af, "getFilters() do not support \(name)!") var result: [MPVFilter] = [] var node = mpv_node() mpv_get_property(mpv, name, MPV_FORMAT_NODE, &node) guard let filters = (try? MPVNode.parse(node)!) as? [[String: Any?]] else { return result } filters.forEach { f in let filter = MPVFilter(name: f["name"] as! String, label: f["label"] as? String, params: f["params"] as? [String: String]) result.append(filter) } mpv_free_node_contents(&node) return result } /** Set filter. only "af" or "vf" is supported for name */ func setFilters(_ name: String, filters: [MPVFilter]) { Logger.ensure(name == MPVProperty.vf || name == MPVProperty.af, "setFilters() do not support \(name)!") let cmd = name == MPVProperty.vf ? MPVCommand.vf : MPVCommand.af let str = filters.map { $0.stringFormat }.joined(separator: ",") command(cmd, args: ["set", str], checkError: false) { returnValue in if returnValue < 0 { Utility.showAlert("filter.incorrect") // reload data in filter setting window self.player.postNotification(.iinaVFChanged) } } } func getNode(_ name: String) -> Any? { var node = mpv_node() mpv_get_property(mpv, name, MPV_FORMAT_NODE, &node) let parsed = try? MPVNode.parse(node) mpv_free_node_contents(&node) return parsed! } // MARK: - Hooks func addHook(_ name: MPVHook, priority: Int32 = 0, hook: @escaping () -> Void) { mpv_hook_add(mpv, hookCounter, name.rawValue, priority) hooks[hookCounter] = hook hookCounter += 1 } // MARK: - Events // Read event and handle it async private func readEvents() { queue.async { while ((self.mpv) != nil) { let event = mpv_wait_event(self.mpv, 0) // Do not deal with mpv-event-none if event?.pointee.event_id == MPV_EVENT_NONE { break } self.handleEvent(event) } } } // Handle the event private func handleEvent(_ event: UnsafePointer<mpv_event>!) { let eventId = event.pointee.event_id switch eventId { case MPV_EVENT_SHUTDOWN: let quitByMPV = !player.isMpvTerminated if quitByMPV { NSApp.terminate(nil) } else { mpv_destroy(mpv) mpv = nil } case MPV_EVENT_LOG_MESSAGE: let dataOpaquePtr = OpaquePointer(event.pointee.data) let msg = UnsafeMutablePointer<mpv_event_log_message>(dataOpaquePtr) let prefix = String(cString: (msg?.pointee.prefix)!) let level = String(cString: (msg?.pointee.level)!) let text = String(cString: (msg?.pointee.text)!) Logger.log("mpv log: [\(prefix)] \(level): \(text)", level: .warning, subsystem: .general, appendNewlineAtTheEnd: false) case MPV_EVENT_HOOK: let userData = event.pointee.reply_userdata let hookEvent = event.pointee.data.bindMemory(to: mpv_event_hook.self, capacity: 1).pointee let hookID = hookEvent.id if let hook = hooks[userData] { hook() } mpv_hook_continue(mpv, hookID) case MPV_EVENT_PROPERTY_CHANGE: let dataOpaquePtr = OpaquePointer(event.pointee.data) if let property = UnsafePointer<mpv_event_property>(dataOpaquePtr)?.pointee { let propertyName = String(cString: property.name) handlePropertyChange(propertyName, property) } case MPV_EVENT_AUDIO_RECONFIG: break case MPV_EVENT_VIDEO_RECONFIG: onVideoReconfig() break case MPV_EVENT_START_FILE: player.info.isIdle = false guard getString(MPVProperty.path) != nil else { break } player.fileStarted() let url = player.info.currentURL let message = player.info.isNetworkResource ? url?.absoluteString : url?.lastPathComponent player.sendOSD(.fileStart(message ?? "-")) case MPV_EVENT_FILE_LOADED: onFileLoaded() case MPV_EVENT_SEEK: player.info.isSeeking = true if needRecordSeekTime { recordedSeekStartTime = CACurrentMediaTime() } player.syncUI(.time) let osdText = (player.info.videoPosition?.stringRepresentation ?? Constants.String.videoTimePlaceholder) + " / " + (player.info.videoDuration?.stringRepresentation ?? Constants.String.videoTimePlaceholder) let percentage = (player.info.videoPosition / player.info.videoDuration) ?? 1 player.sendOSD(.seek(osdText, percentage)) case MPV_EVENT_PLAYBACK_RESTART: player.info.isIdle = false player.info.isSeeking = false if needRecordSeekTime { recordedSeekTimeListener?(CACurrentMediaTime() - recordedSeekStartTime) recordedSeekTimeListener = nil } player.playbackRestarted() player.syncUI(.time) case MPV_EVENT_END_FILE: // if receive end-file when loading file, might be error // wait for idle let reason = event!.pointee.data.load(as: mpv_end_file_reason.self) if player.info.fileLoading { if reason != MPV_END_FILE_REASON_STOP { receivedEndFileWhileLoading = true } } else { player.info.shouldAutoLoadFiles = false } break case MPV_EVENT_IDLE: if receivedEndFileWhileLoading && player.info.fileLoading { player.errorOpeningFileAndCloseMainWindow() player.info.fileLoading = false player.info.currentURL = nil player.info.isNetworkResource = false } player.info.isIdle = true if fileLoaded { fileLoaded = false player.closeMainWindow() } receivedEndFileWhileLoading = false break default: // let eventName = String(cString: mpv_event_name(eventId)) // Utility.log("mpv event (unhandled): \(eventName)") break } } private func onVideoParamsChange (_ data: UnsafePointer<mpv_node_list>) { //let params = data.pointee //params.keys. } private func onFileLoaded() { // mpvSuspend() setFlag(MPVOption.PlaybackControl.pause, true) // Get video size and set the initial window size let width = getInt(MPVProperty.width) let height = getInt(MPVProperty.height) let duration = getDouble(MPVProperty.duration) let pos = getDouble(MPVProperty.timePos) player.info.videoHeight = height player.info.videoWidth = width player.info.displayWidth = 0 player.info.displayHeight = 0 player.info.videoDuration = VideoTime(duration) if let filename = getString(MPVProperty.path) { player.info.cachedVideoDurationAndProgress[filename]?.duration = duration } player.info.videoPosition = VideoTime(pos) player.fileLoaded() fileLoaded = true // mpvResume() if !Preference.bool(for: .pauseWhenOpen) { setFlag(MPVOption.PlaybackControl.pause, false) } player.syncUI(.playlist) } private func onVideoReconfig() { // If loading file, video reconfig can return 0 width and height if player.info.fileLoading { return } var dwidth = getInt(MPVProperty.dwidth) var dheight = getInt(MPVProperty.dheight) if player.info.rotation == 90 || player.info.rotation == 270 { swap(&dwidth, &dheight) } if dwidth != player.info.displayWidth! || dheight != player.info.displayHeight! { // filter the last video-reconfig event before quit if dwidth == 0 && dheight == 0 && getFlag(MPVProperty.coreIdle) { return } // video size changed player.info.displayWidth = dwidth player.info.displayHeight = dheight player.notifyMainWindowVideoSizeChanged() } } // MARK: - Property listeners private func handlePropertyChange(_ name: String, _ property: mpv_event_property) { var needReloadQuickSettingsView = false switch name { case MPVProperty.videoParams: needReloadQuickSettingsView = true onVideoParamsChange(UnsafePointer<mpv_node_list>(OpaquePointer(property.data))) case MPVOption.TrackSelection.vid: player.info.vid = Int(getInt(MPVOption.TrackSelection.vid)) player.postNotification(.iinaVIDChanged) player.sendOSD(.track(player.info.currentTrack(.video) ?? .noneVideoTrack)) case MPVOption.TrackSelection.aid: player.info.aid = Int(getInt(MPVOption.TrackSelection.aid)) DispatchQueue.main.sync { player.mainWindow?.muteButton.isEnabled = (player.info.aid != 0) player.mainWindow?.volumeSlider.isEnabled = (player.info.aid != 0) } player.postNotification(.iinaAIDChanged) player.sendOSD(.track(player.info.currentTrack(.audio) ?? .noneAudioTrack)) case MPVOption.TrackSelection.sid: player.info.sid = Int(getInt(MPVOption.TrackSelection.sid)) player.postNotification(.iinaSIDChanged) player.sendOSD(.track(player.info.currentTrack(.sub) ?? .noneSubTrack)) case MPVOption.Subtitles.secondarySid: player.info.secondSid = Int(getInt(MPVOption.Subtitles.secondarySid)) player.postNotification(.iinaSIDChanged) case MPVOption.PlaybackControl.pause: if let data = UnsafePointer<Bool>(OpaquePointer(property.data))?.pointee { if player.info.isPaused != data { player.sendOSD(data ? .pause : .resume) player.info.isPaused = data } if player.mainWindow.isWindowLoaded { if Preference.bool(for: .alwaysFloatOnTop) { DispatchQueue.main.async { self.player.mainWindow.setWindowFloatingOnTop(!data) } } } } player.syncUI(.playButton) case MPVProperty.chapter: player.syncUI(.time) player.syncUI(.chapterList) player.postNotification(.iinaMediaTitleChanged) case MPVOption.PlaybackControl.speed: needReloadQuickSettingsView = true if let data = UnsafePointer<Double>(OpaquePointer(property.data))?.pointee { player.info.playSpeed = data player.sendOSD(.speed(data)) } case MPVOption.Video.deinterlace: needReloadQuickSettingsView = true if let data = UnsafePointer<Bool>(OpaquePointer(property.data))?.pointee { // this property will fire a change event at file start if player.info.deinterlace != data { player.sendOSD(.deinterlace(data)) player.info.deinterlace = data } } case MPVOption.Audio.mute: player.syncUI(.muteButton) if let data = UnsafePointer<Bool>(OpaquePointer(property.data))?.pointee { player.info.isMuted = data player.sendOSD(data ? OSDMessage.mute : OSDMessage.unMute) } case MPVOption.Audio.volume: if let data = UnsafePointer<Double>(OpaquePointer(property.data))?.pointee { player.info.volume = data player.syncUI(.volume) player.sendOSD(.volume(Int(data))) } case MPVOption.Audio.audioDelay: needReloadQuickSettingsView = true if let data = UnsafePointer<Double>(OpaquePointer(property.data))?.pointee { player.info.audioDelay = data player.sendOSD(.audioDelay(data)) } case MPVOption.Subtitles.subDelay: needReloadQuickSettingsView = true if let data = UnsafePointer<Double>(OpaquePointer(property.data))?.pointee { player.info.subDelay = data player.sendOSD(.subDelay(data)) } case MPVOption.Subtitles.subScale: needReloadQuickSettingsView = true if let data = UnsafePointer<Double>(OpaquePointer(property.data))?.pointee { let displayValue = data >= 1 ? data : -1/data let truncated = round(displayValue * 100) / 100 player.sendOSD(.subScale(truncated)) } case MPVOption.Subtitles.subPos: needReloadQuickSettingsView = true if let data = UnsafePointer<Double>(OpaquePointer(property.data))?.pointee { player.sendOSD(.subPos(data)) } case MPVOption.Equalizer.contrast: needReloadQuickSettingsView = true if let data = UnsafePointer<Int64>(OpaquePointer(property.data))?.pointee { let intData = Int(data) player.info.contrast = intData player.sendOSD(.contrast(intData)) } case MPVOption.Equalizer.hue: needReloadQuickSettingsView = true if let data = UnsafePointer<Int64>(OpaquePointer(property.data))?.pointee { let intData = Int(data) player.info.hue = intData player.sendOSD(.hue(intData)) } case MPVOption.Equalizer.brightness: needReloadQuickSettingsView = true if let data = UnsafePointer<Int64>(OpaquePointer(property.data))?.pointee { let intData = Int(data) player.info.brightness = intData player.sendOSD(.brightness(intData)) } case MPVOption.Equalizer.gamma: needReloadQuickSettingsView = true if let data = UnsafePointer<Int64>(OpaquePointer(property.data))?.pointee { let intData = Int(data) player.info.gamma = intData player.sendOSD(.gamma(intData)) } case MPVOption.Equalizer.saturation: needReloadQuickSettingsView = true if let data = UnsafePointer<Int64>(OpaquePointer(property.data))?.pointee { let intData = Int(data) player.info.saturation = intData player.sendOSD(.saturation(intData)) } // following properties may change before file loaded case MPVProperty.playlistCount: player.postNotification(.iinaPlaylistChanged) case MPVProperty.trackList: player.trackListChanged() player.postNotification(.iinaTracklistChanged) case MPVProperty.vf: needReloadQuickSettingsView = true player.postNotification(.iinaVFChanged) case MPVProperty.af: player.postNotification(.iinaAFChanged) case MPVOption.Window.fullscreen: guard player.mainWindow.isWindowLoaded else { break } let fs = getFlag(MPVOption.Window.fullscreen) if fs != player.mainWindow.fsState.isFullscreen { DispatchQueue.main.async(execute: self.player.mainWindow.toggleWindowFullScreen) } case MPVOption.Window.ontop: guard player.mainWindow.isWindowLoaded else { break } let ontop = getFlag(MPVOption.Window.ontop) if ontop != player.mainWindow.isOntop { DispatchQueue.main.async { self.player.mainWindow.isOntop = ontop self.player.mainWindow.setWindowFloatingOnTop(ontop) } } case MPVOption.Window.windowScale: guard player.mainWindow.isWindowLoaded else { break } let windowScale = getDouble(MPVOption.Window.windowScale) if fabs(windowScale - player.info.cachedWindowScale) > 10e-10 { DispatchQueue.main.async { self.player.mainWindow.setWindowScale(windowScale) } } case MPVProperty.mediaTitle: player.postNotification(.iinaMediaTitleChanged) default: // Utility.log("MPV property changed (unhandled): \(name)") break } if (needReloadQuickSettingsView) { DispatchQueue.main.async { self.player.mainWindow.quickSettingView.reload() } } } // MARK: - User Options private enum UserOptionType { case bool, int, float, string, color, other } private struct OptionObserverInfo { typealias Transformer = (Preference.Key) -> String? var prefKey: Preference.Key var optionName: String var valueType: UserOptionType /** input a pref key and return the option value (as string) */ var transformer: Transformer? init(_ prefKey: Preference.Key, _ optionName: String, _ valueType: UserOptionType, _ transformer: Transformer?) { self.prefKey = prefKey self.optionName = optionName self.valueType = valueType self.transformer = transformer } } private var optionObservers: [String: [OptionObserverInfo]] = [:] private func setUserOption(_ key: Preference.Key, type: UserOptionType, forName name: String, sync: Bool = true, transformer: OptionObserverInfo.Transformer? = nil) { var code: Int32 = 0 let keyRawValue = key.rawValue switch type { case .int: let value = Preference.integer(for: key) var i = Int64(value) code = mpv_set_option(mpv, name, MPV_FORMAT_INT64, &i) case .float: let value = Preference.float(for: key) var d = Double(value) code = mpv_set_option(mpv, name, MPV_FORMAT_DOUBLE, &d) case .bool: let value = Preference.bool(for: key) code = mpv_set_option_string(mpv, name, value ? yes_str : no_str) case .string: let value = Preference.string(for: key) code = mpv_set_option_string(mpv, name, value) case .color: let value = Preference.mpvColor(for: key) code = mpv_set_option_string(mpv, name, value) // Random error here (perhaps a Swift or mpv one), so set it twice // 「没有什么是 set 不了的;如果有,那就 set 两次」 if code < 0 { code = mpv_set_option_string(mpv, name, value) } case .other: guard let tr = transformer else { Logger.log("setUserOption: no transformer!", level: .error) return } if let value = tr(key) { code = mpv_set_option_string(mpv, name, value) } else { code = 0 } } if code < 0 { Utility.showAlert("mpv_error", arguments: [String(cString: mpv_error_string(code)), "\(code)", name]) } if sync { UserDefaults.standard.addObserver(self, forKeyPath: keyRawValue, options: [.new, .old], context: nil) if optionObservers[keyRawValue] == nil { optionObservers[keyRawValue] = [] } optionObservers[keyRawValue]!.append(OptionObserverInfo(key, name, type, transformer)) } } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { guard !(change?[NSKeyValueChangeKey.oldKey] is NSNull) else { return } guard let keyPath = keyPath else { return } guard let infos = optionObservers[keyPath] else { return } for info in infos { switch info.valueType { case .int: let value = Preference.integer(for: info.prefKey) setInt(info.optionName, value) case .float: let value = Preference.float(for: info.prefKey) setDouble(info.optionName, Double(value)) case .bool: let value = Preference.bool(for: info.prefKey) setFlag(info.optionName, value) case .string: if let value = Preference.string(for: info.prefKey) { setString(info.optionName, value) } case .color: if let value = Preference.mpvColor(for: info.prefKey) { setString(info.optionName, value) } case .other: guard let tr = info.transformer else { Logger.log("setUserOption: no transformer!", level: .error) return } if let value = tr(info.prefKey) { setString(info.optionName, value) } } } } // MARK: - Utils /** Utility function for checking mpv api error */ private func chkErr(_ status: Int32!) { guard status < 0 else { return } DispatchQueue.main.async { Logger.fatal("mpv API error: \"\(String(cString: mpv_error_string(status)))\", Return value: \(status!).") } } } fileprivate func mpvGetOpenGLFunc(_ ctx: UnsafeMutableRawPointer?, _ name: UnsafePointer<Int8>?) -> UnsafeMutableRawPointer? { let symbolName: CFString = CFStringCreateWithCString(kCFAllocatorDefault, name, kCFStringEncodingASCII); guard let addr = CFBundleGetFunctionPointerForName(CFBundleGetBundleWithIdentifier(CFStringCreateCopy(kCFAllocatorDefault, "com.apple.opengl" as CFString)), symbolName) else { Logger.fatal("Cannot get OpenGL function pointer!") } return addr } fileprivate func mpvUpdateCallback(_ ctx: UnsafeMutableRawPointer?) { let layer = unsafeBitCast(ctx, to: ViewLayer.self) layer.mpvGLQueue.async { layer.draw() } }
gpl-3.0
7d494f27157b917229b06286b7397b17
35.199816
252
0.679851
3.878552
false
false
false
false
AkkeyLab/STYouTube
STYouTube/ViewController/StoreViewController.swift
1
2268
// // StoreViewController.swift // STYouTube // // Created by AKIO on 2017/07/09. // Copyright © 2017 AKIO. All rights reserved. // import UIKit import UserNotifications class StoreViewController: UIViewController, UNUserNotificationCenterDelegate { var timer: Timer! var request: UNNotificationRequest! override func viewDidLoad() { super.viewDidLoad() let center = UNUserNotificationCenter.current() center.requestAuthorization(options: [.alert, .sound], completionHandler: { (granted, error) in }) center.delegate = self // userNotificationCenter が呼ばれるようにするため createNotification() } // 画面が表示された直後 override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) UNUserNotificationCenter.current().add(request, withCompletionHandler: nil) } func createNotification() { let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false) let content = UNMutableNotificationContent() content.title = "セール実施中!" content.body = "現在、期間限定でセールを実施中です。" content.sound = UNNotificationSound.default() request = UNNotificationRequest(identifier: "normal", content: content, trigger: trigger) } // アプリがフォアグラウンド時に呼ばれる func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { completionHandler([.alert, .sound]) } 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 prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
4825661a215adee819ea4467de057caf
31.378788
129
0.682265
5.137019
false
false
false
false
aidangomez/RandKit
Source/RandomValue.swift
1
2093
// Copyright © 2016 Aidan Gomez. // // This file is part of RandKit. The full RandKit copyright notice, including // terms governing use, modification, and redistribution, is contained in the // file LICENSE at the root of the source code distribution tree. public func random() -> ContinuousValue { return uniform() } public func random(max: Double) -> ContinuousValue { return uniform(max) } public func random(max: Int) -> DiscreteValue { return uniform(max) } public func random(range: Range<Int>) -> ContinuousValue { return uniform(range) } public func random(range: Range<Int>) -> DiscreteValue { return uniform(range) } /// Return `true` with probability `p` public func random(probability p: ContinuousValue) -> Bool { return bernoulli(probability: p) } /// Generate `sample` random values within range `inRange` public func random(sample count: Int, inRange range: Range<Int>, withReplacement replacement: Bool = false) -> [DiscreteValue] { if replacement { let values: [DiscreteValue] = (0..<count).map({ _ in uniform(range) }) return values } else { precondition(count <= range.count) var values = [DiscreteValue]() while values.count < count { let value: DiscreteValue = uniform(range) if values.contains(value) { continue } else { values.append(value) } } return values } } public func random(sample count: Int, inRange range: Range<Int>, withReplacement replacement: Bool = false) -> [ContinuousValue] { if replacement { let values: [ContinuousValue] = (0..<count).map({ _ in uniform(range) }) return values } else { precondition(count <= range.count) var values = [ContinuousValue]() while values.count < count { let value: ContinuousValue = uniform(range) if values.contains(value) { continue } else { values.append(value) } } return values } }
mit
5fb9f41fa10d2a88282c8a98548b6f38
28.885714
130
0.619503
4.260692
false
false
false
false
diwu/LeetCode-Solutions-in-Swift
Solutions/Solutions/Medium/Medium_043_Multiply_Strings.swift
1
1559
/* https://leetcode.com/problems/multiply-strings/ #43 Multiply Strings Level: medium Given two numbers represented as strings, return multiplication of the numbers as a string. Note: The numbers can be arbitrarily large and are non-negative. Inspired by @ChiangKaiShrek at https://leetcode.com/discuss/26602/brief-c-solution-using-only-strings-and-without-reversal */ import Foundation private extension String { subscript (index: Int) -> Character { return self[self.index(self.startIndex, offsetBy: index)] } } struct Medium_043_Multiply_Strings { static func multiply(num1: String, num2: String) -> String { var sum = Array<Character>(repeating: "0", count: num1.count+num2.count) let dict: [Character: Int] = [ "0": 0, "1": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9, ] for i in (0 ... num1.count - 1).reversed() { var carry = 0 for j in (0 ... num2.count - 1).reversed() { let tmp: Int = dict[sum[i + j + 1]]! + dict[num1[i]]! * dict[num2[j]]! + carry; sum[i + j + 1] = Character("\(tmp % 10)") carry = tmp / 10; } sum[i] = Character("\(dict[sum[i]]! + carry)") } for i in (0 ... sum.count - 1).reversed() { if sum[i] != "0" { return String(sum[0...i]) } } return "0" } }
mit
7e95d4f507924f69bebd0c5de735bd76
26.839286
122
0.503528
3.535147
false
false
false
false
Sephiroth87/C-swifty4
Common/ScaleFilter.swift
1
1738
// // ScaleFilter.swift // C-swifty4 Mac // // Created by Fabio on 16/11/2017. // Copyright © 2017 orange in a day. All rights reserved. // import MetalKit // Simple 2x texture scaler // TODO: Maybe implement other scaling factors if the drawing surface is closer to one of them (less blur when scaling) class ScaleFilter { internal let texture: MTLTexture private let kernel: MTLComputePipelineState private let threadGroupSize = MTLSizeMake(16, 16, 1) private let threadGroupCount = MTLSizeMake(64, 64, 1) init(device: MTLDevice, library: MTLLibrary, usesMtlBuffer: Bool) { let textureDescriptor = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: .rgba8Unorm, width: 1024, height: 1024, mipmapped: false) textureDescriptor.usage = [.shaderRead, .shaderWrite] if usesMtlBuffer, #available(OSX 10.13, iOS 8.0, tvOS 9.0, *) { let buffer = device.makeBuffer(length: 1024 * 1024 * 4, options: [])! texture = buffer.makeTexture(descriptor: textureDescriptor, offset: 0, bytesPerRow: 1024 * 4)! } else { texture = device.makeTexture(descriptor: textureDescriptor)! } let function = library.makeFunction(name: "scale")! kernel = try! device.makeComputePipelineState(function: function) } func apply(to: MTLTexture, with commandBuffer: MTLCommandBuffer) { let encoder = commandBuffer.makeComputeCommandEncoder() encoder?.setComputePipelineState(kernel) encoder?.setTexture(to, index: 0) encoder?.setTexture(texture, index: 1) encoder?.dispatchThreadgroups(threadGroupCount, threadsPerThreadgroup: threadGroupSize) encoder?.endEncoding() } }
mit
217ab5cce6f810490ce2e2ff1db58bd5
40.357143
143
0.690271
4.535248
false
false
false
false
brentsimmons/Evergreen
Shared/Tree/WebFeedTreeControllerDelegate.swift
1
4180
// // SidebarTreeControllerDelegate.swift // NetNewsWire // // Created by Brent Simmons on 7/24/16. // Copyright © 2016 Ranchero Software, LLC. All rights reserved. // import Foundation import RSTree import Articles import Account final class WebFeedTreeControllerDelegate: TreeControllerDelegate { private var filterExceptions = Set<FeedIdentifier>() var isReadFiltered = false func addFilterException(_ feedID: FeedIdentifier) { filterExceptions.insert(feedID) } func resetFilterExceptions() { filterExceptions = Set<FeedIdentifier>() } func treeController(treeController: TreeController, childNodesFor node: Node) -> [Node]? { if node.isRoot { return childNodesForRootNode(node) } if node.representedObject is Container { return childNodesForContainerNode(node) } if node.representedObject is SmartFeedsController { return childNodesForSmartFeeds(node) } return nil } } private extension WebFeedTreeControllerDelegate { func childNodesForRootNode(_ rootNode: Node) -> [Node]? { var topLevelNodes = [Node]() let smartFeedsNode = rootNode.existingOrNewChildNode(with: SmartFeedsController.shared) smartFeedsNode.canHaveChildNodes = true smartFeedsNode.isGroupItem = true topLevelNodes.append(smartFeedsNode) topLevelNodes.append(contentsOf: sortedAccountNodes(rootNode)) return topLevelNodes } func childNodesForSmartFeeds(_ parentNode: Node) -> [Node] { return SmartFeedsController.shared.smartFeeds.compactMap { (feed) -> Node? in // All Smart Feeds should remain visible despite the Hide Read Feeds setting return parentNode.existingOrNewChildNode(with: feed as AnyObject) } } func childNodesForContainerNode(_ containerNode: Node) -> [Node]? { let container = containerNode.representedObject as! Container var children = [AnyObject]() for webFeed in container.topLevelWebFeeds { if let feedID = webFeed.feedID, !(!filterExceptions.contains(feedID) && isReadFiltered && webFeed.unreadCount == 0) { children.append(webFeed) } } if let folders = container.folders { for folder in folders { if let feedID = folder.feedID, !(!filterExceptions.contains(feedID) && isReadFiltered && folder.unreadCount == 0) { children.append(folder) } } } var updatedChildNodes = [Node]() children.forEach { (representedObject) in if let existingNode = containerNode.childNodeRepresentingObject(representedObject) { if !updatedChildNodes.contains(existingNode) { updatedChildNodes += [existingNode] return } } if let newNode = self.createNode(representedObject: representedObject, parent: containerNode) { updatedChildNodes += [newNode] } } return updatedChildNodes.sortedAlphabeticallyWithFoldersAtEnd() } func createNode(representedObject: Any, parent: Node) -> Node? { if let webFeed = representedObject as? WebFeed { return createNode(webFeed: webFeed, parent: parent) } if let folder = representedObject as? Folder { return createNode(folder: folder, parent: parent) } if let account = representedObject as? Account { return createNode(account: account, parent: parent) } return nil } func createNode(webFeed: WebFeed, parent: Node) -> Node { return parent.createChildNode(webFeed) } func createNode(folder: Folder, parent: Node) -> Node { let node = parent.createChildNode(folder) node.canHaveChildNodes = true return node } func createNode(account: Account, parent: Node) -> Node { let node = parent.createChildNode(account) node.canHaveChildNodes = true node.isGroupItem = true return node } func sortedAccountNodes(_ parent: Node) -> [Node] { let nodes = AccountManager.shared.sortedActiveAccounts.compactMap { (account) -> Node? in let accountNode = parent.existingOrNewChildNode(with: account) accountNode.canHaveChildNodes = true accountNode.isGroupItem = true return accountNode } return nodes } func nodeInArrayRepresentingObject(_ nodes: [Node], _ representedObject: AnyObject) -> Node? { for oneNode in nodes { if oneNode.representedObject === representedObject { return oneNode } } return nil } }
mit
c3770d8a23449f3fea99b993a4c8b539
26.313725
120
0.736779
3.891061
false
false
false
false
brentsimmons/Evergreen
Account/Sources/Account/FeedProvider/Twitter/TwitterUser.swift
1
964
// // TwitterUser.swift // Account // // Created by Maurice Parker on 4/16/20. // Copyright © 2020 Ranchero Software, LLC. All rights reserved. // import Foundation struct TwitterUser: Codable { let name: String? let screenName: String? let avatarURL: String? enum CodingKeys: String, CodingKey { case name = "name" case screenName = "screen_name" case avatarURL = "profile_image_url_https" } var url: String { return "https://twitter.com/\(screenName ?? "")" } func renderAsHTML() -> String? { var html = String() html += "<div><a href=\"\(url)\">" if let avatarURL = avatarURL { html += "<img class=\"twitterAvatar nnw-nozoom\" src=\"\(avatarURL)\">" } html += "<div class=\"twitterUsername\">" if let name = name { html += " \(name)" } html += "<br><span class=\"twitterScreenName\">" if let screenName = screenName { html += " @\(screenName)" } html += "</span></div></a></div>" return html } }
mit
65008b25714c67e663b2b3b21d032598
20.4
74
0.617861
3.297945
false
false
false
false
tylerbrockett/cse394-principles-of-mobile-applications
hw-2/hw-2/hw-2/AppDelegate.swift
1
7517
/* * @author Tyler Brockett mailto:[email protected] * @course ASU CSE 394 * @project Homework 2 * @version February 25, 2016 * @project-description Combines photo handling and database/coredata operations to store places the user has visited. * @class-name AppDelegate.swift * @class-description Handles lifecycle events of the application * * The MIT License (MIT) * * Copyright (c) 2016 Tyler Brockett * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "edu.asu.bscs.tkbrocke.lab_4" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("hw_2", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
mit
078111b983c4990911bb833f71e5abe7
54.681481
291
0.722895
5.588848
false
false
false
false
SwiftStudies/Duration
Sources/Duration/Duration.swift
1
6693
// // Copyright 2016 Swift Studies // // 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 /// Definition of a block that can be used for measurements public typealias MeasuredBlock = ()->() private var depth = 0 private var depthIndent : String { return String(repeating: "\t", count: depth) } private var now : Double { return Date().timeIntervalSinceReferenceDate } /// Define different styles of reporting public enum MeasurementLogStyle{ /// Don't measure anything case none /// Log results of measurements to the console case print } /// Provides static methods for performing measurements public class Duration{ private static var timingStack = [(startTime:Double,name:String,reported:Bool)]() private static var logStyleStack = [MeasurementLogStyle]() /// When you are releasing and want to turn off logging, and your library /// may be used by another, it is better to push/pop a logging state. This /// will ensure your settings do not impact those of other modules. By pushing /// your desired log style, and sub-sequently pop'ing before returning from /// your measured method only your desired measuremets will be logged. public static func pushLogStyle(style: MeasurementLogStyle) { logStyleStack.append(logStyle) logStyle = style } /// Pops the last pushed logging style and restores the logging style to /// its previous style public static func popLogStyle(){ logStyle = logStyleStack.removeLast() } /// Set to control how measurements are reported. It is recommended to use /// `pushLogStyle` and `popLogStyle` if you intend to make your module /// available for others to use public static var logStyle = MeasurementLogStyle.print /// Ensures that if any parent measurement boundaries have not yet resulted /// in output that their headers are displayed private static func reportContaining() { if depth > 0 && logStyle == .print { for stackPointer in 0..<timingStack.count { let containingMeasurement = timingStack[stackPointer] if !containingMeasurement.reported { print(String(repeating: "\t" + "Measuring \(containingMeasurement.name):", count: stackPointer)) timingStack[stackPointer] = (containingMeasurement.startTime,containingMeasurement.name,true) } } } } /// Start a measurement, call `stopMeasurement` when you have completed your /// desired operations. The `name` will be used to identify this specific /// measurement. Multiple calls will nest measurements within each other. public static func startMeasurement(_ name: String) { reportContaining() timingStack.append((now,name,false)) depth += 1 } /// Stops measuring and generates a log entry. Note if you wish to include /// additional information (for example, the number of items processed) then /// you can use the `stopMeasurement(executionDetails:String?)` version of /// the function. public static func stopMeasurement() -> Double { return stopMeasurement(nil) } /// Prints a message, optionally with a time stamp (measured from the /// start of the current measurement. public static func log(message:String, includeTimeStamp:Bool = false) { reportContaining() if includeTimeStamp{ let currentTime = now let timeStamp = currentTime - timingStack[timingStack.count-1].startTime return print("\(depthIndent)\(message) \(timeStamp.milliSeconds)ms") } else { return print("\(depthIndent)\(message)") } } /// Stop measuring operations and generate log entry. public static func stopMeasurement(_ executionDetails: String?) -> Double { let endTime = now precondition(depth > 0, "Attempt to stop a measurement when none has been started") let beginning = timingStack.removeLast() depth -= 1 let took = endTime - beginning.startTime if logStyle == .print { print("\(depthIndent)\(beginning.name) took: \(took.milliSeconds)" + (executionDetails == nil ? "" : " (\(executionDetails!))")) } return took } /// /// Calls a particular block measuring the time taken to complete the block. /// public static func measure(_ name: String, block: MeasuredBlock) -> Double { startMeasurement(name) block() return stopMeasurement() } /// /// Calls a particular block the specified number of times, returning the average /// number of seconds it took to complete the code. The time /// take for each iteration will be logged as well as the average time and /// standard deviation. public static func measure(name: String, iterations: Int = 10, forBlock block: MeasuredBlock) -> [String: Double] { precondition(iterations > 0, "Iterations must be a positive integer") var data: [String: Double] = [:] var total : Double = 0 var samples = [Double]() if logStyle == .print { print("\(depthIndent)Measuring \(name)") } for i in 0..<iterations{ let took = measure("Iteration \(i+1)",block: block) samples.append(took) total += took data["\(i+1)"] = took } let mean = total / Double(iterations) var deviation = 0.0 for result in samples { let difference = result - mean deviation += difference*difference } let variance = deviation / Double(iterations) data["average"] = mean data["stddev"] = variance if logStyle == .print { print("\(depthIndent)\(name) Average", mean.milliSeconds) print("\(depthIndent)\(name) STD Dev.", variance.milliSeconds) } return data } } private extension Double{ var milliSeconds : String { return String(format: "%03.2fms", self*1000) } }
apache-2.0
3f8b016dec66911e84df40b8c41a348b
32.298507
140
0.646945
4.885401
false
false
false
false
barteljan/VISPER
VISPER/Classes/Bridge/Bridge-Presenter.swift
2
1026
// // Bridge-Presenter.swift // VISPER-Presenter // // Created by bartel on 06.01.18. // import Foundation import VISPER_Presenter public typealias FunctionalControllerPresenter = VISPER_Presenter.FunctionalControllerPresenter public typealias FunctionalPresenter = VISPER_Presenter.FunctionalPresenter public typealias LifecycleEvent = VISPER_Presenter.LifecycleEvent public typealias LoadViewEvent = VISPER_Presenter.LoadViewEvent public typealias ViewDidLoadEvent = VISPER_Presenter.ViewDidLoadEvent public typealias ViewWillAppearEvent = VISPER_Presenter.ViewWillAppearEvent public typealias ViewDidAppearEvent = VISPER_Presenter.ViewDidAppearEvent public typealias ViewWillDisappearEvent = VISPER_Presenter.ViewWillDisappearEvent public typealias ViewDidDisappearEvent = VISPER_Presenter.ViewDidDisappearEvent public typealias ViewControllerEventPresenter = VISPER_Presenter.ViewControllerEventPresenter public typealias ViewControllerLifecycleEventPresenter = VISPER_Presenter.ViewControllerLifecycleEventPresenter
mit
ca18ed21e369578230799276c6a158a9
47.857143
111
0.874269
5.486631
false
false
false
false
atrick/swift
stdlib/public/core/StringGuts.swift
1
15634
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftShims // // StringGuts is a parameterization over String's representations. It provides // functionality and guidance for efficiently working with Strings. // @frozen public // SPI(corelibs-foundation) struct _StringGuts: @unchecked Sendable { @usableFromInline internal var _object: _StringObject @inlinable @inline(__always) internal init(_ object: _StringObject) { self._object = object _invariantCheck() } // Empty string @inlinable @inline(__always) init() { self.init(_StringObject(empty: ())) } } // Raw extension _StringGuts { @inlinable @inline(__always) internal var rawBits: _StringObject.RawBitPattern { return _object.rawBits } } // Creation extension _StringGuts { @inlinable @inline(__always) internal init(_ smol: _SmallString) { self.init(_StringObject(smol)) } @inlinable @inline(__always) internal init(_ bufPtr: UnsafeBufferPointer<UInt8>, isASCII: Bool) { self.init(_StringObject(immortal: bufPtr, isASCII: isASCII)) } @inline(__always) internal init(_ storage: __StringStorage) { self.init(_StringObject(storage)) } internal init(_ storage: __SharedStringStorage) { self.init(_StringObject(storage)) } internal init( cocoa: AnyObject, providesFastUTF8: Bool, isASCII: Bool, length: Int ) { self.init(_StringObject( cocoa: cocoa, providesFastUTF8: providesFastUTF8, isASCII: isASCII, length: length)) } } // Queries extension _StringGuts { // The number of code units @inlinable @inline(__always) internal var count: Int { return _object.count } @inlinable @inline(__always) internal var isEmpty: Bool { return count == 0 } @inlinable @inline(__always) internal var isSmall: Bool { return _object.isSmall } @inline(__always) internal var isSmallASCII: Bool { return _object.isSmall && _object.smallIsASCII } @inlinable @inline(__always) internal var asSmall: _SmallString { return _SmallString(_object) } @inlinable @inline(__always) internal var isASCII: Bool { return _object.isASCII } @inlinable @inline(__always) internal var isFastASCII: Bool { return isFastUTF8 && _object.isASCII } @inline(__always) internal var isNFC: Bool { return _object.isNFC } @inline(__always) internal var isNFCFastUTF8: Bool { // TODO(String micro-performance): Consider a dedicated bit for this return _object.isNFC && isFastUTF8 } internal var hasNativeStorage: Bool { return _object.hasNativeStorage } internal var hasSharedStorage: Bool { return _object.hasSharedStorage } // Whether this string has breadcrumbs internal var hasBreadcrumbs: Bool { return hasSharedStorage || (hasNativeStorage && _object.nativeStorage.hasBreadcrumbs) } } // extension _StringGuts { // Whether we can provide fast access to contiguous UTF-8 code units @_transparent @inlinable internal var isFastUTF8: Bool { return _fastPath(_object.providesFastUTF8) } // A String which does not provide fast access to contiguous UTF-8 code units @inlinable @inline(__always) internal var isForeign: Bool { return _slowPath(_object.isForeign) } @inlinable @inline(__always) internal func withFastUTF8<R>( _ f: (UnsafeBufferPointer<UInt8>) throws -> R ) rethrows -> R { _internalInvariant(isFastUTF8) if self.isSmall { return try _SmallString(_object).withUTF8(f) } defer { _fixLifetime(self) } return try f(_object.fastUTF8) } @inlinable @inline(__always) internal func withFastUTF8<R>( range: Range<Int>, _ f: (UnsafeBufferPointer<UInt8>) throws -> R ) rethrows -> R { return try self.withFastUTF8 { wholeUTF8 in return try f(UnsafeBufferPointer(rebasing: wholeUTF8[range])) } } @inlinable @inline(__always) internal func withFastCChar<R>( _ f: (UnsafeBufferPointer<CChar>) throws -> R ) rethrows -> R { return try self.withFastUTF8 { utf8 in return try utf8.withMemoryRebound(to: CChar.self, f) } } } // Internal invariants extension _StringGuts { #if !INTERNAL_CHECKS_ENABLED @inlinable @inline(__always) internal func _invariantCheck() {} #else @usableFromInline @inline(never) @_effects(releasenone) internal func _invariantCheck() { #if arch(i386) || arch(arm) || arch(arm64_32) || arch(wasm32) _internalInvariant(MemoryLayout<String>.size == 12, """ the runtime is depending on this, update Reflection.mm and \ this if you change it """) #else _internalInvariant(MemoryLayout<String>.size == 16, """ the runtime is depending on this, update Reflection.mm and \ this if you change it """) #endif } #endif // INTERNAL_CHECKS_ENABLED internal func _dump() { _object._dump() } } // C String interop extension _StringGuts { @inlinable @inline(__always) // fast-path: already C-string compatible internal func withCString<Result>( _ body: (UnsafePointer<Int8>) throws -> Result ) rethrows -> Result { if _slowPath(!_object.isFastZeroTerminated) { return try _slowWithCString(body) } return try self.withFastCChar { return try body($0.baseAddress._unsafelyUnwrappedUnchecked) } } @inline(never) // slow-path @usableFromInline internal func _slowWithCString<Result>( _ body: (UnsafePointer<Int8>) throws -> Result ) rethrows -> Result { _internalInvariant(!_object.isFastZeroTerminated) return try String(self).utf8CString.withUnsafeBufferPointer { let ptr = $0.baseAddress._unsafelyUnwrappedUnchecked return try body(ptr) } } } extension _StringGuts { // Copy UTF-8 contents. Returns number written or nil if not enough space. // Contents of the buffer are unspecified if nil is returned. @inlinable internal func copyUTF8(into mbp: UnsafeMutableBufferPointer<UInt8>) -> Int? { let ptr = mbp.baseAddress._unsafelyUnwrappedUnchecked if _fastPath(self.isFastUTF8) { return self.withFastUTF8 { utf8 in guard utf8.count <= mbp.count else { return nil } let utf8Start = utf8.baseAddress._unsafelyUnwrappedUnchecked ptr.initialize(from: utf8Start, count: utf8.count) return utf8.count } } return _foreignCopyUTF8(into: mbp) } @_effects(releasenone) @usableFromInline @inline(never) // slow-path internal func _foreignCopyUTF8( into mbp: UnsafeMutableBufferPointer<UInt8> ) -> Int? { #if _runtime(_ObjC) // Currently, foreign means NSString if let res = _cocoaStringCopyUTF8(_object.cocoaObject, into: UnsafeMutableRawBufferPointer(start: mbp.baseAddress, count: mbp.count)) { return res } // If the NSString contains invalid UTF8 (e.g. unpaired surrogates), we // can get nil from cocoaStringCopyUTF8 in situations where a character by // character loop would get something more useful like repaired contents var ptr = mbp.baseAddress._unsafelyUnwrappedUnchecked var numWritten = 0 for cu in String(self).utf8 { guard numWritten < mbp.count else { return nil } ptr.initialize(to: cu) ptr += 1 numWritten += 1 } return numWritten #else fatalError("No foreign strings on Linux in this version of Swift") #endif } @inline(__always) internal var utf8Count: Int { if _fastPath(self.isFastUTF8) { return count } return String(self).utf8.count } } // Index extension _StringGuts { @usableFromInline internal typealias Index = String.Index @inlinable @inline(__always) internal var startIndex: String.Index { // The start index is always `Character` aligned. Index(_encodedOffset: 0)._characterAligned._encodingIndependent } @inlinable @inline(__always) internal var endIndex: String.Index { // The end index is always `Character` aligned. markEncoding(Index(_encodedOffset: self.count)._characterAligned) } } // Encoding extension _StringGuts { /// Returns whether this string has a UTF-8 storage representation. /// If this returns false, then the string is encoded in UTF-16. /// /// This always returns a value corresponding to the string's actual encoding. @_alwaysEmitIntoClient @inline(__always) internal var isUTF8: Bool { _object.isUTF8 } @_alwaysEmitIntoClient // Swift 5.7 @inline(__always) internal func markEncoding(_ i: String.Index) -> String.Index { isUTF8 ? i._knownUTF8 : i._knownUTF16 } /// Returns true if the encoding of the given index isn't known to be in /// conflict with this string's encoding. /// /// If the index was created by code that was built on a stdlib below 5.7, /// then this check may incorrectly return true on a mismatching index, but it /// is guaranteed to never incorrectly return false. If all loaded binaries /// were built in 5.7+, then this method is guaranteed to always return the /// correct value. @_alwaysEmitIntoClient @inline(__always) internal func hasMatchingEncoding(_ i: String.Index) -> Bool { i._hasMatchingEncoding(isUTF8: isUTF8) } /// Return an index whose encoding can be assumed to match that of `self`, /// trapping if `i` has an incompatible encoding. /// /// If `i` is UTF-8 encoded, but `self` is an UTF-16 string, then trap. /// /// If `i` is UTF-16 encoded, but `self` is an UTF-8 string, then transcode /// `i`'s offset to UTF-8 and return the resulting index. This allows the use /// of indices from a bridged Cocoa string after the string has been converted /// to a native Swift string. (Such indices are technically still considered /// invalid, but we allow this specific case to keep compatibility with /// existing code that assumes otherwise.) /// /// Detecting an encoding mismatch isn't always possible -- older binaries did /// not set the flags that this method relies on. However, false positives /// cannot happen: if this method detects a mismatch, then it is guaranteed to /// be a real one. @_alwaysEmitIntoClient @inline(__always) internal func ensureMatchingEncoding(_ i: Index) -> Index { if _fastPath(hasMatchingEncoding(i)) { return i } if let i = _slowEnsureMatchingEncoding(i) { return i } // Note that this trap is not guaranteed to trigger when the process // includes client binaries compiled with a previous Swift release. // (`i._canBeUTF16` can sometimes return true in that case even if the index // actually came from an UTF-8 string.) However, the trap will still often // trigger in this case, as long as the index was initialized by code that // was compiled with 5.7+. // // This trap will rarely if ever trigger on OSes that have stdlibs <= 5.6, // because those versions never set the `isKnownUTF16` flag in // `_StringObject`. (The flag may still be set within inlinable code, // though.) _preconditionFailure("Invalid string index") } /// Return an index that corresponds to the same position as `i`, but whose /// encoding can be assumed to match that of `self`, returning `nil` if `i` /// has incompatible encoding. /// /// If `i` is UTF-8 encoded, but `self` is an UTF-16 string, then return nil. /// /// If `i` is UTF-16 encoded, but `self` is an UTF-8 string, then transcode /// `i`'s offset to UTF-8 and return the resulting index. This allows the use /// of indices from a bridged Cocoa string after the string has been converted /// to a native Swift string. (Such indices are technically still considered /// invalid, but we allow this specific case to keep compatibility with /// existing code that assumes otherwise.) /// /// Detecting an encoding mismatch isn't always possible -- older binaries did /// not set the flags that this method relies on. However, false positives /// cannot happen: if this method detects a mismatch, then it is guaranteed to /// be a real one. internal func ensureMatchingEncodingNoTrap(_ i: Index) -> Index? { if hasMatchingEncoding(i) { return i } return _slowEnsureMatchingEncoding(i) } @_alwaysEmitIntoClient @inline(never) @_effects(releasenone) internal func _slowEnsureMatchingEncoding(_ i: Index) -> Index? { guard isUTF8 else { // Attempt to use an UTF-8 index on a UTF-16 string. Strings don't usually // get converted to UTF-16 storage, so it seems okay to reject this case // -- the index most likely comes from an unrelated string. (This may // still turn out to affect binary compatibility with broken code in // existing binaries running with new stdlibs. If so, we can replace this // with the same transcoding hack as in the UTF-16->8 case below.) return nil } // Attempt to use an UTF-16 index on a UTF-8 string. // // This can happen if `self` was originally verbatim-bridged, and someone // mistakenly attempts to keep using an old index after a mutation. This is // technically an error, but trapping here would trigger a lot of broken // code that previously happened to work "fine" on e.g. ASCII strings. // Instead, attempt to convert the offset to UTF-8 code units by transcoding // the string. This can be slow, but it often results in a usable index, // even if non-ASCII characters are present. (UTF-16 breadcrumbs help reduce // the severity of the slowdown.) // FIXME: Consider emitting a runtime warning here. // FIXME: Consider performing a linked-on-or-after check & trapping if the // client executable was built on some particular future Swift release. let utf16 = String.UTF16View(self) var r = utf16.index(utf16.startIndex, offsetBy: i._encodedOffset) if i.transcodedOffset != 0 { r = r.encoded(offsetBy: i.transcodedOffset) } else { // Preserve alignment bits if possible. r = r._copyingAlignment(from: i) } return r._knownUTF8 } } // Old SPI(corelibs-foundation) extension _StringGuts { @available(*, deprecated) public // SPI(corelibs-foundation) var _isContiguousASCII: Bool { return !isSmall && isFastUTF8 && isASCII } @available(*, deprecated) public // SPI(corelibs-foundation) var _isContiguousUTF16: Bool { return false } // FIXME: Remove. Still used by swift-corelibs-foundation @available(*, deprecated) public var startASCII: UnsafeMutablePointer<UInt8> { return UnsafeMutablePointer(mutating: _object.fastUTF8.baseAddress!) } // FIXME: Remove. Still used by swift-corelibs-foundation @available(*, deprecated) public var startUTF16: UnsafeMutablePointer<UTF16.CodeUnit> { fatalError("Not contiguous UTF-16") } } @available(*, deprecated) public // SPI(corelibs-foundation) func _persistCString(_ p: UnsafePointer<CChar>?) -> [CChar]? { guard let s = p else { return nil } let bytesToCopy = UTF8._nullCodeUnitOffset(in: s) + 1 // +1 for the terminating NUL let result = [CChar](unsafeUninitializedCapacity: bytesToCopy) { buf, initedCount in buf.baseAddress!.assign(from: s, count: bytesToCopy) initedCount = bytesToCopy } return result }
apache-2.0
ca2cfae5f73c44acd38ac93ac13fa6a5
32.693966
86
0.685365
4.242605
false
false
false
false
oddevan/macguffin
macguffin/Team.swift
1
491
// // Team.swift // macguffin // // Created by Evan Hildreth on 2/17/15. // Copyright (c) 2015 Evan Hildreth. All rights reserved. // class Team { var active: [Character] = [] var bench: [Character] = [] var inventory: [ItemQuantity] = [] func enroll(_ newbie: Character) { if active.count >= Utility.Team.MaxActiveCharacters { bench.append(newbie) } else { active.append(newbie) } newbie.team = self } }
apache-2.0
249e6a99a5a505aed3a267b7f5afe7eb
21.318182
61
0.566191
3.48227
false
false
false
false
emericspiroux/Open42
correct42/views/Table Cells/Friend/FriendTableViewCell.swift
1
5591
// // FriendTableViewCell.swift // Open42 // // Created by larry on 09/07/2016. // Copyright © 2016 42. All rights reserved. // import UIKit import MessageUI class FriendTableViewCell: UITableViewCell { // MARK: - Proprieties /// Friends diplayed inside the cell var cellFriendOpt:Friend? /// View use to present message view controller or Alerts. var viewOpt:FriendViewController? // MARK: - IBOutlets /// Login or Surname of the `cellFriendOpt` @IBOutlet weak var loginOrSurnameLabel: UILabel! /// Location of the `cellFriendOpt` @IBOutlet weak var locationLabel: UILabel! /// Image of the `cellFriendOpt` @IBOutlet weak var imageFriendView: UIImageView! /// Phone button @IBOutlet weak var PhoneButton: UIButton! /// Phone Activity indicator @IBOutlet weak var phoneActivityIndicator: UIActivityIndicatorView! /// Message button @IBOutlet weak var MessageButton: UIButton! /// Message Activity indicator @IBOutlet weak var messageActivityIndicator: UIActivityIndicatorView! // MARK: - IBActions /// Call the friend if the number are available and well formated. @IBAction func callAction(sender: UIButton) { if let phoneNumber = formatPhoneNumber() { if let phoneNumberURL = NSURL(string: "tel://\(phoneNumber)"){ UIApplication.sharedApplication().openURL(phoneNumberURL) } } else { if let view = viewOpt { showAlertWithTitle("Friends", message: NSLocalizedString("invalidPhoneFormat", comment: "invalid format of the number phone"), view: view) } } dispatch_async(dispatch_get_main_queue()){ self.phoneActivityIndicator.stopAnimating() self.PhoneButton.hidden = false } } /// Display messenger to send sms if the number are available and well formated @IBAction func smsAction(sender: UIButton) { if let phoneNumber = formatPhoneNumber(), let view = viewOpt { let messageVC = MFMessageComposeViewController() if MFMessageComposeViewController.canSendText() { messageVC.body = ""; messageVC.recipients = [phoneNumber] messageVC.messageComposeDelegate = view; view.presentViewController(messageVC, animated: true, completion: nil) } } else { if let view = viewOpt { showAlertWithTitle("Friends", message: NSLocalizedString("invalidPhoneFormat", comment: "invalid format of the number phone"), view: view) } } dispatch_async(dispatch_get_main_queue()){ self.messageActivityIndicator.stopAnimating() self.MessageButton.hidden = false } } @IBAction func buttonAnimationActionTouchDown(sender: UIButton) { sender.hidden = true if sender.currentImage == PhoneButton.currentImage { phoneActivityIndicator.startAnimating() } else if sender.currentImage == MessageButton.currentImage { messageActivityIndicator.startAnimating() } } @IBAction func buttonAnimationActionTouchUpOutside(sender: UIButton) { sender.hidden = false if sender.currentImage == PhoneButton.currentImage { phoneActivityIndicator.stopAnimating() } else if sender.currentImage == MessageButton.currentImage { messageActivityIndicator.stopAnimating() } } // MARK: - Cell life cycle /// Init radius corner of the `imageFriendView` override func awakeFromNib() { super.awakeFromNib() // Initialization code initImageButton() } // MARK: - Methods /// Fill the cell, keep friend inside `cellFirendOpt` and view into `viewOpt`. func fill(friend:Friend, view:FriendViewController){ cellFriendOpt = friend viewOpt = view if let cellFriend = cellFriendOpt { if let surname = cellFriend.surname { loginOrSurnameLabel.text = surname } else { loginOrSurnameLabel.text = cellFriend.login } if cellFriend.location != nil && cellFriend.location != "" { locationLabel.text = cellFriend.location } else { locationLabel.text = NSLocalizedString("NoLocation", comment: "Displayed when user has no location on school") } if let imageUrl = cellFriend.imageUrl { ApiRequester.Shared().downloadImage(imageUrl, success: { (image) in self.imageFriendView.image = image }){ (error) in self.imageFriendView.image = nil print("Impossible to fetch image for \(cellFriend.login).") } } } } // MARK: - Private methods /// Check and format phone number. private func formatPhoneNumber() -> String?{ if var phoneNumber = cellFriendOpt?.phoneNumber where cellFriendOpt?.phoneNumber != "" { phoneNumber = phoneNumber.stringByReplacingOccurrencesOfString("(", withString: "") phoneNumber = phoneNumber.stringByReplacingOccurrencesOfString(")", withString: "") phoneNumber = phoneNumber.stringByReplacingOccurrencesOfString("-", withString: "") phoneNumber = phoneNumber.stringByReplacingOccurrencesOfString(".", withString: "") phoneNumber = phoneNumber.stringByReplacingOccurrencesOfString(" ", withString: "") return phoneNumber } return nil } // Init image rounded design and color of button's image private func initImageButton(){ imageFriendView.layer.cornerRadius = imageFriendView.frame.size.width / 2; imageFriendView.clipsToBounds = true; PhoneButton.layer.cornerRadius = imageFriendView.frame.size.width / 2; PhoneButton.clipsToBounds = true; if let phoneImg = PhoneButton.currentImage { PhoneButton.setImage(phoneImg.imageWithColor(Theme.primary.color).imageWithRenderingMode(.AlwaysOriginal), forState: .Normal) } if let messageImg = MessageButton.currentImage { MessageButton.setImage(messageImg.imageWithColor(Theme.accent.color).imageWithRenderingMode(.AlwaysOriginal), forState: .Normal) } } }
apache-2.0
fcaa402a631e54f4f8f69c2ac4ad17eb
33.506173
142
0.736673
4.193548
false
false
false
false
steelwheels/Coconut
CoconutData/Source/Graphics/CNBezierPath.swift
1
1062
/** * @file CNBezierPath.swift * @brief Extend BezierPath class * @par Copyright * Copyright (C) 2021 Steel Wheels Project */ #if os(OSX) import AppKit #else import UIKit #endif import Foundation #if os(OSX) public typealias CNBezierPath = NSBezierPath #else public typealias CNBezierPath = UIBezierPath #endif public extension CNBezierPath { #if os(OSX) func addLine(to pt: CGPoint) { self.line(to: pt) } #else func appendRect(_ rt: CGRect){ let x0 = rt.origin.x let y0 = rt.origin.y let x1 = x0 + rt.size.width let y1 = y0 + rt.size.height self.move(to: CGPoint(x: x0, y: y0)) self.addLine(to: CGPoint(x: x1, y: y0)) self.addLine(to: CGPoint(x: x1, y: y1)) self.addLine(to: CGPoint(x: x0, y: y1)) self.addLine(to: CGPoint(x: x0, y: y0)) } func appendRoundedRect(_ rt: CGRect, xRadius xrad: CGFloat, yRadius yrad: CGFloat){ self.appendRect(rt) } func appendOval(center c: CGPoint, radius r: CGFloat) { self.addArc(withCenter: c, radius: r, startAngle: 0.0, endAngle: CGFloat.pi * 2.0, clockwise: true) } #endif }
lgpl-2.1
9a97ff18efe324d0c8bf814041e8dd9e
20.673469
101
0.683616
2.730077
false
false
false
false
angmu/SwiftPlayCode
protol协议/protol协议/ViewController.swift
1
1280
// // ViewController.swift // protol协议 // // Created by MGBook on 2018/8/7. // Copyright © 2018年 MGBook. All rights reserved. // import UIKit protocol BuyTicketProtocol { func buyTicket() } class Person { // 1.定义协议属性 var delegate : BuyTicketProtocol // 2.自定义构造函数 init (delegate : BuyTicketProtocol) { self.delegate = delegate } // 3.行为 func goToBeijing() { delegate.buyTicket() } } class HuangNiu: BuyTicketProtocol { func buyTicket() { print("买了一张火车票") } } //MARK: - 第二套协议 protocol MyClassDelegate: class { func method() } class MyClass { weak var delegate: MyClassDelegate? } class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let p = Person(delegate: HuangNiu()) // let p2 = Person() p.goToBeijing() // someInstance = MyClass() // someInstance.delegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
54ca2aa9b910b3ae6ec2afb5579490fd
17.753846
80
0.608696
3.996721
false
false
false
false
sclark01/Swift_VIPER_Demo
VIPER_Demo/VIPER_DemoTests/ModulesTests/PeopleListTests/ViewTests/PeopleListViewControllerTests.swift
1
2013
import UIKit import Quick import Nimble @testable import VIPER_Demo class PeopleListViewControllerTests : QuickSpec { override func spec() { describe("the people list view controller") { var viewController: PeopleListViewController! var mockPresenter: PeopleListPresenterMock! let person = Person(id: 1, name: "someName", phone: "somePhone", age: "someAge") beforeEach { let storyBoard = UIStoryboard(name: "PeopleList", bundle: nil) viewController = storyBoard.instantiateInitialViewController() as! PeopleListViewController mockPresenter = PeopleListPresenterMock() mockPresenter.userInterface = viewController mockPresenter.willSetViewWithPerson = person viewController.eventHandler = mockPresenter let _ = viewController.view } it("should ask for data from event handler on load") { expect(mockPresenter.didCallUpdateView).to(beTrue()) } it("should return the count of people for number of rows in section") { let rows = viewController.tableView(viewController.tableView, numberOfRowsInSection: 0) expect(rows).toEventually(equal(1)) } it("should return the correct cell with label set") { let cell = viewController.tableView(viewController.tableView, cellForRowAt: IndexPath(row: 0, section: 0)) expect(cell.textLabel!.text).toEventually(equal(person.name)) expect(cell.detailTextLabel!.text).toEventually(equal("Phone: \(person.phone)")) } it("should notify event handler on selection with corrrect ID") { viewController.tableView(viewController.tableView, didSelectRowAt: IndexPath(row: 0, section: 0)) expect(mockPresenter.didCallDetailsForPersonWithID) == person.id } } } }
mit
7fc91741acbf882deb27fbe7aa5ddab9
40.9375
122
0.629906
5.591667
false
false
false
false
apple/swift-package-manager
Sources/PackageCollectionsSigning/Key/ASN1/Types/ASN1Identifier.swift
2
4002
//===----------------------------------------------------------------------===// // // This source file is part of the Swift open source project // // Copyright (c) 2021 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 // //===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===// // // This source file is part of the SwiftCrypto open source project // // Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors // Licensed under Apache License v2.0 // // See http://swift.org/LICENSE.txt for license information // See CONTRIBUTORS.md for the list of SwiftCrypto project authors // //===----------------------------------------------------------------------===// import Foundation // Source: https://github.com/apple/swift-crypto/blob/main/Sources/Crypto/ASN1/Basic%20ASN1%20Types/ASN1Identifier.swift extension ASN1 { /// An `ASN1Identifier` is a representation of the abstract notion of an ASN.1 identifier. Identifiers have a number of properties that relate to both the specific /// tag number as well as the properties of the identifier in the stream. internal struct ASN1Identifier { /// The base tag. In a general ASN.1 implementation we'd need an arbitrary precision integer here as the tag number can be arbitrarily large, but /// we don't need the full generality here. private(set) var baseTag: UInt8 /// Whether this tag is primitive. var primitive: Bool { return self.baseTag & 0x20 == 0 } /// Whether this tag is constructed. var constructed: Bool { return !self.primitive } enum TagClass { case universal case application case contextSpecific case `private` } /// The class of this tag. var tagClass: TagClass { switch self.baseTag >> 6 { case 0x00: return .universal case 0x01: return .application case 0x02: return .contextSpecific case 0x03: return .private default: fatalError("Unreachable") } } init(rawIdentifier: UInt8) throws { // We don't support multibyte identifiers, which are signalled when the bottom 5 bits are all 1. guard rawIdentifier & 0x1F != 0x1F else { throw ASN1Error.invalidFieldIdentifier } self.baseTag = rawIdentifier } init(explicitTagWithNumber number: Int, tagClass: TagClass) { precondition(number >= 0) precondition(number < 0x1F) self.baseTag = UInt8(number) switch tagClass { case .universal: preconditionFailure("Explicit tags may not be universal") case .application: self.baseTag |= 1 << 6 case .contextSpecific: self.baseTag |= 2 << 6 case .private: self.baseTag |= 3 << 6 } // Explicit tags are always constructed. self.baseTag |= 0x20 } } } extension ASN1.ASN1Identifier { internal static let objectIdentifier = try! ASN1.ASN1Identifier(rawIdentifier: 0x06) internal static let primitiveBitString = try! ASN1.ASN1Identifier(rawIdentifier: 0x03) internal static let primitiveOctetString = try! ASN1.ASN1Identifier(rawIdentifier: 0x04) internal static let integer = try! ASN1.ASN1Identifier(rawIdentifier: 0x02) internal static let sequence = try! ASN1.ASN1Identifier(rawIdentifier: 0x30) } extension ASN1.ASN1Identifier: Hashable {}
apache-2.0
62fe1b8fd1846afeb279901273a8102e
35.381818
167
0.575462
4.827503
false
false
false
false
toshiapp/toshi-ios-client
Toshi/Controllers/Wallet/TokenEtherDetailViewController.swift
1
7503
// Copyright (c) 2018 Token Browser, Inc // // 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 UIKit final class TokenEtherDetailViewController: UIViewController { private lazy var iconImageView: AvatarImageView = { let imageView = AvatarImageView() imageView.contentMode = .scaleAspectFit imageView.width(.defaultAvatarHeight) imageView.height(.defaultAvatarHeight) imageView.contentMode = .scaleAspectFit return imageView }() private lazy var tokenValueLabel: UILabel = { let label = UILabel() label.font = Theme.preferredTitle3(range: 24...38) label.textColor = Theme.darkTextColor label.textAlignment = .center return label }() private lazy var fiatValueLabel: UILabel = { let label = UILabel() label.font = Theme.preferredTitle3(range: 15...25) label.textColor = Theme.darkTextHalfAlpha label.textAlignment = .center return label }() private lazy var sendButton: ActionButton = { let button = ActionButton(margin: 0, cornerRadius: 4) button.title = Localized.wallet_token_detail_send button.addTarget(self, action: #selector(sendButtonTapped), for: .touchUpInside) return button }() private lazy var receiveButton: ActionButton = { let button = ActionButton(margin: 0, cornerRadius: 4) button.title = Localized.wallet_token_detail_receive button.addTarget(self, action: #selector(receiveButtonTapped), for: .touchUpInside) return button }() private var token: Token var tokenContractAddress: String { return token.contractAddress } // MARK: - Initialization init(token: Token) { self.token = token super.init(nibName: nil, bundle: nil) let background = setupContentBackground() setupMainStackView(with: background) view.backgroundColor = Theme.lightGrayBackgroundColor configure(for: token) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - View Setup private func setupContentBackground() -> UIView { let background = UIView() background.backgroundColor = Theme.viewBackgroundColor view.addSubview(background) background.top(to: layoutGuide()) background.leftToSuperview() background.rightToSuperview() let bottomBorder = BorderView() background.addSubview(bottomBorder) bottomBorder.edgesToSuperview(excluding: .top) bottomBorder.addHeightConstraint() return background } private func setupMainStackView(with background: UIView) { let stackView = UIStackView() stackView.alignment = .center stackView.axis = .vertical background.addSubview(stackView) stackView.topToSuperview(offset: .giantInterItemSpacing) stackView.leftToSuperview(offset: .spacingx3) stackView.rightToSuperview(offset: .spacingx3) stackView.bottomToSuperview(offset: -.largeInterItemSpacing) stackView.addArrangedSubview(iconImageView) stackView.addSpacing(.mediumInterItemSpacing, after: iconImageView) stackView.addWithDefaultConstraints(view: tokenValueLabel) addFiatValueIfNeeded(to: stackView, after: tokenValueLabel) addButtons(to: stackView) } private func addFiatValueIfNeeded(to stackView: UIStackView, after previousView: UIView) { let bottomView: UIView if token.canShowFiatValue == true { stackView.addSpacing(.smallInterItemSpacing, after: previousView) stackView.addWithDefaultConstraints(view: fiatValueLabel) bottomView = fiatValueLabel } else { bottomView = previousView } stackView.addSpacing(.giantInterItemSpacing, after: bottomView) } private func addButtons(to stackView: UIStackView) { let buttonStackView = UIStackView() buttonStackView.axis = .horizontal buttonStackView.distribution = .fillEqually buttonStackView.spacing = .mediumInterItemSpacing stackView.addWithDefaultConstraints(view: buttonStackView) buttonStackView.addArrangedSubview(sendButton) buttonStackView.addArrangedSubview(receiveButton) } // MARK: - Setup For Token private func configure(for token: Token) { title = token.name if let ether = token as? EtherToken { iconImageView.image = token.localIcon tokenValueLabel.text = EthereumConverter.ethereumValueString(forWei: ether.wei, fractionDigits: 6) fiatValueLabel.text = EthereumConverter.fiatValueString(forWei: ether.wei, exchangeRate: ExchangeRateClient.exchangeRate) } else { tokenValueLabel.text = "\(token.displayValueString) \(token.symbol)" guard let tokenIcon = token.icon else { return } AvatarManager.shared.avatar(for: tokenIcon) { [weak self] image, _ in self?.iconImageView.image = image } } } // MARK: - Action Targets @objc private func sendButtonTapped() { let sendTokenController = SendTokenViewController(token: token, tokenType: token.canShowFiatValue ? .fiatRepresentable : .nonFiatRepresentable) sendTokenController.delegate = self let navigationController = UINavigationController(rootViewController: sendTokenController) Navigator.presentModally(navigationController) } @objc private func receiveButtonTapped() { guard let screenshot = tabBarController?.view.snapshotView(afterScreenUpdates: false) else { assertionFailure("Could not screenshot?!") return } let walletQRController = WalletQRCodeViewController(address: Cereal.shared.paymentAddress, backgroundView: screenshot) walletQRController.modalTransitionStyle = .crossDissolve present(walletQRController, animated: true) } func update(with token: Token) { self.token = token configure(for: token) } } extension TokenEtherDetailViewController: SendTokenViewControllerDelegate { func sendTokenControllerDidFinish(_ controller: UIViewController?) { controller?.dismiss(animated: true) { self.navigationController?.popViewController(animated: true) } } } extension TokenEtherDetailViewController: NavBarColorChanging { var navTintColor: UIColor? { return Theme.tintColor } var navBarTintColor: UIColor? { return Theme.navigationBarColor } var navTitleColor: UIColor? { return Theme.darkTextColor } var navShadowImage: UIImage? { return nil } }
gpl-3.0
e82bb7f1c4441cc77d4afdcc197100c5
32.950226
151
0.679595
5.20319
false
false
false
false
blockchain/My-Wallet-V3-iOS
Blockchain/Wallet/Bitcoin/BitcoinJSInteropDispatcher.swift
1
4384
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import JavaScriptCore import ToolKit @objc public protocol BitcoinJSInteropDelegateAPI { func didGetDefaultWalletIndex(_ walletIndex: JSValue) func didFailToGetDefaultWalletIndex(errorMessage: JSValue) func didGetWalletIndex(_ walletIndex: JSValue) func didFailToGetWalletIndex(errorMessage: JSValue) func didGetAccounts(_ accounts: JSValue) func didFailToGetAccounts(errorMessage: JSValue) func didGetHDWallet(_ wallet: JSValue) func didFailToGetHDWallet(errorMessage: JSValue) func didGetSignedPayment(_ payment: JSValue) func didFailToSignPayment(errorMessage: JSValue) } protocol BitcoinJSInteropDispatcherAPI { var getWalletIndex: Dispatcher<Int32> { get } var getDefaultWalletIndex: Dispatcher<Int> { get } var getAccounts: Dispatcher<String> { get } var getSignedPayment: Dispatcher<(String, Int)> { get } var getHDWallet: Dispatcher<String> { get } } public class BitcoinJSInteropDispatcher: BitcoinJSInteropDispatcherAPI { static let shared = BitcoinJSInteropDispatcher() let getDefaultWalletIndex = Dispatcher<Int>() let getWalletIndex = Dispatcher<Int32>() let getSignedPayment = Dispatcher<(String, Int)>() let getAccounts = Dispatcher<String>() let getHDWallet = Dispatcher<String>() } extension BitcoinJSInteropDispatcher: BitcoinJSInteropDelegateAPI { public func didGetSignedPayment(_ payment: JSValue) { guard let payload: String = payment.toString() else { getWalletIndex.sendFailure(.unknown) return } let values = payload.components(separatedBy: ",") guard let hex = values.first else { sendFailure(dispatcher: getSignedPayment, errorMessage: payment) return } guard let weight = values.last else { sendFailure(dispatcher: getSignedPayment, errorMessage: payment) return } guard let weightValue = Int(weight) else { sendFailure(dispatcher: getSignedPayment, errorMessage: payment) return } getSignedPayment.sendSuccess(with: (hex, weightValue)) } public func didFailToSignPayment(errorMessage: JSValue) { sendFailure(dispatcher: getSignedPayment, errorMessage: errorMessage) } public func didGetWalletIndex(_ walletIndex: JSValue) { guard let walletIndexInt: Int32 = walletIndex.toNumber()?.int32Value else { getWalletIndex.sendFailure(.unknown) return } getWalletIndex.sendSuccess(with: walletIndexInt) } public func didFailToGetWalletIndex(errorMessage: JSValue) { sendFailure(dispatcher: getWalletIndex, errorMessage: errorMessage) } public func didGetDefaultWalletIndex(_ walletIndex: JSValue) { guard let walletIndexInt: Int = walletIndex.toNumber()?.intValue else { getDefaultWalletIndex.sendFailure(.unknown) return } getDefaultWalletIndex.sendSuccess(with: walletIndexInt) } public func didFailToGetDefaultWalletIndex(errorMessage: JSValue) { sendFailure(dispatcher: getDefaultWalletIndex, errorMessage: errorMessage) } public func didGetAccounts(_ accounts: JSValue) { guard let accountsString: String = accounts.toString() else { getAccounts.sendFailure(.unknown) return } getAccounts.sendSuccess(with: accountsString) } public func didFailToGetAccounts(errorMessage: JSValue) { sendFailure(dispatcher: getAccounts, errorMessage: errorMessage) } public func didGetHDWallet(_ wallet: JSValue) { guard let walletString: String = wallet.toString() else { getHDWallet.sendFailure(.unknown) return } getHDWallet.sendSuccess(with: walletString) } public func didFailToGetHDWallet(errorMessage: JSValue) { sendFailure(dispatcher: getHDWallet, errorMessage: errorMessage) } private func sendFailure<T>(dispatcher: Dispatcher<T>, errorMessage: JSValue) { guard let message: String = errorMessage.toString() else { dispatcher.sendFailure(.unknown) return } Logger.shared.error(message) dispatcher.sendFailure(.jsError(message)) } }
lgpl-3.0
a178d3695e41ddaad4cd31e01f535e92
31.466667
83
0.691764
4.864595
false
false
false
false
djnivek/Fillio-ios
Fillio/FillioTests/Contact.swift
1
746
// // FIOObject.swift // Fillio // // Created by Kévin MACHADO on 10/04/2015. // Copyright (c) 2015 Kévin MACHADO. All rights reserved. // import Foundation import Fillio class Contact: FIONetworkObjectAuto { var firstname: String? var lastname: String? var phone: String? var age: NSNumber? var adresse: Adresse? init(_ data: FIODictionary) { super.init(data, autoMapping: false) adresse = Adresse(data?["adresse"] as? [String: AnyObject]) } override func Map() -> [String : String] { var map = [String: String]() map["prenom"] = "firstname" map["nom"] = "lastname" map["age"] = "age" map["phone"] = "phone" return map } }
gpl-2.0
835478315abd1ee3aee51aba4db548a0
21.575758
67
0.583333
3.492958
false
false
false
false
qiuncheng/study-for-swift
learn-rx-swift/Chocotastic-starter/Pods/RxSwift/RxSwift/Observables/Implementations/Deferred.swift
6
1519
// // Deferred.swift // RxSwift // // Created by Krunoslav Zaher on 4/19/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation class DeferredSink<S: ObservableType, O: ObserverType> : Sink<O>, ObserverType where S.E == O.E { typealias E = O.E private let _observableFactory: () throws -> S init(observableFactory: @escaping () throws -> S, observer: O) { _observableFactory = observableFactory super.init(observer: observer) } func run() -> Disposable { do { let result = try _observableFactory() return result.subscribe(self) } catch let e { forwardOn(.error(e)) dispose() return Disposables.create() } } func on(_ event: Event<E>) { forwardOn(event) switch event { case .next: break case .error: dispose() case .completed: dispose() } } } class Deferred<S: ObservableType> : Producer<S.E> { typealias Factory = () throws -> S private let _observableFactory : Factory init(observableFactory: @escaping Factory) { _observableFactory = observableFactory } override func run<O: ObserverType>(_ observer: O) -> Disposable where O.E == S.E { let sink = DeferredSink(observableFactory: _observableFactory, observer: observer) sink.disposable = sink.run() return sink } }
mit
ca12913aaa1323eb57672adeb3e942db
23.885246
97
0.573123
4.438596
false
false
false
false
toshi0383/RateTV
RateTVTests/RatePointTests.swift
1
1583
// // RatePointTests.swift // RateTV // // Created by toshi0383 on 2017/01/01. // Copyright © 2017 toshi0383. All rights reserved. // import XCTest @testable import RateTV class RatePointTests: XCTestCase { func testSimple() { let rp = RatePoint(number: 1, point: 5) XCTAssertEqual(rp.number, 1) XCTAssertEqual(rp.point, 5) } func testMoveUp() { let rp1 = RatePoint(number: 1, point: 10) XCTAssertEqual(rp1.number, 2) XCTAssertEqual(rp1.point, 0) let rp2 = RatePoint(number: 1, point: 19) XCTAssertEqual(rp2.number, 2) XCTAssertEqual(rp2.point, 9) } func testAddition() { let rp1 = RatePoint(number: 1, point: 9) XCTAssertEqual(rp1.number, 1) XCTAssertEqual(rp1.point, 9) let rp2 = RatePoint(number: 1, point: 9) XCTAssertEqual(rp2.number, 1) XCTAssertEqual(rp2.point, 9) let added = rp1 + rp2 XCTAssertEqual(added.number, 3) XCTAssertEqual(added.point, 8) } func testMultiply() { let rp = RatePoint(number: 1, point: 9) XCTAssertEqual(rp.number, 1) XCTAssertEqual(rp.point, 9) let multiplied = rp * 2 XCTAssertEqual(multiplied.number, 3) XCTAssertEqual(multiplied.point, 8) } func testInitFromFloat() { let rp1 = RatePoint(float: 1.9999) XCTAssertEqual(rp1.number, 1) XCTAssertEqual(rp1.point, 9) let rp2 = RatePoint(float: 2.1118) XCTAssertEqual(rp2.number, 2) XCTAssertEqual(rp2.point, 1) } }
mit
5ac5bf5e4077a78dd820e881f723d853
28.849057
52
0.610619
3.636782
false
true
false
false
coderMONSTER/iosstar
iOSStar/AppAPI/SocketAPI/SocketReqeust/SocketResponse.swift
1
3105
// // SocketResponse.swift // viossvc // // Created by yaowang on 2016/11/25. // Copyright © 2016年 com.yundian. All rights reserved. // import UIKit class SocketResponse { fileprivate var body:SocketDataPacket? var statusCode:Int { get { return Int(body!.operate_code) } } func responseData() -> Data? { return body?.data as Data? } init(packet:SocketDataPacket) { body = packet; } } class SocketJsonResponse: SocketResponse { private var _jsonOjbect:AnyObject?; override var statusCode: Int { get{ let dict:NSDictionary? = responseJsonObject() as? NSDictionary var errorCode: Int = 0; if ( dict == nil ) { errorCode = -11012; //json解析失败 } else if( dict != nil && dict?["result"] != nil ) { errorCode = dict?["result"] as! Int; } else { errorCode = 0; } return errorCode; } } func responseJsonObject() -> AnyObject? { if body?.data?.count == 0 { return nil } if _jsonOjbect == nil { do{ #if false var json = String(data: body!.data!, encoding: .utf8) json = json == nil ? "" : json; // debugPrint("\(body!.operate_code) \(body!.data_length) json\(json!)") #endif _jsonOjbect = try JSONSerialization.jsonObject(with: body!.data!, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject? }catch let error as Error! { var json = String(data: body!.data!, encoding: .utf8) json = json == nil ? "" : json; debugPrint("解析json\(json!) \(error) ") } } return _jsonOjbect } func responseJson<T:NSObject>() ->T? { var object = responseJsonObject() if object != nil && !(T.isKind(of: NSDictionary.self)) && T.isKind(of: NSObject.self) { object = responseModel(T.classForCoder()) } return object as? T } func responseModel(_ modelClass: AnyClass) ->AnyObject?{ let object = responseJsonObject() if object != nil { return try! OEZJsonModelAdapter.model(of: modelClass, fromJSONDictionary: object as! [AnyHashable: Any]) as AnyObject? } return nil } func responseModels(_ modelClass: AnyClass) ->[AnyObject]? { let array:[AnyObject]? = responseJsonObject() as? [AnyObject] if array != nil { return try! OEZJsonModelAdapter.models(of: modelClass, fromJSONArray: nil) as [AnyObject]? } return nil; } func responseResult() -> Int? { let dict = responseJsonObject() as? [String:AnyObject] if dict != nil && dict!["result_"] != nil { return dict!["result_"] as? Int; } return nil; } }
gpl-3.0
f641acd926125dd0c41cab4b23c5ee39
28.428571
156
0.519094
4.504373
false
false
false
false
mpurbo/PurboSwiftCsv
PurboSwiftCsv/Constants.swift
1
1607
// // Constants.swift // PurboSwiftCsv // // Ported from org.apache.commons.csv.Constants // // Created by Purbo Mohamad on 12/7/14. // Copyright (c) 2014 Purbo. All rights reserved. // import Foundation struct Constants { static let BACKSPACE: Character = "\u{0008}" static let COMMA: Character = "," /** Starts a comment, the remainder of the line is the comment. */ static let COMMENT: Character = "#" static let CR: Character = "\r" static let DOUBLE_QUOTE_CHAR: Character = "\"" static let BACKSLASH: Character = "\\" static let FF: Character = "\u{000C}" static let LF: Character = "\n" static let SP: Character = " " static let TAB: Character = "\t" /** ASCII record separator */ static let RS: Character = "\u{001E}" /** ASCII unit separator */ static let US: Character = "\u{001F}" static let EMPTY: String = "" /** The end of stream symbol */ static let END_OF_STREAM: Int = -1 /** Undefined state for the lookahead char */ static let UNDEFINED: Int = -2 /** According to RFC 4180, line breaks are delimited by CRLF */ static let CRLF: String = "\r\n" /** Unicode line separator. */ static let LINE_SEPARATOR: Character = "\u{2028}" /** Unicode paragraph separator. */ static let PARAGRAPH_SEPARATOR: Character = "\u{2029}" /** Unicode next line. */ static let NEXT_LINE: String = "\u{0085}" }
apache-2.0
f1717cff2043cf812f4790855c30afa4
21.027397
67
0.556938
4.047859
false
false
false
false
urbanthings/urbanthings-sdk-apple
Demo/ViewControllers/ContainerViewController.swift
1
2498
// // ContainerViewController.swift // UrbanThingsAPI // // Created by Mark Woollard on 06/05/2016. // Copyright © 2016 UrbanThings. All rights reserved. // import UIKit import CoreLocation import UTAPI class ContainerViewController : UIViewController { var location:DemoLocation? var modes:[TransitMode] = [TransitMode.CycleHired, TransitMode.Car] @IBOutlet weak var attributionImageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() self.location = StopsModel.sharedInstance.demoLocations[0] self.refreshData() } override func viewDidAppear(_ animated: Bool) { // Ensure you have set a valid ApiKey in StopsModel.swift if !StopsModel.sharedInstance.hasValidApiKey() { let alert = UIAlertController(title: "No API Key", message: "To use the demo app you must insert your Api key into the appropriate place in file StopsModel.swift", preferredStyle: UIAlertControllerStyle.alert) self.present(alert, animated: true, completion: nil) } } @IBAction func changeType(_ sender: UISegmentedControl) { switch sender.selectedSegmentIndex { case 1: self.modes = [TransitMode.CycleHired] break case 2: self.modes = [TransitMode.Car] break default: self.modes = [TransitMode.CycleHired, TransitMode.Car] } self.refreshData() } func refreshData() { self.navigationItem.rightBarButtonItem?.title = self.location?.title StopsModel.sharedInstance.setLocation(location: self.location!.location, types: self.modes) } @IBAction func chooseLocation(_ sender: UIBarButtonItem) { let action = UIAlertController(title:"Choose Location", message:nil, preferredStyle: .actionSheet) StopsModel.sharedInstance.demoLocations.forEach { demoLocation in action.addAction(UIAlertAction(title: demoLocation.title, style: .default, handler: { _ in self.location = demoLocation self.refreshData() })) } if action.popoverPresentationController == nil { action.addAction(UIAlertAction(title: "Cancel", style: .default, handler: nil)) } action.popoverPresentationController?.barButtonItem = sender self.present(action, animated: true, completion: nil) } }
apache-2.0
06734b3feac4a4c4fca2492c010ee935
32.743243
221
0.646776
4.994
false
false
false
false
krzysztofzablocki/Sourcery
SourceryFramework/Sources/Parsing/SwiftSyntax/SyntaxTreeCollector.swift
1
12510
import SwiftSyntax import SourceryRuntime import SourceryUtils import Foundation class SyntaxTreeCollector: SyntaxVisitor { var types = [Type]() var typealiases = [Typealias]() var methods = [SourceryMethod]() var imports = [Import]() private var visitingType: Type? let annotationsParser: AnnotationsParser let sourceLocationConverter: SourceLocationConverter let module: String? let file: String init(file: String, module: String?, annotations: AnnotationsParser, sourceLocationConverter: SourceLocationConverter) { self.annotationsParser = annotations self.file = file self.module = module self.sourceLocationConverter = sourceLocationConverter super.init(viewMode: .fixedUp) } private func startVisitingType(_ node: DeclSyntaxProtocol, _ builder: (_ parent: Type?) -> Type) { let type = builder(visitingType) let tokens = node.tokens(viewMode: .fixedUp) if let open = tokens.first(where: { $0.tokenKind == .leftBrace }), let close = tokens .reversed() .first(where: { $0.tokenKind == .rightBrace }) { let startLocation = open.endLocation(converter: sourceLocationConverter) let endLocation = close.startLocation(converter: sourceLocationConverter) type.bodyBytesRange = SourceryRuntime.BytesRange(offset: Int64(startLocation.offset), length: Int64(endLocation.offset - startLocation.offset)) } else { logError("Unable to find bodyRange for \(type.name)") } let startLocation = node.startLocation(converter: sourceLocationConverter, afterLeadingTrivia: true) let endLocation = node.endLocation(converter: sourceLocationConverter, afterTrailingTrivia: false) type.completeDeclarationRange = SourceryRuntime.BytesRange(offset: Int64(startLocation.offset), length: Int64(endLocation.offset - startLocation.offset)) visitingType?.containedTypes.append(type) visitingType = type types.append(type) } public override func visit(_ node: StructDeclSyntax) -> SyntaxVisitorContinueKind { startVisitingType(node) { parent in Struct(node, parent: parent, annotationsParser: annotationsParser) } return .visitChildren } public override func visitPost(_ node: StructDeclSyntax) { visitingType = visitingType?.parent } public override func visit(_ node: ClassDeclSyntax) -> SyntaxVisitorContinueKind { startVisitingType(node) { parent in Class(node, parent: parent, annotationsParser: annotationsParser) } return .visitChildren } public override func visitPost(_ node: ClassDeclSyntax) { visitingType = visitingType?.parent } public override func visit(_ node: ActorDeclSyntax) -> SyntaxVisitorContinueKind { startVisitingType(node) { parent in Actor(node, parent: parent, annotationsParser: annotationsParser) } return .visitChildren } public override func visitPost(_ node: ActorDeclSyntax) { visitingType = visitingType?.parent } public override func visit(_ node: EnumDeclSyntax) -> SyntaxVisitorContinueKind { startVisitingType(node) { parent in Enum(node, parent: parent, annotationsParser: annotationsParser) } return .visitChildren } public override func visitPost(_ node: EnumDeclSyntax) { visitingType = visitingType?.parent } public override func visit(_ node: VariableDeclSyntax) -> SyntaxVisitorContinueKind { let variables = Variable.from(node, visitingType: visitingType, annotationParser: annotationsParser) if let visitingType = visitingType { visitingType.rawVariables.append(contentsOf: variables) } return .skipChildren } public override func visit(_ node: EnumCaseDeclSyntax) -> SyntaxVisitorContinueKind { guard let enumeration = visitingType as? Enum else { logError("EnumCase shouldn't appear outside of enum declaration \(node.description.trimmed)") return .skipChildren } enumeration.cases.append(contentsOf: EnumCase.from(node, annotationsParser: annotationsParser)) return .skipChildren } public override func visit(_ node: DeinitializerDeclSyntax) -> SyntaxVisitorContinueKind { guard let visitingType = visitingType else { logError("deinit shouldn't appear outside of type declaration \(node.description.trimmed)") return .skipChildren } visitingType.rawMethods.append( SourceryMethod(node, parent: visitingType, typeName: TypeName(visitingType.name), annotationsParser: annotationsParser) ) return .skipChildren } public override func visit(_ node: ExtensionDeclSyntax) -> SyntaxVisitorContinueKind { startVisitingType(node) { parent in let modifiers = node.modifiers?.map(Modifier.init) ?? [] let base = modifiers.baseModifiers(parent: nil) return Type( name: node.extendedType.description.trimmingCharacters(in: .whitespaces), parent: parent, accessLevel: base.readAccess, isExtension: true, variables: [], methods: [], subscripts: [], inheritedTypes: node.inheritanceClause?.inheritedTypeCollection.map { $0.typeName.description.trimmed } ?? [], containedTypes: [], typealiases: [], attributes: Attribute.from(node.attributes), modifiers: modifiers.map(SourceryModifier.init), annotations: annotationsParser.annotations(fromToken: node.extensionKeyword), documentation: annotationsParser.documentation(fromToken: node.extensionKeyword), isGeneric: false ) } return .visitChildren } public override func visitPost(_ node: ExtensionDeclSyntax) { visitingType = visitingType?.parent } public override func visit(_ node: FunctionDeclSyntax) -> SyntaxVisitorContinueKind { let method = SourceryMethod(node, parent: visitingType, typeName: visitingType.map { TypeName($0.name) }, annotationsParser: annotationsParser) if let visitingType = visitingType { visitingType.rawMethods.append(method) } else { methods.append(method) } return .skipChildren } public override func visit(_ node: ImportDeclSyntax) -> SyntaxVisitorContinueKind { imports.append(Import(path: node.path.description.trimmed, kind: node.importKind?.text.trimmed)) return .skipChildren } public override func visit(_ node: InitializerDeclSyntax) -> SyntaxVisitorContinueKind { guard let visitingType = visitingType else { logError("init shouldn't appear outside of type declaration \(node.description.trimmed)") return .skipChildren } let method = SourceryMethod(node, parent: visitingType, typeName: TypeName(visitingType.name), annotationsParser: annotationsParser) visitingType.rawMethods.append(method) return .skipChildren } public override func visit(_ node: ProtocolDeclSyntax) -> SyntaxVisitorContinueKind { startVisitingType(node) { parent in SourceryProtocol(node, parent: parent, annotationsParser: annotationsParser) } return .visitChildren } public override func visitPost(_ node: ProtocolDeclSyntax) { visitingType = visitingType?.parent } public override func visit(_ node: SubscriptDeclSyntax) -> SyntaxVisitorContinueKind { guard let visitingType = visitingType else { logError("subscript shouldn't appear outside of type declaration \(node.description.trimmed)") return .skipChildren } visitingType.rawSubscripts.append( Subscript(node, parent: visitingType, annotationsParser: annotationsParser) ) return .skipChildren } public override func visit(_ node: TypealiasDeclSyntax) -> SyntaxVisitorContinueKind { let localName = node.identifier.text.trimmed let typeName = TypeName(node.initializer.value) let modifiers = node.modifiers?.map(Modifier.init) ?? [] let baseModifiers = modifiers.baseModifiers(parent: visitingType) let annotations = annotationsParser.annotations(from: node) if let composition = processPossibleProtocolComposition(for: typeName.name, localName: localName, annotations: annotations, accessLevel: baseModifiers.readAccess) { if let visitingType = visitingType { visitingType.containedTypes.append(composition) } else { types.append(composition) } return .skipChildren } let alias = Typealias( aliasName: localName, typeName: typeName, accessLevel: baseModifiers.readAccess, parent: visitingType, module: module ) // TODO: add generic requirements if let visitingType = visitingType { visitingType.typealiases[localName] = alias } else { // global typealias typealiases.append(alias) } return .skipChildren } public override func visit(_ node: AssociatedtypeDeclSyntax) -> SyntaxVisitorContinueKind { guard let sourceryProtocol = visitingType as? SourceryProtocol else { return .skipChildren } let name = node.identifier.text.trimmed var typeName: TypeName? var type: Type? if let possibleTypeName = node.inheritanceClause?.inheritedTypeCollection.description.trimmed { type = processPossibleProtocolComposition(for: possibleTypeName, localName: "") typeName = TypeName(possibleTypeName) } sourceryProtocol.associatedTypes[name] = AssociatedType(name: name, typeName: typeName, type: type) return .skipChildren } public override func visit(_ node: OperatorDeclSyntax) -> SyntaxVisitorContinueKind { return .skipChildren } public override func visit(_ node: PrecedenceGroupDeclSyntax) -> SyntaxVisitorContinueKind { return .skipChildren } public override func visit(_ node: IfConfigDeclSyntax) -> SyntaxVisitorContinueKind { return .visitChildren } private func processPossibleProtocolComposition(for typeName: String, localName: String, annotations: [String: NSObject] = [:], accessLevel: AccessLevel = .internal) -> Type? { if let composedTypeNames = extractComposedTypeNames(from: typeName, trimmingCharacterSet: .whitespaces), composedTypeNames.count > 1 { let inheritedTypes = composedTypeNames.map { $0.name } let composition = ProtocolComposition( name: localName, parent: visitingType, accessLevel: accessLevel, inheritedTypes: inheritedTypes, annotations: annotations, composedTypeNames: composedTypeNames ) return composition } return nil } /// Extracts list of type names from composition e.g. `ProtocolA & ProtocolB` internal func extractComposedTypeNames(from value: String, trimmingCharacterSet: CharacterSet? = nil) -> [TypeName]? { guard case let closureComponents = value.components(separatedBy: "->"), closureComponents.count <= 1 else { return nil } guard case let components = value.components(separatedBy: CharacterSet(charactersIn: "&")), components.count > 1 else { return nil } var characterSet: CharacterSet = .whitespacesAndNewlines if let trimmingCharacterSet = trimmingCharacterSet { characterSet = characterSet.union(trimmingCharacterSet) } let suffixes = components.map { source in source.trimmingCharacters(in: characterSet) } return suffixes.map { TypeName($0) } } private func logError(_ message: Any) { let prefix = file + ": " if let module = module { Log.astError("\(prefix) \(message) in module \(module)") } else { Log.astError("\(prefix) \(message)") } } }
mit
f43b2621a33bc20c6e751ee368ef4296
39.096154
180
0.661631
5.205993
false
false
false
false
sundeepgupta/chord
chord/KidsViewController.swift
1
2736
import UIKit import CoreData class KidsViewController: UIViewController, KidUpdater, NSFetchedResultsControllerDelegate { @IBOutlet weak var kidsView: UICollectionView! private var kidsResultsController: NSFetchedResultsController! var dataController: DataController! override func viewDidLoad() { super.viewDidLoad() self.title = "My Kids" self.setupKidsResultsController() } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { let cell = sender as! UICollectionViewCell let indexPath = self.kidsView .indexPathForCell(cell)! let kidViewController = segue.destinationViewController as! KidViewController kidViewController.kid = self.kidsResultsController.objectAtIndexPath(indexPath) as! Kid kidViewController.delegate = self } //MARK:- UICollectionViewDataSource func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { guard let sections = self.kidsResultsController.sections else { return 1 } return sections.count } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { guard let objects = self.kidsResultsController.fetchedObjects else { return 0 } guard let sections = self.kidsResultsController.sections else { return objects.count } return sections[section].numberOfObjects } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let identifier = KidCell.identifier() let cell = collectionView.dequeueReusableCellWithReuseIdentifier(identifier, forIndexPath: indexPath) as! KidCell let kid = self.kidsResultsController.objectAtIndexPath(indexPath) as! Kid cell.configure(kid: kid) return cell } //MARK:- KidUpdater func didUpdateKid(kid: Kid) { self.dataController.save() } func didDeleteKid(kid: Kid) { self.dataController.deleteKid(kid) } //MARK:- NSFetchedResultsControllerDelegate func controllerDidChangeContent(controller: NSFetchedResultsController) { self.kidsView.reloadData() } //MARK:- Private private func setupKidsResultsController() { self.kidsResultsController = self.dataController.kidsResultsController(delegate: self) do { try self.kidsResultsController.performFetch() } catch let error as NSError { print("Failed to fetch kids with error: \(error.localizedDescription)") } } }
apache-2.0
9b8ac3a0e6c461d77e7e871478b67269
33.632911
130
0.686769
5.79661
false
false
false
false
quran/quran-ios
Tests/BatchDownloaderTests/DownloadObserversRecorder.swift
1
1855
// // DownloadObserversRecorder.swift // // // Created by Mohamed Afifi on 2022-02-05. // @testable import BatchDownloader import Foundation import Locking class DownloadObserversRecorder<Item: Hashable>: NetworkResponseCancellable { enum Record<Item: Hashable>: Hashable { case progress(Item, Int, Float) case completed(Item, Int) case failed(Item, Int, NSError) case itemsUpdated([Item]) case cancel(response: DownloadBatchResponse) } private var records: Protected<[Record<Item>]> = Protected([]) init(observer: DownloadingObserverCollection<Item>) { observer.downloadProgress = { x, y, z in self.records.sync { $0.append(.progress(x, y, z)) } } observer.downloadCompleted = { x, y in self.records.sync { $0.append(.completed(x, y)) } } observer.downloadFailed = { x, y, z in self.records.sync { $0.append(.failed(x, y, z as NSError)) } } observer.itemsUpdated = { [weak observer] x in self.records.sync { $0.append(.itemsUpdated(x)) } for response in (observer?.responses.values.map { $0 } ?? []) { response.cancellable = self } } } var diffSinceLastCalled: [Record<Item>] { records.sync { value in let lastValue = value // clear the value value = [] return lastValue } } func cancel(batch: DownloadBatchResponse) { records.sync { $0.append(.cancel(response: batch)) } } } extension DownloadBatchResponse: Hashable { public static func == (lhs: DownloadBatchResponse, rhs: DownloadBatchResponse) -> Bool { lhs === rhs } public func hash(into hasher: inout Hasher) { hasher.combine(ObjectIdentifier(self)) } }
apache-2.0
ae5be99b950c4ea39f849b9ad4833263
28.444444
92
0.598922
4.303944
false
false
false
false
goin18/test-ios
Toshl iOS/AppDelegate.swift
1
9122
// // AppDelegate.swift // Toshl iOS // // Created by Marko Budal on 24/03/15. // Copyright (c) 2015 Marko Budal. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? //metoda za testiranje - lahko se tudi odstrani! func initData(){ var day1 = NSEntityDescription.insertNewObjectForEntityForName("DateDay", inManagedObjectContext: self.managedObjectContext!) as! DateDay day1.date = Date.from(year: 2015, month: 3, day: 30) day1.costs = 31.00 day1.numberCost = 3 var day2 = NSEntityDescription.insertNewObjectForEntityForName("DateDay", inManagedObjectContext: self.managedObjectContext!) as! DateDay day2.date = Date.from(year: 2015, month: 3, day: 29) day2.costs = 42.50 day2.numberCost = 1 var cost1 = NSEntityDescription.insertNewObjectForEntityForName("Cost", inManagedObjectContext: self.managedObjectContext!) as! Cost cost1.name = "internet" cost1.category = "Home & Utilities" cost1.toAccount = "Bank" cost1.date = Date.from(year: 2015, month: 3, day: 30) cost1.repeat = 1 cost1.cost = 15.00 var cost2 = NSEntityDescription.insertNewObjectForEntityForName("Cost", inManagedObjectContext: self.managedObjectContext!) as! Cost cost2.name = "shop" cost2.category = "Home & Utilities" cost2.toAccount = "Bank" cost2.date = Date.from(year: 2015, month: 3, day: 30) cost2.repeat = 1 cost2.cost = 10.30 var cost3 = NSEntityDescription.insertNewObjectForEntityForName("Cost", inManagedObjectContext: self.managedObjectContext!) as! Cost cost3.name = "market" cost3.category = "Home & Utilities" cost3.toAccount = "Bank" cost3.date = Date.from(year: 2015, month: 3, day: 30) cost3.repeat = 1 cost3.cost = 5.70 var cost4 = NSEntityDescription.insertNewObjectForEntityForName("Cost", inManagedObjectContext: self.managedObjectContext!) as! Cost cost4.name = "skipass" cost4.category = "Home & Utilities" cost4.toAccount = "Bank" cost4.date = Date.from(year: 2015, month: 3, day: 29) cost4.repeat = 1 cost4.cost = 42.50 var dayRelation1 = day1.mutableSetValueForKey("costsDay") dayRelation1.addObject(cost1) dayRelation1.addObject(cost2) dayRelation1.addObject(cost3) var dayRelation2 = day2.mutableSetValueForKey("costsDay") dayRelation2.addObject(cost4) self.saveContext() } //testiranje - brisanje vseh objektov, ki so v podani entiteti func deleteAllObject(entityName: String){ let fetchRequest = NSFetchRequest(entityName: entityName) let objects = self.managedObjectContext?.executeFetchRequest(fetchRequest, error: nil) for object in objects as! [NSManagedObject] { self.managedObjectContext?.deleteObject(object) } } func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. //pobrisi ze kreirane /* deleteAllObject("DateDay") deleteAllObject("Cost") initData() */ return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "si.goin.mobileDev.Toshl_iOS" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] as! NSURL }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("Toshl_iOS", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("Toshl_iOS.sqlite") var error: NSError? = nil var failureReason = "There was an error creating or loading the application's saved data." if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil { coordinator = nil // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext? = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator if coordinator == nil { return nil } var managedObjectContext = NSManagedObjectContext() managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if let moc = self.managedObjectContext { var error: NSError? = nil if moc.hasChanges && !moc.save(&error) { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } } } }
mit
54385659be1a876532cee6063e88b873
48.846995
290
0.690419
5.139155
false
false
false
false
poetmountain/MotionMachine
Sources/MotionSupport.swift
1
11076
// // MotionSupport.swift // MotionMachine // // Created by Brett Walker on 4/20/16. // Copyright © 2016-2018 Poet & Mountain, LLC. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation import CoreGraphics import QuartzCore #if os(iOS) || os(tvOS) import UIKit #endif /// This struct provides utility methods for Motion classes. public struct MotionSupport { // MARK: Additive utility methods // Holds weak references to all currently-tweening Motion instances which are moving an object's property static var motions = NSHashTable<AnyObject>.weakObjects() static var operationID: UInt = 0 /** * Registers an `Additive` motion. Any custom classes that conform to the `Additive` protocol should register their motion object. * * - parameter additiveMotion: The `Additive` object to register. * - returns: An operation ID that should be assigned to the `Additive` object's `operationID` property. */ public static func register(additiveMotion motion: Additive) -> UInt { if !(MotionSupport.motions.contains(motion)) { MotionSupport.motions.add(motion) } return MotionSupport.currentAdditiveOperationID() } /** * Removes an `Additive` motion from the registered list. Any custom classes that conform to the `Additive` protocol should call this method when it has completed its motion. * * - parameter additiveMotion: The `Additive` object to remove. */ public static func unregister(additiveMotion motion: Additive) { MotionSupport.motions.remove(motion) } /// Internal method that returns an incremented operation id, used to sort the motions set static func currentAdditiveOperationID() -> UInt { operationID += 1 return operationID } /** * Returns the ending value of the most recently started `Additive` motion operation for the specified object and keyPath. In order to participate in additive motion with other `Additive` objects, custom objects should use this method to set a starting value. * * **Example Usage** * `if let last_target_value = MotionSupport.targetValue(forObject: unwrapped_object, keyPath: property.path) { properties[index].start = last_target_value }` * * - parameters: * - forObject: The object whose property value should be queried. * - keyPath: The keypath of the target property, relative to the object. * * - returns: The ending value. Returns `nil` if no `Additive` object is targeting this property. */ public static func targetValue(forObject object: AnyObject, keyPath path: String) -> Double? { var target_value: Double? // create an array from the operations NSSet, using the Motion's operationID as sort key let motions_array = MotionSupport.motions.allObjects let sorted_motions = motions_array.sorted( by: { (motion1, motion2) -> Bool in var test: Bool = false if let m1 = motion1 as? Additive, let m2 = motion2 as? Additive { test = m1.operationID < m2.operationID } return test }) // reverse through the array and find the most recent motion operation that's modifying this object property for motion in sorted_motions { let additive = motion as! Additive for property: PropertyData in additive.properties { if ((property.target === object || property.targetObject === object) && property.path == path) { target_value = property.start + ((property.end - property.start) * additive.additiveWeighting) break } } } return target_value } // MARK: Utility methods public static func cast(_ number: AnyObject) -> Double? { var value: Double? if (number is NSNumber) { value = (number as! NSNumber).doubleValue } else if (number is Double) { value = number as? Double } else if (number is CGFloat) { value = Double(number as! CGFloat) } else if (number is Int) { value = Double(number as! Int) } else if (number is UInt) { value = Double(number as! UInt) } else if (number is Float) { value = Double(number as! Float) } return value } /// Utility method which determines whether the value is of the specified type. public static func matchesType(forValue value: Any, typeToMatch matchType: Any.Type) -> Bool { let does_match: Bool = type(of: value) == matchType || value is NSNumber return does_match } /// Utility method which determines whether the value is of the specified Objective-C type. public static func matchesObjCType(forValue value: NSValue, typeToMatch matchType: UnsafePointer<Int8>) -> Bool { var matches: Bool = false let value_type: UnsafePointer<Int8> = value.objCType matches = (strcmp(value_type, matchType)==0) return matches } /// Utility method that returns a getter method selector for a property name string. static func propertyGetter(forName name: String) -> Selector { let selector = NSSelectorFromString(name) return selector } /// Utility method that returns a setter method selector for a property name string. static func propertySetter(forName name: String) -> Selector { var selector_name = name let capped_first_letter = String(name[name.startIndex]).capitalized let replace_range: Range = selector_name.startIndex ..< selector_name.index(after: selector_name.startIndex) selector_name.replaceSubrange(replace_range, with: capped_first_letter) let setter_string = String.localizedStringWithFormat("%@%@:", "set", selector_name) let selector = NSSelectorFromString(setter_string) return selector } /** * Builds and returns a `PropertyData` object if the values you supply pass one of the following tests: 1) there's a specified start value and that value is different than either the original value or the ending value, or 2) there's just an original value and that value is different than the ending value, or 3) there's no start value passed in, which will return a `PropertyData` object with only an end value. In cases 1 and 2, a `PropertyData` object with both start and end values will be returned. In the third case, a `PropertyData` object that only has an ending value will be returned. If all those tests fail, no object will be returned. * * - parameter path: A base path to be used for the `PropertyData`'s `path` property. * - parameter originalValue: An optional value representing the current value of the target object property. * - parameter startValue: An optional value to be supplied to the `PropertyData`'s `start` property. * - parameter endValue: A value to be supplied to the `PropertyData`'s `end` property. * - returns: An optional `PropertyData` object using the supplied values. */ public static func buildPropertyData(path: String, originalValue: Double?=nil, startValue: Double?, endValue: Double) -> PropertyData? { var data: PropertyData? if let unwrapped_start = startValue { if ((originalValue != nil && unwrapped_start !≈ originalValue!) || endValue !≈ unwrapped_start) { data = PropertyData(path: path, start: unwrapped_start, end: endValue) } } else if let unwrapped_org = originalValue { if (endValue !≈ unwrapped_org) { data = PropertyData(path: path, start: unwrapped_org, end: endValue) } } else { data = PropertyData(path: path, end: endValue) } return data } } // MARK: - Declarations /// An enum representing NSValue-encoded structs supported by MotionMachine. public enum ValueStructTypes { case number case point case size case rect case vector case affineTransform case transform3D #if os(iOS) || os(tvOS) case uiEdgeInsets case uiOffset #endif case unsupported static var valueTypes: [ValueStructTypes: NSValue] = [ValueStructTypes.number : NSNumber.init(value: 0), ValueStructTypes.point : NSValue(cgPoint: CGPoint.zero), ValueStructTypes.size : NSValue(cgSize: CGSize.zero), ValueStructTypes.rect : NSValue(cgRect: CGRect.zero), ValueStructTypes.vector : NSValue(cgVector: CGVector(dx: 0.0, dy: 0.0)), ValueStructTypes.affineTransform : NSValue(cgAffineTransform: CGAffineTransform.identity), ValueStructTypes.transform3D : NSValue.init(caTransform3D: CATransform3DIdentity) ] /** * Provides a C string returned by Foundation's `objCType` method for a specific ValueStructTypes type; this represents a specific Objective-C type. This is useful for Foundation structs which can't be used with Swift's `as` type checking. */ func toObjCType() -> UnsafePointer<Int8> { guard let type_value = ValueStructTypes.valueTypes[self]?.objCType else { return NSNumber(value: false).objCType } return type_value } }
mit
78a512db8536b8e97578c868375ba5cc
42.407843
652
0.63583
4.814702
false
false
false
false
xedin/swift
stdlib/public/core/ManagedBuffer.swift
1
22114
//===--- ManagedBuffer.swift - variable-sized buffer of aligned memory ----===// // // 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 // //===----------------------------------------------------------------------===// import SwiftShims @usableFromInline internal typealias _HeapObject = SwiftShims.HeapObject @usableFromInline @_silgen_name("swift_bufferAllocate") internal func _swift_bufferAllocate( bufferType type: AnyClass, size: Int, alignmentMask: Int ) -> AnyObject /// A class whose instances contain a property of type `Header` and raw /// storage for an array of `Element`, whose size is determined at /// instance creation. /// /// Note that the `Element` array is suitably-aligned **raw memory**. /// You are expected to construct and---if necessary---destroy objects /// there yourself, using the APIs on `UnsafeMutablePointer<Element>`. /// Typical usage stores a count and capacity in `Header` and destroys /// any live elements in the `deinit` of a subclass. /// - Note: Subclasses must not have any stored properties; any storage /// needed should be included in `Header`. @_fixed_layout open class ManagedBuffer<Header, Element> { /// The stored `Header` instance. /// /// During instance creation, in particular during /// `ManagedBuffer.create`'s call to initialize, `ManagedBuffer`'s /// `header` property is as-yet uninitialized, and therefore /// reading the `header` property during `ManagedBuffer.create` is undefined. public final var header: Header // This is really unfortunate. In Swift 5.0, the method descriptor for this // initializer was public and subclasses would "inherit" it, referencing its // method descriptor from their class override table. @usableFromInline internal init(_doNotCallMe: ()) { _internalInvariantFailure("Only initialize these by calling create") } } extension ManagedBuffer { /// Create a new instance of the most-derived class, calling /// `factory` on the partially-constructed object to generate /// an initial `Header`. @inlinable public final class func create( minimumCapacity: Int, makingHeaderWith factory: ( ManagedBuffer<Header, Element>) throws -> Header ) rethrows -> ManagedBuffer<Header, Element> { let p = Builtin.allocWithTailElems_1( self, minimumCapacity._builtinWordValue, Element.self) let initHeaderVal = try factory(p) p.headerAddress.initialize(to: initHeaderVal) // The _fixLifetime is not really needed, because p is used afterwards. // But let's be conservative and fix the lifetime after we use the // headerAddress. _fixLifetime(p) return p } /// The actual number of elements that can be stored in this object. /// /// This header may be nontrivial to compute; it is usually a good /// idea to store this information in the "header" area when /// an instance is created. @inlinable public final var capacity: Int { let storageAddr = UnsafeMutableRawPointer(Builtin.bridgeToRawPointer(self)) let endAddr = storageAddr + _swift_stdlib_malloc_size(storageAddr) let realCapacity = endAddr.assumingMemoryBound(to: Element.self) - firstElementAddress return realCapacity } @inlinable internal final var firstElementAddress: UnsafeMutablePointer<Element> { return UnsafeMutablePointer( Builtin.projectTailElems(self, Element.self)) } @inlinable internal final var headerAddress: UnsafeMutablePointer<Header> { return UnsafeMutablePointer<Header>(Builtin.addressof(&header)) } /// Call `body` with an `UnsafeMutablePointer` to the stored /// `Header`. /// /// - Note: This pointer is valid only for the duration of the /// call to `body`. @inlinable public final func withUnsafeMutablePointerToHeader<R>( _ body: (UnsafeMutablePointer<Header>) throws -> R ) rethrows -> R { return try withUnsafeMutablePointers { (v, _) in return try body(v) } } /// Call `body` with an `UnsafeMutablePointer` to the `Element` /// storage. /// /// - Note: This pointer is valid only for the duration of the /// call to `body`. @inlinable public final func withUnsafeMutablePointerToElements<R>( _ body: (UnsafeMutablePointer<Element>) throws -> R ) rethrows -> R { return try withUnsafeMutablePointers { return try body($1) } } /// Call `body` with `UnsafeMutablePointer`s to the stored `Header` /// and raw `Element` storage. /// /// - Note: These pointers are valid only for the duration of the /// call to `body`. @inlinable public final func withUnsafeMutablePointers<R>( _ body: (UnsafeMutablePointer<Header>, UnsafeMutablePointer<Element>) throws -> R ) rethrows -> R { defer { _fixLifetime(self) } return try body(headerAddress, firstElementAddress) } } /// Contains a buffer object, and provides access to an instance of /// `Header` and contiguous storage for an arbitrary number of /// `Element` instances stored in that buffer. /// /// For most purposes, the `ManagedBuffer` class works fine for this /// purpose, and can simply be used on its own. However, in cases /// where objects of various different classes must serve as storage, /// `ManagedBufferPointer` is needed. /// /// A valid buffer class is non-`@objc`, with no declared stored /// properties. Its `deinit` must destroy its /// stored `Header` and any constructed `Element`s. /// /// Example Buffer Class /// -------------------- /// /// class MyBuffer<Element> { // non-@objc /// typealias Manager = ManagedBufferPointer<(Int, String), Element> /// deinit { /// Manager(unsafeBufferObject: self).withUnsafeMutablePointers { /// (pointerToHeader, pointerToElements) -> Void in /// pointerToElements.deinitialize(count: self.count) /// pointerToHeader.deinitialize(count: 1) /// } /// } /// /// // All properties are *computed* based on members of the Header /// var count: Int { /// return Manager(unsafeBufferObject: self).header.0 /// } /// var name: String { /// return Manager(unsafeBufferObject: self).header.1 /// } /// } /// @frozen public struct ManagedBufferPointer<Header, Element> { @usableFromInline internal var _nativeBuffer: Builtin.NativeObject /// Create with new storage containing an initial `Header` and space /// for at least `minimumCapacity` `element`s. /// /// - parameter bufferClass: The class of the object used for storage. /// - parameter minimumCapacity: The minimum number of `Element`s that /// must be able to be stored in the new buffer. /// - parameter factory: A function that produces the initial /// `Header` instance stored in the buffer, given the `buffer` /// object and a function that can be called on it to get the actual /// number of allocated elements. /// /// - Precondition: `minimumCapacity >= 0`, and the type indicated by /// `bufferClass` is a non-`@objc` class with no declared stored /// properties. The `deinit` of `bufferClass` must destroy its /// stored `Header` and any constructed `Element`s. @inlinable public init( bufferClass: AnyClass, minimumCapacity: Int, makingHeaderWith factory: (_ buffer: AnyObject, _ capacity: (AnyObject) -> Int) throws -> Header ) rethrows { self = ManagedBufferPointer( bufferClass: bufferClass, minimumCapacity: minimumCapacity) // initialize the header field try withUnsafeMutablePointerToHeader { $0.initialize(to: try factory( self.buffer, { ManagedBufferPointer(unsafeBufferObject: $0).capacity })) } // FIXME: workaround for <rdar://problem/18619176>. If we don't // access header somewhere, its addressor gets linked away _ = header } /// Manage the given `buffer`. /// /// - Precondition: `buffer` is an instance of a non-`@objc` class whose /// `deinit` destroys its stored `Header` and any constructed `Element`s. @inlinable public init(unsafeBufferObject buffer: AnyObject) { ManagedBufferPointer._checkValidBufferClass(type(of: buffer)) self._nativeBuffer = Builtin.unsafeCastToNativeObject(buffer) } //===--- internal/private API -------------------------------------------===// /// Internal version for use by _ContiguousArrayBuffer where we know that we /// have a valid buffer class. /// This version of the init function gets called from /// _ContiguousArrayBuffer's deinit function. Since 'deinit' does not get /// specialized with current versions of the compiler, we can't get rid of the /// _debugPreconditions in _checkValidBufferClass for any array. Since we know /// for the _ContiguousArrayBuffer that this check must always succeed we omit /// it in this specialized constructor. @inlinable internal init(_uncheckedUnsafeBufferObject buffer: AnyObject) { ManagedBufferPointer._internalInvariantValidBufferClass(type(of: buffer)) self._nativeBuffer = Builtin.unsafeCastToNativeObject(buffer) } /// Create with new storage containing space for an initial `Header` /// and at least `minimumCapacity` `element`s. /// /// - parameter bufferClass: The class of the object used for storage. /// - parameter minimumCapacity: The minimum number of `Element`s that /// must be able to be stored in the new buffer. /// /// - Precondition: `minimumCapacity >= 0`, and the type indicated by /// `bufferClass` is a non-`@objc` class with no declared stored /// properties. The `deinit` of `bufferClass` must destroy its /// stored `Header` and any constructed `Element`s. @inlinable internal init( bufferClass: AnyClass, minimumCapacity: Int ) { ManagedBufferPointer._checkValidBufferClass(bufferClass, creating: true) _precondition( minimumCapacity >= 0, "ManagedBufferPointer must have non-negative capacity") self.init( _uncheckedBufferClass: bufferClass, minimumCapacity: minimumCapacity) } /// Internal version for use by _ContiguousArrayBuffer.init where we know that /// we have a valid buffer class and that the capacity is >= 0. @inlinable internal init( _uncheckedBufferClass: AnyClass, minimumCapacity: Int ) { ManagedBufferPointer._internalInvariantValidBufferClass(_uncheckedBufferClass, creating: true) _internalInvariant( minimumCapacity >= 0, "ManagedBufferPointer must have non-negative capacity") let totalSize = ManagedBufferPointer._elementOffset + minimumCapacity * MemoryLayout<Element>.stride let newBuffer: AnyObject = _swift_bufferAllocate( bufferType: _uncheckedBufferClass, size: totalSize, alignmentMask: ManagedBufferPointer._alignmentMask) self._nativeBuffer = Builtin.unsafeCastToNativeObject(newBuffer) } /// Manage the given `buffer`. /// /// - Note: It is an error to use the `header` property of the resulting /// instance unless it has been initialized. @inlinable internal init(_ buffer: ManagedBuffer<Header, Element>) { _nativeBuffer = Builtin.unsafeCastToNativeObject(buffer) } } extension ManagedBufferPointer { /// The stored `Header` instance. @inlinable public var header: Header { _read { yield _headerPointer.pointee } _modify { yield &_headerPointer.pointee } } /// Returns the object instance being used for storage. @inlinable public var buffer: AnyObject { return Builtin.castFromNativeObject(_nativeBuffer) } /// The actual number of elements that can be stored in this object. /// /// This value may be nontrivial to compute; it is usually a good /// idea to store this information in the "header" area when /// an instance is created. @inlinable public var capacity: Int { return ( _capacityInBytes &- ManagedBufferPointer._elementOffset ) / MemoryLayout<Element>.stride } /// Call `body` with an `UnsafeMutablePointer` to the stored /// `Header`. /// /// - Note: This pointer is valid only /// for the duration of the call to `body`. @inlinable public func withUnsafeMutablePointerToHeader<R>( _ body: (UnsafeMutablePointer<Header>) throws -> R ) rethrows -> R { return try withUnsafeMutablePointers { (v, _) in return try body(v) } } /// Call `body` with an `UnsafeMutablePointer` to the `Element` /// storage. /// /// - Note: This pointer is valid only for the duration of the /// call to `body`. @inlinable public func withUnsafeMutablePointerToElements<R>( _ body: (UnsafeMutablePointer<Element>) throws -> R ) rethrows -> R { return try withUnsafeMutablePointers { return try body($1) } } /// Call `body` with `UnsafeMutablePointer`s to the stored `Header` /// and raw `Element` storage. /// /// - Note: These pointers are valid only for the duration of the /// call to `body`. @inlinable public func withUnsafeMutablePointers<R>( _ body: (UnsafeMutablePointer<Header>, UnsafeMutablePointer<Element>) throws -> R ) rethrows -> R { defer { _fixLifetime(_nativeBuffer) } return try body(_headerPointer, _elementPointer) } /// Returns `true` iff `self` holds the only strong reference to its buffer. /// /// See `isUniquelyReferenced` for details. @inlinable public mutating func isUniqueReference() -> Bool { return _isUnique(&_nativeBuffer) } } extension ManagedBufferPointer { @inlinable internal static func _checkValidBufferClass( _ bufferClass: AnyClass, creating: Bool = false ) { _debugPrecondition( _class_getInstancePositiveExtentSize(bufferClass) == MemoryLayout<_HeapObject>.size || ( (!creating || bufferClass is ManagedBuffer<Header, Element>.Type) && _class_getInstancePositiveExtentSize(bufferClass) == _headerOffset + MemoryLayout<Header>.size), "ManagedBufferPointer buffer class has illegal stored properties" ) _debugPrecondition( _usesNativeSwiftReferenceCounting(bufferClass), "ManagedBufferPointer buffer class must be non-@objc" ) } @inlinable internal static func _internalInvariantValidBufferClass( _ bufferClass: AnyClass, creating: Bool = false ) { _internalInvariant( _class_getInstancePositiveExtentSize(bufferClass) == MemoryLayout<_HeapObject>.size || ( (!creating || bufferClass is ManagedBuffer<Header, Element>.Type) && _class_getInstancePositiveExtentSize(bufferClass) == _headerOffset + MemoryLayout<Header>.size), "ManagedBufferPointer buffer class has illegal stored properties" ) _internalInvariant( _usesNativeSwiftReferenceCounting(bufferClass), "ManagedBufferPointer buffer class must be non-@objc" ) } } extension ManagedBufferPointer { /// The required alignment for allocations of this type, minus 1 @inlinable internal static var _alignmentMask: Int { return max( MemoryLayout<_HeapObject>.alignment, max(MemoryLayout<Header>.alignment, MemoryLayout<Element>.alignment)) &- 1 } /// The actual number of bytes allocated for this object. @inlinable internal var _capacityInBytes: Int { return _swift_stdlib_malloc_size(_address) } /// The address of this instance in a convenient pointer-to-bytes form @inlinable internal var _address: UnsafeMutableRawPointer { return UnsafeMutableRawPointer(Builtin.bridgeToRawPointer(_nativeBuffer)) } /// Offset from the allocated storage for `self` to the stored `Header` @inlinable internal static var _headerOffset: Int { _onFastPath() return _roundUp( MemoryLayout<_HeapObject>.size, toAlignment: MemoryLayout<Header>.alignment) } /// An **unmanaged** pointer to the storage for the `Header` /// instance. Not safe to use without _fixLifetime calls to /// guarantee it doesn't dangle @inlinable internal var _headerPointer: UnsafeMutablePointer<Header> { _onFastPath() return (_address + ManagedBufferPointer._headerOffset).assumingMemoryBound( to: Header.self) } /// An **unmanaged** pointer to the storage for `Element`s. Not /// safe to use without _fixLifetime calls to guarantee it doesn't /// dangle. @inlinable internal var _elementPointer: UnsafeMutablePointer<Element> { _onFastPath() return (_address + ManagedBufferPointer._elementOffset).assumingMemoryBound( to: Element.self) } /// Offset from the allocated storage for `self` to the `Element` storage @inlinable internal static var _elementOffset: Int { _onFastPath() return _roundUp( _headerOffset + MemoryLayout<Header>.size, toAlignment: MemoryLayout<Element>.alignment) } } extension ManagedBufferPointer: Equatable { @inlinable public static func == ( lhs: ManagedBufferPointer, rhs: ManagedBufferPointer ) -> Bool { return lhs._address == rhs._address } } // FIXME: when our calling convention changes to pass self at +0, // inout should be dropped from the arguments to these functions. // FIXME(docs): isKnownUniquelyReferenced should check weak/unowned counts too, // but currently does not. rdar://problem/29341361 /// Returns a Boolean value indicating whether the given object is known to /// have a single strong reference. /// /// The `isKnownUniquelyReferenced(_:)` function is useful for implementing the /// copy-on-write optimization for the deep storage of value types: /// /// mutating func update(withValue value: T) { /// if !isKnownUniquelyReferenced(&myStorage) { /// myStorage = self.copiedStorage() /// } /// myStorage.update(withValue: value) /// } /// /// Use care when calling `isKnownUniquelyReferenced(_:)` from within a Boolean /// expression. In debug builds, an instance in the left-hand side of a `&&` /// or `||` expression may still be referenced when evaluating the right-hand /// side, inflating the instance's reference count. For example, this version /// of the `update(withValue)` method will re-copy `myStorage` on every call: /// /// // Copies too frequently: /// mutating func badUpdate(withValue value: T) { /// if myStorage.shouldCopy || !isKnownUniquelyReferenced(&myStorage) { /// myStorage = self.copiedStorage() /// } /// myStorage.update(withValue: value) /// } /// /// To avoid this behavior, swap the call `isKnownUniquelyReferenced(_:)` to /// the left-hand side or store the result of the first expression in a local /// constant: /// /// mutating func goodUpdate(withValue value: T) { /// let shouldCopy = myStorage.shouldCopy /// if shouldCopy || !isKnownUniquelyReferenced(&myStorage) { /// myStorage = self.copiedStorage() /// } /// myStorage.update(withValue: value) /// } /// /// `isKnownUniquelyReferenced(_:)` checks only for strong references to the /// given object---if `object` has additional weak or unowned references, the /// result may still be `true`. Because weak and unowned references cannot be /// the only reference to an object, passing a weak or unowned reference as /// `object` always results in `false`. /// /// If the instance passed as `object` is being accessed by multiple threads /// simultaneously, this function may still return `true`. Therefore, you must /// only call this function from mutating methods with appropriate thread /// synchronization. That will ensure that `isKnownUniquelyReferenced(_:)` /// only returns `true` when there is really one accessor, or when there is a /// race condition, which is already undefined behavior. /// /// - Parameter object: An instance of a class. This function does *not* modify /// `object`; the use of `inout` is an implementation artifact. /// - Returns: `true` if `object` is known to have a single strong reference; /// otherwise, `false`. @inlinable public func isKnownUniquelyReferenced<T : AnyObject>(_ object: inout T) -> Bool { return _isUnique(&object) } /// Returns a Boolean value indicating whether the given object is known to /// have a single strong reference. /// /// The `isKnownUniquelyReferenced(_:)` function is useful for implementing the /// copy-on-write optimization for the deep storage of value types: /// /// mutating func update(withValue value: T) { /// if !isKnownUniquelyReferenced(&myStorage) { /// myStorage = self.copiedStorage() /// } /// myStorage.update(withValue: value) /// } /// /// `isKnownUniquelyReferenced(_:)` checks only for strong references to the /// given object---if `object` has additional weak or unowned references, the /// result may still be `true`. Because weak and unowned references cannot be /// the only reference to an object, passing a weak or unowned reference as /// `object` always results in `false`. /// /// If the instance passed as `object` is being accessed by multiple threads /// simultaneously, this function may still return `true`. Therefore, you must /// only call this function from mutating methods with appropriate thread /// synchronization. That will ensure that `isKnownUniquelyReferenced(_:)` /// only returns `true` when there is really one accessor, or when there is a /// race condition, which is already undefined behavior. /// /// - Parameter object: An instance of a class. This function does *not* modify /// `object`; the use of `inout` is an implementation artifact. /// - Returns: `true` if `object` is known to have a single strong reference; /// otherwise, `false`. If `object` is `nil`, the return value is `false`. @inlinable public func isKnownUniquelyReferenced<T : AnyObject>( _ object: inout T? ) -> Bool { return _isUnique(&object) }
apache-2.0
68f8174db83a2cfe74ca154020ead8da
36.228956
98
0.692276
4.728245
false
false
false
false
wfleming/SwiftLint
Source/swiftlint/Commands/RulesCommand.swift
2
3444
// // RulesCommand.swift // SwiftLint // // Created by Chris Eidhof on 20/05/15. // Copyright (c) 2015 Realm. All rights reserved. // import Commandant import Result import SwiftLintFramework import SwiftyTextTable private let violationMarker = "↓" struct RulesCommand: CommandType { let verb = "rules" let function = "Display the list of rules and their identifiers" func run(options: RulesOptions) -> Result<(), CommandantError<()>> { if let ruleID = options.ruleID { guard let rule = masterRuleList.list[ruleID] else { return .Failure(.UsageError(description: "No rule with identifier: \(ruleID)")) } printRuleDescript(rule.description) return .Success() } let configuration = Configuration(commandLinePath: options.configurationFile) print(TextTable(ruleList: masterRuleList, configuration: configuration).render()) return .Success() } private func printRuleDescript(desc: RuleDescription) { print("\(desc.consoleDescription)") if !desc.triggeringExamples.isEmpty { func indent(string: String) -> String { return string.componentsSeparatedByString("\n") .map { " \($0)" } .joinWithSeparator("\n") } print("\nTriggering Examples (violation is marked with '\(violationMarker)'):") for (index, example) in desc.triggeringExamples.enumerate() { print("\nExample #\(index + 1)\n\n\(indent(example))") } } } } struct RulesOptions: OptionsType { private let ruleID: String? private let configurationFile: String static func create(configurationFile: String) -> (ruleID: String) -> RulesOptions { return { ruleID in self.init(ruleID: (ruleID.isEmpty ? nil : ruleID), configurationFile: configurationFile) } } // swiftlint:disable:next line_length static func evaluate(mode: CommandMode) -> Result<RulesOptions, CommandantError<CommandantError<()>>> { return create <*> mode <| configOption <*> mode <| Argument(defaultValue: "", usage: "the rule identifier to display description for") } } // MARK: - SwiftyTextTable extension TextTable { init(ruleList: RuleList, configuration: Configuration) { let columns = [ TextTableColumn(header: "identifier"), TextTableColumn(header: "opt-in"), TextTableColumn(header: "correctable"), TextTableColumn(header: "enabled in your config"), TextTableColumn(header: "configuration") ] self.init(columns: columns) let sortedRules = ruleList.list.sort { $0.0 < $1.0 } for (ruleID, ruleType) in sortedRules { let rule = ruleType.init() let configuredRule: Rule? = { for rule in configuration.rules where rule.dynamicType.description.identifier == ruleID { return rule } return nil }() addRow(ruleID, (rule is OptInRule) ? "yes" : "no", (rule is CorrectableRule) ? "yes" : "no", configuredRule != nil ? "yes" : "no", (configuredRule ?? rule).configurationDescription ) } } }
mit
246d7abd9bd099c6fd59f759be12e73d
33.079208
107
0.586287
4.734525
false
true
false
false
startupthekid/Partybus
Partybus/Models/Bus.swift
1
709
// // Bus.swift // Partybus // // Created by Brendan Conron on 11/16/16. // Copyright © 2016 Swoopy Studios. All rights reserved. // import ObjectMapper struct Bus: ImmutableMappable { let identifier: String let latitude: Double let longitude: Double let header: Int let lastStop: Int let updatedAt: TimeInterval init(map: Map) throws { identifier = try map.value("id", using: TransformOf(fromJSON: { "\($0)" }, toJSON: { Int($0 ?? "") })) latitude = try map.value("lat") longitude = try map.value("lon") header = try map.value("header") lastStop = try map.value("lastStop") updatedAt = try map.value("lastUpdate") } }
mit
f210851af3adbc04001de1694e463709
23.413793
110
0.615819
3.746032
false
false
false
false
wikimedia/wikipedia-ios
Wikipedia/Code/OldTalkPageFetcher.swift
1
7161
class NetworkTalkPage { let url: URL let topics: [NetworkTopic] var revisionId: Int? let displayTitle: String init(url: URL, topics: [NetworkTopic], revisionId: Int?, displayTitle: String) { self.url = url self.topics = topics self.revisionId = revisionId self.displayTitle = displayTitle } } class NetworkBase: Codable { let topics: [NetworkTopic] } class NetworkTopic: NSObject, Codable { let html: String let replies: [NetworkReply] let sectionID: Int let shas: NetworkTopicShas var sort: Int? enum CodingKeys: String, CodingKey { case html case shas case replies case sectionID = "id" } } class NetworkTopicShas: Codable { let html: String let indicator: String } class NetworkReply: NSObject, Codable { let html: String let depth: Int16 let sha: String var sort: Int! enum CodingKeys: String, CodingKey { case html case depth case sha } } import Foundation import WMF enum OldTalkPageType: Int { case user case article func canonicalNamespacePrefix(for siteURL: URL) -> String? { let namespace: PageNamespace switch self { case .article: namespace = PageNamespace.talk case .user: namespace = PageNamespace.userTalk } return namespace.canonicalName + ":" } func titleWithCanonicalNamespacePrefix(title: String, siteURL: URL) -> String { return (canonicalNamespacePrefix(for: siteURL) ?? "") + title } func titleWithoutNamespacePrefix(title: String) -> String { if let firstColon = title.range(of: ":") { var returnTitle = title returnTitle.removeSubrange(title.startIndex..<firstColon.upperBound) return returnTitle } else { return title } } func urlTitle(for title: String) -> String? { assert(title.contains(":"), "Title must already be prefixed with namespace.") return title.denormalizedPageTitle } } enum OldTalkPageFetcherError: Error { case talkPageDoesNotExist } class OldTalkPageFetcher: Fetcher { private let sectionUploader = WikiTextSectionUploader() func addTopic(to title: String, siteURL: URL, subject: String, body: String, completion: @escaping (Result<[AnyHashable : Any], Error>) -> Void) { guard let url = postURL(for: title, siteURL: siteURL) else { completion(.failure(RequestError.invalidParameters)) return } sectionUploader.addSection(withSummary: subject, text: body, forArticleURL: url) { (result, error) in if let error = error { completion(.failure(error)) return } guard let result = result else { completion(.failure(RequestError.unexpectedResponse)) return } completion(.success(result)) } } func addReply(to topic: TalkPageTopic, title: String, siteURL: URL, body: String, completion: @escaping (Result<[AnyHashable : Any], Error>) -> Void) { guard let url = postURL(for: title, siteURL: siteURL) else { completion(.failure(RequestError.invalidParameters)) return } // todo: should sectionID in CoreData be string? sectionUploader.append(toSection: String(topic.sectionID), text: body, forArticleURL: url) { (result, error) in if let error = error { completion(.failure(error)) return } guard let result = result else { completion(.failure(RequestError.unexpectedResponse)) return } completion(.success(result)) } } func fetchTalkPage(urlTitle: String, displayTitle: String, siteURL: URL, revisionID: Int?, completion: @escaping (Result<NetworkTalkPage, Error>) -> Void) { guard let taskURLWithRevID = getURL(for: urlTitle, siteURL: siteURL, revisionID: revisionID), let taskURLWithoutRevID = getURL(for: urlTitle, siteURL: siteURL, revisionID: nil) else { completion(.failure(RequestError.invalidParameters)) return } // todo: track tasks/cancel session.jsonDecodableTask(with: taskURLWithRevID) { (networkBase: NetworkBase?, response: URLResponse?, error: Error?) in if let statusCode = (response as? HTTPURLResponse)?.statusCode, statusCode == 404 { completion(.failure(OldTalkPageFetcherError.talkPageDoesNotExist)) return } if let error = error { completion(.failure(error)) return } guard let networkBase = networkBase else { completion(.failure(RequestError.unexpectedResponse)) return } // update sort // todo performance: should we go back to NSOrderedSets or move sort up into endpoint? for (topicIndex, topic) in networkBase.topics.enumerated() { topic.sort = topicIndex for (replyIndex, reply) in topic.replies.enumerated() { reply.sort = replyIndex } } let talkPage = NetworkTalkPage(url: taskURLWithoutRevID, topics: networkBase.topics, revisionId: revisionID, displayTitle: displayTitle) completion(.success(talkPage)) } } func getURL(for urlTitle: String, siteURL: URL) -> URL? { return getURL(for: urlTitle, siteURL: siteURL, revisionID: nil) } } // MARK: Private private extension OldTalkPageFetcher { func getURL(for urlTitle: String, siteURL: URL, revisionID: Int?) -> URL? { assert(urlTitle.contains(":"), "Title must already be prefixed with namespace.") guard siteURL.host != nil, let percentEncodedUrlTitle = urlTitle.percentEncodedPageTitleForPathComponents else { return nil } var pathComponents = ["page", "talk", percentEncodedUrlTitle] if let revisionID = revisionID { pathComponents.append(String(revisionID)) } guard let taskURL = configuration.pageContentServiceAPIURLForURL(siteURL, appending: pathComponents) else { return nil } return taskURL } func postURL(for urlTitle: String, siteURL: URL) -> URL? { assert(urlTitle.contains(":"), "Title must already be prefixed with namespace.") guard let host = siteURL.host else { return nil } return configuration.articleURLForHost(host, languageVariantCode: siteURL.wmf_languageVariantCode, appending: [urlTitle]) } }
mit
ee2919d0e8ea7256079c902dae7b9bfe
30.546256
160
0.58679
5.07153
false
false
false
false
MA806P/SwiftDemo
Developing_iOS_11_Apps_with_Swift/SwiftDemo/SwiftDemo/PlayingCard/PlayingCard.swift
1
1906
// // PlayingCard.swift // SwiftDemo // // Created by 159CaiMini02 on 2018/1/3. // Copyright © 2018年 MYZ. All rights reserved. // import Foundation struct PlayingCard: CustomStringConvertible { var description: String { return "\(rank)\(suit)" } var suit: Suit var rank: Rank enum Suit: String, CustomStringConvertible { case spades = "♠️" case hearts = "♥️" case clubs = "♣️" case diamonds = "♦️" static var all = [Suit.spades, .hearts, .clubs, .diamonds] var description: String { switch self { case .spades: return "♠️" case .hearts: return "♥️" case .clubs: return "♣️" case .diamonds: return "♦️" } } } enum Rank: CustomStringConvertible { case ace case face(String) case numeric(Int) var order: Int { switch self { case .ace: return 1 case .numeric(let pips): return pips case .face(let kind) where kind == "J": return 11 case .face(let kind) where kind == "Q": return 12 case .face(let kind) where kind == "K": return 13 default: return 0 } } static var all: [Rank] { var allRanks = [Rank.ace] for pips in 2...10 { allRanks.append(Rank.numeric(pips)) } allRanks += [Rank.face("J"), .face("Q"), .face("K")] return allRanks } var description: String { switch self { case .ace: return "A" case .numeric(let pips): return String(pips) case .face(let kind): return kind } } } }
apache-2.0
a3c3c2a1ac7987b216d82fca2ab673cd
23.298701
66
0.467664
4.371495
false
false
false
false
exercism/xswift
exercises/run-length-encoding/Sources/RunLengthEncoding/RunLengthEncodingExample.swift
2
1480
struct RunLengthEncoding { static func encode(_ input: String) -> String { var result = "" var lastCharacter = input.first! var count = 0 for (index, character) in input.enumerated() { if character == lastCharacter { count += 1 } func addCharacter() { if count == 1 { result += "\(lastCharacter)" } else { result += "\(count)\(lastCharacter)" } lastCharacter = character count = 1 } if character != lastCharacter { addCharacter() } let isFinal = index == input.count - 1 if isFinal { addCharacter() } } return result } static func decode(_ input: String) -> String { var result = "" var multiplier: Int? for character in input { if let number = Int(String(character)) { if let currentMultiplier = multiplier { multiplier = currentMultiplier * 10 + number } else { multiplier = number } } else { for _ in 1...(multiplier ?? 1) { result += "\(character)" } multiplier = nil } } return result } }
mit
37f0538aaa816f37e75abe28c1b39ff6
22.870968
64
0.413514
5.943775
false
false
false
false
russbishop/swift
stdlib/private/SwiftPrivateLibcExtras/Subprocess.swift
1
9818
//===--- Subprocess.swift -------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// import SwiftPrivate #if os(OSX) || os(iOS) || os(watchOS) || os(tvOS) import Darwin #elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android) import Glibc #endif // posix_spawn is not available on Android. #if !os(Android) // swift_posix_spawn isn't available in the public watchOS SDK, we sneak by the // unavailable attribute declaration here of the APIs that we need. // FIXME: Come up with a better way to deal with APIs that are pointers on some // platforms but not others. #if os(Linux) typealias swift_posix_spawn_file_actions_t = posix_spawn_file_actions_t #else typealias swift_posix_spawn_file_actions_t = posix_spawn_file_actions_t? #endif @_silgen_name("swift_posix_spawn_file_actions_init") func swift_posix_spawn_file_actions_init( _ file_actions: UnsafeMutablePointer<swift_posix_spawn_file_actions_t> ) -> CInt @_silgen_name("swift_posix_spawn_file_actions_destroy") func swift_posix_spawn_file_actions_destroy( _ file_actions: UnsafeMutablePointer<swift_posix_spawn_file_actions_t> ) -> CInt @_silgen_name("swift_posix_spawn_file_actions_addclose") func swift_posix_spawn_file_actions_addclose( _ file_actions: UnsafeMutablePointer<swift_posix_spawn_file_actions_t>, _ filedes: CInt) -> CInt @_silgen_name("swift_posix_spawn_file_actions_adddup2") func swift_posix_spawn_file_actions_adddup2( _ file_actions: UnsafeMutablePointer<swift_posix_spawn_file_actions_t>, _ filedes: CInt, _ newfiledes: CInt) -> CInt @_silgen_name("swift_posix_spawn") func swift_posix_spawn( _ pid: UnsafeMutablePointer<pid_t>?, _ file: UnsafePointer<Int8>, _ file_actions: UnsafePointer<swift_posix_spawn_file_actions_t>?, _ attrp: UnsafePointer<posix_spawnattr_t>?, _ argv: UnsafePointer<UnsafeMutablePointer<Int8>?>, _ envp: UnsafePointer<UnsafeMutablePointer<Int8>?>?) -> CInt #endif /// Calls POSIX `pipe()`. func posixPipe() -> (readFD: CInt, writeFD: CInt) { var fds: [CInt] = [ -1, -1 ] if pipe(&fds) != 0 { preconditionFailure("pipe() failed") } return (fds[0], fds[1]) } /// Start the same executable as a child process, redirecting its stdout and /// stderr. public func spawnChild(_ args: [String]) -> (pid: pid_t, stdinFD: CInt, stdoutFD: CInt, stderrFD: CInt) { // The stdout, stdin, and stderr from the child process will be redirected // to these pipes. let childStdout = posixPipe() let childStdin = posixPipe() let childStderr = posixPipe() #if os(Android) // posix_spawn isn't available on Android. Instead, we fork and exec. // To correctly communicate the exit status of the child process to this // (parent) process, we'll use this pipe. let childToParentPipe = posixPipe() let pid = fork() precondition(pid >= 0, "fork() failed") if pid == 0 { // pid of 0 means we are now in the child process. // Capture the output before executing the program. dup2(childStdout.writeFD, STDOUT_FILENO) dup2(childStdin.readFD, STDIN_FILENO) dup2(childStderr.writeFD, STDERR_FILENO) // Set the "close on exec" flag on the parent write pipe. This will // close the pipe if the execve() below successfully executes a child // process. let closeResult = fcntl(childToParentPipe.writeFD, F_SETFD, FD_CLOEXEC) let closeErrno = errno precondition( closeResult == 0, "Could not set the close behavior of the child-to-parent pipe; " + "errno: \(closeErrno)") // Start the executable. If execve() does not encounter an error, the // code after this block will never be executed, and the parent write pipe // will be closed. withArrayOfCStrings([Process.arguments[0]] + args) { execve(Process.arguments[0], $0, _getEnviron()) } // If execve() encountered an error, we write the errno encountered to the // parent write pipe. let errnoSize = sizeof(errno.dynamicType) var execveErrno = errno let writtenBytes = withUnsafePointer(&execveErrno) { write(childToParentPipe.writeFD, UnsafePointer($0), errnoSize) } let writeErrno = errno if writtenBytes > 0 && writtenBytes < errnoSize { // We were able to write some of our error, but not all of it. // FIXME: Retry in this case. preconditionFailure("Unable to write entire error to child-to-parent " + "pipe.") } else if writtenBytes == 0 { preconditionFailure("Unable to write error to child-to-parent pipe.") } else if writtenBytes < 0 { preconditionFailure("An error occurred when writing error to " + "child-to-parent pipe; errno: \(writeErrno)") } // Close the pipe when we're done writing the error. close(childToParentPipe.writeFD) } #else var fileActions = _make_posix_spawn_file_actions_t() if swift_posix_spawn_file_actions_init(&fileActions) != 0 { preconditionFailure("swift_posix_spawn_file_actions_init() failed") } // Close the write end of the pipe on the child side. if swift_posix_spawn_file_actions_addclose( &fileActions, childStdin.writeFD) != 0 { preconditionFailure("swift_posix_spawn_file_actions_addclose() failed") } // Remap child's stdin. if swift_posix_spawn_file_actions_adddup2( &fileActions, childStdin.readFD, STDIN_FILENO) != 0 { preconditionFailure("swift_posix_spawn_file_actions_adddup2() failed") } // Close the read end of the pipe on the child side. if swift_posix_spawn_file_actions_addclose( &fileActions, childStdout.readFD) != 0 { preconditionFailure("swift_posix_spawn_file_actions_addclose() failed") } // Remap child's stdout. if swift_posix_spawn_file_actions_adddup2( &fileActions, childStdout.writeFD, STDOUT_FILENO) != 0 { preconditionFailure("swift_posix_spawn_file_actions_adddup2() failed") } // Close the read end of the pipe on the child side. if swift_posix_spawn_file_actions_addclose( &fileActions, childStderr.readFD) != 0 { preconditionFailure("swift_posix_spawn_file_actions_addclose() failed") } // Remap child's stderr. if swift_posix_spawn_file_actions_adddup2( &fileActions, childStderr.writeFD, STDERR_FILENO) != 0 { preconditionFailure("swift_posix_spawn_file_actions_adddup2() failed") } var pid: pid_t = -1 var childArgs = args childArgs.insert(Process.arguments[0], at: 0) let interpreter = getenv("SWIFT_INTERPRETER") if interpreter != nil { if let invocation = String(validatingUTF8: interpreter!) { childArgs.insert(invocation, at: 0) } } let spawnResult = withArrayOfCStrings(childArgs) { swift_posix_spawn( &pid, childArgs[0], &fileActions, nil, $0, _getEnviron()) } if spawnResult != 0 { print(String(cString: strerror(spawnResult))) preconditionFailure("swift_posix_spawn() failed") } if swift_posix_spawn_file_actions_destroy(&fileActions) != 0 { preconditionFailure("swift_posix_spawn_file_actions_destroy() failed") } #endif // Close the read end of the pipe on the parent side. if close(childStdin.readFD) != 0 { preconditionFailure("close() failed") } // Close the write end of the pipe on the parent side. if close(childStdout.writeFD) != 0 { preconditionFailure("close() failed") } // Close the write end of the pipe on the parent side. if close(childStderr.writeFD) != 0 { preconditionFailure("close() failed") } return (pid, childStdin.writeFD, childStdout.readFD, childStderr.readFD) } #if !os(Android) #if os(Linux) internal func _make_posix_spawn_file_actions_t() -> swift_posix_spawn_file_actions_t { return posix_spawn_file_actions_t() } #else internal func _make_posix_spawn_file_actions_t() -> swift_posix_spawn_file_actions_t { return nil } #endif #endif internal func _signalToString(_ signal: Int) -> String { switch CInt(signal) { case SIGILL: return "SIGILL" case SIGTRAP: return "SIGTRAP" case SIGABRT: return "SIGABRT" case SIGFPE: return "SIGFPE" case SIGBUS: return "SIGBUS" case SIGSEGV: return "SIGSEGV" case SIGSYS: return "SIGSYS" default: return "SIG???? (\(signal))" } } public enum ProcessTerminationStatus : CustomStringConvertible { case exit(Int) case signal(Int) public var description: String { switch self { case .exit(let status): return "Exit(\(status))" case .signal(let signal): return "Signal(\(_signalToString(signal)))" } } } public func posixWaitpid(_ pid: pid_t) -> ProcessTerminationStatus { var status: CInt = 0 if waitpid(pid, &status, 0) < 0 { preconditionFailure("waitpid() failed") } if (WIFEXITED(status)) { return .exit(Int(WEXITSTATUS(status))) } if (WIFSIGNALED(status)) { return .signal(Int(WTERMSIG(status))) } preconditionFailure("did not understand what happened to child process") } #if os(OSX) || os(iOS) || os(watchOS) || os(tvOS) @_silgen_name("swift_SwiftPrivateLibcExtras_NSGetEnviron") func _NSGetEnviron() -> UnsafeMutablePointer<UnsafeMutablePointer<UnsafeMutablePointer<CChar>?>> #endif internal func _getEnviron() -> UnsafeMutablePointer<UnsafeMutablePointer<CChar>?> { #if os(OSX) || os(iOS) || os(watchOS) || os(tvOS) return _NSGetEnviron().pointee #elseif os(FreeBSD) return environ #elseif os(PS4) return environ #elseif os(Android) return environ #else return __environ #endif }
apache-2.0
2f3b15988a316455bfccabd997ec7e25
32.281356
96
0.686494
3.761686
false
false
false
false
yonadev/yona-app-ios
Yona/Yona/SMSValidPasscodeLogin/Passcode/SetPasscodeViewController.swift
1
4624
// // SetPasscodeViewController.swift // Yona // // Created by Chandan on 04/04/16. // Copyright © 2016 Yona. All rights reserved. // import UIKit class SetPasscodeViewController: UIViewController { @IBOutlet var progressView:UIView! @IBOutlet var codeView:UIView! @IBOutlet var headerTitleLabel: UILabel! @IBOutlet var infoLabel: UILabel! @IBOutlet var scrollView: UIScrollView! @IBOutlet var gradientView: GradientView! var passcodeString: String? private var colorX : UIColor = UIColor.yiWhiteColor() var posi:CGFloat = 0.0 private var codeInputView: CodeInputView? override func viewDidLoad() { super.viewDidLoad() //Nav bar Back button. self.navigationItem.hidesBackButton = true dispatch_async(dispatch_get_main_queue(), { self.gradientView.colors = [UIColor.yiGrapeTwoColor(), UIColor.yiGrapeTwoColor()] }) let viewWidth = self.view.frame.size.width let customView=UIView(frame: CGRectMake(0, 0, ((viewWidth-60)/3)*2, 2)) customView.backgroundColor=UIColor.yiDarkishPinkColor() self.progressView.addSubview(customView) self.navigationController?.setNavigationBarHidden(true, animated: false) self.infoLabel.text = NSLocalizedString("passcode.user.infomessage", comment: "") self.headerTitleLabel.text = NSLocalizedString("passcode.user.headerTitle", comment: "").uppercaseString UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.LightContent, animated: false) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) codeInputView = CodeInputView(frame: CGRect(x: 0, y: 0, width: 260, height: 55)) if codeInputView != nil { codeInputView!.delegate = self codeInputView?.secure = true codeView.addSubview(codeInputView!) } //keyboard functions let notificationCenter = NSNotificationCenter.defaultCenter() notificationCenter.addObserver(self, selector: Selector.keyboardWasShown, name: UIKeyboardDidShowNotification, object: nil) notificationCenter.addObserver(self, selector: Selector.keyboardWillBeHidden, name: UIKeyboardWillHideNotification, object: nil) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) codeInputView!.becomeFirstResponder() } override func viewWillDisappear(animated: Bool) { super.viewDidDisappear(animated) codeInputView!.resignFirstResponder() NSNotificationCenter.defaultCenter().removeObserver(self) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == R.segue.setPasscodeViewController.confirmPasscodeSegue.identifier, let vc = segue.destinationViewController as? ConfirmPasscodeViewController { vc.passcode = passcodeString } } } extension SetPasscodeViewController: KeyboardProtocol { func keyboardWasShown (notification: NSNotification) { let viewHeight = self.view.frame.size.height let info : NSDictionary = notification.userInfo! let keyboardSize: CGSize = info.objectForKey(UIKeyboardFrameBeginUserInfoKey)!.CGRectValue.size let keyboardInset = keyboardSize.height - viewHeight/3 let pos = (codeView?.frame.origin.y)! + (codeView?.frame.size.height)! + 30.0 if (pos > (viewHeight-keyboardSize.height)) { posi = pos-(viewHeight-keyboardSize.height) self.view.frame.origin.y -= posi } else { scrollView.setContentOffset(CGPointMake(0, keyboardInset), animated: true) } } func keyboardWillBeHidden(notification: NSNotification) { if let position = resetTheView(posi, scrollView: scrollView, view: view) { posi = position } } } extension SetPasscodeViewController: CodeInputViewDelegate { func codeInputView(codeInputView: CodeInputView, didFinishWithCode code: String) { passcodeString = code performSegueWithIdentifier(R.segue.setPasscodeViewController.confirmPasscodeSegue, sender: self) } } private extension Selector { static let keyboardWasShown = #selector(SetPasscodeViewController.keyboardWasShown(_:)) static let keyboardWillBeHidden = #selector(SetPasscodeViewController.keyboardWillBeHidden(_:)) }
mpl-2.0
2381cafe09330b57269db01b6578d09f
35.401575
136
0.679429
5.363109
false
false
false
false
peferron/algo
EPI/Recursion/Generate all nonattacking placements of n-Queens/swift/main.swift
1
1102
public typealias Placement = [Int] public func nonAttackingPlacements(n: Int) -> [Placement] { return nonAttackingPlacements(n: n, extending: []) } private func nonAttackingPlacements(n: Int, extending partial: Placement) -> [Placement] { if partial.count == n { return [partial] } let row = partial.count return (0..<n).flatMap { col -> [Placement] in if isAttacking(position: (row, col), placement: partial) { return [] } let extended = partial + [col] return nonAttackingPlacements(n: n, extending: extended) } } private func isAttacking(position: (row: Int, col: Int), placement: Placement) -> Bool { return placement.enumerated().contains { placementPosition in isAttacking(position: position, otherPosition: placementPosition) } } private func isAttacking(position a: (row: Int, col: Int), otherPosition b: (row: Int, col: Int)) -> Bool { return a.row == b.row || // Row attack. a.col == b.col || // Column attack. abs(a.row - b.row) == abs(a.col - b.col) // Diagonal attack. }
mit
7716adabd95e65305c0d5883e94ca052
32.393939
107
0.634301
3.613115
false
false
false
false
iamyuiwong/swift-sqlite
SwiftSQLiteDEMO/SwiftSQLiteDEMO/AppDelegate.swift
1
5833
// // AppDelegate.swift // SwiftSQLiteDEMO // // Created by 黄锐 on 15/10/11. // Copyright © 2015年 yuiwong. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "yuiwong.SwiftSQLiteDEMO" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("SwiftSQLiteDEMO", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite") var failureReason = "There was an error creating or loading the application's saved data." do { try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
lgpl-3.0
8027f4cccac5795b41cff1cf848732cb
51.486486
288
0.753519
5.394444
false
false
false
false
loudnate/Loop
WatchApp Extension/Scenes/GlucoseChartValueHashable.swift
1
2352
// // GlucoseChartValueHashable.swift // WatchApp Extension // // Copyright © 2018 LoopKit Authors. All rights reserved. // import LoopKit import HealthKit protocol GlucoseChartValueHashable { var start: Date { get } var end: Date { get } var min: HKQuantity { get } var max: HKQuantity { get } var chartHashValue: Int { get } } extension GlucoseChartValueHashable { var chartHashValue: Int { var hashValue = start.timeIntervalSinceReferenceDate.hashValue hashValue ^= end.timeIntervalSince(start).hashValue // HKQuantity.hashValue returns 0, so we need to convert hashValue ^= min.doubleValue(for: .milligramsPerDeciliter).hashValue if min != max { hashValue ^= max.doubleValue(for: .milligramsPerDeciliter).hashValue } return hashValue } } extension SampleValue { var start: Date { return startDate } var end: Date { return endDate } var min: Double { return quantity.doubleValue(for: .milligramsPerDeciliter) } var max: Double { return quantity.doubleValue(for: .milligramsPerDeciliter) } var chartHashValue: Int { var hashValue = start.timeIntervalSinceReferenceDate.hashValue hashValue ^= end.timeIntervalSince(start).hashValue hashValue ^= min.hashValue return hashValue } } extension AbsoluteScheduleValue: GlucoseChartValueHashable where T == ClosedRange<HKQuantity> { var start: Date { return startDate } var end: Date { return endDate } var min: HKQuantity { return value.lowerBound } var max: HKQuantity { return value.upperBound } } struct TemporaryScheduleOverrideHashable: GlucoseChartValueHashable { let override: TemporaryScheduleOverride init?(_ override: TemporaryScheduleOverride) { guard override.settings.targetRange != nil else { return nil } self.override = override } var start: Date { return override.activeInterval.start } var end: Date { return override.activeInterval.end } var min: HKQuantity { return override.settings.targetRange!.lowerBound } var max: HKQuantity { return override.settings.targetRange!.upperBound } }
apache-2.0
c420329217dd114214702d8a7038185e
21.605769
95
0.654615
4.949474
false
false
false
false
icanzilb/SwiftSpinner
Sources/SwiftSpinner/SwiftSpinner.swift
1
19849
// // Copyright (c) 2015-present Marin Todorov, Underplot ltd. // This code is distributed under the terms and conditions of the MIT license. // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // import UIKit public class SwiftSpinner: UIView { fileprivate static let standardAnimationDuration = 0.33 // MARK: - Singleton // // Access the singleton instance // public static let shared = SwiftSpinner(frame: CGRect.zero) // MARK: - Init /// Init /// /// - Parameter frame: the view's frame public override init(frame: CGRect) { currentTitleFont = defaultTitleFont // By default we initialize to the same. super.init(frame: frame) blurEffect = UIBlurEffect(style: blurEffectStyle) blurView = UIVisualEffectView() addSubview(blurView) vibrancyView = UIVisualEffectView(effect: UIVibrancyEffect(blurEffect: blurEffect)) addSubview(vibrancyView) let titleScale: CGFloat = 0.85 titleLabel.frame.size = CGSize(width: frameSize.width * titleScale, height: frameSize.height * titleScale) titleLabel.font = currentTitleFont titleLabel.numberOfLines = 0 titleLabel.textAlignment = .center titleLabel.lineBreakMode = .byWordWrapping titleLabel.adjustsFontSizeToFitWidth = true titleLabel.textColor = UIColor.white blurView.contentView.addSubview(titleLabel) blurView.contentView.addSubview(vibrancyView) outerCircleView.frame.size = frameSize outerCircle.path = UIBezierPath(ovalIn: CGRect(x: 0.0, y: 0.0, width: frameSize.width, height: frameSize.height)).cgPath outerCircle.lineWidth = 8.0 outerCircle.strokeStart = 0.0 outerCircle.strokeEnd = 0.45 outerCircle.lineCap = .round outerCircle.fillColor = UIColor.clear.cgColor outerCircle.strokeColor = outerCircleDefaultColor outerCircleView.layer.addSublayer(outerCircle) outerCircle.strokeStart = 0.0 outerCircle.strokeEnd = 1.0 blurView.contentView.addSubview(outerCircleView) innerCircleView.frame.size = frameSize let innerCirclePadding: CGFloat = 12 innerCircle.path = UIBezierPath(ovalIn: CGRect(x: innerCirclePadding, y: innerCirclePadding, width: frameSize.width - 2*innerCirclePadding, height: frameSize.height - 2*innerCirclePadding)).cgPath innerCircle.lineWidth = 4.0 innerCircle.strokeStart = 0.5 innerCircle.strokeEnd = 0.9 innerCircle.lineCap = .round innerCircle.fillColor = UIColor.clear.cgColor innerCircle.strokeColor = innerCircleDefaultColor innerCircleView.layer.addSublayer(innerCircle) innerCircle.strokeStart = 0.0 innerCircle.strokeEnd = 1.0 blurView.contentView.addSubview(innerCircleView) isUserInteractionEnabled = true } public override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { return self } // MARK: - Public interface /// The label with the spinner's title public lazy var titleLabel = UILabel() /// The label with the spinner's subtitle public var subtitleLabel: UILabel? private let outerCircleDefaultColor = UIColor.white.cgColor fileprivate var _outerColor: UIColor? /// The color of the outer circle public var outerColor: UIColor? { get { return _outerColor } set(newColor) { _outerColor = newColor outerCircle.strokeColor = newColor?.cgColor ?? outerCircleDefaultColor } } private let innerCircleDefaultColor = UIColor.gray.cgColor fileprivate var _innerColor: UIColor? /// The color of the inner circle public var innerColor: UIColor? { get { return _innerColor } set(newColor) { _innerColor = newColor innerCircle.strokeColor = newColor?.cgColor ?? innerCircleDefaultColor } } /// Custom superview for the spinner private static weak var customSuperview: UIView? private static func containerView() -> UIView? { #if EXTENSION return customSuperview #else if #available(iOS 13, *) { return customSuperview ?? UIApplication.shared.windows.first{ $0.isKeyWindow } } else { return customSuperview ?? UIApplication.shared.keyWindow } #endif } /// Custom container for the spinner public class func useContainerView(_ sv: UIView?) { customSuperview = sv } /// Show the blurred background. If false the background content will be visible. Defaults to true. public static var showBlurBackground: Bool = true /// Show the spinner activity on screen, if visible only update the title /// /// - Parameters: /// - title: The title shown under the spiiner /// - animated: Animate the spinner. Defaults to true /// - Returns: The instance of the spinner @discardableResult public class func show(_ title: String, animated: Bool = true) -> SwiftSpinner { let spinner = SwiftSpinner.shared spinner.clearTapHandler() spinner.updateFrame() if spinner.superview == nil { // Show the spinner spinner.blurView.contentView.alpha = 0 guard let containerView = containerView() else { #if EXTENSION fatalError("\n`containerView` is `nil`. `UIApplication.keyWindow` is not available in extensions and so, a containerView is required. Use `useContainerView` to set a view where the spinner should show") #else fatalError("\n`UIApplication.keyWindow` is `nil`. If you're trying to show a spinner from your view controller's `viewDidLoad` method, do that from `viewWillAppear` instead. Alternatively use `useContainerView` to set a view where the spinner should show") #endif } containerView.addSubview(spinner) UIView.animate(withDuration: SwiftSpinner.standardAnimationDuration, delay: 0.0, options: .curveEaseOut, animations: { spinner.blurView.contentView.alpha = 1 spinner.blurView.effect = showBlurBackground ? spinner.blurEffect : .none }, completion: nil) #if os(iOS) // Orientation change observer NotificationCenter.default.addObserver( spinner, selector: #selector(SwiftSpinner.orientationChangedAction), name: UIDevice.orientationDidChangeNotification, object: nil) #endif } else if spinner.dismissing { // If the spinner is hiding, delay the next show. The duration is set to double the standard animation to avoid an edge case that caused endless laoding. See #125 show(delay: SwiftSpinner.standardAnimationDuration, title: title, animated: true) } spinner.title = title spinner.animating = animated return spinner } /// Show the spinner activity on screen with duration, if visible only update the title /// /// - Parameters: /// - duration: The duration of the show animation /// - title: The title shown under the spinner /// - animated: Animate the spinner. Defaults to true /// - completion: An optional completion handler /// - Returns: The instance of the spinner @discardableResult public class func show(duration: Double, title: String, animated: Bool = true, completion: (() -> ())? = nil) -> SwiftSpinner { let spinner = SwiftSpinner.show(title, animated: animated) spinner.delay(duration) { SwiftSpinner.hide { completion?() } } return spinner } private static var delayedTokens = [String]() /// Show the spinner activity on screen, after delay. If new call to show, showWithDelay or hide is maked before execution this call is discarded /// /// - Parameters: /// - delay: The delay time /// - title: The title shown under the spinner /// - animated: Animate the spinner. Defaults to true public class func show(delay: Double, title: String, animated: Bool = true) { let token = UUID().uuidString delayedTokens.append(token) SwiftSpinner.shared.delay(delay, completion: { if let index = delayedTokens.firstIndex(of: token) { delayedTokens.remove(at: index) SwiftSpinner.show(title, animated: animated) } }) } /// Show the spinner with the outer circle representing progress (0 to 1) /// /// - Parameters: /// - progress: The progress percentage. Values between 0 and 1 /// - title: The title shown under the spinner /// - Returns: The instance of the spinner @discardableResult public class func show(progress: Double, title: String) -> SwiftSpinner { let spinner = SwiftSpinner.show(title, animated: false) spinner.outerCircle.strokeEnd = CGFloat(progress) return spinner } /// If set to true, hiding a spinner causes scheduled spinners to be canceled public static var hideCancelsScheduledSpinners = true /// Hide the spinner /// /// - Parameter completion: A closure called upon completion public class func hide(_ completion: (() -> Void)? = nil) { let spinner = SwiftSpinner.shared spinner.dismissing = true NotificationCenter.default.removeObserver(spinner) if hideCancelsScheduledSpinners { delayedTokens.removeAll() } DispatchQueue.main.async(execute: { spinner.clearTapHandler() if spinner.superview == nil { spinner.dismissing = false return } UIView.animate(withDuration: SwiftSpinner.standardAnimationDuration, delay: 0.0, options: .curveEaseOut, animations: { spinner.blurView.contentView.alpha = 0 spinner.blurView.effect = nil }, completion: {_ in spinner.blurView.contentView.alpha = 1 spinner.removeFromSuperview() spinner.titleLabel.text = nil spinner.dismissing = false completion?() }) spinner.animating = false }) } /// Set the default title font /// /// - Parameter font: The title font public class func setTitleFont(_ font: UIFont?) { let spinner = SwiftSpinner.shared spinner.currentTitleFont = font ?? spinner.defaultTitleFont spinner.titleLabel.font = font ?? spinner.defaultTitleFont } /// Set the default title color /// /// - Parameter color: The title color public class func setTitleColor(_ color: UIColor?) { let spinner = SwiftSpinner.shared spinner.titleLabel.textColor = color ?? spinner.defaultTitleColor } /// The spinner title public var title: String = "" { didSet { let spinner = SwiftSpinner.shared guard spinner.animating else { spinner.titleLabel.transform = CGAffineTransform.identity spinner.titleLabel.alpha = 1.0 spinner.titleLabel.text = self.title return } UIView.animate(withDuration: 0.15, delay: 0.0, options: .curveEaseOut, animations: { spinner.titleLabel.transform = CGAffineTransform(scaleX: 0.75, y: 0.75) spinner.titleLabel.alpha = 0.2 }, completion: { _ in spinner.titleLabel.text = self.title UIView.animate(withDuration: 0.35, delay: 0.0, usingSpringWithDamping: 0.35, initialSpringVelocity: 0.0, options: [], animations: { spinner.titleLabel.transform = CGAffineTransform.identity spinner.titleLabel.alpha = 1.0 }, completion: nil) }) } } /// Observe the view frame and update the subviews layout public override var frame: CGRect { didSet { if frame == CGRect.zero { return } blurView.frame = bounds vibrancyView.frame = blurView.bounds titleLabel.center = vibrancyView.center outerCircleView.center = vibrancyView.center innerCircleView.center = vibrancyView.center layoutSubtitle() } } /// Start the spinning animation public var animating: Bool = false { willSet (shouldAnimate) { if shouldAnimate && !animating { spinInner() spinOuter() } } didSet { // Update UI if animating { self.outerCircle.strokeStart = 0.0 self.outerCircle.strokeEnd = 0.45 self.innerCircle.strokeStart = 0.5 self.innerCircle.strokeEnd = 0.9 } else { self.outerCircle.strokeStart = 0.0 self.outerCircle.strokeEnd = 1.0 self.innerCircle.strokeStart = 0.0 self.innerCircle.strokeEnd = 1.0 } } } /// Tap handler /// /// - Parameters: /// - tap: The tap handler closure /// - subtitleText: The optional subtitle public func addTapHandler(_ tap: @escaping (() -> Void), subtitle subtitleText: String? = nil) { clearTapHandler() //vibrancyView.contentView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: Selector("didTapSpinner"))) tapHandler = tap if subtitleText != nil { subtitleLabel = UILabel() if let subtitle = subtitleLabel { subtitle.text = subtitleText subtitle.font = UIFont(name: self.currentTitleFont.familyName, size: currentTitleFont.pointSize * 0.8) subtitle.textColor = UIColor.white subtitle.numberOfLines = 0 subtitle.textAlignment = .center subtitle.lineBreakMode = .byWordWrapping layoutSubtitle() vibrancyView.contentView.addSubview(subtitle) } } } public override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesBegan(touches, with: event) if tapHandler != nil { tapHandler?() tapHandler = nil } } /// Remove the tap handler public func clearTapHandler() { isUserInteractionEnabled = false subtitleLabel?.removeFromSuperview() tapHandler = nil } // MARK: - Private interface // // Layout elements // private var blurEffectStyle: UIBlurEffect.Style = .dark private var blurEffect: UIBlurEffect! private var blurView: UIVisualEffectView! private var vibrancyView: UIVisualEffectView! private let defaultTitleFont = UIFont(name: "HelveticaNeue", size: 22.0)! private var currentTitleFont: UIFont private var defaultTitleColor = UIColor.white let frameSize = CGSize(width: 200.0, height: 200.0) private lazy var outerCircleView = UIView() private lazy var innerCircleView = UIView() private let outerCircle = CAShapeLayer() private let innerCircle = CAShapeLayer() required public init?(coder aDecoder: NSCoder) { fatalError("Not coder compliant") } private var currentOuterRotation: CGFloat = 0.0 private var currentInnerRotation: CGFloat = 0.1 private var dismissing: Bool = false private func spinOuter() { if superview == nil { return } let duration = Double(Float(arc4random()) / Float(UInt32.max)) * 2.0 + 1.5 let randomRotation = Double(Float(arc4random()) / Float(UInt32.max)) * (Double.pi / 4) + (Double.pi / 4) //outer circle UIView.animate(withDuration: duration, delay: 0.0, usingSpringWithDamping: 0.4, initialSpringVelocity: 0.0, options: [], animations: { self.currentOuterRotation -= CGFloat(randomRotation) self.outerCircleView.transform = CGAffineTransform(rotationAngle: self.currentOuterRotation) }, completion: {_ in let waitDuration = Double(Float(arc4random()) / Float(UInt32.max)) * 1.0 + 1.0 self.delay(waitDuration, completion: { if self.animating { self.spinOuter() } }) }) } private func spinInner() { if superview == nil { return } //inner circle UIView.animate(withDuration: 0.5, delay: 0.0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.0, options: [], animations: { self.currentInnerRotation += CGFloat(Double.pi / 4) self.innerCircleView.transform = CGAffineTransform(rotationAngle: self.currentInnerRotation) }, completion: { _ in self.delay(0.5, completion: { if self.animating { self.spinInner() } }) }) } @objc func orientationChangedAction() { if let _ = SwiftSpinner.containerView() { SwiftSpinner.shared.setNeedsLayout() } } public func updateFrame() { if let containerView = SwiftSpinner.containerView() { SwiftSpinner.shared.frame = containerView.bounds containerView.bringSubviewToFront(SwiftSpinner.shared) } } // MARK: - Util methods func delay(_ seconds: Double, completion:@escaping () -> Void) { let popTime = DispatchTime.now() + Double(Int64( Double(NSEC_PER_SEC) * seconds )) / Double(NSEC_PER_SEC) DispatchQueue.main.asyncAfter(deadline: popTime) { completion() } } fileprivate func layoutSubtitle() { if let subtitle = subtitleLabel { subtitle.bounds.size = subtitle.sizeThatFits(bounds.insetBy(dx: 20.0, dy: 0.0).size) var safeArea: CGFloat = 0 if #available(iOS 11.0, tvOS 11.0, *) { safeArea = superview?.safeAreaInsets.bottom ?? 0 } subtitle.center = CGPoint(x: bounds.midX, y: bounds.maxY - subtitle.bounds.midY - subtitle.font.pointSize - safeArea) } } override public func layoutSubviews() { super.layoutSubviews() updateFrame() } // MARK: - Tap handler private var tapHandler: (() -> Void)? func didTapSpinner() { tapHandler?() } }
mit
26b4be87adeda16d7fe4fc6bd444bc86
36.31015
463
0.622399
5.164975
false
false
false
false
alexbasson/swift-experiment
SwiftExperimentTests/Presenters/MovieDetailViewPresenterSpec.swift
1
1052
import Quick import Nimble import SwiftExperiment class MovieDetailViewPresenterSpec: QuickSpec { override func spec() { var subject: MovieDetailViewPresenter! let movie = Movie() let imageService = MockImageService() beforeEach { imageService.resetSentMessages() subject = MovieDetailViewPresenter(movie: movie, imageService: imageService) } describe("presentInView()") { var view: MovieDetailView! beforeEach { let vc = MovieDetailViewController.getInstanceFromStoryboard("Main") view = vc.view as! MovieDetailView subject.present(view) } it("sets the title label's text to the movie's title") { if let titleLabel = view.titleLabel { expect(titleLabel.text).to(equal("A title")) } else { XCTFail() } } it("messages the image service to fetch the poster image") { expect(imageService.fetchImage.wasReceived).to(beTrue()) } } } }
mit
f5d8e18cc6628f8e7697d9f78252baf8
26.684211
84
0.615019
4.962264
false
false
false
false
EasySwift/EasySwift
EasySwift_iOS/Core/EZViewModel.swift
2
3579
// // EZViewModel.swift // medical // // Created by zhuchao on 15/5/11. // Copyright (c) 2015年 zhuchao. All rights reserved. // import UIKit import Bond open class EZData: NSObject { open var dym: Observable<Data>? open var value: Data? { get { return self.dym?.value } set(value) { self.dym?.value = value! } } public init(_ data: Data) { self.dym = Observable<Data>(data) } } open class EZString: NSObject { open var dym: Observable<String>? open var value: String? { get { return self.dym?.value } set(value) { self.dym?.value = value! } } public init(_ str: String) { self.dym = Observable<String>(str) } } open class EZURL: NSObject { open var dym: Observable<URL?>? open var value: URL? { get { return self.dym?.value } set(value) { self.dym?.value = value! } } public init(_ url: URL?) { self.dym = Observable<URL?>(url) } } open class EZAttributedString: NSObject { open var dym: Observable<NSAttributedString>? open var value: NSAttributedString? { get { return self.dym?.value } set(value) { self.dym?.value = value! } } public init(_ str: NSAttributedString) { self.dym = Observable<NSAttributedString>(str) } } open class EZImage: NSObject { open var dym: Observable<UIImage?>? open var value: UIImage? { get { return self.dym?.value } set(value) { self.dym?.value = value! } } public init(_ image: UIImage?) { self.dym = Observable<UIImage?>(image) } } open class EZColor: NSObject { open var dym: Observable<UIColor>? open var value: UIColor? { get { return self.dym?.value } set(value) { self.dym?.value = value! } } public init(_ color: UIColor) { self.dym = Observable<UIColor>(color) } } open class EZBool: NSObject { open var dym: Observable<Bool>? open var value: Bool? { get { return self.dym?.value } set(value) { self.dym?.value = value! } } public init(_ b: Bool) { self.dym = Observable<Bool>(b) } } open class EZFloat: NSObject { open var dym: Observable<CGFloat>? open var value: CGFloat? { get { return self.dym?.value } set(value) { self.dym?.value = value! } } public init(_ fl: CGFloat) { self.dym = Observable<CGFloat>(fl) } } open class EZInt: NSObject { open var dym: Observable<Int>? open var value: Int? { get { return self.dym?.value } set(value) { self.dym?.value = value! } } public init(_ i: Int) { self.dym = Observable<Int>(i) } } open class EZNumber: NSObject { open var dym: Observable<NSNumber>? open var value: NSNumber? { get { return self.dym?.value } set(value) { self.dym?.value = value! } } public init(_ i: NSNumber) { self.dym = Observable<NSNumber>(i) } } extension NSObject { public var model_properyies: Dictionary<String, AnyObject> { return self.listProperties() } public func model_hasKey(_ key: String) -> Bool { return self.model_properyies.keys.contains(key) } } open class EZViewModel: NSObject { }
apache-2.0
03e146188b1842d395286a3e3acdcef8
20.291667
64
0.536483
3.695248
false
false
false
false
syoung-smallwisdom/BridgeAppSDK
BridgeAppSDK/SBAConsentSignature.swift
1
5736
// // SBAConsentSignature.swift // BridgeAppSDK // // Copyright © 2016 Sage Bionetworks. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // 3. Neither the name of the copyright holder(s) nor the names of any contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. No license is granted to the trademarks of // the copyright holders even if such marks are included in this software. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // import Foundation @objc public protocol SBAConsentSignatureWrapper : class { /** * Age verification stored with consent */ var signatureBirthdate: Date? { get set } /** * Name used to sign consent */ var signatureName: String? { get set } /** * UIImage representation of consent signature */ var signatureImage: UIImage? { get set } /** * Date of consent */ var signatureDate: Date? { get set } } @objc open class SBAConsentSignature: NSObject, SBAConsentSignatureWrapper, NSSecureCoding, NSCopying { open let identifier: String open var signatureBirthdate: Date? open var signatureName: String? open var signatureImage: UIImage? open var signatureDate: Date? public required init(identifier: String) { self.identifier = identifier super.init() } public convenience init(signature: ORKConsentSignature) { self.init(identifier: signature.identifier) // Assume given name first if signature.givenName != nil || signature.familyName != nil { let firstName = signature.givenName ?? "" let lastName = signature.familyName ?? "" self.signatureName = (firstName + " " + lastName).trim() } self.signatureImage = signature.signatureImage if let dateString = signature.signatureDate, let dateFormat = signature.signatureDateFormatString { let formatter = DateFormatter() formatter.dateFormat = dateFormat self.signatureDate = formatter.date(from: dateString) } } // MARK: NSSecureCoding public static var supportsSecureCoding : Bool { return true } public required convenience init?(coder aDecoder: NSCoder) { guard let identifier = aDecoder.decodeObject(forKey: "identifier") as? String else { return nil } self.init(identifier: identifier) self.signatureBirthdate = aDecoder.decodeObject(forKey: "signatureBirthdate") as? Date self.signatureName = aDecoder.decodeObject(forKey: "signatureName") as? String self.signatureImage = aDecoder.decodeObject(forKey: "signatureImage") as? UIImage self.signatureDate = aDecoder.decodeObject(forKey: "signatureDate") as? Date } open func encode(with aCoder: NSCoder) { aCoder.encode(self.identifier, forKey: "identifier") aCoder.encode(self.signatureBirthdate, forKey: "signatureBirthdate") aCoder.encode(self.signatureName, forKey: "signatureName") aCoder.encode(self.signatureImage, forKey: "signatureImage") aCoder.encode(self.signatureDate, forKey: "signatureDate") } // MARK: Copying open func copy(with zone: NSZone?) -> Any { let copy = type(of: self).init(identifier: self.identifier) copy.signatureBirthdate = self.signatureBirthdate copy.signatureName = self.signatureName copy.signatureImage = self.signatureImage copy.signatureDate = self.signatureDate return copy } // MARK: Equality open override func isEqual(_ object: Any?) -> Bool { guard let obj = object as? SBAConsentSignature else { return false } return SBAObjectEquality(self.identifier, obj.identifier) && SBAObjectEquality(self.signatureBirthdate, obj.signatureBirthdate) && SBAObjectEquality(self.signatureName, obj.signatureName) && SBAObjectEquality(self.signatureImage, obj.signatureImage) && SBAObjectEquality(self.signatureDate, obj.signatureDate) } open override var hash: Int { return self.identifier.hash ^ SBAObjectHash(self.signatureBirthdate) ^ SBAObjectHash(self.signatureName) ^ SBAObjectHash(self.signatureImage) ^ SBAObjectHash(self.signatureDate) } }
bsd-3-clause
219d80e3f2779182b2b96154b6f73e98
37.75
107
0.684743
4.847844
false
false
false
false
leo-lp/LPIM
LPIM/Common/UIViewController+FormSheet.swift
1
11505
// // UIViewController+FormSheet.swift // LPIM // // Created by 李鹏 on 2017/3/28. // Copyright © 2017年 Hangzhou DangQiang network Technology Co., Ltd. All rights reserved. // import UIKit import SnapKit enum LPPresentationStyle { case activity case formSheet } enum LPTransitionStyle { case coverVertical case curveEaseInOut } extension UIViewController { // MARK: - public /// 显示 activity 视图控制器 func presentActivity(_ contentViewController: UIViewController, enableTapGesture: Bool = true, completion: (() -> Void)?) { self.presentFormSheet(contentViewController, presentationStyle: LPPresentationStyle.activity, transitionStyle: LPTransitionStyle.coverVertical, edgePoint: nil, enableTapGesture: enableTapGesture, completion: completion) } /// 隐藏 activity 视图控制器 func dismissActivity(_ completion: (() -> Void)?) { kFormSheetVCS.last?.dismissViewController(completion) } /// 显示 formSheet 视图控制器 func presentFormSheet(_ contentViewController: UIViewController, edgePoint: CGPoint? = nil, enableTapGesture: Bool = true, transitionStyle: LPTransitionStyle = LPTransitionStyle.coverVertical, completion: (() -> Void)?) { self.presentFormSheet(contentViewController, presentationStyle: LPPresentationStyle.formSheet, transitionStyle: transitionStyle, edgePoint: edgePoint, enableTapGesture: enableTapGesture, completion: completion) } /// 隐藏 formSheet 视图控制器 func dismissFormSheet(_ completion: (() -> Void)?) { kFormSheetVCS.last?.dismissViewController(completion) } // MARK: - private private func presentFormSheet(_ contentViewController: UIViewController, presentationStyle: LPPresentationStyle, transitionStyle: LPTransitionStyle, edgePoint: CGPoint?, enableTapGesture: Bool, completion: (() -> Void)?) { let formSheetVc = LPFormSheetViewController() formSheetVc.modalPresentationStyle = UIModalPresentationStyle.overFullScreen self.present(formSheetVc, animated: false) { formSheetVc.presentViewController(contentViewController, presentationStyle: presentationStyle, transitionStyle: transitionStyle, edgePoint: edgePoint, enableTapGesture: enableTapGesture) completion?() } } } private var kFormSheetVCS: [LPFormSheetViewController] = [] class LPFormSheetViewController: LPBaseViewController { lazy var presentationStyle: LPPresentationStyle = LPPresentationStyle.activity lazy var transitionStyle: LPTransitionStyle = LPTransitionStyle.coverVertical lazy var maskView: UIView = UIView() lazy var tapGesture: UITapGestureRecognizer = { UITapGestureRecognizer(target: self, action: #selector(formSheetTapGestureRecognizer)) }() var contentViewController: UIViewController? var transitionConstraint: Constraint? // MARK: - cycle override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() self.maskView.snp.makeConstraints { (make) in make.edges.equalTo(self.view) } } override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.clear self.maskView.alpha = 0.0 // 初始化灰色遮罩 self.maskView.backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.4) // self.maskView.layer.borderColor = UIColor.redColor().CGColor // self.maskView.layer.borderWidth = 2 self.view.addSubview(self.maskView) // 添加单击手势 self.maskView.addGestureRecognizer(self.tapGesture) } // MARK: - public /// 显示activity、formSheet视图控制器 func presentViewController(_ viewController: UIViewController, presentationStyle: LPPresentationStyle, transitionStyle: LPTransitionStyle, edgePoint: CGPoint?, enableTapGesture: Bool) { self.presentationStyle = presentationStyle self.transitionStyle = transitionStyle self.contentViewController = viewController kFormSheetVCS.append(self) self.tapGesture.isEnabled = enableTapGesture self.addChildViewController(viewController) self.view.addSubview(viewController.view) viewController.didMove(toParentViewController: self) switch presentationStyle { case LPPresentationStyle.activity: self.activityAnimation(viewController) case LPPresentationStyle.formSheet: self.formSheetAnimation(viewController, edgePoint: edgePoint) } } /// 隐藏视图控制器 func dismissViewController(_ completion: (() -> Void)?) { switch self.transitionStyle { case LPTransitionStyle.coverVertical: UIView.animate(withDuration: kDuration_Of_Animation, delay: 0.0, options: UIViewAnimationOptions.curveEaseIn, animations: { self.maskView.alpha = 0.0 if let height = self.contentViewController?.view.frame.height { if self.presentationStyle == LPPresentationStyle.activity { self.transitionConstraint?.update(offset: height) } else { self.transitionConstraint?.update(offset: (self.view.frame.height + height) / 2.0) } } self.view.layoutIfNeeded() }, completion: { (finished) in self.dismiss(animated: false, completion: { self.contentViewController = nil self.transitionConstraint = nil kFormSheetVCS.removeLast() if let completion = completion { completion() } }) }) case LPTransitionStyle.curveEaseInOut: UIView.animate(withDuration: kDuration_Of_Animation, delay: 0.0, options: UIViewAnimationOptions.curveEaseOut, animations: { self.maskView.alpha = 0.0 }) { (finished) in self.dismiss(animated: false, completion: { self.contentViewController = nil self.transitionConstraint = nil kFormSheetVCS.removeLast() if let completion = completion { completion() } }) } } } /// 单击手势用来隐藏视图控制器 func formSheetTapGestureRecognizer(_ recognizer: UIGestureRecognizer) { if let contetnView = self.contentViewController?.view { let point = recognizer.location(in: contetnView) if !contetnView.bounds.contains(point) { dismissViewController(nil) } } } // MARK: - private /// 显示activity视图控制器 private func activityAnimation(_ viewController: UIViewController) { let height = viewController.view.frame.height viewController.view.snp.makeConstraints { (make) -> Void in make.height.equalTo(height) make.left.right.equalTo(self.view) let offset = make.bottom.equalTo(self.view.snp.bottom).offset(height) self.transitionConstraint = offset.constraint } self.maskView.alpha = 0.0 self.view.layoutIfNeeded() self.transitionConstraint?.update(offset: 0.0) UIView.animate(withDuration: kDuration_Of_Animation, delay: 0.0, options: UIViewAnimationOptions.curveEaseOut, animations: { self.maskView.alpha = 1.0 self.view.layoutIfNeeded() }, completion: nil) } /// 显示formSheet视图控制器 private func formSheetAnimation(_ viewController: UIViewController, edgePoint: CGPoint?) { // 设置边距 if let edgePoint = edgePoint { let frame = self.view.frame let size = CGSize(width: frame.width - edgePoint.x * 2.0, height: frame.height - edgePoint.y * 2.0) viewController.view.frame.size = size } viewController.view.snp.makeConstraints( { (make) in make.height.equalTo(viewController.view.frame.height) make.width.equalTo(viewController.view.frame.width) make.centerX.equalTo(self.view.snp.centerX) switch self.transitionStyle { case LPTransitionStyle.coverVertical: let offset = (self.view.frame.height + viewController.view.frame.height) / 2.0 self.transitionConstraint = make.centerY.equalTo(self.view.snp.centerY).offset(offset).constraint case LPTransitionStyle.curveEaseInOut: make.centerY.equalTo(self.view.snp.centerY).offset(0.0) } }) switch self.transitionStyle { case LPTransitionStyle.coverVertical: self.maskView.alpha = 0.0 self.view.layoutIfNeeded() transitionConstraint?.update(offset: 0.0) UIView.animate(withDuration: kDuration_Of_Animation, delay: 0.0, options: UIViewAnimationOptions.curveEaseOut, animations: { self.maskView.alpha = 1.0 self.view.layoutIfNeeded() }, completion: nil) case LPTransitionStyle.curveEaseInOut: self.maskView.alpha = 0.0 UIView.animate(withDuration: 0.1, animations: { self.maskView.alpha = 1.0 }) let previousTransform = viewController.view.transform viewController.view.layer.transform = CATransform3DMakeScale(0.9, 0.9, 0.0) UIView.animate(withDuration: 0.2, animations: { viewController.view.layer.transform = CATransform3DMakeScale(1.1, 1.1, 0.0) }, completion: { (finished) in UIView.animate(withDuration: 0.1, animations: { viewController.view.layer.transform = CATransform3DMakeScale(0.9, 0.9, 0.0) }, completion: { (finished) in UIView.animate(withDuration: 0.1, animations: { viewController.view.layer.transform = CATransform3DMakeScale(1.0, 1.0, 0.0) }, completion: { (finished) in viewController.view.transform = previousTransform }) }) }) } } }
mit
e47e4eae71e4cf2ffc37d82a0761ab84
40.328467
136
0.577093
5.561886
false
false
false
false
jhurray/SQLiteModel-Example-Project
tvOS+SQLiteModel/Pods/SQLite.swift/SQLite/Typed/Query.swift
11
35514
// // SQLite.swift // https://github.com/stephencelis/SQLite.swift // Copyright © 2014-2015 Stephen Celis. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // public protocol QueryType : Expressible { var clauses: QueryClauses { get set } init(_ name: String, database: String?) } public protocol SchemaType : QueryType { static var identifier: String { get } } extension SchemaType { /// Builds a copy of the query with the `SELECT` clause applied. /// /// let users = Table("users") /// let id = Expression<Int64>("id") /// let email = Expression<String>("email") /// /// users.select(id, email) /// // SELECT "id", "email" FROM "users" /// /// - Parameter all: A list of expressions to select. /// /// - Returns: A query with the given `SELECT` clause applied. public func select(column1: Expressible, _ more: Expressible...) -> Self { return select(false, [column1] + more) } /// Builds a copy of the query with the `SELECT DISTINCT` clause applied. /// /// let users = Table("users") /// let email = Expression<String>("email") /// /// users.select(distinct: email) /// // SELECT DISTINCT "email" FROM "users" /// /// - Parameter columns: A list of expressions to select. /// /// - Returns: A query with the given `SELECT DISTINCT` clause applied. public func select(distinct column1: Expressible, _ more: Expressible...) -> Self { return select(true, [column1] + more) } /// Builds a copy of the query with the `SELECT` clause applied. /// /// let users = Table("users") /// let id = Expression<Int64>("id") /// let email = Expression<String>("email") /// /// users.select([id, email]) /// // SELECT "id", "email" FROM "users" /// /// - Parameter all: A list of expressions to select. /// /// - Returns: A query with the given `SELECT` clause applied. public func select(all: [Expressible]) -> Self { return select(false, all) } /// Builds a copy of the query with the `SELECT DISTINCT` clause applied. /// /// let users = Table("users") /// let email = Expression<String>("email") /// /// users.select(distinct: [email]) /// // SELECT DISTINCT "email" FROM "users" /// /// - Parameter columns: A list of expressions to select. /// /// - Returns: A query with the given `SELECT DISTINCT` clause applied. public func select(distinct columns: [Expressible]) -> Self { return select(true, columns) } /// Builds a copy of the query with the `SELECT *` clause applied. /// /// let users = Table("users") /// /// users.select(*) /// // SELECT * FROM "users" /// /// - Parameter star: A star literal. /// /// - Returns: A query with the given `SELECT *` clause applied. public func select(star: Star) -> Self { return select([star(nil, nil)]) } /// Builds a copy of the query with the `SELECT DISTINCT *` clause applied. /// /// let users = Table("users") /// /// users.select(distinct: *) /// // SELECT DISTINCT * FROM "users" /// /// - Parameter star: A star literal. /// /// - Returns: A query with the given `SELECT DISTINCT *` clause applied. public func select(distinct star: Star) -> Self { return select(distinct: [star(nil, nil)]) } /// Builds a scalar copy of the query with the `SELECT` clause applied. /// /// let users = Table("users") /// let id = Expression<Int64>("id") /// /// users.select(id) /// // SELECT "id" FROM "users" /// /// - Parameter all: A list of expressions to select. /// /// - Returns: A query with the given `SELECT` clause applied. public func select<V : Value>(column: Expression<V>) -> ScalarQuery<V> { return select(false, [column]) } public func select<V : Value>(column: Expression<V?>) -> ScalarQuery<V?> { return select(false, [column]) } /// Builds a scalar copy of the query with the `SELECT DISTINCT` clause /// applied. /// /// let users = Table("users") /// let email = Expression<String>("email") /// /// users.select(distinct: email) /// // SELECT DISTINCT "email" FROM "users" /// /// - Parameter column: A list of expressions to select. /// /// - Returns: A query with the given `SELECT DISTINCT` clause applied. public func select<V : Value>(distinct column: Expression<V>) -> ScalarQuery<V> { return select(true, [column]) } public func select<V : Value>(distinct column: Expression<V?>) -> ScalarQuery<V?> { return select(true, [column]) } public var count: ScalarQuery<Int> { return select(Expression.count(*)) } } extension QueryType { private func select<Q : QueryType>(distinct: Bool, _ columns: [Expressible]) -> Q { var query = Q.init(clauses.from.name, database: clauses.from.database) query.clauses = clauses query.clauses.select = (distinct, columns) return query } // MARK: JOIN /// Adds a `JOIN` clause to the query. /// /// let users = Table("users") /// let id = Expression<Int64>("id") /// let posts = Table("posts") /// let userId = Expression<Int64>("user_id") /// /// users.join(posts, on: posts[userId] == users[id]) /// // SELECT * FROM "users" INNER JOIN "posts" ON ("posts"."user_id" = "users"."id") /// /// - Parameters: /// /// - table: A query representing the other table. /// /// - condition: A boolean expression describing the join condition. /// /// - Returns: A query with the given `JOIN` clause applied. public func join(table: QueryType, on condition: Expression<Bool>) -> Self { return join(table, on: Expression<Bool?>(condition)) } /// Adds a `JOIN` clause to the query. /// /// let users = Table("users") /// let id = Expression<Int64>("id") /// let posts = Table("posts") /// let userId = Expression<Int64?>("user_id") /// /// users.join(posts, on: posts[userId] == users[id]) /// // SELECT * FROM "users" INNER JOIN "posts" ON ("posts"."user_id" = "users"."id") /// /// - Parameters: /// /// - table: A query representing the other table. /// /// - condition: A boolean expression describing the join condition. /// /// - Returns: A query with the given `JOIN` clause applied. public func join(table: QueryType, on condition: Expression<Bool?>) -> Self { return join(.Inner, table, on: condition) } /// Adds a `JOIN` clause to the query. /// /// let users = Table("users") /// let id = Expression<Int64>("id") /// let posts = Table("posts") /// let userId = Expression<Int64>("user_id") /// /// users.join(.LeftOuter, posts, on: posts[userId] == users[id]) /// // SELECT * FROM "users" LEFT OUTER JOIN "posts" ON ("posts"."user_id" = "users"."id") /// /// - Parameters: /// /// - type: The `JOIN` operator. /// /// - table: A query representing the other table. /// /// - condition: A boolean expression describing the join condition. /// /// - Returns: A query with the given `JOIN` clause applied. public func join(type: JoinType, _ table: QueryType, on condition: Expression<Bool>) -> Self { return join(type, table, on: Expression<Bool?>(condition)) } /// Adds a `JOIN` clause to the query. /// /// let users = Table("users") /// let id = Expression<Int64>("id") /// let posts = Table("posts") /// let userId = Expression<Int64?>("user_id") /// /// users.join(.LeftOuter, posts, on: posts[userId] == users[id]) /// // SELECT * FROM "users" LEFT OUTER JOIN "posts" ON ("posts"."user_id" = "users"."id") /// /// - Parameters: /// /// - type: The `JOIN` operator. /// /// - table: A query representing the other table. /// /// - condition: A boolean expression describing the join condition. /// /// - Returns: A query with the given `JOIN` clause applied. public func join(type: JoinType, _ table: QueryType, on condition: Expression<Bool?>) -> Self { var query = self query.clauses.join.append((type: type, query: table, condition: table.clauses.filters.map { condition && $0 } ?? condition as Expressible)) return query } // MARK: WHERE /// Adds a condition to the query’s `WHERE` clause. /// /// let users = Table("users") /// let id = Expression<Int64>("id") /// /// users.filter(id == 1) /// // SELECT * FROM "users" WHERE ("id" = 1) /// /// - Parameter condition: A boolean expression to filter on. /// /// - Returns: A query with the given `WHERE` clause applied. public func filter(predicate: Expression<Bool>) -> Self { return filter(Expression<Bool?>(predicate)) } /// Adds a condition to the query’s `WHERE` clause. /// /// let users = Table("users") /// let age = Expression<Int?>("age") /// /// users.filter(age >= 35) /// // SELECT * FROM "users" WHERE ("age" >= 35) /// /// - Parameter condition: A boolean expression to filter on. /// /// - Returns: A query with the given `WHERE` clause applied. public func filter(predicate: Expression<Bool?>) -> Self { var query = self query.clauses.filters = query.clauses.filters.map { $0 && predicate } ?? predicate return query } // MARK: GROUP BY /// Sets a `GROUP BY` clause on the query. /// /// - Parameter by: A list of columns to group by. /// /// - Returns: A query with the given `GROUP BY` clause applied. public func group(by: Expressible...) -> Self { return group(by) } /// Sets a `GROUP BY` clause on the query. /// /// - Parameter by: A list of columns to group by. /// /// - Returns: A query with the given `GROUP BY` clause applied. public func group(by: [Expressible]) -> Self { return group(by, nil) } /// Sets a `GROUP BY`-`HAVING` clause on the query. /// /// - Parameters: /// /// - by: A column to group by. /// /// - having: A condition determining which groups are returned. /// /// - Returns: A query with the given `GROUP BY`–`HAVING` clause applied. public func group(by: Expressible, having: Expression<Bool>) -> Self { return group([by], having: having) } /// Sets a `GROUP BY`-`HAVING` clause on the query. /// /// - Parameters: /// /// - by: A column to group by. /// /// - having: A condition determining which groups are returned. /// /// - Returns: A query with the given `GROUP BY`–`HAVING` clause applied. public func group(by: Expressible, having: Expression<Bool?>) -> Self { return group([by], having: having) } /// Sets a `GROUP BY`-`HAVING` clause on the query. /// /// - Parameters: /// /// - by: A list of columns to group by. /// /// - having: A condition determining which groups are returned. /// /// - Returns: A query with the given `GROUP BY`–`HAVING` clause applied. public func group(by: [Expressible], having: Expression<Bool>) -> Self { return group(by, Expression<Bool?>(having)) } /// Sets a `GROUP BY`-`HAVING` clause on the query. /// /// - Parameters: /// /// - by: A list of columns to group by. /// /// - having: A condition determining which groups are returned. /// /// - Returns: A query with the given `GROUP BY`–`HAVING` clause applied. public func group(by: [Expressible], having: Expression<Bool?>) -> Self { return group(by, having) } private func group(by: [Expressible], _ having: Expression<Bool?>?) -> Self { var query = self query.clauses.group = (by, having) return query } // MARK: ORDER BY /// Sets an `ORDER BY` clause on the query. /// /// let users = Table("users") /// let email = Expression<String>("email") /// let name = Expression<String?>("name") /// /// users.order(email.desc, name.asc) /// // SELECT * FROM "users" ORDER BY "email" DESC, "name" ASC /// /// - Parameter by: An ordered list of columns and directions to sort by. /// /// - Returns: A query with the given `ORDER BY` clause applied. public func order(by: Expressible...) -> Self { return order(by) } /// Sets an `ORDER BY` clause on the query. /// /// let users = Table("users") /// let email = Expression<String>("email") /// let name = Expression<String?>("name") /// /// users.order([email.desc, name.asc]) /// // SELECT * FROM "users" ORDER BY "email" DESC, "name" ASC /// /// - Parameter by: An ordered list of columns and directions to sort by. /// /// - Returns: A query with the given `ORDER BY` clause applied. public func order(by: [Expressible]) -> Self { var query = self query.clauses.order = by return query } // MARK: LIMIT/OFFSET /// Sets the LIMIT clause (and resets any OFFSET clause) on the query. /// /// let users = Table("users") /// /// users.limit(20) /// // SELECT * FROM "users" LIMIT 20 /// /// - Parameter length: The maximum number of rows to return (or `nil` to /// return unlimited rows). /// /// - Returns: A query with the given LIMIT clause applied. public func limit(length: Int?) -> Self { return limit(length, nil) } /// Sets LIMIT and OFFSET clauses on the query. /// /// let users = Table("users") /// /// users.limit(20, offset: 20) /// // SELECT * FROM "users" LIMIT 20 OFFSET 20 /// /// - Parameters: /// /// - length: The maximum number of rows to return. /// /// - offset: The number of rows to skip. /// /// - Returns: A query with the given LIMIT and OFFSET clauses applied. public func limit(length: Int, offset: Int) -> Self { return limit(length, offset) } // prevents limit(nil, offset: 5) private func limit(length: Int?, _ offset: Int?) -> Self { var query = self query.clauses.limit = length.map { ($0, offset) } return query } // MARK: - Clauses // // MARK: SELECT // MARK: - private var selectClause: Expressible { return " ".join([ Expression<Void>(literal: clauses.select.distinct ? "SELECT DISTINCT" : "SELECT"), ", ".join(clauses.select.columns), Expression<Void>(literal: "FROM"), tableName(alias: true) ]) } private var joinClause: Expressible? { guard !clauses.join.isEmpty else { return nil } return " ".join(clauses.join.map { type, query, condition in " ".join([ Expression<Void>(literal: "\(type.rawValue) JOIN"), query.tableName(alias: true), Expression<Void>(literal: "ON"), condition ]) }) } private var whereClause: Expressible? { guard let filters = clauses.filters else { return nil } return " ".join([ Expression<Void>(literal: "WHERE"), filters ]) } private var groupByClause: Expressible? { guard let group = clauses.group else { return nil } let groupByClause = " ".join([ Expression<Void>(literal: "GROUP BY"), ", ".join(group.by) ]) guard let having = group.having else { return groupByClause } return " ".join([ groupByClause, " ".join([ Expression<Void>(literal: "HAVING"), having ]) ]) } private var orderClause: Expressible? { guard !clauses.order.isEmpty else { return nil } return " ".join([ Expression<Void>(literal: "ORDER BY"), ", ".join(clauses.order) ]) } private var limitOffsetClause: Expressible? { guard let limit = clauses.limit else { return nil } let limitClause = Expression<Void>(literal: "LIMIT \(limit.length)") guard let offset = limit.offset else { return limitClause } return " ".join([ limitClause, Expression<Void>(literal: "OFFSET \(offset)") ]) } // MARK: - public func alias(aliasName: String) -> Self { var query = self query.clauses.from = (clauses.from.name, aliasName, clauses.from.database) return query } // MARK: - Operations // // MARK: INSERT public func insert(value: Setter, _ more: Setter...) -> Insert { return insert([value] + more) } public func insert(values: [Setter]) -> Insert { return insert(nil, values) } public func insert(or onConflict: OnConflict, _ values: Setter...) -> Insert { return insert(or: onConflict, values) } public func insert(or onConflict: OnConflict, _ values: [Setter]) -> Insert { return insert(onConflict, values) } private func insert(or: OnConflict?, _ values: [Setter]) -> Insert { let insert = values.reduce((columns: [Expressible](), values: [Expressible]())) { insert, setter in (insert.columns + [setter.column], insert.values + [setter.value]) } let clauses: [Expressible?] = [ Expression<Void>(literal: "INSERT"), or.map { Expression<Void>(literal: "OR \($0.rawValue)") }, Expression<Void>(literal: "INTO"), tableName(), "".wrap(insert.columns) as Expression<Void>, Expression<Void>(literal: "VALUES"), "".wrap(insert.values) as Expression<Void>, whereClause ] return Insert(" ".join(clauses.flatMap { $0 }).expression) } /// Runs an `INSERT` statement against the query with `DEFAULT VALUES`. public func insert() -> Insert { return Insert(" ".join([ Expression<Void>(literal: "INSERT INTO"), tableName(), Expression<Void>(literal: "DEFAULT VALUES") ]).expression) } /// Runs an `INSERT` statement against the query with the results of another /// query. /// /// - Parameter query: A query to `SELECT` results from. /// /// - Returns: The number of updated rows and statement. public func insert(query: QueryType) -> Update { return Update(" ".join([ Expression<Void>(literal: "INSERT INTO"), tableName(), query.expression ]).expression) } // MARK: UPDATE public func update(values: Setter...) -> Update { return update(values) } public func update(values: [Setter]) -> Update { let clauses: [Expressible?] = [ Expression<Void>(literal: "UPDATE"), tableName(), Expression<Void>(literal: "SET"), ", ".join(values.map { " = ".join([$0.column, $0.value]) }), whereClause ] return Update(" ".join(clauses.flatMap { $0 }).expression) } // MARK: DELETE public func delete() -> Delete { let clauses: [Expressible?] = [ Expression<Void>(literal: "DELETE FROM"), tableName(), whereClause ] return Delete(" ".join(clauses.flatMap { $0 }).expression) } // MARK: EXISTS public var exists: Select<Bool> { return Select(" ".join([ Expression<Void>(literal: "SELECT EXISTS"), "".wrap(expression) as Expression<Void> ]).expression) } // MARK: - /// Prefixes a column expression with the query’s table name or alias. /// /// - Parameter column: A column expression. /// /// - Returns: A column expression namespaced with the query’s table name or /// alias. public func namespace<V>(column: Expression<V>) -> Expression<V> { return Expression(".".join([tableName(), column]).expression) } // FIXME: rdar://problem/18673897 // subscript<T>… public subscript(column: Expression<Blob>) -> Expression<Blob> { return namespace(column) } public subscript(column: Expression<Blob?>) -> Expression<Blob?> { return namespace(column) } public subscript(column: Expression<Bool>) -> Expression<Bool> { return namespace(column) } public subscript(column: Expression<Bool?>) -> Expression<Bool?> { return namespace(column) } public subscript(column: Expression<Double>) -> Expression<Double> { return namespace(column) } public subscript(column: Expression<Double?>) -> Expression<Double?> { return namespace(column) } public subscript(column: Expression<Int>) -> Expression<Int> { return namespace(column) } public subscript(column: Expression<Int?>) -> Expression<Int?> { return namespace(column) } public subscript(column: Expression<Int64>) -> Expression<Int64> { return namespace(column) } public subscript(column: Expression<Int64?>) -> Expression<Int64?> { return namespace(column) } public subscript(column: Expression<String>) -> Expression<String> { return namespace(column) } public subscript(column: Expression<String?>) -> Expression<String?> { return namespace(column) } /// Prefixes a star with the query’s table name or alias. /// /// - Parameter star: A literal `*`. /// /// - Returns: A `*` expression namespaced with the query’s table name or /// alias. public subscript(star: Star) -> Expression<Void> { return namespace(star(nil, nil)) } // MARK: - // TODO: alias support func tableName(alias aliased: Bool = false) -> Expressible { guard let alias = clauses.from.alias where aliased else { return database(namespace: clauses.from.alias ?? clauses.from.name) } return " ".join([ database(namespace: clauses.from.name), Expression<Void>(literal: "AS"), Expression<Void>(alias) ]) } func database(namespace name: String) -> Expressible { let name = Expression<Void>(name) guard let database = clauses.from.database else { return name } return ".".join([Expression<Void>(database), name]) } public var expression: Expression<Void> { let clauses: [Expressible?] = [ selectClause, joinClause, whereClause, groupByClause, orderClause, limitOffsetClause ] return " ".join(clauses.flatMap { $0 }).expression } } // TODO: decide: simplify the below with a boxed type instead /// Queries a collection of chainable helper functions and expressions to build /// executable SQL statements. public struct Table : SchemaType { public static let identifier = "TABLE" public var clauses: QueryClauses public init(_ name: String, database: String? = nil) { clauses = QueryClauses(name, alias: nil, database: database) } } public struct View : SchemaType { public static let identifier = "VIEW" public var clauses: QueryClauses public init(_ name: String, database: String? = nil) { clauses = QueryClauses(name, alias: nil, database: database) } } public struct VirtualTable : SchemaType { public static let identifier = "VIRTUAL TABLE" public var clauses: QueryClauses public init(_ name: String, database: String? = nil) { clauses = QueryClauses(name, alias: nil, database: database) } } // TODO: make `ScalarQuery` work in `QueryType.select()`, `.filter()`, etc. public struct ScalarQuery<V> : QueryType { public var clauses: QueryClauses public init(_ name: String, database: String? = nil) { clauses = QueryClauses(name, alias: nil, database: database) } } // TODO: decide: simplify the below with a boxed type instead public struct Select<T> : ExpressionType { public var template: String public var bindings: [Binding?] public init(_ template: String, _ bindings: [Binding?]) { self.template = template self.bindings = bindings } } public struct Insert : ExpressionType { public var template: String public var bindings: [Binding?] public init(_ template: String, _ bindings: [Binding?]) { self.template = template self.bindings = bindings } } public struct Update : ExpressionType { public var template: String public var bindings: [Binding?] public init(_ template: String, _ bindings: [Binding?]) { self.template = template self.bindings = bindings } } public struct Delete : ExpressionType { public var template: String public var bindings: [Binding?] public init(_ template: String, _ bindings: [Binding?]) { self.template = template self.bindings = bindings } } extension Connection { public func prepare(query: QueryType) throws -> AnySequence<Row> { let expression = query.expression let statement = try prepare(expression.template, expression.bindings) let columnNames: [String: Int] = try { var (columnNames, idx) = ([String: Int](), 0) column: for each in query.clauses.select.columns ?? [Expression<Void>(literal: "*")] { var names = each.expression.template.characters.split { $0 == "." }.map(String.init) let column = names.removeLast() let namespace = names.joinWithSeparator(".") func expandGlob(namespace: Bool) -> (QueryType throws -> Void) { return { (query: QueryType) throws -> (Void) in var q = query.dynamicType.init(query.clauses.from.name, database: query.clauses.from.database) q.clauses.select = query.clauses.select let e = q.expression var names = try self.prepare(e.template, e.bindings).columnNames.map { $0.quote() } if namespace { names = names.map { "\(query.tableName().expression.template).\($0)" } } for name in names { columnNames[name] = idx; idx += 1 } } } if column == "*" { var select = query select.clauses.select = (false, [Expression<Void>(literal: "*") as Expressible]) let queries = [select] + query.clauses.join.map { $0.query } if !namespace.isEmpty { for q in queries { if q.tableName().expression.template == namespace { try expandGlob(true)(q) continue column } } fatalError("no such table: \(namespace)") } for q in queries { try expandGlob(query.clauses.join.count > 0)(q) } continue } columnNames[each.expression.template] = idx idx += 1 } return columnNames }() return AnySequence { AnyGenerator { statement.next().map { Row(columnNames, $0) } } } } public func scalar<V : Value>(query: ScalarQuery<V>) -> V { let expression = query.expression return value(scalar(expression.template, expression.bindings)) } public func scalar<V : Value>(query: ScalarQuery<V?>) -> V.ValueType? { let expression = query.expression guard let value = scalar(expression.template, expression.bindings) as? V.Datatype else { return nil } return V.fromDatatypeValue(value) } public func scalar<V : Value>(query: Select<V>) -> V { let expression = query.expression return value(scalar(expression.template, expression.bindings)) } public func scalar<V : Value>(query: Select<V?>) -> V.ValueType? { let expression = query.expression guard let value = scalar(expression.template, expression.bindings) as? V.Datatype else { return nil } return V.fromDatatypeValue(value) } public func pluck(query: QueryType) -> Row? { return try! prepare(query.limit(1, query.clauses.limit?.offset)).generate().next() } /// Runs an `Insert` query. /// /// - SeeAlso: `QueryType.insert(value:_:)` /// - SeeAlso: `QueryType.insert(values:)` /// - SeeAlso: `QueryType.insert(or:_:)` /// - SeeAlso: `QueryType.insert()` /// /// - Parameter query: An insert query. /// /// - Returns: The insert’s rowid. public func run(query: Insert) throws -> Int64 { let expression = query.expression return try sync { try self.run(expression.template, expression.bindings) return self.lastInsertRowid! } } /// Runs an `Update` query. /// /// - SeeAlso: `QueryType.insert(query:)` /// - SeeAlso: `QueryType.update(values:)` /// /// - Parameter query: An update query. /// /// - Returns: The number of updated rows. public func run(query: Update) throws -> Int { let expression = query.expression return try sync { try self.run(expression.template, expression.bindings) return self.changes } } /// Runs a `Delete` query. /// /// - SeeAlso: `QueryType.delete()` /// /// - Parameter query: A delete query. /// /// - Returns: The number of deleted rows. public func run(query: Delete) throws -> Int { let expression = query.expression return try sync { try self.run(expression.template, expression.bindings) return self.changes } } } public struct Row { private let columnNames: [String: Int] private let values: [Binding?] private init(_ columnNames: [String: Int], _ values: [Binding?]) { self.columnNames = columnNames self.values = values } /// Returns a row’s value for the given column. /// /// - Parameter column: An expression representing a column selected in a Query. /// /// - Returns: The value for the given column. public func get<V: Value>(column: Expression<V>) -> V { return get(Expression<V?>(column))! } public func get<V: Value>(column: Expression<V?>) -> V? { func valueAtIndex(idx: Int) -> V? { guard let value = values[idx] as? V.Datatype else { return nil } return (V.fromDatatypeValue(value) as? V)! } guard let idx = columnNames[column.template] else { let similar = Array(columnNames.keys).filter { $0.hasSuffix(".\(column.template)") } switch similar.count { case 0: fatalError("no such column '\(column.template)' in columns: \(columnNames.keys.sort())") case 1: return valueAtIndex(columnNames[similar[0]]!) default: fatalError("ambiguous column '\(column.template)' (please disambiguate: \(similar))") } } return valueAtIndex(idx) } // FIXME: rdar://problem/18673897 // subscript<T>… public subscript(column: Expression<Blob>) -> Blob { return get(column) } public subscript(column: Expression<Blob?>) -> Blob? { return get(column) } public subscript(column: Expression<Bool>) -> Bool { return get(column) } public subscript(column: Expression<Bool?>) -> Bool? { return get(column) } public subscript(column: Expression<Double>) -> Double { return get(column) } public subscript(column: Expression<Double?>) -> Double? { return get(column) } public subscript(column: Expression<Int>) -> Int { return get(column) } public subscript(column: Expression<Int?>) -> Int? { return get(column) } public subscript(column: Expression<Int64>) -> Int64 { return get(column) } public subscript(column: Expression<Int64?>) -> Int64? { return get(column) } public subscript(column: Expression<String>) -> String { return get(column) } public subscript(column: Expression<String?>) -> String? { return get(column) } } /// Determines the join operator for a query’s `JOIN` clause. public enum JoinType : String { /// A `CROSS` join. case Cross = "CROSS" /// An `INNER` join. case Inner = "INNER" /// A `LEFT OUTER` join. case LeftOuter = "LEFT OUTER" } /// ON CONFLICT resolutions. public enum OnConflict: String { case Replace = "REPLACE" case Rollback = "ROLLBACK" case Abort = "ABORT" case Fail = "FAIL" case Ignore = "IGNORE" } // MARK: - Private public struct QueryClauses { var select = (distinct: false, columns: [Expression<Void>(literal: "*") as Expressible]) var from: (name: String, alias: String?, database: String?) var join = [(type: JoinType, query: QueryType, condition: Expressible)]() var filters: Expression<Bool?>? var group: (by: [Expressible], having: Expression<Bool?>?)? var order = [Expressible]() var limit: (length: Int, offset: Int?)? private init(_ name: String, alias: String?, database: String?) { self.from = (name, alias, database) } }
mit
e0dbb09ff25280dd5077e6ccb8f0d940
30.043745
147
0.571259
4.319294
false
false
false
false
digitalcatnip/Pace-SSS-iOS
SSSFreshmanApp/SSSFreshmanApp/CourseVC.swift
1
11554
// // CourseVC.swift // Pace SSS // // Created by James McCarthy on 8/31/16. // Copyright © 2016 Digital Catnip. All rights reserved. // import GoogleAPIClient import GTMOAuth2 import RealmSwift class CourseVC: UIViewController, UITableViewDelegate, UITableViewDataSource { private let kKeychainItemName = "SSS Freshman App" private let kClientID = "1071382956425-khatsf83p2hm5oihev02j2v36q5je8r8.apps.googleusercontent.com" // If modifying these scopes, delete your previously saved credentials by // resetting the iOS simulator or uninstall the app. private let scopes = ["https://www.googleapis.com/auth/spreadsheets.readonly"] private let service = GTLService() private var courses: Results<Course>? private var alphabets = [String]() private var query = "" private var campus = "All Campuses" @IBOutlet var campusButton: UIButton? @IBOutlet var tableView: UITableView? var refresher = UIRefreshControl() override func viewDidLoad() { super.viewDidLoad() if let auth = GTMOAuth2ViewControllerTouch.authForGoogleFromKeychainForName( kKeychainItemName, clientID: kClientID, clientSecret: nil) { service.authorizer = auth } self.navigationController?.navigationBar.tintColor = UIColor.blueColor() let tableVC = UITableViewController() tableVC.tableView = self.tableView refresher = UIRefreshControl() refresher.tintColor = UIColor.blueColor() refresher.addTarget(self, action: #selector(showCourses), forControlEvents: .ValueChanged) tableVC.refreshControl = refresher loadCoursesFromRealm(false) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if let authorizer = service.authorizer, canAuth = authorizer.canAuthorize where canAuth { showCourses() } else { presentViewController( createAuthController(), animated: true, completion: nil ) } } override func viewDidAppear(animated: Bool) { registerScreen("CoursesScreen") } //MARK: UITableViewDataSource functions func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if courses != nil { return courses!.count } else { return 0; } } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if courses != nil { let course = courses![indexPath.row] if course.fullSubject().characters.count < 25 { return 70.0 } } return 90.0 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("courseCell", forIndexPath: indexPath) as! CourseCell cell.courseObj = courses![indexPath.row] cell.configure() return cell } func sectionIndexTitlesForTableView(tableView: UITableView) -> [String]? { return alphabets } func tableView(tableView: UITableView, sectionForSectionIndexTitle title: String, atIndex index: Int) -> Int { if courses != nil { for i in 0..<courses!.count { let course = courses![i] let s = course.title.substringToIndex(course.title.characters.startIndex.successor()) if s == title { tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: i, inSection: 0), atScrollPosition: .Top, animated: true) break } } } return -1 } // MARK: UITableViewDelegate functions func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if courses != nil && indexPath.row < courses!.count { let course = courses![indexPath.row] sendEmailToJonathan(course) } tableView.deselectRowAtIndexPath(indexPath, animated: true) } // MARK: Google Sheets API func showCourses() { NSLog("Loading from network!") refresher.beginRefreshing() let baseUrl = "https://sheets.googleapis.com/v4/spreadsheets" let spreadsheetId = "1mtFnkamBkyWKZZRO4AXdz9azL5TkRjCyHuOknvDkJMI" let courseRange = "Courses!A2:E" let url = String(format:"%@/%@/values/%@", baseUrl, spreadsheetId, courseRange) let params = ["majorDimension": "ROWS"] let fullUrl = GTLUtilities.URLWithString(url, queryParameters: params) service.fetchObjectWithURL(fullUrl, objectClass: GTLObject.self, delegate: self, didFinishSelector: #selector(CourseVC.displayResultWithTicket(_:finishedWithObject:error:)) ) } func displayResultWithTicket(ticket: GTLServiceTicket, finishedWithObject object : GTLObject, error: NSError?) { if error != nil { NSLog("Failed to fetch courses: \(error!.localizedDescription)") showAlert("Network Issue", message: "Course information may be incorrect.") return } let rows = object.JSON["values"] as! [[String]] if rows.isEmpty { NSLog("No data found.") return } //Track the existing courses so we can delete removed entries let oldCourses = ModelManager.sharedInstance.query(Course.self, queryString: nil) var ocArr = [Course]() for course in oldCourses { ocArr.append(course) } var hashes = [Int]() var courses = [Course]() for row in rows { let c = Course() c.initializeFromSpreadsheet(row) courses.append(c) hashes.append(c.id) } //Sort the IDs of the new objects, then check to see if the old objects are in the new list //We'll delete any old object not in the list hashes.sortInPlace() var toDelete = [Course]() for course in ocArr { if let _ = hashes.indexOf(course.id) { } else { toDelete.append(course) } } ModelManager.sharedInstance.saveModels(courses) ModelManager.sharedInstance.deleteModels(toDelete) loadCoursesFromRealm(true) refresher.endRefreshing() } private func createAuthController() -> GTMOAuth2ViewControllerTouch { let scopeString = scopes.joinWithSeparator(" ") return GTMOAuth2ViewControllerTouch( scope: scopeString, clientID: kClientID, clientSecret: nil, keychainItemName: kKeychainItemName, delegate: self, finishedSelector: #selector(CourseVC.viewController(_:finishedWithAuth:error:)) ) } func viewController(vc : UIViewController, finishedWithAuth authResult : GTMOAuth2Authentication, error : NSError?) { if let error = error { service.authorizer = nil showAlert("Authentication Error", message: error.localizedDescription) return } service.authorizer = authResult dismissViewControllerAnimated(true, completion: nil) } func showAlert(title : String, message: String) { let alert = UIAlertController( title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert ) let ok = UIAlertAction( title: "OK", style: UIAlertActionStyle.Default, handler: nil ) alert.addAction(ok) presentViewController(alert, animated: true, completion: nil) } //MARK: Send Email func sendEmailToJonathan(course: Course) { registerButtonAction("Courses", action: "Send Email", label: course.subject_course) EmailAction.emailSomeone( "[email protected]", message: "I would like to take \(course.title).\nCRN: \(course.subject_course)", subject: "From an SSS App User", presenter: self ) } // MARK: Data Management @IBAction func switchCampus() { if campus == "All Campuses" { campus = "New York City" } else if campus == "New York City" { campus = "Pleasantville" } else if campus == "Pleasantville" { campus = "Online" } else if campus == "Online" { campus = "All Campuses" } registerButtonAction("Courses", action: "Switch Campus", label: campus) campusButton?.setTitle(campus, forState: .Normal) loadCoursesFromRealm(true) } func buildPredicate() -> NSPredicate? { var finalQuery = "" var setQuery = false var pred: NSPredicate? = nil if query.characters.count > 0 { finalQuery = "(title CONTAINS[c] %@ or subject_desc CONTAINS[c] %@ or subject_course CONTAINS[c] %@)" setQuery = true } if campus != "All Campuses" && setQuery { finalQuery.appendContentsOf(" AND campus = %@") pred = NSPredicate(format: finalQuery, query, query, query, campus) } else if campus != "All Campuses" { pred = NSPredicate(format: "campus = %@", campus) } else if setQuery { pred = NSPredicate(format: finalQuery, query, query, query) } return pred } func loadCoursesFromRealm(shouldReload: Bool) { let pred = buildPredicate() courses = ModelManager.sharedInstance.query(Course.self, queryString: pred).sorted("title") alphabets = [String]() var letters = [String:Int]() for course in courses! { letters[course.title.substringToIndex(course.title.characters.startIndex.successor())] = 1 } alphabets = Array(letters.keys).sort() if shouldReload { tableView!.reloadData() } NSLog("Done loading from realm!") } } //MARK: Text Field Delegate extension CourseVC: UITextFieldDelegate { func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { if let text = textField.text { let nsString = text as NSString query = nsString.stringByReplacingCharactersInRange(range, withString: string).stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) loadCoursesFromRealm(true) } return true } func textFieldShouldClear(textField: UITextField) -> Bool { query = "" registerButtonAction("Courses", action: "Clear Search", label: "") loadCoursesFromRealm(true) return true } func textFieldShouldReturn(textField: UITextField) -> Bool { if let text = textField.text { if text.characters.count > 0 { registerButtonAction("Courses", action: "Search Course", label: "\(text) - \(campus)") } } textField.resignFirstResponder() return true } }
mit
c2366753a5a2294ad46fa00efe7aaaa3
34.990654
163
0.601229
5.053806
false
false
false
false
devpunk/cartesian
cartesian/View/DrawProject/Menu/VDrawProjectMenuLabelsFontName.swift
1
4217
import UIKit class VDrawProjectMenuLabelsFontName:UIButton, MDrawProjectFontDelegate { let model:MDrawProjectMenuLabelsFont private weak var controller:CDrawProject! private weak var labelFont:UILabel! private let kTitleLeft:CGFloat = 10 private let kTitleWidth:CGFloat = 64 private let kBorderHeight:CGFloat = 1 private let kAlphaSelected:CGFloat = 0.2 private let kAlphaNotSelected:CGFloat = 1 init(controller:CDrawProject) { model = MDrawProjectMenuLabelsFont() super.init(frame:CGRect.zero) clipsToBounds = true backgroundColor = UIColor.clear translatesAutoresizingMaskIntoConstraints = false addTarget( self, action:#selector(actionButton(sender:)), for:UIControlEvents.touchUpInside) self.controller = controller let border:VBorder = VBorder(color:UIColor(white:0, alpha:0.1)) let labelTitle:UILabel = UILabel() labelTitle.translatesAutoresizingMaskIntoConstraints = false labelTitle.isUserInteractionEnabled = false labelTitle.backgroundColor = UIColor.clear labelTitle.font = UIFont.bolder(size:15) labelTitle.textColor = UIColor.cartesianBlue labelTitle.textAlignment = NSTextAlignment.center labelTitle.text = NSLocalizedString("VDrawProjectMenuLabelsFontName_labelTitle", comment:"") let labelFont:UILabel = UILabel() labelFont.translatesAutoresizingMaskIntoConstraints = false labelFont.isUserInteractionEnabled = false labelFont.backgroundColor = UIColor.clear labelFont.textColor = UIColor.black self.labelFont = labelFont addSubview(border) addSubview(labelTitle) addSubview(labelFont) NSLayoutConstraint.equalsVertical( view:labelTitle, toView:self) NSLayoutConstraint.leftToLeft( view:labelTitle, toView:self, constant:kTitleLeft) NSLayoutConstraint.width( view:labelTitle, constant:kTitleWidth) NSLayoutConstraint.equalsVertical( view:labelFont, toView:self) NSLayoutConstraint.leftToRight( view:labelFont, toView:labelTitle) NSLayoutConstraint.rightToRight( view:labelFont, toView:self) NSLayoutConstraint.topToTop( view:border, toView:self) NSLayoutConstraint.height( view:border, constant:kBorderHeight) NSLayoutConstraint.equalsHorizontal( view:border, toView:self) updateFont() } required init?(coder:NSCoder) { return nil } override var isSelected:Bool { didSet { hover() } } override var isHighlighted:Bool { didSet { hover() } } //MARK: actions func actionButton(sender button:UIButton) { let titleFont:String = NSLocalizedString("VDrawProjectMenuLabelsFontName_fontTitle", comment:"") controller.viewProject.showFont( title:titleFont, delegate:self) } //MARK: private private func hover() { if isSelected || isHighlighted { alpha = kAlphaSelected } else { alpha = kAlphaNotSelected } } private func updateFont() { if let font:MDrawProjectMenuLabelsFontItem = model.currentFont { if let currentType:String = font.currentType { labelFont.font = UIFont(name:currentType, size:13) labelFont.text = font.displayName() } } } //MARK: font delegate func fontCurrent() -> String? { return nil } func fontSelected(model:MDrawProjectMenuLabelsFontItem) { updateFont() } func fontModel() -> MDrawProjectMenuLabelsFont? { return model } }
mit
ddbd2088ca2caa52ed685b2000d2a37a
25.859873
104
0.594736
5.58543
false
false
false
false
Ashok28/Kingfisher
Sources/Image/GraphicsContext.swift
7
3087
// // GraphicsContext.swift // Kingfisher // // Created by taras on 19/04/2021. // // Copyright (c) 2021 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if canImport(AppKit) && !targetEnvironment(macCatalyst) import AppKit #endif #if canImport(UIKit) import UIKit #endif enum GraphicsContext { static func begin(size: CGSize, scale: CGFloat) { #if os(macOS) NSGraphicsContext.saveGraphicsState() #else UIGraphicsBeginImageContextWithOptions(size, false, scale) #endif } static func current(size: CGSize, scale: CGFloat, inverting: Bool, cgImage: CGImage?) -> CGContext? { #if os(macOS) guard let rep = NSBitmapImageRep( bitmapDataPlanes: nil, pixelsWide: Int(size.width), pixelsHigh: Int(size.height), bitsPerSample: cgImage?.bitsPerComponent ?? 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: .calibratedRGB, bytesPerRow: 0, bitsPerPixel: 0) else { assertionFailure("[Kingfisher] Image representation cannot be created.") return nil } rep.size = size guard let context = NSGraphicsContext(bitmapImageRep: rep) else { assertionFailure("[Kingfisher] Image context cannot be created.") return nil } NSGraphicsContext.current = context return context.cgContext #else guard let context = UIGraphicsGetCurrentContext() else { return nil } if inverting { // If drawing a CGImage, we need to make context flipped. context.scaleBy(x: 1.0, y: -1.0) context.translateBy(x: 0, y: -size.height) } return context #endif } static func end() { #if os(macOS) NSGraphicsContext.restoreGraphicsState() #else UIGraphicsEndImageContext() #endif } }
mit
c3faff27732b92fdd07caf16306a6a25
34.079545
105
0.648526
4.727412
false
false
false
false
LoopKit/LoopKit
LoopKit/LoopPluginBundleKey.swift
1
919
// // LoopPluginBundleKey.swift // LoopKit // // Created by Pete Schwamb on 7/24/19. // Copyright © 2019 LoopKit Authors. All rights reserved. // import Foundation public enum LoopPluginBundleKey: String { case pumpManagerDisplayName = "com.loopkit.Loop.PumpManagerDisplayName" case pumpManagerIdentifier = "com.loopkit.Loop.PumpManagerIdentifier" case cgmManagerDisplayName = "com.loopkit.Loop.CGMManagerDisplayName" case cgmManagerIdentifier = "com.loopkit.Loop.CGMManagerIdentifier" case serviceDisplayName = "com.loopkit.Loop.ServiceDisplayName" case serviceIdentifier = "com.loopkit.Loop.ServiceIdentifier" case onboardingIdentifier = "com.loopkit.Loop.OnboardingIdentifier" case supportIdentifier = "com.loopkit.Loop.SupportIdentifier" case extensionIdentifier = "com.loopkit.Loop.ExtensionIdentifier" case pluginIsSimulator = "com.loopkit.Loop.PluginIsSimulator" }
mit
78c5243a06c2b6774b07b014d1f9ce74
40.727273
75
0.781046
4.008734
false
false
false
false
fhchina/Form
Demos/CustomField/App/Source/AppController.swift
1
1329
import UIKit import Form.FORMDefaultStyle import NSJSONSerialization_ANDYJSONFile import Hex @UIApplicationMain class AppController: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { if let JSON = NSJSONSerialization.JSONObjectWithContentsOfFile("forms.json") as? [String : AnyObject] { let initialValues = [ "address" : "Burger Park 667", "end_date" : "2017-10-31 23:00:00 +00:00", "first_name" : "Ola", "last_name" : "Nordman", "start_date" : "2014-10-31 23:00:00 +00:00"] let sampleController = RootController(JSON: JSON, initialValues: initialValues) let rootViewController = UINavigationController(rootViewController: sampleController) rootViewController.view.tintColor = UIColor(fromHex: "5182AF") rootViewController.navigationBarHidden = true FORMDefaultStyle.applyStyle() self.window = UIWindow(frame: UIScreen.mainScreen().bounds) self.window?.rootViewController = rootViewController self.window?.makeKeyAndVisible() } return true } }
mit
cebb799a032e4c7d798503f2f6dd00ee
34.918919
127
0.645598
4.996241
false
false
false
false
mercadopago/px-ios
MercadoPagoSDK/MercadoPagoSDK/Services/Models/PXSplitConfiguration.swift
1
1898
import Foundation /// :nodoc: open class PXSplitConfiguration: NSObject, Codable { open var primaryPaymentMethod: PXSplitPaymentMethod? open var secondaryPaymentMethod: PXSplitPaymentMethod? open var splitEnabled: Bool = false public init(primaryPaymentMethod: PXSplitPaymentMethod?, secondaryPaymentMethod: PXSplitPaymentMethod?, splitEnabled: Bool) { self.primaryPaymentMethod = primaryPaymentMethod self.secondaryPaymentMethod = secondaryPaymentMethod self.splitEnabled = splitEnabled } public enum PXPayerCostConfiguration: String, CodingKey { case defaultSplit = "default_enabled" case primaryPaymentMethod = "primary_payment_method" case secondaryPaymentMethod = "secondary_payment_method" } public required convenience init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: PXPayerCostConfiguration.self) let defaultSplit: Bool = try container.decodeIfPresent(Bool.self, forKey: .defaultSplit) ?? false let primaryPaymentMethod: PXSplitPaymentMethod? = try container.decodeIfPresent(PXSplitPaymentMethod.self, forKey: .primaryPaymentMethod) let secondaryPaymentMethod: PXSplitPaymentMethod? = try container.decodeIfPresent(PXSplitPaymentMethod.self, forKey: .secondaryPaymentMethod) self.init(primaryPaymentMethod: primaryPaymentMethod, secondaryPaymentMethod: secondaryPaymentMethod, splitEnabled: defaultSplit) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: PXPayerCostConfiguration.self) try container.encodeIfPresent(self.splitEnabled, forKey: .defaultSplit) try container.encodeIfPresent(self.primaryPaymentMethod, forKey: .primaryPaymentMethod) try container.encodeIfPresent(self.secondaryPaymentMethod, forKey: .secondaryPaymentMethod) } }
mit
9ad1790efddb07d767cb7f30c58cb954
54.823529
149
0.771338
5.171662
false
true
false
false
infobip/mobile-messaging-sdk-ios
Example/MobileMessagingExample/Models/MessagesManager.swift
1
5463
// // MessagesManager.swift // MobileMessagingExample // // Created by Andrey K. on 20/05/16. // import UIKit import MobileMessaging let kMessageSeenAttribute = "seen" let kMessageDeliveryReportSentAttribute = "deliveryReportSent" let kMessagesKey = "kMessagesKey" class Message: NSObject, NSCoding { typealias APNSPayload = [String: Any] var text: String var messageId: String @objc dynamic var deliveryReportSent: Bool = false @objc dynamic var seen : Bool = false required init(text: String, messageId: String){ self.text = text self.messageId = messageId super.init() } //MARK: NSCoding required init(coder aDecoder: NSCoder) { text = aDecoder.decodeObject(forKey: "text") as! String messageId = aDecoder.decodeObject(forKey: "messageId") as! String deliveryReportSent = aDecoder.decodeBool(forKey: kMessageDeliveryReportSentAttribute) seen = aDecoder.decodeBool(forKey: kMessageSeenAttribute) } func encode(with aCoder: NSCoder) { aCoder.encode(text, forKey: "text") aCoder.encode(messageId, forKey: "messageId") aCoder.encode(deliveryReportSent, forKey: kMessageDeliveryReportSentAttribute) aCoder.encode(seen, forKey: kMessageSeenAttribute) } //MARK: Util class func make(from mtMessage: MM_MTMessage) -> Message? { guard let text = mtMessage.text else { return nil } return Message(text: text, messageId: mtMessage.messageId) } } final class MessagesManager: NSObject, UITableViewDataSource { static let sharedInstance = MessagesManager() var newMessageBlock: ((Message) -> Void)? var messages = [Message]() deinit { NotificationCenter.default.removeObserver(self) } override init() { super.init() unarchiveMessages() startObservingNotifications() } func cleanMessages() { synced(self) { self.messages.removeAll() UserDefaults.standard.removeObject(forKey: kMessagesKey) } } //MARK: Private fileprivate func synced(_ lock: AnyObject, closure: () -> Void) { objc_sync_enter(lock) closure() objc_sync_exit(lock) } fileprivate func startObservingNotifications() { NotificationCenter.default.addObserver(self, selector: #selector(MessagesManager.appWillTerminate), name: UIApplication.willTerminateNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(MessagesManager.handleNewMessageReceivedNotification(_:)), name: NSNotification.Name(rawValue: MMNotificationMessageReceived), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(MessagesManager.handleDeliveryReportSentNotification(_:)), name: NSNotification.Name(rawValue: MMNotificationDeliveryReportSent), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(MessagesManager.handleTapNotification), name: NSNotification.Name(rawValue: MMNotificationMessageTapped), object: nil) } fileprivate func archiveMessages() { synced(self) { let data: Data = NSKeyedArchiver.archivedData(withRootObject: self.messages) UserDefaults.standard.set(data, forKey: kMessagesKey) } } fileprivate func unarchiveMessages() { synced(self) { if let messagesData = UserDefaults.standard.object(forKey: kMessagesKey) as? Data, let messages = NSKeyedUnarchiver.unarchiveObject(with: messagesData) as? [Message] { self.messages.append(contentsOf: messages) } } } //MARK: Handle notifications @objc func appWillTerminate() { archiveMessages() } @objc func handleNewMessageReceivedNotification(_ notification: Notification) { guard let userInfo = notification.userInfo, let mtmessage = userInfo[MMNotificationKeyMessage] as? MM_MTMessage, let message = Message.make(from: mtmessage) else { return } synced(self) { self.messages.insert(message, at: 0) } newMessageBlock?(message) } @objc func handleDeliveryReportSentNotification(_ notification: Notification) { guard let userInfo = notification.userInfo, let messageUserInfo = userInfo[MMNotificationKeyDLRMessageIDs] as? [String] else { return } for message in messages { if messageUserInfo.contains(message.messageId) { message.deliveryReportSent = true } } } @objc func handleTapNotification(_ notification: Notification) { guard let userInfo = notification.userInfo, let message = userInfo[MMNotificationKeyMessage] as? MM_MTMessage else { return } LinksHandler.handleLinks(fromMessage: message) } //MARK: UITableViewDataSource func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return messages.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if let cell = tableView.dequeueReusableCell(withIdentifier: kMessageCellId, for: indexPath) as? MessageCell { cell.message = messages[indexPath.row] return cell } fatalError() } }
apache-2.0
6804d3f57790b6a8e8be1666fe74d2a1
30.578035
125
0.671792
4.41633
false
false
false
false
Skorch/VueTabController
VueTabController/VueTabBarSegue.swift
1
1250
// // BurstTabBarSegue.swift // burstprototype // // Created by Drew Beaupre on 2015-09-14. // Copyright © 2015 Glass 10. All rights reserved. // import UIKit class VueTabBarSegue: UIStoryboardSegue { weak var cachedViewController: UIViewController? override func perform() { guard let tabController = self.sourceViewController as? VueTabBarViewController else{ return assertionFailure("Segue source is not Burst Tab Bar controller") } let contentController = cachedViewController ?? self.destinationViewController if let currentViewController = tabController.currentViewController{ currentViewController.willMoveToParentViewController(nil) currentViewController.view.removeFromSuperview() currentViewController.removeFromParentViewController() } tabController.currentViewController = contentController tabController.addChildViewController(contentController) contentController.view.frame = tabController.contentView.bounds tabController.contentView.addSubview(contentController.view) contentController.didMoveToParentViewController(tabController) } }
mit
8de9588e809021332c60045ab30f2b70
32.756757
93
0.716573
6.276382
false
false
false
false
aloe-kawase/aloeutils
Pod/Classes/AloeFile.swift
1
768
// // AloeFile.swift // Pods // // Created by kawase yu on 2015/09/24. // // import UIKit public class AloeFile: NSObject { private class func documentDir()->String{ let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) return paths[0] } public class func saveDocumentFile(fileName:String, data:NSData)->Bool{ let path = documentDir() + "/" + fileName print(path) let success = data.writeToFile(path, atomically: true) return success } public class func loadDocumentFile(fileName:String)->NSData?{ let path = documentDir() + "/" + fileName let data = NSData(contentsOfFile: path) return data } }
mit
c0eb3adf70e2b03ca1a454f88aa1edd1
22.272727
98
0.615885
4.439306
false
false
false
false
cruisediary/GitHub
GitHub/Views/UICollectionViews/ListIssueCell.swift
1
877
// // ListIssueCell.swift // GitHub // // Created by CruzDiary on 15/01/2017. // Copyright © 2017 cruz. All rights reserved. // import UIKit class ListIssueCell: UICollectionViewCell { static let nibName = "ListIssueCell" static let reuseIdentifier = "ListIssueCell" static let height: CGFloat = 64 @IBOutlet weak var repoLabel: UILabel! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var openedInfoLabel: UILabel! @IBOutlet weak var issueNumberLabel: UILabel! func configure(issue: Issue) { guard let number = issue.number else { return } repoLabel.text = issue.url titleLabel.text = issue.title issueNumberLabel.text = "#\(number)" openedInfoLabel.text = issue.openedInfo } override func awakeFromNib() { super.awakeFromNib() // Initialization code } }
mit
e1b2b1a87cbe03182300f5cb3d208972
25.545455
55
0.667808
4.336634
false
false
false
false
RMizin/PigeonMessenger-project
FalconMessenger/Authentication/PhoneAuthentication/PhoneNumberControllers/PhoneNumberContainerView.swift
1
8688
// // PhoneNumberContainerView.swift // Pigeon-project // // Created by Roman Mizin on 8/2/17. // Copyright © 2017 Roman Mizin. All rights reserved. // import UIKit final class PhoneNumberContainerView: UIView { let title: UILabel = { let title = UILabel() title.translatesAutoresizingMaskIntoConstraints = false title.textAlignment = .center title.text = "Phone number" title.textColor = ThemeManager.currentTheme().generalTitleColor title.font = UIFont.systemFont(ofSize: 32) if #available(iOS 11.0, *) { title.isHidden = true } return title }() let instructions: UILabel = { let instructions = UILabel() instructions.translatesAutoresizingMaskIntoConstraints = false instructions.textAlignment = .center instructions.numberOfLines = 2 instructions.textColor = ThemeManager.currentTheme().generalTitleColor instructions.font = UIFont.boldSystemFont(ofSize: 18)//systemFont(ofSize: 18) instructions.sizeToFit() return instructions }() let selectCountry: ControlButton = { let selectCountry = ControlButton() selectCountry.translatesAutoresizingMaskIntoConstraints = false selectCountry.setTitle("Canada", for: .normal) selectCountry.addTarget(self, action: #selector(PhoneNumberController.openCountryCodesList), for: .touchUpInside) return selectCountry }() var countryCode: UILabel = { var countryCode = UILabel() countryCode.translatesAutoresizingMaskIntoConstraints = false countryCode.text = "+1" countryCode.textAlignment = .center countryCode.textColor = ThemeManager.currentTheme().generalTitleColor countryCode.font = UIFont.boldSystemFont(ofSize: 18) countryCode.sizeToFit() return countryCode }() let phoneNumber: UITextField = { let phoneNumber = UITextField() phoneNumber.font = UIFont.boldSystemFont(ofSize: 18) phoneNumber.translatesAutoresizingMaskIntoConstraints = false phoneNumber.textAlignment = .center phoneNumber.keyboardType = .numberPad phoneNumber.keyboardAppearance = ThemeManager.currentTheme().keyboardAppearance phoneNumber.textColor = ThemeManager.currentTheme().generalTitleColor phoneNumber.addTarget(self, action: #selector(PhoneNumberController.textFieldDidChange(_:)), for: .editingChanged) if !DeviceType.isIPad { phoneNumber.addDoneButtonOnKeyboard() } return phoneNumber }() let termsAndPrivacy: UITextView = { let termsAndPrivacy = UITextView() termsAndPrivacy.translatesAutoresizingMaskIntoConstraints = false termsAndPrivacy.isEditable = false termsAndPrivacy.backgroundColor = .clear termsAndPrivacy.textColor = ThemeManager.currentTheme().generalTitleColor termsAndPrivacy.dataDetectorTypes = .all termsAndPrivacy.isScrollEnabled = false termsAndPrivacy.textContainerInset.top = 0 termsAndPrivacy.sizeToFit() return termsAndPrivacy }() var phoneContainer: UIView = { var phoneContainer = UIView() phoneContainer.translatesAutoresizingMaskIntoConstraints = false phoneContainer.layer.cornerRadius = 25 phoneContainer.layer.borderWidth = 1 phoneContainer.layer.borderColor = ThemeManager.currentTheme().inputTextViewColor.cgColor return phoneContainer }() override init(frame: CGRect) { super.init(frame: frame) addSubview(title) addSubview(instructions) addSubview(selectCountry) addSubview(termsAndPrivacy) addSubview(phoneContainer) phoneContainer.addSubview(countryCode) phoneContainer.addSubview(phoneNumber) let countriesFetcher = CountriesFetcher() countriesFetcher.delegate = self countriesFetcher.fetchCountries() phoneNumber.delegate = self configureTextViewText() let leftConstant: CGFloat = 10 let rightConstant: CGFloat = -10 let heightConstant: CGFloat = 50 let spacingConstant: CGFloat = 20 if #available(iOS 11.0, *) { title.heightAnchor.constraint(equalToConstant: 0).isActive = true } else { title.sizeToFit() } NSLayoutConstraint.activate([ title.topAnchor.constraint(equalTo: topAnchor, constant: spacingConstant), title.rightAnchor.constraint(equalTo: rightAnchor, constant: rightConstant), title.leftAnchor.constraint(equalTo: leftAnchor, constant: leftConstant), instructions.topAnchor.constraint(equalTo: title.bottomAnchor, constant: spacingConstant), instructions.rightAnchor.constraint(equalTo: title.rightAnchor), instructions.leftAnchor.constraint(equalTo: title.leftAnchor), selectCountry.topAnchor.constraint(equalTo: instructions.bottomAnchor, constant: spacingConstant), selectCountry.rightAnchor.constraint(equalTo: title.rightAnchor), selectCountry.leftAnchor.constraint(equalTo: title.leftAnchor), selectCountry.heightAnchor.constraint(equalToConstant: heightConstant), phoneContainer.topAnchor.constraint(equalTo: selectCountry.bottomAnchor, constant: spacingConstant), phoneContainer.rightAnchor.constraint(equalTo: title.rightAnchor), phoneContainer.leftAnchor.constraint(equalTo: title.leftAnchor), phoneContainer.heightAnchor.constraint(equalToConstant: heightConstant), countryCode.leftAnchor.constraint(equalTo: phoneContainer.leftAnchor, constant: leftConstant), countryCode.centerYAnchor.constraint(equalTo: phoneContainer.centerYAnchor), countryCode.heightAnchor.constraint(equalTo: phoneContainer.heightAnchor), phoneNumber.rightAnchor.constraint(equalTo: phoneContainer.rightAnchor, constant: rightConstant), phoneNumber.leftAnchor.constraint(equalTo: countryCode.rightAnchor, constant: leftConstant), phoneNumber.centerYAnchor.constraint(equalTo: phoneContainer.centerYAnchor), phoneNumber.heightAnchor.constraint(equalTo: phoneContainer.heightAnchor), termsAndPrivacy.topAnchor.constraint(equalTo: phoneContainer.bottomAnchor, constant: 15), termsAndPrivacy.rightAnchor.constraint(equalTo: title.rightAnchor), termsAndPrivacy.leftAnchor.constraint(equalTo: title.leftAnchor) ]) } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! } private func configureTextViewText() { let font = UIFont.boldSystemFont(ofSize: 14) let termsURL = URL(string: "https://docs.google.com/document/d/19PQFh9LzXz1HO2Zq6U7ysCESIbGoodY6rBJbOeCyjkc/edit?usp=sharing")! let privacyURL = URL(string: "https://docs.google.com/document/d/1r365Yan3Ng4l0T4o7UXqLid8BKm4N4Z3cSGTnzzA7Fg/edit?usp=sharing")! let termsString = "By signing up, you agree to the Terms of Service." let privacyString = " Also if you still have not read the Privacy Policy, please take a look before signing up." let termsAndConditionsAttributes = [NSAttributedString.Key.link: termsURL, NSAttributedString.Key.foregroundColor: UIColor.blue, NSAttributedString.Key.font: font] as [NSAttributedString.Key : Any] let privacyPolicyAttributes = [NSAttributedString.Key.link: privacyURL, NSAttributedString.Key.foregroundColor: UIColor.blue, NSAttributedString.Key.font: font] as [NSAttributedString.Key : Any] //and Conditions let termsAttributedString = NSMutableAttributedString(string: termsString, attributes: [NSAttributedString.Key.foregroundColor: ThemeManager.currentTheme().generalTitleColor, NSAttributedString.Key.font: font]) termsAttributedString.setAttributes(termsAndConditionsAttributes, range: NSRange(location: 31, length: 17)) let privacyAttributedString = NSMutableAttributedString(string: privacyString, attributes: [NSAttributedString.Key.foregroundColor: ThemeManager.currentTheme().generalTitleColor, NSAttributedString.Key.font: font]) privacyAttributedString.setAttributes(privacyPolicyAttributes, range: NSRange(location: 37, length: 14)) termsAttributedString.append(privacyAttributedString) termsAndPrivacy.attributedText = termsAttributedString } } extension PhoneNumberContainerView: UITextFieldDelegate { func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { guard let text = textField.text else { return true } let newLength = text.utf16.count + string.utf16.count - range.length return newLength <= 25 } } extension PhoneNumberContainerView: CountriesFetcherDelegate { func countriesFetcher(_ fetcher: CountriesFetcher, currentCountry country: Country) { selectCountry.setTitle(country.name, for: .normal) countryCode.text = country.dialCode } }
gpl-3.0
d014e93d4b76d2a4545113609fb6edc6
40.966184
216
0.757914
5.050581
false
false
false
false
2794129697/-----mx
CoolXuePlayer/FeedbackUnLoginTipVC.swift
1
2596
// // FeedbackUnLoginTipVC.swift // CoolXuePlayer // // Created by lion-mac on 15/7/23. // Copyright (c) 2015年 lion-mac. All rights reserved. // import UIKit class FeedbackUnLoginTipVC: UIViewController { override func viewDidLoad() { super.viewDidLoad() self.setView() } func setView(){ self.view.backgroundColor = UIColor.whiteColor() var tipLabel = UILabel(frame: CGRectMake((self.view.bounds.width - 200)/2, 100, 200, 40)) tipLabel.font = UIFont.systemFontOfSize(12) tipLabel.text = "登录后才能查看反馈信息" tipLabel.textAlignment = NSTextAlignment.Center self.view.addSubview(tipLabel) var bnLogin = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton bnLogin.backgroundColor = UIColor.redColor() bnLogin.frame = CGRectMake((self.view.bounds.width - 100)/2, 150, 100, 40) bnLogin.titleLabel?.textColor = UIColor.blueColor() bnLogin.titleLabel?.text = "登录" bnLogin.setTitle("登录", forState: UIControlState.Normal) bnLogin.addTarget(self, action: "ToLoginVC", forControlEvents: UIControlEvents.TouchUpInside) self.view.addSubview(bnLogin) self.navigationController?.title = "播放历史" } func ToLoginVC(){ var s = UIStoryboard(name: "Main", bundle: nil) var tab = s.instantiateViewControllerWithIdentifier("loginTab") as? LoginUITabBarController self.navigationController?.pushViewController(tab!, animated: true) } override func viewWillAppear(animated: Bool) { //super.viewWillAppear(animated) if LoginTool.isLogin == true { self.navigationController?.popViewControllerAnimated(true) // for v in self.navigationController!.viewControllers { // if v.isKindOfClass(UserCenterVC){ // v.performSegueWithIdentifier("ToFeedbackVC", sender: nil) // break // } // } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
lgpl-3.0
7b8a1874f3417338e7413b47e6344218
34.5
106
0.646714
4.664234
false
false
false
false
tus/TUSKit
Tests/TUSKitTests/Fixtures.swift
1
1273
import XCTest struct Fixtures { static let chunkSize: Int = 500 * 1024 static func makeFilePath() throws -> URL { // Loading resources normally gives an error on github actions // Originally, you can load like this: // let bundle = Bundle.module // let path = try XCTUnwrap(bundle.path(forResource: "memeCat", ofType: "jpg")) // return try XCTUnwrap(URL(string: path)) // But the CI doesn't accept that. // Instead, we'll look up the current file and load from there. let thisSourceFile = URL(fileURLWithPath: #file) let thisDirectory = thisSourceFile.deletingLastPathComponent() let resourceURL = thisDirectory.appendingPathComponent("Resources/memeCat.jpg") return resourceURL } static func loadData() throws -> Data { // We need to prepend with file:// so Data can load it. let prefixedPath = try "file://" + makeFilePath().absoluteString return try Data(contentsOf: URL(string:prefixedPath)!) } /// Make a Data file larger than the chunk size /// - Returns: Data static func makeLargeData() -> Data { return Data(repeatElement(1, count: chunkSize + 1)) } }
mit
fb497df9b1cf354e89e6c3fc371cf7be
33.405405
87
0.622152
4.803774
false
true
false
false
ben-ng/swift
test/SILGen/builtins.swift
3
33149
// RUN: %target-swift-frontend -emit-silgen -parse-stdlib %s -disable-objc-attr-requires-foundation-module | %FileCheck %s // RUN: %target-swift-frontend -emit-sil -Onone -parse-stdlib %s -disable-objc-attr-requires-foundation-module | %FileCheck -check-prefix=CANONICAL %s import Swift protocol ClassProto : class { } struct Pointer { var value: Builtin.RawPointer } // CHECK-LABEL: sil hidden @_TF8builtins3foo func foo(_ x: Builtin.Int1, y: Builtin.Int1) -> Builtin.Int1 { // CHECK: builtin "cmp_eq_Int1" return Builtin.cmp_eq_Int1(x, y) } // CHECK-LABEL: sil hidden @_TF8builtins8load_pod func load_pod(_ x: Builtin.RawPointer) -> Builtin.Int64 { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.Int64 // CHECK: [[VAL:%.*]] = load [trivial] [[ADDR]] // CHECK: return [[VAL]] return Builtin.load(x) } // CHECK-LABEL: sil hidden @_TF8builtins8load_obj func load_obj(_ x: Builtin.RawPointer) -> Builtin.NativeObject { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.NativeObject // CHECK: [[VAL:%.*]] = load [copy] [[ADDR]] // CHECK: return [[VAL]] return Builtin.load(x) } // CHECK-LABEL: sil hidden @_TF8builtins12load_raw_pod func load_raw_pod(_ x: Builtin.RawPointer) -> Builtin.Int64 { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to $*Builtin.Int64 // CHECK: [[VAL:%.*]] = load [trivial] [[ADDR]] // CHECK: return [[VAL]] return Builtin.loadRaw(x) } // CHECK-LABEL: sil hidden @_TF8builtins12load_raw_obj func load_raw_obj(_ x: Builtin.RawPointer) -> Builtin.NativeObject { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to $*Builtin.NativeObject // CHECK: [[VAL:%.*]] = load [copy] [[ADDR]] // CHECK: return [[VAL]] return Builtin.loadRaw(x) } // CHECK-LABEL: sil hidden @_TF8builtins8load_gen func load_gen<T>(_ x: Builtin.RawPointer) -> T { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*T // CHECK: copy_addr [[ADDR]] to [initialization] {{%.*}} return Builtin.load(x) } // CHECK-LABEL: sil hidden @_TF8builtins8move_pod func move_pod(_ x: Builtin.RawPointer) -> Builtin.Int64 { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.Int64 // CHECK: [[VAL:%.*]] = load [trivial] [[ADDR]] // CHECK: return [[VAL]] return Builtin.take(x) } // CHECK-LABEL: sil hidden @_TF8builtins8move_obj func move_obj(_ x: Builtin.RawPointer) -> Builtin.NativeObject { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.NativeObject // CHECK: [[VAL:%.*]] = load [take] [[ADDR]] // CHECK-NOT: copy_value [[VAL]] // CHECK: return [[VAL]] return Builtin.take(x) } // CHECK-LABEL: sil hidden @_TF8builtins8move_gen func move_gen<T>(_ x: Builtin.RawPointer) -> T { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*T // CHECK: copy_addr [take] [[ADDR]] to [initialization] {{%.*}} return Builtin.take(x) } // CHECK-LABEL: sil hidden @_TF8builtins11destroy_pod func destroy_pod(_ x: Builtin.RawPointer) { var x = x // CHECK: [[XBOX:%[0-9]+]] = alloc_box // CHECK-NOT: pointer_to_address // CHECK-NOT: destroy_addr // CHECK-NOT: destroy_value // CHECK: destroy_value [[XBOX]] : ${{.*}}{ // CHECK-NOT: destroy_value return Builtin.destroy(Builtin.Int64, x) // CHECK: return } // CHECK-LABEL: sil hidden @_TF8builtins11destroy_obj func destroy_obj(_ x: Builtin.RawPointer) { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.NativeObject // CHECK: destroy_addr [[ADDR]] return Builtin.destroy(Builtin.NativeObject, x) } // CHECK-LABEL: sil hidden @_TF8builtins11destroy_gen func destroy_gen<T>(_ x: Builtin.RawPointer, _: T) { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*T // CHECK: destroy_addr [[ADDR]] return Builtin.destroy(T.self, x) } // CHECK-LABEL: sil hidden @_TF8builtins10assign_pod func assign_pod(_ x: Builtin.Int64, y: Builtin.RawPointer) { var x = x var y = y // CHECK: alloc_box // CHECK: alloc_box // CHECK-NOT: alloc_box // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.Int64 // CHECK-NOT: load [[ADDR]] // CHECK: assign {{%.*}} to [[ADDR]] // CHECK: destroy_value // CHECK: destroy_value // CHECK-NOT: destroy_value Builtin.assign(x, y) // CHECK: return } // CHECK-LABEL: sil hidden @_TF8builtins10assign_obj func assign_obj(_ x: Builtin.NativeObject, y: Builtin.RawPointer) { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.NativeObject // CHECK: assign {{%.*}} to [[ADDR]] // CHECK: destroy_value Builtin.assign(x, y) } // CHECK-LABEL: sil hidden @_TF8builtins12assign_tuple func assign_tuple(_ x: (Builtin.Int64, Builtin.NativeObject), y: Builtin.RawPointer) { var x = x var y = y // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*(Builtin.Int64, Builtin.NativeObject) // CHECK: [[T0:%.*]] = tuple_element_addr [[ADDR]] // CHECK: assign {{%.*}} to [[T0]] // CHECK: [[T0:%.*]] = tuple_element_addr [[ADDR]] // CHECK: assign {{%.*}} to [[T0]] // CHECK: destroy_value Builtin.assign(x, y) } // CHECK-LABEL: sil hidden @_TF8builtins10assign_gen func assign_gen<T>(_ x: T, y: Builtin.RawPointer) { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*T // CHECK: copy_addr [take] {{%.*}} to [[ADDR]] : Builtin.assign(x, y) } // CHECK-LABEL: sil hidden @_TF8builtins8init_pod func init_pod(_ x: Builtin.Int64, y: Builtin.RawPointer) { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.Int64 // CHECK-NOT: load [[ADDR]] // CHECK: store {{%.*}} to [trivial] [[ADDR]] // CHECK-NOT: destroy_value [[ADDR]] Builtin.initialize(x, y) } // CHECK-LABEL: sil hidden @_TF8builtins8init_obj func init_obj(_ x: Builtin.NativeObject, y: Builtin.RawPointer) { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*Builtin.NativeObject // CHECK-NOT: load [[ADDR]] // CHECK: store [[SRC:%.*]] to [init] [[ADDR]] // CHECK-NOT: destroy_value [[SRC]] Builtin.initialize(x, y) } // CHECK-LABEL: sil hidden @_TF8builtins8init_gen func init_gen<T>(_ x: T, y: Builtin.RawPointer) { // CHECK: [[ADDR:%.*]] = pointer_to_address {{%.*}} to [strict] $*T // CHECK: copy_addr [[OTHER_LOC:%.*]] to [initialization] [[ADDR]] // CHECK: destroy_addr [[OTHER_LOC]] Builtin.initialize(x, y) } class C {} class D {} // CHECK-LABEL: sil hidden @_TF8builtins22class_to_native_object func class_to_native_object(_ c:C) -> Builtin.NativeObject { // CHECK: [[OBJ:%.*]] = unchecked_ref_cast [[C:%.*]] to $Builtin.NativeObject // CHECK-NOT: destroy_value [[C]] // CHECK-NOT: destroy_value [[OBJ]] // CHECK: return [[OBJ]] return Builtin.castToNativeObject(c) } // CHECK-LABEL: sil hidden @_TF8builtins23class_to_unknown_object func class_to_unknown_object(_ c:C) -> Builtin.UnknownObject { // CHECK: [[OBJ:%.*]] = unchecked_ref_cast [[C:%.*]] to $Builtin.UnknownObject // CHECK-NOT: destroy_value [[C]] // CHECK-NOT: destroy_value [[OBJ]] // CHECK: return [[OBJ]] return Builtin.castToUnknownObject(c) } // CHECK-LABEL: sil hidden @_TF8builtins32class_archetype_to_native_object func class_archetype_to_native_object<T : C>(_ t: T) -> Builtin.NativeObject { // CHECK: [[OBJ:%.*]] = unchecked_ref_cast [[C:%.*]] to $Builtin.NativeObject // CHECK-NOT: destroy_value [[C]] // CHECK-NOT: destroy_value [[OBJ]] // CHECK: return [[OBJ]] return Builtin.castToNativeObject(t) } // CHECK-LABEL: sil hidden @_TF8builtins33class_archetype_to_unknown_object func class_archetype_to_unknown_object<T : C>(_ t: T) -> Builtin.UnknownObject { // CHECK: [[OBJ:%.*]] = unchecked_ref_cast [[C:%.*]] to $Builtin.UnknownObject // CHECK-NOT: destroy_value [[C]] // CHECK-NOT: destroy_value [[OBJ]] // CHECK: return [[OBJ]] return Builtin.castToUnknownObject(t) } // CHECK-LABEL: sil hidden @_TF8builtins34class_existential_to_native_object func class_existential_to_native_object(_ t:ClassProto) -> Builtin.NativeObject { // CHECK: [[REF:%[0-9]+]] = open_existential_ref [[T:%[0-9]+]] : $ClassProto // CHECK: [[PTR:%[0-9]+]] = unchecked_ref_cast [[REF]] : $@opened({{.*}}) ClassProto to $Builtin.NativeObject return Builtin.castToNativeObject(t) } // CHECK-LABEL: sil hidden @_TF8builtins35class_existential_to_unknown_object func class_existential_to_unknown_object(_ t:ClassProto) -> Builtin.UnknownObject { // CHECK: [[REF:%[0-9]+]] = open_existential_ref [[T:%[0-9]+]] : $ClassProto // CHECK: [[PTR:%[0-9]+]] = unchecked_ref_cast [[REF]] : $@opened({{.*}}) ClassProto to $Builtin.UnknownObject return Builtin.castToUnknownObject(t) } // CHECK-LABEL: sil hidden @_TF8builtins24class_from_native_object func class_from_native_object(_ p: Builtin.NativeObject) -> C { // CHECK: [[C:%.*]] = unchecked_ref_cast [[OBJ:%.*]] to $C // CHECK-NOT: destroy_value [[C]] // CHECK-NOT: destroy_value [[OBJ]] // CHECK: return [[C]] return Builtin.castFromNativeObject(p) } // CHECK-LABEL: sil hidden @_TF8builtins25class_from_unknown_object func class_from_unknown_object(_ p: Builtin.UnknownObject) -> C { // CHECK: [[C:%.*]] = unchecked_ref_cast [[OBJ:%.*]] to $C // CHECK-NOT: destroy_value [[C]] // CHECK-NOT: destroy_value [[OBJ]] // CHECK: return [[C]] return Builtin.castFromUnknownObject(p) } // CHECK-LABEL: sil hidden @_TF8builtins34class_archetype_from_native_object func class_archetype_from_native_object<T : C>(_ p: Builtin.NativeObject) -> T { // CHECK: [[C:%.*]] = unchecked_ref_cast [[OBJ:%.*]] : $Builtin.NativeObject to $T // CHECK-NOT: destroy_value [[C]] // CHECK-NOT: destroy_value [[OBJ]] // CHECK: return [[C]] return Builtin.castFromNativeObject(p) } // CHECK-LABEL: sil hidden @_TF8builtins35class_archetype_from_unknown_object func class_archetype_from_unknown_object<T : C>(_ p: Builtin.UnknownObject) -> T { // CHECK: [[C:%.*]] = unchecked_ref_cast [[OBJ:%.*]] : $Builtin.UnknownObject to $T // CHECK-NOT: destroy_value [[C]] // CHECK-NOT: destroy_value [[OBJ]] // CHECK: return [[C]] return Builtin.castFromUnknownObject(p) } // CHECK-LABEL: sil hidden @_TF8builtins41objc_class_existential_from_native_object func objc_class_existential_from_native_object(_ p: Builtin.NativeObject) -> AnyObject { // CHECK: [[C:%.*]] = unchecked_ref_cast [[OBJ:%.*]] : $Builtin.NativeObject to $AnyObject // CHECK-NOT: destroy_value [[C]] // CHECK-NOT: destroy_value [[OBJ]] // CHECK: return [[C]] return Builtin.castFromNativeObject(p) } // CHECK-LABEL: sil hidden @_TF8builtins42objc_class_existential_from_unknown_object func objc_class_existential_from_unknown_object(_ p: Builtin.UnknownObject) -> AnyObject { // CHECK: [[C:%.*]] = unchecked_ref_cast [[OBJ:%.*]] : $Builtin.UnknownObject to $AnyObject // CHECK-NOT: destroy_value [[C]] // CHECK-NOT: destroy_value [[OBJ]] // CHECK: return [[C]] return Builtin.castFromUnknownObject(p) } // CHECK-LABEL: sil hidden @_TF8builtins20class_to_raw_pointer func class_to_raw_pointer(_ c: C) -> Builtin.RawPointer { // CHECK: [[RAW:%.*]] = ref_to_raw_pointer [[C:%.*]] to $Builtin.RawPointer // CHECK: return [[RAW]] return Builtin.bridgeToRawPointer(c) } func class_archetype_to_raw_pointer<T : C>(_ t: T) -> Builtin.RawPointer { return Builtin.bridgeToRawPointer(t) } protocol CP: class {} func existential_to_raw_pointer(_ p: CP) -> Builtin.RawPointer { return Builtin.bridgeToRawPointer(p) } // CHECK-LABEL: sil hidden @_TF8builtins18obj_to_raw_pointer func obj_to_raw_pointer(_ c: Builtin.NativeObject) -> Builtin.RawPointer { // CHECK: [[RAW:%.*]] = ref_to_raw_pointer [[C:%.*]] to $Builtin.RawPointer // CHECK: return [[RAW]] return Builtin.bridgeToRawPointer(c) } // CHECK-LABEL: sil hidden @_TF8builtins22class_from_raw_pointer func class_from_raw_pointer(_ p: Builtin.RawPointer) -> C { // CHECK: [[C:%.*]] = raw_pointer_to_ref [[RAW:%.*]] to $C // CHECK: [[C_COPY:%.*]] = copy_value [[C]] // CHECK: return [[C_COPY]] return Builtin.bridgeFromRawPointer(p) } func class_archetype_from_raw_pointer<T : C>(_ p: Builtin.RawPointer) -> T { return Builtin.bridgeFromRawPointer(p) } // CHECK-LABEL: sil hidden @_TF8builtins20obj_from_raw_pointer func obj_from_raw_pointer(_ p: Builtin.RawPointer) -> Builtin.NativeObject { // CHECK: [[C:%.*]] = raw_pointer_to_ref [[RAW:%.*]] to $Builtin.NativeObject // CHECK: [[C_COPY:%.*]] = copy_value [[C]] // CHECK: return [[C_COPY]] return Builtin.bridgeFromRawPointer(p) } // CHECK-LABEL: sil hidden @_TF8builtins28unknown_obj_from_raw_pointer func unknown_obj_from_raw_pointer(_ p: Builtin.RawPointer) -> Builtin.UnknownObject { // CHECK: [[C:%.*]] = raw_pointer_to_ref [[RAW:%.*]] to $Builtin.UnknownObject // CHECK: [[C_COPY:%.*]] = copy_value [[C]] // CHECK: return [[C_COPY]] return Builtin.bridgeFromRawPointer(p) } // CHECK-LABEL: sil hidden @_TF8builtins28existential_from_raw_pointer func existential_from_raw_pointer(_ p: Builtin.RawPointer) -> AnyObject { // CHECK: [[C:%.*]] = raw_pointer_to_ref [[RAW:%.*]] to $AnyObject // CHECK: [[C_COPY:%.*]] = copy_value [[C]] // CHECK: return [[C_COPY]] return Builtin.bridgeFromRawPointer(p) } // CHECK-LABEL: sil hidden @_TF8builtins9gep_raw64 func gep_raw64(_ p: Builtin.RawPointer, i: Builtin.Int64) -> Builtin.RawPointer { // CHECK: [[GEP:%.*]] = index_raw_pointer // CHECK: return [[GEP]] return Builtin.gepRaw_Int64(p, i) } // CHECK-LABEL: sil hidden @_TF8builtins9gep_raw32 func gep_raw32(_ p: Builtin.RawPointer, i: Builtin.Int32) -> Builtin.RawPointer { // CHECK: [[GEP:%.*]] = index_raw_pointer // CHECK: return [[GEP]] return Builtin.gepRaw_Int32(p, i) } // CHECK-LABEL: sil hidden @_TF8builtins3gep func gep<Elem>(_ p: Builtin.RawPointer, i: Builtin.Word, e: Elem.Type) -> Builtin.RawPointer { // CHECK: [[P2A:%.*]] = pointer_to_address %0 // CHECK: [[GEP:%.*]] = index_addr [[P2A]] : $*Elem, %1 : $Builtin.Word // CHECK: [[A2P:%.*]] = address_to_pointer [[GEP]] // CHECK: return [[A2P]] return Builtin.gep_Word(p, i, e) } public final class Header { } // CHECK-LABEL: sil hidden @_TF8builtins20allocWithTailElems_1 func allocWithTailElems_1<T>(n: Builtin.Word, ty: T.Type) -> Header { // CHECK: [[M:%.*]] = metatype $@thick Header.Type // CHECK: [[A:%.*]] = alloc_ref [tail_elems $T * %0 : $Builtin.Word] $Header // CHECK: return [[A]] return Builtin.allocWithTailElems_1(Header.self, n, ty) } // CHECK-LABEL: sil hidden @_TF8builtins20allocWithTailElems_3 func allocWithTailElems_3<T1, T2, T3>(n1: Builtin.Word, ty1: T1.Type, n2: Builtin.Word, ty2: T2.Type, n3: Builtin.Word, ty3: T3.Type) -> Header { // CHECK: [[M:%.*]] = metatype $@thick Header.Type // CHECK: [[A:%.*]] = alloc_ref [tail_elems $T1 * %0 : $Builtin.Word] [tail_elems $T2 * %2 : $Builtin.Word] [tail_elems $T3 * %4 : $Builtin.Word] $Header // CHECK: return [[A]] return Builtin.allocWithTailElems_3(Header.self, n1, ty1, n2, ty2, n3, ty3) } // CHECK-LABEL: sil hidden @_TF8builtins16projectTailElems func projectTailElems<T>(h: Header, ty: T.Type) -> Builtin.RawPointer { // CHECK: bb0([[ARG1:%.*]] : $Header // CHECK: [[ARG1_COPY:%.*]] = copy_value [[ARG1]] // CHECK: [[TA:%.*]] = ref_tail_addr [[ARG1_COPY]] : $Header // CHECK: [[A2P:%.*]] = address_to_pointer [[TA]] // CHECK: destroy_value [[ARG1_COPY]] // CHECK: destroy_value [[ARG1]] // CHECK: return [[A2P]] return Builtin.projectTailElems(h, ty) } // CHECK: } // end sil function '_TF8builtins16projectTailElemsurFT1hCS_6Header2tyMx_Bp' // CHECK-LABEL: sil hidden @_TF8builtins11getTailAddr func getTailAddr<T1, T2>(start: Builtin.RawPointer, i: Builtin.Word, ty1: T1.Type, ty2: T2.Type) -> Builtin.RawPointer { // CHECK: [[P2A:%.*]] = pointer_to_address %0 // CHECK: [[TA:%.*]] = tail_addr [[P2A]] : $*T1, %1 : $Builtin.Word, $T2 // CHECK: [[A2P:%.*]] = address_to_pointer [[TA]] // CHECK: return [[A2P]] return Builtin.getTailAddr_Word(start, i, ty1, ty2) } // CHECK-LABEL: sil hidden @_TF8builtins8condfail func condfail(_ i: Builtin.Int1) { Builtin.condfail(i) // CHECK: cond_fail {{%.*}} : $Builtin.Int1 } struct S {} @objc class O {} @objc protocol OP1 {} @objc protocol OP2 {} protocol P {} // CHECK-LABEL: sil hidden @_TF8builtins10canBeClass func canBeClass<T>(_: T) { // CHECK: integer_literal $Builtin.Int8, 1 Builtin.canBeClass(O.self) // CHECK: integer_literal $Builtin.Int8, 1 Builtin.canBeClass(OP1.self) // -- FIXME: 'OP1 & OP2' doesn't parse as a value typealias ObjCCompo = OP1 & OP2 // CHECK: integer_literal $Builtin.Int8, 1 Builtin.canBeClass(ObjCCompo.self) // CHECK: integer_literal $Builtin.Int8, 0 Builtin.canBeClass(S.self) // CHECK: integer_literal $Builtin.Int8, 1 Builtin.canBeClass(C.self) // CHECK: integer_literal $Builtin.Int8, 0 Builtin.canBeClass(P.self) typealias MixedCompo = OP1 & P // CHECK: integer_literal $Builtin.Int8, 0 Builtin.canBeClass(MixedCompo.self) // CHECK: builtin "canBeClass"<T> Builtin.canBeClass(T.self) } // FIXME: "T.Type.self" does not parse as an expression // CHECK-LABEL: sil hidden @_TF8builtins18canBeClassMetatype func canBeClassMetatype<T>(_: T) { // CHECK: integer_literal $Builtin.Int8, 0 typealias OT = O.Type Builtin.canBeClass(OT.self) // CHECK: integer_literal $Builtin.Int8, 0 typealias OP1T = OP1.Type Builtin.canBeClass(OP1T.self) // -- FIXME: 'OP1 & OP2' doesn't parse as a value typealias ObjCCompoT = (OP1 & OP2).Type // CHECK: integer_literal $Builtin.Int8, 0 Builtin.canBeClass(ObjCCompoT.self) // CHECK: integer_literal $Builtin.Int8, 0 typealias ST = S.Type Builtin.canBeClass(ST.self) // CHECK: integer_literal $Builtin.Int8, 0 typealias CT = C.Type Builtin.canBeClass(CT.self) // CHECK: integer_literal $Builtin.Int8, 0 typealias PT = P.Type Builtin.canBeClass(PT.self) typealias MixedCompoT = (OP1 & P).Type // CHECK: integer_literal $Builtin.Int8, 0 Builtin.canBeClass(MixedCompoT.self) // CHECK: integer_literal $Builtin.Int8, 0 typealias TT = T.Type Builtin.canBeClass(TT.self) } // CHECK-LABEL: sil hidden @_TF8builtins11fixLifetimeFCS_1CT_ : $@convention(thin) (@owned C) -> () { func fixLifetime(_ c: C) { // CHECK: bb0([[ARG:%.*]] : $C): // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: fix_lifetime [[ARG_COPY]] : $C // CHECK: destroy_value [[ARG_COPY]] // CHECK: destroy_value [[ARG]] Builtin.fixLifetime(c) } // CHECK: } // end sil function '_TF8builtins11fixLifetimeFCS_1CT_' // CHECK-LABEL: sil hidden @_TF8builtins20assert_configuration func assert_configuration() -> Builtin.Int32 { return Builtin.assert_configuration() // CHECK: [[APPLY:%.*]] = builtin "assert_configuration"() : $Builtin.Int32 // CHECK: return [[APPLY]] : $Builtin.Int32 } // CHECK-LABEL: sil hidden @_TF8builtins17assumeNonNegativeFBwBw func assumeNonNegative(_ x: Builtin.Word) -> Builtin.Word { return Builtin.assumeNonNegative_Word(x) // CHECK: [[APPLY:%.*]] = builtin "assumeNonNegative_Word"(%0 : $Builtin.Word) : $Builtin.Word // CHECK: return [[APPLY]] : $Builtin.Word } // CHECK-LABEL: sil hidden @_TF8builtins11autoreleaseFCS_1OT_ : $@convention(thin) (@owned O) -> () { // ==> SEMANTIC ARC TODO: This will be unbalanced... should we allow it? // CHECK: bb0([[ARG:%.*]] : $O): // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: autorelease_value [[ARG_COPY]] // CHECK: destroy_value [[ARG_COPY]] // CHECK: destroy_value [[ARG]] // CHECK: } // end sil function '_TF8builtins11autoreleaseFCS_1OT_' func autorelease(_ o: O) { Builtin.autorelease(o) } // The 'unreachable' builtin is emitted verbatim by SILGen and eliminated during // diagnostics. // CHECK-LABEL: sil hidden @_TF8builtins11unreachable // CHECK: builtin "unreachable"() // CHECK: return // CANONICAL-LABEL: sil hidden @_TF8builtins11unreachableFT_T_ : $@convention(thin) () -> () { func unreachable() { Builtin.unreachable() } // CHECK-LABEL: sil hidden @_TF8builtins15reinterpretCastFTCS_1C1xBw_TBwCS_1DGSqS0__S0__ : $@convention(thin) (@owned C, Builtin.Word) -> (Builtin.Word, @owned D, @owned Optional<C>, @owned C) // CHECK: bb0([[ARG1:%.*]] : $C, [[ARG2:%.*]] : $Builtin.Word): // CHECK-NEXT: debug_value // CHECK-NEXT: debug_value // CHECK-NEXT: [[ARG1_COPY1:%.*]] = copy_value [[ARG1]] : $C // CHECK-NEXT: [[ARG1_TRIVIAL:%.*]] = unchecked_trivial_bit_cast [[ARG1_COPY1]] : $C to $Builtin.Word // CHECK-NEXT: [[ARG1_COPY2:%.*]] = copy_value [[ARG1]] : $C // CHECK-NEXT: [[ARG1_COPY2_CASTED:%.*]] = unchecked_ref_cast [[ARG1_COPY2]] : $C to $D // CHECK-NEXT: [[ARG1_COPY3:%.*]] = copy_value [[ARG1]] // CHECK-NEXT: [[ARG1_COPY3_CAST:%.*]] = unchecked_ref_cast [[ARG1_COPY3]] : $C to $Optional<C> // CHECK-NEXT: [[ARG2_OBJ_CASTED:%.*]] = unchecked_bitwise_cast [[ARG2]] : $Builtin.Word to $C // CHECK-NEXT: [[ARG2_OBJ_CASTED_COPIED:%.*]] = copy_value [[ARG2_OBJ_CASTED]] : $C // CHECK-NEXT: destroy_value [[ARG1_COPY1]] // CHECK-NEXT: destroy_value [[ARG1]] // CHECK-NEXT: [[RESULT:%.*]] = tuple ([[ARG1_TRIVIAL]] : $Builtin.Word, [[ARG1_COPY2_CASTED]] : $D, [[ARG1_COPY3_CAST]] : $Optional<C>, [[ARG2_OBJ_CASTED_COPIED:%.*]] : $C) // CHECK: return [[RESULT]] func reinterpretCast(_ c: C, x: Builtin.Word) -> (Builtin.Word, D, C?, C) { return (Builtin.reinterpretCast(c) as Builtin.Word, Builtin.reinterpretCast(c) as D, Builtin.reinterpretCast(c) as C?, Builtin.reinterpretCast(x) as C) } // CHECK-LABEL: sil hidden @_TF8builtins19reinterpretAddrOnly func reinterpretAddrOnly<T, U>(_ t: T) -> U { // CHECK: unchecked_addr_cast {{%.*}} : $*T to $*U return Builtin.reinterpretCast(t) } // CHECK-LABEL: sil hidden @_TF8builtins28reinterpretAddrOnlyToTrivial func reinterpretAddrOnlyToTrivial<T>(_ t: T) -> Int { // CHECK: [[ADDR:%.*]] = unchecked_addr_cast [[INPUT:%.*]] : $*T to $*Int // CHECK: [[VALUE:%.*]] = load [trivial] [[ADDR]] // CHECK: destroy_addr [[INPUT]] return Builtin.reinterpretCast(t) } // CHECK-LABEL: sil hidden @_TF8builtins27reinterpretAddrOnlyLoadable func reinterpretAddrOnlyLoadable<T>(_ a: Int, _ b: T) -> (T, Int) { // CHECK: [[BUF:%.*]] = alloc_stack $Int // CHECK: store {{%.*}} to [trivial] [[BUF]] // CHECK: [[RES1:%.*]] = unchecked_addr_cast [[BUF]] : $*Int to $*T // CHECK: copy_addr [[RES1]] to [initialization] return (Builtin.reinterpretCast(a) as T, // CHECK: [[RES:%.*]] = unchecked_addr_cast {{%.*}} : $*T to $*Int // CHECK: load [trivial] [[RES]] Builtin.reinterpretCast(b) as Int) } // CHECK-LABEL: sil hidden @_TF8builtins18castToBridgeObject // CHECK: [[BO:%.*]] = ref_to_bridge_object {{%.*}} : $C, {{%.*}} : $Builtin.Word // CHECK: return [[BO]] func castToBridgeObject(_ c: C, _ w: Builtin.Word) -> Builtin.BridgeObject { return Builtin.castToBridgeObject(c, w) } // CHECK-LABEL: sil hidden @_TF8builtins23castRefFromBridgeObject // CHECK: bridge_object_to_ref [[BO:%.*]] : $Builtin.BridgeObject to $C func castRefFromBridgeObject(_ bo: Builtin.BridgeObject) -> C { return Builtin.castReferenceFromBridgeObject(bo) } // CHECK-LABEL: sil hidden @_TF8builtins30castBitPatternFromBridgeObject // CHECK: bridge_object_to_word [[BO:%.*]] : $Builtin.BridgeObject to $Builtin.Word // CHECK: destroy_value [[BO]] func castBitPatternFromBridgeObject(_ bo: Builtin.BridgeObject) -> Builtin.Word { return Builtin.castBitPatternFromBridgeObject(bo) } // CHECK-LABEL: sil hidden @_TF8builtins8pinUnpin // CHECK: bb0([[ARG:%.*]] : $Builtin.NativeObject): // CHECK-NEXT: debug_value func pinUnpin(_ object : Builtin.NativeObject) { // CHECK-NEXT: [[ARG_COPY:%.*]] = copy_value [[ARG]] : $Builtin.NativeObject // CHECK-NEXT: [[HANDLE:%.*]] = strong_pin [[ARG_COPY]] : $Builtin.NativeObject // CHECK-NEXT: debug_value // CHECK-NEXT: destroy_value [[ARG_COPY]] : $Builtin.NativeObject let handle : Builtin.NativeObject? = Builtin.tryPin(object) // CHECK-NEXT: [[HANDLE_COPY:%.*]] = copy_value [[HANDLE]] : $Optional<Builtin.NativeObject> // CHECK-NEXT: strong_unpin [[HANDLE_COPY]] : $Optional<Builtin.NativeObject> // ==> SEMANTIC ARC TODO: This looks like a mispairing or a weird pairing. Builtin.unpin(handle) // CHECK-NEXT: tuple () // CHECK-NEXT: destroy_value [[HANDLE]] : $Optional<Builtin.NativeObject> // CHECK-NEXT: destroy_value [[ARG]] : $Builtin.NativeObject // CHECK-NEXT: [[T0:%.*]] = tuple () // CHECK-NEXT: return [[T0]] : $() } // ---------------------------------------------------------------------------- // isUnique variants // ---------------------------------------------------------------------------- // NativeObject // CHECK-LABEL: sil hidden @_TF8builtins8isUnique // CHECK: bb0(%0 : $*Optional<Builtin.NativeObject>): // CHECK: [[BUILTIN:%.*]] = is_unique %0 : $*Optional<Builtin.NativeObject> // CHECK: return func isUnique(_ ref: inout Builtin.NativeObject?) -> Bool { return _getBool(Builtin.isUnique(&ref)) } // NativeObject nonNull // CHECK-LABEL: sil hidden @_TF8builtins8isUnique // CHECK: bb0(%0 : $*Builtin.NativeObject): // CHECK: [[BUILTIN:%.*]] = is_unique %0 : $*Builtin.NativeObject // CHECK: return func isUnique(_ ref: inout Builtin.NativeObject) -> Bool { return _getBool(Builtin.isUnique(&ref)) } // NativeObject pinned // CHECK-LABEL: sil hidden @_TF8builtins16isUniqueOrPinned // CHECK: bb0(%0 : $*Optional<Builtin.NativeObject>): // CHECK: [[BUILTIN:%.*]] = is_unique_or_pinned %0 : $*Optional<Builtin.NativeObject> // CHECK: return func isUniqueOrPinned(_ ref: inout Builtin.NativeObject?) -> Bool { return _getBool(Builtin.isUniqueOrPinned(&ref)) } // NativeObject pinned nonNull // CHECK-LABEL: sil hidden @_TF8builtins16isUniqueOrPinned // CHECK: bb0(%0 : $*Builtin.NativeObject): // CHECK: [[BUILTIN:%.*]] = is_unique_or_pinned %0 : $*Builtin.NativeObject // CHECK: return func isUniqueOrPinned(_ ref: inout Builtin.NativeObject) -> Bool { return _getBool(Builtin.isUniqueOrPinned(&ref)) } // UnknownObject (ObjC) // CHECK-LABEL: sil hidden @_TF8builtins8isUnique // CHECK: bb0(%0 : $*Optional<Builtin.UnknownObject>): // CHECK: [[BUILTIN:%.*]] = is_unique %0 : $*Optional<Builtin.UnknownObject> // CHECK: return func isUnique(_ ref: inout Builtin.UnknownObject?) -> Bool { return _getBool(Builtin.isUnique(&ref)) } // UnknownObject (ObjC) nonNull // CHECK-LABEL: sil hidden @_TF8builtins8isUnique // CHECK: bb0(%0 : $*Builtin.UnknownObject): // CHECK: [[BUILTIN:%.*]] = is_unique %0 : $*Builtin.UnknownObject // CHECK: return func isUnique(_ ref: inout Builtin.UnknownObject) -> Bool { return _getBool(Builtin.isUnique(&ref)) } // UnknownObject (ObjC) pinned nonNull // CHECK-LABEL: sil hidden @_TF8builtins16isUniqueOrPinned // CHECK: bb0(%0 : $*Builtin.UnknownObject): // CHECK: [[BUILTIN:%.*]] = is_unique_or_pinned %0 : $*Builtin.UnknownObject // CHECK: return func isUniqueOrPinned(_ ref: inout Builtin.UnknownObject) -> Bool { return _getBool(Builtin.isUniqueOrPinned(&ref)) } // BridgeObject nonNull // CHECK-LABEL: sil hidden @_TF8builtins8isUnique // CHECK: bb0(%0 : $*Builtin.BridgeObject): // CHECK: [[BUILTIN:%.*]] = is_unique %0 : $*Builtin.BridgeObject // CHECK: return func isUnique(_ ref: inout Builtin.BridgeObject) -> Bool { return _getBool(Builtin.isUnique(&ref)) } // BridgeObject pinned nonNull // CHECK-LABEL: sil hidden @_TF8builtins16isUniqueOrPinned // CHECK: bb0(%0 : $*Builtin.BridgeObject): // CHECK: [[BUILTIN:%.*]] = is_unique_or_pinned %0 : $*Builtin.BridgeObject // CHECK: return func isUniqueOrPinned(_ ref: inout Builtin.BridgeObject) -> Bool { return _getBool(Builtin.isUniqueOrPinned(&ref)) } // BridgeObject nonNull native // CHECK-LABEL: sil hidden @_TF8builtins15isUnique_native // CHECK: bb0(%0 : $*Builtin.BridgeObject): // CHECK: [[CAST:%.*]] = unchecked_addr_cast %0 : $*Builtin.BridgeObject to $*Builtin.NativeObject // CHECK: return func isUnique_native(_ ref: inout Builtin.BridgeObject) -> Bool { return _getBool(Builtin.isUnique_native(&ref)) } // BridgeObject pinned nonNull native // CHECK-LABEL: sil hidden @_TF8builtins23isUniqueOrPinned_native // CHECK: bb0(%0 : $*Builtin.BridgeObject): // CHECK: [[CAST:%.*]] = unchecked_addr_cast %0 : $*Builtin.BridgeObject to $*Builtin.NativeObject // CHECK: [[BUILTIN:%.*]] = is_unique_or_pinned [[CAST]] : $*Builtin.NativeObject // CHECK: return func isUniqueOrPinned_native(_ ref: inout Builtin.BridgeObject) -> Bool { return _getBool(Builtin.isUniqueOrPinned_native(&ref)) } // ---------------------------------------------------------------------------- // Builtin.castReference // ---------------------------------------------------------------------------- class A {} protocol PUnknown {} protocol PClass : class {} // CHECK-LABEL: sil hidden @_TF8builtins19refcast_generic_any // CHECK: unchecked_ref_cast_addr T in %{{.*}} : $*T to AnyObject in %{{.*}} : $*AnyObject func refcast_generic_any<T>(_ o: T) -> AnyObject { return Builtin.castReference(o) } // CHECK-LABEL: sil hidden @_TF8builtins17refcast_class_anyFCS_1APs9AnyObject_ : // CHECK: bb0([[ARG:%.*]] : $A): // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: [[ARG_COPY_CASTED:%.*]] = unchecked_ref_cast [[ARG_COPY]] : $A to $AnyObject // CHECK: destroy_value [[ARG]] // CHECK: return [[ARG_COPY_CASTED]] // CHECK: } // end sil function '_TF8builtins17refcast_class_anyFCS_1APs9AnyObject_' func refcast_class_any(_ o: A) -> AnyObject { return Builtin.castReference(o) } // CHECK-LABEL: sil hidden @_TF8builtins20refcast_punknown_any // CHECK: unchecked_ref_cast_addr PUnknown in %{{.*}} : $*PUnknown to AnyObject in %{{.*}} : $*AnyObject func refcast_punknown_any(_ o: PUnknown) -> AnyObject { return Builtin.castReference(o) } // CHECK-LABEL: sil hidden @_TF8builtins18refcast_pclass_anyFPS_6PClass_Ps9AnyObject_ : // CHECK: bb0([[ARG:%.*]] : $PClass): // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: [[ARG_COPY_CAST:%.*]] = unchecked_ref_cast [[ARG_COPY]] : $PClass to $AnyObject // CHECK: destroy_value [[ARG]] // CHECK: return [[ARG_COPY_CAST]] // CHECK: } // end sil function '_TF8builtins18refcast_pclass_anyFPS_6PClass_Ps9AnyObject_' func refcast_pclass_any(_ o: PClass) -> AnyObject { return Builtin.castReference(o) } // CHECK-LABEL: sil hidden @_TF8builtins20refcast_any_punknown // CHECK: unchecked_ref_cast_addr AnyObject in %{{.*}} : $*AnyObject to PUnknown in %{{.*}} : $*PUnknown func refcast_any_punknown(_ o: AnyObject) -> PUnknown { return Builtin.castReference(o) } // CHECK-LABEL: sil hidden @_TF8builtins22unsafeGuaranteed_class // CHECK: bb0([[P:%.*]] : $A): // CHECK: [[P_COPY:%.*]] = copy_value [[P]] // CHECK: [[T:%.*]] = builtin "unsafeGuaranteed"<A>([[P_COPY]] : $A) // CHECK: [[R:%.*]] = tuple_extract [[T]] : $(A, Builtin.Int8), 0 // CHECK: [[K:%.*]] = tuple_extract [[T]] : $(A, Builtin.Int8), 1 // CHECK: destroy_value [[R]] : $A // CHECK: [[P_COPY:%.*]] = copy_value [[P]] // CHECK: destroy_value [[P]] // CHECK: return [[P_COPY]] : $A // CHECK: } func unsafeGuaranteed_class(_ a: A) -> A { Builtin.unsafeGuaranteed(a) return a } // CHECK-LABEL: _TF8builtins24unsafeGuaranteed_generic // CHECK: bb0([[P:%.*]] : $T): // CHECK: [[P_COPY:%.*]] = copy_value [[P]] // CHECK: [[T:%.*]] = builtin "unsafeGuaranteed"<T>([[P_COPY]] : $T) // CHECK: [[R:%.*]] = tuple_extract [[T]] : $(T, Builtin.Int8), 0 // CHECK: [[K:%.*]] = tuple_extract [[T]] : $(T, Builtin.Int8), 1 // CHECK: destroy_value [[R]] : $T // CHECK: [[P_RETURN:%.*]] = copy_value [[P]] // CHECK: destroy_value [[P]] // CHECK: return [[P_RETURN]] : $T // CHECK: } func unsafeGuaranteed_generic<T: AnyObject> (_ a: T) -> T { Builtin.unsafeGuaranteed(a) return a } // CHECK_LABEL: sil hidden @_TF8builtins31unsafeGuaranteed_generic_return // CHECK: bb0([[P:%.*]] : $T): // CHECK: [[P_COPY:%.*]] = copy_value [[P]] // CHECK: [[T:%.*]] = builtin "unsafeGuaranteed"<T>([[P_COPY]] : $T) // CHECK: [[R]] = tuple_extract [[T]] : $(T, Builtin.Int8), 0 // CHECK: [[K]] = tuple_extract [[T]] : $(T, Builtin.Int8), 1 // CHECK: destroy_value [[P]] // CHECK: [[S:%.*]] = tuple ([[R]] : $T, [[K]] : $Builtin.Int8) // CHECK: return [[S]] : $(T, Builtin.Int8) // CHECK: } func unsafeGuaranteed_generic_return<T: AnyObject> (_ a: T) -> (T, Builtin.Int8) { return Builtin.unsafeGuaranteed(a) } // CHECK-LABEL: sil hidden @_TF8builtins19unsafeGuaranteedEnd // CHECK: bb0([[P:%.*]] : $Builtin.Int8): // CHECK: builtin "unsafeGuaranteedEnd"([[P]] : $Builtin.Int8) // CHECK: [[S:%.*]] = tuple () // CHECK: return [[S]] : $() // CHECK: } func unsafeGuaranteedEnd(_ t: Builtin.Int8) { Builtin.unsafeGuaranteedEnd(t) } // CHECK-LABEL: sil hidden @_TF8builtins10bindMemory // CHECK: bb0([[P:%.*]] : $Builtin.RawPointer, [[I:%.*]] : $Builtin.Word, [[T:%.*]] : $@thick T.Type): // CHECK: bind_memory [[P]] : $Builtin.RawPointer, [[I]] : $Builtin.Word to $*T // CHECK: return {{%.*}} : $() // CHECK: } func bindMemory<T>(ptr: Builtin.RawPointer, idx: Builtin.Word, _: T.Type) { Builtin.bindMemory(ptr, idx, T.self) }
apache-2.0
7f7e12fca0f391703550dcb39baf68e8
38.747002
192
0.643428
3.324208
false
false
false
false
zhubofei/IGListKit
Examples/Examples-tvOS/IGListKitExamples/ViewControllers/DemosViewController.swift
4
1908
/** Copyright (c) 2016-present, Facebook, Inc. All rights reserved. The examples provided by Facebook are for non-commercial testing and evaluation purposes only. Facebook reserves all rights not expressly granted. 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 FACEBOOK 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 IGListKit import UIKit final class DemosViewController: UIViewController, ListAdapterDataSource { lazy var adapter: ListAdapter = { return ListAdapter(updater: ListAdapterUpdater(), viewController: self) }() let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout()) let demos: [DemoItem] = [ DemoItem(name: "Nested Adapter", controllerClass: NestedAdapterViewController.self) ] override func viewDidLoad() { super.viewDidLoad() title = "Demo Chooser" collectionView.backgroundColor = .clear view.addSubview(collectionView) adapter.collectionView = collectionView adapter.dataSource = self } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() collectionView.frame = view.bounds } // MARK: ListAdapterDataSource func objects(for listAdapter: ListAdapter) -> [ListDiffable] { return demos } func listAdapter(_ listAdapter: ListAdapter, sectionControllerFor object: Any) -> ListSectionController { return DemoSectionController() } func emptyView(for listAdapter: ListAdapter) -> UIView? { return nil } }
mit
a7c9307eafa5b4039d1b01aed27762a6
33.690909
109
0.727987
5.359551
false
false
false
false
avito-tech/Paparazzo
Paparazzo/Core/VIPER/PhotoLibrary/View/PhotoLibraryViewInput.swift
1
2552
import Foundation import ImageSource protocol PhotoLibraryViewInput: class { var onTitleTap: (() -> ())? { get set } var onDimViewTap: (() -> ())? { get set } func setTitle(_: String) func setTitleVisible(_: Bool) func setPlaceholderState(_: PhotoLibraryPlaceholderState) func setItems(_: [PhotoLibraryItemCellData], scrollToBottom: Bool, completion: (() -> ())?) func applyChanges(_: PhotoLibraryViewChanges, completion: (() -> ())?) func setCanSelectMoreItems(_: Bool) func setDimsUnselectedItems(_: Bool) func deselectAllItems() func scrollToBottom() func setAlbums(_: [PhotoLibraryAlbumCellData]) func selectAlbum(withId: String) func showAlbumsList() func hideAlbumsList() func toggleAlbumsList() var onPickButtonTap: (() -> ())? { get set } var onCancelButtonTap: (() -> ())? { get set } var onViewDidLoad: (() -> ())? { get set } func setProgressVisible(_ visible: Bool) // MARK: - Access denied view var onAccessDeniedButtonTap: (() -> ())? { get set } func setAccessDeniedViewVisible(_: Bool) func setAccessDeniedTitle(_: String) func setAccessDeniedMessage(_: String) func setAccessDeniedButtonTitle(_: String) } struct PhotoLibraryAlbumCellData { let identifier: String let title: String let coverImage: ImageSource? let onSelect: () -> () } struct PhotoLibraryItemCellData: Equatable { var image: ImageSource var selected = false var previewAvailable = false var onSelect: (() -> ())? var onSelectionPrepare: (() -> ())? var onDeselect: (() -> ())? var getSelectionIndex: (() -> Int?)? init(image: ImageSource, getSelectionIndex: (() -> Int?)? = nil) { self.image = image self.getSelectionIndex = getSelectionIndex } static func ==(cellData1: PhotoLibraryItemCellData, cellData2: PhotoLibraryItemCellData) -> Bool { return cellData1.image == cellData2.image } } struct PhotoLibraryViewChanges { // Изменения применять в таком порядке: удаление, вставка, обновление, перемещение let removedIndexes: IndexSet let insertedItems: [(index: Int, cellData: PhotoLibraryItemCellData)] let updatedItems: [(index: Int, cellData: PhotoLibraryItemCellData)] let movedIndexes: [(from: Int, to: Int)] } enum PhotoLibraryPlaceholderState { case hidden case visible(title: String) }
mit
1b08b1d41702a7f789cffa7db55ae781
28.235294
102
0.650302
4.778846
false
false
false
false
maximkhatskevich/MKHUniFlow
Sources/BindingsExternal/BDDViewModel_GivenOrThenContext.swift
1
3376
/* MIT License Copyright (c) 2016 Maxim Khatskevich ([email protected]) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import Combine //--- public extension BDDViewModel { struct GivenOrThenContext<W: Publisher> // W - When { public let description: String let source: S //internal let when: (AnyPublisher<StorageDispatcher.AccessReport, Never>) -> W public func given<G>( _ given: @escaping (StorageDispatcher, W.Output) throws -> G? ) -> ThenContext<W, G> { .init( description: description, source: source, when: when, given: given ) } public func given<G>( _ outputOnlyHandler: @escaping (W.Output) throws -> G? ) -> ThenContext<W, G> { given { _, output in try outputOnlyHandler(output) } } public func then( scope: String = #file, location: Int = #line, _ then: @escaping (S, W.Output, StorageDispatcher.StatusProxy) -> Void ) -> BindingViewModel { .init( source: source, description: description, scope: scope, location: location, when: when, given: { $1 }, /// just pass `when` clause output straight through as is then: then ) } public func then( scope: String = #file, location: Int = #line, _ noInputHandler: @escaping (S, StorageDispatcher.StatusProxy) -> Void ) -> BindingViewModel { then(scope: scope, location: location) { src, _, proxy in noInputHandler(src, proxy) } } public func then( scope: String = #file, location: Int = #line, _ sourceOnlyHandler: @escaping (S) -> Void ) -> BindingViewModel { then(scope: scope, location: location) { src, _ in sourceOnlyHandler(src) } } } }
mit
ef1340ecfe48ceadfe91b5b67dff2bf0
29.142857
88
0.550355
5.069069
false
false
false
false
KhunLam/Swift_weibo
LKSwift_weibo/LKSwift_weibo/Classes/Module/Message/Controller/LKMessageTableViewController.swift
1
3256
// // LKMessageTableViewController.swift // LKSwift_weibo // // Created by lamkhun on 15/10/26. // Copyright © 2015年 lamKhun. All rights reserved. // import UIKit class LKMessageTableViewController: LKBaseTableViewController { override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 0 } /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
apache-2.0
29dc36011563d2c9caa25346b515f2e3
33.242105
157
0.688903
5.541738
false
false
false
false
google/JacquardSDKiOS
Tests/TransportTests/TransportV2Tests.swift
1
16036
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Combine import CoreBluetooth import XCTest @testable import JacquardSDK final class TransportV2Tests: XCTestCase { private let requestTimeout = 8.0 struct CatchLogger: Logger { func log(level: LogLevel, file: String, line: Int, function: String, message: () -> String) { let _ = message() if level == .assertion || level == .error || level == .warning { expectation.fulfill() } } var expectation: XCTestExpectation } override func setUp() { super.setUp() let logger = PrintLogger( logLevels: [.debug, .info, .warning, .error, .assertion, .preconditionFailure], includeSourceDetails: true ) setGlobalJacquardSDKLogger(logger) } override func tearDown() { // Other tests may run in the same process. Ensure that any fake logger fulfillment doesn't // cause any assertions later. JacquardSDK.setGlobalJacquardSDKLogger(JacquardSDK.createDefaultLogger()) super.tearDown() } private var commandCharacteristic: FakeCharacteristic { let commandUUID = CBUUID(string: "D2F2EABB-D165-445C-B0E1-2D6B642EC57B") return FakeCharacteristic(uuid: commandUUID, value: nil) } private var responseCharacteristic: FakeCharacteristic { let responseUUID = CBUUID(string: "D2F2B8D0-D165-445C-B0E1-2D6B642EC57B") return FakeCharacteristic(uuid: responseUUID, value: nil) } private var notifyCharacteristic: FakeCharacteristic { let notifyUUID = CBUUID(string: "D2F2B8D1-D165-445C-B0E1-2D6B642EC57B") return FakeCharacteristic(uuid: notifyUUID, value: nil) } private var rawDataCharacteristic: FakeCharacteristic { let rawDataUUID = CBUUID(string: "D2F2B8D2-D165-445C-B0E1-2D6B642EC57B") return FakeCharacteristic(uuid: rawDataUUID, value: nil) } private lazy var requiredCharacteristics = RequiredCharacteristics( commandCharacteristic: commandCharacteristic, responseCharacteristic: responseCharacteristic, notifyCharacteristic: notifyCharacteristic, rawDataCharacteristic: rawDataCharacteristic ) var observations = [Cancellable]() let uuid = UUID(uuidString: "BD415750-8EF1-43EE-8A7F-7EF1E365C35E")! let deviceName = "Fake Device" func testVerifyPeripheralDetails() { let peripheral = FakePeripheralImplementation(identifier: uuid, name: deviceName) let transport = TransportV2Implementation( peripheral: peripheral, characteristics: requiredCharacteristics ) XCTAssertEqual(transport.peripheralName, deviceName) XCTAssertEqual(transport.peripheralIdentifier.uuidString, uuid.uuidString) } func testVerifyPeripheralNamePublisher() { let namePublisherExpectation = expectation(description: "NamePublisher") namePublisherExpectation.expectedFulfillmentCount = 2 let expectedNewDeviceName = "Updated mock device" let peripheral = FakePeripheralImplementation(identifier: uuid, name: deviceName) let transport = TransportV2Implementation( peripheral: peripheral, characteristics: requiredCharacteristics ) transport.peripheralNamePublisher .buffer(size: Int.max, prefetch: .byRequest, whenFull: .dropOldest) .sink { name in XCTAssertEqual(name, peripheral.name) namePublisherExpectation.fulfill() }.addTo(&observations) peripheral.callbackType = .didUpdateName peripheral.updatePeripheralName(expectedNewDeviceName) var config = Google_Jacquard_Protocol_BleConfiguration() config.customAdvName = expectedNewDeviceName let configWriteRequest = UJTWriteConfigCommand(config: config) transport.enqueue( request: configWriteRequest.request, retries: 0, requestTimeout: requestTimeout ) { _ in } wait(for: [namePublisherExpectation], timeout: 1.0) } func testVerifyDidWriteCommandPublisher() { let didWriteCommandExpectation = expectation(description: "DidWriteCommand") let peripheral = FakePeripheralImplementation(identifier: uuid, name: deviceName) let transport = TransportV2Implementation( peripheral: peripheral, characteristics: requiredCharacteristics ) transport.didWriteCommandPublisher .buffer(size: Int.max, prefetch: .byRequest, whenFull: .dropOldest) .sink { error in XCTAssertNil(error) didWriteCommandExpectation.fulfill() }.addTo(&observations) let helloRequest = Google_Jacquard_Protocol_Request.with { $0.domain = .base $0.opcode = .hello } peripheral.writeValueHandler = { _, characteristic, _ in transport.peripheral(peripheral, didWriteValueFor: characteristic, error: nil) } transport.enqueue(request: helloRequest, retries: 0, requestTimeout: requestTimeout) { _ in } wait(for: [didWriteCommandExpectation], timeout: 1.0) } func testBadProtoRequest() { let badProtoRequestExpectation = expectation(description: "BadProtoRequest") let peripheral = FakePeripheralImplementation(identifier: uuid, name: deviceName) peripheral.callbackType = .didWriteValue(.helloCommand) let retry = 2 let transport = TransportV2Implementation( peripheral: peripheral, characteristics: requiredCharacteristics ) transport.didWriteCommandPublisher .buffer(size: Int.max, prefetch: .byRequest, whenFull: .dropOldest) .sink { _ in XCTFail("Bad proto request should not succeed") }.addTo(&observations) let helloRequest = Google_Jacquard_Protocol_Request() transport.enqueue( request: helloRequest, retries: retry, requestTimeout: requestTimeout ) { responseResult in switch responseResult { case .success: XCTFail("Bad proto request should not succeed") case .failure(let error): XCTAssertNotNil(error) XCTAssertEqual(Int(transport.lastRequestId), retry + 1) badProtoRequestExpectation.fulfill() } } wait(for: [badProtoRequestExpectation], timeout: 1.0) } func testVerifyDidWriteCommandPublisherWithError() { let didWriteCommandWithErrorExpectation = expectation(description: "DidWriteCommandWithError") jqLogger = CatchLogger(expectation: didWriteCommandWithErrorExpectation) let peripheral = FakePeripheralImplementation(identifier: uuid, name: deviceName) let transport = TransportV2Implementation( peripheral: peripheral, characteristics: requiredCharacteristics ) transport.didWriteCommandPublisher .buffer(size: Int.max, prefetch: .byRequest, whenFull: .dropOldest) .sink { error in XCTAssertNotNil(error) }.addTo(&observations) let helloRequest = Google_Jacquard_Protocol_Request.with { $0.domain = .base $0.opcode = .hello } peripheral.callbackType = .didWriteValueWithError transport.enqueue(request: helloRequest, retries: 0, requestTimeout: requestTimeout) { _ in } wait(for: [didWriteCommandWithErrorExpectation], timeout: 1.0) } func testVerifyResponseCharacteristic() { let didUpdateForCharacteristicExpectation = expectation( description: "DidUpdateForResponseCharacteristic" ) let peripheral = FakePeripheralImplementation(identifier: uuid, name: deviceName) let transport = TransportV2Implementation( peripheral: peripheral, characteristics: requiredCharacteristics ) let helloRequest = Google_Jacquard_Protocol_Request.with { $0.domain = .base $0.opcode = .hello } peripheral.callbackType = .didUpdateValue(.helloCommand) transport.enqueue( request: helloRequest, retries: 0, requestTimeout: requestTimeout ) { responseResult in switch responseResult { case .success(let packet): do { let response = try Google_Jacquard_Protocol_Response( serializedData: packet, extensions: Google_Jacquard_Protocol_Jacquard_Extensions) XCTAssert(response.status == .ok) } catch (let error) { XCTFail("Error: \(error)") } case .failure(let error): XCTFail("Error: \(error)") } didUpdateForCharacteristicExpectation.fulfill() } wait(for: [didUpdateForCharacteristicExpectation], timeout: 1.0) } func testVerifyResponseCharacteristicWithEmptyData() { let didUpdateForCharacteristicWithEmptyDataExpectation = expectation( description: "DidUpdateForResponseCharacteristicWithEmptyData" ) jqLogger = CatchLogger(expectation: didUpdateForCharacteristicWithEmptyDataExpectation) let peripheral = FakePeripheralImplementation(identifier: uuid, name: deviceName) let transport = TransportV2Implementation( peripheral: peripheral, characteristics: requiredCharacteristics ) let helloRequest = Google_Jacquard_Protocol_Request.with { $0.domain = .base $0.opcode = .hello } peripheral.callbackType = .didUpdateValueForResponseCharacteristicWithEmptyData transport.enqueue( request: helloRequest, retries: 0, requestTimeout: requestTimeout ) { responseResult in XCTFail("Should not be here when received response with empty value.") } wait(for: [didUpdateForCharacteristicWithEmptyDataExpectation], timeout: 1.0) } func testVerifyResendResponseCharacteristic() { let resendResponseCharacteristicExpectation = expectation( description: "ResendResponseCharacteristic" ) resendResponseCharacteristicExpectation.expectedFulfillmentCount = 2 jqLogger = CatchLogger(expectation: resendResponseCharacteristicExpectation) let peripheral = FakePeripheralImplementation(identifier: uuid, name: deviceName) let transport = TransportV2Implementation( peripheral: peripheral, characteristics: requiredCharacteristics ) let helloRequest = Google_Jacquard_Protocol_Request.with { $0.domain = .base $0.opcode = .hello } peripheral.callbackType = .didResendResponseCharacteristic transport.enqueue( request: helloRequest, retries: 0, requestTimeout: requestTimeout ) { responseResult in switch responseResult { case .success(let packet): do { let response = try Google_Jacquard_Protocol_Response( serializedData: packet, extensions: Google_Jacquard_Protocol_Jacquard_Extensions) XCTAssert(response.status == .ok) } catch (let error) { XCTFail("Error: \(error)") } case .failure(let error): XCTFail("Error: \(error)") } resendResponseCharacteristicExpectation.fulfill() } wait(for: [resendResponseCharacteristicExpectation], timeout: 1.0) } func testVerifyNotifyCharacteristic() { let didUpdateForNotifyCharacteristicExpectation = expectation( description: "DidUpdateForNotifyCharacteristic" ) let peripheral = FakePeripheralImplementation(identifier: uuid, name: deviceName) let transport = TransportV2Implementation( peripheral: peripheral, characteristics: requiredCharacteristics ) transport.notificationPublisher .buffer(size: Int.max, prefetch: .byRequest, whenFull: .dropOldest) .sink { notification in XCTAssert(notification.opcode == .attached) didUpdateForNotifyCharacteristicExpectation.fulfill() }.addTo(&observations) transport.stopCachingNotifications() peripheral.postGearAttachNotification() wait(for: [didUpdateForNotifyCharacteristicExpectation], timeout: 1.0) } func testVerifyNotifyCharacteristicWithEmptyData() { let didUpdateForNotifyCharacteristicWithEmptyDataExpectation = expectation( description: "DidUpdateForNotifyCharacteristicWithEmptyData" ) jqLogger = CatchLogger(expectation: didUpdateForNotifyCharacteristicWithEmptyDataExpectation) let peripheral = FakePeripheralImplementation(identifier: uuid, name: deviceName) let transport = TransportV2Implementation( peripheral: peripheral, characteristics: requiredCharacteristics ) transport.notificationPublisher .buffer(size: Int.max, prefetch: .byRequest, whenFull: .dropOldest) .sink { notification in XCTFail("Notification should not publish for empty value.") }.addTo(&observations) peripheral.postNotificationWithEmptyData() wait(for: [didUpdateForNotifyCharacteristicWithEmptyDataExpectation], timeout: 1.0) } func testVerifyUnknownNotificationCharacteristic() { let didUpdateForNotifyCharacteristicWithEmptyDataExpectation = expectation( description: "DidUpdateForNotifyCharacteristicWithEmptyData" ) jqLogger = CatchLogger(expectation: didUpdateForNotifyCharacteristicWithEmptyDataExpectation) let peripheral = FakePeripheralImplementation(identifier: uuid, name: deviceName) let transport = TransportV2Implementation( peripheral: peripheral, characteristics: requiredCharacteristics ) transport.notificationPublisher .buffer(size: Int.max, prefetch: .byRequest, whenFull: .dropOldest) .sink { notification in XCTFail("Notification should not publish for empty value.") }.addTo(&observations) peripheral.postUnknownBluetoothNotification() wait(for: [didUpdateForNotifyCharacteristicWithEmptyDataExpectation], timeout: 1.0) } func testVerifyNotificationPublisherWithCachingOff() { let cachingOffExpectation = expectation(description: "CachingOff") let peripheral = FakePeripheralImplementation(identifier: uuid, name: deviceName) let transport = TransportV2Implementation( peripheral: peripheral, characteristics: requiredCharacteristics ) // Stop notification caching. transport.stopCachingNotifications() // Verify caching stopped. XCTAssert(transport.cacheNotifications) // Wait for the next notification delivery before stopping caching. Not subscribing publisher // here as it has been tested in another test case. peripheral.postGearAttachNotification() transport.notificationPublisher .buffer(size: Int.max, prefetch: .byRequest, whenFull: .dropOldest) .sink { notification in XCTAssertFalse(transport.cacheNotifications) XCTAssert(notification.opcode == .batteryStatus) cachingOffExpectation.fulfill() }.addTo(&observations) // Posting another notification to check caching stops. peripheral.postBatteryStatusNotification() // Checking if stop caching doesn't toggle caching. transport.stopCachingNotifications() XCTAssertFalse(transport.cacheNotifications) wait(for: [cachingOffExpectation], timeout: 1.0) } func testVerifyMalformedDataDeliveryNotification() { let malformedDataExpectation = expectation(description: "MalformedData") jqLogger = CatchLogger(expectation: malformedDataExpectation) let peripheral = FakePeripheralImplementation(identifier: uuid, name: deviceName) let transport = TransportV2Implementation( peripheral: peripheral, characteristics: requiredCharacteristics ) transport.notificationPublisher .buffer(size: Int.max, prefetch: .byRequest, whenFull: .dropOldest) .sink { notification in XCTFail("Notification should not publish for bad packets.") }.addTo(&observations) transport.deliverNotification(packet: peripheral.badPacket) wait(for: [malformedDataExpectation], timeout: 1.0) } }
apache-2.0
04df92b069c40d113307d5bebba15bb9
32.902748
98
0.731167
4.838865
false
false
false
false
pourhadi/DynUI
Pod/Classes/Text.swift
1
3791
// // Text.swift // Pods // // Created by Dan Pourhadi on 1/31/16. // // import Foundation import RxSwift public protocol TextStyleable: class { var dyn_textStyle:TextStyle? { get set } } extension UILabel: TextStyleable { public var dyn_textStyle:TextStyle? { get { return self.dyn_getProp("dyn_textStyleName") } set { self.dyn_setProp(newValue, "dyn_textStyleName") if let style = newValue { if let _ = self.dyn_textStyleDisposeBag { self.dyn_applyTextStyle(style) } else { self.dyn_textStyleDisposeBag = DisposeBag() self.dyn_textStyleDisposeBag!.addDisposable(self.rx_observe(String.self, "text").subscribeNext({ [weak self] (text) -> Void in if let style = self?.dyn_textStyle { self?.dyn_applyTextStyle(style) } })) } } else { self.dyn_textStyleDisposeBag = nil self.dyn_highlightTextStyleDisposeBag = nil } } } private func dyn_applyTextStyle(style:TextStyle) { let attr = style.asAttributes() if let text = self.text { self.attributedText = NSAttributedString(string: text, attributes: attr) } else if let text = self.attributedText { self.attributedText = NSAttributedString(string: text.string, attributes: attr) } self.dyn_configureHighlightStyle() } private func dyn_configureHighlightStyle() { if let highlightColor = self.dyn_textStyle?.highlightedTextColor { if self.dyn_highlightTextStyleDisposeBag != nil { return } self.dyn_highlightTextStyleDisposeBag = DisposeBag() self.dyn_highlightTextStyleDisposeBag!.addDisposable(self.rx_observe(Bool.self, "highlighted").subscribeNext({ [weak self] (_) -> Void in if self == nil { return } if self?.dyn_textStyle == nil { return } if self?.highlighted ?? false { self?.dyn_applyTextStyle(self!.dyn_textStyle!.withColor(highlightColor)) } else { self?.dyn_applyTextStyle(self!.dyn_textStyle!) } })) } else { self.dyn_highlightTextStyleDisposeBag = nil } } private var dyn_textStyleDisposeBag:DisposeBag? { get { return self.dyn_getProp("dyn_textStyleDisposeBag") } set { self.dyn_setProp(newValue, "dyn_textStyleDisposeBag") } } private var dyn_highlightTextStyleDisposeBag:DisposeBag? { get { return self.dyn_getProp("dyn_highlightTextStyleDisposeBag") } set { self.dyn_setProp(newValue, "dyn_highlightTextStyleDisposeBag") } } } extension UIButton: TextStyleable { public var dyn_textStyle:TextStyle? { get { return self.titleLabel!.dyn_textStyle } set { self.titleLabel!.dyn_textStyle = newValue if let newValue = newValue, color = newValue.color { self.setTitleColor(color.color, forState: .Normal) self.setTitleColor(color.color.colorWithAlphaComponent(0.5), forState: .Disabled) } } } } extension UITextField: TextStyleable { public var dyn_textStyle:TextStyle? { get { return self.dyn_getProp("dyn_textStyle") } set { self.dyn_setProp(newValue, "dyn_textStyle") if let style = newValue { self.defaultTextAttributes = style.asAttributes() } } } }
mit
60eb07b56d4cd517abf6429c0c709a26
33.162162
149
0.565022
4.792668
false
false
false
false
liuguya/TestKitchen_1606
TestKitchen/TestKitchen/classes/cookbook/foodCourse/view/FCSerialCell.swift
1
5617
// // FCSerialCell.swift // TestKitchen // // Created by 阳阳 on 16/8/26. // Copyright © 2016年 liuguyang. All rights reserved. // import UIKit protocol FCSerialCellDelegate:NSObjectProtocol { func didSelectSerialAtIndex(index:Int) /*修改展开和收起的状态*/ func changeExpandState(isExpand:Bool) } class FCSerialCell: UITableViewCell { //更多按钮 private var moreBtn:UIButton? //当前集数展开还是合起 var isExpand:Bool = false //代理 var delegate:FCSerialCellDelegate? //选中按钮的序号 var selectIndex:Int = 0{ didSet{ selectBtnAtIndex(selectIndex, lastIndex: oldValue) } } var num:Int?{ didSet{ if num>0{ showData() } } } private var w:CGFloat{ get { return 40 } } private var h:CGFloat{ get { return 40 } } private var spaceY:CGFloat{ get { return 10 } } var margin:CGFloat{ get { return 20 } } //显示数据 func showData(){ for old in contentView.subviews{ old.removeFromSuperview() } //每一行的按钮 let rowNum = Int((kSreenWith - margin*2)/w) //横向间距 let spaceX = (kSreenWith-margin*2 - CGFloat(rowNum)*w)/(CGFloat(rowNum-1)) var cnt = num! if num > rowNum*2{ //超过两行,要判断是否展开 if isExpand == false{ //如果没有展开 cnt = rowNum*2 } } for i in 0..<cnt{ let row = i/rowNum let col = i%rowNum let frame = CGRectMake(margin+(spaceX+w)*CGFloat(col), spaceY+(spaceY+h)*CGFloat(row), w, h) let btn = FCSerialBtn(frame: frame, index: i+1) btn.tag = 500+i btn.addTarget(self, action: #selector(clickBtn(_:)), forControlEvents: .TouchUpInside) contentView.addSubview(btn) } //判断添加展开按钮 if num > rowNum*2 { var imageName = "pull.png" var btnBow:CGFloat = 2 if isExpand == true{ btnBow = CGFloat(num!/rowNum) if num! % rowNum > 0 { btnBow += 1 } imageName = "push.png" } moreBtn = UIButton.createButton(nil, bgImageName: imageName, selectBgImageName: nil, target: self, action: #selector(expandAction)) moreBtn?.frame = CGRectMake((kSreenWith-54)/2, margin+(h+spaceY)*btnBow, 54, 30) contentView.addSubview(moreBtn!) } } func expandAction(){ print("11") //修改展开和收起的状态 delegate?.changeExpandState(!isExpand) self.isExpand = !isExpand } //计算cell的高度 /** num 一共有多少集 isExpand 状态 */ class func heightWithNum(num:Int,isExpand:Bool?)->CGFloat{ //每一行的按钮 //var cell = FCSerialCell() let rowNum = Int((kSreenWith - 20*2)/40) //计算一共有几行 var rows = num/rowNum if num%rowNum > 0{ rows+=1 } var h:CGFloat? //如果num 大于并且是合起 if (num > rowNum*2) && (isExpand == false){ h = 20+CGFloat(2)*(40+10)+30 }else{ h = 20+CGFloat(rows)*(40+10)+30 } return h! } func clickBtn(btn:FCSerialBtn){ //修改当前cell的ui selectIndex = btn.tag - 500 delegate?.didSelectSerialAtIndex(selectIndex) } //点击按钮时修改ui func selectBtnAtIndex(index:Int,lastIndex:Int){ let lastBtn = contentView.viewWithTag(500+lastIndex) if lastBtn?.isKindOfClass(FCSerialBtn.self) == true{ let btn = lastBtn as! FCSerialBtn btn.clicked = false } let curBtn = contentView.viewWithTag(500+index) if curBtn?.isKindOfClass(FCSerialBtn.self) == true{ let btn = curBtn as! FCSerialBtn btn.clicked = true } } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } } class FCSerialBtn:UIControl{ var titleLabel:UILabel? var clicked:Bool = false{ didSet{ if clicked == true{ //选中 backgroundColor = UIColor.orangeColor() titleLabel?.textColor = UIColor.whiteColor() }else if clicked == false{ backgroundColor = UIColor(white: 0.9, alpha: 1.0) titleLabel?.textColor = UIColor.grayColor() } } } init(frame: CGRect,index:Int) { super.init(frame: frame) //文字 titleLabel = UILabel.createLabel("\(index)", font: UIFont.systemFontOfSize(12), textAlignment: .Center, textColor: UIColor.grayColor()) titleLabel?.frame = bounds backgroundColor = UIColor(white: 0.9, alpha: 1.0) addSubview(titleLabel!) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
20a38c2c7c86958073c434c03ca84529
23.740741
143
0.524888
4.234548
false
false
false
false
nanthi1990/SwiftCharts
SwiftCharts/Views/CubicLinePathGenerator.swift
7
2633
// // CubicLinePathGenerator.swift // SwiftCharts // // Created by ischuetz on 28/04/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit public class CubicLinePathGenerator: ChartLinesViewPathGenerator { public init() {} // src: http://stackoverflow.com/a/29876400/930450 public func generatePath(#points: [CGPoint], lineWidth: CGFloat) -> UIBezierPath { var cp1: CGPoint var cp2: CGPoint let path = UIBezierPath() var p0: CGPoint var p1: CGPoint var p2: CGPoint var p3: CGPoint var tensionBezier1: CGFloat = 0.3 var tensionBezier2: CGFloat = 0.3 var previousPoint1: CGPoint = CGPointZero var previousPoint2: CGPoint path.moveToPoint(points.first!) for i in 0..<(points.count - 1) { p1 = points[i] p2 = points[i + 1] let maxTension: CGFloat = 1 / 3 tensionBezier1 = maxTension tensionBezier2 = maxTension if i > 0 { // Exception for first line because there is no previous point p0 = previousPoint1 if p2.y - p1.y == p2.y - p0.y { tensionBezier1 = 0 } } else { tensionBezier1 = 0 p0 = p1 } if i < points.count - 2 { // Exception for last line because there is no next point p3 = points[i + 2] if p3.y - p2.y == p2.y - p1.y { tensionBezier2 = 0 } } else { p3 = p2 tensionBezier2 = 0 } // The tension should never exceed 0.3 if tensionBezier1 > maxTension { tensionBezier1 = maxTension } if tensionBezier1 > maxTension { tensionBezier2 = maxTension } // First control point cp1 = CGPointMake(p1.x + (p2.x - p1.x)/3, p1.y - (p1.y - p2.y)/3 - (p0.y - p1.y)*tensionBezier1) // Second control point cp2 = CGPointMake(p1.x + 2*(p2.x - p1.x)/3, (p1.y - 2*(p1.y - p2.y)/3) + (p2.y - p3.y)*tensionBezier2) path.addCurveToPoint(p2, controlPoint1: cp1, controlPoint2: cp2) previousPoint1 = p1; previousPoint2 = p2; } return path } }
apache-2.0
ab22372babda57c16d27999f2fd1964b
28.931818
95
0.470186
4.226324
false
false
false
false
mukang/MKWeibo
MKWeibo/MKWeibo/Classes/BusinessModel/StatusesData.swift
1
4178
// // StatusesData.swift // MKWeibo // // Created by 穆康 on 15/3/16. // Copyright (c) 2015年 穆康. All rights reserved. // import UIKit /// 加载微博数据 URL private let WB_Hom_Timeline_URL = "https://api.weibo.com/2/statuses/home_timeline.json" /// 微博数据列表模型 class StatusesData: NSObject, DictModelProtocol { /// 微博记录数组 var statuses: [Status]? /// 微博总数 var total_number: Int = 0 /// 未读数量 var has_unread: Int = 0 // 遵守协议 static func customeClassMapping() -> [String : String]? { return ["statuses": "\(Status.self)"] } /// 刷新微博数据 class func loadStatusesData(complation:(data: StatusesData?, error: NSError?) -> ()) { let net = NetworkManager.sharedManager if let token = AccessToken.loadAccessToken() { let params = ["access_token": "\(token.access_token!)"] // 发送网络异步请求 net.requestJSON(.GET, WB_Hom_Timeline_URL, params, { (result, error) -> () in // 错误处理 if error != nil { complation(data: nil, error: error) return } // 字典转模型 let modelTools = SwiftDictModel.sharedManager let data = modelTools.objectWithDict(result as! NSDictionary, StatusesData.self) as? StatusesData if data != nil { // 如果有下载图像的 url,就先下载图像 if let picURLs = StatusesData.pictureURLs(data!.statuses!) { net.downloadImages(picURLs, completion: { (result, error) -> () in // 回调通知视图控制器刷新数据 complation(data: data, error: nil) return }) } } // 回调,将模型通知给视图控制器 complation(data: data, error: nil) }) } } /// 取出给定的微博数据中所有图片的 URL 数组 /// /// :param: statuses statuses 微博数据数组 /// /// :returns: 微博数组中的 url 完整数组,可以为空 class func pictureURLs(statuses: [Status]) -> [String]? { var list = [String]() // 遍历数组 for status in statuses { // 继续遍历 pic_urls if let urls = status.pic_urls { for url in urls { list.append(url.thumbnail_pic!) } } } if list.count > 0 { return list } else { return nil } } } class Status: NSObject, DictModelProtocol { /// 微博创建时间 var created_at: String? /// 微博ID var id: Int = 0 /// 微博信息内容 var text: String? /// 微博来源 var source: String? /// 转发数 var reposts_count: Int = 0 /// 评论数 var comments_count: Int = 0 /// 表态数 var attitudes_count: Int = 0 /// 配图数组 var pic_urls: [StatusPictureURL]? /// 用户信息 var user: UserInfo? /// 转发微博 var retweeted_status: Status? // 遵守协议 static func customeClassMapping() -> [String : String]? { return ["pic_urls": "\(StatusPictureURL.self)", "user": "\(UserInfo.self)", "retweeted_status": "\(Status.self)"] } } class StatusPictureURL: NSObject { /// 缩略图 URL var thumbnail_pic: String? }
mit
d8359069da8a0e22f1ea7c44ee882785
19.26738
121
0.433245
4.71393
false
false
false
false
TheBrewery/Hikes
WorldHeritage/Extensions/UIImage+Tinted.swift
1
1282
import Foundation import UIKit extension UIImage { func imageWithTintColor(tintColor: UIColor) -> UIImage { let imageBounds = CGRectMake( 0, 0, self.size.width, self.size.height ) UIGraphicsBeginImageContextWithOptions( self.size, false, self.scale ) let context: CGContextRef = UIGraphicsGetCurrentContext()! CGContextTranslateCTM( context, 0, self.size.height ) CGContextScaleCTM( context, 1.0, -1.0 ) CGContextClipToMask( context, imageBounds, self.CGImage ) tintColor.setFill() CGContextFillRect( context, imageBounds ) let tintedImage: UIImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return tintedImage } class func imageWithTintColor(tintColor: UIColor, size: CGSize) -> UIImage { let imageBounds = CGRect(origin: CGPointZero, size: size) UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.mainScreen().scale ) let context: CGContextRef = UIGraphicsGetCurrentContext()! tintColor.setFill() CGContextFillRect(context, imageBounds) let tintedImage: UIImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return tintedImage } }
mit
71df94c034efa82a556532072d941ad7
31.05
89
0.704368
5.962791
false
false
false
false
duliodenis/HackingWithSwift
project-09/Whitehouse/Whitehouse/DetailViewController.swift
2
1114
// // DetailViewController.swift // Whitehouse // // Created by Dulio Denis on 1/17/15. // Copyright (c) 2015 ddApps. All rights reserved. // import UIKit import WebKit class DetailViewController: UIViewController { var detailItem: [String: String]! var webView: WKWebView! override func loadView() { webView = WKWebView() self.view = webView } override func viewDidLoad() { super.viewDidLoad() if let body = detailItem["body"] { var html = "<html>" html += "<head>" html += "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">" html += "<style> body { font-size: 150%; } </style>" html += "</head>" html += "<body>" html += body html += "</body>" html += "</html>" webView.loadHTMLString(html, baseURL: nil) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
2dafd8a38db11c802cb0e29784449ebd
22.702128
94
0.5386
4.661088
false
false
false
false
guille969/MGBottomSheet
MGBottomSheet/MGBottomSheet/ActionSheetCell/ActionSheetCell.swift
1
1953
// // ActionSheetCell.swift // MGBottomSheetController // // Created by Guillermo García Rebolo on 23/1/17. // Copyright © 2017 Guillermo Garcia Rebolo. All rights reserved. // import UIKit public class ActionSheetCell: UICollectionViewCell { @IBOutlet weak var actionImage: UIImageView! @IBOutlet weak var actionTitleLabel: UILabel! /** Implementation of the method awakeFromNib od UICollectionViewCell - Author: Guillermo Garcia Rebolo - Version: 1.0.3 */ override public func awakeFromNib() { super.awakeFromNib() } /** Methods for configure an action sheet cell - Author: Guillermo Garcia Rebolo - returns ActionSheetCell instance. - parameters: - action: The action sheet. - font: The font for the cell text. - textColor: The color for the cell text. - imageTint: The tint for the cell image. - Version: 1.0.3 */ public func actionSheetCellWithAction(_ action: ActionSheet, font: UIFont, textColor: UIColor, imageTint: UIColor) { self.actionTitleLabel.font = font; self.actionTitleLabel.textColor = textColor self.actionTitleLabel.text = action.title self.actionImage.image = action.iconImage if (!action.disabled) { self.actionTitleLabel.textColor = textColor if (action.iconImageTint != UIColor.clear) { self.actionImage.tintColor = action.iconImageTint } else { self.actionImage.tintColor = imageTint } self.isUserInteractionEnabled = true; } else { self.actionTitleLabel.textColor = UIColor.lightGray self.actionImage.tintColor = UIColor.lightGray self.isUserInteractionEnabled = false } } }
mit
ddc3c7fe26a9890175818c1d3109f2d5
25.364865
120
0.60328
5.015424
false
false
false
false
hejeffery/Animation
Animation/Animation/LayerAnimation/Controller/ShapeLayerAnimationController.swift
1
860
// // ShapeLayerAnimationController.swift // Animation // // Created by jhe.jeffery on 2017/9/30. // Copyright © 2017年 JefferyHe. All rights reserved. // import UIKit /** CAShapeLayer的动画 */ class ShapeLayerAnimationController: UIViewController { private lazy var shapeLayerAnimationView: ShapeLayerAnimationView = { let shapeLayerAnimationView = ShapeLayerAnimationView() shapeLayerAnimationView.frame = CGRect.zero shapeLayerAnimationView.center = self.view.center return shapeLayerAnimationView }() override func viewDidLoad() { super.viewDidLoad() title = "ShapeLayer Animation" view.backgroundColor = UIColor.white view.addSubview(shapeLayerAnimationView) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
mit
ed2498552bfd544abc4f6753b5591a2e
24.787879
73
0.705053
5.157576
false
false
false
false
mbeloded/discountsPublic
discounts/Classes/UI/MainMenu/MainMenuView.swift
1
1437
// // MainMenuView.swift // discounts // // Created by Michael Bielodied on 9/10/14. // Copyright (c) 2014 Michael Bielodied. All rights reserved. // import Foundation import UIKit let cellName = "CellIdent" class MainMenuView: UIView, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak private var tableView: UITableView! var owner:UIViewController! var selectedIndex:Int! func setupView(_ categoryIndex:Int) { DiscountsManager.sharedInstance.loadDataFromJSON("Company") DiscountsManager.sharedInstance.getCompanyWithCategory(categoryIndex) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return DiscountsManager.sharedInstance.discountsCategoryArrayData.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell:DiscountTableViewCell = self.tableView.dequeueReusableCell(withIdentifier: cellName) as! DiscountTableViewCell let tmp_cmp:CompanyObject = DiscountsManager.sharedInstance.discountsCategoryArrayData[indexPath.row] cell.company = tmp_cmp cell.setupCell() return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { selectedIndex = indexPath.row owner?.performSegue(withIdentifier: "showDiscount", sender: owner) } }
gpl-3.0
d54fbad220d58b57d82633821607d562
30.23913
127
0.722338
5.042105
false
false
false
false
banxi1988/BXiOSUtils
Pod/Classes/UIImageExtensions.swift
4
5058
// // UIImageExtensions.swift // Pods // // Created by Haizhen Lee on 15/12/6. // // import UIKit public extension UIImage{ public class func bx_image(_ hex:Int,alpha:Double=1.0) -> UIImage{ return bx_image(UIColor(hex: hex, alpha: alpha)) } public class func bx_transparentImage(_ size:CGSize=CGSize(width: 1, height: 1)) -> UIImage{ let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) UIGraphicsBeginImageContextWithOptions(size, false, 0) let ctx = UIGraphicsGetCurrentContext() UIColor.clear.setFill() ctx?.fill(rect) let img = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return img! } public static func bx_circleImage(_ color:UIColor,radius:CGFloat) -> UIImage{ let size = CGSize(width: radius * 2, height: radius * 2) let cornerRadius = radius return bx_roundImage(color, size: size, cornerRadius: cornerRadius) } public static func bx_roundImage(_ color:UIColor,size:CGSize=CGSize(width: 32, height: 32),cornerRadius:CGFloat = 4) -> UIImage{ let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) UIGraphicsBeginImageContextWithOptions(size, false, 0) let ctx = UIGraphicsGetCurrentContext() UIColor.clear.setFill() ctx?.fill(rect) color.setFill() let path = UIBezierPath(roundedRect: rect, cornerRadius: cornerRadius) path.lineWidth = 2 path.fill() let img = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return img! } public class func bx_image(_ color:UIColor,width:CGFloat) -> UIImage{ return bx_image(color, size: CGSize(width: width, height: width)) } public class func bx_image(_ color:UIColor,size:CGSize=CGSize(width: 1, height: 1)) -> UIImage{ let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) UIGraphicsBeginImageContextWithOptions(size, true, 0) let ctx = UIGraphicsGetCurrentContext() color.setFill() ctx?.fill(rect) let img = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return img! } @nonobjc public static func bx_placeholder(_ width:CGFloat) -> UIImage{ return bx_placeholder(CGSize(width: width, height: width)) } @nonobjc public static func bx_placeholder(_ size:CGSize) -> UIImage{ return bx_image(UIColor.white, size: size) } /** diameter:直径 **/ public func bx_circularImage(diameter:CGFloat, highlightedColor:UIColor? = nil) -> UIImage { let frame = CGRect(x: 0, y: 0, width: diameter, height: diameter) UIGraphicsBeginImageContextWithOptions(frame.size, false,0.0) let ctx = UIGraphicsGetCurrentContext() ctx?.saveGState() let imgPath = UIBezierPath(ovalIn: frame) imgPath.addClip() draw(in: frame) if let color = highlightedColor{ color.setFill() ctx?.fillEllipse(in: frame) } let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage! } public func bx_highlightImage( _ highlightedColor:UIColor? = nil,circular:Bool=true) -> UIImage { let frame = CGRect(x: 0, y: 0, width: size.width , height: size.height ) let color = highlightedColor ?? UIColor(white: 0.1, alpha: 0.3) UIGraphicsBeginImageContextWithOptions(frame.size, false,scale) let ctx = UIGraphicsGetCurrentContext() ctx?.saveGState() if circular{ let imgPath = UIBezierPath(ovalIn: frame) imgPath.addClip() }else{ let imgPath = UIBezierPath(roundedRect: frame, cornerRadius: 10) imgPath.addClip() } draw(in: frame) color.setFill() if circular{ ctx?.fillEllipse(in: frame) }else{ ctx?.fill(frame) } let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage! } public static func bx_createImage(_ text:String,backgroundColor:UIColor, textColor:UIColor,font:UIFont,diameter:CGFloat) -> UIImage { let frame = CGRect(x: 0, y: 0, width: diameter, height: diameter) let attrs = [NSFontAttributeName:font, NSForegroundColorAttributeName:textColor ] let textFrame = text.boundingRect(with: frame.size, options:.usesFontLeading, attributes: attrs, context: nil) let dx = frame.midX - textFrame.midX let dy = frame.midY - textFrame.midY let drawPoint = CGPoint(x: dx, y: dy) UIGraphicsBeginImageContextWithOptions(frame.size, false, 0.0) let ctx = UIGraphicsGetCurrentContext() ctx?.saveGState() backgroundColor.setFill() ctx?.fill(frame) text.draw(at: drawPoint, withAttributes: attrs) let image = UIGraphicsGetImageFromCurrentImageContext() ctx?.restoreGState() UIGraphicsEndImageContext() return image! } } public extension UIImage{ public var bx_rawImage:UIImage{ return self.withRenderingMode(.alwaysOriginal) } }
mit
cb1c3bf7ff141404c7b55f5c90654de7
31.191083
130
0.676494
4.406277
false
false
false
false
HKMOpen/actor-platform
actor-apps/app-ios/ActorApp/Controllers/Settings/SettingsNotificationsViewController.swift
5
12682
// // Copyright (c) 2014-2015 Actor LLC. <https://actor.im> // import UIKit class SettingsNotificationsViewController: AATableViewController { // MARK: - // MARK: Constructors private let CellIdentifier = "CellIdentifier" init() { super.init(style: UITableViewStyle.Grouped) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - override func viewDidLoad() { super.viewDidLoad() navigationItem.title = NSLocalizedString("NotificationsTitle", comment: "Notifcations and Sounds") tableView.registerClass(CommonCell.self, forCellReuseIdentifier: CellIdentifier) tableView.backgroundColor = MainAppTheme.list.backyardColor tableView.separatorStyle = UITableViewCellSeparatorStyle.None } // MARK: - // MARK: UITableView Data Source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 5 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if (section == 0) { return 1 } else if (section == 2) { return Actor.isNotificationsEnabled() ? 2 : 1 } else if (section == 1) { return Actor.isGroupNotificationsEnabled() ? 2 : 1 } else if (section == 3) { return Actor.isInAppNotificationsEnabled() ? 3 : 1 } else if (section == 4) { return 1 } return 1 } func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if (section == 0) { return NSLocalizedString("NotificationsEffectsTitle", comment: "Effects") } else if (section == 2) { return NSLocalizedString("NotificationsMobileTitle", comment: "Mobile Notifications") } else if (section == 1) { return NSLocalizedString("NotificationsGroups", comment: "Group Notifications") } else if (section == 3) { return NSLocalizedString("NotificationsInAppTitle", comment: "InApp Notifications") } else if (section == 4) { return NSLocalizedString("NotificationsPrivacyTitle", comment: "Privacy") } return nil } func tableView(tableView: UITableView, titleForFooterInSection section: Int) -> String? { if (section == 2) { return NSLocalizedString("NotificationsNotificationHint", comment: "Disable hint") } else if (section == 1) { return NSLocalizedString("NotificationsOnlyMentionsHint", comment: "Only Mentions hint") } else if (section == 3) { return NSLocalizedString("NotificationsPreviewHint", comment: "Preview hint") } return nil } private func notificationsTonesCell(indexPath: NSIndexPath) -> CommonCell { var cell = tableView.dequeueReusableCellWithIdentifier(CellIdentifier, forIndexPath: indexPath) as! CommonCell cell.setContent(NSLocalizedString("NotificationsSoundEffects", comment: "Sound Effects")) cell.style = .Switch cell.selectionStyle = UITableViewCellSelectionStyle.None cell.bottomSeparatorVisible = true cell.topSeparatorVisible = true cell.setSwitcherOn(Actor.isConversationTonesEnabled()) cell.switchBlock = { (nValue: Bool) in Actor.changeConversationTonesEnabledWithValue(nValue) } return cell } private func notificationsEnableCell(indexPath: NSIndexPath) -> CommonCell { var cell = tableView.dequeueReusableCellWithIdentifier(CellIdentifier, forIndexPath: indexPath) as! CommonCell cell.setContent(NSLocalizedString("NotificationsEnable", comment: "Enable")) cell.style = .Switch cell.selectionStyle = UITableViewCellSelectionStyle.None cell.bottomSeparatorVisible = true cell.topSeparatorVisible = true cell.setSwitcherOn(Actor.isNotificationsEnabled()) cell.switchBlock = { (nValue: Bool) in self.tableView.beginUpdates() Actor.changeNotificationsEnabledWithValue(nValue) var rows = [NSIndexPath(forRow: 1, inSection: 2)] if (nValue) { self.tableView.insertRowsAtIndexPaths(rows, withRowAnimation: UITableViewRowAnimation.Middle) } else { self.tableView.deleteRowsAtIndexPaths(rows, withRowAnimation: UITableViewRowAnimation.Middle) } self.tableView.endUpdates() } return cell } private func notificationsAlertCell(indexPath: NSIndexPath) -> CommonCell { var cell = tableView.dequeueReusableCellWithIdentifier(CellIdentifier, forIndexPath: indexPath) as! CommonCell cell.setContent(NSLocalizedString("NotificationsSound", comment: "Sound")) cell.style = .Switch cell.selectionStyle = UITableViewCellSelectionStyle.None cell.bottomSeparatorVisible = true //cell.topSeparatorVisible = true cell.setSwitcherOn(Actor.isNotificationSoundEnabled()) cell.setSwitcherEnabled(Actor.isNotificationsEnabled()) cell.switchBlock = { (nValue: Bool) in Actor.changeNotificationSoundEnabledWithValue(nValue) } return cell } private func groupEnabledCell(indexPath: NSIndexPath) -> CommonCell { var cell = tableView.dequeueReusableCellWithIdentifier(CellIdentifier, forIndexPath: indexPath) as! CommonCell cell.setContent(NSLocalizedString("NotificationsEnable", comment: "Enable")) cell.style = .Switch cell.selectionStyle = UITableViewCellSelectionStyle.None cell.topSeparatorVisible = true cell.bottomSeparatorVisible = true cell.setSwitcherOn(Actor.isGroupNotificationsEnabled()) cell.switchBlock = { (nValue: Bool) in self.tableView.beginUpdates() Actor.changeGroupNotificationsEnabled(nValue) var rows = [NSIndexPath(forRow: 1, inSection: 1)] if (nValue) { self.tableView.insertRowsAtIndexPaths(rows, withRowAnimation: UITableViewRowAnimation.Middle) } else { self.tableView.deleteRowsAtIndexPaths(rows, withRowAnimation: UITableViewRowAnimation.Middle) } self.tableView.endUpdates() } return cell } private func groupEnabledMentionsCell(indexPath: NSIndexPath) -> CommonCell { var cell = tableView.dequeueReusableCellWithIdentifier(CellIdentifier, forIndexPath: indexPath) as! CommonCell cell.setContent(NSLocalizedString("NotificationsOnlyMentions", comment: "Mentions")) cell.style = .Switch cell.selectionStyle = UITableViewCellSelectionStyle.None cell.bottomSeparatorVisible = true //cell.topSeparatorVisible = true cell.setSwitcherOn(Actor.isGroupNotificationsOnlyMentionsEnabled()) cell.setSwitcherEnabled(Actor.isGroupNotificationsEnabled()) cell.switchBlock = { (nValue: Bool) in Actor.changeGroupNotificationsOnlyMentionsEnabled(nValue) } return cell } private func inAppAlertCell(indexPath: NSIndexPath) -> CommonCell { var cell = tableView.dequeueReusableCellWithIdentifier(CellIdentifier, forIndexPath: indexPath) as! CommonCell cell.setContent(NSLocalizedString("NotificationsEnable", comment: "Enable")) cell.style = .Switch cell.selectionStyle = UITableViewCellSelectionStyle.None cell.bottomSeparatorVisible = true cell.topSeparatorVisible = true cell.setSwitcherOn(Actor.isInAppNotificationsEnabled()) cell.switchBlock = { (nValue: Bool) in self.tableView.beginUpdates() Actor.changeInAppNotificationsEnabledWithValue(nValue) var rows = [NSIndexPath(forRow: 1, inSection: 3), NSIndexPath(forRow: 2, inSection: 3)] if (nValue) { self.tableView.insertRowsAtIndexPaths(rows, withRowAnimation: UITableViewRowAnimation.Middle) } else { self.tableView.deleteRowsAtIndexPaths(rows, withRowAnimation: UITableViewRowAnimation.Middle) } self.tableView.endUpdates() } return cell } private func inAppSoundCell(indexPath: NSIndexPath) -> CommonCell { var cell = tableView.dequeueReusableCellWithIdentifier(CellIdentifier, forIndexPath: indexPath) as! CommonCell cell.setContent(NSLocalizedString("NotificationsSound", comment: "Sound")) cell.style = .Switch cell.selectionStyle = UITableViewCellSelectionStyle.None cell.bottomSeparatorVisible = true // cell.topSeparatorVisible = true cell.setSwitcherOn(Actor.isInAppNotificationSoundEnabled()) cell.setSwitcherEnabled(Actor.isInAppNotificationsEnabled()) cell.switchBlock = { (nValue: Bool) in Actor.changeInAppNotificationSoundEnabledWithValue(nValue) } return cell } private func inAppVibrateCell(indexPath: NSIndexPath) -> CommonCell { var cell = tableView.dequeueReusableCellWithIdentifier(CellIdentifier, forIndexPath: indexPath) as! CommonCell cell.setContent(NSLocalizedString("NotificationsVibration", comment: "Vibration")) cell.style = .Switch cell.selectionStyle = UITableViewCellSelectionStyle.None cell.bottomSeparatorVisible = true //cell.topSeparatorVisible = true cell.setSwitcherOn(Actor.isInAppNotificationVibrationEnabled()) cell.setSwitcherEnabled(Actor.isInAppNotificationsEnabled()) cell.switchBlock = { (nValue: Bool) in Actor.changeInAppNotificationVibrationEnabledWithValue(nValue) } return cell } private func notificationsPreviewCell(indexPath: NSIndexPath) -> CommonCell { var cell = tableView.dequeueReusableCellWithIdentifier(CellIdentifier, forIndexPath: indexPath) as! CommonCell cell.setContent(NSLocalizedString("NotificationsPreview", comment: "Message Preview")) cell.style = .Switch cell.selectionStyle = UITableViewCellSelectionStyle.None cell.bottomSeparatorVisible = true cell.topSeparatorVisible = true cell.setSwitcherOn(Actor.isShowNotificationsText()) cell.switchBlock = { (nValue: Bool) in Actor.changeShowNotificationTextEnabledWithValue(nValue) } return cell } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if indexPath.section == 0 { return notificationsTonesCell(indexPath) } else if (indexPath.section == 2) { if (indexPath.row == 0) { return notificationsEnableCell(indexPath) } else if (indexPath.row == 1) { return notificationsAlertCell(indexPath) } }else if (indexPath.section == 1) { if (indexPath.row == 0) { return groupEnabledCell(indexPath) } else { return groupEnabledMentionsCell(indexPath) } } else if (indexPath.section == 3) { if (indexPath.row == 0) { return inAppAlertCell(indexPath) } else if (indexPath.row == 1) { return inAppSoundCell(indexPath) } else if (indexPath.row == 2) { return inAppVibrateCell(indexPath) } } else if (indexPath.section == 4 ) { return notificationsPreviewCell(indexPath) } return UITableViewCell() } func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { let header: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView header.textLabel.textColor = MainAppTheme.list.sectionColor } func tableView(tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) { let header: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView header.textLabel.textColor = MainAppTheme.list.hintColor } // MARK: - // MARK: UITableView Delegate }
mit
9b7c543ec1d53bf98dcc0ada433947ef
39.260317
118
0.64974
5.656557
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/ViewRelated/Media/StockPhotos/StockPhotosDataSource.swift
2
5334
import WPMediaPicker /// Data Source for Stock Photos final class StockPhotosDataSource: NSObject, WPMediaCollectionDataSource { fileprivate static let paginationThreshold = 10 fileprivate var photosMedia = [StockPhotosMedia]() var observers = [String: WPMediaChangesBlock]() private var dataLoader: StockPhotosDataLoader? var onStartLoading: (() -> Void)? var onStopLoading: (() -> Void)? private let scheduler = Scheduler(seconds: 0.5) private(set) var searchQuery: String = "" init(service: StockPhotosService) { super.init() self.dataLoader = StockPhotosDataLoader(service: service, delegate: self) } func clearSearch(notifyObservers shouldNotify: Bool) { photosMedia.removeAll() if shouldNotify { notifyObservers() } } func numberOfGroups() -> Int { return 1 } func search(for searchText: String?) { searchQuery = searchText ?? "" guard searchText?.isEmpty == false else { clearSearch(notifyObservers: true) scheduler.cancel() return } scheduler.debounce { [weak self] in let params = StockPhotosSearchParams(text: searchText, pageable: StockPhotosPageable.first()) self?.search(params) self?.onStartLoading?() } } private func search(_ params: StockPhotosSearchParams) { dataLoader?.search(params) } func group(at index: Int) -> WPMediaGroup { return StockPhotosMediaGroup() } func selectedGroup() -> WPMediaGroup? { return StockPhotosMediaGroup() } func numberOfAssets() -> Int { return photosMedia.count } func media(at index: Int) -> WPMediaAsset { fetchMoreContentIfNecessary(index) return photosMedia[index] } func media(withIdentifier identifier: String) -> WPMediaAsset? { return photosMedia.filter { $0.identifier() == identifier }.first } func registerChangeObserverBlock(_ callback: @escaping WPMediaChangesBlock) -> NSObjectProtocol { let blockKey = UUID().uuidString observers[blockKey] = callback return blockKey as NSString } func unregisterChangeObserver(_ blockKey: NSObjectProtocol) { guard let key = blockKey as? String else { assertionFailure("blockKey must be of type String") return } observers.removeValue(forKey: key) } func registerGroupChangeObserverBlock(_ callback: @escaping WPMediaGroupChangesBlock) -> NSObjectProtocol { // The group never changes return NSNull() } func unregisterGroupChangeObserver(_ blockKey: NSObjectProtocol) { // The group never changes } func loadData(with options: WPMediaLoadOptions, success successBlock: WPMediaSuccessBlock?, failure failureBlock: WPMediaFailureBlock? = nil) { successBlock?() } func mediaTypeFilter() -> WPMediaType { return .image } func ascendingOrdering() -> Bool { return true } func searchCancelled() { searchQuery = "" clearSearch(notifyObservers: true) } // MARK: Unnused protocol methods func setSelectedGroup(_ group: WPMediaGroup) { // } func add(_ image: UIImage, metadata: [AnyHashable: Any]?, completionBlock: WPMediaAddedBlock? = nil) { // } func addVideo(from url: URL, completionBlock: WPMediaAddedBlock? = nil) { // } func setMediaTypeFilter(_ filter: WPMediaType) { // } func setAscendingOrdering(_ ascending: Bool) { // } } // MARK: - Helpers extension StockPhotosDataSource { private func notifyObservers(incremental: Bool = false, inserted: IndexSet = IndexSet()) { observers.forEach { $0.value(incremental, IndexSet(), inserted, IndexSet(), []) } } } // MARK: - Pagination extension StockPhotosDataSource { fileprivate func fetchMoreContentIfNecessary(_ index: Int) { if shoudLoadMore(index) { dataLoader?.loadNextPage() } } private func shoudLoadMore(_ index: Int) -> Bool { return index + type(of: self).paginationThreshold >= numberOfAssets() } } extension StockPhotosDataSource: StockPhotosDataLoaderDelegate { func didLoad(media: [StockPhotosMedia], reset: Bool) { defer { onStopLoading?() } guard media.count > 0 && searchQuery.count > 0 else { clearSearch(notifyObservers: true) return } if reset { overwriteMedia(with: media) } else { appendMedia(with: media) } } private func overwriteMedia(with media: [StockPhotosMedia]) { photosMedia = media notifyObservers(incremental: false) } private func appendMedia(with media: [StockPhotosMedia]) { let currentMaxIndex = photosMedia.count let newMaxIndex = currentMaxIndex + media.count - 1 let isIncremental = currentMaxIndex != 0 let insertedIndexes = IndexSet(integersIn: currentMaxIndex...newMaxIndex) photosMedia.append(contentsOf: media) notifyObservers(incremental: isIncremental, inserted: insertedIndexes) } }
gpl-2.0
b176c85538716c5aae70eb66de705fa8
26.353846
147
0.634046
4.92976
false
false
false
false
prachigauriar/PropertyListEditor
PropertyListEditor/Models/Property Lists/Items/PropertyListItem.swift
1
8346
// // PropertyListItem.swift // PropertyListEditor // // Created by Prachi Gauriar on 7/3/2015. // Copyright © 2015 Quantum Lens Cap. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// `PropertyListItems` represent property list types as an enum, with one case per property list /// type. They are the primary type for modeling property lists in this application. Due to their /// nested, value-type nature, they are not well-suited to editing in place, particularly when the /// edit is occurring more than one level deep in the property list’s data hierarchy. As such, we /// have defined an extension below for making edits recursively using index paths. See the /// documentation below for more information. enum PropertyListItem : CustomStringConvertible, Hashable { case array(PropertyListArray) case boolean(NSNumber) case data(NSData) case date(NSDate) case dictionary(PropertyListDictionary) case number(NSNumber) case string(NSString) var description: String { switch self { case let .array(array): return array.description case let .boolean(boolean): return boolean.boolValue.description case let .data(data): return data.description case let .date(date): return date.description case let .dictionary(dictionary): return dictionary.description case let .number(number): return number.description case let .string(string): return string.description } } var hashValue: Int { switch self { case let .array(array): return array.hashValue case let .boolean(boolean): return boolean.hashValue case let .data(data): return data.hashValue case let .date(date): return date.hashValue case let .dictionary(dictionary): return dictionary.hashValue case let .number(number): return number.hashValue case let .string(string): return string.hashValue } } /// Returns if the instance is an array or dictionary. var isCollection: Bool { return propertyListType == .array || propertyListType == .dictionary } } func ==(lhs: PropertyListItem, rhs: PropertyListItem) -> Bool { switch (lhs, rhs) { case let (.array(left), .array(right)): return left == right case let (.boolean(left), .boolean(right)): return left == right case let (.data(left), .data(right)): return left == right case let (.date(left), .date(right)): return left == right case let (.dictionary(left), .dictionary(right)): return left == right case let (.number(left), .number(right)): return left == right case let (.string(left), .string(right)): return left == right default: return false } } // MARK: - Property List Types /// `PropertyListType` is a simple enum that contains cases for each property list type. These are /// primarily useful when you need the type of a `PropertyListItem` for use in an arbitrary boolean /// expression. For example, /// /// ``` /// extension PropertyListItem { /// var isScalar: Bool { /// return propertyListType != .ArrayType && propertyListType != .DictionaryType /// } /// } /// ``` /// /// This type of concise expression isn’t possible with `PropertyListItem` because each of its enum /// cases has an associated value. enum PropertyListType { case array case boolean case data case date case dictionary case number case string } extension PropertyListItem { /// Returns the property list type of the instance. var propertyListType: PropertyListType { switch self { case .array: return .array case .boolean: return .boolean case .data: return .data case .date: return .date case .dictionary: return .dictionary case .number: return .number case .string: return .string } } } // MARK: - Accessing Items with Index Paths /// This extension adds the ability to access and change property lists using index paths. Rather /// than editing the property list items in place, the methods in this extension return new items /// that are the result of setting an item at particular index paths. extension PropertyListItem { /// Returns the item at the specified index path relative to the instance. /// /// - parameter indexPath: The index path. Raises an assertion if any element of the index path /// indexes into a scalar. func item(at indexPath: IndexPath) -> PropertyListItem { var item = self for index in indexPath { switch item { case let .array(array): item = array[index] case let .dictionary(dictionary): item = dictionary[index].value default: fatalError("non-empty indexPath for scalar type") } } return item } /// Returns a copy of the instance in which the item at `indexPath` is set to `newItem`. /// - parameter newItem: The new item to set at the specified index path relative to the instance /// - parameter indexPath: The index path. Raises an assertion if any element of the index path /// indexes into a scalar. func setting(_ newItem: PropertyListItem, at indexPath: IndexPath) -> PropertyListItem { return (indexPath as NSIndexPath).length > 0 ? setting(newItem, at: indexPath, indexPosition: 0) : newItem } /// A private method that actually implements `setting(_:at:)` by setting the /// item at the index position inside the index path. It is called recursively starting from /// index position 0 and continuing until the entire index path is traversed. /// /// - parameter newItem: The new item to set at the specified index path relative to the instance /// - parameter indexPath: The index path. Raises an assertion if any element of the index path /// indexes into a scalar. /// - parameter indexPosition: The position in the index path to get the current index private func setting(_ newItem: PropertyListItem, at indexPath: IndexPath, indexPosition: Int) -> PropertyListItem { if indexPosition == indexPath.count { return newItem } let index = indexPath[indexPosition] switch self { case var .array(array): let element = array[index] let newElement = element.setting(newItem, at: indexPath, indexPosition: indexPosition + 1) array[index] = newElement return .array(array) case var .dictionary(dictionary): let value = dictionary[index].value let newValue = value.setting(newItem, at: indexPath, indexPosition: indexPosition + 1) dictionary.setValue(newValue, at: index) return .dictionary(dictionary) default: fatalError("non-empty indexPath for scalar type") } } }
mit
d4bec78879c0cee04e2542d6d0b20efb
34.952586
120
0.65172
4.779943
false
false
false
false
PedroTrujilloV/TIY-Assignments
07--Clean-Up/LotteryNumber/LotteryNumber/LotteryNumberTableViewController.swift
1
4652
// // LotteryNumberTableViewController.swift // LotteryNumber // // Created by Pedro Trujillo on 10/13/15. // Copyright © 2015 Pedro Trujillo. All rights reserved. // import UIKit class LotteryNumberTableViewController: UITableViewController { //@IBOutlet var addNumber:UIButton! var arrayNumber = Array<Array<Int>>() override func viewDidLoad() { title = "Lotery Numbers" super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return arrayNumber.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("cellNumber", forIndexPath: indexPath) // Configure the cell... let NumberCell = arrayNumber[indexPath.row] cell.textLabel?.text = String(NumberCell) cell.detailTextLabel?.text = String(indexPath.row+1)//indexPath.row as! String return cell } @IBAction func refreshNumbersTable(sender: UIBarButtonItem) { cleanTable() } @IBAction func AddRandomNumber(sender: UIBarButtonItem) { var tempArray = Array<Int>() while tempArray.count < 6 { tempArray.append(generateRandomNumber()) } let newIndexPath = NSIndexPath(forRow: arrayNumber.count, inSection: 0) arrayNumber.append(tempArray) tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Top) } func generateRandomNumber() ->Int { let randomNumber = arc4random_uniform(53)//http://stackoverflow.com/questions/24119714/swift-random-number return Int(randomNumber) } func cleanTable() { while arrayNumber.count > 0 { let newIndexPath = NSIndexPath(forRow: arrayNumber.count-1, inSection: 0) arrayNumber.removeFirst() tableView.deleteRowsAtIndexPaths([newIndexPath], withRowAnimation: .Automatic) } } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ // Override to support editing the table view. /* override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } }*/ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } }
cc0-1.0
b90fdc051c78d1b6671ce8785ceecb51
30.856164
157
0.671469
5.40814
false
false
false
false
lenssss/whereAmI
Whereami/Controller/Personal/PersonalPerformanceChallengesTableViewCell.swift
1
5365
// // PersonalPerformanceChallengesTableViewCell.swift // Whereami // // Created by A on 16/4/26. // Copyright © 2016年 WuQifei. All rights reserved. // import UIKit class PersonalPerformanceChallengesTableViewCell: UITableViewCell { var winLabel:UILabel? = nil var loseLabel:UILabel? = nil var totalLabel:UILabel? = nil override func awakeFromNib() { super.awakeFromNib() // Initialization code } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setupUI() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupUI() } func setupUI() { let grayView = UIView() grayView.backgroundColor = UIColor(red: 231/255.0, green: 231/255.0, blue: 231/255.0, alpha: 1) self.contentView.addSubview(grayView) let line1 = UIView() line1.backgroundColor = UIColor.lightGrayColor() self.contentView.addSubview(line1) let line2 = UIView() line2.backgroundColor = UIColor.lightGrayColor() self.contentView.addSubview(line2) let line3 = UIView() line3.backgroundColor = UIColor.lightGrayColor() self.contentView.addSubview(line3) let challengeLabel = UILabel() challengeLabel.text = NSLocalizedString("challenges",tableName:"Localizable", comment: "") challengeLabel.textAlignment = .Left challengeLabel.textColor = UIColor.blackColor() self.contentView.addSubview(challengeLabel) let failedView = UIView() failedView.layer.cornerRadius = 5.0 failedView.backgroundColor = UIColor(red: 253/255.0, green: 121/255.0, blue: 126/255.0, alpha: 1) self.contentView.addSubview(failedView) let winedView = UIView() winedView.layer.cornerRadius = 5.0 winedView.backgroundColor = UIColor(red: 137/255.0, green: 223/255.0, blue: 126/255.0, alpha: 1) failedView.addSubview(winedView) self.winLabel = UILabel() winLabel!.textAlignment = .Left winLabel!.layer.cornerRadius = 5.0 winLabel!.textColor = UIColor.whiteColor() winLabel!.font = UIFont.boldSystemFontOfSize(20.0) failedView.addSubview(winLabel!) self.loseLabel = UILabel() loseLabel!.textAlignment = .Right loseLabel!.textColor = UIColor.whiteColor() loseLabel!.font = UIFont.boldSystemFontOfSize(20.0) failedView.addSubview(loseLabel!) self.totalLabel = UILabel() totalLabel!.textAlignment = .Center self.contentView.addSubview(totalLabel!) grayView.autoPinEdgeToSuperviewEdge(.Top) grayView.autoPinEdgeToSuperviewEdge(.Left) grayView.autoPinEdgeToSuperviewEdge(.Right) grayView.autoSetDimension(.Height, toSize: 20) line1.autoPinEdge(.Top, toEdge: .Bottom, ofView: grayView) line1.autoPinEdgeToSuperviewEdge(.Left) line1.autoPinEdgeToSuperviewEdge(.Right) line1.autoSetDimension(.Height, toSize: 1) challengeLabel.autoPinEdge(.Top, toEdge: .Bottom, ofView: line1) challengeLabel.autoPinEdgeToSuperviewEdge(.Left) challengeLabel.autoPinEdge(.Bottom, toEdge: .Top, ofView: line2) challengeLabel.autoSetDimensionsToSize(CGSize(width: 100,height: 50)) line2.autoPinEdgeToSuperviewEdge(.Left) line2.autoPinEdgeToSuperviewEdge(.Right) line2.autoSetDimension(.Height, toSize: 1) line2.autoPinEdge(.Bottom, toEdge: .Top, ofView: failedView, withOffset: -15) failedView.autoPinEdgeToSuperviewEdge(.Left, withInset: 40) failedView.autoPinEdgeToSuperviewEdge(.Right, withInset: 40) failedView.autoPinEdge(.Bottom, toEdge: .Top, ofView: totalLabel!,withOffset: -8) winedView.autoPinEdgeToSuperviewEdge(.Top) winedView.autoPinEdgeToSuperviewEdge(.Left) winedView.autoPinEdgeToSuperviewEdge(.Bottom) winedView.autoMatchDimension(.Width, toDimension: .Width, ofView: failedView, withMultiplier: 0.5) winLabel!.autoPinEdgeToSuperviewEdge(.Top) winLabel!.autoPinEdgeToSuperviewEdge(.Bottom) winLabel!.autoPinEdgeToSuperviewEdge(.Left,withInset: 8) winLabel!.autoSetDimension(.Width, toSize: 150) loseLabel!.autoPinEdgeToSuperviewEdge(.Top) loseLabel!.autoPinEdgeToSuperviewEdge(.Bottom) loseLabel!.autoPinEdgeToSuperviewEdge(.Right,withInset: 8) loseLabel!.autoSetDimension(.Width, toSize: 150) totalLabel!.autoPinEdgeToSuperviewEdge(.Left, withInset: 0) totalLabel!.autoPinEdgeToSuperviewEdge(.Right, withInset: 0) totalLabel!.autoPinEdge(.Bottom, toEdge: .Top, ofView: line3,withOffset: -8) line3.autoPinEdgeToSuperviewEdge(.Left) line3.autoPinEdgeToSuperviewEdge(.Right) line3.autoPinEdgeToSuperviewEdge(.Bottom) line3.autoSetDimension(.Height, toSize: 1) } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
mit
968cb62e3cc0b4dadc3d9d06bfe3a01d
38.138686
106
0.666542
4.852489
false
false
false
false
ViennaRSS/vienna-rss
Vienna/Sources/Main window/ArticleStyleLoader.swift
2
841
// // ArticleStyleLoader.swift // Vienna // // Copyright 2019 // import Foundation class ArticleStyleLoader: NSObject { @objc static var stylesDirectoryURL = FileManager.default.applicationSupportDirectory.appendingPathComponent("Styles", isDirectory: true) private static var loaded = false private static var styles = NSMutableDictionary() @objc static var stylesMap: NSMutableDictionary { loaded ? styles : reloadStylesMap() } @objc static func reloadStylesMap() -> NSMutableDictionary { guard let path = Bundle.main.sharedSupportURL?.appendingPathComponent("Styles").path else { return [:] } loadMapFromPath(path, styles, true, nil) loadMapFromPath(stylesDirectoryURL.path, styles, true, nil) loaded = true return styles } }
apache-2.0
3c5ec5329aa12453919b5e1dad998bfa
23.735294
141
0.684899
4.861272
false
false
false
false
Chaosspeeder/YourGoals
YourGoals/Business/Data Model/Extensions/Task+State.swift
1
939
// // Tasks+State.swift // YourGoals // // Created by André Claaßen on 25.10.17. // Copyright © 2017 André Claaßen. All rights reserved. // import Foundation // MARK: - task state handling extension Task { /// change the task state to active or done /// /// - Parameter state: active or done func setTaskState(state:ActionableState) { self.state = Int16(state.rawValue) } /// retrieve the state of the task /// /// - Returns: a task state func getTaskState() -> ActionableState { return ActionableState(rawValue: Int(self.state))! } /// true, if task is active /// /// - Returns: true, if task is active func taskIsActive() -> Bool { return getTaskState() == .active } /// true, if task is done /// /// - Returns: true if task is done func taskIsDone() -> Bool { return getTaskState() == .done } }
lgpl-3.0
841d9094cca31a13ecdf41bad0dd271e
20.72093
58
0.584582
4.078603
false
false
false
false
kzaher/RegX
RegX/RegXPlugin.swift
1
850
// // RegXPlugin.swift // RegX // // Created by Krunoslav Zaher on 10/18/14. // Copyright (c) 2014 Krunoslav Zaher. All rights reserved. // import Foundation var service : XCodeService? = nil extension RegXPlugin { private struct Instances { static var service : XCodeService? = nil } public class func pluginDidLoad(plugin: Bundle) { Log("RegXPlugin Loaded") let sharedApplication = NSApplication.shared() let errorPresenter = AlertErrorPresenter() let tabWidth = { 1 } // { return Int(RegX_tabWidth()) } Instances.service = XCodeService(xcodeApp:sharedApplication, tabWidth: tabWidth, notificationCenter: NotificationCenter.default, errorPresenter: errorPresenter, forms: Configuration.forms) } }
mit
e5213d5632e1169f688c3e5573115434
25.5625
68
0.632941
4.67033
false
false
false
false
superk589/CGSSGuide
DereGuide/Common/CloudKitSync/FavoriteSongRemover.swift
3
3257
// // FavoriteSongRemover.swift // DereGuide // // Created by zzk on 29/09/2017. // Copyright © 2017 zzk. All rights reserved. // import CoreData /// delete remote units when local units are deleted final class FavoriteSongRemover: ElementChangeProcessor { var remote: FavoriteSongsRemote init(remote: FavoriteSongsRemote) { self.remote = remote } var elementsInProgress = InProgressTracker<FavoriteSong>() func setup(for context: ChangeProcessorContext) { // no-op } func processChangedLocalElements(_ elements: [FavoriteSong], in context: ChangeProcessorContext) { processDeletedUnits(elements, in: context) } func processRemoteChanges<T>(_ changes: [RemoteRecordChange<T>], in context: ChangeProcessorContext, completion: () -> ()) { // no-op completion() } func fetchLatestRemoteRecords(in context: ChangeProcessorContext) { // no-op } var predicateForLocallyTrackedElements: NSPredicate { let marked = FavoriteSong.markedForRemoteDeletionPredicate let notDeleted = FavoriteSong.notMarkedForLocalDeletionPredicate return NSCompoundPredicate(andPredicateWithSubpredicates:[marked, notDeleted]) } } extension FavoriteSongRemover { fileprivate func processDeletedUnits(_ deletions: [FavoriteSong], in context: ChangeProcessorContext) { context.perform { let allObjects = Set(deletions) let localOnly = allObjects.filter { $0.remoteIdentifier == nil } let objectsToDeleteRemotely = Array(allObjects.subtracting(localOnly)) if Config.cloudKitDebug { if localOnly.count > 0 { print("favorite song remover: delete local \(localOnly.count)") } if objectsToDeleteRemotely.count > 0 { print("favorite song remover: delete remote \(objectsToDeleteRemotely.count)") } } self.deleteLocally(Array(localOnly), context: context) self.deleteRemotely(objectsToDeleteRemotely, context: context) } } fileprivate func deleteLocally(_ deletions: [FavoriteSong], context: ChangeProcessorContext) { deletions.forEach { $0.markForLocalDeletion() } } fileprivate func deleteRemotely(_ deletions: [FavoriteSong], context: ChangeProcessorContext) { remote.remove(deletions, completion: context.perform { deletedRecordIDs, error in var deletedIDs = Set(deletedRecordIDs) if case .permanent(let ids)? = error { deletedIDs.formUnion(ids) } let toBeDeleted = deletions.filter { deletedIDs.contains($0.remoteIdentifier ?? "") } self.deleteLocally(toBeDeleted, context: context) // This will retry failures with non-permanent failures: if case .temporary(let interval)? = error { self.retryAfter(interval, in: context, task: { self.didComplete(Array(deletions), in: context) }) } context.delayedSaveOrRollback() }) } }
mit
b21d5df1bdc4abd6f07704b8f4129dad
32.916667
128
0.628993
5.127559
false
false
false
false
mathewsheets/SwiftLearning
SwiftLearning.playground/Pages/Protocols.xcplaygroundpage/Contents.swift
1
18218
/*: [Table of Contents](@first) | [Previous](@previous) | [Next](@next) - - - # Protocols * callout(Session Overview): In the context of the English language, a protocol is a set of rules that explain the conduct and procedures to be followed. You can also think of it as a contract between two parties and consequences if the contract is broken. In the context of typed programming languages, a protocol defines what must be implemented by a data type, with a compiler responding with errors if you don’t follow the protocol. - - - */ import Foundation /*: ## What Are They and Why Use Them? Swift protocols are essentially types without the implementation of properties or methods. They create a contract with a conforming type. The conforming type must implement the properties and methods defined in the protocol. As we have learned in earlier sessions, types can contain other types, as well as contain a collection of types. When applying that to protocols, you as the developer are unaware of the implementation, you only care that a property or method exists for you to access or call. This single attribute of protocols, not being aware of the implementation, gives you the ability to change the implementation or have multiple implementations of a protocol. This provides you with low coupling between two data types and a pluggable application architecture. */ /*: ## Conforming To In earlier sessions, we have already encountered protocols. Most of the data types we have worked with such as `Int`, `String` and `Bool` all **conform** to one of the following three protocols, `Equatable`, `Comparable`, and `Hashable`. We have also seen the `Error` protocol when creating a enumeration that can be used in a throwing function. Conforming to a protocol implies that the data type provides the implementation of the properties or methods defined in the protocol. You indicate conforming to a protocol by placing the protocol after a colon `:`, similar to how a class is inheriting from a superclass. If a class is inheriting and conforming, place the inheriting class first then the protocols separated by a comma. Protocols can also inherit from one another, similar to classes, but protocols can inherit from multiple protocols unlike classes. */ /*: ### The `Equatable` Protocol By conforming to the `Equatable` protocol, you are implying that your data type will implement `public func ==(lhs: Self, rhs: Self) -> Bool` and that instances of that type can be compared for value equality using operators `==` and `!=`. */ class Father: Equatable { var name: String var age: Int init(name: String, age: Int) { self.name = name self.age = age } // it's an operator, the implementation must be defined with static static func ==(lhs: Father, rhs: Father) -> Bool { return lhs.name == rhs.name && lhs.age == rhs.age } } let moe1 = Father(name: "Moe", age: 28) let moe2 = Father(name: "Moe", age: 28) let curly = Father(name: "Curly", age: 50) if moe1 == moe2 { print("same moe") } else { print("not the same moe") } if moe1 === moe2 { print("same moe identity") } else { print("not the same moe identity") } if moe1 == curly { print("same father") } else { print("not the same father") } if moe1 != curly { print("not the same father") } else { print("same father") } /*: Above we created a `Father` class conforming to the `Equatable` protocol. The `Equatable` protocol requires us to implement `public func ==(lhs: Self, rhs: Self) -> Bool`, which we have with `func ==(lhs: Father, rhs: Father) -> Bool {...}`. Next we created three instances of `Father`, two of which are actually equals according to our implementation of `public func ==(lhs: Self, rhs: Self) -> Bool`. Also notice the use of the *identity Operator* `===`. */ /*: ### The `Comparable` Protocol By conforming to the `Comparable` protocol, you are implying that your data type will implement: - `public func <(lhs: Self, rhs: Self) -> Bool` - `public func <=(lhs: Self, rhs: Self) -> Bool` - `public func >=(lhs: Self, rhs: Self) -> Bool` - `public func >(lhs: Self, rhs: Self) -> Bool` */ class Son: Father, Comparable { var favoriteTruck: String init(name: String, age: Int, truck: String) { favoriteTruck = truck super.init(name: name, age: age) } static func <(lhs: Son, rhs: Son) -> Bool { return lhs.age < rhs.age } static func <=(lhs: Son, rhs: Son) -> Bool { return lhs.age <= rhs.age } static func >=(lhs: Son, rhs: Son) -> Bool { return lhs.age >= rhs.age } static func >(lhs: Son, rhs: Son) -> Bool { return lhs.age > rhs.age } // allow to "override the operator" static func ==(lhs: Son, rhs: Son) -> Bool { return lhs.age == rhs.age } } let larry2 = Son(name: "Larry", age: 2, truck: "Blue Dump") let larry4 = Son(name: "Larry", age: 4, truck: "Blue Dump") let larry7 = Son(name: "Larry", age: 7, truck: "Blue Dump") let larry10 = Son(name: "Larry", age: 10, truck: "Blue Dump") if larry2 < larry4 { print("larry 2 < larry 4") } if larry4 <= larry4 { print("larry 4 <= larry 4") } if larry7 >= larry4 { print("larry 7 >= larry 4") } if larry10 > larry7 { print("larry 10 >= larry 7") } let larry2a = Son(name: "Larry2", age: 2, truck: "Blue Dump") if larry2 == larry2a { print("same larry") } /*: Above we created a `Son` class inheriting from `Father` and also conforming to the `Comparable` protocol. The `Son` class need to implement all the functions defined in the `Comparable` protocol. Next we create four instances of a `Son` class exercising the comparison operators of `<, <=, >=, >`. */ /*: ### The `Hashable` Protocol By conforming to the `Hashable` protocol, you are implying that your data type will implement `public var hashValue: Int { get }` and that instances of that type can be as `Dictionary` keys. */ class Daughter: Father, Hashable { var favoriteDoll: String var hashValue: Int { return "\(name),\(age),\(favoriteDoll)".hashValue } init(name: String, age: Int, doll: String) { favoriteDoll = doll super.init(name: name, age: age) } } let abby1 = Daughter(name: "abby", age: 3, doll: "Barbie") let abby2 = Daughter(name: "abby", age: 3, doll: "Barbie") let katie = Daughter(name: "katie", age: 5, doll: "Cabbage Patch") if abby1.hashValue == abby2.hashValue { print("same hashValue") } else { print("different hashValue") } if abby1.hashValue == katie.hashValue { print("same hashValue") } else { print("different hashValue") } var fathersByDaughter: [Daughter:Father] = [:] fathersByDaughter[abby1] = moe1 print(fathersByDaughter[abby1]!.name) fathersByDaughter[abby2] = curly print(fathersByDaughter[abby1]!.name) fathersByDaughter[katie] = curly if fathersByDaughter[abby2] == fathersByDaughter[katie] { print("abby2 and katie have the same father") } /*: Above we created a `Daughter` class inheriting from `Father` and also conforming to the `Hashable` protocol. The `Daughter` class needs to conform to the ‘Hashable protocol’ by implementing the property `public var hashValue: Int { get }`. Next we create three instances of the `Daughter` class, two of which have the same `hashValue`, but are different instances. We also use a `Dictionary` using the `Daughter` instances as keys. */ /*: ## Creating Protocols Protocols are created with the `protocol` keyword. The properties and methods definitions of the protocol must be implemented by the conforming data type. */ protocol Crawlable { // type & instance properties to conform to // type & instance methods to conform to } class Crawler: Crawlable { } let crawler = Crawler() /*: Above we created a protocol with no properties or methods, simply as an example of how to create a protocol. The `Crawler` conforms to the `Crawlable` protocol, and in this case, nothing has to be implemented. */ /*: ## Protocols & Properties Protocols can define both type and instance properties. The conforming data type property could be either a stored or computed property, as long as the name and type are correct. When defining a property in a protocol, you need to specify what property methods need to be implemented with the `get` and/or `set` property methods. */ protocol Walkable: Crawlable { var direction: String { get set } } class Walker: Walkable { var direction: String init(direction: String) { self.direction = direction } } let walker = Walker(direction: "North") print(walker.direction) /*: Above we created a `Walkable` protocol with an instance property. We also created a class `Walker` conforming to `Walkable` implementing the instance property. And finally we created an instance of `Walker` printing the direction. */ /*: ## Protocols & Methods Protocols can define both type and instance methods. Again, conforming data types need to implement the defined type or instance protocol method. */ protocol Runnable: Walkable { func run(speed: Float) } class Runner: Runnable { var direction: String init(direction: String) { self.direction = direction } func run(speed: Float) { print("running \(speed) mph \(direction)") } } let runner = Runner(direction: "West") runner.run(speed: 6.5) /*: Above we created a `Runnable` protocol with an instance method. We also created a class `Runner` conforming to `Runnable` implementing the instance method. And finally we create an instance of `Runner` printing the speed and direction. */ /*: ## Protocols & Initializers Protocols can also defined initializers. In doing so, the conforming data type is required to implement the initializer. The `required` keyword must be included in the conforming data type’s implementation of the initializer. */ protocol Talkable { init(son: Son) } class TalkingSon: Son, Talkable { required init(son: Son) { super.init(name: son.name, age: son.age, truck: son.favoriteTruck) } var description: String { return "My name is \(name). I'm \(age) years old and my favorite truck is \(favoriteTruck)" } } let talker = TalkingSon(son: Son(name: "Oliver", age: 2, truck: "Red")) print(talker.description) /*: Above we created a `Talkable` protocol with an initializer. We also created a class `TalkingSon` inheriting from `Son` and conforming to `Talkable` implementing the required initializer. And finally we create an instance of `TalkingSon` printing the description. */ /*: ## Protocols as Types With protocols and classes, the properties and methods defined in the protocol and the properties and methods implemented in the conforming class appear to be one in the same. Remember, protocols don’t provide the implementation, but classes do. You cannot create an instance of just a protocol, you must create an instance of a concrete data type that conforms to a protocol. This enables you do store, return, and pass as arguments to functions, data types confirming to a protocol with just the protocol name. */ var crawers: [Crawlable] = [] // an array of Crawlable instances. Crawlable is a protocol let walkable: Walkable? // an instance of Walkable protocol RunnerWalkable { init(walker: Walkable) } class RunnerWalker: Runnable, RunnerWalkable { var direction: String required init(walker: Walkable) { // initializer with a protocol parameter self.direction = walker.direction } func run(speed: Float) { print("I can run \(speed) mph \(direction)") } } let runnerWalker: Runnable = RunnerWalker(walker: Walker(direction: "North")) runnerWalker.run(speed: 4.5) /*: Above we store multiple instances of different classes conforming to specific protocols. We store an array of `Crawlable` instances, and an instance of a `Walkable`. We also created a `RunnerWalker` class conforming to `Runnable` and `RunnerWalkable` which accepts a protocol of `Walkable` as in argument in the required initializer. Finally we create an instance of `RunnerWalker` calling the `run(:Int)` method. */ /*: ## Delegating the work with Protocols In the world of iOS development, the delegation design pattern is leveraged all through out the SDK. The delegation design pattern enables concrete classes to delegate work to other data types that conform to a protocol. The protocol is responsible to define what work that needs to be executed and conforming data types implement the work. The concrete data type that does the delegation does not need to know the underlining implementation of the protocol. ### The Protocols Protocols are what make the delegation design pattern powerful. We don't want our concrete classes coupled to a another concrete class. */ protocol DoableAction { var action: String { get } } protocol DoableActionDelegate { func willDo(what: DoableAction) func doing(what: DoableAction) func didDo(what: DoableAction) } protocol Doable { func doingWhat() } /*: ### The Comforming Types We need classes to conform to the above protocols to swap out implementations. */ class NothingAction: DoableAction { var action: String { return "Nothing" } } class EatingAction: DoableAction { var action: String { return "Eating" } } class DrinkingAction: DoableAction { var action: String { return "Drinking" } } class SleepingAction: DoableAction { var action: String { return "Sleeping" } } class BusyWorkAction: DoableAction { var action: String { return "Busy Work" } } class DoingSomethingPrinter: DoableActionDelegate { func willDo(what: DoableAction) { print("will do \(what.action)") } func doing(what: DoableAction) { print("doing \(what.action)") } func didDo(what: DoableAction) { print("did do \(what.action)") } } class DoingSomethingTimeTracker: DoableActionDelegate { func willDo(what: DoableAction) { print("will track time of doing \(what.action)") } func doing(what: DoableAction) { print("track time of doing \(what.action)") } func didDo(what: DoableAction) { print("did track time of doing \(what.action)") } } class DoingSomething: Doable { var action: DoableAction = NothingAction() var delegate: DoableActionDelegate? func doingWhat() { delegate?.willDo(what: action) delegate?.doing(what: action) delegate?.didDo(what: action) } } /*: ### Bringing it all together When leveraging the delegation design pattern, we can swap out the implementation of the of the protocol providing different behavior. */ let worker = DoingSomething() worker.delegate = DoingSomethingPrinter() // let's just print what the worker is doing worker.doingWhat() worker.action = EatingAction() worker.doingWhat() worker.action = DrinkingAction() worker.doingWhat() worker.action = SleepingAction() worker.doingWhat() worker.action = BusyWorkAction() worker.delegate = DoingSomethingTimeTracker() // pretend that this will actually persist somewhere worker.doingWhat() /*: Above we leverage the delegation design pattern swapping out different implementation of the `DoableAction` and `DoableActionDelegate` protocols. We call the `doingWhat()` method on the `worker` constant printing out the different string per implementation. */ /*: ## Type Checking & Type Casting Protocols As we learned in the [Inheritance](Inheritance) session, we can leverage the type check operator `is` and the type cast operator `as` when checking if a data type is a subclass of a superclass. The same applies to protocols, because protocols represent an instance of a concrete class. */ if talker is Crawlable { // this is false print("I'm a crawler") } if let aTalker = crawler as? Talkable { // this is false print("I'm a talker") } var objects: [AnyObject] = [] objects.append(crawler) // conforms to Crawlable objects.append(walker) // conforms to Walkable objects.append(runner) // conforms to Runnable objects.append(talker) // conforms to Talkable objects.append(worker) // conforms to Doable for object in objects { switch object { case let crawler as Crawlable: print("I'm a Crawlable") case let crawler as Walker: print("I'm a Walker") case let crawler as Runner: print("I'm a Runner") case let talker as Talkable: print("I'm a Talkable") case let worker as Doable: print("I'm a Doable") default: print("I'm something strange") } } /*: Above we leverage the type checking and type casting operators to determine what instances conform to specified protocols, similar to the example in the Inheritance session. */ /*: - - - * callout(Checkpoint): At this point, you have learned how to leverage and see the power of protocols. Protocols and the delegation design pattern enable you to build data type low coupling relationships. Protocols provide the capability to swap out the underlying implementation without suffering the consequence of compiler errors if you had coupled to a concrete class. **Keywords to remember:** - `protocol` = The creation of a protocol * callout(Supporting Materials): Chapters and sections from the Guide and Vidoes from WWDC - [Guide: Protocols](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Protocols.html) - [Video: Protocol-Oriented Programming in Swift](https://developer.apple.com/videos/play/wwdc2015-408/) - - - [Table of Contents](@first) | [Previous](@previous) | [Next](@next) */
mit
e19ffda10ddbbc2ec2a64be9d40dc681
34.082852
863
0.691839
4.048922
false
false
false
false
Incipia/IncipiaKit
IncipiaKit/UIKit-Extensions/UIImage+Extensions.swift
1
8941
// // UIImage+Extensions.swift // IncipiaKit // // Created by Gregory Klein on 6/28/16. // Copyright © 2016 Incipia. All rights reserved. // import Foundation import Accelerate public extension UIImage { // MARK: - Utilities class public func convertGradientToImage(colors: [UIColor], frame: CGRect) -> UIImage { // start with a CAGradientLayer let gradientLayer = CAGradientLayer() gradientLayer.frame = frame // add colors as CGCologRef to a new array and calculate the distances var colorsRef : [CGColorRef] = [] var locations : [NSNumber] = [] for i in 0 ... colors.count-1 { colorsRef.append(colors[i].CGColor as CGColorRef) locations.append(Float(i)/Float(colors.count)) } gradientLayer.colors = colorsRef gradientLayer.locations = locations // now build a UIImage from the gradient UIGraphicsBeginImageContext(gradientLayer.bounds.size) gradientLayer.renderInContext(UIGraphicsGetCurrentContext()!) let gradientImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() // return the gradient image return gradientImage } class public func imageWithColor(color: UIColor) -> UIImage { return imageWithColor(color, size: CGSize(width: 1, height: 1)) } class public func imageWithColor(color: UIColor, size: CGSize) -> UIImage { let rect = CGRectMake(0, 0, size.width, size.height) UIGraphicsBeginImageContextWithOptions(size, false, 0) color.setFill() UIRectFill(rect) let image: UIImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } public func correctlyOrientedImage() -> UIImage { guard imageOrientation != UIImageOrientation.Up else { return self } UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale) self.drawInRect(CGRectMake(0, 0, self.size.width, self.size.height)) let normalizedImage: UIImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return normalizedImage; } // MARK: - Effects public func applyLightEffect() -> UIImage? { return applyBlur(withRadius: 30, tintColor: UIColor(white: 1.0, alpha: 0.3), saturationDeltaFactor: 1.8) } public func applyExtraLightEffect() -> UIImage? { return applyBlur(withRadius: 20, tintColor: UIColor(white: 0.97, alpha: 0.82), saturationDeltaFactor: 1.8) } public func applyDarkEffect() -> UIImage? { return applyBlur(withRadius: 20, tintColor: UIColor(white: 0.11, alpha: 0.73), saturationDeltaFactor: 1.8) } public func applyTintEffectWithColor(tintColor: UIColor) -> UIImage? { let effectColorAlpha: CGFloat = 0.6 var effectColor = tintColor let componentCount = CGColorGetNumberOfComponents(tintColor.CGColor) if componentCount == 2 { var b: CGFloat = 0 if tintColor.getWhite(&b, alpha: nil) { effectColor = UIColor(white: b, alpha: effectColorAlpha) } } else { var red: CGFloat = 0 var green: CGFloat = 0 var blue: CGFloat = 0 if tintColor.getRed(&red, green: &green, blue: &blue, alpha: nil) { effectColor = UIColor(red: red, green: green, blue: blue, alpha: effectColorAlpha) } } return applyBlur(withRadius: 10, tintColor: effectColor, saturationDeltaFactor: -1.0, maskImage: nil) } public func applyBlur(withRadius radius: CGFloat, tintColor: UIColor?, saturationDeltaFactor: CGFloat, maskImage: UIImage? = nil) -> UIImage? { // Check pre-conditions. if (size.width < 1 || size.height < 1) { print("*** error: invalid size: \(size.width) x \(size.height). Both dimensions must be >= 1: \(self)") return nil } if self.CGImage == nil { print("*** error: image must be backed by a CGImage: \(self)") return nil } if maskImage != nil && maskImage!.CGImage == nil { print("*** error: maskImage must be backed by a CGImage: \(maskImage)") return nil } let __FLT_EPSILON__ = CGFloat(FLT_EPSILON) let screenScale = UIScreen.mainScreen().scale let imageRect = CGRect(origin: CGPointZero, size: size) var effectImage = self let hasBlur = radius > __FLT_EPSILON__ let hasSaturationChange = fabs(saturationDeltaFactor - 1.0) > __FLT_EPSILON__ if hasBlur || hasSaturationChange { func createEffectBuffer(context: CGContext?) -> vImage_Buffer { let data = CGBitmapContextGetData(context) let width = vImagePixelCount(CGBitmapContextGetWidth(context)) let height = vImagePixelCount(CGBitmapContextGetHeight(context)) let rowBytes = CGBitmapContextGetBytesPerRow(context) return vImage_Buffer(data: data, height: height, width: width, rowBytes: rowBytes) } UIGraphicsBeginImageContextWithOptions(size, false, screenScale) let effectInContext = UIGraphicsGetCurrentContext() CGContextScaleCTM(effectInContext, 1.0, -1.0) CGContextTranslateCTM(effectInContext, 0, -size.height) CGContextDrawImage(effectInContext, imageRect, self.CGImage) var effectInBuffer = createEffectBuffer(effectInContext) UIGraphicsBeginImageContextWithOptions(size, false, screenScale) let effectOutContext = UIGraphicsGetCurrentContext() var effectOutBuffer = createEffectBuffer(effectOutContext) if hasBlur { // A description of how to compute the box kernel width from the Gaussian // radius (aka standard deviation) appears in the SVG spec: // http://www.w3.org/TR/SVG/filters.html#feGaussianBlurElement // // For larger values of 's' (s >= 2.0), an approximation can be used: Three // successive box-blurs build a piece-wise quadratic convolution kernel, which // approximates the Gaussian kernel to within roughly 3%. // // let d = floor(s * 3*sqrt(2*pi)/4 + 0.5) // // ... if d is odd, use three box-blurs of size 'd', centered on the output pixel. // let inputRadius = radius * screenScale var radius = UInt32(floor(inputRadius * 3.0 * CGFloat(sqrt(2 * M_PI)) / 4 + 0.5)) if radius % 2 != 1 { radius += 1 // force radius to be odd so that the three box-blur methodology works. } let imageEdgeExtendFlags = vImage_Flags(kvImageEdgeExtend) vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags) vImageBoxConvolve_ARGB8888(&effectOutBuffer, &effectInBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags) vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags) } var effectImageBuffersAreSwapped = false if hasSaturationChange { let s: CGFloat = saturationDeltaFactor let floatingPointSaturationMatrix: [CGFloat] = [ 0.0722 + 0.9278 * s, 0.0722 - 0.0722 * s, 0.0722 - 0.0722 * s, 0, 0.7152 - 0.7152 * s, 0.7152 + 0.2848 * s, 0.7152 - 0.7152 * s, 0, 0.2126 - 0.2126 * s, 0.2126 - 0.2126 * s, 0.2126 + 0.7873 * s, 0, 0, 0, 0, 1 ] let divisor: CGFloat = 256 let matrixSize = floatingPointSaturationMatrix.count var saturationMatrix = [Int16](count: matrixSize, repeatedValue: 0) for i: Int in 0 ..< matrixSize { saturationMatrix[i] = Int16(round(floatingPointSaturationMatrix[i] * divisor)) } if hasBlur { vImageMatrixMultiply_ARGB8888(&effectOutBuffer, &effectInBuffer, saturationMatrix, Int32(divisor), nil, nil, vImage_Flags(kvImageNoFlags)) effectImageBuffersAreSwapped = true } else { vImageMatrixMultiply_ARGB8888(&effectInBuffer, &effectOutBuffer, saturationMatrix, Int32(divisor), nil, nil, vImage_Flags(kvImageNoFlags)) } } if !effectImageBuffersAreSwapped { effectImage = UIGraphicsGetImageFromCurrentImageContext() } UIGraphicsEndImageContext() if effectImageBuffersAreSwapped { effectImage = UIGraphicsGetImageFromCurrentImageContext() } UIGraphicsEndImageContext() } // Set up output context. UIGraphicsBeginImageContextWithOptions(size, false, screenScale) let outputContext = UIGraphicsGetCurrentContext() CGContextScaleCTM(outputContext, 1.0, -1.0) CGContextTranslateCTM(outputContext, 0, -size.height) // Draw base image. CGContextDrawImage(outputContext, imageRect, self.CGImage) // Draw effect image. if hasBlur { CGContextSaveGState(outputContext) if let image = maskImage { CGContextClipToMask(outputContext, imageRect, image.CGImage); } CGContextDrawImage(outputContext, imageRect, effectImage.CGImage) CGContextRestoreGState(outputContext) } // Add in color tint. if let color = tintColor { CGContextSaveGState(outputContext) CGContextSetFillColorWithColor(outputContext, color.CGColor) CGContextFillRect(outputContext, imageRect) CGContextRestoreGState(outputContext) } // Output image is ready. let outputImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return outputImage } }
apache-2.0
a3c5dd3997d6aa3df7e0eab08ca7d812
33.921875
144
0.710626
4.056261
false
false
false
false
Baza207/Alamofire
Source/ResponseSerialization.swift
1
14546
// ResponseSerialization.swift // // Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation // MARK: ResponseSerializer /** The type in which all response serializers must conform to in order to serialize a response. */ public protocol ResponseSerializerType { /// The type of serialized object to be created by this `ResponseSerializerType`. typealias SerializedObject /// The type of error to be created by this `ResponseSerializer` if serialization fails. typealias ErrorObject: ErrorType /** A closure used by response handlers that takes a request, response, data and error and returns a result. */ var serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Result<SerializedObject, ErrorObject> { get } } // MARK: - /** A generic `ResponseSerializerType` used to serialize a request, response, and data into a serialized object. */ public struct ResponseSerializer<Value, Error: ErrorType>: ResponseSerializerType { /// The type of serialized object to be created by this `ResponseSerializer`. public typealias SerializedObject = Value /// The type of error to be created by this `ResponseSerializer` if serialization fails. public typealias ErrorObject = Error /** A closure used by response handlers that takes a request, response, data and error and returns a result. */ public var serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Result<Value, Error> /** Initializes the `ResponseSerializer` instance with the given serialize response closure. - parameter serializeResponse: The closure used to serialize the response. - returns: The new generic response serializer instance. */ public init(serializeResponse: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Result<Value, Error>) { self.serializeResponse = serializeResponse } } // MARK: - Default extension Request { /** Adds a handler to be called once the request has finished. - parameter queue: The queue on which the completion handler is dispatched. - parameter completionHandler: The code to be executed once the request has finished. - returns: The request. */ public func response( queue queue: dispatch_queue_t? = nil, completionHandler: (NSURLRequest?, NSHTTPURLResponse?, NSData?, NSError?) -> Void) -> Self { delegate.queue.addOperationWithBlock { dispatch_async(queue ?? dispatch_get_main_queue()) { completionHandler(self.request, self.response, self.delegate.data, self.delegate.error) } } return self } /** Adds a handler to be called once the request has finished. - parameter queue: The queue on which the completion handler is dispatched. - parameter responseSerializer: The response serializer responsible for serializing the request, response, and data. - parameter completionHandler: The code to be executed once the request has finished. - returns: The request. */ public func response<T: ResponseSerializerType>( queue queue: dispatch_queue_t? = nil, responseSerializer: T, completionHandler: Response<T.SerializedObject, T.ErrorObject> -> Void) -> Self { delegate.queue.addOperationWithBlock { let result = responseSerializer.serializeResponse( self.request, self.response, self.delegate.data, self.delegate.error ) let requestCompletedTime = self.endTime ?? CFAbsoluteTimeGetCurrent() let initialResponseTime = self.delegate.initialResponseTime ?? requestCompletedTime let timeline = Timeline( requestStartTime: self.startTime ?? CFAbsoluteTimeGetCurrent(), initialResponseTime: initialResponseTime, requestCompletedTime: requestCompletedTime, serializationCompletedTime: CFAbsoluteTimeGetCurrent() ) let response = Response<T.SerializedObject, T.ErrorObject>( request: self.request, response: self.response, data: self.delegate.data, result: result, timeline: timeline ) dispatch_async(queue ?? dispatch_get_main_queue()) { completionHandler(response) } } return self } } // MARK: - Data extension Request { /** Creates a response serializer that returns the associated data as-is. - returns: A data response serializer. */ public static func dataResponseSerializer() -> ResponseSerializer<NSData, NSError> { return ResponseSerializer { _, response, data, error in guard error == nil else { return .Failure(error!) } if let response = response where response.statusCode == 204 { return .Success(NSData()) } guard let validData = data else { let failureReason = "Data could not be serialized. Input data was nil." let error = Error.errorWithCode(.DataSerializationFailed, failureReason: failureReason) return .Failure(error) } return .Success(validData) } } /** Adds a handler to be called once the request has finished. - parameter completionHandler: The code to be executed once the request has finished. - returns: The request. */ public func responseData( queue queue: dispatch_queue_t? = nil, completionHandler: Response<NSData, NSError> -> Void) -> Self { return response(queue: queue, responseSerializer: Request.dataResponseSerializer(), completionHandler: completionHandler) } } // MARK: - String extension Request { /** Creates a response serializer that returns a string initialized from the response data with the specified string encoding. - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server response, falling back to the default HTTP default character set, ISO-8859-1. - returns: A string response serializer. */ public static func stringResponseSerializer( encoding encoding: NSStringEncoding? = nil) -> ResponseSerializer<String, NSError> { return ResponseSerializer { _, response, data, error in guard error == nil else { return .Failure(error!) } if let response = response where response.statusCode == 204 { return .Success("") } guard let validData = data else { let failureReason = "String could not be serialized. Input data was nil." let error = Error.errorWithCode(.StringSerializationFailed, failureReason: failureReason) return .Failure(error) } var convertedEncoding = encoding if let encodingName = response?.textEncodingName where convertedEncoding == nil { convertedEncoding = CFStringConvertEncodingToNSStringEncoding( CFStringConvertIANACharSetNameToEncoding(encodingName) ) } let actualEncoding = convertedEncoding ?? NSISOLatin1StringEncoding if let string = String(data: validData, encoding: actualEncoding) { return .Success(string) } else { let failureReason = "String could not be serialized with encoding: \(actualEncoding)" let error = Error.errorWithCode(.StringSerializationFailed, failureReason: failureReason) return .Failure(error) } } } /** Adds a handler to be called once the request has finished. - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server response, falling back to the default HTTP default character set, ISO-8859-1. - parameter completionHandler: A closure to be executed once the request has finished. - returns: The request. */ public func responseString( queue queue: dispatch_queue_t? = nil, encoding: NSStringEncoding? = nil, completionHandler: Response<String, NSError> -> Void) -> Self { return response( queue: queue, responseSerializer: Request.stringResponseSerializer(encoding: encoding), completionHandler: completionHandler ) } } // MARK: - JSON extension Request { /** Creates a response serializer that returns a JSON object constructed from the response data using `NSJSONSerialization` with the specified reading options. - parameter options: The JSON serialization reading options. `.AllowFragments` by default. - returns: A JSON object response serializer. */ public static func JSONResponseSerializer( options options: NSJSONReadingOptions = .AllowFragments) -> ResponseSerializer<AnyObject, NSError> { return ResponseSerializer { _, response, data, error in guard error == nil else { return .Failure(error!) } if let response = response where response.statusCode == 204 { return .Success(NSNull()) } guard let validData = data where validData.length > 0 else { let failureReason = "JSON could not be serialized. Input data was nil or zero length." let error = Error.errorWithCode(.JSONSerializationFailed, failureReason: failureReason) return .Failure(error) } do { let JSON = try NSJSONSerialization.JSONObjectWithData(validData, options: options) return .Success(JSON) } catch { return .Failure(error as NSError) } } } /** Adds a handler to be called once the request has finished. - parameter options: The JSON serialization reading options. `.AllowFragments` by default. - parameter completionHandler: A closure to be executed once the request has finished. - returns: The request. */ public func responseJSON( queue queue: dispatch_queue_t? = nil, options: NSJSONReadingOptions = .AllowFragments, completionHandler: Response<AnyObject, NSError> -> Void) -> Self { return response( queue: queue, responseSerializer: Request.JSONResponseSerializer(options: options), completionHandler: completionHandler ) } } // MARK: - Property List extension Request { /** Creates a response serializer that returns an object constructed from the response data using `NSPropertyListSerialization` with the specified reading options. - parameter options: The property list reading options. `NSPropertyListReadOptions()` by default. - returns: A property list object response serializer. */ public static func propertyListResponseSerializer( options options: NSPropertyListReadOptions = NSPropertyListReadOptions()) -> ResponseSerializer<AnyObject, NSError> { return ResponseSerializer { _, response, data, error in guard error == nil else { return .Failure(error!) } if let response = response where response.statusCode == 204 { return .Success(NSNull()) } guard let validData = data where validData.length > 0 else { let failureReason = "Property list could not be serialized. Input data was nil or zero length." let error = Error.errorWithCode(.PropertyListSerializationFailed, failureReason: failureReason) return .Failure(error) } do { let plist = try NSPropertyListSerialization.propertyListWithData(validData, options: options, format: nil) return .Success(plist) } catch { return .Failure(error as NSError) } } } /** Adds a handler to be called once the request has finished. - parameter options: The property list reading options. `0` by default. - parameter completionHandler: A closure to be executed once the request has finished. The closure takes 3 arguments: the URL request, the URL response, the server data and the result produced while creating the property list. - returns: The request. */ public func responsePropertyList( queue queue: dispatch_queue_t? = nil, options: NSPropertyListReadOptions = NSPropertyListReadOptions(), completionHandler: Response<AnyObject, NSError> -> Void) -> Self { return response( queue: queue, responseSerializer: Request.propertyListResponseSerializer(options: options), completionHandler: completionHandler ) } }
mit
18d3b0babdf4e748e3a4cd0252006ac2
37.680851
130
0.642395
5.630662
false
false
false
false