repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
philipgreat/b2b-swift-app
refs/heads/master
B2BSimpleApp/B2BSimpleApp/Footer.swift
mit
1
//Domain B2B/Footer/ import Foundation import ObjectMapper //Use this to generate Object import SwiftyJSON //Use this to verify the JSON Object struct Footer{ var id : String? var page : HomePage? var image : String? var action : String? var version : Int? init(){ //lazy load for all the properties //This is good for UI applications as it might saves RAM which is very expensive in mobile devices } static var CLASS_VERSION = "1" //This value is for serializer like message pack to identify the versions match between //local and remote object. } extension Footer: Mappable{ //Confirming to the protocol Mappable of ObjectMapper //Reference on https://github.com/Hearst-DD/ObjectMapper/ init?(_ map: Map){ } mutating func mapping(map: Map) { //Map each field to json fields id <- map["id"] page <- map["page"] image <- map["image"] action <- map["action"] version <- map["version"] } } extension Footer:CustomStringConvertible{ //Confirming to the protocol CustomStringConvertible of Foundation var description: String{ //Need to find out a way to improve this method performance as this method might called to //debug or log, using + is faster than \(var). var result = "footer{"; if id != nil { result += "\tid='\(id!)'" } if page != nil { result += "\tpage='\(page!)'" } if image != nil { result += "\timage='\(image!)'" } if action != nil { result += "\taction='\(action!)'" } if version != nil { result += "\tversion='\(version!)'" } result += "}" return result } }
0a979c70cd29a621ac695a74370bf3f0
20.843373
100
0.547468
false
false
false
false
wpuricz/vapor-database-sample
refs/heads/master
Sources/App/Controllers/ApplicationController.swift
mit
1
import Vapor import HTTP extension Vapor.KeyAccessible where Key == HeaderKey, Value == String { var contentType: String? { get { return self["Content-Type"] } set { self["Content-Type"] = newValue } } var authorization: String? { get { return self["Authorization"] } set { self["Authorization"] = newValue } } } public enum ContentType: String { case html = "text/html" case json = "application/json" } open class ApplicationController { private var resourcefulName: String { let className = String(describing: type(of: self)) return className.replacingOccurrences(of: "Controller", with: "").lowercased() } public func respond(to request: Request, with response: [ContentType : ResponseRepresentable]) -> ResponseRepresentable { let contentTypeValue = request.headers.contentType ?? ContentType.html.rawValue let contentType = ContentType(rawValue: contentTypeValue) ?? ContentType.html return response[contentType] ?? Response(status: .notFound) } public func render(_ path: String, _ context: NodeRepresentable? = nil) throws -> View { return try drop.view.make("\(resourcefulName)/\(path)", context ?? Node.null) } public func render(_ path: String, _ context: [String : NodeRepresentable]?) throws -> View { return try render(path, context?.makeNode()) } } extension Resource { public convenience init( index: Multiple? = nil, show: Item? = nil, create: Multiple? = nil, replace: Item? = nil, update: Item? = nil, destroy: Item? = nil, clear: Multiple? = nil, aboutItem: Item? = nil, aboutMultiple: Multiple? = nil) { self.init( index: index, store: create, show: show, replace: replace, modify: update, destroy: destroy, clear: clear, aboutItem: aboutItem, aboutMultiple: aboutMultiple ) } }
40750eb9a8df547a5b3d7037779c0c84
27.194805
125
0.576693
false
false
false
false
CNKCQ/oschina
refs/heads/master
OSCHINA/Models/Discover/DiscoverModel.swift
mit
1
// // DiscoverModel.swift // OSCHINA // // Created by KingCQ on 2017/1/15. // Copyright © 2017年 KingCQ. All rights reserved. // import Foundation import ObjectMapper class ArticleEntity: Mappable { var who: String? var id: String? var desc: String? var publishedAt: Date? var used: Int? var createdAt: Date? var url: String? var type: String? // MARK: Mappable func mapping(map: Map) { who <- map["who"] id <- map["_id"] desc <- map["desc"] publishedAt <- (map["publishedAt"], CustomDateFormatTransform(formatString: DateUtil.dateFormatter)) used <- map["used"] createdAt <- (map["createdAt"], CustomDateFormatTransform(formatString: DateUtil.dateFormatter)) url <- map["url"] type <- map["type"] } required init?(map _: Map) { } } public class DateUtil { static let dateFormatter = "yyyy-MM-dd'T'HH:mm:ss.SSSZ" public static func stringToNSDate(dateString: String, formatter: String = dateFormatter) -> Date { let dateFormatter = DateFormatter() dateFormatter.dateFormat = formatter return dateFormatter.date(from: dateString)! } public static func nsDateToString(date: Date, formatter: String = "yyyy-MM-dd HH:mm:ss") -> String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = formatter return dateFormatter.string(from: date) } public static func areDatesSameDay(dateOne _: Date, dateTwo _: Date) -> Bool { return true } }
9ab88da662c4ac7c545cefb9763a2f13
25.827586
108
0.634961
false
false
false
false
mpatelCAS/MDAlamofireCheck
refs/heads/master
Pods/Alamofire/Source/Upload.swift
mit
2
// Upload.swift // // Copyright (c) 2014–2015 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 extension Manager { private enum Uploadable { case Data(NSURLRequest, NSData) case File(NSURLRequest, NSURL) case Stream(NSURLRequest, NSInputStream) } private func upload(uploadable: Uploadable) -> Request { var uploadTask: NSURLSessionUploadTask! var HTTPBodyStream: NSInputStream? switch uploadable { case .Data(let request, let data): dispatch_sync(queue) { uploadTask = self.session.uploadTaskWithRequest(request, fromData: data) } case .File(let request, let fileURL): dispatch_sync(queue) { uploadTask = self.session.uploadTaskWithRequest(request, fromFile: fileURL) } case .Stream(let request, let stream): dispatch_sync(queue) { uploadTask = self.session.uploadTaskWithStreamedRequest(request) } HTTPBodyStream = stream } let request = Request(session: session, task: uploadTask) if HTTPBodyStream != nil { request.delegate.taskNeedNewBodyStream = { _, _ in return HTTPBodyStream } } delegate[request.delegate.task] = request.delegate if startRequestsImmediately { request.resume() } return request } // MARK: File /** Creates a request for uploading a file to the specified URL request. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - parameter URLRequest: The URL request - parameter file: The file to upload - returns: The created upload request. */ public func upload(URLRequest: URLRequestConvertible, file: NSURL) -> Request { return upload(.File(URLRequest.URLRequest, file)) } /** Creates a request for uploading a file to the specified URL request. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - parameter method: The HTTP method. - parameter URLString: The URL string. - parameter headers: The HTTP headers. `nil` by default. - parameter file: The file to upload - returns: The created upload request. */ public func upload( method: Method, _ URLString: URLStringConvertible, headers: [String: String]? = nil, file: NSURL) -> Request { let mutableURLRequest = URLRequest(method, URLString, headers: headers) return upload(mutableURLRequest, file: file) } // MARK: Data /** Creates a request for uploading data to the specified URL request. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - parameter URLRequest: The URL request. - parameter data: The data to upload. - returns: The created upload request. */ public func upload(URLRequest: URLRequestConvertible, data: NSData) -> Request { return upload(.Data(URLRequest.URLRequest, data)) } /** Creates a request for uploading data to the specified URL request. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - parameter method: The HTTP method. - parameter URLString: The URL string. - parameter headers: The HTTP headers. `nil` by default. - parameter data: The data to upload - returns: The created upload request. */ public func upload( method: Method, _ URLString: URLStringConvertible, headers: [String: String]? = nil, data: NSData) -> Request { let mutableURLRequest = URLRequest(method, URLString, headers: headers) return upload(mutableURLRequest, data: data) } // MARK: Stream /** Creates a request for uploading a stream to the specified URL request. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - parameter URLRequest: The URL request. - parameter stream: The stream to upload. - returns: The created upload request. */ public func upload(URLRequest: URLRequestConvertible, stream: NSInputStream) -> Request { return upload(.Stream(URLRequest.URLRequest, stream)) } /** Creates a request for uploading a stream to the specified URL request. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - parameter method: The HTTP method. - parameter URLString: The URL string. - parameter headers: The HTTP headers. `nil` by default. - parameter stream: The stream to upload. - returns: The created upload request. */ public func upload( method: Method, _ URLString: URLStringConvertible, headers: [String: String]? = nil, stream: NSInputStream) -> Request { let mutableURLRequest = URLRequest(method, URLString, headers: headers) return upload(mutableURLRequest, stream: stream) } // MARK: MultipartFormData /// Default memory threshold used when encoding `MultipartFormData`. public static let MultipartFormDataEncodingMemoryThreshold: UInt64 = 10 * 1024 * 1024 /** Defines whether the `MultipartFormData` encoding was successful and contains result of the encoding as associated values. - Success: Represents a successful `MultipartFormData` encoding and contains the new `Request` along with streaming information. - Failure: Used to represent a failure in the `MultipartFormData` encoding and also contains the encoding error. */ public enum MultipartFormDataEncodingResult { case Success(request: Request, streamingFromDisk: Bool, streamFileURL: NSURL?) case Failure(NSError) } /** Encodes the `MultipartFormData` and creates a request to upload the result to the specified URL request. It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative payload is small, encoding the data in-memory and directly uploading to a server is the by far the most efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be used for larger payloads such as video content. The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding technique was used. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - parameter method: The HTTP method. - parameter URLString: The URL string. - parameter headers: The HTTP headers. `nil` by default. - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. `MultipartFormDataEncodingMemoryThreshold` by default. - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. */ public func upload( method: Method, _ URLString: URLStringConvertible, headers: [String: String]? = nil, multipartFormData: MultipartFormData -> Void, encodingMemoryThreshold: UInt64 = Manager.MultipartFormDataEncodingMemoryThreshold, encodingCompletion: (MultipartFormDataEncodingResult -> Void)?) { let mutableURLRequest = URLRequest(method, URLString, headers: headers) return upload( mutableURLRequest, multipartFormData: multipartFormData, encodingMemoryThreshold: encodingMemoryThreshold, encodingCompletion: encodingCompletion ) } /** Encodes the `MultipartFormData` and creates a request to upload the result to the specified URL request. It is important to understand the memory implications of uploading `MultipartFormData`. If the cummulative payload is small, encoding the data in-memory and directly uploading to a server is the by far the most efficient approach. However, if the payload is too large, encoding the data in-memory could cause your app to be terminated. Larger payloads must first be written to disk using input and output streams to keep the memory footprint low, then the data can be uploaded as a stream from the resulting file. Streaming from disk MUST be used for larger payloads such as video content. The `encodingMemoryThreshold` parameter allows Alamofire to automatically determine whether to encode in-memory or stream from disk. If the content length of the `MultipartFormData` is below the `encodingMemoryThreshold`, encoding takes place in-memory. If the content length exceeds the threshold, the data is streamed to disk during the encoding process. Then the result is uploaded as data or as a stream depending on which encoding technique was used. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. - parameter URLRequest: The URL request. - parameter multipartFormData: The closure used to append body parts to the `MultipartFormData`. - parameter encodingMemoryThreshold: The encoding memory threshold in bytes. `MultipartFormDataEncodingMemoryThreshold` by default. - parameter encodingCompletion: The closure called when the `MultipartFormData` encoding is complete. */ public func upload( URLRequest: URLRequestConvertible, multipartFormData: MultipartFormData -> Void, encodingMemoryThreshold: UInt64 = Manager.MultipartFormDataEncodingMemoryThreshold, encodingCompletion: (MultipartFormDataEncodingResult -> Void)?) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { let formData = MultipartFormData() multipartFormData(formData) let URLRequestWithContentType = URLRequest.URLRequest URLRequestWithContentType.setValue(formData.contentType, forHTTPHeaderField: "Content-Type") if formData.contentLength < encodingMemoryThreshold { do { let data = try formData.encode() let encodingResult = MultipartFormDataEncodingResult.Success( request: self.upload(URLRequestWithContentType, data: data), streamingFromDisk: false, streamFileURL: nil ) dispatch_async(dispatch_get_main_queue()) { encodingCompletion?(encodingResult) } } catch { dispatch_async(dispatch_get_main_queue()) { encodingCompletion?(.Failure(error as NSError)) } } } else { let fileManager = NSFileManager.defaultManager() let tempDirectoryURL = NSURL(fileURLWithPath: NSTemporaryDirectory()) let directoryURL = tempDirectoryURL.URLByAppendingPathComponent("com.alamofire.manager/multipart.form.data") let fileName = NSUUID().UUIDString let fileURL = directoryURL.URLByAppendingPathComponent(fileName) do { try fileManager.createDirectoryAtURL(directoryURL, withIntermediateDirectories: true, attributes: nil) try formData.writeEncodedDataToDisk(fileURL) dispatch_async(dispatch_get_main_queue()) { let encodingResult = MultipartFormDataEncodingResult.Success( request: self.upload(URLRequestWithContentType, file: fileURL), streamingFromDisk: true, streamFileURL: fileURL ) encodingCompletion?(encodingResult) } } catch { dispatch_async(dispatch_get_main_queue()) { encodingCompletion?(.Failure(error as NSError)) } } } } } } // MARK: - extension Request { // MARK: - UploadTaskDelegate class UploadTaskDelegate: DataTaskDelegate { var uploadTask: NSURLSessionUploadTask? { return task as? NSURLSessionUploadTask } var uploadProgress: ((Int64, Int64, Int64) -> Void)! // MARK: - NSURLSessionTaskDelegate // MARK: Override Closures var taskDidSendBodyData: ((NSURLSession, NSURLSessionTask, Int64, Int64, Int64) -> Void)? // MARK: Delegate Methods func URLSession( session: NSURLSession, task: NSURLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) { if let taskDidSendBodyData = taskDidSendBodyData { taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) } else { progress.totalUnitCount = totalBytesExpectedToSend progress.completedUnitCount = totalBytesSent uploadProgress?(bytesSent, totalBytesSent, totalBytesExpectedToSend) } } } }
58d23edef43a0c9d4ccbab9fa50b0486
41.562162
124
0.649225
false
false
false
false
mleiv/MEGameTracker
refs/heads/master
MEGameTracker/Models/Alert.swift
mit
1
// // Alert.swift // MEGameTracker // // Created by Emily Ivie on 4/14/16. // Copyright © 2016 Emily Ivie. All rights reserved. // import UIKit /// Helper for showing alerts. public struct Alert { // MARK: Types public typealias ActionButtonType = (title: String, style: UIAlertAction.Style, handler: ((UIAlertAction) -> Void)) // MARK: Properties public var title: String public var description: String public var actions: [ActionButtonType] = [] // MARK: Change Listeners And Change Status Flags public static var onSignal = Signal<(Alert)>() // MARK: Initialization public init(title: String?, description: String) { self.title = title ?? "" self.description = description } } // MARK: Basic Actions extension Alert { /// Pops up an alert in the specified controller. public func show(fromController controller: UIViewController, sender: UIView? = nil) { let alert = UIAlertController(title: title, message: description, preferredStyle: .alert) if actions.isEmpty { alert.addAction(UIAlertAction(title: "Okay", style: .default, handler: { _ in })) } else { for action in actions { alert.addAction(UIAlertAction(title: action.title, style: action.style, handler: action.handler)) } } alert.popoverPresentationController?.sourceView = sender ?? controller.view alert.modalPresentationStyle = .popover // Alert default button defaults to window tintColor (red), // Which is too similar to destructive button (red), // And I can't change it in Styles using appearance(), // So I have to do it here, which pisses me off. alert.view.tintColor = UIColor.systemBlue // Styles.colors.altTint if let bounds = sender?.bounds { alert.popoverPresentationController?.sourceRect = bounds } controller.present(alert, animated: true, completion: nil) } }
86d28705497d73ce6e80672899d8f164
27.968254
116
0.716164
false
false
false
false
jkolb/midnightbacon
refs/heads/master
MidnightBacon/Modules/Common/Services/Logger.swift
mit
1
// Copyright (c) 2016 Justin Kolb - http://franticapparatus.net // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation public protocol LogFormatter { func format(record: LogRecord) -> String } public protocol LogHandler { func publish(record: LogRecord) } public class LogRecord { public let timestamp: NSDate public let level: LogLevel public let processName: String public let threadID: UInt64 public let fileName: String public let lineNumber: Int public let message: String public init(timestamp: NSDate, level: LogLevel, processName: String, threadID: UInt64, fileName: String, lineNumber: Int, message: String) { self.timestamp = timestamp self.level = level self.processName = processName self.threadID = threadID self.fileName = fileName self.lineNumber = lineNumber self.message = message } } public enum LogLevel : UInt8, Comparable { case None case Error case Warn case Info case Debug public var formatted: String { switch self { case .Error: fallthrough case .Debug: return "\(self)".uppercaseString default: return "\(self)".uppercaseString + " " } } } public class LogStringFormatter : LogFormatter { private let dateFormatter: NSDateFormatter public init() { self.dateFormatter = NSDateFormatter() self.dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS" } public init(dateFormatter: NSDateFormatter) { self.dateFormatter = dateFormatter } public func format(record: LogRecord) -> String { return "\(dateFormatter.stringFromDate(record.timestamp)) \(record.level.formatted) \(record.processName)[\(record.threadID)] \(record.fileName):\(record.lineNumber) \(record.message)" } } public class LogConsoleHandler : LogHandler { private let formatter: LogFormatter public init(formatter: LogFormatter = LogStringFormatter()) { self.formatter = formatter } public func publish(record: LogRecord) { print(formatter.format(record)) } } public class LogCompositeHandler : LogHandler { private let handlers: [LogHandler] public init(handlers: [LogHandler]) { self.handlers = handlers } public func publish(record: LogRecord) { for handler in handlers { handler.publish(record) } } } public class Logger { public let level: LogLevel private let handler: LogHandler private let processName = NSProcessInfo.processInfo().processName private static let queue = dispatch_queue_create("net.franticapparatus.Logger", DISPATCH_QUEUE_SERIAL) public init(level: LogLevel, handler: LogHandler = LogConsoleHandler()) { self.level = level self.handler = handler } private var threadID: UInt64 { var ID: __uint64_t = 0 pthread_threadid_np(nil, &ID) return ID } private func log(@autoclosure message: () -> String, level: LogLevel, fileName: String = __FILE__, lineNumber: Int = __LINE__) { if level > self.level { return } let record = LogRecord( timestamp: NSDate(), level: level, processName: processName, threadID: self.threadID, fileName: NSString(string: fileName).lastPathComponent, lineNumber: lineNumber, message: message() ) let handler = self.handler dispatch_async(Logger.queue) { handler.publish(record) } } public func error(@autoclosure message: () -> String, fileName: String = __FILE__, lineNumber: Int = __LINE__) { log(message, level: .Error, fileName: fileName, lineNumber: lineNumber) } public func error(fileName: String = __FILE__, lineNumber: Int = __LINE__, message: () -> String) { log(message(), level: .Error, fileName: fileName, lineNumber: lineNumber) } public func warn(@autoclosure message: () -> String, fileName: String = __FILE__, lineNumber: Int = __LINE__) { log(message, level: .Warn, fileName: fileName, lineNumber: lineNumber) } public func warn(fileName: String = __FILE__, lineNumber: Int = __LINE__, message: () -> String) { log(message(), level: .Warn, fileName: fileName, lineNumber: lineNumber) } public func info(@autoclosure message: () -> String, fileName: String = __FILE__, lineNumber: Int = __LINE__) { log(message, level: .Info, fileName: fileName, lineNumber: lineNumber) } public func info(fileName: String = __FILE__, lineNumber: Int = __LINE__, message: () -> String) { log(message(), level: .Info, fileName: fileName, lineNumber: lineNumber) } public func debug(@autoclosure message: () -> String, fileName: String = __FILE__, lineNumber: Int = __LINE__) { log(message, level: .Debug, fileName: fileName, lineNumber: lineNumber) } public func debug(fileName: String = __FILE__, lineNumber: Int = __LINE__, message: () -> String) { log(message(), level: .Debug, fileName: fileName, lineNumber: lineNumber) } } public func < (lhs: LogLevel, rhs: LogLevel) -> Bool { return lhs.rawValue < rhs.rawValue }
aa36e343a9cd484543312cf886a213b7
33.805405
192
0.648703
false
false
false
false
benwwchen/sysujwxt-ios
refs/heads/master
SYSUJwxt/LocalNotification.swift
bsd-3-clause
1
// // LocalNotification.swift // SYSUJwxt // // Created by benwwchen on 2017/8/25. // // reference: mourodrigo // https://stackoverflow.com/questions/42688760/local-and-push-notifications-in-ios-9-and-10-using-swift3 // import UIKit import UserNotifications class LocalNotification: NSObject, UNUserNotificationCenterDelegate { class func registerForLocalNotification(on application:UIApplication, currentViewController: UIViewController) { if (UIApplication.instancesRespond(to: #selector(UIApplication.registerUserNotificationSettings(_:)))) { if #available(iOS 10.0, *) { UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.sound,.badge]) { (granted, error) in if granted { print("用户允许") } else { // Alert fail and navigate user to settings currentViewController.alert(title: AlertTitles.PermissionDenied, message: AlertTitles.NotificationPermissionRequest, titleDefault: AlertTitles.Settings, titleCancel: AlertTitles.Cancel, handler: { (action) in DispatchQueue.main.async { switch action.style { case .default: // go to settings UIApplication.shared.open(URL(string: "App-prefs:root=com.bencww.SYSUJwxt")!, completionHandler: { (success) in currentViewController.dismiss(animated: true, completion: nil) }) break case .cancel: currentViewController.dismiss(animated: true, completion: nil) break default: break } } }) } } } else { let notificationCategory:UIMutableUserNotificationCategory = UIMutableUserNotificationCategory() notificationCategory.identifier = "NOTIFICATION_CATEGORY" //registerting for the notification. application.registerUserNotificationSettings(UIUserNotificationSettings(types:[.sound, .alert, .badge], categories: nil)) // check if the notification setting is on let notificationType = UIApplication.shared.currentUserNotificationSettings?.types if notificationType?.rawValue == 0 { currentViewController.alert(title: AlertTitles.PermissionDenied, message: AlertTitles.NotificationPermissionRequest, titleDefault: AlertTitles.Settings, titleCancel: AlertTitles.Cancel, handler: { (action) in DispatchQueue.main.async { switch action.style { case .default: // go to settings UIApplication.shared.openURL(URL(string: UIApplicationOpenSettingsURLString)!) break case .cancel: currentViewController.dismiss(animated: true, completion: nil) break default: break } } }) } } } } class func dispatchlocalNotification(with title: String, body: String, userInfo: [AnyHashable: Any]? = nil, at timeInterval: TimeInterval) { let date = Date(timeIntervalSinceNow: timeInterval) if #available(iOS 10.0, *) { let center = UNUserNotificationCenter.current() let content = UNMutableNotificationContent() content.title = title content.body = body content.categoryIdentifier = "update" if let info = userInfo { content.userInfo = info } content.sound = UNNotificationSound.default() let comp = Calendar.current.dateComponents([.hour, .minute, .second], from: date) let trigger = UNCalendarNotificationTrigger(dateMatching: comp, repeats: false) let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger) center.add(request) } else { let notification = UILocalNotification() notification.fireDate = date notification.alertTitle = title notification.alertBody = body if let info = userInfo { notification.userInfo = info } notification.soundName = UILocalNotificationDefaultSoundName UIApplication.shared.scheduleLocalNotification(notification) } print("WILL DISPATCH LOCAL NOTIFICATION AT ", date) } }
a01a0329b205b8993e29f9cde94ba56f
42.777778
232
0.505983
false
false
false
false
luckymore0520/leetcode
refs/heads/master
Rotate Image.playground/Contents.swift
mit
1
//: Playground - noun: a place where people can play import UIKit //You are given an n x n 2D matrix representing an image. // //Rotate the image by 90 degrees (clockwise). // //Follow up: //Could you do this in-place? class Solution { func rotate(_ matrix: inout [[Int]]) { let n = matrix.count if (n <= 1) { return } for k in 0...n/2-1 { for i in k...n-2-k { (matrix[k][i],matrix[i][n-1-k],matrix[n-1-k][n-i-1],matrix[n-i-1][k]) = (matrix[n-i-1][k],matrix[k][i],matrix[i][n-1-k],matrix[n-1-k][n-i-1]) } } } } //1 2 3 4 //5 6 7 8 //9 10 11 12 //13 14 15 16 let solution = Solution() var matric = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]] solution.rotate(&matric) print(matric)
c5d3737114bab21122ad83c6fc5559b7
20.621622
157
0.52816
false
false
false
false
devpunk/velvet_room
refs/heads/master
Source/GenericExtensions/ExtensionUIFont.swift
mit
2
import UIKit extension UIFont { static let kFontLight:String = "HelveticaNeue-Thin" static let kFontRegular:String = "HelveticaNeue" static let kFontMedium:String = "HelveticaNeue-Medium" static let kFontBold:String = "HelveticaNeue-Bold" class func light(size:CGFloat) -> UIFont { let font:UIFont = UIFont(name:kFontLight, size:size)! return font } class func regular(size:CGFloat) -> UIFont { let font:UIFont = UIFont(name:kFontRegular, size:size)! return font } class func medium(size:CGFloat) -> UIFont { let font:UIFont = UIFont(name:kFontMedium, size:size)! return font } class func bold(size:CGFloat) -> UIFont { let font:UIFont = UIFont(name:kFontBold, size:size)! return font } }
3e97395cb02325e8d9a8b150537afce2
22.621622
63
0.601831
false
false
false
false
hollance/swift-algorithm-club
refs/heads/master
Dijkstra Algorithm/VisualizedDijkstra.playground/Sources/Graph.swift
mit
4
import Foundation import UIKit public enum GraphState { case initial case autoVisualization case interactiveVisualization case parsing case completed } public class Graph { private var verticesCount: UInt private var _vertices: Set<Vertex> = Set() public weak var delegate: GraphDelegate? public var nextVertices: [Vertex] = [] public var state: GraphState = .initial public var pauseVisualization = false public var stopVisualization = false public var startVertex: Vertex? public var interactiveNeighborCheckAnimationDuration: Double = 1.8 { didSet { _interactiveOneSleepDuration = UInt32(interactiveNeighborCheckAnimationDuration * 1000000.0 / 3.0) } } private var _interactiveOneSleepDuration: UInt32 = 600000 public var visualizationNeighborCheckAnimationDuration: Double = 2.25 { didSet { _visualizationOneSleepDuration = UInt32(visualizationNeighborCheckAnimationDuration * 1000000.0 / 3.0) } } private var _visualizationOneSleepDuration: UInt32 = 750000 public var vertices: Set<Vertex> { return _vertices } public init(verticesCount: UInt) { self.verticesCount = verticesCount } public func removeGraph() { _vertices.removeAll() startVertex = nil } public func createNewGraph() { guard _vertices.isEmpty, startVertex == nil else { assertionFailure("Clear graph before creating new one") return } createNotConnectedVertices() setupConnections() let offset = Int(arc4random_uniform(UInt32(_vertices.count))) let index = _vertices.index(_vertices.startIndex, offsetBy: offset) startVertex = _vertices[index] setVertexLevels() } private func clearCache() { _vertices.forEach { $0.clearCache() } } public func reset() { for vertex in _vertices { vertex.clearCache() } } private func createNotConnectedVertices() { for i in 0..<verticesCount { let vertex = Vertex(identifier: "\(i)") _vertices.insert(vertex) } } private func setupConnections() { for vertex in _vertices { let randomEdgesCount = arc4random_uniform(4) + 1 for _ in 0..<randomEdgesCount { let randomWeight = Double(arc4random_uniform(10)) let neighbor = randomVertex(except: vertex) let edge1 = Edge(vertex: neighbor, weight: randomWeight) if vertex.edges.contains(where: { $0.neighbor == neighbor }) { continue } let edge2 = Edge(vertex: vertex, weight: randomWeight) vertex.edges.append(edge1) neighbor.edges.append(edge2) } } } private func randomVertex(except vertex: Vertex) -> Vertex { var newSet = _vertices newSet.remove(vertex) let offset = Int(arc4random_uniform(UInt32(newSet.count))) let index = newSet.index(newSet.startIndex, offsetBy: offset) return newSet[index] } private func setVertexLevels() { _vertices.forEach { $0.clearLevelInfo() } guard let startVertex = startVertex else { assertionFailure() return } var queue: [Vertex] = [startVertex] startVertex.levelChecked = true //BFS while !queue.isEmpty { let currentVertex = queue.first! for edge in currentVertex.edges { let neighbor = edge.neighbor if !neighbor.levelChecked { neighbor.levelChecked = true neighbor.level = currentVertex.level + 1 queue.append(neighbor) } } queue.removeFirst() } } public func findShortestPathsWithVisualization(completion: () -> Void) { guard let startVertex = self.startVertex else { assertionFailure("start vertex is nil") return } clearCache() startVertex.pathLengthFromStart = 0 startVertex.pathVerticesFromStart.append(startVertex) var currentVertex: Vertex? = startVertex var totalVertices = _vertices breakableLoop: while let vertex = currentVertex { totalVertices.remove(vertex) while pauseVisualization == true { if stopVisualization == true { break breakableLoop } } if stopVisualization == true { break breakableLoop } DispatchQueue.main.async { vertex.setVisitedColor() } usleep(750000) vertex.visited = true let filteredEdges = vertex.edges.filter { !$0.neighbor.visited } for edge in filteredEdges { let neighbor = edge.neighbor let weight = edge.weight let edgeRepresentation = edge.edgeRepresentation while pauseVisualization == true { if stopVisualization == true { break breakableLoop } } if stopVisualization == true { break breakableLoop } DispatchQueue.main.async { edgeRepresentation?.setCheckingColor() neighbor.setCheckingPathColor() self.delegate?.willCompareVertices(startVertexPathLength: vertex.pathLengthFromStart, edgePathLength: weight, endVertexPathLength: neighbor.pathLengthFromStart) } usleep(_visualizationOneSleepDuration) let theoreticNewWeight = vertex.pathLengthFromStart + weight if theoreticNewWeight < neighbor.pathLengthFromStart { while pauseVisualization == true { if stopVisualization == true { break breakableLoop } } if stopVisualization == true { break breakableLoop } neighbor.pathLengthFromStart = theoreticNewWeight neighbor.pathVerticesFromStart = vertex.pathVerticesFromStart neighbor.pathVerticesFromStart.append(neighbor) } usleep(_visualizationOneSleepDuration) DispatchQueue.main.async { self.delegate?.didFinishCompare() edge.edgeRepresentation?.setDefaultColor() edge.neighbor.setDefaultColor() } usleep(_visualizationOneSleepDuration) } if totalVertices.isEmpty { currentVertex = nil break } currentVertex = totalVertices.min { $0.pathLengthFromStart < $1.pathLengthFromStart } } if stopVisualization == true { DispatchQueue.main.async { self.delegate?.didStop() } } else { completion() } } public func parseNeighborsFor(vertex: Vertex, completion: @escaping () -> ()) { DispatchQueue.main.async { vertex.setVisitedColor() } DispatchQueue.global(qos: .background).async { vertex.visited = true let nonVisitedVertices = self._vertices.filter { $0.visited == false } if nonVisitedVertices.isEmpty { self.state = .completed DispatchQueue.main.async { self.delegate?.didCompleteGraphParsing() } return } let filteredEdges = vertex.edges.filter { !$0.neighbor.visited } breakableLoop: for edge in filteredEdges { while self.pauseVisualization == true { if self.stopVisualization == true { break breakableLoop } } if self.stopVisualization == true { break breakableLoop } let weight = edge.weight let neighbor = edge.neighbor DispatchQueue.main.async { edge.neighbor.setCheckingPathColor() edge.edgeRepresentation?.setCheckingColor() self.delegate?.willCompareVertices(startVertexPathLength: vertex.pathLengthFromStart, edgePathLength: weight, endVertexPathLength: neighbor.pathLengthFromStart) } usleep(self._interactiveOneSleepDuration) let theoreticNewWeight = vertex.pathLengthFromStart + weight if theoreticNewWeight < neighbor.pathLengthFromStart { while self.pauseVisualization == true { if self.stopVisualization == true { break breakableLoop } } if self.stopVisualization == true { break breakableLoop } neighbor.pathLengthFromStart = theoreticNewWeight neighbor.pathVerticesFromStart = vertex.pathVerticesFromStart neighbor.pathVerticesFromStart.append(neighbor) } usleep(self._interactiveOneSleepDuration) while self.pauseVisualization == true { if self.stopVisualization == true { break breakableLoop } } if self.stopVisualization == true { break breakableLoop } DispatchQueue.main.async { self.delegate?.didFinishCompare() edge.neighbor.setDefaultColor() edge.edgeRepresentation?.setDefaultColor() } usleep(self._interactiveOneSleepDuration) } if self.stopVisualization == true { DispatchQueue.main.async { self.delegate?.didStop() } } else { let nextVertexPathLength = nonVisitedVertices.sorted { $0.pathLengthFromStart < $1.pathLengthFromStart }.first!.pathLengthFromStart self.nextVertices = nonVisitedVertices.filter { $0.pathLengthFromStart == nextVertexPathLength } completion() } } } public func didTapVertex(vertex: Vertex) { if nextVertices.contains(vertex) { delegate?.willStartVertexNeighborsChecking() state = .parsing parseNeighborsFor(vertex: vertex) { self.state = .interactiveVisualization self.delegate?.didFinishVertexNeighborsChecking() } } else { self.delegate?.didTapWrongVertex() } } }
22236069ff52f0ee613740fdf2bec5b2
35.877419
147
0.540238
false
false
false
false
nalck/Barliman
refs/heads/master
cocoa/Barliman/AppDelegate.swift
mit
1
// // AppDelegate.swift // Barliman // // Created by William Byrd on 5/14/16. // Copyright © 2016 William E. Byrd. // Released under MIT License (see LICENSE file) import Cocoa @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { var semanticsWindowController: SemanticsWindowController? var editorWindowController: EditorWindowController? func applicationDidFinishLaunching(_ aNotification: Notification) { // Create window controllers with XIB files of the same name let semanticsWindowController = SemanticsWindowController() let editorWindowController = EditorWindowController() semanticsWindowController.editorWindowController = editorWindowController editorWindowController.semanticsWindowController = semanticsWindowController // Put the windows of the controllers on screen semanticsWindowController.showWindow(self) editorWindowController.showWindow(self) // Set the property to point to the window controllers self.semanticsWindowController = semanticsWindowController self.editorWindowController = editorWindowController } func applicationWillTerminate(_ aNotification: Notification) { // Insert code here to tear down your application editorWindowController!.cleanup() semanticsWindowController!.cleanup() } }
9a75fe294e8da9c9a332b1311e604f97
33.634146
84
0.734507
false
false
false
false
futurechallenger/MVVM
refs/heads/master
MVVMTests/ViewModelTest.swift
mit
1
// // ViewModelTest.swift // MVVM // // Created by Bruce Lee on 9/12/14. // Copyright (c) 2014 Dynamic Cell. All rights reserved. // import UIKit import XCTest class ViewModelTest: XCTestCase { var person: Person! override func setUp() { super.setUp() var salutation = "Dr." var firstName = "first" var lastName = "last" var birthDate = NSDate(timeIntervalSince1970: 0) self.person = Person(salutation: salutation, firstName: firstName, lastName: lastName, birthDate: birthDate) } func testUserSalutation(){ var viewModel = PersonViewModel(person: self.person) XCTAssert(viewModel.nameText! == "Dr. first last" , "use salutation available \(viewModel.nameText!)") } func testNoSalutation(){ var localPerson = Person(salutation: nil, firstName: "first", lastName: "last", birthDate: NSDate(timeIntervalSince1970: 0)) var viewModel = PersonViewModel(person: localPerson) XCTAssert(viewModel.nameText! == "first last", "should not use salutation \(viewModel.nameText!)") } func testBirthDateFormat(){ var viewModel = PersonViewModel(person: self.person) XCTAssert(viewModel.birthDateText! == "Thursday January 1, 1970", "date \(viewModel.birthDateText!)") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } }
5727f8df53822d95d0af194693ad7ee2
31.730769
132
0.649824
false
true
false
false
Barry-Wang/iOS-Animation-Guide-Swift
refs/heads/master
Animation-Guide2-GooeySlideMenu/Animation-Guide2-GooeySlideMenu/ViewController.swift
apache-2.0
1
// // ViewController.swift // Animation-Guide2-GooeySlideMenu // // Created by barryclass on 15/11/19. // Copyright © 2015年 barry. All rights reserved. // import UIKit class ViewController: UIViewController { var menu:YMGooeySlideMenu? override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.yellowColor() // Do any additional setup after loading the view, typically from a nib. let button = UIButton(type: UIButtonType.Custom) button.frame = CGRectMake(300, 100, 30, 30) button.backgroundColor = UIColor.greenColor() button.setTitle("123", forState: UIControlState.Normal) button.addTarget(self, action: "triiger", forControlEvents: UIControlEvents.TouchUpInside) self.view.addSubview(button) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) } func triiger() { if self.menu == nil { self.menu = YMGooeySlideMenu(titles: ["Hello"]) } self.menu!.triggeredMenu() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
137bb94769331d09dea78906368157c8
22.4
98
0.626068
false
false
false
false
ITzTravelInTime/TINU
refs/heads/development
TINU/IconsManager.swift
gpl-2.0
1
/* TINU, the open tool to create bootable macOS installers. Copyright (C) 2017-2022 Pietro Caruso (ITzTravelInTime) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ import Cocoa import TINURecovery import SwiftPackagesBase public struct SFSymbol: Hashable, Codable, Copying, Equatable{ private let name: String public var description: String? = nil @available(macOS 11.0, *) public static var defaultWeight: NSFont.Weight = .light public init(name: String, description: String? = nil){ self.name = name self.description = description } public init(symbol: SFSymbol){ self.name = symbol.name self.description = symbol.description } public func copy() -> SFSymbol { return SFSymbol(symbol: self) } public func adding(attribute: String) -> SFSymbol?{ if #available(macOS 11.0, *){ if name.contains(".\(attribute)"){ return copy() } let segmented = self.name.split(separator: ".") for i in (0...segmented.count).reversed(){ var str = "" for k in 0..<i{ str += ".\(segmented[k])" } if !str.isEmpty{ str.removeFirst() } str += ".\(attribute)" if i <= segmented.count{ for k in i..<segmented.count{ str += ".\(segmented[k])" } } //Really unefficient way of checking if a symbol exists if NSImage(systemSymbolName: str, accessibilityDescription: nil) != nil{ return SFSymbol(name: str, description: description) } } } return nil } public func fill() -> SFSymbol?{ return adding(attribute: "fill") } public func circular() -> SFSymbol?{ return adding(attribute: "circle") } public func triangular() -> SFSymbol?{ return adding(attribute: "triangle") } public func octagonal() -> SFSymbol?{ return adding(attribute: "octagon") } public func duplicated() -> SFSymbol?{ return adding(attribute: "2") } public func image(accessibilityDescription: String? = nil) -> NSImage?{ if #available(macOS 11.0, *) { return NSImage(systemSymbolName: self.name, accessibilityDescription: accessibilityDescription)?.withSymbolWeight(Self.defaultWeight) } else { return nil } } public func imageWithSystemDefaultWeight(accessibilityDescription: String? = nil) -> NSImage?{ if #available(macOS 11.0, *) { return NSImage(systemSymbolName: self.name, accessibilityDescription: accessibilityDescription) } else { return nil } } } public struct Icon: Hashable, Codable, Equatable{ public init(path: String? = nil, symbol: SFSymbol? = nil, imageName: String? = nil, alternativeImage: Data? = nil) { assert(imageName != nil || path != nil || alternativeImage != nil || symbol != nil, "This is not a valid configuration for an icon") self.path = path self.symbol = symbol self.imageName = imageName self.alternativeImage = alternativeImage } public init(path: String?, symbol: SFSymbol?, imageName: String?, alternative: NSImage?) { assert(imageName != nil || path != nil || alternative != nil || symbol != nil, "This is not a valid configuration for an icon") self.path = path self.symbol = symbol self.imageName = imageName self.alternativeImage = alternative?.tiffRepresentation } public init(symbol: SFSymbol) { self.symbol = symbol } public init(symbolName: String) { self.symbol = SFSymbol(name: symbolName) } public init(imageName: String) { self.imageName = imageName } public init(alternativeImage: Data?) { self.alternativeImage = alternativeImage } private var path: String? = nil private var symbol: SFSymbol? = nil private var imageName: String? = nil private var alternativeImage: Data? = nil private var alternative: NSImage?{ get{ guard let alt = alternativeImage else { return nil } return NSImage(data: alt) } set{ alternativeImage = newValue?.tiffRepresentation } } public var sfSymbol: SFSymbol?{ return symbol } public func normalImage() -> NSImage?{ assert(imageName != nil || path != nil || alternativeImage != nil) var image: NSImage? if imageName != nil{ assert(imageName != "", "The image name must be a valid image name") image = NSImage(named: imageName!) } if image == nil && path != nil{ assert(path != "", "The path must be a valid path") //Commented this to allow for testing if an image exists and then if not use the alternate image //assert(FileManager.default.fileExists(atPath: path!), "The specified path must be the one of a file that exists") image = NSImage(contentsOfFile: path!) } if image == nil && alternativeImage != nil{ image = alternative } return image } public func sFSymbolImage() -> NSImage?{ return symbol?.image() } public func themedImage() -> NSImage?{ if #available(macOS 11.0, *),symbol != nil && look.usesSFSymbols(){ if look.usesFilledSFSymbols(){ return symbol?.fill()?.image() ?? normalImage() } return sFSymbolImage() ?? normalImage() } return normalImage() } } public final class IconsManager{ public static let shared = IconsManager() //warning icon used by the app public var warningIcon: Icon{ //return getIconFor(path: "", symbol: "exclamationmark.triangle", name: NSImage.cautionName) struct Mem{ static var icon: Icon? = nil } if Mem.icon == nil{ Mem.icon = Icon(path: nil, symbol: SFSymbol(name: "exclamationmark.triangle"), imageName: NSImage.cautionName) } return Mem.icon! } public var roundWarningIcon: Icon{ //return getIconFor(path: "", symbol: "exclamationmark.circle", name: NSImage.cautionName) struct Mem{ static var icon: Icon? = nil } if Mem.icon == nil{ Mem.icon = Icon(path: nil, symbol: SFSymbol(name: "exclamationmark").circular(), imageName: NSImage.cautionName) } return Mem.icon! } //stop icon used by the app public var stopIcon: Icon{ //return getIconFor(path: "/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/AlertStopIcon.icns", symbol: "xmark.octagon", name: "uncheck") struct Mem{ static var icon: Icon? = nil } if Mem.icon == nil{ Mem.icon = Icon(path: "/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/AlertStopIcon.icns", symbol: SFSymbol(name: "xmark").octagonal(), imageName: "uncheck") } return Mem.icon! } public var roundStopIcon: Icon{ //return getIconFor(path: "/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/AlertStopIcon.icns", symbol: "xmark.circle", name: "uncheck") struct Mem{ static var icon: Icon? = nil } if Mem.icon == nil{ Mem.icon = Icon(path: "/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/AlertStopIcon.icns", symbol: SFSymbol(name: "xmark").circular(), imageName: "uncheck") } return Mem.icon! } public var checkIcon: Icon{ //return getIconFor(path: "", symbol: "checkmark.circle", name: "checkVector") struct Mem{ static var icon: Icon? = nil } if Mem.icon == nil{ Mem.icon = Icon(path: nil, symbol: SFSymbol(name: "checkmark").circular(), imageName: "checkVector") } return Mem.icon! } public var copyIcon: Icon{ //return getIconFor(path: "", symbol: "doc.on.doc", name: NSImage.multipleDocumentsName) struct Mem{ static var icon: Icon? = nil } if Mem.icon == nil{ Mem.icon = Icon(path: nil, symbol: SFSymbol(name: "doc.on.doc"), imageName: NSImage.multipleDocumentsName) } return Mem.icon! } public var saveIcon: Icon{ //return getIconFor(path: "/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/GenericDocumentIcon.icns", symbol: "tray.and.arrow.down", name: NSImage.multipleDocumentsName) struct Mem{ static var icon: Icon? = nil } if Mem.icon == nil{ Mem.icon = Icon(path: "/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/GenericDocumentIcon.icns", symbol: SFSymbol(name: "tray.and.arrow.down"), imageName: NSImage.multipleDocumentsName) } return Mem.icon! } public var removableDiskIcon: Icon{ //return getIconFor(path: "/System/Library/Extensions/IOStorageFamily.kext/Contents/Resources/Removable.icns", symbol: "externaldrive", name: "Removable") struct Mem{ static var icon: Icon? = nil } if Mem.icon == nil{ Mem.icon = Icon(path: "/System/Library/Extensions/IOStorageFamily.kext/Contents/Resources/Removable.icns", symbol: SFSymbol(name: "externaldrive"), imageName: "Removable") } return Mem.icon! } public var externalDiskIcon: Icon{ //return getIconFor(path: "/System/Library/Extensions/IOStorageFamily.kext/Contents/Resources/External.icns", symbol: "externaldrive", alternate: removableDiskIcon) struct Mem{ static var icon: Icon? = nil } if Mem.icon == nil{ Mem.icon = Icon(path: "/System/Library/Extensions/IOStorageFamily.kext/Contents/Resources/External.icns", symbol: SFSymbol(name: "externaldrive"), imageName: nil, alternative: removableDiskIcon.normalImage()) } return Mem.icon! } public var internalDiskIcon: Icon{ //return getIconFor(path: "/System/Library/Extensions/IOStorageFamily.kext/Contents/Resources/Internal.icns", symbol: "internaldrive", alternate: removableDiskIcon) struct Mem{ static var icon: Icon? = nil } if Mem.icon == nil{ Mem.icon = Icon(path: "/System/Library/Extensions/IOStorageFamily.kext/Contents/Resources/Internal.icns", symbol: SFSymbol(name: "internaldrive"), imageName: "internaldrive", alternative: removableDiskIcon.normalImage()) } return Mem.icon! } public var timeMachineDiskIcon: Icon{ //return getIconFor(path: "/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/GenericTimeMachineDiskIcon.icns", symbol: "externaldrive.badge.timemachine", alternate: removableDiskIcon) struct Mem{ static var icon: Icon? = nil } if Mem.icon == nil{ Mem.icon = Icon(path: "/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/GenericTimeMachineDiskIcon.icns", symbol: SFSymbol(name: "externaldrive.badge.timemachine"), imageName: nil, alternative: removableDiskIcon.normalImage()) } return Mem.icon! } public var genericInstallerAppIcon: Icon{ //return getIconFor(path: "/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/GenericApplicationIcon.icns", symbol: "square.and.arrow.down", name: "InstallApp", alternateFirst: true) struct Mem{ static var icon: Icon? = nil } if Mem.icon == nil{ Mem.icon = Icon(path: "/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/GenericApplicationIcon.icns", symbol: SFSymbol(name: "square.and.arrow.down"), imageName: "InstallApp") } return Mem.icon! } public var optionsIcon: Icon{ //return getIconFor(path: "", symbol: "gearshape", name: NSImage.preferencesGeneralName) struct Mem{ static var icon: Icon? = nil } if Mem.icon == nil{ Mem.icon = Icon(path: nil, symbol: SFSymbol(name: "gearshape"), imageName: NSImage.preferencesGeneralName) } return Mem.icon! } public var advancedOptionsIcon: Icon{ //return getIconFor(path: "", symbol: "gearshape.2", name: NSImage.advancedName) struct Mem{ static var icon: Icon? = nil } if Mem.icon == nil{ Mem.icon = Icon(path: nil, symbol: SFSymbol(name: "gearshape").duplicated(), imageName: NSImage.advancedName) } return Mem.icon! } public var folderIcon: Icon{ //return getIconFor(path: "", symbol: "folder", name: NSImage.folderName) struct Mem{ static var icon: Icon? = nil } if Mem.icon == nil{ Mem.icon = Icon(path: nil, symbol: SFSymbol(name: "folder"), imageName: NSImage.folderName) } return Mem.icon! } //return the icon of thespecified installer app func getInstallerAppIconFrom(path app: String) ->NSImage{ let iconp = app + "/Contents/Resources/InstallAssistant.icns" if FileManager.default.fileExists(atPath: iconp){ if let i = NSImage(contentsOfFile: iconp){ return i } } return NSWorkspace.shared.icon(forFile: app) } /* //gets an icon from a file, if the file do not exists, it uses an icon from the assets public func getIconFor(path: String, symbol: String, name: String, alternateFirst: Bool = false) -> NSImage!{ return getIconFor(path: path, symbol: symbol, alternate: NSImage(named: name), alternateFirst: alternateFirst) } //TODO: caching for icons from the file system public func getIconFor(path: String, symbol: String, alternate: NSImage! = nil, alternateFirst: Bool = false) -> NSImage!{ if #available(macOS 11.0, *), look.usesSFSymbols() && !symbol.isEmpty{ var ret = NSImage(systemSymbolName: symbol + (look.usesFilledSFSymbols() && !symbol.contains(".fill") ? ".fill" : ""), accessibilityDescription: nil) if ret == nil{ ret = NSImage(systemSymbolName: symbol, accessibilityDescription: nil) } ret?.isTemplate = true return ret } if path.isEmpty{ return alternate } if FileManager.default.fileExists(atPath: path) && !(alternate != nil && alternateFirst){ return NSImage(contentsOfFile: path) }else{ return alternate } } */ public func getCorrectDiskIcon(_ id: BSDID) -> NSImage{ if id.isVolume{ if let mount = id.mountPoint(){ if !(mount.isEmpty){ if FileManager.default.directoryExists(atPath: mount + "/Backups.backupdb"){ return timeMachineDiskIcon.themedImage()! }else{ if FileManager.default.fileExists(atPath: mount + "/.VolumeIcon.icns"){ return NSWorkspace.shared.icon(forFile: mount) } } } } } var image = IconsManager.shared.removableDiskIcon if let i = id.isRemovable(){ if !i{ image = IconsManager.shared.internalDiskIcon }else if let i = id.isExternalHardDrive(){ if !i{ image = IconsManager.shared.externalDiskIcon } } } return image.themedImage()! } }
466a585b0ee691f6b212595a20d306d9
27.693069
245
0.695514
false
false
false
false
ArnavChawla/InteliChat
refs/heads/master
Carthage/Checkouts/swift-sdk/Source/DiscoveryV1/Models/Notice.swift
mit
1
/** * Copyright IBM Corporation 2018 * * 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 /** A notice produced for the collection. */ public struct Notice: Decodable { /// Severity level of the notice. public enum Severity: String { case warning = "warning" case error = "error" } /// Identifies the notice. Many notices might have the same ID. This field exists so that user applications can programmatically identify a notice and take automatic corrective action. public var noticeID: String? /// The creation date of the collection in the format yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. public var created: String? /// Unique identifier of the document. public var documentID: String? /// Unique identifier of the query used for relevance training. public var queryID: String? /// Severity level of the notice. public var severity: String? /// Ingestion or training step in which the notice occurred. public var step: String? /// The description of the notice. public var description: String? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case noticeID = "notice_id" case created = "created" case documentID = "document_id" case queryID = "query_id" case severity = "severity" case step = "step" case description = "description" } }
48651151f7e9fa5b551bcc2b0aaac8b3
32.216667
188
0.69142
false
false
false
false
alirsamar/BiOS
refs/heads/master
RobotMaze2/Maze/MazeActor.swift
mit
1
// // MovingObject.swift // Maze // // Created by Jarrod Parkes on 8/14/15. // Copyright © 2015 Udacity, Inc. All rights reserved. // import UIKit // MARK: - MazeActor class MazeActor: MazeObject { // MARK: Properities var location: MazeLocation var direction: MazeDirection var view: UIView var mazeController: MazeController? let objectSize = CGSize(width: 50, height: 50) let queueManager = QueueManager.sharedManager // MARK: Initializers init(location: MazeLocation, direction: MazeDirection) { self.location = location self.direction = direction self.view = SimpleRobotView() self.view.opaque = false if self.direction != MazeDirection.Up { self.view.transform = CGAffineTransformRotate(self.view.transform, CGFloat(M_PI_2) * CGFloat(self.direction.rawValue)) } } init(location: MazeLocation, direction: MazeDirection, imagePath: String) { self.location = location self.direction = direction self.view = UIView(frame: CGRectMake(0, 0, objectSize.width, objectSize.height)) self.view.opaque = false if let image = UIImage(named: imagePath) { let imageView = UIImageView(image: image) imageView.frame = self.view.frame self.view.addSubview(imageView) } if self.direction != MazeDirection.Up { self.view.transform = CGAffineTransformRotate(self.view.transform, CGFloat(M_PI_2) * CGFloat(self.direction.rawValue)) } } // MARK: Enqueue MazeMovesOperation (NSOperation) func rotate(rotateDirection: RotateDirection, completionHandler: (() -> Void)? = nil) { if rotateDirection == RotateDirection.Left { if direction.rawValue > 0 { direction = MazeDirection(rawValue: direction.rawValue - 1)! } else { direction = MazeDirection.Left } } else if rotateDirection == RotateDirection.Right { if direction.rawValue < 3 { direction = MazeDirection(rawValue: direction.rawValue + 1)! } else { direction = MazeDirection.Up } } let move = MazeMove(coords: Move(dx: 0, dy: 0), rotateDirection: rotateDirection) enqueueMove(move, completionHandler: completionHandler) } func move(moveDirection: MazeDirection, moves: Int, completionHandler: (() -> Void)? = nil) { if moveDirection != self.direction { var movesToRotate = moveDirection.rawValue - self.direction.rawValue if movesToRotate == 3 { movesToRotate = -1 } else if movesToRotate == -3 { movesToRotate = 1 } for _ in 0..<abs(movesToRotate) { rotate((movesToRotate > 0) ? RotateDirection.Right : RotateDirection.Left, completionHandler: completionHandler) } } let dx = (moveDirection == MazeDirection.Right) ? 1 : ((moveDirection == MazeDirection.Left) ? -1 : 0) let dy = (moveDirection == MazeDirection.Up) ? -1 : ((moveDirection == MazeDirection.Down) ? 1 : 0) for var i = 0; i < moves; ++i { let move = MazeMove(coords: Move(dx: dx, dy: dy), rotateDirection: .None) enqueueMove(move, completionHandler: completionHandler) } } func enqueueMove(move: MazeMove, completionHandler: (() -> Void)? = nil) { guard let mazeController = mazeController else { return } let operation = MazeMoveOperation(object: self, move: move, mazeController: mazeController) queueManager.addDependentMove(operation) if let completionHandler = completionHandler { completionHandler() } } } extension MazeActor: Hashable { var hashValue: Int { return self.view.hashValue } }
b9159856c65e093f14ca4a96450cf8bd
35.745283
130
0.619928
false
false
false
false
Kekiiwaa/Localize
refs/heads/master
Tests/UIViewComponentsWithString.swift
mit
2
// // UIViewComponentsWithString.swift // LocalizeTests // // Copyright © 2019 @andresilvagomez. // import XCTest import UIKit import Localize class UIViewComponentsWithString: XCTestCase { override func setUp() { super.setUp() Localize.update(bundle: Bundle(for: type(of: self))) Localize.update(language: "en") } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } // MARK: - UIBarButtonItem func testButtonItemWithLocalizeKey() { let button = UIBarButtonItem(title: "", style: .plain, target: self, action: nil) button.localizeKey = "the.same.lavel" button.localize() XCTAssertTrue(button.title == "This is a localized in the same level") } func testButtonItemWithTextKey() { let button = UIBarButtonItem(title: "the.same.lavel", style: .plain, target: self, action: nil) button.localize() XCTAssertTrue(button.title == "This is a localized in the same level") } func testButtonItemWithoutKeys() { let button = UIBarButtonItem(barButtonSystemItem: .add, target: nil, action: nil) button.localize() XCTAssertTrue(button.title == nil) } // MARK: - UIButton func testButtonWithLocalizeKey() { let button = UIButton(frame: CGRect(x: 0, y: 0, width: 0, height: 0)) button.localizeKey = "the.same.lavel" button.localize() XCTAssertTrue(button.titleLabel?.text == "This is a localized in the same level") } func testButtonWithTextKey() { let button = UIButton(frame: CGRect(x: 0, y: 0, width: 0, height: 0)) button.titleLabel?.text = "the.same.lavel" button.localize() XCTAssertTrue(button.titleLabel?.text == "This is a localized in the same level") } func testButtonWithoutKeys() { let button = UIButton(frame: CGRect(x: 0, y: 0, width: 0, height: 0)) button.localize() XCTAssertTrue(button.titleLabel?.text == "") } // MARK: - UILabel func testLabelWithLocalizeKey() { let label = UILabel(frame: CGRect(x: 0, y: 0, width: 0, height: 0)) label.localizeKey = "the.same.lavel" label.localize() XCTAssertTrue(label.text == "This is a localized in the same level") } func testLabelWithTextKey() { let label = UILabel(frame: CGRect(x: 0, y: 0, width: 0, height: 0)) label.text = "the.same.lavel" label.localize() XCTAssertTrue(label.text == "This is a localized in the same level") } func testLabelWithoutKeys() { let label = UILabel(frame: CGRect(x: 0, y: 0, width: 0, height: 0)) label.localize() XCTAssertTrue(label.text == nil) } // MARK: - UINavigationItem func testNavigationItemWithLocalizeKey() { let item = UINavigationItem(title: "") item.localizeTitle = "the.same.lavel" item.localizePrompt = "the.same.lavel" item.localize() XCTAssertTrue(item.title == "This is a localized in the same level") XCTAssertTrue(item.prompt == "This is a localized in the same level") } func testNavigationItemWithTextKey() { let item = UINavigationItem(title: "the.same.lavel") item.prompt = "the.same.lavel" item.localize() XCTAssertTrue(item.title == "This is a localized in the same level") XCTAssertTrue(item.prompt == "This is a localized in the same level") } func testNavigationItemWithoutKeys() { let item = UINavigationItem(title: "") item.localize() XCTAssertTrue(item.title == "") XCTAssertTrue(item.prompt == nil) } // MARK: - UISearchBar func testSearchBarWithLocalizeKey() { let bar = UISearchBar(frame: CGRect(x: 0, y: 0, width: 0, height: 0)) bar.localizePlaceholder = "the.same.lavel" bar.localizePrompt = "the.same.lavel" bar.localize() XCTAssertTrue(bar.placeholder == "This is a localized in the same level") XCTAssertTrue(bar.prompt == "This is a localized in the same level") } func testSearchBarWithTextKey() { let bar = UISearchBar(frame: CGRect(x: 0, y: 0, width: 0, height: 0)) bar.placeholder = "the.same.lavel" bar.prompt = "the.same.lavel" bar.localize() XCTAssertTrue(bar.placeholder == "This is a localized in the same level") XCTAssertTrue(bar.prompt == "This is a localized in the same level") } func testSearchBarWithoutKeys() { let bar = UISearchBar(frame: CGRect(x: 0, y: 0, width: 0, height: 0)) bar.localize() XCTAssertTrue(bar.placeholder == nil) XCTAssertTrue(bar.prompt == nil) } // MARK: - UITabBarItem func testTabBarItemWithLocalizeKey() { let bar = UITabBarItem(title: "", image: nil, tag: 0) bar.localizeKey = "the.same.lavel" bar.localize() XCTAssertTrue(bar.title == "This is a localized in the same level") } func testTabBarItemWithTextKey() { let bar = UITabBarItem(title: "the.same.lavel", image: nil, tag: 0) bar.localize() XCTAssertTrue(bar.title == "This is a localized in the same level") } func testTabBarItemWithoutKeys() { let bar = UITabBarItem(title: "", image: nil, tag: 0) bar.localize() XCTAssertTrue(bar.title == "") } // MARK: - UITextField func testTextFieldWithLocalizeKey() { let textField = UITextField(frame: CGRect(x: 0, y: 0, width: 0, height: 0)) textField.localizeText = "the.same.lavel" textField.localizePlaceholder = "the.same.lavel" textField.localize() XCTAssertTrue(textField.text == "This is a localized in the same level") XCTAssertTrue(textField.placeholder == "This is a localized in the same level") } func testTextFieldWithTextKey() { let textField = UITextField(frame: CGRect(x: 0, y: 0, width: 0, height: 0)) textField.text = "the.same.lavel" textField.placeholder = "the.same.lavel" textField.localize() XCTAssertTrue(textField.text == "This is a localized in the same level") XCTAssertTrue(textField.placeholder == "This is a localized in the same level") } func testTextFieldWithoutKeys() { let textField = UITextField(frame: CGRect(x: 0, y: 0, width: 0, height: 0)) textField.localize() XCTAssertTrue(textField.text == "") XCTAssertTrue(textField.placeholder == nil) } // MARK: - UITextView func testTextViewWithLocalizeKey() { let textView = UITextView(frame: CGRect(x: 0, y: 0, width: 0, height: 0)) textView.localizeKey = "the.same.lavel" textView.localize() XCTAssertTrue(textView.text == "This is a localized in the same level") } func testTextViewWithTextKey() { let textView = UITextView(frame: CGRect(x: 0, y: 0, width: 0, height: 0)) textView.text = "the.same.lavel" textView.localize() XCTAssertTrue(textView.text == "This is a localized in the same level") } func testTextViewWithoutKeys() { let textView = UITextView(frame: CGRect(x: 0, y: 0, width: 0, height: 0)) textView.localize() XCTAssertTrue(textView.text == "") } // MARK: - UISegmentedControl func testSegmentedControlWithLocalizeKey() { let segment = UISegmentedControl(frame: CGRect(x: 0, y: 0, width: 0, height: 0)) segment.insertSegment(withTitle: "", at: 0, animated: false) segment.insertSegment(withTitle: "", at: 1, animated: false) segment.localizeKey = "one, two" segment.localize() XCTAssertTrue(segment.titleForSegment(at: 0) == "First") XCTAssertTrue(segment.titleForSegment(at: 1) == "Second") } func testSegmentedControlWithLocalizeKeyBased() { let segment = UISegmentedControl(frame: CGRect(x: 0, y: 0, width: 0, height: 0)) segment.insertSegment(withTitle: "", at: 0, animated: false) segment.insertSegment(withTitle: "", at: 1, animated: false) segment.localizeKey = "segment.base: one, two" segment.localize() XCTAssertTrue(segment.titleForSegment(at: 0) == "First") XCTAssertTrue(segment.titleForSegment(at: 1) == "Second") } func testSegmentedControlWithTextKey() { let segment = UISegmentedControl(frame: CGRect(x: 0, y: 0, width: 0, height: 0)) segment.insertSegment(withTitle: "segment.base.one", at: 0, animated: false) segment.insertSegment(withTitle: "segment.base.two", at: 1, animated: false) segment.localize() XCTAssertTrue(segment.titleForSegment(at: 0) == "First") XCTAssertTrue(segment.titleForSegment(at: 1) == "Second") } func testSegmentedControlWithoutKeys() { let segment = UISegmentedControl(frame: CGRect(x: 0, y: 0, width: 0, height: 0)) segment.insertSegment(withTitle: "", at: 0, animated: false) segment.insertSegment(withTitle: "", at: 1, animated: false) segment.localize() XCTAssertTrue(segment.titleForSegment(at: 0) == "") XCTAssertTrue(segment.titleForSegment(at: 1) == "") } }
6dc9fe61b0f0b8ef4995bcfcd862c580
33.67037
111
0.630381
false
true
false
false
jjatie/Charts
refs/heads/master
Source/Charts/Renderers/DataRenderer/BarChartRenderer.swift
apache-2.0
1
// // BarChartRenderer.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Algorithms import CoreGraphics import Foundation #if !os(OSX) import UIKit #endif public class BarChartRenderer: DataRenderer { public let viewPortHandler: ViewPortHandler public final var accessibleChartElements: [NSUIAccessibilityElement] = [] public let animator: Animator let xBounds = XBounds() /// A nested array of elements ordered logically (i.e not in visual/drawing order) for use with VoiceOver /// /// Its use is apparent when there are multiple data sets, since we want to read bars in left to right order, /// irrespective of dataset. However, drawing is done per dataset, so using this array and then flattening it prevents us from needing to /// re-render for the sake of accessibility. /// /// In practise, its structure is: /// /// ```` /// [ /// [dataset1 element1, dataset2 element1], /// [dataset1 element2, dataset2 element2], /// [dataset1 element3, dataset2 element3] /// ... /// ] /// ```` /// This is done to provide numerical inference across datasets to a screenreader user, in the same way that a sighted individual /// uses a multi-dataset bar chart. /// /// The ````internal```` specifier is to allow subclasses (HorizontalBar) to populate the same array final lazy var accessibilityOrderedElements: [[NSUIAccessibilityElement]] = accessibilityCreateEmptyOrderedElements() private typealias Buffer = [CGRect] public weak var dataProvider: BarChartDataProvider? // [CGRect] per dataset private var _buffers = [Buffer]() public init( dataProvider: BarChartDataProvider, animator: Animator, viewPortHandler: ViewPortHandler ) { self.viewPortHandler = viewPortHandler self.animator = animator self.dataProvider = dataProvider } public func initBuffers() { guard let barData = dataProvider?.barData else { return _buffers.removeAll() } // Match buffers count to dataset count if _buffers.count != barData.count { while _buffers.count < barData.count { _buffers.append(Buffer()) } while _buffers.count > barData.count { _buffers.removeLast() } } _buffers = zip(_buffers, barData).map { buffer, set -> Buffer in let set = set as! BarChartDataSet let size = set.count * (set.isStacked ? set.stackSize : 1) return buffer.count == size ? buffer : Buffer(repeating: .zero, count: size) } } private func prepareBuffer(dataSet: BarChartDataSet, index: Int) { guard let dataProvider = dataProvider, let barData = dataProvider.barData else { return } let barWidthHalf = CGFloat(barData.barWidth / 2.0) var bufferIndex = 0 let containsStacks = dataSet.isStacked let isInverted = dataProvider.isInverted(axis: dataSet.axisDependency) let phaseY = CGFloat(animator.phaseY) for i in (0 ..< dataSet.count).clamped(to: 0 ..< Int(ceil(Double(dataSet.count) * animator.phaseX))) { guard let e = dataSet[i] as? BarChartDataEntry else { continue } let x = CGFloat(e.x) let left = x - barWidthHalf let right = x + barWidthHalf var y = e.y if containsStacks, let vals = e.yValues { var posY = 0.0 var negY = -e.negativeSum var yStart = 0.0 // fill the stack for value in vals { if value == 0.0, posY == 0.0 || negY == 0.0 { // Take care of the situation of a 0.0 value, which overlaps a non-zero bar y = value yStart = y } else if value >= 0.0 { y = posY yStart = posY + value posY = yStart } else { y = negY yStart = negY + abs(value) negY += abs(value) } var top = isInverted ? (y <= yStart ? CGFloat(y) : CGFloat(yStart)) : (y >= yStart ? CGFloat(y) : CGFloat(yStart)) var bottom = isInverted ? (y >= yStart ? CGFloat(y) : CGFloat(yStart)) : (y <= yStart ? CGFloat(y) : CGFloat(yStart)) // multiply the height of the rect with the phase top *= phaseY bottom *= phaseY let barRect = CGRect(x: left, y: top, width: right - left, height: bottom - top) _buffers[index][bufferIndex] = barRect bufferIndex += 1 } } else { var top = isInverted ? (y <= 0.0 ? CGFloat(y) : 0) : (y >= 0.0 ? CGFloat(y) : 0) var bottom = isInverted ? (y >= 0.0 ? CGFloat(y) : 0) : (y <= 0.0 ? CGFloat(y) : 0) /* When drawing each bar, the renderer actually draws each bar from 0 to the required value. * This drawn bar is then clipped to the visible chart rect in BarLineChartViewBase's draw(rect:) using clipDataToContent. * While this works fine when calculating the bar rects for drawing, it causes the accessibilityFrames to be oversized in some cases. * This offset attempts to undo that unnecessary drawing when calculating barRects * * +---------------------------------------------------------------+---------------------------------------------------------------+ * | Situation 1: (!inverted && y >= 0) | Situation 3: (inverted && y >= 0) | * | | | * | y -> +--+ <- top | 0 -> ---+--+---+--+------ <- top | * | |//| } topOffset = y - max | | | |//| } topOffset = min | * | max -> +---------+--+----+ <- top - topOffset | min -> +--+--+---+--+----+ <- top + topOffset | * | | +--+ |//| | | | | | |//| | | * | | | | |//| | | | +--+ |//| | | * | | | | |//| | | | |//| | | * | min -> +--+--+---+--+----+ <- bottom + bottomOffset | max -> +---------+--+----+ <- bottom - bottomOffset | * | | | |//| } bottomOffset = min | |//| } bottomOffset = y - max | * | 0 -> ---+--+---+--+----- <- bottom | y -> +--+ <- bottom | * | | | * +---------------------------------------------------------------+---------------------------------------------------------------+ * | Situation 2: (!inverted && y < 0) | Situation 4: (inverted && y < 0) | * | | | * | 0 -> ---+--+---+--+----- <- top | y -> +--+ <- top | * | | | |//| } topOffset = -max | |//| } topOffset = min - y | * | max -> +--+--+---+--+----+ <- top - topOffset | min -> +---------+--+----+ <- top + topOffset | * | | | | |//| | | | +--+ |//| | | * | | +--+ |//| | | | | | |//| | | * | | |//| | | | | | |//| | | * | min -> +---------+--+----+ <- bottom + bottomOffset | max -> +--+--+---+--+----+ <- bottom - bottomOffset | * | |//| } bottomOffset = min - y | | | |//| } bottomOffset = -max | * | y -> +--+ <- bottom | 0 -> ---+--+---+--+------- <- bottom | * | | | * +---------------------------------------------------------------+---------------------------------------------------------------+ */ var topOffset: CGFloat = 0.0 var bottomOffset: CGFloat = 0.0 if let offsetView = dataProvider as? BarChartView { let offsetAxis = offsetView.getAxis(dataSet.axisDependency) if y >= 0 { // situation 1 if offsetAxis.axisMaximum < y { topOffset = CGFloat(y - offsetAxis.axisMaximum) } if offsetAxis.axisMinimum > 0 { bottomOffset = CGFloat(offsetAxis.axisMinimum) } } else // y < 0 { // situation 2 if offsetAxis.axisMaximum < 0 { topOffset = CGFloat(offsetAxis.axisMaximum * -1) } if offsetAxis.axisMinimum > y { bottomOffset = CGFloat(offsetAxis.axisMinimum - y) } } if isInverted { // situation 3 and 4 // exchange topOffset/bottomOffset based on 1 and 2 // see diagram above (topOffset, bottomOffset) = (bottomOffset, topOffset) } } // apply offset top = isInverted ? top + topOffset : top - topOffset bottom = isInverted ? bottom - bottomOffset : bottom + bottomOffset // multiply the height of the rect with the phase // explicitly add 0 + topOffset to indicate this is changed after adding accessibility support (#3650, #3520) if top > 0 + topOffset { top *= phaseY } else { bottom *= phaseY } let barRect = CGRect(x: left, y: top, width: right - left, height: bottom - top) _buffers[index][bufferIndex] = barRect bufferIndex += 1 } } } public func drawData(context: CGContext) { guard let dataProvider = dataProvider, let barData = dataProvider.barData else { return } // If we redraw the data, remove and repopulate accessible elements to update label values and frames accessibleChartElements.removeAll() accessibilityOrderedElements = accessibilityCreateEmptyOrderedElements() // Make the chart header the first element in the accessible elements array if let chart = dataProvider as? BarChartView { let element = createAccessibleHeader(usingChart: chart, andData: barData, withDefaultDescription: "Bar Chart") accessibleChartElements.append(element) } // Populate logically ordered nested elements into accessibilityOrderedElements in drawDataSet() for i in barData.indices { guard let set = barData[i] as? BarChartDataSet else { fatalError("Datasets for BarChartRenderer must conform to IBarChartDataset") } guard set.isVisible else { continue } drawDataSet(context: context, dataSet: set, index: i) } // Merge nested ordered arrays into the single accessibleChartElements. accessibleChartElements.append(contentsOf: accessibilityOrderedElements.flatMap { $0 }) accessibilityPostLayoutChangedNotification() } private var _barShadowRectBuffer = CGRect() public func drawDataSet(context: CGContext, dataSet: BarChartDataSet, index: Int) { guard let dataProvider = dataProvider else { return } let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency) prepareBuffer(dataSet: dataSet, index: index) trans.rectValuesToPixel(&_buffers[index]) let borderWidth = dataSet.barBorderWidth let borderColor = dataSet.barBorderColor let drawBorder = borderWidth > 0.0 context.saveGState() defer { context.restoreGState() } // draw the bar shadow before the values if dataProvider.isDrawBarShadowEnabled { guard let barData = dataProvider.barData else { return } let barWidth = barData.barWidth let barWidthHalf = barWidth / 2.0 var x: Double = 0.0 let range = (0 ..< dataSet.count).clamped(to: 0 ..< Int(ceil(Double(dataSet.count) * animator.phaseX))) for i in range { guard let e = dataSet[i] as? BarChartDataEntry else { continue } x = e.x _barShadowRectBuffer.origin.x = CGFloat(x - barWidthHalf) _barShadowRectBuffer.size.width = CGFloat(barWidth) trans.rectValueToPixel(&_barShadowRectBuffer) guard viewPortHandler.isInBoundsLeft(_barShadowRectBuffer.origin.x + _barShadowRectBuffer.size.width) else { continue } guard viewPortHandler.isInBoundsRight(_barShadowRectBuffer.origin.x) else { break } _barShadowRectBuffer.origin.y = viewPortHandler.contentTop _barShadowRectBuffer.size.height = viewPortHandler.contentHeight context.setFillColor(dataSet.barShadowColor.cgColor) context.fill(_barShadowRectBuffer) } } let buffer = _buffers[index] // draw the bar shadow before the values if dataProvider.isDrawBarShadowEnabled { for barRect in buffer where viewPortHandler.isInBoundsLeft(barRect.origin.x + barRect.size.width) { guard viewPortHandler.isInBoundsRight(barRect.origin.x) else { break } context.setFillColor(dataSet.barShadowColor.cgColor) context.fill(barRect) } } let isSingleColor = dataSet.colors.count == 1 if isSingleColor { context.setFillColor(dataSet.color(at: 0).cgColor) } // In case the chart is stacked, we need to accomodate individual bars within accessibilityOrdereredElements let isStacked = dataSet.isStacked let stackSize = isStacked ? dataSet.stackSize : 1 for (j, barRect) in buffer.indexed() { guard viewPortHandler.isInBoundsLeft(barRect.origin.x + barRect.size.width) else { continue } guard viewPortHandler.isInBoundsRight(barRect.origin.x) else { break } if !isSingleColor { // Set the color for the currently drawn value. If the index is out of bounds, reuse colors. context.setFillColor(dataSet.color(at: j).cgColor) } context.fill(barRect) if drawBorder { context.setStrokeColor(borderColor.cgColor) context.setLineWidth(borderWidth) context.stroke(barRect) } // Create and append the corresponding accessibility element to accessibilityOrderedElements if let chart = dataProvider as? BarChartView { let element = createAccessibleElement( withIndex: j, container: chart, dataSet: dataSet, dataSetIndex: index, stackSize: stackSize ) { element in element.accessibilityFrame = barRect } accessibilityOrderedElements[j / stackSize].append(element) } } } public func prepareBarHighlight( x: Double, y1: Double, y2: Double, barWidthHalf: Double, trans: Transformer, rect: inout CGRect ) { let left = x - barWidthHalf let right = x + barWidthHalf let top = y1 let bottom = y2 rect.origin.x = CGFloat(left) rect.origin.y = CGFloat(top) rect.size.width = CGFloat(right - left) rect.size.height = CGFloat(bottom - top) trans.rectValueToPixel(&rect, phaseY: animator.phaseY) } public func drawValues(context: CGContext) { guard let dataProvider = dataProvider, isDrawingValuesAllowed(dataProvider: dataProvider), let barData = dataProvider.barData else { return } let valueOffsetPlus: CGFloat = 4.5 var posOffset: CGFloat var negOffset: CGFloat let drawValueAboveBar = dataProvider.isDrawValueAboveBarEnabled for dataSetIndex in barData.indices { guard let dataSet = barData[dataSetIndex] as? BarChartDataSet, shouldDrawValues(forDataSet: dataSet) else { continue } let angleRadians = dataSet.valueLabelAngle.DEG2RAD let isInverted = dataProvider.isInverted(axis: dataSet.axisDependency) // calculate the correct offset depending on the draw position of the value let valueFont = dataSet.valueFont let valueTextHeight = valueFont.lineHeight posOffset = (drawValueAboveBar ? -(valueTextHeight + valueOffsetPlus) : valueOffsetPlus) negOffset = (drawValueAboveBar ? valueOffsetPlus : -(valueTextHeight + valueOffsetPlus)) if isInverted { posOffset = -posOffset - valueTextHeight negOffset = -negOffset - valueTextHeight } let buffer = _buffers[dataSetIndex] let formatter = dataSet.valueFormatter let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency) let phaseY = animator.phaseY let iconsOffset = dataSet.iconsOffset // if only single values are drawn (sum) if !dataSet.isStacked { let range = 0 ..< Int(ceil(Double(dataSet.count) * animator.phaseX)) for j in range { guard let e = dataSet[j] as? BarChartDataEntry else { continue } let rect = buffer[j] let x = rect.origin.x + rect.size.width / 2.0 guard viewPortHandler.isInBoundsRight(x) else { break } guard viewPortHandler.isInBoundsY(rect.origin.y), viewPortHandler.isInBoundsLeft(x) else { continue } let val = e.y if dataSet.isDrawValuesEnabled { drawValue( context: context, value: formatter.stringForValue( val, entry: e, dataSetIndex: dataSetIndex, viewPortHandler: viewPortHandler ), xPos: x, yPos: val >= 0.0 ? (rect.origin.y + posOffset) : (rect.origin.y + rect.size.height + negOffset), font: valueFont, align: .center, color: dataSet.valueTextColorAt(j), anchor: CGPoint(x: 0.5, y: 0.5), angleRadians: angleRadians ) } if let icon = e.icon, dataSet.isDrawIconsEnabled { var px = x var py = val >= 0.0 ? (rect.origin.y + posOffset) : (rect.origin.y + rect.size.height + negOffset) px += iconsOffset.x py += iconsOffset.y context.drawImage(icon, atCenter: CGPoint(x: px, y: py), size: icon.size) } } } else { // if we have stacks var bufferIndex = 0 let lastIndex = ceil(Double(dataSet.count) * animator.phaseX) for index in 0 ..< Int(lastIndex) { guard let e = dataSet[index] as? BarChartDataEntry else { continue } let vals = e.yValues let rect = buffer[bufferIndex] let x = rect.origin.x + rect.size.width / 2.0 // we still draw stacked bars, but there is one non-stacked in between if let values = vals { // draw stack values var transformed = [CGPoint]() var posY = 0.0 var negY = -e.negativeSum for value in values { let y: Double if value == 0.0, posY == 0.0 || negY == 0.0 { // Take care of the situation of a 0.0 value, which overlaps a non-zero bar y = value } else if value >= 0.0 { posY += value y = posY } else { y = negY negY -= value } transformed.append(CGPoint(x: 0.0, y: CGFloat(y * phaseY))) } trans.pointValuesToPixel(&transformed) for (value, transformed) in zip(values, transformed) { let drawBelow = (value == 0.0 && negY == 0.0 && posY > 0.0) || value < 0.0 let y = transformed.y + (drawBelow ? negOffset : posOffset) guard viewPortHandler.isInBoundsRight(x) else { break } guard viewPortHandler.isInBoundsY(y), viewPortHandler.isInBoundsLeft(x) else { continue } if dataSet.isDrawValuesEnabled { drawValue( context: context, value: formatter.stringForValue( value, entry: e, dataSetIndex: dataSetIndex, viewPortHandler: viewPortHandler ), xPos: x, yPos: y, font: valueFont, align: .center, color: dataSet.valueTextColorAt(index), anchor: CGPoint(x: 0.5, y: 0.5), angleRadians: angleRadians ) } if let icon = e.icon, dataSet.isDrawIconsEnabled { context.drawImage(icon, atCenter: CGPoint(x: x + iconsOffset.x, y: y + iconsOffset.y), size: icon.size) } } } else { guard viewPortHandler.isInBoundsRight(x) else { break } guard viewPortHandler.isInBoundsY(rect.origin.y), viewPortHandler.isInBoundsLeft(x) else { continue } if dataSet.isDrawValuesEnabled { drawValue( context: context, value: formatter.stringForValue( e.y, entry: e, dataSetIndex: dataSetIndex, viewPortHandler: viewPortHandler ), xPos: x, yPos: rect.origin.y + (e.y >= 0 ? posOffset : negOffset), font: valueFont, align: .center, color: dataSet.valueTextColorAt(index), anchor: CGPoint(x: 0.5, y: 0.5), angleRadians: angleRadians ) } if let icon = e.icon, dataSet.isDrawIconsEnabled { var px = x var py = rect.origin.y + (e.y >= 0 ? posOffset : negOffset) px += iconsOffset.x py += iconsOffset.y context.drawImage(icon, atCenter: CGPoint(x: px, y: py), size: icon.size) } } bufferIndex += vals?.count ?? 1 } } } } /// Draws a value at the specified x and y position. public func drawValue(context: CGContext, value: String, xPos: CGFloat, yPos: CGFloat, font: NSUIFont, align: TextAlignment, color: NSUIColor, anchor: CGPoint, angleRadians: CGFloat) { if angleRadians == 0.0 { context.drawText(value, at: CGPoint(x: xPos, y: yPos), align: align, attributes: [.font: font, .foregroundColor: color]) } else { // align left to center text with rotation context.drawText(value, at: CGPoint(x: xPos, y: yPos), align: align, anchor: anchor, angleRadians: angleRadians, attributes: [.font: font, .foregroundColor: color]) } } public func drawHighlighted(context: CGContext, indices: [Highlight]) { guard let dataProvider = dataProvider, let barData = dataProvider.barData else { return } context.saveGState() defer { context.restoreGState() } var barRect = CGRect() for high in indices { guard let set = barData[high.dataSetIndex] as? BarChartDataSet, set.isHighlightEnabled else { continue } if let e = set.element(withX: high.x, closestToY: high.y) as? BarChartDataEntry { guard isInBoundsX(entry: e, dataSet: set) else { continue } let trans = dataProvider.getTransformer(forAxis: set.axisDependency) context.setFillColor(set.highlightColor.cgColor) context.setAlpha(set.highlightAlpha) let isStack = high.stackIndex >= 0 && e.isStacked let y1: Double let y2: Double if isStack { if dataProvider.isHighlightFullBarEnabled { y1 = e.positiveSum y2 = -e.negativeSum } else { let range = e.ranges?[high.stackIndex] y1 = range?.lowerBound ?? 0.0 y2 = range?.upperBound ?? 0.0 } } else { y1 = e.y y2 = 0.0 } prepareBarHighlight(x: e.x, y1: y1, y2: y2, barWidthHalf: barData.barWidth / 2.0, trans: trans, rect: &barRect) setHighlightDrawPos(highlight: high, barRect: barRect) context.fill(barRect) } } } /// Sets the drawing position of the highlight object based on the given bar-rect. internal func setHighlightDrawPos(highlight high: Highlight, barRect: CGRect) { high.setDraw(x: barRect.midX, y: barRect.origin.y) } /// Creates a nested array of empty subarrays each of which will be populated with NSUIAccessibilityElements. /// This is marked internal to support HorizontalBarChartRenderer as well. private func accessibilityCreateEmptyOrderedElements() -> [[NSUIAccessibilityElement]] { guard let chart = dataProvider as? BarChartView else { return [] } // Unlike Bubble & Line charts, here we use the maximum entry count to account for stacked bars let maxEntryCount = chart.data?.maxEntryCountSet?.count ?? 0 return Array(repeating: [NSUIAccessibilityElement](), count: maxEntryCount) } /// Creates an NSUIAccessibleElement representing the smallest meaningful bar of the chart /// i.e. in case of a stacked chart, this returns each stack, not the combined bar. /// Note that it is marked internal to support subclass modification in the HorizontalBarChart. internal func createAccessibleElement(withIndex idx: Int, container: BarChartView, dataSet: BarChartDataSet, dataSetIndex: Int, stackSize: Int, modifier: (NSUIAccessibilityElement) -> Void) -> NSUIAccessibilityElement { let element = NSUIAccessibilityElement(accessibilityContainer: container) let xAxis = container.xAxis guard let e = dataSet[idx / stackSize] as? BarChartDataEntry else { return element } guard let dataProvider = dataProvider else { return element } // NOTE: The formatter can cause issues when the x-axis labels are consecutive ints. // i.e. due to the Double conversion, if there are more than one data set that are grouped, // there is the possibility of some labels being rounded up. A floor() might fix this, but seems to be a brute force solution. let label = xAxis.valueFormatter?.stringForValue(e.x, axis: xAxis) ?? "\(e.x)" var elementValueText = dataSet.valueFormatter.stringForValue( e.y, entry: e, dataSetIndex: dataSetIndex, viewPortHandler: viewPortHandler ) if dataSet.isStacked, let vals = e.yValues { let labelCount = min(dataSet.colors.count, stackSize) let stackLabel: String? if !dataSet.stackLabels.isEmpty, labelCount > 0 { let labelIndex = idx % labelCount stackLabel = dataSet.stackLabels.indices.contains(labelIndex) ? dataSet.stackLabels[labelIndex] : nil } else { stackLabel = nil } // Handles empty array of yValues let yValue = vals.isEmpty ? 0.0 : vals[idx % vals.count] elementValueText = dataSet.valueFormatter.stringForValue( yValue, entry: e, dataSetIndex: dataSetIndex, viewPortHandler: viewPortHandler ) if let stackLabel = stackLabel { elementValueText = stackLabel + " \(elementValueText)" } else { elementValueText = "\(elementValueText)" } } let dataSetCount = dataProvider.barData?.count ?? -1 let doesContainMultipleDataSets = dataSetCount > 1 element.accessibilityLabel = "\(doesContainMultipleDataSets ? (dataSet.label ?? "") + ", " : "") \(label): \(elementValueText)" modifier(element) return element } }
6c07ae694f1da48d5a67cf86e949f390
43.458333
186
0.458997
false
false
false
false
andr3a88/TryNetworkLayer
refs/heads/master
TryNetworkLayer/Controllers/Users/UsersCoordinator.swift
mit
1
// // UsersCoordinator.swift // TryNetworkLayer // // Created by Andrea Stevanato on 13/03/2020. // Copyright © 2020 Andrea Stevanato. All rights reserved. // import UIKit final class UsersCoordinator: Coordinator { var window: UIWindow var navigationController: UINavigationController! var userDetailCoordinator: UserDetailCoordinator? init(window: UIWindow) { self.window = window } func start() { let usersViewController = Storyboard.main.instantiate(UsersViewController.self) usersViewController.viewModel = UsersViewModel() usersViewController.viewModel.coordinatorDelegate = self self.navigationController = UINavigationController(rootViewController: usersViewController) self.window.rootViewController = navigationController } } extension UsersCoordinator: UsersViewModelCoordinatorDelegate { func usersViewModelPresent(user: GHUser) { userDetailCoordinator = UserDetailCoordinator(navigationController: navigationController, user: user) userDetailCoordinator?.start() } }
e07e18b44832933b9fa156deef29d75b
28.72973
109
0.741818
false
false
false
false
alobanov/ALFormBuilder
refs/heads/master
Sources/FormBuilder/FormItemsComposite/sections/SectionFormComposite.swift
mit
1
// // SectionFormItemComposite.swift // ALFormBuilder // // Created by Lobanov Aleksey on 26/10/2017. // Copyright © 2017 Lobanov Aleksey. All rights reserved. // import Foundation public protocol SectionFormCompositeOutput { var header: String? {get} var footer: String? {get} } public class SectionFormComposite: FormItemCompositeProtocol, SectionFormCompositeOutput { // MARK: - SectionFormCompositeOutput public var header: String? public var footer: String? // MARK: - Provate propery private let decoratedComposite: FormItemCompositeProtocol // MARK: - FormItemCompositeProtocol properties public var identifier: String { return self.decoratedComposite.identifier } public var children: [FormItemCompositeProtocol] { return self.decoratedComposite.children } public var datasource: [FormItemCompositeProtocol] { return self.decoratedComposite.children.flatMap { $0.datasource } } public var leaves: [FormItemCompositeProtocol] { return self.decoratedComposite.leaves.flatMap { $0.leaves } } public var level: ALFB.FormModelLevel = .section public init(composite: FormItemCompositeProtocol, header: String?, footer: String?) { self.decoratedComposite = composite self.header = header self.footer = footer } // MARK :- FormItemCompositeProtocol methods public func add(_ model: FormItemCompositeProtocol...) { for item in model { if item.level != .section { self.decoratedComposite.add(item) } else { print("You can`t add section in other section") } } } public func remove(_ model: FormItemCompositeProtocol) { self.decoratedComposite.remove(model) } }
8c620e36e8f3638979acdafd5c656cdc
25.828125
90
0.716948
false
false
false
false
efremidze/NumPad
refs/heads/master
Example/ViewController.swift
mit
1
// // ViewController.swift // Example // // Created by Lasha Efremidze on 5/27/16. // Copyright © 2016 Lasha Efremidze. All rights reserved. // import UIKit import NumPad class ViewController: UIViewController { lazy var containerView: UIView = { [unowned self] in let containerView = UIView() containerView.layer.borderColor = self.borderColor.cgColor containerView.layer.borderWidth = 1 self.view.addSubview(containerView) containerView.constrainToEdges() return containerView }() lazy var textField: UITextField = { [unowned self] in let textField = UITextField() textField.translatesAutoresizingMaskIntoConstraints = false textField.textAlignment = .right textField.textColor = UIColor(white: 0.3, alpha: 1) textField.font = .systemFont(ofSize: 40) textField.placeholder = "0".currency() textField.isEnabled = false self.containerView.addSubview(textField) return textField }() lazy var numPad: NumPad = { [unowned self] in let numPad = DefaultNumPad() numPad.delegate = self numPad.translatesAutoresizingMaskIntoConstraints = false numPad.backgroundColor = self.borderColor self.containerView.addSubview(numPad) return numPad }() let borderColor = UIColor(white: 0.9, alpha: 1) override func viewDidLoad() { super.viewDidLoad() let views: [String : Any] = ["textField": textField, "numPad": numPad] containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-20-[textField]-20-|", options: [], metrics: nil, views: views)) containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[numPad]|", options: [], metrics: nil, views: views)) containerView.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-20-[textField(==120)][numPad]|", options: [], metrics: nil, views: views)) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() numPad.invalidateLayout() } } extension ViewController: NumPadDelegate { func numPad(_ numPad: NumPad, itemTapped item: Item, atPosition position: Position) { switch (position.row, position.column) { case (3, 0): textField.text = nil default: let item = numPad.item(for: position)! let string = textField.text!.sanitized() + item.title! if Int(string) == 0 { textField.text = nil } else { textField.text = string.currency() } } } }
211fbf0a282f4fe07b91f92a4501aa0c
33.1375
165
0.633834
false
false
false
false
borisyurkevich/Wallet
refs/heads/master
Wallet/Currency Converter/Converter.swift
gpl-3.0
1
// // Converter.swift // Wallet // // Created by Boris Yurkevich on 30/09/2017. // Copyright © 2017 Boris Yurkevich. All rights reserved. // import Foundation struct Converter { private var rates: [Currency] init(rates: [Currency]) { self.rates = rates } func convert(fromCurrency: CurrencyType, toCurrency: CurrencyType, amount: Double) -> (sucess: Bool, error: String?, amount: Double?) { if fromCurrency == toCurrency { return (true, nil, amount) } var euroRateRelativeToGivenCurrency: Double? = nil var rateFromEuroToNeededCurrency: Double? = nil for rate in rates { if rate.type == fromCurrency { euroRateRelativeToGivenCurrency = rate.valueInEuro } else if rate.type == toCurrency { rateFromEuroToNeededCurrency = rate.valueInEuro } } if toCurrency == .eur { rateFromEuroToNeededCurrency = 1.0 } if fromCurrency == .eur { euroRateRelativeToGivenCurrency = 1.0 } if euroRateRelativeToGivenCurrency == nil { return (false, "Couldn't find EUR rate to \(fromCurrency.rawValue).", nil) } if rateFromEuroToNeededCurrency == nil { return (false, "Couldn't find EUR rate to \(toCurrency.rawValue).", nil) } // Because our rates are relative to € we need to convert to € first. let inEuro = amount / euroRateRelativeToGivenCurrency! let result = inEuro * rateFromEuroToNeededCurrency! return (true, nil, result) } }
85f7e19d4f1d41af45401f14ac9839c6
30.811321
86
0.585409
false
false
false
false
jfosterdavis/FlashcardHero
refs/heads/master
FlashcardHero/CommandCenterViewController.swift
apache-2.0
1
// // FirstViewController.swift // FlashcardHero // // Created by Jacob Foster Davis on 10/24/16. // Copyright © 2016 Zero Mu, LLC. All rights reserved. // import UIKit import CoreData //import Charts class CommandCenterViewController: CoreDataQuizletCollectionViewController, UICollectionViewDataSource, GameCaller { @IBOutlet weak var missionsCollectionView: UICollectionView! @IBOutlet weak var flowLayout: UICollectionViewFlowLayout! @IBOutlet weak var segmentedControl: UISegmentedControl! @IBOutlet weak var essenceLabel: UILabel! @IBOutlet weak var termsLoadedLabel: UILabel! var keyGameLevel = "GameLevel" var keySets = "Sets" override func viewDidLoad() { super.viewDidLoad() //link the collection view to the coredata class self.collectionView = self.missionsCollectionView collectionView.delegate = self collectionView.dataSource = self _ = setupFetchedResultsController(frcKey: keyGameLevel, entityName: "GameLevel", sortDescriptors: [NSSortDescriptor(key: "level", ascending: false)], predicate: nil) //create FRC for sets _ = setupFetchedResultsController(frcKey: keySets, entityName: "QuizletSet", sortDescriptors: [NSSortDescriptor(key: "title", ascending: false),NSSortDescriptor(key: "id", ascending: true)], predicate: NSPredicate(format: "isActive = %@", argumentArray: [true])) //set up the status bar refreshStatusBar() // Do any additional setup after loading the view, typically from a nib. showMissionsSegment() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) refreshStatusBar() } //adapted from http://stackoverflow.com/questions/28347878/ios8-swift-buttons-inside-uicollectionview-cell @IBAction func startMissionButtonPressed(_ sender: UIButton) { let touchPoint = collectionView.convert(CGPoint.zero, from: sender) if let indexPath = collectionView.indexPathForItem(at: touchPoint) { // now you know indexPath. You can get data or cell from here. let gameVariant = GameDirectory.activeGameVariants[indexPath.row] let game = gameVariant.game let gameId = game.name print("You pushed button for game \(gameId)") let vc = storyboard?.instantiateViewController(withIdentifier: game.storyboardId) if let trueFalseVc = vc as? GameTrueFalseViewController { //if it is a true false game //set the level //let objective = //check for the variant if let objective = getGameObjective(gameVariant: gameVariant) as? GameObjectiveMaxPoints { present(trueFalseVc, animated: true, completion: {trueFalseVc.playGameUntil(playerScoreIs: objective.maxPoints, unlessPlayerScoreReaches: objective.minPoints, sender: self)}) } else if let objective = getGameObjective(gameVariant: gameVariant) as? GameObjectivePerfectScore { present(trueFalseVc, animated: true, completion: {trueFalseVc.playGameUntil(playerReaches: objective.maxPoints, unlessPlayerMisses: objective.missedPoints, sender: self)}) } } } } /******************************************************/ /*******************///MARK: Segmented Control /******************************************************/ @IBAction func indexChanged(_ sender: UISegmentedControl) { switch segmentedControl.selectedSegmentIndex { case 0: showMissionsSegment() case 1: showGoalsSegment() default: break; } } func showMissionsSegment() { print("Showing the missions segment") UIView.animate(withDuration: 0.1, animations: { self.missionsCollectionView.alpha = 1.0 self.missionsCollectionView.isHidden = false }) } func showGoalsSegment() { UIView.animate(withDuration: 0.1, animations: { self.missionsCollectionView.alpha = 0.0 self.missionsCollectionView.isHidden = true }) } /******************************************************/ /*******************///MARK: Status Bar /******************************************************/ func refreshStatusBar() { termsLoadedLabel.text = String(describing: getNumTermsLoaded()) } /******************************************************/ /*******************///MARK: Model Operations /******************************************************/ /** Returns number of terms whose sets are in an active state (selected by user switch) */ func getNumTermsLoaded() -> Int { var count: Int = 0 guard let sets = frcDict[keySets]?.fetchedObjects as? [QuizletSet] else { return 0 } for set in sets { count += Int(set.termCount) } return count } /******************************************************/ /*******************///MARK: GameCaller /******************************************************/ func gameFinished(_ wasObjectiveAchieved: Bool, forGame sender: Game) { print("Game finished. Player success? \(wasObjectiveAchieved)") //if they succeeded award reward and increase level. If they lost, decrease by 2 if wasObjectiveAchieved { //increase level increaseGameLevel(of: sender) } else { decreaseGameLevel(of: sender) } collectionView.reloadData() } /******************************************************/ /*******************///MARK: UICollectionViewDataSource /******************************************************/ func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { print("The are \(GameDirectory.activeGames.count) active games that will be displayed") return GameDirectory.activeGameVariants.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MissionCell", for: indexPath as IndexPath) as! CustomMissionCollectionViewCell let gameVariant = GameDirectory.activeGameVariants[indexPath.row] let game = gameVariant.game print("Showing mission for game: \(game.name)") //associate the photo with this cell, which will set all parts of image view cell.gameVariant = gameVariant //set the level let level = getGameLevel(game: game) let objective = getGameObjective(gameVariant: gameVariant) cell.level.text = String(describing: level) cell.objective.text = objective.description if objective.reward < 1 { cell.reward.text = "Unlockable at higher level!" } else { cell.reward.text = "\(objective.reward) Essence" } //if numTermsLoaded is zero, make start mission button disabled cell.startMissionButton.setTitleColor(UIColor.white, for: .normal) cell.startMissionButton.setTitleColor(UIColor.gray, for: .disabled) cell.startMissionButton.setTitle("Start Mission", for: .normal) cell.startMissionButton.setTitle("Load Terms to Enable Mission", for: .disabled) //this formatting approach adapted from http://stackoverflow.com/questions/6178545/adjust-uibutton-font-size-to-width cell.startMissionButton.titleLabel?.numberOfLines = 2 cell.startMissionButton.titleLabel?.adjustsFontSizeToFitWidth = true cell.startMissionButton.titleLabel?.lineBreakMode = NSLineBreakMode.byWordWrapping cell.startMissionButton.titleLabel?.textAlignment = NSTextAlignment.center if getNumTermsLoaded() < 1 { cell.startMissionButton.isEnabled = false cell.startMissionButton.alpha = 0.7 } else { cell.startMissionButton.isEnabled = true cell.startMissionButton.alpha = 1.0 } return cell } //When a user selects an item from the collection override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { return } override func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) { return } /******************************************************/ /*******************///MARK: Game level and objectives /******************************************************/ func increaseGameLevel(of game: Game) { if let fc = frcDict[keyGameLevel] { if (fc.sections?.count)! > 0, let gameLevels = fc.fetchedObjects as? [GameLevel]{ for gameLevel in gameLevels { if gameLevel.gameId == Int64(game.id) { //update this record to the next game level and return gameLevel.level += 1 return } } //if didn't find at end of loop, must not be an entry, so create one at level 1 _ = GameLevel(gameId: game.id, level: 1, context: fc.managedObjectContext) return } else { return } } else { return } } func decreaseGameLevel(of game: Game) { if let fc = frcDict[keyGameLevel] { if (fc.sections?.count)! > 0, let gameLevels = fc.fetchedObjects as? [GameLevel]{ for gameLevel in gameLevels { if gameLevel.gameId == Int64(game.id) { //update this record to the next game level and return gameLevel.level -= 2 //don't let level go below 0 if gameLevel.level < 0 { gameLevel.level = 0 } return } } //if didn't find at end of loop, must not be an entry, so create one at level 0 _ = GameLevel(gameId: game.id, level: 0, context: fc.managedObjectContext) return } else { return } } else { return } } /** check records to see if this game has an indicated level and return it or 0 */ func getGameLevel(game: Game) -> Int { if let fc = frcDict[keyGameLevel] { if (fc.sections?.count)! > 0, let gameLevels = fc.fetchedObjects as? [GameLevel]{ for gameLevel in gameLevels { if gameLevel.gameId == Int64(game.id) { return Int(gameLevel.level) } } //if didn't find at end of loop, must not be an entry, so level 0 return 0 } else { return 0 } } else { return 0 } } //TODO: make following function return something that conforms with GameObjective protocol func getGameObjective(gameVariant: GameVariant) -> GameObjective { //check for the variant switch gameVariant.gameProtocol { case GameVariantProtocols.MaxPoints: return getGameObjectiveMaxPoints(game: gameVariant.game) case GameVariantProtocols.PerfectGame: return getGameObjectivePerfectScore(game: gameVariant.game) default: fatalError("Asked for a game variant that doesn't exist") } } /** Based on the level of the game, develop some objectives and return */ func getGameObjectiveMaxPoints(game: Game) -> GameObjectiveMaxPoints { //TODO: Impliment fibonnaci method let gameLevel = getGameLevel(game: game) let maxPoints = gameLevel + 5 let minPoints = -5 let description = "Achieve a score of \(maxPoints) points!" let reward = 0 let objective = GameObjectiveMaxPoints() objective.maxPoints = maxPoints objective.minPoints = minPoints objective.description = description objective.reward = reward return objective } func getGameObjectivePerfectScore(game: Game) -> GameObjectivePerfectScore { //TODO: Impliment fibonnaci method let gameLevel = getGameLevel(game: game) let maxPoints = gameLevel + 5 var missedPointsAllowed = 15 - gameLevel if missedPointsAllowed < 1 { missedPointsAllowed = 1 } //make sure missed points is greater than 1 let description = "Achieve a score of \(maxPoints) points... but don't get \(missedPointsAllowed) wrong!" let reward = 0 let objective = GameObjectivePerfectScore() objective.maxPoints = maxPoints objective.missedPoints = missedPointsAllowed objective.description = description objective.reward = reward return objective } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } protocol GameObjectiveProtocol: class { var maxPoints: Int {get set} var description: String {get set} var reward: Int {get set} } class GameObjective: GameObjectiveProtocol { var maxPoints: Int = 0 var description: String = "" var reward: Int = 0 } class GameObjectiveMaxPoints: GameObjective { //var maxPoints: Int = 0 var minPoints: Int = -1 //var description: String = "" //var reward: Int = 0 } class GameObjectivePerfectScore: GameObjective { //var maxPoints: Int = 0 var missedPoints: Int = -1 //var description: String = "" //var reward: Int = 0 }
cb3a0de08edd8cc071b5b38366f3a1d0
34.525301
198
0.559655
false
false
false
false
JGiola/swift
refs/heads/main
validation-test/stdlib/ArrayTrapsObjC.swift
apache-2.0
9
// RUN: %empty-directory(%t) // RUN: %target-build-swift %s -o %t/a.out_Debug -Onone -swift-version 4.2 && %target-codesign %t/a.out_Debug && %target-run %t/a.out_Debug // RUN: %target-build-swift %s -o %t/a.out_Release -O -swift-version 4.2 && %target-codesign %t/a.out_Release && %target-run %t/a.out_Release // REQUIRES: executable_test // REQUIRES: objc_interop // Temporarily disable for backdeployment (rdar://89821303) // UNSUPPORTED: use_os_stdlib import StdlibUnittest import Foundation let testSuiteSuffix = _isDebugAssertConfiguration() ? "_debug" : "_release" var ArrayTraps = TestSuite("ArrayTraps" + testSuiteSuffix) class Base { } class Derived : Base { } class Derived2 : Derived { } ArrayTraps.test("downcast1") .skip(.custom( { _isFastAssertConfiguration() }, reason: "this trap is not guaranteed to happen in -Ounchecked")) .code { let ba: [Base] = [ Derived(), Base() ] let da = ba as! [Derived] _ = da[0] expectCrashLater() _ = da[1] } ArrayTraps.test("downcast2") .skip(.custom( { _isFastAssertConfiguration() }, reason: "this trap is not guaranteed to happen in -Ounchecked")) .code { let a: [AnyObject] = ["String" as NSString, 1 as NSNumber] let sa = a as! [NSString] _ = sa[0] expectCrashLater() _ = sa[1] } ArrayTraps.test("downcast3") .skip(.custom( { _isFastAssertConfiguration() }, reason: "this trap is not guaranteed to happen in -Ounchecked")) .code { let ba: [Base] = [ Derived2(), Derived(), Base() ] let d2a = ba as! [Derived2] _ = d2a[0] let d1a = d2a as [Derived] _ = d1a[0] _ = d1a[1] expectCrashLater() _ = d1a[2] } @objc protocol ObjCProto { } class ObjCBase : NSObject, ObjCProto { } class ObjCDerived : ObjCBase { } ArrayTraps.test("downcast4") .skip(.custom( { _isFastAssertConfiguration() }, reason: "this trap is not guaranteed to happen in -Ounchecked")) .code { let ba: [ObjCProto] = [ ObjCDerived(), ObjCBase() ] let da = ba as! [ObjCDerived] _ = da[0] expectCrashLater() _ = da[1] } ArrayTraps.test("bounds_with_downcast") .skip(.custom( { _isFastAssertConfiguration() }, reason: "this trap is not guaranteed to happen in -Ounchecked")) .crashOutputMatches(_isDebugAssertConfiguration() ? "Fatal error: Index out of range" : "") .code { let ba: [Base] = [ Derived(), Base() ] let da = ba as! [Derived] expectCrashLater() _ = da[2] } func hasBackdeployedConcurrencyRuntime() -> Bool { // If the stdlib we've loaded predates Swift 5.5, then we're running on a back // deployed concurrency runtime, which has the side effect of disabling // regular runtime exclusivity checks. // // This makes the two tests below fall back to older, higher-level exclusivity // checks in the stdlib, which will still trap, but with a different message. if #available(SwiftStdlib 5.5, *) { return false } // recent enough production stdlib if #available(SwiftStdlib 9999, *) { return false } // dev stdlib return true } var ArraySemanticOptzns = TestSuite("ArraySemanticOptzns" + testSuiteSuffix) class BaseClass { } class ElementClass : BaseClass { var val: String init(_ x: String) { val = x } } class ViolateInoutSafetySwitchToObjcBuffer { final var anArray: [ElementClass] = [] let nsArray = NSArray( objects: ElementClass("a"), ElementClass("b"), ElementClass("c")) @inline(never) func accessArrayViaInoutViolation() { anArray = nsArray as! [ElementClass] } @inline(never) func runLoop(_ A: inout [ElementClass]) { // Simulate what happens if we hoist array properties out of a loop and the // loop calls a function that violates inout safety and overrides the array. let isNativeTypeChecked = A._hoistableIsNativeTypeChecked() for i in 0..<A.count { // Note: the compiler is sometimes able to eliminate this // `_checkSubscript` call when optimizations are enabled, skipping the // exclusivity check contained within. let t = A._checkSubscript( i, wasNativeTypeChecked: isNativeTypeChecked) _ = A._getElement( i, wasNativeTypeChecked: isNativeTypeChecked, matchingSubscriptCheck: t) accessArrayViaInoutViolation() } } @inline(never) func inoutViolation() { anArray = [ ElementClass("1"), ElementClass("2"), ElementClass("3") ] runLoop(&anArray) } } ArraySemanticOptzns.test("inout_rule_violated_isNativeBuffer") .skip(.custom( { !_isDebugAssertConfiguration() }, reason: "this trap is not guaranteed to happen in -O or -Ounchecked")) .crashOutputMatches( hasBackdeployedConcurrencyRuntime() ? "inout rules were violated" : "Fatal access conflict detected." ) .code { let v = ViolateInoutSafetySwitchToObjcBuffer() expectCrashLater() v.inoutViolation() } class ViolateInoutSafetyNeedElementTypeCheck { final var anArray : [ElementClass] = [] @inline(never) func accessArrayViaInoutViolation() { // Overwrite the array with one that needs an element type check. let ba: [BaseClass] = [ BaseClass(), BaseClass() ] anArray = ba as! [ElementClass] } @inline(never) func runLoop(_ A: inout [ElementClass]) { // Simulate what happens if we hoist array properties out of a loop and the // loop calls a function that violates inout safety and overrides the array. let isNativeTypeChecked = A._hoistableIsNativeTypeChecked() for i in 0..<A.count { // Note: the compiler is sometimes able to eliminate this // `_checkSubscript` call when optimizations are enabled, skipping the // exclusivity check contained within. let t = A._checkSubscript( i, wasNativeTypeChecked: isNativeTypeChecked) _ = A._getElement( i, wasNativeTypeChecked: isNativeTypeChecked, matchingSubscriptCheck: t) accessArrayViaInoutViolation() } } @inline(never) func inoutViolation() { anArray = [ ElementClass("1"), ElementClass("2"), ElementClass("3")] runLoop(&anArray) } } ArraySemanticOptzns.test("inout_rule_violated_needsElementTypeCheck") .skip(.custom( { !_isDebugAssertConfiguration() }, reason: "this trap is not guaranteed to happen in -O or -Ounchecked")) .crashOutputMatches( hasBackdeployedConcurrencyRuntime() ? "inout rules were violated" : "Fatal access conflict detected." ) .code { let v = ViolateInoutSafetyNeedElementTypeCheck() expectCrashLater() v.inoutViolation() } runAllTests()
50f3ebc05dfcb7eb6fee484a389eea1e
29.495283
141
0.683217
false
true
false
false
sanekgusev/xkcd-swift
refs/heads/master
src/Services/Implementations/ImageNetworkingServiceImpl.swift
mit
1
// // ComicImageNetworkingServiceImpl.swift // xkcd-swift // // Created by Aleksandr Gusev on 2/17/15. // // import Foundation import ReactiveCocoa final class ImageNetworkingServiceImpl: NSObject, ImageNetworkingService { private let URLSessionConfiguration: NSURLSessionConfiguration private let completionQueueQualityOfService: NSQualityOfService private lazy var URLSession: NSURLSession = { let completionQueue = NSOperationQueue() completionQueue.qualityOfService = self.completionQueueQualityOfService completionQueue.name = "com.sanekgusev.xkcd.ComicImageNetworkingServiceImpl.completionQueue" return NSURLSession(configuration: self.URLSessionConfiguration, delegate: nil, delegateQueue: completionQueue) }() init(URLSessionConfiguration: NSURLSessionConfiguration, completionQueueQualityOfService: NSQualityOfService) { self.URLSessionConfiguration = URLSessionConfiguration self.completionQueueQualityOfService = completionQueueQualityOfService } func downloadImageForURL(imageURL: NSURL) -> SignalProducer<FileURL, ImageNetworkingServiceError> { let URLRequest = NSURLRequest(URL:imageURL) return SignalProducer { observer, disposable in let downloadTask = self.URLSession.downloadTaskWithRequest(URLRequest, completionHandler: { url, response, error in guard !disposable.disposed else { return } switch (url, response, error) { case (let url?, _, _): observer.sendNext(url) observer.sendCompleted() case (_, _?, let error): observer.sendFailed(.ServerError(underlyingError:error)) case (_, _, let error): observer.sendFailed(.NetworkError(underlyingError:error)) } }) disposable += ActionDisposable { [weak downloadTask] in downloadTask?.cancel() } downloadTask.resume() } } }
2228e113837181a0dc4de20f461c7053
40.196429
103
0.602775
false
true
false
false
maxbritto/cours-ios11-swift4
refs/heads/master
Apprendre/Objectif 3/LifeGoals/LifeGoals/GoalManager.swift
apache-2.0
1
// // GoalManager.swift // LifeGoals // // Created by Maxime Britto on 31/07/2017. // Copyright © 2017 Purple Giraffe. All rights reserved. // import Foundation class GoalManager { private let GOAL_LIST_KEY = "GoalList" private var _goalList:[String] init() { if let loadedGoalList = UserDefaults.standard.array(forKey: GOAL_LIST_KEY) as? [String] { _goalList = loadedGoalList } else { _goalList = [] } } func getGoalCount() -> Int { return _goalList.count } func getGoal(atIndex index:Int) -> String { return _goalList[index] } func addGoal(withText text:String) -> Int? { let newIndex:Int? if text.count > 0 { _goalList.append(text) newIndex = _goalList.count - 1 UserDefaults.standard.set(_goalList, forKey: GOAL_LIST_KEY) } else { newIndex = nil } return newIndex } func removeGoal(atIndex index:Int) { _goalList.remove(at: index) UserDefaults.standard.set(_goalList, forKey: GOAL_LIST_KEY) } }
9259ffc6c88ff124ea65484d9e5d9708
23.891304
97
0.570306
false
false
false
false
DrabWeb/Komikan
refs/heads/master
Komikan/Komikan/KMAddMangaViewController.swift
gpl-3.0
1
// // KMAddMangaViewController.swift // Komikan // // Created by Seth on 2016-01-03. // import Cocoa class KMAddMangaViewController: NSViewController { // The visual effect view for the background of the window @IBOutlet weak var backgroundVisualEffectView: NSVisualEffectView! // The manga we will send back var newManga : KMManga = KMManga(); // An array to store all the manga we want to batch open, if thats what we are doing var newMangaMultiple : [KMManga] = [KMManga()]; // The NSTimer to update if we can add the manga with our given values var addButtonUpdateLoop : Timer = Timer(); // Does the user want to batch add them? var addingMultiple : Bool = false; /// The image view for the cover image @IBOutlet weak var coverImageView: NSImageView! /// The token text field for the mangas title @IBOutlet weak var titleTokenTextField: KMSuggestionTokenField! /// The token text field for the mangas series @IBOutlet weak var seriesTokenTextField: KMSuggestionTokenField! /// The token text field for the mangas artist @IBOutlet weak var artistTokenTextField: KMSuggestionTokenField! /// The token text field for the mangas writer @IBOutlet weak var writerTokenTextField: KMSuggestionTokenField! /// The text field for the mangas tags @IBOutlet weak var tagsTextField: KMAlwaysActiveTextField! /// The token text field for the mangas group @IBOutlet weak var groupTokenTextField: KMSuggestionTokenField! /// The text field for setting the manga's release date(s) @IBOutlet var releaseDateTextField: KMAlwaysActiveTextField! /// The date formatter for releaseDateTextField @IBOutlet var releaseDateTextFieldDateFormatter: DateFormatter! /// The checkbox to say if this manga is l-lewd... @IBOutlet weak var llewdCheckBox: NSButton! /// The button to say if the manga we add should be favourited @IBOutlet weak var favouriteButton: KMFavouriteButton! /// The open panel to let the user choose the mangas directory var chooseDirectoryOpenPanel : NSOpenPanel = NSOpenPanel(); /// The "Choose Directory" button @IBOutlet weak var chooseDirectoryButton: NSButton! /// When we click chooseDirectoryButton... @IBAction func chooseDirectoryButtonPressed(_ sender: AnyObject) { // Run he choose directory open panel chooseDirectoryOpenPanel.runModal(); } /// The add button @IBOutlet weak var addButton: NSButton! /// When we click the add button... @IBAction func addButtonPressed(_ sender: AnyObject) { // Dismiss the popver self.dismiss(self); // Add the manga we described in the open panel addSelf(); } /// The URLs of the files we are adding var addingMangaURLs : [URL] = []; /// The local key down monitor var keyDownMonitor : AnyObject?; override func viewDidLoad() { super.viewDidLoad() // Do view setup here. // Style the window styleWindow(); // Update the favourite button favouriteButton.updateButton(); // Setup the choose directory open panel // Allow multiple files chooseDirectoryOpenPanel.allowsMultipleSelection = true; // Only allow CBZ, CBR, ZIP, RAR and Folders chooseDirectoryOpenPanel.allowedFileTypes = ["cbz", "cbr", "zip", "rar"]; chooseDirectoryOpenPanel.canChooseDirectories = true; // Set the Open button to say choose chooseDirectoryOpenPanel.prompt = "Choose"; // Setup all the suggestions for the property text fields seriesTokenTextField.suggestions = (NSApplication.shared().delegate as! AppDelegate).mangaGridController.allSeries(); artistTokenTextField.suggestions = (NSApplication.shared().delegate as! AppDelegate).mangaGridController.allArtists(); writerTokenTextField.suggestions = (NSApplication.shared().delegate as! AppDelegate).mangaGridController.allWriters(); groupTokenTextField.suggestions = (NSApplication.shared().delegate as! AppDelegate).mangaGridController.allGroups(); // Start a 0.1 second loop that will set if we can add this manga or not addButtonUpdateLoop = Timer.scheduledTimer(timeInterval: TimeInterval(0.1), target: self, selector: #selector(KMAddMangaViewController.updateAddButton), userInfo: nil, repeats: true); // Prompt for a manga startPrompt(); } func addSelf() { // If we are only adding one... if(!addingMultiple) { // Set the new mangas cover image newManga.coverImage = coverImageView.image!; // Resize the cover image to be compressed for faster loading newManga.coverImage = newManga.coverImage.resizeToHeight(400); // Set the new mangas title newManga.title = titleTokenTextField.stringValue; // Set the new mangas series newManga.series = seriesTokenTextField.stringValue; // Set the new mangas artist newManga.artist = artistTokenTextField.stringValue; // If the release date field isnt blank... if(releaseDateTextField.stringValue != "") { // Set the release date newManga.releaseDate = releaseDateTextFieldDateFormatter.date(from: releaseDateTextField.stringValue)!; } // Set if the manga is l-lewd... newManga.lewd = Bool(llewdCheckBox.state as NSNumber); // Set the new mangas directory newManga.directory = (addingMangaURLs[0].absoluteString.removingPercentEncoding!).replacingOccurrences(of: "file://", with: ""); // Set the new mangas writer newManga.writer = writerTokenTextField.stringValue; // For every part of the tags text field's string value split at every ", "... for (_, currentTag) in tagsTextField.stringValue.components(separatedBy: ", ").enumerated() { // Print to the log what tag we are adding and what manga we are adding it to print("KMAddMangaViewController: Adding tag \"" + currentTag + "\" to \"" + newManga.title + "\""); // Append the current tags to the mangas tags newManga.tags.append(currentTag); } // Set the new manga's group newManga.group = groupTokenTextField.stringValue; // Set if the manga is a favourite newManga.favourite = Bool(favouriteButton.state as NSNumber); // Post the notification saying we are done and sending back the manga NotificationCenter.default.post(name: Notification.Name(rawValue: "KMAddMangaViewController.Finished"), object: newManga); } else { for (_, currentMangaURL) in addingMangaURLs.enumerated() { // A temporary variable for storing the manga we are currently working on var currentManga : KMManga = KMManga(); // Set the new mangas directory currentManga.directory = (currentMangaURL.absoluteString).removingPercentEncoding!.replacingOccurrences(of: "file://", with: ""); // Get the information of the manga(Cover image, title, ETC.)(Change this function to be in KMManga) currentManga = getMangaInfo(currentManga); // Set the manga's series currentManga.series = seriesTokenTextField.stringValue; // Set the manga's artist currentManga.artist = artistTokenTextField.stringValue; // Set the manga's writer currentManga.writer = writerTokenTextField.stringValue; // If the release date field isnt blank... if(releaseDateTextField.stringValue != "") { // Set the release date currentManga.releaseDate = releaseDateTextFieldDateFormatter.date(from: releaseDateTextField.stringValue)!; } // Set if the manga is l-lewd... currentManga.lewd = Bool(llewdCheckBox.state as NSNumber); // For every part of the tags text field's string value split at every ", "... for (_, currentTag) in tagsTextField.stringValue.components(separatedBy: ", ").enumerated() { // Print to the log what tag we are adding and what manga we are adding it to print("KMAddMangaViewController: Adding tag \"" + currentTag + "\" to \"" + newManga.title + "\""); // Append the current tags to the mangas tags currentManga.tags.append(currentTag); } // Set the manga's group currentManga.group = groupTokenTextField.stringValue; // Set if the manga is a favourite currentManga.favourite = Bool(favouriteButton.state as NSNumber); // Add curentManga to the newMangaMultiple array newMangaMultiple.append(currentManga); } // Remove the first element in newMangaMultiple, for some reason its always empty newMangaMultiple.remove(at: 0); // Post the notification saying we are done and sending back the manga NotificationCenter.default.post(name: Notification.Name(rawValue: "KMAddMangaViewController.Finished"), object: newMangaMultiple); } } /// DId the user specify a custom title in the JSON? var gotTitleFromJSON : Bool = false; /// Did the user specify a custom cover image in the JSON? var gotCoverImageFromJSON : Bool = false; /// Gets the data from the optional JSON file that contains metadata info func fetchJsonData() { // If we actually selected anything... if(addingMangaURLs != []) { // Print to the log that we are fetching the JSON data print("KMAddMangaViewController: Fetching JSON data..."); /// The selected Mangas folder it is in var folderURLString : String = (addingMangaURLs.first?.absoluteString)!; // Remove everything after the last "/" in the string so we can get the folder folderURLString = folderURLString.substring(to: folderURLString.range(of: "/", options: NSString.CompareOptions.backwards, range: nil, locale: nil)!.lowerBound); // Append a slash to the end because it removes it folderURLString += "/"; // Remove the file:// from the folder URL string folderURLString = folderURLString.replacingOccurrences(of: "file://", with: ""); // Remove the percent encoding from the folder URL string folderURLString = folderURLString.removingPercentEncoding!; // Add the "Komikan" folder to the end of it folderURLString += "Komikan/" // If we chose multiple manga... if(addingMangaURLs.count > 1) { /// The URL of the multiple Manga's possible JSON file let mangaJsonURL : String = folderURLString + "series.json"; // If there is a "series.json" file in the Manga's folder... if(FileManager.default.fileExists(atPath: mangaJsonURL)) { // Print to the log that we found the JSON file for the selected manga print("KMAddMangaViewController: Found a series.json file for the selected Manga at \"" + mangaJsonURL + "\""); /// The SwiftyJSON object for the Manga's JSON info let mangaJson = JSON(data: FileManager.default.contents(atPath: mangaJsonURL)!); // Set the series text field's value to the series value seriesTokenTextField.stringValue = mangaJson["series"].stringValue; // Set the series text field's value to the artist value artistTokenTextField.stringValue = mangaJson["artist"].stringValue; // Set the series text field's value to the writer value writerTokenTextField.stringValue = mangaJson["writer"].stringValue; // If there is a released value... if(mangaJson["published"].exists()) { // If there is a release date listed... if(mangaJson["published"].stringValue.lowercased() != "unknown" && mangaJson["published"].stringValue != "") { // If the release date is valid... if(releaseDateTextFieldDateFormatter.date(from: mangaJson["published"].stringValue) != nil) { // Set the release date text field's value to the release date value releaseDateTextField.stringValue = releaseDateTextFieldDateFormatter.string(from: (releaseDateTextFieldDateFormatter.date(from: mangaJson["published"].stringValue)!)); } } } // For every item in the tags value of the JSON... for(_, currentTag) in mangaJson["tags"].arrayValue.enumerated() { // Print the current tag print("KMAddMangaViewController: Found tag \"" + currentTag.stringValue + "\""); // Add the current item to the tag text field tagsTextField.stringValue += currentTag.stringValue + ", "; } // If the tags text field is not still blank... if(tagsTextField.stringValue != "") { // Remove the extra ", " from the tags text field tagsTextField.stringValue = tagsTextField.stringValue.substring(to: tagsTextField.stringValue.index(before: tagsTextField.stringValue.characters.index(before: tagsTextField.stringValue.endIndex))); } // Set the group text field's value to the group value groupTokenTextField.stringValue = mangaJson["group"].stringValue; // Set the favourites buttons value to the favourites value of the JSON favouriteButton.state = Int.fromBool(bool: mangaJson["favourite"].boolValue); // Update the favourites button favouriteButton.updateButton(); // Set the l-lewd... checkboxes state to the lewd value of the JSON llewdCheckBox.state = Int.fromBool(bool: mangaJson["lewd"].boolValue); } } // If we chose 1 manga... else if(addingMangaURLs.count == 1) { /// The URL to the single Manga's possible JSON file let mangaJsonURL : String = folderURLString + (addingMangaURLs.first?.lastPathComponent.removingPercentEncoding!)! + ".json"; // If there is a file that has the same name but with a .json on the end... if(FileManager.default.fileExists(atPath: mangaJsonURL)) { // Print to the log that we found the JSON file for the single manga print("KMAddMangaViewController: Found single Manga's JSON file at \"" + mangaJsonURL + "\""); /// The SwiftyJSON object for the Manga's JSON info let mangaJson = JSON(data: FileManager.default.contents(atPath: mangaJsonURL)!); // If the title value from the JSON is not "auto" or blank... if(mangaJson["title"].stringValue != "auto" && mangaJson["title"].stringValue != "") { // Set the title text fields value to the title value from the JSON titleTokenTextField.stringValue = mangaJson["title"].stringValue; // Say we got a title from the JSON gotTitleFromJSON = true; } // If the cover image value from the JSON is not "auto" or blank... if(mangaJson["cover-image"].stringValue != "auto" && mangaJson["cover-image"].stringValue != "") { // If the first character is not a "/"... if(mangaJson["cover-image"].stringValue.substring(to: mangaJson["cover-image"].stringValue.characters.index(after: mangaJson["cover-image"].stringValue.startIndex)) == "/") { // Set the cover image views image to an NSImage at the path specified in the JSON coverImageView.image = NSImage(contentsOf: URL(fileURLWithPath: mangaJson["cover-image"].stringValue)); // Say we got a cover image from the JSON gotCoverImageFromJSON = true; } else { // Get the relative image coverImageView.image = NSImage(contentsOf: URL(fileURLWithPath: folderURLString + mangaJson["cover-image"].stringValue)); // Say we got a cover image from the JSON gotCoverImageFromJSON = true; } } // Set the series text field's value to the series value seriesTokenTextField.stringValue = mangaJson["series"].stringValue; // Set the series text field's value to the artist value artistTokenTextField.stringValue = mangaJson["artist"].stringValue; // Set the series text field's value to the writer value writerTokenTextField.stringValue = mangaJson["writer"].stringValue; // If there is a released value... if(mangaJson["published"].exists()) { // If there is a release date listed... if(mangaJson["published"].stringValue.lowercased() != "unknown" && mangaJson["published"].stringValue != "") { // If the release date is valid... if(releaseDateTextFieldDateFormatter.date(from: mangaJson["published"].stringValue) != nil) { // Set the release date text field's value to the release date value releaseDateTextField.stringValue = releaseDateTextFieldDateFormatter.string(from: (releaseDateTextFieldDateFormatter.date(from: mangaJson["published"].stringValue)!)); } } } // For every item in the tags value of the JSON... for(_, currentTag) in mangaJson["tags"].arrayValue.enumerated() { // Print the current tag print("KMAddMangaViewController: Found tag \"" + currentTag.stringValue + "\""); // Add the current item to the tag text field tagsTextField.stringValue += currentTag.stringValue + ", "; } // If the tags text field is not still blank... if(tagsTextField.stringValue != "") { // Remove the extra ", " from the tags text field tagsTextField.stringValue = tagsTextField.stringValue.substring(to: tagsTextField.stringValue.index(before: tagsTextField.stringValue.characters.index(before: tagsTextField.stringValue.endIndex))); } // Set the group text field's value to the group value groupTokenTextField.stringValue = mangaJson["group"].stringValue; // Set the favourites buttons value to the favourites value of the JSON favouriteButton.state = Int.fromBool(bool: mangaJson["favourite"].boolValue); // Update the favourites button favouriteButton.updateButton(); // Set the l-lewd... checkboxes state to the lewd value of the JSON llewdCheckBox.state = Int.fromBool(bool: mangaJson["lewd"].boolValue); } } } } // Updates the add buttons enabled state func updateAddButton() { // A variable to say if we can add the manga with the given values var canAdd : Bool = false; // If we are only adding one... if(!addingMultiple) { // If the cover image selected is not the default one... if(coverImageView.image != NSImage(named: "NSRevealFreestandingTemplate")) { // If the title is not nothing... if(titleTokenTextField.stringValue != "") { // If the directory is not nothing... if(addingMangaURLs != []) { // Say we can add with these variables canAdd = true; } } } } else { // Say we can add canAdd = true; } // If we can add with these variables... if(canAdd) { // Enable the add button addButton.isEnabled = true; } else { // Disable the add button addButton.isEnabled = false; } } func getMangaInfo(_ manga : KMManga) -> KMManga { // Set the mangas title to the mangas archive name manga.title = KMFileUtilities().getFileNameWithoutExtension(manga.directory); // Delete /tmp/komikan/addmanga, if it exists do { // Remove /tmp/komikan/addmanga try FileManager().removeItem(atPath: "/tmp/komikan/addmanga"); // Print to the log that we deleted it print("KMAddMangaViewController: Deleted /tmp/komikan/addmanga folder for \"" + manga.title + "\""); // If there is an error... } catch _ as NSError { // Print to the log that there is no /tmp/komikan/addmanga folder to delete print("KMAddMangaViewController: No /tmp/komikan/addmanga to delete for \"" + manga.title + "\""); } // If the manga's file isnt a folder... if(!KMFileUtilities().isFolder(manga.directory.replacingOccurrences(of: "file://", with: ""))) { // Extract the passed manga to /tmp/komikan/addmanga KMFileUtilities().extractArchive(manga.directory.replacingOccurrences(of: "file://", with: ""), toDirectory: "/tmp/komikan/addmanga"); } // If the manga's file is a folder... else { // Copy the folder to /tmp/komikan/addmanga do { try FileManager.default.copyItem(atPath: manga.directory.replacingOccurrences(of: "file://", with: ""), toPath: "/tmp/komikan/addmanga"); } catch _ as NSError { } } // Clean up the directory print("KMAddMangaViewController: \(KMCommandUtilities().runCommand(Bundle.main.bundlePath + "/Contents/Resources/cleanmangadir", arguments: ["/tmp/komikan/addmanga"], waitUntilExit: true))"); /// All the files in /tmp/komikan/addmanga var addMangaFolderContents : [String] = []; // Get the contents of /tmp/komikan/addmanga do { // Set addMangaFolderContents to all the files in /tmp/komikan/addmanga addMangaFolderContents = try FileManager().contentsOfDirectory(atPath: "/tmp/komikan/addmanga"); // Sort the files by their integer values addMangaFolderContents = (addMangaFolderContents as NSArray).sortedArray(using: [NSSortDescriptor(key: "integerValue", ascending: true)]) as! [String]; } catch _ as NSError { // Do nothing } // Get the first image in the folder, and set the cover image selection views image to it // The first item in /tmp/komikan/addmanga var firstImage : NSImage = NSImage(); // For every item in the addmanga folder... for(_, currentFile) in addMangaFolderContents.enumerated() { // If this file is an image and not a dot file... if(KMFileUtilities().isImage("/tmp/komikan/addmanga/" + (currentFile )) && ((currentFile).substring(to: (currentFile).characters.index(after: (currentFile).startIndex))) != ".") { // If the first image isnt already set... if(firstImage.size == NSSize.zero) { // Set the first image to the current image file firstImage = NSImage(contentsOfFile: "/tmp/komikan/addmanga/\(currentFile)")!; } } } // Set the cover image selecting views image to firstImage manga.coverImage = firstImage; // Resize the cover image to be compressed for faster loading manga.coverImage = manga.coverImage.resizeToHeight(400); // Print the image to the log(It for some reason needs this print or it wont work) print("KMAddMangaViewController: \(firstImage)"); // Return the changed manga return manga; } // Asks for a manga, and deletes the old ones tmp folder func promptForManga() { // Delete /tmp/komikan/addmanga do { // Remove /tmp/komikan/addmanga try FileManager().removeItem(atPath: "/tmp/komikan/addmanga"); // If there is an error... } catch _ as NSError { // Do nothing } // Ask for the manga's directory, and if we clicked "Choose"... if(Bool(chooseDirectoryOpenPanel.runModal() as NSNumber)) { // Set the adding manga URLs to the choose directory open panels URLs addingMangaURLs = chooseDirectoryOpenPanel.urls; } } // The prompt you get when you open this view with the open panel func startPrompt() { // If addingMangaURLs is []... if(addingMangaURLs == []) { // Prompt for a file promptForManga(); } // Fetch the JSON data fetchJsonData(); // Subscribe to the key down event keyDownMonitor = NSEvent.addLocalMonitorForEvents(matching: NSEventMask.keyDown, handler: keyHandler) as AnyObject?; // If we selected multiple files... if(addingMangaURLs.count > 1) { // Say we are adding multiple addingMultiple = true; // Say we cant edit the image view coverImageView.isEditable = false; // Dont allow us to set the title titleTokenTextField.isEnabled = false; // Dont allow us to change the directory chooseDirectoryButton.isEnabled = false; // Set the cover image image views image to NSFlowViewTemplate coverImageView.image = NSImage(named: "NSFlowViewTemplate"); } else { // If the directory is not nothing... if(addingMangaURLs != []) { // Set the new mangas directory newManga.directory = addingMangaURLs[0].absoluteString.removingPercentEncoding!; // Get the information of the manga(Cover image, title, ETC.)(Change this function to be in KMManga) newManga = getMangaInfo(newManga); // If we didnt get a cover image from the JSON... if(!gotCoverImageFromJSON) { // Set the cover image views cover image coverImageView.image = newManga.coverImage; } // If we didnt get a title from the JSON... if(!gotTitleFromJSON) { // Set the title text fields value to the mangas title titleTokenTextField.stringValue = newManga.title; } } } } func keyHandler(_ event : NSEvent) -> NSEvent { // If we pressed enter... if(event.keyCode == 36 || event.keyCode == 76) { // If the add button is enabled... if(addButton.isEnabled) { // Hide the popover self.dismiss(self); // Add the chosen manga addSelf(); } } // Return the event return event; } override func viewWillDisappear() { // Unsubscribe from key down NSEvent.removeMonitor(keyDownMonitor!); // Stop the add button update loop addButtonUpdateLoop.invalidate(); } func styleWindow() { // Set the background effect view to be dark backgroundVisualEffectView.material = NSVisualEffectMaterial.dark; } }
7d18839ce2521f72f5ba3e4a7f749108
47.162717
221
0.560272
false
false
false
false
cnbin/swiftmi-app
refs/heads/master
swiftmi/swiftmi/LoginController.swift
mit
4
// // LoginController.swift // swiftmi // // Created by yangyin on 15/4/17. // Copyright (c) 2015年 swiftmi. All rights reserved. // import UIKit import Alamofire import SwiftyJSON import Kingfisher class LoginController: UIViewController { @IBOutlet weak var password: UITextField! @IBOutlet weak var username: UITextField! @IBOutlet weak var loginBtn: UIButton! var loadingView:UIActivityIndicatorView? override func viewDidLoad() { super.viewDidLoad() self.title = "登录" self.setView() // Do any additional setup after loading the view. } private func setView(){ self.password.secureTextEntry = true } private func showMsg(msg:String) { var alert = UIAlertView(title: "提醒", message: msg, delegate: nil, cancelButtonTitle: "确定") alert.show() } private func login() { if username.text.isEmpty { showMsg("用户名不能为空") return } if password.text.isEmpty || (password.text as NSString).length<6 { showMsg("密码不能为空且长度大于6位数") return } var loginname = username.text var loginpass = password.text let params = ["username":loginname,"password":loginpass] self.pleaseWait() self.loginBtn.enabled = false self.loginBtn.setTitle("登录ing...", forState: UIControlState.allZeros) Alamofire.request(Router.UserLogin(parameters: params)).responseJSON{ (_,_,json,error) in self.clearAllNotice() self.loginBtn.enabled = true self.loginBtn.setTitle("登录", forState: UIControlState.allZeros) if error != nil { var alert = UIAlertView(title: "网络异常", message: "请检查网络设置", delegate: nil, cancelButtonTitle: "确定") alert.show() return } var result = JSON(json!) if result["isSuc"].boolValue { var user = result["result"] var token = user["token"].stringValue KeychainWrapper.setString(token, forKey: "token") Router.token = token var dalUser = UsersDal() dalUser.deleteAll() var currentUser = dalUser.addUser(user, save: true) self.goToBackView(currentUser!) } else { var errMsg = result["msg"].stringValue var alert = UIAlertView(title: "登录失败", message: "\(errMsg)", delegate: nil, cancelButtonTitle: "确定") alert.show() } } } @IBAction func userLogin(sender: UIButton) { login() } @IBAction func regAction(sender: AnyObject) { var toViewController:RegisterController = Utility.GetViewController("registerController") self.navigationController?.pushViewController(toViewController, animated: true) } private func goToBackView(user:Users) { var desController = self.navigationController?.popViewControllerAnimated(true) } 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. } */ }
758ef0999b8b83f8594c6e8c93979a61
27.789855
116
0.552228
false
false
false
false
krimpedance/KRActivityIndicator
refs/heads/master
KRActivityIndicatorView/Classes/KRActivityIndicatorView.swift
mit
2
// // KRActivityIndicatorView.swift // KRActivityIndicatorView // // Copyright © 2016 Krimpedance. All rights reserved. // import UIKit /// KRActivityIndicatorView is a simple and customizable activity indicator @IBDesignable public final class KRActivityIndicatorView: UIView { private let animationKey = "KRActivityIndicatorViewAnimationKey" private var animationLayer = CALayer() /// Activity indicator's head color (read-only). /// You can set head color from IB. /// If you want to change color from code, use colors property. @IBInspectable public fileprivate(set) var headColor: UIColor { get { return colors.first ?? .black } set { colors = [newValue, tailColor] } } /// Activity indicator's tail color (read-only). /// You can set tail color from IB. /// If you want to change color from code, use colors property. @IBInspectable public fileprivate(set) var tailColor: UIColor { get { return colors.last ?? .black } set { colors = [headColor, newValue] } } /// Number of dots @IBInspectable public var numberOfDots: Int = 8 { didSet { drawIndicatorPath() } } // Duration for one rotation @IBInspectable public var duration: Double = 1.0 { didSet { guard isAnimating else { return } stopAnimating() startAnimating() } } /// Animation of activity indicator when it's shown. @IBInspectable public var animating: Bool = true { didSet { animating ? startAnimating() : stopAnimating() } } /// set `true` to `isHidden` when call `stopAnimating()` @IBInspectable public var hidesWhenStopped: Bool = false { didSet { animationLayer.isHidden = !isAnimating && hidesWhenStopped } } /// Activity indicator gradient colors. public var colors: [UIColor] = [.black, .lightGray] { didSet { drawIndicatorPath() } } /// Whether view performs animation public var isAnimating: Bool { return animationLayer.animation(forKey: animationKey) != nil } // Initializer ---------- public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) layer.addSublayer(animationLayer) } public override init(frame: CGRect) { super.init(frame: frame) backgroundColor = UIColor.clear layer.addSublayer(animationLayer) } /// Initializer public convenience init() { self.init(frame: CGRect(x: 0, y: 0, width: 20, height: 20)) } /// Initializer with colors /// /// - Parameter colors: Activity indicator gradient colors. public convenience init(colors: [UIColor]) { self.init(frame: CGRect(x: 0, y: 0, width: 20, height: 20)) self.colors = colors } // Deprecated ---------- /// Activity indicator color style. @available(*, deprecated) public var style = KRActivityIndicatorViewStyle.gradationColor(head: .black, tail: .lightGray) { didSet { colors = [style.headColor, style.tailColor] } } /// Initialize with style. /// - Parameter style: Activity indicator default color use of KRActivityIndicatorViewStyle @available(*, deprecated) public convenience init(style: KRActivityIndicatorViewStyle) { self.init(colors: [style.headColor, style.tailColor]) } // Lyfecycle ---------- public override func layoutSubviews() { super.layoutSubviews() viewResized() } } // MARK: - Private actions ------------ private extension KRActivityIndicatorView { func viewResized() { animationLayer.frame = layer.bounds animationLayer.isHidden = !isAnimating && hidesWhenStopped drawIndicatorPath() if animating { startAnimating() } } func drawIndicatorPath() { animationLayer.sublayers?.forEach { $0.removeFromSuperlayer() } let width = Double(min(animationLayer.bounds.width, animationLayer.bounds.height)) // 各ドットの直径を求めるためのベースとなる比率 let diff = 0.6 / Double(numberOfDots-1) let baseRatio = 100 / (1.8 * Double(numberOfDots) - Double(numberOfDots * (numberOfDots - 1)) * diff) // ベースとなる円の直径(レイヤー内にドットが収まるように調整する) var diameter = width while true { let circumference = diameter * Double.pi let dotDiameter = baseRatio * 0.9 * circumference / 100 let space = width - diameter - dotDiameter if space > 0 { break } diameter -= 2 } let colors = getGradientColors(dividedIn: numberOfDots) let circumference = diameter * Double.pi let spaceRatio = 50 / Double(numberOfDots) / 100 var degree = Double(20) // 全体を 20° 傾ける (0..<numberOfDots).forEach { let number = Double($0) let ratio = (0.9 - diff * number) * baseRatio / 100 let dotDiameter = circumference * ratio let rect = CGRect( x: (width - dotDiameter) / 2, y: (width - diameter - dotDiameter) / 2, width: dotDiameter, height: dotDiameter ) if number != 0 { let preRatio = (0.9 - diff * (number - 1)) * baseRatio / 100 let arc = (preRatio / 2 + spaceRatio + ratio / 2) * circumference degree += 360 * arc / circumference } let pathLayer = CAShapeLayer() pathLayer.frame.size = CGSize(width: width, height: width) pathLayer.position = animationLayer.position pathLayer.fillColor = colors[$0].cgColor pathLayer.lineWidth = 0 pathLayer.path = UIBezierPath(ovalIn: rect).cgPath pathLayer.setAffineTransform(CGAffineTransform(rotationAngle: CGFloat(-degree) * CGFloat.pi / 180)) animationLayer.addSublayer(pathLayer) } } func getGradientColors(dividedIn num: Int) -> [UIColor] { let gradient = CAGradientLayer() gradient.frame = CGRect(x: 0, y: 0, width: 2, height: (num-1) * 10 + 1) switch colors.count { case 0: gradient.colors = [UIColor.black.cgColor, UIColor.lightGray.cgColor] case 1: gradient.colors = [colors.first!.cgColor, colors.first!.cgColor] default: gradient.colors = colors.map { $0.cgColor } } return (0..<num).map { let point = CGPoint(x: 1, y: 10*CGFloat($0)) return gradient.color(point: point) } } } // MARK: - Public actions ------------------ public extension KRActivityIndicatorView { /// Start animating. func startAnimating() { if animationLayer.animation(forKey: animationKey) != nil { return } let animation = CABasicAnimation(keyPath: "transform.rotation") animation.fromValue = 0 animation.toValue = Double.pi * 2 animation.duration = duration animation.timingFunction = CAMediaTimingFunction(name: .linear) animation.isRemovedOnCompletion = false animation.repeatCount = Float(NSIntegerMax) animation.fillMode = .forwards animation.autoreverses = false animationLayer.isHidden = false animationLayer.add(animation, forKey: animationKey) } /// Stop animating. func stopAnimating() { animationLayer.removeAllAnimations() animationLayer.isHidden = hidesWhenStopped } }
790821c09f43b1503f6e632734ddf967
32.714932
111
0.619514
false
false
false
false
arkverse/J
refs/heads/master
Sources/ExtensionArray.swift
mit
1
// // ExtensionArray.swift // Gloss // // Copyright (c) 2016 Rahul Katariya // // 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: - Decodable public extension Array where Element: Decodable { // MARK: Public functions /** Returns array of new objects created from provided JSON array. If any decodings fail, nil is returned. - parameter jsonArray: Array of JSON representations of objects. - returns: Array of objects created from JSON. */ static func from(jsonArray: [JSON]) throws -> [Element] { var models: [Element] = [] for json in jsonArray { let model = try Element.with(json: json) models.append(model) } return models } /** Initializes array of model objects from provided data. - parameter data: Raw JSON array data. - returns: Array with model objects when decoding is successful, empty otherwise. */ /** Returns array of new objects created from provided data. If creation of JSON or any decodings fail, nil is returned. - parameter data: Raw JSON data. - parameter serializer: Serializer to use when creating JSON from data. - parameter ooptions: Options for reading the JSON data. - returns: Object or nil. */ static func from(data: Data, serializer: JSONSerializer = JJSONSerializer(), options: JSONSerialization.ReadingOptions = .mutableContainers) throws -> [Element] { let jsonValues = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) guard let jsonArray = jsonValues as? [JSON] else { throw JParseError.incorrectType("", jsonValues, [JSON].self, type(of: jsonValues)) } let models = try [Element].from(jsonArray: jsonArray) return models } } // MARK: - Encodable public extension Array where Element: Encodable { // MARK: Public functions /** Encodes array of objects as JSON array. If any encodings fail, nil is returned. - returns: Array of JSON created from objects. */ func toJSONArray() -> [JSON] { var jsonArray: [JSON] = [] for json in self { jsonArray.append(json.toJSON()) } return jsonArray } }
2914542af3a75fb356428d4af9618cc3
31.556604
166
0.657201
false
false
false
false
pushtechnology/diffusion-examples
refs/heads/6.8
apple/ConsumingRecordV2TopicsExample.swift
apache-2.0
1
// Diffusion Client Library for iOS, tvOS and OS X / macOS - Examples // // Copyright (C) 2017, 2020 Push Technology Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation import Diffusion /** This example demonstrates a client consuming RecordV2 topics. It has been contrived to demonstrate the various techniques for Diffusion record topics and is not necessarily realistic or efficient in its processing. It can be run using a schema or not using a schema and demonstrates how the processing could be done in both cases. This makes use of the 'Topics' feature only. To subscribe to a topic, the client session must have the 'select_topic' and 'read_topic' permissions for that branch of the topic tree. This example receives updates to currency conversion rates via a branch of the topic tree where the root topic is called "FX" which under it has a topic for each base currency and under each of those is a topic for each target currency which contains the bid and ask rates. So a topic FX/GBP/USD would contain the rates for GBP to USD. This example maintains a local map of the rates and also notifies a listener of any rates changes. */ public class ClientConsumingRecordV2Topics { private static let rootTopic = "FX" private var subscriber: Subscriber? /** Constructor. @param serverUrl For example "ws://diffusion.example.com" @param listener An object that will be notified of rates and rate changes. @param withSchema Whether schema processing should be used or not. */ init(serverUrl: URL, listener: RatesListener, withSchema: Bool) { let schema = withSchema ? ClientConsumingRecordV2Topics.createSchema() : nil let configuration = PTDiffusionSessionConfiguration( principal: "client", credentials: PTDiffusionCredentials(password: "password")) PTDiffusionSession.open(with: serverUrl, configuration: configuration) { (session, error) in if let connectedSession = session { self.subscriber = Subscriber(connectedSession, listener: listener, schema: schema) } else { print(error!) } } } private class Subscriber { let session: PTDiffusionSession let valueStreamDelegate: ValueStreamDelegate init(_ session: PTDiffusionSession, listener: RatesListener, schema: PTDiffusionRecordV2Schema?) { self.session = session // Use the Topics feature to add a record value stream and subscribe // to all topics under the root. valueStreamDelegate = ValueStreamDelegate( listener: listener, schema: schema) let valueStream = PTDiffusionRecordV2.valueStream( with: valueStreamDelegate) let topics = session.topics let topicSelector = "?" + rootTopic + "//" do { try topics.add(valueStream, withSelectorExpression: topicSelector, error:()) } catch { print("Error while adding stream with selector expression") } topics.subscribe(withTopicSelectorExpression: topicSelector) { (error) in if let subscriptionError = error { print(subscriptionError) } } } } private class ValueStreamDelegate: PTDiffusionRecordV2ValueStreamDelegate { let listener: RatesListener let schema: PTDiffusionRecordV2Schema? var currencies = [String: Currency]() init(listener: RatesListener, schema: PTDiffusionRecordV2Schema?) { self.listener = listener self.schema = schema } func diffusionStream(_ stream: PTDiffusionStream, didSubscribeToTopicPath topicPath: String, specification: PTDiffusionTopicSpecification) { print("Value stream subscribed to topic path: \(topicPath)") } func diffusionStream(_ stream: PTDiffusionValueStream, didUpdateTopicPath topicPath: String, specification: PTDiffusionTopicSpecification, oldRecord: PTDiffusionRecordV2?, newRecord: PTDiffusionRecordV2) { let topicElements = elements(topicPath) // It is only a rate update if topic has 2 elements below root path if topicElements.count == 2 { applyUpdate( currencyCode: topicElements[0], targetCurrencyCode: topicElements[1], oldValue: oldRecord, newValue: newRecord) } } func diffusionStream(_ stream: PTDiffusionStream, didUnsubscribeFromTopicPath topicPath: String, specification: PTDiffusionTopicSpecification, reason: PTDiffusionTopicUnsubscriptionReason) { let topicElements = elements(topicPath) if topicElements.count == 2 { removeRate( currencyCode: topicElements[0], targetCurrencyCode: topicElements[1]) } else if topicElements.count == 1 { removeCurrency(code: topicElements[0]) } } func diffusionDidClose( _ stream: PTDiffusionStream) { print("Value stream closed.") } func diffusionStream( _ stream: PTDiffusionStream, didFailWithError error: Error) { print("Value stream failed: \(error)") } func elements(_ topicPath: String) -> [String] { let prefix = rootTopic + "/" if let prefixRange = topicPath.range(of: prefix) { var subPath = topicPath subPath.removeSubrange(prefixRange) return subPath.components(separatedBy: "/") } return [] } func applyUpdate( currencyCode: String, targetCurrencyCode: String, oldValue: PTDiffusionRecordV2?, newValue: PTDiffusionRecordV2) { let currency = currencies[currencyCode] ?? Currency() currencies[currencyCode] = currency if let schema = self.schema { // Update using Schema. applyUpdate( currencyCode: currencyCode, targetCurrencyCode: targetCurrencyCode, oldValue: oldValue, newValue: newValue, currency: currency, schema: schema) return; } // Update without using Schema. let fields = try! newValue.fields() let bid = fields[0] let ask = fields[1] currency.setRatesForTargetCurrency( code: targetCurrencyCode, bid: bid, ask: ask) if let previousValue = oldValue { // Compare fields individually in order to determine what has // changed. let oldFields = try! previousValue.fields() let oldBid = oldFields[0] let oldAsk = oldFields[1] if bid != oldBid { listener.onRateChange( currency: currencyCode, targetCurrency: targetCurrencyCode, bidOrAsk: "Bid", rate: bid) } if ask != oldAsk { listener.onRateChange( currency: currencyCode, targetCurrency: targetCurrencyCode, bidOrAsk: "Ask", rate: ask) } } else { listener.onNewRate( currency: currencyCode, targetCurrency: targetCurrencyCode, bid: bid, ask: ask) } } func applyUpdate( currencyCode: String, targetCurrencyCode: String, oldValue: PTDiffusionRecordV2?, newValue: PTDiffusionRecordV2, currency: Currency, schema: PTDiffusionRecordV2Schema) { let model = try! newValue.model(with: schema) let bid = try! model.fieldValue(forKey: "Bid") let ask = try! model.fieldValue(forKey: "Ask") currency.setRatesForTargetCurrency( code: targetCurrencyCode, bid: bid, ask: ask) if let previousValue = oldValue { // Generate a structural delta to determine what has changed. let delta = newValue.diff(fromOriginalRecord: previousValue) for change in try! delta.changes(with: schema) { let fieldName = change.fieldName listener.onRateChange( currency: currencyCode, targetCurrency: targetCurrencyCode, bidOrAsk: fieldName, rate: try! model.fieldValue(forKey: fieldName)) } } else { listener.onNewRate( currency: currencyCode, targetCurrency: targetCurrencyCode, bid: bid, ask: ask) } } func removeCurrency(code: String) { if let oldCurrency = currencies.removeValue(forKey: code) { for targetCurrencyCode in oldCurrency.targetCurrencyCodes() { listener.onRateRemoved( currency: code, targetCurrency: targetCurrencyCode) } } } func removeRate(currencyCode: String, targetCurrencyCode: String) { if let currency = currencies.removeValue(forKey: currencyCode) { if currency.removeTargetCurrency(code: targetCurrencyCode) { listener.onRateRemoved( currency: currencyCode, targetCurrency: targetCurrencyCode) } } } } /** Encapsulates a base currency and all of its known rates. */ private class Currency { var rates = [String: (bid: String, ask: String)]() func targetCurrencyCodes() -> [String] { return Array(rates.keys) } func removeTargetCurrency(code: String) -> Bool { return nil != rates.removeValue(forKey: code) } func setRatesForTargetCurrency(code: String, bid: String, ask: String) { rates[code] = (bid: bid, ask: ask) } } /** Create the record schema for the rates topic, with two decimal fields which are maintained to 5 decimal places */ private static func createSchema() -> PTDiffusionRecordV2Schema { return PTDiffusionRecordV2SchemaBuilder() .addRecord(withName: "Rates") .addDecimal(withName: "Bid", scale: 5) .addDecimal(withName: "Ask", scale: 5) .build() } } /** A listener for rates updates. */ public protocol RatesListener { /** Notification of a new rate or rate update. @param currency The base currency. @param targetCurrency The target currency. @param bid Rate. @param ask Rate. */ func onNewRate(currency: String, targetCurrency: String, bid: String, ask: String) /** Notification of a change to the bid or ask value for a rate. @param currency the base currency. @param targetCurrency The target currency. @param bidOrAsk Either "Bid" or "Ask". @param rate The new rate. */ func onRateChange(currency: String, targetCurrency: String, bidOrAsk: String, rate: String) /** Notification of a rate being removed. @param currency The base currency. @param targetCurrency The target currency. */ func onRateRemoved(currency: String, targetCurrency: String) }
2f82205f79da35d79f488efca3d574ac
35.146479
95
0.577307
false
false
false
false
hikelee/hotel
refs/heads/master
Sources/Common/Controllers/HostController.swift
mit
1
import Vapor import HTTP import Foundation final class HostAdminController : HotelBasedController<Host> { typealias M = Host override var path:String {return "/admin/common/host"} override func preSave(request:Request,model:M) throws{ if let hotelId = model.hotelId?.int, let hotel = try Hotel.load(id:hotelId){ model.channelId = hotel.channelId } } override func preUpdate(request:Request,new:M,old:M) throws{ new.ids = old.ids new.lastSyncTime = old.lastSyncTime } override func getModel(request:Request) throws -> M{ let model = try super.getModel(request:request) model.macAddress = model.macAddress?.uppercased() return model } } class HostApiController: Controller { override func makeRouter(){ routerGroup.get("/api/common/ip/sync/"){return try self.sync($0)} routerGroup.post("/api/common/ip/sync/"){return try self.sync($0)} } func sync(_ request: Request) throws -> String { guard let ip = request.data["ip"]?.string else { return "no ip\n" } guard let mac = request.data["mac"]?.string else{ return "no mac address\n" } if try Host.load(macAddress: mac) == nil { return "no host found" } //if host.ipAddress == ip { // return "ok,on-change" //} try Host.sync(macAddress:mac,ipAddress:ip) return "ok\n" } }
ce623b4939e19cd7c8e06f927409bf53
28.88
74
0.60241
false
false
false
false
saurabytes/JSQCoreDataKit
refs/heads/develop
Source/StackResult.swift
mit
1
// // Created by Jesse Squires // http://www.jessesquires.com // // // Documentation // http://www.jessesquires.com/JSQCoreDataKit // // // GitHub // https://github.com/jessesquires/JSQCoreDataKit // // // License // Copyright © 2015 Jesse Squires // Released under an MIT license: http://opensource.org/licenses/MIT // import CoreData import Foundation /** A result object representing the result of creating a `CoreDataStack` via a `CoreDataStackFactory`. */ public enum StackResult: CustomStringConvertible, Equatable { /// The success result, containing the successfully initialized `CoreDataStack`. case success(CoreDataStack) /// The failure result, containing an `NSError` instance that describes the error. case failure(NSError) // MARK: Methods /** - returns: The result's `CoreDataStack` if `.Success`, otherwise `nil`. */ public func stack() -> CoreDataStack? { if case .success(let stack) = self { return stack } return nil } /** - returns: The result's `NSError` if `.Failure`, otherwise `nil`. */ public func error() -> NSError? { if case .failure(let error) = self { return error } return nil } // MARK: CustomStringConvertible /// :nodoc: public var description: String { get { var str = "<\(StackResult.self): " switch self { case .success(let s): str += ".success(\(s)" case .failure(let e): str += ".failure(\(e))" } return str + ">" } } }
8f7a497cd6658b383f811840265f1b82
21.657534
100
0.579807
false
false
false
false
xNekOIx/StoryboardStyles
refs/heads/master
MyPlayground.playground/Pages/Untitled Page 3.xcplaygroundpage/Contents.swift
mit
1
//: [Previous](@previous) import Foundation let storyboardData = ("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>" + "<document type=\"com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB\" version=\"3.0\" toolsVersion=\"9059\" systemVersion=\"15B42\" targetRuntime=\"iOS.CocoaTouch\" propertyAccessControl=\"none\" useAutolayout=\"YES\" useTraitCollections=\"YES\">" + "<dependencies>" + "<plugIn identifier=\"com.apple.InterfaceBuilder.IBCocoaTouchPlugin\" version=\"9049\"/>" + "</dependencies>" + "<scenes>" + "<!--View Controller-->" + "<scene sceneID=\"X5B-PV-zIh\">" + "<objects>" + "<viewController id=\"iHD-XU-1t3\" sceneMemberID=\"viewController\">" + "<layoutGuides>" + "<viewControllerLayoutGuide type=\"top\" id=\"vBi-pL-j8v\"/>" + "<viewControllerLayoutGuide type=\"bottom\" id=\"YIc-tN-jzC\"/>" + "</layoutGuides>" + "<view key=\"view\" contentMode=\"scaleToFill\" id=\"D67-Go-AuY\">" + "<rect key=\"frame\" x=\"0.0\" y=\"0.0\" width=\"600\" height=\"600\"/>" + "<autoresizingMask key=\"autoresizingMask\" widthSizable=\"YES\" heightSizable=\"YES\"/>" + "<animations/>" + "<color key=\"backgroundColor\" white=\"1\" alpha=\"1\" colorSpace=\"calibratedWhite\"/>" + "<userDefinedRuntimeAttributes>" + "<userDefinedRuntimeAttribute type=\"string\" keyPath=\"styleClass\" value=\"PewPew\"/>" + "</userDefinedRuntimeAttributes>" + "</view>" + "</viewController>" + "<placeholder placeholderIdentifier=\"IBFirstResponder\" id=\"wG4-Wr-g0G\" userLabel=\"First Responder\" sceneMemberID=\"firstResponder\"/>" + "</objects>" + "<point key=\"canvasLocation\" x=\"977\" y=\"394\"/>" + "</scene>" + "</scenes>" + "</document>").dataUsingEncoding(NSUTF8StringEncoding)! let stylesheetData = ("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">" + "<xsl:template match=\"//userDefinedRuntimeAttribute[@keyPath='styleClass' and @value='PewPew']\">" + // "<xsl:template match=\"@* | node()\">" + "<xsl:copy-of select=\".\"/>" + // "<color></color>" + // "<xsl:copy>" + // "<color></color>" + // "<xsl:apply-templates select=\"@* | node()\"/>" + // "</xsl:copy>" + "</xsl:template>" + "</xsl:stylesheet>").dataUsingEncoding(NSUTF8StringEncoding)! let doc = try! NSXMLDocument(data: storyboardData, options: Int(NSXMLDocumentContentKind.XMLKind.rawValue)) let xslt = try! doc.objectByApplyingXSLT(stylesheetData, arguments: nil) print(xslt) //: [Next](@next)
4dd1c8c4cadec776c4ba241e7ecfb6a1
46.636364
257
0.621374
false
false
false
false
KoCMoHaBTa/MHAppKit
refs/heads/master
MHAppKit/Extensions/UIKit/UIControl+Action.swift
mit
1
// // UIControl+Action.swift // MHAppKit // // Created by Milen Halachev on 5/30/16. // Copyright © 2016 Milen Halachev. All rights reserved. // #if canImport(UIKit) && !os(watchOS) import Foundation import UIKit extension UIControl { public typealias Action = (_ sender: UIControl) -> Void ///Adds an action handler to the receiver for the given `UIControlEvents` (default to `.touchUpInside`) public func addAction(forEvents events: UIControl.Event = [.touchUpInside], action: @escaping Action) { //the action should be called for every event let handler = ActionHandler(control: self, events: events, action: action) self.actionHandlers.append(handler) } ///Returns an array of actions added to the receiver for the given control events public func actions(forEvents events: UIControl.Event) -> [Action] { return self.actionHandlers.filter({ $0.events.contains(events) }).map({ $0.action }) } ///removes all actions from the receiver for the given control events public func removeActions(forEvents events: UIControl.Event) { self.actionHandlers = self.actionHandlers.filter({ !$0.events.contains(events) }) } } extension UIControl { private static var actionHandlersKey = "" fileprivate var actionHandlers: [ActionHandler] { get { let result = objc_getAssociatedObject(self, &UIControl.actionHandlersKey) as? [ActionHandler] ?? [] return result } set { let newValue = newValue.filter({ $0.control != nil }) objc_setAssociatedObject(self, &UIControl.actionHandlersKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } } extension UIControl { fileprivate class ActionHandler { weak var control: UIControl? let events: UIControl.Event let action: Action deinit { self.control?.removeTarget(self, action: #selector(handleAction(_:)), for: self.events) } init(control: UIControl, events: UIControl.Event, action: @escaping Action) { self.control = control self.events = events self.action = action control.addTarget(self, action: #selector(handleAction(_:)), for: events) } @objc dynamic func handleAction(_ sender: UIControl) { self.action(sender) } } } #endif
769d46c9dc71c859b54750ea5b1a0c90
29.247059
118
0.60949
false
false
false
false
SnipDog/ETV
refs/heads/master
ETV/Moudel/Home/HomeViewController.swift
mit
1
// // HomeViewController.swift // ETV // // Created by Heisenbean on 16/9/29. // Copyright © 2016年 Heisenbean. All rights reserved. // import UIKit import Alamofire import Then import SwiftyJSON class HomeViewController: UIViewController { // MARK: Init Properties var titleView = TitleView().then { $0.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 40) } @IBOutlet weak var tableview: UITableView! let kBannerReqeutUrl = "http://api.m.panda.tv/ajax_rmd_ads_get?__version=1.1.4.1261&__plat=ios&__channel=appstore&pt_sign=ef767d23f0a6ccd476b738c0b91c4109&pt_time=1475204481" let kDataReqeutUrl = "http://api.m.panda.tv/ajax_get_live_list_by_multicate?pagenum=4&hotroom=1&__version=1.1.4.1261&__plat=ios&__channel=appstore&pt_sign=ef767d23f0a6ccd476b738c0b91c4109&pt_time=1475204481" var banners = [[String:AnyObject]]() var datas = [JSON]() // MARK: Life Cycle override func viewDidLoad() { super.viewDidLoad() configUI() loadBanner() loadData() loadTitleView() // Do any additional setup after loading the view. } func configUI(){ self.title = nil self.navigationController?.tabBarItem.title = "首页" let navView = UIImageView().then { let img = UIImage(named: "slogon") $0.image = img $0.sizeToFit() } self.navigationItem.titleView = navView } func loadBanner() { let banner = tableview.dequeueReusableCell(withIdentifier: "header") as! HomeHeaderCell tableview.tableHeaderView = banner Alamofire.request(kBannerReqeutUrl).responseJSON { response in if let json = response.result.value { self.banners.removeAll() let jsonData = json as! [String:AnyObject] for data in jsonData["data"] as! [[String : AnyObject]]{ self.banners.append(data) } banner.banners = self.banners } } } func loadTitleView() { view.addSubview(titleView) // load data from service titleView.titles = ["精彩推荐","全部直播","DOTA2"] } func loadData() { Alamofire.request(kDataReqeutUrl).responseJSON { response in if let json = response.data { let jsonData = JSON(data: json) let jsons = jsonData["data"].arrayValue for j in jsons{ self.datas.append(j) } self.tableview.reloadData() } } } // MARK: Actions @IBAction func search(_ sender: UIBarButtonItem) { } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension HomeViewController:UITableViewDataSource,UITableViewDelegate{ func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return datas.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! HomeCell cell.data = datas[indexPath.row] return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 321 } }
f8f2fb4b7645375d8cd1a87003cfaaf1
29.637931
211
0.599043
false
false
false
false
Morkrom/googlyeyes
refs/heads/master
googlyeyes/Classes/GooglyEye.swift
mit
1
// // GooglyEye.swift // googlyeyes // // Created by Michael Mork on 10/24/16. // Copyright © 2016 CocoaPods. All rights reserved. // import Foundation import UIKit class GooglyEye: UIView { var pupilDiameterPercentageWidth: CGFloat = 0.62 { didSet { updateDimensions() } } var pupil = Pupil() private class func grayColor() -> UIColor { return GooglyEye.paperGray(alpha: 1.0) } private class func paperGray(alpha: CGFloat) -> UIColor {return UIColor(red: 0.99, green: 0.99, blue: 0.99, alpha: alpha)} private class func cutoutRadius(dimension: CGFloat) -> CGFloat {return dimension/2 * 0.97} private class func diameterFromFrame(rectSize: CGSize) -> CGFloat {return rectSize.width > rectSize.height ? rectSize.height : rectSize.width} private var displayLink: CADisplayLink! private var animation: PupilBehaviorManager? private var diameter: CGFloat = 0 private var orientation = UIApplication.shared.statusBarOrientation private var baseCutout = Sclera() private let innerStamp = HeatStamp() class func autoLayout() -> GooglyEye { let gEye = GooglyEye(frame: CGRect(origin: .zero, size: CGSize(width: 100, height: 100))) gEye.translatesAutoresizingMaskIntoConstraints = false return gEye } override init(frame: CGRect) { super.init(frame: frame) displayLink = CADisplayLink(target: self, selector: #selector(GooglyEye.link)) //initialization displayLink.add(to: RunLoop.main, forMode: RunLoop.Mode.default) //properties displayLink.frameInterval = 2 addSubview(pupil) layer.addSublayer(baseCutout) layer.addSublayer(innerStamp) layer.insertSublayer(pupil.layer, below: innerStamp) if frame.size != .zero { animation = PupilBehaviorManager(googlyEye: self, center: baseCutout.startCenter, travelRadius: diameter) } updateDimensions() } private func updateDimensions() { guard animation != nil else { return } diameter = GooglyEye.diameterFromFrame(rectSize: frame.size) baseCutout.frame = CGRect(x: 0, y: 0, width: diameter, height: diameter) innerStamp.startCenter = baseCutout.startCenter innerStamp.frame = baseCutout.bounds if orientation == UIApplication.shared.statusBarOrientation { // Avoid changing the pupil frame if there's a status bar animation happening - doing so compromises an otherwise concentric pupil. adjustPupilForNewWidth() pupil.layer.setNeedsDisplay() } innerStamp.update() baseCutout.setNeedsDisplay() innerStamp.setNeedsDisplay() animation?.updateBehaviors(googlyEye: self, center: baseCutout.startCenter, travelRadius: GooglyEye.cutoutRadius(dimension: diameter)) } private func adjustPupilForNewWidth() { if pupilDiameterPercentageWidth > 1.0 { pupilDiameterPercentageWidth = 1.0 } else if pupilDiameterPercentageWidth < 0 { pupilDiameterPercentageWidth = 0.01 } pupil.frame = CGRect(x: pupil.frame.minX - (pupil.frame.width - diameter*pupilDiameterPercentageWidth)/2, y: pupil.frame.minY - (pupil.frame.height - diameter*pupilDiameterPercentageWidth)/2, width: diameter*pupilDiameterPercentageWidth, height: diameter*pupilDiameterPercentageWidth) } let motionManager = MotionProvider.shared.motionManager() @objc func link(link: CADisplayLink) { // motionManager.deviceMotion?.rotationRate guard let motion = motionManager.deviceMotion else {return} // print("\(motion.rotationRate)") animation?.update(gravity: motion.gravity, acceleration: motion.userAcceleration) } override var frame: CGRect { didSet { updateDimensions() } } override func setNeedsLayout() { super.setNeedsLayout() animation = PupilBehaviorManager(googlyEye: self, center: baseCutout.startCenter, travelRadius: diameter) updateDimensions() } override func layoutIfNeeded() { super.layoutIfNeeded() animation = PupilBehaviorManager(googlyEye: self, center: baseCutout.startCenter, travelRadius: diameter) updateDimensions() } override func layoutSubviews() { super.layoutSubviews() let currentOrientation = UIApplication.shared.statusBarOrientation if orientation != currentOrientation { orientation = currentOrientation switch orientation { case .landscapeLeft: layer.setAffineTransform(CGAffineTransform(rotationAngle: CGFloat(Double.pi/2))) case .landscapeRight: layer.setAffineTransform(CGAffineTransform(rotationAngle: -CGFloat(Double.pi/2))) case .portraitUpsideDown: layer.setAffineTransform(CGAffineTransform(rotationAngle: CGFloat(Double.pi))) default: layer.setAffineTransform(.identity) } } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } class HeatStamp: CALayer { var endCenter: CGPoint = .zero var startCenter: CGPoint = .zero let edgeShadowGradient = CGGradient(colorsSpace: nil, colors: [UIColor(red: 0.2, green: 0.1, blue: 0.2, alpha: 0.01).cgColor, UIColor(red: 0.1, green: 0.1, blue: 0.2, alpha: 0.6).cgColor, UIColor.clear.cgColor] as CFArray, locations: [0.78, 0.95, 0.999] as [CGFloat]) let innerShadowGradient = CGGradient(colorsSpace: nil, colors: [GooglyEye.paperGray(alpha: 0.2).cgColor, UIColor.clear.cgColor] as CFArray, locations: nil) func update() { endCenter = CGPoint(x: startCenter.x, y: startCenter.y) } override init(layer: Any) { super.init(layer: layer) contentsScale = UIScreen.main.scale } override init() { super.init() contentsScale = UIScreen.main.scale } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func draw(in ctx: CGContext) { super.draw(in: ctx) let radius = GooglyEye.cutoutRadius(dimension: bounds.width) ctx.drawRadialGradient(edgeShadowGradient!, startCenter: endCenter, startRadius: radius - (bounds.width*0.5), endCenter: startCenter, endRadius: radius, options: .drawsBeforeStartLocation) ctx.drawRadialGradient(innerShadowGradient!, startCenter: endCenter, startRadius: 1, endCenter: endCenter, endRadius: radius*0.4, options: .drawsBeforeStartLocation) } } class Pupil: UIView { let diameter: CGFloat = 11.0 override var collisionBoundsType: UIDynamicItemCollisionBoundsType { get { return .ellipse } } override class var layerClass: Swift.AnyClass { return PupilLayer.self } override init(frame: CGRect) { super.init(frame: frame) backgroundColor = UIColor.clear } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } class PupilLayer: CAShapeLayer { override init(layer: Any) { super.init(layer: layer) contentsScale = UIScreen.main.scale fillColor = UIColor.black.cgColor } override init() { super.init() contentsScale = UIScreen.main.scale fillColor = UIColor.black.cgColor } override func setNeedsDisplay() { super.setNeedsDisplay() path = CGPath(ellipseIn: bounds, transform: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } } class Sclera: CAShapeLayer { let stampPercentSizeDifference: CGFloat = 0.1 let baseStampGradient = CGGradient(colorsSpace: nil, colors: [GooglyEye.grayColor().cgColor, UIColor.clear.cgColor] as CFArray, locations: nil) var startCenter: CGPoint = .zero var diameter: CGFloat = 0 override init(layer: Any) { super.init(layer: layer) contentsScale = UIScreen.main.scale // this one is key fillColor = GooglyEye.grayColor().cgColor } override init() { super.init() contentsScale = UIScreen.main.scale // this one is key fillColor = GooglyEye.grayColor().cgColor } override var bounds: CGRect { didSet { diameter = GooglyEye.diameterFromFrame(rectSize: bounds.size) startCenter = CGPoint(x: diameter/2, y: diameter/2) } } override func setNeedsDisplay() { super.setNeedsDisplay() path = CGPath(ellipseIn: bounds, transform: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func draw(in ctx: CGContext) { super.draw(in: ctx) ctx.setShouldAntialias(true) ctx.setAllowsAntialiasing(true) ctx.setFillColor(GooglyEye.grayColor().cgColor) let path = CGPath(ellipseIn: CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: diameter, height: diameter)), transform: nil) ctx.addPath(path) ctx.fillPath() let radius = GooglyEye.cutoutRadius(dimension: diameter) ctx.drawRadialGradient(baseStampGradient!, startCenter: startCenter, startRadius: radius - (diameter*0.05), endCenter: startCenter, endRadius: radius + (diameter*0.02), options: .drawsAfterEndLocation) } } }
0466b09080811e876a3f6e45a1098b55
37.372263
292
0.606144
false
false
false
false
Kukiwon/rfduino-swift
refs/heads/master
Pod/Classes/RFDuino.swift
mit
1
// // RFDuino.swift // Pods // // Created by Jordy van Kuijk on 27/01/16. // // import Foundation import CoreBluetooth @objc public protocol RFDuinoDelegate { @objc optional func rfDuinoDidTimeout(rfDuino: RFDuino) @objc optional func rfDuinoDidDisconnect(rfDuino: RFDuino) @objc optional func rfDuinoDidDiscover(rfDuino: RFDuino) @objc optional func rfDuinoDidDiscoverServices(rfDuino: RFDuino) @objc optional func rfDuinoDidDiscoverCharacteristics(rfDuino: RFDuino) @objc optional func rfDuinoDidSendData(rfDuino: RFDuino, forCharacteristic: CBCharacteristic, error: Error?) @objc optional func rfDuinoDidReceiveData(rfDuino: RFDuino, data: Data?) } public class RFDuino: NSObject { public var isTimedOut = false public var isConnected = false public var didDiscoverCharacteristics = false public var delegate: RFDuinoDelegate? public static let timeoutThreshold = 5.0 public var RSSI: NSNumber? var whenDoneBlock: (() -> ())? var peripheral: CBPeripheral var timeoutTimer: Timer? init(peripheral: CBPeripheral) { self.peripheral = peripheral super.init() self.peripheral.delegate = self } } /* Internal methods */ internal extension RFDuino { func confirmAndTimeout() { isTimedOut = false delegate?.rfDuinoDidDiscover?(rfDuino: self) timeoutTimer?.invalidate() timeoutTimer = nil timeoutTimer = Timer.scheduledTimer(timeInterval: RFDuino.timeoutThreshold, target: self, selector: #selector(RFDuino.didTimeout), userInfo: nil, repeats: false) } @objc func didTimeout() { isTimedOut = true isConnected = false delegate?.rfDuinoDidTimeout?(rfDuino: self) } func didConnect() { timeoutTimer?.invalidate() timeoutTimer = nil isConnected = true isTimedOut = false } func didDisconnect() { isConnected = false confirmAndTimeout() delegate?.rfDuinoDidDisconnect?(rfDuino: self) } func findCharacteristic(characteristicUUID: RFDuinoUUID, forServiceWithUUID serviceUUID: RFDuinoUUID) -> CBCharacteristic? { if let discoveredServices = peripheral.services, let service = (discoveredServices.filter { return $0.uuid == serviceUUID.id }).first, let characteristics = service.characteristics { return (characteristics.filter { return $0.uuid == characteristicUUID.id}).first } return nil } } /* Public methods */ public extension RFDuino { func discoverServices() { "Going to discover services for peripheral".log() peripheral.discoverServices([RFDuinoUUID.Discover.id]) } func sendDisconnectCommand(whenDone: @escaping () -> ()) { self.whenDoneBlock = whenDone // if no services were discovered, imediately invoke done block if peripheral.services == nil { whenDone() return } if let characteristic = findCharacteristic(characteristicUUID: RFDuinoUUID.Disconnect, forServiceWithUUID: RFDuinoUUID.Discover) { var byte = UInt8(1) let data = NSData(bytes: &byte, length: 1) peripheral.writeValue(data as Data, for: characteristic, type: .withResponse) } } func send(data: Data) { if let characteristic = findCharacteristic(characteristicUUID: RFDuinoUUID.Send, forServiceWithUUID: RFDuinoUUID.Discover) { peripheral.writeValue(data, for: characteristic, type: .withResponse) } } } /* Calculated vars */ public extension RFDuino { var name: String { get { return peripheral.name ?? "Unknown device" } } } extension RFDuino: CBPeripheralDelegate { public func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) { "Did send data to peripheral".log() if characteristic.uuid == RFDuinoUUID.Disconnect.id { if let doneBlock = whenDoneBlock { doneBlock() } } else { delegate?.rfDuinoDidSendData?(rfDuino: self, forCharacteristic: self.findCharacteristic(characteristicUUID: RFDuinoUUID.Send, forServiceWithUUID: RFDuinoUUID.Discover)!, error: error) } } public func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) { "Did discover services".log() if let discoveredServices = peripheral.services { for service in discoveredServices { if service.uuid == RFDuinoUUID.Discover.id { peripheral.discoverCharacteristics(nil, for: service) } } } delegate?.rfDuinoDidDiscoverServices?(rfDuino: self) } public func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) { for characteristic in service.characteristics! { ("did discover characteristic with UUID: " + characteristic.uuid.description).log() if characteristic.uuid == RFDuinoUUID.Receive.id { peripheral.setNotifyValue(true, for: characteristic) } else if characteristic.uuid == RFDuinoUUID.Send.id { peripheral.setNotifyValue(true, for: characteristic) } } "Did discover characteristics for service".log() delegate?.rfDuinoDidDiscoverCharacteristics?(rfDuino: self) } public func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) { "Did receive data for rfDuino".log() delegate?.rfDuinoDidReceiveData?(rfDuino: self, data: characteristic.value) } }
0840dd543cc7db4f6b1764916e7f3cd0
34.385542
195
0.655941
false
false
false
false
f2m2/f2m2-swift-forms
refs/heads/master
Cartography/Compound.swift
mit
5
// // Compound.swift // Cartography // // Created by Robert Böhnke on 18/06/14. // Copyright (c) 2014 Robert Böhnke. All rights reserved. // #if os(iOS) import UIKit #else import AppKit #endif protocol Compound { var properties: [Property] { get } } func apply(from: Compound, coefficients: [Coefficients]? = nil, to: Compound? = nil, relation: NSLayoutRelation = NSLayoutRelation.Equal) -> [NSLayoutConstraint] { var results: [NSLayoutConstraint] = [] for i in 0..<from.properties.count { let n: Coefficients = coefficients?[i] ?? Coefficients() results.append(apply(from.properties[i], coefficients: n, to: to?.properties[i], relation: relation)) } return results }
f944429904f3449ada266166b17c8f83
23.62069
163
0.677871
false
false
false
false
marcelmueller/MyWeight
refs/heads/master
MyWeight/Views/TitleDescriptionView.swift
mit
1
// // TitleDescriptionView.swift // MyWeight // // Created by Diogo on 18/10/16. // Copyright © 2016 Diogo Tridapalli. All rights reserved. // import UIKit public protocol TitleDescriptionViewModelProtocol { var title: NSAttributedString { get } var description: NSAttributedString { get } var flexibleHeight: Bool { get } } public class TitleDescriptionView: UIView { struct EmptyViewModel: TitleDescriptionViewModelProtocol { let title: NSAttributedString = NSAttributedString() let description: NSAttributedString = NSAttributedString() let flexibleHeight: Bool = false } let titleLabel: UILabel = { let label = UILabel() label.numberOfLines = 0 label.setContentHuggingPriority(UILayoutPriorityRequired, for: .vertical) return label }() let descriptionLabel: UILabel = { let label = UILabel() label.numberOfLines = 0 label.setContentHuggingPriority(UILayoutPriorityRequired, for: .vertical) return label }() var bottomFixedConstraint: NSLayoutConstraint? let style: StyleProvider = Style() public var viewModel: TitleDescriptionViewModelProtocol { didSet { update() } } override public init(frame: CGRect) { viewModel = EmptyViewModel() super.init(frame: frame) setUp() update() } @available(*, unavailable) required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setUp() { let grid = style.grid let padding = grid * 3 let space = grid * 2 let contentView = self contentView.backgroundColor = style.backgroundColor titleLabel.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(titleLabel) titleLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: padding).isActive = true titleLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: padding).isActive = true titleLabel.trailingAnchor.constraint(lessThanOrEqualTo: contentView.trailingAnchor, constant: -padding).isActive = true descriptionLabel.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(descriptionLabel) descriptionLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: space).isActive = true descriptionLabel.leadingAnchor.constraint(equalTo: titleLabel.leadingAnchor).isActive = true descriptionLabel.trailingAnchor.constraint(lessThanOrEqualTo: contentView.trailingAnchor, constant: -padding).isActive = true let bottomGuide = UILayoutGuide() contentView.addLayoutGuide(bottomGuide) bottomGuide.topAnchor.constraint(equalTo: descriptionLabel.bottomAnchor).isActive = true bottomGuide.leftAnchor.constraint(equalTo: contentView.leftAnchor).isActive = true bottomGuide.rightAnchor.constraint(equalTo: contentView.rightAnchor).isActive = true bottomGuide.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -padding).isActive = true bottomFixedConstraint = bottomGuide.heightAnchor.constraint(equalToConstant: 0) } func update() { titleLabel.attributedText = viewModel.title descriptionLabel.attributedText = viewModel.description bottomFixedConstraint?.isActive = !viewModel.flexibleHeight } }
1a355ce865bf820513e0edbaf6aeb128
32.059829
100
0.642709
false
false
false
false
lingyijie/DYZB
refs/heads/master
DYZB/DYZB/Class/Home/Controller/RecommendViewController.swift
mit
1
// // RecommendViewController.swift // DYZB // // Created by ling yijie on 2017/8/31. // Copyright © 2017年 ling yijie. All rights reserved. // import UIKit fileprivate let kPrettyCell = "kPrettyCell" fileprivate let kMargin : CGFloat = 10 fileprivate let kNormalItemW : CGFloat = (kScreenW - 3 * kMargin) / 2 fileprivate let kNormalItemH : CGFloat = 3 * kNormalItemW / 4 fileprivate let kPrettyItemH : CGFloat = 4 * kNormalItemW / 3 fileprivate let kCycleViewH : CGFloat = 150 fileprivate let kGameViewH : CGFloat = 90 class RecommendViewController: BaseAnchorViewController { // 数据模型 fileprivate lazy var recommendVM : RecommentVM = RecommentVM() // 推荐view fileprivate lazy var gameView : RecommendGameView = { let gameView = RecommendGameView.recommendGameView() gameView.frame = CGRect(x: 0, y: -kGameViewH, width: kScreenW, height: kGameViewH) return gameView }() // 无线循环view fileprivate lazy var cycleView : RecommendCycleView = { let cycleView = RecommendCycleView.recommendCycleView() cycleView.frame = CGRect(x: 0, y: -(kCycleViewH + kGameViewH), width: kScreenW, height: kCycleViewH) return cycleView }() } extension RecommendViewController { override func setupUI() { super.setupUI() //设置上边距以显示cycleview&gameview collectionView.contentInset = UIEdgeInsets(top: kCycleViewH + kGameViewH, left: 0, bottom: 0, right: 0) // 设置代理遵循UICollectionViewDelegateFlowLayout collectionView.delegate = self collectionView.addSubview(cycleView) collectionView.addSubview(gameView) } } extension RecommendViewController { override func loadData() { // 请求主播数据 recommendVM.requestData(){ self.baseVM = self.recommendVM self.collectionView.reloadData() self.gameView.groups = self.recommendVM.anchorGroups } // 请求无限轮播数据 recommendVM.requestCycleData { self.cycleView.cycleModelGroup = self.recommendVM.cycleGroup } //停止动画 super.stopAnimation() } } extension RecommendViewController: UICollectionViewDelegateFlowLayout { override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let group = recommendVM.anchorGroups[indexPath.section] let anchor = group.anchors[indexPath.item] if indexPath.section == 1 { let prettyCell = collectionView.dequeueReusableCell(withReuseIdentifier: kPrettyCell, for: indexPath) as! CollectionPrettyCell prettyCell.anchor = anchor return prettyCell } else { return super.collectionView(collectionView, cellForItemAt: indexPath) } } // 根据section返回不同尺寸的cell func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { if indexPath.section == 1 { return CGSize(width: kNormalItemW, height: kPrettyItemH) } return CGSize(width: kNormalItemW, height: kNormalItemH) } }
0589870eff04d50b67331068fbdf4d7c
34.88764
160
0.6866
false
false
false
false
iOSDevLog/iOSDevLog
refs/heads/master
Checklists/Checklists/Checklist.swift
mit
1
// // Checklist.swift // Checklists // // Created by iosdevlog on 16/1/3. // Copyright © 2016年 iosdevlog. All rights reserved. // import UIKit class Checklist: NSObject, NSCoding { var name = "" var iconName = "No Icon" var items = [ChecklistItem]() convenience init(name: String) { self.init(name: name, iconName: "No Icon") } init(name: String, iconName: String) { self.name = name self.iconName = iconName super.init() } // MARK: - protocol NSCoding func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(name, forKey: "Name") aCoder.encodeObject(iconName, forKey: "IconName") aCoder.encodeObject(items, forKey: "Items") } required init?(coder aDecoder: NSCoder) { name = aDecoder.decodeObjectForKey("Name") as! String iconName = aDecoder.decodeObjectForKey("IconName") as! String items = aDecoder.decodeObjectForKey("Items") as! [ChecklistItem] super.init() } // MARK: - Helper func countUncheckedItems() -> Int { var count = 0 for item in items where !item.checked { count += 1 } return count } }
ea90c100f3541711471aa39436fa1557
22.981132
72
0.575924
false
false
false
false
Hussain-it/Onboard-Walkthrough
refs/heads/master
Onboard-Walkthrough/Onboard-Walkthrough/MainNavigationController.swift
mit
1
// // MainNavigationController.swift // Onboard-Walkthrough // // Created by Khan Hussain on 19/10/17. // Copyright © 2017 kb. All rights reserved. // import UIKit class MainNavigationController: UINavigationController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.white //Login Controller || Home Controller based on user loggedin status if isLoggedin(){ let hvc = HomeViewController() viewControllers = [hvc] }else{ perform(#selector(showLoginController), with: nil, afterDelay: 0.001) } } fileprivate func isLoggedin() -> Bool{ return true } @objc func showLoginController(){ let layout = UICollectionViewFlowLayout() layout.scrollDirection = .horizontal layout.minimumLineSpacing = 0 let cv = LoginViewController(collectionViewLayout: layout) present(cv, animated: true, completion: nil) } @objc func showHomeController(){ let hvc = HomeViewController() present(hvc, animated: true, completion: nil) } }
3f201f5e5cad5f35be5221f461c7c8dc
25.133333
81
0.622449
false
false
false
false
hanhailong/practice-swift
refs/heads/master
CoreData/Deleting data from CoreData/Deleting data from CoreData/AppDelegate.swift
mit
2
// // AppDelegate.swift // Deleting data from CoreData // // Created by Domenico Solazzo on 17/05/15. // License MIT // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? //- MARK: Helper methods func createNewPerson(firstName: String, lastName: String, age:Int) -> Bool{ let entityName = NSStringFromClass(Person.classForCoder()) let newPerson = NSEntityDescription.insertNewObjectForEntityForName(entityName, inManagedObjectContext: managedObjectContext!) as! Person (newPerson.firstName, newPerson.lastName, newPerson.age) = (firstName, lastName, age) var savingError: NSError? if managedObjectContext!.save(&savingError){ println("Successfully saved...") }else{ if let error = savingError{ println("Failed to save the new person. Error = \(error)") } } return false } //- MARK: Application Delegate func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. /* Create the entities first */ createNewPerson("Anthony", lastName: "Robbins", age: 52) createNewPerson("Richard", lastName: "Branson", age: 62) /* Tell the request that we want to read the contents of the Person entity */ /* Create the fetch request first */ let fetchRequest = NSFetchRequest(entityName: "Person") var requestError: NSError? /* And execute the fetch request on the context */ let persons = managedObjectContext!.executeFetchRequest(fetchRequest, error: &requestError) as! [Person] if persons.count > 0{ /* Delete the last person in the array */ let lastPerson = (persons as NSArray).lastObject as! Person managedObjectContext!.deleteObject(lastPerson) // .deleted check if an entity has been deleted in the context if lastPerson.deleted{ println("Successfully deleted the last person...") var savingError: NSError? if managedObjectContext!.save(&savingError){ println("Successfully saved the context") } else { if let error = savingError{ println("Failed to save the context. Error = \(error)") } } } else { println("Failed to delete the last person") } }else{ println("Could not find any Person entity in the context") } 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 "com.domenicosolazzo.swift.Deleting_data_from_CoreData" 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("Deleting_data_from_CoreData", 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("Deleting_data_from_CoreData.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() } } } }
0bf883b7c39840fde12836f2b1c47f12
47.741573
290
0.667243
false
false
false
false
eurofurence/ef-app_ios
refs/heads/release/4.0.0
Packages/EurofurenceComponents/Tests/TutorialComponentTests/Test Doubles/CapturingTutorialPageScene.swift
mit
1
import Foundation import TutorialComponent import UIKit class CapturingTutorialPageSceneDelegate: TutorialPageSceneDelegate { private(set) var primaryActionButtonTapped = false func tutorialPageSceneDidTapPrimaryActionButton(_ tutorialPageScene: TutorialPageScene) { primaryActionButtonTapped = true } private(set) var secondaryActionButtonTapped = false func tutorialPageSceneDidTapSecondaryActionButton(_ tutorialPageScene: TutorialPageScene) { secondaryActionButtonTapped = true } } class CapturingTutorialPageScene: TutorialPageScene { var tutorialPageSceneDelegate: TutorialPageSceneDelegate? private(set) var capturedPageTitle: String? func showPageTitle(_ title: String?) { capturedPageTitle = title } private(set) var capturedPageDescription: String? func showPageDescription(_ description: String?) { capturedPageDescription = description } private(set) var capturedPageImage: UIImage? func showPageImage(_ image: UIImage?) { capturedPageImage = image } private(set) var didShowPrimaryActionButton = false func showPrimaryActionButton() { didShowPrimaryActionButton = true } private(set) var capturedPrimaryActionDescription: String? func showPrimaryActionDescription(_ primaryActionDescription: String) { capturedPrimaryActionDescription = primaryActionDescription } private(set) var didShowSecondaryActionButton = false func showSecondaryActionButton() { didShowSecondaryActionButton = true } private(set) var capturedSecondaryActionDescription: String? func showSecondaryActionDescription(_ secondaryActionDescription: String) { capturedSecondaryActionDescription = secondaryActionDescription } func simulateTappingPrimaryActionButton() { tutorialPageSceneDelegate?.tutorialPageSceneDidTapPrimaryActionButton(self) } func simulateTappingSecondaryActionButton() { tutorialPageSceneDelegate?.tutorialPageSceneDidTapSecondaryActionButton(self) } }
6a0b108f961d0fe55965cb63b8a69123
30.651515
95
0.762566
false
false
false
false
Mayfleet/SimpleChat
refs/heads/master
Frontend/iOS/SimpleChat/Simple Chat Screenshots/Simple_Chat_Screenshots.swift
mit
1
// // Simple_Chat_Screenshots.swift // Simple Chat Screenshots // // Created by Maxim Pervushin on 18/03/16. // Copyright © 2016 Maxim Pervushin. All rights reserved. // import XCTest class Simple_Chat_Screenshots: XCTestCase { override func setUp() { super.setUp() let app = XCUIApplication() setupSnapshot(app) app.launch() } override func tearDown() { super.tearDown() } func testExample() { let app = XCUIApplication() snapshot("01ChatsListScreen") app.tables.cells.staticTexts.elementBoundByIndex(0).tap() snapshot("02ChatScreen") let collectionView = app.otherElements.containingType(.NavigationBar, identifier:"Local:3000").childrenMatchingType(.Other).element.childrenMatchingType(.Other).element.childrenMatchingType(.Other).element.childrenMatchingType(.Other).element.childrenMatchingType(.Other).element.childrenMatchingType(.Other).element.childrenMatchingType(.CollectionView).element collectionView.twoFingerTap() collectionView.twoFingerTap() snapshot("03LogInScreen") app.buttons["SignUpButton"].tap() snapshot("04SignUpScreen") /* let app = XCUIApplication() snapshot("01ChatsListScreen") app.tables.cells.staticTexts["Local:3000"].tap() snapshot("02ChatScreen") let local3000NavigationBar = app.navigationBars["Local:3000"] local3000NavigationBar.buttons["Authentication"].tap() snapshot("02LogInScreen") app.buttons["Sign Up"].tap() snapshot("02SignUpScreen") let closeButton = app.buttons["Close"] closeButton.tap() closeButton.tap() local3000NavigationBar.buttons["Chats"].tap() */ /* let app = XCUIApplication() snapshot("01ChatsListScreen") app.tables.cells.staticTexts.elementBoundByIndex(0).tap() snapshot("02ChatScreen") let collectionView = app.otherElements.containingType(.NavigationBar, identifier:"Local:3000").childrenMatchingType(.Other).element.childrenMatchingType(.Other).element.childrenMatchingType(.Other).element.childrenMatchingType(.Other).element.childrenMatchingType(.Other).element.childrenMatchingType(.Other).element.childrenMatchingType(.CollectionView).element // let collectionView = app.otherElements.childrenMatchingType(.CollectionView).element collectionView.twoFingerTap() collectionView.twoFingerTap() snapshot("03LogInScreen") app.buttons["SignUpButton"].tap() snapshot("04SignUpScreen") */ } }
54634aacdc5770195cfbeba10ffbc873
31.4
370
0.658315
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/FeatureForm/Sources/FeatureFormUI/Form.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import BlockchainComponentLibrary import FeatureFormDomain import SwiftUI public struct PrimaryForm: View { @Binding private var form: FeatureFormDomain.Form private let submitActionTitle: String private let submitActionLoading: Bool private let submitAction: () -> Void public init( form: Binding<FeatureFormDomain.Form>, submitActionTitle: String, submitActionLoading: Bool, submitAction: @escaping () -> Void ) { _form = form self.submitActionTitle = submitActionTitle self.submitActionLoading = submitActionLoading self.submitAction = submitAction } public var body: some View { ScrollView { LazyVStack(spacing: Spacing.padding4) { if let header = form.header { VStack { Icon.user .frame(width: 32.pt, height: 32.pt) Text(header.title) .typography(.title2) Text(header.description) .typography(.paragraph1) } .multilineTextAlignment(.center) .foregroundColor(.semantic.title) } ForEach($form.nodes) { question in FormQuestionView(question: question) } PrimaryButton( title: submitActionTitle, isLoading: submitActionLoading, action: submitAction ) .disabled(!form.nodes.isValidForm) } .padding(Spacing.padding3) .background(Color.semantic.background) } } } struct PrimaryForm_Previews: PreviewProvider { static var previews: some View { let jsonData = formPreviewJSON.data(using: .utf8)! // swiftlint:disable:next force_try let formRawData = try! JSONDecoder().decode(FeatureFormDomain.Form.self, from: jsonData) PreviewHelper(form: formRawData) } struct PreviewHelper: View { @State var form: FeatureFormDomain.Form var body: some View { PrimaryForm( form: $form, submitActionTitle: "Next", submitActionLoading: false, submitAction: {} ) } } }
4c34c464d0b8e067333c0fe36df4ea8d
29.207317
96
0.547033
false
false
false
false
iNoles/NolesFootball
refs/heads/master
NolesFootball.iOS/Noles Football/DemandViewController.swift
gpl-3.0
1
// // DemandViewController.swift // Noles Football // // Created by Jonathan Steele on 5/6/16. // Copyright © 2016 Jonathan Steele. All rights reserved. // import UIKit import AVKit import AVFoundation class DemandViewController: UITableViewController { private var list = [Demand]() required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() let format = DateUtils(format: "yyyy-MM-dd'T'HH:mm:ss'Z'", isGMTWithLocale: true) let dateFormatter = DateUtils(format: "EEE, MMM d, yyyy h:mm a") parseXML(withURL: "http://www.seminoles.com/XML/services/v2/onDemand.v2.dbml?DB_OEM_ID=32900&maxrows=10&start=0&spid=157113", query: "//clip", callback: { [unowned self] childNode in var demand = Demand() childNode.forEach { nodes in if nodes.tagName == "short_description" { demand.description = nodes.firstChild?.content } if nodes.tagName == "start_date" { let date = format.dateFromString(string: nodes.firstChild?.content) demand.date = dateFormatter.stringFromDate(date: date!) } if nodes.tagName == "external_m3u8" { demand.link = nodes.firstChild?.content } } self.list.append(demand) }, deferCallback: tableView.reloadData) // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in _: UITableView) -> Int { // Return the number of sections. return 1 } override func tableView(_: UITableView, numberOfRowsInSection _: Int) -> Int { // Return the number of rows in the section. return list.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "OnDemand", for: indexPath) // Configure the cell... let demand = list[indexPath.row] cell.textLabel?.text = demand.description cell.detailTextLabel?.text = demand.date return cell } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender _: Any?) { guard let int = tableView.indexPathForSelectedRow?.row else { assertionFailure("Couldn't get TableView Selected Row") return } if let url = URL(string: list[int].link!) { let destination = segue.destination as! AVPlayerViewController destination.player = AVPlayer(url: url) } } }
489887102dcb70f78b589511fc80eda5
34.597701
190
0.627058
false
false
false
false
mleiv/MEGameTracker
refs/heads/master
MEGameTracker/Models/Map/MapLocationPoint.swift
mit
1
// // MapLocationPoint.swift // MEGameTracker // // Created by Emily Ivie on 9/26/15. // Copyright © 2015 Emily Ivie. All rights reserved. // import UIKit public typealias MapLocationPointKey = Duplet<CGFloat, CGFloat> /// Defines a scalable location marker on a map, either square or circular. public struct MapLocationPoint: Codable { enum CodingKeys: String, CodingKey { case x case y case radius case width case height } // MARK: Properties public var x: CGFloat public var y: CGFloat public var radius: CGFloat? public var width: CGFloat public var height: CGFloat // x, y is altered for rectangles to locate center, so keep original values for encode: private var _x: CGFloat? private var _y: CGFloat? // MARK: Computed Properties public var cgRect: CGRect { return CGRect(x: x, y: y, width: width, height: height) } public var cgPoint: CGPoint { return CGPoint(x: x, y: y) } public var key: MapLocationPointKey { return MapLocationPointKey(x, y) } // MARK: Initialization public init(x: CGFloat, y: CGFloat, radius: CGFloat) { self.x = x self.y = y self.radius = radius self.width = radius * 2 self.height = radius * 2 } public init(x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat) { self.x = x self.y = y self.radius = nil self.width = width self.height = height } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let x = try container.decode(CGFloat.self, forKey: .x) let y = try container.decode(CGFloat.self, forKey: .y) if let radius = try container.decodeIfPresent(CGFloat.self, forKey: .radius) { self.init(x: x, y: y, radius: radius) } else { let width = try container.decode(CGFloat.self, forKey: .width) let height = try container.decode(CGFloat.self, forKey: .height) self.init(x: x + width/2, y: y + height/2, width: width, height: height) self._x = x self._y = y } } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(_x ?? x, forKey: .x) try container.encode(_y ?? y, forKey: .y) if let radius = self.radius { try container.encode(radius, forKey: .radius) } else { try container.encode(width, forKey: .width) try container.encode(height, forKey: .height) } } } // MARK: Basic Actions extension MapLocationPoint { /// Converts a map location point from where it is on a base size map to where it is on an adjusted size map. public func fromSize(_ oldSize: CGSize, toSize newSize: CGSize) -> MapLocationPoint { let ratio = newSize.width / oldSize.width let x = self.x * ratio let y = self.y * ratio if let radius = radius { let r = radius * ratio return MapLocationPoint(x: x, y: y, radius: r) } else { let w = width * ratio let h = height * ratio return MapLocationPoint(x: x, y: y, width: w, height: h) } } } //// MARK: SerializedDataStorable //extension MapLocationPoint: SerializedDataStorable { // // public func getData() -> SerializableData { // var list: [String: SerializedDataStorable?] = [:] // if let radius = self.radius { // list["x"] = "\(x)" // list["y"] = "\(y)" // list["radius"] = "\(radius)" // } else { // // rect uses top left; convert from center // list["x"] = "\(x - (width / 2))" // list["y"] = "\(y - (height / 2))" // list["width"] = "\(width)" // list["height"] = "\(height)" // } // return SerializableData.safeInit(list) // } // //} // //// MARK: SerializedDataRetrievable //extension MapLocationPoint: SerializedDataRetrievable { // // public init?(data: SerializableData?) { // guard let data = data, // var x = data["x"]?.cgFloat, // var y = data["y"]?.cgFloat // else { // return nil // } // // if let width = data["width"]?.cgFloat, let height = data["height"]?.cgFloat { // // rect uses top left; convert to center // x += (width / 2) // y += (height / 2) // self.init(x: x, y: y, width: width, height: height) // } else { // self.init(x: x, y: y, radius: data["radius"]?.cgFloat ?? 0) // } // } // // public mutating func setData(_ data: SerializableData) {} //} // MARK: Equatable extension MapLocationPoint: Equatable { public static func == ( _ lhs: MapLocationPoint, _ rhs: MapLocationPoint ) -> Bool { return lhs.x == rhs.x && lhs.y == rhs.y } }
23980eb247d631ac574911ad15c28377
29.528662
110
0.592739
false
false
false
false
juanm95/Soundwich
refs/heads/master
Quaggify/TrackCell.swift
mit
1
// // TrackCell.swift // Quaggify // // Created by Jonathan Bijos on 01/02/17. // Copyright © 2017 Quaggie. All rights reserved. // import UIKit class TrackCell: CollectionViewCell { var track: Track? { didSet { guard let track = track else { return } if let artistName = track.name { titleLabel.text = artistName } if let artists = track.artists { let names = artists.map { $0.name ?? "Uknown Artist" }.joined(separator: ", ") subTitleLabel.text = names if let albumName = track.album?.name { subTitleLabel.text?.append(" ・ \(albumName)") } } } } var position: Int? let stackView: UIStackView = { let sv = UIStackView() sv.axis = .vertical sv.alignment = .fill sv.distribution = .fillEqually sv.backgroundColor = .clear sv.spacing = 4 return sv }() let titleLabel: UILabel = { let label = UILabel() label.textColor = ColorPalette.white label.font = Font.montSerratBold(size: 16) label.textAlignment = .left label.translatesAutoresizingMaskIntoConstraints = false return label }() let subTitleLabel: UILabel = { let label = UILabel() label.textColor = ColorPalette.lightGray label.font = Font.montSerratRegular(size: 12) label.textAlignment = .left label.translatesAutoresizingMaskIntoConstraints = false return label }() lazy var moreButton: UIButton = { let button = UIButton(type: .system) button.setImage(#imageLiteral(resourceName: "icon_more").withRenderingMode(.alwaysTemplate), for: .normal) button.tintColor = ColorPalette.white button.addTarget(self, action: #selector(showTrackOptions), for: .touchUpInside) return button }() override init(frame: CGRect) { super.init(frame: frame) let longGesture = UILongPressGestureRecognizer(target: self, action: #selector(onHold(sender:))) addGestureRecognizer(longGesture) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func setupViews() { super.setupViews() addSubview(stackView) addSubview(moreButton) stackView.addArrangedSubview(titleLabel) stackView.addArrangedSubview(subTitleLabel) stackView.anchor(topAnchor, left: leftAnchor, bottom: bottomAnchor, right: moreButton.leftAnchor, topConstant: 8, leftConstant: 8, bottomConstant: 8, rightConstant: 8, widthConstant: 0, heightConstant: 0) moreButton.anchor(topAnchor, left: nil, bottom: bottomAnchor, right: rightAnchor, topConstant: 0, leftConstant: 8, bottomConstant: 0, rightConstant: 0, widthConstant: 56, heightConstant: 0) } func onHold (sender : UIGestureRecognizer) { if sender.state == .began { showTrackOptions() } } func showTrackOptions () { let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) if let name = track?.name { alertController.title = name } alertController.addAction(UIAlertAction(title: "Send to Friend", style: .default) { [weak self] _ in let trackOptionsVC = TrackOptionsViewController() trackOptionsVC.track = self?.track let trackOptionsNav = NavigationController(rootViewController: trackOptionsVC) UIApplication.topViewController()?.present(trackOptionsNav, animated: true, completion: nil) }) if let topViewController = UIApplication.topViewController() { /*if !(topViewController is AlbumViewController) { alertController.addAction(UIAlertAction(title: "Go to Album", style: .default, handler: { [weak self] _ in let albumVC = AlbumViewController() albumVC.album = self?.track?.album topViewController.navigationController?.pushViewController(albumVC, animated: true) })) } if !(topViewController is ArtistViewController) { alertController.addAction(UIAlertAction(title: "Go to Artist", style: .default, handler: { [weak self] _ in let artistVC = ArtistViewController() artistVC.artist = self?.track?.artists?.first topViewController.navigationController?.pushViewController(artistVC, animated: true) })) }*/ alertController.addAction(UIAlertAction(title: "Open in Spotify", style: .default) { [weak self] _ in if let uri = self?.track?.uri, let url = URL(string: uri), UIApplication.shared.canOpenURL(url) { UIApplication.shared.openURL(url) } else if let href = self?.track?.externalUrls?.spotify, let url = URL(string: href), UIApplication.shared.canOpenURL(url) { UIApplication.shared.openURL(url) } }) if let playlistVC = topViewController as? PlaylistViewController, User.current.id == playlistVC.playlist?.owner?.id { alertController.addAction(UIAlertAction(title: "Remove from playlist", style: .destructive, handler: { [weak self] _ in playlistVC.removeFromPlaylist(track: self?.track, position: self?.position) })) } } alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) UIApplication.topViewController()?.present(alertController, animated: true, completion: nil) } }
2eee2079694ec14ceb23887f3c1042d4
35.383562
208
0.678087
false
false
false
false
catalanjrj/BarMate
refs/heads/master
BarMateCustomer/BarMateCustomer/barMenuViewViewController.swift
cc0-1.0
1
// // barMenuViewViewController.swift // BarMateCustomer // // Created by Jorge Catalan on 6/23/16. // Copyright © 2016 Jorge Catalan. All rights reserved. // import UIKit import Firebase import FirebaseDatabase class barMenuViewViewController:UIViewController,UITableViewDelegate,UITableViewDataSource { @IBOutlet weak var barMenuTableView: UITableView! @IBOutlet weak var barNameLabel: UILabel! var ref : FIRDatabaseReference = FIRDatabase.database().reference() var barMenuArray = [String]() var barMenuDict = [String:Drink]() override func viewDidLoad() { super.viewDidLoad() //present drinkReady Alert drinkReadyPopUp() } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) // remove observers when user leaves view self.ref.removeAllObservers() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) bars() } // retrive barMenus func bars(){ self.ref.child("Bars").child("aowifjeafasg").observeEventType(FIRDataEventType.Value, withBlock: {(snapshot) in guard snapshot.value != nil else{ return } self.barMenuArray = [String]() self.barMenuDict = [String:Drink]() for (key,value)in snapshot.value!["barMenu"] as! [String:AnyObject]{ self.barMenuArray.append(key) self.barMenuDict[key] = Drink(data: value as! [String:AnyObject]) } dispatch_async(dispatch_get_main_queue(), {self.barMenuTableView.reloadData()}) }) } // MARK: - Table view data source func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return barMenuArray.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("drinkMenuTableCell", forIndexPath: indexPath)as! drinkMenuTableCell let label = barMenuArray[indexPath.row] let bar = barMenuDict[label] cell.configurMenuCell(bar!) return cell } // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "drinkDetailView"{ if let indexPath = self.barMenuTableView.indexPathForSelectedRow{ let object = barMenuArray[indexPath.row] let destinationViewController = segue.destinationViewController as! confirmOrderViewController destinationViewController.drink = barMenuDict[object] } } // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } func barNameLabel(bar:Bar){ barNameLabel.text = bar.barName } func drinkReadyPopUp(){ _ = self.ref.child("Orders/completed/").queryOrderedByChild("bar").queryEqualToValue("aowifjeafasg").observeEventType(FIRDataEventType.ChildAdded, withBlock: {(snapshot) in if snapshot.value != nil{ let drinkReadyAlert = UIAlertController(title:"Order Status", message: "Your order is ready for pick up!", preferredStyle: .Alert) let okAction = UIAlertAction(title:"Ok",style: .Default){(action) in } drinkReadyAlert.addAction(okAction) self.presentViewController(drinkReadyAlert, animated:true){} }else{ return } }) } }
92baa548751251095d79efe181494f53
30.376812
180
0.604157
false
false
false
false
IngmarStein/swift
refs/heads/master
test/SILGen/switch.swift
apache-2.0
3
// RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s func markUsed<T>(_ t: T) {} // TODO: Implement tuple equality in the library. // BLOCKED: <rdar://problem/13822406> func ~= (x: (Int, Int), y: (Int, Int)) -> Bool { return x.0 == y.0 && x.1 == y.1 } // Some fake predicates for pattern guards. func runced() -> Bool { return true } func funged() -> Bool { return true } func ansed() -> Bool { return true } func foo() -> Int { return 0 } func bar() -> Int { return 0 } func foobar() -> (Int, Int) { return (0, 0) } func a() {} func b() {} func c() {} func d() {} func e() {} func f() {} func g() {} // CHECK-LABEL: sil hidden @_TF6switch5test1FT_T_ func test1() { switch foo() { // CHECK: function_ref @_TF6switch3fooFT_Si case _: // CHECK: function_ref @_TF6switch1aFT_T_ // CHECK: br [[CONT:bb[0-9]+]] a() } // CHECK: [[CONT]]: // CHECK: function_ref @_TF6switch1bFT_T_ b() } // CHECK-LABEL: sil hidden @_TF6switch5test2FT_T_ func test2() { switch foo() { // CHECK: function_ref @_TF6switch3fooFT_Si case _: // CHECK: function_ref @_TF6switch1aFT_T_ // CHECK: br [[CONT:bb[0-9]+]] a() case _: // The second case is unreachable. b() } // CHECK: [[CONT]]: // CHECK: function_ref @_TF6switch1cFT_T_ c() } // CHECK-LABEL: sil hidden @_TF6switch5test3FT_T_ func test3() { switch foo() { // CHECK: function_ref @_TF6switch3fooFT_Si // CHECK: function_ref @_TF6switch6runcedFT_Sb // CHECK: cond_br {{%.*}}, [[CASE1:bb[0-9]+]], [[NO_CASE2:bb[0-9]+]] case _ where runced(): // CHECK: [[CASE1]]: // CHECK: function_ref @_TF6switch1aFT_T_ // CHECK: br [[CONT:bb[0-9]+]] a() // CHECK: [[NO_CASE2]]: // CHECK: br [[CASE2:bb[0-9]+]] case _: // CHECK: [[CASE2]]: // CHECK: function_ref @_TF6switch1bFT_T_ // CHECK: br [[CONT]] b() } // CHECK: [[CONT]]: // CHECK: function_ref @_TF6switch1cFT_T_ c() } // CHECK-LABEL: sil hidden @_TF6switch5test4FT_T_ func test4() { switch (foo(), bar()) { // CHECK: function_ref @_TF6switch3fooFT_Si // CHECK: function_ref @_TF6switch3barFT_Si case _: // CHECK: function_ref @_TF6switch1aFT_T_ // CHECK: br [[CONT:bb[0-9]+]] a() } // CHECK: [[CONT]]: // CHECK: function_ref @_TF6switch1bFT_T_ b() } // CHECK-LABEL: sil hidden @_TF6switch5test5FT_T_ func test5() { switch (foo(), bar()) { // CHECK: function_ref @_TF6switch3fooFT_Si // CHECK: function_ref @_TF6switch3barFT_Si // CHECK: function_ref @_TF6switch6runcedFT_Sb // CHECK: cond_br {{%.*}}, [[CASE1:bb[0-9]+]], [[NOT_CASE1:bb[0-9]+]] case _ where runced(): // CHECK: [[CASE1]]: // CHECK: function_ref @_TF6switch1aFT_T_ // CHECK: br [[CONT:bb[0-9]+]] a() // CHECK: [[NOT_CASE1]]: // CHECK: function_ref @_TF6switch6fungedFT_Sb // CHECK: cond_br {{%.*}}, [[YES_CASE2:bb[0-9]+]], [[NOT_CASE2:bb[0-9]+]] // CHECK: [[YES_CASE2]]: case (_, _) where funged(): // CHECK: function_ref @_TF6switch1bFT_T_ // CHECK: br [[CONT]] b() // CHECK: [[NOT_CASE2]]: // CHECK: br [[CASE3:bb[0-9]+]] case _: // CHECK: [[CASE3]]: // CHECK: function_ref @_TF6switch1cFT_T_ // CHECK: br [[CONT]] c() } // CHECK: [[CONT]]: // CHECK: function_ref @_TF6switch1dFT_T_ d() } // CHECK-LABEL: sil hidden @_TF6switch5test6FT_T_ func test6() { switch (foo(), bar()) { // CHECK: function_ref @_TF6switch3fooFT_Si // CHECK: function_ref @_TF6switch3barFT_Si case (_, _): // CHECK: function_ref @_TF6switch1aFT_T_ // CHECK: br [[CONT:bb[0-9]+]] a() case (_, _): // The second case is unreachable. b() } // CHECK: [[CONT]]: // CHECK: function_ref @_TF6switch1cFT_T_ c() } // CHECK-LABEL: sil hidden @_TF6switch5test7FT_T_ func test7() { switch (foo(), bar()) { // CHECK: function_ref @_TF6switch3fooFT_Si // CHECK: function_ref @_TF6switch3barFT_Si // CHECK: function_ref @_TF6switch6runcedFT_Sb // CHECK: cond_br {{%.*}}, [[YES_CASE1:bb[0-9]+]], [[NOT_CASE1:bb[0-9]+]] // CHECK: [[YES_CASE1]]: case (_, _) where runced(): // CHECK: function_ref @_TF6switch1aFT_T_ // CHECK: br [[CONT:bb[0-9]+]] a() // CHECK: [[NOT_CASE1]]: // CHECK: br [[CASE2:bb[0-9]+]] case (_, _): // CHECK: [[CASE2]]: // CHECK: function_ref @_TF6switch1bFT_T_ // CHECK: br [[CONT]] b() } c() // CHECK: [[CONT]]: // CHECK: function_ref @_TF6switch1cFT_T_ } // CHECK-LABEL: sil hidden @_TF6switch5test8FT_T_ func test8() { switch (foo(), bar()) { // CHECK: function_ref @_TF6switch3fooFT_Si // CHECK: function_ref @_TF6switch3barFT_Si // CHECK: function_ref @_TF6switch6foobarFT_TSiSi_ // CHECK: cond_br {{%.*}}, [[CASE1:bb[0-9]+]], [[NOT_CASE1:bb[0-9]+]] case foobar(): // CHECK: [[CASE1]]: // CHECK: function_ref @_TF6switch1aFT_T_ // CHECK: br [[CONT:bb[0-9]+]] a() // CHECK: [[NOT_CASE1]]: // CHECK: function_ref @_TF6switch3fooFT_Si // CHECK: cond_br {{%.*}}, [[CASE2:bb[0-9]+]], [[NOT_CASE2:bb[0-9]+]] case (foo(), _): // CHECK: [[CASE2]]: // CHECK: function_ref @_TF6switch1bFT_T_ // CHECK: br [[CONT]] b() // CHECK: [[NOT_CASE2]]: // CHECK: function_ref @_TF6switch3barFT_Si // CHECK: cond_br {{%.*}}, [[CASE3_GUARD:bb[0-9]+]], [[NOT_CASE3:bb[0-9]+]] // CHECK: [[CASE3_GUARD]]: // CHECK: function_ref @_TF6switch6runcedFT_Sb // CHECK: cond_br {{%.*}}, [[CASE3:bb[0-9]+]], [[NOT_CASE3_GUARD:bb[0-9]+]] case (_, bar()) where runced(): // CHECK: [[CASE3]]: // CHECK: function_ref @_TF6switch1cFT_T_ // CHECK: br [[CONT]] c() // CHECK: [[NOT_CASE3_GUARD]]: // CHECK: [[NOT_CASE3]]: // CHECK: function_ref @_TF6switch3fooFT_Si // CHECK: cond_br {{%.*}}, [[CASE4_GUARD_1:bb[0-9]+]], [[NOT_CASE4_1:bb[0-9]+]] // CHECK: [[CASE4_GUARD_1]]: // CHECK: function_ref @_TF6switch3barFT_Si // CHECK: cond_br {{%.*}}, [[CASE4_GUARD_2:bb[0-9]+]], [[NOT_CASE4_2:bb[0-9]+]] // CHECK: [[CASE4_GUARD_2]]: // CHECK: function_ref @_TF6switch6fungedFT_Sb // CHECK: cond_br {{%.*}}, [[CASE4:bb[0-9]+]], [[NOT_CASE4_3:bb[0-9]+]] case (foo(), bar()) where funged(): // CHECK: [[CASE4]]: // CHECK: function_ref @_TF6switch1dFT_T_ // CHECK: br [[CONT]] d() // CHECK: [[NOT_CASE4_3]]: // CHECK: [[NOT_CASE4_2]]: // CHECK: [[NOT_CASE4_1]]: // CHECK: function_ref @_TF6switch3fooFT_Si // CHECK: cond_br {{%.*}}, [[CASE5_GUARD_1:bb[0-9]+]], [[NOT_CASE5:bb[0-9]+]] // CHECK: [[CASE5_GUARD_1]]: // CHECK: function_ref @_TF6switch3barFT_Si // CHECK: cond_br {{%.*}}, [[YES_CASE5:bb[0-9]+]], [[NOT_CASE5:bb[0-9]+]] // CHECK: [[YES_CASE5]]: case (foo(), bar()): // CHECK: function_ref @_TF6switch1eFT_T_ // CHECK: br [[CONT]] e() // CHECK: [[NOT_CASE5]]: // CHECK: br [[CASE6:bb[0-9]+]] case _: // CHECK: [[CASE6]]: // CHECK: function_ref @_TF6switch1fFT_T_ // CHECK: br [[CONT]] f() } // CHECK: [[CONT]]: // CHECK: function_ref @_TF6switch1gFT_T_ g() } // CHECK-LABEL: sil hidden @_TF6switch5test9FT_T_ func test9() { switch (foo(), bar()) { // CHECK: function_ref @_TF6switch3fooFT_Si // CHECK: function_ref @_TF6switch3barFT_Si // CHECK: function_ref @_TF6switch3fooFT_Si // CHECK: cond_br {{%.*}}, [[YES_CASE1:bb[0-9]+]], [[NOT_CASE1:bb[0-9]+]] // CHECK: [[YES_CASE1]]: case (foo(), _): // CHECK: function_ref @_TF6switch1aFT_T_ // CHECK: br [[CONT:bb[0-9]+]] a() // CHECK: [[NOT_CASE1]]: // CHECK: function_ref @_TF6switch6foobarFT_TSiSi_ // CHECK: cond_br {{%.*}}, [[CASE2:bb[0-9]+]], [[NOT_CASE2:bb[0-9]+]] case foobar(): // CHECK: [[CASE2]]: // CHECK: function_ref @_TF6switch1bFT_T_ // CHECK: br [[CONT]] b() // CHECK: [[NOT_CASE2]]: // CHECK: br [[CASE3:bb[0-9]+]] case _: // CHECK: [[CASE3]]: // CHECK: function_ref @_TF6switch1cFT_T_ // CHECK: br [[CONT]] c() } // CHECK: [[CONT]]: // CHECK: function_ref @_TF6switch1dFT_T_ d() } // CHECK-LABEL: sil hidden @_TF6switch6test10FT_T_ func test10() { switch (foo(), bar()) { // CHECK: function_ref @_TF6switch3fooFT_Si // CHECK: function_ref @_TF6switch3barFT_Si // CHECK: cond_br {{%.*}}, [[YES_CASE1:bb[0-9]+]], [[NOT_CASE1:bb[0-9]+]] // CHECK: [[YES_CASE1]]: case (foo()...bar(), _): // CHECK: function_ref @_TF6switch1aFT_T_ // CHECK: br [[CONT:bb[0-9]+]] a() // CHECK: [[NOT_CASE1]]: // CHECK: br [[CASE2:bb[0-9]+]] case _: // CHECK: [[CASE2]]: // CHECK: function_ref @_TF6switch1bFT_T_ // CHECK: br [[CONT]] b() } // CHECK: [[CONT]]: // CHECK: function_ref @_TF6switch1cFT_T_ c() } protocol P { func p() } struct X : P { func p() {} } struct Y : P { func p() {} } struct Z : P { func p() {} } // CHECK-LABEL: sil hidden @_TF6switch10test_isa_1FT1pPS_1P__T_ func test_isa_1(p: P) { // CHECK: [[PTMPBUF:%[0-9]+]] = alloc_stack $P // CHECK-NEXT: copy_addr %0 to [initialization] [[PTMPBUF]] : $*P switch p { // CHECK: [[TMPBUF:%[0-9]+]] = alloc_stack $X // CHECK: checked_cast_addr_br copy_on_success P in [[P:%.*]] : $*P to X in [[TMPBUF]] : $*X, [[IS_X:bb[0-9]+]], [[IS_NOT_X:bb[0-9]+]] case is X: // CHECK: [[IS_X]]: // CHECK-NEXT: load [[TMPBUF]] // CHECK-NEXT: dealloc_stack [[TMPBUF]] // CHECK-NEXT: destroy_addr [[PTMPBUF]] // CHECK-NEXT: dealloc_stack [[PTMPBUF]] a() // CHECK: function_ref @_TF6switch1aFT_T_ // CHECK: br [[CONT:bb[0-9]+]] // CHECK: [[IS_NOT_X]]: // CHECK: checked_cast_addr_br copy_on_success P in [[P]] : $*P to Y in {{%.*}} : $*Y, [[IS_Y:bb[0-9]+]], [[IS_NOT_Y:bb[0-9]+]] // CHECK: [[IS_Y]]: case is Y: // CHECK: function_ref @_TF6switch1bFT_T_ // CHECK: br [[Y_CONT:bb[0-9]+]] b() // CHECK: [[IS_NOT_Y]]: // CHECK: checked_cast_addr_br copy_on_success P in [[P]] : $*P to Z in {{%.*}} : $*Z, [[IS_Z:bb[0-9]+]], [[IS_NOT_Z:bb[0-9]+]] // CHECK: [[IS_Z]]: case is Z: // CHECK: function_ref @_TF6switch1cFT_T_ // CHECK: br [[Z_CONT:bb[0-9]+]] c() // CHECK: [[IS_NOT_Z]]: case _: // CHECK: function_ref @_TF6switch1dFT_T_ // CHECK: br [[CONT]] d() } // CHECK: [[CONT]]: // CHECK: function_ref @_TF6switch1eFT_T_ e() } // CHECK-LABEL: sil hidden @_TF6switch10test_isa_2FT1pPS_1P__T_ func test_isa_2(p: P) { switch (p, foo()) { // CHECK: checked_cast_addr_br copy_on_success P in [[P:%.*]] : $*P to X in {{%.*}} : $*X, [[IS_X:bb[0-9]+]], [[IS_NOT_X:bb[0-9]+]] // CHECK: [[IS_X]]: // CHECK: function_ref @_TF6switch3fooFT_Si // CHECK: cond_br {{%.*}}, [[CASE1:bb[0-9]+]], [[NOT_CASE1:bb[0-9]+]] case (is X, foo()): // CHECK: [[CASE1]]: // CHECK: function_ref @_TF6switch1aFT_T_ // CHECK: br [[CONT:bb[0-9]+]] a() // CHECK: [[IS_NOT_X]]: // CHECK: checked_cast_addr_br copy_on_success P in [[P]] : $*P to Y in {{%.*}} : $*Y, [[IS_Y:bb[0-9]+]], [[IS_NOT_Y:bb[0-9]+]] // CHECK: [[IS_Y]]: // CHECK: function_ref @_TF6switch3fooFT_Si // CHECK: cond_br {{%.*}}, [[CASE2:bb[0-9]+]], [[NOT_CASE2:bb[0-9]+]] case (is Y, foo()): // CHECK: [[CASE2]]: // CHECK: function_ref @_TF6switch1bFT_T_ // CHECK: br [[CONT]] b() // CHECK: [[NOT_CASE2]]: // CHECK: [[IS_NOT_Y]]: // CHECK: checked_cast_addr_br copy_on_success P in [[P:%.*]] : $*P to X in {{%.*}} : $*X, [[CASE3:bb[0-9]+]], [[IS_NOT_X:bb[0-9]+]] case (is X, _): // CHECK: [[CASE3]]: // CHECK: function_ref @_TF6switch1cFT_T_ // CHECK: br [[CONT]] c() // -- case (is Y, foo()): // CHECK: [[IS_NOT_X]]: // CHECK: checked_cast_addr_br copy_on_success P in [[P]] : $*P to Y in {{%.*}} : $*Y, [[IS_Y:bb[0-9]+]], [[IS_NOT_Y:bb[0-9]+]] // CHECK: [[IS_Y]]: // CHECK: function_ref @_TF6switch3barFT_Si // CHECK: cond_br {{%.*}}, [[CASE4:bb[0-9]+]], [[NOT_CASE4:bb[0-9]+]] case (is Y, bar()): // CHECK: [[CASE4]]: // CHECK: function_ref @_TF6switch1dFT_T_ // CHECK: br [[CONT]] d() // CHECK: [[NOT_CASE4]]: // CHECK: br [[CASE5:bb[0-9]+]] // CHECK: [[IS_NOT_Y]]: // CHECK: br [[CASE5]] case _: // CHECK: [[CASE5]]: // CHECK: function_ref @_TF6switch1eFT_T_ // CHECK: br [[CONT]] e() } // CHECK: [[CONT]]: // CHECK: function_ref @_TF6switch1fFT_T_ f() } class B {} class C : B {} class D1 : C {} class D2 : D1 {} class E : C {} // CHECK-LABEL: sil hidden @_TF6switch16test_isa_class_1FT1xCS_1B_T_ func test_isa_class_1(x: B) { // CHECK: strong_retain %0 switch x { // CHECK: checked_cast_br [[X:%.*]] : $B to $D1, [[IS_D1:bb[0-9]+]], [[IS_NOT_D1:bb[0-9]+]] // CHECK: [[IS_D1]]([[CAST_D1:%.*]]): // CHECK: function_ref @_TF6switch6runcedFT_Sb // CHECK: cond_br {{%.*}}, [[YES_CASE1:bb[0-9]+]], [[NO_CASE1:bb[0-9]+]] // CHECK: [[YES_CASE1]]: case is D1 where runced(): // CHECK: strong_release [[CAST_D1]] // CHECK: function_ref @_TF6switch1aFT_T_ // CHECK: br [[CONT:bb[0-9]+]] a() // CHECK: [[NO_CASE1]]: // CHECK: [[IS_NOT_D1]]: // CHECK: checked_cast_br [[X]] : $B to $D2, [[IS_D2:bb[0-9]+]], [[IS_NOT_D2:bb[0-9]+]] // CHECK: [[IS_D2]]([[CAST_D2:%.*]]): case is D2: // CHECK: strong_release %0 // CHECK: function_ref @_TF6switch1bFT_T_ // CHECK: br [[CONT]] b() // CHECK: [[IS_NOT_D2]]: // CHECK: checked_cast_br [[X]] : $B to $E, [[IS_E:bb[0-9]+]], [[IS_NOT_E:bb[0-9]+]] // CHECK: [[IS_E]]([[CAST_E:%.*]]): // CHECK: function_ref @_TF6switch6fungedFT_Sb // CHECK: cond_br {{%.*}}, [[CASE3:bb[0-9]+]], [[NO_CASE3:bb[0-9]+]] case is E where funged(): // CHECK: [[CASE3]]: // CHECK: function_ref @_TF6switch1cFT_T_ // CHECK: br [[CONT]] c() // CHECK: [[NO_CASE3]]: // CHECK: [[IS_NOT_E]]: // CHECK: checked_cast_br [[X]] : $B to $C, [[IS_C:bb[0-9]+]], [[IS_NOT_C:bb[0-9]+]] // CHECK: [[IS_C]]([[CAST_C:%.*]]): case is C: // CHECK: function_ref @_TF6switch1dFT_T_ // CHECK: br [[CONT]] d() // CHECK: [[IS_NOT_C]]: default: // CHECK: strong_release [[X]] // CHECK: function_ref @_TF6switch1eFT_T_ // CHECK: br [[CONT]] e() } // CHECK: [[CONT]]: // CHECK: strong_release %0 f() } // CHECK-LABEL: sil hidden @_TF6switch16test_isa_class_2FT1xCS_1B_Ps9AnyObject_ func test_isa_class_2(x: B) -> AnyObject { // CHECK: strong_retain [[X:%0]] switch x { // CHECK: checked_cast_br [[X]] : $B to $D1, [[IS_D1:bb[0-9]+]], [[IS_NOT_D1:bb[0-9]+]] // CHECK: [[IS_D1]]([[CAST_D1:%.*]]): // CHECK: strong_retain [[CAST_D1]] // CHECK: function_ref @_TF6switch6runcedFT_Sb // CHECK: cond_br {{%.*}}, [[CASE1:bb[0-9]+]], [[NO_CASE1:bb[0-9]+]] case let y as D1 where runced(): // CHECK: [[CASE1]]: // CHECK: function_ref @_TF6switch1aFT_T_ // CHECK: [[RET:%.*]] = init_existential_ref [[CAST_D1]] // CHECK: strong_release [[X]] : $B // CHECK: br [[CONT:bb[0-9]+]]([[RET]] : $AnyObject) a() return y // CHECK: [[NO_CASE1]]: // CHECK: strong_release [[CAST_D1]] // CHECK: [[IS_NOT_D1]]: // CHECK: checked_cast_br [[X]] : $B to $D2, [[CASE2:bb[0-9]+]], [[IS_NOT_D2:bb[0-9]+]] case let y as D2: // CHECK: [[CASE2]]([[CAST_D2:%.*]]): // CHECK: function_ref @_TF6switch1bFT_T_ // CHECK: [[RET:%.*]] = init_existential_ref [[CAST_D2]] // CHECK: br [[CONT]]([[RET]] : $AnyObject) b() return y // CHECK: [[IS_NOT_D2]]: // CHECK: checked_cast_br [[X]] : $B to $E, [[IS_E:bb[0-9]+]], [[IS_NOT_E:bb[0-9]+]] // CHECK: [[IS_E]]([[CAST_E:%.*]]): // CHECK: strong_retain [[CAST_E]] // CHECK: function_ref @_TF6switch6fungedFT_Sb // CHECK: cond_br {{%.*}}, [[CASE3:bb[0-9]+]], [[NO_CASE3:bb[0-9]+]] case let y as E where funged(): // CHECK: [[CASE3]]: // CHECK: function_ref @_TF6switch1cFT_T_ // CHECK: [[RET:%.*]] = init_existential_ref [[CAST_E]] // CHECK: strong_release [[X]] : $B // CHECK: br [[CONT]]([[RET]] : $AnyObject) c() return y // CHECK: [[NO_CASE3]]: // CHECK strong_release [[CAST_E]] // CHECK: [[IS_NOT_E]]: // CHECK: checked_cast_br [[X]] : $B to $C, [[CASE4:bb[0-9]+]], [[IS_NOT_C:bb[0-9]+]] case let y as C: // CHECK: [[CASE4]]([[CAST_C:%.*]]): // CHECK: function_ref @_TF6switch1dFT_T_ // CHECK: [[RET:%.*]] = init_existential_ref [[CAST_C]] // CHECK: br [[CONT]]([[RET]] : $AnyObject) d() return y // CHECK: [[IS_NOT_C]]: default: // CHECK: function_ref @_TF6switch1eFT_T_ // CHECK: [[RET:%.*]] = init_existential_ref [[X]] // CHECK: br [[CONT]]([[RET]] : $AnyObject) e() return x } // CHECK: [[CONT]]([[T0:%.*]] : $AnyObject): // CHECK: strong_release [[X]] // CHECK: return [[T0]] } enum MaybePair { case Neither case Left(Int) case Right(String) case Both(Int, String) } // CHECK-LABEL: sil hidden @_TF6switch12test_union_1FT1uOS_9MaybePair_T_ func test_union_1(u: MaybePair) { switch u { // CHECK: switch_enum [[SUBJECT:%.*]] : $MaybePair, // CHECK: case #MaybePair.Neither!enumelt: [[IS_NEITHER:bb[0-9]+]], // CHECK: case #MaybePair.Left!enumelt.1: [[IS_LEFT:bb[0-9]+]], // CHECK: case #MaybePair.Right!enumelt.1: [[IS_RIGHT:bb[0-9]+]], // CHECK: case #MaybePair.Both!enumelt.1: [[IS_BOTH:bb[0-9]+]] // CHECK: [[IS_NEITHER]]: // CHECK-NOT: release case .Neither: // CHECK: function_ref @_TF6switch1aFT_T_ // CHECK: br [[CONT:bb[0-9]+]] a() // CHECK: [[IS_LEFT]]({{%.*}}): // CHECK-NOT: release case (.Left): // CHECK: function_ref @_TF6switch1bFT_T_ // CHECK: br [[CONT]] b() // CHECK: [[IS_RIGHT]]([[STR:%.*]] : $String): case var .Right: // CHECK: release_value [[STR]] : $String // CHECK: function_ref @_TF6switch1cFT_T_ // CHECK: br [[CONT]] c() // CHECK: [[IS_BOTH]]([[TUP:%.*]] : $(Int, String)): case .Both: // CHECK: release_value [[TUP]] : $(Int, String) // CHECK: function_ref @_TF6switch1dFT_T_ // CHECK: br [[CONT]] d() } // CHECK: [[CONT]]: // CHECK-NOT: switch_enum [[SUBJECT]] // CHECK: function_ref @_TF6switch1eFT_T_ e() } // CHECK-LABEL: sil hidden @_TF6switch12test_union_2FT1uOS_9MaybePair_T_ func test_union_2(u: MaybePair) { switch u { // CHECK: switch_enum {{%.*}} : $MaybePair, // CHECK: case #MaybePair.Neither!enumelt: [[IS_NEITHER:bb[0-9]+]], // CHECK: case #MaybePair.Left!enumelt.1: [[IS_LEFT:bb[0-9]+]], // CHECK: case #MaybePair.Right!enumelt.1: [[IS_RIGHT:bb[0-9]+]], // CHECK: default [[DEFAULT:bb[0-9]+]] // CHECK: [[IS_NEITHER]]: case .Neither: // CHECK: function_ref @_TF6switch1aFT_T_ // CHECK: br [[CONT:bb[0-9]+]] a() // CHECK: [[IS_LEFT]]({{%.*}}): case .Left: // CHECK: function_ref @_TF6switch1bFT_T_ // CHECK: br [[CONT]] b() // CHECK: [[IS_RIGHT]]({{%.*}}): case .Right: // CHECK: function_ref @_TF6switch1cFT_T_ // CHECK: br [[CONT]] c() // -- missing .Both case // CHECK: [[DEFAULT]]: // CHECK: unreachable } // CHECK: [[CONT]]: // CHECK: function_ref @_TF6switch1dFT_T_ d() } // CHECK-LABEL: sil hidden @_TF6switch12test_union_3FT1uOS_9MaybePair_T_ func test_union_3(u: MaybePair) { // CHECK: retain_value [[SUBJECT:%0]] switch u { // CHECK: switch_enum [[SUBJECT]] : $MaybePair, // CHECK: case #MaybePair.Neither!enumelt: [[IS_NEITHER:bb[0-9]+]], // CHECK: case #MaybePair.Left!enumelt.1: [[IS_LEFT:bb[0-9]+]], // CHECK: case #MaybePair.Right!enumelt.1: [[IS_RIGHT:bb[0-9]+]], // CHECK: default [[DEFAULT:bb[0-9]+]] // CHECK: [[IS_NEITHER]]: case .Neither: // CHECK: function_ref @_TF6switch1aFT_T_ // CHECK: br [[CONT:bb[0-9]+]] a() // CHECK: [[IS_LEFT]]({{%.*}}): case .Left: // CHECK: function_ref @_TF6switch1bFT_T_ // CHECK: br [[CONT]] b() // CHECK: [[IS_RIGHT]]([[STR:%.*]] : $String): case .Right: // CHECK: release_value [[STR]] : $String // CHECK: function_ref @_TF6switch1cFT_T_ // CHECK: br [[CONT]] c() // CHECK: [[DEFAULT]]: // -- Ensure the fully-opaque value is destroyed in the default case. // CHECK: release_value [[SUBJECT]] : // CHECK: function_ref @_TF6switch1dFT_T_ // CHECK: br [[CONT]] default: d() } // CHECK: [[CONT]]: // CHECK-NOT: switch_enum [[SUBJECT]] // CHECK: function_ref @_TF6switch1eFT_T_ // CHECK: release_value [[SUBJECT]] e() } // CHECK-LABEL: sil hidden @_TF6switch12test_union_4FT1uOS_9MaybePair_T_ func test_union_4(u: MaybePair) { switch u { // CHECK: switch_enum {{%.*}} : $MaybePair, // CHECK: case #MaybePair.Neither!enumelt: [[IS_NEITHER:bb[0-9]+]], // CHECK: case #MaybePair.Left!enumelt.1: [[IS_LEFT:bb[0-9]+]], // CHECK: case #MaybePair.Right!enumelt.1: [[IS_RIGHT:bb[0-9]+]], // CHECK: case #MaybePair.Both!enumelt.1: [[IS_BOTH:bb[0-9]+]] // CHECK: [[IS_NEITHER]]: case .Neither(_): // CHECK: function_ref @_TF6switch1aFT_T_ // CHECK: br [[CONT:bb[0-9]+]] a() // CHECK: [[IS_LEFT]]({{%.*}}): case .Left(_): // CHECK: function_ref @_TF6switch1bFT_T_ // CHECK: br [[CONT]] b() // CHECK: [[IS_RIGHT]]({{%.*}}): case .Right(_): // CHECK: function_ref @_TF6switch1cFT_T_ // CHECK: br [[CONT]] c() // CHECK: [[IS_BOTH]]({{%.*}}): case .Both(_): // CHECK: function_ref @_TF6switch1dFT_T_ // CHECK: br [[CONT]] d() } // CHECK: [[CONT]]: // CHECK: function_ref @_TF6switch1eFT_T_ e() } // CHECK-LABEL: sil hidden @_TF6switch12test_union_5FT1uOS_9MaybePair_T_ func test_union_5(u: MaybePair) { switch u { // CHECK: switch_enum {{%.*}} : $MaybePair, // CHECK: case #MaybePair.Neither!enumelt: [[IS_NEITHER:bb[0-9]+]], // CHECK: case #MaybePair.Left!enumelt.1: [[IS_LEFT:bb[0-9]+]], // CHECK: case #MaybePair.Right!enumelt.1: [[IS_RIGHT:bb[0-9]+]], // CHECK: case #MaybePair.Both!enumelt.1: [[IS_BOTH:bb[0-9]+]] // CHECK: [[IS_NEITHER]]: case .Neither(): // CHECK: function_ref @_TF6switch1aFT_T_ // CHECK: br [[CONT:bb[0-9]+]] a() // CHECK: [[IS_LEFT]]({{%.*}}): case .Left(_): // CHECK: function_ref @_TF6switch1bFT_T_ // CHECK: br [[CONT]] b() // CHECK: [[IS_RIGHT]]({{%.*}}): case .Right(_): // CHECK: function_ref @_TF6switch1cFT_T_ // CHECK: br [[CONT]] c() // CHECK: [[IS_BOTH]]({{%.*}}): case .Both(_, _): // CHECK: function_ref @_TF6switch1dFT_T_ // CHECK: br [[CONT]] d() } // CHECK: [[CONT]]: // CHECK: function_ref @_TF6switch1eFT_T_ e() } enum MaybeAddressOnlyPair { case Neither case Left(P) case Right(String) case Both(P, String) } // CHECK-LABEL: sil hidden @_TF6switch22test_union_addr_only_1FT1uOS_20MaybeAddressOnlyPair_T_ func test_union_addr_only_1(u: MaybeAddressOnlyPair) { switch u { // CHECK: switch_enum_addr [[ENUM_ADDR:%.*]] : $*MaybeAddressOnlyPair, // CHECK: case #MaybeAddressOnlyPair.Neither!enumelt: [[IS_NEITHER:bb[0-9]+]], // CHECK: case #MaybeAddressOnlyPair.Left!enumelt.1: [[IS_LEFT:bb[0-9]+]], // CHECK: case #MaybeAddressOnlyPair.Right!enumelt.1: [[IS_RIGHT:bb[0-9]+]], // CHECK: case #MaybeAddressOnlyPair.Both!enumelt.1: [[IS_BOTH:bb[0-9]+]] // CHECK: [[IS_NEITHER]]: case .Neither: // CHECK: function_ref @_TF6switch1aFT_T_ // CHECK: br [[CONT:bb[0-9]+]] a() // CHECK: [[IS_LEFT]]: // CHECK: [[P:%.*]] = unchecked_take_enum_data_addr [[ENUM_ADDR]] : $*MaybeAddressOnlyPair, #MaybeAddressOnlyPair.Left!enumelt.1 case .Left(_): // CHECK: destroy_addr [[P]] // CHECK: function_ref @_TF6switch1bFT_T_ // CHECK: br [[CONT]] b() // CHECK: [[IS_RIGHT]]: // CHECK: [[STR_ADDR:%.*]] = unchecked_take_enum_data_addr [[ENUM_ADDR]] : $*MaybeAddressOnlyPair, #MaybeAddressOnlyPair.Right!enumelt.1 // CHECK: [[STR:%.*]] = load [[STR_ADDR]] case .Right(_): // CHECK: release_value [[STR]] : $String // CHECK: function_ref @_TF6switch1cFT_T_ // CHECK: br [[CONT]] c() // CHECK: [[IS_BOTH]]: // CHECK: [[P_STR_TUPLE:%.*]] = unchecked_take_enum_data_addr [[ENUM_ADDR]] : $*MaybeAddressOnlyPair, #MaybeAddressOnlyPair.Both!enumelt.1 case .Both(_): // CHECK: destroy_addr [[P_STR_TUPLE]] // CHECK: function_ref @_TF6switch1dFT_T_ // CHECK: br [[CONT]] d() } // CHECK: [[CONT]]: // CHECK: function_ref @_TF6switch1eFT_T_ e() } enum Generic<T, U> { case Foo(T) case Bar(U) } // Check that switching over a generic instance generates verified SIL. func test_union_generic_instance(u: Generic<Int, String>) { switch u { case .Foo(var x): a() case .Bar(var y): b() } c() } enum Foo { case A, B } // CHECK-LABEL: sil hidden @_TF6switch22test_switch_two_unionsFT1xOS_3Foo1yS0__T_ func test_switch_two_unions(x: Foo, y: Foo) { // CHECK: [[T0:%.*]] = tuple (%0 : $Foo, %1 : $Foo) // CHECK: [[X:%.*]] = tuple_extract [[T0]] : $(Foo, Foo), 0 // CHECK: [[Y:%.*]] = tuple_extract [[T0]] : $(Foo, Foo), 1 // CHECK: switch_enum [[Y]] : $Foo, case #Foo.A!enumelt: [[IS_CASE1:bb[0-9]+]], default [[IS_NOT_CASE1:bb[0-9]+]] switch (x, y) { // CHECK: [[IS_CASE1]]: case (_, Foo.A): // CHECK: function_ref @_TF6switch1aFT_T_ a() // CHECK: [[IS_NOT_CASE1]]: // CHECK: switch_enum [[X]] : $Foo, case #Foo.B!enumelt: [[IS_CASE2:bb[0-9]+]], default [[IS_NOT_CASE2:bb[0-9]+]] // CHECK: [[IS_CASE2]]: case (Foo.B, _): // CHECK: function_ref @_TF6switch1bFT_T_ b() // CHECK: [[IS_NOT_CASE2]]: // CHECK: switch_enum [[Y]] : $Foo, case #Foo.B!enumelt: [[IS_CASE3:bb[0-9]+]], default [[UNREACHABLE:bb[0-9]+]] // CHECK: [[IS_CASE3]]: case (_, Foo.B): // CHECK: function_ref @_TF6switch1cFT_T_ c() // CHECK: [[UNREACHABLE]]: // CHECK: unreachable } } // <rdar://problem/14826416> func rdar14826416<T, U>(t: T, u: U) { switch t { case is Int: markUsed("Int") case is U: markUsed("U") case _: markUsed("other") } } // CHECK-LABEL: sil hidden @_TF6switch12rdar14826416 // CHECK: checked_cast_addr_br copy_on_success T in {{%.*}} : $*T to Int in {{%.*}} : $*Int, [[IS_INT:bb[0-9]+]], [[ISNT_INT:bb[0-9]+]] // CHECK: [[ISNT_INT]]: // CHECK: checked_cast_addr_br copy_on_success T in {{%.*}} : $*T to U in {{%.*}} : $*U, [[ISNT_INT_IS_U:bb[0-9]+]], [[ISNT_INT_ISNT_U:bb[0-9]+]] // <rdar://problem/14835992> class Rdar14835992 {} class SubRdar14835992 : Rdar14835992 {} // CHECK-LABEL: sil hidden @_TF6switch12rdar14835992 func rdar14835992<T, U>(t: Rdar14835992, tt: T, uu: U) { switch t { case is SubRdar14835992: markUsed("Sub") case is T: markUsed("T") case is U: markUsed("U") case _: markUsed("other") } } // <rdar://problem/17272985> enum ABC { case A, B, C } // CHECK-LABEL: sil hidden @_TF6switch18testTupleWildcardsFTOS_3ABCS0__T_ // CHECK: [[X:%.*]] = tuple_extract {{%.*}} : $(ABC, ABC), 0 // CHECK: [[Y:%.*]] = tuple_extract {{%.*}} : $(ABC, ABC), 1 // CHECK: switch_enum [[X]] : $ABC, case #ABC.A!enumelt: [[X_A:bb[0-9]+]], default [[X_NOT_A:bb[0-9]+]] // CHECK: [[X_A]]: // CHECK: function_ref @_TF6switch1aFT_T_ // CHECK: [[X_NOT_A]]: // CHECK: switch_enum [[Y]] : $ABC, case #ABC.A!enumelt: [[Y_A:bb[0-9]+]], case #ABC.B!enumelt: [[Y_B:bb[0-9]+]], case #ABC.C!enumelt: [[Y_C:bb[0-9]+]] // CHECK-NOT: default // CHECK: [[Y_A]]: // CHECK: function_ref @_TF6switch1bFT_T_ // CHECK: [[Y_B]]: // CHECK: function_ref @_TF6switch1cFT_T_ // CHECK: [[Y_C]]: // CHECK: switch_enum [[X]] : $ABC, case #ABC.C!enumelt: [[X_C:bb[0-9]+]], default [[X_NOT_C:bb[0-9]+]] // CHECK: [[X_C]]: // CHECK: function_ref @_TF6switch1dFT_T_ // CHECK: [[X_NOT_C]]: // CHECK: function_ref @_TF6switch1eFT_T_ func testTupleWildcards(_ x: ABC, _ y: ABC) { switch (x, y) { case (.A, _): a() case (_, .A): b() case (_, .B): c() case (.C, .C): d() default: e() } } enum LabeledScalarPayload { case Payload(name: Int) } // CHECK-LABEL: sil hidden @_TF6switch24testLabeledScalarPayloadFOS_20LabeledScalarPayloadP_ func testLabeledScalarPayload(_ lsp: LabeledScalarPayload) -> Any { // CHECK: switch_enum {{%.*}}, case #LabeledScalarPayload.Payload!enumelt.1: bb1 switch lsp { // CHECK: bb1([[TUPLE:%.*]] : $(name: Int)): // CHECK: [[X:%.*]] = tuple_extract [[TUPLE]] // CHECK: [[ANY_X_ADDR:%.*]] = init_existential_addr {{%.*}}, $Int // CHECK: store [[X]] to [[ANY_X_ADDR]] case let .Payload(x): return x } } // There should be no unreachable generated. // CHECK-LABEL: sil hidden @_TF6switch19testOptionalPatternFGSqSi_T_ func testOptionalPattern(_ value : Int?) { // CHECK: switch_enum %0 : $Optional<Int>, case #Optional.some!enumelt.1: bb1, case #Optional.none!enumelt: [[NILBB:bb[0-9]+]] switch value { case 1?: a() case 2?: b() case nil: d() default: e() } } // x? and .none should both be considered "similar" and thus handled in the same // switch on the enum kind. There should be no unreachable generated. // CHECK-LABEL: sil hidden @_TF6switch19testOptionalEnumMixFGSqSi_Si func testOptionalEnumMix(_ a : Int?) -> Int { // CHECK: debug_value %0 : $Optional<Int>, let, name "a" // CHECK-NEXT: switch_enum %0 : $Optional<Int>, case #Optional.some!enumelt.1: [[SOMEBB:bb[0-9]+]], case #Optional.none!enumelt: [[NILBB:bb[0-9]+]] switch a { case let x?: return 0 // CHECK: [[SOMEBB]](%3 : $Int): // CHECK-NEXT: debug_value %3 : $Int, let, name "x" // CHECK: integer_literal $Builtin.Int2048, 0 case .none: return 42 // CHECK: [[NILBB]]: // CHECK: integer_literal $Builtin.Int2048, 42 } } // x? and nil should both be considered "similar" and thus handled in the same // switch on the enum kind. There should be no unreachable generated. // CHECK-LABEL: sil hidden @_TF6switch26testOptionalEnumMixWithNilFGSqSi_Si func testOptionalEnumMixWithNil(_ a : Int?) -> Int { // CHECK: debug_value %0 : $Optional<Int>, let, name "a" // CHECK-NEXT: switch_enum %0 : $Optional<Int>, case #Optional.some!enumelt.1: [[SOMEBB:bb[0-9]+]], case #Optional.none!enumelt: [[NILBB:bb[0-9]+]] switch a { case let x?: return 0 // CHECK: [[SOMEBB]](%3 : $Int): // CHECK-NEXT: debug_value %3 : $Int, let, name "x" // CHECK: integer_literal $Builtin.Int2048, 0 case nil: return 42 // CHECK: [[NILBB]]: // CHECK: integer_literal $Builtin.Int2048, 42 } }
d9171e379bcade628a4660844ab5c9bf
28.617332
159
0.548706
false
true
false
false
nervousnet/nervousnet-iOS
refs/heads/master
Pods/Zip/Zip/ZipUtilities.swift
gpl-3.0
1
// // ZipUtilities.swift // Zip // // Created by Roy Marmelstein on 26/01/2016. // Copyright © 2016 Roy Marmelstein. All rights reserved. // import Foundation internal class ZipUtilities { // File manager let fileManager = NSFileManager.defaultManager() /** * ProcessedFilePath struct */ internal struct ProcessedFilePath { let filePathURL: NSURL let fileName: String? func filePath() -> String { if let filePath = filePathURL.path { return filePath } else { return String() } } } //MARK: Path processing /** Process zip paths - parameter paths: Paths as NSURL. - returns: Array of ProcessedFilePath structs. */ internal func processZipPaths(paths: [NSURL]) -> [ProcessedFilePath]{ var processedFilePaths = [ProcessedFilePath]() for path in paths { guard let filePath = path.path else { continue } var isDirectory: ObjCBool = false fileManager.fileExistsAtPath(filePath, isDirectory: &isDirectory) if !isDirectory { let processedPath = ProcessedFilePath(filePathURL: path, fileName: path.lastPathComponent) processedFilePaths.append(processedPath) } else { let directoryContents = expandDirectoryFilePath(path) processedFilePaths.appendContentsOf(directoryContents) } } return processedFilePaths } /** Recursive function to expand directory contents and parse them into ProcessedFilePath structs. - parameter directory: Path of folder as NSURL. - returns: Array of ProcessedFilePath structs. */ internal func expandDirectoryFilePath(directory: NSURL) -> [ProcessedFilePath] { var processedFilePaths = [ProcessedFilePath]() if let directoryPath = directory.path, let enumerator = fileManager.enumeratorAtPath(directoryPath) { while let filePathComponent = enumerator.nextObject() as? String { let path = directory.URLByAppendingPathComponent(filePathComponent) guard let filePath = path.path, let directoryName = directory.lastPathComponent else { continue } var isDirectory: ObjCBool = false fileManager.fileExistsAtPath(filePath, isDirectory: &isDirectory) if !isDirectory { let fileName = (directoryName as NSString).stringByAppendingPathComponent(filePathComponent) let processedPath = ProcessedFilePath(filePathURL: path, fileName: fileName) processedFilePaths.append(processedPath) } else { let directoryContents = expandDirectoryFilePath(path) processedFilePaths.appendContentsOf(directoryContents) } } } return processedFilePaths } }
24ce6d3476252e116951a5b036955f6e
32.404255
112
0.596687
false
false
false
false
Shivol/Swift-CS333
refs/heads/master
assignments/task5/schedule/schedule/DataLoader.swift
mit
2
// // DataLoader.swift // schedule // // Created by Илья Лошкарёв on 30.03.17. // Copyright © 2017 mmcs. All rights reserved. // import Foundation import UIKit protocol DataLoader: class { func loadData() var source: URL { get } weak var delegate: DataLoaderDelegate? { get set } } protocol DataLoaderDelegate: class { func dataLoader(_ dataLoader: DataLoader, didFinishLoadingWith data: Any?) func dataLoader(_ dataLoader: DataLoader, didFinishLoadingWith error: NSError) } class JSONDataLoader<T>: DataLoader { let source: URL weak var delegate: DataLoaderDelegate? private(set) var parsedData: T? = nil init(with url: URL) { source = url } func errorFor(response: URLResponse?, with data: Data?, error: Error?) -> NSError? { if let error = error as? NSError { return error } guard data != nil else { return NSError(domain: "Empty Response", code: 0, userInfo: ["response": response as Any]) } guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else { return NSError(domain: "Unexpected Response", code: 0, userInfo: ["response": response as Any]) } return nil } func loadData() { let task = URLSession.shared.dataTask(with: source) { (data, response, error) in if let error = self.errorFor(response: response, with: data, error: error) { DispatchQueue.main.async { self.delegate?.dataLoader(self, didFinishLoadingWith: error) } return } do { let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String:Any] self.parsedData = try self.parseJSON(json) DispatchQueue.main.async { self.delegate?.dataLoader(self, didFinishLoadingWith: self.parsedData) } } catch let error as NSError { DispatchQueue.main.async { self.delegate?.dataLoader(self, didFinishLoadingWith: error) } } } task.resume() } func parseJSON(_ json: [String : Any] ) throws -> T { let typename = String(describing: T.self) guard let result = json[typename] as? T else { throw NSError(domain: "JSON Error", code: 0, userInfo: ["json" : json]) } return result } }
5816d33faf8c516f3bfd5b3740587b97
30.634146
115
0.570933
false
false
false
false
RevenueCat/purchases-ios
refs/heads/main
Tests/UnitTests/Purchasing/PurchasesDeprecation.swift
mit
1
// // Copyright RevenueCat Inc. All Rights Reserved. // // Licensed under the MIT License (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://opensource.org/licenses/MIT // // PurchasesDeprecation.swift // // Created by Joshua Liebowitz on 10/18/21. import Foundation import RevenueCat // Protocol that enables us to call deprecated methods without triggering warnings. protocol PurchasesDeprecatable { var allowSharingAppStoreAccount: Bool { get set } static func addAttributionData(_ data: [String: Any], fromNetwork network: AttributionNetwork) static func addAttributionData(_ data: [String: Any], from network: AttributionNetwork, forNetworkUserId networkUserId: String?) static var automaticAppleSearchAdsAttributionCollection: Bool { get set } } class PurchasesDeprecation: PurchasesDeprecatable { let purchases: Purchases init(purchases: Purchases) { self.purchases = purchases } @available(*, deprecated) var allowSharingAppStoreAccount: Bool { get { return purchases.allowSharingAppStoreAccount } set { purchases.allowSharingAppStoreAccount = newValue } } @available(*, deprecated) static func addAttributionData(_ data: [String: Any], fromNetwork network: AttributionNetwork) { Purchases.addAttributionData(data, fromNetwork: network) } @available(*, deprecated) static func addAttributionData(_ data: [String: Any], from network: AttributionNetwork, forNetworkUserId networkUserId: String?) { Purchases.addAttributionData(data, from: network, forNetworkUserId: networkUserId) } @available(*, deprecated) static var automaticAppleSearchAdsAttributionCollection: Bool { get { return Purchases.automaticAppleSearchAdsAttributionCollection } set { Purchases.automaticAppleSearchAdsAttributionCollection = newValue } } } extension Purchases { /** * Computed property you should use if you receive deprecation warnings. This is a proxy for a Purchases object. * By calling `.deprecated` you will have access to the same API, but it won't trigger a deprecation. * If you need to set a property that is deprecated, you'll need to create a var in your test to hold a copy of * the `deprecated` object. This is because the `deprecated` property is computed and so you cannot mutate it. * e.g.: * var deprecatedVarObject = purchases.deprecated * deprecatedVarObject.allowSharingAppStoreAccount = true */ var deprecated: PurchasesDeprecatable { return PurchasesDeprecation(purchases: self) } /** * Computed property you should use if you receive deprecation warnings. This is a proxy for the Purchases class. * By calling `.deprecated` you will have access to the same API, but it won't trigger a deprecation. */ static var deprecated: PurchasesDeprecatable.Type { return PurchasesDeprecation.self } }
0c363119ea2b56ddaf1e918dfbd4896d
34.086957
117
0.686493
false
false
false
false
Johennes/firefox-ios
refs/heads/master
Sync/Synchronizers/Bookmarks/Merging.swift
mpl-2.0
4
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Deferred import Foundation import Shared import Storage import XCGLogger private let log = Logger.syncLogger // Because generic protocols in Swift are a pain in the ass. public protocol BookmarkStorer: class { // TODO: this should probably return a timestamp. func applyUpstreamCompletionOp(op: UpstreamCompletionOp, itemSources: ItemSources, trackingTimesInto local: LocalOverrideCompletionOp) -> Deferred<Maybe<POSTResult>> } public class UpstreamCompletionOp: PerhapsNoOp { // Upload these records from the buffer, but with these child lists. public var amendChildrenFromBuffer: [GUID: [GUID]] = [:] // Upload these records from the mirror, but with these child lists. public var amendChildrenFromMirror: [GUID: [GUID]] = [:] // Upload these records from local, but with these child lists. public var amendChildrenFromLocal: [GUID: [GUID]] = [:] // Upload these records as-is. public var records: [Record<BookmarkBasePayload>] = [] public let ifUnmodifiedSince: Timestamp? public var isNoOp: Bool { return records.isEmpty } public init(ifUnmodifiedSince: Timestamp?=nil) { self.ifUnmodifiedSince = ifUnmodifiedSince } } public class BookmarksMergeResult: PerhapsNoOp { let uploadCompletion: UpstreamCompletionOp let overrideCompletion: LocalOverrideCompletionOp let bufferCompletion: BufferCompletionOp let itemSources: ItemSources public var isNoOp: Bool { return self.uploadCompletion.isNoOp && self.overrideCompletion.isNoOp && self.bufferCompletion.isNoOp } func applyToClient(client: BookmarkStorer, storage: SyncableBookmarks, buffer: BookmarkBufferStorage) -> Success { return client.applyUpstreamCompletionOp(self.uploadCompletion, itemSources: self.itemSources, trackingTimesInto: self.overrideCompletion) >>> { storage.applyLocalOverrideCompletionOp(self.overrideCompletion, itemSources: self.itemSources) } >>> { buffer.applyBufferCompletionOp(self.bufferCompletion, itemSources: self.itemSources) } } init(uploadCompletion: UpstreamCompletionOp, overrideCompletion: LocalOverrideCompletionOp, bufferCompletion: BufferCompletionOp, itemSources: ItemSources) { self.uploadCompletion = uploadCompletion self.overrideCompletion = overrideCompletion self.bufferCompletion = bufferCompletion self.itemSources = itemSources } static func NoOp(itemSources: ItemSources) -> BookmarksMergeResult { return BookmarksMergeResult(uploadCompletion: UpstreamCompletionOp(), overrideCompletion: LocalOverrideCompletionOp(), bufferCompletion: BufferCompletionOp(), itemSources: itemSources) } } // MARK: - Errors. public class BookmarksMergeError: MaybeErrorType { private let error: ErrorType? init(error: ErrorType?=nil) { self.error = error } public var description: String { return "Merge error: \(self.error)" } } public class BookmarksMergeConsistencyError: BookmarksMergeError { override public var description: String { return "Merge consistency error" } } public class BookmarksMergeErrorTreeIsUnrooted: BookmarksMergeConsistencyError { public let roots: Set<GUID> public init(roots: Set<GUID>) { self.roots = roots } override public var description: String { return "Tree is unrooted: roots are \(self.roots)" } } enum MergeState<T> { case Unknown // Default state. case Unchanged // Nothing changed: no work needed. case Remote // Take the associated remote value. case Local // Take the associated local value. case New(value: T) // Take this synthesized value. var isUnchanged: Bool { if case .Unchanged = self { return true } return false } var isUnknown: Bool { if case .Unknown = self { return true } return false } var label: String { switch self { case .Unknown: return "Unknown" case .Unchanged: return "Unchanged" case .Remote: return "Remote" case .Local: return "Local" case .New: return "New" } } } func ==<T: Equatable>(lhs: MergeState<T>, rhs: MergeState<T>) -> Bool { switch (lhs, rhs) { case (.Unknown, .Unknown): return true case (.Unchanged, .Unchanged): return true case (.Remote, .Remote): return true case (.Local, .Local): return true case let (.New(lh), .New(rh)): return lh == rh default: return false } } /** * Using this: * * You get one for the root. Then you give it children for the roots * from the mirror. * * Then you walk those, populating the remote and local nodes by looking * at the left/right trees. * * By comparing left and right, and doing value-based comparisons if necessary, * a merge state is decided and assigned for both value and structure. * * One then walks both left and right child structures (both to ensure that * all nodes on both left and right will be visited!) recursively. */ class MergedTreeNode { let guid: GUID let mirror: BookmarkTreeNode? var remote: BookmarkTreeNode? var local: BookmarkTreeNode? var hasLocal: Bool { return self.local != nil } var hasMirror: Bool { return self.mirror != nil } var hasRemote: Bool { return self.remote != nil } var valueState: MergeState<BookmarkMirrorItem> = MergeState.Unknown var structureState: MergeState<BookmarkTreeNode> = MergeState.Unknown var hasDecidedChildren: Bool { return !self.structureState.isUnknown } var mergedChildren: [MergedTreeNode]? = nil // One-sided constructors. static func forRemote(remote: BookmarkTreeNode, mirror: BookmarkTreeNode?=nil) -> MergedTreeNode { let n = MergedTreeNode(guid: remote.recordGUID, mirror: mirror, structureState: MergeState.Remote) n.remote = remote n.valueState = MergeState.Remote return n } static func forLocal(local: BookmarkTreeNode, mirror: BookmarkTreeNode?=nil) -> MergedTreeNode { let n = MergedTreeNode(guid: local.recordGUID, mirror: mirror, structureState: MergeState.Local) n.local = local n.valueState = MergeState.Local return n } static func forUnchanged(mirror: BookmarkTreeNode) -> MergedTreeNode { let n = MergedTreeNode(guid: mirror.recordGUID, mirror: mirror, structureState: MergeState.Unchanged) n.valueState = MergeState.Unchanged return n } init(guid: GUID, mirror: BookmarkTreeNode?, structureState: MergeState<BookmarkTreeNode>) { self.guid = guid self.mirror = mirror self.structureState = structureState } init(guid: GUID, mirror: BookmarkTreeNode?) { self.guid = guid self.mirror = mirror } // N.B., you cannot recurse down `decidedStructure`: you'll depart from the // merged tree. You need to use `mergedChildren` instead. private var decidedStructure: BookmarkTreeNode? { switch self.structureState { case .Unknown: return nil case .Unchanged: return self.mirror case .Remote: return self.remote case .Local: return self.local case let .New(node): return node } } func asUnmergedTreeNode() -> BookmarkTreeNode { return self.decidedStructure ?? BookmarkTreeNode.Unknown(guid: self.guid) } // Recursive. Starts returning Unknown when nodes haven't been processed. func asMergedTreeNode() -> BookmarkTreeNode { guard let decided = self.decidedStructure, let merged = self.mergedChildren else { return BookmarkTreeNode.Unknown(guid: self.guid) } if case .Folder = decided { let children = merged.map { $0.asMergedTreeNode() } return BookmarkTreeNode.Folder(guid: self.guid, children: children) } return decided } var isFolder: Bool { return self.mergedChildren != nil } func dump(indent: Int) { precondition(indent < 200) let r: Character = "R" let l: Character = "L" let m: Character = "M" let ind = indenting(indent) print(ind, "[V: ", box(self.remote, r), box(self.mirror, m), box(self.local, l), self.guid, self.valueState.label, "]") guard self.isFolder else { return } print(ind, "[S: ", self.structureState.label, "]") if let children = self.mergedChildren { print(ind, " ..") for child in children { child.dump(indent + 2) } } } } private func box<T>(x: T?, _ c: Character) -> Character { if x == nil { return "□" } return c } private func indenting(by: Int) -> String { return String(count: by, repeatedValue: " " as Character) } class MergedTree { var root: MergedTreeNode var deleteLocally: Set<GUID> = Set() var deleteRemotely: Set<GUID> = Set() var deleteFromMirror: Set<GUID> = Set() var acceptLocalDeletion: Set<GUID> = Set() var acceptRemoteDeletion: Set<GUID> = Set() var allGUIDs: Set<GUID> { var out = Set<GUID>([self.root.guid]) func acc(node: MergedTreeNode) { guard let children = node.mergedChildren else { return } out.unionInPlace(children.map { $0.guid }) children.forEach(acc) } acc(self.root) return out } init(mirrorRoot: BookmarkTreeNode) { self.root = MergedTreeNode(guid: mirrorRoot.recordGUID, mirror: mirrorRoot, structureState: MergeState.Unchanged) self.root.valueState = MergeState.Unchanged } func dump() { print("Deleted locally: \(self.deleteLocally.joinWithSeparator(", "))") print("Deleted remotely: \(self.deleteRemotely.joinWithSeparator(", "))") print("Deleted from mirror: \(self.deleteFromMirror.joinWithSeparator(", "))") print("Accepted local deletions: \(self.acceptLocalDeletion.joinWithSeparator(", "))") print("Accepted remote deletions: \(self.acceptRemoteDeletion.joinWithSeparator(", "))") print("Root: ") self.root.dump(0) } }
b416ee7fa40d1ef67fa8a95b61ebc819
31.370482
192
0.649577
false
false
false
false
Reedyuk/Charts
refs/heads/Swift-3.0
Charts/Classes/Renderers/HorizontalBarChartRenderer.swift
apache-2.0
6
// // HorizontalBarChartRenderer.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics #if !os(OSX) import UIKit #endif open class HorizontalBarChartRenderer: BarChartRenderer { public override init(dataProvider: BarChartDataProvider?, animator: ChartAnimator?, viewPortHandler: ChartViewPortHandler) { super.init(dataProvider: dataProvider, animator: animator, viewPortHandler: viewPortHandler) } open override func drawDataSet(context: CGContext, dataSet: IBarChartDataSet, index: Int) { guard let dataProvider = dataProvider, let barData = dataProvider.barData, let animator = animator else { return } context.saveGState() let trans = dataProvider.getTransformer(dataSet.axisDependency) let drawBarShadowEnabled: Bool = dataProvider.drawBarShadowEnabled let dataSetOffset = (barData.dataSetCount - 1) let groupSpace = barData.groupSpace let groupSpaceHalf = groupSpace / 2.0 let barSpace = dataSet.barSpace let barSpaceHalf = barSpace / 2.0 let containsStacks = dataSet.isStacked let inverted = dataProvider.inverted(dataSet.axisDependency) let barWidth: CGFloat = 0.5 let phaseY = animator.phaseY var barRect = CGRect() var barShadow = CGRect() let borderWidth = dataSet.barBorderWidth let borderColor = dataSet.barBorderColor let drawBorder = borderWidth > 0.0 var y: Double // do the drawing for j in 0 ..< Int(ceil(CGFloat(dataSet.entryCount) * animator.phaseX)) { guard let e = dataSet.entryForIndex(j) as? BarChartDataEntry else { continue } // calculate the x-position, depending on datasetcount let x = CGFloat(e.xIndex + e.xIndex * dataSetOffset) + CGFloat(index) + groupSpace * CGFloat(e.xIndex) + groupSpaceHalf let values = e.values if (!containsStacks || values == nil) { y = e.value let bottom = x - barWidth + barSpaceHalf let top = x + barWidth - barSpaceHalf var right = inverted ? (y <= 0.0 ? CGFloat(y) : 0) : (y >= 0.0 ? CGFloat(y) : 0) var left = inverted ? (y >= 0.0 ? CGFloat(y) : 0) : (y <= 0.0 ? CGFloat(y) : 0) // multiply the height of the rect with the phase if (right > 0) { right *= phaseY } else { left *= phaseY } barRect.origin.x = left barRect.size.width = right - left barRect.origin.y = top barRect.size.height = bottom - top trans.rectValueToPixel(&barRect) if (!viewPortHandler.isInBoundsLeft(barRect.origin.x + barRect.size.width)) { continue } if (!viewPortHandler.isInBoundsRight(barRect.origin.x)) { break } // if drawing the bar shadow is enabled if (drawBarShadowEnabled) { barShadow.origin.x = viewPortHandler.contentLeft barShadow.origin.y = barRect.origin.y barShadow.size.width = viewPortHandler.contentWidth barShadow.size.height = barRect.size.height context.setFillColor(dataSet.barShadowColor.cgColor) context.fill(barShadow) } // Set the color for the currently drawn value. If the index is out of bounds, reuse colors. context.setFillColor(dataSet.colorAt(j).cgColor) context.fill(barRect) if drawBorder { context.setStrokeColor(borderColor.cgColor) context.setLineWidth(borderWidth) context.stroke(barRect) } } else { let vals = values! var posY = 0.0 var negY = -e.negativeSum var yStart = 0.0 // if drawing the bar shadow is enabled if (drawBarShadowEnabled) { y = e.value let bottom = x - barWidth + barSpaceHalf let top = x + barWidth - barSpaceHalf var right = inverted ? (y <= 0.0 ? CGFloat(y) : 0) : (y >= 0.0 ? CGFloat(y) : 0) var left = inverted ? (y >= 0.0 ? CGFloat(y) : 0) : (y <= 0.0 ? CGFloat(y) : 0) // multiply the height of the rect with the phase if (right > 0) { right *= phaseY } else { left *= phaseY } barRect.origin.x = left barRect.size.width = right - left barRect.origin.y = top barRect.size.height = bottom - top trans.rectValueToPixel(&barRect) barShadow.origin.x = viewPortHandler.contentLeft barShadow.origin.y = barRect.origin.y barShadow.size.width = viewPortHandler.contentWidth barShadow.size.height = barRect.size.height context.setFillColor(dataSet.barShadowColor.cgColor) context.fill(barShadow) } // fill the stack for k in 0 ..< vals.count { let value = vals[k] if value >= 0.0 { y = posY yStart = posY + value posY = yStart } else { y = negY yStart = negY + abs(value) negY += abs(value) } let bottom = x - barWidth + barSpaceHalf let top = x + barWidth - barSpaceHalf var right: CGFloat, left: CGFloat if inverted { left = y >= yStart ? CGFloat(y) : CGFloat(yStart) right = y <= yStart ? CGFloat(y) : CGFloat(yStart) } else { right = y >= yStart ? CGFloat(y) : CGFloat(yStart) left = y <= yStart ? CGFloat(y) : CGFloat(yStart) } // multiply the height of the rect with the phase right *= phaseY left *= phaseY barRect.origin.x = left barRect.size.width = right - left barRect.origin.y = top barRect.size.height = bottom - top trans.rectValueToPixel(&barRect) if (k == 0 && !viewPortHandler.isInBoundsTop(barRect.origin.y + barRect.size.height)) { // Skip to next bar break } // avoid drawing outofbounds values if (!viewPortHandler.isInBoundsBottom(barRect.origin.y)) { break } // Set the color for the currently drawn value. If the index is out of bounds, reuse colors. context.setFillColor(dataSet.colorAt(k).cgColor) context.fill(barRect) if drawBorder { context.setStrokeColor(borderColor.cgColor) context.setLineWidth(borderWidth) context.stroke(barRect) } } } } context.restoreGState() } open override func prepareBarHighlight(x: CGFloat, y1: Double, y2: Double, barspacehalf: CGFloat, trans: ChartTransformer, rect: inout CGRect) { let barWidth: CGFloat = 0.5 let top = x - barWidth + barspacehalf let bottom = x + barWidth - barspacehalf let left = CGFloat(y1) let right = CGFloat(y2) rect.origin.x = left rect.origin.y = top rect.size.width = right - left rect.size.height = bottom - top trans.rectValueToPixelHorizontal(&rect, phaseY: animator?.phaseY ?? 1.0) } open override func drawValues(context: CGContext) { // if values are drawn if (passesCheck()) { guard let dataProvider = dataProvider, let barData = dataProvider.barData, let animator = animator else { return } var dataSets = barData.dataSets let drawValueAboveBar = dataProvider.drawValueAboveBarEnabled let textAlign = NSTextAlignment.left let valueOffsetPlus: CGFloat = 5.0 var posOffset: CGFloat var negOffset: CGFloat for dataSetIndex in 0 ..< barData.dataSetCount { guard let dataSet = dataSets[dataSetIndex] as? IBarChartDataSet else { continue } if !dataSet.drawValuesEnabled || dataSet.entryCount == 0 { continue } let inverted = dataProvider.inverted(dataSet.axisDependency) let valueFont = dataSet.valueFont let yOffset = -valueFont.lineHeight / 2.0 guard let formatter = dataSet.valueFormatter else { continue } let trans = dataProvider.getTransformer(dataSet.axisDependency) let phaseY = animator.phaseY let dataSetCount = barData.dataSetCount let groupSpace = barData.groupSpace // if only single values are drawn (sum) if (!dataSet.isStacked) { for j in 0 ..< Int(ceil(CGFloat(dataSet.entryCount) * animator.phaseX)) { guard let e = dataSet.entryForIndex(j) as? BarChartDataEntry else { continue } let valuePoint = trans.getTransformedValueHorizontalBarChart(entry: e, xIndex: e.xIndex, dataSetIndex: dataSetIndex, phaseY: phaseY, dataSetCount: dataSetCount, groupSpace: groupSpace) if (!viewPortHandler.isInBoundsTop(valuePoint.y)) { break } if (!viewPortHandler.isInBoundsX(valuePoint.x)) { continue } if (!viewPortHandler.isInBoundsBottom(valuePoint.y)) { continue } let val = e.value let valueText = formatter.string(from: val as NSNumber)! // calculate the correct offset depending on the draw position of the value let valueTextWidth = valueText.size(attributes: [NSFontAttributeName: valueFont]).width posOffset = (drawValueAboveBar ? valueOffsetPlus : -(valueTextWidth + valueOffsetPlus)) negOffset = (drawValueAboveBar ? -(valueTextWidth + valueOffsetPlus) : valueOffsetPlus) if (inverted) { posOffset = -posOffset - valueTextWidth negOffset = -negOffset - valueTextWidth } drawValue( context: context, value: valueText, xPos: valuePoint.x + (val >= 0.0 ? posOffset : negOffset), yPos: valuePoint.y + yOffset, font: valueFont, align: textAlign, color: dataSet.valueTextColorAt(j)) } } else { // if each value of a potential stack should be drawn for j in 0 ..< Int(ceil(CGFloat(dataSet.entryCount) * animator.phaseX)) { guard let e = dataSet.entryForIndex(j) as? BarChartDataEntry else { continue } let valuePoint = trans.getTransformedValueHorizontalBarChart(entry: e, xIndex: e.xIndex, dataSetIndex: dataSetIndex, phaseY: phaseY, dataSetCount: dataSetCount, groupSpace: groupSpace) let values = e.values // we still draw stacked bars, but there is one non-stacked in between if (values == nil) { if (!viewPortHandler.isInBoundsTop(valuePoint.y)) { break } if (!viewPortHandler.isInBoundsX(valuePoint.x)) { continue } if (!viewPortHandler.isInBoundsBottom(valuePoint.y)) { continue } let val = e.value let valueText = formatter.string(from: val as NSNumber)! // calculate the correct offset depending on the draw position of the value let valueTextWidth = valueText.size(attributes: [NSFontAttributeName: valueFont]).width posOffset = (drawValueAboveBar ? valueOffsetPlus : -(valueTextWidth + valueOffsetPlus)) negOffset = (drawValueAboveBar ? -(valueTextWidth + valueOffsetPlus) : valueOffsetPlus) if (inverted) { posOffset = -posOffset - valueTextWidth negOffset = -negOffset - valueTextWidth } drawValue( context: context, value: valueText, xPos: valuePoint.x + (val >= 0.0 ? posOffset : negOffset), yPos: valuePoint.y + yOffset, font: valueFont, align: textAlign, color: dataSet.valueTextColorAt(j)) } else { let vals = values! var transformed = [CGPoint]() var posY = 0.0 var negY = -e.negativeSum for k in 0 ..< vals.count { let value = vals[k] var y: Double if value >= 0.0 { posY += value y = posY } else { y = negY negY -= value } transformed.append(CGPoint(x: CGFloat(y) * animator.phaseY, y: 0.0)) } trans.pointValuesToPixel(&transformed) for k in 0 ..< transformed.count { let val = vals[k] let valueText = formatter.string(from: val as NSNumber)! // calculate the correct offset depending on the draw position of the value let valueTextWidth = valueText.size(attributes: [NSFontAttributeName: valueFont]).width posOffset = (drawValueAboveBar ? valueOffsetPlus : -(valueTextWidth + valueOffsetPlus)) negOffset = (drawValueAboveBar ? -(valueTextWidth + valueOffsetPlus) : valueOffsetPlus) if (inverted) { posOffset = -posOffset - valueTextWidth negOffset = -negOffset - valueTextWidth } let x = transformed[k].x + (val >= 0 ? posOffset : negOffset) let y = valuePoint.y if (!viewPortHandler.isInBoundsTop(y)) { break } if (!viewPortHandler.isInBoundsX(x)) { continue } if (!viewPortHandler.isInBoundsBottom(y)) { continue } drawValue(context: context, value: valueText, xPos: x, yPos: y + yOffset, font: valueFont, align: textAlign, color: dataSet.valueTextColorAt(j)) } } } } } } } internal override func passesCheck() -> Bool { guard let dataProvider = dataProvider, let barData = dataProvider.barData else { return false } return CGFloat(barData.yValCount) < CGFloat(dataProvider.maxVisibleValueCount) * viewPortHandler.scaleY } }
e3e6157ebe66f07ed02740a9dbfbfe12
41.278351
208
0.411119
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/BlockchainNamespace/Sources/BlockchainNamespace/Session/Session+Event.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Combine import Foundation extension Session { public typealias Events = PassthroughSubject<Session.Event, Never> public struct Event: Identifiable, Hashable { public let id: UInt public let date: Date public let origin: Tag.Event public let reference: Tag.Reference public let context: Tag.Context public let source: (file: String, line: Int) public var tag: Tag { reference.tag } init( date: Date = Date(), origin: Tag.Event, reference: Tag.Reference, context: Tag.Context = [:], file: String = #fileID, line: Int = #line ) { id = Self.id self.date = date self.origin = origin self.reference = reference self.context = context source = (file, line) } public func hash(into hasher: inout Hasher) { hasher.combine(id) } public static func == (lhs: Self, rhs: Self) -> Bool { lhs.id == rhs.id } } } extension Session.Event: CustomStringConvertible { public var description: String { String(describing: origin) } } extension Session.Event { private static var count: UInt = 0 private static let lock = NSLock() private static var id: UInt { lock.lock() defer { lock.unlock() } count += 1 return count } } extension Publisher where Output == Session.Event { public func filter(_ type: L) -> Publishers.Filter<Self> { filter(type[]) } public func filter(_ type: Tag) -> Publishers.Filter<Self> { filter([type]) } public func filter(_ type: Tag.Reference) -> Publishers.Filter<Self> { filter([type]) } public func filter<S: Sequence>(_ types: S) -> Publishers.Filter<Self> where S.Element == Tag { filter { $0.tag.is(types) } } public func filter<S: Sequence>(_ types: S) -> Publishers.Filter<Self> where S.Element == Tag.Reference { filter { event in types.contains { type in event.reference == type || (event.tag.is(type.tag) && type.indices.allSatisfy { event.reference.indices[$0] == $1 }) } } } } extension AppProtocol { @inlinable public func on( _ first: Tag.Event, _ rest: Tag.Event..., file: String = #fileID, line: Int = #line, action: @escaping (Session.Event) throws -> Void ) -> BlockchainEventSubscription { on([first] + rest, file: file, line: line, action: action) } @inlinable public func on( _ first: Tag.Event, _ rest: Tag.Event..., file: String = #fileID, line: Int = #line, priority: TaskPriority? = nil, action: @escaping (Session.Event) async throws -> Void ) -> BlockchainEventSubscription { on([first] + rest, file: file, line: line, priority: priority, action: action) } @inlinable public func on<Events>( _ events: Events, file: String = #fileID, line: Int = #line, action: @escaping (Session.Event) throws -> Void ) -> BlockchainEventSubscription where Events: Sequence, Events.Element: Tag.Event { on(events.map { $0 as Tag.Event }, file: file, line: line, action: action) } @inlinable public func on<Events>( _ events: Events, file: String = #fileID, line: Int = #line, priority: TaskPriority? = nil, action: @escaping (Session.Event) async throws -> Void ) -> BlockchainEventSubscription where Events: Sequence, Events.Element: Tag.Event { on(events.map { $0 as Tag.Event }, file: file, line: line, priority: priority, action: action) } @inlinable public func on<Events>( _ events: Events, file: String = #fileID, line: Int = #line, action: @escaping (Session.Event) throws -> Void ) -> BlockchainEventSubscription where Events: Sequence, Events.Element == Tag.Event { BlockchainEventSubscription( app: self, events: Array(events), file: file, line: line, action: action ) } @inlinable public func on<Events>( _ events: Events, file: String = #fileID, line: Int = #line, priority: TaskPriority? = nil, action: @escaping (Session.Event) async throws -> Void ) -> BlockchainEventSubscription where Events: Sequence, Events.Element == Tag.Event { BlockchainEventSubscription( app: self, events: Array(events), file: file, line: line, priority: priority, action: action ) } } public final class BlockchainEventSubscription: Hashable { enum Action { case sync((Session.Event) throws -> Void) case async((Session.Event) async throws -> Void) } let id: UInt let app: AppProtocol let events: [Tag.Event] let action: Action let priority: TaskPriority? let file: String, line: Int deinit { stop() } @usableFromInline init( app: AppProtocol, events: [Tag.Event], file: String, line: Int, action: @escaping (Session.Event) throws -> Void ) { id = Self.id self.app = app self.events = events self.file = file self.line = line priority = nil self.action = .sync(action) } @usableFromInline init( app: AppProtocol, events: [Tag.Event], file: String, line: Int, priority: TaskPriority? = nil, action: @escaping (Session.Event) async throws -> Void ) { id = Self.id self.app = app self.events = events self.file = file self.line = line self.priority = priority self.action = .async(action) } private var subscription: AnyCancellable? @discardableResult public func start() -> Self { guard subscription == nil else { return self } subscription = app.on(events).sink( receiveValue: { [weak self] event in guard let self = self else { return } switch self.action { case .sync(let action): do { try action(event) } catch { self.app.post(error: error, file: self.file, line: self.line) } case .async(let action): Task(priority: self.priority) { do { try await action(event) } catch { self.app.post(error: error, file: self.file, line: self.line) } } } } ) return self } public func cancel() { stop() } @discardableResult public func stop() -> Self { subscription?.cancel() subscription = nil return self } } extension BlockchainEventSubscription { @inlinable public func subscribe() -> AnyCancellable { start() return AnyCancellable { [self] in stop() } } private static var count: UInt = 0 private static let lock = NSLock() private static var id: UInt { lock.lock() defer { lock.unlock() } count += 1 return count } public static func == (lhs: BlockchainEventSubscription, rhs: BlockchainEventSubscription) -> Bool { lhs.id == rhs.id } public func hash(into hasher: inout Hasher) { hasher.combine(id) } }
13dbe8099f948d21af0b8364fae9fb2d
27.117857
109
0.546806
false
false
false
false
kamawshuang/iOS---Animation
refs/heads/master
Spring(一)/iOS Animation(一)--First:Spring/Animation-First/ViewController.swift
apache-2.0
1
// // ViewController.swift // Animation-First // // Created by 51Testing on 15/11/26. // Copyright © 2015年 HHW. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var tilteLab: UILabel! @IBOutlet weak var userTF: UITextField! @IBOutlet weak var passwordTF: UITextField! @IBOutlet weak var loginbutton: UIButton! @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var rightImageView: UIImageView! @IBOutlet weak var tomImageView: UIImageView! //在视图将要出现的时候改变坐标 override func viewWillAppear(animated: Bool) { super.viewWillAppear(true) tilteLab.frame.origin.x -= view.frame.width userTF.frame.origin.x -= view.frame.width passwordTF.frame.origin.x -= view.frame.width rightImageView.frame.origin.x -= view.frame.width tomImageView.frame.origin.x -= view.frame.width } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) UIView.animateWithDuration(0.5) { () -> Void in self.tilteLab.frame.origin.x += self.view.frame.width } UIView.animateWithDuration(0.5, delay: 0.2, options: [], animations: { self.userTF.frame.origin.x += self.view.frame.width }, completion: nil) UIView.animateWithDuration(0.5, delay: 0.6, options: [], animations: { self.passwordTF.frame.origin.x += self.view.frame.width }, completion: nil) //旋转角度,顺时针转 /// 创建了一个旋转的结构,参数是一个CGFloat类型的角度,这里我们使用预定义好的常量比如M_PI代表3.14...,也就是旋转一周、M_PI_2代表1.57...,也就是旋转半周等 let rotation = CGAffineTransformMakeRotation(CGFloat(M_PI)) UIView.animateWithDuration(1, animations: { self.loginbutton.transform = rotation }) //缩放 /// 首先创建了一个缩放的结构,第一个参数是x轴的缩放比例,第二个参数是y轴的缩放比例。 let scale = CGAffineTransformMakeScale(0.5, 0.5) UIView.animateWithDuration(0.5, animations: { self.imageView.transform = scale }) // animationWithDuration(_:delay:options:animations:completion:)方法,其中的options当时没有详细的讲述,这节会向大家说明该属性。options选项可以使你自定义让UIKit如何创建你的动画。该属性需要一个或多个UIAnimationOptions枚举类型,让我们来看看都有哪些动画选项吧。 /** 重复类 .Repeat:该属性可以使你的动画永远重复的运行。 .Autoreverse:该属性可以使你的动画当运行结束后按照相反的行为继续运行回去。该属性只能和.Repeat属性组合使用。 */ UIView.animateWithDuration(2, delay: 0.5, options: [.Repeat, .Autoreverse], animations: { self.rightImageView.center.x += self.view.bounds.width }, completion: nil) /** 动画缓冲 */ /** .CurveLinear :该属性既不会使动画加速也不会使动画减速,只是做以线性运动。 .CurveEaseIn:该属性使动画在开始时加速运行。 .CurveEaseOut:该属性使动画在结束时减速运行。 .CurveEaseInOut:该属性结合了上述两种情况,使动画在开始时加速,在结束时减速。 */ UIView.animateWithDuration(2, delay: 1, options: [.Repeat, .Autoreverse, .CurveEaseOut], animations: { self.tomImageView.frame.origin.x += self.view.frame.width }, completion: nil) } /** usingSpringWithDamping:弹簧动画的阻尼值,也就是相当于摩擦力的大小,该属性的值从0.0到1.0之间,越靠近0,阻尼越小,弹动的幅度越大,反之阻尼越大,弹动的幅度越小,如果大道一定程度,会出现弹不动的情况。 initialSpringVelocity:弹簧动画的速率,或者说是动力。值越小弹簧的动力越小,弹簧拉伸的幅度越小,反之动力越大,弹簧拉伸的幅度越大。这里需要注意的是,如果设置为0,表示忽略该属性,由动画持续时间和阻尼计算动画的效果。 */ /** 以下为设置同样的时间,不同的阻尼系数,不同的动力的效果;并在动画中增大宽和高 */ @IBAction func doClickloginButton(sender: AnyObject) { UIView.animateWithDuration(2, delay: 0, usingSpringWithDamping: 0.3, initialSpringVelocity: 30, options: .AllowUserInteraction, animations: { self.loginbutton.center.y += 30; }, completion: nil) } @IBAction func doClickRegister(sender: UIButton) { UIView.animateWithDuration(2, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 1, options: .AllowAnimatedContent, animations: { sender.center.y += 30 sender.bounds.size.width += 10 }, completion: nil) } @IBAction func doClickExit(sender: UIButton) { UIView.animateWithDuration(2, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 10, options: .AllowAnimatedContent, animations: { sender.center.y += 30 sender.bounds.size.height += 10 }, completion: nil) } override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
f1a1f8abbc4cdaf8a3c81952d71128a5
25.719577
189
0.586733
false
false
false
false
TZLike/GiftShow
refs/heads/master
GiftShow/GiftShow/Classes/CategoryPage/Controller/LeeCategoryViewController.swift
apache-2.0
1
// // LeeCategoryViewController.swift // GiftShow // // Created by admin on 16/10/27. // Copyright © 2016年 Mr_LeeKi. All rights reserved. // import UIKit //import SnapKit private let titleHeight:CGFloat = 44 class LeeCategoryViewController: UIViewController { //底部的数据控件 fileprivate lazy var bottomView:LeeHotBottomView = { var arr:[UIViewController] = [UIViewController]() arr.append(LeeRaidersViewController()) arr.append(LeeSingleProductViewController()) let view = LeeHotBottomView(frame:CGRect(x: 0, y: 35, width: WIDTH, height: HEIGHT - 35),vcs:arr,parent:self) view.delegate = self return view }() //搜索 fileprivate lazy var search:LeeHomeSearchView = { let view = LeeHomeSearchView.getInfo() view.backgroundColor = UIColor.colorWithHexString("FDF5F3") view.layer.cornerRadius = 12.5 view.delegate = self view.clipsToBounds = true return view }() //头部banner fileprivate lazy var topBanner:LeeCategoryNavView = {[weak self] in let topBanner = LeeCategoryNavView(frame:CGRect(x: 0, y: 0, width: WIDTH / 3 - 20 ,height: titleHeight),arrs:["攻略","单品"]) topBanner.delegate = self topBanner.backgroundColor = UIColor.white return topBanner }() override func viewDidLoad() { super.viewDidLoad() setNav() view.backgroundColor = UIColor.white navigationController?.navigationBar.shadowImage = UIImage() } } extension LeeCategoryViewController { fileprivate func setNav(){ navigationItem.titleView = topBanner view.addSubview(search) view.addSubview(bottomView) search.snp.makeConstraints { (make) in make.left.equalTo(view).offset(15) make.right.equalTo(view).offset(-15) make.top.equalTo(view).offset(5) make.height.equalTo(25) } // showAge(age: 10) } } extension LeeCategoryViewController :LeeCategoryNavViewDelegate { func categoryTopTitleClick(_ hot: LeeCategoryNavView, index: Int) { self.bottomView.changePageControler(index) } // func showAge(age:Int){ // print(age) // } } extension LeeCategoryViewController :LeeHomeSearchViewDelegate { func searchBtnClick() { print("aaa") } } //MARK:改变collectionView的页码 extension LeeCategoryViewController :LeePageContentViewDelegate { func scrollContentIndex(_ pageContent: LeeHotBottomView, progress: CGFloat, targetIndex: Int, sourceIndex: Int) { topBanner.showProgress(progress, targetInex: targetIndex, sourceIndex: sourceIndex) } }
89e45c8225b037151c4e70e38ac32c87
26.712871
129
0.637728
false
false
false
false
amraboelela/swift
refs/heads/master
test/SILGen/specialize_attr.swift
apache-2.0
6
// RUN: %target-swift-emit-silgen -module-name specialize_attr -emit-verbose-sil %s | %FileCheck %s // CHECK-LABEL: @_specialize(exported: false, kind: full, where T == Int, U == Float) // CHECK-NEXT: func specializeThis<T, U>(_ t: T, u: U) @_specialize(where T == Int, U == Float) func specializeThis<T, U>(_ t: T, u: U) {} public protocol PP { associatedtype PElt } public protocol QQ { associatedtype QElt } public struct RR : PP { public typealias PElt = Float } public struct SS : QQ { public typealias QElt = Int } public struct GG<T : PP> {} // CHECK-LABEL: public class CC<T> where T : PP { // CHECK-NEXT: @_specialize(exported: false, kind: full, where T == RR, U == SS) // CHECK-NEXT: @inline(never) public func foo<U>(_ u: U, g: GG<T>) -> (U, GG<T>) where U : QQ public class CC<T : PP> { @inline(never) @_specialize(where T == RR, U == SS) public func foo<U : QQ>(_ u: U, g: GG<T>) -> (U, GG<T>) { return (u, g) } } // CHECK-LABEL: sil hidden [_specialize exported: false, kind: full, where T == Int, U == Float] [ossa] @$s15specialize_attr0A4This_1uyx_q_tr0_lF : $@convention(thin) <T, U> (@in_guaranteed T, @in_guaranteed U) -> () { // CHECK-LABEL: sil [noinline] [_specialize exported: false, kind: full, where T == RR, U == SS] [ossa] @$s15specialize_attr2CCC3foo_1gqd___AA2GGVyxGtqd___AHtAA2QQRd__lF : $@convention(method) <T where T : PP><U where U : QQ> (@in_guaranteed U, GG<T>, @guaranteed CC<T>) -> (@out U, GG<T>) { // ----------------------------------------------------------------------------- // Test user-specialized subscript accessors. public protocol TestSubscriptable { associatedtype Element subscript(i: Int) -> Element { get set } } public class ASubscriptable<Element> : TestSubscriptable { var storage: UnsafeMutablePointer<Element> init(capacity: Int) { storage = UnsafeMutablePointer<Element>.allocate(capacity: capacity) } public subscript(i: Int) -> Element { @_specialize(where Element == Int) get { return storage[i] } @_specialize(where Element == Int) set(rhs) { storage[i] = rhs } } } // ASubscriptable.subscript.getter with _specialize // CHECK-LABEL: sil [_specialize exported: false, kind: full, where Element == Int] [ossa] @$s15specialize_attr14ASubscriptableCyxSicig : $@convention(method) <Element> (Int, @guaranteed ASubscriptable<Element>) -> @out Element { // ASubscriptable.subscript.setter with _specialize // CHECK-LABEL: sil [_specialize exported: false, kind: full, where Element == Int] [ossa] @$s15specialize_attr14ASubscriptableCyxSicis : $@convention(method) <Element> (@in Element, Int, @guaranteed ASubscriptable<Element>) -> () { // ASubscriptable.subscript.modify with no attribute // CHECK-LABEL: sil [transparent] [serialized] [ossa] @$s15specialize_attr14ASubscriptableCyxSiciM : $@yield_once @convention(method) <Element> (Int, @guaranteed ASubscriptable<Element>) -> @yields @inout Element { public class Addressable<Element> : TestSubscriptable { var storage: UnsafeMutablePointer<Element> init(capacity: Int) { storage = UnsafeMutablePointer<Element>.allocate(capacity: capacity) } public subscript(i: Int) -> Element { @_specialize(where Element == Int) unsafeAddress { return UnsafePointer<Element>(storage + i) } @_specialize(where Element == Int) unsafeMutableAddress { return UnsafeMutablePointer<Element>(storage + i) } } } // Addressable.subscript.getter with no attribute // CHECK-LABEL: sil [transparent] [serialized] [ossa] @$s15specialize_attr11AddressableCyxSicig : $@convention(method) <Element> (Int, @guaranteed Addressable<Element>) -> @out Element { // Addressable.subscript.unsafeAddressor with _specialize // CHECK-LABEL: sil [_specialize exported: false, kind: full, where Element == Int] [ossa] @$s15specialize_attr11AddressableCyxSicilu : $@convention(method) <Element> (Int, @guaranteed Addressable<Element>) -> UnsafePointer<Element> { // Addressable.subscript.setter with no attribute // CHECK-LABEL: sil [transparent] [serialized] [ossa] @$s15specialize_attr11AddressableCyxSicis : $@convention(method) <Element> (@in Element, Int, @guaranteed Addressable<Element>) -> () { // Addressable.subscript.unsafeMutableAddressor with _specialize // CHECK-LABEL: sil [_specialize exported: false, kind: full, where Element == Int] [ossa] @$s15specialize_attr11AddressableCyxSiciau : $@convention(method) <Element> (Int, @guaranteed Addressable<Element>) -> UnsafeMutablePointer<Element> { // Addressable.subscript.materializeForSet with no attribute // CHECK-LABEL: sil [transparent] [serialized] [ossa] @$s15specialize_attr11AddressableCyxSiciM : $@yield_once @convention(method) <Element> (Int, @guaranteed Addressable<Element>) -> @yields @inout Element {
deccf2b10a5290dd7e762c14ae9b5ec5
43.055046
291
0.690962
false
false
false
false
giangbvnbgit128/AnViet
refs/heads/master
AnViet/Class/Helpers/Network/AVUploadRouter.swift
apache-2.0
1
// // File.swift // AnViet // // Created by Bui Giang on 6/11/17. // Copyright © 2017 Bui Giang. All rights reserved. // import UIKit import Alamofire enum PostEndPoint { case UploadImage case PostNews(userId:String,token:String,image:String,content:String) } class AVUploadRouter : AVBaseRouter { var endpoint: PostEndPoint var UrlConfig:URL? init(endpoint: PostEndPoint) { self.endpoint = endpoint } func getUrl() -> String { return self.baseUrl + "api/upload_image" } override var path: String { switch endpoint { case .PostNews(let userId,let token,let image,let content): return "api/create_post?user_id=\(userId)&token=\(token)&image=\(image)&content=\(content)" case .UploadImage: return "api/upload_image" default: break } } override var parameters: APIParams { return nil } override var encoding: Alamofire.ParameterEncoding? { return URLEncoding() } }
0501c80405f3722548fb85bad154482d
21.434783
159
0.627907
false
false
false
false
296245482/ILab-iOS
refs/heads/master
Charts-master/Charts/Classes/Renderers/CombinedChartRenderer.swift
apache-2.0
2
// // CombinedChartRenderer.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics public class CombinedChartRenderer: ChartDataRendererBase { public weak var chart: CombinedChartView? /// flag that enables or disables the highlighting arrow public var drawHighlightArrowEnabled = false /// if set to true, all values are drawn above their bars, instead of below their top public var drawValueAboveBarEnabled = true /// if set to true, a grey area is drawn behind each bar that indicates the maximum value public var drawBarShadowEnabled = true internal var _renderers = [ChartDataRendererBase]() internal var _drawOrder: [CombinedChartView.DrawOrder] = [.Bar, .Bubble, .Line, .Candle, .Scatter] public init(chart: CombinedChartView, animator: ChartAnimator, viewPortHandler: ChartViewPortHandler) { super.init(animator: animator, viewPortHandler: viewPortHandler) self.chart = chart createRenderers() } /// Creates the renderers needed for this combined-renderer in the required order. Also takes the DrawOrder into consideration. internal func createRenderers() { _renderers = [ChartDataRendererBase]() guard let chart = chart, animator = animator else { return } for order in drawOrder { switch (order) { case .Bar: if (chart.barData !== nil) { _renderers.append(BarChartRenderer(dataProvider: chart, animator: animator, viewPortHandler: viewPortHandler)) } break case .Line: if (chart.lineData !== nil) { _renderers.append(LineChartRenderer(dataProvider: chart, animator: animator, viewPortHandler: viewPortHandler)) } break case .Candle: if (chart.candleData !== nil) { _renderers.append(CandleStickChartRenderer(dataProvider: chart, animator: animator, viewPortHandler: viewPortHandler)) } break case .Scatter: if (chart.scatterData !== nil) { _renderers.append(ScatterChartRenderer(dataProvider: chart, animator: animator, viewPortHandler: viewPortHandler)) } break case .Bubble: if (chart.bubbleData !== nil) { _renderers.append(BubbleChartRenderer(dataProvider: chart, animator: animator, viewPortHandler: viewPortHandler)) } break } } } public override func drawData(context context: CGContext) { for renderer in _renderers { renderer.drawData(context: context) } } public override func drawValues(context context: CGContext) { for renderer in _renderers { renderer.drawValues(context: context) } } public override func drawExtras(context context: CGContext) { for renderer in _renderers { renderer.drawExtras(context: context) } } public override func drawHighlighted(context context: CGContext, indices: [ChartHighlight]) { for renderer in _renderers { var data: ChartData? if renderer is BarChartRenderer { data = (renderer as! BarChartRenderer).dataProvider?.barData } else if renderer is LineChartRenderer { data = (renderer as! LineChartRenderer).dataProvider?.lineData } else if renderer is CandleStickChartRenderer { data = (renderer as! CandleStickChartRenderer).dataProvider?.candleData } else if renderer is ScatterChartRenderer { data = (renderer as! ScatterChartRenderer).dataProvider?.scatterData } else if renderer is BubbleChartRenderer { data = (renderer as! BubbleChartRenderer).dataProvider?.bubbleData } let dataIndex = data == nil ? nil : (chart?.data as? CombinedChartData)?.allData.indexOf(data!) let dataIndices = indices.filter{ $0.dataIndex == dataIndex || $0.dataIndex == -1 } renderer.drawHighlighted(context: context, indices: dataIndices) } } public override func calcXBounds(chart chart: BarLineChartViewBase, xAxisModulus: Int) { for renderer in _renderers { renderer.calcXBounds(chart: chart, xAxisModulus: xAxisModulus) } } /// - returns: the sub-renderer object at the specified index. public func getSubRenderer(index index: Int) -> ChartDataRendererBase? { if (index >= _renderers.count || index < 0) { return nil } else { return _renderers[index] } } /// Returns all sub-renderers. public var subRenderers: [ChartDataRendererBase] { get { return _renderers } set { _renderers = newValue } } // MARK: Accessors /// - returns: true if drawing the highlighting arrow is enabled, false if not public var isDrawHighlightArrowEnabled: Bool { return drawHighlightArrowEnabled; } /// - returns: true if drawing values above bars is enabled, false if not public var isDrawValueAboveBarEnabled: Bool { return drawValueAboveBarEnabled; } /// - returns: true if drawing shadows (maxvalue) for each bar is enabled, false if not public var isDrawBarShadowEnabled: Bool { return drawBarShadowEnabled; } /// the order in which the provided data objects should be drawn. /// The earlier you place them in the provided array, the further they will be in the background. /// e.g. if you provide [DrawOrder.Bar, DrawOrder.Line], the bars will be drawn behind the lines. public var drawOrder: [CombinedChartView.DrawOrder] { get { return _drawOrder } set { if (newValue.count > 0) { _drawOrder = newValue } } } }
4737d631ceaf08ac74e81cfac752b7d1
31.265403
138
0.576087
false
false
false
false
johnno1962d/swift
refs/heads/master
test/SILGen/materializeForSet.swift
apache-2.0
1
// RUN: %target-swift-frontend -emit-silgen %s | FileCheck %s class Base { var stored: Int = 0 // The ordering here is unfortunate: we generate the property // getters and setters after we've processed the decl. // CHECK-LABEL: sil hidden [transparent] @_TFC17materializeForSet4Basem8computedSi : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed Base) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) { // CHECK: bb0([[BUFFER:%.*]] : $Builtin.RawPointer, [[STORAGE:%.*]] : $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : $Base): // CHECK: [[ADDR:%.*]] = pointer_to_address [[BUFFER]] : $Builtin.RawPointer to $*Int // CHECK: [[T0:%.*]] = function_ref @_TFC17materializeForSet4Baseg8computedSi // CHECK: [[T1:%.*]] = apply [[T0]]([[SELF]]) // CHECK: store [[T1]] to [[ADDR]] : $*Int // CHECK: [[BUFFER:%.*]] = address_to_pointer [[ADDR]] // CHECK: [[T0:%.*]] = function_ref @_TFFC17materializeForSet4Basem8computedSiU_T_ : $@convention(thin) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout Base, @thick Base.Type) -> () // CHECK: [[T2:%.*]] = thin_function_to_pointer [[T0]] // CHECK: [[T3:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.some!enumelt.1, [[T2]] : $Builtin.RawPointer // CHECK: [[T4:%.*]] = tuple ([[BUFFER]] : $Builtin.RawPointer, [[T3]] : $Optional<Builtin.RawPointer>) // CHECK: return [[T4]] : $(Builtin.RawPointer, Optional<Builtin.RawPointer>) // CHECK: } // CHECK-LABEL: sil hidden [transparent] @_TFFC17materializeForSet4Basem8computedSiU_T_ : $@convention(thin) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout Base, @thick Base.Type) -> () { // CHECK: bb0([[BUFFER:%.*]] : $Builtin.RawPointer, [[STORAGE:%.*]] : $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : $*Base, [[SELFTYPE:%.*]] : $@thick Base.Type): // CHECK: [[T0:%.*]] = load [[SELF]] // CHECK: [[T1:%.*]] = pointer_to_address [[BUFFER]] : $Builtin.RawPointer to $*Int // CHECK: [[T2:%.*]] = load [[T1]] : $*Int // CHECK: [[SETTER:%.*]] = function_ref @_TFC17materializeForSet4Bases8computedSi // CHECK: apply [[SETTER]]([[T2]], [[T0]]) // CHECK-LABEL: sil hidden [transparent] @_TFC17materializeForSet4Basem6storedSi : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed Base) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) { // CHECK: bb0([[BUFFER:%.*]] : $Builtin.RawPointer, [[STORAGE:%.*]] : $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : $Base): // CHECK: [[T0:%.*]] = ref_element_addr [[SELF]] : $Base, #Base.stored // CHECK: [[T1:%.*]] = address_to_pointer [[T0]] : $*Int to $Builtin.RawPointer // CHECK: [[T2:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.none // CHECK: [[T3:%.*]] = tuple ([[T1]] : $Builtin.RawPointer, [[T2]] : $Optional<Builtin.RawPointer>) // CHECK: return [[T3]] : $(Builtin.RawPointer, Optional<Builtin.RawPointer>) // CHECK: } var computed: Int { get { return 0 } set(value) {} } var storedFunction: () -> Int = { 0 } final var finalStoredFunction: () -> Int = { 0 } var computedFunction: () -> Int { get { return {0} } set {} } static var staticFunction: () -> Int { get { return {0} } set {} } } class Derived : Base {} protocol Abstractable { associatedtype Result var storedFunction: () -> Result { get set } var finalStoredFunction: () -> Result { get set } var computedFunction: () -> Result { get set } static var staticFunction: () -> Result { get set } } // Validate that we thunk materializeForSet correctly when there's // an abstraction pattern present. extension Derived : Abstractable {} // CHECK: sil hidden [transparent] [thunk] @_TTWC17materializeForSet7DerivedS_12AbstractableS_FS1_m14storedFunction // CHECK: bb0(%0 : $Builtin.RawPointer, %1 : $*Builtin.UnsafeValueBuffer, %2 : $*Derived): // CHECK-NEXT: [[RESULT_ADDR:%.*]] = pointer_to_address %0 : $Builtin.RawPointer to $*@callee_owned () -> @out Int // CHECK-NEXT: [[T0:%.*]] = load %2 : $*Derived // CHECK-NEXT: [[SELF:%.*]] = upcast [[T0]] : $Derived to $Base // CHECK-NEXT: [[TEMP:%.*]] = alloc_stack $@callee_owned () -> Int // CHECK-NEXT: [[FN:%.*]] = class_method [[SELF]] : $Base, #Base.storedFunction!getter.1 // CHECK-NEXT: [[RESULT:%.*]] = apply [[FN]]([[SELF]]) // CHECK-NEXT: store [[RESULT]] to [[TEMP]] // CHECK-NEXT: [[RESULT:%.*]] = load [[TEMP]] // CHECK-NEXT: strong_retain [[RESULT]] // CHECK-NEXT: function_ref // CHECK-NEXT: [[REABSTRACTOR:%.*]] = function_ref @_TTRXFo__dSi_XFo__iSi_ : $@convention(thin) (@owned @callee_owned () -> Int) -> @out Int // CHECK-NEXT: [[T1:%.*]] = partial_apply [[REABSTRACTOR]]([[RESULT]]) // CHECK-NEXT: store [[T1]] to [[RESULT_ADDR]] // CHECK-NEXT: [[RESULT_PTR:%.*]] = address_to_pointer [[RESULT_ADDR]] : $*@callee_owned () -> @out Int to $Builtin.RawPointer // CHECK-NEXT: function_ref // CHECK-NEXT: [[T0:%.*]] = function_ref @_TTWC17materializeForSet7DerivedS_12AbstractableS_FFS1_m14storedFunctionFT_wx6ResultU_T_ // CHECK-NEXT: [[T1:%.*]] = thin_function_to_pointer [[T0]] // CHECK-NEXT: [[CALLBACK:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.some!enumelt.1, [[T1]] // CHECK-NEXT: [[T0:%.*]] = tuple ([[RESULT_PTR]] : $Builtin.RawPointer, [[CALLBACK]] : $Optional<Builtin.RawPointer>) // CHECK-NEXT: destroy_addr [[TEMP]] // CHECK-NEXT: dealloc_stack [[TEMP]] // CHECK-NEXT: return [[T0]] // CHECK: sil hidden [transparent] @_TTWC17materializeForSet7DerivedS_12AbstractableS_FFS1_m14storedFunctionFT_wx6ResultU_T_ : $@convention(thin) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout Derived, @thick Derived.Type) -> () // CHECK: bb0(%0 : $Builtin.RawPointer, %1 : $*Builtin.UnsafeValueBuffer, %2 : $*Derived, %3 : $@thick Derived.Type): // CHECK-NEXT: [[T0:%.*]] = load %2 : $*Derived // CHECK-NEXT: [[SELF:%.*]] = upcast [[T0]] : $Derived to $Base // CHECK-NEXT: [[RESULT_ADDR:%.*]] = pointer_to_address %0 : $Builtin.RawPointer to $*@callee_owned () -> @out Int // CHECK-NEXT: [[VALUE:%.*]] = load [[RESULT_ADDR]] : $*@callee_owned () -> @out Int // CHECK-NEXT: function_ref // CHECK-NEXT: [[REABSTRACTOR:%.*]] = function_ref @_TTRXFo__iSi_XFo__dSi_ : $@convention(thin) (@owned @callee_owned () -> @out Int) -> Int // CHECK-NEXT: [[NEWVALUE:%.*]] = partial_apply [[REABSTRACTOR]]([[VALUE]]) // CHECK-NEXT: [[FN:%.*]] = class_method [[SELF]] : $Base, #Base.storedFunction!setter.1 : (Base) -> (() -> Int) -> () // CHECK-NEXT: apply [[FN]]([[NEWVALUE]], [[SELF]]) // CHECK-NEXT: tuple () // CHECK-NEXT: return // CHECK: sil hidden [transparent] [thunk] @_TTWC17materializeForSet7DerivedS_12AbstractableS_FS1_m19finalStoredFunction // CHECK: bb0(%0 : $Builtin.RawPointer, %1 : $*Builtin.UnsafeValueBuffer, %2 : $*Derived): // CHECK-NEXT: [[RESULT_ADDR:%.*]] = pointer_to_address %0 : $Builtin.RawPointer to $*@callee_owned () -> @out Int // CHECK-NEXT: [[T0:%.*]] = load %2 : $*Derived // CHECK-NEXT: [[SELF:%.*]] = upcast [[T0]] : $Derived to $Base // CHECK-NEXT: [[ADDR:%.*]] = ref_element_addr [[SELF]] : $Base, #Base.finalStoredFunction // CHECK-NEXT: [[RESULT:%.*]] = load [[ADDR]] // CHECK-NEXT: strong_retain [[RESULT]] // CHECK-NEXT: function_ref // CHECK-NEXT: [[REABSTRACTOR:%.*]] = function_ref @_TTRXFo__dSi_XFo__iSi_ : $@convention(thin) (@owned @callee_owned () -> Int) -> @out Int // CHECK-NEXT: [[T1:%.*]] = partial_apply [[REABSTRACTOR]]([[RESULT]]) // CHECK-NEXT: store [[T1]] to [[RESULT_ADDR]] // CHECK-NEXT: [[RESULT_PTR:%.*]] = address_to_pointer [[RESULT_ADDR]] : $*@callee_owned () -> @out Int to $Builtin.RawPointer // CHECK-NEXT: function_ref // CHECK-NEXT: [[T0:%.*]] = function_ref @_TTWC17materializeForSet7DerivedS_12AbstractableS_FFS1_m19finalStoredFunctionFT_wx6ResultU_T_ // CHECK-NEXT: [[T1:%.*]] = thin_function_to_pointer [[T0]] // CHECK-NEXT: [[CALLBACK:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.some!enumelt.1, [[T1]] // CHECK-NEXT: [[T0:%.*]] = tuple ([[RESULT_PTR]] : $Builtin.RawPointer, [[CALLBACK]] : $Optional<Builtin.RawPointer>) // CHECK-NEXT: return [[T0]] // CHECK: sil hidden [transparent] @_TTWC17materializeForSet7DerivedS_12AbstractableS_FFS1_m19finalStoredFunctionFT_wx6ResultU_T_ : // CHECK: bb0(%0 : $Builtin.RawPointer, %1 : $*Builtin.UnsafeValueBuffer, %2 : $*Derived, %3 : $@thick Derived.Type): // CHECK-NEXT: [[T0:%.*]] = load %2 : $*Derived // CHECK-NEXT: [[SELF:%.*]] = upcast [[T0]] : $Derived to $Base // CHECK-NEXT: [[RESULT_ADDR:%.*]] = pointer_to_address %0 : $Builtin.RawPointer to $*@callee_owned () -> @out Int // CHECK-NEXT: [[VALUE:%.*]] = load [[RESULT_ADDR]] : $*@callee_owned () -> @out Int // CHECK-NEXT: function_ref // CHECK-NEXT: [[REABSTRACTOR:%.*]] = function_ref @_TTRXFo__iSi_XFo__dSi_ : $@convention(thin) (@owned @callee_owned () -> @out Int) -> Int // CHECK-NEXT: [[NEWVALUE:%.*]] = partial_apply [[REABSTRACTOR]]([[VALUE]]) // CHECK-NEXT: [[ADDR:%.*]] = ref_element_addr [[SELF]] : $Base, #Base.finalStoredFunction // CHECK-NEXT: assign [[NEWVALUE]] to [[ADDR]] // CHECK-NEXT: tuple () // CHECK-NEXT: return // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC17materializeForSet7DerivedS_12AbstractableS_ZFS1_m14staticFunctionFT_wx6Result // CHECK: bb0(%0 : $Builtin.RawPointer, %1 : $*Builtin.UnsafeValueBuffer, %2 : $@thick Derived.Type): // CHECK-NEXT: [[RESULT_ADDR:%.*]] = pointer_to_address %0 : $Builtin.RawPointer to $*@callee_owned () -> @out Int // CHECK-NEXT: [[SELF:%.*]] = upcast %2 : $@thick Derived.Type to $@thick Base.Type // CHECK-NEXT: [[OUT:%.*]] = alloc_stack $@callee_owned () -> Int // CHECK: [[GETTER:%.*]] = function_ref @_TZFC17materializeForSet4Baseg14staticFunctionFT_Si : $@convention(method) (@thick Base.Type) -> @owned @callee_owned () -> Int // CHECK-NEXT: [[VALUE:%.*]] = apply [[GETTER]]([[SELF]]) : $@convention(method) (@thick Base.Type) -> @owned @callee_owned () -> Int // CHECK-NEXT: store [[VALUE]] to [[OUT]] : $*@callee_owned () -> Int // CHECK-NEXT: [[VALUE:%.*]] = load [[OUT]] : $*@callee_owned () -> Int // CHECK-NEXT: strong_retain [[VALUE]] : $@callee_owned () -> Int // CHECK: [[REABSTRACTOR:%.*]] = function_ref @_TTRXFo__dSi_XFo__iSi_ : $@convention(thin) (@owned @callee_owned () -> Int) -> @out Int // CHECK-NEXT: [[NEWVALUE:%.*]] = partial_apply [[REABSTRACTOR]]([[VALUE]]) // CHECK-NEXT: store [[NEWVALUE]] to [[RESULT_ADDR]] : $*@callee_owned () -> @out Int // CHECK-NEXT: [[ADDR:%.*]] = address_to_pointer [[RESULT_ADDR]] : $*@callee_owned () -> @out Int to $Builtin.RawPointer // CHECK: [[CALLBACK_FN:%.*]] = function_ref @_TTWC17materializeForSet7DerivedS_12AbstractableS_FZFS1_m14staticFunctionFT_wx6ResultU_T_ : $@convention(thin) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout @thick Derived.Type, @thick Derived.Type.Type) -> () // CHECK-NEXT: [[CALLBACK_ADDR:%.*]] = thin_function_to_pointer [[CALLBACK_FN]] : $@convention(thin) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout @thick Derived.Type, @thick Derived.Type.Type) -> () to $Builtin.RawPointer // CHECK-NEXT: [[CALLBACK:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.some!enumelt.1, [[CALLBACK_ADDR]] : $Builtin.RawPointer // CHECK-NEXT: [[RESULT:%.*]] = tuple ([[ADDR]] : $Builtin.RawPointer, [[CALLBACK]] : $Optional<Builtin.RawPointer>) // CHECK-NEXT: destroy_addr [[OUT]] : $*@callee_owned () -> Int // CHECK-NEXT: dealloc_stack [[OUT]] : $*@callee_owned () -> Int // CHECK-NEXT: return [[RESULT]] : $(Builtin.RawPointer, Optional<Builtin.RawPointer>) // CHECK-LABEL: sil hidden [transparent] @_TTWC17materializeForSet7DerivedS_12AbstractableS_FZFS1_m14staticFunctionFT_wx6ResultU_T_ // CHECK: bb0(%0 : $Builtin.RawPointer, %1 : $*Builtin.UnsafeValueBuffer, %2 : $*@thick Derived.Type, %3 : $@thick Derived.Type.Type): // CHECK-NEXT: [[SELF:%.*]] = load %2 : $*@thick Derived.Type // CHECK-NEXT: [[BASE_SELF:%.*]] = upcast [[SELF]] : $@thick Derived.Type to $@thick Base.Type // CHECK-NEXT: [[BUFFER:%.*]] = pointer_to_address %0 : $Builtin.RawPointer to $*@callee_owned () -> @out Int // CHECK-NEXT: [[VALUE:%.*]] = load [[BUFFER]] : $*@callee_owned () -> @out Int // CHECK: [[REABSTRACTOR:%.*]] = function_ref @_TTRXFo__iSi_XFo__dSi_ : $@convention(thin) (@owned @callee_owned () -> @out Int) -> Int // CHECK-NEXT: [[NEWVALUE:%.*]] = partial_apply [[REABSTRACTOR]]([[VALUE]]) : $@convention(thin) (@owned @callee_owned () -> @out Int) -> Int // CHECK: [[SETTER_FN:%.*]] = function_ref @_TZFC17materializeForSet4Bases14staticFunctionFT_Si : $@convention(method) (@owned @callee_owned () -> Int, @thick Base.Type) -> () // CHECK-NEXT: apply [[SETTER_FN]]([[NEWVALUE]], [[BASE_SELF]]) : $@convention(method) (@owned @callee_owned () -> Int, @thick Base.Type) -> () // CHECK-NEXT: [[RESULT:%.*]] = tuple () // CHECK-NEXT: return [[RESULT]] : $() protocol ClassAbstractable : class { associatedtype Result var storedFunction: () -> Result { get set } var finalStoredFunction: () -> Result { get set } var computedFunction: () -> Result { get set } static var staticFunction: () -> Result { get set } } extension Derived : ClassAbstractable {} protocol Signatures { associatedtype Result var computedFunction: () -> Result { get set } } protocol Implementations {} extension Implementations { var computedFunction: () -> Int { get { return {0} } set {} } } class ImplementingClass : Implementations, Signatures {} struct ImplementingStruct : Implementations, Signatures { var ref: ImplementingClass? } class HasDidSet : Base { override var stored: Int { didSet {} } // CHECK-LABEL: sil hidden [transparent] @_TFC17materializeForSet9HasDidSetm6storedSi : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed HasDidSet) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) { // CHECK: bb0([[BUFFER:%.*]] : $Builtin.RawPointer, [[STORAGE:%.*]] : $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : $HasDidSet): // CHECK: [[T2:%.*]] = pointer_to_address [[BUFFER]] : $Builtin.RawPointer to $*Int // CHECK: [[T0:%.*]] = function_ref @_TFC17materializeForSet9HasDidSetg6storedSi // CHECK: [[T1:%.*]] = apply [[T0]]([[SELF]]) // CHECK: store [[T1]] to [[T2]] : $*Int // CHECK: [[BUFFER:%.*]] = address_to_pointer [[T2]] // CHECK: [[CALLBACK_FN:%.*]] = function_ref @_TFFC17materializeForSet9HasDidSetm6storedSiU_T_ : $@convention(thin) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout HasDidSet, @thick HasDidSet.Type) -> () // CHECK: [[CALLBACK_ADDR:%.*]] = thin_function_to_pointer [[CALLBACK_FN]] // CHECK: [[CALLBACK:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.some!enumelt.1, [[CALLBACK_ADDR]] // CHECK: [[T4:%.*]] = tuple ([[BUFFER]] : $Builtin.RawPointer, [[CALLBACK]] : $Optional<Builtin.RawPointer>) // CHECK: return [[T4]] : $(Builtin.RawPointer, Optional<Builtin.RawPointer>) // CHECK: } override var computed: Int { get { return 0 } set(value) {} } // CHECK-LABEL: sil hidden [transparent] @_TFC17materializeForSet9HasDidSetm8computedSi : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed HasDidSet) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) { // CHECK: bb0([[BUFFER:%.*]] : $Builtin.RawPointer, [[STORAGE:%.*]] : $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : $HasDidSet): // CHECK: [[T2:%.*]] = pointer_to_address [[BUFFER]] : $Builtin.RawPointer to $*Int // CHECK: [[T0:%.*]] = function_ref @_TFC17materializeForSet9HasDidSetg8computedSi // CHECK: [[T1:%.*]] = apply [[T0]]([[SELF]]) // CHECK: store [[T1]] to [[T2]] : $*Int // CHECK: [[BUFFER:%.*]] = address_to_pointer [[T2]] // CHECK: [[CALLBACK_FN:%.*]] = function_ref @_TFFC17materializeForSet9HasDidSetm8computedSiU_T_ : $@convention(thin) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout HasDidSet, @thick HasDidSet.Type) -> () // CHECK: [[CALLBACK_ADDR:%.*]] = thin_function_to_pointer [[CALLBACK_FN]] // CHECK: [[CALLBACK:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.some!enumelt.1, [[CALLBACK_ADDR]] // CHECK: [[T4:%.*]] = tuple ([[BUFFER]] : $Builtin.RawPointer, [[CALLBACK]] : $Optional<Builtin.RawPointer>) // CHECK: return [[T4]] : $(Builtin.RawPointer, Optional<Builtin.RawPointer>) // CHECK: } } class HasStoredDidSet { var stored: Int = 0 { didSet {} } // CHECK-LABEL: sil hidden [transparent] @_TFC17materializeForSet15HasStoredDidSetm6storedSi : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed HasStoredDidSet) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) { // CHECK: bb0([[BUFFER:%.*]] : $Builtin.RawPointer, [[STORAGE:%.*]] : $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : $HasStoredDidSet): // CHECK: [[T2:%.*]] = pointer_to_address [[BUFFER]] : $Builtin.RawPointer to $*Int // CHECK: [[T0:%.*]] = function_ref @_TFC17materializeForSet15HasStoredDidSetg6storedSi // CHECK: [[T1:%.*]] = apply [[T0]]([[SELF]]) // CHECK: store [[T1]] to [[T2]] : $*Int // CHECK: [[BUFFER:%.*]] = address_to_pointer [[T2]] // CHECK: [[CALLBACK_FN:%.*]] = function_ref @_TFFC17materializeForSet15HasStoredDidSetm6storedSiU_T_ : $@convention(thin) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout HasStoredDidSet, @thick HasStoredDidSet.Type) -> () // CHECK: [[CALLBACK_ADDR:%.*]] = thin_function_to_pointer [[CALLBACK_FN]] // CHECK: [[CALLBACK:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.some!enumelt.1, [[CALLBACK_ADDR]] // CHECK: [[T4:%.*]] = tuple ([[BUFFER]] : $Builtin.RawPointer, [[CALLBACK]] : $Optional<Builtin.RawPointer>) // CHECK: return [[T4]] : $(Builtin.RawPointer, Optional<Builtin.RawPointer>) // CHECK: } } // CHECK-LABEL: sil hidden [transparent] @_TFFC17materializeForSet15HasStoredDidSetm6storedSiU_T_ : $@convention(thin) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout HasStoredDidSet, @thick HasStoredDidSet.Type) -> () { // CHECK: bb0([[BUFFER:%.*]] : $Builtin.RawPointer, [[STORAGE:%.*]] : $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : $*HasStoredDidSet, [[METATYPE:%.*]] : $@thick HasStoredDidSet.Type): // CHECK: [[SELF_VALUE:%.*]] = load [[SELF]] : $*HasStoredDidSet // CHECK: [[BUFFER_ADDR:%.*]] = pointer_to_address [[BUFFER]] : $Builtin.RawPointer to $*Int // CHECK: [[VALUE:%.*]] = load [[BUFFER_ADDR]] : $*Int // CHECK: [[SETTER_FN:%.*]] = function_ref @_TFC17materializeForSet15HasStoredDidSets6storedSi : $@convention(method) (Int, @guaranteed HasStoredDidSet) -> () // CHECK: apply [[SETTER_FN]]([[VALUE]], [[SELF_VALUE]]) : $@convention(method) (Int, @guaranteed HasStoredDidSet) -> () // CHECK: return // CHECK: } class HasWeak { weak var weakvar: HasWeak? = nil } // CHECK-LABEL: sil hidden [transparent] @_TFC17materializeForSet7HasWeakm7weakvarXwGSqS0__ : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed HasWeak) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) { // CHECK: bb0([[BUFFER:%.*]] : $Builtin.RawPointer, [[STORAGE:%.*]] : $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : $HasWeak): // CHECK: [[T2:%.*]] = pointer_to_address [[BUFFER]] : $Builtin.RawPointer to $*Optional<HasWeak> // CHECK: [[T0:%.*]] = ref_element_addr [[SELF]] : $HasWeak, #HasWeak.weakvar // CHECK: [[T1:%.*]] = load_weak [[T0]] : $*@sil_weak Optional<HasWeak> // CHECK: store [[T1]] to [[T2]] : $*Optional<HasWeak> // CHECK: [[BUFFER:%.*]] = address_to_pointer [[T2]] // CHECK: [[T0:%.*]] = function_ref @_TFFC17materializeForSet7HasWeakm7weakvarXwGSqS0__U_T_ : $@convention(thin) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout HasWeak, @thick HasWeak.Type) -> () // CHECK: [[T4:%.*]] = tuple ([[BUFFER]] : $Builtin.RawPointer, {{.*}} : $Optional<Builtin.RawPointer>) // CHECK: return [[T4]] : $(Builtin.RawPointer, Optional<Builtin.RawPointer>) // CHECK: } // rdar://22109071 // Test that we don't use materializeForSet from a protocol extension. protocol Magic {} extension Magic { var hocus: Int { get { return 0 } set {} } } struct Wizard : Magic {} func improve(_ x: inout Int) {} func improveWizard(_ wizard: inout Wizard) { improve(&wizard.hocus) } // CHECK-LABEL: sil hidden @_TF17materializeForSet13improveWizardFRVS_6WizardT_ // CHECK: [[IMPROVE:%.*]] = function_ref @_TF17materializeForSet7improveFRSiT_ : // CHECK-NEXT: [[TEMP:%.*]] = alloc_stack $Int // Call the getter and materialize the result in the temporary. // CHECK-NEXT: [[T0:%.*]] = load [[WIZARD:.*]] : $*Wizard // CHECK-NEXT: function_ref // CHECK-NEXT: [[GETTER:%.*]] = function_ref @_TFE17materializeForSetPS_5Magicg5hocusSi // CHECK-NEXT: [[WTEMP:%.*]] = alloc_stack $Wizard // CHECK-NEXT: store [[T0]] to [[WTEMP]] // CHECK-NEXT: [[T0:%.*]] = apply [[GETTER]]<Wizard>([[WTEMP]]) // CHECK-NEXT: store [[T0]] to [[TEMP]] // Call improve. // CHECK-NEXT: apply [[IMPROVE]]([[TEMP]]) // CHECK-NEXT: [[T0:%.*]] = load [[TEMP]] // CHECK-NEXT: function_ref // CHECK-NEXT: [[SETTER:%.*]] = function_ref @_TFE17materializeForSetPS_5Magics5hocusSi // CHECK-NEXT: apply [[SETTER]]<Wizard>([[T0]], [[WIZARD]]) // CHECK-NEXT: dealloc_stack [[WTEMP]] // CHECK-NEXT: dealloc_stack [[TEMP]] protocol Totalled { var total: Int { get set } } struct Bill : Totalled { var total: Int } // CHECK-LABEL: sil hidden [transparent] @_TFV17materializeForSet4Billm5totalSi : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout Bill) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) { // CHECK: bb0([[BUFFER:%.*]] : $Builtin.RawPointer, [[STORAGE:%.*]] : $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : $*Bill): // CHECK: [[T0:%.*]] = struct_element_addr [[SELF]] : $*Bill, #Bill.total // CHECK: [[T1:%.*]] = address_to_pointer [[T0]] : $*Int to $Builtin.RawPointer // CHECK: [[T3:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.none!enumelt // CHECK: [[T4:%.*]] = tuple ([[T1]] : $Builtin.RawPointer, [[T3]] : $Optional<Builtin.RawPointer>) // CHECK: return [[T4]] : $(Builtin.RawPointer, Optional<Builtin.RawPointer>) // CHECK: } // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV17materializeForSet4BillS_8TotalledS_FS1_m5totalSi : $@convention(witness_method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout Bill) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) { // CHECK: bb0([[BUFFER:%.*]] : $Builtin.RawPointer, [[STORAGE:%.*]] : $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : $*Bill): // CHECK: [[T0:%.*]] = function_ref @_TFV17materializeForSet4Billm5totalSi // CHECK: [[T1:%.*]] = apply [[T0]]([[BUFFER]], [[STORAGE]], [[SELF]]) // CHECK: return [[T1]] : protocol AddressOnlySubscript { associatedtype Index subscript(i: Index) -> Index { get set } } struct Foo<T>: AddressOnlySubscript { subscript(i: T) -> T { get { return i } set { print("\(i) = \(newValue)") } } } func increment(_ x: inout Int) { x += 1 } // Test for materializeForSet vs static properties of structs. protocol Beverage { static var abv: Int { get set } } struct Beer : Beverage { static var abv: Int { get { return 7 } set { } } } struct Wine<Color> : Beverage { static var abv: Int { get { return 14 } set { } } } // Make sure we can perform an inout access of such a property too. func inoutAccessOfStaticProperty<T : Beverage>(_ t: T.Type) { increment(&t.abv) } // Test for materializeForSet vs static properties of classes. class ReferenceBeer { class var abv: Int { get { return 7 } set { } } } func inoutAccessOfClassProperty() { increment(&ReferenceBeer.abv) } // Test for materializeForSet when Self is re-abstracted. // // We have to open-code the materializeForSelf witness, and not screw up // the re-abstraction. protocol Panda { var x: Self -> Self { get set } } func id<T>(_ t: T) -> T { return t } extension Panda { var x: Self -> Self { get { return id } set { } } } struct TuxedoPanda : Panda { } // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV17materializeForSet11TuxedoPandaS_5PandaS_FS1_m1xFxx // Call the getter: // CHECK: function_ref @_TFE17materializeForSetPS_5Pandag1xFxx : $@convention(method) <τ_0_0 where τ_0_0 : Panda> (@in_guaranteed τ_0_0) -> @owned @callee_owned (@in τ_0_0) -> @out τ_0_0 // Result of calling the getter is re-abstracted to the maximally substituted type // by SILGenFunction::emitApply(): // CHECK: function_ref @_TTRXFo_iV17materializeForSet11TuxedoPanda_iS0__XFo_dS0__dS0__ : $@convention(thin) (TuxedoPanda, @owned @callee_owned (@in TuxedoPanda) -> @out TuxedoPanda) -> TuxedoPanda // ... then we re-abstract to the requirement signature: // FIXME: Peephole this away with the previous one since there's actually no // abstraction change in this case. // CHECK: function_ref @_TTRXFo_dV17materializeForSet11TuxedoPanda_dS0__XFo_iS0__iS0__ : $@convention(thin) (@in TuxedoPanda, @owned @callee_owned (TuxedoPanda) -> TuxedoPanda) -> @out TuxedoPanda // The callback: // CHECK: function_ref @_TTWV17materializeForSet11TuxedoPandaS_5PandaS_FFS1_m1xFxxU_T_ : $@convention(thin) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout TuxedoPanda, @thick TuxedoPanda.Type) -> () // CHECK: } // CHECK-LABEL: sil hidden [transparent] @_TTWV17materializeForSet11TuxedoPandaS_5PandaS_FFS1_m1xFxxU_T_ : $@convention(thin) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout TuxedoPanda, @thick TuxedoPanda.Type) -> () // FIXME: Useless re-abstractions // CHECK: function_ref @_TTRXFo_iV17materializeForSet11TuxedoPanda_iS0__XFo_dS0__dS0__ : $@convention(thin) (TuxedoPanda, @owned @callee_owned (@in TuxedoPanda) -> @out TuxedoPanda) -> TuxedoPanda // CHECK: function_ref @_TFE17materializeForSetPS_5Pandas1xFxx : $@convention(method) <τ_0_0 where τ_0_0 : Panda> (@owned @callee_owned (@in τ_0_0) -> @out τ_0_0, @inout τ_0_0) -> () // CHECK: function_ref @_TTRXFo_dV17materializeForSet11TuxedoPanda_dS0__XFo_iS0__iS0__ : $@convention(thin) (@in TuxedoPanda, @owned @callee_owned (TuxedoPanda) -> TuxedoPanda) -> @out TuxedoPanda // CHECK: } // Test for materializeForSet vs lazy properties of structs. struct LazyStructProperty { lazy var cat: Int = 5 } // CHECK-LABEL: sil hidden @_TF17materializeForSet31inoutAccessOfLazyStructPropertyFT1lRVS_18LazyStructProperty_T_ // CHECK: function_ref @_TFV17materializeForSet18LazyStructPropertyg3catSi // CHECK: function_ref @_TFV17materializeForSet18LazyStructPropertys3catSi func inoutAccessOfLazyStructProperty(l: inout LazyStructProperty) { increment(&l.cat) } // Test for materializeForSet vs lazy properties of classes. // CHECK-LABEL: sil hidden [transparent] @_TFC17materializeForSet17LazyClassPropertym3catSi class LazyClassProperty { lazy var cat: Int = 5 } // CHECK-LABEL: sil hidden @_TF17materializeForSet30inoutAccessOfLazyClassPropertyFT1lRCS_17LazyClassProperty_T_ // CHECK: class_method {{.*}} : $LazyClassProperty, #LazyClassProperty.cat!materializeForSet.1 func inoutAccessOfLazyClassProperty(l: inout LazyClassProperty) { increment(&l.cat) } // Test for materializeForSet vs lazy properties of final classes. final class LazyFinalClassProperty { lazy var cat: Int = 5 } // CHECK-LABEL: sil hidden @_TF17materializeForSet35inoutAccessOfLazyFinalClassPropertyFT1lRCS_22LazyFinalClassProperty_T_ // CHECK: function_ref @_TFC17materializeForSet22LazyFinalClassPropertyg3catSi // CHECK: function_ref @_TFC17materializeForSet22LazyFinalClassPropertys3catSi func inoutAccessOfLazyFinalClassProperty(l: inout LazyFinalClassProperty) { increment(&l.cat) } // CHECK-LABEL: sil_witness_table hidden Bill: Totalled module materializeForSet { // CHECK: method #Totalled.total!getter.1: @_TTWV17materializeForSet4BillS_8TotalledS_FS1_g5totalSi // CHECK: method #Totalled.total!setter.1: @_TTWV17materializeForSet4BillS_8TotalledS_FS1_s5totalSi // CHECK: method #Totalled.total!materializeForSet.1: @_TTWV17materializeForSet4BillS_8TotalledS_FS1_m5totalSi // CHECK: }
17bacde433abb07fc2ce059052c7f9d0
54.08284
276
0.664375
false
false
false
false
LiuSky/XBKit
refs/heads/master
Pods/RxExtension/RxExtension/Classes/Operators+Rx.swift
mit
1
// // Operators+Rx.swift // DianDan // // Created by xiaobin liu on 2017/3/10. // Copyright © 2017年 Sky. All rights reserved. // import UIKit import RxSwift import RxCocoa // Two way binding operator between control property and variable, that's all it takes { infix operator <-> : DefaultPrecedence public func nonMarkedText(_ textInput: UITextInput) -> String? { let start = textInput.beginningOfDocument let end = textInput.endOfDocument guard let rangeAll = textInput.textRange(from: start, to: end), let text = textInput.text(in: rangeAll) else { return nil } guard let markedTextRange = textInput.markedTextRange else { return text } guard let startRange = textInput.textRange(from: start, to: markedTextRange.start), let endRange = textInput.textRange(from: markedTextRange.end, to: end) else { return text } return (textInput.text(in: startRange) ?? "") + (textInput.text(in: endRange) ?? "") } public func <-> <Base: UITextInput>(textInput: TextInput<Base>, variable: Variable<String>) -> Disposable { let bindToUIDisposable = variable.asObservable() .bindTo(textInput.text.orEmpty) let bindToVariable = textInput.text .subscribe(onNext: { [weak base = textInput.base] n in guard let base = base else { return } let nonMarkedTextValue = nonMarkedText(base) /** In some cases `textInput.textRangeFromPosition(start, toPosition: end)` will return nil even though the underlying value is not nil. This appears to be an Apple bug. If it's not, and we are doing something wrong, please let us know. The can be reproed easily if replace bottom code with if nonMarkedTextValue != variable.value { variable.value = nonMarkedTextValue ?? "" } and you hit "Done" button on keyboard. */ if let nonMarkedTextValue = nonMarkedTextValue, nonMarkedTextValue != variable.value { variable.value = nonMarkedTextValue } }, onCompleted: { bindToUIDisposable.dispose() }) return Disposables.create(bindToUIDisposable, bindToVariable) } public func <-> <T>(property: ControlProperty<T>, variable: Variable<T>) -> Disposable { if T.self == String.self { #if DEBUG fatalError("It is ok to delete this message, but this is here to warn that you are maybe trying to bind to some `rx_text` property directly to variable.\n" + "That will usually work ok, but for some languages that use IME, that simplistic method could cause unexpected issues because it will return intermediate results while text is being inputed.\n" + "REMEDY: Just use `textField <-> variable` instead of `textField.rx_text <-> variable`.\n" + "Find out more here: https://github.com/ReactiveX/RxSwift/issues/649\n" ) #endif } let bindToUIDisposable = variable.asObservable() .bindTo(property) let bindToVariable = property .subscribe(onNext: { n in variable.value = n }, onCompleted: { bindToUIDisposable.dispose() }) return Disposables.create(bindToUIDisposable, bindToVariable) } // } public func <-> <T: Equatable>(lhs: Variable<T>, rhs: Variable<T>) -> Disposable { let bindToUIDisposable = lhs.asObservable() .distinctUntilChanged() .bindTo(rhs) let bindToVariable = rhs.asObservable() .distinctUntilChanged() .bindTo(lhs) return Disposables.create(bindToUIDisposable, bindToVariable) }
607efc07f109bf7def759f2e3dc0e1ea
33.63964
211
0.622887
false
false
false
false
ushios/SwifTumb
refs/heads/master
Sources/SwifTumb/SwifTumb.swift
mit
1
// // SwifTumb.swift // SwifTumb // // Created by Ushio Shugo on 2016/12/11. // // import Foundation /// Tumblr client written by Swift open class SwifTumb { static let EnvConsumerKey: String = "SWIFTUMB_CONSUMER_KEY" static let EnvConsumerSecret: String = "SWIFTUMB_CONSUMER_SECRET" static let EnvOAuthToken: String = "SWIFTUMB_OAUTH_TOKEN" static let EnvOAuthTokenSecret: String = "SWIFTUMB_OAUTH_TOKEN_SECRET" /// Post types /// /// - Text: text post type /// - Quote: quote post type /// - Link: link post type /// - Answer: answer post type /// - Video: video post type /// - Audio: audio post type /// - Photo: photo post type /// - Chat: chat post type public enum PostType: String { case Text = "text" case Quote = "quote" case Link = "link" case Answer = "answer" case Video = "video" case Audio = "audio" case Photo = "photo" case Chat = "chat" } public static let DefaultProtocol: String = "https" public static let DefaultHost: String = "api.tumblr.com" public static let DefaultVersion: String = "v2" public static let RequestTokenUrl: String = "https://www.tumblr.com/oauth/request_token" public static let AuthorizeUrl: String = "https://www.tumblr.com/oauth/authorize" public static let AccessTokenUrl: String = "https://www.tumblr.com/oauth/access_token" /// OAuth adapter private var adapter: SwifTumbOAuthAdapter /// Make base url /// /// - Returns: url open static func baseUrl() -> String { return "\(SwifTumb.DefaultProtocol)://\(SwifTumb.DefaultHost)/\(SwifTumb.DefaultVersion)" } /// Make endpoint url /// /// - Parameter path: path string without prefix slash /// - Returns: endpoint url open static func url(_ path: String) -> String { return "\(SwifTumb.baseUrl())/\(path)" } /// init /// /// - Parameter adapter: oauth adapter public init(adapter: SwifTumbOAuthAdapter) { self.adapter = adapter } /// init /// /// - Parameters: /// - consumerKey: consumer key /// - consumerSecret: consumer secret /// - oauthToken: oauth token /// - oauthTokenSecret: oauth token secret public convenience init( consumerKey: String, consumerSecret: String, oauthToken: String, oauthTokenSecret: String ) { let adapter = OAuthSwiftAdapter( consumerKey: consumerKey, consumerSecret: consumerSecret, oauthToken: oauthToken, oauthTokenSecret: oauthTokenSecret ) self.init(adapter: adapter) } /// init from environments public convenience init?() { guard let consumerKey = getenv(SwifTumb.EnvConsumerKey), let consumerSecret = getenv(SwifTumb.EnvConsumerSecret), let oauthToken = getenv(SwifTumb.EnvOAuthToken), let oauthTokenSecret = getenv(SwifTumb.EnvOAuthTokenSecret) else { return nil } self.init( consumerKey: String(utf8String: consumerKey) ?? "", consumerSecret: String(utf8String: consumerSecret) ?? "", oauthToken: String(utf8String: oauthToken) ?? "", oauthTokenSecret: String(utf8String: oauthTokenSecret) ?? "" ) } /// Request to tumblr api /// /// - Parameters: /// - urlString: path /// - method: HTTP method /// - paramHolder: parameter struct /// - headers: HTTP headers /// - body: request body /// - checkTokenExpiration: <#checkTokenExpiration description#> /// - success: success handler /// - failure: failure handler /// - Returns: request handle private func request( _ urlString: String, method: SwifTumbHttpRequest.Method, paramHolder: SwifTumbParameterHolder? = nil, headers: SwifTumb.Headers? = nil, body: Data? = nil, checkTokenExpiration: Bool = true, success: SwifTumbHttpRequest.SuccessHandler?, failure: SwifTumbHttpRequest.FailureHandler? ) -> SwifTumbRequestHandle? { var params: [String: Any] if paramHolder == nil { params = [:] } else { params = paramHolder!.parameters() } return self.adapter.request(urlString, method: method, parameters: params, headers: headers, body: body, checkTokenExpiration: checkTokenExpiration, success: success, failure: failure) } /// Request user/info api /// /// - Parameters: /// - success: success handler /// - failure: failure handler /// - Returns: request handle /// - Throws: request exceptions open func userInfo( success: SwifTumbHttpRequest.SuccessHandler?, failure: SwifTumbHttpRequest.FailureHandler? ) throws -> SwifTumbRequestHandle? { let handle = self.request( SwifTumb.url("user/info"), method: SwifTumbHttpRequest.Method.GET, success: success, failure: failure ) return handle } /// Request parameters for user/dashboard public struct UserDashboardParameters: SwifTumbParameterHolder { var limit: Int? var offset: Int? var type: SwifTumb.PostType? var sinceId: Int? var reblogInfo: Bool? var notesInfo: Bool? } /// Request user/dashboard api /// /// - Parameters: /// - params: user/dashboard parameter /// - success: sucess handler /// - failure: failure handler /// - Returns: request handle /// - Throws: request exceptions open func userDashboard( params: UserDashboardParameters? = nil, success: SwifTumbHttpRequest.SuccessHandler?, failure: SwifTumbHttpRequest.FailureHandler? ) throws -> SwifTumbRequestHandle? { let handle = self.request( SwifTumb.url("user/dashboard"), method: SwifTumbHttpRequest.Method.GET, paramHolder: params, success: success, failure: failure ) return handle } /// Request parameters for user/likes public struct UserLikesParameters: SwifTumbParameterHolder { var limit: Int? var offset: Int? var before: Int? var after: Int? } /// Request user/likes api /// /// - Parameters: /// - params: user/likes parameter /// - success: success handler /// - failure: failure handler /// - Returns: request handle /// - Throws: request exceptions open func userLikes( params: UserLikesParameters? = nil, success: SwifTumbHttpRequest.SuccessHandler?, failure: SwifTumbHttpRequest.FailureHandler? ) throws -> SwifTumbRequestHandle? { let handle = self.request( SwifTumb.url("user/likes"), method: SwifTumbHttpRequest.Method.GET, paramHolder: params, success: success, failure: failure ) return handle } /// Request parameters for posts public struct PostsParameters: SwifTumbParameterHolder { var blogIdentifier: String var type: PostType? var id: Int? var tag: String? var limit: Int? var offset: Int? var reblogInfo: Bool? var notesInfo: Bool? var filter: String? } /// Request /blog/xxxx/posts api /// /// - Parameters: /// - params: posts parameters /// - success: success handler /// - failure: failure handler /// - Returns: request handle /// - Throws: request exceptions open func posts( params: PostsParameters, success: SwifTumbHttpRequest.SuccessHandler?, failure: SwifTumbHttpRequest.FailureHandler? ) throws -> SwifTumbRequestHandle? { var url: String if params.type != nil { url = SwifTumb.url("blog/\(params.blogIdentifier)/posts/\(params.type!.rawValue)") } else { url = SwifTumb.url("blog/\(params.blogIdentifier)/posts") } let handle = self.request( url, method: SwifTumbHttpRequest.Method.GET, paramHolder: params, success: success, failure: failure ) return handle } /// Request parameters for post/reblog public struct PostReblogParameters: SwifTumbParameterHolder { var blogIdentifier: String var id: Int? var reblogKey: String? var comment: String? var nativeInlineImages: Bool? } open func postReblog( params: PostReblogParameters, success: SwifTumbHttpRequest.SuccessHandler?, failure: SwifTumbHttpRequest.FailureHandler? ) throws -> SwifTumbRequestHandle? { let handle = self.request( SwifTumb.url("blog/\(params.blogIdentifier)/post/reblog"), method: SwifTumbHttpRequest.Method.POST, paramHolder: params, success: success, failure: failure ) return handle } } extension SwifTumb { public typealias Parameters = [String : Any] public typealias Headers = [String : String] } extension SwifTumb.UserDashboardParameters { public func parameters() -> [String : Any] { var param: [String: Any] = [:] if self.limit != nil { param["limit"] = self.limit! } if self.offset != nil { param["offset"] = self.offset! } if self.type != nil { param["type"] = self.type!.rawValue } if self.sinceId != nil { param["since_id"] = self.sinceId! } if self.reblogInfo != nil { param["reblog_info"] = self.reblogInfo! } if self.notesInfo != nil { param["notes_info"] = self.notesInfo! } return param } } extension SwifTumb.PostsParameters { public init(_ blogIdentifier: String) { self.blogIdentifier = blogIdentifier } public func parameters() -> [String : Any] { var param: [String: Any] = [:] if self.id != nil { param["id"] = self.id! } if self.tag != nil { param["tag"] = self.tag! } if self.limit != nil { param["limit"] = self.limit! } if self.offset != nil { param["offset"] = self.offset! } if self.reblogInfo != nil { param["reblog_info"] = self.reblogInfo! } if self.notesInfo != nil { param["notes_info"] = self.notesInfo! } if self.filter != nil { param["filter"] = self.filter! } return param } } extension SwifTumb.PostReblogParameters { public init( _ blogIdentifier: String, id: Int? = nil, reblogKey: String? = nil, comment: String? = nil, nativeInlineImages: Bool? = nil ) { self.blogIdentifier = blogIdentifier self.id = id ?? nil self.reblogKey = reblogKey ?? nil self.comment = comment self.nativeInlineImages = nativeInlineImages } public func parameters() -> [String: Any] { var param: [String: Any] = [:] param["id"] = self.id param["reblog_key"] = self.reblogKey if self.comment != nil { param["comment"] = self.comment } if self.nativeInlineImages != nil { param["native_inline_images"] = self.nativeInlineImages } return param } } extension SwifTumb.UserLikesParameters { public func parameters() -> [String: Any] { var param: [String: Any] = [:] if self.limit != nil { param["limit"] = self.limit! } if self.offset != nil { param["offset"] = self.offset } if self.after != nil { param["after"] = self.after } if self.before != nil { param["before"] = self.before } return param } } /// Parameters protocol public protocol SwifTumbParameterHolder { /// Get request parameters map /// /// - Returns: parameters func parameters() -> [String: Any] }
9116e4dc330b62daf4d9ab507dbc2d1f
27.48
192
0.560003
false
false
false
false
olejnjak/KartingCoach
refs/heads/development
KartingCoach/Model/LapTime.swift
gpl-3.0
1
// // LapTime.swift // KartingCoach // // Created by Jakub Olejník on 01/09/2017. // import Foundation struct LapTime: Codable { static var zero: LapTime { return LapTime(duration: 0) } var minutes: Int { return duration / 1000 / 60 } var seconds: Int { return duration / 1000 % 60 } var miliseconds: Int { return duration % 1000 } let duration: Int } extension LapTime { init(minutes: Int, seconds: Int, miliseconds: Int) { self.init(duration: minutes * 60 * 1000 + seconds * 1000 + miliseconds) } init?(string: String) { if let int = Int(string) { self.init(duration: int) } else { var components = string.trimmingCharacters(in: .whitespacesAndNewlines) .components(separatedBy: CharacterSet(charactersIn: ".:")) .compactMap { Int($0) } if components.isEmpty { return nil } var duration = components.last ?? 0 components.removeLast() if components.isEmpty { self.init(duration: duration) return } duration += components.last.flatMap { $0 * 1000 } ?? 0 components.removeLast() if components.isEmpty { self.init(duration: duration) return } duration += components.last.flatMap { $0 * 1000 * 60 } ?? 0 if duration > 0 { self.init(duration: duration) } else { return nil } } } } extension LapTime: CustomStringConvertible { var description: String { let secondsAndMiliseconds = String(format: "%02d", seconds) + "." + String(format: "%03d", miliseconds) return minutes > 0 ? String(minutes) + ":" + secondsAndMiliseconds : secondsAndMiliseconds } } extension LapTime: CustomDebugStringConvertible { var debugDescription: String { return "\(self)" } } extension LapTime: Comparable { static func < (lhs: LapTime, rhs: LapTime) -> Bool { return lhs.duration < rhs.duration } static func == (lhs: LapTime, rhs: LapTime) -> Bool { return lhs.duration == rhs.duration } } func + (lhs: LapTime, rhs: LapTime) -> LapTime { return LapTime(duration: lhs.duration + rhs.duration) } func / (lhs: LapTime, rhs: Int) -> LapTime { return LapTime(duration: lhs.duration / rhs) } extension Collection where Iterator.Element == LapTime { func average() -> Iterator.Element? { if isEmpty { return nil } return reduce(.zero, +) / Int(count) } }
a8aa945d3672816116ec743534a6efde
26.555556
111
0.557185
false
false
false
false
alexmiragall/Gourmet-iOS
refs/heads/master
gourmet/gourmet/viewcontrollers/FirstViewController.swift
mit
1
// // FirstViewController.swift // gourmet // // Created by Alejandro Miragall Arnal on 15/3/16. // Copyright © 2016 Alejandro Miragall Arnal. All rights reserved. // import UIKit import MapKit import Firebase import AlamofireImage class FirstViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, MKMapViewDelegate, CLLocationManagerDelegate, GIDSignInUIDelegate { @IBOutlet var mapView: MKMapView! @IBOutlet var tableView: UITableView! let locationManager = CLLocationManager() var restaurantRepository: RestaurantsRepository! var items: [Restaurant] = [] var userManager = UserManager.instance @IBAction func viewChanged(sender: UISegmentedControl) { if sender.selectedSegmentIndex == 0 { tableView.hidden = true mapView.hidden = false } else { tableView.hidden = false mapView.hidden = true } } override func viewDidLoad() { super.viewDidLoad() userManager.signIn(self, callback: { (error, errorType) in if (error) { print("Error login: \(errorType)") } else { print("Success login") } }) restaurantRepository = RestaurantsRepository() let nib = UINib(nibName: "RestaurantTableViewCell", bundle: nil) tableView.registerNib(nib, forCellReuseIdentifier: RestaurantTableViewCell.name) locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.requestWhenInUseAuthorization() mapView.delegate = self getRestaurants() } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "segueToRestaurantDetail" { let viewController = segue.destinationViewController as! RestaurantDetailViewController viewController.hidesBottomBarWhenPushed = true viewController.restaurant = sender as? Restaurant } } func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) { switch status { case .Authorized, .AuthorizedWhenInUse: manager.startUpdatingLocation() self.mapView.showsUserLocation = true default: break } } func mapView(mapView: MKMapView, didUpdateUserLocation userLocation: MKUserLocation) { let region = MKCoordinateRegionMakeWithDistance ( userLocation.location!.coordinate, 10000, 10000) mapView.setRegion(region, animated: true) } override func viewDidAppear(animated: Bool) { } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.items.count; } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell:RestaurantTableViewCell = self.tableView.dequeueReusableCellWithIdentifier(RestaurantTableViewCell.name) as! RestaurantTableViewCell let restaurant:Restaurant = self.items[indexPath.row] cell.loadItem(title: restaurant.name, image: restaurant.photo, completion: { cell.setNeedsLayout() }) return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) performSegueWithIdentifier("segueToRestaurantDetail", sender: self.items[indexPath.row]) print("You selected cell #\(indexPath.row)!") } func getRestaurants() { restaurantRepository.getItems({ self.items.appendContentsOf($0) dispatch_async(dispatch_get_main_queue(), { self.tableView.reloadData() self.updateMap() }) }) } func updateMap() { for rest in items { mapView.addAnnotation(RestaurantItem(title: rest.name, coordinate: CLLocationCoordinate2D(latitude: rest.lat!, longitude: rest.lon!), info: rest.description)) } } }
1e28f56db5b0d9345391da4d6f5062b0
33.677419
170
0.665116
false
false
false
false
kinetic-fit/sensors-swift
refs/heads/master
SwiftySensorsExample/ServiceDetailsViewController.swift
mit
1
// // ServiceDetailsViewController.swift // SwiftySensors // // https://github.com/kinetic-fit/sensors-swift // // Copyright © 2017 Kinetic. All rights reserved. // import UIKit import SwiftySensors class ServiceDetailsViewController: UIViewController { var service: Service! @IBOutlet var nameLabel: UILabel! @IBOutlet var tableView: UITableView! fileprivate var characteristics: [Characteristic] = [] override func viewDidLoad() { super.viewDidLoad() service.sensor.onCharacteristicDiscovered.subscribe(with: self) { [weak self] sensor, characteristic in self?.rebuildData() } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) nameLabel.text = "\(service!)".components(separatedBy: ".").last rebuildData() } fileprivate func rebuildData() { characteristics = Array(service.characteristics.values) tableView.reloadData() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let charViewController = segue.destination as? CharacteristicViewController { guard let indexPath = tableView.indexPathForSelectedRow else { return } if indexPath.row >= characteristics.count { return } charViewController.characteristic = characteristics[indexPath.row] } } } extension ServiceDetailsViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let charCell = tableView.dequeueReusableCell(withIdentifier: "CharCell")! let characteristic = characteristics[indexPath.row] charCell.textLabel?.text = "\(characteristic)".components(separatedBy: ".").last return charCell } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return characteristics.count } }
ed040f85c4378e3e54084248cbb80cc1
28.214286
111
0.664059
false
false
false
false
czerenkow/LublinWeather
refs/heads/master
App/Dashboard/DashboardInteractor.swift
mit
1
// // DashboardInteractor.swift // LublinWeather // // Created by Damian Rzeszot on 24/04/2018. // Copyright © 2018 Damian Rzeszot. All rights reserved. // import Foundation final class DashboardInteractor: Interactor { weak var router: DashboardRouter! weak var presentable: DashboardPresentable! // MARK: - var fetch: WeatherFetchService! var provider: StationsListProvider! var selected: SelectedStationWorker! var tracker: Tracker<DashboardEvent>! // MARK: - var station: Station! var measurements: [DashboardViewModel.Measurement: String]! var obsolete: Bool! // MARK: - override func activate() { super.activate() tracker.track(.activate) } override func deactivate() { super.deactivate() tracker.track(.deactivate) } // MARK: - Helpers private func reload() { let active = selected.load() let stations = provider.load().flatMap { $0.stations } station = stations.first(where: { $0.identifier == active }) ?? stations.first refresh() } private func update(loading: Bool = false) { let model = DashboardViewModel(station: station?.name ?? "???", loading: loading, obsolete: obsolete ?? false, measurements: self.measurements ?? [:]) presentable.configure(with: model) } } extension DashboardInteractor: DashboardOutput { func appearing() { reload() } func stations() { tracker.track(.stations) router.stations() } func settings() { tracker.track(.settings) router.settings() } func refresh() { tracker.track(.refresh(station?.source ?? "nil")) update(loading: true) fetch.fetch(identifier: station.identifier) { result in if let value = result.value { let measurements: [DashboardViewModel.Measurement: String?] = [ .date: self.format(date: value.date), .temperatureAir: self.format(number: value.temperatureAir), .temperatureGround: self.format(number: value.temperatureGround), .temperaturePerceptible: self.format(number: value.temperaturePerceptible), .pressure: self.format(number: value.pressure), .rain: self.format(number: value.rain), .windSpeed: self.format(number: value.windSpeed), .windDirection: self.format(direction: value.windDirection), .humidity: self.format(number: value.humidity) ] self.obsolete = value.obsolete self.measurements = measurements.filter { $0.value != nil }.mapValues { $0! } } else if let error = result.error { print("error \(error)") } self.update() } } private func format(date: Date?) -> String? { guard let date = date else { return nil } let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd HH:mm" return formatter.string(from: date) } private func format(number: Double?) -> String? { guard let number = number else { return nil } let formatter = NumberFormatter() formatter.numberStyle = .decimal formatter.usesGroupingSeparator = true formatter.minimumFractionDigits = 1 formatter.maximumFractionDigits = 1 return formatter.string(from: NSNumber(value: number)) } private func format(direction: WeatherResult.Direction?) -> String? { guard let direction = direction else { return nil } return String(direction) } }
850994b8688c9ad46de025d74c959429
27.212121
158
0.603921
false
false
false
false
IvanVorobei/RequestPermission
refs/heads/master
Example/SPPermission/SPPermission/Frameworks/SPPermission/SPPermissionType.swift
mit
2
// The MIT License (MIT) // Copyright © 2017 Ivan Vorobei ([email protected]) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit @objc public enum SPPermissionType: Int { case camera = 0 case photoLibrary = 1 case notification = 2 case microphone = 3 case calendar = 4 case contacts = 5 case reminders = 6 case speech = 7 case locationWhenInUse = 9 case locationAlwaysAndWhenInUse = 10 case motion = 11 case mediaLibrary = 12 var name: String { switch self { case .camera: return "Camera" case .photoLibrary: return "Photo Library" case .notification: return "Notification" case .microphone: return "Microphone" case .calendar: return "Calendar" case .contacts: return "Contacts" case .reminders: return "Reminders" case .speech: return "Speech" case .locationWhenInUse, .locationAlwaysAndWhenInUse: return "Location" case .motion: return "Motion" case .mediaLibrary: return "Media Library" } } var usageDescriptionKey: String? { switch self { case .camera: return "NSCameraUsageDescription" case .photoLibrary: return "NSPhotoLibraryUsageDescription" case .notification: return nil case .microphone: return "NSMicrophoneUsageDescription" case .calendar: return "NSCalendarsUsageDescription" case .contacts: return "NSContactsUsageDescription" case .reminders: return "NSRemindersUsageDescription" case .speech: return "NSSpeechRecognitionUsageDescription" case .locationWhenInUse: return "NSLocationWhenInUseUsageDescription" case .locationAlwaysAndWhenInUse: return "NSLocationAlwaysAndWhenInUseUsageDescription" case .motion: return "NSMotionUsageDescription" case .mediaLibrary: return "NSAppleMusicUsageDescription" } } }
e56f9f8a00af707323b8139f484a06c8
33.468085
81
0.65
false
false
false
false
aschwaighofer/swift
refs/heads/master
test/stdlib/Accelerate_vDSPClippingLimitThreshold.swift
apache-2.0
8
// RUN: %target-run-simple-swift // REQUIRES: executable_test // REQUIRES: rdar50301438 // REQUIRES: objc_interop // UNSUPPORTED: OS=watchos import StdlibUnittest import Accelerate var Accelerate_vDSPClippingLimitThresholdTests = TestSuite("Accelerate_vDSPClippingLimitThreshold") //===----------------------------------------------------------------------===// // // vDSP clipping, limit, and threshold tests; single-precision. // //===----------------------------------------------------------------------===// if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) { let count = 256 let n = vDSP_Length(256) let bounds = Float(-0.5) ... Float(0.5) let outputConstant: Float = 99 let source: [Float] = (0 ..< 256).map { i in return sin(Float(i) * 0.05) + sin(Float(i) * 0.025) } Accelerate_vDSPClippingLimitThresholdTests.test("vDSP/SinglePrecisionClipping") { var result = [Float](repeating: 0, count: count) vDSP.clip(source, to: bounds, result: &result) var legacyResult = [Float](repeating: -1, count: count) vDSP_vclip(source, 1, [bounds.lowerBound], [bounds.upperBound], &legacyResult, 1, n) let returnedResult = vDSP.clip(source, to: bounds) expectTrue(result.elementsEqual(legacyResult)) expectTrue(result.elementsEqual(returnedResult)) } Accelerate_vDSPClippingLimitThresholdTests.test("vDSP/SinglePrecisionInvertedClipping") { var result = [Float](repeating: 0, count: count) vDSP.invertedClip(source, to: bounds, result: &result) var legacyResult = [Float](repeating: -1, count: count) vDSP_viclip(source, 1, [bounds.lowerBound], [bounds.upperBound], &legacyResult, 1, n) let returnedResult = vDSP.invertedClip(source, to: bounds) expectTrue(result.elementsEqual(legacyResult)) expectTrue(result.elementsEqual(returnedResult)) } Accelerate_vDSPClippingLimitThresholdTests.test("vDSP/SinglePrecisionThreshold") { var result = [Float](repeating: 0, count: count) vDSP.threshold(source, to: bounds.lowerBound, with: .clampToThreshold, result: &result) var legacyResult = [Float](repeating: -1, count: count) vDSP_vthr(source, 1, [bounds.lowerBound], &legacyResult, 1, n) let returnedResult = vDSP.threshold(source, to: bounds.lowerBound, with: .clampToThreshold) expectTrue(result.elementsEqual(legacyResult)) expectTrue(result.elementsEqual(returnedResult)) } Accelerate_vDSPClippingLimitThresholdTests.test("vDSP/SinglePrecisionThresholdWithConstant") { var result = [Float](repeating: 0, count: count) vDSP.threshold(source, to: bounds.lowerBound, with: .signedConstant(outputConstant), result: &result) var legacyResult = [Float](repeating: -1, count: count) vDSP_vthrsc(source, 1, [bounds.lowerBound], [outputConstant], &legacyResult, 1, n) let returnedResult = vDSP.threshold(source, to: bounds.lowerBound, with: .signedConstant(outputConstant)) expectTrue(result.elementsEqual(legacyResult)) expectTrue(result.elementsEqual(returnedResult)) } Accelerate_vDSPClippingLimitThresholdTests.test("vDSP/SinglePrecisionThresholdWithZeroFill") { var result = [Float](repeating: 0, count: count) vDSP.threshold(source, to: bounds.lowerBound, with: .zeroFill, result: &result) var legacyResult = [Float](repeating: -1, count: count) vDSP_vthres(source, 1, [bounds.lowerBound], &legacyResult, 1, n) let returnedResult = vDSP.threshold(source, to: bounds.lowerBound, with: .zeroFill) expectTrue(result.elementsEqual(legacyResult)) expectTrue(result.elementsEqual(returnedResult)) } Accelerate_vDSPClippingLimitThresholdTests.test("vDSP/SinglePrecisionLimit") { var result = [Float](repeating: 0, count: count) vDSP.limit(source, limit: bounds.upperBound, withOutputConstant: outputConstant, result: &result) var legacyResult = [Float](repeating: -1, count: count) vDSP_vlim(source, 1, [bounds.upperBound], [outputConstant], &legacyResult, 1, n) let returnedResult = vDSP.limit(source, limit: bounds.upperBound, withOutputConstant: outputConstant) expectTrue(result.elementsEqual(legacyResult)) expectTrue(result.elementsEqual(returnedResult)) } } //===----------------------------------------------------------------------===// // // vDSP clipping, limit, and threshold tests; double-precision. // //===----------------------------------------------------------------------===// if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) { let count = 256 let n = vDSP_Length(256) let bounds = Double(-0.5) ... Double(0.5) let outputConstant: Double = 99 let source: [Double] = (0 ..< 256).map { i in return sin(Double(i) * 0.05) + sin(Double(i) * 0.025) } Accelerate_vDSPClippingLimitThresholdTests.test("vDSP/DoublePrecisionClipping") { var result = [Double](repeating: 0, count: count) vDSP.clip(source, to: bounds, result: &result) var legacyResult = [Double](repeating: -1, count: count) vDSP_vclipD(source, 1, [bounds.lowerBound], [bounds.upperBound], &legacyResult, 1, n) let returnedResult = vDSP.clip(source, to: bounds) expectTrue(result.elementsEqual(legacyResult)) expectTrue(result.elementsEqual(returnedResult)) } Accelerate_vDSPClippingLimitThresholdTests.test("vDSP/DoublePrecisionInvertedClipping") { var result = [Double](repeating: 0, count: count) vDSP.invertedClip(source, to: bounds, result: &result) var legacyResult = [Double](repeating: -1, count: count) vDSP_viclipD(source, 1, [bounds.lowerBound], [bounds.upperBound], &legacyResult, 1, n) let returnedResult = vDSP.invertedClip(source, to: bounds) expectTrue(result.elementsEqual(legacyResult)) expectTrue(result.elementsEqual(returnedResult)) } Accelerate_vDSPClippingLimitThresholdTests.test("vDSP/DoublePrecisionThreshold") { var result = [Double](repeating: 0, count: count) vDSP.threshold(source, to: bounds.lowerBound, with: .clampToThreshold, result: &result) var legacyResult = [Double](repeating: -1, count: count) vDSP_vthrD(source, 1, [bounds.lowerBound], &legacyResult, 1, n) let returnedResult = vDSP.threshold(source, to: bounds.lowerBound, with: .clampToThreshold) expectTrue(result.elementsEqual(legacyResult)) expectTrue(result.elementsEqual(returnedResult)) expectTrue(result.elementsEqual(legacyResult)) expectTrue(result.elementsEqual(returnedResult)) } Accelerate_vDSPClippingLimitThresholdTests.test("vDSP/DoublePrecisionThresholdWithConstant") { var result = [Double](repeating: 0, count: count) vDSP.threshold(source, to: bounds.lowerBound, with: .signedConstant(outputConstant), result: &result) var legacyResult = [Double](repeating: -1, count: count) vDSP_vthrscD(source, 1, [bounds.lowerBound], [outputConstant], &legacyResult, 1, n) let returnedResult = vDSP.threshold(source, to: bounds.lowerBound, with: .signedConstant(outputConstant)) expectTrue(result.elementsEqual(legacyResult)) expectTrue(result.elementsEqual(returnedResult)) } Accelerate_vDSPClippingLimitThresholdTests.test("vDSP/DoublePrecisionThresholdWithZeroFill") { var result = [Double](repeating: 0, count: count) vDSP.threshold(source, to: bounds.lowerBound, with: .zeroFill, result: &result) var legacyResult = [Double](repeating: -1, count: count) vDSP_vthresD(source, 1, [bounds.lowerBound], &legacyResult, 1, n) let returnedResult = vDSP.threshold(source, to: bounds.lowerBound, with: .zeroFill) expectTrue(result.elementsEqual(legacyResult)) expectTrue(result.elementsEqual(returnedResult)) } Accelerate_vDSPClippingLimitThresholdTests.test("vDSP/DoublePrecisionLimit") { var result = [Double](repeating: 0, count: count) vDSP.limit(source, limit: bounds.upperBound, withOutputConstant: outputConstant, result: &result) var legacyResult = [Double](repeating: -1, count: count) vDSP_vlimD(source, 1, [bounds.upperBound], [outputConstant], &legacyResult, 1, n) let returnedResult = vDSP.limit(source, limit: bounds.upperBound, withOutputConstant: outputConstant) expectTrue(result.elementsEqual(legacyResult)) expectTrue(result.elementsEqual(returnedResult)) } } runAllTests()
5dead1d7ac556724025568a1c5bd3ac7
34.431818
99
0.466325
false
true
false
false
Rapid-SDK/ios
refs/heads/master
Examples/RapiDO - ToDo list/RapiDO tvOS/FilterViewController.swift
mit
1
// // FilterViewController.swift // ExampleApp // // Created by Jan on 05/05/2017. // Copyright © 2017 Rapid. All rights reserved. // import UIKit import Rapid protocol FilterViewControllerDelegate: class { func filterViewControllerDidCancel(_ controller: FilterViewController) func filterViewControllerDidFinish(_ controller: FilterViewController, withFilter filter: RapidFilter?) } class FilterViewController: UIViewController { weak var delegate: FilterViewControllerDelegate? var filter: RapidFilter? @IBOutlet weak var segmentedControl: UISegmentedControl! @IBOutlet weak var tagsTableView: TagsTableView! @IBOutlet weak var doneButton: UIButton! @IBOutlet weak var cancelButton: UIButton! override func viewDidLoad() { super.viewDidLoad() setupUI() } // MARK: Actions @IBAction func cancel(_ sender: Any) { delegate?.filterViewControllerDidCancel(self) } @IBAction func done(_ sender: Any) { var operands = [RapidFilter]() // Segmented control selected index equal to 1 means "show all tasks regardless completion state", so no filter is needed // Otherwise, create filter for either completed or incompleted tasks if segmentedControl.selectedSegmentIndex != 1 { let completed = segmentedControl.selectedSegmentIndex == 0 operands.append(RapidFilter.equal(keyPath: Task.completedAttributeName, value: completed)) } // Create filter for selected tags let selectedTags = tagsTableView.selectedTags if selectedTags.count > 0 { var tagFilters = [RapidFilter]() for tag in selectedTags { tagFilters.append(RapidFilter.arrayContains(keyPath: Task.tagsAttributeName, value: tag.rawValue)) } // Combine single tag filters with logical "OR" operator operands.append(RapidFilter.or(tagFilters)) } // If there are any filters combine them with logical "AND" let filter: RapidFilter? if operands.count > 0 { filter = RapidFilter.and(operands) } else { filter = nil } delegate?.filterViewControllerDidFinish(self, withFilter: filter) } } fileprivate extension FilterViewController { func setupUI() { if let expression = filter?.expression, case .compound(_, let operands) = expression { var tagsSet = false var completionSet = false for operand in operands { switch operand { case .simple(_, _, let value): completionSet = true let done = value as? Bool ?? false let index = done ? 0 : 2 segmentedControl.selectedSegmentIndex = index case .compound(_, let operands): tagsSet = true var tags = [Tag]() for case .simple(_, _, let value) in operands { switch value as? String { case .some(Tag.home.rawValue): tags.append(.home) case .some(Tag.work.rawValue): tags.append(.work) case .some(Tag.other.rawValue): tags.append(.other) default: break } } tagsTableView.selectTags(tags) } } if !tagsSet { tagsTableView.selectTags([]) } if !completionSet { segmentedControl.selectedSegmentIndex = 1 } } else { segmentedControl.selectedSegmentIndex = 1 tagsTableView.selectTags([]) } setupFocusGuide() } func setupFocusGuide() { let doneGuide = UIFocusGuide() doneGuide.preferredFocusEnvironments = [doneButton] view.addLayoutGuide(doneGuide) view.addConstraint(NSLayoutConstraint(item: doneGuide, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 1)) view.addConstraint(NSLayoutConstraint(item: doneGuide, attribute: .bottom, relatedBy: .equal, toItem: doneButton, attribute: .top, multiplier: 1, constant: 0)) view.addConstraint(NSLayoutConstraint(item: doneGuide, attribute: .left, relatedBy: .equal, toItem: cancelButton, attribute: .right, multiplier: 1, constant: 0)) view.addConstraint(NSLayoutConstraint(item: doneGuide, attribute: .right, relatedBy: .equal, toItem: doneButton, attribute: .left, multiplier: 1, constant: 0)) let segmentGuide = UIFocusGuide() segmentGuide.preferredFocusEnvironments = [segmentedControl] view.addLayoutGuide(segmentGuide) view.addConstraint(NSLayoutConstraint(item: segmentGuide, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 1)) view.addConstraint(NSLayoutConstraint(item: segmentGuide, attribute: .centerY, relatedBy: .equal, toItem: segmentedControl, attribute: .centerY, multiplier: 1, constant: 0)) view.addConstraint(NSLayoutConstraint(item: segmentGuide, attribute: .left, relatedBy: .equal, toItem: cancelButton, attribute: .left, multiplier: 1, constant: 0)) view.addConstraint(NSLayoutConstraint(item: segmentGuide, attribute: .right, relatedBy: .equal, toItem: doneButton, attribute: .right, multiplier: 1, constant: 0)) } }
d719d8fb9350feb78a30240fb3652c4d
38.973154
181
0.588146
false
false
false
false
asynchrony/Re-Lax
refs/heads/master
ReLaxExample/StaticTextViewController.swift
mit
1
import UIKit import ReLax class StaticTextViewController: UIViewController { override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) tabBarItem = UITabBarItem(title: "Static Text", image: nil, tag: 0) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func loadView() { guard let image = UIImage(contentsOfFile: Bundle.main.path(forResource: "monstersinc", ofType: "lcr")!) else { fatalError("monstersinc LCR missing") } let example = StaticTextExampleView(layerContainer: DefaultContainer(views: [UIImageView(image: image)])) let parallaxParent = StaticTextParentButton(standardLCR: image, exampleView: example) view = parallaxParent view.backgroundColor = .darkGray } private var images: [UIImage] { return (1...5) .map { "\($0)" } .map { UIImage(contentsOfFile: Bundle.main.path(forResource: $0, ofType: "png")!)! } } private func generateLCR() -> UIImage? { let parallaxImage = ParallaxImage(images: Array(images.reversed())) return parallaxImage.image() } } class StaticTextExampleView: ParallaxView<DefaultContainer> { private let label = UILabel() override init(layerContainer: DefaultContainer, effectMultiplier: CGFloat = 1.0, sheenContainer: UIView? = nil) { super.init(layerContainer: layerContainer, effectMultiplier: effectMultiplier, sheenContainer: sheenContainer) label.text = "Release Date: 11/2/2001\nRunning Time: 1h 32m" label.numberOfLines = 0 label.font = UIFont.boldSystemFont(ofSize: 30) label.textAlignment = .center label.textColor = .white label.shadowColor = UIColor(white: 0.0, alpha: 0.5) addSubview(label) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() label.frame = bounds.divided(atDistance: 150, from: .maxYEdge).slice } }
7d95fbb9ceb595d7c3f530490e428c75
32.779661
152
0.736076
false
false
false
false
apple/swift-nio
refs/heads/main
IntegrationTests/tests_04_performance/test_01_resources/test_1000_copying_circularbuffer_to_array.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2022 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import NIOCore func run(identifier: String) { let data = CircularBuffer(repeating: UInt8(0xfe), count: 1024) measure(identifier: identifier) { var count = 0 for _ in 0..<1_000 { let copy = Array(data) count &+= copy.count } return count } }
82b38db7d4140c7ced6ee9f26eba0d27
26.758621
80
0.515528
false
false
false
false
devpunk/velvet_room
refs/heads/master
Source/Model/Sfo/MSfoHeaderFactory.swift
mit
1
import Foundation extension MSfoHeader { static let kBytes:Int = 20 private static let kElements:Int = 5 //MARK: internal static func factoryHeader( data:Data) -> MSfoHeader? { guard let array:[UInt32] = data.arrayFromBytes( elements:kElements) else { return nil } let rawMagic:UInt32 = array[0] let rawVersion:UInt32 = array[1] let rawKeysOffset:UInt32 = array[2] let rawValuesOffset:UInt32 = array[3] let rawCount:UInt32 = array[4] let magic:Int = Int(rawMagic) let version:Int = Int(rawVersion) let keysOffset:Int = Int(rawKeysOffset) let valuesOffset:Int = Int(rawValuesOffset) let count:Int = Int(rawCount) let header:MSfoHeader = MSfoHeader( magic:magic, version:version, keysOffset:keysOffset, valuesOffset:valuesOffset, count:count) return header } }
598fcaceeabf74fac429498199ee7f0c
23.636364
53
0.54428
false
false
false
false
bbqsrc/tasty-imitation-keyboard
refs/heads/master
Keyboard/KeyboardModel.swift
bsd-3-clause
1
// // KeyboardModel.swift // TransliteratingKeyboard // // Created by Alexei Baboulevitch on 7/10/14. // Copyright (c) 2014 Apple. All rights reserved. // import Foundation var counter = 0 enum ShiftState { case disabled case enabled case locked func uppercase() -> Bool { switch self { case .disabled: return false case .enabled: return true case .locked: return true } } } class Keyboard { var pages: [Page] init() { self.pages = [] } func addKey(_ key: Key, row: Int, page: Int) { if self.pages.count <= page { for _ in self.pages.count...page { self.pages.append(Page()) } } self.pages[page].addKey(key, row: row) } } class Page { var rows: [[Key]] init() { self.rows = [] } func addKey(_ key: Key, row: Int) { if self.rows.count <= row { for _ in self.rows.count...row { self.rows.append([]) } } self.rows[row].append(key) } } class Key: Hashable { enum KeyType { case character case specialCharacter case shift case backspace case modeChange case keyboardChange case keyboardHide case period case space case `return` case settings case other } var type: KeyType var uppercaseKeyCap: String? var lowercaseKeyCap: String? var uppercaseOutput: String? var lowercaseOutput: String? var uppercaseLongPressOutput: [String]? var lowercaseLongPressOutput: [String]? var toMode: Int? //if the key is a mode button, this indicates which page it links to var isCharacter: Bool { get { switch self.type { case .character, .specialCharacter, .period: return true default: return false } } } var isSpecial: Bool { get { switch self.type { case .shift, .backspace, .modeChange, .keyboardChange, .keyboardHide, .return, .settings: return true default: return false } } } var hasOutput: Bool { get { return (self.uppercaseOutput != nil) || (self.lowercaseOutput != nil) } } var hasLowercaseLongPress: Bool { get { return self.lowercaseLongPressOutput != nil } } var hasUppercaseLongPress: Bool { get { return self.uppercaseLongPressOutput != nil } } // TODO: this is kind of a hack var hashValue: Int init(_ type: KeyType) { self.type = type self.hashValue = counter counter += 1 } convenience init(_ key: Key) { self.init(key.type) self.uppercaseKeyCap = key.uppercaseKeyCap self.lowercaseKeyCap = key.lowercaseKeyCap self.uppercaseOutput = key.uppercaseOutput self.lowercaseOutput = key.lowercaseOutput self.toMode = key.toMode } func setLetter(_ letter: String) { self.lowercaseOutput = (letter as NSString).lowercased self.uppercaseOutput = (letter as NSString).uppercased self.lowercaseKeyCap = self.lowercaseOutput self.uppercaseKeyCap = self.uppercaseOutput } func setUppercaseLongPress(_ letters: [String]) { self.uppercaseLongPressOutput = letters } func setLowercaseLongPress(_ letters: [String]) { self.lowercaseLongPressOutput = letters } func longPressForCase(_ uppercase: Bool) -> [String] { if uppercase && self.hasUppercaseLongPress { return self.uppercaseLongPressOutput! } else if !uppercase && self.hasLowercaseLongPress { return self.lowercaseLongPressOutput! } else { return [] } } func outputForCase(_ uppercase: Bool) -> String { if uppercase { if self.uppercaseOutput != nil { return self.uppercaseOutput! } else if self.lowercaseOutput != nil { return self.lowercaseOutput! } else { return "" } } else { if self.lowercaseOutput != nil { return self.lowercaseOutput! } else if self.uppercaseOutput != nil { return self.uppercaseOutput! } else { return "" } } } func keyCapForCase(_ uppercase: Bool) -> String { if uppercase { if self.uppercaseKeyCap != nil { return self.uppercaseKeyCap! } else if self.lowercaseKeyCap != nil { return self.lowercaseKeyCap! } else { return "" } } else { if self.lowercaseKeyCap != nil { return self.lowercaseKeyCap! } else if self.uppercaseKeyCap != nil { return self.uppercaseKeyCap! } else { return "" } } } } func ==(lhs: Key, rhs: Key) -> Bool { return lhs.hashValue == rhs.hashValue }
ae784b714820fcc8b0bb65d4837b4410
22.638655
89
0.50391
false
false
false
false
OrielBelzer/StepCoin
refs/heads/master
Models/User.swift
mit
1
// // User.swift // StepCoin // // Created by Oriel Belzer on 12/22/16. // import ObjectMapper import Haneke class User: NSObject, NSCoding, Mappable { var id: Int? var email: String? var password: String? var phoneNumber: String? var notificationId: String? var credits: String? var createTime: String? var coins: [Coin2]? required init?(map: Map) { } func mapping(map: Map) { id <- map["id"] email <- map["email"] password <- map["password"] phoneNumber <- map["phoneNumber"] notificationId <- map["notificationId"] credits <- map["credits"] createTime <- map["createTime"] coins <- map["coins"] } //MARK: NSCoding required init(coder aDecoder: NSCoder) { self.id = aDecoder.decodeObject(forKey: "id") as? Int self.email = aDecoder.decodeObject(forKey: "email") as? String self.password = aDecoder.decodeObject(forKey: "password") as? String self.phoneNumber = aDecoder.decodeObject(forKey: "phoneNumber") as? String self.notificationId = aDecoder.decodeObject(forKey: "notificationId") as? String self.credits = aDecoder.decodeObject(forKey: "credits") as? String self.createTime = aDecoder.decodeObject(forKey: "createTime") as? String self.coins = aDecoder.decodeObject(forKey: "coins") as? [Coin2] } func encode(with aCoder: NSCoder) { aCoder.encode(id, forKey: "id") aCoder.encode(email, forKey: "email") aCoder.encode(password, forKey: "password") aCoder.encode(phoneNumber, forKey: "phoneNumber") aCoder.encode(notificationId, forKey: "notificationId") aCoder.encode(credits, forKey: "credits") aCoder.encode(createTime, forKey: "createTime") aCoder.encode(coins, forKey: "coins") } } extension User : DataConvertible, DataRepresentable { public typealias Result = User public class func convertFromData(_ data:Data) -> Result? { return NSKeyedUnarchiver.unarchiveObject(with: data as Data) as? User } public func asData() -> Data! { return (NSKeyedArchiver.archivedData(withRootObject: self) as NSData!) as Data! } }
b3a6c21346a16f09aa9c9c2e115a7186
31.027397
88
0.616339
false
false
false
false
DrabWeb/Azusa
refs/heads/master
Source/Azusa/Azusa/View Controllers/MusicPlayerController.swift
gpl-3.0
1
// // MusicPlayerController.swift // Azusa // // Created by Ushio on 2/10/17. // import Cocoa import Yui class MusicPlayerController: NSViewController { // MARK: - Properties // MARK: Public Properties var splitViewController : MusicPlayerSplitViewController! { return childViewControllers[0] as? MusicPlayerSplitViewController } var playerBarController : PlayerBarController! { return childViewControllers[1] as? PlayerBarController; } // MARK: Private Properties private var musicSource : MusicSource! { didSet { musicSource.eventManager.add(subscriber: EventSubscriber(events: [.connect, .player, .queue, .options, .database], performer: { event in self.musicSource.getPlayerStatus({ status, _ in self.playerBarController.display(status: status); self.playerBarController.canSkipPrevious = status.currentSongPosition != 0; if status.playingState == .stopped || status.currentSong.isEmpty { self.popOutPlayerBar(); } else { self.popInPlayerBar(); } }); // Keep the mini queue updated if self.playerBarController.isQueueOpen { self.playerBarController.onQueueOpen?(); } })); musicSource.connect(nil); } } private var window : NSWindow! private weak var playerBarBottomConstraint : NSLayoutConstraint! // MARK: - Methods // MARK: Public Methods override func viewDidLoad() { super.viewDidLoad(); initialize(); // I don't even // Maybe temporary? Creating an IBOutlet to the constraint(or even the player bar) makes the window not appear view.constraints.forEach { c in if c.identifier == "playerBarBottomConstraint" { self.playerBarBottomConstraint = c; return; } } NotificationCenter.default.addObserver(forName: PreferencesNotification.loaded, object: nil, queue: nil, using: { _ in let d = PluginManager.global.defaultPlugin!; self.musicSource = d.getPlugin!.getMusicSource(settings: d.settings); }); } func sourceMenuItemPressed(_ sender : NSMenuItem) { let p = (sender.representedObject as! PluginInfo); musicSource = p.getPlugin!.getMusicSource(settings: p.settings); } func popInPlayerBar(animate : Bool = true) { NSAnimationContext.runAnimationGroup({ (context) in context.duration = animate ? 0.2 : 0; context.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn); playerBarBottomConstraint.animator().constant = 0; }, completionHandler: nil); } func popOutPlayerBar(animate : Bool = true) { NSAnimationContext.runAnimationGroup({ (context) in context.duration = animate ? 0.2 : 0; context.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseIn); playerBarBottomConstraint.animator().constant = -62; }, completionHandler: nil); } // MARK: Private methods private func initialize() { window = NSApp.windows.last!; window.appearance = NSAppearance(named: NSAppearanceNameVibrantLight); window.styleMask.insert(NSWindowStyleMask.fullSizeContentView); window.titleVisibility = .hidden; // Set up all the player bar actions playerBarController.onSeek = { time in self.musicSource.seek(to: time, completionHandler: nil); }; self.playerBarController.onRepeat = { mode in self.musicSource.setRepeatMode(to: mode.next(), completionHandler: nil); }; self.playerBarController.onPrevious = { playingState in self.musicSource.skipPrevious(completionHandler: nil); }; self.playerBarController.onPausePlay = { _ in // TODO: Make MusicSource use playing states instead of bools self.musicSource.togglePaused(completionHandler: { state, _ in self.playerBarController.display(playingState: state ? .playing : .paused); }); }; self.playerBarController.onNext = { playingState in self.musicSource.skipNext(completionHandler: nil); }; self.playerBarController.onShuffle = { self.musicSource.shuffleQueue(completionHandler: nil); }; self.playerBarController.onVolumeChanged = { volume in self.musicSource.setVolume(to: volume, completionHandler: nil); }; self.playerBarController.onQueueOpen = { self.musicSource.getQueue(completionHandler: { songs, currentPos, _ in // Drop the songs before and the current song so only up next songs are shown self.playerBarController.display(queue: Array(songs.dropFirst(currentPos + 1))); }); }; self.playerBarController.onClear = { self.musicSource.clearQueue(completionHandler: nil); }; Timer.scheduledTimer(timeInterval: TimeInterval(0.25), target: self, selector: #selector(MusicPlayerController.updateProgress), userInfo: nil, repeats: true); } internal func updateProgress() { self.musicSource.getElapsed({ elapsed, _ in self.playerBarController.display(progress: elapsed); }); } }
7e3a2ae5c0cc5c6fdbc8d042c7ddd494
35.31677
166
0.598084
false
false
false
false
getsocial-im/getsocial-ios-sdk
refs/heads/master
example/GetSocialDemo/Views/Communities/Groups/CreateGroups/CreateGroupViewController.swift
apache-2.0
1
// // CreateGroupsViewController.swift // GetSocialInternalDemo // // Created by Gábor Vass on 09/10/2020. // Copyright © 2020 GrambleWorld. All rights reserved. // import Foundation import UIKit class CreateGroupViewController: UIViewController { var oldGroup: Group? var model: CreateGroupModel private let scrollView = UIScrollView() private let idLabel = UILabel() private let idText = UITextFieldWithCopyPaste() private let titleLabel = UILabel() private let titleText = UITextFieldWithCopyPaste() private let descriptionLabel = UILabel() private let descriptionText = UITextFieldWithCopyPaste() private let avatarImageUrlLabel = UILabel() private let avatarImageUrlText = UITextFieldWithCopyPaste() private let avatarImage = UIImageView() private var avatarImageHeightConstraint: NSLayoutConstraint? private let avatarAddImageButton = UIButton(type: .roundedRect) private let avatarClearImageButton = UIButton(type: .roundedRect) private let allowPostLabel = UILabel() private let allowPostSegmentedControl = UISegmentedControl() private let allowInteractLabel = UILabel() private let allowInteractSegmentedControl = UISegmentedControl() private let property1KeyLabel = UILabel() private let property1KeyText = UITextFieldWithCopyPaste() private let property1ValueLabel = UILabel() private let property1ValueText = UITextFieldWithCopyPaste() private let isDiscoverableLabel = UILabel() private let isDiscoverableSwitch = UISwitch() private let isPrivateLabel = UILabel() private let isPrivateSwitch = UISwitch() private let labelsLabel = UILabel() private let labelsValueText = UITextFieldWithCopyPaste() private let createButton = UIButton(type: .roundedRect) private var isKeyboardShown = false private let imagePicker = UIImagePickerController() required init(_ groupToEdit: Group? = nil) { self.oldGroup = groupToEdit self.model = CreateGroupModel(oldGroupId: groupToEdit?.id) super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { NotificationCenter.default.removeObserver(self) } override func viewDidLoad() { setup() setupModel() } private func setupModel() { self.model.onGroupCreated = { [weak self] group in self?.hideActivityIndicatorView() self?.showAlert(withTitle: "Group created", andText: group.description) } self.model.onGroupUpdated = { [weak self] group in self?.hideActivityIndicatorView() self?.showAlert(withTitle: "Group updated", andText: group.description) } self.model.onError = { [weak self] error in self?.hideActivityIndicatorView() self?.showAlert(withTitle: "Error", andText: "Failed to create group, error: \(error)") } } private func setup() { // setup keyboard observers NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil) self.view.backgroundColor = UIDesign.Colors.viewBackground self.scrollView.translatesAutoresizingMaskIntoConstraints = false self.scrollView.contentSize = CGSize(width: self.view.frame.size.width, height: self.view.frame.size.height + 300) self.view.addSubview(self.scrollView) NSLayoutConstraint.activate([ self.scrollView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor), self.scrollView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor), self.scrollView.topAnchor.constraint(equalTo: self.view.topAnchor), self.scrollView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor), ]) setupIdRow() setupTitleRow() setupDescriptionRow() setupAvatarImageUrlRow() setupAvatarImageRow() setupAllowPostRow() setupAllowInteractRow() setupProperty1KeyRow() setupProperty1ValueRow() setupIsDiscoverableRow() setupIsPrivateRow() setupLabelsRow() setupCreateButton() } private func setupIdRow() { self.idLabel.translatesAutoresizingMaskIntoConstraints = false self.idLabel.text = "Group ID" self.idLabel.textColor = UIDesign.Colors.label self.scrollView.addSubview(self.idLabel) NSLayoutConstraint.activate([ self.idLabel.leadingAnchor.constraint(equalTo: self.scrollView.leadingAnchor, constant: 8), self.idLabel.trailingAnchor.constraint(equalTo: self.scrollView.trailingAnchor, constant: -8), self.idLabel.topAnchor.constraint(equalTo: self.scrollView.topAnchor, constant: 8), self.idLabel.heightAnchor.constraint(equalToConstant: 20) ]) self.idText.translatesAutoresizingMaskIntoConstraints = false self.idText.borderStyle = .roundedRect self.idText.isEnabled = true if let oldGroup = self.oldGroup { self.idText.text = oldGroup.id self.idText.isEnabled = false } self.scrollView.addSubview(self.idText) NSLayoutConstraint.activate([ self.idText.leadingAnchor.constraint(equalTo: self.scrollView.leadingAnchor, constant: 8), self.idText.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -8), self.idText.topAnchor.constraint(equalTo: self.idLabel.bottomAnchor, constant: 4), self.idText.heightAnchor.constraint(equalToConstant: 30) ]) } private func setupTitleRow() { self.titleLabel.translatesAutoresizingMaskIntoConstraints = false self.titleLabel.text = "Name" self.titleLabel.textColor = UIDesign.Colors.label self.scrollView.addSubview(self.titleLabel) NSLayoutConstraint.activate([ self.titleLabel.leadingAnchor.constraint(equalTo: self.scrollView.leadingAnchor, constant: 8), self.titleLabel.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -8), self.titleLabel.topAnchor.constraint(equalTo: self.idText.bottomAnchor, constant: 8), self.titleLabel.heightAnchor.constraint(equalToConstant: 20) ]) self.titleText.translatesAutoresizingMaskIntoConstraints = false self.titleText.borderStyle = .roundedRect self.titleText.text = self.oldGroup?.title self.scrollView.addSubview(self.titleText) NSLayoutConstraint.activate([ self.titleText.leadingAnchor.constraint(equalTo: self.scrollView.leadingAnchor, constant: 8), self.titleText.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -8), self.titleText.topAnchor.constraint(equalTo: self.titleLabel.bottomAnchor, constant: 4), self.titleText.heightAnchor.constraint(equalToConstant: 30) ]) } private func setupDescriptionRow() { self.descriptionLabel.translatesAutoresizingMaskIntoConstraints = false self.descriptionLabel.text = "Description" self.descriptionLabel.textColor = UIDesign.Colors.label self.scrollView.addSubview(self.descriptionLabel) NSLayoutConstraint.activate([ self.descriptionLabel.leadingAnchor.constraint(equalTo: self.scrollView.leadingAnchor, constant: 8), self.descriptionLabel.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -8), self.descriptionLabel.topAnchor.constraint(equalTo: self.titleText.bottomAnchor, constant: 8), self.descriptionLabel.heightAnchor.constraint(equalToConstant: 20) ]) self.descriptionText.translatesAutoresizingMaskIntoConstraints = false self.descriptionText.borderStyle = .roundedRect self.descriptionText.text = self.oldGroup?.groupDescription self.scrollView.addSubview(self.descriptionText) NSLayoutConstraint.activate([ self.descriptionText.leadingAnchor.constraint(equalTo: self.scrollView.leadingAnchor, constant: 8), self.descriptionText.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -8), self.descriptionText.topAnchor.constraint(equalTo: self.descriptionLabel.bottomAnchor, constant: 4), self.descriptionText.heightAnchor.constraint(equalToConstant: 30) ]) } private func setupAvatarImageUrlRow() { self.avatarImageUrlLabel.translatesAutoresizingMaskIntoConstraints = false self.avatarImageUrlLabel.text = "Avatar URL" self.avatarImageUrlLabel.textColor = UIDesign.Colors.label self.scrollView.addSubview(self.avatarImageUrlLabel) NSLayoutConstraint.activate([ self.avatarImageUrlLabel.leadingAnchor.constraint(equalTo: self.scrollView.leadingAnchor, constant: 8), self.avatarImageUrlLabel.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -8), self.avatarImageUrlLabel.topAnchor.constraint(equalTo: self.descriptionText.bottomAnchor, constant: 8), self.avatarImageUrlLabel.heightAnchor.constraint(equalToConstant: 20) ]) self.avatarImageUrlText.translatesAutoresizingMaskIntoConstraints = false self.avatarImageUrlText.borderStyle = .roundedRect self.avatarImageUrlText.text = self.oldGroup?.avatarUrl self.scrollView.addSubview(self.avatarImageUrlText) NSLayoutConstraint.activate([ self.avatarImageUrlText.leadingAnchor.constraint(equalTo: self.scrollView.leadingAnchor, constant: 8), self.avatarImageUrlText.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -8), self.avatarImageUrlText.topAnchor.constraint(equalTo: self.avatarImageUrlLabel.bottomAnchor, constant: 4), self.avatarImageUrlText.heightAnchor.constraint(equalToConstant: 30) ]) } private func setupAvatarImageRow() { self.avatarImage.translatesAutoresizingMaskIntoConstraints = false self.avatarImage.isHidden = true self.scrollView.addSubview(self.avatarImage) self.avatarAddImageButton.translatesAutoresizingMaskIntoConstraints = false self.avatarAddImageButton.isHidden = false self.avatarAddImageButton.setTitle("Select", for: .normal) self.avatarAddImageButton.addTarget(self, action: #selector(selectImage), for: .touchUpInside) self.scrollView.addSubview(self.avatarAddImageButton) self.avatarClearImageButton.translatesAutoresizingMaskIntoConstraints = false self.avatarClearImageButton.isHidden = true self.avatarClearImageButton.setTitle("Clear", for: .normal) self.avatarClearImageButton.addTarget(self, action: #selector(clearImage), for: .touchUpInside) self.scrollView.addSubview(self.avatarClearImageButton) self.avatarImageHeightConstraint = self.avatarImage.heightAnchor.constraint(equalToConstant: 0) NSLayoutConstraint.activate([ self.avatarImage.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 8), self.avatarImage.topAnchor.constraint(equalTo: self.avatarImageUrlText.bottomAnchor, constant: 8), self.avatarImage.widthAnchor.constraint(equalToConstant: 200), self.avatarImageHeightConstraint!, ]) NSLayoutConstraint.activate([ self.avatarAddImageButton.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 8), self.avatarAddImageButton.topAnchor.constraint(equalTo: self.avatarImage.bottomAnchor, constant: 8), self.avatarAddImageButton.heightAnchor.constraint(equalToConstant: 30), self.avatarAddImageButton.widthAnchor.constraint(equalToConstant: 100) ]) NSLayoutConstraint.activate([ self.avatarClearImageButton.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: 8), self.avatarClearImageButton.topAnchor.constraint(equalTo: self.avatarImage.bottomAnchor, constant: 8), self.avatarClearImageButton.heightAnchor.constraint(equalToConstant: 30), self.avatarClearImageButton.widthAnchor.constraint(equalToConstant: 100) ]) } private func setupAllowPostRow() { self.allowPostLabel.translatesAutoresizingMaskIntoConstraints = false self.allowPostLabel.text = "Allow Post" self.allowPostLabel.textColor = UIDesign.Colors.label self.scrollView.addSubview(self.allowPostLabel) NSLayoutConstraint.activate([ self.allowPostLabel.leadingAnchor.constraint(equalTo: self.scrollView.leadingAnchor, constant: 8), self.allowPostLabel.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -8), self.allowPostLabel.topAnchor.constraint(equalTo: self.avatarAddImageButton.bottomAnchor, constant: 8), self.allowPostLabel.heightAnchor.constraint(equalToConstant: 20) ]) self.allowPostSegmentedControl.translatesAutoresizingMaskIntoConstraints = false self.allowPostSegmentedControl.insertSegment(withTitle: "Owner", at: 0, animated: false) self.allowPostSegmentedControl.insertSegment(withTitle: "Admin", at: 1, animated: false) self.allowPostSegmentedControl.insertSegment(withTitle: "Member", at: 2, animated: false) self.allowPostSegmentedControl.selectedSegmentIndex = 0 if let oldGroup = self.oldGroup { let oldValue = oldGroup.settings.permissions[CommunitiesAction.post]?.rawValue ?? 0 if oldValue == 3 { self.allowPostSegmentedControl.selectedSegmentIndex = 2 } else { self.allowPostSegmentedControl.selectedSegmentIndex = oldValue } } self.scrollView.addSubview(self.allowPostSegmentedControl) NSLayoutConstraint.activate([ self.allowPostSegmentedControl.leadingAnchor.constraint(equalTo: self.scrollView.leadingAnchor, constant: 8), self.allowPostSegmentedControl.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -8), self.allowPostSegmentedControl.topAnchor.constraint(equalTo: self.allowPostLabel.bottomAnchor, constant: 8), self.allowPostSegmentedControl.heightAnchor.constraint(equalToConstant: 20) ]) } private func setupAllowInteractRow() { self.allowInteractLabel.translatesAutoresizingMaskIntoConstraints = false self.allowInteractLabel.text = "Allow Interact" self.allowInteractLabel.textColor = UIDesign.Colors.label self.scrollView.addSubview(self.allowInteractLabel) NSLayoutConstraint.activate([ self.allowInteractLabel.leadingAnchor.constraint(equalTo: self.scrollView.leadingAnchor, constant: 8), self.allowInteractLabel.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -8), self.allowInteractLabel.topAnchor.constraint(equalTo: self.allowPostSegmentedControl.bottomAnchor, constant: 8), self.allowInteractLabel.heightAnchor.constraint(equalToConstant: 20) ]) self.allowInteractSegmentedControl.translatesAutoresizingMaskIntoConstraints = false self.allowInteractSegmentedControl.insertSegment(withTitle: "Owner", at: 0, animated: false) self.allowInteractSegmentedControl.insertSegment(withTitle: "Admin", at: 1, animated: false) self.allowInteractSegmentedControl.insertSegment(withTitle: "Member", at: 2, animated: false) self.allowInteractSegmentedControl.selectedSegmentIndex = 0 if let oldGroup = self.oldGroup { let oldValue = oldGroup.settings.permissions[CommunitiesAction.comment]?.rawValue ?? 0 if oldValue == 3 { self.allowInteractSegmentedControl.selectedSegmentIndex = 2 } else { self.allowInteractSegmentedControl.selectedSegmentIndex = oldValue } } self.scrollView.addSubview(self.allowInteractSegmentedControl) NSLayoutConstraint.activate([ self.allowInteractSegmentedControl.leadingAnchor.constraint(equalTo: self.scrollView.leadingAnchor, constant: 8), self.allowInteractSegmentedControl.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -8), self.allowInteractSegmentedControl.topAnchor.constraint(equalTo: self.allowInteractLabel.bottomAnchor, constant: 8), self.allowInteractSegmentedControl.heightAnchor.constraint(equalToConstant: 20) ]) } private func setupProperty1KeyRow() { self.property1KeyLabel.translatesAutoresizingMaskIntoConstraints = false self.property1KeyLabel.text = "Property key" self.property1KeyLabel.textColor = UIDesign.Colors.label self.scrollView.addSubview(self.property1KeyLabel) NSLayoutConstraint.activate([ self.property1KeyLabel.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 8), self.property1KeyLabel.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -8), self.property1KeyLabel.topAnchor.constraint(equalTo: self.allowInteractSegmentedControl.bottomAnchor, constant: 8), self.property1KeyLabel.heightAnchor.constraint(equalToConstant: 20) ]) self.property1KeyText.translatesAutoresizingMaskIntoConstraints = false self.property1KeyText.borderStyle = .roundedRect self.property1KeyText.text = self.oldGroup?.settings.properties.first?.key self.scrollView.addSubview(self.property1KeyText) NSLayoutConstraint.activate([ self.property1KeyText.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 8), self.property1KeyText.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -8), self.property1KeyText.topAnchor.constraint(equalTo: self.property1KeyLabel.bottomAnchor, constant: 4), self.property1KeyText.heightAnchor.constraint(equalToConstant: 30) ]) } private func setupProperty1ValueRow() { self.property1ValueLabel.translatesAutoresizingMaskIntoConstraints = false self.property1ValueLabel.text = "Property value" self.property1ValueLabel.textColor = UIDesign.Colors.label self.scrollView.addSubview(self.property1ValueLabel) NSLayoutConstraint.activate([ self.property1ValueLabel.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 8), self.property1ValueLabel.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -8), self.property1ValueLabel.topAnchor.constraint(equalTo: self.property1KeyText.bottomAnchor, constant: 8), self.property1ValueLabel.heightAnchor.constraint(equalToConstant: 20) ]) self.property1ValueText.translatesAutoresizingMaskIntoConstraints = false self.property1ValueText.borderStyle = .roundedRect self.property1ValueText.text = self.oldGroup?.settings.properties.first?.value self.scrollView.addSubview(self.property1ValueText) NSLayoutConstraint.activate([ self.property1ValueText.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 8), self.property1ValueText.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -8), self.property1ValueText.topAnchor.constraint(equalTo: self.property1ValueLabel.bottomAnchor, constant: 4), self.property1ValueText.heightAnchor.constraint(equalToConstant: 30) ]) } private func setupIsDiscoverableRow() { self.isDiscoverableLabel.translatesAutoresizingMaskIntoConstraints = false self.isDiscoverableLabel.text = "Discoverable?" self.isDiscoverableLabel.textColor = UIDesign.Colors.label self.scrollView.addSubview(self.isDiscoverableLabel) NSLayoutConstraint.activate([ self.isDiscoverableLabel.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 8), self.isDiscoverableLabel.topAnchor.constraint(equalTo: self.property1ValueText.bottomAnchor, constant: 8), self.isDiscoverableLabel.widthAnchor.constraint(equalToConstant: 200), self.isDiscoverableLabel.heightAnchor.constraint(equalToConstant: 30) ]) self.isDiscoverableSwitch.translatesAutoresizingMaskIntoConstraints = false if let oldGroup = self.oldGroup { self.isDiscoverableSwitch.isOn = oldGroup.settings.isDiscovarable } self.scrollView.addSubview(self.isDiscoverableSwitch) NSLayoutConstraint.activate([ self.isDiscoverableSwitch.leadingAnchor.constraint(equalTo: self.isDiscoverableLabel.trailingAnchor, constant: 8), self.isDiscoverableSwitch.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -8), self.isDiscoverableSwitch.centerYAnchor.constraint(equalTo: self.isDiscoverableLabel.centerYAnchor), self.isDiscoverableSwitch.heightAnchor.constraint(equalToConstant: 20) ]) } private func setupIsPrivateRow() { self.isPrivateLabel.translatesAutoresizingMaskIntoConstraints = false self.isPrivateLabel.text = "Private?" self.isPrivateLabel.textColor = UIDesign.Colors.label self.scrollView.addSubview(self.isPrivateLabel) NSLayoutConstraint.activate([ self.isPrivateLabel.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 8), self.isPrivateLabel.topAnchor.constraint(equalTo: self.isDiscoverableSwitch.bottomAnchor, constant: 8), self.isPrivateLabel.widthAnchor.constraint(equalToConstant: 200), self.isPrivateLabel.heightAnchor.constraint(equalToConstant: 40) ]) self.isPrivateSwitch.translatesAutoresizingMaskIntoConstraints = false if let oldGroup = self.oldGroup { self.isPrivateSwitch.isOn = oldGroup.settings.isPrivate } self.scrollView.addSubview(self.isPrivateSwitch) NSLayoutConstraint.activate([ self.isPrivateSwitch.leadingAnchor.constraint(equalTo: self.isPrivateLabel.trailingAnchor, constant: 8), self.isPrivateSwitch.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -8), self.isPrivateSwitch.centerYAnchor.constraint(equalTo: self.isPrivateLabel.centerYAnchor), self.isPrivateSwitch.heightAnchor.constraint(equalToConstant: 20) ]) } private func setupLabelsRow() { self.labelsLabel.translatesAutoresizingMaskIntoConstraints = false self.labelsLabel.text = "Labels" self.labelsLabel.textColor = UIDesign.Colors.label self.scrollView.addSubview(self.labelsLabel) NSLayoutConstraint.activate([ self.labelsLabel.leadingAnchor.constraint(equalTo: self.scrollView.leadingAnchor, constant: 8), self.labelsLabel.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -8), self.labelsLabel.topAnchor.constraint(equalTo: self.isPrivateLabel.bottomAnchor, constant: 8), self.labelsLabel.heightAnchor.constraint(equalToConstant: 20) ]) self.labelsValueText.translatesAutoresizingMaskIntoConstraints = false self.labelsValueText.borderStyle = .roundedRect self.labelsValueText.text = self.oldGroup?.settings.labels.joined(separator: ",") self.labelsValueText.placeholder = "label1,label2" self.scrollView.addSubview(self.labelsValueText) NSLayoutConstraint.activate([ self.labelsValueText.leadingAnchor.constraint(equalTo: self.scrollView.leadingAnchor, constant: 8), self.labelsValueText.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -8), self.labelsValueText.topAnchor.constraint(equalTo: self.labelsLabel.bottomAnchor, constant: 4), self.labelsValueText.heightAnchor.constraint(equalToConstant: 30) ]) } private func setupCreateButton() { self.createButton.translatesAutoresizingMaskIntoConstraints = false self.createButton.setTitle(self.oldGroup == nil ? "Create": "Update", for: .normal) self.createButton.addTarget(self, action: #selector(executeCreate(sender:)), for: .touchUpInside) self.scrollView.addSubview(self.createButton) NSLayoutConstraint.activate([ self.createButton.topAnchor.constraint(equalTo: self.labelsValueText.bottomAnchor, constant: 8), self.createButton.heightAnchor.constraint(equalToConstant: 40), self.createButton.widthAnchor.constraint(equalToConstant: 100), self.createButton.centerXAnchor.constraint(equalTo: self.view.centerXAnchor), self.createButton.bottomAnchor.constraint(equalTo: self.scrollView.bottomAnchor, constant: -8) ]) } @objc private func executeCreate(sender: UIView) { UIApplication.shared.sendAction(#selector(UIApplication.resignFirstResponder), to: nil, from: nil, for: nil) guard let groupId = self.idText.text, groupId.count > 0 else { showAlert(withText: "Group ID is mandatory!") return } if self.oldGroup == nil { guard let groupTitle = self.titleText.text, groupTitle.count > 0 else { showAlert(withText: "Name is mandatory!") return } } let groupContent = GroupContent(groupId: groupId) groupContent.title = self.titleText.text?.count == 0 ? nil : self.titleText.text groupContent.groupDescription = self.descriptionText.text if let avatarImage = self.avatarImage.image { groupContent.avatar = MediaAttachment.image(avatarImage) } else if let avatarUrl = self.avatarImageUrlText.text { groupContent.avatar = MediaAttachment.imageUrl(avatarUrl) } if let propertyKey = self.property1KeyText.text, let propertyValue = self.property1ValueText.text, propertyKey.count > 0, propertyValue.count > 0 { groupContent.properties = [propertyKey: propertyValue] } switch(self.allowPostSegmentedControl.selectedSegmentIndex) { case 0: groupContent.permissions[.post] = .owner break case 1: groupContent.permissions[.post] = .admin break case 2: groupContent.permissions[.post] = .member break default: groupContent.permissions[.post] = .member break } switch(self.allowInteractSegmentedControl.selectedSegmentIndex) { case 0: groupContent.permissions[.react] = .owner groupContent.permissions[.comment] = .owner break case 1: groupContent.permissions[.react] = .admin groupContent.permissions[.comment] = .admin break case 2: groupContent.permissions[.react] = .member groupContent.permissions[.comment] = .member break default: groupContent.permissions[.react] = .member groupContent.permissions[.comment] = .member break } groupContent.isDiscoverable = self.isDiscoverableSwitch.isOn groupContent.isPrivate = self.isPrivateSwitch.isOn if let labelsText = self.labelsValueText.text { groupContent.labels = labelsText.components(separatedBy: ",") } self.showActivityIndicatorView() self.model.createGroup(groupContent) } // MARK: Handle keyboard @objc private func keyboardWillShow(notification: NSNotification) { let userInfo = notification.userInfo if let keyboardSize = (userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue { self.scrollView.contentInset = UIEdgeInsets.init(top: self.scrollView.contentInset.top, left: self.scrollView.contentInset.left, bottom: keyboardSize.height, right: self.scrollView.contentInset.right) } } @objc private func keyboardWillHide(notification: NSNotification) { self.scrollView.contentInset = UIEdgeInsets.init(top: self.scrollView.contentInset.top, left: self.scrollView.contentInset.left, bottom: 0, right: self.scrollView.contentInset.right) } @objc func selectImage() { self.imagePicker.sourceType = .photoLibrary self.imagePicker.delegate = self self .present(self.imagePicker, animated: true, completion: nil) } @objc func clearImage() { self.avatarImage.image = nil self.avatarImage.isHidden = true self.avatarImageHeightConstraint?.constant = 0 self.avatarClearImageButton.isHidden = true } } extension CreateGroupViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate { func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { if let uiImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage { self.avatarImage.image = uiImage self.avatarImage.isHidden = false self.avatarClearImageButton.isHidden = false self.avatarImageHeightConstraint?.constant = 100.0 } self.imagePicker.dismiss(animated: true, completion: nil) } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { self.imagePicker.dismiss(animated: true, completion: nil) } }
27d8f745e5ac03351fa5a1fef5366049
49.178037
212
0.713533
false
false
false
false
rockgarden/swift_language
refs/heads/swift3
Playground/FibonacciSequence-original.playground/section-1.swift
mit
2
// Thinkful Playground // Thinkful.com // Fibonacci Sequence // By definition, the first two numbers in the Fibonacci sequence are 1 and 1, or 0 and 1, depending on the chosen starting point of the sequence, and each subsequent number is the sum of the previous two. class FibonacciSequence { let includesZero: Bool let values: [UInt] init(maxNumber: UInt, includesZero: Bool) { self.includesZero = includesZero if maxNumber == 0 && includesZero == false { values = [] } else if maxNumber == 0 { values = [0] } else { var sequence: [UInt] = [0,1,1] var nextNumber: UInt = 2 while nextNumber <= maxNumber { sequence.append(nextNumber) let lastNumber = sequence.last! let secondToLastNumber = sequence[sequence.count-2] let (sum, didOverflow) = UInt.addWithOverflow(lastNumber, secondToLastNumber) if didOverflow == true { print("Overflow! The next number is too big to store in a UInt!") break } nextNumber = sum } if includesZero == false { sequence.remove(at: 0) } values = sequence } } init(numberOfItemsInSequence: UInt, includesZero: Bool) { self.includesZero = includesZero if numberOfItemsInSequence == 0 { values = [] } else if numberOfItemsInSequence == 1 { if includesZero == true { values = [0] } else { values = [1] } } else { var sequence: [UInt] if includesZero == true { sequence = [0,1] } else { sequence = [1,1] } for _ in 2 ..< Int(numberOfItemsInSequence) { let lastNumber = sequence.last! let secondToLastNumber = sequence[sequence.count-2] let (nextNumber, didOverflow) = UInt.addWithOverflow(lastNumber, secondToLastNumber) if didOverflow == true { print("Overflow! The next number is too big to store in a UInt!") break } sequence.append(nextNumber) } values = sequence } } } let fibonacciSequence = FibonacciSequence(maxNumber:12345, includesZero: true) print(fibonacciSequence.values) let anotherSequence = FibonacciSequence(numberOfItemsInSequence: 113, includesZero: true) print(anotherSequence.values) UInt.max
83fb0e19f8ecb66b758bd00b15ac3023
32.4125
205
0.542462
false
false
false
false
whiteshadow-gr/HatForIOS
refs/heads/master
Pods/URITemplate/Sources/URITemplate.swift
mpl-2.0
1
// // URITemplate.swift // URITemplate // // Created by Kyle Fuller on 25/11/2014. // Copyright (c) 2014 Kyle Fuller. All rights reserved. // import Foundation // MARK: URITemplate /// A data structure to represent an RFC6570 URI template. public struct URITemplate : CustomStringConvertible, Equatable, Hashable, ExpressibleByStringLiteral, ExpressibleByExtendedGraphemeClusterLiteral, ExpressibleByUnicodeScalarLiteral { /// The underlying URI template public let template:String var regex:NSRegularExpression { let expression: NSRegularExpression? do { expression = try NSRegularExpression(pattern: "\\{([^\\}]+)\\}", options: NSRegularExpression.Options(rawValue: 0)) } catch let error as NSError { fatalError("Invalid Regex \(error)") } return expression! } var operators:[Operator] { return [ StringExpansion(), ReservedExpansion(), FragmentExpansion(), LabelExpansion(), PathSegmentExpansion(), PathStyleParameterExpansion(), FormStyleQueryExpansion(), FormStyleQueryContinuation(), ] } /// Initialize a URITemplate with the given template public init(template:String) { self.template = template } public typealias ExtendedGraphemeClusterLiteralType = StringLiteralType public init(extendedGraphemeClusterLiteral value: ExtendedGraphemeClusterLiteralType) { template = value } public typealias UnicodeScalarLiteralType = StringLiteralType public init(unicodeScalarLiteral value: UnicodeScalarLiteralType) { template = value } public init(stringLiteral value: StringLiteralType) { template = value } /// Returns a description of the URITemplate public var description: String { return template } public func hash(into hasher: inout Hasher) { hasher.combine(template.hashValue) } /// Returns the set of keywords in the URI Template public var variables: [String] { let expressions = regex.matches(template).map { expression -> String in // Removes the { and } from the expression #if swift(>=4.0) return String(expression[expression.index(after: expression.startIndex)..<expression.index(before: expression.endIndex)]) #else return expression.substring(with: expression.characters.index(after: expression.startIndex)..<expression.characters.index(before: expression.endIndex)) #endif } return expressions.map { expression -> [String] in var expression = expression for op in self.operators { if let op = op.op { if expression.hasPrefix(op) { #if swift(>=4.0) expression = String(expression[expression.index(after: expression.startIndex)...]) #else expression = expression.substring(from: expression.characters.index(after: expression.startIndex)) #endif break } } } return expression.components(separatedBy: ",").map { component in if component.hasSuffix("*") { #if swift(>=4.0) return String(component[..<component.index(before: component.endIndex)]) #else return component.substring(to: component.characters.index(before: component.endIndex)) #endif } else { return component } } }.reduce([], +) } /// Expand template as a URI Template using the given variables public func expand(_ variables: [String: Any]) -> String { return regex.substitute(template) { string in #if swift(>=4.0) var expression = String(string[string.index(after: string.startIndex)..<string.index(before: string.endIndex)]) let firstCharacter = String(expression[..<expression.index(after: expression.startIndex)]) #else var expression = string.substring(with: string.characters.index(after: string.startIndex)..<string.characters.index(before: string.endIndex)) let firstCharacter = expression.substring(to: expression.characters.index(after: expression.startIndex)) #endif var op = self.operators.filter { if let op = $0.op { return op == firstCharacter } return false }.first if (op != nil) { #if swift(>=4.0) expression = String(expression[expression.index(after: expression.startIndex)...]) #else expression = expression.substring(from: expression.characters.index(after: expression.startIndex)) #endif } else { op = self.operators.first } let rawExpansions = expression.components(separatedBy: ",").map { vari -> String? in var variable = vari var prefix:Int? if let range = variable.range(of: ":") { #if swift(>=4.0) prefix = Int(String(variable[range.upperBound...])) variable = String(variable[..<range.lowerBound]) #else prefix = Int(variable.substring(from: range.upperBound)) variable = variable.substring(to: range.lowerBound) #endif } let explode = variable.hasSuffix("*") if explode { #if swift(>=4.0) variable = String(variable[..<variable.index(before: variable.endIndex)]) #else variable = variable.substring(to: variable.characters.index(before: variable.endIndex)) #endif } if let value: Any = variables[variable] { return op!.expand(variable, value: value, explode: explode, prefix:prefix) } return op!.expand(variable, value:nil, explode:false, prefix:prefix) } let expansions = rawExpansions.reduce([], { accumulator, expansion -> [String] in if let expansion = expansion { return accumulator + [expansion] } return accumulator }) if expansions.count > 0 { return op!.prefix + expansions.joined(separator: op!.joiner) } return "" } } func regexForVariable(_ variable:String, op:Operator?) -> String { if op != nil { return "(.*)" } else { return "([A-z0-9%_\\-]+)" } } func regexForExpression(_ expression:String) -> String { var expression = expression let op = operators.filter { $0.op != nil && expression.hasPrefix($0.op!) }.first if op != nil { #if swift(>=4.0) expression = String(expression[expression.index(after: expression.startIndex)..<expression.endIndex]) #else expression = expression.substring(with: expression.characters.index(after: expression.startIndex)..<expression.endIndex) #endif } let regexes = expression.components(separatedBy: ",").map { variable -> String in self.regexForVariable(variable, op: op) } return regexes.joined(separator: (op ?? StringExpansion()).joiner) } var extractionRegex:NSRegularExpression? { let regex = try! NSRegularExpression(pattern: "(\\{([^\\}]+)\\})|[^(.*)]", options: NSRegularExpression.Options(rawValue: 0)) let pattern = regex.substitute(self.template) { expression in if expression.hasPrefix("{") && expression.hasSuffix("}") { let startIndex = expression.index(after: expression.startIndex) let endIndex = expression.index(before: expression.endIndex) #if swift(>=4.0) return self.regexForExpression(String(expression[startIndex..<endIndex])) #else return self.regexForExpression(expression.substring(with: startIndex..<endIndex)) #endif } else { return NSRegularExpression.escapedPattern(for: expression) } } do { return try NSRegularExpression(pattern: "^\(pattern)$", options: NSRegularExpression.Options(rawValue: 0)) } catch _ { return nil } } /// Extract the variables used in a given URL public func extract(_ url:String) -> [String:String]? { if let expression = extractionRegex { let input = url as NSString let range = NSRange(location: 0, length: input.length) let results = expression.matches(in: url, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: range) if let result = results.first { var extractedVariables:[String: String] = [:] for (index, variable) in variables.enumerated() { #if swift(>=4.0) let range = result.range(at: index + 1) #else let range = result.rangeAt(index + 1) #endif let value = NSString(string: input.substring(with: range)).removingPercentEncoding extractedVariables[variable] = value } return extractedVariables } } return nil } } /// Determine if two URITemplate's are equivalent public func ==(lhs:URITemplate, rhs:URITemplate) -> Bool { return lhs.template == rhs.template } // MARK: Extensions extension NSRegularExpression { func substitute(_ string:String, block:((String) -> (String))) -> String { let oldString = string as NSString let range = NSRange(location: 0, length: oldString.length) var newString = string as NSString let matches = self.matches(in: string, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: range) for match in Array(matches.reversed()) { let expression = oldString.substring(with: match.range) let replacement = block(expression) newString = newString.replacingCharacters(in: match.range, with: replacement) as NSString } return newString as String } func matches(_ string:String) -> [String] { let input = string as NSString let range = NSRange(location: 0, length: input.length) let results = self.matches(in: string, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: range) return results.map { result -> String in input.substring(with: result.range) } } } extension String { func percentEncoded() -> String { return addingPercentEncoding(withAllowedCharacters: CharacterSet.URITemplate.unreserved)! } } // MARK: Operators protocol Operator { /// Operator var op:String? { get } /// Prefix for the expanded string var prefix:String { get } /// Character to use to join expanded components var joiner:String { get } func expand(_ variable:String, value: Any?, explode:Bool, prefix:Int?) -> String? } class BaseOperator { var joiner:String { return "," } func expand(_ variable:String, value: Any?, explode:Bool, prefix:Int?) -> String? { if let value = value { if let values = value as? [String: Any] { return expand(variable:variable, value: values, explode: explode) } else if let values = value as? [Any] { return expand(variable:variable, value: values, explode: explode) } else if let _ = value as? NSNull { return expand(variable:variable) } else { return expand(variable:variable, value:"\(value)", prefix:prefix) } } return expand(variable:variable) } // Point to overide to expand a value (i.e, perform encoding) func expand(value:String) -> String { return value } // Point to overide to expanding a string func expand(variable:String, value:String, prefix:Int?) -> String { if let prefix = prefix { if value.count > prefix { let index = value.index(value.startIndex, offsetBy: prefix, limitedBy: value.endIndex) #if swift(>=4.0) return expand(value: String(value[..<index!])) #else return expand(value: value.substring(to: index!)) #endif } } return expand(value: value) } // Point to overide to expanding an array func expand(variable:String, value:[Any], explode:Bool) -> String? { let joiner = explode ? self.joiner : "," return value.map { self.expand(value: "\($0)") }.joined(separator: joiner) } // Point to overide to expanding a dictionary func expand(variable: String, value: [String: Any], explode: Bool) -> String? { let joiner = explode ? self.joiner : "," let keyValueJoiner = explode ? "=" : "," let elements = value.map({ key, value -> String in let expandedKey = self.expand(value: key) let expandedValue = self.expand(value: "\(value)") return "\(expandedKey)\(keyValueJoiner)\(expandedValue)" }) return elements.joined(separator: joiner) } // Point to overide when value not found func expand(variable: String) -> String? { return nil } } /// RFC6570 (3.2.2) Simple String Expansion: {var} class StringExpansion : BaseOperator, Operator { var op:String? { return nil } var prefix:String { return "" } override var joiner:String { return "," } override func expand(value:String) -> String { return value.percentEncoded() } } /// RFC6570 (3.2.3) Reserved Expansion: {+var} class ReservedExpansion : BaseOperator, Operator { var op:String? { return "+" } var prefix:String { return "" } override var joiner:String { return "," } override func expand(value:String) -> String { return value.addingPercentEncoding(withAllowedCharacters: CharacterSet.uriTemplateReservedAllowed)! } } /// RFC6570 (3.2.4) Fragment Expansion {#var} class FragmentExpansion : BaseOperator, Operator { var op:String? { return "#" } var prefix:String { return "#" } override var joiner:String { return "," } override func expand(value:String) -> String { return value.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlFragmentAllowed)! } } /// RFC6570 (3.2.5) Label Expansion with Dot-Prefix: {.var} class LabelExpansion : BaseOperator, Operator { var op:String? { return "." } var prefix:String { return "." } override var joiner:String { return "." } override func expand(value:String) -> String { return value.percentEncoded() } override func expand(variable:String, value:[Any], explode:Bool) -> String? { if value.count > 0 { return super.expand(variable: variable, value: value, explode: explode) } return nil } } /// RFC6570 (3.2.6) Path Segment Expansion: {/var} class PathSegmentExpansion : BaseOperator, Operator { var op:String? { return "/" } var prefix:String { return "/" } override var joiner:String { return "/" } override func expand(value:String) -> String { return value.percentEncoded() } override func expand(variable:String, value:[Any], explode:Bool) -> String? { if value.count > 0 { return super.expand(variable: variable, value: value, explode: explode) } return nil } } /// RFC6570 (3.2.7) Path-Style Parameter Expansion: {;var} class PathStyleParameterExpansion : BaseOperator, Operator { var op:String? { return ";" } var prefix:String { return ";" } override var joiner:String { return ";" } override func expand(value:String) -> String { return value.percentEncoded() } override func expand(variable:String, value:String, prefix:Int?) -> String { if value.count > 0 { let expandedValue = super.expand(variable: variable, value: value, prefix: prefix) return "\(variable)=\(expandedValue)" } return variable } override func expand(variable:String, value:[Any], explode:Bool) -> String? { let joiner = explode ? self.joiner : "," let expandedValue = value.map { let expandedValue = self.expand(value: "\($0)") if explode { return "\(variable)=\(expandedValue)" } return expandedValue }.joined(separator: joiner) if !explode { return "\(variable)=\(expandedValue)" } return expandedValue } override func expand(variable: String, value: [String: Any], explode: Bool) -> String? { let expandedValue = super.expand(variable: variable, value: value, explode: explode) if let expandedValue = expandedValue { if (!explode) { return "\(variable)=\(expandedValue)" } } return expandedValue } } /// RFC6570 (3.2.8) Form-Style Query Expansion: {?var} class FormStyleQueryExpansion : BaseOperator, Operator { var op:String? { return "?" } var prefix:String { return "?" } override var joiner:String { return "&" } override func expand(value:String) -> String { return value.percentEncoded() } override func expand(variable:String, value:String, prefix:Int?) -> String { let expandedValue = super.expand(variable: variable, value: value, prefix: prefix) return "\(variable)=\(expandedValue)" } override func expand(variable: String, value: [Any], explode: Bool) -> String? { if value.count > 0 { let joiner = explode ? self.joiner : "," let expandedValue = value.map { let expandedValue = self.expand(value: "\($0)") if explode { return "\(variable)=\(expandedValue)" } return expandedValue }.joined(separator: joiner) if !explode { return "\(variable)=\(expandedValue)" } return expandedValue } return nil } override func expand(variable: String, value: [String: Any], explode: Bool) -> String? { if value.count > 0 { let expandedVariable = self.expand(value: variable) let expandedValue = super.expand(variable: variable, value: value, explode: explode) if let expandedValue = expandedValue { if (!explode) { return "\(expandedVariable)=\(expandedValue)" } } return expandedValue } return nil } } /// RFC6570 (3.2.9) Form-Style Query Continuation: {&var} class FormStyleQueryContinuation : BaseOperator, Operator { var op:String? { return "&" } var prefix:String { return "&" } override var joiner:String { return "&" } override func expand(value:String) -> String { return value.percentEncoded() } override func expand(variable:String, value:String, prefix:Int?) -> String { let expandedValue = super.expand(variable: variable, value: value, prefix: prefix) return "\(variable)=\(expandedValue)" } override func expand(variable: String, value: [Any], explode: Bool) -> String? { let joiner = explode ? self.joiner : "," let expandedValue = value.map { let expandedValue = self.expand(value: "\($0)") if explode { return "\(variable)=\(expandedValue)" } return expandedValue }.joined(separator: joiner) if !explode { return "\(variable)=\(expandedValue)" } return expandedValue } override func expand(variable: String, value: [String: Any], explode: Bool) -> String? { let expandedValue = super.expand(variable: variable, value: value, explode: explode) if let expandedValue = expandedValue { if (!explode) { return "\(variable)=\(expandedValue)" } } return expandedValue } } private extension CharacterSet { struct URITemplate { static let digits = CharacterSet(charactersIn: "0"..."9") static let genDelims = CharacterSet(charactersIn: ":/?#[]@") static let subDelims = CharacterSet(charactersIn: "!$&'()*+,;=") static let unreservedSymbols = CharacterSet(charactersIn: "-._~") static let unreserved = { alpha.union(digits).union(unreservedSymbols) }() static let reserved = { genDelims.union(subDelims) }() static let alpha = { () -> CharacterSet in let upperAlpha = CharacterSet(charactersIn: "A"..."Z") let lowerAlpha = CharacterSet(charactersIn: "a"..."z") return upperAlpha.union(lowerAlpha) }() } static let uriTemplateReservedAllowed = { URITemplate.unreserved.union(URITemplate.reserved) }() }
b1a3b651d840b42ade2b21c630e557cc
29.191223
182
0.659225
false
false
false
false
pvieito/PythonKit
refs/heads/master
Tests/PythonKitTests/PythonFunctionTests.swift
apache-2.0
1
import XCTest import PythonKit class PythonFunctionTests: XCTestCase { private var canUsePythonFunction: Bool { let versionMajor = Python.versionInfo.major let versionMinor = Python.versionInfo.minor return (versionMajor == 3 && versionMinor >= 1) || versionMajor > 3 } func testPythonFunction() { guard canUsePythonFunction else { return } let pythonAdd = PythonFunction { args in let lhs = args[0] let rhs = args[1] return lhs + rhs }.pythonObject let pythonSum = pythonAdd(2, 3) XCTAssertNotNil(Double(pythonSum)) XCTAssertEqual(pythonSum, 5) // Test function with keyword arguments // Since there is no alternative function signature, `args` and `kwargs` // can be used without manually stating their type. This differs from // the behavior when there are no keywords. let pythonSelect = PythonFunction { args, kwargs in // NOTE: This may fail on Python versions before 3.6 because they do // not preserve order of keyword arguments XCTAssertEqual(args[0], true) XCTAssertEqual(kwargs[0].key, "y") XCTAssertEqual(kwargs[0].value, 2) XCTAssertEqual(kwargs[1].key, "x") XCTAssertEqual(kwargs[1].value, 3) let conditional = Bool(args[0])! let xIndex = kwargs.firstIndex(where: { $0.key == "x" })! let yIndex = kwargs.firstIndex(where: { $0.key == "y" })! return kwargs[conditional ? xIndex : yIndex].value }.pythonObject let pythonSelectOutput = pythonSelect(true, y: 2, x: 3) XCTAssertEqual(pythonSelectOutput, 3) } // From https://www.geeksforgeeks.org/create-classes-dynamically-in-python func testPythonClassConstruction() { guard canUsePythonFunction else { return } let constructor = PythonInstanceMethod { args in let `self` = args[0] `self`.constructor_arg = args[1] return Python.None } // Instead of calling `print`, use this to test what would be output. var printOutput: String? // Example of function using an alternative syntax for `args`. let displayMethod = PythonInstanceMethod { (args: [PythonObject]) in // let `self` = args[0] printOutput = String(args[1]) return Python.None } let classMethodOriginal = PythonInstanceMethod { args in // let cls = args[0] printOutput = String(args[1]) return Python.None } // Did not explicitly convert `constructor` or `displayMethod` to // PythonObject. This is intentional, as the `PythonClass` initializer // should take any `PythonConvertible` and not just `PythonObject`. let classMethod = Python.classmethod(classMethodOriginal.pythonObject) let Geeks = PythonClass("Geeks", members: [ // Constructor "__init__": constructor, // Data members "string_attribute": "Geeks 4 geeks!", "int_attribute": 1706256, // Member functions "func_arg": displayMethod, "class_func": classMethod, ]).pythonObject let obj = Geeks("constructor argument") XCTAssertEqual(obj.constructor_arg, "constructor argument") XCTAssertEqual(obj.string_attribute, "Geeks 4 geeks!") XCTAssertEqual(obj.int_attribute, 1706256) obj.func_arg("Geeks for Geeks") XCTAssertEqual(printOutput, "Geeks for Geeks") Geeks.class_func("Class Dynamically Created!") XCTAssertEqual(printOutput, "Class Dynamically Created!") } // Previously, there was a build error where passing a simple // `PythonClass.Members` literal made the literal's type ambiguous. It was // confused with `[String: PythonObject]`. The solution was adding a // `@_disfavoredOverload` attribute to the more specific initializer. func testPythonClassInitializer() { guard canUsePythonFunction else { return } let MyClass = PythonClass( "MyClass", superclasses: [Python.object], members: [ "memberName": "memberValue", ] ).pythonObject let memberValue = MyClass().memberName XCTAssertEqual(String(memberValue), "memberValue") } func testPythonClassInheritance() { guard canUsePythonFunction else { return } var helloOutput: String? var helloWorldOutput: String? // Declare subclasses of `Python.Exception` let HelloException = PythonClass( "HelloException", superclasses: [Python.Exception], members: [ "str_prefix": "HelloException-prefix ", "__init__": PythonInstanceMethod { args in let `self` = args[0] let message = "hello \(args[1])" helloOutput = String(message) // Conventional `super` syntax does not work; use this instead. Python.Exception.__init__(`self`, message) return Python.None }, // Example of function using the `self` convention instead of `args`. "__str__": PythonInstanceMethod { (`self`: PythonObject) in return `self`.str_prefix + Python.repr(`self`) } ] ).pythonObject let HelloWorldException = PythonClass( "HelloWorldException", superclasses: [HelloException], members: [ "str_prefix": "HelloWorldException-prefix ", "__init__": PythonInstanceMethod { args in let `self` = args[0] let message = "world \(args[1])" helloWorldOutput = String(message) `self`.int_param = args[2] // Conventional `super` syntax does not work; use this instead. HelloException.__init__(`self`, message) return Python.None }, // Example of function using the `self` convention instead of `args`. "custom_method": PythonInstanceMethod { (`self`: PythonObject) in return `self`.int_param } ] ).pythonObject // Test that inheritance works as expected let error1 = HelloException("test 1") XCTAssertEqual(helloOutput, "hello test 1") XCTAssertEqual(Python.str(error1), "HelloException-prefix HelloException('hello test 1')") XCTAssertEqual(Python.repr(error1), "HelloException('hello test 1')") let error2 = HelloWorldException("test 1", 123) XCTAssertEqual(helloOutput, "hello world test 1") XCTAssertEqual(helloWorldOutput, "world test 1") XCTAssertEqual(Python.str(error2), "HelloWorldException-prefix HelloWorldException('hello world test 1')") XCTAssertEqual(Python.repr(error2), "HelloWorldException('hello world test 1')") XCTAssertEqual(error2.custom_method(), 123) XCTAssertNotEqual(error2.custom_method(), "123") // Test that subclasses behave like Python exceptions // Example of function with no named parameters, which can be stated // ergonomically using an underscore. The ignored input is a [PythonObject]. let testFunction = PythonFunction { _ in throw HelloWorldException("EXAMPLE ERROR MESSAGE", 2) }.pythonObject do { try testFunction.throwing.dynamicallyCall(withArguments: []) XCTFail("testFunction did not throw an error.") } catch PythonError.exception(let error, _) { guard let description = String(error) else { XCTFail("A string could not be created from a HelloWorldException.") return } XCTAssertTrue(description.contains("EXAMPLE ERROR MESSAGE")) XCTAssertTrue(description.contains("HelloWorldException")) } catch { XCTFail("Got error that was not a Python exception: \(error.localizedDescription)") } } // Tests the ability to dynamically construct an argument list with keywords // and instantiate a `PythonInstanceMethod` with keywords. func testPythonClassInheritanceWithKeywords() { guard canUsePythonFunction else { return } func getValue(key: String, kwargs: [(String, PythonObject)]) -> PythonObject { let index = kwargs.firstIndex(where: { $0.0 == key })! return kwargs[index].1 } // Base class has the following arguments: // __init__(): // - 1 unnamed argument // - param1 // - param2 // // test_method(): // - param1 // - param2 let BaseClass = PythonClass( "BaseClass", superclasses: [], members: [ "__init__": PythonInstanceMethod { args, kwargs in let `self` = args[0] `self`.arg1 = args[1] `self`.param1 = getValue(key: "param1", kwargs: kwargs) `self`.param2 = getValue(key: "param2", kwargs: kwargs) return Python.None }, "test_method": PythonInstanceMethod { args, kwargs in let `self` = args[0] `self`.param1 += getValue(key: "param1", kwargs: kwargs) `self`.param2 += getValue(key: "param2", kwargs: kwargs) return Python.None } ] ).pythonObject // Derived class accepts the following arguments: // __init__(): // - param2 // - param3 // // test_method(): // - param1 // - param2 // - param3 let DerivedClass = PythonClass( "DerivedClass", superclasses: [], members: [ "__init__": PythonInstanceMethod { args, kwargs in let `self` = args[0] `self`.param3 = getValue(key: "param3", kwargs: kwargs) // Lists the arguments in an order different than they are // specified (self, param2, param3, param1, arg1). The // correct order is (self, arg1, param1, param2, param3). let newKeywordArguments = args.map { ("", $0) } + kwargs + [ ("param1", 1), ("", 0) ] BaseClass.__init__.dynamicallyCall( withKeywordArguments: newKeywordArguments) return Python.None }, "test_method": PythonInstanceMethod { args, kwargs in let `self` = args[0] `self`.param3 += getValue(key: "param3", kwargs: kwargs) BaseClass.test_method.dynamicallyCall( withKeywordArguments: args.map { ("", $0) } + kwargs) return Python.None } ] ).pythonObject let derivedInstance = DerivedClass(param2: 2, param3: 3) XCTAssertEqual(derivedInstance.arg1, 0) XCTAssertEqual(derivedInstance.param1, 1) XCTAssertEqual(derivedInstance.param2, 2) XCTAssertEqual(derivedInstance.checking.param3, 3) derivedInstance.test_method(param1: 1, param2: 2, param3: 3) XCTAssertEqual(derivedInstance.arg1, 0) XCTAssertEqual(derivedInstance.param1, 2) XCTAssertEqual(derivedInstance.param2, 4) XCTAssertEqual(derivedInstance.checking.param3, 6) // Validate that subclassing and instantiating the derived class does // not affect behavior of the parent class. let baseInstance = BaseClass(0, param1: 10, param2: 20) XCTAssertEqual(baseInstance.arg1, 0) XCTAssertEqual(baseInstance.param1, 10) XCTAssertEqual(baseInstance.param2, 20) XCTAssertEqual(baseInstance.checking.param3, nil) baseInstance.test_method(param1: 10, param2: 20) XCTAssertEqual(baseInstance.arg1, 0) XCTAssertEqual(baseInstance.param1, 20) XCTAssertEqual(baseInstance.param2, 40) XCTAssertEqual(baseInstance.checking.param3, nil) } }
8495db2129024084ea4d8d35e36d6d9e
38.167155
114
0.542078
false
true
false
false
Estimote/iOS-SDK
refs/heads/master
Examples/swift/LoyaltyStore/LoyaltyStore/Controllers/OffersViewController.swift
mit
1
// // Please report any problems with this app template to [email protected] // import UIKit class OffersViewController: UIViewController { @IBOutlet var collectionView: UICollectionView! var customer: Customer! @objc var offers = [Any]() fileprivate let itemsPerRow: CGFloat = 3 override func viewDidLoad() { super.viewDidLoad() // register header self.registerHeader() self.offers = exampleOffers() // register cell in table view self.addCustomerObserver() } // observe for selected customer @objc func addCustomerObserver() { let notificationCenter = NotificationCenter.default notificationCenter.addObserver(self, selector: #selector(setNewlySelectedCustomer), name: NSNotification.Name(rawValue: "customer selected"), object: nil) } @objc func setNewlySelectedCustomer(_ notification: Notification) { guard let newCustomer = notification.object as? Customer else { if notification.object == nil { self.customer = nil } return } self.customer = newCustomer } } // MARK: Table View extension OffersViewController: UICollectionViewDataSource, UICollectionViewDelegate { // MARK: Cell config func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "offerCell", for: indexPath) as! OfferCell let offer = self.offers[indexPath.item] as! Offer cell.imageView.image = offer.image cell.nameLabel.text = offer.name cell.costLabel.text = "\(offer.cost)" return cell } func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.offers.count } // MARK: Header func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "header", for: indexPath) as! HeaderView return header } @objc func registerHeader() { let headerNib = UINib.init(nibName: "HeaderView", bundle: Bundle.main) self.collectionView.register(headerNib, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "header") } // Substract points func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let offer = offers[indexPath.item] as! Offer AlertHelper.displayValidationAlert("Redeem \(offer.name) for \(emojiPoints[offer.cost]!)⭐️?", subtitle: nil, viewController: self) { _ in if (self.customer) != nil { self.customer.substractPoints(offer.cost) } else { let notEnoughPointsPopup = UIAlertController(title: "Detected customers", message: "Redeeming products is only available once there is a customer nearby 💁‍♂️", preferredStyle: UIAlertControllerStyle.alert) let understandAction = UIAlertAction(title: "Sure", style: UIAlertActionStyle.default, handler: nil) notEnoughPointsPopup.addAction(understandAction) self.present(notEnoughPointsPopup, animated: true, completion: nil) } } } }
f93164f3302ebab356eb6cf5bfd5a615
33.787879
217
0.714866
false
false
false
false
practicalswift/swift
refs/heads/master
test/Parse/enum.swift
apache-2.0
1
// RUN: %target-typecheck-verify-swift // FIXME: this test only passes on platforms which have Float80. // <rdar://problem/19508460> Floating point enum raw values are not portable // REQUIRES: CPU=i386 || CPU=x86_64 enum Empty {} enum Boolish { case falsy case truthy init() { self = .falsy } } var b = Boolish.falsy b = .truthy enum Optionable<T> { case Nought case Mere(T) } var o = Optionable<Int>.Nought o = .Mere(0) enum Color { case Red, Green, Grayscale(Int), Blue } var c = Color.Red c = .Green c = .Grayscale(255) c = .Blue let partialApplication = Color.Grayscale // Cases are excluded from non-enums. case FloatingCase // expected-error{{enum 'case' is not allowed outside of an enum}} struct SomeStruct { case StructCase // expected-error{{enum 'case' is not allowed outside of an enum}} } class SomeClass { case ClassCase // expected-error{{enum 'case' is not allowed outside of an enum}} } enum EnumWithExtension1 { case A1 } extension EnumWithExtension1 { case A2 // expected-error{{enum 'case' is not allowed outside of an enum}} } // Attributes for enum cases. enum EnumCaseAttributes { @xyz case EmptyAttributes // expected-error {{unknown attribute 'xyz'}} } // Recover when a switch 'case' label is spelled inside an enum (or outside). enum SwitchEnvy { case X: // expected-error{{'case' label can only appear inside a 'switch' statement}} case X(Y): // expected-error{{'case' label can only appear inside a 'switch' statement}} case X, Y: // expected-error{{'case' label can only appear inside a 'switch' statement}} case X where true: // expected-error{{'case' label can only appear inside a 'switch' statement}} case X(Y), Z(W): // expected-error{{'case' label can only appear inside a 'switch' statement}} case X(Y) where true: // expected-error{{'case' label can only appear inside a 'switch' statement}} case 0: // expected-error{{'case' label can only appear inside a 'switch' statement}} case _: // expected-error{{'case' label can only appear inside a 'switch' statement}} case (_, var x, 0): // expected-error{{'case' label can only appear inside a 'switch' statement}} } enum HasMethodsPropertiesAndCtors { case TweedleDee case TweedleDum func method() {} func staticMethod() {} init() {} subscript(x:Int) -> Int { return 0 } var property : Int { return 0 } } enum ImproperlyHasIVars { case Flopsy case Mopsy var ivar : Int // expected-error{{enums must not contain stored properties}} } // We used to crash on this. rdar://14678675 enum rdar14678675 { case U1, case U2 // expected-error{{expected identifier after comma in enum 'case' declaration}} case U3 } enum Recovery1 { case: // expected-error {{'case' label can only appear inside a 'switch' statement}} expected-error {{expected pattern}} } enum Recovery2 { case UE1: // expected-error {{'case' label can only appear inside a 'switch' statement}} } enum Recovery3 { case UE2(Void): // expected-error {{'case' label can only appear inside a 'switch' statement}} } enum Recovery4 { // expected-note {{in declaration of 'Recovery4'}} case Self Self // expected-error {{keyword 'Self' cannot be used as an identifier here}} expected-note {{if this name is unavoidable, use backticks to escape it}} {{8-12=`Self`}} expected-error {{consecutive declarations on a line must be separated by ';'}} {{12-12=;}} expected-error {{expected declaration}} } enum Recovery5 { case .UE3 // expected-error {{extraneous '.' in enum 'case' declaration}} {{8-9=}} case .UE4, .UE5 // expected-error@-1{{extraneous '.' in enum 'case' declaration}} {{8-9=}} // expected-error@-2{{extraneous '.' in enum 'case' declaration}} {{14-15=}} } enum Recovery6 { case Snout, _; // expected-error {{expected identifier after comma in enum 'case' declaration}} case _; // expected-error {{keyword '_' cannot be used as an identifier here}} expected-note {{if this name is unavoidable, use backticks to escape it}} {{8-9=`_`}} case Tusk, // expected-error {{expected pattern}} } // expected-error {{expected identifier after comma in enum 'case' declaration}} enum RawTypeEmpty : Int {} // expected-error {{an enum with no cases cannot declare a raw type}} // expected-error@-1{{'RawTypeEmpty' declares raw type 'Int', but does not conform to RawRepresentable and conformance could not be synthesized}} enum Raw : Int { case Ankeny, Burnside } enum MultiRawType : Int64, Int32 { // expected-error {{multiple enum raw types 'Int64' and 'Int32'}} case Couch, Davis } protocol RawTypeNotFirstProtocol {} enum RawTypeNotFirst : RawTypeNotFirstProtocol, Int { // expected-error {{raw type 'Int' must appear first in the enum inheritance clause}} {{24-24=Int, }} {{47-52=}} case E } enum ExpressibleByRawTypeNotLiteral : Array<Int> { // expected-error {{raw type 'Array<Int>' is not expressible by a string, integer, or floating-point literal}} // expected-error@-1{{'ExpressibleByRawTypeNotLiteral' declares raw type 'Array<Int>', but does not conform to RawRepresentable and conformance could not be synthesized}} case Ladd, Elliott, Sixteenth, Harrison } enum RawTypeCircularityA : RawTypeCircularityB, ExpressibleByIntegerLiteral { // expected-error {{'RawTypeCircularityA' has a raw type that depends on itself}} case Morrison, Belmont, Madison, Hawthorne init(integerLiteral value: Int) { self = .Morrison } } enum RawTypeCircularityB : RawTypeCircularityA, ExpressibleByIntegerLiteral { // expected-note {{enum 'RawTypeCircularityB' declared here}} case Willamette, Columbia, Sandy, Multnomah init(integerLiteral value: Int) { self = .Willamette } } struct ExpressibleByFloatLiteralOnly : ExpressibleByFloatLiteral { init(floatLiteral: Double) {} } enum ExpressibleByRawTypeNotIntegerLiteral : ExpressibleByFloatLiteralOnly { // expected-error {{'ExpressibleByRawTypeNotIntegerLiteral' declares raw type 'ExpressibleByFloatLiteralOnly', but does not conform to RawRepresentable and conformance could not be synthesized}} expected-error {{RawRepresentable conformance cannot be synthesized because raw type 'ExpressibleByFloatLiteralOnly' is not Equatable}} case Everett // expected-error {{enum cases require explicit raw values when the raw type is not expressible by integer or string literal}} case Flanders } enum RawTypeWithIntValues : Int { case Glisan = 17, Hoyt = 219, Irving, Johnson = 97209 } enum RawTypeWithNegativeValues : Int { case Glisan = -17, Hoyt = -219, Irving, Johnson = -97209 case AutoIncAcrossZero = -1, Zero, One } enum RawTypeWithUnicodeScalarValues : UnicodeScalar { // expected-error {{'RawTypeWithUnicodeScalarValues' declares raw type 'UnicodeScalar' (aka 'Unicode.Scalar'), but does not conform to RawRepresentable and conformance could not be synthesized}} case Kearney = "K" case Lovejoy // expected-error {{enum cases require explicit raw values when the raw type is not expressible by integer or string literal}} case Marshall = "M" } enum RawTypeWithCharacterValues : Character { // expected-error {{'RawTypeWithCharacterValues' declares raw type 'Character', but does not conform to RawRepresentable and conformance could not be synthesized}} case First = "い" case Second // expected-error {{enum cases require explicit raw values when the raw type is not expressible by integer or string literal}} case Third = "は" } enum RawTypeWithCharacterValues_Correct : Character { case First = "😅" // ok case Second = "👩‍👩‍👧‍👦" // ok case Third = "👋🏽" // ok case Fourth = "\u{1F3F4}\u{E0067}\u{E0062}\u{E0065}\u{E006E}\u{E0067}\u{E007F}" // ok } enum RawTypeWithCharacterValues_Error1 : Character { // expected-error {{'RawTypeWithCharacterValues_Error1' declares raw type 'Character', but does not conform to RawRepresentable and conformance could not be synthesized}} case First = "abc" // expected-error {{cannot convert value of type 'String' to raw type 'Character'}} } enum RawTypeWithFloatValues : Float { // expected-error {{'RawTypeWithFloatValues' declares raw type 'Float', but does not conform to RawRepresentable and conformance could not be synthesized}} case Northrup = 1.5 case Overton // expected-error {{enum case must declare a raw value when the preceding raw value is not an integer}} case Pettygrove = 2.25 } enum RawTypeWithStringValues : String { case Primrose // okay case Quimby = "Lucky Lab" case Raleigh // okay case Savier = "McMenamin's", Thurman = "Kenny and Zuke's" } enum RawValuesWithoutRawType { case Upshur = 22 // expected-error {{enum case cannot have a raw value if the enum does not have a raw type}} } enum RawTypeWithRepeatValues : Int { case Vaughn = 22 // expected-note {{raw value previously used here}} case Wilson = 22 // expected-error {{raw value for enum case is not unique}} } enum RawTypeWithRepeatValues2 : Double { case Vaughn = 22 // expected-note {{raw value previously used here}} case Wilson = 22.0 // expected-error {{raw value for enum case is not unique}} } enum RawTypeWithRepeatValues3 : Double { // 2^63-1 case Vaughn = 9223372036854775807 // expected-note {{raw value previously used here}} case Wilson = 9223372036854775807.0 // expected-error {{raw value for enum case is not unique}} } enum RawTypeWithRepeatValues4 : Double { // 2^64-1 case Vaughn = 18446744073709551615 // expected-note {{raw value previously used here}} case Wilson = 18446744073709551615.0 // expected-error {{raw value for enum case is not unique}} } enum RawTypeWithRepeatValues5 : Double { // FIXME: should reject. // 2^65-1 case Vaughn = 36893488147419103231 case Wilson = 36893488147419103231.0 } enum RawTypeWithRepeatValues6 : Double { // FIXME: should reject. // 2^127-1 case Vaughn = 170141183460469231731687303715884105727 case Wilson = 170141183460469231731687303715884105727.0 } enum RawTypeWithRepeatValues7 : Double { // FIXME: should reject. // 2^128-1 case Vaughn = 340282366920938463463374607431768211455 case Wilson = 340282366920938463463374607431768211455.0 } enum RawTypeWithRepeatValues8 : String { case Vaughn = "XYZ" // expected-note {{raw value previously used here}} case Wilson = "XYZ" // expected-error {{raw value for enum case is not unique}} } enum RawTypeWithNonRepeatValues : Double { case SantaClara = 3.7 case SanFernando = 7.4 case SanAntonio = -3.7 case SanCarlos = -7.4 } enum RawTypeWithRepeatValuesAutoInc : Double { case Vaughn = 22 // expected-note {{raw value auto-incremented from here}} case Wilson // expected-note {{raw value previously used here}} case Yeon = 23 // expected-error {{raw value for enum case is not unique}} } enum RawTypeWithRepeatValuesAutoInc2 : Double { case Vaughn = 23 // expected-note {{raw value previously used here}} case Wilson = 22 // expected-note {{raw value auto-incremented from here}} case Yeon // expected-error {{raw value for enum case is not unique}} } enum RawTypeWithRepeatValuesAutoInc3 : Double { case Vaughn // expected-note {{raw value implicitly auto-incremented from zero}} case Wilson // expected-note {{raw value previously used here}} case Yeon = 1 // expected-error {{raw value for enum case is not unique}} } enum RawTypeWithRepeatValuesAutoInc4 : String { case A = "B" // expected-note {{raw value previously used here}} case B // expected-error {{raw value for enum case is not unique}} } enum RawTypeWithRepeatValuesAutoInc5 : String { case A // expected-note {{raw value previously used here}} case B = "A" // expected-error {{raw value for enum case is not unique}} } enum RawTypeWithRepeatValuesAutoInc6 : String { case A case B // expected-note {{raw value previously used here}} case C = "B" // expected-error {{raw value for enum case is not unique}} } enum NonliteralRawValue : Int { case Yeon = 100 + 20 + 3 // expected-error {{raw value for enum case must be a literal}} } enum RawTypeWithPayload : Int { // expected-error {{'RawTypeWithPayload' declares raw type 'Int', but does not conform to RawRepresentable and conformance could not be synthesized}} expected-note {{declared raw type 'Int' here}} expected-note {{declared raw type 'Int' here}} case Powell(Int) // expected-error {{enum with raw type cannot have cases with arguments}} case Terwilliger(Int) = 17 // expected-error {{enum with raw type cannot have cases with arguments}} } enum RawTypeMismatch : Int { // expected-error {{'RawTypeMismatch' declares raw type 'Int', but does not conform to RawRepresentable and conformance could not be synthesized}} case Barbur = "foo" // expected-error {{}} } enum DuplicateMembers1 { case Foo // expected-note {{'Foo' previously declared here}} case Foo // expected-error {{invalid redeclaration of 'Foo'}} } enum DuplicateMembers2 { case Foo, Bar // expected-note {{'Foo' previously declared here}} expected-note {{'Bar' previously declared here}} case Foo // expected-error {{invalid redeclaration of 'Foo'}} case Bar // expected-error {{invalid redeclaration of 'Bar'}} } enum DuplicateMembers3 { case Foo // expected-note {{'Foo' previously declared here}} case Foo(Int) // expected-error {{invalid redeclaration of 'Foo'}} } enum DuplicateMembers4 : Int { // expected-error {{'DuplicateMembers4' declares raw type 'Int', but does not conform to RawRepresentable and conformance could not be synthesized}} case Foo = 1 // expected-note {{'Foo' previously declared here}} case Foo = 2 // expected-error {{invalid redeclaration of 'Foo'}} } enum DuplicateMembers5 : Int { // expected-error {{'DuplicateMembers5' declares raw type 'Int', but does not conform to RawRepresentable and conformance could not be synthesized}} case Foo = 1 // expected-note {{'Foo' previously declared here}} case Foo = 1 + 1 // expected-error {{invalid redeclaration of 'Foo'}} expected-error {{raw value for enum case must be a literal}} } enum DuplicateMembers6 { case Foo // expected-note 2{{'Foo' previously declared here}} case Foo // expected-error {{invalid redeclaration of 'Foo'}} case Foo // expected-error {{invalid redeclaration of 'Foo'}} } enum DuplicateMembers7 : String { // expected-error {{'DuplicateMembers7' declares raw type 'String', but does not conform to RawRepresentable and conformance could not be synthesized}} case Foo // expected-note {{'Foo' previously declared here}} case Foo = "Bar" // expected-error {{invalid redeclaration of 'Foo'}} } // Refs to duplicated enum cases shouldn't crash the compiler. // rdar://problem/20922401 func check20922401() -> String { let x: DuplicateMembers1 = .Foo switch x { case .Foo: return "Foo" } } enum PlaygroundRepresentation : UInt8 { case Class = 1 case Struct = 2 case Tuple = 3 case Enum = 4 case Aggregate = 5 case Container = 6 case IDERepr = 7 case Gap = 8 case ScopeEntry = 9 case ScopeExit = 10 case Error = 11 case IndexContainer = 12 case KeyContainer = 13 case MembershipContainer = 14 case Unknown = 0xFF static func fromByte(byte : UInt8) -> PlaygroundRepresentation { let repr = PlaygroundRepresentation(rawValue: byte) if repr == .none { return .Unknown } else { return repr! } } } struct ManyLiteralable : ExpressibleByIntegerLiteral, ExpressibleByStringLiteral, Equatable { init(stringLiteral: String) {} init(integerLiteral: Int) {} init(unicodeScalarLiteral: String) {} init(extendedGraphemeClusterLiteral: String) {} } func ==(lhs: ManyLiteralable, rhs: ManyLiteralable) -> Bool { return true } enum ManyLiteralA : ManyLiteralable { case A // expected-note {{raw value previously used here}} expected-note {{raw value implicitly auto-incremented from zero}} case B = 0 // expected-error {{raw value for enum case is not unique}} } enum ManyLiteralB : ManyLiteralable { // expected-error {{'ManyLiteralB' declares raw type 'ManyLiteralable', but does not conform to RawRepresentable and conformance could not be synthesized}} case A = "abc" case B // expected-error {{enum case must declare a raw value when the preceding raw value is not an integer}} } enum ManyLiteralC : ManyLiteralable { case A case B = "0" } // rdar://problem/22476643 public protocol RawValueA: RawRepresentable { var rawValue: Double { get } } enum RawValueATest: Double, RawValueA { case A, B } public protocol RawValueB { var rawValue: Double { get } } enum RawValueBTest: Double, RawValueB { case A, B } enum foo : String { // expected-error {{'foo' declares raw type 'String', but does not conform to RawRepresentable and conformance could not be synthesized}} case bar = nil // expected-error {{cannot convert 'nil' to raw type 'String'}} } // Static member lookup from instance methods struct EmptyStruct {} enum EnumWithStaticMember { static let staticVar = EmptyStruct() func foo() { let _ = staticVar // expected-error {{static member 'staticVar' cannot be used on instance of type 'EnumWithStaticMember'}} } } // SE-0036: struct SE0036_Auxiliary {} enum SE0036 { case A case B(SE0036_Auxiliary) case C(SE0036_Auxiliary) static func staticReference() { _ = A _ = self.A _ = SE0036.A } func staticReferenceInInstanceMethod() { _ = A // expected-error {{enum case 'A' cannot be used as an instance member}} {{9-9=SE0036.}} _ = self.A // expected-error {{enum case 'A' cannot be used as an instance member}} {{9-9=SE0036.}} _ = SE0036.A } static func staticReferenceInSwitchInStaticMethod() { switch SE0036.A { case A: break case B(_): break case C(let x): _ = x; break } } func staticReferenceInSwitchInInstanceMethod() { switch self { case A: break // expected-error {{enum case 'A' cannot be used as an instance member}} {{10-10=.}} case B(_): break // expected-error {{enum case 'B' cannot be used as an instance member}} {{10-10=.}} case C(let x): _ = x; break // expected-error {{enum case 'C' cannot be used as an instance member}} {{10-10=.}} } } func explicitReferenceInSwitch() { switch SE0036.A { case SE0036.A: break case SE0036.B(_): break case SE0036.C(let x): _ = x; break } } func dotReferenceInSwitchInInstanceMethod() { switch self { case .A: break case .B(_): break case .C(let x): _ = x; break } } static func dotReferenceInSwitchInStaticMethod() { switch SE0036.A { case .A: break case .B(_): break case .C(let x): _ = x; break } } init() { self = .A self = A // expected-error {{enum case 'A' cannot be used as an instance member}} {{12-12=SE0036.}} self = SE0036.A self = .B(SE0036_Auxiliary()) self = B(SE0036_Auxiliary()) // expected-error {{enum case 'B' cannot be used as an instance member}} {{12-12=SE0036.}} self = SE0036.B(SE0036_Auxiliary()) } } enum SE0036_Generic<T> { case A(x: T) func foo() { switch self { case A(_): break // expected-error {{enum case 'A' cannot be used as an instance member}} {{10-10=.}} expected-error {{missing argument label 'x:' in call}} } switch self { case .A(let a): print(a) } switch self { case SE0036_Generic.A(let a): print(a) } } } enum switch {} // expected-error {{keyword 'switch' cannot be used as an identifier here}} expected-note {{if this name is unavoidable, use backticks to escape it}} {{6-12=`switch`}} enum SE0155 { case emptyArgs() // expected-warning {{enum element with associated values must have at least one associated value}} // expected-note@-1 {{did you mean to remove the empty associated value list?}} {{17-18=}} // expected-note@-2 {{did you mean to explicitly add a 'Void' associated value?}} {{17-17=Void}} }
6f06ff9efbb48c5b095609d5e6e56051
34.85118
407
0.709426
false
false
false
false
macemmi/HBCI4Swift
refs/heads/master
HBCI4Swift/HBCI4Swift/Source/Sepa/HBCISepaUtility.swift
gpl-2.0
1
// // HBCISepaUtility.swift // HBCI4Swift // // Created by Frank Emminghaus on 03.07.20. // Copyright © 2020 Frank Emminghaus. All rights reserved. // import Foundation class HBCISepaUtility { let numberFormatter = NumberFormatter(); let dateFormatter = DateFormatter(); init() { initFormatters(); } fileprivate func initFormatters() { numberFormatter.decimalSeparator = "."; numberFormatter.alwaysShowsDecimalSeparator = true; numberFormatter.minimumFractionDigits = 2; numberFormatter.maximumFractionDigits = 2; numberFormatter.generatesDecimalNumbers = true; dateFormatter.dateFormat = "yyyy-MM-dd"; } func stringToNumber(_ s:String) ->NSDecimalNumber? { if let number = numberFormatter.number(from: s) as? NSDecimalNumber { return number; } else { logInfo("Sepa document parser: not able to convert \(s) to a value"); return nil; } } func stringToDate(_ s:String) ->Date? { if let date = dateFormatter.date(from: s) { return date; } else { logInfo("Sepa document parser: not able to convert \(s) to a date"); return nil; } } }
85e3705bad336c23a8c4f7d8d7e1212e
25.957447
81
0.611681
false
false
false
false
kjantzer/FolioReaderKit
refs/heads/master
Source/EPUBCore/FRBook.swift
bsd-3-clause
1
// // FRBook.swift // FolioReaderKit // // Created by Heberti Almeida on 09/04/15. // Extended by Kevin Jantzer on 12/30/15 // Copyright (c) 2015 Folio Reader. All rights reserved. // import UIKit public class FRBook: NSObject { var resources = FRResources() var metadata = FRMetadata() var spine = FRSpine() var smils = FRSmils() var tableOfContents: [FRTocReference]! var flatTableOfContents: [FRTocReference]! var opfResource: FRResource! var tocResource: FRResource? var coverImage: FRResource? var version: Double? var uniqueIdentifier: String? func hasAudio() -> Bool { return smils.smils.count > 0 ? true : false } func title() -> String? { return metadata.titles.first } // MARK: - Media Overlay Metadata // http://www.idpf.org/epub/301/spec/epub-mediaoverlays.html#sec-package-metadata func duration() -> String? { return metadata.findMetaByProperty("media:duration"); } // @NOTE: should "#" be automatically prefixed with the ID? func durationFor(ID: String) -> String? { return metadata.findMetaByProperty("media:duration", refinedBy: ID) } func activeClass() -> String! { let className = metadata.findMetaByProperty("media:active-class"); return className ?? "epub-media-overlay-active"; } func playbackActiveClass() -> String! { let className = metadata.findMetaByProperty("media:playback-active-class"); return className ?? "epub-media-overlay-playing"; } // MARK: - Media Overlay (SMIL) retrieval /** Get Smil File from a resource (if it has a media-overlay) */ func smilFileForResource(resource: FRResource!) -> FRSmilFile! { if( resource == nil || resource.mediaOverlay == nil ){ return nil } // lookup the smile resource to get info about the file let smilResource = resources.findById(resource.mediaOverlay) // use the resource to get the file return smils.findByHref( smilResource!.href ) } func smilFileForHref(href: String) -> FRSmilFile! { return smilFileForResource(resources.findByHref(href)) } func smilFileForId(ID: String) -> FRSmilFile! { return smilFileForResource(resources.findById(ID)) } }
0ca27af398d5a59cb21868e4db4b5397
28.158537
85
0.634463
false
false
false
false
andreamazz/Tropos
refs/heads/master
Sources/TroposCore/Formatters/TemperatureFormatter.swift
mit
3
public struct TemperatureFormatter { public var unitSystem: UnitSystem public init(unitSystem: UnitSystem = SettingsController().unitSystem) { self.unitSystem = unitSystem } public func stringFromTemperature(_ temperature: Temperature) -> String { let usesMetricSystem = unitSystem == .metric let rawTemperature = usesMetricSystem ? temperature.celsiusValue : temperature.fahrenheitValue return String(format: "%.f°", Double(rawTemperature)) } }
2bdcacea5b32e6a8370e038f4591c8fa
37.461538
102
0.716
false
false
false
false
benbahrenburg/BucketList
refs/heads/master
BucketList/Classes/Converters.swift
mit
1
// // BucketList - Just another cache provider with security built in // Converters.swift // // Created by Ben Bahrenburg on 3/23/16. // Copyright © 2016 bencoding.com. All rights reserved. // import Foundation import ImageIO import MobileCoreServices /** Internal Helper functions to convert formats */ internal struct Converters { static func convertImage(_ image: UIImage, option: CacheOptions.imageConverter) -> Data? { if option == .imageIO { return UIImageToDataIO(image) } return image.jpegData(compressionQuality: 0.9) } fileprivate static func UIImageToDataIO(_ image: UIImage) -> Data? { return autoreleasepool(invoking: { () -> Data in let data = NSMutableData() let options: NSDictionary = [ kCGImagePropertyOrientation: 1, // Top left kCGImagePropertyHasAlpha: true, kCGImageDestinationLossyCompressionQuality: 0.9 ] let imageDestinationRef = CGImageDestinationCreateWithData(data as CFMutableData, kUTTypeJPEG, 1, nil)! CGImageDestinationAddImage(imageDestinationRef, image.cgImage!, options) CGImageDestinationFinalize(imageDestinationRef) return data as Data }) } }
521696cc7c01fffbdbb4c371969ccfa1
28.777778
115
0.637313
false
false
false
false
AnirudhDas/ADEmailAndPassword
refs/heads/master
Classes/ADEmailAndPassword.swift
mit
1
import Foundation enum PasswordStrength { case None case Weak case Moderate case Strong } public class ADEmailAndPassword { public static func validateEmail(emailId: String) -> Bool { let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}" return NSPredicate(format: "SELF MATCHES %@", emailRegex).evaluate(with: emailId) } public static func validatePassword(password: String, length: Int, patternsToEscape: [String], caseSensitivty: Bool, numericDigits: Bool) -> Bool { if (password.characters.count < length) { return false } if caseSensitivty { let hasUpperCase = self.matchesForRegexInText(regex: "[A-Z]", text: password).count > 0 if !hasUpperCase { return false } let hasLowerCase = self.matchesForRegexInText(regex: "[a-z]", text: password).count > 0 if !hasLowerCase { return false } } if numericDigits { let hasNumbers = self.matchesForRegexInText(regex: "\\d", text: password).count > 0 if !hasNumbers { return false } } if patternsToEscape.count > 0 { let passwordLowerCase = password.lowercased() for pattern in patternsToEscape { let hasMatchesWithPattern = self.matchesForRegexInText(regex: pattern, text: passwordLowerCase).count > 0 if hasMatchesWithPattern { return false } } } return true } public static func matchesForRegexInText(regex: String, text: String) -> [String] { do { let regex = try NSRegularExpression(pattern: regex, options: []) let nsString = text as NSString let results = regex.matches(in: text, options: [], range: NSMakeRange(0, nsString.length)) return results.map { nsString.substring(with: $0.range)} } catch let error as NSError { print("invalid regex: \(error.localizedDescription)") return [] } } public static func checkPasswordStrength(password: String) -> String { let len: Int = password.characters.count var strength: Int = 0 switch len { case 0: return "None" case 1...4: strength += 1 case 5...8: strength += 2 default: strength += 3 } // Upper case, Lower case, Number & Symbols let patterns = ["^(?=.*[A-Z]).*$", "^(?=.*[a-z]).*$", "^(?=.*[0-9]).*$", "^(?=.*[!@#%&-_=:;\"'<>,`~\\*\\?\\+\\[\\]\\(\\)\\{\\}\\^\\$\\|\\\\\\.\\/]).*$"] for pattern in patterns { if (password.range(of: pattern, options: .regularExpression) != nil) { strength += 1 } } switch strength { case 0: return "None" case 1...3: return "Weak" case 4...6: return "Moderate" default: return "Strong" } } }
03d7cf67958f0d0a003b1b5375c8fdbc
31.846939
160
0.504505
false
false
false
false
softman123g/SMImagesShower
refs/heads/master
SMImagesShower/SMImageShowerViewController.swift
mit
1
// // SMImageBrowerViewController.swift // TakePictureAndRecordVideo // // Created by softman on 16/1/25. // Copyright © 2016年 softman. All rights reserved. // // Contact me: [email protected] // Or Star me: https://github.com/softman123g/SMImagesShower // // 原理: // 在一个大ScrollView中,嵌入两个小ScrollView,以达到复用的目的。小ScrollView负责从网络加载图片。 // 并且小ScrollView负责图片的点击放大等的处理,而大ScrollView负责翻页等的效果。 // // 优势: // 1.支持横屏竖屏 // 2.存储空间小。使用复用ScrollView,当图片很多时,依旧不耗费存储空间 // 3.支持底部页码显示 // 4.支持双击图片放大/缩小 // 5.支持双指放大/缩小图片 // 6.支持长按保存图片到相册 // 7.支持单击隐藏图片 // // 使用方法: // let imageUrls = ["http://image.photophoto.cn/m-6/Animal/Amimal%20illustration/0180300271.jpg", // "http://img4.3lian.com/sucai/img6/230/29.jpg", // "http://img.taopic.com/uploads/allimg/130501/240451-13050106450911.jpg", // "http://pic1.nipic.com/2008-08-12/200881211331729_2.jpg", // "http://a2.att.hudong.com/38/59/300001054794129041591416974.jpg"] // let imagesShowViewController = SMImagesShowerViewController() // do { // try imagesShowViewController.prepareDatas(imageUrls, currentDisplayIndex: 0) // } catch { // print("图片显示出错:第一个图片指定索引错误") // return // } // presentViewController(imagesShowViewController, animated: true, completion: nil) import UIKit public class SMImagesShowerViewController: UIViewController, UIScrollViewDelegate, LongPressGestureRecognizerDelegate{ // MARK: Properties private let pageScaleRadio = CGFloat(9.8/10)//页码位置垂直比例 private let pageLabelHeight = CGFloat(15.0)//页码高度 var currentImageIndex:Int = 0 //当前图片索引,从0开始 pre var currentPageNumber:Int = 0 //当前页码,从0开始,真正滑动后展现的页码 after var prePointX:Float = 0.0 //scrollview 滑过的上一个点x坐标 var currentSubScrollView:SMImageScrollView?//当前滑动的子ScrollView var imageModels:[SMImageModel] = [] //所有图片信息的model数组 var imageScrollViews:[SMImageScrollView] = [] //用于复用的子ScrollView var scrollView:UIScrollView!//大ScrollView var pageLabel:UILabel = UILabel()//页码 // MARK: Super override public func viewDidLoad() { super.viewDidLoad() self.scrollView = UIScrollView(frame: self.view.bounds) self.scrollView.backgroundColor = UIColor.blackColor() self.scrollView.showsHorizontalScrollIndicator = false self.scrollView.showsVerticalScrollIndicator = false self.scrollView.alwaysBounceVertical = false self.scrollView.pagingEnabled = true //翻页效果,一页显示一个子内容 self.scrollView.delegate = self self.addSubScrollView()//增加子ScrollView self.view.addSubview(self.scrollView) self.pageLabel.textAlignment = .Center self.pageLabel.font = UIFont.systemFontOfSize(12) self.pageLabel.textColor = UIColor.whiteColor() self.pageLabel.text = self.pageText() self.view.addSubview(self.pageLabel) self.addGesture() } override public func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override public func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { return UIInterfaceOrientationMask.All //支持横竖屏 } //第一次调用,以及横竖屏切换的时候,将重新布局 override public func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() self.scrollView.frame = self.view.bounds var size = self.scrollView.bounds.size size.width *= CGFloat(self.imageModels.count) self.scrollView.contentSize = size var frame = self.view.bounds frame.origin.y = frame.size.height * pageScaleRadio - pageLabelHeight frame.size.height = pageLabelHeight self.pageLabel.frame = frame //布局scrollview内部的控件 for imageScrollView in self.imageScrollViews { if let _imageModel = imageScrollView.imageModel { var frame = self.scrollView.bounds frame.origin.x = CGFloat(_imageModel.index) * frame.size.width imageScrollView.frame = frame imageScrollView.refleshSubview() } } currentSubScrollView?.resetScale(true) self.scrollView.setContentOffset((currentSubScrollView?.frame.origin)!, animated: true) } // MARK: Self Functions //准备数据相关,应该在展现前调用 currentDisplayIndex,从0开始 public func prepareDatas(imageUrls:[String], currentDisplayIndex:Int) throws { guard currentDisplayIndex >= 0 && currentDisplayIndex < imageUrls.count else { throw SMImageShowerError.ArrayOutOfBounds } imageModels.appendContentsOf(SMImageModel.initImages([], imageURLs: imageUrls)) currentPageNumber = currentDisplayIndex currentImageIndex = -1 //表示之前还没有显示 } func addSubScrollView(){ //当图片数大于2张时,使用2个UIScrollView重用。之所以用2个,因为翻页的时候用页面上只会存在2个页面 for _ in 0 ..< min(2, self.imageModels.count) { let imageScrollView = SMImageScrollView(frame: self.scrollView.bounds) imageScrollView.longpressGrstureRecorgnizerDelegate = self self.scrollView.addSubview(imageScrollView) self.imageScrollViews.append(imageScrollView) } self.setCurrentPage(currentPageNumber) } func pageText()->String{ return String(format: "%d/%d", currentPageNumber+1, self.imageModels.count) } //设置指定索引位置的图片页 func setCurrentPage(index:Int){ if currentImageIndex == index || index >= self.imageModels.count || index < 0{ return } //重置某一页,实现翻页后的效果 currentImageIndex = index let imageScrollView = dequeueScrollViewForResuable() if let _imageScrollView = imageScrollView { currentSubScrollView = _imageScrollView if _imageScrollView.tag == index { return } currentSubScrollView?.resetScale(true) var frame = self.scrollView.bounds frame.origin.x = CGFloat(index) * (frame.size.width)//frame的x坐标为当前scrollview的index倍,此时刚好是每一张图对应的在父ScrollView中的位置 currentSubScrollView?.frame = frame currentSubScrollView?.tag = index currentSubScrollView?.imageModel = self.imageModels[index] } } //重用SMImageScrollView。当前界面显示页为第1个ScrollView,下1个页面(左滑或者右滑产生的下一个页面)则始终是第2个Scrollview func dequeueScrollViewForResuable() -> SMImageScrollView?{ let imageScrollView = self.imageScrollViews.last if let _imageScrollView = imageScrollView { self.imageScrollViews.removeLast() self.imageScrollViews.insert(_imageScrollView, atIndex: 0) } return imageScrollView } func addGesture(){ //添加单击返回手势 let tap = UITapGestureRecognizer(target: self, action: "tapAction:") self.view.addGestureRecognizer(tap) //添加双击缩放手势 let doubleTap = UITapGestureRecognizer(target: self, action: "doubleTapAction:") doubleTap.numberOfTapsRequired = 2 self.view.addGestureRecognizer(doubleTap) //双击优先级比单击高 tap.requireGestureRecognizerToFail(doubleTap) } //单击 func tapAction(tap:UITapGestureRecognizer){ self.dismissViewControllerAnimated(true, completion: nil) } //双击 func doubleTapAction(doubleTap:UITapGestureRecognizer){ self.currentSubScrollView?.responseDoubleTapAction() } //该方法在滑动结束时(或滑动减速结束)调用,触发重置当前应该显示哪个子ScrollView。参数scrollView是父ScrollView func pageDragOperate(scrollView:UIScrollView){ let pointX = scrollView.contentOffset.x / scrollView.bounds.width //通过向上或向下取整,使得在滑动相对距离 超过一半 时才可以滑向下一页。也就是说什么时候滑动到下一页,是由自己决定的,而不是由别人决定的。 if Float(scrollView.contentOffset.x) > prePointX {//手向左滑 self.setCurrentPage(Int(ceil(pointX)))//取上整,取到下一个要显示的index值 } else {//手向右滑 self.setCurrentPage(Int(floor(pointX)))//取下整,取到上一个已显示的index值 } prePointX = Float(scrollView.contentOffset.x) //显示图片的页码,这里实时显示,是用于在用户滑动的时候,能够实时的展现,而不像用户翻页图片的时候只有超过0.5的大小才翻页 let int = Int(Float(pointX) + 0.5) if int != currentPageNumber { currentPageNumber = int self.pageLabel.text = self.pageText() } } // MARK: Delegate //会调用多次 public func scrollViewDidScroll(scrollView: UIScrollView) { if !self.scrollView.dragging { return } pageDragOperate(scrollView) } //会调用多次 public func scrollViewDidEndDecelerating(scrollView: UIScrollView) { pageDragOperate(scrollView) //将所有的子ScrollView都全部设置成原始的大小。因为可能用户当前界面中的子ScrollView放大了,所以滑动结束后,需要设置回原来的大小。也可以不设置,就看是不是需要这样的设置回原来大小的需求了。 for imgsc in self.imageScrollViews{ if imgsc != currentSubScrollView { imgsc.resetScale(true) } } } func longPressPresentAlertController(alertController: UIAlertController) { self.presentViewController(alertController, animated: true, completion: nil) } } enum SMImageShowerError:ErrorType { case ArrayOutOfBounds }
7c0e4a8a28cbd8b7bd9012a5b7518fb9
36.958159
124
0.674383
false
false
false
false
schrockblock/gtfs-stations
refs/heads/develop
Example/GTFS StationsTests/PredictionSpec.swift
mit
1
// // PredictionSpec.swift // GTFS Stations // // Created by Elliot Schrock on 7/30/15. // Copyright (c) 2015 Elliot Schrock. All rights reserved. // import GTFSStations import Quick import Nimble import SubwayStations class PredictionSpec: QuickSpec { override func spec() { describe("Prediction", { () -> Void in it("is equal when everything matches") { let route = NYCRoute(objectId: "1") let time = NSDate() let first = Prediction(time: time as Date) let second = Prediction(time: time as Date) first.route = route first.direction = .downtown second.route = route second.direction = .downtown expect([first].contains(where: {second == $0})).to(beTruthy()) } }) } }
1f95cf6de3a2ddf408b8c674d11bb3ad
26.085714
78
0.509494
false
false
false
false
mitochrome/complex-gestures-demo
refs/heads/master
apps/GestureRecognizer/Source/RootViewController.swift
mit
1
import UIKit import RxSwift extension GestureModel { static var shared = GestureModel() } class RootViewController: UIViewController { var disposeBag = DisposeBag() let complexGestureInput = ComplexGestureInput() @objc private func showInstructions() { let gestureList = GestureList() present(gestureList, animated: true, completion: nil) } // MARK: UIViewController override func viewDidLoad() { super.viewDidLoad() let canvas = UIView() view.addSubview(canvas) canvas.snp.makeConstraints { (make) in make.size.equalToSuperview() make.center.equalToSuperview() } complexGestureInput.view = canvas complexGestureInput.switchStatesOnFlatTap = false complexGestureInput.isGesturing.value = true let instructions = InstructionsView() instructions.button.addTarget(self, action: #selector(showInstructions), for: .touchUpInside) view.addSubview(instructions) instructions.snp.makeConstraints { (make) in make.top.equalTo(view.safeAreaLayoutGuide.snp.topMargin).inset(20) make.centerX.equalToSuperview() } let notification = NotificationPopover() notification.isUserInteractionEnabled = false view.addSubview(notification) notification.makeSizeConstraints() notification.snp.makeConstraints { (make) in make.centerX.equalToSuperview() make.bottom.equalToSuperview().inset(30) } view.addSubview(complexGestureInput.previewView) complexGestureInput.previewView.snp.makeConstraints { (make) in make.size.equalToSuperview() make.center.equalToSuperview() } let drawingLabelValues = complexGestureInput .currentDrawing .filter({ $0.strokes.count > 0 }) .distinctUntilChanged() .throttle(0.1, scheduler: MainScheduler.instance) .flatMap({ drawing -> Observable<(Drawing, [Double])> in guard let labelValues = predictLabel(drawing: drawing) else { return Observable.empty() } print("labelValues", labelValues) return Observable.just((drawing, labelValues)) }) .share() let immediateRecognition: Observable<Touches_Label> = drawingLabelValues .flatMap { (drawing: Drawing, labelValues: [Double]) -> Observable<Touches_Label> in // labelValues are the softmax outputs ("probabilities") // for each label in Touches_Label.all, in the the order // that they're present there. let max = labelValues.max()! if max < 0.8 { return Observable.empty() } let argMax = labelValues.index(where: { $0 == max })! let prediction = Touches_Label.all[argMax] if drawing.strokes.count < requiredNumberOfStrokes(label: prediction) { return Observable.empty() } return Observable.just(prediction) } let delayedRecognition = immediateRecognition .flatMapLatest { label -> Observable<Touches_Label> in if shouldDelayRecognition(of: label) { return Observable.just(label) .delay(0.5, scheduler: MainScheduler.instance) } return Observable.just(label) } delayedRecognition .subscribe(onNext: { label in notification.show(label: label) }) .disposed(by: disposeBag) let clearTimeout = Observable<Observable<Observable<()>>>.of( // Don't clear while the user is stroking. complexGestureInput .didStartStroke .map({ Observable.never() }), // After the user finishes a stroke, clear slowly (time out). complexGestureInput .currentDrawing .map({ _ in Observable.just(()) .delay(1, scheduler: MainScheduler.instance) }), // After the gesture is recognized, clear quickly unless the // user continues drawing. delayedRecognition .map({ _ in Observable.just(()) .delay(0.5, scheduler: MainScheduler.instance) }) ) .merge() .flatMapLatest({ $0 }) clearTimeout .subscribe(onNext: { [weak self] _ in self?.complexGestureInput.clear() }) .disposed(by: disposeBag) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } fileprivate class InstructionsView: UIView { private let label = UILabel() let button = UIButton() init() { super.init(frame: .zero) label.isUserInteractionEnabled = false label.font = UIFont.systemFont(ofSize: 18) label.textColor = UIColor(white: 0.2, alpha: 1) label.textAlignment = .center label.text = "Make a gesture below." addSubview(label) label.snp.makeConstraints { (make) in make.top.equalToSuperview() make.left.equalToSuperview() make.right.equalToSuperview() } button.titleLabel?.font = UIFont.systemFont(ofSize: 18, weight: UIFont.Weight.medium) button.titleLabel?.textAlignment = .center button.setTitleColor(UIColor("#37A0F4"), for: .normal) button.setTitle("See available gestures.", for: .normal) addSubview(button) button.snp.makeConstraints { (make) in make.top.equalTo(label.snp.bottom) make.left.equalToSuperview() make.right.equalToSuperview() make.bottom.equalToSuperview() } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
95333371717bff2ecfd9115074d989c7
34.849462
101
0.544841
false
false
false
false
wess/inquire
refs/heads/master
Sources/Toolbar.swift
mit
1
// // Toolbar.swift // Inquire // // Created by Wesley Cope on 2/15/16. // Copyright © 2016 Wess Cope. All rights reserved. // import Foundation import UIKit public typealias FieldBarButtonHandler = ((_ sender:AnyObject?) -> Void) open class FieldToolbarButtonItem : UIBarButtonItem { internal var handler:FieldBarButtonHandler? @objc internal func targetAction(_ sender:AnyObject?) { self.handler?(sender) } } public enum ToolbarButtonFlexType { case fixed case flexible } public func ToolbarButtonItem(_ flexType:ToolbarButtonFlexType) -> FieldToolbarButtonItem { switch flexType { case .fixed: return FieldToolbarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil) case .flexible: return FieldToolbarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) } } public func ToolbarButtonItem(_ image: UIImage?, style: UIBarButtonItem.Style, handler:FieldBarButtonHandler?) -> FieldToolbarButtonItem { return { $0.target = $0 $0.handler = handler return $0 }(FieldToolbarButtonItem(image: image, style: style, target: nil, action: #selector(FieldToolbarButtonItem.targetAction(_:)))) } public func ToolbarButtonItem(_ image: UIImage?, landscapeImagePhone: UIImage?, style: UIBarButtonItem.Style, handler:FieldBarButtonHandler?) -> FieldToolbarButtonItem { return { $0.target = $0 $0.handler = handler return $0 }(FieldToolbarButtonItem(image: image, landscapeImagePhone: landscapeImagePhone, style: style, target: nil, action: #selector(FieldToolbarButtonItem.targetAction(_:)))) } public func ToolbarButtonItem(_ title: String?, style: UIBarButtonItem.Style, handler:FieldBarButtonHandler?) -> FieldToolbarButtonItem { return { $0.target = $0 $0.handler = handler return $0 }(FieldToolbarButtonItem(title: title, style: style, target: nil, action: #selector(FieldToolbarButtonItem.targetAction(_:)))) } public func ToolbarButtonItem(barButtonSystemItem systemItem: UIBarButtonItem.SystemItem, handler:FieldBarButtonHandler?) -> FieldToolbarButtonItem { return { $0.target = $0 $0.handler = handler return $0 }(FieldToolbarButtonItem(barButtonSystemItem: systemItem, target: nil, action: #selector(FieldToolbarButtonItem.targetAction(_:)))) }
2f9e35cfb2c47f70e05db66941352904
28.095238
172
0.7009
false
false
false
false
24/ios-o2o-c
refs/heads/master
gxc/Order/SendOrderViewController.swift
mit
1
// // SendOrderViewController.swift // gxc // // Created by gx on 14/12/8. // Copyright (c) 2014年 zheng. All rights reserved. // import Foundation class SendOrderViewController: UIViewController ,UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate { var timerTxt = UITextField() var dataTxt = UITextField() var datePicker:UIPickerView = UIPickerView() var pickerView:UIPickerView = UIPickerView() var orderDetail = GXViewState.OrderDetail var messagetxt = UITextField() var shopOrder:GX_ShopNewOrder! var shopOrderTimes = Dictionary<String,([String])>() var elements:[String] = [String]() var loginBtn = UIButton() override func viewDidLoad() { super.viewDidLoad() self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "bar_back.png"), style: UIBarButtonItemStyle.Done, target: self, action: Selector("NavigationControllerBack")) /*navigation 不遮住View*/ self.automaticallyAdjustsScrollViewInsets = false self.edgesForExtendedLayout = UIRectEdge() /*self view*/ self.view.backgroundColor = UIColor.whiteColor() //superview let superview: UIView = self.view /* navigation titleView */ self.navigationController?.navigationBar.barTintColor = UIColor(fromHexString: "#008FD7") var navigationBar = self.navigationController?.navigationBar navigationBar?.tintColor = UIColor.whiteColor() self.navigationItem.title = "预约送衣" let iconWidth = 30 let iconHeight = 30 let txtHeight = 40 var elements:[String] = [String]() var shopId = orderDetail.shopDetail?.ShopMini?.ShopId GxApiCall().ShopOrder(GXViewState.userInfo.Token!, shopId: String(shopId!)) NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("Set_View_Value:"), name: GXNotifaction_Shop_NewOrder, object: nil) MBProgressHUD.showHUDAddedTo(self.view, animated: true) //日期 var dataView = UIView() self.view.addSubview(dataView) dataView.snp_makeConstraints { make in make.left.equalTo(CGPointZero) make.top.equalTo(superview).offset(20) make.width.equalTo(superview) make.height.equalTo(45) } var dataImageView = UIImageView(image: UIImage(named: "order_date.png")) dataView.addSubview(dataImageView) dataView.addSubview(dataTxt) dataImageView.snp_makeConstraints { make in make.left.equalTo(CGPointZero).offset(3) make.centerY.equalTo(dataView.snp_centerY) make.width.equalTo(iconWidth) make.height.equalTo(iconHeight) } dataTxt.snp_makeConstraints { make in make.left.equalTo(dataImageView.snp_right).offset(5) make.centerY.equalTo(dataView.snp_centerY) make.right.equalTo(dataView.snp_right).offset(-5) make.height.equalTo(txtHeight) } dataTxt.placeholder = "设置日期" dataTxt.adjustsFontSizeToFitWidth = true dataTxt.clearButtonMode = UITextFieldViewMode.WhileEditing dataTxt.borderStyle = UITextBorderStyle.RoundedRect dataTxt.keyboardAppearance = UIKeyboardAppearance.Dark dataTxt.delegate = self //timer var timeView = UIView() self.view.addSubview(timeView) timeView.snp_makeConstraints { make in make.left.equalTo(CGPointZero) make.top.equalTo(dataView.snp_bottom) make.width.equalTo(superview) make.height.equalTo(45) } var timerImageView = UIImageView(image: UIImage(named: "order_time.png")) timeView.addSubview(timerImageView) timeView.addSubview(timerTxt) timerImageView.snp_makeConstraints { make in make.left.equalTo(CGPointZero).offset(3) make.centerY.equalTo(timeView.snp_centerY) make.width.equalTo(iconWidth) make.height.equalTo(iconHeight) } timerTxt.delegate = self timerTxt.snp_makeConstraints { make in make.left.equalTo(timerImageView.snp_right).offset(5) make.centerY.equalTo(timeView.snp_centerY) make.right.equalTo(timeView.snp_right).offset(-5) make.height.equalTo(txtHeight) } timerTxt.placeholder = "设置时间" timerTxt.adjustsFontSizeToFitWidth = true timerTxt.clearButtonMode = UITextFieldViewMode.WhileEditing timerTxt.borderStyle = UITextBorderStyle.RoundedRect timerTxt.keyboardAppearance = UIKeyboardAppearance.Dark //message var messageView = UIView() self.view.addSubview(messageView) messageView.snp_makeConstraints { make in make.left.equalTo(CGPointZero) make.top.equalTo(timeView.snp_bottom) make.width.equalTo(superview) make.height.equalTo(45) } var messageImageView = UIImageView(image: UIImage(named: "order_message.png")) messageView.addSubview(messageImageView) messageView.addSubview(messagetxt) messagetxt.placeholder = "给饲料厂留言" messagetxt.adjustsFontSizeToFitWidth = true messagetxt.clearButtonMode = UITextFieldViewMode.WhileEditing messagetxt.borderStyle = UITextBorderStyle.RoundedRect messagetxt.keyboardAppearance = UIKeyboardAppearance.Dark messagetxt.delegate = self messageImageView.snp_makeConstraints { make in make.left.equalTo(CGPointZero).offset(5) make.centerY.equalTo(messageView.snp_centerY) make.width.equalTo(iconWidth) make.height.equalTo(iconHeight) } messagetxt.snp_makeConstraints { make in make.left.equalTo(messageImageView.snp_right).offset(5) make.centerY.equalTo(messageView.snp_centerY) make.right.equalTo(messageView.snp_right).offset(-5) make.height.equalTo(txtHeight) } dataTxt.inputView = datePicker datePicker.tag = 12 pickerView.tag = 23 timerTxt.inputView = pickerView pickerView.delegate = self // pickerView.dataSource = self datePicker.delegate = self // datePicker.dataSource = self loginBtn.backgroundColor = UIColor(fromHexString: "#E61D4C") loginBtn.addTarget(self, action: Selector("SetSendOrder"), forControlEvents: .TouchUpInside) loginBtn.setTitle("立即预约", forState: UIControlState.Normal) self.view.addSubview(loginBtn) loginBtn.snp_makeConstraints { make in make.top.equalTo(self.messagetxt.snp_bottom).offset(15) make.left.equalTo(CGPointZero).offset(5) make.right.equalTo(superview).offset(-5) // make.width.equalTo(superview) make.height.equalTo(40) } } func Set_View_Value(notif :NSNotification) { shopOrder = notif.userInfo?["GXNotifaction_Shop_NewOrder"] as GX_ShopNewOrder var messagetxt = "" //拼假时间 for time in shopOrder.shopOrderdata!.orderTimes! { var tip = "\(time.Tip!)" var k = time.Date! var newArray = [String]() if let kd = shopOrderTimes[k] { newArray = kd newArray.append(tip) }else { newArray = [tip] } shopOrderTimes.updateValue(newArray, forKey: k) } elements = [String](shopOrderTimes.keys) elements.sort { $0 < $1 } var key = elements[0] dataTxt.text = key timerTxt.text = shopOrderTimes[key]![0] MBProgressHUD.hideAllHUDsForView(self.view, animated: true) } func SetSendOrder() { MBProgressHUD.showHUDAddedTo(self.view, animated: true) NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("OrderSendSuccess:"), name: GXNotifaction_User_Order_Send, object: nil) //无地址 var orderId = NSString(format: "%.0f", orderDetail.shopDetail!.OrderId!) var content = messagetxt.text! var token = GXViewState.userInfo.Token! var getTime = dataTxt.text + " " + timerTxt.text GxApiCall().OrderSend(orderId, remark: content, token: token, sendTime: getTime) } func OrderSendSuccess(notif :NSNotification) { MBProgressHUD.hideHUDForView(self.view, animated: true) SweetAlert().showAlert("", subTitle: "预约送衣成功!", style: AlertStyle.Success) self.navigationController?.popViewControllerAnimated(true) } func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 1 } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { if(pickerView.tag == 12) { return elements.count } else { var key = dataTxt.text! var c = shopOrderTimes[key]!.count println(c) return c } } func pickerView(pickerView: UIPickerView!, titleForRow row: Int, forComponent component: Int) -> String { if(pickerView.tag == 12) { return elements[row] } else { var key = dataTxt.text! var lx = shopOrderTimes[key]![row] println(lx) return lx } } func pickerView(pickerView: UIPickerView!, didSelectRow row: Int, inComponent component: Int) { if(pickerView.tag == 12) { dataTxt.text = elements[row] } else { var key = dataTxt.text! timerTxt.text = shopOrderTimes[key]![row] } } func NavigationControllerBack() { self.navigationController?.popViewControllerAnimated(true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
f22e517fed13583ed3d2f5c5093ed924
31.767584
204
0.59832
false
false
false
false
AlwaysRightInstitute/SwiftyHTTP
refs/heads/develop
SwiftSockets/Socket.swift
mit
1
// // Socket.swift // SwiftSockets // // Created by Helge Heß on 6/9/14. // Copyright (c) 2014-2015 Always Right Institute. All rights reserved. // #if os(Linux) import Glibc #else import Darwin #endif import Dispatch /** * Simple Socket classes for Swift. * * PassiveSockets are 'listening' sockets, ActiveSockets are open connections. */ public class Socket<T: SocketAddress> { public var fd : FileDescriptor = nil public var boundAddress : T? = nil public var isValid : Bool { return fd.isValid } public var isBound : Bool { return boundAddress != nil } var closeCB : ((FileDescriptor) -> Void)? = nil var closedFD : FileDescriptor? = nil // for delayed callback /* initializer / deinitializer */ public init(fd: FileDescriptor) { self.fd = fd } deinit { close() // TBD: is this OK/safe? } public convenience init?(type: Int32 = sys_SOCK_STREAM) { let lfd = socket(T.domain, type, 0) guard lfd != -1 else { return nil } self.init(fd: FileDescriptor(lfd)) } /* explicitly close the socket */ let debugClose = false public func close() { if fd.isValid { closedFD = fd if debugClose { print("Closing socket \(closedFD) for good ...") } fd.close() fd = nil if let cb = closeCB { // can be used to unregister socket etc when the socket is really closed if debugClose { print(" let closeCB \(closedFD) know ...") } cb(closedFD!) closeCB = nil // break potential cycles } if debugClose { print("done closing \(closedFD)") } } else if debugClose { print("socket \(closedFD) already closed.") } boundAddress = nil } public func onClose(cb: ((FileDescriptor) -> Void)?) -> Self { if let fd = closedFD { // socket got closed before event-handler attached if let lcb = cb { lcb(fd) } else { closeCB = nil } } else { closeCB = cb } return self } /* bind the socket. */ public func bind(address: T) -> Bool { guard fd.isValid else { return false } guard !isBound else { print("Socket is already bound!") return false } // Note: must be 'var' for ptr stuff, can't use let var addr = address let rc = withUnsafePointer(&addr) { ptr -> Int32 in let bptr = UnsafePointer<sockaddr>(ptr) // cast return sysBind(fd.fd, bptr, socklen_t(addr.len)) } if rc == 0 { // Generics TBD: cannot check for isWildcardPort, always grab the name boundAddress = getsockname() /* if it was a wildcard port bind, get the address */ // boundAddress = addr.isWildcardPort ? getsockname() : addr } return rc == 0 ? true : false } public func getsockname() -> T? { return _getaname(sysGetsockname) } public func getpeername() -> T? { return _getaname(sysGetpeername) } typealias GetNameFN = ( Int32, UnsafeMutablePointer<sockaddr>, UnsafeMutablePointer<socklen_t>) -> Int32 func _getaname(nfn: GetNameFN) -> T? { guard fd.isValid else { return nil } // FIXME: tried to encapsulate this in a sockaddrbuf which does all the // ptr handling, but it ain't work (autoreleasepool issue?) var baddr = T() var baddrlen = socklen_t(baddr.len) // Note: we are not interested in the length here, would be relevant // for AF_UNIX sockets let rc = withUnsafeMutablePointer(&baddr) { ptr -> Int32 in let bptr = UnsafeMutablePointer<sockaddr>(ptr) // cast return nfn(fd.fd, bptr, &baddrlen) } guard rc == 0 else { print("Could not get sockname? \(rc)") return nil } // print("PORT: \(baddr.sin_port)") return baddr } /* description */ // must live in the main-class as 'declarations in extensions cannot be // overridden yet' (Same in Swift 2.0) func descriptionAttributes() -> String { var s = fd.isValid ? " fd=\(fd.fd)" : (closedFD != nil ? " closed[\(closedFD)]" :" not-open") if boundAddress != nil { s += " \(boundAddress!)" } return s } } extension Socket { // Socket Flags public var flags : Int32? { get { return fd.flags } set { fd.flags = newValue! } } public var isNonBlocking : Bool { get { return fd.isNonBlocking } set { fd.isNonBlocking = newValue } } } extension Socket { // Socket Options public var reuseAddress: Bool { get { return getSocketOption(SO_REUSEADDR) } set { setSocketOption(SO_REUSEADDR, value: newValue) } } #if os(Linux) // No: SO_NOSIGPIPE on Linux, use MSG_NOSIGNAL in send() public var isSigPipeDisabled: Bool { get { return false } set { /* DANGER, DANGER, ALERT */ } } #else public var isSigPipeDisabled: Bool { get { return getSocketOption(SO_NOSIGPIPE) } set { setSocketOption(SO_NOSIGPIPE, value: newValue) } } #endif public var keepAlive: Bool { get { return getSocketOption(SO_KEEPALIVE) } set { setSocketOption(SO_KEEPALIVE, value: newValue) } } public var dontRoute: Bool { get { return getSocketOption(SO_DONTROUTE) } set { setSocketOption(SO_DONTROUTE, value: newValue) } } public var socketDebug: Bool { get { return getSocketOption(SO_DEBUG) } set { setSocketOption(SO_DEBUG, value: newValue) } } public var sendBufferSize: Int32 { get { return getSocketOption(SO_SNDBUF) ?? -42 } set { setSocketOption(SO_SNDBUF, value: newValue) } } public var receiveBufferSize: Int32 { get { return getSocketOption(SO_RCVBUF) ?? -42 } set { setSocketOption(SO_RCVBUF, value: newValue) } } public var socketError: Int32 { return getSocketOption(SO_ERROR) ?? -42 } /* socket options (TBD: would we use subscripts for such?) */ public func setSocketOption(option: Int32, value: Int32) -> Bool { if !isValid { return false } var buf = value let rc = setsockopt(fd.fd, SOL_SOCKET, option, &buf, socklen_t(sizeof(Int32))) if rc != 0 { // ps: Great Error Handling print("Could not set option \(option) on socket \(self)") } return rc == 0 } // TBD: Can't overload optionals in a useful way? // func getSocketOption(option: Int32) -> Int32 public func getSocketOption(option: Int32) -> Int32? { if !isValid { return nil } var buf = Int32(0) var buflen = socklen_t(sizeof(Int32)) let rc = getsockopt(fd.fd, SOL_SOCKET, option, &buf, &buflen) if rc != 0 { // ps: Great Error Handling print("Could not get option \(option) from socket \(self)") return nil } return buf } public func setSocketOption(option: Int32, value: Bool) -> Bool { return setSocketOption(option, value: value ? 1 : 0) } public func getSocketOption(option: Int32) -> Bool { let v: Int32? = getSocketOption(option) return v != nil ? (v! == 0 ? false : true) : false } } extension Socket { // poll() public var isDataAvailable: Bool { return fd.isDataAvailable } public func pollFlag(flag: Int32) -> Bool { return fd.pollFlag(flag) } public func poll(events: Int32, timeout: UInt? = 0) -> Int32? { return fd.poll(events, timeout: timeout) } } extension Socket: CustomStringConvertible { public var description : String { return "<Socket:" + descriptionAttributes() + ">" } } extension Socket: BooleanType { // TBD: Swift doesn't want us to do this public var boolValue : Bool { return isValid } }
42205c35d3e6dffcc61b288c92f30049
24.304918
80
0.608966
false
false
false
false
xhjkl/rayban
refs/heads/master
Rayban/GLESRenderer.swift
mit
1
// // OpenGL renderer // import Cocoa import OpenGL.GL3 fileprivate let passThroughVertSrc = "#version 100\n" + "attribute vec2 attr;" + "varying vec2 position;" + "void main() {" + "gl_Position = vec4((position = attr), 0.0, 1.0);" + "}" fileprivate let passThroughFragSrc = "#version 100\n" + "uniform sampler2D texture;" + "uniform vec2 density;" + "void main() {" + "gl_FragColor = texture2D(texture, gl_FragCoord.xy * density);" + "}" fileprivate let unitQuadVertices = Array<GLfloat>([ GLfloat(+1.0), GLfloat(-1.0), GLfloat(-1.0), GLfloat(-1.0), GLfloat(+1.0), GLfloat(+1.0), GLfloat(-1.0), GLfloat(+1.0), ]) // OpenGL ES 2 // class GLESRenderer: Renderer { private var progId = GLuint(0) private var vertexArrayId = GLuint(0) private var unitQuadBufferId = GLuint(0) private var timeUniform: GLint? = nil private var densityUniform: GLint? = nil private var resolutionUniform: GLint? = nil var logListener: RenderLogListener? = nil func prepare() { glClearColor(1.0, 0.33, 0.77, 1.0) glGenVertexArrays(1, &vertexArrayId) glBindVertexArray(vertexArrayId) let size = unitQuadVertices.count * MemoryLayout<GLfloat>.size glGenBuffers(1, &unitQuadBufferId) glBindBuffer(GLenum(GL_ARRAY_BUFFER), unitQuadBufferId) unitQuadVertices.withUnsafeBufferPointer { bytes in glBufferData(GLenum(GL_ARRAY_BUFFER), size, bytes.baseAddress, GLenum(GL_STATIC_DRAW)) } glVertexAttribPointer(0, 2, GLenum(GL_FLOAT), GLboolean(GL_FALSE), GLsizei(0), UnsafeRawPointer(bitPattern: 0)) glEnableVertexAttribArray(0) } func setSource(_ source: String) { if glIsProgram(progId) == GLboolean(GL_TRUE) { glDeleteProgram(progId) } let newProgId = makeShader(vertSource: passThroughVertSrc, fragSource: source) guard newProgId != nil else { return } progId = newProgId! glUseProgram(progId) } func yieldFrame(size: (width: Float64, height: Float64), time: Float64) { glUniform1f(timeUniform ?? -1, GLfloat(time)) glUniform2f(densityUniform ?? -1, GLfloat(1.0 / size.width), GLfloat(1.0 / size.height)) glUniform2f(resolutionUniform ?? -1, GLfloat(size.width), GLfloat(size.height)) let _ = glGetError() glClear(GLbitfield(GL_COLOR_BUFFER_BIT)) glViewport(0, 0, GLsizei(size.width), GLsizei(size.height)) glDrawArrays(GLenum(GL_TRIANGLE_STRIP), 0, 4) } private func retrieveCompilationLog(id: GLuint) -> String { let oughtToBeEnough = 1024 var storage = ContiguousArray<CChar>(repeating: 0, count: oughtToBeEnough) var log: String! = nil storage.withUnsafeMutableBufferPointer { mutableBytes in glGetShaderInfoLog(id, GLsizei(oughtToBeEnough), nil, mutableBytes.baseAddress!) log = String(cString: mutableBytes.baseAddress!) } return log } private func retrieveLinkageLog(id: GLuint) -> String { let oughtToBeEnough = 1024 var storage = ContiguousArray<CChar>(repeating: 0, count: oughtToBeEnough) var log: String! = nil storage.withUnsafeMutableBufferPointer { mutableBytes in glGetProgramInfoLog(id, GLsizei(oughtToBeEnough), nil, mutableBytes.baseAddress!) log = String(cString: mutableBytes.baseAddress!) } return log } private func makeShader(vertSource: String, fragSource: String) -> GLuint? { var status: GLint = 0 let progId = glCreateProgram() let vertId = glCreateShader(GLenum(GL_VERTEX_SHADER)) defer { glDeleteShader(vertId) } vertSource.withCString { bytes in glShaderSource(vertId, 1, [bytes], nil) } glCompileShader(vertId) glGetShaderiv(vertId, GLenum(GL_COMPILE_STATUS), &status) guard status == GL_TRUE else { let log = retrieveCompilationLog(id: vertId) emitReports(per: log) return nil } let fragId = glCreateShader(GLenum(GL_FRAGMENT_SHADER)) defer { glDeleteShader(fragId) } fragSource.withCString { bytes in glShaderSource(fragId, 1, [bytes], nil) } glCompileShader(fragId) glGetShaderiv(fragId, GLenum(GL_COMPILE_STATUS), &status) guard status == GL_TRUE else { let log = retrieveCompilationLog(id: fragId) emitReports(per: log) return nil } glBindAttribLocation(progId, 0, "attr") glAttachShader(progId, vertId) glAttachShader(progId, fragId) glLinkProgram(progId) defer { glDetachShader(progId, vertId) glDetachShader(progId, fragId) } glGetProgramiv(progId, GLenum(GL_LINK_STATUS), &status) guard status == GL_TRUE else { let log = retrieveLinkageLog(id: progId) emitReports(per: log) return nil } timeUniform = glGetUniformLocation(progId, "time") densityUniform = glGetUniformLocation(progId, "density") resolutionUniform = glGetUniformLocation(progId, "resolution") return progId } private func emitReports(per log: String) { guard logListener != nil else { return } let reports = parseLog(log) for report in reports { logListener!.onReport(report) } } }
00eae86fb614296484ced617d971229f
28.074286
115
0.684945
false
false
false
false
a497500306/MLSideslipView
refs/heads/master
MLSideslipViewDome/MLSideslipViewDome/ViewController.swift
apache-2.0
1
// // ViewController.swift // MLSideslipViewDome // // Created by 洛耳 on 16/1/5. // Copyright © 2016年 workorz. All rights reserved. import UIKit //第一步继承--MLViewController class ViewController: MLViewController , UITableViewDelegate , UITableViewDataSource { /// 侧滑栏图片数组 var images : NSArray! /// 侧滑栏文字数组 var texts : NSArray! override func viewDidLoad() { super.viewDidLoad() //设置左上角的放回按钮 let righBtn = UIButton(frame: CGRectMake(0, 0, 24, 24)) righBtn.setBackgroundImage(UIImage(named: "椭圆-19"), forState: UIControlState.Normal) righBtn.setBackgroundImage(UIImage(named: "椭圆-19" ), forState: UIControlState.Highlighted) righBtn.addTarget(self, action: "dianjiNavZuoshangjiao", forControlEvents: UIControlEvents.TouchUpInside) let rightBarItem = UIBarButtonItem(customView: righBtn) self.navigationItem.leftBarButtonItem = rightBarItem //第二步创建侧滑栏中需要添加的控件 添加控件() } func 添加控件(){ self.images = ["二维码","手势密码","指纹图标","我的收藏","设置"] self.texts = ["我的二维码","手势解锁","指纹解锁","我的收藏","设置"] let imageView = UIImageView(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width * 2 / 3 , UIScreen.mainScreen().bounds.height)) imageView.userInteractionEnabled = true imageView.image = UIImage(named: "我的—背景图") let table = UITableView.init(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width * 2 / 3 , UIScreen.mainScreen().bounds.height)) table.backgroundColor = UIColor.clearColor() table.tag = 1000 table.separatorStyle = UITableViewCellSeparatorStyle.None //1添加头部控件 let touView : UIView = UIView() //1.1头像 let btn : UIButton = UIButton() let w : CGFloat = 75 btn.frame = CGRectMake(((UIScreen.mainScreen().bounds.width * 2 / 3)-w)/2, w/2, w, w) //圆角 btn.layer.cornerRadius = 10 btn.layer.masksToBounds = true btn.setImage(UIImage(named: "IMG_1251.JPG"), forState: UIControlState.Normal) touView.addSubview(btn) //1.2名字 let nameText : UILabel = UILabel() let WH : CGSize = MLGongju().计算文字宽高("2131231", sizeMake: CGSizeMake(10000, 10000), font: UIFont.systemFontOfSize(15)) nameText.frame = CGRectMake(0, btn.frame.height + btn.frame.origin.y+10, table.frame.width, WH.height) nameText.font = UIFont.systemFontOfSize(15) nameText.textAlignment = NSTextAlignment.Center nameText.text = "毛哥哥是神" touView.addSubview(nameText) //1.3线 let xian : UIView = UIView() xian.frame = CGRectMake(25, nameText.frame.height + nameText.frame.origin.y + 10, table.frame.width - 50, 0.5) xian.backgroundColor = UIColor(red: 149/255.0, green: 149/255.0, blue: 149/255.0, alpha: 1) touView.addSubview(xian) touView.frame = CGRectMake(0, 0, table.frame.width, xian.frame.origin.y + xian.frame.height + 10) table.tableHeaderView = touView //设置代理数据源 table.dataSource = self table.delegate = self super.sideslipView.contentView.addSubview(imageView) super.sideslipView.contentView.addSubview(table) }//MARK: - tableView代理和数据源方法 //多少行 func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.images.count } //点击每行做什么 func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { //取消选择 tableView.deselectRowAtIndexPath(indexPath, animated: true) //关闭侧滑栏 super.down() print("在这里做跳转") } //MARK: - tableView代理数据源 //每行cell张什么样子 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{ let ID = "cell" var cell : UITableViewCell! = tableView.dequeueReusableCellWithIdentifier(ID) if cell == nil { cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: ID) } cell.backgroundColor = UIColor.clearColor() cell.textLabel?.text = self.texts[indexPath.row] as? String cell.imageView?.image = UIImage(named: (self.images[indexPath.row] as? String)!) return cell } //cell的高度 func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 55 } //MARK: - 点击左上角按钮 func dianjiNavZuoshangjiao(){ super.show() } }
30629a059b2b2342aebb7a06b3c02b87
41.396226
144
0.654651
false
false
false
false
gyro-n/PaymentsIos
refs/heads/master
GyronPayments/Classes/Models/Webhook.swift
mit
1
// // Webhook.swift // GyronPayments // // Created by Ye David on 11/1/16. // Copyright © 2016 gyron. All rights reserved. // import Foundation /** The Webhook class stores information about webhooks. A webhook is a URL that can be used as a callback to receive information when an event is triggered in the Gopay system. Payloads for a webhook are delivered via a POST request. The body of the request will contain a JSON object with pertinent data. Webhooks can be created via the merchant console. The following table displays all events you can register a webhook, their payload, and a short description of the triggering event. */ open class Webhook: BaseModel { /** The unique identifier for the webhook. */ public var id: String /** The unique identifier for the merchant. */ public var merchantId: String /** The unique identifier for the store. */ public var storeId: String /** The triggers that fire the webhook request. */ public var triggers: [String] /** The url of the webhook. */ public var url: String /** Whether or not the webhook is active. */ public var active: Bool /** The date the webhook was created. */ public var createdOn: String /** The date the webhook was updated. */ public var updatedOn: String /** Initializes the Webhook object */ override init() { id = "" merchantId = "" storeId = "" triggers = [] url = "" active = false createdOn = "" updatedOn = "" } /** Maps the values from a hash map object into the Webhook. */ override open func mapFromObject(map: ResponseData) { id = map["id"] as? String ?? "" merchantId = map["merchant_id"] as? String ?? "" storeId = map["store_id"] as? String ?? "" triggers = map["triggers"] as? [String] ?? [] url = map["url"] as? String ?? "" active = map["active"] as? Bool ?? false createdOn = map["created_on"] as? String ?? "" updatedOn = map["updated_on"] as? String ?? "" } }
35f6648b0975de3b8c0deafed7d43f14
26.746835
300
0.597172
false
false
false
false
joerocca/GitHawk
refs/heads/master
Classes/PullReqeustReviews/PullRequestReviewCommentsViewController.swift
mit
1
// // PullRequestReviewCommentsViewController.swift // Freetime // // Created by Ryan Nystrom on 11/4/17. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import UIKit import IGListKit final class PullRequestReviewCommentsViewController: BaseListViewController<NSNumber>, BaseListViewControllerDataSource { private let model: IssueDetailsModel private let client: GithubClient private var models = [ListDiffable]() init(model: IssueDetailsModel, client: GithubClient) { self.model = model self.client = client super.init( emptyErrorMessage: NSLocalizedString("Error loading review comments.", comment: ""), dataSource: self ) title = NSLocalizedString("Review Comments", comment: "") } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: Overrides override func fetch(page: NSNumber?) { client.fetchPRComments( owner: model.owner, repo: model.repo, number: model.number, width: view.bounds.width ) { [weak self] (result) in switch result { case .error: ToastManager.showGenericError() case .success(let models, let page): self?.models = models self?.update(page: page as NSNumber?, animated: trueUnlessReduceMotionEnabled) } } } // MARK: BaseListViewControllerDataSource func headModels(listAdapter: ListAdapter) -> [ListDiffable] { return [] } func models(listAdapter: ListAdapter) -> [ListDiffable] { return models } func sectionController(model: Any, listAdapter: ListAdapter) -> ListSectionController { switch model { case is NSAttributedStringSizing: return IssueTitleSectionController() case is IssueCommentModel: return IssueCommentSectionController(model: self.model, client: client) case is IssueDiffHunkModel: return IssueDiffHunkSectionController() default: fatalError("Unhandled object: \(model)") } } func emptySectionController(listAdapter: ListAdapter) -> ListSectionController { return ListSingleSectionController(cellClass: LabelCell.self, configureBlock: { (_, cell: UICollectionViewCell) in guard let cell = cell as? LabelCell else { return } cell.label.text = NSLocalizedString("No review comments found.", comment: "") }, sizeBlock: { [weak self] (_, context: ListCollectionContext?) -> CGSize in guard let context = context, let strongSelf = self else { return .zero } return CGSize( width: context.containerSize.width, height: context.containerSize.height - strongSelf.topLayoutGuide.length - strongSelf.bottomLayoutGuide.length ) }) } // MARK: IssueCommentSectionControllerDelegate }
64cba61d371971fc75f7cbf97921d783
33.298851
125
0.650469
false
false
false
false