repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
202 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
icylydia/PlayWithLeetCode
22. Generate Parentheses/solution.swift
1
663
class Solution { var ans = [String]() var total = 0 func generateParenthesis(n: Int) -> [String] { total = n helper(n, 0, "") return ans } private func helper(left: Int, _ opened: Int, _ status: String) { if left == 0 { var str = status for _ in 0..<opened { str += ")" } ans.append(str) return } if opened == 0 { helper(left - 1, 1, status + "(") return } else { helper(left, opened - 1, status + ")") helper(left - 1, opened + 1, status + "(") } } }
mit
73371a2e45c1e11ad3a077f0bff19b04
24.538462
69
0.408748
4.196203
false
false
false
false
RubyNative/RubyKit
String.swift
2
4712
// // String.swift // SwiftRuby // // Created by John Holdsworth on 26/09/2015. // Copyright © 2015 John Holdsworth. All rights reserved. // // $Id: //depot/SwiftRuby/String.swift#13 $ // // Repo: https://github.com/RubyNative/SwiftRuby // // See: http://ruby-doc.org/core-2.2.3/String.html // import Foundation public var STRING_ENCODING = String.Encoding.utf8 public let FALLBACK_INPUT_ENCODING = String.Encoding.isoLatin1 public let FALLBACK_OUTPUT_ENCODING = String.Encoding.utf8 public enum StringIndexDisposition { case warnAndFail, truncate } public var STRING_INDEX_DISPOSITION: StringIndexDisposition = .warnAndFail public protocol string_like: array_like { var to_s: String { get } } public protocol char_like { var to_c: [CChar] { get } } extension String: string_like, array_like, data_like, char_like { public subscript (i: Int) -> String { return slice(i) } public subscript (start: Int, len: Int) -> String { return slice(start, len: len) } public subscript (r: Range<Int>) -> String { return String(self[index(startIndex, offsetBy: r.lowerBound) ..< index(startIndex, offsetBy: r.upperBound)]) } public var to_s: String { return self } public var to_a: [String] { // ??? self.characters.count return [self] } public var to_c: [CChar] { if let chars = cString(using: STRING_ENCODING) { return chars } SRLog("String.to_c, unable to encode string for output") return U(cString(using: FALLBACK_OUTPUT_ENCODING)) } public var to_d: Data { return Data(array: self.to_c) } public var to_i: Int { if let val = Int(self) { return val } let dummy = -99999999 SRLog("Unable to convert \(self) to Int. Returning \(dummy)") return dummy } public var to_f: Double { if let val = Double(self) { return val } let dummy = -99999999.0 SRLog("Unable to convert \(self) to Doubleb. Returning \(dummy)") return dummy } public func characterAtIndex(_ i: Int) -> Int { if let char = self[i].unicodeScalars.first { return Int(char.value) } SRLog("No character available in string '\(self)' returning nul char") return 0 } public var downcase: String { return self.lowercased() } public func each_byte(_ block: (UInt8) -> ()) { for char in utf8 { block(char) } } public func each_char(_ block: (UInt16) -> ()) { for char in utf16 { block(char) } } public func each_codepoint(_ block: (String) -> ()) { for char in self { block(String(char )) } } public func each_line(_ block: (String) -> ()) { StringIO(self).each_line(LINE_SEPARATOR, nil, block) } public var length: Int { return count } public var ord: Int { return characterAtIndex(0) } public func slice(_ start: Int, len: Int = 1) -> String { var vstart = start, vlen = len let length = self.length if start < 0 { vstart = length + start } if vstart < 0 { SRLog("String.str(\(start), \(len)) start before front of string '\(self)', length \(length)") if STRING_INDEX_DISPOSITION == .truncate { vstart = 0 } } else if vstart > length { SRLog("String.str(\(start), \(len)) start after end of string '\(self)', length \(length)") if STRING_INDEX_DISPOSITION == .truncate { vstart = length } } if len < 0 { vlen = length + len - vstart } else if len == NSNotFound { vlen = length - vstart } if vlen < 0 { SRLog("String.str(\(start), \(len)) start + len before start of substring '\(self)', length \(length)") if STRING_INDEX_DISPOSITION == .truncate { vlen = 0 } } else if vstart + vlen > length { SRLog("String.str(\(start), \(len)) start + len after end of string '\(self)', length \(length)") if STRING_INDEX_DISPOSITION == .truncate { vlen = length - vstart } } return self[vstart..<vstart+vlen] } public func split(_ delimiter: String) -> [String] { return components(separatedBy: delimiter) } public var upcase: String { return self.uppercased() } }
mit
2cf435bdc725ffe007742df6d75e0eba
24.192513
115
0.545532
3.9555
false
false
false
false
carabina/AlecrimAsyncKit
Source/AlecrimAsyncKit/Convenience/Observers/NetworkActivityTaskObserver.swift
1
2007
// // NetworkActivityTaskObserver.swift // AlecrimAsyncKit // // Created by Vanderlei Martinelli on 2015-08-15. // Copyright (c) 2015 Alecrim. All rights reserved. // import Foundation #if os(iOS) private var _activitySpinLock = OS_SPINLOCK_INIT private var _activity: Int = 0 public final class NetworkActivityTaskObserver: TaskObserver { private let delay: NSTimeInterval = 0.5 private let application: UIApplication private var activity: Int { get { withUnsafeMutablePointer(&_activitySpinLock, OSSpinLockLock) let v = _activity withUnsafeMutablePointer(&_activitySpinLock, OSSpinLockUnlock) return v } set { withUnsafeMutablePointer(&_activitySpinLock, OSSpinLockLock) _activity = newValue withUnsafeMutablePointer(&_activitySpinLock, OSSpinLockUnlock) if self.activity > 0 { let when = dispatch_time(DISPATCH_TIME_NOW, Int64(self.delay * Double(NSEC_PER_SEC))) dispatch_after(when, dispatch_get_main_queue()) { if self.activity > 0 { self.application.networkActivityIndicatorVisible = true } } } else { let when = dispatch_time(DISPATCH_TIME_NOW, Int64((self.delay / 2.0) * Double(NSEC_PER_SEC))) dispatch_after(when, dispatch_get_main_queue()) { if self.activity == 0 { self.application.networkActivityIndicatorVisible = false } } } } } public init(application: UIApplication) { self.application = application super.init() self.didStart { [unowned self] _ in self.activity++ } self.didFinish { [unowned self] _ in self.activity-- } } } #endif
mit
4011f91ae61f2c6ca7548e63d25715d1
28.086957
109
0.554559
5.081013
false
false
false
false
keyfun/synology_ds_get
DSGetLite/DSGetLite/Task.swift
1
874
// // Task.swift // DSGetLite // // Created by Hui Key on 20/10/2016. // Copyright © 2016 Key Hui. All rights reserved. // import Foundation class Task { var id: String var size: Int64 var status: String var title: String var type: String var username: String init(json: [String: Any]) { id = json["id"] as! String size = (json["size"] as! NSNumber).int64Value status = json["status"] as! String title = json["title"] as! String type = json["type"] as! String username = json["username"] as! String } func toString() -> String { var str: String = "id = \(id), " str += "size = \(size), " str += "status = \(status), " str += "title = \(title), " str += "type = \(type), " str += "username = \(username)" return str } }
mit
aedc461eaf3017e7a31b7aeb2f6d79f2
21.384615
53
0.523482
3.607438
false
false
false
false
acchou/RxGmail
Example/RxGmail/ThreadsViewModel.swift
1
1879
import RxSwift import RxGmail struct Thread { var identifier: String var sender: String var subject: String var date: String } enum ThreadsQueryMode { case All case Unread } struct ThreadsViewModelInputs { var selectedLabel: Label var mode: ThreadsQueryMode } struct ThreadsViewModelOutputs { var threadHeaders: Observable<[Thread]> } typealias ThreadsViewModelType = (ThreadsViewModelInputs) -> ThreadsViewModelOutputs func ThreadsViewModel(rxGmail: RxGmail) -> ThreadsViewModelType { return { inputs in let query = RxGmail.ThreadListQuery.query(withUserId: "me") query.labelIds = [inputs.selectedLabel.identifier] if case .Unread = inputs.mode { query.q = "is:unread" } // Do the lazy thing and load all message headers every time this view appears. A more production ready implementation would use caching. let threadHeaders = rxGmail .listThreads(query: query) // RxGmail.ThreadListResponse .flatMap { rxGmail.fetchDetails($0.threads ?? [], detailType: .metadata) } // [RxGmail.Thread] (with all headers) .flatMap { Observable.from($0) } // RxGmail.Thread .map { thread -> Thread in let headers = thread.messages?.first?.parseHeaders() ?? [:] return Thread( identifier: thread.identifier ?? "", sender: headers["From"] ?? "", subject: headers["Subject"] ?? "", date: headers["Date"] ?? "" ) } // MessageHeader .toArray() .shareReplay(1) return ThreadsViewModelOutputs(threadHeaders: threadHeaders) } }
mit
0f1eda493d9967a38dd4608d5b214144
32.553571
145
0.568387
5.147945
false
false
false
false
r4phab/ECAB
ECAB/SpeechRecognitionHelper.swift
1
5847
// // SpeechRecognitionHelper.swift // ECAB // // Created by Raphaël Bertin on 15/07/2016. // Copyright © 2016 Oliver Braddick and Jan Atkinson. All rights reserved. // import Foundation class SpeechRecognitionHelper : NSObject, OEEventsObserverDelegate{ var openEarsEventsObserver = OEEventsObserver(); var startupFailedDueToLackOfPermissions = Bool() var lmPath: String! var dicPath: String! var words: Array<String> = [] var currentWord: String! static var helper = SpeechRecognitionHelper(); static func sharedInstance() -> SpeechRecognitionHelper { return helper; } override init() { super.init() openEarsEventsObserver.delegate = self let lmGenerator = OELanguageModelGenerator() addWords() let name = "LanguageModelFileStarSaver" lmGenerator.generateLanguageModelFromArray(words, withFilesNamed: name, forAcousticModelAtPath: OEAcousticModel.pathToModel("AcousticModelEnglish")) lmPath = lmGenerator.pathToSuccessfullyGeneratedLanguageModelWithRequestedName(name) dicPath = lmGenerator.pathToSuccessfullyGeneratedDictionaryWithRequestedName(name) } func setThreshold(th: Float) { do { try OEPocketsphinxController.sharedInstance().setActive(true) OEPocketsphinxController.sharedInstance().vadThreshold = th OEPocketsphinxController.sharedInstance().secondsOfSilenceToDetect = 0.1 } catch _ { } } func pocketsphinxDidStartListening() { print("Listening...") } func pocketsphinxDidDetectSpeech() { print("Speech detected") } func pocketsphinxDidDetectFinishedSpeech() { print("Silence detected") } func pocketsphinxDidStopListening() { print("Listening stopped") } func pocketsphinxDidSuspendRecognition() { print("Recognition suspended") } func pocketsphinxDidResumeRecognition() { print("Recognition resumed") } func pocketsphinxDidChangeLanguageModelToFile(newLanguageModelPathAsString: String, newDictionaryPathAsString: String) { print("Pocketsphinx is now using the following language model: \(newLanguageModelPathAsString) and the following dictionary: \(newDictionaryPathAsString)") } func pocketSphinxContinuousSetupDidFailWithReason(reasonForFailure: String) { print("Listening setup wasn't successful and returned the failure reason: \(reasonForFailure)") } func pocketSphinxContinuousTeardownDidFailWithReason(reasonForFailure: String) { print("Listening teardown wasn't successful and returned the failure reason: \(reasonForFailure)") } func testRecognitionCompleted() { print("A test file that was submitted for recognition is now complete.") } func startListening() { if(!OEPocketsphinxController.sharedInstance().isListening){ do { try OEPocketsphinxController.sharedInstance().setActive(true) } catch { print("Invalid Selection.") } OEPocketsphinxController.sharedInstance().startListeningWithLanguageModelAtPath(lmPath, dictionaryAtPath: dicPath, acousticModelAtPath: OEAcousticModel.pathToModel("AcousticModelEnglish"), languageModelIsJSGF: false) } } func stopListening() { if(OEPocketsphinxController.sharedInstance().isListening){ OEPocketsphinxController.sharedInstance().stopListening() do { try OEPocketsphinxController.sharedInstance().setActive(false) // TODO test } catch { print("Invalid Selection.") } } } func addWords() { //add any thing here that you want to be recognized. Must be in capital letters words.append("CAT") words.append("DOG") } func pocketsphinxFailedNoMicPermissions() { if (AVAudioSession.sharedInstance().respondsToSelector(#selector(AVAudioSession.requestRecordPermission(_:)))) { AVAudioSession.sharedInstance().requestRecordPermission({(granted: Bool)-> Void in if granted { self.startListening() } else{ NSLog("Local callback: The user has never set mic permissions or denied permission to this app's mic, so listening will not start.") self.startupFailedDueToLackOfPermissions = true if OEPocketsphinxController.sharedInstance().isListening { let error = OEPocketsphinxController.sharedInstance().stopListening() // Stop listening if we are listening. if(error != nil) { NSLog("Error while stopping listening in micPermissionCheckCompleted: %@", error); } } } }) } } func pocketsphinxDidReceiveHypothesis(hypothesis: String!, recognitionScore: String!, utteranceID: String!) { // Send notification to the controller with the animal name and the score NSNotificationCenter.defaultCenter().postNotificationName("speakAnimalName", object:nil, userInfo:[ "hypothesis": hypothesis, "recognitionScore": recognitionScore ]) } }
mit
7fcb3ad2534ddf48d997ad1726add38a
36.954545
228
0.608554
5.412037
false
false
false
false
ravero/CoreDataContext
CoreDataContext/BaseDataContext.swift
1
6774
// // BaseDataContext.swift // CoreDataContext // // Created by Rafael Veronezi on 9/30/14. // Copyright (c) 2014 Syligo. All rights reserved. // import Foundation import CoreData public class BaseDataContext : NSObject { // // MARK: - Properties var resourceName: String // // MARK: - Initializers public init(resourceName: String) { self.resourceName = resourceName } // // MARK: - Utilitarian Methods /** Clear the current database of this context. */ public func clearDatabase() -> Bool { if let persistentStore = self.persistentStore { // First tell the persistent store coordinator that the current store will be clear. var error: NSError? self.persistentStoreCoordinator?.removePersistentStore(persistentStore, error: &error) if error != nil { return false } // Delete the data files error = nil if let path = storeUrl.path where NSFileManager.defaultManager().fileExistsAtPath(path) { NSFileManager.defaultManager().removeItemAtURL(self.storeUrl, error: &error) if error != nil { return false } } error = nil if let path = storeUrl_wal.path where NSFileManager.defaultManager().fileExistsAtPath(path) { NSFileManager.defaultManager().removeItemAtURL(self.storeUrl_wal, error: &error) if error != nil { return false } } error = nil if let path = storeUrl_shm.path where NSFileManager.defaultManager().fileExistsAtPath(path) { NSFileManager.defaultManager().removeItemAtURL(self.storeUrl_shm, error: &error) if error != nil { return false } } // Re-create the persistent store coordinator self.createPersistentStore(self.persistentStoreCoordinator!) return true } return false } /** A simple utilitarian method to print the path of the SQLite file of this instance. */ public func printDatabasePath() { println("SwiftyIO - Model '\(resourceName)' database path: \(self.storeUrl)") } // // MARK: - Core Data Stack private var persistentStore: NSPersistentStore? lazy private var storeUrl: NSURL = { return self.applicationDocumentsDirectory.URLByAppendingPathComponent("\(self.resourceName).sqlite") }() lazy private var storeUrl_wal: NSURL = { return self.applicationDocumentsDirectory.URLByAppendingPathComponent("\(self.resourceName).sqlite-wal") }() lazy private var storeUrl_shm: NSURL = { return self.applicationDocumentsDirectory.URLByAppendingPathComponent("\(self.resourceName).sqlite-shm") }() lazy private var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.syligo.labs.CoreDataTest" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] as! NSURL }() lazy private 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(self.resourceName, withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy private 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) if let coordinator = coordinator { self.createPersistentStore(coordinator) } return coordinator }() lazy public 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: - Support Methods private func createPersistentStore(coordinator: NSPersistentStoreCoordinator) { let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("\(self.resourceName).sqlite") var error: NSError? = nil var failureReason = "There was an error creating or loading the application's saved data." self.persistentStore = coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) if self.persistentStore == nil { // Report any error we got. let dict = NSMutableDictionary() 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 as [NSObject : AnyObject]) // 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() } } // // MARK: - Core Data Saving support public func saveContext () { self.managedObjectContext?.save() } }
mit
971137f0d631e509253ec32ea4129166
41.3375
290
0.646738
5.864935
false
false
false
false
lemonandlime/Strax
Strax/Trip.swift
1
3332
// // Trip.swift // Strax // // Created by Karl Söderberg on 2015-07-05. // Copyright © 2015 lemonandlime. All rights reserved. // import UIKit import SwiftyJSON enum TravelType : String{ case UNKNOWN = "UNKNOWN" case METRO = "METRO" case BUS = "BUS" case TRAIN = "TRAIN" case TRAM = "TRAM" case WALK = "WALK" func name()->String{ switch self{ case .UNKNOWN: return "" case .METRO: return "Tunnelbana" case .BUS: return "Buss" case .TRAIN: return "Tåg" case .TRAM: return "Spårvagn" case .WALK: return "Promenad" } } func verb()->String{ switch self{ case .UNKNOWN: return "" case .METRO, .BUS, .TRAIN, TRAM: return "åk" case .WALK: return "gå" } } } protocol BaseLeg{ var name: String {get} var type: TravelType {get} var direction: String? {get} var line: String? {get} var hide: Bool {get} var distance: String? {get} var origin: TravelLocation {get} var destination: TravelLocation {get} var JourneyDetailRef: String? {get} var GeometryRef: String {get} } struct Leg: BaseLeg{ let name: String let type: TravelType let direction: String? let line: String? let hide: Bool let distance: String? let origin: TravelLocation let destination: TravelLocation let JourneyDetailRef: String? let GeometryRef: String init(info: Dictionary<String, AnyObject>) { name = info["name"] as! String type = TravelType(rawValue: info["type"] as! String)! direction = info["dir"] as? String line = info["line"] as? String hide = info["hide"] as? String == "true" distance = info["dist"] as? String origin = TravelLocation(info: info["Origin"] as! Dictionary<String, String>) destination = TravelLocation(info: info["Destination"] as! Dictionary<String, String>) GeometryRef = (info["GeometryRef"] as! Dictionary<String, String>)["ref"]! if let journeyDetail = info["JourneyDetailRef"] as? Dictionary<String, String>{ JourneyDetailRef = journeyDetail["ref"] }else{ JourneyDetailRef = nil } } } protocol BaseTrip{ var duration: String {get} var numberOfChanges: String {get} var legs: Array<BaseLeg> {get} } struct Trip: BaseTrip { let duration: String let numberOfChanges: String var legs: Array<BaseLeg> = Array<BaseLeg>() init(info: JSON) { switch info["LegList"]["Leg"].type { case .Array: let legList = info["LegList"]["Leg"] for var i = 0; i<legList.count; i+=1{ let newLeg = Leg(info: legList[i].dictionaryObject!) legs.append(newLeg) } case .Dictionary: legs.append(Leg(info: info["LegList"]["Leg"].dictionaryObject!)) default: legs = Array<BaseLeg>() } duration = info["dur"].stringValue numberOfChanges = info["chg"].stringValue } }
gpl-2.0
9810f601693e532220fae8e53167f69d
26.487603
102
0.547805
3.973716
false
false
false
false
nifty-swift/Nifty
Sources/mvnrnd.swift
2
3440
/*************************************************************************************************** * mvnrnd.swift * * This file provides multivariate normal random numbers. * * Author: Philip Erickson * Creation Date: 17 Jan 2017 * * 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. * * Copyright 2017 Philip Erickson **************************************************************************************************/ // Algorithm based on: // Press, William H. "Numerical recipes 3rd edition: The art of scientific computing.", Cambridge // university press, 2007. Chapter 7.4, pg 379. /// Compute a vector of multivariate normal random numbers. /// /// - Parameters: /// - mu: d-dimensionsal mean vector /// - sigma: d-by-d symmetric positive semi-definite covariance matrix /// - seed: optionally provide specific seed for generator. If threadSafe is set, this seed will /// not be applied to global generator, but to the temporary generator instance /// - threadSafe: if set to true, a new random generator instance will be created that will be /// be used and exist only for the duration of this call. Otherwise, global instance is used. /// - Returns: d-dimensional vector from the given distribution public func mvnrnd(mu: Vector<Double>, sigma: Matrix<Double>, seed: UInt64? = nil, threadSafe: Bool = false) -> Vector<Double> { let d = mu.count precondition(sigma.size == [d, d], "Sigma must be d-by-d matrix") let y = randn(mu.count, 1, mean: 0.0, std: 1.0, seed: seed, threadSafe: threadSafe) let L = chol(sigma, .lower) let Ly = L*y var v = Vector(Ly) for i in 0..<d { v[i] += mu[i] } v.name = mu.name != nil && sigma .name != nil ? "mvnrnd(\(mu.name!), \(sigma.name!))" : nil v.showName = mu.showName || sigma.showName return v } /// Compute multiple vectors of multivariate normal random numbers. /// /// - Parameters: /// - mu: d-dimensionsal mean vector /// - sigma: d-by-d symmetric positive semi-definite covariance matrix /// - cases: number of vectors to generate /// - seed: optionally provide specific seed for generator. If threadSafe is set, this seed will /// not be applied to global generator, but to the temporary generator instance /// - threadSafe: if set to true, a new random generator instance will be created that will be /// be used and exist only for the duration of this call. Otherwise, global instance is used. /// - Returns: a list of d-dimensional vectors from the given distribution public func mvnrnd(mu: Vector<Double>, sigma: Matrix<Double>, cases: Int, seed: UInt64? = nil, threadSafe: Bool = false) -> [Vector<Double>] { var l = [Vector<Double>]() l.reserveCapacity(cases) for _ in 0..<cases { let v = mvnrnd(mu: mu, sigma: sigma, seed: seed, threadSafe: threadSafe) l.append(v) } return l }
apache-2.0
e6d576cd71c388d176dd11bf5dd8c8ba
40.963415
101
0.638081
4.066194
false
false
false
false
BrisyIOS/zhangxuWeiBo
zhangxuWeiBo/zhangxuWeiBo/Account/ZXAccountManager.swift
1
1951
// // ZXAccountManager.swift // zhangxuWeiBo // // Created by zhangxu on 16/6/11. // Copyright © 2016年 zhangxu. All rights reserved. // import UIKit let accountPath = (kDocumentPath as NSString).stringByAppendingPathComponent("account.data"); class ZXAccountManager: NSObject { // 保存账户 class func saveAccount(account : ZXAccount?) -> Void { if account != nil { NSKeyedArchiver.archiveRootObject(account!, toFile: accountPath); } } // 获取账户 class func account() -> ZXAccount? { // 判断账号是否过期 let account = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? ZXAccount; print(account?.access_token); // 当前时间 let now = NSDate(); // 比较当前时间和账号的过期时间 if account?.expires_time?.compare(now) == NSComparisonResult.OrderedAscending { // 过期 return nil; } // 没有过期,直接返回 return account; } // 授权获取accessToken class func accessTokenWithParam(param : ZXAccessTokenParam? , success: ((ZXAccessTokenResult) -> Void)? , failure : ((NSError) -> Void)?) -> Void { // post请求 HttpManager.shareInstance.request(RequestType.POST, urlString: "https://api.weibo.com/oauth2/access_token", parameters: param?.mj_keyValues()) { (result, error) in if error != nil { print(error); return; } // 获取可选类型中的数据 guard let result = result else { return; } let model = ZXAccessTokenResult.mj_objectWithKeyValues(result); success!(model); } } }
apache-2.0
87893430b8418fe09107c82f0b21428d
25.085714
171
0.529025
4.975477
false
false
false
false
diesmal/thisorthat
ThisOrThat/Code/Core/KeychainAccess.swift
1
2384
// // KeychainAccess.swift // ThisOrThat // // Created by Ilya Nikolaenko on 09/01/2017. // Copyright © 2017 Ilya Nikolaenko. All rights reserved. // import Foundation import Security let kSecClassGenericPasswordValue = String(format: kSecClassGenericPassword as String) let kSecClassValue = String(format: kSecClass as String) let kSecAttrServiceValue = String(format: kSecAttrService as String) let kSecValueDataValue = String(format: kSecValueData as String) let kSecMatchLimitValue = String(format: kSecMatchLimit as String) let kSecReturnDataValue = String(format: kSecReturnData as String) let kSecMatchLimitOneValue = String(format: kSecMatchLimitOne as String) let kSecAttrAccountValue = String(format: kSecAttrAccount as String) struct KeychainAccess { func deletePasscode(identifier: String) { let keychainQuery = [ kSecClassValue: kSecClassGenericPasswordValue, kSecAttrServiceValue: identifier, ] as CFDictionary SecItemDelete(keychainQuery) } func setPasscode(identifier: String, passcode: String) { if let dataFromString = passcode.data(using: String.Encoding.utf8) { let keychainQuery = [ kSecClassValue: kSecClassGenericPasswordValue, kSecAttrServiceValue: identifier, kSecValueDataValue: dataFromString ] as CFDictionary SecItemDelete(keychainQuery) print(SecItemAdd(keychainQuery, nil)) } } func getPasscode(identifier: String) -> String? { let keychainQuery = [ kSecClassValue: kSecClassGenericPasswordValue, kSecAttrServiceValue: identifier, kSecReturnDataValue: kCFBooleanTrue, kSecMatchLimitValue: kSecMatchLimitOneValue ] as CFDictionary var dataTypeRef: AnyObject? let status: OSStatus = SecItemCopyMatching(keychainQuery, &dataTypeRef) var passcode: String? if (status == errSecSuccess) { if let retrievedData = dataTypeRef as? Data, let result = String(data: retrievedData, encoding: String.Encoding.utf8) { passcode = result as String } } else { print("Nothing was retrieved from the keychain. Status code \(status)") } return passcode } }
apache-2.0
142740e6fded144595326338ba9c4ae5
36.234375
90
0.671003
5.428246
false
false
false
false
thetotaljim/thetotaljim.github.io
Stopwatch/Stopwatch/ControlButtonView.swift
1
3164
import UIKit @IBDesignable class ControlButtonView: UIControl { fileprivate(set) var titleLabel = UILabel() override var isEnabled: Bool { didSet { if isEnabled { borderLayer.strokeColor = borderColor?.cgColor titleLabel.textColor = UIColor.black } else { borderLayer.strokeColor = UIColor.lightGray.cgColor titleLabel.textColor = UIColor.lightGray } } } @IBInspectable var typeTitle: String? { didSet { titleLabel.text = typeTitle } } @IBInspectable var borderColor: UIColor? = UIColor.bone { didSet{ borderLayer.strokeColor = borderColor?.cgColor } } fileprivate let borderLayer = CAShapeLayer() required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) backgroundColor = UIColor.bone } override init(frame: CGRect) { super.init(frame: frame) backgroundColor = UIColor.bone } override func draw(_ rect: CGRect) { setupView() } override func prepareForInterfaceBuilder() { backgroundColor = UIColor.bone setupView() } func setupView() { let shapeLayer = CAShapeLayer() shapeLayer.path = CGPath(ellipseIn: bounds, transform: nil) layer.mask = shapeLayer borderLayer.path = CGPath(ellipseIn: CGRect.init(x: 1.25, y: 1.25, width: bounds.width - 2.5, height: bounds.height - 2.5), transform: nil) borderLayer.strokeColor = borderColor?.cgColor borderLayer.lineWidth = 2.5 borderLayer.fillColor = UIColor.clear.cgColor layer.addSublayer(borderLayer) addSubview(titleLabel) titleLabel.translatesAutoresizingMaskIntoConstraints = false titleLabel.textAlignment = .center titleLabel.textColor = UIColor.black titleLabel.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true titleLabel.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true titleLabel.widthAnchor.constraint(lessThanOrEqualTo: widthAnchor, multiplier: 0.9).isActive = true } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { backgroundColor = UIColor(red: 220/255, green: 220/255, blue: 220/255, alpha: 1.0) } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { guard let touch = touches.first else { return } let location = touch.location(in: touch.window) let touchTarget = convert(bounds, to: nil) if location.x > touchTarget.origin.x && location.x < (touchTarget.width + touchTarget.origin.x) && location.y > touchTarget.origin.y && location.y < (touchTarget.height + touchTarget.origin.y) { backgroundColor = UIColor(red: 220/255, green: 220/255, blue: 220/255, alpha: 1.0) } else { backgroundColor = UIColor.bone } } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { backgroundColor = UIColor.bone guard let touch = touches.first else { return } let location = touch.location(in: touch.window) let touchTarget = convert(bounds, to: nil) if location.x > touchTarget.origin.x && location.x < (touchTarget.width + touchTarget.origin.x) && location.y > touchTarget.origin.y && location.y < (touchTarget.height + touchTarget.origin.y) { sendActions(for: UIControlEvents.touchUpInside) } } }
mit
c8a032825c9752a8b0082217ed76f6f6
29.423077
141
0.723135
3.717979
false
false
false
false
warnerbros/cpe-manifest-ios-experience
Source/Shared Views/TalentTableViewCell.swift
1
2980
// // TalentTableViewCell.swift // import UIKit import CPEData class TalentTableViewCell: UITableViewCell { static let NibNameNarrow = "TalentTableViewCell-Narrow" static let NibNameWide = "TalentTableViewCell-Wide" static let ReuseIdentifier = "TalentTableViewCell" @IBOutlet weak private var talentImageView: UIImageView! @IBOutlet weak private var talentInitialLabel: UILabel! @IBOutlet weak private var nameLabel: UILabel? @IBOutlet weak private var roleLabel: UILabel? private var imageURL: URL? { didSet { talentImageView.alpha = 1 talentImageView.backgroundColor = UIColor.clear talentInitialLabel.isHidden = true if let url = imageURL { if url != oldValue { self.talentImageView.sd_setImage(with: url) } } else { talentImageView.sd_cancelCurrentImageLoad() talentImageView.image = nil if let name = name { talentImageView.alpha = 0.9 talentImageView.backgroundColor = UIColor.themePrimary talentInitialLabel.isHidden = false talentInitialLabel.text = name[0] } } } } private var name: String? { set { nameLabel?.text = newValue?.uppercased() } get { return nameLabel?.text } } private var character: String? { set { roleLabel?.text = newValue } get { return roleLabel?.text } } var talent: Person? { didSet { if let talent = talent { if talent != oldValue { name = talent.name character = talent.character imageURL = talent.thumbnailImageURL } } else { name = nil character = nil imageURL = nil } } } override func prepareForReuse() { super.prepareForReuse() talent = nil } override func layoutSubviews() { super.layoutSubviews() self.contentView.layoutIfNeeded() self.backgroundColor = UIColor.clear talentImageView.layer.cornerRadius = talentImageView.frame.width / 2 } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) if selected { talentImageView.layer.borderWidth = 2 talentImageView.layer.borderColor = UIColor.white.cgColor nameLabel?.textColor = UIColor.themePrimary roleLabel?.textColor = UIColor.themePrimary } else { talentImageView.layer.borderWidth = 0 nameLabel?.textColor = UIColor.white roleLabel?.textColor = UIColor.themeLightGray } } }
apache-2.0
c77816682169e50daaf54375f4a2e529
26.592593
76
0.558725
5.457875
false
false
false
false
Tarovk/Mundus_Client
Mundus_ios/GameSetupVC.swift
1
3569
// // GameSetupVC.swift // Mundus_ios // // Created by Team Aldo on 19/12/2016. // Copyright © 2016 Team Aldo. All rights reserved. // import UIKit import Alamofire import Aldo import Toaster class GameSetupVC: UIViewController, Callback { @IBOutlet weak var usernameField: UITextField! @IBOutlet weak var createGameButton: UIButton! @IBOutlet weak var joinGameButton: UIButton! @IBOutlet weak var mainIndicator: UIActivityIndicatorView! override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } /// Checks whether to go to the Admin dashboard or the User dashboard. override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if let player = Aldo.getPlayer() { if player.isAdmin() { succesfullCreate() return } succesfullJoin() } } override func viewDidLoad() { super.viewDidLoad() self.joinGameButton.layer.cornerRadius = 5 self.createGameButton.layer.cornerRadius = 5 } func onResponse(request: String, responseCode: Int, response: NSDictionary) { self.mainIndicator.stopAnimating() if responseCode == 200 { switch request { case Regex(pattern: RequestURI.SESSION_CREATE.regex()): succesfullCreate() break case Regex(pattern: RequestURI.SESSION_JOIN.regex()): succesfullJoin() break default: break } return } Toast(text: "The token you entered is not valid").show() } /// Starts the Admin panel. public func succesfullCreate() { performSegue(withIdentifier: "adminSegue", sender: nil) } /// Starts the user panel. func succesfullJoin() { performSegue(withIdentifier: "playerSegue", sender: nil) } /// Sends a create request to the server running the Aldo Framework. @IBAction func createGame(_ sender: Any) { if !nameIsEmpty() { self.mainIndicator.startAnimating() let username = usernameField.text!.replacingOccurrences(of: " ", with: "_") Aldo.createSession(username: username, callback: self) } } /** Checks whether the user entered a name. - Returns: *True* if a name is entered, otherwise *false*. */ func nameIsEmpty() -> Bool { if self.usernameField.text!.isEmpty { Toast(text: "Enter a valid username").show() return true } return false } /// Sends a join request to the server running the Aldo Framework. @IBAction func joinGame(_ sender: Any) { if !nameIsEmpty() { self.mainIndicator.startAnimating() let message = "Enter the token of the game you want to join." let alert = UIAlertController(title: "Join Game", message: message, preferredStyle: .alert) let username = self.usernameField.text! alert.addTextField { (textField) in textField.text = "" } alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { [weak alert] (_) in let textField = alert!.textFields![0] let token = textField.text! Aldo.joinSession(username: username, token: token, callback: self) })) self.present(alert, animated: true, completion: nil) } } }
mit
81357fda5ce17c7b38e6e0f452175708
29.495726
103
0.593049
4.880985
false
false
false
false
Latyntsev/bumper
bumper/Bumper.swift
1
2718
// // Bumper.swift // bumper // // Created by Aleksandr Latyntsev on 1/12/16. // Copyright © 2016 Aleksandr Latyntsev. All rights reserved. // import Foundation import AppKit class Bumper { private var fontName:String init(fontName:String) { self.fontName = fontName } func makeOnImage(image:NSImage, text: String) -> NSImage { let blureConst: CGFloat = 0.03 let source = CGImageSourceCreateWithData(image.TIFFRepresentation!, [:]) let maskRef = CGImageSourceCreateImageAtIndex(source!, 0, [:])! var inputImage = NSImage(CGImage: maskRef, size: CGSizeMake(0,0)) let fontSize = inputImage.size.width * 0.17 let textRect = CGRectMake(0, 0, inputImage.size.width, inputImage.size.height / 2) let paragraph = NSMutableParagraphStyle() paragraph.alignment = .Center paragraph.maximumLineHeight = fontSize let backgroundTextFontAttributes = [ NSFontAttributeName:NSFont(name: fontName, size: fontSize)!, NSForegroundColorAttributeName: NSColor.blackColor(), NSParagraphStyleAttributeName:paragraph ] let textFontAttributes = [ NSFontAttributeName: NSFont(name: fontName, size: fontSize)!, NSForegroundColorAttributeName: NSColor.whiteColor(), NSParagraphStyleAttributeName:paragraph ] let radisuLow = inputImage.size.width * (blureConst * 0.2) let radisu = inputImage.size.width * (blureConst * 0.8) inputImage = inputImage.addBlure(textRect, radisu:radisu) inputImage = inputImage.addText(text, inRect: textRect , attributes: backgroundTextFontAttributes) inputImage = inputImage.addBlure(textRect, radisu: radisuLow) inputImage = inputImage.addText(text, inRect: textRect, attributes: textFontAttributes) return inputImage } func make(imagesFolderPath:String, text: String) { let fileManager = NSFileManager.defaultManager() let enumerator = fileManager.enumeratorAtPath(imagesFolderPath) while let element = enumerator?.nextObject() as? String { if (element.hasSuffix("png") && element.componentsSeparatedByString("/").count == 1) { let pathToImage = "\(imagesFolderPath)/\(element)" if let inputImage = NSImage.init(contentsOfFile: pathToImage) { let outputImage = makeOnImage(inputImage, text:text) outputImage.saveImage(pathToImage) print("Done \(element)") } } } } }
mit
81b111968de2fee410e629e10d12c313
36.219178
106
0.627898
5.145833
false
false
false
false
wesj/firefox-ios-1
Extensions/SendTo/ActionViewController.swift
1
5196
/* 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 UIKit import Storage import Snap protocol ClientPickerViewControllerDelegate { func clientPickerViewControllerDidCancel(clientPickerViewController: ClientPickerViewController) -> Void func clientPickerViewController(clientPickerViewController: ClientPickerViewController, didPickClients clients: [Client]) -> Void } /*! The ClientPickerViewController displays a list of clients associated with the provided Account. The user can select a number of devices and hit the Send button. This viewcontroller does not implement any specific business logic that needs to happen with the selected clients. That is up to it's delegate, who can listen for cancellation and success events. */ class ClientPickerViewController: UITableViewController { var profile: Profile? var clientPickerDelegate: ClientPickerViewControllerDelegate? var clients: [Client] = [] override func viewDidLoad() { super.viewDidLoad() title = NSLocalizedString("Send To Device", comment: "Title of the dialog that allows you to send a tab to a different device") refreshControl = UIRefreshControl() refreshControl?.addTarget(self, action: "refresh", forControlEvents: UIControlEvents.ValueChanged) navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Cancel, target: self, action: "cancel") } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) reloadClients() } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return clients.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = UITableViewCell() cell.textLabel?.font = UIFont(name: "HelveticaNeue", size: 17) cell.textLabel?.text = String(format: NSLocalizedString("Send to %@", comment: "Text in a table view row that lets the user pick a device to which to send a tab to"), clients[indexPath.row].name) return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) clientPickerDelegate?.clientPickerViewController(self, didPickClients: [clients[indexPath.row]]) } private func reloadClients() { profile?.clients.getAll( { response in self.clients = response dispatch_async(dispatch_get_main_queue()) { self.refreshControl?.endRefreshing() self.tableView.reloadData() } }, error: { err in // TODO: Figure out a good way to handle this. print("Error: could not load clients: ") println(err) }) } func refresh() { reloadClients() } func cancel() { self.extensionContext!.completeRequestReturningItems(nil, completionHandler: nil) } } /*! The ActionViewController is the initial viewcontroller that is presented (full screen) when the share extension is activated. Depending on whether the user is logged in or not, this viewcontroller will present either a Login or ClientPicker. */ @objc(ActionViewController) class ActionViewController: UINavigationController, ClientPickerViewControllerDelegate { var profile: Profile? var sharedItem: ShareItem? override func viewDidLoad() { super.viewDidLoad() ExtensionUtils.extractSharedItemFromExtensionContext(self.extensionContext, completionHandler: { (item, error) -> Void in if error == nil && item != nil { self.sharedItem = item if self.profile == nil { // XXX todo. } else { let clientPickerViewController = ClientPickerViewController() clientPickerViewController.clientPickerDelegate = self clientPickerViewController.profile = self.profile self.pushViewController(clientPickerViewController, animated: false) } } else { self.extensionContext!.completeRequestReturningItems([], completionHandler: nil); } }) } func finish() { self.extensionContext!.completeRequestReturningItems(nil, completionHandler: nil) } func clientPickerViewController(clientPickerViewController: ClientPickerViewController, didPickClients clients: [Client]) { profile?.clients.sendItem(self.sharedItem!, toClients: clients) finish() } func clientPickerViewControllerDidCancel(clientPickerViewController: ClientPickerViewController) { finish() } }
mpl-2.0
2b1622cb01a571417bc916d862d5bfa4
39.27907
203
0.680523
5.760532
false
false
false
false
tuannme/Up
Up+/Pods/NVActivityIndicatorView/NVActivityIndicatorView/Animations/NVActivityIndicatorAnimationBallZigZagDeflect.swift
2
3685
// // NVActivityIndicatorAnimationBallZigZagDeflect.swift // NVActivityIndicatorViewDemo // // The MIT License (MIT) // Copyright (c) 2016 Vinh Nguyen // 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 class NVActivityIndicatorAnimationBallZigZagDeflect: NVActivityIndicatorAnimationDelegate { func setUpAnimation(in layer: CALayer, size: CGSize, color: UIColor) { let circleSize: CGFloat = size.width / 5 let duration: CFTimeInterval = 0.75 let deltaX = size.width / 2 - circleSize / 2 let deltaY = size.height / 2 - circleSize / 2 let frame = CGRect(x: (layer.bounds.size.width - circleSize) / 2, y: (layer.bounds.size.height - circleSize) / 2, width: circleSize, height: circleSize) // Circle 1 animation let animation = CAKeyframeAnimation(keyPath:"transform") animation.keyTimes = [0.0, 0.33, 0.66, 1.0] animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) animation.values = [NSValue(caTransform3D: CATransform3DMakeTranslation(0, 0, 0)), NSValue(caTransform3D: CATransform3DMakeTranslation(-deltaX, -deltaY, 0)), NSValue(caTransform3D: CATransform3DMakeTranslation(deltaX, -deltaY, 0)), NSValue(caTransform3D: CATransform3DMakeTranslation(0, 0, 0))] animation.duration = duration animation.repeatCount = HUGE animation.autoreverses = true animation.isRemovedOnCompletion = false // Draw circle 1 circleAt(frame: frame, layer: layer, size: CGSize(width: circleSize, height: circleSize), color: color, animation: animation) // Circle 2 animation animation.values = [NSValue(caTransform3D: CATransform3DMakeTranslation(0, 0, 0)), NSValue(caTransform3D: CATransform3DMakeTranslation(deltaX, deltaY, 0)), NSValue(caTransform3D: CATransform3DMakeTranslation(-deltaX, deltaY, 0)), NSValue(caTransform3D: CATransform3DMakeTranslation(0, 0, 0))] // Draw circle 2 circleAt(frame: frame, layer: layer, size: CGSize(width: circleSize, height: circleSize), color: color, animation: animation) } func circleAt(frame: CGRect, layer: CALayer, size: CGSize, color: UIColor, animation: CAAnimation) { let circle = NVActivityIndicatorShape.circle.layerWith(size: size, color: color) circle.frame = frame circle.add(animation, forKey: "animation") layer.addSublayer(circle) } }
mit
080bada22f7cf95f5d34f19a230950da
48.797297
160
0.684396
4.861478
false
false
false
false
mrackwitz/Stencil
Stencil/Node.swift
1
7528
import Foundation struct NodeError : Error { let token:Token let message:String init(token:Token, message:String) { self.token = token self.message = message } var description:String { return "\(token.components().first!): \(message)" } } public protocol Node { /// Return the node rendered as a string, or returns a failure func render(context:Context) -> Result } extension Array { func map<U>(block:((Element) -> (U?, Error?))) -> ([U]?, Error?) { var results = [U]() for item in self { let (result, error) = block(item) if let error = error { return (nil, error) } else if (result != nil) { // let result = result exposing a bug in the Swift compier :( results.append(result!) } } return (results, nil) } } public func renderNodes(nodes:[Node], context:Context) -> Result { var result = "" for item in nodes { switch item.render(context) { case .Success(let string): result += string case .Error(let error): return .Error(error) } } return .Success(result) } public class SimpleNode : Node { let handler:(Context) -> (Result) public init(handler:((Context) -> (Result))) { self.handler = handler } public func render(context:Context) -> Result { return handler(context) } } public class TextNode : Node { public let text:String public init(text:String) { self.text = text } public func render(context:Context) -> Result { return .Success(self.text) } } public class VariableNode : Node { public let variable:Variable public init(variable:Variable) { self.variable = variable } public init(variable:String) { self.variable = Variable(variable) } public func render(context:Context) -> Result { let result:AnyObject? = variable.resolve(context) if let result = result as? String { return .Success(result) } else if let result = result as? NSObject { return .Success(result.description) } return .Success("") } } public class NowNode : Node { public let format:Variable public class func parse(parser:TokenParser, token:Token) -> TokenParser.Result { var format:Variable? let components = token.components() if components.count == 2 { format = Variable(components[1]) } return .Success(node:NowNode(format:format)) } public init(format:Variable?) { if let format = format { self.format = format } else { self.format = Variable("\"yyyy-MM-dd 'at' HH:mm\"") } } public func render(context: Context) -> Result { let date = NSDate() let format: AnyObject? = self.format.resolve(context) var formatter:NSDateFormatter? if let format = format as? NSDateFormatter { formatter = format } else if let format = format as? String { formatter = NSDateFormatter() formatter!.dateFormat = format } else { return .Success("") } return .Success(formatter!.stringFromDate(date)) } } public class ForNode : Node { let variable:Variable let loopVariable:String let nodes:[Node] public class func parse(parser:TokenParser, token:Token) -> TokenParser.Result { let components = token.components() if count(components) == 4 && components[2] == "in" { let loopVariable = components[1] let variable = components[3] var forNodes:[Node]! var emptyNodes = [Node]() switch parser.parse(until(["endfor", "empty"])) { case .Success(let nodes): forNodes = nodes case .Error(let error): return .Error(error: error) } if let token = parser.nextToken() { if token.contents == "empty" { switch parser.parse(until(["endfor"])) { case .Success(let nodes): emptyNodes = nodes case .Error(let error): return .Error(error: error) } parser.nextToken() } } else { return .Error(error: NodeError(token: token, message: "`endfor` was not found.")) } return .Success(node:ForNode(variable: variable, loopVariable: loopVariable, nodes: forNodes, emptyNodes:emptyNodes)) } return .Error(error: NodeError(token: token, message: "Invalid syntax. Expected `for x in y`.")) } public init(variable:String, loopVariable:String, nodes:[Node], emptyNodes:[Node]) { self.variable = Variable(variable) self.loopVariable = loopVariable self.nodes = nodes } public func render(context: Context) -> Result { let values = variable.resolve(context) as? [AnyObject] var output = "" if let values = values { for item in values { context.push() context[loopVariable] = item let result = renderNodes(nodes, context) context.pop() switch result { case .Success(let string): output += string case .Error(let error): return .Error(error) } } } return .Success(output) } } public class IfNode : Node { public let variable:Variable public let trueNodes:[Node] public let falseNodes:[Node] public class func parse(parser:TokenParser, token:Token) -> TokenParser.Result { let variable = token.components()[1] var trueNodes = [Node]() var falseNodes = [Node]() switch parser.parse(until(["endif", "else"])) { case .Success(let nodes): trueNodes = nodes case .Error(let error): return .Error(error: error) } if let token = parser.nextToken() { if token.contents == "else" { switch parser.parse(until(["endif"])) { case .Success(let nodes): falseNodes = nodes case .Error(let error): return .Error(error: error) } parser.nextToken() } } else { return .Error(error:NodeError(token: token, message: "`endif` was not found.")) } return .Success(node:IfNode(variable: variable, trueNodes: trueNodes, falseNodes: falseNodes)) } public class func parse_ifnot(parser:TokenParser, token:Token) -> TokenParser.Result { let variable = token.components()[1] var trueNodes = [Node]() var falseNodes = [Node]() switch parser.parse(until(["endif", "else"])) { case .Success(let nodes): falseNodes = nodes case .Error(let error): return .Error(error: error) } if let token = parser.nextToken() { if token.contents == "else" { switch parser.parse(until(["endif"])) { case .Success(let nodes): trueNodes = nodes case .Error(let error): return .Error(error: error) } parser.nextToken() } } else { return .Error(error:NodeError(token: token, message: "`endif` was not found.")) } return .Success(node:IfNode(variable: variable, trueNodes: trueNodes, falseNodes: falseNodes)) } public init(variable:String, trueNodes:[Node], falseNodes:[Node]) { self.variable = Variable(variable) self.trueNodes = trueNodes self.falseNodes = falseNodes } public func render(context: Context) -> Result { let result: AnyObject? = variable.resolve(context) var truthy = false if let result = result as? [AnyObject] { if result.count > 0 { truthy = true } } else if let result: AnyObject = result { truthy = true } context.push() let output = renderNodes(truthy ? trueNodes : falseNodes, context) context.pop() return output } }
bsd-2-clause
5b903ebe1854148d9b1b89466f079065
23.763158
123
0.618092
4.012793
false
false
false
false
ruslanskorb/CoreStore
Sources/DispatchQueue+CoreStore.swift
1
3176
// // DispatchQueue+CoreStore.swift // CoreStore // // Copyright © 2018 John Rommel Estropia // // 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: - DispatchQueue extension DispatchQueue { @nonobjc @inline(__always) internal static func serial(_ label: String, qos: DispatchQoS = .default) -> DispatchQueue { return DispatchQueue( label: label, qos: qos, attributes: [], autoreleaseFrequency: .inherit, target: nil ) } @nonobjc @inline(__always) internal static func concurrent(_ label: String, qos: DispatchQoS = .default) -> DispatchQueue { return DispatchQueue( label: label, qos: qos, attributes: .concurrent, autoreleaseFrequency: .inherit, target: nil ) } @nonobjc internal func cs_isCurrentExecutionContext() -> Bool { enum Static { static let specificKey = DispatchSpecificKey<ObjectIdentifier>() } let specific = ObjectIdentifier(self) self.setSpecific(key: Static.specificKey, value: specific) return DispatchQueue.getSpecific(key: Static.specificKey) == specific } @nonobjc @inline(__always) internal func cs_sync<T>(_ closure: () throws -> T) rethrows -> T { return try self.sync { try autoreleasepool(invoking: closure) } } @nonobjc @inline(__always) internal func cs_async(_ closure: @escaping () -> Void) { self.async { autoreleasepool(invoking: closure) } } @nonobjc @inline(__always) internal func cs_barrierSync<T>(_ closure: () throws -> T) rethrows -> T { return try self.sync(flags: .barrier) { try autoreleasepool(invoking: closure) } } @nonobjc @inline(__always) internal func cs_barrierAsync(_ closure: @escaping () -> Void) { self.async(flags: .barrier) { autoreleasepool(invoking: closure) } } // MARK: Private }
mit
84fa52306495b10866651f2226339673
31.731959
100
0.634646
4.76012
false
false
false
false
tkremenek/swift
stdlib/public/core/ArrayCast.swift
34
3333
//===--- ArrayCast.swift - Casts and conversions for Array ----------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // Because NSArray is effectively an [AnyObject], casting [T] -> [U] // is an integral part of the bridging process and these two issues // are handled together. // //===----------------------------------------------------------------------===// /// Called by the casting machinery. @_silgen_name("_swift_arrayDownCastIndirect") internal func _arrayDownCastIndirect<SourceValue, TargetValue>( _ source: UnsafePointer<Array<SourceValue>>, _ target: UnsafeMutablePointer<Array<TargetValue>>) { target.initialize(to: _arrayForceCast(source.pointee)) } /// Implements `source as! [TargetElement]`. /// /// - Note: When SourceElement and TargetElement are both bridged verbatim, type /// checking is deferred until elements are actually accessed. @inlinable //for performance reasons public func _arrayForceCast<SourceElement, TargetElement>( _ source: Array<SourceElement> ) -> Array<TargetElement> { #if _runtime(_ObjC) if _isClassOrObjCExistential(SourceElement.self) && _isClassOrObjCExistential(TargetElement.self) { let src = source._buffer if let native = src.requestNativeBuffer() { if native.storesOnlyElementsOfType(TargetElement.self) { // A native buffer that is known to store only elements of the // TargetElement can be used directly return Array(_buffer: src.cast(toBufferOf: TargetElement.self)) } // Other native buffers must use deferred element type checking return Array(_buffer: src.downcast(toBufferWithDeferredTypeCheckOf: TargetElement.self)) } return Array(_immutableCocoaArray: source._buffer._asCocoaArray()) } #endif return source.map { $0 as! TargetElement } } /// Called by the casting machinery. @_silgen_name("_swift_arrayDownCastConditionalIndirect") internal func _arrayDownCastConditionalIndirect<SourceValue, TargetValue>( _ source: UnsafePointer<Array<SourceValue>>, _ target: UnsafeMutablePointer<Array<TargetValue>> ) -> Bool { if let result: Array<TargetValue> = _arrayConditionalCast(source.pointee) { target.initialize(to: result) return true } return false } /// Implements `source as? [TargetElement]`: convert each element of /// `source` to a `TargetElement` and return the resulting array, or /// return `nil` if any element fails to convert. /// /// - Complexity: O(n), because each element must be checked. @inlinable //for performance reasons public func _arrayConditionalCast<SourceElement, TargetElement>( _ source: [SourceElement] ) -> [TargetElement]? { var successfulCasts = ContiguousArray<TargetElement>() successfulCasts.reserveCapacity(source.count) for element in source { if let casted = element as? TargetElement { successfulCasts.append(casted) } else { return nil } } return Array(successfulCasts) }
apache-2.0
e6ff8bd0358df8ba08e43e7e38ffed93
37.310345
80
0.690669
4.491914
false
false
false
false
stormpath/stormpath-swift-example
Stormpath Swift Example/ProfileViewController.swift
1
2054
// // ProfileViewController.swift // Stormpath iOS Example // // Created by Edward Jiang on 2/18/16. // Copyright © 2016 Stormpath. All rights reserved. // import UIKit import Stormpath class ProfileViewController: UIViewController { @IBOutlet weak var helloLabel: UILabel! @IBOutlet weak var emailLabel: UILabel! @IBOutlet weak var usernameLabel: UILabel! @IBOutlet weak var createdAtLabel: UILabel! @IBOutlet weak var modifiedAtLabel: UILabel! @IBOutlet weak var customDataTextView: UITextView! @IBOutlet weak var hrefTextField: UITextField! @IBOutlet weak var accessTokenTextField: UITextField! @IBOutlet weak var refreshTokenTextField: UITextField! var account: Account! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) helloLabel.text = "Hello, \(account.fullName)!" emailLabel.text = "Email: \(account.email)" usernameLabel.text = "Username: \(account.username)" createdAtLabel.text = "Created At: \(account.createdAt)" modifiedAtLabel.text = "Updated At: \(account.modifiedAt)" customDataTextView.text = "Custom Data: " + (account.customData ?? "nil") hrefTextField.text = account.href.description accessTokenTextField.text = Stormpath.sharedSession.accessToken refreshTokenTextField.text = Stormpath.sharedSession.refreshToken } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func refreshAccessToken(_ sender: AnyObject) { Stormpath.sharedSession.refreshAccessToken { (success, error) -> Void in self.viewWillAppear(false) } } @IBAction func logout(_ sender: AnyObject) { Stormpath.sharedSession.logout() dismiss(animated: false, completion: nil) } }
mit
6a327cc9f5cd97940485315f787dd895
33.216667
81
0.685826
5.007317
false
false
false
false
yysskk/SwipeMenuViewController
Sources/Classes/ContentScrollView.swift
1
4760
import UIKit public protocol ContentScrollViewDataSource { func numberOfPages(in contentScrollView: ContentScrollView) -> Int func contentScrollView(_ contentScrollView: ContentScrollView, viewForPageAt index: Int) -> UIView? } open class ContentScrollView: UIScrollView { open var dataSource: ContentScrollViewDataSource? fileprivate var pageViews: [UIView] = [] fileprivate var currentIndex: Int = 0 fileprivate var options: SwipeMenuViewOptions.ContentScrollView = SwipeMenuViewOptions.ContentScrollView() public init(frame: CGRect, default defaultIndex: Int, options: SwipeMenuViewOptions.ContentScrollView? = nil) { super.init(frame: frame) currentIndex = defaultIndex if #available(iOS 11.0, *) { self.contentInsetAdjustmentBehavior = .never } if let options = options { self.options = options } } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } open override func didMoveToSuperview() { setup() } override open func layoutSubviews() { super.layoutSubviews() self.contentSize = CGSize(width: frame.width * CGFloat(pageViews.count), height: frame.height) } public func reset() { pageViews = [] currentIndex = 0 } public func reload() { self.didMoveToSuperview() } public func update(_ newIndex: Int) { currentIndex = newIndex } // MARK: - Setup fileprivate func setup() { guard let dataSource = dataSource else { return } if dataSource.numberOfPages(in: self) <= 0 { return } setupScrollView() setupPages() } fileprivate func setupScrollView() { backgroundColor = options.backgroundColor showsHorizontalScrollIndicator = false showsVerticalScrollIndicator = false isScrollEnabled = options.isScrollEnabled isPagingEnabled = true isDirectionalLockEnabled = false alwaysBounceHorizontal = false scrollsToTop = false bounces = false bouncesZoom = false setContentOffset(.zero, animated: false) } private func setupPages() { pageViews = [] guard let dataSource = dataSource, dataSource.numberOfPages(in: self) > 0 else { return } self.contentSize = CGSize(width: frame.width * CGFloat(dataSource.numberOfPages(in: self)), height: frame.height) for i in 0...currentIndex { guard let pageView = dataSource.contentScrollView(self, viewForPageAt: i) else { return } pageViews.append(pageView) addSubview(pageView) let leadingAnchor = i > 0 ? pageViews[i - 1].trailingAnchor : self.leadingAnchor pageView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ pageView.topAnchor.constraint(equalTo: self.topAnchor), pageView.widthAnchor.constraint(equalTo: self.widthAnchor), pageView.heightAnchor.constraint(equalTo: self.heightAnchor), pageView.leadingAnchor.constraint(equalTo: leadingAnchor) ]) } guard currentIndex < dataSource.numberOfPages(in: self) else { return } for i in (currentIndex + 1)..<dataSource.numberOfPages(in: self) { guard let pageView = dataSource.contentScrollView(self, viewForPageAt: i) else { return } pageViews.append(pageView) addSubview(pageView) pageView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ pageView.topAnchor.constraint(equalTo: self.topAnchor), pageView.widthAnchor.constraint(equalTo: self.widthAnchor), pageView.heightAnchor.constraint(equalTo: self.heightAnchor), pageView.leadingAnchor.constraint(equalTo: pageViews[i - 1].trailingAnchor) ]) } } } extension ContentScrollView { var currentPage: UIView? { if currentIndex < pageViews.count && currentIndex >= 0 { return pageViews[currentIndex] } return nil } var nextPage: UIView? { if currentIndex < pageViews.count - 1 { return pageViews[currentIndex + 1] } return nil } var previousPage: UIView? { if currentIndex > 0 { return pageViews[currentIndex - 1] } return nil } public func jump(to index: Int, animated: Bool) { update(index) self.setContentOffset(CGPoint(x: self.frame.width * CGFloat(currentIndex), y: 0), animated: animated) } }
mit
d48df41bc35dc3fb9e5ec95e4836dc9a
29.126582
121
0.639496
5.384615
false
false
false
false
mortenbekditlevsen/SmappeeKit
Carthage/Checkouts/SwiftyJSON/Source/SwiftyJSON.swift
1
35686
// SwiftyJSON.swift // // Copyright (c) 2014 Ruoyu Fu, Pinglin Tang // // 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: - Error ///Error domain public let ErrorDomain: String! = "SwiftyJSONErrorDomain" ///Error code public let ErrorUnsupportedType: Int! = 999 public let ErrorIndexOutOfBounds: Int! = 900 public let ErrorWrongType: Int! = 901 public let ErrorNotExist: Int! = 500 // MARK: - JSON Type /** JSON's type definitions. See http://tools.ietf.org/html/rfc7231#section-4.3 */ public enum Type :Int{ case Number case String case Bool case Array case Dictionary case Null case Unknown } // MARK: - JSON Base public struct JSON { /** Creates a JSON using the data. - parameter data: The NSData used to convert to json.Top level object in data is an NSArray or NSDictionary - parameter opt: The JSON serialization reading options. `.AllowFragments` by default. - parameter error: error The NSErrorPointer used to return the error. `nil` by default. - returns: The created JSON */ public init(data:NSData, options opt: NSJSONReadingOptions = .AllowFragments, error: NSErrorPointer = nil) { do { let object: AnyObject = try NSJSONSerialization.JSONObjectWithData(data, options: opt) self.init(object) } catch let aError as NSError { if error != nil { error.memory = aError } self.init(NSNull()) } } /** Creates a JSON using the object. - parameter object: The object must have the following properties: All objects are NSString/String, NSNumber/Int/Float/Double/Bool, NSArray/Array, NSDictionary/Dictionary, or NSNull; All dictionary keys are NSStrings/String; NSNumbers are not NaN or infinity. - returns: The created JSON */ public init(_ object: AnyObject) { self.object = object } /** Creates a JSON from a [JSON] - parameter jsonArray: A Swift array of JSON objects - returns: The created JSON */ public init(_ jsonArray:[JSON]) { self.init(jsonArray.map { $0.object }) } /// Private object private var _object: AnyObject = NSNull() /// Private type private var _type: Type = .Null /// prviate error private var _error: NSError? /// Object in JSON public var object: AnyObject { get { return _object } set { _object = newValue switch newValue { case let number as NSNumber: if number.isBool { _type = .Bool } else { _type = .Number } case _ as NSString: _type = .String case _ as NSNull: _type = .Null case _ as [AnyObject]: _type = .Array case _ as [String : AnyObject]: _type = .Dictionary default: _type = .Unknown _object = NSNull() _error = NSError(domain: ErrorDomain, code: ErrorUnsupportedType, userInfo: [NSLocalizedDescriptionKey: "It is a unsupported type"]) } } } /// json type public var type: Type { get { return _type } } /// Error in JSON public var error: NSError? { get { return self._error } } /// The static null json @available(*, unavailable, renamed="null") public static var nullJSON: JSON { get { return null } } public static var null: JSON { get { return JSON(NSNull()) } } } // MARK: - SequenceType extension JSON : Swift.SequenceType { /// If `type` is `.Array` or `.Dictionary`, return `array.empty` or `dictonary.empty` otherwise return `false`. public var isEmpty: Bool { get { switch self.type { case .Array: return (self.object as! [AnyObject]).isEmpty case .Dictionary: return (self.object as! [String : AnyObject]).isEmpty default: return false } } } /// If `type` is `.Array` or `.Dictionary`, return `array.count` or `dictonary.count` otherwise return `0`. public var count: Int { get { switch self.type { case .Array: return self.arrayValue.count case .Dictionary: return self.dictionaryValue.count default: return 0 } } } /** If `type` is `.Array` or `.Dictionary`, return a generator over the elements like `Array` or `Dictionary`, otherwise return a generator over empty. - returns: Return a *generator* over the elements of this *sequence*. */ public func generate() -> AnyGenerator<(String, JSON)> { switch self.type { case .Array: let array_ = object as! [AnyObject] var generate_ = array_.generate() var index_: Int = 0 return anyGenerator { if let element_: AnyObject = generate_.next() { return ("\(index_++)", JSON(element_)) } else { return nil } } case .Dictionary: let dictionary_ = object as! [String : AnyObject] var generate_ = dictionary_.generate() return anyGenerator { if let (key_, value_): (String, AnyObject) = generate_.next() { return (key_, JSON(value_)) } else { return nil } } default: return anyGenerator { return nil } } } } // MARK: - Subscript /** * To mark both String and Int can be used in subscript. */ public protocol SubscriptType {} extension Int: SubscriptType {} extension String: SubscriptType {} extension JSON { /// If `type` is `.Array`, return json which's object is `array[index]`, otherwise return null json with error. private subscript(index index: Int) -> JSON { get { if self.type != .Array { var errorResult_ = JSON.null errorResult_._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] failure, It is not an array"]) return errorResult_ } let array_ = self.object as! [AnyObject] if index >= 0 && index < array_.count { return JSON(array_[index]) } var errorResult_ = JSON.null errorResult_._error = NSError(domain: ErrorDomain, code:ErrorIndexOutOfBounds , userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] is out of bounds"]) return errorResult_ } set { if self.type == .Array { var array_ = self.object as! [AnyObject] if array_.count > index { array_[index] = newValue.object self.object = array_ } } } } /// If `type` is `.Dictionary`, return json which's object is `dictionary[key]` , otherwise return null json with error. private subscript(key key: String) -> JSON { get { var returnJSON = JSON.null if self.type == .Dictionary { let dictionary_ = self.object as! [String : AnyObject] if let object_: AnyObject = dictionary_[key] { returnJSON = JSON(object_) } else { returnJSON._error = NSError(domain: ErrorDomain, code: ErrorNotExist, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] does not exist"]) } } else { returnJSON._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] failure, It is not an dictionary"]) } return returnJSON } set { if self.type == .Dictionary { var dictionary_ = self.object as! [String : AnyObject] dictionary_[key] = newValue.object self.object = dictionary_ } } } /// If `sub` is `Int`, return `subscript(index:)`; If `sub` is `String`, return `subscript(key:)`. private subscript(sub sub: SubscriptType) -> JSON { get { if sub is String { return self[key:sub as! String] } else { return self[index:sub as! Int] } } set { if sub is String { self[key:sub as! String] = newValue } else { self[index:sub as! Int] = newValue } } } /** Find a json in the complex data structuresby using the Int/String's array. - parameter path: The target json's path. Example: let json = JSON[data] let path = [9,"list","person","name"] let name = json[path] The same as: let name = json[9]["list"]["person"]["name"] - returns: Return a json found by the path or a null json with error */ public subscript(path: [SubscriptType]) -> JSON { get { switch path.count { case 0: return JSON.null case 1: return self[sub: path[0]] default: var aPath = path; aPath.removeAtIndex(0) let nextJSON = self[sub: path[0]] return nextJSON[aPath] } } set { switch path.count { case 0: return case 1: self[sub:path[0]].object = newValue.object default: var aPath = path; aPath.removeAtIndex(0) var nextJSON = self[sub: path[0]] nextJSON[aPath] = newValue self[sub: path[0]] = nextJSON } } } /** Find a json in the complex data structuresby using the Int/String's array. - parameter path: The target json's path. Example: let name = json[9,"list","person","name"] The same as: let name = json[9]["list"]["person"]["name"] - returns: Return a json found by the path or a null json with error */ public subscript(path: SubscriptType...) -> JSON { get { return self[path] } set { self[path] = newValue } } } // MARK: - LiteralConvertible extension JSON: Swift.StringLiteralConvertible { public init(stringLiteral value: StringLiteralType) { self.init(value) } public init(extendedGraphemeClusterLiteral value: StringLiteralType) { self.init(value) } public init(unicodeScalarLiteral value: StringLiteralType) { self.init(value) } } extension JSON: Swift.IntegerLiteralConvertible { public init(integerLiteral value: IntegerLiteralType) { self.init(value) } } extension JSON: Swift.BooleanLiteralConvertible { public init(booleanLiteral value: BooleanLiteralType) { self.init(value) } } extension JSON: Swift.FloatLiteralConvertible { public init(floatLiteral value: FloatLiteralType) { self.init(value) } } extension JSON: Swift.DictionaryLiteralConvertible { public init(dictionaryLiteral elements: (String, AnyObject)...) { var dictionary_ = [String : AnyObject]() for (key_, value) in elements { dictionary_[key_] = value } self.init(dictionary_) } } extension JSON: Swift.ArrayLiteralConvertible { public init(arrayLiteral elements: AnyObject...) { self.init(elements) } } extension JSON: Swift.NilLiteralConvertible { public init(nilLiteral: ()) { self.init(NSNull()) } } // MARK: - Raw extension JSON: Swift.RawRepresentable { public init?(rawValue: AnyObject) { if JSON(rawValue).type == .Unknown { return nil } else { self.init(rawValue) } } public var rawValue: AnyObject { return self.object } public func rawData(options opt: NSJSONWritingOptions = NSJSONWritingOptions(rawValue: 0)) throws -> NSData { return try NSJSONSerialization.dataWithJSONObject(self.object, options: opt) } public func rawString(encoding: UInt = NSUTF8StringEncoding, options opt: NSJSONWritingOptions = .PrettyPrinted) -> String? { switch self.type { case .Array, .Dictionary: do { let data = try self.rawData(options: opt) return NSString(data: data, encoding: encoding) as? String } catch _ { return nil } case .String: return (self.object as! String) case .Number: return (self.object as! NSNumber).stringValue case .Bool: return (self.object as! Bool).description case .Null: return "null" default: return nil } } } // MARK: - Printable, DebugPrintable extension JSON: Swift.Printable, Swift.DebugPrintable { public var description: String { if let string = self.rawString(options:.PrettyPrinted) { return string } else { return "unknown" } } public var debugDescription: String { return description } } // MARK: - Array extension JSON { //Optional [JSON] public var array: [JSON]? { get { if self.type == .Array { return (self.object as! [AnyObject]).map{ JSON($0) } } else { return nil } } } //Non-optional [JSON] public var arrayValue: [JSON] { get { return self.array ?? [] } } //Optional [AnyObject] public var arrayObject: [AnyObject]? { get { switch self.type { case .Array: return self.object as? [AnyObject] default: return nil } } set { if newValue != nil { self.object = NSMutableArray(array: newValue!, copyItems: true) } else { self.object = NSNull() } } } } // MARK: - Dictionary extension JSON { private func _map<Key:Hashable ,Value, NewValue>(source: [Key: Value], transform: Value -> NewValue) -> [Key: NewValue] { var result = [Key: NewValue](minimumCapacity:source.count) for (key,value) in source { result[key] = transform(value) } return result } //Optional [String : JSON] public var dictionary: [String : JSON]? { get { if self.type == .Dictionary { return _map(self.object as! [String : AnyObject]){ JSON($0) } } else { return nil } } } //Non-optional [String : JSON] public var dictionaryValue: [String : JSON] { get { return self.dictionary ?? [:] } } //Optional [String : AnyObject] public var dictionaryObject: [String : AnyObject]? { get { switch self.type { case .Dictionary: return self.object as? [String : AnyObject] default: return nil } } set { if newValue != nil { self.object = NSMutableDictionary(dictionary: newValue!, copyItems: true) } else { self.object = NSNull() } } } } // MARK: - Bool extension JSON: Swift.BooleanType { //Optional bool public var bool: Bool? { get { switch self.type { case .Bool: return self.object.boolValue default: return nil } } set { if newValue != nil { self.object = NSNumber(bool: newValue!) } else { self.object = NSNull() } } } //Non-optional bool public var boolValue: Bool { get { switch self.type { case .Bool, .Number, .String: return self.object.boolValue default: return false } } set { self.object = NSNumber(bool: newValue) } } } // MARK: - String extension JSON { //Optional string public var string: String? { get { switch self.type { case .String: return self.object as? String default: return nil } } set { if newValue != nil { self.object = NSString(string:newValue!) } else { self.object = NSNull() } } } //Non-optional string public var stringValue: String { get { switch self.type { case .String: return self.object as! String case .Number: return self.object.stringValue case .Bool: return (self.object as! Bool).description default: return "" } } set { self.object = NSString(string:newValue) } } } // MARK: - Number extension JSON { //Optional number public var number: NSNumber? { get { switch self.type { case .Number, .Bool: return self.object as? NSNumber default: return nil } } set { self.object = newValue?.copy() ?? NSNull() } } //Non-optional number public var numberValue: NSNumber { get { switch self.type { case .String: let scanner = NSScanner(string: self.object as! String) if scanner.scanDouble(nil){ if (scanner.atEnd) { return NSNumber(double:(self.object as! NSString).doubleValue) } } return NSNumber(double: 0.0) case .Number, .Bool: return self.object as! NSNumber default: return NSNumber(double: 0.0) } } set { self.object = newValue.copy() } } } //MARK: - Null extension JSON { public var null: NSNull? { get { switch self.type { case .Null: return NSNull() default: return nil } } set { self.object = NSNull() } } } //MARK: - URL extension JSON { //Optional URL public var URL: NSURL? { get { switch self.type { case .String: if let encodedString_ = self.object.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) { return NSURL(string: encodedString_) } else { return nil } default: return nil } } set { self.object = newValue?.absoluteString ?? NSNull() } } } // MARK: - Int, Double, Float, Int8, Int16, Int32, Int64 extension JSON { public var double: Double? { get { return self.number?.doubleValue } set { if newValue != nil { self.object = NSNumber(double: newValue!) } else { self.object = NSNull() } } } public var doubleValue: Double { get { return self.numberValue.doubleValue } set { self.object = NSNumber(double: newValue) } } public var float: Float? { get { return self.number?.floatValue } set { if newValue != nil { self.object = NSNumber(float: newValue!) } else { self.object = NSNull() } } } public var floatValue: Float { get { return self.numberValue.floatValue } set { self.object = NSNumber(float: newValue) } } public var int: Int? { get { return self.number?.longValue } set { if newValue != nil { self.object = NSNumber(integer: newValue!) } else { self.object = NSNull() } } } public var intValue: Int { get { return self.numberValue.integerValue } set { self.object = NSNumber(integer: newValue) } } public var uInt: UInt? { get { return self.number?.unsignedLongValue } set { if newValue != nil { self.object = NSNumber(unsignedLong: newValue!) } else { self.object = NSNull() } } } public var uIntValue: UInt { get { return self.numberValue.unsignedLongValue } set { self.object = NSNumber(unsignedLong: newValue) } } public var int8: Int8? { get { return self.number?.charValue } set { if newValue != nil { self.object = NSNumber(char: newValue!) } else { self.object = NSNull() } } } public var int8Value: Int8 { get { return self.numberValue.charValue } set { self.object = NSNumber(char: newValue) } } public var uInt8: UInt8? { get { return self.number?.unsignedCharValue } set { if newValue != nil { self.object = NSNumber(unsignedChar: newValue!) } else { self.object = NSNull() } } } public var uInt8Value: UInt8 { get { return self.numberValue.unsignedCharValue } set { self.object = NSNumber(unsignedChar: newValue) } } public var int16: Int16? { get { return self.number?.shortValue } set { if newValue != nil { self.object = NSNumber(short: newValue!) } else { self.object = NSNull() } } } public var int16Value: Int16 { get { return self.numberValue.shortValue } set { self.object = NSNumber(short: newValue) } } public var uInt16: UInt16? { get { return self.number?.unsignedShortValue } set { if newValue != nil { self.object = NSNumber(unsignedShort: newValue!) } else { self.object = NSNull() } } } public var uInt16Value: UInt16 { get { return self.numberValue.unsignedShortValue } set { self.object = NSNumber(unsignedShort: newValue) } } public var int32: Int32? { get { return self.number?.intValue } set { if newValue != nil { self.object = NSNumber(int: newValue!) } else { self.object = NSNull() } } } public var int32Value: Int32 { get { return self.numberValue.intValue } set { self.object = NSNumber(int: newValue) } } public var uInt32: UInt32? { get { return self.number?.unsignedIntValue } set { if newValue != nil { self.object = NSNumber(unsignedInt: newValue!) } else { self.object = NSNull() } } } public var uInt32Value: UInt32 { get { return self.numberValue.unsignedIntValue } set { self.object = NSNumber(unsignedInt: newValue) } } public var int64: Int64? { get { return self.number?.longLongValue } set { if newValue != nil { self.object = NSNumber(longLong: newValue!) } else { self.object = NSNull() } } } public var int64Value: Int64 { get { return self.numberValue.longLongValue } set { self.object = NSNumber(longLong: newValue) } } public var uInt64: UInt64? { get { return self.number?.unsignedLongLongValue } set { if newValue != nil { self.object = NSNumber(unsignedLongLong: newValue!) } else { self.object = NSNull() } } } public var uInt64Value: UInt64 { get { return self.numberValue.unsignedLongLongValue } set { self.object = NSNumber(unsignedLongLong: newValue) } } } //MARK: - Comparable extension JSON: Swift.Comparable {} public func ==(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.Number, .Number): return (lhs.object as! NSNumber) == (rhs.object as! NSNumber) case (.String, .String): return (lhs.object as! String) == (rhs.object as! String) case (.Bool, .Bool): return (lhs.object as! Bool) == (rhs.object as! Bool) case (.Array, .Array): return (lhs.object as! NSArray) == (rhs.object as! NSArray) case (.Dictionary, .Dictionary): return (lhs.object as! NSDictionary) == (rhs.object as! NSDictionary) case (.Null, .Null): return true default: return false } } public func <=(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.Number, .Number): return (lhs.object as! NSNumber) <= (rhs.object as! NSNumber) case (.String, .String): return (lhs.object as! String) <= (rhs.object as! String) case (.Bool, .Bool): return (lhs.object as! Bool) == (rhs.object as! Bool) case (.Array, .Array): return (lhs.object as! NSArray) == (rhs.object as! NSArray) case (.Dictionary, .Dictionary): return (lhs.object as! NSDictionary) == (rhs.object as! NSDictionary) case (.Null, .Null): return true default: return false } } public func >=(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.Number, .Number): return (lhs.object as! NSNumber) >= (rhs.object as! NSNumber) case (.String, .String): return (lhs.object as! String) >= (rhs.object as! String) case (.Bool, .Bool): return (lhs.object as! Bool) == (rhs.object as! Bool) case (.Array, .Array): return (lhs.object as! NSArray) == (rhs.object as! NSArray) case (.Dictionary, .Dictionary): return (lhs.object as! NSDictionary) == (rhs.object as! NSDictionary) case (.Null, .Null): return true default: return false } } public func >(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.Number, .Number): return (lhs.object as! NSNumber) > (rhs.object as! NSNumber) case (.String, .String): return (lhs.object as! String) > (rhs.object as! String) default: return false } } public func <(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.Number, .Number): return (lhs.object as! NSNumber) < (rhs.object as! NSNumber) case (.String, .String): return (lhs.object as! String) < (rhs.object as! String) default: return false } } private let trueNumber = NSNumber(bool: true) private let falseNumber = NSNumber(bool: false) private let trueObjCType = String.fromCString(trueNumber.objCType) private let falseObjCType = String.fromCString(falseNumber.objCType) // MARK: - NSNumber: Comparable extension NSNumber: Swift.Comparable { var isBool:Bool { get { let objCType = String.fromCString(self.objCType) if (self.compare(trueNumber) == NSComparisonResult.OrderedSame && objCType == trueObjCType) || (self.compare(falseNumber) == NSComparisonResult.OrderedSame && objCType == falseObjCType){ return true } else { return false } } } } public func ==(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) == NSComparisonResult.OrderedSame } } public func !=(lhs: NSNumber, rhs: NSNumber) -> Bool { return !(lhs == rhs) } public func <(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) == NSComparisonResult.OrderedAscending } } public func >(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) == NSComparisonResult.OrderedDescending } } public func <=(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) != NSComparisonResult.OrderedDescending } } public func >=(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) != NSComparisonResult.OrderedAscending } } //MARK:- Unavailable @available(*, unavailable, renamed="JSON") public typealias JSONValue = JSON extension JSON { @available(*, unavailable, message="use 'init(_ object:AnyObject)' instead") public init(object: AnyObject) { self = JSON(object) } @available(*, unavailable, renamed="dictionaryObject") public var dictionaryObjects: [String : AnyObject]? { get { return self.dictionaryObject } } @available(*, unavailable, renamed="arrayObject") public var arrayObjects: [AnyObject]? { get { return self.arrayObject } } @available(*, unavailable, renamed="int8") public var char: Int8? { get { return self.number?.charValue } } @available(*, unavailable, renamed="int8Value") public var charValue: Int8 { get { return self.numberValue.charValue } } @available(*, unavailable, renamed="uInt8") public var unsignedChar: UInt8? { get{ return self.number?.unsignedCharValue } } @available(*, unavailable, renamed="uInt8Value") public var unsignedCharValue: UInt8 { get{ return self.numberValue.unsignedCharValue } } @available(*, unavailable, renamed="int16") public var short: Int16? { get{ return self.number?.shortValue } } @available(*, unavailable, renamed="int16Value") public var shortValue: Int16 { get{ return self.numberValue.shortValue } } @available(*, unavailable, renamed="uInt16") public var unsignedShort: UInt16? { get{ return self.number?.unsignedShortValue } } @available(*, unavailable, renamed="uInt16Value") public var unsignedShortValue: UInt16 { get{ return self.numberValue.unsignedShortValue } } @available(*, unavailable, renamed="int") public var long: Int? { get{ return self.number?.longValue } } @available(*, unavailable, renamed="intValue") public var longValue: Int { get{ return self.numberValue.longValue } } @available(*, unavailable, renamed="uInt") public var unsignedLong: UInt? { get{ return self.number?.unsignedLongValue } } @available(*, unavailable, renamed="uIntValue") public var unsignedLongValue: UInt { get{ return self.numberValue.unsignedLongValue } } @available(*, unavailable, renamed="int64") public var longLong: Int64? { get{ return self.number?.longLongValue } } @available(*, unavailable, renamed="int64Value") public var longLongValue: Int64 { get{ return self.numberValue.longLongValue } } @available(*, unavailable, renamed="uInt64") public var unsignedLongLong: UInt64? { get{ return self.number?.unsignedLongLongValue } } @available(*, unavailable, renamed="uInt64Value") public var unsignedLongLongValue: UInt64 { get{ return self.numberValue.unsignedLongLongValue } } @available(*, unavailable, renamed="int") public var integer: Int? { get { return self.number?.integerValue } } @available(*, unavailable, renamed="intValue") public var integerValue: Int { get { return self.numberValue.integerValue } } @available(*, unavailable, renamed="uInt") public var unsignedInteger: Int? { get { return self.number?.unsignedIntegerValue } } @available(*, unavailable, renamed="uIntValue") public var unsignedIntegerValue: Int { get { return self.numberValue.unsignedIntegerValue } } }
mit
2d8bbbe1be7a2e29aacdd45c531568ea
25.571854
264
0.529507
4.689972
false
false
false
false
Molbie/Outlaw-SpriteKit
Tests/OutlawSpriteKitTests/Enums/SKInterpolationModeTests.swift
1
1784
// // SKInterpolationModeTests.swift // OutlawSpriteKit // // Created by Brian Mullen on 12/17/16. // Copyright © 2016 Molbie LLC. All rights reserved. // import XCTest import Outlaw import OutlawCoreGraphics import OutlawSimd import SpriteKit @testable import OutlawSpriteKit class SKInterpolationModeTests: XCTestCase { fileprivate typealias strings = SKInterpolationMode.StringValues func testStringInit() { let linear = SKInterpolationMode(stringValue: strings.linear) XCTAssertEqual(linear, .linear) let spline = SKInterpolationMode(stringValue: strings.spline) XCTAssertEqual(spline, .spline) let step = SKInterpolationMode(stringValue: strings.step) XCTAssertEqual(step, .step) let invalid = SKInterpolationMode(stringValue: "invalid") XCTAssertNil(invalid) } func testUpperStringInit() { let linear = SKInterpolationMode(stringValue: strings.linear.uppercased()) XCTAssertEqual(linear, .linear) let spline = SKInterpolationMode(stringValue: strings.spline.uppercased()) XCTAssertEqual(spline, .spline) let step = SKInterpolationMode(stringValue: strings.step.uppercased()) XCTAssertEqual(step, .step) let invalid = SKInterpolationMode(stringValue: "INVALID") XCTAssertNil(invalid) } func testStringValue() { let linear = SKInterpolationMode.linear XCTAssertEqual(linear.stringValue, strings.linear) let spline = SKInterpolationMode.spline XCTAssertEqual(spline.stringValue, strings.spline) let step = SKInterpolationMode.step XCTAssertEqual(step.stringValue, strings.step) } }
mit
45e189c216a1799b773bce4ee4564507
29.741379
82
0.681997
5.036723
false
true
false
false
LarsStegman/ColumnView
Sources/ColumnTransitioningContext.swift
1
4392
// // ColumnTransitioningContext.swift // ColumnView // // Created by Lars Stegman on 07-03-17. // Copyright © 2017 Stegman. All rights reserved. // import Foundation import UIKit class ColumnTransitioningContext: NSObject, UIViewControllerContextTransitioning { private var viewControllers: [UITransitionContextViewControllerKey: UIViewController] = [:] var completion: (Bool) -> Void private var toVc: UIViewController! { return self.viewControllers[.to] } private var fromVc: UIViewController? { return self.viewControllers[.from] } public var containerView: UIView public var isAnimated: Bool public var isInteractive: Bool = false public var transitionWasCancelled: Bool = false public var presentationStyle: UIModalPresentationStyle { return .custom } public var direction: Direction init?(container: ColumnView, from fromVc: UIViewController?, to toVc: UIViewController, animated: Bool, direction: Direction, completion: @escaping (Bool) -> Void) { guard toVc.isViewLoaded else { return nil } self.containerView = container self.viewControllers[.from] = fromVc self.viewControllers[.to] = toVc self.completion = completion self.isAnimated = animated self.direction = direction } public func viewController(forKey key: UITransitionContextViewControllerKey) -> UIViewController? { return self.viewControllers[key] } public func view(forKey key: UITransitionContextViewKey) -> UIView? { switch key { case UITransitionContextViewKey.from: return nil case UITransitionContextViewKey.to: return self.toVc.view default: return nil } } public func initialFrame(for vc: UIViewController) -> CGRect { let laidOutFrame = vc.view.frame if vc == fromVc { return laidOutFrame } let scrollView = containerView.superview! switch direction { case .right: let scrollViewOriginInContainerViewCoordinateSpace = scrollView.convert(scrollView.bounds.origin, to: containerView) .offsetBy(dx: -laidOutFrame.width, dy: 0) return CGRect(origin: scrollViewOriginInContainerViewCoordinateSpace, size: laidOutFrame.size) case .left: let scrollViewTopRightInContainerViewCoordinateSpace = scrollView.convert(scrollView.bounds.topRight, to: containerView) return CGRect(origin: scrollViewTopRightInContainerViewCoordinateSpace, size: laidOutFrame.size) case .down: return laidOutFrame.offsetBy(dx: 0, dy: -containerView.frame.height) case .up: return laidOutFrame.offsetBy(dx: 0, dy: containerView.frame.height) } } public func finalFrame(for vc: UIViewController) -> CGRect { let laidOutFrame = vc.view.frame if vc == toVc { return laidOutFrame } let scrollView = containerView.superview! switch direction { case .right: let scrollViewTopRightInContainerViewCoordinateSpace = scrollView.convert(scrollView.bounds.topRight, to: containerView) return CGRect(origin: scrollViewTopRightInContainerViewCoordinateSpace, size: laidOutFrame.size) case .left: return CGRect(origin: containerView.superview!.frame.origin .offsetBy(dx: -laidOutFrame.width, dy: 0), size: laidOutFrame.size) case .down: return laidOutFrame.offsetBy(dx: 0, dy: containerView.frame.height) case .up: return laidOutFrame.offsetBy(dx: 0, dy: -containerView.frame.height) } } public var targetTransform: CGAffineTransform { return CGAffineTransform.identity } public func completeTransition(_ didComplete: Bool) { transitionWasCancelled = didComplete completion(didComplete) } public func updateInteractiveTransition(_ percentComplete: CGFloat) { } public func finishInteractiveTransition() { transitionWasCancelled = false } public func cancelInteractiveTransition() { transitionWasCancelled = true } public func pauseInteractiveTransition() { } }
mit
94285f592fe56a6b83d332e260d5ad05
33.849206
132
0.662491
5.246117
false
false
false
false
ashfurrow/Nimble-Snapshots
Nimble_Snapshots/DynamicType/PrettyDynamicTypeSyntax.swift
1
2380
import Nimble import UIKit // MARK: - Nicer syntax using == operator public struct DynamicTypeSnapshot { let name: String? let identifier: String? let record: Bool let sizes: [UIContentSizeCategory] let deviceAgnostic: Bool init(name: String?, identifier: String?, record: Bool, sizes: [UIContentSizeCategory], deviceAgnostic: Bool) { self.name = name self.identifier = identifier self.record = record self.sizes = sizes self.deviceAgnostic = deviceAgnostic } } public func dynamicTypeSnapshot(_ name: String? = nil, identifier: String? = nil, sizes: [UIContentSizeCategory] = allContentSizeCategories(), deviceAgnostic: Bool = false) -> DynamicTypeSnapshot { return DynamicTypeSnapshot(name: name, identifier: identifier, record: false, sizes: sizes, deviceAgnostic: deviceAgnostic) } public func recordDynamicTypeSnapshot(_ name: String? = nil, identifier: String? = nil, sizes: [UIContentSizeCategory] = allContentSizeCategories(), deviceAgnostic: Bool = false) -> DynamicTypeSnapshot { return DynamicTypeSnapshot(name: name, identifier: identifier, record: true, sizes: sizes, deviceAgnostic: deviceAgnostic) } public func ==<Expectation: Nimble.Expectation>(lhs: Expectation, rhs: DynamicTypeSnapshot) where Expectation.Value: Snapshotable { if let name = rhs.name { if rhs.record { lhs.to(recordDynamicTypeSnapshot(named: name, sizes: rhs.sizes, isDeviceAgnostic: rhs.deviceAgnostic)) } else { lhs.to(haveValidDynamicTypeSnapshot(named: name, sizes: rhs.sizes, isDeviceAgnostic: rhs.deviceAgnostic)) } } else { if rhs.record { lhs.to(recordDynamicTypeSnapshot(sizes: rhs.sizes, isDeviceAgnostic: rhs.deviceAgnostic)) } else { lhs.to(haveValidDynamicTypeSnapshot(sizes: rhs.sizes, isDeviceAgnostic: rhs.deviceAgnostic)) } } }
mit
1ad077b1a164a9e8979431498aa6542c
39.338983
131
0.571008
4.897119
false
false
false
false
BugMomon/weibo
NiceWB/NiceWB/Classes/Main(主要)/WelcomeView/WelcomeViewController.swift
1
1897
// // WelcomeViewController.swift // NiceWB // // Created by HongWei on 2017/4/5. // Copyright © 2017年 HongWei. All rights reserved. // import UIKit class WelcomeViewController: UIViewController { @IBOutlet weak var icon: UIImageView! @IBOutlet weak var welcomename: UILabel! @IBOutlet weak var iconBottomCons: NSLayoutConstraint! override func viewDidLoad() { super.viewDidLoad() //0.设置头像 let path = UserAccountViewModel.shareInstance.account?.avatar_large let userName = UserAccountViewModel.shareInstance.account?.screen_name let welText = NSMutableAttributedString(string: "欢迎回来,\(userName!)!") print(welText.length) //给label添加颜色 welText.addAttribute(NSForegroundColorAttributeName, value: UIColor.gray, range: NSMakeRange(0, 4)) welText.addAttribute(NSForegroundColorAttributeName, value: UIColor.red, range: NSMakeRange(5, 8)) welcomename.attributedText = welText // print("用户照片路径:\(path!)") let url = URL(string:path ?? "") icon.sd_setImage(with:url, placeholderImage: UIImage(named:"avatar_default_big")) print("layout\(iconBottomCons.constant)") //1.改变约束的值 iconBottomCons.constant = UIScreen.main.bounds.height - 200 //执行动画 UIView.animate(withDuration: 1.0, delay: 0.0, usingSpringWithDamping: 0.7, initialSpringVelocity:5.0, options: [], animations: { self.view.layoutIfNeeded() // self.icon.center = CGPoint(x: self.icon.center.x, y: self.icon.center.y - 500) }) { (_) in UIApplication.shared.keyWindow?.rootViewController = UIStoryboard.init(name: "Main", bundle: nil).instantiateInitialViewController() } } }
apache-2.0
a5e8033d7c1b8a258aabe827611d6f5e
34.960784
144
0.642857
4.473171
false
false
false
false
Shopify/mobile-buy-sdk-ios
Buy/Generated/Storefront/FulfillmentLineItem.swift
1
3935
// // FulfillmentLineItem.swift // Buy // // Created by Shopify. // Copyright (c) 2017 Shopify Inc. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation extension Storefront { /// Represents a single line item in a fulfillment. There is at most one /// fulfillment line item for each order line item. open class FulfillmentLineItemQuery: GraphQL.AbstractQuery, GraphQLQuery { public typealias Response = FulfillmentLineItem /// The associated order's line item. @discardableResult open func lineItem(alias: String? = nil, _ subfields: (OrderLineItemQuery) -> Void) -> FulfillmentLineItemQuery { let subquery = OrderLineItemQuery() subfields(subquery) addField(field: "lineItem", aliasSuffix: alias, subfields: subquery) return self } /// The amount fulfilled in this fulfillment. @discardableResult open func quantity(alias: String? = nil) -> FulfillmentLineItemQuery { addField(field: "quantity", aliasSuffix: alias) return self } } /// Represents a single line item in a fulfillment. There is at most one /// fulfillment line item for each order line item. open class FulfillmentLineItem: GraphQL.AbstractResponse, GraphQLObject { public typealias Query = FulfillmentLineItemQuery internal override func deserializeValue(fieldName: String, value: Any) throws -> Any? { let fieldValue = value switch fieldName { case "lineItem": guard let value = value as? [String: Any] else { throw SchemaViolationError(type: FulfillmentLineItem.self, field: fieldName, value: fieldValue) } return try OrderLineItem(fields: value) case "quantity": guard let value = value as? Int else { throw SchemaViolationError(type: FulfillmentLineItem.self, field: fieldName, value: fieldValue) } return Int32(value) default: throw SchemaViolationError(type: FulfillmentLineItem.self, field: fieldName, value: fieldValue) } } /// The associated order's line item. open var lineItem: Storefront.OrderLineItem { return internalGetLineItem() } func internalGetLineItem(alias: String? = nil) -> Storefront.OrderLineItem { return field(field: "lineItem", aliasSuffix: alias) as! Storefront.OrderLineItem } /// The amount fulfilled in this fulfillment. open var quantity: Int32 { return internalGetQuantity() } func internalGetQuantity(alias: String? = nil) -> Int32 { return field(field: "quantity", aliasSuffix: alias) as! Int32 } internal override func childResponseObjectMap() -> [GraphQL.AbstractResponse] { var response: [GraphQL.AbstractResponse] = [] objectMap.keys.forEach { switch($0) { case "lineItem": response.append(internalGetLineItem()) response.append(contentsOf: internalGetLineItem().childResponseObjectMap()) default: break } } return response } } }
mit
c31cc8e2703e6ad59aeb09983c15efdd
34.45045
115
0.729352
4.222103
false
false
false
false
HarveyHu/PoolScoreboard
Pool Scoreboard/Pool Scoreboard/PoolTableViewController.swift
1
5574
// // PoolTableViewController.swift // Pool Scoreboard // // Created by HarveyHu on 15/06/2017. // Copyright © 2017 HarveyHu. All rights reserved. // import UIKit import RxSwift import RxCocoa class PoolTableViewController: BaseViewController { let backgroundView = UIView() let imageView = UIImageView() let resetButton = UIButton() var ball: Ball? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func setUI() { super.setUI() self.view.addSubview(backgroundView) backgroundView.addSubview(imageView) backgroundView.addSubview(resetButton) self.view.backgroundColor = UIColor.white self.backgroundView.backgroundColor = UIColor.black imageView.image = UIImage(named: "pool_table") self.resetButton.setTitle(" RESET ", for: .normal) self.resetButton.setBackgroundImage(UIColor.gray.tinyImage(), for: .normal) self.resetButton.setBackgroundImage(UIColor.darkGray.tinyImage(), for: .selected) self.resetButton.layer.cornerRadius = 10 self.resetButton.layer.masksToBounds = true self.resetButton.layer.borderWidth = 2 self.resetButton.layer.borderColor = UIColor.red.cgColor let height = self.view.frame.size.height ball = Ball(diameter: Double(height) / 40.0, touchDiameter: Double(height) / 40.0 * 2.0) for ballView in ball!.ballViews { ballView.center = ball!.getLocationCenterPoint(number: ballView.tag) self.backgroundView.addSubview(ballView) } } override func setUIConstraints() { super.setUIConstraints() backgroundView.snp.makeConstraints { (make) in make.top.equalToSuperview().offset(20) make.leading.equalToSuperview().offset(10) make.trailing.equalToSuperview().offset(-10) make.bottom.equalToSuperview().offset(-10) } imageView.snp.makeConstraints { (make) in make.centerX.equalToSuperview() make.centerY.equalToSuperview() make.height.equalToSuperview().multipliedBy(0.9) make.width.equalTo(self.imageView.snp.height).multipliedBy(857.0 / 1564) // the ratio of the image } resetButton.snp.makeConstraints { (make) in make.leading.equalToSuperview().offset(20.0) make.bottom.equalTo(imageView.snp.bottom) make.height.equalToSuperview().multipliedBy(0.05) //make.trailing.equalTo(imageView.snp.leading).offset(-20) } } override func setUIEvents() { super.setUIEvents() if let ball = self.ball { for ballView in ball.ballViews { self.addPanGestureToBalls(view: ballView, diameter: ball.diameter) } } resetButton.rx.tap.asDriver() .drive(onNext: {[weak self] in self?.ball?.resetLocations() for ballView in self!.ball!.ballViews { ballView.center = self!.ball!.getLocationCenterPoint(number: ballView.tag) } }, onCompleted: nil, onDisposed: nil) .disposed(by: disposeBag) } private func addPanGestureToBalls(view: UIView, diameter: Double) { let panGR = UIPanGestureRecognizer() panGR.rx.event.asDriver().drive(onNext: {[weak self](pan) in if pan.state == .changed || pan.state == .ended { let radius = CGFloat(diameter / 2) let offset = pan.translation(in: pan.view!) let x = view.center.x + offset.x let y = view.center.y + offset.y let parentViewFrame = self!.view.frame let tabbarHeight: CGFloat = 49.0 let rightLimit = parentViewFrame.size.width - radius let bottomLimit = parentViewFrame.size.height - radius - tabbarHeight if x >= radius && x <= rightLimit { if y < radius { view.center = CGPoint(x: x, y: radius) } else if y > bottomLimit { view.center = CGPoint(x: x, y: bottomLimit) } else { view.center = CGPoint(x: x, y: y) } } else { if y < radius { view.center = CGPoint(x: x < radius ? radius : rightLimit, y: radius) } else if y > bottomLimit { view.center = CGPoint(x: x < radius ? radius : rightLimit, y: bottomLimit) } else { view.center = CGPoint(x: x < radius ? radius : rightLimit, y: y) } } pan.setTranslation(CGPoint(x:0, y:0), in: pan.view!) // keep the last position to userDefault if pan.state == .ended { self?.ball?.updateLocation(number: view.tag, center: view.center) } } }, onCompleted: nil, onDisposed: nil) .disposed(by: disposeBag) view.isUserInteractionEnabled = true view.addGestureRecognizer(panGR) } }
mit
ad288ec2e6bc13e567f3092a6bfd1d3e
37.171233
110
0.565225
4.800172
false
false
false
false
kevin-zqw/play-swift
swift-lang/04b. Dictionaries.playground/section-1.swift
1
5283
// ------------------------------------------------------------------------------------------------ // Things to know: // // * Dictionaries store multiple values of the same type, each associated with a key which acts as // an identifier for that value within the dictionary. // // * Dictionaries are type-safe and always clear about what they contain. // // * The types of values that can be stored in a dictionary must always be made clear either // through explicit type annotation or through type inference. // ------------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------------ // Creating a dictionary // // This is a Dictionary literal. They contain a comma-separated list of key:value pairs: ["TYO": "Tokyo", "DUB": "Dublin"] // Let's use that literal to define and initialize a Dictionary. // // In this case, we use type annotation to explicitly declare a Dictionary containing String keys // and String values. This uses the syntactic sugar "[ KeyType: ValueType ]" to declare the // dictionary. var airports: [String : String] = ["TYO": "Tokyo", "DUB": "Dublin", "APL": "Apple Intl"] // The declaration for airports above could also have been declared in this way: var players: Dictionary<String, String> = ["Who" : "First", "What" : "Second"] // In the case below, the literal contains only Strings for all keys and only Strings for all // values, so type inference works in our favor allowing us to avoid the type annotation: let inferredDictionary = ["TYO": "Tokyo", "DUB": "Dublin"] let myDict: Dictionary<Int, Int> = [Int: Int]() var myDict2 = ["hello": "world", "haha": "xixi"] myDict2.count myDict2.isEmpty myDict2["fuck"] myDict2["hello"] myDict2["fuck"] = "hh" myDict2["hello"] = nil myDict2 myDict2 = [:] let oldValue = myDict2.updateValue("Kevin", forKey: "fuck") myDict2 for (key, value) in myDict2 { print("\(key) -> \(value)") } for key in myDict2.keys { print(key) } for value in myDict2.values { print(value) } // ------------------------------------------------------------------------------------------------ // Accessing and modifying a Dictionary // // Let's get a value from the dictionary for the TYO airport: airports["TYO"] // What happens if we try to get a value that doesn't exist? // // Since this can happen, the Dictionary always retuns an optional, so in the next line of code, // notFound will be nil. It will also be of type String? var notFound = airports["FOO"] // We can get the number of elements in the dictionary: airports.count // We can add an element by accessing a key that doesn't exist: airports["LHR"] = "London" // Here's another way to set/update a value. This lets us get the previous value before we set // the new one. The returned value is optional, in case the new value doesn't replace an existing // one: var previousValue = airports.updateValue("Dublin International", forKey: "DUB") // We can remove an entry by setting the value for a key to nil: airports["APL"] = nil // Here's another way to remove a value. The returned value is set to the value that was removed. // Again, this is optional in case there was no value to remove. In this case, the APL airport // was already removed, so the return value will be a nil optional: var removedValue = airports.removeValueForKey("APL") // ------------------------------------------------------------------------------------------------ // Iterating over a Dictionary // // We can iterating over key/value pairs with a for-in loop, which uses a Tuple to hold the // key/value pair for each entry in the Dictionary: for (airportCode, airportName) in airports { airportCode airportName } // We can iterate over just the keys for airportCode in airports.keys { airportCode } // We can iterate over jsut the values for airportName in airports.values { airportName } // We can create an array from the keys or values // // Note that when doing this, the use of Array() is needed to convert the keys or values into // an array. var airportCodes = Array(airports.keys) var airportNames = Array(airports.values) // ------------------------------------------------------------------------------------------------ // Creating an empty Dictionary // // Here, we create an empty Dictionary of Int keys and String values: var namesOfIntegers = Dictionary<Int, String>() // Let's set one of the values namesOfIntegers[16] = "Sixteen" // We can empty a dictionary using an empty dictionary literal: namesOfIntegers = [:] // An immutable dictionary is a constant. let immutableDict = ["a": "one", "b": "two"] // Similar to arrays, we cannot modify the contents of an immutable dictionary. The following lines // will not compile: // // immutableDict["a"] = "b" // You cannot modify an element // immutableDict["c"] = "three" // You cannot add a new entry or change the size // Dictionaries are value types, which means they are copied on assignment. // // Let's create a Dictionary and copy it: var ages = ["Peter": 23, "Wei": 35, "Anish": 65, "Katya": 19] var copiedAges = ages // Next, we'll modify the copy: copiedAges["Peter"] = 24 // And we can see that the original is not changed: ages["Peter"]
apache-2.0
dd721691c2d980900547ebdb94fa8f5a
33.083871
99
0.636949
4.130571
false
false
false
false
rchatham/SwiftyAnimate
SwiftyAnimateDemo/ViewController.swift
1
3401
// // ViewController.swift // SwiftyAnimateDemo // // Created by Reid Chatham on 12/4/16. // Copyright © 2016 Reid Chatham. All rights reserved. // import UIKit import SwiftyAnimate class ViewController: UIViewController { var liked: Bool = false { didSet { guard oldValue != liked else { return } switch liked { case true: heartView.image = #imageLiteral(resourceName: "RedHeart") case false: heartView.image = #imageLiteral(resourceName: "Heart") } } } @IBOutlet weak var heartView: UIImageView! { didSet { heartView.image = #imageLiteral(resourceName: "Heart") let tap = UITapGestureRecognizer(target: self, action: #selector(ViewController.tappedHeart(_:))) tap.numberOfTapsRequired = 1 tap.numberOfTouchesRequired = 1 heartView.addGestureRecognizer(tap) } } func tappedHeart(_ sender: UITapGestureRecognizer) { liked = !liked // heartView.goCrazy().perform() switch liked { case true: heartView.bounce().perform() default: heartView.tilt(angle: -0.33).perform() } } // MARK: -Lifecycle override func viewDidLoad() { super.viewDidLoad() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) Animate() .then(animation: heartView.tilt(angle: -30)) .do { [unowned self] in self.liked = !self.liked } .then(animation: heartView.bounce()) .do { [unowned self] in self.liked = !self.liked } .then(animation: heartView.tilt(angle: -30)) .perform { [unowned self] in self.heartView.isUserInteractionEnabled = true } } } /* Writing custom animations is EASY!!!!! */ protocol Bounceable { func bounce() -> Animate } protocol Tiltable { func tilt(angle: CGFloat) -> Animate } extension UIView: Bounceable { func bounce() -> Animate { return Animate() .then(animation: scale(duration: 0.3, x: 1.3, y: 1.3)) .then(animation: scale(duration: 0.3, x: 0.8, y: 0.8)) .then(animation: scale(duration: 0.3, x: 1.1, y: 1.1)) .then(animation: scale(duration: 0.3, x: 1.0, y: 1.0)) } } extension UIView: Tiltable { func tilt(angle: CGFloat) -> Animate { return Animate() .then(animation: rotate(duration: 0.3, angle: angle)) .wait(timeout: 0.5) .then(animation: rotate(duration: 0.3, angle: 0)) } } /* Combine animations together! */ protocol GoCrazy { func goCrazy() -> Animate } extension UIView: GoCrazy { func goCrazy() -> Animate { return Animate() .then(animation: transform(duration: 0.3, transforms: [ .rotate(angle: 180), .scale(x: 1.5, y: 1.5), .move(x: -10, y: -10), ])) .wait(timeout: 0.3) .then(animation: transform(duration: 0.3, transforms: [ .move(x: 10, y: 10), .scale(x: 1.0, y: 1.0), .rotate(angle: 0), ])) } }
mit
2dba1bc661f7e2c8562f2bf1680eb675
24.954198
109
0.529412
4.047619
false
false
false
false
saagarjha/iina
iina/PrefUtilsViewController.swift
1
5532
// // PrefUtilsViewController.swift // iina // // Created by Collider LI on 9/7/2018. // Copyright © 2018 lhc. All rights reserved. // import Cocoa class PrefUtilsViewController: PreferenceViewController, PreferenceWindowEmbeddable { override var nibName: NSNib.Name { return NSNib.Name("PrefUtilsViewController") } var preferenceTabTitle: String { return NSLocalizedString("preference.utilities", comment: "Utilities") } var preferenceTabImage: NSImage { return NSImage(named: NSImage.Name("pref_utils"))! } override var sectionViews: [NSView] { return [sectionDefaultAppView, sectionRestoreAlertsView, sectionClearCacheView, sectionBrowserExtView] } @IBOutlet var sectionDefaultAppView: NSView! @IBOutlet var sectionRestoreAlertsView: NSView! @IBOutlet var sectionClearCacheView: NSView! @IBOutlet var sectionBrowserExtView: NSView! @IBOutlet var setAsDefaultSheet: NSWindow! @IBOutlet weak var setAsDefaultVideoCheckBox: NSButton! @IBOutlet weak var setAsDefaultAudioCheckBox: NSButton! @IBOutlet weak var setAsDefaultPlaylistCheckBox: NSButton! @IBOutlet weak var thumbCacheSizeLabel: NSTextField! @IBOutlet weak var savedPlaybackProgressClearedLabel: NSTextField! @IBOutlet weak var playHistoryClearedLabel: NSTextField! @IBOutlet weak var restoreAlertsRestoredLabel: NSTextField! override func viewDidLoad() { super.viewDidLoad() DispatchQueue.main.async { self.updateThumbnailCacheStat() } } private func updateThumbnailCacheStat() { thumbCacheSizeLabel.stringValue = "\(FloatingPointByteCountFormatter.string(fromByteCount: CacheManager.shared.getCacheSize(), countStyle: .binary))B" } @IBAction func setIINAAsDefaultAction(_ sender: Any) { view.window!.beginSheet(setAsDefaultSheet) } @IBAction func setAsDefaultOKBtnAction(_ sender: Any) { guard let utiTypes = Bundle.main.infoDictionary?["UTImportedTypeDeclarations"] as? [[String: Any]], let cfBundleID = Bundle.main.bundleIdentifier as CFString? else { return } Logger.log("Set self as default") var successCount = 0 var failedCount = 0 let utiChecked = [ "public.movie": setAsDefaultVideoCheckBox.state == .on, "public.audio": setAsDefaultAudioCheckBox.state == .on, "public.text": setAsDefaultPlaylistCheckBox.state == .on ] for utiType in utiTypes { guard let conformsTo = utiType["UTTypeConformsTo"] as? [String], let tagSpec = utiType["UTTypeTagSpecification"] as? [String: Any], let exts = tagSpec["public.filename-extension"] as? [String] else { return } // make sure that `conformsTo` contains a checked UTI type guard utiChecked.map({ (uti, checked) in checked && conformsTo.contains(uti) }).contains(true) else { continue } for ext in exts { let utiString = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, ext as CFString, nil)!.takeUnretainedValue() let status = LSSetDefaultRoleHandlerForContentType(utiString, .all, cfBundleID) if status == kOSReturnSuccess { successCount += 1 } else { Logger.log("failed for \(ext): return value \(status)", level: .error) failedCount += 1 } } } Utility.showAlert("set_default.success", arguments: [successCount, failedCount], style: .informational, sheetWindow: view.window) view.window!.endSheet(setAsDefaultSheet) } @IBAction func setAsDefaultCancelBtnAction(_ sender: Any) { view.window!.endSheet(setAsDefaultSheet) } @IBAction func resetSuppressedAlertsBtnAction(_ sender: Any) { Utility.quickAskPanel("restore_alerts", sheetWindow: view.window) { respond in guard respond == .alertFirstButtonReturn else { return } Preference.set(false, for: .suppressCannotPreventDisplaySleep) self.restoreAlertsRestoredLabel.isHidden = false } } @IBAction func clearWatchLaterBtnAction(_ sender: Any) { Utility.quickAskPanel("clear_watch_later", sheetWindow: view.window) { respond in guard respond == .alertFirstButtonReturn else { return } try? FileManager.default.removeItem(atPath: Utility.watchLaterURL.path) Utility.createDirIfNotExist(url: Utility.watchLaterURL) self.savedPlaybackProgressClearedLabel.isHidden = false } } @IBAction func clearHistoryBtnAction(_ sender: Any) { Utility.quickAskPanel("clear_history", sheetWindow: view.window) { respond in guard respond == .alertFirstButtonReturn else { return } try? FileManager.default.removeItem(atPath: Utility.playbackHistoryURL.path) NSDocumentController.shared.clearRecentDocuments(self) Preference.set(nil, for: .iinaLastPlayedFilePath) self.playHistoryClearedLabel.isHidden = false } } @IBAction func clearCacheBtnAction(_ sender: Any) { Utility.quickAskPanel("clear_cache", sheetWindow: view.window) { respond in guard respond == .alertFirstButtonReturn else { return } try? FileManager.default.removeItem(atPath: Utility.thumbnailCacheURL.path) Utility.createDirIfNotExist(url: Utility.thumbnailCacheURL) self.updateThumbnailCacheStat() } } @IBAction func extChromeBtnAction(_ sender: Any) { NSWorkspace.shared.open(URL(string: AppData.chromeExtensionLink)!) } @IBAction func extFirefoxBtnAction(_ sender: Any) { NSWorkspace.shared.open(URL(string: AppData.firefoxExtensionLink)!) } }
gpl-3.0
299150ebcd316dec2f200225985a5912
34.915584
154
0.720485
4.507742
false
false
false
false
Stitch7/Instapod
Instapod/Extensions/UIImage+imageEffects.swift
1
13472
/* File: UIImage+ImageEffects.m Abstract: This is a category of UIImage that adds methods to apply blur and tint effects to an image. This is the code you’ll want to look out to find out how to use vImage to efficiently calculate a blur. Version: 1.0 Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. ("Apple") in consideration of your agreement to the following terms, and your use, installation, modification or redistribution of this Apple software constitutes acceptance of these terms. If you do not agree with these terms, please do not use, install, modify or redistribute this Apple software. In consideration of your agreement to abide by the following terms, and subject to these terms, Apple grants you a personal, non-exclusive license, under Apple's copyrights in this original Apple software (the "Apple Software"), to use, reproduce, modify and redistribute the Apple Software, with or without modifications, in source and/or binary forms; provided that if you redistribute the Apple Software in its entirety and without modifications, you must retain this notice and the following text and disclaimers in all such redistributions of the Apple Software. Neither the name, trademarks, service marks or logos of Apple Inc. may be used to endorse or promote products derived from the Apple Software without specific prior written permission from Apple. Except as expressly stated in this notice, no other rights or licenses, express or implied, are granted by Apple herein, including but not limited to any patent rights that may be infringed by your derivative works or by other works in which the Apple Software may be incorporated. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Copyright (C) 2013 Apple Inc. All Rights Reserved. Copyright © 2013 Apple Inc. All rights reserved. WWDC 2013 License NOTE: This Apple Software was supplied by Apple as part of a WWDC 2013 Session. Please refer to the applicable WWDC 2013 Session for further information. IMPORTANT: This Apple software is supplied to you by Apple Inc. ("Apple") in consideration of your agreement to the following terms, and your use, installation, modification or redistribution of this Apple software constitutes acceptance of these terms. If you do not agree with these terms, please do not use, install, modify or redistribute this Apple software. In consideration of your agreement to abide by the following terms, and subject to these terms, Apple grants you a non-exclusive license, under Apple's copyrights in this original Apple software (the "Apple Software"), to use, reproduce, modify and redistribute the Apple Software, with or without modifications, in source and/or binary forms; provided that if you redistribute the Apple Software in its entirety and without modifications, you must retain this notice and the following text and disclaimers in all such redistributions of the Apple Software. Neither the name, trademarks, service marks or logos of Apple Inc. may be used to endorse or promote products derived from the Apple Software without specific prior written permission from Apple. Except as expressly stated in this notice, no other rights or licenses, express or implied, are granted by Apple herein, including but not limited to any patent rights that may be infringed by your derivative works or by other works in which the Apple Software may be incorporated. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. EA1002 5/3/2013 */ // // UIImage.swift // Today // // Created by Alexey Globchastyy on 15/09/14. // Copyright (c) 2014 Alexey Globchastyy. All rights reserved. // import UIKit import Accelerate public extension UIImage { public func applyLightEffect() -> UIImage? { return applyBlurWithRadius(30, tintColor: UIColor(white: 1.0, alpha: 0.3), saturationDeltaFactor: 1.8) } public func applyExtraLightEffect() -> UIImage? { return applyBlurWithRadius(20, tintColor: UIColor(white: 0.97, alpha: 0.82), saturationDeltaFactor: 1.8) } public func applyDarkEffect() -> UIImage? { return applyBlurWithRadius(20, tintColor: UIColor(white: 0.11, alpha: 0.73), saturationDeltaFactor: 1.8) } public func applyTintEffectWithColor(_ tintColor: UIColor) -> UIImage? { let effectColorAlpha: CGFloat = 0.6 var effectColor = tintColor let componentCount = tintColor.cgColor.numberOfComponents if componentCount == 2 { var b: CGFloat = 0 if tintColor.getWhite(&b, alpha: nil) { effectColor = UIColor(white: b, alpha: effectColorAlpha) } } else { var red: CGFloat = 0 var green: CGFloat = 0 var blue: CGFloat = 0 if tintColor.getRed(&red, green: &green, blue: &blue, alpha: nil) { effectColor = UIColor(red: red, green: green, blue: blue, alpha: effectColorAlpha) } } return applyBlurWithRadius(10, tintColor: effectColor, saturationDeltaFactor: -1.0, maskImage: nil) } public func applyBlurWithRadius(_ blurRadius: CGFloat, tintColor: UIColor?, saturationDeltaFactor: CGFloat, maskImage: UIImage? = nil) -> UIImage? { // Check pre-conditions. if (size.width < 1 || size.height < 1) { print("*** error: invalid size: \(size.width) x \(size.height). Both dimensions must be >= 1: \(self)") return nil } if self.cgImage == nil { print("*** error: image must be backed by a CGImage: \(self)") return nil } if maskImage != nil && maskImage!.cgImage == nil { print("*** error: maskImage must be backed by a CGImage: \(maskImage)") return nil } let __FLT_EPSILON__ = CGFloat(FLT_EPSILON) let screenScale = UIScreen.main.scale let imageRect = CGRect(origin: CGPoint.zero, size: size) var effectImage = self let hasBlur = blurRadius > __FLT_EPSILON__ let hasSaturationChange = fabs(saturationDeltaFactor - 1.0) > __FLT_EPSILON__ if hasBlur || hasSaturationChange { func createEffectBuffer(_ context: CGContext?) -> vImage_Buffer { let data = context?.data let width = vImagePixelCount((context?.width)!) let height = vImagePixelCount((context?.height)!) let rowBytes = context?.bytesPerRow return vImage_Buffer(data: data, height: height, width: width, rowBytes: rowBytes!) } UIGraphicsBeginImageContextWithOptions(size, false, screenScale) let effectInContext = UIGraphicsGetCurrentContext() effectInContext?.scaleBy(x: 1.0, y: -1.0) effectInContext?.translateBy(x: 0, y: -size.height) effectInContext?.draw(self.cgImage!, in: imageRect) var effectInBuffer = createEffectBuffer(effectInContext) UIGraphicsBeginImageContextWithOptions(size, false, screenScale) let effectOutContext = UIGraphicsGetCurrentContext() var effectOutBuffer = createEffectBuffer(effectOutContext) if hasBlur { // A description of how to compute the box kernel width from the Gaussian // radius (aka standard deviation) appears in the SVG spec: // http://www.w3.org/TR/SVG/filters.html#feGaussianBlurElement // // For larger values of 's' (s >= 2.0), an approximation can be used: Three // successive box-blurs build a piece-wise quadratic convolution kernel, which // approximates the Gaussian kernel to within roughly 3%. // // let d = floor(s * 3*sqrt(2*pi)/4 + 0.5) // // ... if d is odd, use three box-blurs of size 'd', centered on the output pixel. // // let inputRadius = blurRadius * screenScale // var radius = UInt32(floor(inputRadius * 3.0 * CGFloat(sqrt(2 * M_PI)) / 4 + 0.5)) let d = ((blurRadius * screenScale) * 3.0 * CGFloat(sqrt(2 * M_PI)) / 4.0) var radius = UInt32(floor(d + 0.5)) if radius % 2 != 1 { radius += 1 // force radius to be odd so that the three box-blur methodology works. } let imageEdgeExtendFlags = vImage_Flags(kvImageEdgeExtend) vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags) vImageBoxConvolve_ARGB8888(&effectOutBuffer, &effectInBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags) vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags) } var effectImageBuffersAreSwapped = false if hasSaturationChange { let s: CGFloat = saturationDeltaFactor let floatingPointSaturationMatrix: [CGFloat] = [ 0.0722 + 0.9278 * s, 0.0722 - 0.0722 * s, 0.0722 - 0.0722 * s, 0, 0.7152 - 0.7152 * s, 0.7152 + 0.2848 * s, 0.7152 - 0.7152 * s, 0, 0.2126 - 0.2126 * s, 0.2126 - 0.2126 * s, 0.2126 + 0.7873 * s, 0, 0, 0, 0, 1 ] let divisor: CGFloat = 256 let matrixSize = floatingPointSaturationMatrix.count var saturationMatrix = [Int16](repeating: 0, count: matrixSize) for i: Int in 0 ..< matrixSize { saturationMatrix[i] = Int16(round(floatingPointSaturationMatrix[i] * divisor)) } if hasBlur { vImageMatrixMultiply_ARGB8888(&effectOutBuffer, &effectInBuffer, saturationMatrix, Int32(divisor), nil, nil, vImage_Flags(kvImageNoFlags)) effectImageBuffersAreSwapped = true } else { vImageMatrixMultiply_ARGB8888(&effectInBuffer, &effectOutBuffer, saturationMatrix, Int32(divisor), nil, nil, vImage_Flags(kvImageNoFlags)) } } if !effectImageBuffersAreSwapped { effectImage = UIGraphicsGetImageFromCurrentImageContext()! } UIGraphicsEndImageContext() if effectImageBuffersAreSwapped { effectImage = UIGraphicsGetImageFromCurrentImageContext()! } UIGraphicsEndImageContext() } // Set up output context. UIGraphicsBeginImageContextWithOptions(size, false, screenScale) let outputContext = UIGraphicsGetCurrentContext() outputContext?.scaleBy(x: 1.0, y: -1.0) outputContext?.translateBy(x: 0, y: -size.height) // Draw base image. outputContext?.draw(self.cgImage!, in: imageRect) // Draw effect image. if hasBlur { outputContext?.saveGState() if let image = maskImage { outputContext?.clip(to: imageRect, mask: image.cgImage!); } outputContext?.draw(effectImage.cgImage!, in: imageRect) outputContext?.restoreGState() } // Add in color tint. if let color = tintColor { outputContext?.saveGState() outputContext?.setFillColor(color.cgColor) outputContext?.fill(imageRect) outputContext?.restoreGState() } // Output image is ready. let outputImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return outputImage } }
mit
ede29df4ad3a2de40fd18179978810bf
44.503378
206
0.663449
4.960958
false
false
false
false
SLance/Currency
Currency/FavoriteTableDelegate.swift
1
2028
// // FavoriteTableDelegate.swift // Currency // // Created by Lance Blue on 10/01/2017. // Copyright © 2017 Lance Blue. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import UIKit class FavoriteTableDelegate: NSObject, UITableViewDelegate, UITableViewDataSource { var cellIdentifier = "favCellIdentifier" func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 5 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: FavoriteCell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as! FavoriteCell? ?? UINib(nibName: "FavoriteCell", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! FavoriteCell cell.currencyImageView.backgroundColor = UIColor.red cell.currencyCodeLabel.text = "CNY" cell.currencyValueLabel.text = "100" return cell } }
mit
7fba2a01240b3ae27f3944e0628309f6
42.12766
221
0.730636
4.596372
false
false
false
false
johnno1962/eidolon
Kiosk/Bid Fulfillment/BidderNetworkModel.swift
1
7718
import Foundation import RxSwift import Moya protocol BidderNetworkModelType { var createdNewUser: Observable<Bool> { get } var bidDetails: BidDetails { get } func createOrGetBidder() -> Observable<AuthorizedNetworking> } class BidderNetworkModel: NSObject, BidderNetworkModelType { let bidDetails: BidDetails let provider: Networking var createdNewUser: Observable<Bool> { return self.bidDetails.newUser.hasBeenRegistered.asObservable() } init(provider: Networking, bidDetails: BidDetails) { self.provider = provider self.bidDetails = bidDetails } // MARK: - Main observable /// Returns an authorized provider func createOrGetBidder() -> Observable<AuthorizedNetworking> { return createOrUpdateUser() .flatMap { provider -> Observable<AuthorizedNetworking> in return self.createOrUpdateBidder(provider).mapReplace(provider) } .flatMap { provider -> Observable<AuthorizedNetworking> in self.getMyPaddleNumber(provider).mapReplace(provider) } } } private extension BidderNetworkModel { // MARK: - Chained observables func checkUserEmailExists(email: String) -> Observable<Bool> { let request = provider.request(.FindExistingEmailRegistration(email: email)) return request.map { response in return response.statusCode != 404 } } func createOrUpdateUser() -> Observable<AuthorizedNetworking> { // observable to test for user existence (does a user exist with this email?) let bool = self.checkUserEmailExists(bidDetails.newUser.email.value ?? "") // If the user exists, update their info to the API, otherwise create a new user. return bool .flatMap { emailExists -> Observable<AuthorizedNetworking> in if emailExists { return self.updateUser() } else { return self.createNewUser() } } .flatMap { provider -> Observable<AuthorizedNetworking> in self.addCardToUser(provider).mapReplace(provider) // After update/create observable finishes, add a CC to their account (if we've collected one) } } func createNewUser() -> Observable<AuthorizedNetworking> { let newUser = bidDetails.newUser let endpoint: ArtsyAPI = ArtsyAPI.CreateUser(email: newUser.email.value!, password: newUser.password.value!, phone: newUser.phoneNumber.value!, postCode: newUser.zipCode.value ?? "", name: newUser.name.value ?? "") return provider.request(endpoint) .filterSuccessfulStatusCodes() .map(void) .doOnError { error in logger.log("Creating user failed.") logger.log("Error: \((error as NSError).localizedDescription). \n \((error as NSError).artsyServerError())") }.flatMap { _ -> Observable<AuthorizedNetworking> in self.bidDetails.authenticatedNetworking(self.provider) } } func updateUser() -> Observable<AuthorizedNetworking> { let newUser = bidDetails.newUser let endpoint = ArtsyAuthenticatedAPI.UpdateMe(email: newUser.email.value!, phone: newUser.phoneNumber.value!, postCode: newUser.zipCode.value ?? "", name: newUser.name.value ?? "") return bidDetails.authenticatedNetworking(provider) .flatMap { (provider) -> Observable<AuthorizedNetworking> in provider.request(endpoint) .mapJSON() .logNext() .mapReplace(provider) } .logServerError("Updating user failed.") } func addCardToUser(provider: AuthorizedNetworking) -> Observable<Void> { // If the user was asked to swipe a card, we'd have stored the token. // If the token is not there, then the user must already have one on file. So we can skip this step. guard let token = bidDetails.newUser.creditCardToken.value else { return .empty() } let swiped = bidDetails.newUser.swipedCreditCard let endpoint = ArtsyAuthenticatedAPI.RegisterCard(stripeToken: token, swiped: swiped) return provider.request(endpoint) .filterSuccessfulStatusCodes() .map(void) .doOnCompleted { [weak self] in // Adding the credit card succeeded, so we shoudl clear the newUser.creditCardToken so that we don't // inadvertently try to re-add their card token if they need to increase their bid. self?.bidDetails.newUser.creditCardToken.value = nil } .logServerError("Adding Card to User failed") } // MARK: - Auction / Bidder observables func createOrUpdateBidder(provider: AuthorizedNetworking) -> Observable<Void> { let bool = self.checkForBidderOnAuction(bidDetails.auctionID, provider: provider) return bool.flatMap { exists -> Observable<Void> in if exists { return .empty() } else { return self.registerToAuction(self.bidDetails.auctionID, provider: provider).then { [weak self] in self?.generateAPIN(provider) } } } } func checkForBidderOnAuction(auctionID: String, provider: AuthorizedNetworking) -> Observable<Bool> { let endpoint = ArtsyAuthenticatedAPI.MyBiddersForAuction(auctionID: auctionID) let request = provider.request(endpoint) .filterSuccessfulStatusCodes() .mapJSON() .mapToObjectArray(Bidder) return request.map { [weak self] bidders -> Bool in if let bidder = bidders.first { self?.bidDetails.bidderID.value = bidder.id self?.bidDetails.bidderPIN.value = bidder.pin return true } return false }.logServerError("Getting user bidders failed.") } func registerToAuction(auctionID: String, provider: AuthorizedNetworking) -> Observable<Void> { let endpoint = ArtsyAuthenticatedAPI.RegisterToBid(auctionID: auctionID) let register = provider.request(endpoint) .filterSuccessfulStatusCodes() .mapJSON() .mapToObject(Bidder) return register.doOnNext{ [weak self] bidder in self?.bidDetails.bidderID.value = bidder.id self?.bidDetails.newUser.hasBeenRegistered.value = true } .logServerError("Registering for Auction Failed.") .map(void) } func generateAPIN(provider: AuthorizedNetworking) -> Observable<Void> { let endpoint = ArtsyAuthenticatedAPI.CreatePINForBidder(bidderID: bidDetails.bidderID.value!) return provider.request(endpoint) .filterSuccessfulStatusCodes() .mapJSON() .doOnNext { [weak self] json in let pin = json["pin"] as? String self?.bidDetails.bidderPIN.value = pin } .logServerError("Generating a PIN for bidder has failed.") .map(void) } func getMyPaddleNumber(provider: AuthorizedNetworking) -> Observable<Void> { let endpoint = ArtsyAuthenticatedAPI.Me return provider.request(endpoint) .filterSuccessfulStatusCodes() .mapJSON() .mapToObject(User.self) .doOnNext { [weak self] user in self?.bidDetails.paddleNumber.value = user.paddleNumber } .logServerError("Getting Bidder ID failed.") .map(void) } }
mit
ddce59b7509982d1240e1b1650b598c9
38.177665
222
0.628142
5.091029
false
false
false
false
TonnyTao/HowSwift
how_to_update_view_in_mvvm.playground/Sources/RxSwift/RxSwift/Observables/Take.swift
8
6365
// // Take.swift // RxSwift // // Created by Krunoslav Zaher on 6/12/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // extension ObservableType { /** Returns a specified number of contiguous elements from the start of an observable sequence. - seealso: [take operator on reactivex.io](http://reactivex.io/documentation/operators/take.html) - parameter count: The number of elements to return. - returns: An observable sequence that contains the specified number of elements from the start of the input sequence. */ public func take(_ count: Int) -> Observable<Element> { if count == 0 { return Observable.empty() } else { return TakeCount(source: self.asObservable(), count: count) } } } extension ObservableType { /** Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. - seealso: [take operator on reactivex.io](http://reactivex.io/documentation/operators/take.html) - parameter duration: Duration for taking elements from the start of the sequence. - parameter scheduler: Scheduler to run the timer on. - returns: An observable sequence with the elements taken during the specified duration from the start of the source sequence. */ public func take(for duration: RxTimeInterval, scheduler: SchedulerType) -> Observable<Element> { TakeTime(source: self.asObservable(), duration: duration, scheduler: scheduler) } /** Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. - seealso: [take operator on reactivex.io](http://reactivex.io/documentation/operators/take.html) - parameter duration: Duration for taking elements from the start of the sequence. - parameter scheduler: Scheduler to run the timer on. - returns: An observable sequence with the elements taken during the specified duration from the start of the source sequence. */ @available(*, deprecated, renamed: "take(for:scheduler:)") public func take(_ duration: RxTimeInterval, scheduler: SchedulerType) -> Observable<Element> { take(for: duration, scheduler: scheduler) } } // count version final private class TakeCountSink<Observer: ObserverType>: Sink<Observer>, ObserverType { typealias Element = Observer.Element typealias Parent = TakeCount<Element> private let parent: Parent private var remaining: Int init(parent: Parent, observer: Observer, cancel: Cancelable) { self.parent = parent self.remaining = parent.count super.init(observer: observer, cancel: cancel) } func on(_ event: Event<Element>) { switch event { case .next(let value): if self.remaining > 0 { self.remaining -= 1 self.forwardOn(.next(value)) if self.remaining == 0 { self.forwardOn(.completed) self.dispose() } } case .error: self.forwardOn(event) self.dispose() case .completed: self.forwardOn(event) self.dispose() } } } final private class TakeCount<Element>: Producer<Element> { private let source: Observable<Element> fileprivate let count: Int init(source: Observable<Element>, count: Int) { if count < 0 { rxFatalError("count can't be negative") } self.source = source self.count = count } override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { let sink = TakeCountSink(parent: self, observer: observer, cancel: cancel) let subscription = self.source.subscribe(sink) return (sink: sink, subscription: subscription) } } // time version final private class TakeTimeSink<Element, Observer: ObserverType> : Sink<Observer> , LockOwnerType , ObserverType , SynchronizedOnType where Observer.Element == Element { typealias Parent = TakeTime<Element> private let parent: Parent let lock = RecursiveLock() init(parent: Parent, observer: Observer, cancel: Cancelable) { self.parent = parent super.init(observer: observer, cancel: cancel) } func on(_ event: Event<Element>) { self.synchronizedOn(event) } func synchronized_on(_ event: Event<Element>) { switch event { case .next(let value): self.forwardOn(.next(value)) case .error: self.forwardOn(event) self.dispose() case .completed: self.forwardOn(event) self.dispose() } } func tick() { self.lock.performLocked { self.forwardOn(.completed) self.dispose() } } func run() -> Disposable { let disposeTimer = self.parent.scheduler.scheduleRelative((), dueTime: self.parent.duration) { _ in self.tick() return Disposables.create() } let disposeSubscription = self.parent.source.subscribe(self) return Disposables.create(disposeTimer, disposeSubscription) } } final private class TakeTime<Element>: Producer<Element> { typealias TimeInterval = RxTimeInterval fileprivate let source: Observable<Element> fileprivate let duration: TimeInterval fileprivate let scheduler: SchedulerType init(source: Observable<Element>, duration: TimeInterval, scheduler: SchedulerType) { self.source = source self.scheduler = scheduler self.duration = duration } override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { let sink = TakeTimeSink(parent: self, observer: observer, cancel: cancel) let subscription = sink.run() return (sink: sink, subscription: subscription) } }
mit
8b517c11fb088a79efd58f441032dbdd
31.974093
171
0.636864
4.906708
false
false
false
false
coderMONSTER/ioscelebrity
YStar/YStar/Scenes/Controller/BaseTabbarViewController.swift
1
4184
// // BaseTabbarViewController.swift // YStar // // Created by mu on 2017/7/4. // Copyright © 2017年 com.yundian. All rights reserved. // import UIKit class BaseTabbarViewController: UITabBarController,NIMLoginManagerDelegate,NIMConversationManagerDelegate,NIMSystemNotificationManagerDelegate { // 未读消息 private var sessionUnreadCount : Int = 0 // MARK: - 初始化 override func viewDidLoad() { super.viewDidLoad() let storyboardNames = ["Benifity","Fans","Meet"] let itemIconNames = ["\u{e65e}","\u{e65b}"] let titles = ["收益管理","联系粉丝","约见管理"] for (index, name) in storyboardNames.enumerated() { let storyboard = UIStoryboard.init(name: name, bundle: nil) let controller = storyboard.instantiateInitialViewController() if index == 2 { controller?.tabBarItem.title = titles[2] controller?.tabBarItem.image = UIImage(named: "meetManager_normal") controller?.tabBarItem.selectedImage = UIImage(named: "meetManager_selected") controller?.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.init(rgbHex: AppConst.ColorKey.main.rawValue)], for: .selected) } else { controller?.tabBarItem.title = titles[index] controller?.tabBarItem.image = UIImage.imageWith(itemIconNames[index], fontSize: CGSize.init(width: 22, height: 22), fontColor: UIColor.init(rgbHex: 0x999999)).withRenderingMode(.alwaysOriginal) controller?.tabBarItem.selectedImage = UIImage.imageWith(itemIconNames[index], fontSize: CGSize.init(width: 22, height: 22), fontColor: UIColor.init(rgbHex: AppConst.ColorKey.main.rawValue)).withRenderingMode(.alwaysOriginal) controller?.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.init(rgbHex: AppConst.ColorKey.main.rawValue)], for: .selected) } addChildViewController(controller!) } NotificationCenter.default.addObserver(self, selector: #selector(WYIMLoginSuccess( _ :)), name: Notification.Name(rawValue:AppConst.NoticeKey.WYIMLoginSuccess.rawValue), object: nil) NotificationCenter.default.addObserver(self, selector: #selector(showUpdateInfo), name: NSNotification.Name(rawValue: AppConst.NoticeKey.checkUpdte.rawValue), object: nil) } // MARK: - 网易云登录成功 func WYIMLoginSuccess(_ IMloginSuccess : NSNotification) { print("登陆成功") NIMSDK.shared().loginManager.add(self) NIMSDK.shared().conversationManager.add(self) NIMSDK.shared().systemNotificationManager.add(self) self.sessionUnreadCount = NIMSDK.shared().conversationManager.allUnreadCount() print("未读消息条数====\(self.sessionUnreadCount)") // 刷新红点 self.refreshSessionRedDot() } // 刷新是否显示红点 func refreshSessionRedDot() { if self.sessionUnreadCount == 0 { self.tabBar.hideBadgeOnItemIndex(index: 1) } else { self.tabBar.showshowBadgeOnItemIndex(index: 1) } } func didAdd(_ recentSession: NIMRecentSession, totalUnreadCount: Int) { self.sessionUnreadCount = totalUnreadCount self.refreshSessionRedDot() } func didUpdate(_ recentSession: NIMRecentSession, totalUnreadCount: Int) { self.sessionUnreadCount = totalUnreadCount self.refreshSessionRedDot() } func didRemove(_ recentSession: NIMRecentSession, totalUnreadCount: Int) { self.sessionUnreadCount = totalUnreadCount; self.refreshSessionRedDot() } func allMessagesDeleted() { self.sessionUnreadCount = 0 self.refreshSessionRedDot() } deinit { NIMSDK.shared().loginManager.remove(self) NIMSDK.shared().conversationManager.remove(self) NIMSDK.shared().systemNotificationManager.remove(self) NotificationCenter.default.removeObserver(self) } }
mit
57b758908d73d33e44558d0807aa1c8a
39.445545
237
0.665361
4.690011
false
false
false
false
groue/GRDB.swift
Tests/GRDBTests/AssociationHasOneSQLDerivationTests.swift
1
19827
import XCTest import GRDB // A <- B private struct A : TableRecord { static let databaseTableName = "a" static let b = hasOne(B.self) static let restrictedB = hasOne(RestrictedB.self) static let extendedB = hasOne(ExtendedB.self) } private struct B : TableRecord { static let a = belongsTo(A.self) static let databaseTableName = "b" } private struct RestrictedB : TableRecord { static let databaseTableName = "b" static let databaseSelection: [SQLSelectable] = [Column("name")] } private struct ExtendedB : TableRecord { static let databaseTableName = "b" static let databaseSelection: [SQLSelectable] = [AllColumns(), Column.rowID] } /// Test SQL generation class AssociationHasOneSQLDerivationTests: GRDBTestCase { override func setup(_ dbWriter: some DatabaseWriter) throws { try dbWriter.write { db in try db.create(table: "a") { t in t.column("id", .integer).primaryKey() } try db.create(table: "b") { t in t.column("id", .integer).primaryKey() t.column("aid", .integer).references("a") t.column("name", .text) } } } func testDefaultSelection() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in try assertEqualSQL(db, A.including(required: A.b), """ SELECT "a".*, "b".* \ FROM "a" \ JOIN "b" ON "b"."aid" = "a"."id" """) try assertEqualSQL(db, A.including(required: A.restrictedB), """ SELECT "a".*, "b"."name" \ FROM "a" \ JOIN "b" ON "b"."aid" = "a"."id" """) try assertEqualSQL(db, A.including(required: A.extendedB), """ SELECT "a".*, "b".*, "b"."rowid" \ FROM "a" \ JOIN "b" ON "b"."aid" = "a"."id" """) } } func testCustomSelection() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in do { let request = A.including(required: A.b .select(Column("name"))) try assertEqualSQL(db, request, """ SELECT "a".*, "b"."name" \ FROM "a" \ JOIN "b" ON "b"."aid" = "a"."id" """) } do { let request = A.including(required: A.b .select( AllColumns(), Column.rowID)) try assertEqualSQL(db, request, """ SELECT "a".*, "b".*, "b"."rowid" \ FROM "a" \ JOIN "b" ON "b"."aid" = "a"."id" """) } do { let aAlias = TableAlias() let request = A .aliased(aAlias) .including(required: A.b .select( Column("name"), (Column("id") + aAlias[Column("id")]).forKey("foo"))) try assertEqualSQL(db, request, """ SELECT "a".*, "b"."name", "b"."id" + "a"."id" AS "foo" \ FROM "a" \ JOIN "b" ON "b"."aid" = "a"."id" """) } } } func testFilteredAssociationImpactsJoinOnClause() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in do { let request = A.including(required: A.b.filter(Column("name") != nil)) try assertEqualSQL(db, request, """ SELECT "a".*, "b".* \ FROM "a" \ JOIN "b" ON ("b"."aid" = "a"."id") AND ("b"."name" IS NOT NULL) """) } do { let request = A.including(required: A.b.filter(key: 1)) try assertEqualSQL(db, request, """ SELECT "a".*, "b".* \ FROM "a" \ JOIN "b" ON ("b"."aid" = "a"."id") AND ("b"."id" = 1) """) } do { let request = A.including(required: A.b.filter(keys: [1, 2, 3])) try assertEqualSQL(db, request, """ SELECT "a".*, "b".* \ FROM "a" \ JOIN "b" ON ("b"."aid" = "a"."id") AND ("b"."id" IN (1, 2, 3)) """) } do { let request = A.including(required: A.b.filter(key: ["id": 1])) try assertEqualSQL(db, request, """ SELECT "a".*, "b".* \ FROM "a" \ JOIN "b" ON ("b"."aid" = "a"."id") AND ("b"."id" = 1) """) } do { let request = A.including(required: A.b.filter(keys: [["id": 1], ["id": 2]])) try assertEqualSQL(db, request, """ SELECT "a".*, "b".* \ FROM "a" \ JOIN "b" ON ("b"."aid" = "a"."id") AND (("b"."id" = 1) OR ("b"."id" = 2)) """) } do { let bAlias = TableAlias(name: "customB") let request = A.including(required: A.b .aliased(bAlias) .filter(sql: "customB.name = ?", arguments: ["foo"])) try assertEqualSQL(db, request, """ SELECT "a".*, "customB".* \ FROM "a" \ JOIN "b" "customB" ON ("customB"."aid" = "a"."id") AND (customB.name = 'foo') """) } } } func testFilterAssociationInWhereClause() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let bAlias = TableAlias() let request = A .including(required: A.b.aliased(bAlias)) .filter(bAlias[Column("name")] != nil) try assertEqualSQL(db, request, """ SELECT "a".*, "b".* \ FROM "a" \ JOIN "b" ON "b"."aid" = "a"."id" \ WHERE "b"."name" IS NOT NULL """) } } func testAssociationOrderBubbleUp() throws { let dbQueue = try makeDatabaseQueue() try dbQueue.inDatabase { db in let aBase = A.all().aliased(TableAlias(name: "a")) let abBase = A.b.aliased(TableAlias(name: "ab")) let abaBase = B.a.aliased(TableAlias(name: "aba")) let aTransforms = [ { (r: QueryInterfaceRequest<A>) in return r }, { (r: QueryInterfaceRequest<A>) in return r.order(Column("id")) }, { (r: QueryInterfaceRequest<A>) in return r.order(Column("id")).reversed() }, ] let abTransforms = [ { (r: HasOneAssociation<A, B>) in return r }, { (r: HasOneAssociation<A, B>) in return r.order(Column("name"), Column("id").desc) }, { (r: HasOneAssociation<A, B>) in return r.order(Column("name")).order(Column("id").desc) }, { (r: HasOneAssociation<A, B>) in return r.order(Column("name")).reversed() }, { (r: HasOneAssociation<A, B>) in return r.reversed() }, ] let abaTransforms = [ { (r: BelongsToAssociation<B, A>) in return r }, { (r: BelongsToAssociation<B, A>) in return r.order(Column("id")) }, { (r: BelongsToAssociation<B, A>) in return r.order(Column("id")).reversed() }, ] var sqls: [String] = [] for aTransform in aTransforms { for abTransform in abTransforms { for abaTransform in abaTransforms { let request = aTransform(aBase) .including(required: abTransform(abBase) .including(required: abaTransform(abaBase))) try sqls.append(request.build(db).sql) } } } let prefix = """ SELECT "a".*, "ab".*, "aba".* \ FROM "a" \ JOIN "b" "ab" ON "ab"."aid" = "a"."id" \ JOIN "a" "aba" ON "aba"."id" = "ab"."aid" """ let orderClauses = sqls.map { sql -> String in let prefixEndIndex = sql.index(sql.startIndex, offsetBy: prefix.count) return String(sql.suffix(from: prefixEndIndex)) } XCTAssertEqual(orderClauses, [ // a: { (r: QueryInterfaceRequest<A>) in return r }, // ab: { (r: BelongsToAssociation<A, B>) in return r } // aba: { (r: HasOneAssociation<B, A>) in return r } "", // aba: { (r: HasOneAssociation<B, A>) in return r.order(Column("id")) } " ORDER BY \"aba\".\"id\"", // aba: { (r: HasOneAssociation<B, A>) in return r.order(Column("id")).reversed() } " ORDER BY \"aba\".\"id\" DESC", // ab: { (r: BelongsToAssociation<A, B>) in return r.order(Column("name"), Column("id").desc) } // aba: { (r: HasOneAssociation<B, A>) in return r } " ORDER BY \"ab\".\"name\", \"ab\".\"id\" DESC", // aba: { (r: HasOneAssociation<B, A>) in return r.order(Column("id")) } " ORDER BY \"ab\".\"name\", \"ab\".\"id\" DESC, \"aba\".\"id\"", // aba: { (r: HasOneAssociation<B, A>) in return r.order(Column("id")).reversed() } " ORDER BY \"ab\".\"name\", \"ab\".\"id\" DESC, \"aba\".\"id\" DESC", // ab: { (r: BelongsToAssociation<A, B>) in return r.order(Column("name")).order(Column("id").desc) } // aba: { (r: HasOneAssociation<B, A>) in return r } " ORDER BY \"ab\".\"id\" DESC", // aba: { (r: HasOneAssociation<B, A>) in return r.order(Column("id")) } " ORDER BY \"ab\".\"id\" DESC, \"aba\".\"id\"", // aba: { (r: HasOneAssociation<B, A>) in return r.order(Column("id")).reversed() } " ORDER BY \"ab\".\"id\" DESC, \"aba\".\"id\" DESC", // ab: { (r: BelongsToAssociation<A, B>) in return r.order(Column("name")).reversed() } // aba: { (r: HasOneAssociation<B, A>) in return r } " ORDER BY \"ab\".\"name\" DESC", // aba: { (r: HasOneAssociation<B, A>) in return r.order(Column("id")) } " ORDER BY \"ab\".\"name\" DESC, \"aba\".\"id\" DESC", // aba: { (r: HasOneAssociation<B, A>) in return r.order(Column("id")).reversed() } " ORDER BY \"ab\".\"name\" DESC, \"aba\".\"id\"", // ab: { (r: BelongsToAssociation<A, B>) in return r.reversed() } // aba: { (r: HasOneAssociation<B, A>) in return r } "", // aba: { (r: HasOneAssociation<B, A>) in return r.order(Column("id")) } " ORDER BY \"aba\".\"id\" DESC", // aba: { (r: HasOneAssociation<B, A>) in return r.order(Column("id")).reversed() } " ORDER BY \"aba\".\"id\"", // a: { (r: QueryInterfaceRequest<A>) in return r.order(Column("id")) }, // ab: { (r: BelongsToAssociation<A, B>) in return r } // aba: { (r: HasOneAssociation<B, A>) in return r } " ORDER BY \"a\".\"id\"", // aba: { (r: HasOneAssociation<B, A>) in return r.order(Column("id")) } " ORDER BY \"a\".\"id\", \"aba\".\"id\"", // aba: { (r: HasOneAssociation<B, A>) in return r.order(Column("id")).reversed() } " ORDER BY \"a\".\"id\", \"aba\".\"id\" DESC", // ab: { (r: BelongsToAssociation<A, B>) in return r.order(Column("name"), Column("id").desc) } // aba: { (r: HasOneAssociation<B, A>) in return r } " ORDER BY \"a\".\"id\", \"ab\".\"name\", \"ab\".\"id\" DESC", // aba: { (r: HasOneAssociation<B, A>) in return r.order(Column("id")) } " ORDER BY \"a\".\"id\", \"ab\".\"name\", \"ab\".\"id\" DESC, \"aba\".\"id\"", // aba: { (r: HasOneAssociation<B, A>) in return r.order(Column("id")).reversed() } " ORDER BY \"a\".\"id\", \"ab\".\"name\", \"ab\".\"id\" DESC, \"aba\".\"id\" DESC", // ab: { (r: BelongsToAssociation<A, B>) in return r.order(Column("name")).order(Column("id").desc) } // aba: { (r: HasOneAssociation<B, A>) in return r } " ORDER BY \"a\".\"id\", \"ab\".\"id\" DESC", // aba: { (r: HasOneAssociation<B, A>) in return r.order(Column("id")) } " ORDER BY \"a\".\"id\", \"ab\".\"id\" DESC, \"aba\".\"id\"", // aba: { (r: HasOneAssociation<B, A>) in return r.order(Column("id")).reversed() } " ORDER BY \"a\".\"id\", \"ab\".\"id\" DESC, \"aba\".\"id\" DESC", // ab: { (r: BelongsToAssociation<A, B>) in return r.order(Column("name")).reversed() } // aba: { (r: HasOneAssociation<B, A>) in return r } " ORDER BY \"a\".\"id\", \"ab\".\"name\" DESC", // aba: { (r: HasOneAssociation<B, A>) in return r.order(Column("id")) } " ORDER BY \"a\".\"id\", \"ab\".\"name\" DESC, \"aba\".\"id\" DESC", // aba: { (r: HasOneAssociation<B, A>) in return r.order(Column("id")).reversed() } " ORDER BY \"a\".\"id\", \"ab\".\"name\" DESC, \"aba\".\"id\"", // ab: { (r: BelongsToAssociation<A, B>) in return r.reversed() } // aba: { (r: HasOneAssociation<B, A>) in return r } " ORDER BY \"a\".\"id\"", // aba: { (r: HasOneAssociation<B, A>) in return r.order(Column("id")) } " ORDER BY \"a\".\"id\", \"aba\".\"id\" DESC", // aba: { (r: HasOneAssociation<B, A>) in return r.order(Column("id")).reversed() } " ORDER BY \"a\".\"id\", \"aba\".\"id\"", // a: { (r: QueryInterfaceRequest<A>) in return r.order(Column("id")).reversed() } // ab: { (r: BelongsToAssociation<A, B>) in return r } // aba: { (r: HasOneAssociation<B, A>) in return r } " ORDER BY \"a\".\"id\" DESC", // aba: { (r: HasOneAssociation<B, A>) in return r.order(Column("id")) } " ORDER BY \"a\".\"id\" DESC, \"aba\".\"id\" DESC", // aba: { (r: HasOneAssociation<B, A>) in return r.order(Column("id")).reversed() } " ORDER BY \"a\".\"id\" DESC, \"aba\".\"id\"", // ab: { (r: BelongsToAssociation<A, B>) in return r.order(Column("name"), Column("id").desc) } // aba: { (r: HasOneAssociation<B, A>) in return r } " ORDER BY \"a\".\"id\" DESC, \"ab\".\"name\" DESC, \"ab\".\"id\" ASC", // aba: { (r: HasOneAssociation<B, A>) in return r.order(Column("id")) } " ORDER BY \"a\".\"id\" DESC, \"ab\".\"name\" DESC, \"ab\".\"id\" ASC, \"aba\".\"id\" DESC", // aba: { (r: HasOneAssociation<B, A>) in return r.order(Column("id")).reversed() } " ORDER BY \"a\".\"id\" DESC, \"ab\".\"name\" DESC, \"ab\".\"id\" ASC, \"aba\".\"id\"", // ab: { (r: BelongsToAssociation<A, B>) in return r.order(Column("name")).order(Column("id").desc) } // aba: { (r: HasOneAssociation<B, A>) in return r } " ORDER BY \"a\".\"id\" DESC, \"ab\".\"id\" ASC", // aba: { (r: HasOneAssociation<B, A>) in return r.order(Column("id")) } " ORDER BY \"a\".\"id\" DESC, \"ab\".\"id\" ASC, \"aba\".\"id\" DESC", // aba: { (r: HasOneAssociation<B, A>) in return r.order(Column("id")).reversed() } " ORDER BY \"a\".\"id\" DESC, \"ab\".\"id\" ASC, \"aba\".\"id\"", // ab: { (r: BelongsToAssociation<A, B>) in return r.order(Column("name")).reversed() } // aba: { (r: HasOneAssociation<B, A>) in return r } " ORDER BY \"a\".\"id\" DESC, \"ab\".\"name\"", // aba: { (r: HasOneAssociation<B, A>) in return r.order(Column("id")) } " ORDER BY \"a\".\"id\" DESC, \"ab\".\"name\", \"aba\".\"id\"", // aba: { (r: HasOneAssociation<B, A>) in return r.order(Column("id")).reversed() } " ORDER BY \"a\".\"id\" DESC, \"ab\".\"name\", \"aba\".\"id\" DESC", // ab: { (r: BelongsToAssociation<A, B>) in return r.reversed() } // aba: { (r: HasOneAssociation<B, A>) in return r } " ORDER BY \"a\".\"id\" DESC", // aba: { (r: HasOneAssociation<B, A>) in return r.order(Column("id")) } " ORDER BY \"a\".\"id\" DESC, \"aba\".\"id\"", // aba: { (r: HasOneAssociation<B, A>) in return r.order(Column("id")).reversed() } " ORDER BY \"a\".\"id\" DESC, \"aba\".\"id\" DESC", ]) } } // TODO: Test if and only if we really want to build an association from any request // func testAssociationFromRequest() throws { // let dbQueue = try makeDatabaseQueue() // try dbQueue.inDatabase { db in // do { // let bRequest = B // .filter(Column("name") != nil) // .order(Column("id")) // let association = A.hasOne(bRequest) // let request = A.including(required: association) // try assertEqualSQL(db, request, """ // SELECT "a".*, "b".* \ // FROM "a" \ // JOIN "b" ON ("b"."aid" = "a"."id") AND ("b"."name" IS NOT NULL) \ // ORDER BY "b"."id" // """) // } // do { // let bRequest = RestrictedB // .filter(Column("name") != nil) // .order(Column("id")) // let association = A.hasOne(bRequest) // let request = A.including(required: association) // try assertEqualSQL(db, request, """ // SELECT "a".*, "b"."name" \ // FROM "a" \ // JOIN "b" ON ("b"."aid" = "a"."id") AND ("b"."name" IS NOT NULL) \ // ORDER BY "b"."id" // """) // } // do { // let bRequest = ExtendedB // .select([Column("name")]) // .filter(Column("name") != nil) // .order(Column("id")) // let association = A.hasOne(bRequest) // let request = A.including(required: association) // try assertEqualSQL(db, request, """ // SELECT "a".*, "b"."name" \ // FROM "a" \ // JOIN "b" ON ("b"."aid" = "a"."id") AND ("b"."name" IS NOT NULL) \ // ORDER BY "b"."id" // """) // } // } // } }
mit
58a0931be78d7f0eae52a55eddb98919
48.691729
117
0.424673
4.019258
false
false
false
false
AlexSmet/ExtButtonProgress
ExtButtonProgress/Classes/ExtButtonProgress.swift
1
4937
// // ExtButtonProgress.swift // // // This simple extension adds a progress indicator to circular UIButton // // Use method showProgressIndicator( width:color:backgroundColor:) to begin show progress indicator // and method hideProgressIndicator() to hide indicator // // // Created by Alexander Smetannikov ([email protected]) on 17/03/2017. // Thanks to Evgeny Safronov // Copyright © 2017 AlexSmetannikov. All rights reserved. import UIKit public extension UIButton { class SHProgressIndicator: UIView { var width: CGFloat = 5.0 var color: UIColor = UIColor.darkGray var shadowColor: UIColor = UIColor.lightGray var animationDuration: CFTimeInterval = 3.0 private let indicatorLayer = CAShapeLayer() override init(frame: CGRect) { super.init(frame: frame) layer.addSublayer(indicatorLayer) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) layer.addSublayer(indicatorLayer) } private func setLayer(_ aLayer: CAShapeLayer, srokeColor: UIColor, background: UIColor, start: CGFloat, end: CGFloat) { aLayer.frame = self.bounds aLayer.path = UIBezierPath(ovalIn: aLayer.bounds.insetBy(dx: width / 2.0, dy: width / 2.0 )).cgPath aLayer.lineWidth = width aLayer.backgroundColor = background.cgColor aLayer.fillColor = background.cgColor aLayer.strokeColor = srokeColor.cgColor aLayer.strokeStart = start aLayer.strokeEnd = end aLayer.setAffineTransform(CGAffineTransform(rotationAngle: -(CGFloat.pi / 2.0))) } fileprivate func startAnimation() { // make animation setLayer(indicatorLayer, srokeColor: color, background: shadowColor, start: 0, end: 0) let strokeEndAnimation = CABasicAnimation(keyPath: "strokeEnd") strokeEndAnimation.fromValue = 0 strokeEndAnimation.toValue = 1 strokeEndAnimation.duration = animationDuration / 2 indicatorLayer.strokeEnd = 1 let strokeStartAnimation = CABasicAnimation(keyPath: "strokeStart") strokeStartAnimation.beginTime = strokeEndAnimation.duration strokeStartAnimation.fromValue = 0 strokeStartAnimation.toValue = 1 strokeStartAnimation.duration = animationDuration / 2 let group = CAAnimationGroup() group.animations = [strokeEndAnimation, strokeStartAnimation] group.duration = animationDuration group.autoreverses = false group.repeatCount = HUGE indicatorLayer.add(group, forKey: nil) } } private func indicator(frame: CGRect) -> UIView { let indicator = SHProgressIndicator(frame: frame) return indicator } // Show progress indicator. Just set width, foreground and background colors for progress indicator, and animation duration public func showProgressIndicator( width: CGFloat, color: UIColor, backgroundColor: UIColor, cycleDuration: CFTimeInterval = 3.0){ guard let superview = superview else { print("First of all add a button") return } if let _ = superview.subviews.index(where: {$0 is SHProgressIndicator}) { print("Indicator already exist") return } let buttonFrame = frame let indicatorFrame = CGRect(x: buttonFrame.minX, y: buttonFrame.minY, width: buttonFrame.width + width * 2, height: buttonFrame.height + width * 2) let indicator = self.indicator(frame: indicatorFrame) as! SHProgressIndicator indicator.center = center indicator.layer.cornerRadius = 0.5 * indicator.bounds.size.width indicator.clipsToBounds = true indicator.width = width indicator.color = color indicator.shadowColor = backgroundColor indicator.animationDuration = cycleDuration superview.addSubview(indicator) let indicatorIndex = superview.subviews.index(where: {$0 is SHProgressIndicator}) let buttonIndex = superview.subviews.index(where: {$0 == self}) superview.exchangeSubview(at: buttonIndex!, withSubviewAt: indicatorIndex!) indicator.startAnimation() } // Hide indicator public func hideProgressIndicator(){ if let indicator = superview?.subviews.first(where: {$0 is SHProgressIndicator}) { indicator.removeFromSuperview() } } public var isProgressIndicatorVisible: Bool { return superview?.subviews.first(where: {$0 is SHProgressIndicator}) != nil } }
mit
0d614662c97edf449965e6bdd803c6be
36.969231
155
0.632901
5.359392
false
false
false
false
TrustWallet/trust-wallet-ios
Trust/Lock/ViewControllers/LockEnterPasscodeViewController.swift
1
4316
// Copyright DApps Platform Inc. All rights reserved. import UIKit import LocalAuthentication final class LockEnterPasscodeViewController: LockPasscodeViewController { private lazy var lockEnterPasscodeViewModel: LockEnterPasscodeViewModel = { return self.model as! LockEnterPasscodeViewModel }() var unlockWithResult: ((_ success: Bool, _ bioUnlock: Bool) -> Void)? private var context: LAContext! override func viewDidLoad() { super.viewDidLoad() lockView.lockTitle.text = lockEnterPasscodeViewModel.initialLabelText } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) //If max attempt limit is reached we should valdiate if one minute gone. if lock.incorrectMaxAttemptTimeIsSet() { lockView.lockTitle.text = lockEnterPasscodeViewModel.tryAfterOneMinute maxAttemptTimerValidation() } else { showBiometricAuth() } } private func showBiometricAuth() { self.context = LAContext() self.touchValidation() } func cleanUserInput() { self.clearPasscode() } override func enteredPasscode(_ passcode: String) { super.enteredPasscode(passcode) if lock.isPasscodeValid(passcode: passcode) { lock.resetPasscodeAttemptHistory() lock.removeIncorrectMaxAttemptTime() self.lockView.lockTitle.text = lockEnterPasscodeViewModel.initialLabelText unlock(withResult: true, bioUnlock: false) } else { let numberOfAttempts = self.lock.numberOfAttempts() let passcodeAttemptLimit = model.passcodeAttemptLimit() let text = String(format: NSLocalizedString("lock.enter.passcode.view.model.incorrect.passcode", value: "Incorrect passcode. You have %d attempts left.", comment: ""), passcodeAttemptLimit - numberOfAttempts) lockView.lockTitle.text = text lockView.shake() if numberOfAttempts >= passcodeAttemptLimit { exceededLimit() return } self.lock.recordIncorrectPasscodeAttempt() } } private func exceededLimit() { self.lockView.lockTitle.text = lockEnterPasscodeViewModel.tryAfterOneMinute lock.recordIncorrectMaxAttemptTime() self.hideKeyboard() } private func maxAttemptTimerValidation() { // if there is no recordedMaxAttemptTime user has logged successfuly previous time guard let maxAttemptTimer = lock.recordedMaxAttemptTime() else { self.lockView.lockTitle.text = lockEnterPasscodeViewModel.initialLabelText self.showKeyboard() return } let now = Date() let interval = now.timeIntervalSince(maxAttemptTimer) //if interval is greater or equal 60 seconds we give 1 attempt. if interval >= 60 { self.lockView.lockTitle.text = lockEnterPasscodeViewModel.initialLabelText self.showKeyboard() } } private func unlock(withResult success: Bool, bioUnlock: Bool) { self.view.endEditing(true) if success { lock.removeAutoLockTime() } if let unlock = unlockWithResult { unlock(success, bioUnlock) } } private func canEvaluatePolicy() -> Bool { return context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil) } private func touchValidation() { guard canEvaluatePolicy() else { return } self.hideKeyboard() context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: lockEnterPasscodeViewModel.loginReason) { [weak self] success, _ in DispatchQueue.main.async { guard let `self` = self else { return } if success { self.lock.resetPasscodeAttemptHistory() self.lock.removeIncorrectMaxAttemptTime() self.lockView.lockTitle.text = self.lockEnterPasscodeViewModel.initialLabelText self.unlock(withResult: true, bioUnlock: true) } else { self.maxAttemptTimerValidation() } } } } }
gpl-3.0
d150150c37e8b68e8df9fbcecfcd017a
40.5
220
0.64481
5.131986
false
false
false
false
huang1988519/WechatArticles
WechatArticles/WechatArticles/Library/AwesomeCache/Cache.swift
1
10872
import Foundation /// Represents the expiry of a cached object public enum CacheExpiry { case Never case Seconds(NSTimeInterval) case Date(NSDate) } /// A generic cache that persists objects to disk and is backed by a NSCache. /// Supports an expiry date for every cached object. Expired objects are automatically deleted upon their next access via `objectForKey:`. /// If you want to delete expired objects, call `removeAllExpiredObjects`. /// /// Subclassing notes: This class fully supports subclassing. /// The easiest way to implement a subclass is to override `objectForKey` and `setObject:forKey:expires:`, /// e.g. to modify values prior to reading/writing to the cache. public class Cache<T: NSCoding> { public let name: String public let cacheDirectory: NSURL internal let cache = NSCache() // marked internal for testing private let fileManager = NSFileManager() private let diskWriteQueue: dispatch_queue_t = dispatch_queue_create("com.aschuch.cache.diskWriteQueue", DISPATCH_QUEUE_SERIAL) private let diskReadQueue: dispatch_queue_t = dispatch_queue_create("com.aschuch.cache.diskReadQueue", DISPATCH_QUEUE_SERIAL) // MARK: Initializers /// Designated initializer. /// /// - parameter name: Name of this cache /// - parameter directory: Objects in this cache are persisted to this directory. /// If no directory is specified, a new directory is created in the system's Caches directory /// /// - returns: A new cache with the given name and directory public init(name: String, directory: NSURL?) throws { self.name = name cache.name = name if let d = directory { cacheDirectory = d } else { let url = NSFileManager.defaultManager().URLsForDirectory(.CachesDirectory, inDomains: .UserDomainMask).first! cacheDirectory = url.URLByAppendingPathComponent("com.aschuch.cache/\(name)") } // Create directory on disk if needed try fileManager.createDirectoryAtURL(cacheDirectory, withIntermediateDirectories: true, attributes: nil) } /// Convenience Initializer /// /// - parameter name: Name of this cache /// /// - returns A new cache with the given name and the default cache directory public convenience init(name: String) throws { try self.init(name: name, directory: nil) } // MARK: Awesome caching /// Returns a cached object immediately or evaluates a cacheBlock. /// The cacheBlock will not be re-evaluated until the object is expired or manually deleted. /// If the cache already contains an object, the completion block is called with the cached object immediately. /// /// If no object is found or the cached object is already expired, the `cacheBlock` is called. /// You might perform any tasks (e.g. network calls) within this block. Upon completion of these tasks, /// make sure to call the `success` or `failure` block that is passed to the `cacheBlock`. /// The completion block is invoked as soon as the cacheBlock is finished and the object is cached. /// /// - parameter key: The key to lookup the cached object /// - parameter cacheBlock: This block gets called if there is no cached object or the cached object is already expired. /// The supplied success or failure blocks must be called upon completion. /// If the error block is called, the object is not cached and the completion block is invoked with this error. /// - parameter completion: Called as soon as a cached object is available to use. The second parameter is true if the object was already cached. public func setObjectForKey(key: String, cacheBlock: ((T, CacheExpiry) -> (), (NSError?) -> ()) -> (), completion: (T?, Bool, NSError?) -> ()) { if let object = objectForKey(key) { completion(object, true, nil) } else { let successBlock: (T, CacheExpiry) -> () = { (obj, expires) in self.setObject(obj, forKey: key, expires: expires) completion(obj, false, nil) } let failureBlock: (NSError?) -> () = { (error) in completion(nil, false, error) } cacheBlock(successBlock, failureBlock) } } // MARK: Get object /// Looks up and returns an object with the specified name if it exists. /// If an object is already expired, it is automatically deleted and `nil` will be returned. /// /// - parameter key: The name of the object that should be returned /// /// - returns: The cached object for the given name, or nil public func objectForKey(key: String) -> T? { var possibleObject: CacheObject? // Check if object exists in local cache possibleObject = cache.objectForKey(key) as? CacheObject if possibleObject == nil { // Try to load object from disk (synchronously) dispatch_sync(diskReadQueue) { let path = self.urlForKey(key).path! if self.fileManager.fileExistsAtPath(path) { possibleObject = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? CacheObject } } } // Check if object is not already expired and return // Delete object if expired if let object = possibleObject { if !object.isExpired() { return object.value as? T } else { removeObjectForKey(key) } } return nil } // MARK: Set object /// Adds a given object to the cache. /// The object is automatically marked as expired as soon as its expiry date is reached. /// /// - parameter object: The object that should be cached /// - parameter forKey: A key that represents this object in the cache /// - parameter expires: The CacheExpiry that indicates when the given object should be expired public func setObject(object: T, forKey key: String, expires: CacheExpiry = .Never) { setObject(object, forKey: key, expires: expires, completion: { }) } /// For internal testing only, might add this to the public API if needed internal func setObject(object: T, forKey key: String, expires: CacheExpiry = .Never, completion: () -> ()) { let expiryDate = expiryDateForCacheExpiry(expires) let cacheObject = CacheObject(value: object, expiryDate: expiryDate) // Set object in local cache cache.setObject(cacheObject, forKey: key) // Write object to disk (asyncronously) dispatch_async(diskWriteQueue) { let path = self.urlForKey(key).path! NSKeyedArchiver.archiveRootObject(cacheObject, toFile: path) completion() } } // MARK: Remove objects /// Removes an object from the cache. /// /// - parameter key: The key of the object that should be removed public func removeObjectForKey(key: String) { cache.removeObjectForKey(key) dispatch_async(diskWriteQueue) { let url = self.urlForKey(key) do { try self.fileManager.removeItemAtURL(url) } catch _ {} } } /// Removes all objects from the cache. /// /// - parameter completion: Called as soon as all cached objects are removed from disk. public func removeAllObjects(completion: (() -> Void)? = nil) { cache.removeAllObjects() dispatch_async(diskWriteQueue) { let keys = self.allKeys() for key in keys { let url = self.urlForKey(key) do { try self.fileManager.removeItemAtURL(url) } catch _ {} } dispatch_async(dispatch_get_main_queue()) { completion?() } } } // MARK: Remove Expired Objects /// Removes all expired objects from the cache. public func removeExpiredObjects() { dispatch_async(diskWriteQueue) { let keys = self.allKeys() for key in keys { // `objectForKey:` deletes the object if it is expired self.objectForKey(key) } } } // MARK: Subscripting public subscript(key: String) -> T? { get { return objectForKey(key) } set(newValue) { if let value = newValue { setObject(value, forKey: key) } else { removeObjectForKey(key) } } } // MARK: Private Helper private func allKeys() -> [String] { let urls = try? self.fileManager.contentsOfDirectoryAtURL(self.cacheDirectory, includingPropertiesForKeys: nil, options: []) return urls?.flatMap { $0.URLByDeletingPathExtension?.lastPathComponent } ?? [] } private func urlForKey(key: String) -> NSURL { let k = sanitizedKey(key) return cacheDirectory .URLByAppendingPathComponent(k) .URLByAppendingPathExtension("cache") } private func sanitizedKey(key: String) -> String { let regex = try! NSRegularExpression(pattern: "[^a-zA-Z0-9_]+", options: NSRegularExpressionOptions()) let range = NSRange(location: 0, length: key.characters.count) return regex.stringByReplacingMatchesInString(key, options: NSMatchingOptions(), range: range, withTemplate: "-") } private func expiryDateForCacheExpiry(expiry: CacheExpiry) -> NSDate { switch expiry { case .Never: return NSDate.distantFuture() case .Seconds(let seconds): return NSDate().dateByAddingTimeInterval(seconds) case .Date(let date): return date } } public func calculateDiskCacheSizeWithCompletionHandler(completionHandler: ((size: UInt) -> ())?) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in let diskCacheURL = self.cacheDirectory let resourceKeys = [NSURLIsDirectoryKey, NSURLTotalFileAllocatedSizeKey] var diskCacheSize: UInt = 0 if let fileEnumerator = self.fileManager.enumeratorAtURL(diskCacheURL, includingPropertiesForKeys: resourceKeys, options: NSDirectoryEnumerationOptions.SkipsHiddenFiles, errorHandler: nil), urls = fileEnumerator.allObjects as? [NSURL] { for fileURL in urls { do { let resourceValues = try fileURL.resourceValuesForKeys(resourceKeys) // If it is a Directory. Continue to next file URL. if let isDirectory = resourceValues[NSURLIsDirectoryKey]?.boolValue { if isDirectory { continue } } if let fileSize = resourceValues[NSURLTotalFileAllocatedSizeKey] as? NSNumber { diskCacheSize += fileSize.unsignedLongValue } } catch _ { } } } dispatch_async(dispatch_get_main_queue(), { () -> Void in if let completionHandler = completionHandler { completionHandler(size: diskCacheSize) } }) }) } }
apache-2.0
15bc89bf79a9109225092b4509976b41
35.361204
201
0.651122
4.452088
false
false
false
false
imjerrybao/FutureKit
FutureKit/Promise.swift
1
7830
// // Promise.swift // FutureKit // // Created by Michael Gray on 4/13/15. // 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 enum CancelRequestResponse { case DoNothing case CompleteWithCancel } public typealias CancelRequestHandler = ((force:Bool) -> CancelRequestResponse) public class Promise<T> { // Warning - reusing this lock for other purposes is danger when using LOCKING_STRATEGY.NSLock // don't read or write values on the Promise or Future internal var synchObject : SynchronizationProtocol { get { return future.synchObject } } public typealias CompletionErrorHandler = (() -> Void) public var future : Future<T> public init() { self.future = Future<T>() } public convenience init(automaticallyCancelAfter delay: NSTimeInterval) { self.init() self.automaticallyCancelAfter(delay) } public convenience init(automaticallyFailAfter delay: NSTimeInterval, error:ErrorType ) { self.init() self.automaticallyFailAfter(delay,error:error) } // untestable? public convenience init(automaticallyAssertAfter delay: NSTimeInterval, file : String = __FILE__, line : Int32 = __LINE__) { self.init() } public final func automaticallyCancelAfter(delay: NSTimeInterval) { self.automaticallyCancelOnRequestCancel() Executor.Default.executeAfterDelay(delay) { () -> Void in self.completeWithCancel() } } public final func automaticallyFailAfter(delay: NSTimeInterval, error:ErrorType) { self.automaticallyCancelOnRequestCancel() Executor.Default.executeAfterDelay(delay) { () -> Void in self.failIfNotCompleted(error) } } public final func automaticallyAssertOnFail(message:String, file : String = __FILE__, line : Int32 = __LINE__) { self.future.onFail { (error) -> Void in assertionFailure("\(message) on at:\(file):\(line)") return } } public final func onRequestCancel(executor:Executor, handler : (force:Bool) -> CancelRequestResponse) { let handler : (Bool) -> Void = { [weak self] (force) -> Void in switch handler(force: force) { case .CompleteWithCancel: self?.completeWithCancel() default: break } } let newHandler = Executor.Primary.callbackBlockFor(handler) self.future.addRequestHandler(newHandler) } public final func onRequestCancel(handler :(force:Bool) -> CancelRequestResponse) { self.onRequestCancel(.Primary, handler: handler) } public final func automaticallyCancelOnRequestCancel() { self.onRequestCancel { (force) -> CancelRequestResponse in return .CompleteWithCancel } } public final func complete(completion : Completion<T>) { self.future.completeWith(completion) } public final func completeWithSuccess(result : T) { self.future.completeWith(.Success(result)) } public final func completeWithFail(error : ErrorType) { self.future.completeWith(.Fail(error)) } public final func completeWithFail(errorMessage : String) { self.future.completeWith(Completion<T>(failWithErrorMessage: errorMessage)) } public final func completeWithException(e : NSException) { self.future.completeWith(Completion<T>(exception: e)) } public final func completeWithCancel(forced:Bool = false) { self.future.completeWith(.Cancelled(forced)) } public final func completeUsingFuture(f : Future<T>) { self.future.completeWith(.CompleteUsing(f)) } /* public final func completeWithThrowingBlock(block: () throws -> T) { do { let t = try block() self.completeWithSuccess(t) } catch { self.completeWithFail(error) } } */ /** completes the Future using the supplied completionBlock. the completionBlock will ONLY be executed if the future is successfully completed. If the future/promise has already been completed than the block will not be executed. if you need to know if the completion was successful, use 'completeWithBlocks()' - parameter completionBlock: a block that will run iff the future has not yet been completed. It must return a completion value for the promise. */ public final func completeWithBlock(completionBlock : ()->Completion<T>) { self.future.completeWithBlocks(waitUntilDone: false,completionBlock: completionBlock,onCompletionError: nil) } /** completes the Future using the supplied completionBlock. the completionBlock will ONLY be executed if the future has not yet been completed prior to this call. the onAlreadyCompleted will ONLY be executed if the future was already been completed prior to this call. These blocks may end up running inside any potential thread or queue, so avoid using external/shared memory. - parameter completionBlock: a block that will run iff the future has not yet been completed. It must return a completion value for the promise. - parameter onAlreadyCompleted: a block that will run iff the future has already been completed. */ public final func completeWithBlocks(completionBlock : () ->Completion<T>, onAlreadyCompleted : () -> Void) { self.future.completeWithBlocks(waitUntilDone: false,completionBlock: completionBlock, onCompletionError: onAlreadyCompleted) } public final func failIfNotCompleted(e : ErrorType) -> Bool { if (!self.isCompleted) { return self.future.completeWithSync(.Fail(e)) } return false } public final func failIfNotCompleted(errorMessage : String) -> Bool { if (!self.isCompleted) { return self.future.completeWithSync(Completion<T>(failWithErrorMessage: errorMessage)) } return false } public var isCompleted : Bool { get { return self.future.isCompleted } } // can return true if completion was successful. // can block the current thread public final func tryComplete(completion : Completion<T>) -> Bool { return self.future.completeWithSync(completion) } // execute a block if the completion "fails" because the future is already completed. public final func complete(completion : Completion<T>,onCompletionError errorBlock: CompletionErrorHandler) { self.future.completeWith(completion,onCompletionError:errorBlock) } }
mit
7d27559b6f71d6307b3e6cb646b74880
34.753425
149
0.675862
4.851301
false
false
false
false
exyte/Macaw-Examples
HealthStat/HealthStat/Views/TotalOfStepsView.swift
1
4501
import Macaw open class TotalOfStepsView: MacawView { private var barsGroup = Group() private var captionsGroup = Group() private var animations = [Animation]() private let barsValues = [3, 4, 6, 10, 5] private let barsCaptions = ["2,265", "6,412", "8,972", "12,355", "7,773"] private let barsCount = 5 private let barSegmentsCount = 10 private let barsSpacing = 20 private let segmentWidth = 40 private let segmentHeight = 10 private let segmentsSpacing = 10 private let emptyBarSegmentColor = Color.rgba(r: 255, g: 255, b: 255, a: 0.1) private let barSegmentColors = [ 0x359DDC, 0x5984C7, 0x5F81C5, 0x796EB6, 0xA3519E, 0xB54493, 0xC13C8D, 0xBF3D8E, 0xCC3385, 0xE42479 ].map { Color(val: $0) } private func createBars(centerX: Double, isEmpty: Bool) -> Group { let barsGroup = Group() barsGroup.place = Transform.move(dx: centerX, dy: 90) for barIndex in 0...barsCount - 1 { let barGroup = Group() barGroup.place = Transform.move(dx: Double((barsSpacing + segmentWidth) * barIndex), dy: 0) for segmentIndex in 0...barSegmentsCount - 1 { barGroup.contents.append(createSegment(segmentIndex: segmentIndex, isEmpty: isEmpty)) } barGroup.contents.reverse() barsGroup.contents.append(barGroup) } return barsGroup } private func createSegment(segmentIndex: Int, isEmpty: Bool) -> Shape { return Shape( form: RoundRect( rect: Rect( x: 0, y: Double((segmentHeight + segmentsSpacing) * segmentIndex), w: Double(segmentWidth), h: Double(segmentHeight) ), rx: Double(segmentHeight), ry: Double(segmentHeight) ), fill: isEmpty ? emptyBarSegmentColor : barSegmentColors[segmentIndex], opacity: isEmpty ? 1 : 0 ) } private func createScene() { let viewCenterX = Double(self.frame.width / 2) let text = Text( text: "Total of Steps", font: Font(name: "Serif", size: 24), fill: Color(val: 0xFFFFFF) ) text.align = .mid text.place = .move(dx: viewCenterX, dy: 30) let barsWidth = Double((segmentWidth * barsCount) + (barsSpacing * (barsCount - 1))) let barsCenterX = viewCenterX - barsWidth / 2 let barsBackgroundGroup = createBars(centerX: barsCenterX, isEmpty: true) barsGroup = createBars(centerX: barsCenterX, isEmpty: false) captionsGroup = Group() captionsGroup.place = Transform.move( dx: barsCenterX, dy: 100 + Double((segmentHeight + segmentsSpacing) * barSegmentsCount) ) for barIndex in 0...barsCount - 1 { let text = Text( text: barsCaptions[barIndex], font: Font(name: "Serif", size: 14), fill: Color(val: 0xFFFFFF) ) text.align = .mid text.place = .move(dx: Double((barsSpacing + segmentWidth) * barIndex + (segmentWidth / 2)), dy: 0) captionsGroup.contents.append(text) } self.node = [text, barsGroup, barsBackgroundGroup, captionsGroup].group() self.backgroundColor = UIColor(cgColor: Color(val: 0x5B2FA1).toCG()) } private func createAnimations() { animations.removeAll() barsGroup.contents.enumerated().forEach { nodeIndex, node in if let barGroup = node as? Group { let barSize = self.barsValues[nodeIndex] barGroup.contents.enumerated().forEach { barNodeIndex, barNode in if let segmentShape = barNode as? Shape, barNodeIndex <= barSize - 1 { let delay = Double(barNodeIndex) * 0.05 + Double(nodeIndex) * 0.1 self.animations.append( segmentShape.opacityVar.animation(from: 0, to: 1, during: 0.2, delay: delay) ) } } } } } open func play() { createScene() createAnimations() animations.forEach { $0.play() } } }
mit
8882cd958289cd3ca5a5abe7eee4eedc
34.164063
111
0.545212
4.307177
false
false
false
false
huonw/swift
test/SILGen/collection_subtype_upcast.swift
1
2010
// RUN: %target-swift-emit-silgen -module-name collection_subtype_upcast -enable-sil-ownership -sdk %S/Inputs %s | %FileCheck %s struct S { var x, y: Int } // CHECK-LABEL: sil hidden @$S25collection_subtype_upcast06array_C00D0SayypGSayAA1SVG_tF : // CHECK: bb0([[ARG:%.*]] : @guaranteed $Array<S>): // CHECK: debug_value [[ARG]] // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: // function_ref // CHECK: [[FN:%.*]] = function_ref @$Ss15_arrayForceCastySayq_GSayxGr0_lF // CHECK: [[BORROWED_ARG_COPY:%.*]] = begin_borrow [[ARG_COPY]] // CHECK: [[RESULT:%.*]] = apply [[FN]]<S, Any>([[BORROWED_ARG_COPY]]) : $@convention(thin) <τ_0_0, τ_0_1> (@guaranteed Array<τ_0_0>) -> @owned Array<τ_0_1> // CHECK: end_borrow [[BORROWED_ARG_COPY]] from [[ARG_COPY]] // CHECK: destroy_value [[ARG_COPY]] // CHECK: return [[RESULT]] func array_upcast(array: [S]) -> [Any] { return array } extension S : Hashable { var hashValue : Int { return x + y } } func ==(lhs: S, rhs: S) -> Bool { return true } // FIXME: This entrypoint name should not be bridging-specific // CHECK-LABEL: sil hidden @$S25collection_subtype_upcast05dict_C00D0s10DictionaryVyAA1SVypGAEyAGSiG_tF : // CHECK: bb0([[ARG:%.*]] : @guaranteed $Dictionary<S, Int>): // CHECK: debug_value [[ARG]] // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: // function_ref // CHECK: [[FN:%.*]] = function_ref @$Ss17_dictionaryUpCastys10DictionaryVyq0_q1_GACyxq_Gs8HashableRzsAFR0_r2_lF // CHECK: [[BORROWED_ARG_COPY:%.*]] = begin_borrow [[ARG_COPY]] // CHECK: [[RESULT:%.*]] = apply [[FN]]<S, Int, S, Any>([[BORROWED_ARG_COPY]]) : $@convention(thin) <τ_0_0, τ_0_1, τ_0_2, τ_0_3 where τ_0_0 : Hashable, τ_0_2 : Hashable> (@guaranteed Dictionary<τ_0_0, τ_0_1>) -> @owned Dictionary<τ_0_2, τ_0_3> // CHECK: destroy_value [[ARG_COPY]] // CHECK: return [[RESULT]] func dict_upcast(dict: [S: Int]) -> [S: Any] { return dict } // It's not actually possible to test this for Sets independent of // the bridging rules.
apache-2.0
aad5ae4b544f4fc35e7969ec226a2c23
42.391304
243
0.637275
2.884393
false
false
false
false
teambition/SwipeableTableViewCell
SwipeableTableViewCellExample/ExampleMenuViewController.swift
1
1800
// // ExampleMenuViewController.swift // SwipeableTableViewCellExample // // Created by 洪鑫 on 16/6/5. // Copyright © 2016年 Teambition. All rights reserved. // import UIKit class ExampleMenuViewController: UITableViewController { // MARK: - Life cycle override func viewDidLoad() { super.viewDidLoad() navigationItem.title = "SwipeableTableViewCell" tableView.separatorColor = UIColor(white: 0.1, alpha: 0.1) } // MARK: - Table view data source and delegate override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 2 } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 70 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCell(withIdentifier: "Cell") if cell == nil { cell = UITableViewCell(style: .default, reuseIdentifier: "Cell") } switch indexPath.row { case 0: cell?.textLabel?.text = "Styles Example" case 1: cell?.textLabel?.text = "BackgroundView Example" default: break } return cell! } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { switch indexPath.row { case 0: performSegue(withIdentifier: "ShowStylesExampleViewController", sender: self) case 1: performSegue(withIdentifier: "ShowBackgroundViewExampleViewController", sender: self) default: break } } }
mit
41b251c499603c37b231a5c112dfec73
29.913793
109
0.641941
5.09375
false
false
false
false
Fortyfox/DZImageView
Pod/Classes/DZImageView.swift
1
7237
// // DZImageView.swift // Pods // // Created by Melvin Beemer on 12/4/15. // // import UIKit public class DZImageView: UIView { // Public vars public var animationDuration: NSTimeInterval = 0.3 // Internal and private vars var image: UIImage! private var imageView: UIImageView! override init(frame: CGRect) { super.init(frame: frame) } public convenience init(image: UIImage, frame: CGRect) { self.init(frame: frame) commonInit() self.image = image self.imageView.image = image } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func commonInit() { self.clipsToBounds = true self.contentMode = UIViewContentMode.ScaleAspectFill if imageView == nil { imageView = UIImageView(frame: self.frame) imageView.contentMode = UIViewContentMode.ScaleAspectFill self.addSubview(imageView) } } private func updateView() { if self.bounds.size.width == 0 || self.bounds.size.height == 0 || image.size.width == 0 || image.size.height == 0 { return } switch self.contentMode { case .ScaleAspectFit: updateViewToAspectFit() break case .ScaleAspectFill: updateViewToAspectFill() break case .ScaleToFill: updateViewToScaleToFill() break case .Center: updateViewToCenter() break case .Bottom: updateViewToBottom() break case .BottomLeft: updateViewToBottomLeft() break case .BottomRight: updateViewToBottomRight() break case .Left: updateViewToLeft() break case .Right: updateViewToRight() break case .Top: updateViewToTop() break case .TopLeft: updateViewToTopLeft() break case .TopRight: updateViewToTopRight() break case .Redraw: updateViewToScaleToFill() break } } private func updateViewToAspectFit() { guard let image = imageView.image else { return } var imageSize = CGSizeMake(image.size.width / image.scale, image.size.height / image.scale) let widthRatio = imageSize.width / self.bounds.size.width let heightRatio = imageSize.height / self.bounds.size.height let imageScaleRatio = max(widthRatio, heightRatio) imageSize = CGSizeMake(imageSize.width / imageScaleRatio, imageSize.height / imageScaleRatio) imageView.bounds = CGRectMake(0, 0, imageSize.width, imageSize.height) centerImageViewToSuperView() } private func updateViewToAspectFill() { var imageSize = CGSizeMake(imageView.image!.size.width / imageView.image!.scale, imageView.image!.size.height / imageView.image!.scale) let widthRatio = imageSize.width / self.bounds.size.width let heightRatio = imageSize.height / self.bounds.size.height let imageScaleRatio = min(widthRatio, heightRatio) imageSize = CGSizeMake(imageSize.width / imageScaleRatio, imageSize.height / imageScaleRatio) imageView.bounds = CGRectMake(0, 0, imageSize.width, imageSize.height) centerImageViewToSuperView() } private func updateViewToScaleToFill() { imageView.bounds = CGRectMake(0, 0, self.bounds.size.width, self.bounds.size.height) centerImageViewToSuperView() } private func updateViewToCenter() { fitImageViewSizeToImageSize() centerImageViewToSuperView() } private func updateViewToBottom() { fitImageViewSizeToImageSize() imageView.center = CGPointMake(self.bounds.size.width / 2, self.bounds.size.height - image.size.height / 2) } private func updateViewToBottomLeft() { fitImageViewSizeToImageSize() imageView.center = CGPointMake(image.size.width / 2, self.bounds.size.height - image.size.height / 2) } private func updateViewToBottomRight() { fitImageViewSizeToImageSize() imageView.center = CGPointMake(self.bounds.size.width - image.size.width / 2, self.bounds.size.height - image.size.height / 2) } private func updateViewToLeft() { fitImageViewSizeToImageSize() imageView.center = CGPointMake(image.size.width / 2, self.bounds.size.height / 2) } private func updateViewToRight() { fitImageViewSizeToImageSize() imageView.center = CGPointMake(self.bounds.size.width - image.size.width / 2, self.bounds.size.height / 2) } private func updateViewToTop() { fitImageViewSizeToImageSize() imageView.center = CGPointMake(self.bounds.size.width / 2, image.size.height / 2) } private func updateViewToTopLeft() { fitImageViewSizeToImageSize() imageView.center = CGPointMake(image.size.width / 2, image.size.height / 2) } private func updateViewToTopRight() { fitImageViewSizeToImageSize() imageView.center = CGPointMake(self.bounds.size.width - image.size.width / 2, image.size.height / 2) } // MARK: - Helper Methods private func fitImageViewSizeToImageSize() { guard let image = imageView.image else { return } let imageSize = CGSizeMake(image.size.width / image.scale, image.size.height / image.scale) imageView.bounds = CGRectMake(0, 0, imageSize.width, imageSize.height) } private func centerImageViewToSuperView() { imageView.center = CGPointMake(self.bounds.size.width / 2, self.bounds.size.height / 2) } } public extension DZImageView { public func animateImageViewTo(contentMode: UIViewContentMode, frame: CGRect) { UIView.animateWithDuration(animationDuration, delay: 0, usingSpringWithDamping: 0.9, initialSpringVelocity: 1, options: .CurveEaseInOut, animations: { () -> Void in self.frame = frame self.contentMode = contentMode self.updateView() }, completion: nil) } public func animateImageViewContentModeTo(contentMode: UIViewContentMode) { UIView.animateWithDuration(animationDuration, delay: 0, usingSpringWithDamping: 0.9, initialSpringVelocity: 1, options: .CurveEaseInOut, animations: { () -> Void in self.contentMode = contentMode self.updateView() }, completion: nil) } public func animateImageViewFrameTo(frame: CGRect) { UIView.animateWithDuration(animationDuration, delay: 0, usingSpringWithDamping: 0.9, initialSpringVelocity: 1, options: .CurveEaseInOut, animations: { () -> Void in self.frame = frame self.updateView() }, completion: nil) } public func presentationImageSize() -> CGSize { return imageView.bounds.size } }
mit
a48470dc083902f70b51832a0d5e5190
32.660465
172
0.624706
4.906441
false
false
false
false
cocoatoucher/AIFlatSwitch
Sources/AIFlatSwitch.swift
1
17356
// // AIFlatSwitch.swift // AIFlatSwitch // // Created by cocoatoucher on 11/02/15. // Copyright (c) 2015 cocoatoucher. All rights reserved. // import UIKit /** A flat design switch alternative to UISwitch */ @IBDesignable open class AIFlatSwitch: UIControl { // MARK: - Public /** Line width for the circle, trail and checkmark parts of the switch. */ @IBInspectable open var lineWidth: CGFloat = 2.0 { didSet { self.circle.lineWidth = lineWidth self.checkmark.lineWidth = lineWidth self.trailCircle.lineWidth = lineWidth } } /** Set to false if the selection should not be animated with touch up inside events. */ @IBInspectable open var animatesOnTouch: Bool = true /** Stroke color for circle and checkmark. Circle disappears and trail becomes visible when the switch is selected. */ @IBInspectable open var strokeColor: UIColor = UIColor.black { didSet { self.circle.strokeColor = strokeColor.cgColor self.checkmark.strokeColor = strokeColor.cgColor } } /** Stroke color for trail. Trail disappears and circle becomes visible when the switch is deselected. */ @IBInspectable open var trailStrokeColor: UIColor = UIColor.gray { didSet { self.trailCircle.strokeColor = trailStrokeColor.cgColor } } /** Color for the inner circle. */ @IBInspectable open var backgroundLayerColor: UIColor = UIColor.clear { didSet { self.backgroundLayer.fillColor = backgroundLayerColor.cgColor } } /** Overrides isSelected from UIControl using internal state flag. Default value is false. */ @IBInspectable open override var isSelected: Bool { get { return isSelectedInternal } set { super.isSelected = newValue self.setSelected(newValue, animated: false) } } /** Called when selection animation started Either when selecting or deselecting */ public var selectionAnimationDidStart: ((_ isSelected: Bool) -> Void)? /** Called when selection animation stopped Either when selecting or deselecting */ public var selectionAnimationDidStop: ((_ isSelected: Bool) -> Void)? public override init(frame: CGRect) { super.init(frame: frame) // Configure switch when created with frame self.configure() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) // Configure switch when created from xib self.configure() } /** Switches between selected and deselected state. Use this method to programmatically change the value of selected state. - Parameter isSelected: Whether the switch should be selected or not - Parameter animated: Whether the transition should be animated or not */ open func setSelected(_ isSelected: Bool, animated: Bool) { self.isSelectedInternal = isSelected // Remove all animations before switching to new state checkmark.removeAllAnimations() circle.removeAllAnimations() trailCircle.removeAllAnimations() // Reset sublayer values self.resetLayerValues(self.isSelectedInternal, stateWillBeAnimated: animated) // Animate to new state if animated { self.addAnimations(desiredSelectedState: isSelectedInternal) self.accessibilityValue = isSelected ? "checked" : "unchecked" } } open override func layoutSublayers(of layer: CALayer) { super.layoutSublayers(of: layer) guard layer == self.layer else { return } var offset: CGPoint = CGPoint.zero let radius = fmin(self.bounds.width, self.bounds.height) / 2 - (lineWidth / 2) offset.x = (self.bounds.width - radius * 2) / 2.0 offset.y = (self.bounds.height - radius * 2) / 2.0 CATransaction.begin() CATransaction.setDisableActions(true) // Calculate frame for circle and trail circle let circleAndTrailFrame = CGRect(x: offset.x, y: offset.y, width: radius * 2, height: radius * 2) let circlePath = UIBezierPath(ovalIn: circleAndTrailFrame) trailCircle.path = circlePath.cgPath circle.transform = CATransform3DIdentity circle.frame = self.bounds circle.path = UIBezierPath(ovalIn: circleAndTrailFrame).cgPath // Rotating circle by 212 degrees to be able to manipulate stroke end location. circle.transform = CATransform3DMakeRotation(CGFloat(212 * Double.pi / 180), 0, 0, 1) let origin = CGPoint(x: offset.x + radius, y: offset.y + radius) // Calculate checkmark path let checkmarkPath = UIBezierPath() var checkmarkStartPoint = CGPoint.zero // Checkmark will start from circle's stroke end calculated above. checkmarkStartPoint.x = origin.x + radius * CGFloat(cos(212 * Double.pi / 180)) checkmarkStartPoint.y = origin.y + radius * CGFloat(sin(212 * Double.pi / 180)) checkmarkPath.move(to: checkmarkStartPoint) self.checkmarkSplitPoint = CGPoint(x: offset.x + radius * 0.9, y: offset.y + radius * 1.4) checkmarkPath.addLine(to: self.checkmarkSplitPoint) var checkmarkEndPoint = CGPoint.zero // Checkmark will end 320 degrees location of the circle layer. checkmarkEndPoint.x = origin.x + radius * CGFloat(cos(320 * Double.pi / 180)) checkmarkEndPoint.y = origin.y + radius * CGFloat(sin(320 * Double.pi / 180)) checkmarkPath.addLine(to: checkmarkEndPoint) checkmark.frame = self.bounds checkmark.path = checkmarkPath.cgPath let innerCircleRadius = fmin(self.bounds.width, self.bounds.height) / 2.1 - (lineWidth / 2.1) offset.x = (self.bounds.width - innerCircleRadius * 2) / 2.0 offset.y = (self.bounds.height - innerCircleRadius * 2) / 2.0 backgroundLayer.path = UIBezierPath(ovalIn: CGRect(x: offset.x, y: offset.y, width: innerCircleRadius * 2, height: innerCircleRadius * 2)).cgPath CATransaction.commit() } // MARK: - Private /** Animation duration for the whole selection transition */ private let animationDuration: CFTimeInterval = 0.3 /** Percentage where the checkmark tail ends */ private let finalStrokeEndForCheckmark: CGFloat = 0.85 /** Percentage where the checkmark head begins */ private let finalStrokeStartForCheckmark: CGFloat = 0.3 /** Percentage of the bounce amount of checkmark near animation completion */ private let checkmarkBounceAmount: CGFloat = 0.1 /** Internal flag to keep track of selected state. */ private var isSelectedInternal: Bool = false /** Trail layer. Trail is the circle which appears when the switch is in deselected state. */ private var trailCircle: CAShapeLayer = CAShapeLayer() /** Circle layer. Circle appears when the switch is in selected state. */ private var circle: CAShapeLayer = CAShapeLayer() /** Checkmark layer. Checkmark appears when the switch is in selected state. */ private var checkmark: CAShapeLayer = CAShapeLayer() /** circleLayer, is the layer which appears inside the circle. */ private var backgroundLayer: CAShapeLayer = CAShapeLayer() /** Middle point of the checkmark layer. Calculated each time the sublayers are layout. */ private var checkmarkSplitPoint: CGPoint = CGPoint.zero /** Configures circle, trail and checkmark layers after initialization. Setups switch with the default selection state. Configures target for tocuh up inside event for triggering selection. */ private func configure() { func configureShapeLayer(_ shapeLayer: CAShapeLayer) { shapeLayer.lineJoin = CAShapeLayerLineJoin.round shapeLayer.lineCap = CAShapeLayerLineCap.round shapeLayer.lineWidth = self.lineWidth shapeLayer.fillColor = UIColor.clear.cgColor self.layer.addSublayer(shapeLayer) } // Setup layers self.layer.addSublayer(backgroundLayer) backgroundLayer.fillColor = backgroundLayerColor.cgColor configureShapeLayer(trailCircle) trailCircle.strokeColor = trailStrokeColor.cgColor configureShapeLayer(circle) circle.strokeColor = strokeColor.cgColor configureShapeLayer(checkmark) checkmark.strokeColor = strokeColor.cgColor // Setup initial state self.setSelected(false, animated: false) // Add target for handling touch up inside event as a default manner self.addTarget(self, action: #selector(AIFlatSwitch.handleTouchUpInside), for: UIControl.Event.touchUpInside) } /** Switches between selected and deselected state with touch up inside events. Set animatesOnTouch to false to disable animation on touch. Send valueChanged event as a result. */ @objc private func handleTouchUpInside() { self.setSelected(!self.isSelected, animated: self.animatesOnTouch) self.sendActions(for: UIControl.Event.valueChanged) } /** Switches layer values to selected or deselected state without any animation. If the there is going to be an animation(stateWillBeAnimated parameter is true), then the layer values are reset to reverse of the desired state value to provide the transition for animation. - Parameter desiredSelectedState: Desired selection state for the reset to handle - Parameter stateWillBeAnimated: If the reset should prepare the layers for animation */ private func resetLayerValues(_ desiredSelectedState: Bool, stateWillBeAnimated: Bool) { CATransaction.begin() CATransaction.setDisableActions(true) if (desiredSelectedState && stateWillBeAnimated) || (desiredSelectedState == false && stateWillBeAnimated == false) { // Switch to deselected state checkmark.strokeEnd = 0.0 checkmark.strokeStart = 0.0 trailCircle.opacity = 0.0 circle.strokeStart = 0.0 circle.strokeEnd = 1.0 } else { // Switch to selected state checkmark.strokeEnd = finalStrokeEndForCheckmark checkmark.strokeStart = finalStrokeStartForCheckmark trailCircle.opacity = 1.0 circle.strokeStart = 0.0 circle.strokeEnd = 0.0 } CATransaction.commit() } /** Animates the selected state transition. - Parameter desiredSelectedState: Desired selection state for the animation to handle */ private func addAnimations(desiredSelectedState selected: Bool) { let circleAnimationDuration = animationDuration * 0.5 let checkmarkEndDuration = animationDuration * 0.8 let checkmarkStartDuration = checkmarkEndDuration - circleAnimationDuration let checkmarkBounceDuration = animationDuration - checkmarkEndDuration let checkmarkAnimationGroup = CAAnimationGroup() checkmarkAnimationGroup.isRemovedOnCompletion = false checkmarkAnimationGroup.fillMode = CAMediaTimingFillMode.forwards checkmarkAnimationGroup.duration = animationDuration checkmarkAnimationGroup.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.linear) let checkmarkStrokeEndAnimation = CAKeyframeAnimation(keyPath: "strokeEnd") checkmarkStrokeEndAnimation.duration = checkmarkEndDuration + checkmarkBounceDuration checkmarkStrokeEndAnimation.isRemovedOnCompletion = false checkmarkStrokeEndAnimation.fillMode = CAMediaTimingFillMode.forwards checkmarkStrokeEndAnimation.calculationMode = CAAnimationCalculationMode.paced if selected { checkmarkStrokeEndAnimation.values = [NSNumber(value: 0.0 as Float), NSNumber(value: Float(finalStrokeEndForCheckmark + checkmarkBounceAmount) as Float), NSNumber(value: Float(finalStrokeEndForCheckmark) as Float)] checkmarkStrokeEndAnimation.keyTimes = [NSNumber(value: 0.0 as Double), NSNumber(value: checkmarkEndDuration as Double), NSNumber(value: checkmarkEndDuration + checkmarkBounceDuration as Double)] } else { checkmarkStrokeEndAnimation.values = [NSNumber(value: Float(finalStrokeEndForCheckmark) as Float), NSNumber(value: Float(finalStrokeEndForCheckmark + checkmarkBounceAmount) as Float), NSNumber(value: -0.1 as Float)] checkmarkStrokeEndAnimation.keyTimes = [NSNumber(value: 0.0 as Double), NSNumber(value: checkmarkBounceDuration as Double), NSNumber(value: checkmarkEndDuration + checkmarkBounceDuration as Double)] } let checkmarkStrokeStartAnimation = CAKeyframeAnimation(keyPath: "strokeStart") checkmarkStrokeStartAnimation.duration = checkmarkStartDuration + checkmarkBounceDuration checkmarkStrokeStartAnimation.isRemovedOnCompletion = false checkmarkStrokeStartAnimation.fillMode = CAMediaTimingFillMode.forwards checkmarkStrokeStartAnimation.calculationMode = CAAnimationCalculationMode.paced if selected { checkmarkStrokeStartAnimation.values = [NSNumber(value: 0.0 as Float), NSNumber(value: Float(finalStrokeStartForCheckmark + checkmarkBounceAmount) as Float), NSNumber(value: Float(finalStrokeStartForCheckmark) as Float)] checkmarkStrokeStartAnimation.keyTimes = [NSNumber(value: 0.0 as Double), NSNumber(value: checkmarkStartDuration as Double), NSNumber(value: checkmarkStartDuration + checkmarkBounceDuration as Double)] } else { checkmarkStrokeStartAnimation.values = [NSNumber(value: Float(finalStrokeStartForCheckmark) as Float), NSNumber(value: Float(finalStrokeStartForCheckmark + checkmarkBounceAmount) as Float), NSNumber(value: 0.0 as Float)] checkmarkStrokeStartAnimation.keyTimes = [NSNumber(value: 0.0 as Double), NSNumber(value: checkmarkBounceDuration as Double), NSNumber(value: checkmarkStartDuration + checkmarkBounceDuration as Double)] } if selected { checkmarkStrokeStartAnimation.beginTime = circleAnimationDuration } checkmarkAnimationGroup.animations = [checkmarkStrokeEndAnimation, checkmarkStrokeStartAnimation] checkmark.add(checkmarkAnimationGroup, forKey: "checkmarkAnimation") let circleAnimationGroup = CAAnimationGroup() circleAnimationGroup.duration = animationDuration circleAnimationGroup.isRemovedOnCompletion = false circleAnimationGroup.fillMode = CAMediaTimingFillMode.forwards circleAnimationGroup.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.linear) let circleStrokeEnd = CABasicAnimation(keyPath: "strokeEnd") circleStrokeEnd.duration = circleAnimationDuration if selected { circleStrokeEnd.beginTime = 0.0 circleStrokeEnd.fromValue = NSNumber(value: 1.0 as Float) circleStrokeEnd.toValue = NSNumber(value: -0.1 as Float) } else { circleStrokeEnd.beginTime = animationDuration - circleAnimationDuration circleStrokeEnd.fromValue = NSNumber(value: 0.0 as Float) circleStrokeEnd.toValue = NSNumber(value: 1.0 as Float) } circleStrokeEnd.isRemovedOnCompletion = false circleStrokeEnd.fillMode = CAMediaTimingFillMode.forwards circleAnimationGroup.animations = [circleStrokeEnd] circleAnimationGroup.delegate = self circle.add(circleAnimationGroup, forKey: "circleStrokeEnd") let trailCircleColor = CABasicAnimation(keyPath: "opacity") trailCircleColor.duration = animationDuration if selected { trailCircleColor.fromValue = NSNumber(value: 0.0 as Float) trailCircleColor.toValue = NSNumber(value: 1.0 as Float) } else { trailCircleColor.fromValue = NSNumber(value: 1.0 as Float) trailCircleColor.toValue = NSNumber(value: 0.0 as Float) } trailCircleColor.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.linear) trailCircleColor.fillMode = CAMediaTimingFillMode.forwards trailCircleColor.isRemovedOnCompletion = false trailCircle.add(trailCircleColor, forKey: "trailCircleColor") } } extension AIFlatSwitch: CAAnimationDelegate { public func animationDidStart(_ anim: CAAnimation) { selectionAnimationDidStart?(isSelectedInternal) } public func animationDidStop(_ anim: CAAnimation, finished flag: Bool) { selectionAnimationDidStop?(isSelectedInternal) } }
mit
3f99c73b89691db13022c13fa29f2407
41.643735
232
0.675847
5.322294
false
false
false
false
natangr/KohanaTextField
KohanaTextField/KohanaTextField.swift
1
9875
// // KohanaTextField.swift // KohanaTextField // // Created by Natan Grando on 3/30/17. // Copyright © 2017. All rights reserved. // import UIKit @IBDesignable public class KohanaTextField: UIView { private var imageView: UIImageView? private var placeholderLabel: UILabel? private var textField: UITextField? private var toggleSecureTextButton: UIButton? public var textFieldDelegate: UITextFieldDelegate? fileprivate var placeholderVisible: Bool = true { willSet { if placeholderVisible != newValue { newValue ? showPlaceholder(animated: true) : hidePlaceholder(animated: true) } } } @IBInspectable public var image: UIImage? { didSet { imageView?.image = image } } @IBInspectable public var text: String? { set { textField?.text = newValue if (text?.isEmpty ?? true) { showPlaceholder(animated: false) } else { hidePlaceholder(animated: false) } } get { return textField?.text } } @IBInspectable public var textColor: UIColor = UIColor(red: 75/255, green: 68/255, blue: 54/255, alpha: 1) { didSet { textField?.textColor = textColor } } @IBInspectable public var textFontSize: CGFloat = 15 { didSet { textField?.font = UIFont.systemFont(ofSize: textFontSize) } } @IBInspectable public var placeholder: String? { didSet { placeholderLabel?.text = placeholder } } @IBInspectable public var placeholderTextColor: UIColor = UIColor(red: 168/255, green: 164/255, blue: 155/255, alpha: 1) { didSet { placeholderLabel?.textColor = placeholderTextColor } } @IBInspectable public var placeholderTextFontSize: CGFloat = 15 { didSet { placeholderLabel?.font = UIFont.systemFont(ofSize: placeholderTextFontSize) } } @IBInspectable public var borderColor: UIColor = UIColor(red: 233/255, green: 232/255, blue: 229/255, alpha: 1) { didSet { layer.borderColor = borderColor.cgColor } } @IBInspectable public var borderRadius: CGFloat = 4 { didSet { layer.borderWidth = borderRadius } } @IBInspectable public var isSecureTextEntry: Bool = false { didSet { textField?.isSecureTextEntry = isSecureTextEntry let title = isSecureTextEntry ? showText : hideText toggleSecureTextButton?.setTitle(title, for: .normal) setNeedsLayout() } } @IBInspectable public var toggleSecureTextButtonVisible: Bool = false { didSet { if toggleSecureTextButtonVisible { initToggleSecureTextButton() } else { toggleSecureTextButton?.removeFromSuperview() } } } @IBInspectable public var toggleSecureTextButtonFontSize: CGFloat = 10 { didSet { toggleSecureTextButton?.titleLabel?.font = UIFont.systemFont(ofSize: toggleSecureTextButtonFontSize) } } @IBInspectable public var showText: String = "SHOW" @IBInspectable public var hideText: String = "HIDE" override init(frame: CGRect) { super.init(frame: frame) commonInit() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } override public func layoutSubviews() { super.layoutSubviews() let placeholderRect = CGRect(x: 12, y: bounds.height/2 - 10, width: bounds.width - 24, height: 20) placeholderLabel?.frame = placeholderRect let imageViewRect = CGRect(x: 12, y: bounds.height/2 - 10, width: 20, height: 20) imageView?.frame = imageViewRect if toggleSecureTextButtonVisible { toggleSecureTextButton?.sizeToFit() let buttonWidth = toggleSecureTextButton?.bounds.width ?? 0 let buttonRect = CGRect(x: bounds.width - buttonWidth - 12, y: 0, width: buttonWidth, height: bounds.height) toggleSecureTextButton?.frame = buttonRect let textFieldRect = CGRect(x: 44, y: 0, width: bounds.width - 68 - buttonWidth, height: bounds.height) textField?.frame = textFieldRect } else { let textFieldRect = CGRect(x: 44, y: 0, width: bounds.width - 56, height: bounds.height) textField?.frame = textFieldRect } } private func commonInit() { initImageView() initPlaceholderLabel() initTextField() addClickRecognizer() addBorder() clipsToBounds = true } private func initImageView() { let rect = CGRect(x: 12, y: bounds.height/2 - 10, width: 20, height: 20) imageView = UIImageView(frame: rect) imageView?.alpha = 0 addSubview(imageView!) } private func initPlaceholderLabel() { placeholderLabel = UILabel(frame: frame) placeholderLabel?.textColor = UIColor(red: 168/255, green: 164/255, blue: 155/255, alpha: 1) addSubview(placeholderLabel!) } private func initTextField() { let rect = CGRect(x: 44, y: 0, width: bounds.width - 56, height: bounds.height) textField = UITextField(frame: rect) textField?.delegate = self textField?.alpha = 0 textField?.textColor = UIColor(red: 75/255, green: 68/255, blue: 54/255, alpha: 1) addSubview(textField!) } private func initToggleSecureTextButton() { let rect = CGRect(x: 44, y: 0, width: bounds.width - 56, height: bounds.height) toggleSecureTextButton = UIButton(frame: rect) toggleSecureTextButton?.alpha = 0 toggleSecureTextButton?.setTitleColor(UIColor(red: 75/255, green: 68/255, blue: 54/255, alpha: 1), for: .normal) let title = isSecureTextEntry ? showText : hideText toggleSecureTextButton?.setTitle(title, for: .normal) toggleSecureTextButton?.addTarget(self, action: #selector(showSecureTextClicked), for: .touchUpInside) toggleSecureTextButton?.titleLabel?.font = UIFont.systemFont(ofSize: toggleSecureTextButtonFontSize) addSubview(toggleSecureTextButton!) } private func addClickRecognizer() { let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(requestFocus)) addGestureRecognizer(gestureRecognizer) } private func addBorder() { layer.cornerRadius = 4 layer.borderColor = UIColor(red: 233/255, green: 232/255, blue: 229/255, alpha: 1).cgColor layer.borderWidth = 1 } private func showPlaceholder(animated: Bool) { if (animated) { UIView.animate(withDuration: 0.3) { self.showPlaceholder(animated: false) } } else { self.imageView?.alpha = 0 self.imageView?.frame.origin.x = -20 self.textField?.alpha = 0 self.toggleSecureTextButton?.alpha = 0 self.placeholderLabel?.frame.origin.x = 12 self.placeholderLabel?.alpha = 1 } } private func hidePlaceholder(animated: Bool) { if (animated) { UIView.animate(withDuration: 0.3) { self.hidePlaceholder(animated: false) } } else { self.placeholderLabel?.frame.origin.x = 44 self.placeholderLabel?.alpha = 0 self.imageView?.frame.origin.x = 12 self.imageView?.alpha = 1 self.textField?.alpha = 1 self.toggleSecureTextButton?.alpha = 1 } } func showSecureTextClicked() { isSecureTextEntry = !isSecureTextEntry } func requestFocus() { textField?.becomeFirstResponder() } } extension KohanaTextField: UITextFieldDelegate { public func textFieldDidBeginEditing(_ textField: UITextField) { placeholderVisible = false textFieldDelegate?.textFieldDidBeginEditing?(textField) } public func textFieldDidEndEditing(_ textField: UITextField) { if textField.text?.isEmpty ?? true { placeholderVisible = true } textFieldDelegate?.textFieldDidEndEditing?(textField) } public func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool { return textFieldDelegate?.textFieldShouldBeginEditing?(textField) ?? true } public func textFieldShouldEndEditing(_ textField: UITextField) -> Bool { return textFieldDelegate?.textFieldShouldEndEditing?(textField) ?? true } @available(iOS 10.0, *) public func textFieldDidEndEditing(_ textField: UITextField, reason: UITextFieldDidEndEditingReason) { if textField.text?.isEmpty ?? true { placeholderVisible = true } textFieldDelegate?.textFieldDidEndEditing?(textField, reason: reason) } public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { return textFieldDelegate?.textField?(textField, shouldChangeCharactersIn: range, replacementString: string) ?? true } public func textFieldShouldClear(_ textField: UITextField) -> Bool { return textFieldDelegate?.textFieldShouldClear?(textField) ?? true } public func textFieldShouldReturn(_ textField: UITextField) -> Bool { return textFieldDelegate?.textFieldShouldReturn?(textField) ?? true } }
mit
75b2cdc59ea1e229d9558221d7787497
31.695364
136
0.614645
5.042901
false
false
false
false
JerrySir/YCOA
YCOA/Main/Stock/Controller/StockChildTableViewController.swift
1
8207
// // StockChildTableViewController.swift // YCOA // // Created by Jerry on 2017/1/17. // Copyright © 2017年 com.baochunsteel. All rights reserved. // import UIKit class StockChildTableViewController: UITableViewController { private var warehouseID: String = "" //仓库ID // private var currentPage: Int = 1 //库位的货物列表是持续加载的,记录当前页码 private var items : [(id_: String, owner: String, storageLocation: String, supplier: String, materiel: String, specifications: String, stockQuantity: String)] = [] override func viewDidLoad() { super.viewDidLoad() self.initUI() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - 配置 // 数据 // 配置数据源 open func configure(warehouseID: String) { self.warehouseID = warehouseID self.reloadDataFromServer(page: 1) } // MARK: - 组件 // 初始化 private func initUI() { self.view.backgroundColor = UIColor.groupTableViewBackground self.initTableView() //这一步已在控制器初始化的时候进行了 } private func initTableView() { self.tableView.separatorStyle = .none self.tableView.register(StockVC_ItemTableViewCell.self, forCellReuseIdentifier: "StockVC_ItemTableViewCell") } // MARK: - 事件 // 网络请求 private func reloadDataFromServer(page: Int) { /* 方案1:如果一次请求加载不完,就递归请求,等待所有数据都请求到了,再显示(目前数据不多,可以采取这种方式) 方案2:记录当前页,做持续加载 */ let parameters = ["adminid": UserCenter.shareInstance().uid!, "timekey": NSDate.nowTimeToTimeStamp(), "token": UserCenter.shareInstance().token!, "cfrom": "appiphone", "appapikey": UserCenter.shareInstance().apikey!, "page": page, "wareid": self.warehouseID] as [String : Any] YCOA_NetWork.get(url: "/index.php?d=taskrun&m=warehouse|appapi&a=getgoodslist&ajaxbool=true", parameters: parameters) { (error, returnValue) in guard parameters["wareid"] as! String == self.warehouseID else{ //如果请求的仓库ID与当前ID不符,则重新获取数据 NSLog("请求的仓库ID与当前ID不符,则重新获取数据") self.reloadDataFromServer(page: 1) return } guard error == nil else{ self.view.jrShow(withTitle: error!.domain) return } guard let dataDic = (returnValue as! NSDictionary).value(forKey: "data") as? NSDictionary else{ self.view.jrShow(withTitle: "暂无数据") return } guard dataDic.count > 0 else{ self.view.jrShow(withTitle: "暂无数据") return } guard let dataItemsArr: [NSDictionary] = (dataDic["rows"] as? [NSDictionary]) else{ self.view.jrShow(withTitle: "暂无数据") return } //同步数据 let values = dataItemsArr.map({ ($0.value(forKey: "id") as! String, $0.value(forKey: "goodsfirm") as! String, $0.value(forKey: "shelvesname") as! String, $0.value(forKey: "vendorname") as! String, $0.value(forKey: "goodswuliao") as! String, $0.value(forKey: "goodsguige") as! String, $0.value(forKey: "goodstock") as! String) }) //判断是追加还是刷新 if((dataDic["page"] as! Int) == 1){ self.items = values }else{ self.items = self.items + values } //如果当前不是最后一页,继续请求下一页数据 if(!((dataDic["maxpage"] as! Int) == (dataDic["page"] as! Int))){ self.reloadDataFromServer(page: (page + 1)) } self.tableView.reloadData() } } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.items.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: StockVC_ItemTableViewCell = tableView.dequeueReusableCell(withIdentifier: "StockVC_ItemTableViewCell", for: indexPath) as! StockVC_ItemTableViewCell let dataItem = self.items[indexPath.row] cell.configure(id_: dataItem.id_, owner: dataItem.owner, storageLocation: dataItem.storageLocation, supplier: dataItem.supplier, materiel: dataItem.materiel, specifications: dataItem.specifications, stockQuantity: dataItem.stockQuantity) { (id_) in NSLog("点击了库存id为: \(id_)的Cell") let vc = StockDetailTableViewController(style: .plain) vc.configure(id_: self.items[indexPath.row].id_) self.navigationController?.pushViewController(vc, animated: true) } return cell } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return tableView.fd_heightForCell(withIdentifier: "StockVC_ItemTableViewCell", cacheBy: indexPath, configuration: { (cell) in let dataItem = self.items[indexPath.row] (cell as! StockVC_ItemTableViewCell).configure(id_: dataItem.id_, owner: dataItem.owner, storageLocation: dataItem.storageLocation, supplier: dataItem.supplier, materiel: dataItem.materiel, specifications: dataItem.specifications, stockQuantity: dataItem.stockQuantity) { (id_) in NSLog("点击了库存id为: \(id_)的Cell") } }) } /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
ada9708e2b314b0bc7fd067dc25cfc9c
37.646766
292
0.582003
4.780308
false
false
false
false
chrisjmendez/swift-exercises
GUI/Layout/NSAutoLayout/BasicLayoutConstraint/ViewController.swift
1
1578
// // ViewController.swift // BasicLayoutConstraint // // Created by Chris on 1/22/16. // Copyright © 2016 Chris Mendez. All rights reserved. // import UIKit class ViewController: UIViewController { func onLoad(){ let subView = UIView() subView.translatesAutoresizingMaskIntoConstraints = false subView.backgroundColor = UIColor.greenColor() self.view.addSubview(subView) let leading = NSLayoutConstraint(item: subView, attribute: .Leading, relatedBy: .Equal, toItem: view, attribute: .Leading, multiplier: 1, constant: 0) let trailing = NSLayoutConstraint(item: subView, attribute: .Trailing, relatedBy: .Equal, toItem: view, attribute: .TrailingMargin, multiplier: 1, constant: 0) let top = NSLayoutConstraint(item: subView, attribute: .Top, relatedBy: .Equal, toItem: topLayoutGuide, attribute: .Bottom, multiplier: 1, constant: 0) let bottom = NSLayoutConstraint(item: subView, attribute: .Bottom, relatedBy: .Equal, toItem: bottomLayoutGuide, attribute: .BottomMargin, multiplier: 1, constant: 0) NSLayoutConstraint.activateConstraints([leading, trailing, top, bottom]) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. onLoad() self.view.backgroundColor = UIColor.redColor() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
1332adf957798c449c769d88daa30a10
34.044444
174
0.684211
4.912773
false
false
false
false
tlax/GaussSquad
GaussSquad/View/LinearEquations/Solution/Base/VLinearEquationsSolutionFlow.swift
1
7507
import UIKit class VLinearEquationsSolutionFlow:UICollectionViewLayout { private weak var model:MLinearEquationsSolution! private var headerLayoutAttributes:[UICollectionViewLayoutAttributes] private var footerLayoutAttributes:[UICollectionViewLayoutAttributes] private var cellLayoutAttributes:[UICollectionViewLayoutAttributes] private var contentWidth:CGFloat private var contentHeight:CGFloat private let barHeight:CGFloat private let footerHeight:CGFloat private let cellHeight:CGFloat private let kMarginRight:CGFloat = 20 init( model:MLinearEquationsSolution, barHeight:CGFloat, footerHeight:CGFloat, cellHeight:CGFloat) { self.model = model self.barHeight = barHeight self.footerHeight = footerHeight self.cellHeight = cellHeight contentWidth = 0 contentHeight = 0 headerLayoutAttributes = [] footerLayoutAttributes = [] cellLayoutAttributes = [] super.init() } required init?(coder:NSCoder) { return nil } override func prepare() { super.prepare() guard let collectionView:UICollectionView = self.collectionView else { return } headerLayoutAttributes = [] footerLayoutAttributes = [] cellLayoutAttributes = [] let collectionWidth:CGFloat = collectionView.bounds.maxX let collectionHeight:CGFloat = collectionView.bounds.maxY var maxPositionX:CGFloat = min(collectionWidth, collectionHeight) var section:Int = 0 var positionY:CGFloat = barHeight for step:MLinearEquationsSolutionStep in model.steps { let headerHeight:CGFloat = step.headerHeight let sectionIndexPath:IndexPath = IndexPath( item:0, section:section) let headerAttribute:UICollectionViewLayoutAttributes = UICollectionViewLayoutAttributes( forSupplementaryViewOfKind:UICollectionElementKindSectionHeader, with:sectionIndexPath) headerAttribute.frame = CGRect( x:0, y:positionY, width:0, height:headerHeight) headerLayoutAttributes.append(headerAttribute) positionY += headerHeight var index:Int = 0 for equation:MLinearEquationsSolutionEquation in step.equations { var positionX:CGFloat = 0 for item:MLinearEquationsSolutionEquationItem in equation.plainItems { let indexPath:IndexPath = IndexPath( item:index, section:section) let cellWidth:CGFloat = item.cellWidth let frame:CGRect = CGRect( x:positionX, y:positionY, width:cellWidth, height:cellHeight) index += 1 positionX += cellWidth let attributes:UICollectionViewLayoutAttributes = UICollectionViewLayoutAttributes( forCellWith:indexPath) attributes.frame = frame cellLayoutAttributes.append(attributes) } let positionMargin:CGFloat = positionX + kMarginRight if positionMargin > maxPositionX { maxPositionX = positionMargin } positionY += cellHeight } let footerAttribute:UICollectionViewLayoutAttributes = UICollectionViewLayoutAttributes( forSupplementaryViewOfKind:UICollectionElementKindSectionFooter, with:sectionIndexPath) footerAttribute.frame = CGRect( x:0, y:positionY, width:0, height:footerHeight) footerLayoutAttributes.append(footerAttribute) positionY += footerHeight section += 1 } contentWidth = maxPositionX contentHeight = positionY var listReusables:[UICollectionViewLayoutAttributes] = [] listReusables.append(contentsOf:headerLayoutAttributes) listReusables.append(contentsOf:footerLayoutAttributes) for attributesReusable:UICollectionViewLayoutAttributes in listReusables { let origin:CGPoint = attributesReusable.frame.origin let height:CGFloat = attributesReusable.frame.size.height let newSize:CGSize = CGSize(width:contentWidth, height:height) let newFrame:CGRect = CGRect(origin:origin, size:newSize) attributesReusable.frame = newFrame } } override var collectionViewContentSize:CGSize { get { let size:CGSize = CGSize( width:contentWidth, height:contentHeight) return size } } override func layoutAttributesForElements(in rect:CGRect) -> [UICollectionViewLayoutAttributes]? { var attributes:[UICollectionViewLayoutAttributes]? var allAttributes:[UICollectionViewLayoutAttributes] = [] allAttributes.append(contentsOf:cellLayoutAttributes) allAttributes.append(contentsOf:headerLayoutAttributes) allAttributes.append(contentsOf:footerLayoutAttributes) for layoutAttribute:UICollectionViewLayoutAttributes in allAttributes { let frame:CGRect = layoutAttribute.frame if frame.intersects(rect) { if attributes == nil { attributes = [] } attributes!.append(layoutAttribute) } } return attributes } override func layoutAttributesForSupplementaryView(ofKind elementKind:String, at indexPath:IndexPath) -> UICollectionViewLayoutAttributes? { let listAttributes:[UICollectionViewLayoutAttributes] if elementKind == UICollectionElementKindSectionHeader { listAttributes = headerLayoutAttributes } else { listAttributes = footerLayoutAttributes } for layoutAttribute:UICollectionViewLayoutAttributes in listAttributes { if layoutAttribute.indexPath.section == indexPath.section { return layoutAttribute } } return nil } override func layoutAttributesForItem(at indexPath:IndexPath) -> UICollectionViewLayoutAttributes? { for layoutAttribute:UICollectionViewLayoutAttributes in cellLayoutAttributes { if layoutAttribute.indexPath == indexPath { return layoutAttribute } } return nil } override func shouldInvalidateLayout(forBoundsChange newBounds:CGRect) -> Bool { return false } }
mit
9d68ab6abf838a1100a6c8f8031371f3
31.781659
142
0.576395
7.062088
false
false
false
false
a7ex/ServicesFromWSDL
ServicesFromWSDL/Helper/HelperFunctions.swift
1
2665
// // HelperFunctions.swift // SwiftDTO // // Created by Alex da Franca on 24.05.17. // Copyright © 2017 Farbflash. All rights reserved. // import Foundation func writeToStdError(_ str: String) { let handle = FileHandle.standardError if let data = str.data(using: String.Encoding.utf8) { handle.write(data) } } func writeToStdOut(_ str: String) { let handle = FileHandle.standardOutput if let data = "\(str)\n".data(using: String.Encoding.utf8) { handle.write(data) } } func createClassNameFromType(_ nsType: String?) -> String? { guard let nsType = nsType, !nsType.isEmpty else { return nil } guard let type = nsType.components(separatedBy: ":").last else { return nil } let capType = type.capitalizedFirst switch capType { case "Error": return "DTOError" default: return capType } } func writeContent(_ content: String, toFileAtPath fpath: String?) { guard let fpath = fpath else { writeToStdError("Error creating enum file. Path for target file is nil.") return } do { try content.write(toFile: fpath, atomically: false, encoding: String.Encoding.utf8) writeToStdOut("Successfully written file to: \(fpath)\n") } catch let error as NSError { writeToStdError("error: \(error.localizedDescription)") } } func pathForClassName(_ className: String, inFolder target: String?, outputType: OutputType = .swift) -> String? { guard let target = target else { return nil } let fileurl = URL(fileURLWithPath: target) let fileExt: String switch outputType { case .swift: fileExt = "swift" case .java: fileExt = "java" } let newUrl = fileurl.appendingPathComponent(className).appendingPathExtension(fileExt) return newUrl.path } func readProtocolParentLookup(targetFolder: String?) -> [String: [String]] { guard let targetFolder = targetFolder else { return [String: [String]]() } let fileurl = URL(fileURLWithPath: targetFolder) let newUrl = fileurl.appendingPathComponent("DTOParentInfo.json") guard let data = try? Data(contentsOf: newUrl), let json = try? JSONSerialization.jsonObject(with: data as Data, options: .allowFragments), let lookuplist = json as? [String: [String]] else { return [String: [String]]() } return lookuplist } func filename(for url: URL) -> String? { if let nameParts = url.pathComponents.last?.components(separatedBy: "."), !nameParts.isEmpty { if nameParts.count == 1 { return nameParts[0] } return "\((nameParts[0..<(nameParts.count - 1)].joined(separator: ".")))" } return nil }
apache-2.0
ca5231ee228fa6abe1dbdd80473ca6d3
31.888889
114
0.667417
3.970194
false
false
false
false
volendavidov/NagBar
NagBar/ThrukHTTPClient.swift
1
3796
// // ThrukHTTPClient.swift // NagBar // // Created by Volen Davidov on 28.09.19. // Copyright © 2019 Volen Davidov. All rights reserved. // // Thruk uses cookie authentication by default. We can force // basic auth as well but we have to send the Authorization header // before receiving a challenge. The .authenticate() method in // Alamofire does not do this, so we use a workaround - manually sending // the Authorization header (https://github.com/Alamofire/Alamofire/issues/32). // Also, we have to fake the user agent as curl for this to work. import Alamofire import Foundation import PromiseKit class ThrukHTTPClient : MonitoringProcessorBase, HTTPClient { func get(_ url: String) -> Promise<Data> { return Promise{ seal in let authTuple: (key: String, value: String)? = Request.authorizationHeader(user: self.monitoringInstance!.username, password: self.monitoringInstance!.password) let userAgent: (key: String, value: String)? = ("User-agent", "curl") ConnectionManager.sharedInstance.manager!.request(url, method: .get, parameters: nil, encoding: Alamofire.JSONEncoding.default, headers: [authTuple!.key : authTuple!.value, userAgent!.key : userAgent!.value]).response { response in if response.error == nil { if response.response!.statusCode == 401 { seal.reject(NSError(domain: "", code: -999, userInfo: nil)) } else { seal.fulfill(response.data!) } } else { seal.reject(response.error!) } } } } func checkConnection() -> Promise<Bool> { return Promise{ seal in let authTuple: (key: String, value: String)? = Request.authorizationHeader(user: self.monitoringInstance!.username, password: self.monitoringInstance!.password) let userAgent: (key: String, value: String)? = ("User-agent", "curl") ConnectionManager.sharedInstance.manager!.request(self.monitoringInstance!.url, method: .get, parameters: nil, encoding: Alamofire.JSONEncoding.default, headers: [authTuple!.key : authTuple!.value, userAgent!.key : userAgent!.value]).response { response in if response.error == nil { if response.response!.statusCode == 401 { seal.fulfill(false) } else { seal.fulfill(true) } } else { seal.fulfill(false) } } } } func post(_ url: String, postData: Dictionary<String, String>) -> Promise<Data> { return Promise{ seal in let authTuple: (key: String, value: String)? = Request.authorizationHeader(user: self.monitoringInstance!.username, password: self.monitoringInstance!.password) let userAgent: (key: String, value: String)? = ("User-agent", "curl") ConnectionManager.sharedInstance.manager!.request(url, method: .post, parameters: postData, encoding: Alamofire.URLEncoding.default, headers: [authTuple!.key : authTuple!.value, userAgent!.key : userAgent!.value]).response { response in if response.error == nil { if response.response!.statusCode == 401 { seal.reject(NSError(domain: "", code: -999, userInfo: nil)) } else { seal.fulfill(response.data!) } } else { seal.reject(response.error!) } } } } }
apache-2.0
cca5d4fb0d562df49e6bb6e0c85da2d6
42.62069
268
0.572859
4.81599
false
false
false
false
el-hoshino/NotAutoLayout
Sources/NotAutoLayout/LayoutInfoStorable/SubviewSetupWizard.swift
1
7134
// // SubviewSetupWizard.swift // NotAutoLayout // // Created by 史翔新 on 2017/06/17. // Copyright © 2017年 史翔新. All rights reserved. // import UIKit public struct SubviewSetupWizard<ParentView> { private let parentView: ParentView private let setteeView: UIView typealias ConditionLayout = [ConditionEnum.RawValue: () -> IndividualProperty.Layout] typealias ConditionOrder = [ConditionEnum.RawValue: () -> Int] typealias ConditionZIndex = [ConditionEnum.RawValue: () -> Int] private var layouts: ConditionLayout private var orders: ConditionOrder private var zIndices: ConditionZIndex private enum AddingMethod { case none case add case insertAt(() -> Int?) case insertAbove(() -> UIView?) case insertBelow(() -> UIView?) } private var addingMethod: AddingMethod init(parent: ParentView, settee: UIView) { self.parentView = parent self.setteeView = settee self.layouts = [:] self.orders = [:] self.zIndices = [:] self.addingMethod = .none } } extension SubviewSetupWizard where ParentView: UIView & LayoutInfoStorable { private func setupLayouts() { for (condition, layout) in self.layouts { self.parentView.nal.appendLayout(layout, under: condition, for: self.setteeView) } } private func setupOrders() { for (condition, order) in self.orders { self.parentView.nal.appendLayoutOrder(order, under: condition, for: self.setteeView) } } private func setupZIndices() { for (condition, zIndex) in self.zIndices { self.parentView.nal.appendZIndex(zIndex, under: condition, for: self.setteeView) } } private func addSetteeToParent() { switch self.addingMethod { case .none: break case .add: self.parentView.addSubview(self.setteeView) case .insertAt(let index): if let index = index() { self.parentView.insertSubview(self.setteeView, at: index) } else { self.parentView.addSubview(self.setteeView) } case .insertAbove(let view): if let view = view() { self.parentView.insertSubview(self.setteeView, aboveSubview: view) } else { self.parentView.addSubview(self.setteeView) } case .insertBelow(let view): if let view = view() { self.parentView.insertSubview(self.setteeView, belowSubview: view) } else { self.parentView.addSubview(self.setteeView) } } } func commit() { self.setupLayouts() self.setupOrders() self.setupZIndices() self.addSetteeToParent() } } extension SubviewSetupWizard where ParentView: UIView & LayoutInfoStorable { public func setLayout(for condition: ConditionEnum, by layout: @escaping () -> IndividualProperty.Layout) -> SubviewSetupWizard { var wizard = self wizard.layouts[condition.rawValue] = layout return wizard } public func setLayout(for condition: ConditionEnum, to layout: IndividualProperty.Layout) -> SubviewSetupWizard { let layout = { layout } return self.setLayout(for: condition, by: layout) } public func setDefaultLayout(by layout: @escaping () -> IndividualProperty.Layout) -> SubviewSetupWizard { let condition = self.parentView.getDefaultCondition() return self.setLayout(for: condition, by: layout) } public func setDefaultLayout(to layout: IndividualProperty.Layout) -> SubviewSetupWizard { let condition = self.parentView.getDefaultCondition() return self.setLayout(for: condition, to: layout) } public func setDefaultLayout(_ making: (LayoutMaker<IndividualProperty.Initial>) -> LayoutMaker<IndividualProperty.Layout>) -> SubviewSetupWizard { let maker = LayoutMaker(parentView: self.parentView, didSetProperty: IndividualProperty.Initial()) let layout = making(maker).didSetProperty return self.setDefaultLayout(to: layout) } public func setLayout(for condition: ConditionEnum, making: (LayoutMaker<IndividualProperty.Initial>) -> LayoutMaker<IndividualProperty.Layout>) -> SubviewSetupWizard { let maker = LayoutMaker(parentView: self.parentView, didSetProperty: IndividualProperty.Initial()) let layout = making(maker).didSetProperty return self.setLayout(for: condition, to: layout) } } extension SubviewSetupWizard where ParentView: UIView & LayoutInfoStorable { public func setOrder(for condition: ConditionEnum, by order: @escaping () -> Int) -> SubviewSetupWizard { var wizard = self wizard.orders[condition.rawValue] = order return wizard } public func setOrder(for condition: ConditionEnum, to order: Int) -> SubviewSetupWizard { let order = { order } return self.setOrder(for: condition, by: order) } public func setDefaultOrder(by order: @escaping () -> Int) -> SubviewSetupWizard { let condition = self.parentView.getDefaultCondition() return self.setOrder(for: condition, by: order) } public func setDefaultOrder(to order: Int) -> SubviewSetupWizard { let condition = self.parentView.getDefaultCondition() return self.setOrder(for: condition, to: order) } } extension SubviewSetupWizard where ParentView: UIView & LayoutInfoStorable { public func setZIndex(for condition: ConditionEnum, by zIndex: @escaping () -> Int) -> SubviewSetupWizard { var wizard = self wizard.zIndices[condition.rawValue] = zIndex return wizard } public func setZIndex(for condition: ConditionEnum, to zIndex: Int) -> SubviewSetupWizard { let zIndex = { zIndex } return self.setZIndex(for: condition, by: zIndex) } public func setDefaultZIndex(by zIndex: @escaping () -> Int) -> SubviewSetupWizard { let condition = self.parentView.getDefaultCondition() return self.setZIndex(for: condition, by: zIndex) } public func setDefaultZIndex(to zIndex: Int) -> SubviewSetupWizard { let condition = self.parentView.getDefaultCondition() return self.setZIndex(for: condition, to: zIndex) } } extension SubviewSetupWizard where ParentView: UIView & LayoutInfoStorable { public func addToParent() -> SubviewSetupWizard { var wizard = self wizard.addingMethod = .add return wizard } public func insertToParent(at index: Int) -> SubviewSetupWizard { var wizard = self wizard.addingMethod = .insertAt({ index }) return wizard } public func insertToParent(at index: @escaping () -> Int?) -> SubviewSetupWizard { var wizard = self wizard.addingMethod = .insertAt(index) return wizard } public func insertToParent(above view: UIView) -> SubviewSetupWizard { var wizard = self wizard.addingMethod = .insertAbove({ [weak view] in view }) return wizard } public func insertToParent(above view: @escaping () -> UIView?) -> SubviewSetupWizard { var wizard = self wizard.addingMethod = .insertAbove(view) return wizard } public func insertToParent(below view: UIView) -> SubviewSetupWizard { var wizard = self wizard.addingMethod = .insertBelow({ [weak view] in view }) return wizard } public func insertToParent(below view: @escaping () -> UIView?) -> SubviewSetupWizard { var wizard = self wizard.addingMethod = .insertBelow(view) return wizard } }
apache-2.0
7d77b523d6bfc67521ffb3475996ba1b
23.463918
169
0.714567
3.764675
false
false
false
false
alexreidy/Digital-Ear
Digital Ear/Util.swift
1
4814
// // Util.swift // Digital Ear // // Created by Alex Reidy on 3/7/15. // Copyright (c) 2015 Alex Reidy. All rights reserved. // import Foundation import AVFoundation let MAX_REC_DURATION: Double = 5 // seconds let DOCUMENT_DIR = NSHomeDirectory() + "/Documents/" let utilAudioSession = AVAudioSession() var utilAudioRecorder: AVAudioRecorder? var utilAudioPlayer: AVAudioPlayer? let DEFAULT_SAMPLE_RATE = 44100 let defaultAudioSettings: [AnyHashable: Any] = [ AVFormatIDKey: kAudioFormatLinearPCM, AVLinearPCMIsFloatKey: true, AVNumberOfChannelsKey: 1, AVSampleRateKey: DEFAULT_SAMPLE_RATE, ] func timestampDouble() -> Double { return Date().timeIntervalSince1970 } func now() -> Int { return time(nil) } func sign(_ x: Float) -> Int { if x < 0 { return -1 } return 1 } func max(_ nums: [Float]) -> Float { var max: Float = -MAXFLOAT for n in nums { if n > max { max = n } } return max } func average(_ data: [Float], absolute: Bool = false) -> Float { // If absolute, return the average absolute distance from zero var sum: Float = 0 for x in data { if absolute { sum += abs(x) } else { sum += x } } return sum / Float(data.count) } func startRecordingAudio(toPath path: String, delegate: AVAudioRecorderDelegate? = nil, seconds: Double = MAX_REC_DURATION) { // if utilAudioRecorder == nil ??? don't want to record while recording... utilAudioRecorder = try! AVAudioRecorder(url: URL(fileURLWithPath: path), settings: defaultAudioSettings as! [String: Any]) if let recorder = utilAudioRecorder { recorder.delegate = delegate recorder.record(forDuration: seconds) } } func stopRecordingAudio() { if let recorder = utilAudioRecorder { recorder.stop() utilAudioRecorder = nil } } func recording() -> Bool { if let recorder = utilAudioRecorder { return recorder.isRecording } return false } func playAudio(_ filePath: String) { try! utilAudioSession.setCategory(AVAudioSessionCategoryPlayAndRecord) utilAudioPlayer = try! AVAudioPlayer(contentsOf: URL(fileURLWithPath: filePath)) if let player = utilAudioPlayer { player.volume = 1 if player.play() { print("playing") } } } func extractSamplesFromWAV(_ path: String) -> [Float] { let audioFile: AVAudioFile? do { audioFile = try AVAudioFile(forReading: URL(fileURLWithPath: path), commonFormat: AVAudioCommonFormat.pcmFormatFloat32, interleaved: false) } catch { audioFile = nil print("Error opening audio file with path \(path), and error: \(error)") return [Float]() } guard let af = audioFile else { return [Float]() } let N_SAMPLES = Int(af.length) let buffer = AVAudioPCMBuffer(pcmFormat: AVAudioFormat(settings: defaultAudioSettings as! [String: Any]), frameCapacity: AVAudioFrameCount(N_SAMPLES)) guard N_SAMPLES > 0 else { return [Float]() } do { try af.read(into: buffer, frameCount: AVAudioFrameCount(N_SAMPLES)) } catch { print("problem reading \(error)") return [Float]() } var samples = [Float](repeating: 0.0, count: N_SAMPLES) for i in 0 ..< N_SAMPLES { if let data = buffer.floatChannelData { samples[i] = data.pointee[i] } } return samples } func formatTimeBetween(_ startTime: Int, endTime: Int) -> String { if endTime < startTime { return "error" } let secondsElapsed = endTime - startTime if secondsElapsed >= 3600 * 24 { let days = secondsElapsed / (3600 * 24) let hours = (secondsElapsed % (3600 * 24)) / 3600 return "\(days)d, \(hours)h" } if secondsElapsed >= 3600 { let hours = secondsElapsed / 3600 let seconds = secondsElapsed % 3600 let minutes = seconds / 60 return "\(hours)h, \(minutes)m" } if secondsElapsed >= 60 { let minutesElapsed: Int = secondsElapsed / 60 let seconds: Int = secondsElapsed % 60 return "\(minutesElapsed)m, \(seconds)s" } return "\(secondsElapsed)s" } func formatTimeSince(_ time: Int) -> String { return formatTimeBetween(time, endTime: now()) } func canAddSound() -> Bool { if UserDefaults().bool(forKey: "unlimited") || getSoundNames().count < 1 { return true } return false } import StoreKit extension SKProduct { // Thanks to Ben Dodson func localizedPrice() -> String { let formatter = NumberFormatter() formatter.numberStyle = .currency formatter.locale = self.priceLocale return formatter.string(from: self.price)! } }
mit
ff1e9182ac3430f9bd002340875dbfdc
26.352273
147
0.628168
4.24141
false
false
false
false
stripe/stripe-ios
StripePayments/StripePayments/API Bindings/Models/STPCustomer.swift
1
9690
// // STPCustomer.swift // StripePayments // // Created by Jack Flintermann on 6/9/16. // Copyright © 2016 Stripe, Inc. All rights reserved. // import Foundation @_spi(STP) import StripeCore /// An `STPCustomer` represents a deserialized Customer object from the Stripe API. /// You shouldn't need to instantiate an `STPCustomer` – you should instead use /// `STPCustomerContext` to manage retrieving and updating a customer. public class STPCustomer: NSObject { /// The Stripe ID of the customer, e.g. `cus_1234` @objc public let stripeID: String /// The default source used to charge the customer. @objc public private(set) var defaultSource: STPSourceProtocol? /// The available payment sources the customer has (this may be an empty array). @objc public private(set) var sources: [STPSourceProtocol] /// The customer’s email address. @objc public private(set) var email: String? /// The customer's shipping address. @objc public var shippingAddress: STPAddress? @objc public let allResponseFields: [AnyHashable: Any] /// Initialize a customer object with the provided values. /// - Parameters: /// - stripeID: The ID of the customer, e.g. `cus_abc` /// - defaultSource: The default source of the customer, such as an `STPCard` object. Can be nil. /// - sources: All of the customer's payment sources. This might be an empty array. /// - Returns: an instance of STPCustomer @objc public convenience init( stripeID: String, defaultSource: STPSourceProtocol?, sources: [STPSourceProtocol] ) { self.init( stripeID: stripeID, defaultSource: defaultSource, sources: sources, shippingAddress: nil, email: nil, allResponseFields: [:] ) } internal init( stripeID: String, defaultSource: STPSourceProtocol?, sources: [STPSourceProtocol], shippingAddress: STPAddress?, email: String?, allResponseFields: [AnyHashable: Any] ) { self.stripeID = stripeID self.defaultSource = defaultSource self.sources = sources self.shippingAddress = shippingAddress self.email = email self.allResponseFields = allResponseFields super.init() } convenience override init() { self.init( stripeID: "", defaultSource: nil, sources: [], shippingAddress: nil, email: nil, allResponseFields: [:] ) } // MARK: - Description /// :nodoc: @objc public override var description: String { let props: [String] = [ // Object String(format: "%@: %p", NSStringFromClass(STPCustomer.self), self), // Identifier "stripeID = \(stripeID)", // Sources "defaultSource = \(String(describing: defaultSource))", "sources = \(sources)", ] return "<\(props.joined(separator: "; "))>" } /// Replaces the customer's `sources` and `defaultSource` based on whether or not /// they should include Apple Pay sources. More details on documentation for /// `STPCustomerContext includeApplePaySources` /// /// @param filteringApplePay If YES, Apple Pay sources will be ignored @objc(updateSourcesFilteringApplePay:) public func updateSources(filteringApplePay: Bool) { let (defaultSource, sources) = STPCustomer.sources( from: allResponseFields, filterApplePay: filteringApplePay ) self.defaultSource = defaultSource self.sources = sources } } extension STPCustomer: STPAPIResponseDecodable { @objc public class func decodedObject(fromAPIResponse response: [AnyHashable: Any]?) -> Self? { guard let dict = response, let stripeID = dict["id"] as? String else { return nil } let shippingAddress: STPAddress? if let shippingDict = dict["shipping"] as? [AnyHashable: Any], let addressDict = shippingDict["address"] as? [AnyHashable: Any], let shipping = STPAddress.decodedObject(fromAPIResponse: addressDict) { shipping.name = shippingDict["name"] as? String shipping.phone = shippingDict["phone"] as? String shippingAddress = shipping } else { shippingAddress = nil } let (defaultSource, sources) = STPCustomer.sources(from: dict, filterApplePay: true) return STPCustomer( stripeID: stripeID, defaultSource: defaultSource, sources: sources, shippingAddress: shippingAddress, email: dict["email"] as? String, allResponseFields: dict ) as? Self } private class func sources( from response: [AnyHashable: Any], filterApplePay: Bool ) -> ( default: STPSourceProtocol?, sources: [STPSourceProtocol] ) { guard let sourcesDict = response["sources"] as? [AnyHashable: Any], let data = sourcesDict["data"] as? [[AnyHashable: Any]] else { return (nil, []) } var defaultSource: STPSourceProtocol? let defaultSourceId = response["default_source"] as? String var sources: [STPSourceProtocol] = [] for contents in data { if let object = contents["object"] as? String { if object == "card" { if let card = STPCard.decodedObject(fromAPIResponse: contents), !filterApplePay || !card.isApplePayCard { sources.append(card) if let defaultSourceId = defaultSourceId, card.stripeID == defaultSourceId { defaultSource = card } } } else if object == "source" { if let source = STPSource.decodedObject(fromAPIResponse: contents), !filterApplePay || !(source.cardDetails?.isApplePayCard ?? false) { sources.append(source) if let defaultSourceId = defaultSourceId, source.stripeID == defaultSourceId { defaultSource = source } } } } else { continue } } return (defaultSource, sources) } } /// Use `STPCustomerDeserializer` to convert a response from the Stripe API into an `STPCustomer` object. `STPCustomerDeserializer` expects the JSON response to be in the exact same format as the Stripe API. public class STPCustomerDeserializer: NSObject { /// If a customer was successfully parsed from the response, it will be set here. Otherwise, this value wil be nil (and the `error` property will explain what went wrong). @objc public let customer: STPCustomer? /// If the deserializer failed to parse a customer, this property will explain why (and the `customer` property will be nil). @objc public let error: Error? /// Initialize a customer deserializer. The `data`, `urlResponse`, and `error` /// parameters are intended to be passed from an `NSURLSessionDataTask` callback. /// After it has been initialized, you can inspect the `error` and `customer` /// properties to see if the deserialization was successful. If `error` is nil, /// `customer` will be non-nil (and vice versa). /// - Parameters: /// - data: An `NSData` object representing encoded JSON for a Customer object /// - urlResponse: The URL response obtained from the `NSURLSessionTask` /// - error: Any error that occurred from the URL session task (if this /// is non-nil, the `error` property will be set to this value after initialization). @objc public convenience init( data: Data?, urlResponse: URLResponse?, error: Error? ) { if let error = error { self.init(customer: nil, error: error) } else if let data = data { var json: Any? do { json = try JSONSerialization.jsonObject(with: data, options: []) } catch let jsonError { self.init(customer: nil, error: jsonError) return } self.init(jsonResponse: json) } else { self.init(customer: nil, error: NSError.stp_genericFailedToParseResponseError()) } } /// Initializes a customer deserializer with a JSON dictionary. This JSON should be /// in the exact same format as what the Stripe API returns. If it's successfully /// parsed, the `customer` parameter will be present after initialization; /// otherwise `error` will be present. /// - Parameter json: a JSON dictionary. @objc public convenience init( jsonResponse json: Any? ) { if let customer = STPCustomer.decodedObject(fromAPIResponse: json as? [AnyHashable: Any]) { self.init(customer: customer, error: nil) } else { self.init(customer: nil, error: NSError.stp_genericFailedToParseResponseError()) } } private init( customer: STPCustomer?, error: Error? ) { self.customer = customer self.error = error super.init() } }
mit
9e0c61d759575dd48cdabe5fac1a7c7f
35.13806
207
0.59143
4.89636
false
false
false
false
Yalantis/AppearanceNavigationController
AppearanceNavigationController/Misc/Appearance+Extension.swift
1
1474
import Foundation import UIKit extension Appearance { static func random() -> Appearance { var value = Appearance() let navigationBarColor = UIColor.randomColor() value.navigationBar.backgroundColor = navigationBarColor value.navigationBar.tintColor = navigationBarColor.isBright ? .black : .white let toolbarColor = UIColor.randomColor() value.toolbar.backgroundColor = toolbarColor value.toolbar.tintColor = toolbarColor.isBright ? .black : .white value.statusBarStyle = navigationBarColor.brightness > 0.5 ? .default : .lightContent return value } func inverse() -> Appearance { var value = Appearance() value.navigationBar.backgroundColor = navigationBar.backgroundColor.inverse() value.navigationBar.tintColor = navigationBar.tintColor.inverse() value.toolbar.backgroundColor = toolbar.backgroundColor.inverse() value.toolbar.tintColor = toolbar.tintColor.inverse() value.statusBarStyle = value.navigationBar.backgroundColor.isBright ? .default : .lightContent return value } static let lightAppearance: Appearance = { var value = Appearance() value.navigationBar.backgroundColor = .lightGray value.navigationBar.tintColor = .white value.statusBarStyle = .lightContent return value }() }
mit
8b50e2a594b9be7e854aedf72f3dfa74
32.5
102
0.65536
5.80315
false
false
false
false
aulas-lab/ads-mobile
swift/ListaMercado/ListaMercado/ViewController.swift
1
1567
// // ViewController.swift // ListaMercado // // Created by Mobitec on 19/05/16. // Copyright (c) 2016 Unopar. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDataSource { @IBOutlet weak var txfMerc: UITextField! @IBOutlet weak var txfQtd: UITextField! @IBOutlet weak var tbvDados: UITableView! private var dados = [ItemCompra]() override func viewDidLoad() { super.viewDidLoad() //tbvDados.registerClass(UITableViewCell.self, forCellReuseIdentifier: "c") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func btnAddClick(sender: AnyObject) { var mercadoria = txfMerc.text var qtd = (txfQtd.text as NSString).integerValue var itemCompra = ItemCompra(mercadoria: mercadoria, qtd: qtd) dados.append(itemCompra) tbvDados.reloadData() } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dados.count; } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { // Desinfilerar a celular var celula : ItemCompraCell = tbvDados.dequeueReusableCellWithIdentifier("c") as ItemCompraCell // Obter o dado a ser apresentado var itemCompra = dados[indexPath.row] // Ajustar a celular quanto ao dado celula.atualizar(itemCompra) return celula } }
mit
d2e270404951ec17bbc56e8da4b18aaa
27.490909
109
0.656031
4.201072
false
false
false
false
ben-ng/swift
validation-test/stdlib/CoreGraphics-execute.swift
15
14892
// RUN: %target-run-simple-swift // REQUIRES: executable_test // REQUIRES: objc_interop // REQUIRES: OS=macosx import CoreGraphics import StdlibUnittest let CoreGraphicsTests = TestSuite("CoreGraphics") //===----------------------------------------------------------------------===// // CGAffineTransform //===----------------------------------------------------------------------===// CoreGraphicsTests.test("CGAffineTransform/Equatable") { checkEquatable([ CGAffineTransform(a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0), CGAffineTransform.identity, CGAffineTransform(a: 1, b: 10, c: 10, d: 1, tx: 0, ty: 0), CGAffineTransform(a: 1, b: 10, c: 10, d: 1, tx: 0, ty: 0), ] as [CGAffineTransform], oracle: { $0 / 2 == $1 / 2 }) } //===----------------------------------------------------------------------===// // CGColor //===----------------------------------------------------------------------===// CoreGraphicsTests.test("CGColor/Equatable") { checkEquatable([ CGColor(red: 1, green: 0, blue: 0, alpha: 1), CGColor(red: 1, green: 0, blue: 0, alpha: 0), CGColor(red: 0, green: 1, blue: 0, alpha: 1), CGColor(red: 0, green: 1, blue: 0, alpha: 0), CGColor(red: 0, green: 0, blue: 1, alpha: 1), CGColor(red: 0, green: 0, blue: 1, alpha: 0), ] as [CGColor], oracle: { $0 == $1 }) } CoreGraphicsTests.test("CGColor.components") { let red = CGColor(red: 1, green: 0, blue: 0, alpha: 1) let components = red.components! expectEqual(components.count, 4) expectEqual(components[0], 1) expectEqual(components[1], 0) expectEqual(components[2], 0) expectEqual(components[3], 1) } //===----------------------------------------------------------------------===// // CGPoint //===----------------------------------------------------------------------===// CoreGraphicsTests.test("CGPoint/Equatable") { checkEquatable([ CGPoint(x: 0, y: 0), CGPoint(x: -1, y: -1), CGPoint(x: -1, y: 0), CGPoint(x: 0, y: -1), CGPoint(x: 1, y: 1), CGPoint(x: 1, y: 0), CGPoint(x: 0, y: 1), CGPoint(x: 1.nextUp, y: 1.nextUp), CGPoint(x: 1.nextUp, y: 0), CGPoint(x: 0, y: 1.nextUp), CGPoint(x: CGFloat.greatestFiniteMagnitude, y: 0), ] as [CGPoint], oracle: { $0 == $1 }) } CoreGraphicsTests.test("CGPoint.init(x:y:)") { var fractional = CGPoint() fractional.x = 1.25 fractional.y = 2.25 var negativeFractional = CGPoint() negativeFractional.x = -1.25 negativeFractional.y = -2.25 var integral = CGPoint() integral.x = 1.0 integral.y = 2.0 var negativeIntegral = CGPoint() negativeIntegral.x = -1.0 negativeIntegral.y = -2.0 // Initialize from floating point literals. expectEqual(fractional, CGPoint(x: 1.25, y: 2.25)) expectEqual(negativeFractional, CGPoint(x: -1.25, y: -2.25)) // Initialize from integer literals. expectEqual(integral, CGPoint(x: 1, y: 2)) expectEqual(negativeIntegral, CGPoint(x: -1, y: -2)) expectEqual(fractional, CGPoint(x: 1.25 as CGFloat, y: 2.25 as CGFloat)) expectEqual(fractional, CGPoint(x: 1.25 as Double, y: 2.25 as Double)) expectEqual(integral, CGPoint(x: 1 as Int, y: 2 as Int)) } CoreGraphicsTests.test("CGPoint.dictionaryRepresentation, CGPoint.init(dictionaryRepresentation:)") { let point = CGPoint(x: 1, y: 2) let dict = point.dictionaryRepresentation let newPoint = CGPoint(dictionaryRepresentation: dict) expectOptionalEqual(point, newPoint) } CoreGraphicsTests.test("CGPoint.zero") { expectEqual(0.0, CGPoint.zero.x) expectEqual(0.0, CGPoint.zero.y) } //===----------------------------------------------------------------------===// // CGSize //===----------------------------------------------------------------------===// CoreGraphicsTests.test("CGSize/Equatable") { checkEquatable([ CGSize(width: 0, height: 0), CGSize(width: -1, height: -1), CGSize(width: -1, height: 0), CGSize(width: 0, height: -1), CGSize(width: 1, height: 1), CGSize(width: 1, height: 0), CGSize(width: 0, height: 1), CGSize(width: 1.nextUp, height: 1.nextUp), CGSize(width: 1.nextUp, height: 0), CGSize(width: 0, height: 1.nextUp), CGSize(width: CGFloat.greatestFiniteMagnitude, height: 0), ] as [CGSize], oracle: { $0 == $1 }) } CoreGraphicsTests.test("CGSize.init(width:height:)") { var fractional = CGSize() fractional.width = 1.25 fractional.height = 2.25 var negativeFractional = CGSize() negativeFractional.width = -1.25 negativeFractional.height = -2.25 var integral = CGSize() integral.width = 1.0 integral.height = 2.0 var negativeIntegral = CGSize() negativeIntegral.width = -1.0 negativeIntegral.height = -2.0 // Initialize from floating point literals. expectEqual(fractional, CGSize(width: 1.25, height: 2.25)) expectEqual(negativeFractional, CGSize(width: -1.25, height: -2.25)) // Initialize from integer literals. expectEqual(integral, CGSize(width: 1, height: 2)) expectEqual(negativeIntegral, CGSize(width: -1, height: -2)) expectEqual(fractional, CGSize(width: 1.25 as CGFloat, height: 2.25 as CGFloat)) expectEqual(fractional, CGSize(width: 1.25 as Double, height: 2.25 as Double)) expectEqual(integral, CGSize(width: 1 as Int, height: 2 as Int)) } CoreGraphicsTests.test("CGSize.dictionaryRepresentation, CGSize.init(dictionaryRepresentation:)") { let size = CGSize(width: 3, height: 4) let dict = size.dictionaryRepresentation let newSize = CGSize(dictionaryRepresentation: dict) expectOptionalEqual(size, newSize) } CoreGraphicsTests.test("CGSize.zero") { expectEqual(0.0, CGSize.zero.width) expectEqual(0.0, CGSize.zero.height) } //===----------------------------------------------------------------------===// // CGRect //===----------------------------------------------------------------------===// CoreGraphicsTests.test("CGRect/Equatable") { checkEquatable([ CGRect.null, CGRect(x: 0, y: 0, width: 0, height: 0), CGRect(x: 1.25, y: 2.25, width: 3.25, height: 4.25), CGRect(x: -1.25, y: -2.25, width: -3.25, height: -4.25), CGRect(x: 1, y: 2, width: 3, height: 4), CGRect(x: -1, y: -2, width: -3, height: -4), ] as [CGRect], oracle: { $0 == $1 }) } CoreGraphicsTests.test("CGRect.init(x:y:width:height:)") { var fractional = CGRect() fractional.origin = CGPoint(x: 1.25, y: 2.25) fractional.size = CGSize(width: 3.25, height: 4.25) var negativeFractional = CGRect() negativeFractional.origin = CGPoint(x: -1.25, y: -2.25) negativeFractional.size = CGSize(width: -3.25, height: -4.25) var integral = CGRect() integral.origin = CGPoint(x: 1.0, y: 2.0) integral.size = CGSize(width: 3.0, height: 4.0) var negativeIntegral = CGRect() negativeIntegral.origin = CGPoint(x: -1.0, y: -2.0) negativeIntegral.size = CGSize(width: -3.0, height: -4.0) // Initialize from floating point literals. expectEqual(fractional, CGRect(x: 1.25, y: 2.25, width: 3.25, height: 4.25)) expectEqual( negativeFractional, CGRect(x: -1.25, y: -2.25, width: -3.25, height: -4.25)) // Initialize from integer literals. expectEqual(integral, CGRect(x: 1, y: 2, width: 3, height: 4)) expectEqual(negativeIntegral, CGRect(x: -1, y: -2, width: -3, height: -4)) expectEqual( fractional, CGRect( x: 1.25 as CGFloat, y: 2.25 as CGFloat, width: 3.25 as CGFloat, height: 4.25 as CGFloat)) expectEqual( fractional, CGRect( x: 1.25 as Double, y: 2.25 as Double, width: 3.25 as Double, height: 4.25 as Double)) expectEqual( integral, CGRect( x: 1 as Int, y: 2 as Int, width: 3 as Int, height: 4 as Int)) } CoreGraphicsTests.test("CGRect.init(origin:size:)") { let point = CGPoint(x: 1.25, y: 2.25) let size = CGSize(width: 3.25, height: 4.25) expectEqual( CGRect(x: 1.25, y: 2.25, width: 3.25, height: 4.25), CGRect(origin: point, size: size)) } CoreGraphicsTests.test("CGRect.dictionaryRepresentation, CGRect.init(dictionaryRepresentation:)") { let point = CGPoint(x: 1, y: 2) let size = CGSize(width: 3, height: 4) let rect = CGRect(origin: point, size: size) let dict = rect.dictionaryRepresentation let newRect = CGRect(dictionaryRepresentation: dict) expectOptionalEqual(rect, newRect) } CoreGraphicsTests.test("CGRect.isNull") { expectFalse(CGRect.infinite.isNull) expectTrue(CGRect.null.isNull) expectFalse(CGRect.zero.isNull) expectFalse(CGRect(x: 0, y: 0, width: 10, height: 20).isNull) } CoreGraphicsTests.test("CGRect.isEmpty") { expectFalse(CGRect.infinite.isEmpty) expectTrue(CGRect.null.isEmpty) expectTrue(CGRect.zero.isEmpty) expectFalse(CGRect(x: 0, y: 0, width: 10, height: 20).isEmpty) } CoreGraphicsTests.test("CGRect.isInfinite") { expectTrue(CGRect.infinite.isInfinite) expectFalse(CGRect.null.isInfinite) expectFalse(CGRect.zero.isInfinite) expectFalse(CGRect(x: 0, y: 0, width: 10, height: 20).isInfinite) } CoreGraphicsTests.test("CGRect.contains(CGPoint)") { let rect = CGRect(x: 11.25, y: 22.25, width: 33.25, height: 44.25) expectTrue(rect.contains(CGPoint(x: 15, y: 25))) expectFalse(rect.contains(CGPoint(x: -15, y: 25))) } CoreGraphicsTests.test("CGRect.contains(CGRect)") { let rect = CGRect(x: 11.25, y: 22.25, width: 33.25, height: 44.25) let bigRect = CGRect(x: 1, y: 2, width: 101, height: 102) expectTrue(bigRect.contains(rect)) expectFalse(rect.contains(bigRect)) } CoreGraphicsTests.test("CGRect.divided()") { let rect = CGRect(x: 11.25, y: 22.25, width: 33.25, height: 44.25) let (slice, remainder) = rect.divided(atDistance: 5, from: CGRectEdge.minXEdge) expectEqual(CGRect(x: 11.25, y: 22.25, width: 5.0, height: 44.25), slice) expectEqual(CGRect(x: 16.25, y: 22.25, width: 28.25, height: 44.25), remainder) } CoreGraphicsTests.test("CGRect.standardized") { var unstandard = CGRect(x: 10, y: 20, width: -30, height: -50) var standard = unstandard.standardized expectEqual(CGPoint(x: 10, y: 20), unstandard.origin) expectEqual(CGPoint(x: -20, y: -30), standard.origin) expectEqual(CGSize(width: -30, height: -50), unstandard.size) expectEqual(CGSize(width: 30, height: 50), standard.size) expectEqual(unstandard, standard) expectEqual(standard, standard.standardized) expectEqual(30, unstandard.width) expectEqual(30, standard.width) expectEqual(50, unstandard.height) expectEqual(50, standard.height) expectEqual(-20, unstandard.minX) expectEqual(-5, unstandard.midX) expectEqual(10, unstandard.maxX) expectEqual(-20, standard.minX) expectEqual(-5, standard.midX) expectEqual(10, standard.maxX) expectEqual(-30, unstandard.minY) expectEqual(-5, unstandard.midY) expectEqual(20, unstandard.maxY) expectEqual(-30, standard.minY) expectEqual(-5, standard.midY) expectEqual(20, standard.maxY) } CoreGraphicsTests.test("CGRect.insetBy(self:dx:dy:)") { let rect = CGRect(x: 11.25, y: 22.25, width: 33.25, height: 44.25) expectEqual( CGRect(x: 12.25, y: 20.25, width: 31.25, height: 48.25), rect.insetBy(dx: 1, dy: -2)) } CoreGraphicsTests.test("CGRect.offsetBy(self:dx:dy:)") { let rect = CGRect(x: 11.25, y: 22.25, width: 33.25, height: 44.25) expectEqual( CGRect(x: 14.25, y: 18.25, width: 33.25, height: 44.25), rect.offsetBy(dx: 3, dy: -4)) } CoreGraphicsTests.test("CGRect.integral") { let rect = CGRect(x: 11.25, y: 22.25, width: 33.25, height: 44.25) expectEqual( CGRect(x: 11, y: 22, width: 34, height: 45), rect.integral) } CoreGraphicsTests.test("CGRect.union(_:)") { let smallRect = CGRect(x: 10, y: 25, width: 5, height: -5) let bigRect = CGRect(x: 1, y: 2, width: 101, height: 102) let distantRect = CGRect(x: 1000, y: 2000, width: 1, height: 1) let rect = CGRect(x: 11.25, y: 22.25, width: 33.25, height: 44.25) expectEqual( CGRect(x: 10.0, y: 20.0, width: 34.5, height: 46.5), rect.union(smallRect)) expectEqual( CGRect(x: 1.0, y: 2.0, width: 101.0, height: 102.0), rect.union(bigRect)) expectEqual( CGRect(x: 11.25, y: 22.25, width: 989.75, height: 1978.75), rect.union(distantRect)) expectEqual( CGRect(x: 1.0, y: 2.0, width: 1000.0, height: 1999.0), rect.union(smallRect).union(bigRect).union(distantRect)) } CoreGraphicsTests.test("CGRect.intersection(_:)") { let smallRect = CGRect(x: 10, y: 25, width: 5, height: -5) let bigRect = CGRect(x: 1, y: 2, width: 101, height: 102) let distantRect = CGRect(x: 1000, y: 2000, width: 1, height: 1) var rect = CGRect(x: 11.25, y: 22.25, width: 33.25, height: 44.25) expectTrue(rect.intersects(smallRect)) expectEqual( CGRect(x: 11.25, y: 22.25, width: 3.75, height: 2.75), rect.intersection(smallRect)) expectTrue(rect.intersects(bigRect)) expectEqual( CGRect(x: 11.25, y: 22.25, width: 33.25, height: 44.25), rect.intersection(bigRect)) expectFalse(rect.intersects(distantRect)) expectEqual(CGRect.null, rect.intersection(distantRect)) expectFalse( rect .intersection(smallRect) .intersection(bigRect) .isEmpty) expectTrue( rect .intersection(smallRect) .intersection(bigRect) .intersection(distantRect) .isEmpty) } //===----------------------------------------------------------------------===// // CGVector //===----------------------------------------------------------------------===// CoreGraphicsTests.test("CGVector/Equatable") { checkEquatable([ CGVector(dx: 0, dy: 0), CGVector(dx: -1, dy: -1), CGVector(dx: -1, dy: 0), CGVector(dx: 0, dy: -1), CGVector(dx: 1, dy: 1), CGVector(dx: 1, dy: 0), CGVector(dx: 0, dy: 1), CGVector(dx: 1.nextUp, dy: 1.nextUp), CGVector(dx: 1.nextUp, dy: 0), CGVector(dx: 0, dy: 1.nextUp), CGVector(dx: CGFloat.greatestFiniteMagnitude, dy: 0), ] as [CGVector], oracle: { $0 == $1 }) } CoreGraphicsTests.test("CGVector.init(dx:dy:)") { var fractional = CGVector() fractional.dx = 1.25 fractional.dy = 2.25 var negativeFractional = CGVector() negativeFractional.dx = -1.25 negativeFractional.dy = -2.25 var integral = CGVector() integral.dx = 1.0 integral.dy = 2.0 var negativeIntegral = CGVector() negativeIntegral.dx = -1.0 negativeIntegral.dy = -2.0 // Initialize from floating point literals. expectEqual(fractional, CGVector(dx: 1.25, dy: 2.25)) expectEqual(negativeFractional, CGVector(dx: -1.25, dy: -2.25)) // Initialize from integer literals. expectEqual(integral, CGVector(dx: 1, dy: 2)) expectEqual(negativeIntegral, CGVector(dx: -1, dy: -2)) expectEqual(fractional, CGVector(dx: 1.25 as CGFloat, dy: 2.25 as CGFloat)) expectEqual(fractional, CGVector(dx: 1.25 as Double, dy: 2.25 as Double)) expectEqual(integral, CGVector(dx: 1 as Int, dy: 2 as Int)) } CoreGraphicsTests.test("CGVector.zero") { expectEqual(0.0, CGVector.zero.dx) expectEqual(0.0, CGVector.zero.dy) } runAllTests()
apache-2.0
76270337c84aca523d8076f1a12f3687
30.025
101
0.626779
3.445627
false
true
false
false
avalanched/Rex
Source/UIKit/UIBarButtonItem.swift
2
1162
// // UIBarButtonItem.swift // Rex // // Created by Bjarke Hesthaven Søndergaard on 24/07/15. // Copyright (c) 2015 Neil Pankey. All rights reserved. // import ReactiveCocoa import UIKit extension UIBarButtonItem { /// Exposes a property that binds an action to bar button item. The action is set as /// a target of the button. When property changes occur the previous action is /// overwritten. This also binds the enabled state of the action to the `rex_enabled` /// property on the button. public var rex_action: MutableProperty<CocoaAction> { return associatedObject(self, key: &action) { [weak self] _ in let initial = CocoaAction.rex_disabled let property = MutableProperty(initial) property.producer.start(Observer(next: { next in self?.target = next self?.action = CocoaAction.selector })) if let strongSelf = self { strongSelf.rex_enabled <~ property.producer.flatMap(.Latest) { $0.rex_enabledProducer } } return property } } } private var action: UInt8 = 0
mit
0d4271d50f54bb9864cd34b8bc8e4c9d
31.25
103
0.627907
4.535156
false
false
false
false
thomasvl/swift-protobuf
Sources/SwiftProtobufCore/TextFormatEncodingVisitor.swift
2
27112
// Sources/SwiftProtobuf/TextFormatEncodingVisitor.swift - Text format encoding support // // Copyright (c) 2014 - 2016 Apple Inc. and the project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See LICENSE.txt for license information: // https://github.com/apple/swift-protobuf/blob/main/LICENSE.txt // // ----------------------------------------------------------------------------- /// /// Text format serialization engine. /// // ----------------------------------------------------------------------------- import Foundation private let mapNameResolver: [Int:StaticString] = [1: "key", 2: "value"] /// Visitor that serializes a message into protobuf text format. internal struct TextFormatEncodingVisitor: Visitor { private var encoder: TextFormatEncoder private var nameMap: _NameMap? private var nameResolver: [Int:StaticString] private var extensions: ExtensionFieldValueSet? private let options: TextFormatEncodingOptions /// The protobuf text produced by the visitor. var result: String { return encoder.stringResult } /// Creates a new visitor that serializes the given message to protobuf text /// format. init(message: Message, options: TextFormatEncodingOptions) { let nameMap: _NameMap? if let nameProviding = message as? _ProtoNameProviding { nameMap = type(of: nameProviding)._protobuf_nameMap } else { nameMap = nil } let extensions = (message as? ExtensibleMessage)?._protobuf_extensionFieldValues self.nameMap = nameMap self.nameResolver = [:] self.extensions = extensions self.encoder = TextFormatEncoder() self.options = options } // TODO: This largely duplicates emitFieldName() below. // But, it's slower so we don't want to just have emitFieldName() use // formatFieldName(). Also, we need to measure whether the optimization // this provides to repeated fields is worth the effort; consider just // removing this and having repeated fields just re-run emitFieldName() // for each item. private func formatFieldName(lookingUp fieldNumber: Int) -> [UInt8] { var bytes = [UInt8]() if let protoName = nameMap?.names(for: fieldNumber)?.proto { bytes.append(contentsOf: protoName.utf8Buffer) } else if let protoName = nameResolver[fieldNumber] { let buff = UnsafeBufferPointer(start: protoName.utf8Start, count: protoName.utf8CodeUnitCount) bytes.append(contentsOf: buff) } else if let extensionName = extensions?[fieldNumber]?.protobufExtension.fieldName { bytes.append(UInt8(ascii: "[")) bytes.append(contentsOf: extensionName.utf8) bytes.append(UInt8(ascii: "]")) } else { bytes.append(contentsOf: fieldNumber.description.utf8) } return bytes } private mutating func emitFieldName(lookingUp fieldNumber: Int) { if let protoName = nameMap?.names(for: fieldNumber)?.proto { encoder.emitFieldName(name: protoName.utf8Buffer) } else if let protoName = nameResolver[fieldNumber] { encoder.emitFieldName(name: protoName) } else if let extensionName = extensions?[fieldNumber]?.protobufExtension.fieldName { encoder.emitExtensionFieldName(name: extensionName) } else { encoder.emitFieldNumber(number: fieldNumber) } } mutating func visitUnknown(bytes: Data) throws { if options.printUnknownFields { try bytes.withUnsafeBytes { (body: UnsafeRawBufferPointer) -> () in if let baseAddress = body.baseAddress, body.count > 0 { // All fields will be directly handled, so there is no need for // the unknown field buffering/collection (when scannings to see // if something is a message, this would be extremely wasteful). var binaryOptions = BinaryDecodingOptions() binaryOptions.discardUnknownFields = true var decoder = BinaryDecoder(forReadingFrom: baseAddress, count: body.count, options: binaryOptions) try visitUnknown(decoder: &decoder) } } } } /// Helper for printing out unknowns. /// /// The implementation tries to be "helpful" and if a length delimited field /// appears to be a submessage, it prints it as such. However, that opens the /// door to someone sending a message with an unknown field that is a stack /// bomb, i.e. - it causes this code to recurse, exhausing the stack and /// thus opening up an attack vector. To keep this "help", but avoid the /// attack, a limit is placed on how many times it will recurse before just /// treating the length delimted fields as bytes and not trying to decode /// them. private mutating func visitUnknown( decoder: inout BinaryDecoder, recursionBudget: Int = 10 ) throws { // This stack serves to avoid recursion for groups within groups within // groups..., this avoid the stack attack that the message detection // hits. No limit is placed on this because there is no stack risk with // recursion, and because if a limit was hit, there is no other way to // encode the group (the message field can just print as length // delimited, groups don't have an option like that). var groupFieldNumberStack: [Int] = [] while let tag = try decoder.getTag() { switch tag.wireFormat { case .varint: encoder.emitFieldNumber(number: tag.fieldNumber) var value: UInt64 = 0 encoder.startRegularField() try decoder.decodeSingularUInt64Field(value: &value) encoder.putUInt64(value: value) encoder.endRegularField() case .fixed64: encoder.emitFieldNumber(number: tag.fieldNumber) var value: UInt64 = 0 encoder.startRegularField() try decoder.decodeSingularFixed64Field(value: &value) encoder.putUInt64Hex(value: value, digits: 16) encoder.endRegularField() case .lengthDelimited: encoder.emitFieldNumber(number: tag.fieldNumber) var bytes = Data() try decoder.decodeSingularBytesField(value: &bytes) bytes.withUnsafeBytes { (body: UnsafeRawBufferPointer) -> () in if let baseAddress = body.baseAddress, body.count > 0 { var encodeAsBytes: Bool if (recursionBudget > 0) { do { // Walk all the fields to test if it looks like a message var testDecoder = BinaryDecoder(forReadingFrom: baseAddress, count: body.count, parent: decoder) while let _ = try testDecoder.nextFieldNumber() { } // No error? Output the message body. encodeAsBytes = false var subDecoder = BinaryDecoder(forReadingFrom: baseAddress, count: bytes.count, parent: decoder) encoder.startMessageField() try visitUnknown(decoder: &subDecoder, recursionBudget: recursionBudget - 1) encoder.endMessageField() } catch { encodeAsBytes = true } } else { encodeAsBytes = true } if (encodeAsBytes) { encoder.startRegularField() encoder.putBytesValue(value: bytes) encoder.endRegularField() } } } case .startGroup: encoder.emitFieldNumber(number: tag.fieldNumber) encoder.startMessageField() groupFieldNumberStack.append(tag.fieldNumber) case .endGroup: let groupFieldNumber = groupFieldNumberStack.popLast() // Unknown data is scanned and verified by the // binary parser, so this can never fail. assert(tag.fieldNumber == groupFieldNumber) encoder.endMessageField() case .fixed32: encoder.emitFieldNumber(number: tag.fieldNumber) var value: UInt32 = 0 encoder.startRegularField() try decoder.decodeSingularFixed32Field(value: &value) encoder.putUInt64Hex(value: UInt64(value), digits: 8) encoder.endRegularField() } } // Unknown data is scanned and verified by the binary parser, so this can // never fail. assert(groupFieldNumberStack.isEmpty) } // Visitor.swift defines default versions for other singular field types // that simply widen and dispatch to one of the following. Since Text format // does not distinguish e.g., Fixed64 vs. UInt64, this is sufficient. mutating func visitSingularFloatField(value: Float, fieldNumber: Int) throws { emitFieldName(lookingUp: fieldNumber) encoder.startRegularField() encoder.putFloatValue(value: value) encoder.endRegularField() } mutating func visitSingularDoubleField(value: Double, fieldNumber: Int) throws { emitFieldName(lookingUp: fieldNumber) encoder.startRegularField() encoder.putDoubleValue(value: value) encoder.endRegularField() } mutating func visitSingularInt64Field(value: Int64, fieldNumber: Int) throws { emitFieldName(lookingUp: fieldNumber) encoder.startRegularField() encoder.putInt64(value: value) encoder.endRegularField() } mutating func visitSingularUInt64Field(value: UInt64, fieldNumber: Int) throws { emitFieldName(lookingUp: fieldNumber) encoder.startRegularField() encoder.putUInt64(value: value) encoder.endRegularField() } mutating func visitSingularBoolField(value: Bool, fieldNumber: Int) throws { emitFieldName(lookingUp: fieldNumber) encoder.startRegularField() encoder.putBoolValue(value: value) encoder.endRegularField() } mutating func visitSingularStringField(value: String, fieldNumber: Int) throws { emitFieldName(lookingUp: fieldNumber) encoder.startRegularField() encoder.putStringValue(value: value) encoder.endRegularField() } mutating func visitSingularBytesField(value: Data, fieldNumber: Int) throws { try visitSingularBytesField(value: Array(value), fieldNumber: fieldNumber) } mutating func visitSingularBytesField(value: [UInt8], fieldNumber: Int) throws { emitFieldName(lookingUp: fieldNumber) encoder.startRegularField() encoder.putBytesValue(value: value) encoder.endRegularField() } mutating func visitSingularEnumField<E: Enum>(value: E, fieldNumber: Int) throws { emitFieldName(lookingUp: fieldNumber) encoder.startRegularField() encoder.putEnumValue(value: value) encoder.endRegularField() } mutating func visitSingularMessageField<M: Message>(value: M, fieldNumber: Int) throws { emitFieldName(lookingUp: fieldNumber) // Cache old visitor configuration let oldNameMap = self.nameMap let oldNameResolver = self.nameResolver let oldExtensions = self.extensions // Update configuration for new message self.nameMap = (M.self as? _ProtoNameProviding.Type)?._protobuf_nameMap self.nameResolver = [:] self.extensions = (value as? ExtensibleMessage)?._protobuf_extensionFieldValues // Encode submessage encoder.startMessageField() if let any = value as? Google_Protobuf_Any { any.textTraverse(visitor: &self) } else { try! value.traverse(visitor: &self) } encoder.endMessageField() // Restore configuration before returning self.extensions = oldExtensions self.nameResolver = oldNameResolver self.nameMap = oldNameMap } // Emit the full "verbose" form of an Any. This writes the typeURL // as a field name in `[...]` followed by the fields of the // contained message. internal mutating func visitAnyVerbose(value: Message, typeURL: String) { encoder.emitExtensionFieldName(name: typeURL) encoder.startMessageField() // Cache old visitor configuration let oldNameMap = self.nameMap let oldNameResolver = self.nameResolver let oldExtensions = self.extensions // Update configuration for new message self.nameMap = (type(of: value) as? _ProtoNameProviding.Type)?._protobuf_nameMap self.nameResolver = [:] self.extensions = (value as? ExtensibleMessage)?._protobuf_extensionFieldValues if let any = value as? Google_Protobuf_Any { any.textTraverse(visitor: &self) } else { try! value.traverse(visitor: &self) } // Restore configuration before returning self.extensions = oldExtensions self.nameResolver = oldNameResolver self.nameMap = oldNameMap encoder.endMessageField() } // Write a single special field called "#json". This // is used for Any objects with undecoded JSON contents. internal mutating func visitAnyJSONDataField(value: SwiftProtobufContiguousBytes) { encoder.indent() encoder.append(staticText: "#json: ") encoder.putBytesValue(value: value) encoder.append(staticText: "\n") } // The default implementations in Visitor.swift provide the correct // results, but we get significantly better performance by only doing // the name lookup once for the array, rather than once for each element: mutating func visitRepeatedFloatField(value: [Float], fieldNumber: Int) throws { assert(!value.isEmpty) let fieldName = formatFieldName(lookingUp: fieldNumber) for v in value { encoder.emitFieldName(name: fieldName) encoder.startRegularField() encoder.putFloatValue(value: v) encoder.endRegularField() } } mutating func visitRepeatedDoubleField(value: [Double], fieldNumber: Int) throws { assert(!value.isEmpty) let fieldName = formatFieldName(lookingUp: fieldNumber) for v in value { encoder.emitFieldName(name: fieldName) encoder.startRegularField() encoder.putDoubleValue(value: v) encoder.endRegularField() } } mutating func visitRepeatedInt32Field(value: [Int32], fieldNumber: Int) throws { assert(!value.isEmpty) let fieldName = formatFieldName(lookingUp: fieldNumber) for v in value { encoder.emitFieldName(name: fieldName) encoder.startRegularField() encoder.putInt64(value: Int64(v)) encoder.endRegularField() } } mutating func visitRepeatedInt64Field(value: [Int64], fieldNumber: Int) throws { assert(!value.isEmpty) let fieldName = formatFieldName(lookingUp: fieldNumber) for v in value { encoder.emitFieldName(name: fieldName) encoder.startRegularField() encoder.putInt64(value: v) encoder.endRegularField() } } mutating func visitRepeatedUInt32Field(value: [UInt32], fieldNumber: Int) throws { assert(!value.isEmpty) let fieldName = formatFieldName(lookingUp: fieldNumber) for v in value { encoder.emitFieldName(name: fieldName) encoder.startRegularField() encoder.putUInt64(value: UInt64(v)) encoder.endRegularField() } } mutating func visitRepeatedUInt64Field(value: [UInt64], fieldNumber: Int) throws { assert(!value.isEmpty) let fieldName = formatFieldName(lookingUp: fieldNumber) for v in value { encoder.emitFieldName(name: fieldName) encoder.startRegularField() encoder.putUInt64(value: v) encoder.endRegularField() } } mutating func visitRepeatedSInt32Field(value: [Int32], fieldNumber: Int) throws { try visitRepeatedInt32Field(value: value, fieldNumber: fieldNumber) } mutating func visitRepeatedSInt64Field(value: [Int64], fieldNumber: Int) throws { try visitRepeatedInt64Field(value: value, fieldNumber: fieldNumber) } mutating func visitRepeatedFixed32Field(value: [UInt32], fieldNumber: Int) throws { try visitRepeatedUInt32Field(value: value, fieldNumber: fieldNumber) } mutating func visitRepeatedFixed64Field(value: [UInt64], fieldNumber: Int) throws { try visitRepeatedUInt64Field(value: value, fieldNumber: fieldNumber) } mutating func visitRepeatedSFixed32Field(value: [Int32], fieldNumber: Int) throws { try visitRepeatedInt32Field(value: value, fieldNumber: fieldNumber) } mutating func visitRepeatedSFixed64Field(value: [Int64], fieldNumber: Int) throws { try visitRepeatedInt64Field(value: value, fieldNumber: fieldNumber) } mutating func visitRepeatedBoolField(value: [Bool], fieldNumber: Int) throws { assert(!value.isEmpty) let fieldName = formatFieldName(lookingUp: fieldNumber) for v in value { encoder.emitFieldName(name: fieldName) encoder.startRegularField() encoder.putBoolValue(value: v) encoder.endRegularField() } } mutating func visitRepeatedStringField(value: [String], fieldNumber: Int) throws { assert(!value.isEmpty) let fieldName = formatFieldName(lookingUp: fieldNumber) for v in value { encoder.emitFieldName(name: fieldName) encoder.startRegularField() encoder.putStringValue(value: v) encoder.endRegularField() } } mutating func visitRepeatedBytesField(value: [Data], fieldNumber: Int) throws { assert(!value.isEmpty) let fieldName = formatFieldName(lookingUp: fieldNumber) for v in value { encoder.emitFieldName(name: fieldName) encoder.startRegularField() encoder.putBytesValue(value: v) encoder.endRegularField() } } mutating func visitRepeatedEnumField<E: Enum>(value: [E], fieldNumber: Int) throws { assert(!value.isEmpty) let fieldName = formatFieldName(lookingUp: fieldNumber) for v in value { encoder.emitFieldName(name: fieldName) encoder.startRegularField() encoder.putEnumValue(value: v) encoder.endRegularField() } } // Messages and groups mutating func visitRepeatedMessageField<M: Message>(value: [M], fieldNumber: Int) throws { assert(!value.isEmpty) // Look up field name against outer message encoding state let fieldName = formatFieldName(lookingUp: fieldNumber) // Cache old visitor state let oldNameMap = self.nameMap let oldNameResolver = self.nameResolver let oldExtensions = self.extensions // Update encoding state for new message type self.nameMap = (M.self as? _ProtoNameProviding.Type)?._protobuf_nameMap self.nameResolver = [:] self.extensions = (value as? ExtensibleMessage)?._protobuf_extensionFieldValues // Iterate and encode each message for v in value { encoder.emitFieldName(name: fieldName) encoder.startMessageField() if let any = v as? Google_Protobuf_Any { any.textTraverse(visitor: &self) } else { try! v.traverse(visitor: &self) } encoder.endMessageField() } // Restore state self.extensions = oldExtensions self.nameResolver = oldNameResolver self.nameMap = oldNameMap } // Google's C++ implementation of Text format supports two formats // for repeated numeric fields: "short" format writes the list as a // single field with values enclosed in `[...]`, "long" format // writes a separate field name/value for each item. They provide // an option for callers to select which output version they prefer. // Since this distinction mirrors the difference in Protobuf Binary // between "packed" and "non-packed", I've chosen to use the short // format for packed fields and the long version for repeated // fields. This provides a clear visual distinction between these // fields (including proto3's default use of packed) without // introducing the baggage of a separate option. private mutating func _visitPacked<T>( value: [T], fieldNumber: Int, encode: (T, inout TextFormatEncoder) -> () ) throws { assert(!value.isEmpty) emitFieldName(lookingUp: fieldNumber) encoder.startRegularField() var firstItem = true encoder.startArray() for v in value { if !firstItem { encoder.arraySeparator() } encode(v, &encoder) firstItem = false } encoder.endArray() encoder.endRegularField() } mutating func visitPackedFloatField(value: [Float], fieldNumber: Int) throws { try _visitPacked(value: value, fieldNumber: fieldNumber) { (v: Float, encoder: inout TextFormatEncoder) in encoder.putFloatValue(value: v) } } mutating func visitPackedDoubleField(value: [Double], fieldNumber: Int) throws { try _visitPacked(value: value, fieldNumber: fieldNumber) { (v: Double, encoder: inout TextFormatEncoder) in encoder.putDoubleValue(value: v) } } mutating func visitPackedInt32Field(value: [Int32], fieldNumber: Int) throws { try _visitPacked(value: value, fieldNumber: fieldNumber) { (v: Int32, encoder: inout TextFormatEncoder) in encoder.putInt64(value: Int64(v)) } } mutating func visitPackedInt64Field(value: [Int64], fieldNumber: Int) throws { try _visitPacked(value: value, fieldNumber: fieldNumber) { (v: Int64, encoder: inout TextFormatEncoder) in encoder.putInt64(value: v) } } mutating func visitPackedUInt32Field(value: [UInt32], fieldNumber: Int) throws { try _visitPacked(value: value, fieldNumber: fieldNumber) { (v: UInt32, encoder: inout TextFormatEncoder) in encoder.putUInt64(value: UInt64(v)) } } mutating func visitPackedUInt64Field(value: [UInt64], fieldNumber: Int) throws { try _visitPacked(value: value, fieldNumber: fieldNumber) { (v: UInt64, encoder: inout TextFormatEncoder) in encoder.putUInt64(value: v) } } mutating func visitPackedSInt32Field(value: [Int32], fieldNumber: Int) throws { try visitPackedInt32Field(value: value, fieldNumber: fieldNumber) } mutating func visitPackedSInt64Field(value: [Int64], fieldNumber: Int) throws { try visitPackedInt64Field(value: value, fieldNumber: fieldNumber) } mutating func visitPackedFixed32Field(value: [UInt32], fieldNumber: Int) throws { try visitPackedUInt32Field(value: value, fieldNumber: fieldNumber) } mutating func visitPackedFixed64Field(value: [UInt64], fieldNumber: Int) throws { try visitPackedUInt64Field(value: value, fieldNumber: fieldNumber) } mutating func visitPackedSFixed32Field(value: [Int32], fieldNumber: Int) throws { try visitPackedInt32Field(value: value, fieldNumber: fieldNumber) } mutating func visitPackedSFixed64Field(value: [Int64], fieldNumber: Int) throws { try visitPackedInt64Field(value: value, fieldNumber: fieldNumber) } mutating func visitPackedBoolField(value: [Bool], fieldNumber: Int) throws { try _visitPacked(value: value, fieldNumber: fieldNumber) { (v: Bool, encoder: inout TextFormatEncoder) in encoder.putBoolValue(value: v) } } mutating func visitPackedEnumField<E: Enum>(value: [E], fieldNumber: Int) throws { try _visitPacked(value: value, fieldNumber: fieldNumber) { (v: E, encoder: inout TextFormatEncoder) in encoder.putEnumValue(value: v) } } /// Helper to encapsulate the common structure of iterating over a map /// and encoding the keys and values. private mutating func _visitMap<K, V>( map: Dictionary<K, V>, fieldNumber: Int, isOrderedBefore: (K, K) -> Bool, coder: (inout TextFormatEncodingVisitor, K, V) throws -> () ) throws { // Cache old visitor configuration let oldNameMap = self.nameMap let oldNameResolver = self.nameResolver let oldExtensions = self.extensions for (k,v) in map.sorted(by: { isOrderedBefore( $0.0, $1.0) }) { emitFieldName(lookingUp: fieldNumber) encoder.startMessageField() // Update visitor configuration for map self.nameMap = nil self.nameResolver = mapNameResolver self.extensions = nil try coder(&self, k, v) // Restore configuration before resuming containing message self.extensions = oldExtensions self.nameResolver = oldNameResolver self.nameMap = oldNameMap encoder.endMessageField() } } mutating func visitMapField<KeyType, ValueType: MapValueType>( fieldType: _ProtobufMap<KeyType, ValueType>.Type, value: _ProtobufMap<KeyType, ValueType>.BaseType, fieldNumber: Int ) throws { try _visitMap(map: value, fieldNumber: fieldNumber, isOrderedBefore: KeyType._lessThan) { (visitor: inout TextFormatEncodingVisitor, key, value) throws -> () in try KeyType.visitSingular(value: key, fieldNumber: 1, with: &visitor) try ValueType.visitSingular(value: value, fieldNumber: 2, with: &visitor) } } mutating func visitMapField<KeyType, ValueType>( fieldType: _ProtobufEnumMap<KeyType, ValueType>.Type, value: _ProtobufEnumMap<KeyType, ValueType>.BaseType, fieldNumber: Int ) throws where ValueType.RawValue == Int { try _visitMap(map: value, fieldNumber: fieldNumber, isOrderedBefore: KeyType._lessThan) { (visitor: inout TextFormatEncodingVisitor, key, value) throws -> () in try KeyType.visitSingular(value: key, fieldNumber: 1, with: &visitor) try visitor.visitSingularEnumField(value: value, fieldNumber: 2) } } mutating func visitMapField<KeyType, ValueType>( fieldType: _ProtobufMessageMap<KeyType, ValueType>.Type, value: _ProtobufMessageMap<KeyType, ValueType>.BaseType, fieldNumber: Int ) throws { try _visitMap(map: value, fieldNumber: fieldNumber, isOrderedBefore: KeyType._lessThan) { (visitor: inout TextFormatEncodingVisitor, key, value) throws -> () in try KeyType.visitSingular(value: key, fieldNumber: 1, with: &visitor) try visitor.visitSingularMessageField(value: value, fieldNumber: 2) } } }
apache-2.0
bd1ce3df878ed30e743ee62e1317cdf5
38.988201
104
0.652552
4.883285
false
false
false
false
BellAppLab/Permissionable
Source/Photos/Permissionable+Photos.swift
1
1219
import Photos import Alertable extension Permissions.Photos { public static var isThere: Bool { if let result = Permissions.Photos().hasAccess() { return result.boolValue } return false } public static var hasAsked: Bool { return Permissions.Photos().hasAccess() != nil } @objc func hasAccess() -> NSNumber? { let status = PHPhotoLibrary.authorizationStatus() switch status { case .Authorized: return NSNumber(bool: true) case .Denied, .Restricted: return NSNumber(bool: false) case .NotDetermined: return nil } } @objc func makeAction(sender: UIViewController, _ block: Permissions.Result?) -> AnyObject { return Alert.Action(title: NSLocalizedString("Yes", comment: ""), style: .Default, handler: { (UIAlertAction) -> Void in Alert.on = true PHPhotoLibrary.requestAuthorization { (status: PHAuthorizationStatus) -> Void in Alert.on = false dispatch_async(dispatch_get_main_queue()) { () -> Void in block?(success: status == .Authorized) } } }) } }
mit
e734cad62d602118dca0b6a209bc136f
30.25641
128
0.581624
4.955285
false
false
false
false
catloafsoft/AudioKit
AudioKit/Common/Nodes/Effects/AudioKit Operation-Based Effect/AKOperationEffect.swift
1
3551
// // AKOperationEffect.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright (c) 2015 Aurelius Prochazka. All rights reserved. // import AVFoundation /// Operation-based effect public class AKOperationEffect: AKNode, AKToggleable { // MARK: - Properties private var internalAU: AKOperationEffectAudioUnit? /// Tells whether the node is processing (ie. started, playing, or active) public var isStarted: Bool { return internalAU!.isPlaying() } /// Parameters for changing internal operations public var parameters: [Double] = [] { didSet { internalAU?.setParameters(parameters) } } // MARK: - Initializers /// Initialize the effect with an input and an operation /// /// - parameter input: AKNode to use for processing /// - parameter operation: AKOperation stack to use /// public convenience init(_ input: AKNode, operation: AKOperation) { // add "dup" to copy the left channel output to the right channel output self.init(input, sporth:"\(operation) dup") } /// Initialize the effect with an input and a stereo operation /// /// - parameter input: AKNode to use for processing /// - parameter stereoOperation: AKStereoOperation stack to use /// public convenience init(_ input: AKNode, stereoOperation: AKStereoOperation) { self.init(input, sporth:"\(stereoOperation) swap") } /// Initialize the effect with an input and separate operations for each channel /// /// - parameter input: AKNode to use for processing /// - parameter left: AKOperation stack to use on the left /// - parameter right: AKOperation stack to use on the right /// public convenience init(_ input: AKNode, left: AKOperation, right: AKOperation) { self.init(input, sporth:"\(left) swap \(right) swap") } /// Initialize the effect with an input and a valid Sporth string /// /// - parameter input: AKNode to use for processing /// - parameter sporth: String of valid Sporth code /// public init(_ input: AKNode, sporth: String) { var description = AudioComponentDescription() description.componentType = kAudioUnitType_Effect description.componentSubType = 0x6373746d /*'cstm'*/ description.componentManufacturer = 0x41754b74 /*'AuKt'*/ description.componentFlags = 0 description.componentFlagsMask = 0 AUAudioUnit.registerSubclass( AKOperationEffectAudioUnit.self, asComponentDescription: description, name: "Local AKOperationEffect", version: UInt32.max) super.init() AVAudioUnit.instantiateWithComponentDescription(description, options: []) { avAudioUnit, error in guard let avAudioUnitEffect = avAudioUnit else { return } self.avAudioNode = avAudioUnitEffect self.internalAU = avAudioUnitEffect.AUAudioUnit as? AKOperationEffectAudioUnit AudioKit.engine.attachNode(self.avAudioNode) input.addConnectionPoint(self) self.internalAU?.setSporth(sporth) } } /// Function to start, play, or activate the node, all do the same thing public func start() { internalAU!.start() } /// Function to stop or bypass the node, both are equivalent public func stop() { internalAU!.stop() } }
mit
ecc950f44a6b87e27f20e54b7b4c54a6
32.819048
90
0.644889
5.222059
false
false
false
false
k-san/SegueHandling
Source/SegueHandling.swift
1
2632
// // SegueHandling.swift // // Copyright (c) 2017 Keiichi Sato. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #if os(iOS) import UIKit #elseif os(macOS) import AppKit #endif public protocol SegueHandling { associatedtype SegueIdentifier: RawRepresentable } #if os(iOS) public extension SegueHandling where Self: UIViewController, SegueIdentifier.RawValue == String { func performSegue(withIdentifier segueIdentifier: SegueIdentifier, sender: Any?) { performSegue(withIdentifier: segueIdentifier.rawValue, sender: sender) } func segueIdentifier(for segue: UIStoryboardSegue) -> SegueIdentifier? { guard let identifier = segue.identifier, let segueIdentifier = SegueIdentifier(rawValue: identifier) else { return nil } return segueIdentifier } } #endif #if os(macOS) public extension SegueHandling where Self: NSViewController, SegueIdentifier.RawValue == String { func performSegue(withIdentifier segueIdentifier: SegueIdentifier, sender: Any?) { performSegue(withIdentifier: segueIdentifier.rawValue, sender: sender) } func segueIdentifier(for segue: NSStoryboardSegue) -> SegueIdentifier? { guard let identifier = segue.identifier, let segueIdentifier = SegueIdentifier(rawValue: identifier) else { return nil } return segueIdentifier } } #endif
mit
52228b6a9bd4ec88253d7f4d62d4b34a
35.054795
101
0.68769
5.061538
false
false
false
false
googlesamples/mlkit
ios/quickstarts/automl/AutoMLExample/ViewController.swift
1
22608
// // Copyright (c) 2018 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import MLKit import UIKit /// Main view controller class. @objc(ViewController) class ViewController: UIViewController, UINavigationControllerDelegate { /// Manager for local and remote models. lazy var modelManager = ModelManager.modelManager() /// A string holding current results from detection. var resultsText = "" /// An overlay view that displays detection annotations. private lazy var annotationOverlayView: UIView = { precondition(isViewLoaded) let annotationOverlayView = UIView(frame: .zero) annotationOverlayView.translatesAutoresizingMaskIntoConstraints = false return annotationOverlayView }() /// An image picker for accessing the photo library or camera. var imagePicker = UIImagePickerController() // Image counter. var currentImage = 0 // MARK: - IBOutlets @IBOutlet fileprivate weak var detectorPicker: UIPickerView! @IBOutlet fileprivate weak var imageView: UIImageView! @IBOutlet fileprivate weak var photoCameraButton: UIBarButtonItem! @IBOutlet fileprivate weak var videoCameraButton: UIBarButtonItem! @IBOutlet fileprivate weak var downloadOrDeleteModelButton: UIBarButtonItem! @IBOutlet weak var detectButton: UIBarButtonItem! @IBOutlet var downloadProgressView: UIProgressView! // MARK: - UIViewController override func viewDidLoad() { super.viewDidLoad() downloadOrDeleteModelButton.image = modelManager.isModelDownloaded(remoteModel()) ? #imageLiteral(resourceName: "delete") : #imageLiteral(resourceName: "cloud_download") imageView.image = UIImage(named: Constants.images[currentImage]) imageView.addSubview(annotationOverlayView) NSLayoutConstraint.activate([ annotationOverlayView.topAnchor.constraint(equalTo: imageView.topAnchor), annotationOverlayView.leadingAnchor.constraint(equalTo: imageView.leadingAnchor), annotationOverlayView.trailingAnchor.constraint(equalTo: imageView.trailingAnchor), annotationOverlayView.bottomAnchor.constraint(equalTo: imageView.bottomAnchor), ]) imagePicker.delegate = self imagePicker.sourceType = .photoLibrary detectorPicker.delegate = self detectorPicker.dataSource = self let isCameraAvailable = UIImagePickerController.isCameraDeviceAvailable(.front) || UIImagePickerController.isCameraDeviceAvailable(.rear) if isCameraAvailable { // `CameraViewController` uses `AVCaptureDevice.DiscoverySession` which is only supported for // iOS 10 or newer. if #available(iOS 10.0, *) { videoCameraButton.isEnabled = true } } else { photoCameraButton.isEnabled = false } let defaultRow = (DetectorPickerRow.rowsCount / 2) - 1 detectorPicker.selectRow(defaultRow, inComponent: 0, animated: false) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.navigationBar.isHidden = true NotificationCenter.default.addObserver( self, selector: #selector(remoteModelDownloadDidSucceed(_:)), name: .mlkitModelDownloadDidSucceed, object: nil ) NotificationCenter.default.addObserver( self, selector: #selector(remoteModelDownloadDidFail(_:)), name: .mlkitModelDownloadDidFail, object: nil ) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) navigationController?.navigationBar.isHidden = false // We wouldn't have needed to remove the observers if iOS 9.0+ had cleaned up the observer "the // next time it would have posted to it" as documented here: // https://developer.apple.com/documentation/foundation/nsnotificationcenter/1413994-removeobserver NotificationCenter.default.removeObserver( self, name: .mlkitModelDownloadDidSucceed, object: nil) NotificationCenter.default.removeObserver(self, name: .mlkitModelDownloadDidFail, object: nil) } // MARK: - IBActions @IBAction func detect(_ sender: Any) { clearResults() let row = detectorPicker.selectedRow(inComponent: 0) let shouldEnableClassification = row == DetectorPickerRow.detectorObjectsSingleWithClassifier.rawValue || row == DetectorPickerRow.detectorObjectsMultipleWithClassifier.rawValue let shouldEnableMultipleObjects = row == DetectorPickerRow.detectorObjectsMultipleNoClassifier.rawValue || row == DetectorPickerRow.detectorObjectsMultipleWithClassifier.rawValue if let rowIndex = DetectorPickerRow(rawValue: row) { switch rowIndex { case .detectorImageLabels: detectImageLabels(image: imageView.image) case .detectorObjectsSingleNoClassifier, .detectorObjectsSingleWithClassifier, .detectorObjectsMultipleNoClassifier, .detectorObjectsMultipleWithClassifier: detectObjects( image: imageView.image, shouldEnableClassification: shouldEnableClassification, shouldEnableMultipleObjects: shouldEnableMultipleObjects) } } else { print("No such item at row \(row) in detector picker.") } } @IBAction func openPhotoLibrary(_ sender: Any) { imagePicker.sourceType = .photoLibrary present(imagePicker, animated: true) } @IBAction func openCamera(_ sender: Any) { guard UIImagePickerController.isCameraDeviceAvailable(.front) || UIImagePickerController .isCameraDeviceAvailable(.rear) else { return } imagePicker.sourceType = .camera present(imagePicker, animated: true) } @IBAction func changeImage(_ sender: Any) { clearResults() currentImage = (currentImage + 1) % Constants.images.count imageView.image = UIImage(named: Constants.images[currentImage]) } @IBAction func downloadOrDeleteModel(_ sender: Any) { clearResults() let remoteModel = self.remoteModel() if modelManager.isModelDownloaded(remoteModel) { weak var weakSelf = self modelManager.deleteDownloadedModel(remoteModel) { error in guard error == nil else { preconditionFailure("Failed to delete the AutoML model.") } print("The downloaded remote model has been successfully deleted.\n") weakSelf?.downloadOrDeleteModelButton.image = #imageLiteral(resourceName: "cloud_download") } } else { downloadAutoMLRemoteModel(remoteModel) } } // MARK: - Private private func remoteModel() -> RemoteModel { let firebaseModelSource = FirebaseModelSource(name: Constants.remoteAutoMLModelName) return CustomRemoteModel(remoteModelSource: firebaseModelSource) } /// Removes the detection annotations from the annotation overlay view. private func removeDetectionAnnotations() { for annotationView in annotationOverlayView.subviews { annotationView.removeFromSuperview() } } /// Clears the results text view and removes any frames that are visible. private func clearResults() { removeDetectionAnnotations() self.resultsText = "" } private func showResults() { let resultsAlertController = UIAlertController( title: "Detection Results", message: nil, preferredStyle: .actionSheet ) resultsAlertController.addAction( UIAlertAction(title: "OK", style: .destructive) { _ in resultsAlertController.dismiss(animated: true, completion: nil) } ) resultsAlertController.message = resultsText resultsAlertController.popoverPresentationController?.barButtonItem = detectButton resultsAlertController.popoverPresentationController?.sourceView = self.view present(resultsAlertController, animated: true, completion: nil) print(resultsText) } /// Updates the image view with a scaled version of the given image. private func updateImageView(with image: UIImage) { let orientation = UIApplication.shared.statusBarOrientation var scaledImageWidth: CGFloat = 0.0 var scaledImageHeight: CGFloat = 0.0 switch orientation { case .portrait, .portraitUpsideDown, .unknown: scaledImageWidth = imageView.bounds.size.width scaledImageHeight = image.size.height * scaledImageWidth / image.size.width case .landscapeLeft, .landscapeRight: scaledImageWidth = image.size.width * scaledImageHeight / image.size.height scaledImageHeight = imageView.bounds.size.height } DispatchQueue.global(qos: .userInitiated).async { // Scale image while maintaining aspect ratio so it displays better in the UIImageView. var scaledImage = image.scaledImage( with: CGSize(width: scaledImageWidth, height: scaledImageHeight) ) scaledImage = scaledImage ?? image guard let finalImage = scaledImage else { return } weak var weakSelf = self DispatchQueue.main.async { weakSelf?.imageView.image = finalImage } } } private func transformMatrix() -> CGAffineTransform { guard let image = imageView.image else { return CGAffineTransform() } let imageViewWidth = imageView.frame.size.width let imageViewHeight = imageView.frame.size.height let imageWidth = image.size.width let imageHeight = image.size.height let imageViewAspectRatio = imageViewWidth / imageViewHeight let imageAspectRatio = imageWidth / imageHeight let scale = (imageViewAspectRatio > imageAspectRatio) ? imageViewHeight / imageHeight : imageViewWidth / imageWidth // Image view's `contentMode` is `scaleAspectFit`, which scales the image to fit the size of the // image view by maintaining the aspect ratio. Multiple by `scale` to get image's original size. let scaledImageWidth = imageWidth * scale let scaledImageHeight = imageHeight * scale let xValue = (imageViewWidth - scaledImageWidth) / CGFloat(2.0) let yValue = (imageViewHeight - scaledImageHeight) / CGFloat(2.0) var transform = CGAffineTransform.identity.translatedBy(x: xValue, y: yValue) transform = transform.scaledBy(x: scale, y: scale) return transform } private func requestAutoMLRemoteModelIfNeeded() { let remoteModel = self.remoteModel() if modelManager.isModelDownloaded(remoteModel) { return } downloadAutoMLRemoteModel(remoteModel) } private func downloadAutoMLRemoteModel(_ remoteModel: RemoteModel) { downloadProgressView.isHidden = false let conditions = ModelDownloadConditions( allowsCellularAccess: true, allowsBackgroundDownloading: true) downloadProgressView.observedProgress = modelManager.download( remoteModel, conditions: conditions) print("Start downloading AutoML remote model") } // MARK: - Notifications @objc private func remoteModelDownloadDidSucceed(_ notification: Notification) { weak var weakSelf = self let notificationHandler = { guard let strongSelf = weakSelf else { print("Self is nil!") return } strongSelf.downloadProgressView.isHidden = true strongSelf.downloadOrDeleteModelButton.image = #imageLiteral(resourceName: "delete") guard let userInfo = notification.userInfo, let remoteModel = userInfo[ModelDownloadUserInfoKey.remoteModel.rawValue] as? RemoteModel else { strongSelf.resultsText += "MLKitModelDownloadDidSucceed notification posted without a RemoteModel instance." return } strongSelf.resultsText += "Successfully downloaded the remote model with name: \(remoteModel.name)." strongSelf.resultsText += "The model is ready for detection." print("Sucessfully downloaded AutoML remote model.") } if Thread.isMainThread { notificationHandler() return } DispatchQueue.main.async { notificationHandler() } } @objc private func remoteModelDownloadDidFail(_ notification: Notification) { weak var weakSelf = self let notificationHandler = { guard let strongSelf = weakSelf else { print("Self is nil!") return } strongSelf.downloadProgressView.isHidden = true guard let userInfo = notification.userInfo, let remoteModel = userInfo[ModelDownloadUserInfoKey.remoteModel.rawValue] as? RemoteModel, let error = userInfo[ModelDownloadUserInfoKey.error.rawValue] as? NSError else { strongSelf.resultsText += "MLKitModelDownloadDidFail notification posted without a RemoteModel instance or error." return } strongSelf.resultsText += "Failed to download the remote model with name: \(remoteModel.name), error: \(error)." print("Failed to download AutoML remote model.") } if Thread.isMainThread { notificationHandler() return } DispatchQueue.main.async { notificationHandler() } } } extension ViewController: UIPickerViewDataSource, UIPickerViewDelegate { // MARK: - UIPickerViewDataSource func numberOfComponents(in pickerView: UIPickerView) -> Int { return DetectorPickerRow.componentsCount } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return DetectorPickerRow.rowsCount } // MARK: - UIPickerViewDelegate func pickerView( _ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int ) -> String? { return DetectorPickerRow(rawValue: row)?.description } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { clearResults() } } // MARK: - UIImagePickerControllerDelegate extension ViewController: UIImagePickerControllerDelegate { func imagePickerController( _ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any] ) { // Local variable inserted by Swift 4.2 migrator. let info = convertFromUIImagePickerControllerInfoKeyDictionary(info) clearResults() if let pickedImage = info[ convertFromUIImagePickerControllerInfoKey(UIImagePickerController.InfoKey.originalImage)] as? UIImage { updateImageView(with: pickedImage) } dismiss(animated: true) } } /// Extension of ViewController for AutoML image labeling. extension ViewController { // MARK: - AutoML Image Labeling /// Detects labels on the specified image using AutoML Image Labeling API. /// /// - Parameter image: The image. func detectImageLabels(image: UIImage?) { guard let image = image else { return } requestAutoMLRemoteModelIfNeeded() // [START config_automl_label] let remoteModel = self.remoteModel() guard let localModelFilePath = Bundle.main.path( forResource: Constants.localModelManifestFileName, ofType: Constants.autoMLManifestFileType ) else { print("Failed to find AutoML local model manifest file.") return } let isModelDownloaded = modelManager.isModelDownloaded(remoteModel) var options: CommonImageLabelerOptions! guard let localModel = LocalModel(manifestPath: localModelFilePath) else { return } options = isModelDownloaded ? CustomImageLabelerOptions(remoteModel: remoteModel as! CustomRemoteModel) : CustomImageLabelerOptions(localModel: localModel) print("Use AutoML \(isModelDownloaded ? "remote" : "local") in detector picker.") options.confidenceThreshold = NSNumber(value: Constants.labelConfidenceThreshold) // [END config_automl_label] // [START init_automl_label] let autoMLImageLabeler = ImageLabeler.imageLabeler(options: options) // [END init_automl_label] // Initialize a VisionImage object with the given UIImage. let visionImage = VisionImage(image: image) visionImage.orientation = image.imageOrientation // [START detect_automl_label] weak var weakSelf = self autoMLImageLabeler.process(visionImage) { labels, error in guard let strongSelf = weakSelf else { print("Self is nil!") return } guard error == nil, let labels = labels, !labels.isEmpty else { // [START_EXCLUDE] let errorString = error?.localizedDescription ?? Constants.detectionNoResultsMessage strongSelf.resultsText = "AutoML image labeling failed with error: \(errorString)" strongSelf.showResults() // [END_EXCLUDE] return } // [START_EXCLUDE] strongSelf.resultsText = labels.map { label -> String in return "Label: \(label.text), Confidence: \(label.confidence)" }.joined(separator: "\n") strongSelf.showResults() // [END_EXCLUDE] } // [END detect_automl_label] } /// Detects objects on the specified image using image classification models trained by AutoML /// via Custom Object Detection API. /// /// - Parameter image: The image. /// - Parameter shouldEnableClassification: Whether image classification should be enabled. /// - Parameter shouldEnableMultipleObjects: Whether multi-object detection should be enabled. func detectObjects( image: UIImage?, shouldEnableClassification: Bool, shouldEnableMultipleObjects: Bool ) { guard let image = image else { return } requestAutoMLRemoteModelIfNeeded() let remoteModel = self.remoteModel() var options: CustomObjectDetectorOptions! if modelManager.isModelDownloaded(remoteModel) { print("Use AutoML remote model.") options = CustomObjectDetectorOptions(remoteModel: remoteModel as! CustomRemoteModel) } else { print("Use AutoML local model.") guard let localModelFilePath = Bundle.main.path( forResource: Constants.localModelManifestFileName, ofType: Constants.autoMLManifestFileType ) else { print( "Failed to find AutoML local model manifest file: \(Constants.localModelManifestFileName)" ) return } guard let localModel = LocalModel(manifestPath: localModelFilePath) else { return } options = CustomObjectDetectorOptions(localModel: localModel) } options.shouldEnableClassification = shouldEnableClassification options.shouldEnableMultipleObjects = shouldEnableMultipleObjects options.detectorMode = .singleImage let autoMLObjectDetector = ObjectDetector.objectDetector(options: options) // Initialize a VisionImage object with the given UIImage. let visionImage = VisionImage(image: image) visionImage.orientation = image.imageOrientation weak var weakSelf = self autoMLObjectDetector.process(visionImage) { objects, error in guard let strongSelf = weakSelf else { print("Self is nil!") return } guard error == nil, let objects = objects, !objects.isEmpty else { let errorString = error?.localizedDescription ?? Constants.detectionNoResultsMessage strongSelf.resultsText = "AutoML object detection failed with error: \(errorString)" strongSelf.showResults() return } strongSelf.resultsText = objects.map { object -> String in let transform = strongSelf.transformMatrix() let transformedRect = object.frame.applying(transform) UIUtilities.addRectangle( transformedRect, to: strongSelf.annotationOverlayView, color: .green) let labels = object.labels.enumerated().map { (index, label) -> String in return "Label \(index): \(label.text), \(label.confidence), \(label.index)" }.joined(separator: "\n") return "Frame: \(object.frame)\nObject ID: \(String(describing: object.trackingID))\nLabels:\(labels)" }.joined(separator: "\n") strongSelf.showResults() } } } // MARK: - Enums private enum DetectorPickerRow: Int { // AutoML image label detector. case detectorImageLabels // AutoML object detector, single, only tracking. case detectorObjectsSingleNoClassifier // AutoML object detector, single, with classification. case detectorObjectsSingleWithClassifier // AutoML object detector, multiple, only tracking. case detectorObjectsMultipleNoClassifier // AutoML object detector, multiple, with classification. case detectorObjectsMultipleWithClassifier static let rowsCount = 5 static let componentsCount = 1 public var description: String { switch self { case .detectorImageLabels: return "AutoML Image Labeling" case .detectorObjectsSingleNoClassifier: return "AutoML ODT, single, no labeling" case .detectorObjectsSingleWithClassifier: return "AutoML ODT, single, labeling" case .detectorObjectsMultipleNoClassifier: return "AutoML ODT, multiple, no labeling" case .detectorObjectsMultipleWithClassifier: return "AutoML ODT, multiple, labeling" } } } private enum Constants { static let images = [ "dandelion.jpg", "sunflower.jpg", "tulips.jpeg", "daisy.jpeg", "roses.jpeg", ] static let modelExtension = "tflite" static let localModelName = "mobilenet" static let quantizedModelFilename = "mobilenet_quant_v1_224" static let detectionNoResultsMessage = "No results returned." static let sparseTextModelName = "Sparse" static let denseTextModelName = "Dense" static let remoteAutoMLModelName = "remote_automl_model" static let localModelManifestFileName = "automl_labeler_manifest" static let autoMLManifestFileType = "json" static let labelConfidenceThreshold: Float = 0.75 static let smallDotRadius: CGFloat = 5.0 static let largeDotRadius: CGFloat = 10.0 static let lineColor = UIColor.yellow.cgColor static let fillColor = UIColor.clear.cgColor } // Helper function inserted by Swift 4.2 migrator. private func convertFromUIImagePickerControllerInfoKeyDictionary( _ input: [UIImagePickerController.InfoKey: Any] ) -> [String: Any] { return Dictionary(uniqueKeysWithValues: input.map { key, value in (key.rawValue, value) }) } // Helper function inserted by Swift 4.2 migrator. private func convertFromUIImagePickerControllerInfoKey(_ input: UIImagePickerController.InfoKey) -> String { return input.rawValue }
apache-2.0
31eb9535fa39ef71f9525902299f797e
35.523425
105
0.723195
4.897747
false
false
false
false
honghaoz/Wattpad-Life
Wattpad Life/Controller/MainViewController.swift
1
4459
// // MainViewController.swift // Wattpad Life // // Created by Honghao Zhang on 2014-09-25. // Copyright (c) 2014 HonghaoZ. All rights reserved. // import UIKit let hud:JGProgressHUD = JGProgressHUD() let searchBar:UISearchBar = UISearchBar() class MainViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { @IBOutlet weak var collectionView: UICollectionView! override func viewDidLoad() { super.viewDidLoad() self.navigationController?.navigationBar.barTintColor = mainColor collectionView.delegate = self collectionView.dataSource = self People.sharedPeople.getPeople(nil, failure: nil) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) UIApplication.sharedApplication().setStatusBarStyle(UIStatusBarStyle.LightContent, animated: true) NSNotificationCenter.defaultCenter().addObserver(self, selector: "refresh:", name: "DataUpdated", object: nil) hud.textLabel.text = "Loading" hud.showInView(self.view) } override func viewDidAppear(animated: Bool) { hud.dismissAfterDelay(0.5) } override func viewWillDisappear(animated: Bool) { NSNotificationCenter.defaultCenter().removeObserver(self) hud.dismissAfterDelay(0.5) } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { var cell:CustomCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as CustomCollectionViewCell cell.configureCell(People.sharedPeople.people[indexPath.row].avatarURL, name: People.sharedPeople.people[indexPath.row].name) cell.layoutIfNeeded() return cell } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return People.sharedPeople.people.count } func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets { return UIEdgeInsetsMake(10.0, 10.0, 10.0, 10.0) } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat { return 20.0 } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat { return 10.0 } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { return CGSizeMake(80.0, 100.0) } func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { People.sharedPeople.currentIndex = indexPath.row var detailViewController:DetailUserViewController = UIViewController.viewControllerInStoryboard("Main", viewControllerName: "detailView") as DetailUserViewController var formSheet:MZFormSheetController = MZFormSheetController(viewController: detailViewController) formSheet.shouldCenterVertically = true formSheet.shouldDismissOnBackgroundViewTap = true formSheet.transitionStyle = MZFormSheetTransitionStyle.Bounce formSheet.cornerRadius = 8.0; formSheet.portraitTopInset = 6.0; formSheet.landscapeTopInset = 6.0; formSheet.presentedFormSheetSize = CGSizeMake(self.view.frame.size.width-40.0, self.view.frame.size.height/2.0); var backgroundWindow:MZFormSheetBackgroundWindow = MZFormSheetController.sharedBackgroundWindow() backgroundWindow.backgroundBlurEffect = true backgroundWindow.blurRadius = 5.0 backgroundWindow.backgroundColor = UIColor.clearColor() var appearance:AnyObject = MZFormSheetController.appearance() self.mz_presentFormSheetController(formSheet, animated: true, completionHandler:nil) } @IBAction func refresh(sender: AnyObject) { collectionView.reloadData() } }
apache-2.0
d3899edf06e642d7c1d6cca67fda7b16
41.466667
178
0.738058
5.601759
false
false
false
false
petester42/R.swift
R.swift/func.swift
5
8984
// // func.swift // R.swift // // Created by Mathijs Kadijk on 14-12-14. // From: https://github.com/mac-cain13/R.swift // License: MIT License // import Foundation // MARK: Helper functions let indent = indentWithString(IndentationString) func warn(warning: String) { println("warning: \(warning)") } func fail(error: String) { println("error: \(error)") } func failOnError(error: NSError?) { if let error = error { fail("\(error)") } } func inputDirectories(processInfo: NSProcessInfo) -> [NSURL] { return processInfo.arguments.skip(1).map { NSURL(fileURLWithPath: $0 as! String)! } } func filterDirectoryContentsRecursively(fileManager: NSFileManager, filter: (NSURL) -> Bool)(url: NSURL) -> [NSURL] { var assetFolders = [NSURL]() let errorHandler: (NSURL!, NSError!) -> Bool = { url, error in failOnError(error) return true } if let enumerator = fileManager.enumeratorAtURL(url, includingPropertiesForKeys: [NSURLIsDirectoryKey], options: NSDirectoryEnumerationOptions.SkipsHiddenFiles|NSDirectoryEnumerationOptions.SkipsPackageDescendants, errorHandler: errorHandler) { while let enumeratorItem: AnyObject = enumerator.nextObject() { if let url = enumeratorItem as? NSURL { if filter(url) { assetFolders.append(url) } } } } return assetFolders } func sanitizedSwiftName(name: String, lowercaseFirstCharacter: Bool = true) -> String { var components = name.componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString: " -")) let firstComponent = components.removeAtIndex(0) let swiftName = components.reduce(firstComponent) { $0 + $1.capitalizedString } let capitalizedSwiftName = lowercaseFirstCharacter ? swiftName.lowercaseFirstCharacter : swiftName return contains(SwiftKeywords, capitalizedSwiftName) ? "`\(capitalizedSwiftName)`" : capitalizedSwiftName } func writeResourceFile(code: String, toFolderURL folderURL: NSURL) { let outputURL = folderURL.URLByAppendingPathComponent(ResourceFilename) var error: NSError? code.writeToURL(outputURL, atomically: true, encoding: NSUTF8StringEncoding, error: &error) failOnError(error) } func readResourceFile(folderURL: NSURL) -> String? { let inputURL = folderURL.URLByAppendingPathComponent(ResourceFilename) if let resourceFileString = String(contentsOfURL: inputURL, encoding: NSUTF8StringEncoding, error: nil) { return resourceFileString } return nil } // MARK: Struct/function generators // Image func imageStructFromAssetFolders(assetFolders: [AssetFolder]) -> Struct { let vars = distinct(assetFolders.flatMap { $0.imageAssets }) .map { Var(isStatic: true, name: $0, type: Type._UIImage.asOptional(), getter: "return UIImage(named: \"\($0)\")") } return Struct(type: Type(name: "image"), lets: [], vars: vars, functions: [], structs: []) } // Segue func segueStructFromStoryboards(storyboards: [Storyboard]) -> Struct { let vars = distinct(storyboards.flatMap { $0.segues }) .map { Var(isStatic: true, name: $0, type: Type._String, getter: "return \"\($0)\"") } return Struct(type: Type(name: "segue"), lets: [], vars: vars, functions: [], structs: []) } // Storyboard func storyboardStructFromStoryboards(storyboards: [Storyboard]) -> Struct { return Struct(type: Type(name: "storyboard"), lets: [], vars: [], functions: [], structs: storyboards.map(storyboardStructForStoryboard)) } func storyboardStructForStoryboard(storyboard: Storyboard) -> Struct { let instanceVars = [Var(isStatic: true, name: "instance", type: Type._UIStoryboard, getter: "return UIStoryboard(name: \"\(storyboard.name)\", bundle: nil)")] let initialViewControllerVar = catOptionals([storyboard.initialViewController.map { Var(isStatic: true, name: "initialViewController", type: $0.type.asOptional(), getter: "return instance.instantiateInitialViewController() as? \($0.type.asNonOptional())") }]) let viewControllerVars = catOptionals(storyboard.viewControllers .map { vc in vc.storyboardIdentifier.map { return Var(isStatic: true, name: $0, type: vc.type.asOptional(), getter: "return instance.instantiateViewControllerWithIdentifier(\"\($0)\") as? \(vc.type.asNonOptional())") } }) let validateImagesLines = distinct(storyboard.usedImageIdentifiers) .map { "assert(UIImage(named: \"\($0)\") != nil, \"[R.swift] Image named '\($0)' is used in storyboard '\(storyboard.name)', but couldn't be loaded.\")" } let validateImagesFunc = Function(isStatic: true, name: "validateImages", generics: nil, parameters: [], returnType: Type._Void, body: join("\n", validateImagesLines)) let validateViewControllersLines = catOptionals(storyboard.viewControllers .map { vc in vc.storyboardIdentifier.map { "assert(\(sanitizedSwiftName($0)) != nil, \"[R.swift] ViewController with identifier '\(sanitizedSwiftName($0))' could not be loaded from storyboard '\(storyboard.name)' as '\(vc.type)'.\")" } }) let validateViewControllersFunc = Function(isStatic: true, name: "validateViewControllers", generics: nil, parameters: [], returnType: Type._Void, body: join("\n", validateViewControllersLines)) return Struct(type: Type(name: sanitizedSwiftName(storyboard.name)), lets: [], vars: instanceVars + initialViewControllerVar + viewControllerVars, functions: [validateImagesFunc, validateViewControllersFunc], structs: []) } // Nib func nibStructFromNibs(nibs: [Nib]) -> Struct { return Struct(type: Type(name: "nib"), lets: [], vars: nibs.map(nibVarForNib), functions: [], structs: []) } func internalNibStructFromNibs(nibs: [Nib]) -> Struct { return Struct(type: Type(name: "nib"), lets: [], vars: [], functions: [], structs: nibs.map(nibStructForNib)) } func nibVarForNib(nib: Nib) -> Var { let structType = Type(name: "_R.nib._\(nib.name)") return Var(isStatic: true, name: nib.name, type: structType, getter: "return \(structType)()") } func nibStructForNib(nib: Nib) -> Struct { let instantiateParameters = [ Function.Parameter(name: "ownerOrNil", type: Type._AnyObject.asOptional()), Function.Parameter(name: "options", localName: "optionsOrNil", type: Type(name: "[NSObject : AnyObject]", optional: true)) ] let instanceVar = Var( isStatic: false, name: "instance", type: Type._UINib, getter: "return UINib.init(nibName: \"\(nib.name)\", bundle: nil)" ) let instantiateFunc = Function( isStatic: false, name: "instantiateWithOwner", generics: nil, parameters: instantiateParameters, returnType: Type(name: "[AnyObject]"), body: "return instance.instantiateWithOwner(ownerOrNil, options: optionsOrNil)" ) let viewFuncs = zip(nib.rootViews, Ordinals) .map { (view: $0.0, ordinal: $0.1) } .map { Function( isStatic: false, name: "\($0.ordinal.word)View", generics: nil, parameters: instantiateParameters, returnType: $0.view.asOptional(), body: "return \(instantiateFunc.callName)(ownerOrNil, options: optionsOrNil)[\($0.ordinal.number - 1)] as? \($0.view)" ) } let reuseIdentifierVars: [Var] let reuseProtocols: [Type] if let reusable = nib.reusables.first where nib.rootViews.count == 1 && nib.reusables.count == 1 { let reusableVar = varFromReusable(reusable) reuseIdentifierVars = [Var( isStatic: false, name: "reuseIdentifier", type: reusableVar.type, getter: reusableVar.getter )] reuseProtocols = [ReusableProtocol.type] } else { reuseIdentifierVars = [] reuseProtocols = [] } let sanitizedName = sanitizedSwiftName(nib.name, lowercaseFirstCharacter: false) return Struct( type: Type(name: "_\(sanitizedName)"), implements: [NibResourceProtocol.type] + reuseProtocols, lets: [], vars: [instanceVar] + reuseIdentifierVars, functions: [instantiateFunc] + viewFuncs, structs: [] ) } // Reuse identifiers func reuseIdentifierStructFromReusables(reusables: [Reusable]) -> Struct { let reuseIdentifierVars = reusables.map(varFromReusable) return Struct(type: Type(name: "reuseIdentifier"), lets: [], vars: reuseIdentifierVars, functions: [], structs: []) } func varFromReusable(reusable: Reusable) -> Var { return Var( isStatic: true, name: reusable.identifier, type: ReuseIdentifier.type.withGenericType(reusable.type), getter: "return \(ReuseIdentifier.type.name)(identifier: \"\(reusable.identifier)\")" ) } // Validation func validateAllFunctionWithStoryboards(storyboards: [Storyboard]) -> Function { return Function(isStatic: true, name: "validate", generics: nil, parameters: [], returnType: Type._Void, body: join("\n", storyboards.map(swiftCallStoryboardValidators))) } func swiftCallStoryboardValidators(storyboard: Storyboard) -> String { return "storyboard.\(sanitizedSwiftName(storyboard.name)).validateImages()\n" + "storyboard.\(sanitizedSwiftName(storyboard.name)).validateViewControllers()" }
mit
f4ee9d28c22e0bf12f22f19c2105933b
35.520325
246
0.706256
4.102283
false
false
false
false
chrisbudro/GrowlerHour
growlers/BreweryBrowseTableViewController.swift
1
1318
// // BreweryBrowseTableViewController.swift // growlers // // Created by Chris Budro on 9/8/15. // Copyright (c) 2015 chrisbudro. All rights reserved. // import UIKit class BreweryBrowseTableViewController: BaseBrowseViewController { //MARK: Life Cycle Methods override func viewDidLoad() { super.viewDidLoad() title = "Breweries" cellReuseIdentifier = kBreweryCellReuseIdentifier tableView.registerNib(UINib(nibName: kBreweryNibName, bundle: nil), forCellReuseIdentifier: cellReuseIdentifier) dataSource = TableViewDataSource(cellReuseIdentifier:cellReuseIdentifier, configureCell: configureCell) tableView.dataSource = dataSource updateBrowseList() } } //MARK: Table View Delegate extension BreweryBrowseTableViewController { override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let vc = BreweryDetailTableViewController(style: .Plain) if let brewery = dataSource?.objectAtIndexPath(indexPath) as? Brewery { vc.brewery = brewery if let queryManager = queryManager { let breweryQueryManager = QueryManager(type: .Tap, filter: queryManager.filter) vc.queryManager = breweryQueryManager } } navigationController?.pushViewController(vc, animated: true) } }
mit
49f06f41ce82b06f90728a8559047998
29.651163
116
0.745068
4.758123
false
false
false
false
CaptainTeemo/IGKit
IGKit/Utils/Global.swift
1
643
// // Global.swift // IGKit // // Created by CaptainTeemo on 5/13/16. // Copyright © 2016 CaptainTeemo. All rights reserved. // /** Register with necessary information. - parameter clientId: Instagram client id. - parameter secret: Instagram client secret. - parameter redirectURI: Instagram redirect uri. */ public func register(clientId: String, secret: String, redirectURI: String) { UserDefaults.clientId = clientId UserDefaults.secret = secret UserDefaults.redirectURI = redirectURI } let AccessTokenKey = "access_token" let ErrorDomain = "com.igkit.error" let BaseUrl = "https://api.instagram.com/v1"
mit
0f67fd7e5e571f3ee152efadec5dc678
23.692308
77
0.719626
3.86747
false
false
false
false
mozilla-mobile/firefox-ios
Client/Frontend/Home/Wallpapers/v1/Models/WallpaperCollectionAvailability.swift
2
833
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/ import Foundation /// Describes the start and end date of a collection's availability. Either case being /// `nil` implies forever availability in that time direction. struct WallpaperCollectionAvailability: Codable, Equatable { static func == (lhs: WallpaperCollectionAvailability, rhs: WallpaperCollectionAvailability) -> Bool { return lhs.start == rhs.start && lhs.end == rhs.end } let start: Date? let end: Date? var isAvailable: Bool { let now = Date() let start = start ?? now - 1 let end = end ?? now + 1 return start < now && end > now } }
mpl-2.0
7829db65b8bb9c1fe25d7b03f2b62411
33.708333
105
0.655462
4.228426
false
false
false
false
snakajima/SNTrim
src/SNTrimColorPicker.swift
1
5534
// // SNTrimColorPicker.swift // SNTrim // // Created by satoshi on 9/13/16. // Copyright © 2016 Satoshi Nakajima. All rights reserved. // import UIKit protocol SNTrimColorPickerDelegate: class { func wasColorSelected(_ vc:SNTrimColorPicker, color:UIColor?) } class SNTrimColorPicker: UIViewController { @IBOutlet var mainView:UIView! @IBOutlet var colorView:UIView! @IBOutlet var labelHint:UILabel! let preView = UIView(frame: CGRect(origin: .zero, size: CGSize(width: 80, height: 80))) weak var delegate:SNTrimColorPickerDelegate! var image:UIImage! var color:UIColor! var helpText = "Pick A Color" var xform = CGAffineTransform.identity let imageLayer = CALayer() // Transient properties for handlePinch fileprivate var anchor = CGPoint.zero fileprivate var delta = CGPoint.zero override func viewDidLoad() { super.viewDidLoad() //mainView.image = image mainView.layer.addSublayer(imageLayer) mainView.transform = xform imageLayer.contents = image.cgImage imageLayer.contentsGravity = CALayerContentsGravity.resizeAspect colorView.backgroundColor = color labelHint.text = helpText self.view.addSubview(preView) preView.alpha = 0 preView.layer.cornerRadius = preView.bounds.size.width / 2.0 preView.layer.masksToBounds = true } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() imageLayer.frame = mainView.layer.bounds } 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. } */ @IBAction func done() { self.presentingViewController?.dismiss(animated: true) { self.delegate.wasColorSelected(self, color: self.color) } } @IBAction func cancel() { self.presentingViewController?.dismiss(animated: true) { self.delegate.wasColorSelected(self, color: nil) } } private func pickColor(with recognizer:UIGestureRecognizer, offset:CGSize) { let pt = recognizer.location(in: mainView) let data = NSMutableData(length: 4)! let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue) let context = CGContext(data: data.mutableBytes, width: 1, height: 1, bitsPerComponent: 8, bytesPerRow: 4, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: bitmapInfo.rawValue)! context.concatenate(CGAffineTransform(translationX: -pt.x, y: -pt.y)) imageLayer.render(in: context) let bytes = data.bytes.assumingMemoryBound(to: UInt8.self) color = UIColor(red: CGFloat(bytes[0]) / 255, green: CGFloat(bytes[1]) / 255, blue: CGFloat(bytes[2]) / 255, alpha: 1.0) colorView.backgroundColor = color preView.backgroundColor = color preView.center = recognizer.location(in: view).translate(x: offset.width, y: offset.height) UIView.animate(withDuration: 0.2) { self.labelHint.alpha = 0.0 } } @IBAction func handlePan(_ recognizer:UIPanGestureRecognizer) { switch(recognizer.state) { case .began: preView.alpha = 1.0 pickColor(with:recognizer, offset:CGSize(width: 0.0, height: -88.0)) case .changed: pickColor(with:recognizer, offset:CGSize(width: 0.0, height: -88.0)) default: UIView.animate(withDuration: 0.2) { self.preView.alpha = 0.0 } } } @IBAction func handleTap(_ recognizer:UITapGestureRecognizer) { pickColor(with:recognizer, offset:.zero) preView.alpha = 1.0 UIView.animate(withDuration: 0.2) { self.preView.alpha = 0.0 } } } // // MARK: HandlePinch // extension SNTrimColorPicker { private func setTransformAnimated(xform:CGAffineTransform) { self.xform = xform UIView.animate(withDuration: 0.2) { self.mainView.transform = xform } } @IBAction func handlePinch(_ recognizer:UIPinchGestureRecognizer) { let ptMain = recognizer.location(in: mainView) let ptView = recognizer.location(in: view) switch(recognizer.state) { case .began: anchor = ptView delta = ptMain.delta(mainView.center) case .changed: if recognizer.numberOfTouches == 2 { var offset = ptView.delta(anchor) offset.x /= xform.a offset.y /= xform.a var xf = xform.translatedBy(x: offset.x + delta.x, y: offset.y + delta.y) xf = xf.scaledBy(x: recognizer.scale, y: recognizer.scale) xf = xf.translatedBy(x: -delta.x, y: -delta.y) self.mainView.transform = xf } case .ended: xform = self.mainView.transform if xform.a < 0.5 { setTransformAnimated(xform: CGAffineTransform.identity) } default: self.mainView.transform = xform } } }
mit
e1476a2b3837f1d2103dd52cbbb7d776
33.798742
186
0.63293
4.458501
false
false
false
false
theappbusiness/ConfigGenerator
configen/CommandLineKit/CommandLineKit.swift
1
13969
/* * CommandLine.swift * Copyright (c) 2014 Ben Gollmer. * * 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 /* Required for setlocale(3) */ #if os(OSX) import Darwin #elseif os(Linux) import Glibc #endif let shortOptionPrefix = "-" let longOptionPrefix = "--" /* Stop parsing arguments when an ArgumentStopper (--) is detected. This is a GNU getopt * convention; cf. https://www.gnu.org/prep/standards/html_node/Command_002dLine-Interfaces.html */ let argumentStopper = "--" /* Allow arguments to be attached to flags when separated by this character. * --flag=argument is equivalent to --flag argument */ let argumentAttacher: Character = "=" /* An output stream to stderr; used by CommandLine.printUsage(). */ private struct StderrOutputStream: TextOutputStream { static let stream = StderrOutputStream() func write(_ s: String) { fputs(s, stderr) } } /** * The CommandLine class implements a command-line interface for your app. * * To use it, define one or more Options (see Option.swift) and add them to your * CommandLine object, then invoke `parse()`. Each Option object will be populated with * the value given by the user. * * If any required options are missing or if an invalid value is found, `parse()` will throw * a `ParseError`. You can then call `printUsage()` to output an automatically-generated usage * message. */ public final class CommandLineKit { private var _arguments: [String] private var _options: [Option] = [Option]() private var _maxFlagDescriptionWidth: Int = 0 private var _usedFlags: Set<String> { var usedFlags = Set<String>(minimumCapacity: _options.count * 2) for option in _options { for case let flag? in [option.shortFlag, option.longFlag] { usedFlags.insert(flag) } } return usedFlags } /** * After calling `parse()`, this property will contain any values that weren't captured * by an Option. For example: * * ``` * let cli = CommandLine() * let fileType = StringOption(shortFlag: "t", longFlag: "type", required: true, helpMessage: "Type of file") * * do { * try cli.parse() * print("File type is \(type), files are \(cli.unparsedArguments)") * catch { * cli.printUsage(error) * exit(EX_USAGE) * } * * --- * * $ ./readfiles --type=pdf ~/file1.pdf ~/file2.pdf * File type is pdf, files are ["~/file1.pdf", "~/file2.pdf"] * ``` */ public private(set) var unparsedArguments: [String] = [String]() /** * If supplied, this function will be called when printing usage messages. * * You can use the `defaultFormat` function to get the normally-formatted * output, either before or after modifying the provided string. For example: * * ``` * let cli = CommandLine() * cli.formatOutput = { str, type in * switch(type) { * case .Error: * // Make errors shouty * return defaultFormat(str.uppercaseString, type: type) * case .OptionHelp: * // Don't use the default indenting * return ">> \(s)\n" * default: * return defaultFormat(str, type: type) * } * } * ``` * * - note: Newlines are not appended to the result of this function. If you don't use * `defaultFormat()`, be sure to add them before returning. */ public var formatOutput: ((String, OutputType) -> String)? /** * The maximum width of all options' `flagDescription` properties; provided for use by * output formatters. * * - seealso: `defaultFormat`, `formatOutput` */ public var maxFlagDescriptionWidth: Int { if _maxFlagDescriptionWidth == 0 { _maxFlagDescriptionWidth = _options.map { $0.flagDescription.count }.sorted().first ?? 0 } return _maxFlagDescriptionWidth } /** * The type of output being supplied to an output formatter. * * - seealso: `formatOutput` */ public enum OutputType { /** About text: `Usage: command-example [options]` and the like */ case about /** An error message: `Missing required option --extract` */ case error /** An Option's `flagDescription`: `-h, --help:` */ case optionFlag /** An Option's help message */ case optionHelp } /** A ParseError is thrown if the `parse()` method fails. */ public enum ParseError: Error, CustomStringConvertible { /** Thrown if an unrecognized argument is passed to `parse()` in strict mode */ case invalidArgument(String) /** Thrown if the value for an Option is invalid (e.g. a string is passed to an IntOption) */ case invalidValueForOption(Option, [String]) /** Thrown if an Option with required: true is missing */ case missingRequiredOptions([Option]) public var description: String { switch self { case let .invalidArgument(arg): return "Invalid argument: \(arg)" case let .invalidValueForOption(opt, vals): let vs = vals.joined(separator: ", ") return "Invalid value(s) for option \(opt.flagDescription): \(vs)" case let .missingRequiredOptions(opts): return "Missing required options: \(opts.map { return $0.flagDescription })" } } } /** * Initializes a CommandLine object. * * - parameter arguments: Arguments to parse. If omitted, the arguments passed to the app * on the command line will automatically be used. * * - returns: An initalized CommandLine object. */ public init(arguments: [String] = Swift.CommandLine.arguments) { self._arguments = arguments /* Initialize locale settings from the environment */ setlocale(LC_ALL, "") } /* Returns all argument values from flagIndex to the next flag or the end of the argument array. */ private func _getFlagValues(_ flagIndex: Int, _ attachedArg: String? = nil) -> [String] { var args: [String] = [String]() var skipFlagChecks = false if let a = attachedArg { args.append(a) } for i in flagIndex + 1 ..< _arguments.count { if !skipFlagChecks { if _arguments[i] == argumentStopper { skipFlagChecks = true continue } if _arguments[i].hasPrefix(shortOptionPrefix) && Int(_arguments[i]) == nil && _arguments[i].toDouble() == nil { break } } args.append(_arguments[i]) } return args } /** * Adds an Option to the command line. * * - parameter option: The option to add. */ public func addOption(_ option: Option) { let uf = _usedFlags for case let flag? in [option.shortFlag, option.longFlag] { assert(!uf.contains(flag), "Flag '\(flag)' already in use") } _options.append(option) _maxFlagDescriptionWidth = 0 } /** * Adds one or more Options to the command line. * * - parameter options: An array containing the options to add. */ public func addOptions(_ options: [Option]) { for o in options { addOption(o) } } /** * Adds one or more Options to the command line. * * - parameter options: The options to add. */ public func addOptions(_ options: Option...) { for o in options { addOption(o) } } /** * Sets the command line Options. Any existing options will be overwritten. * * - parameter options: An array containing the options to set. */ public func setOptions(_ options: [Option]) { _options = [Option]() addOptions(options) } /** * Sets the command line Options. Any existing options will be overwritten. * * - parameter options: The options to set. */ public func setOptions(_ options: Option...) { _options = [Option]() addOptions(options) } /** * Parses command-line arguments into their matching Option values. * * - parameter strict: Fail if any unrecognized flags are present (default: false). * * - throws: A `ParseError` if argument parsing fails: * - `.InvalidArgument` if an unrecognized flag is present and `strict` is true * - `.InvalidValueForOption` if the value supplied to an option is not valid (for * example, a string is supplied for an IntOption) * - `.MissingRequiredOptions` if a required option isn't present */ public func parse(strict: Bool = false) throws { var strays = _arguments /* Nuke executable name */ strays[0] = "" let argumentsEnumerator = _arguments.enumerated() for (idx, arg) in argumentsEnumerator { if arg == argumentStopper { break } if !arg.hasPrefix(shortOptionPrefix) { continue } let skipChars = arg.hasPrefix(longOptionPrefix) ? longOptionPrefix.count : shortOptionPrefix.count let flagWithArg = arg[arg.index(arg.startIndex, offsetBy: skipChars)..<arg.endIndex] /* The argument contained nothing but ShortOptionPrefix or LongOptionPrefix */ if flagWithArg.isEmpty { continue } /* Remove attached argument from flag */ let splitFlag = flagWithArg.split(separator: argumentAttacher, maxSplits: 1) let flag = splitFlag[0] let attachedArg: String? = splitFlag.count == 2 ? String(splitFlag[1]) : nil var flagMatched = false for option in _options where option.flagMatch(String(flag)) { let vals = self._getFlagValues(idx, attachedArg) guard option.setValue(vals) else { throw ParseError.invalidValueForOption(option, vals) } var claimedIdx = idx + option.claimedValues if attachedArg != nil { claimedIdx -= 1 } for i in idx...claimedIdx { strays[i] = "" } flagMatched = true break } /* Flags that do not take any arguments can be concatenated */ let flagLength = flag.count if !flagMatched && !arg.hasPrefix(longOptionPrefix) { let flagCharactersEnumerator = flag.enumerated() for (i, c) in flagCharactersEnumerator { for option in _options where option.flagMatch(String(c)) { /* Values are allowed at the end of the concatenated flags, e.g. * -xvf <file1> <file2> */ let vals = (i == flagLength - 1) ? self._getFlagValues(idx, attachedArg) : [String]() guard option.setValue(vals) else { throw ParseError.invalidValueForOption(option, vals) } var claimedIdx = idx + option.claimedValues if attachedArg != nil { claimedIdx -= 1 } for i in idx...claimedIdx { strays[i] = "" } flagMatched = true break } } } /* Invalid flag */ guard !strict || flagMatched else { throw ParseError.invalidArgument(arg) } } /* Check to see if any required options were not matched */ let missingOptions = _options.filter { $0.required && !$0.wasSet } guard missingOptions.count == 0 else { throw ParseError.missingRequiredOptions(missingOptions) } unparsedArguments = strays.filter { $0 != "" } } /** * Provides the default formatting of `printUsage()` output. * * - parameter s: The string to format. * - parameter type: Type of output. * * - returns: The formatted string. * - seealso: `formatOutput` */ public func defaultFormat(s: String, type: OutputType) -> String { switch type { case .about: return "\(s)\n" case .error: return "\(s)\n\n" case .optionFlag: return " \(s.padded(toWidth: maxFlagDescriptionWidth)):\n" case .optionHelp: return " \(s)\n" } } /* printUsage() is generic for OutputStreamType because the Swift compiler crashes * on inout protocol function parameters in Xcode 7 beta 1 (rdar://21372694). */ /** * Prints a usage message. * * - parameter to: An OutputStreamType to write the error message to. */ public func printUsage<TargetStream: TextOutputStream>(_ to: inout TargetStream) { /* Nil coalescing operator (??) doesn't work on closures :( */ let format = formatOutput != nil ? formatOutput! : defaultFormat let name = _arguments[0] print(format("Usage: \(name) [options]", .about), terminator: "", to: &to) for opt in _options { print(format(opt.flagDescription, .optionFlag), terminator: "", to: &to) print(format(opt.helpMessage, .optionHelp), terminator: "", to: &to) } } /** * Prints a usage message. * * - parameter error: An error thrown from `parse()`. A description of the error * (e.g. "Missing required option --extract") will be printed before the usage message. * - parameter to: An OutputStreamType to write the error message to. */ public func printUsage<TargetStream: TextOutputStream>(_ error: Error, to: inout TargetStream) { let format = formatOutput != nil ? formatOutput! : defaultFormat print(format("\(error)", .error), terminator: "", to: &to) printUsage(&to) } /** * Prints a usage message. * * - parameter error: An error thrown from `parse()`. A description of the error * (e.g. "Missing required option --extract") will be printed before the usage message. */ public func printUsage(_ error: Error) { var out = StderrOutputStream.stream printUsage(error, to: &out) } /** * Prints a usage message. */ public func printUsage() { var out = StderrOutputStream.stream printUsage(&out) } }
mit
746a799a5714f72bbe7a01019a5e8073
29.633772
111
0.636696
4.222793
false
false
false
false
lethianqt94/Swift-DropdownMenu-ParallaxTableView
ModuleDemo/ModuleDemo/Classes/Helpers/Common/DropdownMenu/DropdownMenu/DropdownMenuView.swift
1
7771
// // DropdownMenuView.swift // ModuleDemo // // Created by An Le on 3/1/16. // Copyright © 2016 Le Thi An. All rights reserved. // import UIKit enum Selection { case Default case Single case Multiple } enum IconType { case Default case None case Custom } @objc protocol DropdownMenuDelegate: NSObjectProtocol{ optional func menuDidSelectedAtIndex(index: Int) optional func menuDidSelectedAtIndexs(indexItems: [Int]) } class DropdownMenuView: UIView { //MARK: Outlets @IBOutlet weak var view: UIView! @IBOutlet weak var fadeView: UIView! @IBOutlet weak var tableView: UITableView! // var selectRowAtIndexPathHandler: ((indexPath: Int) -> ())? weak var delegate:DropdownMenuDelegate? var selection:Selection = .Default var iconType:IconType = .Default var cellIcon:UIImage = UIImage(named: "img_header.png")! var menuTitles:[String] = [] var currentItems:[Int] = [] var cellHeight:CGFloat = 30 var textColorNomal:UIColor = UIColor.blackColor() var textColorHighlight:UIColor = UIColor(red: 76/266, green: 175/266, blue: 80/255, alpha: 1) var isShown: Bool = false //MARK: Lifecycle override func layoutSubviews() { super.layoutSubviews() } // MARK: Init override init(frame: CGRect) { super.init(frame: frame) initSubviews() } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! initSubviews() } func initSubviews() { if let nibsView = NSBundle.mainBundle().loadNibNamed("DropdownMenuView", owner: self, options: nil) as? [UIView] { let nibRoot = nibsView[0] self.addSubview(nibRoot) nibRoot.frame = self.bounds } tableView.registerNib(UINib(nibName: "DropdownMenuCell", bundle: nil), forCellReuseIdentifier: "DropdownMenuCell") tableView.contentSize.height = cellHeight*CGFloat(menuTitles.count) tableView.scrollEnabled = false tableView.layer.borderWidth = 1 tableView.layer.borderColor = UIColor(red: 240/255, green: 240/255, blue: 240/255, alpha: 1).CGColor tableView.clipsToBounds = false tableView.layer.masksToBounds = false tableView.layer.shadowColor = UIColor(red: 240/255, green: 240/255, blue: 240/255, alpha: 1).CGColor tableView.layer.shadowOffset = CGSizeMake(0, 0) tableView.layer.shadowRadius = 2.0 tableView.layer.shadowOpacity = 1 // self.selectRowAtIndexPathHandler = { (indexPath: Int) -> () in // } switch (selection) { case Selection.Multiple: tableView.allowsMultipleSelection = true default: tableView.allowsMultipleSelection = false } } convenience init(uSelection: Selection = Selection.Default, uIconType:IconType = IconType.Default, uMenuTitles:[String]) { self.init(frame: CGRect(x: 0, y: 0, width: 0, height: 0)) self.selection = uSelection self.iconType = uIconType self.menuTitles = uMenuTitles } convenience init(uSelection: Selection = Selection.Default, icon:UIImage, uMenuTitles:[String]) { self.init(frame: CGRect(x: 0, y: 0, width: 0, height: 0)) self.selection = uSelection self.iconType = IconType.Custom self.cellIcon = icon self.menuTitles = uMenuTitles } // MARK: show/hide action override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { hide() } internal func show() { if self.isShown == false { self.showMenu() } } internal func hide() { if self.isShown == true { self.hideMenu() } } func showMenu() { self.isShown = true tableView.reloadData() // Animation UIView.animateWithDuration(0.3, animations: { () -> Void in self.alpha = 1 }) } func hideMenu() { self.isShown = false // Animation UIView.animateWithDuration(0.3, animations: { () -> Void in self.alpha = 0 }) } // MARK: setup View internal func setIconImage(image:UIImage) { self.cellIcon = image } internal func setBg(color:UIColor) { fadeView.backgroundColor = color } internal func setTableBorderColor(color:UIColor) { tableView.layer.borderColor = color.CGColor } internal func setColorHighlight(color:UIColor) { textColorHighlight = color } internal func setColorNomal(color:UIColor) { textColorNomal = color } } //MARK: UITableViewDelegate methods extension DropdownMenuView: UITableViewDelegate { func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return cellHeight } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if selection == Selection.Multiple { if currentItems.count == 0 { currentItems.append(indexPath.row) } else { var isOld:Bool = false for index in currentItems { if index == indexPath.row { isOld = true break } else { isOld = false } } if isOld == false { currentItems.append(indexPath.row) } else { tableView.deselectRowAtIndexPath(indexPath, animated: true) currentItems.removeAtIndex(currentItems.indexOf(indexPath.row)!) } } } else { currentItems = [] currentItems.append(indexPath.row) if let d = delegate where d.respondsToSelector("menuDidSelectedAtIndex:") { d.menuDidSelectedAtIndex!(indexPath.row) } self.hide() } if let d = delegate where d.respondsToSelector("menuDidSelectedAtIndexs:") { d.menuDidSelectedAtIndexs!(currentItems) } // delegate!.menuDidSelectedAtIndex!(indexPath.row) // selectRowAtIndexPathHandler!(indexPath: indexPath.row) tableView.reloadData() } } //MARK: UITableViewDataSource methods extension DropdownMenuView: UITableViewDataSource { func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return menuTitles.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("DropdownMenuCell") as! DropdownMenuCell cell.lblTitle.text = menuTitles[indexPath.row] cell.initWithItemType(iconType, iconCustom: cellIcon) var isSelected:Bool = false for index in currentItems { if index == indexPath.row { isSelected = true break } else { isSelected = false } } if isSelected == true { cell.imvIcon.hidden = false cell.lblTitle.textColor = textColorHighlight } else { cell.imvIcon.hidden = true cell.lblTitle.textColor = textColorNomal } return cell } }
mit
1647e8cbb032469cff022a2a7863b168
27.671587
126
0.58314
4.968031
false
false
false
false
yoha/Thoughtless
Pods/CFAlertViewController/CFAlertViewController/Transitions/CFAlertViewControllerActionSheetTransition.swift
1
6524
// // CFAlertViewControllerActionSheetTransition.swift // CFAlertViewControllerDemo // // Created by Shivam Bhalla on 1/20/17. // Copyright © 2017 Codigami Inc. All rights reserved. // import UIKit @objc(CFAlertViewControllerActionSheetTransition) public class CFAlertViewControllerActionSheetTransition: NSObject { // MARK: - Declarations @objc public enum CFAlertActionSheetTransitionType : Int { case present = 0 case dismiss } // MARK: - Variables // MARK: Public public var transitionType = CFAlertActionSheetTransitionType(rawValue: 0) // MARK: - Initialisation Methods public override init() { super.init() // Default Transition Type transitionType = CFAlertActionSheetTransitionType(rawValue: 0) } } // MARK: - UIViewControllerAnimatedTransitioning extension CFAlertViewControllerActionSheetTransition: UIViewControllerAnimatedTransitioning { public func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.4 } public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { // Get context vars let duration: TimeInterval = self.transitionDuration(using: transitionContext) let containerView: UIView? = transitionContext.containerView let fromViewController: UIViewController? = transitionContext.viewController(forKey: .from) let toViewController: UIViewController? = transitionContext.viewController(forKey: .to) // Call Will System Methods fromViewController?.beginAppearanceTransition(false, animated: true) toViewController?.beginAppearanceTransition(true, animated: true) if self.transitionType == .present { /** SHOW ANIMATION **/ if let alertViewController = toViewController as? CFAlertViewController, let containerView = containerView { alertViewController.view?.frame = containerView.frame alertViewController.view?.autoresizingMask = [.flexibleWidth, .flexibleHeight] alertViewController.view?.translatesAutoresizingMaskIntoConstraints = true containerView.addSubview(alertViewController.view) alertViewController.view?.layoutIfNeeded() var frame: CGRect? = alertViewController.containerView?.frame frame?.origin.y = containerView.frame.size.height alertViewController.containerView?.frame = frame! // Background let backgroundColorRef: UIColor? = alertViewController.backgroundColor alertViewController.backgroundColor = UIColor.clear if alertViewController.backgroundStyle == .blur { alertViewController.backgroundBlurView?.alpha = 0.0 } UIView.animate(withDuration: duration, delay: 0.0, usingSpringWithDamping: 1.0, initialSpringVelocity: 0.0, options: [.curveEaseIn, .beginFromCurrentState], animations: {() -> Void in // Background if alertViewController.backgroundStyle == .blur { alertViewController.backgroundBlurView?.alpha = 1.0 } alertViewController.backgroundColor = backgroundColorRef }, completion: nil) // Animate height changes UIView.animate(withDuration: duration, delay: 0.0, usingSpringWithDamping: 1.0, initialSpringVelocity: 0.0, options: [.curveEaseIn, .beginFromCurrentState], animations: {() -> Void in alertViewController.view?.layoutIfNeeded() var frame: CGRect? = alertViewController.containerView?.frame frame?.origin.y = (frame?.origin.y)! - (frame?.size.height)! - 10 alertViewController.containerView?.frame = frame! }, completion: {(_ finished: Bool) -> Void in // Call Did System Methods toViewController?.endAppearanceTransition() fromViewController?.endAppearanceTransition() // Declare Animation Finished transitionContext.completeTransition(!transitionContext.transitionWasCancelled) }) } else { // Call Did System Methods toViewController?.endAppearanceTransition() fromViewController?.endAppearanceTransition() // Declare Animation Finished transitionContext.completeTransition(!transitionContext.transitionWasCancelled) } } else if self.transitionType == .dismiss { /** HIDE ANIMATION **/ let alertViewController: CFAlertViewController? = (fromViewController as? CFAlertViewController) // Animate height changes UIView.animate(withDuration: duration, delay: 0.0, usingSpringWithDamping: 1.0, initialSpringVelocity: 0.0, options: [.curveEaseIn, .beginFromCurrentState], animations: {() -> Void in alertViewController?.view?.layoutIfNeeded() var frame: CGRect? = alertViewController?.containerView?.frame frame?.origin.y = (containerView?.frame.size.height)! alertViewController?.containerView?.frame = frame! // Background if alertViewController?.backgroundStyle == .blur { alertViewController?.backgroundBlurView?.alpha = 0.0 } alertViewController?.view?.backgroundColor = UIColor.clear }, completion: {(_ finished: Bool) -> Void in // Call Did System Methods toViewController?.endAppearanceTransition() fromViewController?.endAppearanceTransition() // Declare Animation Finished transitionContext.completeTransition(!transitionContext.transitionWasCancelled) }) } } }
mit
948edc355e60e4a06a3f0b914abe0840
43.678082
199
0.602024
6.96158
false
false
false
false
malkouz/ListPlaceholder
Example/ListPlaceholder/MFlatView.swift
1
1364
import UIKit @IBDesignable class MFlatView: UIView { /* // Only override draw() if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func draw(_ rect: CGRect) { // Drawing code } */ @IBInspectable var borderColor:UIColor = UIColor.lightGray @IBInspectable var cornerRadius:CGFloat = 5.0 @IBInspectable var shadowRadius:CGFloat = 5.0 @IBInspectable var borderWidth:CGFloat = 0.5 @IBInspectable var shadowOffset:CGFloat = -1 @IBInspectable var shadowColor:UIColor = UIColor.lightGray @IBInspectable var shadowOpacity:Float = 0.8 override func layoutSubviews() { super.layoutSubviews() if(self.shadowOffset >= 0){ self.layer.shadowColor = self.shadowColor.cgColor self.layer.shadowOffset = CGSize(width: shadowOffset, height: shadowOffset) self.layer.shadowOpacity = shadowOpacity self.layer.shadowRadius = shadowRadius self.clipsToBounds = true self.layer.masksToBounds = false } self.layer.cornerRadius = self.cornerRadius self.layer.borderColor = self.borderColor.cgColor self.layer.borderWidth = self.borderWidth //self.layer.masksToBounds = true } }
mit
067fcecb5c250010e7edef1afb041092
30.72093
87
0.652493
5.206107
false
false
false
false
ahayman/RxStream
RxStream/Utilities/Throttle.swift
1
6892
// // Throttle.swift // RxStream // // Created by Aaron Hayman on 3/7/17. // Copyright © 2017 Aaron Hayman. All rights reserved. // import Foundation /// Handler that should be called when a piece of throttled work is complete public typealias WorkCompletion = () -> Void /** Throttled work is a simple closure that takes a WorkSignal to indicate whether the work should be performed or cancelled. If the work is to be performed, a completion handler is passed in to be called when the work is complete. Failing to call the completion handler may result in a Throttle becoming locked up. */ public typealias ThrottledWork = (WorkSignal) -> Void /// Defines the signal whether work should execute or be cancelled. public enum WorkSignal { /// A signal that work should be executed. When the work is complete, the provided completion handler should be called. case perform(WorkCompletion) /// A signal that work should be cancelled. Any relevant cleanup should be done. case cancel } /** A throttle is a simple protocol that defines a function to take a piece of work and process it according the specific throttle's internal rules. - note: Depending on the throttle, not all work may end up being processed. - warning: Many throttles will retain the work for processing later. Be careful about creating retain cycles. - warning: All work should call the WorkCompletion handler when finished or else risk locking up the throttle. Some throttles will retain themself (create a lock) while work is being processed, which may cause leaks if the WorkCompletion handler isn't called. */ public protocol Throttle { /// A throttle should take the work provided and process it according to it's internal rules. The work closure should call the completion handler when it's finished. func process(work: @escaping (WorkSignal) -> Void) } /** A timed throttle will only process work on a specific interval. Any additional work that is added will replace whatever work is in the current queue and that work will be dropped. Once the interval has passed, whatever work is currently in the queue will be processed and discarded. */ public final class TimedThrottle : Throttle { /// The last time work was processed. Used to calculate the next time work can be processed. private var last: Double? /// The interval between the last time a work was processed and the next time new work can be processed. private let interval: Double /// Current work waiting for processing. private var work: ThrottledWork? /// Used to keep track of when a dispatch was sent to process the next work so we don't send a new dispatch. private var dispatched = false /// If `true`, the first work presented will be delayed by the interval. Otherwise, the first work will be processed immeditialy and all subsequent work will be timed. private let delayFirst: Bool /** Initializes a new TimedThrottle with an interval and optionally whether the first work should be delayed. - note: all work is dispatched on the main thread. - parameter interval: The allowable interval between which work can be processed. - parameter delayFirst: Whether the first work should be processed immediately or delayed by the interval - returns: TimedThrottle */ public init(interval: Double, delayFirst: Bool = false) { self.delayFirst = delayFirst self.interval = interval } /// Calculates the remaining interval left before new work can be processed. If negative or 0, work can be processed immediately. private var remainingInterval: Double { guard let last = self.last else { return delayFirst ? interval : 0.0 } let next = last + interval return next - Date.timeIntervalSinceReferenceDate } public func process(work: @escaping ThrottledWork) { let remaining = remainingInterval guard remaining > 0.0 else { last = Date.timeIntervalSinceReferenceDate Dispatch.sync(on: .main).execute{ work(.perform{ }) } return } self.work?(.cancel) //If pending work, cancel it. self.work = work guard !dispatched else { return } dispatched = true Dispatch.after(delay: remaining, on: .main).execute { self.last = Date.timeIntervalSinceReferenceDate self.work?(.perform{ }) self.work = nil self.dispatched = false } } } /** A Pressure Throttle limits the amount of work that can be processed by defining a limit of current work that can be run and using a buffer to store extra work. As work is finished, new work is pulled from the buffer. All incoming work will be dropped if both the buffer and working queue limits are reached. - Note: The `pressureLimit` essentially defines the maximum number of concurrent tasks/work that can be performed. - Warning: You cannot set a `pressureLimit` below 1. - Warning: Setting the `buffer` to `0` means all work will be dropped if the pressure limit is reached. */ public final class PressureThrottle : Throttle { private let bufferSize: Int private let limit: Int private var working = [String: ThrottledWork]() private var buffer = [ThrottledWork]() private let lockQueue = Dispatch.sync(on: .custom(CustomQueue(type: .serial, name: "PressureThrottleLockQueue"))) /** Initialize a PressureThrottle with a buffer and a limit. - parameter buffer: The size of the buffer to hold work when the pressure limit is reached. If a buffer is full, then work will be dropped until there is room. - parameter limit: Basically represents the number of concurrent work that can be processed. Default: 1 - returns: PressureThrottle */ public init(buffer: Int, limit: Int = 1) { self.bufferSize = max(0, buffer) self.limit = max(1, limit) } /// This will queue work into the working buffer. Once work is finished, it's removed from working and work is pulled from the buffer until the pressure limit is filled or the buffer is empty. private func queue(work: @escaping ThrottledWork) { let key = String.newUUID() self.working[key] = work Dispatch.sync(on: .main).execute { work(.perform{ self.lockQueue.execute { self.working[key] = nil while self.buffer.count > 0 && self.working.count < self.limit { self.queue(work: self.buffer.removeFirst()) } } }) } } /// Work is either queued up for processing if the pressure is less than the limit, appended to the buffer if it has room, or else dropped. public func process(work: @escaping ThrottledWork) { lockQueue.execute { guard self.working.count >= self.limit else { return self.queue(work: work) } if self.buffer.count < self.bufferSize { self.buffer.append(work) } else { work(.cancel) } } } }
mit
0517dc7a4d332d8a020f9ed2f66b6b2d
41.018293
308
0.716152
4.471772
false
false
false
false
Lves/LLRefresh
LLRefresh/Extension/UIScrollView+LLExtension.swift
1
4086
// // UIScrollView+LLExtension.swift // LLRefrsh // // Created by 李兴乐 on 2016/12/2. // Copyright © 2016年 com.wildcat. All rights reserved. // import UIKit var LLRefreshHeaderKey = "\0" var LLRefreshFooterKey = "\0" var LLRefreshReloadDataBlockKey = "\0" public typealias VoidBlock = (_ count: Int?)->(Void) class LLObjectWrapper: NSObject { let value: ((_ count: Int?) -> Void)? init(value: @escaping (_ count: Int?) -> Void) { self.value = value } } public extension UIScrollView { public var ll_header:LLBaseRefreshHeader? { set{ if newValue != ll_header { self.ll_header?.removeFromSuperview() self.insertSubview(newValue!, at: 0) //存储 self.willChangeValue(forKey: "ll_header") objc_setAssociatedObject(self, &LLRefreshHeaderKey, newValue, .OBJC_ASSOCIATION_ASSIGN) self.didChangeValue(forKey: "ll_header") } } get{ let header = objc_getAssociatedObject(self, &LLRefreshHeaderKey) as? LLBaseRefreshHeader return header } } public var ll_footer:LLBaseRefreshHeader? { set{ if newValue != ll_footer { self.ll_footer?.removeFromSuperview() self.insertSubview(newValue!, at: 0) //存储 self.willChangeValue(forKey: "ll_footer") objc_setAssociatedObject(self, &LLRefreshFooterKey, newValue, .OBJC_ASSOCIATION_ASSIGN) self.didChangeValue(forKey: "ll_footer") } } get{ let header = objc_getAssociatedObject(self, &LLRefreshFooterKey) as? LLBaseRefreshHeader return header } } public var ll_reloadDataBlock:VoidBlock? { set{ self.willChangeValue(forKey: "ll_reloadDataBlock") let wrapper = LLObjectWrapper(value: newValue!) objc_setAssociatedObject(self, &LLRefreshReloadDataBlockKey, wrapper, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) self.didChangeValue(forKey: "ll_reloadDataBlock") } get{ let wrapper:LLObjectWrapper? = objc_getAssociatedObject(self, &LLRefreshReloadDataBlockKey) as? LLObjectWrapper return wrapper?.value } } } extension UIScrollView { public var ll_offsetY: CGFloat { get { return self.contentOffset.y } set(value) { var offset = self.contentOffset offset.y = ll_offsetY self.contentOffset = offset } } public var ll_contentH: CGFloat { get { return self.contentSize.height } set(value) { var contentSize = self.contentSize contentSize.height = value self.contentSize = contentSize } } public var ll_insetTop: CGFloat { get { return self.contentInset.top } set(value) { var contentInset = self.contentInset contentInset.top = value self.contentInset = contentInset } } public var ll_insetBottom: CGFloat { get { return self.contentInset.bottom } set(value) { var contentInset = self.contentInset contentInset.bottom = value self.contentInset = contentInset } } public var ll_insetLeft: CGFloat { get { return self.contentInset.left } set(value) { var contentInset = self.contentInset contentInset.left = value self.contentInset = contentInset } } public var ll_insetRight: CGFloat { get { return self.contentInset.right } set(value) { var contentInset = self.contentInset contentInset.right = value self.contentInset = contentInset } } }
mit
979c2f921f39a121f9a587173a3b118a
26.680272
123
0.557385
4.86141
false
false
false
false
LucyJeong/LearningCS50
Week5/ListAndGeneric.playground/Contents.swift
1
5944
//: Playground - noun: a place where people can play import Foundation //리스트 public class LinkedListNode<T> { var value: T var next: LinkedListNode? weak var previous: LinkedListNode? public init(value: T) { self.value = value } } public class LinkedList<T> { public typealias Node = LinkedListNode<T> //we're using a typealias so inside LinkedList we can write the shorter Node instead of LinkedListNode<T>. var head: Node? public var isEmpty: Bool { return head == nil } public var first: Node? { return head } public var last: Node? { //If you're new to Swift, you've probably seen if let but maybe not if var. It does the same thing -- it unwraps the head optional and puts the result in a new local variable named node. The difference is that node is not a constant but an actual variable, so we can change it inside the loop. if var node = head { while case let next? = node.next { node = next } return node } else { return nil } } public func append(value: T) { let newNode = Node(value: value) if let lastNode = last { newNode.previous = lastNode lastNode.next = newNode } else { head = newNode } } //One way to speed up count from O(n) to O(1) is to keep track of a variable that counts how many nodes are in the list. Whenever you add or remove a node, you also update this variable. public var count: Int { if var node = head { var c = 1 while case let next? = node.next { node = next c += 1 } return c } else { return 0 } } public func nodeAt(_ index: Int) -> Node? { if index >= 0 { var node = head var i = index while node != nil { if i == 0 { return node } i -= 1 node = node!.next } } return nil } public subscript(index: Int) -> T { let node = nodeAt(index) assert(node != nil) return node!.value } private func nodesBeforeAndAfter(index: Int) -> (Node?,Node?) { var i = index var next = head var prev: Node? while next != nil && i > 0 { i -= 1 prev = next next = next!.next } assert(i == 0) return (prev,next) } public func insert(_ value: T, atIndex index: Int) { let (prev,next) = nodesBeforeAndAfter(index: index) let newNode = Node(value: value) newNode.previous = prev newNode.next = next prev?.next = newNode next?.previous = newNode if prev == nil { head = newNode } } public func removeAll() { head = nil } public func remove(node: Node) -> T { let prev = node.previous let next = node.next if let prev = prev { prev.next = next } else { head = next } next?.previous = prev node.previous = nil node.next = nil return node.value } public func removeLast() -> T { assert(!isEmpty) return remove(node: last!) } public func removeAt(_ index: Int) -> T { let node = nodeAt(index) assert(node != nil) return remove(node: node!) } } let list = LinkedList<String>() list.isEmpty list.first list.append(value: "Hello") list.isEmpty list.first!.value list.last!.value /* +---------+ head --->| |---> nil | "Hello" | nil <---| | +---------+ */ list.append(value: "World") list.first!.value list.last!.value /* +---------+ +---------+ head --->| |--->| |---> nil | "Hello" | | "World" | nil <---| |<---| | +---------+ +---------+ */ list.nodeAt(0)!.value list[0] list.insert("Swift", atIndex: 1) list[1] list.remove(node: list.first!) list.count //제네릭 //not using generic struct IntStack { var items = [Int]() mutating func push(_ item: Int) { items.append(item) } mutating func pop() -> Int { return items.removeLast() } } var integerStack = IntStack() integerStack.push(3) integerStack.push(5) integerStack.push(3) print(integerStack.items) integerStack.pop() print(integerStack.items) //using generic struct Stack<Element> { var items = [Element]() mutating func push(_ item: Element){ items.append(item) } mutating func pop() -> Element { return items.removeLast() } } var doubleStack = Stack<Double>() doubleStack.push(1.0) doubleStack.push(2.0) doubleStack.pop() //Stack item array를 Any타입으로 정의하는 것보다 제네릭을 사용했을 때 훨씬 유연하고 광범위하게 사용할 수 있으며, Element 타입을 정해주면 그 타입에만 동작하도록 제한할 수 있어 더욱 안전하고 의도된 대로 기능을 사용하도록 유도할 수 있습니다. var anyStack = Stack<Any>() anyStack.push("1") anyStack.push(1) anyStack.pop() //익스텐션을 토해 제네릭을 사용하는데 기능을 추가하고자 한다면, 정의에 타입 매개변수를 명시하지 않음. 대신 원래의 제네릭 정의에 명시된 타입 매개변수를 익스텐션에서 사용 가능함. extension Stack { var topElement: Element? { return self.items.last } } //타입제약은 클래스타입 또는 프로토콜로만 줄 수 있습니다. 열거형, 구조체 타입은 사용 될 수 없음.
mit
7af741a78f55f3d35247a0508f9c41ab
22.615385
301
0.52624
3.579016
false
false
false
false
mmrmmlrr/ExamMaster
Pods/ModelsTreeKit/JetPack/UIKit+Signal/UIControl+Signal.swift
1
2413
// // UIControl+Signal.swift // ModelsTreeKit // // Created by aleksey on 06.03.16. // Copyright © 2016 aleksey chernish. All rights reserved. // import UIKit extension UIControl { public func signalForControlEvents(events: UIControlEvents) -> Pipe<UIControl> { return signalEmitter.signalForControlEvents(events) } } private class ControlSignalEmitter: NSObject { init(control: UIControl) { self.control = control super.init() initializeSignalsMap() } func signalForControlEvents(events: UIControlEvents) -> Pipe<UIControl> { var correspondingSignals = [Pipe<UIControl>]() for event in eventsList { if events.contains(UIControlEvents(rawValue: event)) { correspondingSignals.append(signalsMap[event]!) } } return Signals.merge(correspondingSignals).pipe() } private static var EmitterHandler: Int = 0 private weak var control: UIControl! private var signalsMap = [UInt: Pipe<UIControl>]() private let controlProxy = ControlProxy.newProxy() private let eventsList: [UInt] = [ UIControlEvents.EditingChanged.rawValue, UIControlEvents.ValueChanged.rawValue, UIControlEvents.EditingDidEnd.rawValue, UIControlEvents.EditingDidBegin.rawValue, UIControlEvents.EditingDidEndOnExit.rawValue, UIControlEvents.TouchUpInside.rawValue ] private let signaturePrefix = "selector" private func initializeSignalsMap() { for eventRawValue in eventsList { signalsMap[eventRawValue] = Pipe<UIControl>() let signal = signalsMap[eventRawValue] let selectorString = signaturePrefix + String(eventRawValue) controlProxy.registerBlock({ [weak signal, unowned self] in signal?.sendNext(self.control) }, forKey: selectorString) control.addTarget(self.controlProxy, action: NSSelectorFromString(selectorString), forControlEvents: UIControlEvents(rawValue: eventRawValue)) } } } private extension UIControl { var signalEmitter: ControlSignalEmitter { get { var emitter = objc_getAssociatedObject(self, &ControlSignalEmitter.EmitterHandler) as? ControlSignalEmitter if (emitter == nil) { emitter = ControlSignalEmitter(control: self) objc_setAssociatedObject(self, &ControlSignalEmitter.EmitterHandler, emitter, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } return emitter! } } }
mit
f7864d5ee19dc584237ca54dceb38188
27.72619
148
0.717662
4.692607
false
false
false
false
embryoconcepts/TIY-Assignments
17 -- GithubFriends/GithubFriends/GithubFriends/AppDelegate.swift
1
2728
// // AppDelegate.swift // GithubFriends // // Created by Jennifer Hamilton on 10/27/15. // Copyright © 2015 The Iron Yard. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. // set up window == screen size window = UIWindow(frame: UIScreen.mainScreen().bounds) // let friendListVC = FriendTableViewController() // let newFriendVC = NewFriendViewController() // create navigation controller let navController = UINavigationController(rootViewController: friendListVC) // puts albumVC in navController, in window window?.rootViewController = navController window?.makeKeyAndVisible() // navController.pushViewController(newFriendVC, animated: false) 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:. } }
cc0-1.0
b907dbe5fb3ca3e78ec25546f3fde0dc
44.45
285
0.73744
5.657676
false
false
false
false
embryoconcepts/TIY-Assignments
02 -- Human/Human.playground/Contents.swift
1
8027
class BodyPart { let latinName: String let exists: Bool let healthy: Bool init(argLatinName: String, argExists: Bool, argHealthy: Bool){ self.latinName = argLatinName self.exists = argExists self.healthy = argHealthy } func repair(latinName: String, doctor: String, technique: String) { } func replace(latinName: String, exists: Bool, donor: String) { } func remove(latinName: String, patientApproval: Bool, isEmergency: Bool) { } } class Head : BodyPart { let hairColor: String = "" let hairStyle: String = "" let hasNose: Bool = true func changeHairColor(currentColor: String, newColor: String) { } func changeHairStyle(currentStyle: String, newStyle: String, cost: Double) { } func blowNose(hasTissue: Bool, hasNose: Bool) { } } class Hand : BodyPart { let length: Double = 0 let width: Double = 0 let fingerCount: Int = 0 func makeFist(fingerCount: Int, isAngry: Bool) { } func openHand(fingerCount: Int, isHoldingSomething: Bool) { } func waveHand(isGreeting: Bool) { } } class Foot : BodyPart { let shoeSize: Double = 0 let shoeWidth: String = "" let toeCount: Int = 10 func flexToes(footExists: Bool) { } func fixFoot(footExists: Bool, footIsHealthy: Bool) { // utilize super.repair() } func wiggleToes(isHealthy: Bool) { } } class Finger : BodyPart { let hasNail: Bool = true let nailColor: String = "" let isDoubleJointed: Bool = false func paintNail(nailExists: Bool, hasNail: Bool, colorSelection: String) { } func poke(fingerExists: Bool, fingerIsHealthy: Bool, victim: String) { } func scratch(hasNail: Bool, target: String) { } } class Toe : BodyPart { let littlePiggieDestination: String = "market" let isBlistered: Bool = false let nickname: String = "This Little Piggie" func goHome(whichPiggy: String, whereTo: String) { } func healToe(isBlistered: Bool, nickname: String) { } func fitTightShooes(toeExists: Bool) { // super.remove(toe) } } class Limb : BodyPart { var isJointHealthy: Bool = true var rightOrLeft: String = "" var needsBrace: Bool = false func bend(healthyJoint: Bool) { } func straighten(whichSide: String) { } func wearBrace(latinName: String, needsBrace: Bool) { } } class Leg : Limb { let isKneeIntact: Bool = true let numOfSurgeries: Int = 0 let isHairy: Bool = true func shave(wearingBrace: Bool, isStraight: Bool, isHairy: Bool) { // utilizes super.straighten(<#T##whichSide: String##String#>) } func replace(latinName: String, healthyJoint: Bool, doctor: String) { // overides superclass func } func bend(healthyJoint: Bool, isIntact: Bool) { // overloads Limb bend func } } class Arm : Limb { let length: Double = 0 let width: Double = 0 let jointName: String = "" func liftWeights(isStrong: Bool, isHealthy: Bool) { } func showGuns(isStrong: Bool) { } func hug(armExists: Bool) { } } class Organ : BodyPart { let isOriginal: Bool = true let availableToDonate: Bool = true let isViable: Bool = true func recieveDonation(isViable: Bool, latinName: String) { // utilize super.replace() } func giveDonation(availableToDonate: Bool, isViable: Bool, recipient: String, doctor: String) { // utilize remove method } func test(organExists: Bool, doctor: String) { } } class Heart : Organ { let beatsPerMin: Int = 0 let hasMurmur: Bool = false let hasPalpitations: Bool = false func restart(exists: Bool, isViable: Bool, hasShockerThingie: Bool) { } func repair(latinName: String, doctor: String, technique: String, isViable: Bool) { // overloads super method } func breakHeart(exists: Bool, nemesis: String) { } } class Liver : Organ { let numOfLobes: Int = 4 let color: String = "" let feels: String = "" func partialDonation(latinName: String, patientApproval: Bool, isEmergency: Bool) { } func abuse(numOfBeers: Int) { } func rest(status: String, timeToRest: Int) { } } class Kidney : Organ { let numOfKidneys: Int = 2 let healthOfKid1: String = "fair" let healthOfKid2: String = "excellent" func donateOneKidney(whichKidney: Int, viable: Bool) { // isViable() // remove() } func insertDonatedKidney(patientHealth: String, doctor: String) { } func checkSymptoms(feelsPain: Bool, discomfortLevel: Int) { } } class Skin : Organ { let hasTattoos: Bool = false let skinType: String = "" let isHairy: Bool = false func removeTattoos(isHairy: Bool, isHealthy: Bool) { } func wash(skinExists: Bool, skinDirty: Bool, skinType: String) { } func wax(isHairy: Bool, waxType: String) { } } class Lungs : Organ { let numOfLungs: Int = 2 let lungColor: String = "" let coughing: Bool = false func testLungs(doctor: String, testType: String, isCoughing: Bool) { } func treatForCough(isCoughing: Bool, medicine: String) { } func aspirate(lungExists: Bool, doctor: String) { } } class Stomach : Organ { let phLevel: Double = 7.0 let isDistended: Bool = false let hungerLevel1to10: Int = 5 func feed(howHungry: Int, isHealthy: Bool) { } func takeAntacid(phLevel: Double) { } func test(organExists: Bool, doctor: String, isDistended: Bool) { } } class Gallbladder : Organ { let isNeeded: Bool = true let painLevel1to10: Int = 0 let hasStones: Bool = false func remove(latinName: String, patientApproval: Bool, isEmergency: Bool, surgeryType: String) { // over load super method } func checkBileProduction(testMethod: String, doctor: String) { } func rename(latinName: String, newFunName: String) { // I'm getting desperate here } } class Appendix : Organ { let isObsolete: Bool = true let isInflamed: Bool = false let appendixColor: String = "" func checkAppendix(doesItExist: Bool, isInflamed: Bool, testMethod: String) { } func treatAppendix(doctor: String, treatmentCourse: String) { } func remove(latinName: String, isEmergency: Bool, patientConsentSigned: Bool) { } } class Pancreas : Organ { let condition: String = "" let weight: Double = 0 let doingBusinessAs: String = "" func rename(formalName: String, newName: String) { } func putOnDiet(currentWeight: Double, targetWeight: Double) { } func improveHealth(currentCondition: String, treatment: String, targetCondition: String) { } } class Bladder : Organ { let isFull: Bool = false let hasUTI: Bool = false let hasStones: Bool = false func emptyBladder(isBladderFull: Bool) { } func treatStones(doctor: String, treatment: String) { } func treatUTI(doctor: String, medication: String) { } }
cc0-1.0
33becf582af3c0c0f54a92b9a0ff31fd
16.957494
97
0.565093
3.831504
false
false
false
false
Jnosh/swift
test/NameBinding/scope_map.swift
6
28697
// Note: test of the scope map. All of these tests are line- and // column-sensitive, so any additions should go at the end. struct S0 { class InnerC0 { } } extension S0 { } class C0 { } enum E0 { case C0 case C1(Int, Int) } struct GenericS0<T, U> { } func genericFunc0<T, U>(t: T, u: U, i: Int = 10) { } class ContainsGenerics0 { init<T, U>(t: T, u: U) { } deinit { } } typealias GenericAlias0<T> = [T] #if arch(unknown) struct UnknownArchStruct { } #else struct OtherArchStruct { } #endif func functionBodies1(a: Int, b: Int?) { let (x1, x2) = (a, b), (y1, y2) = (b, a) let (z1, z2) = (a, a) do { let a1 = a let a2 = a do { let b1 = b let b2 = b } } do { let b1 = b let b2 = b } func f(_ i: Int) -> Int { return i } let f2 = f(_:) struct S7 { } typealias S7Alias = S7 if let b1 = b, let b2 = b { let c1 = b } else { let c2 = b } guard let b1 = b, { $0 > 5 }(b1), let b2 = b else { let c = 5 return } while let b3 = b, let b4 = b { let c = 5 } repeat { } while true; for (x, y) in [(1, "hello"), (2, "world")] where x % 2 == 0 { } do { try throwing() } catch let mine as MyError where mine.value == 17 { } catch { } switch MyEnum.second(1) { case .second(let x) where x == 17: break; case .first: break; default: break; } for (var i = 0; i != 10; i += 1) { } } func throwing() throws { } struct MyError : Error { var value: Int } enum MyEnum { case first case second(Int) case third } struct StructContainsAbstractStorageDecls { subscript (i: Int, j: Int) -> Int { set { } get { return i + j } } var computed: Int { get { return 0 } set { } } } class ClassWithComputedProperties { var willSetProperty: Int = 0 { willSet { } } var didSetProperty: Int = 0 { didSet { } } } func funcWithComputedProperties(i: Int) { var computed: Int { set { } get { return 0 } }, var (stored1, stored2) = (1, 2), var alsoComputed: Int { return 17 } do { } } func closures() { { x, y in return { $0 + $1 }(x, y) }(1, 2) + { a, b in a * b }(3, 4) } { closures() }() func defaultArguments(i: Int = 1, j: Int = { $0 + $1 }(1, 2)) { func localWithDefaults(i: Int = 1, j: Int = { $0 + $1 }(1, 2)) { } let a = i + j { $0 }(a) } struct PatternInitializers { var (a, b) = (1, 2), (c, d) = (1.5, 2.5) } protocol ProtoWithSubscript { subscript(native: Int) -> Int { get set } } func localPatternsWithSharedType() { let i, j, k: Int } class LazyProperties { var value: Int = 17 lazy var prop: Int = self.value } // RUN: not %target-swift-frontend -dump-scope-maps expanded %s 2> %t.expanded // RUN: %FileCheck -check-prefix CHECK-EXPANDED %s < %t.expanded // CHECK-EXPANDED: SourceFile{{.*}}scope_map.swift{{.*}}expanded // CHECK-EXPANDED-NEXT: TypeDecl {{.*}} S0 [4:1 - 6:1] expanded // CHECK-EXPANDED-NEXT: TypeOrExtensionBody {{.*}} 'S0' [4:11 - 6:1] expanded // CHECK-EXPANDED-NEXT: -TypeDecl {{.*}} InnerC0 [5:3 - 5:19] expanded // CHECK-EXPANDED-NEXT: `-TypeOrExtensionBody {{.*}} 'InnerC0' [5:17 - 5:19] expanded // CHECK-EXPANDED-NEXT: -ExtensionGenericParams {{.*}} extension of 'S0' [8:14 - 9:1] expanded // CHECK-EXPANDED-NEXT: -TypeOrExtensionBody {{.*}} extension of 'S0' [8:14 - 9:1] expanded // CHECK-EXPANDED-NEXT: TypeDecl {{.*}} C0 [11:1 - 12:1] expanded // CHECK-EXPANDED-NEXT: -TypeOrExtensionBody {{.*}} 'C0' [11:10 - 12:1] expanded // CHECK-EXPANDED-NEXT: TypeDecl {{.*}} E0 [14:1 - 17:1] expanded // CHECK-EXPANDED-NEXT: -TypeOrExtensionBody {{.*}} 'E0' [14:9 - 17:1] expanded // CHECK-EXPANDED-NEXT: TypeDecl {{.*}} GenericS0 [19:1 - 20:1] expanded // CHECK-EXPANDED-NEXT: -GenericParams {{.*}} param 0 [19:18 - 20:1] expanded // CHECK-EXPANDED-NEXT: -GenericParams {{.*}} param 1 [19:21 - 20:1] expanded // CHECK-EXPANDED-NEXT: -TypeOrExtensionBody {{.*}} 'GenericS0' [19:24 - 20:1] expanded // CHECK-EXPANDED-NEXT:-AbstractFunctionDecl {{.*}} genericFunc0(t:u:i:) [22:1 - 23:1] expanded // CHECK-EXPANDED-NEXT: -GenericParams {{.*}} param 0 [22:19 - 23:1] expanded // CHECK-EXPANDED-NEXT: -GenericParams {{.*}} param 1 [22:22 - 23:1] expanded // CHECK-EXPANDED-NEXT: -AbstractFunctionParams {{.*}} genericFunc0(t:u:i:) param 0:0 [22:28 - 23:1] expanded // CHECK-EXPANDED-NEXT: -AbstractFunctionParams {{.*}} genericFunc0(t:u:i:) param 0:1 [22:34 - 23:1] expanded // CHECK-EXPANDED: |-DefaultArgument {{.*}} [22:46 - 22:46] expanded // CHECK-EXPANDED: `-AbstractFunctionParams {{.*}} genericFunc0(t:u:i:) param 0:2 [22:46 - 23:1] expanded // CHECK-EXPANDED-NEXT: `-AbstractFunctionBody {{.*}} genericFunc0(t:u:i:) [22:50 - 23:1] expanded // CHECK-EXPANDED-NEXT: -BraceStmt {{.*}} [22:50 - 23:1] expanded // CHECK-EXPANDED-NEXT: TypeDecl {{.*}} ContainsGenerics0 [25:1 - 31:1] expanded // CHECK-EXPANDED-NEXT: -TypeOrExtensionBody {{.*}} 'ContainsGenerics0' [25:25 - 31:1] expanded // CHECK-EXPANDED-NEXT: -AbstractFunctionDecl {{.*}} init(t:u:) [26:3 - 27:3] expanded // CHECK-EXPANDED-NEXT: -GenericParams {{.*}} param 0 [26:8 - 27:3] expanded // CHECK-EXPANDED-NEXT: -GenericParams {{.*}} param 1 [26:11 - 27:3] expanded // CHECK-EXPANDED-NEXT: -AbstractFunctionParams {{.*}} init(t:u:) param 0:0 [26:13 - 27:3] expanded // CHECK-EXPANDED-NEXT: -AbstractFunctionParams {{.*}} init(t:u:) param 1:0 [26:17 - 27:3] expanded // CHECK-EXPANDED-NEXT: -AbstractFunctionParams {{.*}} init(t:u:) param 1:1 [26:23 - 27:3] expanded // CHECK-EXPANDED-NEXT: `-AbstractFunctionBody {{.*}} init(t:u:) [26:26 - 27:3] expanded // CHECK-EXPANDED-NEXT: -BraceStmt {{.*}} [26:26 - 27:3] expanded // CHECK-EXPANDED-NEXT: -AbstractFunctionDecl {{.*}} deinit // CHECK-EXPANDED-NEXT: -AbstractFunctionParams {{.*}} deinit param 0:0 [29:3 - 30:3] expanded // CHECK-EXPANDED-NEXT: `-AbstractFunctionBody {{.*}} deinit [29:10 - 30:3] expanded // CHECK-EXPANDED-NEXT: -BraceStmt {{.*}} [29:10 - 30:3] expanded // CHECK-EXPANDED-NEXT: TypeDecl {{.*}} GenericAlias0 [33:1 - 33:32] expanded // CHECK-EXPANDED-NEXT: -GenericParams {{.*}} param 0 [33:25 - 33:32] expanded // CHECK-EXPANDED-NEXT: TypeDecl {{.*}} {{.*}}ArchStruct [{{.*}}] expanded // CHECK-EXPANDED-NEXT: TypeOrExtensionBody {{.*}} '{{.*}}ArchStruct' [{{.*}}] expanded // CHECK-EXPANDED-NEXT: {{^}}|-AbstractFunctionDecl {{.*}} functionBodies1(a:b:) [41:1 - 100:1] expanded // CHECK-EXPANDED-NEXT: {{^}} `-AbstractFunctionParams {{.*}} functionBodies1(a:b:) param 0:0 [41:25 - 100:1] expanded // CHECK-EXPANDED-NEXT: {{^}} `-AbstractFunctionParams {{.*}} functionBodies1(a:b:) param 0:1 [41:36 - 100:1] expanded // CHECK-EXPANDED-NEXT: `-AbstractFunctionBody {{.*}} functionBodies1(a:b:) [41:39 - 100:1] expanded // CHECK-EXPANDED-NEXT: {{^}} `-BraceStmt {{.*}} [41:39 - 100:1] expanded // CHECK-EXPANDED-NEXT: {{^}} `-PatternBinding {{.*}} entry 0 [42:7 - 100:1] expanded // CHECK-EXPANDED-NEXT: {{^}} |-PatternInitializer {{.*}} entry 0 [42:18 - 42:23] expanded // CHECK-EXPANDED-NEXT: {{^}} `-AfterPatternBinding {{.*}} entry 0 [42:23 - 100:1] expanded // CHECK-EXPANDED-NEXT: {{^}} `-PatternBinding {{.*}} entry 1 [43:7 - 100:1] expanded // CHECK-EXPANDED-NEXT: {{^}} |-PatternInitializer {{.*}} entry 1 [43:18 - 43:23] expanded // CHECK-EXPANDED-NEXT: {{^}} `-AfterPatternBinding {{.*}} entry 1 [43:23 - 100:1] expanded // CHECK-EXPANDED-NEXT: {{^}} `-PatternBinding {{.*}} entry 0 [44:7 - 100:1] expanded // CHECK-EXPANDED-NEXT: {{^}} |-PatternInitializer {{.*}} entry 0 [44:18 - 44:23] expanded // CHECK-EXPANDED-NEXT: {{^}} `-AfterPatternBinding {{.*}} entry 0 [44:23 - 100:1] expanded // CHECK-EXPANDED-NEXT: {{^}} |-BraceStmt {{.*}} [45:6 - 52:3] expanded // CHECK-EXPANDED-NEXT: {{^}} `-PatternBinding {{.*}} entry 0 [46:9 - 52:3] expanded // CHECK-EXPANDED-NEXT: {{^}} |-PatternInitializer {{.*}} entry 0 [46:14 - 46:14] expanded // CHECK-EXPANDED-NEXT: {{^}} `-AfterPatternBinding {{.*}} entry 0 [46:14 - 52:3] expanded // CHECK-EXPANDED-NEXT: {{^}} `-PatternBinding {{.*}} entry 0 [47:9 - 52:3] expanded // CHECK-EXPANDED-NEXT: {{^}} |-PatternInitializer {{.*}} entry 0 [47:14 - 47:14] expanded // CHECK-EXPANDED-NEXT: {{^}} `-AfterPatternBinding {{.*}} entry 0 [47:14 - 52:3] expanded // CHECK-EXPANDED-NEXT: {{^}} `-BraceStmt {{.*}} [48:8 - 51:5] expanded // CHECK-EXPANDED-NEXT: {{^}} `-PatternBinding {{.*}} entry 0 [49:11 - 51:5] expanded // CHECK-EXPANDED-NEXT: {{^}} |-PatternInitializer {{.*}} entry 0 [49:16 - 49:16] expanded // CHECK-EXPANDED-NEXT: {{^}} `-AfterPatternBinding {{.*}} entry 0 [49:16 - 51:5] expanded // CHECK-EXPANDED-NEXT: {{^}} `-PatternBinding {{.*}} entry 0 [50:11 - 51:5] expanded // CHECK-EXPANDED-NEXT: {{^}} |-PatternInitializer {{.*}} entry 0 [50:16 - 50:16] expanded // CHECK-EXPANDED-NEXT: {{^}} `-AfterPatternBinding {{.*}} entry 0 [50:16 - 51:5] expanded // CHECK-EXPANDED-NEXT: {{^}} |-BraceStmt {{.*}} [53:6 - 56:3] expanded // CHECK-EXPANDED-NEXT: {{^}} `-PatternBinding {{.*}} entry 0 [54:9 - 56:3] expanded // CHECK-EXPANDED-NEXT: {{^}} |-PatternInitializer {{.*}} entry 0 [54:14 - 54:14] expanded // CHECK-EXPANDED-NEXT: {{^}} `-AfterPatternBinding {{.*}} entry 0 [54:14 - 56:3] expanded // CHECK-EXPANDED: {{^}} `-AfterPatternBinding {{.*}} entry 0 [55:14 - 56:3] expanded // CHECK-EXPANDED-NEXT: {{^}} |-AbstractFunctionDecl {{.*}} f(_:) [57:3 - 57:38] expanded // CHECK-EXPANDED-NEXT: {{^}} `-AbstractFunctionParams {{.*}} f(_:) param 0:0 [57:15 - 57:38] expanded // CHECK-EXPANDED-NEXT: `-AbstractFunctionBody {{.*}} f(_:) [57:27 - 57:38] expanded // CHECK-EXPANDED-NEXT: {{^}} `-BraceStmt {{.*}} [57:27 - 57:38] expanded // CHECK-EXPANDED: {{^}} `-AfterPatternBinding {{.*}} entry 0 [58:16 - 100:1] expanded // CHECK-EXPANDED-NEXT: {{^}} |-TypeDecl {{.*}} S7 [59:3 - 59:15] expanded // CHECK-EXPANDED-NEXT: {{^}} `-TypeOrExtensionBody {{.*}} 'S7' [59:13 - 59:15] expanded // CHECK-EXPANDED-NEXT: {{^}} |-TypeDecl {{.*}} S7Alias [60:3 - 60:23] expanded // CHECK-EXPANDED-NEXT: {{^}} |-IfStmt {{.*}} [62:3 - 66:3] expanded // CHECK-EXPANDED-NEXT: {{^}} |-ConditionalClause {{.*}} index 0 [62:18 - 64:3] expanded // CHECK-EXPANDED-NEXT: {{^}} `-ConditionalClause {{.*}} index 1 [62:29 - 64:3] expanded // CHECK-EXPANDED-NEXT: {{^}} `-BraceStmt {{.*}} [62:29 - 64:3] expanded // CHECK-EXPANDED: {{^}} `-AfterPatternBinding {{.*}} entry 0 [63:14 - 64:3] expanded // CHECK-EXPANDED-NEXT: {{^}} `-BraceStmt {{.*}} [64:10 - 66:3] expanded // CHECK-EXPANDED: {{^}} `-AfterPatternBinding {{.*}} entry 0 [65:14 - 66:3] expanded // CHECK-EXPANDED-NEXT: {{^}} `-GuardStmt {{.*}} [68:3 - 100:1] expanded // CHECK-EXPANDED-NEXT: {{^}} |-ConditionalClause {{.*}} index 0 [68:21 - 68:53] expanded // CHECK-EXPANDED-NEXT: {{^}} `-ConditionalClause {{.*}} index 1 [68:21 - 68:53] expanded // CHECK-EXPANDED-NEXT: {{^}} |-Closure {{.*}} [68:21 - 68:30] expanded // CHECK-EXPANDED-NEXT: {{^}} `-BraceStmt {{.*}} [68:21 - 68:30] expanded // CHECK-EXPANDED-NEXT: {{^}} `-ConditionalClause {{.*}} index 2 [68:53 - 68:53] expanded // CHECK-EXPANDED-NEXT: {{^}} |-BraceStmt {{.*}} [68:53 - 71:3] expanded // CHECK-EXPANDED: {{^}} `-AfterPatternBinding {{.*}} entry 0 [69:13 - 71:3] expanded // CHECK-EXPANDED-NEXT: {{^}} `-ConditionalClause {{.*}} index 0 guard-continuation [71:3 - 100:1] expanded // CHECK-EXPANDED-NEXT: {{^}} `-ConditionalClause {{.*}} index 1 guard-continuation [71:3 - 100:1] expanded // CHECK-EXPANDED-NEXT: {{^}} `-ConditionalClause {{.*}} index 2 guard-continuation [71:3 - 100:1] expanded // CHECK-EXPANDED-NEXT: {{^}} |-ConditionalClause {{.*}} index 0 [73:21 - 75:3] expanded // CHECK-EXPANDED-NEXT: {{^}} `-ConditionalClause {{.*}} index 1 [73:32 - 75:3] expanded // CHECK-EXPANDED-NEXT: {{^}} `-BraceStmt {{.*}} [73:32 - 75:3] expanded // CHECK-EXPANDED: {{^}} `-AfterPatternBinding {{.*}} entry 0 [74:13 - 75:3] expanded // CHECK-EXPANDED-NEXT: {{^}} |-RepeatWhileStmt {{.*}} [77:3 - 77:20] expanded // CHECK-EXPANDED-NEXT: {{^}} `-BraceStmt {{.*}} [77:10 - 77:12] expanded // CHECK-EXPANDED-NEXT: {{^}} |-ForEachStmt {{.*}} [79:3 - 81:3] expanded // CHECK-EXPANDED-NEXT: {{^}} `-ForEachPattern {{.*}} [79:52 - 81:3] expanded // CHECK-EXPANDED-NEXT: {{^}} `-BraceStmt {{.*}} [79:63 - 81:3] expanded // CHECK-EXPANDED-NEXT: {{^}} |-DoCatchStmt {{.*}} [83:3 - 87:3] expanded // CHECK-EXPANDED-NEXT: {{^}} |-BraceStmt {{.*}} [83:6 - 85:3] expanded // CHECK-EXPANDED-NEXT: {{^}} |-CatchStmt {{.*}} [85:31 - 86:3] expanded // CHECK-EXPANDED-NEXT: {{^}} `-BraceStmt {{.*}} [85:54 - 86:3] expanded // CHECK-EXPANDED-NEXT: {{^}} `-CatchStmt {{.*}} [86:11 - 87:3] expanded // CHECK-EXPANDED-NEXT: {{^}} `-BraceStmt {{.*}} [86:11 - 87:3] expanded // CHECK-EXPANDED-NEXT: {{^}} |-SwitchStmt {{.*}} [89:3 - 98:3] expanded // CHECK-EXPANDED-NEXT: {{^}} |-CaseStmt {{.*}} [90:29 - 91:10] expanded // CHECK-EXPANDED-NEXT: {{^}} `-BraceStmt {{.*}} [91:5 - 91:10] expanded // CHECK-EXPANDED-NEXT: {{^}} |-CaseStmt {{.*}} [94:5 - 94:10] expanded // CHECK-EXPANDED-NEXT: {{^}} `-BraceStmt {{.*}} [94:5 - 94:10] expanded // CHECK-EXPANDED-NEXT: {{^}} `-CaseStmt {{.*}} [97:5 - 97:10] expanded // CHECK-EXPANDED-NEXT: {{^}} `-BraceStmt {{.*}} [97:5 - 97:10] expanded // CHECK-EXPANDED-NEXT: {{^}} `-ForStmt {{.*}} [99:3 - 99:38] expanded // CHECK-EXPANDED-NEXT: {{^}} `-ForStmtInitializer {{.*}} [99:17 - 99:38] expanded // CHECK-EXPANDED-NEXT: {{^}} `-BraceStmt {{.*}} [99:36 - 99:38] expanded // CHECK-EXPANDED: TypeDecl {{.*}} StructContainsAbstractStorageDecls [114:1 - 130:1] expanded // CHECK-EXPANDED-NEXT: `-TypeOrExtensionBody {{.*}} 'StructContainsAbstractStorageDecls' [114:43 - 130:1] expanded // CHECK-EXPANDED-NEXT: {{^}} |-Accessors {{.*}} scope_map.(file).StructContainsAbstractStorageDecls.subscript@{{.*}}scope_map.swift:115:3 [115:37 - 121:3] expanded // CHECK-EXPANDED-NEXT: {{^}} |-AbstractFunctionDecl {{.*}} _ [116:5 - 117:5] expanded // CHECK-EXPANDED-NEXT: {{^}} `-AbstractFunctionParams {{.*}} _ param 0:0 [116:5 - 117:5] expanded // CHECK-EXPANDED-NEXT: {{^}} `-AbstractFunctionParams {{.*}} _ param 1:0 [116:5 - 117:5] expanded // CHECK-EXPANDED-NEXT: {{^}} `-AbstractFunctionParams {{.*}} _ param 1:1 [116:5 - 117:5] expanded // CHECK-EXPANDED-NEXT: {{^}} `-AbstractFunctionParams {{.*}} _ param 1:2 [116:5 - 117:5] expanded // CHECK-EXPANDED-NEXT: `-AbstractFunctionBody {{.*}} _ [116:9 - 117:5] expanded // CHECK-EXPANDED-NEXT: {{^}} `-BraceStmt {{.*}} [116:9 - 117:5] expanded // CHECK-EXPANDED-NEXT: {{^}} `-AbstractFunctionDecl {{.*}} _ [118:5 - 120:5] expanded // CHECK-EXPANDED-NEXT: {{^}} `-AbstractFunctionParams {{.*}} _ param 0:0 [118:5 - 120:5] expanded // CHECK-EXPANDED-NEXT: {{^}} `-AbstractFunctionParams {{.*}} _ param 1:0 [118:5 - 120:5] expanded // CHECK-EXPANDED-NEXT: {{^}} `-AbstractFunctionParams {{.*}} _ param 1:1 [118:5 - 120:5] expanded // CHECK-EXPANDED-NEXT: `-AbstractFunctionBody {{.*}} _ [118:9 - 120:5] expanded // CHECK-EXPANDED-NEXT: {{^}} `-BraceStmt {{.*}} [118:9 - 120:5] expanded // CHECK-EXPANDED: {{^}} `-Accessors {{.*}} scope_map.(file).StructContainsAbstractStorageDecls.computed@{{.*}}scope_map.swift:123:7 [123:21 - 129:3] expanded // CHECK-EXPANDED-NEXT: {{^}} |-AbstractFunctionDecl {{.*}} _ [124:5 - 126:5] expanded // CHECK-EXPANDED-NEXT: {{^}} `-AbstractFunctionParams {{.*}} _ param 0:0 [124:5 - 126:5] expanded // CHECK-EXPANDED-NEXT: `-AbstractFunctionBody {{.*}} _ [124:9 - 126:5] expanded // CHECK-EXPANDED-NEXT: {{^}} `-BraceStmt {{.*}} [124:9 - 126:5] expanded // CHECK-EXPANDED-NEXT: {{^}} `-AbstractFunctionDecl {{.*}} _ [127:5 - 128:5] expanded // CHECK-EXPANDED-NEXT: {{^}} `-AbstractFunctionParams {{.*}} _ param 0:0 [127:5 - 128:5] expanded // CHECK-EXPANDED-NEXT: {{^}} `-AbstractFunctionParams {{.*}} _ param 1:0 [127:5 - 128:5] expanded // CHECK-EXPANDED-NEXT: `-AbstractFunctionBody {{.*}} _ [127:9 - 128:5] expanded // CHECK-EXPANDED-NEXT: {{^}} `-BraceStmt {{.*}} [127:9 - 128:5] expanded // CHECK-EXPANDED: TypeDecl {{.*}} ClassWithComputedProperties [132:1 - 140:1] expanded // CHECK-EXPANDED-NEXT: -TypeOrExtensionBody {{.*}} 'ClassWithComputedProperties' [132:35 - 140:1] expanded // CHECK-EXPANDED: {{^}} `-Accessors {{.*}} scope_map.(file).ClassWithComputedProperties.willSetProperty@{{.*}}scope_map.swift:133:7 [133:32 - 135:3] expanded // CHECK-EXPANDED-NEXT: {{^}} `-AbstractFunctionDecl {{.*}} _ [134:5 - 134:15] expanded // CHECK-EXPANDED-NEXT: {{^}} `-AbstractFunctionParams {{.*}} _ param 0:0 [134:5 - 134:15] expanded // CHECK-EXPANDED-NEXT: {{^}} `-AbstractFunctionParams {{.*}} _ param 1:0 [134:5 - 134:15] expanded // CHECK-EXPANDED: {{^}} `-BraceStmt {{.*}} [134:13 - 134:15] expanded // CHECK-EXPANDED: {{^}} `-Accessors {{.*}} scope_map.(file).ClassWithComputedProperties.didSetProperty@{{.*}}scope_map.swift:137:7 [137:31 - 139:3] expanded // CHECK-EXPANDED-NEXT: {{^}} `-AbstractFunctionDecl {{.*}} _ [138:5 - 138:14] expanded // CHECK-EXPANDED-NEXT: {{^}} `-AbstractFunctionParams {{.*}} _ param 0:0 [138:5 - 138:14] expanded // CHECK-EXPANDED-NEXT: {{^}} `-AbstractFunctionParams {{.*}} _ param 1:0 [138:5 - 138:14] expanded // CHECK-EXPANDED: {{^}} `-BraceStmt {{.*}} [138:12 - 138:14] expanded // CHECK-EXPANDED: {{^}} `-AbstractFunctionParams {{.*}} funcWithComputedProperties(i:) param 0:0 [142:36 - 155:1] expanded // CHECK-EXPANDED: {{^}} `-BraceStmt {{.*}} [142:41 - 155:1] expanded // CHECK-EXPANDED-NEXT: {{^}} `-PatternBinding {{.*}} entry 0 [143:7 - 155:1] expanded // CHECK-EXPANDED-NEXT: {{^}} `-AfterPatternBinding {{.*}} entry 0 [143:17 - 155:1] expanded // CHECK-EXPANDED-NEXT: {{^}} |-Accessors {{.*}} scope_map.(file).funcWithComputedProperties(i:).computed@{{.*}}scope_map.swift:143:7 [143:21 - 149:3] expanded // CHECK-EXPANDED-NEXT: {{^}} |-AbstractFunctionDecl {{.*}} _ [144:5 - 145:5] expanded // CHECK-EXPANDED-NEXT: {{^}} `-AbstractFunctionParams {{.*}} _ param 0:0 [144:5 - 145:5] expanded // CHECK-EXPANDED: {{^}} `-BraceStmt {{.*}} [144:9 - 145:5] expanded // CHECK-EXPANDED-NEXT: {{^}} `-AbstractFunctionDecl {{.*}} _ [146:5 - 148:5] expanded // CHECK-EXPANDED: {{^}} `-BraceStmt {{.*}} [146:9 - 148:5] expanded // CHECK-EXPANDED: {{^}} `-AfterPatternBinding {{.*}} entry 1 [149:36 - 155:1] expanded // CHECK-EXPANDED: {{^}} `-AfterPatternBinding {{.*}} entry 2 [150:21 - 155:1] expanded // CHECK-EXPANDED-NEXT: {{^}} |-AbstractFunctionDecl {{.*}} _ [150:25 - 152:3] expanded // CHECK-EXPANDED: {{^}} `-BraceStmt {{.*}} [150:25 - 152:3] expanded // CHECK-EXPANDED-NEXT: {{^}} `-BraceStmt {{.*}} [154:6 - 154:8] expanded // CHECK-EXPANDED: |-AbstractFunctionDecl {{.*}} closures() [157:1 - 162:1] expanded // CHECK-EXPANDED: {{^}} `-BraceStmt {{.*}} [157:17 - 162:1] expanded // CHECK-EXPANDED-NEXT: {{^}} `-Preexpanded {{.*}} [158:10 - 161:19] expanded // CHECK-EXPANDED-NEXT: {{^}} |-Closure {{.*}} [158:10 - 160:3] expanded // CHECK-EXPANDED-NEXT: {{^}} `-BraceStmt {{.*}} [158:10 - 160:3] expanded // CHECK-EXPANDED-NEXT: {{^}} `-Closure {{.*}} [159:12 - 159:22] expanded // CHECK-EXPANDED-NEXT: {{^}} `-BraceStmt {{.*}} [159:12 - 159:22] expanded // CHECK-EXPANDED-NEXT: {{^}} `-Closure {{.*}} [161:10 - 161:19] expanded // CHECK-EXPANDED-NEXT: {{^}} `-BraceStmt {{.*}} [161:10 - 161:19] expanded // CHECK-EXPANDED: `-TopLevelCode {{.*}} [164:1 - [[EOF:[0-9]+:[0-9]+]]] expanded // CHECK-EXPANDED-NEXT: {{^}} `-BraceStmt {{.*}} [164:1 - [[EOF]]] expanded // CHECK-EXPANDED-NEXT: {{^}} |-Closure {{.*}} [164:1 - 164:14] expanded // CHECK-EXPANDED-NEXT: {{^}} `-BraceStmt {{.*}} [164:1 - 164:14] expanded // CHECK-EXPANDED: -AbstractFunctionDecl {{.*}} defaultArguments(i:j:) [166:1 - 175:1] expanded // CHECK-EXPANDED: {{^}} |-DefaultArgument {{.*}} [166:32 - 166:32] expanded // CHECK-EXPANDED-NEXT: {{^}} `-AbstractFunctionParams {{.*}} defaultArguments(i:j:) param 0:0 [166:32 - 175:1] expanded // CHECK-EXPANDED: {{^}} |-DefaultArgument {{.*}} [167:32 - 167:48] expanded // CHECK-EXPANDED-NEXT: {{^}} `-Closure {{.*}} [167:32 - 167:42] expanded // CHECK-EXPANDED-NEXT: {{^}} `-BraceStmt {{.*}} [167:32 - 167:42] expanded // CHECK-EXPANDED-NEXT: {{^}} `-AbstractFunctionParams {{.*}} defaultArguments(i:j:) param 0:1 [167:48 - 175:1] expanded // CHECK-EXPANDED: -Accessors {{.*}} scope_map.(file).ProtoWithSubscript.subscript@{{.*}}scope_map.swift:183:3 [183:33 - 183:43] expanded // CHECK-EXPANDED-NEXT: |-AbstractFunctionDecl {{.*}} _ [183:35 - 183:35] expanded // CHECK-EXPANDED-NEXT: `-AbstractFunctionParams {{.*}} _ param 0:0 [183:35 - 183:35] expanded // CHECK-EXPANDED-NEXT: `-AbstractFunctionParams {{.*}} _ param 1:0 [183:35 - 183:35] expanded // CHECK-EXPANDED-NEXT: `-AbstractFunctionDecl {{.*}} _ [183:39 - 183:39] expanded // CHECK-EXPANDED-NEXT: `-AbstractFunctionParams {{.*}} _ param 0:0 [183:39 - 183:39] expanded // CHECK-EXPANDED-NEXT: `-AbstractFunctionParams {{.*}} _ param 1:0 [183:39 - 183:39] expanded // CHECK-EXPANDED-NEXT: `-AbstractFunctionParams {{.*}} _ param 1:1 [183:39 - 183:39] expanded // CHECK-EXPANDED: -AbstractFunctionDecl {{.*}} localPatternsWithSharedType() [186:1 - 188:1] expanded // CHECK-EXPANDED: `-BraceStmt {{.*}} [186:36 - 188:1] expanded // CHECK-EXPANDED-NEXT: `-PatternBinding {{.*}} entry 0 [187:7 - 188:1] expanded // CHECK-EXPANDED-NEXT: `-AfterPatternBinding {{.*}} entry 0 [187:7 - 188:1] expanded // CHECK-EXPANDED-NEXT: `-PatternBinding {{.*}} entry 1 [187:10 - 188:1] expanded // CHECK-EXPANDED-NEXT: `-AfterPatternBinding {{.*}} entry 1 [187:10 - 188:1] expanded // CHECK-EXPANDED-NEXT: `-PatternBinding {{.*}} entry 2 [187:13 - 188:1] expanded // CHECK-EXPANDED-NEXT: `-AfterPatternBinding {{.*}} entry 2 [187:16 - 188:1] expanded // RUN: not %target-swift-frontend -dump-scope-maps 70:8,26:20,5:18,166:32,179:18,193:26 %s 2> %t.searches // RUN: %FileCheck -check-prefix CHECK-SEARCHES %s < %t.searches // CHECK-SEARCHES-LABEL: ***Scope at 70:8*** // CHECK-SEARCHES-NEXT: AfterPatternBinding {{.*}} entry 0 [69:13 - 71:3] expanded // CHECK-SEARCHES-NEXT: Local bindings: c // CHECK-SEARCHES-LABEL: ***Scope at 26:20*** // CHECK-SEARCHES-NEXT: AbstractFunctionParams {{.*}} init(t:u:) param 1:0 [26:17 - 27:3] expanded // CHECK-SEARCHES-NEXT: Local bindings: t // CHECK-SEARCHES-LABEL: ***Scope at 5:18*** // CHECK-SEARCHES-NEXT: TypeOrExtensionBody {{.*}} 'InnerC0' [5:17 - 5:19] expanded // CHECK-SEARCHES-NEXT: Module name=scope_map // CHECK-SEARCHES-NEXT: FileUnit file="{{.*}}scope_map.swift" // CHECK-SEARCHES-NEXT: StructDecl name=S0 // CHECK-SEARCHES-NEXT: ClassDecl name=InnerC0 // CHECK-SEARCHES-LABEL: ***Scope at 166:32*** // CHECK-SEARCHES-NEXT: DefaultArgument {{.*}} [166:32 - 166:32] expanded // CHECK-SEARCHES-NEXT: Module name=scope_map // CHECK-SEARCHES-NEXT: FileUnit file="{{.*}}scope_map.swift" // CHECK-SEARCHES-NEXT: AbstractFunctionDecl name=defaultArguments : (Int, Int) -> () // CHECK-SEARCHES-NEXT: {{.*}} Initializer DefaultArgument index=0 // CHECK-SEARCHES-LABEL: ***Scope at 179:18*** // CHECK-SEARCHES-NEXT: PatternInitializer {{.*}} entry 1 [179:16 - 179:25] expanded // CHECK-SEARCHES-NEXT: {{.*}} Module name=scope_map // CHECK-SEARCHES-NEXT: {{.*}} FileUnit file="{{.*}}scope_map.swift" // CHECK-SEARCHES-NEXT: {{.*}} StructDecl name=PatternInitializers // CHECK-SEARCHES-NEXT: {{.*}} Initializer PatternBinding {{.*}} #1 // CHECK-SEARCHES-LABEL: ***Scope at 193:26*** // CHECK-SEARCHES-NEXT: PatternInitializer {{.*}} entry 0 [193:24 - 193:29] expanded // CHECK-SEARCHES-NEXT: name=scope_map // CHECK-SEARCHES-NEXT: FileUnit file="{{.*}}scope_map.swift" // CHECK-SEARCHES-NEXT: ClassDecl name=LazyProperties // CHECK-SEARCHES-NEXT: Initializer PatternBinding {{.*}} #0 // CHECK-SEARCHES-NEXT: Local bindings: self // CHECK-SEARCHES-LABEL: ***Complete scope map*** // CHECK-SEARCHES-NEXT: SourceFile {{.*}} '{{.*}}scope_map.swift' [1:1 - [[EOF:[0-9]+:[0-9]+]]] unexpanded // CHECK-SEARCHES: TypeOrExtensionBody {{.*}} 'S0' [4:11 - 6:1] expanded // CHECK-SEARCHES: -TypeOrExtensionBody {{.*}} 'InnerC0' [5:17 - 5:19] expanded // CHECK-SEARCHES-NOT: {{ expanded}} // CHECK-SEARCHES: -TypeDecl {{.*}} ContainsGenerics0 [25:1 - 31:1] expanded // CHECK-SEARCHES-NEXT: `-TypeOrExtensionBody {{.*}} 'ContainsGenerics0' [25:25 - 31:1] expanded // CHECK-SEARCHES-NEXT: |-AbstractFunctionDecl {{.*}} init(t:u:) [26:3 - 27:3] expanded // CHECK-SEARCHES-NEXT: `-GenericParams {{.*}} param 0 [26:8 - 27:3] expanded // CHECK-SEARCHES-NEXT: `-GenericParams {{.*}} param 1 [26:11 - 27:3] expanded // CHECK-SEARCHES-NEXT: `-AbstractFunctionParams {{.*}} init(t:u:) param 0:0 [26:13 - 27:3] expanded // CHECK-SEARCHES-NEXT: `-AbstractFunctionParams {{.*}} init(t:u:) param 1:0 [26:17 - 27:3] expanded // CHECK-SEARCHES-NEXT: `-AbstractFunctionParams {{.*}} init(t:u:) param 1:1 [26:23 - 27:3] unexpanded // CHECK-SEARCHES-NOT: {{ expanded}} // CHECK-SEARCHES: |-AbstractFunctionDecl {{.*}} functionBodies1(a:b:) [41:1 - 100:1] expanded // CHECK-SEARCHES: `-AbstractFunctionParams {{.*}} functionBodies1(a:b:) param 0:0 [41:25 - 100:1] expanded // CHECK-SEARCHES: |-AbstractFunctionDecl {{.*}} throwing() [102:1 - 102:26] unexpanded // CHECK-SEARCHES: -AbstractFunctionDecl {{.*}} defaultArguments(i:j:) [166:1 - 175:1] expanded // CHECK-SEARCHES: DefaultArgument {{.*}} [166:32 - 166:32] expanded // CHECK-SEARCHES-NOT: {{ expanded}} // CHECK-SEARCHES: |-TypeDecl {{.*}} PatternInitializers [177:1 - 180:1] expanded // CHECK-SEARCHES: -TypeOrExtensionBody {{.*}} 'PatternInitializers' [177:28 - 180:1] expanded // CHECK-SEARCHES: |-PatternBinding {{.*}} entry 0 [178:7 - 178:21] unexpanded // CHECK-SEARCHES: `-PatternBinding {{.*}} entry 1 [179:7 - 179:25] expanded // CHECK-SEARCHES: `-PatternInitializer {{.*}} entry 1 [179:16 - 179:25] expanded // CHECK-SEARCHES-NOT: {{ expanded}} // CHECK-SEARCHES: |-TypeDecl {{.*}} ProtoWithSubscript [182:1 - 184:1] unexpanded // CHECK-SEARCHES-NOT: {{ expanded}} // CHECK-SEARCHES: |-AbstractFunctionDecl {{.*}} localPatternsWithSharedType() [186:1 - 188:1] unexpanded // CHECK-SEARCHES: `-TypeDecl {{.*}} LazyProperties [190:1 - 194:1] expanded // CHECK-SEARCHES: -TypeOrExtensionBody {{.*}} 'LazyProperties' [190:22 - 194:1] expanded // CHECK-SEARCHES-NEXT: |-PatternBinding {{.*}} entry 0 [191:7 - 191:20] unexpanded // CHECK-SEARCHES-NEXT: `-PatternBinding {{.*}} entry 0 [193:12 - 193:29] expanded // CHECK-SEARCHES-NEXT: `-PatternInitializer {{.*}} entry 0 [193:24 - 193:29] expanded // CHECK-SEARCHES-NOT: {{ expanded}}
apache-2.0
cc1b31fd753c772688333485362417a9
56.509018
165
0.575565
3.537599
false
false
false
false
electricobjects/FeedKit
Source/FeedController.swift
2
9701
// // FeedController.swift // FeedController // // Created by Rob Seward on 7/16/15. // Copyright (c) 2015 Rob Seward. All rights reserved. // import UIKit public protocol FeedFetchRequest { associatedtype H: FeedItem /// If set to true, cache data will be cleared when new data is loaded. This is usually set to true on the first page of a feed. var clearStaleDataOnCompletion: Bool { get } /** Fetch items for the feed. This method is called by the FeedController. When overriding this function your should make your api calls inside this method. The success method will trigger the item processing and eventually the items added/deleted callback in FeedController delegate. Failure closure will trigger the `requestFailed` delegate method. - parameter success: <#success description#> - parameter failure: <#failure description#> */ func fetchItems(success: @escaping ([H])->(), failure: @escaping (Error)->()) } /** * Your item models should follow this protocol, impelmenting `Hashable` and `NSCoding`. The `FeedController` * compares incoming items to the ones already present, integrating new ones while eliminating redundant ones. It must compare the * items using the `hashValue` in order to determine what items are new and which ones are not. */ public protocol FeedItem: Hashable, NSCoding { } public protocol FeedControllerDelegate: class { /** The delegate method called when changes are made to the controller's items via a FeedFetchRequest - Parameter feedController: The feed controller. - Parameter itemsCopy: A copy of the feed controller's updated items array. - Parameter itemsAdded: The index paths of items that were added to the items array. - Parameter itemsDeleted: The index paths of items that were deleted from the items array. */ func feedController(feedController: FeedControllerGeneric, itemsCopy: [AnyObject], itemsAdded: [IndexPath], itemsDeleted: [IndexPath]) /** The delegate method called if there is an error making a FeedFetchRequest - parameter feedController: The feed controller. - parameter feedController: The error that occured in the FeedFetchRequest. */ func feedController(feedController: FeedControllerGeneric, requestFailed error: Error) } /** * `CachePreferences` tell the FeedController whether or not to cache the feed items, and if so, what the cache should be called. */ public protocol CachePreferences { /// The name of the cache. To be saved in Library/Caches/FeedCache var cacheName: String { get } /// Turn caching on or off var cacheOn: Bool { get } } /** Since Feed Controllers use generics to ensure type saftey, they inherit from this common class so we can compare different Feed Controllers with the '==' operator */ open class FeedControllerGeneric { } func == (lhs: FeedControllerGeneric, rhs: FeedControllerGeneric) -> Bool { return Unmanaged.passUnretained(lhs).toOpaque() == Unmanaged.passUnretained(rhs).toOpaque() } /// The FeedController keeps track of incoming feed items and caches them accordingly. It is designed to be controlled by a UITableViewController or /// `UICollectionViewController`, and is modeled after the `NSFetchedResultsController`. open class FeedController <T:FeedItem> : FeedControllerGeneric { ///The items in the feed. fileprivate(set) open var items: [T]! = [] /// The FeedController delegate. Usually a `UITableViewController` or `UICollectionViewController`. open weak var delegate: FeedControllerDelegate? /// The `cachePreferences` tell the FeedController whether or not to cache the feed items, and if so, what the cache should be called. fileprivate(set) var cachePreferences: CachePreferences /// The cache object is responsible for saving and retrieving the feed items. open var cache: FeedCache<T>? ///The section in a UITableView or UICollectionView that the Feed Controller corresponds to. public let section: Int! /** Initialize the Feed Controller - parameter cachePreferences: The cache preferences. - parameter section: The section of the tableview or collection view that the controller corresponds to. */ public init(cachePreferences: CachePreferences, section: Int) { self.section = section self.cachePreferences = cachePreferences if self.cachePreferences.cacheOn { self.cache = FeedCache(name: cachePreferences.cacheName) } } /** Load the Feed Controller's cache and block until it finishes. */ open func loadCacheSynchronously() { cache?.loadCache() cache?.waitUntilSynchronized() _processCacheLoad() } fileprivate func _addItems(_ items: [T]) { self.items = self.items + items } /// Fetch items with a FeedFetchRequest. open func fetchItems<G: FeedFetchRequest>(_ request: G) { request.fetchItems(success: { [weak self](newItems) -> () in if let strongSelf = self { fk_dispatch_on_queue(DispatchQueue.global(qos: DispatchQoS.QoSClass.default), block: { () -> Void in if let items = newItems as Any as? [T] { strongSelf._processNewItems(items, clearCacheIfNewItemsAreDifferent: request.clearStaleDataOnCompletion) } }) } }) { [weak self](error) -> () in if let delegate = self?.delegate, let strongSelf = self { delegate.feedController(feedController: strongSelf, requestFailed: error) } } } /** Remove an item. This can be useful when rearranging items, e.g. if the user is manually arranging items in a tableview, we can use these to keep the FeedCache items in the correct position. - parameter index: the index of the item to be removed. */ open func removeItemAtIndex(_ index: Int) { items.remove(at: index) if let cache = cache { cache.clearCache() cache.addItems(items) } } /** Insert an item. This can be useful when rearranging items, e.g. if the user is manually arranging items in a tableview, we can use these to keep the FeedCache items in the correct position. - parameter item: The item to be inserted. - parameter atIndex: The index at which to insert the item. */ open func insertItem(_ item: T, atIndex index: Int) { items.insert(item, at: index) if let cache = cache { cache.clearCache() cache.addItems(items) } } fileprivate func _processCacheLoad() { if let cache = cache { items = _unique(cache.items) } } fileprivate func _processNewItems(_ newItems: [T], clearCacheIfNewItemsAreDifferent: Bool) { //prevent calls of this method on other threads from mutating items array while we are working with it. objc_sync_enter(self) defer { objc_sync_exit(self) } let uniqueNewItems = _unique(newItems) if uniqueNewItems == items { fk_dispatch_on_queue(DispatchQueue.main) { () -> Void in self.delegate?.feedController(feedController: self, itemsCopy: self.items, itemsAdded: [], itemsDeleted: []) } return } let newSet = Set(uniqueNewItems) let oldSet = Set(items) let insertSet = newSet.subtracting(oldSet) var indexPathsForInsertion: [IndexPath] = [] var indexPathsForDeletion: [IndexPath] = [] if clearCacheIfNewItemsAreDifferent { indexPathsForInsertion = _indexesForItems(insertSet, inArray: uniqueNewItems) let deleteSet = oldSet.subtracting(newSet) indexPathsForDeletion = _indexesForItems(deleteSet, inArray: items) items = uniqueNewItems cache?.clearCache() fk_dispatch_on_queue(DispatchQueue.main) { () -> Void in self.cache?.addItems(self.items) } } else { let itemsToAdd = _orderSetWithArray(insertSet, array: uniqueNewItems) _addItems(itemsToAdd) indexPathsForInsertion = _indexesForItems(insertSet, inArray: items) } fk_dispatch_on_queue(DispatchQueue.main) { () -> Void in self.delegate?.feedController(feedController: self, itemsCopy: self.items, itemsAdded: indexPathsForInsertion, itemsDeleted: indexPathsForDeletion) } } fileprivate func _indexesForItems(_ itemsToFind: Set<T>, inArray array: [T]) -> [IndexPath] { var returnPaths: [IndexPath] = [] for item in itemsToFind { if let index = array.index(of: item) { returnPaths.append(IndexPath(row: index, section: section)) } } return returnPaths } fileprivate func _orderSetWithArray(_ set: Set<T>, array: [T]) -> [T] { let forDeletion = Set(array).subtracting(set) var returnArray = [T](array) for item in forDeletion { let removeIndex = returnArray.index(of: item)! returnArray.remove(at: removeIndex) } return returnArray } /** Remove duplicates - parameter source: The original sequence. - returns: A sequence of unique items. */ fileprivate func _unique<S: Sequence, E: Hashable>(_ source: S) -> [E] where E == S.Iterator.Element { var seen = [E: Bool]() return source.filter { seen.updateValue(true, forKey: $0) == nil } } }
mit
d6940b372786a418fa123ff46b100b16
36.894531
159
0.659829
4.619524
false
false
false
false
tnako/Challenge_ios
Challenge/ChallengeTableViewCell.swift
1
1317
// // ChallengeTableViewCell.swift // Challenge // // Created by Anton Korshikov on 27.09.15. // Copyright © 2015 Anton Korshikov. All rights reserved. // import UIKit struct ImageRow { var Title: String; var Imager: UIImage; var Likes: UInt; } class ChallengeTableViewCell: UITableViewCell { var CurrentImage:ImageRow?; @IBOutlet var LikeButton: UIButton! @IBOutlet weak var Imager: UIImageView! @IBOutlet weak var Title: UILabel! @IBOutlet weak var Subtitle: UILabel! override func awakeFromNib() { super.awakeFromNib() Imager.contentMode = .ScaleAspectFit; } @IBAction func PressedLike() { if (LikeButton.titleLabel!.enabled) { ++CurrentImage!.Likes; LikeButton.titleLabel?.enabled = false; } else { --CurrentImage!.Likes; LikeButton.titleLabel?.enabled = true; } SetRowData(); } func SetRowData() { Subtitle.text = "Likes: \(CurrentImage!.Likes)"; Title.text = CurrentImage!.Title; Imager.image = CurrentImage!.Imager; } /* override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) }*/ }
gpl-3.0
3416667be6fe39cef8a5317caca4be18
20.57377
63
0.597264
4.553633
false
false
false
false
Jean-Daniel/hadron
swift/Hadron/Log.swift
1
3151
// // Log.swift // Hadron // // Created by Jean-Daniel Dupas // Copyright © 2018 Xenonium. All rights reserved. // import os import Foundation @inline(__always) func spx_info(dso: UnsafeRawPointer = #dsohandle, log: OSLog = OSLog.default, _ message: StaticString) { os_log(message, dso: dso, log: log, type: .info) } @inline(__always) func spx_info(dso: UnsafeRawPointer = #dsohandle, log: OSLog = OSLog.default, _ message: StaticString, _ args: CVarArg) { os_log(message, dso: dso, log: log, type: .info, args) } @inline(__always) func spx_info(dso: UnsafeRawPointer = #dsohandle, log: OSLog = OSLog.default, _ message: StaticString, _ args1: CVarArg, _ args2: CVarArg) { os_log(message, dso: dso, log: log, type: .info, args1, args2) } @inline(__always) func spx_log(dso: UnsafeRawPointer = #dsohandle, log: OSLog = OSLog.default, _ message: StaticString) { os_log(message, dso: dso, log: log, type: .default) } @inline(__always) func spx_log(dso: UnsafeRawPointer = #dsohandle, log: OSLog = OSLog.default, _ message: StaticString, _ args: CVarArg) { os_log(message, dso: dso, log: log, type: .default, args) } @inline(__always) func spx_log(dso: UnsafeRawPointer = #dsohandle, log: OSLog = OSLog.default, _ message: StaticString, _ args1: CVarArg, _ args2: CVarArg) { os_log(message, dso: dso, log: log, type: .default, args1, args2) } @inline(__always) func spx_error(dso: UnsafeRawPointer = #dsohandle, log: OSLog = OSLog.default, _ message: StaticString) { os_log(message, dso: dso, log: log, type: .error) } @inline(__always) func spx_error(dso: UnsafeRawPointer = #dsohandle, log: OSLog = OSLog.default, _ message: StaticString, _ args: CVarArg) { os_log(message, dso: dso, log: log, type: .error, args) } @inline(__always) func spx_error(dso: UnsafeRawPointer = #dsohandle, log: OSLog = OSLog.default, _ message: StaticString, _ args1: CVarArg, _ args2: CVarArg) { os_log(message, dso: dso, log: log, type: .error, args1, args2) } #if DEBUG @inline(__always) func spx_debug(dso: UnsafeRawPointer = #dsohandle, log: OSLog = OSLog.default, _ message: StaticString) { os_log(message, dso: dso, log: log, type: .debug) } @inline(__always) func spx_debug(dso: UnsafeRawPointer = #dsohandle, log: OSLog = OSLog.default, _ message: StaticString, _ args: CVarArg) { os_log(message, dso: dso, log: log, type: .debug, args) } @inline(__always) func spx_debug(dso: UnsafeRawPointer = #dsohandle, log: OSLog = OSLog.default, _ message: StaticString, _ args1: CVarArg, _ args2: CVarArg) { os_log(message, dso: dso, log: log, type: .debug, args1, args2) } @inline(__always) func spx_trace(args: String = "", file : String = #file, line : Int = #line, function : String = #function, dso: UnsafeRawPointer? = #dsohandle) { let filename = (file as NSString).lastPathComponent os_log("[%@:%d]: %@ (%@)", dso: dso, log: OSLog.default, type: .debug, filename, line, function, args) } #else // MARK: Release @inline(__always) func spx_debug(log: OSLog = OSLog.default, _ message: StaticString, _ args: CVarArg...) { /* noop */ } @inline(__always) func spx_trace(args: @autoclosure () -> String = "") { /* Noop */ } #endif
mit
779781054f7b0e16852b5d6963160c22
39.909091
146
0.680317
3.115727
false
false
false
false
Zewo/HTTPJSON
Sources/Request+JSON.swift
1
1660
// Request+JSON.swift // // The MIT License (MIT) // // Copyright (c) 2015 Zewo // // 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. @_exported import HTTP @_exported import JSON extension Request { public init(method: Method = .get, uri: URI = URI(path: "/"), headers: Headers = [:], json: JSON, didUpgrade: DidUpgrade? = nil) { var headers = headers headers["content-type"] = "application/json; charset=utf-8" self.init( method: method, uri: uri, headers: headers, body: json.description, didUpgrade: didUpgrade ) } }
mit
364caf2432b0a33708c302e57b323b12
39.487805
89
0.693373
4.462366
false
false
false
false
jamy0801/LGWeChatKit
LGWeChatKit/LGChatKit/conversion/view/LGChatVoiceCell.swift
1
5143
// // LGChatVoiceCell.swift // LGChatViewController // // Created by jamy on 10/12/15. // Copyright © 2015 jamy. All rights reserved. // import UIKit let voiceIndicatorImageTag = 10040 class LGChatVoiceCell: LGChatBaseCell { let voicePlayIndicatorImageView: UIImageView override init(style: UITableViewCellStyle, reuseIdentifier: String?) { voicePlayIndicatorImageView = UIImageView(frame: CGRectZero) voicePlayIndicatorImageView.tag = voiceIndicatorImageTag voicePlayIndicatorImageView.animationDuration = 1.0 super.init(style: style, reuseIdentifier: reuseIdentifier) backgroundImageView.addSubview(voicePlayIndicatorImageView) voicePlayIndicatorImageView.translatesAutoresizingMaskIntoConstraints = false voicePlayIndicatorImageView.addConstraint(NSLayoutConstraint(item: voicePlayIndicatorImageView, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 12.5)) voicePlayIndicatorImageView.addConstraint(NSLayoutConstraint(item: voicePlayIndicatorImageView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 17)) backgroundImageView.addConstraint(NSLayoutConstraint(item: voicePlayIndicatorImageView, attribute: .Left, relatedBy: .Equal, toItem: backgroundImageView, attribute: .Left, multiplier: 1, constant: 15)) backgroundImageView.addConstraint(NSLayoutConstraint(item: voicePlayIndicatorImageView, attribute: .CenterY, relatedBy: .Equal, toItem: backgroundImageView, attribute: .CenterY, multiplier: 1, constant: -5)) contentView.addConstraint(NSLayoutConstraint(item: backgroundImageView, attribute: .Bottom, relatedBy: .Equal, toItem: contentView, attribute: .Bottom, multiplier: 1, constant: -5)) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) if selected { voicePlayIndicatorImageView.startAnimating() } else { voicePlayIndicatorImageView.stopAnimating() } } override func setMessage(message: Message) { super.setMessage(message) let message = message as! voiceMessage setUpVoicePlayIndicatorImageView(!message.incoming) // hear we can set backgroudImageView's length dure to the voice timer let margin = CGFloat(2) * CGFloat(message.voiceTime.intValue) backgroundImageView.addConstraint(NSLayoutConstraint(item: backgroundImageView, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 60 + margin)) indicatorView.hidden = false indicatorView.setBackgroundImage(UIImage.imageWithColor(UIColor.clearColor()), forState: .Normal) indicatorView.setTitle("\(message.voiceTime.integerValue)\"", forState: .Normal) var layoutAttribute: NSLayoutAttribute var layoutConstant: CGFloat if message.incoming { layoutAttribute = .Left layoutConstant = 15 } else { layoutAttribute = .Right layoutConstant = -15 } let constraints: NSArray = backgroundImageView.constraints let indexOfBackConstraint = constraints.indexOfObjectPassingTest { (constraint, idx, stop) in return (constraint.firstItem as! UIView).tag == voiceIndicatorImageTag && (constraint.firstAttribute == NSLayoutAttribute.Left || constraint.firstAttribute == NSLayoutAttribute.Right) } backgroundImageView.removeConstraint(constraints[indexOfBackConstraint] as! NSLayoutConstraint) backgroundImageView.addConstraint(NSLayoutConstraint(item: voicePlayIndicatorImageView, attribute: layoutAttribute, relatedBy: .Equal, toItem: backgroundImageView, attribute: layoutAttribute, multiplier: 1, constant: layoutConstant)) } func stopAnimation() { if voicePlayIndicatorImageView.isAnimating() { voicePlayIndicatorImageView.stopAnimating() } } func beginAnimation() { voicePlayIndicatorImageView.startAnimating() } func setUpVoicePlayIndicatorImageView(send: Bool) { var images = NSArray() if send { images = NSArray(objects: UIImage(named: "SenderVoiceNodePlaying001")!, UIImage(named: "SenderVoiceNodePlaying002")!, UIImage(named: "SenderVoiceNodePlaying003")!) voicePlayIndicatorImageView.image = UIImage(named: "SenderVoiceNodePlaying") } else { images = NSArray(objects: UIImage(named: "ReceiverVoiceNodePlaying001")!, UIImage(named: "ReceiverVoiceNodePlaying002")!, UIImage(named: "ReceiverVoiceNodePlaying003")!) voicePlayIndicatorImageView.image = UIImage(named: "ReceiverVoiceNodePlaying") } voicePlayIndicatorImageView.animationImages = (images as! [UIImage]) } }
mit
70dc076956b9caf4528c33c81ce2c33a
47.509434
241
0.710035
5.470213
false
false
false
false
austinzheng/swift
test/IDE/print_omit_needless_words_appkit.swift
15
3496
// RUN: %empty-directory(%t) // REQUIRES: objc_interop // REQUIRES: OS=macosx // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t) -emit-module -o %t %S/../Inputs/clang-importer-sdk/swift-modules/ObjectiveC.swift -disable-objc-attr-requires-foundation-module // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t) -emit-module -o %t %S/../Inputs/clang-importer-sdk/swift-modules/CoreGraphics.swift // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t) -emit-module -o %t %S/../Inputs/clang-importer-sdk/swift-modules/Foundation.swift // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t) -emit-module -o %t %S/../Inputs/clang-importer-sdk/swift-modules/AppKit.swift // RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -print-module -source-filename %s -module-to-print=AppKit -function-definitions=false -prefer-type-repr=true -skip-parameter-names > %t.AppKit.txt // RUN: %FileCheck %s -check-prefix=CHECK-APPKIT -strict-whitespace < %t.AppKit.txt // Note: class method name stripping context type. // CHECK-APPKIT: class func red() -> NSColor // Note: instance method name stripping context type. // CHECK-APPKIT: func same() -> Self // Note: Unsafe(Mutable)Pointers don't get defaulted to 'nil' // CHECK-APPKIT: func getRGBAComponents(_: UnsafeMutablePointer<Int8>?) // Note: Skipping over "3D" // CHECK-APPKIT: func drawInAir(at: Point3D) // Note: with<something> -> <something> // CHECK-APPKIT: func draw(at: Point3D, withAttributes: [String : Any]? = nil) // Note: Don't strip names that aren't preceded by a verb or preposition. // CHECK-APPKIT: func setTextColor(_: NSColor?) // Note: Splitting with default arguments. // CHECK-APPKIT: func draw(in: NSView?) // Note: NSDictionary default arguments for "options" // CHECK-APPKIT: func drawAnywhere(in: NSView?, options: [AnyHashable : Any] = [:]) // CHECK-APPKIT: func drawAnywhere(options: [AnyHashable : Any] = [:]) // CHECK-APPKIT: func drawAnywhere(optionalOptions: [AnyHashable : Any]? = nil) // Make sure we're removing redundant context type info at both the // beginning and the end. // CHECK-APPKIT: func reversing() -> NSBezierPath // Make sure we're dealing with 'instancetype' properly. // CHECK-APPKIT: func inventing() -> Self // Make sure we're removing redundant context type info at both the // beginning and the end of a property. // CHECK-APPKIT: var flattened: NSBezierPath { get } // CHECK-APPKIT: func dismiss(animated: Bool) // CHECK-APPKIT: func shouldCollapseAutoExpandedItems(forDeposited: Bool) -> Bool // Introducing argument labels and pruning the base name. // CHECK-APPKIT: func rectForCancelButton(whenCentered: Bool) // CHECK-APPKIT: func openUntitledDocumentAndDisplay(_: Bool) // Don't strip due to weak type information. // CHECK-APPKIT: func setContentHuggingPriority(_: NSLayoutPriority) // Look through typedefs of pointers. // CHECK-APPKIT: func layout(at: NSPointPointer!) // The presence of a property prevents us from stripping redundant // type information from the base name. // CHECK-APPKIT: func addGestureRecognizer(_: NSGestureRecognizer) // CHECK-APPKIT: func removeGestureRecognizer(_: NSGestureRecognizer) // CHECK-APPKIT: func favoriteView(for: NSGestureRecognizer) -> NSView? // CHECK-APPKIT: func addLayoutConstraints(_: Set<NSLayoutConstraint>) // CHECK-APPKIT: func add(_: NSRect) // CHECK-APPKIT: class func conjureRect(_: NSRect)
apache-2.0
92b5e5d3517afea10f1e893abdf76641
46.890411
232
0.736842
3.513568
false
false
false
false
mozilla-mobile/firefox-ios
Client/Frontend/Toolbar+URLBar/TabLocationView.swift
2
15480
// 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 UIKit import Shared protocol TabLocationViewDelegate: AnyObject { func tabLocationViewDidTapLocation(_ tabLocationView: TabLocationView) func tabLocationViewDidLongPressLocation(_ tabLocationView: TabLocationView) func tabLocationViewDidTapReaderMode(_ tabLocationView: TabLocationView) func tabLocationViewDidTapReload(_ tabLocationView: TabLocationView) func tabLocationViewDidTapShield(_ tabLocationView: TabLocationView) func tabLocationViewDidBeginDragInteraction(_ tabLocationView: TabLocationView) /// - returns: whether the long-press was handled by the delegate; i.e. return `false` when the conditions for even starting handling long-press were not satisfied @discardableResult func tabLocationViewDidLongPressReaderMode(_ tabLocationView: TabLocationView) -> Bool func tabLocationViewDidLongPressReload(_ tabLocationView: TabLocationView) func tabLocationViewLocationAccessibilityActions(_ tabLocationView: TabLocationView) -> [UIAccessibilityCustomAction]? } struct TabLocationViewUX { static let HostFontColor = UIColor.black static let BaseURLFontColor = UIColor.Photon.Grey50 static let Spacing: CGFloat = 8 static let StatusIconSize: CGFloat = 18 static let TPIconSize: CGFloat = 44 static let ReaderModeButtonWidth: CGFloat = 34 static let ButtonSize: CGFloat = 44 static let URLBarPadding = 4 } class TabLocationView: UIView { var delegate: TabLocationViewDelegate? var longPressRecognizer: UILongPressGestureRecognizer! var tapRecognizer: UITapGestureRecognizer! var contentView: UIStackView! private let menuBadge = BadgeWithBackdrop(imageName: "menuBadge", backdropCircleSize: 32) @objc dynamic var baseURLFontColor: UIColor = TabLocationViewUX.BaseURLFontColor { didSet { updateTextWithURL() } } var url: URL? { didSet { updateTextWithURL() trackingProtectionButton.isHidden = isTrackingProtectionHidden setNeedsUpdateConstraints() } } var readerModeState: ReaderModeState { get { return readerModeButton.readerModeState } set (newReaderModeState) { guard newReaderModeState != self.readerModeButton.readerModeState else { return } setReaderModeState(newReaderModeState) } } lazy var placeholder: NSAttributedString = { return NSAttributedString(string: .TabLocationURLPlaceholder, attributes: [NSAttributedString.Key.foregroundColor: UIColor.Photon.Grey50]) }() lazy var urlTextField: URLTextField = .build { urlTextField in // Prevent the field from compressing the toolbar buttons on the 4S in landscape. urlTextField.setContentCompressionResistancePriority(UILayoutPriority(rawValue: 250), for: .horizontal) urlTextField.attributedPlaceholder = self.placeholder urlTextField.accessibilityIdentifier = "url" urlTextField.accessibilityActionsSource = self urlTextField.font = UIConstants.DefaultChromeFont urlTextField.backgroundColor = .clear urlTextField.accessibilityLabel = .TabLocationAddressBarAccessibilityLabel urlTextField.font = UIFont.preferredFont(forTextStyle: .body) urlTextField.adjustsFontForContentSizeCategory = true // Remove the default drop interaction from the URL text field so that our // custom drop interaction on the BVC can accept dropped URLs. if let dropInteraction = urlTextField.textDropInteraction { urlTextField.removeInteraction(dropInteraction) } } lazy var trackingProtectionButton: LockButton = .build { trackingProtectionButton in trackingProtectionButton.addTarget(self, action: #selector(self.didPressTPShieldButton(_:)), for: .touchUpInside) trackingProtectionButton.clipsToBounds = false trackingProtectionButton.accessibilityIdentifier = AccessibilityIdentifiers.Toolbar.trackingProtection } private lazy var readerModeButton: ReaderModeButton = .build { readerModeButton in readerModeButton.addTarget(self, action: #selector(self.tapReaderModeButton), for: .touchUpInside) readerModeButton.addGestureRecognizer( UILongPressGestureRecognizer(target: self, action: #selector(self.longPressReaderModeButton))) readerModeButton.isAccessibilityElement = true readerModeButton.isHidden = true readerModeButton.accessibilityLabel = .TabLocationReaderModeAccessibilityLabel readerModeButton.accessibilityIdentifier = AccessibilityIdentifiers.Toolbar.readerModeButton readerModeButton.accessibilityCustomActions = [ UIAccessibilityCustomAction( name: .TabLocationReaderModeAddToReadingListAccessibilityLabel, target: self, selector: #selector(self.readerModeCustomAction))] } lazy var reloadButton: StatefulButton = { let reloadButton = StatefulButton(frame: .zero, state: .disabled) reloadButton.addTarget(self, action: #selector(tapReloadButton), for: .touchUpInside) reloadButton.addGestureRecognizer( UILongPressGestureRecognizer(target: self, action: #selector(longPressReloadButton))) reloadButton.tintColor = UIColor.Photon.Grey50 reloadButton.imageView?.contentMode = .scaleAspectFit reloadButton.contentHorizontalAlignment = .left reloadButton.accessibilityLabel = .TabLocationReloadAccessibilityLabel reloadButton.accessibilityIdentifier = AccessibilityIdentifiers.Toolbar.reloadButton reloadButton.isAccessibilityElement = true reloadButton.translatesAutoresizingMaskIntoConstraints = false return reloadButton }() override init(frame: CGRect) { super.init(frame: frame) register(self, forTabEvents: .didGainFocus, .didToggleDesktopMode, .didChangeContentBlocking) longPressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(longPressLocation)) longPressRecognizer.delegate = self tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapLocation)) tapRecognizer.delegate = self addGestureRecognizer(longPressRecognizer) addGestureRecognizer(tapRecognizer) let space1px = UIView.build() space1px.widthAnchor.constraint(equalToConstant: 1).isActive = true let subviews = [trackingProtectionButton, space1px, urlTextField, readerModeButton, reloadButton] contentView = UIStackView(arrangedSubviews: subviews) contentView.distribution = .fill contentView.alignment = .center contentView.translatesAutoresizingMaskIntoConstraints = false addSubview(contentView) contentView.edges(equalTo: self) NSLayoutConstraint.activate([ trackingProtectionButton.widthAnchor.constraint(equalToConstant: TabLocationViewUX.TPIconSize), trackingProtectionButton.heightAnchor.constraint(equalToConstant: TabLocationViewUX.ButtonSize), readerModeButton.widthAnchor.constraint(equalToConstant: TabLocationViewUX.ReaderModeButtonWidth), readerModeButton.heightAnchor.constraint(equalToConstant: TabLocationViewUX.ButtonSize), reloadButton.widthAnchor.constraint(equalToConstant: TabLocationViewUX.ReaderModeButtonWidth), reloadButton.heightAnchor.constraint(equalToConstant: TabLocationViewUX.ButtonSize), ]) // Setup UIDragInteraction to handle dragging the location // bar for dropping its URL into other apps. let dragInteraction = UIDragInteraction(delegate: self) dragInteraction.allowsSimultaneousRecognitionDuringLift = true self.addInteraction(dragInteraction) menuBadge.add(toParent: contentView) menuBadge.show(false) } required init(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Accessibility private lazy var _accessibilityElements = [urlTextField, readerModeButton, reloadButton, trackingProtectionButton] override var accessibilityElements: [Any]? { get { return _accessibilityElements.filter { !$0.isHidden } } set { super.accessibilityElements = newValue } } func overrideAccessibility(enabled: Bool) { _accessibilityElements.forEach { $0.isAccessibilityElement = enabled } } // MARK: - User actions @objc func tapReaderModeButton() { delegate?.tabLocationViewDidTapReaderMode(self) } @objc func tapReloadButton() { delegate?.tabLocationViewDidTapReload(self) } @objc func longPressReaderModeButton(_ recognizer: UILongPressGestureRecognizer) { if recognizer.state == .began { delegate?.tabLocationViewDidLongPressReaderMode(self) } } @objc func longPressReloadButton(_ recognizer: UILongPressGestureRecognizer) { if recognizer.state == .began { delegate?.tabLocationViewDidLongPressReload(self) } } @objc func longPressLocation(_ recognizer: UITapGestureRecognizer) { if recognizer.state == .began { delegate?.tabLocationViewDidLongPressLocation(self) } } @objc func tapLocation(_ recognizer: UITapGestureRecognizer) { delegate?.tabLocationViewDidTapLocation(self) } @objc func didPressTPShieldButton(_ button: UIButton) { delegate?.tabLocationViewDidTapShield(self) } @objc func readerModeCustomAction() -> Bool { return delegate?.tabLocationViewDidLongPressReaderMode(self) ?? false } private func updateTextWithURL() { if let host = url?.host, AppConstants.MOZ_PUNYCODE { urlTextField.text = url?.absoluteString.replacingOccurrences(of: host, with: host.asciiHostToUTF8()) } else { urlTextField.text = url?.absoluteString } // remove https:// (the scheme) from the url when displaying if let scheme = url?.scheme, let range = url?.absoluteString.range(of: "\(scheme)://") { urlTextField.text = url?.absoluteString.replacingCharacters(in: range, with: "") } } } // MARK: - Private private extension TabLocationView { var isTrackingProtectionHidden: Bool { !["https", "http"].contains(url?.scheme ?? "") } func setReaderModeState(_ newReaderModeState: ReaderModeState) { let wasHidden = readerModeButton.isHidden self.readerModeButton.readerModeState = newReaderModeState readerModeButton.isHidden = (newReaderModeState == ReaderModeState.unavailable) if wasHidden != readerModeButton.isHidden { UIAccessibility.post(notification: UIAccessibility.Notification.layoutChanged, argument: nil) if !readerModeButton.isHidden { // Delay the Reader Mode accessibility announcement briefly to prevent interruptions. DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(2)) { UIAccessibility.post(notification: UIAccessibility.Notification.announcement, argument: String.ReaderModeAvailableVoiceOverAnnouncement) } } } UIView.animate(withDuration: 0.1, animations: { () -> Void in self.readerModeButton.alpha = newReaderModeState == .unavailable ? 0 : 1 }) } } extension TabLocationView: UIGestureRecognizerDelegate { func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { // When long pressing a button make sure the textfield's long press gesture is not triggered return !(otherGestureRecognizer.view is UIButton) } func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool { // If the longPressRecognizer is active, fail the tap recognizer to avoid conflicts. return gestureRecognizer == longPressRecognizer && otherGestureRecognizer == tapRecognizer } } extension TabLocationView: UIDragInteractionDelegate { func dragInteraction(_ interaction: UIDragInteraction, itemsForBeginning session: UIDragSession) -> [UIDragItem] { // Ensure we actually have a URL in the location bar and that the URL is not local. guard let url = self.url, !InternalURL.isValid(url: url), let itemProvider = NSItemProvider(contentsOf: url) else { return [] } TelemetryWrapper.recordEvent(category: .action, method: .drag, object: .locationBar) let dragItem = UIDragItem(itemProvider: itemProvider) return [dragItem] } func dragInteraction(_ interaction: UIDragInteraction, sessionWillBegin session: UIDragSession) { delegate?.tabLocationViewDidBeginDragInteraction(self) } } extension TabLocationView: AccessibilityActionsSource { func accessibilityCustomActionsForView(_ view: UIView) -> [UIAccessibilityCustomAction]? { if view === urlTextField { return delegate?.tabLocationViewLocationAccessibilityActions(self) } return nil } } extension TabLocationView: NotificationThemeable { func applyTheme() { urlTextField.textColor = UIColor.theme.textField.textAndTint readerModeButton.applyTheme() trackingProtectionButton.applyTheme() let color = LegacyThemeManager.instance.currentName == .dark ? UIColor(white: 0.3, alpha: 0.6): UIColor.theme.textField.background menuBadge.badge.tintBackground(color: color) } } extension TabLocationView: TabEventHandler { func tabDidChangeContentBlocking(_ tab: Tab) { updateBlockerStatus(forTab: tab) } private func updateBlockerStatus(forTab tab: Tab) { assertIsMainThread("UI changes must be on the main thread") guard let blocker = tab.contentBlocker else { return } trackingProtectionButton.alpha = 1.0 var lockImage: UIImage? // TODO: FXIOS-5101 Use theme.type.getThemedImageName() let imageID = LegacyThemeManager.instance.currentName == .dark ? "lock_blocked_dark" : "lock_blocked" if !(tab.webView?.hasOnlySecureContent ?? false) { lockImage = UIImage(imageLiteralResourceName: imageID) } else if let tintColor = trackingProtectionButton.tintColor { lockImage = UIImage(imageLiteralResourceName: ImageIdentifiers.lockVerifed) .withTintColor(tintColor, renderingMode: .alwaysTemplate) } switch blocker.status { case .blocking, .noBlockedURLs: trackingProtectionButton.setImage(lockImage, for: .normal) case .safelisted: trackingProtectionButton.setImage(lockImage?.overlayWith(image: UIImage(imageLiteralResourceName: "MarkAsRead")), for: .normal) case .disabled: trackingProtectionButton.setImage(lockImage, for: .normal) } } func tabDidGainFocus(_ tab: Tab) { updateBlockerStatus(forTab: tab) } }
mpl-2.0
d2c7cdea7181f7052177890663306055
42.728814
167
0.714147
5.839306
false
false
false
false
GXFrighting/GXComboBox
GXComboBox/Classes/GXComboBoxBtn.swift
1
725
// // GXComboBoxBtn.swift // GXComboBox // // Created by Jiang on 2017/9/19. // Copyright © 2017年 Jiang. All rights reserved. // import UIKit class GXComboBoxBtn: UIButton { var space: CGFloat = 5 override func layoutSubviews() { super.layoutSubviews() guard let titleLabel = titleLabel else { return } guard let imageView = imageView else { return } let titleFrame = titleLabel.frame let imageFrame = imageView.frame titleLabel.frame.origin.x = (frame.size.width - (titleFrame.size.width + imageFrame.size.width + space)) * 0.5 imageView.frame.origin.x = titleLabel.frame.origin.x + titleLabel.frame.size.width + space } }
mit
24aec4b3ed332fab0fbf39cf86c8730c
26.769231
118
0.646814
4.17341
false
false
false
false
smartnsoft/Extra
Extra/Classes/Foundation/String+Extra.swift
1
2952
// The MIT License (MIT) // // Copyright (c) 2017 Smart&Soft // // 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 String { /// Same as boundingRect(), but simplified ! /// /// - parameter width: width into the string is constrained /// - parameter attributes: Your attributed string attributes /// /// - returns: computed height according to the string length public func heightConstrained(to width: CGFloat, attributes: [NSAttributedString.Key: Any]? = nil) -> CGFloat { let constraintRect = CGSize(width: width, height: CGFloat.greatestFiniteMagnitude) let boundingBox = self.boundingRect(with: constraintRect, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: attributes, context: nil) return boundingBox.height } /// regex : [A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6} /// /// - returns: True or false mail validation public func isValidEmail() -> Bool { let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}" return NSPredicate(format: "SELF MATCHES %@", emailRegex).evaluate(with: self) } /// Capitalize only the first letter of the entire string (localized capitalized) public func firstCapitalized() -> String { if self.isEmpty { return self } return String(self.prefix(1)).uppercased() + String(self.dropFirst()) } /// Check if the string matches to the passed regex public func matchesRegex(regex: String) -> Bool { let predicate = NSPredicate(format: "SELF MATCHES %@", regex) return predicate.evaluate(with: self) } /// Base-64 encoded String from a raw String /// /// - Returns: encoded string func base64() -> String? { return self.data(using: String.Encoding.utf8)?.base64EncodedString() } }
mit
4de7e2c80c0635028ec36d82528558b9
38.891892
113
0.676152
4.541538
false
false
false
false
JackYoustra/Aubade-Word-Acrobat
Aubade Word Acrobat/GameScene.swift
1
9208
// // GameScene.swift // Aubade Word Acrobat // // Created by Jack Youstra on 11/20/15. // Copyright (c) 2015 HouseMixer. All rights reserved. // import SpriteKit struct PhysicsCategory { static let None : UInt32 = 0 static let All : UInt32 = UInt32.max static let Window : UInt32 = 0b1 static let Word : UInt32 = 0b10 } class GameScene: SKScene { var start: Bool = false; var falling: Bool = false let title = SKLabelNode(fontNamed:"Cornerstone") var positionTable = Dictionary<SKLabelNode, CGPoint>(minimumCapacity: AubadeFileInteractor.getWords().count) // holds labels and where they should go when clicked on var lineNodeTable = Dictionary<String, Array<SKLabelNode>>() func initialization(){ self.backgroundColor = SKColor.blackColor() self.physicsBody = SKPhysicsBody(edgeLoopFromRect: self.frame) } override func didMoveToView(view: SKView) { initialization(); /* Setup your scene here */ title.text = "Aubade"; title.fontSize = 150; title.position = CGPoint(x:CGRectGetMidX(self.frame), y:CGRectGetMidY(self.frame)); self.addChild(title) } override func mouseDown(theEvent: NSEvent) { /* Called when a mouse click occurs */ if(!start){ start = true initialExplosion(); falling = true return; } if falling{ return } let location = theEvent.locationInNode(self) let clickedNode = self.nodeAtPoint(location) if clickedNode.name == "word" && clickedNode.physicsBody?.pinned == false{ let clickedWord = clickedNode as! SKLabelNode //clickedWord.physicsBody?.applyImpulse(CGVector(dx: 0.0, dy: 20.0)) let wordText = clickedWord.text! let lines = AubadeFileInteractor.getLines() for var index = 0; index < lines.count; ++index{ let line = lines[index] if lineNodeTable[line]![0].physicsBody?.pinned == true{ // check for already on continue } let words = line.componentsSeparatedByString(" ") var containsYes = false for word in words{ if word == wordText{ containsYes = true break } } if containsYes { let nodes = lineNodeTable[line]! for textNode in nodes{ // calculate let destination = positionTable[textNode]! // move //textNode.position = destination let moveToPoint = SKAction.moveTo(destination, duration: 2.0) let pushUp = SKAction.runBlock({ () -> Void in textNode.physicsBody?.applyImpulse(CGVector(dx: 0.0, dy: 25.0)) }) textNode.runAction(SKAction.sequence( [ pushUp, SKAction.waitForDuration(0.5), moveToPoint, ]), completion: { () -> Void in // fix node textNode.position = destination textNode.zRotation = 0.0 textNode.physicsBody?.pinned = true textNode.physicsBody?.allowsRotation = false textNode.physicsBody?.dynamic = false var over = true for child in self.children{ let textChild = child as? SKLabelNode if textChild != nil{ if textChild?.physicsBody?.pinned == false{ over = false break } } } if over{ self.gameOver() } }) } break } } } /* let sprite = SKSpriteNode(imageNamed:"Spaceship") sprite.position = location; sprite.setScale(0.5) let action = SKAction.rotateByAngle(CGFloat(M_PI), duration:1) sprite.runAction(SKAction.repeatActionForever(action)) self.addChild(sprite) */ } override func update(currentTime: CFTimeInterval) { /* Called before each frame is rendered */ } func gameOver(){ for child in self.children{ let textChild = child as? SKLabelNode if textChild != nil{ let destination = CGPoint(x: textChild!.position.x + (self.frame.size.width/2) - 140, y: textChild!.position.y) textChild!.runAction(SKAction.sequence( [ SKAction.waitForDuration(0.5), SKAction.moveTo(destination, duration: 5.0), SKAction.waitForDuration(0.5), SKAction.runBlock({ () -> Void in // cleanup and explode textChild!.physicsBody?.pinned = false textChild!.physicsBody?.allowsRotation = true textChild!.physicsBody?.dynamic = true textChild!.physicsBody?.applyImpulse(CGVector(dx: self.randomVelocity(), dy: self.randomVelocity())) }) ] )) } } } func randomVelocity() ->Double{ return (10.0 - Double(arc4random_uniform(100))/5.0) * 2.0 } func initialExplosion(){ // cleanup title.removeFromParent() let lines = AubadeFileInteractor.getLines(); let importance = AubadeFileInteractor.getWordImportance() for var index = 0; index < lines.count; ++index{ let line = lines[index] let wordsInLine = line.componentsSeparatedByString(" ") var lineNodes = Array<SKLabelNode>() var currentX: CGFloat = 0.0 for word in wordsInLine{ let label = createWordLabel(word) label.fontSize = label.fontSize + (CGFloat(importance[word.lowercaseString]!) * 2.0) // calculate let poemPlacement = CGPoint(x: currentX+(label.frame.size.width/2) + 10, y: CGRectGetMaxY(self.frame) - CGFloat(index)*14 - 15) // take into account centering & top row currentX += label.frame.size.width positionTable[label] = poemPlacement lineNodes.append(label) // place /* label.position = CGPoint(x:CGFloat(arc4random() % UInt32(UInt(self.frame.size.width))), y:self.frame.size.height-50); self.addChild(label) */ } lineNodeTable[line] = lineNodes } let lineLabels = lineNodeTable.values var actionQueue = Array<SKAction>() for var currentImportance = 1; currentImportance <= 5; ++currentImportance{ for lineLabelArr in lineLabels{ for label in lineLabelArr{ if importance[label.text!.lowercaseString] == currentImportance{ let action = SKAction.runBlock({ () -> Void in let modBase = UInt32(UInt(self.frame.size.width-label.frame.size.width)) let xCoordinate = CGFloat(UInt32(label.frame.size.width/2.0) + arc4random() % modBase) label.position = CGPoint(x:xCoordinate, y:self.frame.size.height-label.frame.size.height-30); self.addChild(label) }) actionQueue.append(SKAction.sequence([action, SKAction.waitForDuration(0.25)])) } } } } self.runAction(SKAction.sequence(actionQueue)) { () -> Void in self.falling = false } } func createWordLabel(word: String) -> SKLabelNode{ let label = SKLabelNode(text: word) label.fontName = "Cornerstone" label.fontSize = 8 label.name = "word" label.physicsBody = SKPhysicsBody(rectangleOfSize: label.frame.size) label.physicsBody?.mass = 0.01 label.physicsBody?.restitution = 0.5 label.physicsBody?.angularDamping = 0.3 return label } }
mit
2d704e5aa9c7447f4ca92925e88d7eb6
37.527197
184
0.488162
5.445299
false
false
false
false
rsyncOSX/RsyncOSX
RsyncOSX/Catalogsandfiles.swift
1
5843
// // files.swift // RsyncOSX // // Created by Thomas Evensen on 26.04.2017. // Copyright © 2017 Thomas Evensen. All rights reserved. // import Foundation enum Result<Value, Error: Swift.Error> { case success(Value) case failure(Error) } // typealias HandlerRsyncOSX = (Result<Data, RsyncOSXTypeErrors>) -> Void // typealias Handler = (Result<Data, Error>) -> Void typealias HandlerNSNumber = (Result<NSNumber, Error>) throws -> Void /* extension Result { func get() throws -> Value { switch self { case let .success(value): return value case let .failure(error): throw error } } } */ enum RsyncOSXTypeErrors: LocalizedError { case writelogfile case profilecreatedirectory case profiledeletedirectory case logfilesize case createsshdirectory case combine case emptylogfile case readerror case rsyncerror case task var errorDescription: String? { switch self { case .writelogfile: return "Error writing to logfile" case .profilecreatedirectory: return "Error in creating profile directory" case .profiledeletedirectory: return "Error in delete profile directory" case .logfilesize: return "Error filesize logfile, is getting bigger" case .createsshdirectory: return "Error in creating ssh directory" case .combine: return "Error in Combine" case .emptylogfile: return "Error empty logfile" case .readerror: return "Some error trying to read a file" case .rsyncerror: return NSLocalizedString("There are errors in output", comment: "rsync error") case .task: return "Execute task failed" } } } // Protocol for reporting file errors protocol ErrorMessage: AnyObject { func errormessage(errorstr: String, error: RsyncOSXTypeErrors) } protocol Errors { var errorDelegate: ErrorMessage? { get } } extension Errors { var errorDelegate: ErrorMessage? { return SharedReference.shared.getvcref(viewcontroller: .vctabmain) as? ViewControllerMain } func error(errordescription: String, errortype: RsyncOSXTypeErrors) { errorDelegate?.errormessage(errorstr: errordescription, error: errortype) } } class Catalogsandfiles: NamesandPaths { func getfullpathsshkeys() -> [String]? { if let atpath = fullpathsshkeys { do { var array = [String]() for file in try Folder(path: atpath).files { array.append(file.name) } return array } catch { return nil } } return nil } func getcatalogsasstringnames() -> [String]? { if let atpath = fullpathmacserial { var array = [String]() // Append default profile array.append(NSLocalizedString("Default profile", comment: "default profile")) do { for folders in try Folder(path: atpath).subfolders { array.append(folders.name) } return array } catch { return nil } } return nil } // Create profile catalog at first start of RsyncOSX. // If profile catalog exists - bail out, no need to create func createrootprofilecatalog() { var root: Folder? var catalog: String? // First check if profilecatalog exists, if yes bail out if let macserialnumber = macserialnumber, let fullrootnomacserial = fullpathnomacserial { do { let pathexists = try Folder(path: fullrootnomacserial).containsSubfolder(named: macserialnumber) guard pathexists == false else { return } } catch { // if fails then create profile catalogs // Creating profile catalalog is a two step task // 1: create profilecatalog // 2: create profilecatalog/macserialnumber // config path (/.rsyncosx) catalog = SharedReference.shared.configpath root = Folder.home do { try root?.createSubfolder(at: catalog ?? "") } catch let e { let error = e self.error(errordescription: error.localizedDescription, errortype: .profilecreatedirectory) return } if let macserialnumber = self.macserialnumber, let fullrootnomacserial = fullpathnomacserial { do { try Folder(path: fullrootnomacserial).createSubfolder(at: macserialnumber) } catch let e { let error = e self.error(errordescription: error.localizedDescription, errortype: .profilecreatedirectory) return } } } } } // Create SSH catalog // If ssh catalog exists - bail out, no need to create func createsshkeyrootpath() { if let path = onlysshkeypath { let root = Folder.home guard root.containsSubfolder(named: path) == false else { return } do { try root.createSubfolder(at: path) } catch let e { let error = e as NSError self.error(errordescription: error.description, errortype: .createsshdirectory) return } } } override init(_ whichroot: Rootpath) { super.init(whichroot) } }
mit
f53de4a72e9905ced151e7280f741213
30.923497
116
0.567614
4.888703
false
false
false
false
joalbright/Relax
Example/Relax/MarvelTVC.swift
1
2314
// // MarvelTVC.swift // Relax // // Created by Jo Albright on 1/15/16. // Copyright © 2016 CocoaPods. All rights reserved. // import UIKit class MarvelTVC: UITableViewController { override func viewDidLoad() { super.viewDidLoad() MarvelAPI.session().start() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) MarvelAPI.session().request(MarvelAPI.Endpoints.characters.endpoint) { guard let data = $0.0?["data"] as? [String:Any] else { return } self.characters = data["results"] as? [[String:Any]] ?? [] self.tableView.reloadData() } } var characters: [ParsedInfo] = [] override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return characters.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "CharacterCell", for: indexPath) as! CharacterCell let character = characters[indexPath.row] cell.characterNameLabel?.text = character["name"] as? String DispatchQueue.global().async { guard let thumbnail = character["thumbnail"] as? ParsedInfo else { return } guard let path = thumbnail["path"] as? String else { return } guard let ext = thumbnail["extension"] as? String else { return } guard let url = URL(string: path + "." + ext) else { return } guard let data = try? Data(contentsOf: url) else { return } let image = UIImage(data: data) DispatchQueue.main.async(execute: { cell.characterImageView?.image = image }) } return cell } } class CharacterCell: UITableViewCell { @IBOutlet weak var characterImageView: UIImageView! @IBOutlet weak var characterNameLabel: UILabel! override func prepareForReuse() { characterImageView.image = nil } }
mit
595e8bbccb42ddb2f4ea2c4abd67fa16
27.555556
124
0.562473
5.256818
false
false
false
false
nikrad/ios
FiveCalls/FiveCalls/Extensions/UIColor+FiveCalls.swift
2
1858
// // UIColor+FiveCalls.swift // FiveCalls // // Created by Ellen Shapiro on 2/13/17. // Copyright © 2017 5calls. All rights reserved. // import UIKit // Copy and paste into a playground to be able to see all colors. extension UIColor { //MARK: - Blues static let fvc_lightBlue = UIColor(red:0.68, green:0.82, blue:0.92, alpha:1.00) static let fvc_lightBlueBackground = UIColor(red:0.73, green:0.87, blue:0.98, alpha:1.0) static let fvc_darkBlue = UIColor(red:0.12, green:0.47, blue:0.81, alpha:1.00) static let fvc_darkBlueText = UIColor(colorLiteralRed:0.09, green:0.46, blue:0.82, alpha:1.0) //MARK - Grays static let fvc_superLightGray = UIColor(white: 0.96, alpha: 1.0) static let fvc_lightGray = UIColor(white: 0.90, alpha: 1.0) static let fvc_mediumGray = UIColor(white:0.88, alpha: 1.0) static let fvc_darkGray = UIColor(white: 0.4, alpha: 1.0) //MARK: - Other colors static let fvc_red = UIColor(red:0.90, green:0.22, blue:0.21, alpha:1.00) static let fvc_green = UIColor(red:0.00, green:0.62, blue:0.36, alpha:1.00) }
mit
6814dd16be1779f88d3c9cf1ccc289c4
31.017241
68
0.394723
4.665829
false
false
false
false
powerytg/PearlCam
PearlCam/PearlFX/Filters/SharpenFilterNode.swift
2
695
// // SharpenFilterNode.swift // PearlCam // // Created by Tiangong You on 6/10/17. // Copyright © 2017 Tiangong You. All rights reserved. // import UIKit import GPUImage class SharpenFilterNode: FilterNode { var sharpenFilter = Sharpen() init() { super.init(filter: sharpenFilter) enabled = true } var sharpness : Float? { didSet { if sharpness != nil { sharpenFilter.sharpness = sharpness! } } } override func cloneFilter() -> FilterNode? { let clone = SharpenFilterNode() clone.enabled = enabled clone.sharpness = sharpness return clone } }
bsd-3-clause
18a0b3105965140db341fa34f7b0bbf6
18.828571
55
0.576369
4.106509
false
false
false
false
gezi0630/weiboDemo
weiboDemo/weiboDemo/Classes/Main/MainViewController.swift
1
5806
// // MainViewController.swift // weiboDemo // // Created by MAC on 2016/12/23. // Copyright © 2016年 GuoDongge. All rights reserved. // import UIKit class MainViewController: UITabBarController { override func viewDidLoad() { super.viewDidLoad() //将图片和文字颜色设为橘色 tabBar.tintColor = UIColor.orange //添加子控制器 addChildViewControllers() // 从iOS7开始就不推荐在viewDidLoad中设置frame // print(tabBar.subviews) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // print(tabBar.subviews) //添加加号按钮 tabBar.addSubview(composeBtn) let width = UIScreen.main.bounds.size.width / CGFloat(viewControllers!.count) let rect = CGRect(x: 0, y: 0, width: width, height: 49) composeBtn.frame = rect.offsetBy(dx: 2 * width, dy: 0) } /** 监听加号按钮点击 注意: 监听按钮点击的方法不能是私有方法 按钮点击事件的调用是由 运行循环 监听并且以消息机制传递的,因此,按钮监听函数不能设置为 private */ func composeBtnClick() { print(#function) } //MARK: - 内部控制方法 /** *添加所有子控制器 */ private func addChildViewControllers() { /* 有时候需要动态改变控制器,所以就要把控制器用字符串形式添加上去*/ //1、获取json文件的路径 let path = Bundle.main.path(forResource: "MainVCSettings.json", ofType: nil) //2、通过文件路径创建NSData if let jsonPath = path { let jsonData = NSData(contentsOfFile: jsonPath) do{ // 有可能发生异常的代码放到这里 // 3.序列化json数据 --> Array // try : 发生异常会跳到catch中继续执行 // try! : 发生异常程序直接崩溃 let dictArr = try JSONSerialization.jsonObject(with: jsonData! as Data, options: JSONSerialization.ReadingOptions.mutableContainers) // print(dictArr) // 4.遍历数组, 动态创建控制器和设置数据 // 在Swift中, 如果需要遍历一个数组, 必须明确数据的类型 for dict in dictArr as! [[String: String]] { // 报错的原因是因为addChildViewController参数必须有值, 但是字典的返回值是可选类型 addChildViewController(childControllerName: dict["vcName"]!, title: dict["title"]!, imageName: dict["imageName"]!) } } catch { //发生异常之后会执行的代码 print(error) //从本地创建控制器 addChildViewController(childControllerName: "HomeViewController", title: "首页", imageName: "tabbar_home") addChildViewController(childControllerName: "MessageViewController", title: "消息", imageName: "tabbar_message_center") //在中间再添加一个占位控制器 addChildViewController(childControllerName: "NullViewController", title: "", imageName: "") addChildViewController(childControllerName: "DiscoverViewController", title: "发现", imageName: "tabbar_discover") addChildViewController(childControllerName: "ProfileViewController", title: "我", imageName: "tabbar_profile") } } } /** 初始化子控制器 childController 需要初始化的自控制器 title 子控制器的标题 imageName 子控制器的图片 */ private func addChildViewController(childControllerName: String,title:String,imageName:String) { //_1.动态获取命名空间(获取项目名称) let ns = Bundle.main.infoDictionary!["CFBundleExecutable"]as! String //_2.将字符串转化成类 let cls:AnyClass? = NSClassFromString(ns + "." + childControllerName) //_3.将AnyClass转换为指定类型 let vcCls = cls as! UIViewController.Type //_4.通过类创建对象 let vc = vcCls.init() // 1、设置控制器tabbar对应的数据 vc.tabBarItem.image = UIImage(named: imageName) vc.tabBarItem.selectedImage = UIImage(named: imageName + "_highlighted") vc.title = title //2、给控制器包装一个导航控制器 let nav = UINavigationController() nav.addChildViewController(vc) //3、将导航控制器添加到当前控制器上 addChildViewController(nav) } // MARK: - 懒加载 -中间按钮 private lazy var composeBtn: UIButton = { let btn = UIButton() //2、设置前景图片 btn.setImage(UIImage(named:"tabbar_compose_icon_add"), for: UIControlState.normal) btn.setImage(UIImage(named:"tabbar_compose_icon_add_highlighted"), for: UIControlState.highlighted) //3、设置背景图片 btn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), for: UIControlState.normal) btn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), for: UIControlState.highlighted) //4、添加点击事件 btn.addTarget(self, action: #selector(MainViewController.composeBtnClick), for: UIControlEvents.touchUpInside) return btn }() }
apache-2.0
65ad6b186a2acdee3a1f8de9aa9f161f
27.852941
144
0.579817
4.671429
false
false
false
false
ZeroFengLee/CmdBluetooth
CmdBluetoothDemo/Pods/CmdBluetooth/CmdBluetooth/CmdBase/CmdAccessory.swift
1
1405
// // CmdAccessory.swift // CmdBluetooth // // Created by 李锋 on 16/5/6. // Copyright © 2016年 Zero. All rights reserved. // import UIKit class CmdAccessory: NSObject { /** `BCD转码` `补齐16位 */ class func stringToBytesWithCRC(_ string: String) -> Data? { let stringLength = string.characters.count if stringLength % 2 != 0 { return nil } var crc: unichar = 0x00 var bytes:[UInt8] = [UInt8]() for index in 0...(stringLength - 1) { if index % 2 != 0 { continue } let range:Range = string.characters.index(string.startIndex, offsetBy: index)..<string.characters.index(string.startIndex, offsetBy: index + 2) let byteStr = string.substring(with: range) let scanner = Scanner(string: byteStr) var byteInt: UInt32 = 0 scanner.scanHexInt32(&byteInt) crc += UInt16(byteInt) bytes.append(UInt8(byteInt)) } //补齐字段 let leftCount: Int = 16 - string.characters.count / 2 - 1 for _ in 0...leftCount { bytes.append(0x00) } bytes.append(UInt8(crc & 0xff)) return Data(bytes: UnsafePointer<UInt8>(bytes), count: 16) } }
mit
773ba22c726d6f9eb13a9bb8bceebbc2
25.037736
155
0.515217
4.169184
false
false
false
false
vizllx/goeuro-iOS
goeuro_SM/HelperClass/HelperUtilityClass.swift
1
2909
// // HelperUtilityClass.swift // goeuro_SM // // Created by Sandeep-M on 12/09/16. // Copyright © 2016 Sandeep-Mukherjee. All rights reserved. // import UIKit import AFNetworking.AFNetworkReachabilityManager public class HelperUtilityClass: NSObject { public class var sharedInstance: HelperUtilityClass { struct Static { static var onceToken: dispatch_once_t = 0 static var instance: HelperUtilityClass? = nil } dispatch_once(&Static.onceToken) { Static.instance = HelperUtilityClass() } return Static.instance! } public func startMonitoringInternet() { AFNetworkReachabilityManager.sharedManager().setReachabilityStatusChangeBlock { (status: AFNetworkReachabilityStatus) -> Void in switch status { case .NotReachable: print("Not reachable") case .ReachableViaWiFi, .ReachableViaWWAN: print("Reachable") NSNotificationCenter.defaultCenter().postNotificationName("ActiveConnectionFound", object: nil) case .Unknown: print("Unknown") } } AFNetworkReachabilityManager.sharedManager().startMonitoring() } public func stringToDateTransformer(date: String) -> NSDate { let dateFormatter: NSDateFormatter = NSDateFormatter() dateFormatter.dateStyle = .ShortStyle dateFormatter.dateFormat = "HH:mm" return dateFormatter.dateFromString(date)! } public func dateToStringTransformer(date: NSDate) -> String { let dateFormatter: NSDateFormatter = NSDateFormatter() dateFormatter.dateStyle = .ShortStyle dateFormatter.dateFormat = "HH:mm" return dateFormatter.stringFromDate(date) } public func getTimeDuration(arrivalTime:NSDate ,departureTime:NSDate)-> NSDate { let diff: NSTimeInterval = arrivalTime.timeIntervalSinceDate(departureTime) return NSDate(timeIntervalSinceReferenceDate: diff) } public func getImgURLwithSize(url:NSString, size:Float)-> NSString { let newString = url.stringByReplacingOccurrencesOfString("{size}", withString:NSString(format: "%.0f", size) as String) return newString } public func showHUD(vw: UIView) { let activityView = UIActivityIndicatorView(activityIndicatorStyle: .WhiteLarge) activityView.color! = UIColor.redColor() activityView.tag = 999 activityView.center = vw.center activityView.startAnimating() vw.addSubview(activityView) } public func removeHUD(vw: UIView) { for vw: UIView in vw.subviews { if vw.tag == 999 { vw.removeFromSuperview() } } } }
mit
3ea22db0ffc5323af7d61ff3e7570871
27.792079
136
0.629642
5.497164
false
false
false
false
Harry-L/5-3-1
ios-charts-master/Charts/Classes/Renderers/ChartXAxisRenderer.swift
4
14686
// // ChartXAxisRenderer.swift // Charts // // Created by Daniel Cohen Gindi on 3/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics import UIKit public class ChartXAxisRenderer: ChartAxisRendererBase { public var xAxis: ChartXAxis? public init(viewPortHandler: ChartViewPortHandler, xAxis: ChartXAxis, transformer: ChartTransformer!) { super.init(viewPortHandler: viewPortHandler, transformer: transformer) self.xAxis = xAxis } public func computeAxis(xValAverageLength xValAverageLength: Double, xValues: [String?]) { guard let xAxis = xAxis else { return } var a = "" let max = Int(round(xValAverageLength + Double(xAxis.spaceBetweenLabels))) for (var i = 0; i < max; i++) { a += "h" } let widthText = a as NSString let labelSize = widthText.sizeWithAttributes([NSFontAttributeName: xAxis.labelFont]) let labelWidth = labelSize.width let labelHeight = labelSize.height let labelRotatedSize = ChartUtils.sizeOfRotatedRectangle(labelSize, degrees: xAxis.labelRotationAngle) xAxis.labelWidth = labelWidth xAxis.labelHeight = labelHeight xAxis.labelRotatedWidth = labelRotatedSize.width xAxis.labelRotatedHeight = labelRotatedSize.height xAxis.values = xValues } public override func renderAxisLabels(context context: CGContext) { guard let xAxis = xAxis else { return } if (!xAxis.isEnabled || !xAxis.isDrawLabelsEnabled) { return } let yOffset = xAxis.yOffset if (xAxis.labelPosition == .Top) { drawLabels(context: context, pos: viewPortHandler.contentTop - yOffset, anchor: CGPoint(x: 0.5, y: 1.0)) } else if (xAxis.labelPosition == .TopInside) { drawLabels(context: context, pos: viewPortHandler.contentTop + yOffset + xAxis.labelRotatedHeight, anchor: CGPoint(x: 0.5, y: 1.0)) } else if (xAxis.labelPosition == .Bottom) { drawLabels(context: context, pos: viewPortHandler.contentBottom + yOffset, anchor: CGPoint(x: 0.5, y: 0.0)) } else if (xAxis.labelPosition == .BottomInside) { drawLabels(context: context, pos: viewPortHandler.contentBottom - yOffset - xAxis.labelRotatedHeight, anchor: CGPoint(x: 0.5, y: 0.0)) } else { // BOTH SIDED drawLabels(context: context, pos: viewPortHandler.contentTop - yOffset, anchor: CGPoint(x: 0.5, y: 1.0)) drawLabels(context: context, pos: viewPortHandler.contentBottom + yOffset, anchor: CGPoint(x: 0.5, y: 0.0)) } } private var _axisLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint()) public override func renderAxisLine(context context: CGContext) { guard let xAxis = xAxis else { return } if (!xAxis.isEnabled || !xAxis.isDrawAxisLineEnabled) { return } CGContextSaveGState(context) CGContextSetStrokeColorWithColor(context, xAxis.axisLineColor.CGColor) CGContextSetLineWidth(context, xAxis.axisLineWidth) if (xAxis.axisLineDashLengths != nil) { CGContextSetLineDash(context, xAxis.axisLineDashPhase, xAxis.axisLineDashLengths, xAxis.axisLineDashLengths.count) } else { CGContextSetLineDash(context, 0.0, nil, 0) } if (xAxis.labelPosition == .Top || xAxis.labelPosition == .TopInside || xAxis.labelPosition == .BothSided) { _axisLineSegmentsBuffer[0].x = viewPortHandler.contentLeft _axisLineSegmentsBuffer[0].y = viewPortHandler.contentTop _axisLineSegmentsBuffer[1].x = viewPortHandler.contentRight _axisLineSegmentsBuffer[1].y = viewPortHandler.contentTop CGContextStrokeLineSegments(context, _axisLineSegmentsBuffer, 2) } if (xAxis.labelPosition == .Bottom || xAxis.labelPosition == .BottomInside || xAxis.labelPosition == .BothSided) { _axisLineSegmentsBuffer[0].x = viewPortHandler.contentLeft _axisLineSegmentsBuffer[0].y = viewPortHandler.contentBottom _axisLineSegmentsBuffer[1].x = viewPortHandler.contentRight _axisLineSegmentsBuffer[1].y = viewPortHandler.contentBottom CGContextStrokeLineSegments(context, _axisLineSegmentsBuffer, 2) } CGContextRestoreGState(context) } /// draws the x-labels on the specified y-position public func drawLabels(context context: CGContext, pos: CGFloat, anchor: CGPoint) { guard let xAxis = xAxis else { return } let paraStyle = NSParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle paraStyle.alignment = .Center let labelAttrs = [NSFontAttributeName: xAxis.labelFont, NSForegroundColorAttributeName: xAxis.labelTextColor, NSParagraphStyleAttributeName: paraStyle] let labelRotationAngleRadians = xAxis.labelRotationAngle * ChartUtils.Math.FDEG2RAD let valueToPixelMatrix = transformer.valueToPixelMatrix var position = CGPoint(x: 0.0, y: 0.0) var labelMaxSize = CGSize() if (xAxis.isWordWrapEnabled) { labelMaxSize.width = xAxis.wordWrapWidthPercent * valueToPixelMatrix.a } for i in self.minX.stride(to: min(self.maxX + 1, xAxis.values.count), by: xAxis.axisLabelModulus) { let label = xAxis.values[i] if (label == nil) { continue } position.x = CGFloat(i) position.y = 0.0 position = CGPointApplyAffineTransform(position, valueToPixelMatrix) if (viewPortHandler.isInBoundsX(position.x)) { let labelns = label! as NSString if (xAxis.isAvoidFirstLastClippingEnabled) { // avoid clipping of the last if (i == xAxis.values.count - 1 && xAxis.values.count > 1) { let width = labelns.boundingRectWithSize(labelMaxSize, options: .UsesLineFragmentOrigin, attributes: labelAttrs, context: nil).size.width if (width > viewPortHandler.offsetRight * 2.0 && position.x + width > viewPortHandler.chartWidth) { position.x -= width / 2.0 } } else if (i == 0) { // avoid clipping of the first let width = labelns.boundingRectWithSize(labelMaxSize, options: .UsesLineFragmentOrigin, attributes: labelAttrs, context: nil).size.width position.x += width / 2.0 } } drawLabel(context: context, label: label!, xIndex: i, x: position.x, y: pos, attributes: labelAttrs, constrainedToSize: labelMaxSize, anchor: anchor, angleRadians: labelRotationAngleRadians) } } } public func drawLabel(context context: CGContext, label: String, xIndex: Int, x: CGFloat, y: CGFloat, attributes: [String: NSObject], constrainedToSize: CGSize, anchor: CGPoint, angleRadians: CGFloat) { guard let xAxis = xAxis else { return } let formattedLabel = xAxis.valueFormatter?.stringForXValue(xIndex, original: label, viewPortHandler: viewPortHandler) ?? label ChartUtils.drawMultilineText(context: context, text: formattedLabel, point: CGPoint(x: x, y: y), attributes: attributes, constrainedToSize: constrainedToSize, anchor: anchor, angleRadians: angleRadians) } private var _gridLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint()) public override func renderGridLines(context context: CGContext) { guard let xAxis = xAxis else { return } if (!xAxis.isDrawGridLinesEnabled || !xAxis.isEnabled) { return } CGContextSaveGState(context) if (!xAxis.gridAntialiasEnabled) { CGContextSetShouldAntialias(context, false) } CGContextSetStrokeColorWithColor(context, xAxis.gridColor.CGColor) CGContextSetLineWidth(context, xAxis.gridLineWidth) if (xAxis.gridLineDashLengths != nil) { CGContextSetLineDash(context, xAxis.gridLineDashPhase, xAxis.gridLineDashLengths, xAxis.gridLineDashLengths.count) } else { CGContextSetLineDash(context, 0.0, nil, 0) } let valueToPixelMatrix = transformer.valueToPixelMatrix var position = CGPoint(x: 0.0, y: 0.0) for i in self.minX.stride(to: self.maxX, by: xAxis.axisLabelModulus) { position.x = CGFloat(i) position.y = 0.0 position = CGPointApplyAffineTransform(position, valueToPixelMatrix) if (position.x >= viewPortHandler.offsetLeft && position.x <= viewPortHandler.chartWidth) { _gridLineSegmentsBuffer[0].x = position.x _gridLineSegmentsBuffer[0].y = viewPortHandler.contentTop _gridLineSegmentsBuffer[1].x = position.x _gridLineSegmentsBuffer[1].y = viewPortHandler.contentBottom CGContextStrokeLineSegments(context, _gridLineSegmentsBuffer, 2) } } CGContextRestoreGState(context) } public override func renderLimitLines(context context: CGContext) { guard let xAxis = xAxis else { return } var limitLines = xAxis.limitLines if (limitLines.count == 0) { return } CGContextSaveGState(context) let trans = transformer.valueToPixelMatrix var position = CGPoint(x: 0.0, y: 0.0) for (var i = 0; i < limitLines.count; i++) { let l = limitLines[i] if !l.isEnabled { continue } position.x = CGFloat(l.limit) position.y = 0.0 position = CGPointApplyAffineTransform(position, trans) renderLimitLineLine(context: context, limitLine: l, position: position) renderLimitLineLabel(context: context, limitLine: l, position: position, yOffset: 2.0 + l.yOffset) } CGContextRestoreGState(context) } private var _limitLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint()) public func renderLimitLineLine(context context: CGContext, limitLine: ChartLimitLine, position: CGPoint) { _limitLineSegmentsBuffer[0].x = position.x _limitLineSegmentsBuffer[0].y = viewPortHandler.contentTop _limitLineSegmentsBuffer[1].x = position.x _limitLineSegmentsBuffer[1].y = viewPortHandler.contentBottom CGContextSetStrokeColorWithColor(context, limitLine.lineColor.CGColor) CGContextSetLineWidth(context, limitLine.lineWidth) if (limitLine.lineDashLengths != nil) { CGContextSetLineDash(context, limitLine.lineDashPhase, limitLine.lineDashLengths!, limitLine.lineDashLengths!.count) } else { CGContextSetLineDash(context, 0.0, nil, 0) } CGContextStrokeLineSegments(context, _limitLineSegmentsBuffer, 2) } public func renderLimitLineLabel(context context: CGContext, limitLine: ChartLimitLine, position: CGPoint, yOffset: CGFloat) { let label = limitLine.label // if drawing the limit-value label is enabled if (label.characters.count > 0) { let labelLineHeight = limitLine.valueFont.lineHeight let xOffset: CGFloat = limitLine.lineWidth + limitLine.xOffset if (limitLine.labelPosition == .RightTop) { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: position.x + xOffset, y: viewPortHandler.contentTop + yOffset), align: .Left, attributes: [NSFontAttributeName: limitLine.valueFont, NSForegroundColorAttributeName: limitLine.valueTextColor]) } else if (limitLine.labelPosition == .RightBottom) { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: position.x + xOffset, y: viewPortHandler.contentBottom - labelLineHeight - yOffset), align: .Left, attributes: [NSFontAttributeName: limitLine.valueFont, NSForegroundColorAttributeName: limitLine.valueTextColor]) } else if (limitLine.labelPosition == .LeftTop) { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: position.x - xOffset, y: viewPortHandler.contentTop + yOffset), align: .Right, attributes: [NSFontAttributeName: limitLine.valueFont, NSForegroundColorAttributeName: limitLine.valueTextColor]) } else { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: position.x - xOffset, y: viewPortHandler.contentBottom - labelLineHeight - yOffset), align: .Right, attributes: [NSFontAttributeName: limitLine.valueFont, NSForegroundColorAttributeName: limitLine.valueTextColor]) } } } }
mit
60d68f97cd6795ef376202a7a78b958b
37.445026
210
0.585932
5.696664
false
false
false
false