repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
kripple/bti-watson
ios-app/Carthage/Checkouts/AlamofireObjectMapper/Carthage/Checkouts/ObjectMapper/Carthage/Checkouts/Nimble/Nimble/Utils/Stringers.swift
159
1605
import Foundation internal func identityAsString(value: AnyObject?) -> String { if value == nil { return "nil" } return NSString(format: "<%p>", unsafeBitCast(value!, Int.self)).description } internal func arrayAsString<T>(items: [T], joiner: String = ", ") -> String { return items.reduce("") { accum, item in let prefix = (accum.isEmpty ? "" : joiner) return accum + prefix + "\(stringify(item))" } } @objc internal protocol NMBStringer { func NMB_stringify() -> String } internal func stringify<S: SequenceType>(value: S) -> String { var generator = value.generate() var strings = [String]() var value: S.Generator.Element? repeat { value = generator.next() if value != nil { strings.append(stringify(value)) } } while value != nil let str = strings.joinWithSeparator(", ") return "[\(str)]" } extension NSArray : NMBStringer { func NMB_stringify() -> String { let str = self.componentsJoinedByString(", ") return "[\(str)]" } } internal func stringify<T>(value: T) -> String { if let value = value as? Double { return NSString(format: "%.4f", (value)).description } return String(value) } internal func stringify(value: NMBDoubleConvertible) -> String { if let value = value as? Double { return NSString(format: "%.4f", (value)).description } return value.stringRepresentation } internal func stringify<T>(value: T?) -> String { if let unboxed = value { return stringify(unboxed) } return "nil" }
mit
4eae5b45f5cfa424b2c5e3d66344b600
24.887097
80
0.612461
4.104859
false
false
false
false
Eonil/Editor
Editor4/ArraySynchronizationManager.swift
1
8813
//// //// ArraySynchronizationManager.swift //// Editor4 //// //// Created by Hoon H. on 2016/05/13. //// Copyright © 2016 Eonil. All rights reserved. //// // //import Foundation // //protocol SynchronizableElementType { // associatedtype SourceType: VersioningStateType // mutating func syncFrom(source: SourceType) //} //struct ArraySynchronizationManager<Element: SynchronizableElementType> { // private var latestSourceArrayVersion: Version? // private(set) var array = [Element]() //} // // // // // // //protocol DefaultInitializableType { // init() //} //protocol IdentifiableType { // associatedtype Identity: Hashable // func identify() -> Identity //} //extension ArraySynchronizationManager where //Element: DefaultInitializableType, //Element: IdentifiableType, //Element.SourceType: IdentifiableType, //Element.Identity == Element.SourceType.Identity { // // /// Performs synchronization with any possible optimizations. // /// // /// 1. If current version is equal to source array version, this is no-op. // /// 2. If source array has journal with current version, // /// journaling logs will be replayed on this array from there. // /// 3. If no proper version journal could be found, // /// this will perform full-resync, which means recreation of all elements. // /// // /// - Returns: // /// Indexes of changed elements. // /// // mutating func syncFrom<A: IndexJournalingArrayType where A.Generator.Element == Element.SourceType, A.Index == Int>(sourceArray: A) -> [Int] { // // Check and skip if possible. // guard latestSourceArrayVersion != sourceArray.version else { // // Nothing to do. // return [] // } // // switch syncUsingJournalFrom(sourceArray) { // case .OK: // break // // case .CancelBecauseJournalUnavailableForCurrentVersion: // resyncAllFrom(sourceArray) // } // } // // private mutating func syncUsingJournalFrom<A: IndexJournalingArrayType where A.Generator.Element == Element.SourceType, A.Index == Int>(sourceArray: A) -> SyncUsingJournalResult { // var journalAvailable = false // // // Sync partially using journal if possible. // for log in sourceArray.journal.logs { // if log.version == latestSourceArrayVersion { // journalAvailable = true // } // if journalAvailable { // switch log.operation { // case .Insert(let index): // // Concept of this code block is *following array changes as-is*. // // Because calculating final array only from index history is too hard... // // Which means this is designed only for small amount of changes. // // If you have massive amount of changes, you have to reload whole data // // into view. // // // // Problems and Solutions // // ---------------------- // // If the index is out-of-range, that means source element at the index // // does not exist, so we don't need to make a view for the index. // // So just ignore it. // // // // And also, always sync to latest version. // // Duplicated sync can happen but // // or elided by version check if you did it. // // var newElement = Element() // if sourceArray.entireRange.contains(index) { // newElement.syncFrom(sourceArray[index]) // } // array.insert(newElement, atIndex: index) // // case .Update(let index): // if sourceArray.entireRange.contains(index) { // array[index].syncFrom(sourceArray[index]) // } // // case .Delete(let index): // array.removeAtIndex(index) // } // } // } // // if journalAvailable == false { // // In this case, no mutation should be performed. // return .CancelBecauseJournalUnavailableForCurrentVersion // } // // latestSourceArrayVersion = sourceArray.version // return .OK // } // private mutating func resyncAllFrom<A: IndexJournalingArrayType where A.Generator.Element == Element.SourceType, A.Index == Int>(sourceArray: A) { // // Sync fully at worst case. // var reusables = Dictionary<Element.SourceType.Identity, Element>() // for r in array { // let id = r.identify() // reusables[id] = r // } // array = [] // array.reserveCapacity(sourceArray.count) // for s in sourceArray { // let id = s.identify() // var e = reusables[id] ?? Element() // e.syncFrom(s) // array.append(e) // } // latestSourceArrayVersion = sourceArray.version // } //} // //private enum SyncUsingJournalResult { // /// - Parameters: // /// First paramter is index of changed elements. // case OK([Int]) // case CancelBecauseJournalUnavailableForCurrentVersion //} // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // ////extension ArraySynchronizationManager { //// mutating func syncFrom(sourceArray: IndexJournalingArray<Element.SourceType>, @noescape produce: Element.SourceType->Element) { //// syncFrom(sourceArray, produce: produce, prepareFullSync: { _ in }) //// } //// /// Performs synchronization with any possible optimizations. //// /// //// /// 1. If current version is equal to source array version, this is no-op. //// /// 2. If source array has journal with current version, //// /// journaling logs will be replayed on this array from there. //// /// 3. If no proper version journal could be found, //// /// this will perform full-resync, which means recreation of all elements. //// /// //// /// - Parameter prepareFullSync: //// /// You can take some old instances to re-use them. //// /// This is required because some Cocoa components pointer equality //// /// to work properly. //// mutating func syncFrom(sourceArray: IndexJournalingArray<Element.SourceType>, @noescape produce: Element.SourceType->Element, @noescape prepareFullSync: (reusableInstances: [Element])->()) { //// // Check and skip if possible. //// guard latestSourceArrayVersion != sourceArray.version else { //// // Nothing to do. //// return //// } //// //// var journalAvailable = false //// //// // Sync partially using journal if possible. //// for log in sourceArray.journal.logs { //// if log.version == latestSourceArrayVersion { //// journalAvailable = true //// } //// if journalAvailable { //// switch log.operation { //// case .Insert(let index): //// // Sync to latest version, and duplicated call will be ignored by version comparison. //// var newElement = produce(sourceArray[index]) //// newElement.syncFrom(sourceArray[index]) //// array.insert(newElement, atIndex: index) //// //// case .Update(let index): //// array[index].syncFrom(sourceArray[index]) //// //// case .Delete(let index): //// array.removeAtIndex(index) //// } //// } //// } //// //// // Sync fully at worst case. //// if journalAvailable == false { //// prepareFullSync(reusableInstances: array) //// array = [] //// array.reserveCapacity(sourceArray.count) //// for s in sourceArray { //// var e = produce(s) //// e.syncFrom(s) //// array.append(e) //// } //// } //// //// latestSourceArrayVersion = sourceArray.version //// } //// mutating func syncFrom(sourceArray: Array<Element.SourceType>, @noescape produce: Element.SourceType->Element, @noescape prepareFullSync: (reusableInstances: [Element])->()) { //// // Sync fully at worst case. //// prepareFullSync(reusableInstances: array) //// array = [] //// array.reserveCapacity(sourceArray.count) //// for s in sourceArray { //// var e = produce(s) //// e.syncFrom(s) //// array.append(e) //// } //// latestSourceArrayVersion?.revise() //// } ////}
mit
dce1586d81b61519ac86faeb74521e59
33.425781
198
0.551975
4.292255
false
false
false
false
rcach/Tasks
TODO/TaskTableCellView.swift
1
17007
import Cocoa func dec(left:Float, right: Int) -> String { let nf = NSNumberFormatter() nf.maximumSignificantDigits = Int(right) return nf.stringFromNumber(NSNumber(float: left)) } var activeTimers = [String: Timer]() enum TaskCellState { case Todo case TodoMutationActivityInProgress case DoingTimerOff case DoingTimerOffMutationActivityInProgress case DoingTimerOn case DoingTimerOnMutationActivityInProgress case DoingEditHours case DoingSetHoursRemaining case DoneSetHours case Done case DoneMutationActivityInProgress case Empty } // TODO: Method indicateActivityStateForCurrentState enum ControlButtonImage: String { case CheckOutlineBlue = "CheckOutlineBlue" case CheckOutlineOrange = "CheckOutlineOrange" case CheckFilledGreen = "CheckFilledGreen" case ClockOutlineBlue = "ClockOutlineBlue" case OnOutlineOrange = "OnOutlineOrange" case CircleFilledOrange = "CircleFilledOrange" case CircleOutlineOrange = "CircleOutlineOrange" case CircleOutlineGreen = "CircleOutlineGreen" } enum MiddleButtonLabelText: String { case Doing = "DOING" case StartTimer = "START" case StopTimer = "STOP" } func imageForControlButton(controlButtonImage: ControlButtonImage) -> NSImage { return NSImage(named: controlButtonImage.toRaw()) } // TODO: Don't attempt to mark as doing when start timer button is on screen. class TaskTableCellView: NSTableCellView { @IBOutlet var numberPad: NumberPadView! @IBOutlet weak var leadingButton: NSButton! @IBOutlet weak var leadingButtonLabel: NSTextField! @IBOutlet weak var middleButton: NSButton! @IBOutlet weak var middleButtonLabel: NSTextField! @IBOutlet weak var trailingButton: NSButton! @IBOutlet weak var trailingButtonLabel: NSTextField! @IBOutlet weak var timeSpentLabel: NSTextField! var handler: TaskUIHandler? var rowHeightsOrNil: TableViewRowHeights? var state: TaskCellState? var indexOrNil: Int? @IBAction func done(sender: NSButton) { // TODO: Think about this, should this if branch be based on the status of the task or the current UI state? if state == .Done { transitionToState(.DoneMutationActivityInProgress) handler?.markTaskDoing() { [weak self] (errorOrNil: NSError?) -> () in if self == nil { return } if errorOrNil == nil { if let task = self?.handler?.task { self?.updateWithTask(task) } else { self?.transitionToState(.DoingTimerOff) } } else { self?.transitionToState(.Done) println("Error marking task as doing (from done): \(errorOrNil!)") } } return } if state == .Todo { transitionToState(.TodoMutationActivityInProgress) } else if state == .DoingTimerOff { transitionToState(.DoingTimerOffMutationActivityInProgress) } else { return } handler?.markTaskDone() { [weak self] (error: NSError?) -> () in if self == nil { return } if error == nil { if let task = self?.handler?.task { self?.updateWithTask(task) } else { self?.transitionToState(.Done) } } else { if let task = self?.handler?.task { self?.updateWithTask(task) } else { self?.transitionToState(.DoingTimerOff) } println("Error marking task as done: \(error!)") } } } @IBAction func doing(sender: NSButton) { if state == .Todo { transitionToState(.TodoMutationActivityInProgress) handler?.markTaskDoing() { [weak self] (error: NSError?) -> () in if self == nil { return } if error == nil { if let task = self?.handler?.task { self?.updateWithTask(task) } else { self?.transitionToState(.DoingTimerOff) } } else { println("Error marking task as doing: \(error!)") } } return } if state == .DoingTimerOff { if let realHandler = self.handler { activeTimers[realHandler.task.identifier] = Timer(task: realHandler.task) transitionToState(.DoingTimerOn) } return } if state == .DoingTimerOn { transitionToState(.DoingSetHoursRemaining) } } func updateWithTask(task: Task) { timeSpentLabel.stringValue = "\(Float(task.timeSpentSeconds)/(60.0 * 60.0))" switch task.status() { case .InDefinition: transitionToState(.Todo) case .Development, .Testing: if let timer = activeTimers[task.identifier] { transitionToState(.DoingTimerOn) } else { transitionToState(.DoingTimerOff) } case .Done: transitionToState(.Done) default: println() } } override func prepareForReuse() { super.prepareForReuse() handler = nil indexOrNil = nil } func transitionToState(state: TaskCellState) { loadNumberPadViewIfNeeded() switch state { case TaskCellState.Todo: leadingButton.image = imageForControlButton(.CheckOutlineBlue) leadingButtonLabel.textColor = NSColor.todoColor() leadingButton.enabled = true leadingButton.hidden = false leadingButtonLabel.hidden = false middleButton.image = imageForControlButton(.ClockOutlineBlue) middleButtonLabel.textColor = NSColor.todoColor() middleButtonLabel.stringValue = MiddleButtonLabelText.Doing.toRaw() middleButton.hidden = false middleButtonLabel.hidden = false trailingButton.hidden = true trailingButtonLabel.hidden = true timeSpentLabel.hidden = true middleButton.enabled = true trailingButton.enabled = true numberPad.hidden = true updateRowHeightUseCustomHeight(false) case TaskCellState.TodoMutationActivityInProgress: leadingButton.image = imageForControlButton(.CheckOutlineBlue) leadingButtonLabel.textColor = NSColor.todoColor() leadingButton.enabled = false leadingButton.hidden = false leadingButtonLabel.hidden = false middleButton.image = imageForControlButton(.ClockOutlineBlue) middleButtonLabel.textColor = NSColor.todoColor() middleButtonLabel.stringValue = MiddleButtonLabelText.Doing.toRaw() middleButton.hidden = false middleButtonLabel.hidden = false trailingButton.hidden = true trailingButtonLabel.hidden = true timeSpentLabel.hidden = true middleButton.enabled = false trailingButton.enabled = false numberPad.hidden = true updateRowHeightUseCustomHeight(false) case TaskCellState.DoingTimerOn: leadingButton.image = imageForControlButton(.CheckOutlineOrange) leadingButtonLabel.textColor = NSColor.doingColor() leadingButton.enabled = false leadingButton.hidden = false leadingButtonLabel.hidden = false middleButton.image = imageForControlButton(.CircleFilledOrange) middleButtonLabel.textColor = NSColor.doingColor() middleButtonLabel.stringValue = MiddleButtonLabelText.StopTimer.toRaw() middleButton.hidden = false middleButtonLabel.hidden = false trailingButton.hidden = true trailingButtonLabel.hidden = true timeSpentLabel.hidden = true middleButton.enabled = true trailingButton.enabled = false numberPad.hidden = true updateRowHeightUseCustomHeight(false) case TaskCellState.DoingTimerOnMutationActivityInProgress: leadingButton.image = imageForControlButton(.CheckOutlineOrange) leadingButtonLabel.textColor = NSColor.doingColor() leadingButton.enabled = false leadingButton.hidden = false leadingButtonLabel.hidden = false middleButton.image = imageForControlButton(.CircleFilledOrange) middleButtonLabel.textColor = NSColor.doingColor() middleButtonLabel.stringValue = MiddleButtonLabelText.StopTimer.toRaw() middleButton.hidden = false middleButtonLabel.hidden = false trailingButton.hidden = true trailingButtonLabel.hidden = true timeSpentLabel.hidden = true middleButton.enabled = false trailingButton.enabled = false numberPad.hidden = true updateRowHeightUseCustomHeight(false) case TaskCellState.DoingTimerOff: leadingButton.image = imageForControlButton(.CheckOutlineOrange) leadingButtonLabel.textColor = NSColor.doingColor() leadingButton.enabled = true leadingButton.hidden = false leadingButtonLabel.hidden = false middleButton.image = imageForControlButton(.OnOutlineOrange) middleButtonLabel.textColor = NSColor.doingColor() middleButtonLabel.stringValue = MiddleButtonLabelText.StartTimer.toRaw() middleButton.hidden = false middleButtonLabel.hidden = false trailingButton.image = imageForControlButton(.CircleOutlineOrange) trailingButtonLabel.textColor = NSColor.doingColor() trailingButton.hidden = true trailingButtonLabel.hidden = false timeSpentLabel.hidden = false timeSpentLabel.textColor = NSColor.doingColor() middleButton.enabled = true trailingButton.enabled = true numberPad.hidden = true updateRowHeightUseCustomHeight(false) case TaskCellState.DoingTimerOffMutationActivityInProgress: leadingButton.image = imageForControlButton(.CheckOutlineOrange) leadingButtonLabel.textColor = NSColor.doingColor() leadingButton.enabled = false leadingButton.hidden = false leadingButtonLabel.hidden = false middleButton.image = imageForControlButton(.OnOutlineOrange) middleButtonLabel.textColor = NSColor.doingColor() middleButtonLabel.stringValue = MiddleButtonLabelText.StartTimer.toRaw() middleButton.hidden = false middleButtonLabel.hidden = false trailingButton.image = imageForControlButton(.CircleOutlineOrange) trailingButtonLabel.textColor = NSColor.doingColor() trailingButton.hidden = true trailingButtonLabel.hidden = false timeSpentLabel.hidden = false timeSpentLabel.textColor = NSColor.doingColor() middleButton.enabled = false trailingButton.enabled = false numberPad.hidden = true updateRowHeightUseCustomHeight(false) case TaskCellState.DoingEditHours: leadingButton.image = imageForControlButton(.CheckOutlineOrange) leadingButtonLabel.textColor = NSColor.doingColor() leadingButton.enabled = true leadingButton.hidden = false leadingButtonLabel.hidden = false middleButton.image = imageForControlButton(.OnOutlineOrange) middleButtonLabel.textColor = NSColor.doingColor() middleButtonLabel.stringValue = "" middleButton.hidden = false middleButtonLabel.hidden = false trailingButton.image = imageForControlButton(.CircleOutlineOrange) trailingButtonLabel.textColor = NSColor.doingColor() trailingButton.hidden = true trailingButtonLabel.hidden = false timeSpentLabel.hidden = false timeSpentLabel.textColor = NSColor.doingColor() middleButton.enabled = false trailingButton.enabled = true numberPad.hidden = true updateRowHeightUseCustomHeight(false) case TaskCellState.DoingSetHoursRemaining: leadingButton.hidden = true leadingButtonLabel.hidden = true middleButton.hidden = true middleButtonLabel.hidden = true trailingButton.hidden = true trailingButtonLabel.hidden = true timeSpentLabel.hidden = true numberPad.hidden = false updateRowHeightUseCustomHeight(true) self.numberPad.onNumberPress = { hoursRemaining in if let realHandler = self.handler { if let timer = activeTimers[realHandler.task.identifier] { var seconds = timer.secondsSinceStart() self.handler?.logTime(seconds, numberOfHoursRemaining: hoursRemaining) { [weak self] (errorOrNil: NSError?) -> () in if self == nil { return } self!.transitionToState(TaskCellState.DoingTimerOff) if let error = errorOrNil { println("Error logging time: \(error)") } } self.transitionToState(.DoingTimerOnMutationActivityInProgress) activeTimers[realHandler.task.identifier] = nil return } } self.transitionToState(.DoingTimerOff) // TODO: Place in an error state. } case TaskCellState.DoneSetHours: leadingButton.image = imageForControlButton(.CheckOutlineOrange) leadingButtonLabel.textColor = NSColor.doingColor() leadingButton.enabled = true leadingButton.hidden = false leadingButtonLabel.hidden = false middleButton.image = imageForControlButton(.OnOutlineOrange) middleButtonLabel.textColor = NSColor.doingColor() middleButtonLabel.stringValue = "" middleButton.hidden = false middleButtonLabel.hidden = false trailingButton.image = imageForControlButton(.CircleOutlineOrange) trailingButtonLabel.textColor = NSColor.doingColor() trailingButton.hidden = true trailingButtonLabel.hidden = false timeSpentLabel.hidden = false timeSpentLabel.textColor = NSColor.doingColor() middleButton.enabled = false trailingButton.enabled = true numberPad.hidden = true updateRowHeightUseCustomHeight(false) case TaskCellState.Done: leadingButton.image = imageForControlButton(.CheckFilledGreen) leadingButtonLabel.textColor = NSColor.doneColor() leadingButton.enabled = true leadingButton.hidden = false leadingButtonLabel.hidden = false middleButton.hidden = true middleButtonLabel.hidden = true trailingButton.image = imageForControlButton(.CircleOutlineGreen) trailingButtonLabel.textColor = NSColor.doneColor() trailingButton.hidden = true trailingButtonLabel.hidden = false timeSpentLabel.hidden = false timeSpentLabel.textColor = NSColor.doneColor() middleButton.enabled = false trailingButton.enabled = true numberPad.hidden = true updateRowHeightUseCustomHeight(false) case TaskCellState.DoneMutationActivityInProgress: leadingButton.image = imageForControlButton(.CheckFilledGreen) leadingButtonLabel.textColor = NSColor.doneColor() leadingButton.enabled = false leadingButton.hidden = false leadingButtonLabel.hidden = false middleButton.hidden = true middleButtonLabel.hidden = true trailingButton.image = imageForControlButton(.CircleOutlineGreen) trailingButtonLabel.textColor = NSColor.doneColor() trailingButton.hidden = true trailingButtonLabel.hidden = false timeSpentLabel.hidden = false timeSpentLabel.textColor = NSColor.doneColor() middleButton.enabled = false trailingButton.enabled = false numberPad.hidden = true updateRowHeightUseCustomHeight(false) case TaskCellState.Empty: leadingButton.image = imageForControlButton(.CheckFilledGreen) leadingButtonLabel.textColor = NSColor.doneColor() leadingButton.enabled = false leadingButton.hidden = true leadingButtonLabel.hidden = true middleButton.hidden = true middleButtonLabel.hidden = true trailingButton.image = imageForControlButton(.CircleOutlineGreen) trailingButtonLabel.textColor = NSColor.doneColor() trailingButton.hidden = true trailingButtonLabel.hidden = true timeSpentLabel.hidden = true timeSpentLabel.textColor = NSColor.doneColor() middleButton.enabled = false trailingButton.enabled = true numberPad.hidden = true updateRowHeightUseCustomHeight(false) } self.state = state self.window?.recalculateKeyViewLoop() } func loadNumberPadViewIfNeeded() { if numberPad == nil { loadNumberPadView() // TODO: Use auto layout. numberPad.frame = NSRect(x: 0, y: -80, width: 320, height: 162) addSubview(numberPad) } } func loadNumberPadView() { NSBundle.mainBundle().loadNibNamed("NumberPadView", owner: self, topLevelObjects: nil) } // TODO: Use 'expanded' instead of 'custom.' func updateRowHeightUseCustomHeight(useCustomHeight: Bool) { if let rowHeights = self.rowHeightsOrNil { if let index = self.indexOrNil { if useCustomHeight { rowHeights.cellNeedsCustomHeight(230, atIndex: index) } else { rowHeights.cellNeedsDefaultHeightAtIndex(index) } } } } }
apache-2.0
46e99fdba3ecfd9687091c9fd4b28998
32.2818
112
0.686188
4.95542
false
false
false
false
jpush/jchat-swift
JChat/Src/Utilites/3rdParty/InputBar/SAIToolboxItem.swift
1
592
// // SAIToolboxItem.swift // SAC // // Created by SAGESSE on 9/15/16. // Copyright © 2016-2017 SAGESSE. All rights reserved. // import UIKit @objc open class SAIToolboxItem: NSObject { open var name: String open var identifier: String open var image: UIImage? open var highlightedImage: UIImage? public init(_ identifier: String, _ name: String, _ image: UIImage?, _ highlightedImage: UIImage? = nil) { self.identifier = identifier self.name = name self.image = image self.highlightedImage = highlightedImage } }
mit
6493945e9b0fe36100709d0fd39d0ca5
22.64
110
0.64467
3.966443
false
false
false
false
googleapis/google-auth-library-swift
Sources/Examples/TokenSource/main.swift
1
1327
// Copyright 2019 Google LLC. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation import Dispatch import OAuth2 let scopes = ["https://www.googleapis.com/auth/cloud-platform"] if let provider = DefaultTokenProvider(scopes: scopes) { let sem = DispatchSemaphore(value: 0) try provider.withToken() {(token, error) -> Void in if let token = token { let encoder = JSONEncoder() if let token = try? encoder.encode(token) { print("\(String(data:token, encoding:.utf8)!)") } } if let error = error { print("ERROR \(error)") } sem.signal() } _ = sem.wait(timeout: DispatchTime.distantFuture) } else { print("Unable to obtain an auth token.\nTry pointing GOOGLE_APPLICATION_CREDENTIALS to your service account credentials.") }
apache-2.0
be3d47e4b6409c5d038f6302b2c4fb77
33.921053
124
0.70535
4.108359
false
false
false
false
sjtu-meow/iOS
Meow/UserProfileViewController.swift
1
9094
// // UserProfileViewController.swift // Meow // // Created by 林武威 on 2017/7/19. // Copyright © 2017年 喵喵喵的伙伴. All rights reserved. // import UIKit import RxSwift import SwiftyJSON class UserProfileViewController: UITableViewController { class func show(_ profile: Profile, from viewController: UIViewController) { let vc = R.storyboard.main.userProfileViewController()! vc.profile = profile vc.userId = profile.userId viewController.navigationController?.pushViewController(vc, animated: true) } enum ContentType: Int { case article = 1, moment = 0, questionAnswer = 2 } let disposeBag = DisposeBag() var userId: Int! var contentType = ContentType.moment // var answers = [AnswerSummary]() // var questions = [QuestionSummary]() var isFollowing = false var questionAnswers = [ItemProtocol]() var articles = [ArticleSummary]() var moments = [Moment]() var profile: Profile? override func viewDidLoad() { tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 44 tableView.register(R.nib.articleUserPageTableViewCell) // tableView.register(R.nib.momentHomePageTableViewCell) tableView.register(R.nib.questionRecordTableViewCell) tableView.register(R.nib.answerRecordTableViewCell) loadData() } override func numberOfSections(in tableView: UITableView) -> Int { return 3 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section <= 1 { return profile != nil ? 1: 0 } switch contentType { case .article: return articles.count case .moment: return moments.count case .questionAnswer: return questionAnswers.count } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.section == 0 { let view = tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.userProfileWithButtonsTableViewCell)! view.configure(model: profile!) view.delegate = self view.updateFollowingButton(isFollowing: isFollowing) return view } else if indexPath.section == 1 { let view = tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.userProfileContentSwitcherCell)! initContentSwitcher(switcher: view) return view } switch contentType { case .moment: let item = moments[indexPath.row] //let view = tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.momentHomePageTableViewCell)! let view = R.nib.momentHomePageTableViewCell.firstView(owner: nil)! view.configure(model: item) return view case .article: let item = articles[indexPath.row] let view = tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.articleUserPageTableViewCell)! view.configure(model: item) return view case .questionAnswer: let item = questionAnswers[indexPath.row] if item is QuestionSummary { let view = tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.questionRecordTableViewCell)! view.configure(model: item as! QuestionSummary) return view } else { let view = tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.answerRecordTableViewCell)! view.configure(model: item as! AnswerSummary) return view } } } func initContentSwitcher(switcher: UserProfileContentSwitcher) { switcher.momentButton.tag = 0 switcher.articleButton.tag = 1 switcher.answerButton.tag = 2 for button in [switcher.momentButton, switcher.articleButton, switcher.answerButton] { button!.addTarget(self, action: #selector(self.switchContent(_:)), for: .touchUpInside) } } func switchContent(_ sender: UIButton) { let raw = sender.tag contentType = ContentType(rawValue: raw)! tableView.reloadData() } func configure(userId: Int) { self.userId = userId } func loadData() { MeowAPIProvider.shared .request(.herMoments(id: self.userId)) .mapTo(arrayOf: Moment.self) .subscribe(onNext: { [weak self] items in self?.moments.append(contentsOf: items) self?.tableView.reloadData() }) .addDisposableTo(disposeBag) MeowAPIProvider.shared.request(.herArticles(id: self.userId)) .mapTo(arrayOf: ArticleSummary.self) .subscribe(onNext: { [weak self] items in self?.articles.append(contentsOf: items) self?.tableView.reloadData() }) .addDisposableTo(disposeBag) let observableQuestions = MeowAPIProvider.shared.request(.herQuestions(id: userId)).mapTo(arrayOf: QuestionSummary.self) MeowAPIProvider.shared .request(.herAnswers(id: userId)) .mapTo(arrayOf: AnswerSummary.self) .flatMap{[weak self] items -> Observable<[QuestionSummary]> in for item in items { self?.questionAnswers.append(item) } return observableQuestions } .subscribe(onNext: { [weak self] items in for item in items { self?.questionAnswers.append(item) } self?.tableView.reloadData() }) .addDisposableTo(disposeBag) MeowAPIProvider.shared.request(.herProfile(id: userId)).mapTo(type: Profile.self).subscribe(onNext: { [weak self] profile in self?.profile = profile self?.tableView.reloadData() }).addDisposableTo(disposeBag) MeowAPIProvider.shared.request(.isFollowingUser(id: userId)) .subscribe(onNext: { [weak self] json in self?.isFollowing = (json as! JSON)["following"].bool! self?.tableView.reloadData() }).addDisposableTo(disposeBag) } func isCurrentContentType(_ type: ContentType) -> Bool { return type == self.contentType } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { guard indexPath.section == 2 else { return } switch contentType { case .article : let article = articles[indexPath.row] let vc = R.storyboard.articlePage.articleDetailViewController()! vc.configure(id: article.id, type: .article) navigationController?.pushViewController(vc, animated: true) case .questionAnswer: let item = questionAnswers[indexPath.row] if item.type == .question { let vc = R.storyboard.questionAnswerPage.questionDetailViewController()! vc.configure(questionId: item.id) navigationController?.pushViewController(vc, animated: true) } else { ArticleDetailViewController.show(item, from: self) } default: break } } override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? { if indexPath.section == 0 { return nil } return indexPath } } extension UserProfileViewController: UserProfileCellDelegate { func didTapFollowButton(_ sender: UIButton) { if isFollowing { MeowAPIProvider.shared .request(.unfollowUser(id: userId)) .subscribe(onNext: { [weak self] _ in self?.isFollowing = false self?.tableView.reloadData() }).addDisposableTo(disposeBag) } else { MeowAPIProvider.shared .request(.followUser(id: userId)) .subscribe(onNext: { [weak self] _ in self?.isFollowing = true self?.tableView.reloadData() }) .addDisposableTo(disposeBag) } } func didTapSendMessageButton(_ sender: UIButton) { guard let profile = profile else { return } let clientId = "\(profile.userId!)" ChatManager.openConversationViewController(withPeerId: clientId, from: self.navigationController!) } }
apache-2.0
aa6ecd81ebfec0c290508b0e15308a32
34.580392
128
0.587678
5.400595
false
false
false
false
zisko/swift
benchmark/single-source/BinaryFloatingPointConversionFromBinaryInteger.swift
1
5292
//===--- BinaryFloatingPointConversionFromBinaryInteger.swift -------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // This test checks performance of generic binary floating-point conversion from // a binary integer. import Foundation import TestsUtils public let BinaryFloatingPointConversionFromBinaryInteger = BenchmarkInfo( name: "BinaryFloatingPointConversionFromBinaryInteger", runFunction: run_BinaryFloatingPointConversionFromBinaryInteger, tags: [.validation, .algorithm] ) struct MockBinaryInteger<T : BinaryInteger> { var _value: T init(_ value: T) { _value = value } } extension MockBinaryInteger : CustomStringConvertible { var description: String { return _value.description } } extension MockBinaryInteger : ExpressibleByIntegerLiteral { init(integerLiteral value: T.IntegerLiteralType) { _value = T(integerLiteral: value) } } extension MockBinaryInteger : Comparable { static func < (lhs: MockBinaryInteger<T>, rhs: MockBinaryInteger<T>) -> Bool { return lhs._value < rhs._value } static func == ( lhs: MockBinaryInteger<T>, rhs: MockBinaryInteger<T> ) -> Bool { return lhs._value == rhs._value } } extension MockBinaryInteger : Hashable { var hashValue: Int { return _value.hashValue } } extension MockBinaryInteger : BinaryInteger { static var isSigned: Bool { return T.isSigned } init<Source>(_ source: Source) where Source : BinaryFloatingPoint { _value = T(source) } init?<Source>(exactly source: Source) where Source : BinaryFloatingPoint { guard let result = T(exactly: source) else { return nil } _value = result } init<Source>(_ source: Source) where Source : BinaryInteger { _value = T(source) } init?<Source>(exactly source: Source) where Source : BinaryInteger { guard let result = T(exactly: source) else { return nil } _value = result } init<Source>(truncatingIfNeeded source: Source) where Source : BinaryInteger { _value = T(truncatingIfNeeded: source) } init<Source>(clamping source: Source) where Source : BinaryInteger { _value = T(clamping: source) } var magnitude: MockBinaryInteger<T.Magnitude> { return MockBinaryInteger<T.Magnitude>(_value.magnitude) } var words: T.Words { return _value.words } var bitWidth: Int { return _value.bitWidth } var trailingZeroBitCount: Int { return _value.trailingZeroBitCount } static func + ( lhs: MockBinaryInteger<T>, rhs: MockBinaryInteger<T> ) -> MockBinaryInteger<T> { return MockBinaryInteger(lhs._value + rhs._value) } static func += (lhs: inout MockBinaryInteger<T>, rhs: MockBinaryInteger<T>) { lhs._value += rhs._value } static func - ( lhs: MockBinaryInteger<T>, rhs: MockBinaryInteger<T> ) -> MockBinaryInteger<T> { return MockBinaryInteger(lhs._value - rhs._value) } static func -= (lhs: inout MockBinaryInteger<T>, rhs: MockBinaryInteger<T>) { lhs._value -= rhs._value } static func * ( lhs: MockBinaryInteger<T>, rhs: MockBinaryInteger<T> ) -> MockBinaryInteger<T> { return MockBinaryInteger(lhs._value * rhs._value) } static func *= (lhs: inout MockBinaryInteger<T>, rhs: MockBinaryInteger<T>) { lhs._value *= rhs._value } static func / ( lhs: MockBinaryInteger<T>, rhs: MockBinaryInteger<T> ) -> MockBinaryInteger<T> { return MockBinaryInteger(lhs._value / rhs._value) } static func /= (lhs: inout MockBinaryInteger<T>, rhs: MockBinaryInteger<T>) { lhs._value /= rhs._value } static func % ( lhs: MockBinaryInteger<T>, rhs: MockBinaryInteger<T> ) -> MockBinaryInteger<T> { return MockBinaryInteger(lhs._value % rhs._value) } static func %= (lhs: inout MockBinaryInteger<T>, rhs: MockBinaryInteger<T>) { lhs._value %= rhs._value } static func &= (lhs: inout MockBinaryInteger<T>, rhs: MockBinaryInteger<T>) { lhs._value &= rhs._value } static func |= (lhs: inout MockBinaryInteger<T>, rhs: MockBinaryInteger<T>) { lhs._value |= rhs._value } static func ^= (lhs: inout MockBinaryInteger<T>, rhs: MockBinaryInteger<T>) { lhs._value ^= rhs._value } static prefix func ~ (x: MockBinaryInteger<T>) -> MockBinaryInteger<T> { return MockBinaryInteger(~x._value) } static func >>= <RHS>( lhs: inout MockBinaryInteger<T>, rhs: RHS ) where RHS : BinaryInteger { lhs._value >>= rhs } static func <<= <RHS>( lhs: inout MockBinaryInteger<T>, rhs: RHS ) where RHS : BinaryInteger { lhs._value <<= rhs } } @inline(never) public func run_BinaryFloatingPointConversionFromBinaryInteger(_ N: Int) { var xs = [Double]() xs.reserveCapacity(N) for _ in 1...N { var x = 0 as Double for i in 0..<2000 { x += Double._convert(from: MockBinaryInteger(getInt(i))).value } xs.append(x) } CheckResults(xs[getInt(0)] == 1999000) }
apache-2.0
d24f33661a17854c308beb131427e477
25.328358
80
0.668745
4.061397
false
false
false
false
higegiraffe/detectFaces4
detectFaces4/ViewController.swift
1
5652
// // ViewController.swift // detectFaces4 // // Created by yuki on 2015/07/30. // Copyright (c) 2015年 higegiraffe. All rights reserved. // import UIKit import AVFoundation //var imageView: UIImageView! class ViewController: UIViewController, AVCaptureVideoDataOutputSampleBufferDelegate { @IBOutlet weak var imageView: UIImageView! // セッション var mySession : AVCaptureSession! // カメラデバイス var myDevice : AVCaptureDevice! // 出力先 var myOutput : AVCaptureVideoDataOutput! override func viewDidLoad() { super.viewDidLoad() //画面の生成 // initDisplay() // カメラを準備 if initCamera() { // 撮影開始 mySession.startRunning() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // 画面の生成処理 func initDisplay() { //スクリーンの幅 let screenWidth = UIScreen.mainScreen().bounds.size.width; //スクリーンの高さ let screenHeight = UIScreen.mainScreen().bounds.size.height; imageView = UIImageView(frame: CGRectMake(0.0, 0.0, screenWidth, screenHeight)) } */ // カメラの準備処理 func initCamera() -> Bool { // セッションの作成. mySession = AVCaptureSession() // 解像度の指定. mySession.sessionPreset = AVCaptureSessionPresetMedium // デバイス一覧の取得. let devices = AVCaptureDevice.devices() // フロントカメラをmyDeviceに格納. for device in devices { if(device.position == AVCaptureDevicePosition.Front){ myDevice = device as! AVCaptureDevice } } if myDevice == nil { return false } // フロントカメラからVideoInputを取得. let myInput = AVCaptureDeviceInput.deviceInputWithDevice(myDevice, error: nil) as! AVCaptureDeviceInput // セッションに追加. if mySession.canAddInput(myInput) { mySession.addInput(myInput) } else { return false } // 出力先を設定 myOutput = AVCaptureVideoDataOutput() myOutput.videoSettings = [ kCVPixelBufferPixelFormatTypeKey: kCVPixelFormatType_32BGRA ] // FPSを設定 var lockError: NSError? if myDevice.lockForConfiguration(&lockError) { if let error = lockError { println("lock error: \(error.localizedDescription)") return false } else { myDevice.activeVideoMinFrameDuration = CMTimeMake(1, 15) myDevice.unlockForConfiguration() } } // デリゲートを設定 let queue: dispatch_queue_t = dispatch_queue_create("myqueue", nil) myOutput.setSampleBufferDelegate(self, queue: queue) // 遅れてきたフレームは無視する myOutput.alwaysDiscardsLateVideoFrames = true // セッションに追加. if mySession.canAddOutput(myOutput) { mySession.addOutput(myOutput) } else { return false } // カメラの向きを合わせる for connection in myOutput.connections { if let conn = connection as? AVCaptureConnection { if conn.supportsVideoOrientation { conn.videoOrientation = AVCaptureVideoOrientation.Portrait } } } return true } // 毎フレーム実行される処理 func captureOutput(captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, fromConnection connection: AVCaptureConnection!) { var q_global: dispatch_queue_t = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) var q_main: dispatch_queue_t = dispatch_get_main_queue() dispatch_async(q_global, { dispatch_async(q_main, { // UIImageへ変換して表示させる self.imageView.image = CameraUtil.imageFromSampleBuffer(sampleBuffer) return }) // UIImageへ変換 // let image = CameraUtil.imageFromSampleBuffer(sampleBuffer) // 顔認識 let detectFace = detectFaces.recognizeFace(self.imageView.image!) dispatch_async(q_main, { // 検出された顔のデータをCIFaceFeatureで処理. var feature : CIFaceFeature = CIFaceFeature() for feature in detectFace.faces { // 座標変換. let faceRect : CGRect = CGRectApplyAffineTransform(feature.bounds, detectFace.transform) // 画像の顔の周りを線で囲うUIViewを生成. var faceOutline = UIView(frame: faceRect) faceOutline.layer.borderWidth = 1 faceOutline.layer.borderColor = UIColor.redColor().CGColor self.imageView.addSubview(faceOutline) } return }) }) } }
mit
c72f4b610f324655f31542db8458dc1f
27.888889
159
0.548654
5.058366
false
false
false
false
EZ-NET/ESSwim
Sources/Tree/TreeFunction.swift
1
11635
// // TreeFunction.swift // ESSwim // // Created by 熊谷 友宏 on H26/12/29. // // // MARK: - Tree // MARK: Tree Operation /** Returns a Boolean value that indicates whether the tree have a root node. :return: True if the tree have a root node, otherwise false. */ public func hasRootNode<Tree:TreeType>(tree:Tree) -> Bool { return tree.rootNode != nil } /** Get Total number of nodes in the tree. */ public func nodeSize<Tree:TreeType>(tree:Tree) -> Int { return tree.rootNode.map { Swim.nodeSize($0) } ?? 0 } /** Get node height of the tree. */ public func nodeHeight<Tree:TreeType>(tree:Tree) -> Int { return tree.rootNode.map { Swim.nodeHeight($0) } ?? 0 } // MARK: SearchableTreeTree /** Find a node having `value` in `domain`. */ public func search<Tree:TreeType where Tree:Swim.SearchableNodeType>(domain:Tree, value:Tree.SearchValue) -> Tree.SearchResult { return domain.search(value) } // MARK: - TreeNodeType // MARK: Node Operation public func firstChild<Node:Swim.TreeNodeType>(node:Node) -> Node? { return node.childNodes.first } public func lastChild<Node:Swim.TreeNodeType>(node:Node) -> Node? { return node.childNodes.last } // MARK: State /** Get Total number of nodes in the node, includes the node. */ public func nodeSize<Node:Swim.TreeNodeType>(node:Node) -> Int { return node.childNodes.reduce(1) { $0 + Swim.nodeSize($1) } } /** Get height of the node. Height means maximum of the edge count from the node to a leaf node. */ public func nodeHeight<Node:Swim.TreeNodeType>(node:Node) -> Int { let childNodes = node.childNodes if childNodes.isEmpty { return 0 } else { let childHeights = childNodes.map { nodeHeight($0) } return 1 + (childHeights.maxElement() ?? 0) } } /** Get depth of the node. Depth means maximum of the edge count from the node to the root node. */ public func nodeDepth<Node:Swim.TreeNodeType>(node:Node) -> Int { return Swim.isRootNode(node) ? 0 : 1 + Swim.nodeDepth(node.parentNode!) } // MARK: Condition /** Returns a Boolean value that indicates whether the node is a root node of a tree. :return: True if the node has no parent node, otherwise false. **/ public func isRootNode<Node:Swim.TreeNodeType>(node:Node) -> Bool { return node.parentNode == nil } /** Returns a Boolean value that indicates whether the node is a leaf node of a tree. :return: True if the node has no child nodes, otherwise false. */ public func isLeafNode<Node:Swim.TreeNodeType>(node:Node) -> Bool { return !node.hasChildNodes } /** Returns a Boolean value that indicates whether the node is a internal node of a tree. :return: True if the node has rootNode and child nodes, otherwise false. */ public func isInternalNode<Node:Swim.TreeNodeType>(node:Node) -> Bool { return !(Swim.isRootNode(node) || Swim.isLeafNode(node)) } /** Returns a Boolean value that indicates whether the node is a external node of a tree. :return: True if the node has rootNode and no child nodes, otherwise false. */ public func isExternalNode<Node:Swim.TreeNodeType>(node:Node) -> Bool { return !(Swim.isRootNode(node) || node.hasChildNodes) } /** Returns a Boolean value that indicates whether the node has no parent node and has no child nodes. */ public func isAloneNode<Node:Swim.TreeNodeType>(node:Node) -> Bool { return node.parentNode == nil && node.degree == 0 } /** A node reachable by repeated proceeding from parent to child. :return: True if `node` was found in all child nodes of `baseNode`. */ public func isDescendant<Node:Swim.TreeNodeType>(node:Node, of baseNode:Node) -> Bool { if node == baseNode { return false } else { // Abort traverse if node found. let continueIfNodeNotFound = Swim.alternative(trueValue: Swim.ContinuousState.Continue, falseValue: Swim.ContinuousState.Abort, predicate: notEqual(node)) return Swim.traverseByPreOrder(baseNode, predicate: continueIfNodeNotFound).aborted } } /** A node reachable by repeated proceeding from child to parent. :return: True if `node` was found in all parent nodes of `baseNode`. */ public func isAncestor<Node:Swim.TreeNodeType>(node:Node, of baseNode:Node) -> Bool { if node == baseNode { return false } else { if let parentNode = baseNode.parentNode { return parentNode == node ? true : Swim.isAncestor(node, of:parentNode) } else { return false } } } // MARK: Node Traverse /** Traverse nodes in the node by Pre-Order. Pre-Order: the node -> left node -> ... -> right node :return: False if traverse abort, otherwise true. */ public func traverseByPreOrder<Node:Swim.TreeNodeType>(node:Node, predicate:(Node) -> Swim.ContinuousState) -> Swim.ProcessingState { return node.traverseByPreOrder(predicate) } /** Traverse nodes in the node by Post-Order. Post-Order: left node -> ... -> right node -> the node :return: False if traverse abort, otherwise true. */ public func traverseByPostOrder<Node:Swim.TreeNodeType>(node:Node, predicate:(Node) -> Swim.ContinuousState) -> Swim.ProcessingState { return node.traverseByPostOrder(predicate) } /** Traverse nodes in the node by Level-Order. Level-Order: the node -> next level nodes -> ... :return: False if traverse abort, otherwise true. */ public func traverseByLevelOrder<Node:Swim.TreeNodeType>(node:Node, predicate:(Node) -> Swim.ContinuousState) -> Swim.ProcessingState { return node.traverseByLevelOrder(predicate) } /** Return an `Array` containing the results of calling by Pre-Order. `transform(x)` on each element `x` of `node` */ public func mapByPreOrder<Node:Swim.TreeNodeType,Result>(node:Node, transform:(Node) -> Result) -> [Result] { return node.mapBy(Swim.traverseByPreOrder)(transform: transform) } /** Return an `Array` containing the results of calling by Post-Order. `transform(x)` on each element `x` of `node` */ public func mapByPostOrder<Node:Swim.TreeNodeType,Result>(node:Node, transform:(Node) -> Result) -> [Result] { return node.mapBy(Swim.traverseByPostOrder)(transform: transform) } /** Return an `Array` containing the results of calling by Level-Order. `transform(x)` on each element `x` of `node` */ public func mapByLevelOrder<Node:Swim.TreeNodeType,Result>(node:Node, transform:(Node) -> Result) -> [Result] { return node.mapBy(Swim.traverseByLevelOrder)(transform: transform) } /** Return an `Array` containing the results of calling by Pre-Order. `transform(x)` on each element `x` of `node` */ public func filterByPreOrder<Node:Swim.TreeNodeType>(node:Node, includeElement:(Node) -> Bool) -> [Node] { return node.filterBy(Swim.traverseByPreOrder)(includeElement: includeElement) } /** Return an `Array` containing the results of calling by Post-Order. `transform(x)` on each element `x` of `node` */ public func filterByPostOrder<Node:Swim.TreeNodeType>(node:Node, includeElement:(Node) -> Bool) -> [Node] { return node.filterBy(Swim.traverseByPostOrder)(includeElement: includeElement) } /** Return an `Array` containing the results of calling by Level-Order. `transform(x)` on each element `x` of `node` */ public func filterByLevelOrder<Node:Swim.TreeNodeType>(node:Node, includeElement:(Node) -> Bool) -> [Node] { return node.filterBy(Swim.traverseByLevelOrder)(includeElement: includeElement) } /** Return the result of repeatedly calling `combine` with an accumulated value initialized to `initial` and each element of `node`, by Pre-Order. */ public func reduceByPreOrder<Node:Swim.TreeNodeType,Value>(node:Node, _ initial:Value, combine:(Value, Node) -> Value) -> Value { return node.reduceBy(Swim.traverseByPreOrder)(initial: initial, combine: combine) } /** Return the result of repeatedly calling `combine` with an accumulated value initialized to `initial` and each element of `node`, by Post-Order. */ public func reduceByPostOrder<Node:Swim.TreeNodeType,Value>(node:Node, _ initial:Value, combine:(Value, Node) -> Value) -> Value { return node.reduceBy(Swim.traverseByPostOrder)(initial: initial, combine: combine) } /** Return the result of repeatedly calling `combine` with an accumulated value initialized to `initial` and each element of `node`, by Level-Order. */ public func reduceByLevelOrder<Node:Swim.TreeNodeType,Value>(node:Node, _ initial:Value, combine:(Value, Node) -> Value) -> Value { return node.reduceBy(Swim.traverseByLevelOrder)(initial: initial, combine: combine) } // MARK: - BinaryTreeNodeType // MARK: Node Traverse /** Traverse nodes in the node by In-Order. In-Order: left node -> the node -> right node :return: False if traverse abort, otherwise true. */ public func traverseByInOrder<Node:Swim.BinaryTreeNodeType>(node:Node, predicate:(Node) -> Swim.ContinuousState) -> Swim.ProcessingState { return node.traverseByInOrder(predicate) } /** Return an `Array` containing the results of calling by In-Order. `transform(x)` on each element `x` of `node` */ public func mapByInOrder<Node:Swim.BinaryTreeNodeType,Result>(node:Node, transform:(Node) -> Result) -> [Result] { return node.mapBy(traverseByInOrder)(transform: transform) } /** Return an `Array` containing the results of calling by In-Order. `transform(x)` on each element `x` of `node` */ public func filterByInOrder<Node:Swim.BinaryTreeNodeType>(node:Node, includeElement:(Node) -> Bool) -> [Node] { return node.filterBy(traverseByInOrder)(includeElement: includeElement) } /** Return the result of repeatedly calling `combine` with an accumulated value initialized to `initial` and each element of `node`, by In-Order. */ public func reduceByInOrder<Node:Swim.BinaryTreeNodeType, Value>(node:Node, _ initial:Value, combine:(Value, Node) -> Value) -> Value { return node.reduceBy(traverseByInOrder)(initial: initial, combine: combine) } // MARK: - SiblingSearchableNodeType // MARK: Node Operation /** Get the node's first sibling node. :return: The first node of the node's sibling nodes. Nil if the node has no parent node. */ public func firstSibling<Node:Swim.SiblingSearchableNodeType>(node:Node) -> Node? { return node.parentNode.flatMap { firstChild($0) } } /** Get the node's last sibling node. :return: The last node of the node's sibling nodes. Nil if the node has no parent node. */ public func lastSibling<Node:Swim.SiblingSearchableNodeType>(node:Node) -> Node? { return node.parentNode.flatMap { lastChild($0) } } /** Get the node's previous sibling node. :return: Node if the node has previous sibling node, otherwise nil. The node has no parent node, return nil. */ public func previousSibling<Node:Swim.TreeNodeType where Node:Swim.SiblingSearchableNodeType, Node.Generator.Element == Node>(node:Node) -> Node? { let getPreviousSiblingNode = { (parentNode:Node) -> Node? in let childIndex = parentNode.findElement(node)!.index let childNodes = parentNode.childNodes if let previousIndex = Swim.advance(childIndex, -1, childNodes) { return childNodes[previousIndex] } else { return nil } } return node.parentNode.flatMap { getPreviousSiblingNode($0) } } /** Get the node's next sibling node. :return: Node if the node has next sibling node, otherwise nil. The node has no parent node, return nil. */ public func nextSibling<Node:Swim.SiblingSearchableNodeType where Node.Generator.Element == Node>(node:Node) -> Node? { let getNextSiblingNode = { (parentNode:Node) -> Node? in let childIndex = parentNode.findElement(node)!.index let childNodes = parentNode.childNodes if let nextIndex = Swim.advance(childIndex, 1, childNodes) { return childNodes[nextIndex] } else { return nil } } return node.parentNode.flatMap { getNextSiblingNode($0) } }
mit
781118a7cc450367cc73bb521b6aca34
26.815789
156
0.729251
3.534043
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/Platform/Sources/PlatformUIKit/Views/TextField/TextFieldView.swift
1
13919
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import PlatformKit import RxCocoa import RxRelay import RxSwift import UIKit /// A styled text field component with validation and password expression scoring public class TextFieldView: UIView { private static let defaultTopInset: CGFloat = 8 private static let defaultBottomInset: CGFloat = 0 /// Determines the top insert: title label to superview public var topInset: CGFloat = TextFieldView.defaultTopInset { didSet { topInsetConstraint.constant = topInset layoutIfNeeded() } } public var bottomInset: CGFloat = TextFieldView.defaultBottomInset { didSet { bottomInsetConstraint.constant = bottomInset layoutIfNeeded() } } public var isEmpty: Bool { textField.text?.isEmpty ?? true } /// Equals to the expression: `textField.text ?? ""` var text: String { textField.text ?? "" } /// Returns a boolean indicating whether the field is currently focused var isTextFieldFocused: Bool { textField.isFirstResponder } // MARK: - UI Properties let accessoryView = UIView() let textFieldBackgroundView = UIView() private let button = UIButton() private let textField = UITextField() private let titleLabel = UILabel() private let subtitleLabel = UILabel() private var bottomInsetConstraint: NSLayoutConstraint! private var topInsetConstraint: NSLayoutConstraint! private var subtitleLabelHeightConstraint: NSLayoutConstraint! private var subtitleLabelTopConstraint: NSLayoutConstraint! private var titleLabelHeightConstraint: NSLayoutConstraint! private var keyboardInteractionController: KeyboardInteractionController! /// Scroll view container. /// To being the text field into focus when it becomes first responder private weak var scrollView: UIScrollView? // Mutable since we would like to make the text field // compatible with constructs like table/collection views private var disposeBag = DisposeBag() // MARK: - Injected private var viewModel: TextFieldViewModel! // MARK: - Setup override public init(frame: CGRect) { super.init(frame: frame) setup() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } // MARK: - Internal API /// Should be called once upon instantiation func setup() { addSubview(titleLabel) addSubview(subtitleLabel) addSubview(textFieldBackgroundView) addSubview(accessoryView) addSubview(button) addSubview(textField) textField.delegate = self titleLabelHeightConstraint = titleLabel.layout(dimension: .height, to: 24) titleLabel.layoutToSuperview(axis: .horizontal) topInsetConstraint = titleLabel.layoutToSuperview(.top, offset: Self.defaultTopInset) titleLabel.layout( edge: .bottom, to: .top, of: textFieldBackgroundView, priority: .penultimateHigh ) textFieldBackgroundView.layoutToSuperview(axis: .horizontal) textFieldBackgroundView.layout(dimension: .height, to: 48) subtitleLabelHeightConstraint = subtitleLabel.layout(dimension: .height, to: 0) subtitleLabel.layoutToSuperview(axis: .horizontal) subtitleLabelTopConstraint = subtitleLabel.layout( edge: .top, to: .bottom, of: textFieldBackgroundView, offset: 0, priority: .penultimateHigh ) bottomInsetConstraint = bottomAnchor .constraint( equalTo: subtitleLabel.bottomAnchor, constant: Self.defaultBottomInset ) textField.layout(edges: .leading, to: textFieldBackgroundView, offset: 16) textField.layout(edges: .bottom, .top, to: textFieldBackgroundView) textField.layout(edge: .trailing, to: .leading, of: accessoryView) textFieldBackgroundView.layout(edges: .trailing, to: accessoryView) textFieldBackgroundView.layout(edges: .centerY, to: accessoryView) accessoryView.layout(dimension: .height, to: 30, priority: .init(rawValue: 251)) accessoryView.layout(dimension: .width, to: 0.5, priority: .defaultHigh) textField.textAlignment = .left titleLabel.font = .main(.medium, 12) titleLabel.textColor = .destructive titleLabel.verticalContentHuggingPriority = .required titleLabel.verticalContentCompressionResistancePriority = .required subtitleLabel.font = .main(.medium, 12) subtitleLabel.textColor = .destructive subtitleLabel.verticalContentHuggingPriority = .required subtitleLabel.verticalContentCompressionResistancePriority = .required subtitleLabel.numberOfLines = 0 /// Cleanup the sensitive data if necessary NotificationCenter.when(UIApplication.didEnterBackgroundNotification) { [weak textField, weak viewModel] _ in guard let textField = textField else { return } guard let viewModel = viewModel else { return } if viewModel.type.requiresCleanupOnBackgroundState { textField.text = "" viewModel.textFieldEdited(with: "") } } } // MARK: - API /// Must be called by specialized subclasses public func setup( viewModel: TextFieldViewModel, keyboardInteractionController: KeyboardInteractionController, scrollView: UIScrollView? = nil ) { disposeBag = DisposeBag() self.scrollView = scrollView self.keyboardInteractionController = keyboardInteractionController self.viewModel = viewModel /// Set the accessibility property textField.accessibility = viewModel.accessibility textField.returnKeyType = viewModel.returnKeyType textField.inputAccessoryView = keyboardInteractionController.toolbar textField.autocorrectionType = viewModel.type.autocorrectionType textField.autocapitalizationType = viewModel.type.autocapitalizationType textField.font = viewModel.textFont textField.spellCheckingType = .no textField.placeholder = nil titleLabel.font = viewModel.titleFont subtitleLabel.font = viewModel.subtitleFont textFieldBackgroundView.clipsToBounds = true textFieldBackgroundView.backgroundColor = .clear textFieldBackgroundView.layer.cornerRadius = 8 textFieldBackgroundView.layer.borderWidth = 1 /// Bind `accessoryContentType` viewModel.accessoryContentType .bindAndCatch(to: rx.accessoryContentType) .disposed(by: disposeBag) /// Bind `isSecure` viewModel.isSecure .drive(textField.rx.isSecureTextEntry) .disposed(by: disposeBag) /// Bind `contentType` viewModel.contentType .drive(textField.rx.contentType) .disposed(by: disposeBag) /// Bind `keyboardType` viewModel.keyboardType .drive(textField.rx.keyboardType) .disposed(by: disposeBag) // Bind `placeholder` viewModel.placeholder .drive(textField.rx.placeholderAttributedText) .disposed(by: disposeBag) // Bind `textColor` viewModel.textColor .drive(textField.rx.textColor) .disposed(by: disposeBag) // Take only the first value emitted by `text` viewModel.text .asObservable() .take(1) .bindAndCatch(to: textField.rx.text) .disposed(by: disposeBag) // Take all values emitted by `originalText` viewModel.originalText .compactMap { $0 } .bindAndCatch(to: textField.rx.text) .disposed(by: disposeBag) viewModel.mode .drive(rx.mode) .disposed(by: disposeBag) viewModel.isEnabled .bindAndCatch(to: textField.rx.isEnabled) .disposed(by: disposeBag) button.rx.tap .throttle( .milliseconds(200), latest: false, scheduler: ConcurrentDispatchQueueScheduler(qos: .background) ) .observe(on: MainScheduler.instance) .bindAndCatch(to: viewModel.tapRelay) .disposed(by: disposeBag) if viewModel.type == .newPassword || viewModel.type == .confirmNewPassword { textField.rx.text.orEmpty .bindAndCatch(weak: self) { [weak viewModel] (self, text) in guard !self.textField.isFirstResponder else { return } viewModel?.textFieldEdited(with: text) } .disposed(by: disposeBag) } viewModel.focus .map(\.isOn) .drive(onNext: { [weak self] shouldGainFocus in guard let self = self else { return } if shouldGainFocus { self.textFieldGainedFocus() } else { self.textField.resignFirstResponder() } }) .disposed(by: disposeBag) } private func textFieldGainedFocus() { if let scrollView = scrollView { let frameInScrollView = convert(frame, to: scrollView) scrollView.scrollRectToVisible(frameInScrollView, animated: true) } } fileprivate func set(mode: TextFieldViewModel.Mode) { UIView.transition( with: titleLabel, duration: 0.15, options: [.beginFromCurrentState, .transitionCrossDissolve], animations: { self.titleLabel.text = mode.title self.titleLabel.textColor = mode.titleColor self.titleLabelHeightConstraint.constant = mode.title.isEmpty ? 0 : 24 self.subtitleLabel.text = mode.subtitle self.subtitleLabel.textColor = mode.titleColor self.subtitleLabelHeightConstraint.isActive = mode.subtitle.isEmpty self.subtitleLabelTopConstraint.constant = mode.subtitle.isEmpty ? 0 : 4 self.textFieldBackgroundView.layer.borderColor = mode.borderColor.cgColor self.textField.tintColor = mode.cursorColor }, completion: nil ) } fileprivate func set(accessoryContentType: TextFieldViewModel.AccessoryContentType) { let resetAccessoryView = { [weak self] in self?.button.removeFromSuperview() self?.accessoryView.subviews.forEach { $0.removeFromSuperview() } } switch accessoryContentType { case .empty: resetAccessoryView() case .badgeImageView(let viewModel): if let badgeImageView = accessoryView.subviews.first as? BadgeImageView { badgeImageView.viewModel = viewModel } else { resetAccessoryView() let badgeImageView = BadgeImageView() badgeImageView.viewModel = viewModel accessoryView.addSubview(badgeImageView) accessoryView.addSubview(button) button.layoutToSuperview(.leading) button.layoutToSuperview(.trailing, offset: -8) button.layoutToSuperview(axis: .vertical) badgeImageView.layoutToSuperview(.leading) badgeImageView.layoutToSuperview(.trailing, offset: -8) badgeImageView.layoutToSuperview(axis: .vertical) } case .badgeLabel(let viewModel): if let badgeView = accessoryView.subviews.first as? BadgeView { badgeView.viewModel = viewModel } else { resetAccessoryView() let badgeView = BadgeView() badgeView.viewModel = viewModel accessoryView.addSubview(badgeView) badgeView.layoutToSuperview(.leading) badgeView.layoutToSuperview(.trailing, offset: -16) badgeView.layoutToSuperview(axis: .vertical) } } } } // MARK: UITextFieldDelegate extension TextFieldView: UITextFieldDelegate { public func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool { viewModel.textFieldShouldBeginEditing() } public func textField( _ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String ) -> Bool { let text = textField.text ?? "" let input = (text as NSString).replacingCharacters(in: range, with: string) let operation: TextInputOperation = string.isEmpty ? .deletion : .addition let result = viewModel.editIfNecessary(input, operation: operation) switch result { case .formatted(to: let text): textField.text = text return false case .original: return true } } public func textFieldShouldReturn(_ textField: UITextField) -> Bool { viewModel.textFieldShouldReturn() } public func textFieldDidEndEditing(_ textField: UITextField) { viewModel.textFieldDidEndEditing() } } // MARK: - Rx extension Reactive where Base: TextFieldView { fileprivate var accessoryContentType: Binder<TextFieldViewModel.AccessoryContentType> { Binder(base) { view, contentType in view.set(accessoryContentType: contentType) } } /// Binder for the error handling fileprivate var mode: Binder<TextFieldViewModel.Mode> { Binder(base) { view, mode in view.set(mode: mode) } } }
lgpl-3.0
59cfe4eb7e37db926ccb6eba70594ac6
34.324873
117
0.634718
5.585072
false
false
false
false
kstaring/swift
validation-test/compiler_crashers_fixed/01751-swift-type-walk.swift
11
676
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse struct Q<f = { protocol a { class A { func b: Sequence where H) -> Int -> { } } func c<T: c] = f: Collection where I.C) { protocol A { } func call() { protocol d where k) { class A<h == Swift.B<S { class c in x } typealias d = { } } } } } self, (f<1 { 0] = g<T>(" typealias B.init(a)
apache-2.0
1a7b26fa9497c0f3a03005bdf5e6fe4b
21.533333
78
0.671598
3.045045
false
false
false
false
cubixlabs/GIST-Framework
GISTFramework/Classes/Controls/AnimatedTextInput/AnimatedTextInputStyle.swift
1
4920
import UIKit public protocol AnimatedTextInputStyle { var sizeForIPad:Bool? { get } var activeColor: String? { get } var inactiveColor: String? { get } var lineInactiveColor: String? { get } var errorColor: String? { get } var textFontName: String? { get } var textFontStyle: String? { get } var textFontColor: String? { get } var titleFontName: String? { get } var titleFontStyle: String? { get } var titleFontColor: String? { get } var counterLabelFontName: String? { get } var counterLabelFontStyle: String? { get } var placeholderMinFontStyle: String? { get } var leftMargin: CGFloat? { get } var topMargin: CGFloat? { get } var rightMargin: CGFloat? { get } var bottomMargin: CGFloat? { get } var yHintPositionOffset: CGFloat? { get } var yPlaceholderPositionOffset: CGFloat? { get } var textAttributes: [String: Any]? { get } /* //TO DO LATER var placeholderInactiveColor: UIColor { get } var lineActiveColor: UIColor { get } var lineHeight: CGFloat { get } var textInputFont: UIFont { get } var textInputFontColor: UIColor { get } var placeholderMinFontSize: CGFloat { get } var counterLabelFont: UIFont? { get } */ } struct InternalAnimatedTextInputStyle { let sizeForIPad:Bool; let activeColor: UIColor; let inactiveColor: UIColor; let lineInactiveColor: UIColor; let errorColor: UIColor; let textInputFont: UIFont; let textInputFontColor: UIColor; let titleFont: UIFont; let titleFontColor: UIColor; let placeholderMinFontSize: CGFloat; let counterLabelFont: UIFont; let leftMargin: CGFloat; let topMargin: CGFloat; let rightMargin: CGFloat; let bottomMargin: CGFloat; let yHintPositionOffset: CGFloat; let yPlaceholderPositionOffset: CGFloat; let textAttributes: [String: Any]?; init(_ style:AnimatedTextInputStyle?) { sizeForIPad = style?.sizeForIPad ?? GIST_CONFIG.sizeForIPad; activeColor = SyncedColors.color(forKey: style?.activeColor) ?? UIColor(red: 51.0/255.0, green: 175.0/255.0, blue: 236.0/255.0, alpha: 1.0); inactiveColor = SyncedColors.color(forKey: style?.inactiveColor) ?? UIColor(white: 0.80, alpha: 1); lineInactiveColor = SyncedColors.color(forKey: style?.lineInactiveColor) ?? UIColor.gray.withAlphaComponent(0.2); errorColor = SyncedColors.color(forKey: style?.errorColor) ?? UIColor.red; textInputFont = UIFont.font(style?.textFontName, fontStyle: style?.textFontStyle, sizedForIPad: sizeForIPad); titleFont = UIFont.font(style?.titleFontName ?? style?.textFontName, fontStyle: style?.titleFontStyle ?? style?.textFontStyle, sizedForIPad: sizeForIPad); textInputFontColor = SyncedColors.color(forKey: style?.textFontColor) ?? UIColor.black; titleFontColor = SyncedColors.color(forKey: style?.titleFontColor ?? style?.textFontColor) ?? UIColor.black; placeholderMinFontSize = GISTUtility.convertToRatio(CGFloat(SyncedFontStyles.style(forKey: style?.placeholderMinFontStyle ?? "small"))); counterLabelFont = UIFont.font(style?.counterLabelFontName, fontStyle: style?.counterLabelFontStyle, sizedForIPad: sizeForIPad); leftMargin = style?.leftMargin ?? 15; rightMargin = style?.rightMargin ?? 15; topMargin = GISTUtility.convertToRatio(style?.topMargin ?? 25); bottomMargin = GISTUtility.convertToRatio(style?.bottomMargin ?? 20); yHintPositionOffset = GISTUtility.convertToRatio(style?.yHintPositionOffset ?? 5); yPlaceholderPositionOffset = GISTUtility.convertToRatio(style?.yPlaceholderPositionOffset ?? 0); textAttributes = style?.textAttributes; } } // CLS End /* public struct AnimatedTextInputStyleBlue: AnimatedTextInputStyle { public let activeColor = UIColor(red: 51.0/255.0, green: 175.0/255.0, blue: 236.0/255.0, alpha: 1.0) public let inactiveColor = UIColor.gray.withAlphaComponent(0.5) public let lineInactiveColor = UIColor.gray.withAlphaComponent(0.2) public let errorColor = UIColor.red public let textInputFont = UIFont.systemFont(ofSize: 14) public let textInputFontColor = UIColor.black public let placeholderMinFontSize: CGFloat = 9 public let counterLabelFont: UIFont? = UIFont.systemFont(ofSize: 9) public let leftMargin: CGFloat = 25 public let topMargin: CGFloat = 20 public let rightMargin: CGFloat = 0 public let bottomMargin: CGFloat = 10 public let yHintPositionOffset: CGFloat = 7 public let yPlaceholderPositionOffset: CGFloat = 0 //Text attributes will override properties like textInputFont, textInputFontColor... public let textAttributes: [String: Any]? = nil public init() { } } */
agpl-3.0
89890b7f5a90f02f5a339afaf16650b4
38.677419
162
0.690854
4.572491
false
false
false
false
AdaptiveMe/adaptive-arp-darwin
adaptive-arp-rt/Source/Sources.Common/utils/GeolocationDelegateHelper.swift
1
8212
/* * =| ADAPTIVE RUNTIME PLATFORM |======================================================================================= * * (C) Copyright 2013-2014 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>. * * 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. * * Original author: * * * Carlos Lozano Diez * <http://github.com/carloslozano> * <http://twitter.com/adaptivecoder> * <mailto:[email protected]> * * Contributors: * * * Ferran Vila Conesa * <http://github.com/fnva> * <http://twitter.com/ferran_vila> * <mailto:[email protected]> * * ===================================================================================================================== */ import Foundation import CoreLocation import AdaptiveArpApi public class GeolocationDelegateHelper: NSObject, CLLocationManagerDelegate { /// Logging variable let logger: ILogging = AppRegistryBridge.sharedInstance.getLoggingBridge() let loggerTag: String = "GeolocationDelegateHelper" /// Geo location manager private let listener: IGeolocationListener! /// Location manager var locationManager: CLLocationManager! /** Class constructor :param: listener Geolocation listener :author: Ferran Vila Conesa :since: ARP1.0 */ init(listener: IGeolocationListener) { self.listener = listener } /** Starts the Location Manager :author: Ferran Vila Conesa :since: ARP1.0 */ func initLocationManager() { locationManager = CLLocationManager() locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest #if os(iOS) locationManager.requestAlwaysAuthorization() // The request type for geolocation is always #endif } /** This delegate method is launched when a update on the geolocation service is fired :param: manager Location Manager :param: locations Locations :author: Ferran Vila Conesa :since: ARP1.0 */ public func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let locationArray = locations as NSArray let locationObject = locationArray.lastObject as! CLLocation let coordinates = locationObject.coordinate let latitude:Double = coordinates.latitude let longitude:Double = coordinates.longitude let altitude:Double = locationObject.altitude let horizontalAccuracy:Float = Float(locationObject.horizontalAccuracy) let verticalAccuracy:Float = Float(locationObject.verticalAccuracy) let date = NSDate() let timestamp:Int64 = Int64(date.timeIntervalSince1970*1000) // Create a method Geolocation and send ot to the listener let geolocation: Geolocation = Geolocation(latitude: latitude, longitude: longitude, altitude: altitude, xDoP: horizontalAccuracy, yDoP: verticalAccuracy, timestamp: timestamp) logger.log(ILoggingLogLevel.Debug, category: loggerTag, message: "Updating the geolocation delegate at \(locationObject.timestamp)") // Fire the listener self.listener.onResult(geolocation) } /** This delegate method is lanched when an error is produced during the geolocation updates :param: manager Location manager :param: error Error produced :author: Ferran Vila Conesa :since: ARP1.0 */ public func locationManager(manager: CLLocationManager, didFailWithError error: NSError) { logger.log(ILoggingLogLevel.Error, category: loggerTag, message: "There is an error in the geolocation update service: \(error.description)") // Stop the geolocation service stopUpdatingLocation() } /** This delegate method is executed when the location manager trys to access to the geolocation service :param: manager Location manager :param: status Status of the location manager start :author: Ferran Vila Conesa :since: ARP1.0 */ public func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) { switch status { case CLAuthorizationStatus.Restricted: logger.log(ILoggingLogLevel.Error, category: loggerTag, message: "Restricted Access to location") listener.onError(IGeolocationListenerError.RestrictedAccess) case CLAuthorizationStatus.Denied: logger.log(ILoggingLogLevel.Error, category: loggerTag, message: "User denied access to location") listener.onError(IGeolocationListenerError.DeniedAccess) case CLAuthorizationStatus.NotDetermined: logger.log(ILoggingLogLevel.Error, category: loggerTag, message: "Status not determined") listener.onError(IGeolocationListenerError.StatusNotDetermined) default: logger.log(ILoggingLogLevel.Error, category: loggerTag, message: "This status: \(status) is not handled by the manager") } #if os(OSX) // Special switch for iOS permissions switch status { case CLAuthorizationStatus.Authorized: NSNotificationCenter.defaultCenter().postNotificationName("LabelHasbeenUpdated", object: nil) // start the geolocation updates locationManager.startUpdatingLocation() logger.log(ILoggingLogLevel.Debug, category: loggerTag, message: "Status Authorized") default: logger.log(ILoggingLogLevel.Error, category: loggerTag, message: "This status: \(status) is not handled by the manager") } #endif #if os(iOS) // Special switch for iOS permissions switch status { case CLAuthorizationStatus.AuthorizedWhenInUse: NSNotificationCenter.defaultCenter().postNotificationName("LabelHasbeenUpdated", object: nil) // start the geolocation updates locationManager.startUpdatingLocation() logger.log(ILoggingLogLevel.Debug, category: loggerTag, message: "Status AuthorizedWhenInUse") case CLAuthorizationStatus.AuthorizedAlways: NSNotificationCenter.defaultCenter().postNotificationName("LabelHasbeenUpdated", object: nil) // start the geolocation updates locationManager.startUpdatingLocation() logger.log(ILoggingLogLevel.Debug, category: loggerTag, message: "Status AuthorizedAlways") default: logger.log(ILoggingLogLevel.Error, category: loggerTag, message: "This status: \(status) is not handled by the manager") } #endif } /** Method that stops the geolocation updates :author: Ferran Vila Conesa :since: ARP1.0 */ public func stopUpdatingLocation() { logger.log(ILoggingLogLevel.Debug, category: loggerTag, message: "Stopping the geolocation updates of \(self.getListener())") locationManager.stopUpdatingLocation() } /** Method that returns the listener of this delegate :returns: Returns the listener :author: Ferran Vila Conesa :since: ARP1.0 */ public func getListener() -> IGeolocationListener { return self.listener } }
apache-2.0
c12755500af24627849b846126b4a88e
35.829596
184
0.638821
5.578804
false
false
false
false
kusalshrestha/SKSwipeableCard
SwipableCard/View/CardViewContainer.swift
1
3834
// // DraggableViewContainer.swift // SwipableCard // // Created by Kusal Shrestha on 6/2/16. // Copyright © 2016 Kusal Shrestha. All rights reserved. // import UIKit class CardViewContainer: UIView { enum Cards: Int { case BaseCard = 1 case BottomCard case MiddleCard case TopCard var frame: CGRect { switch self { case .BaseCard: return CardViewContainer.bottomCardFrame case .BottomCard: return CardViewContainer.bottomCardFrame case .MiddleCard: return CardViewContainer.middleCardFrame case .TopCard: return CardViewContainer.topCardFrame } } } var maxCards = 10 private var currentCardIndex = 1 private var cards: [CardView?] = [] private static var topCardFrame = CGRectZero private static var middleCardFrame = CGRectZero private static var bottomCardFrame = CGRectZero convenience init(WithMaxCards number: Int, frame: CGRect) { self.init(frame: frame) if number < 1 { self.maxCards = 1 } self.maxCards = number commonInit() } override init(frame: CGRect) { super.init(frame: frame) commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } private func commonInit() {} override func layoutSubviews() { super.layoutSubviews() setCardsFrames() } private func setCardsFrames() { CardViewContainer.bottomCardFrame = CGRect(x: 8, y: 24, width: self.bounds.width - 16, height: self.bounds.height - 8) CardViewContainer.middleCardFrame = CGRect(x: 4, y: 12, width: self.bounds.width - 8, height: self.bounds.height - 4) CardViewContainer.topCardFrame = CGRect(x: 0, y: 0, width: self.bounds.width, height: self.bounds.height) } func generateSwipeableCards() { // Gererates first four cards for i in currentCardIndex...4 { let card = NSBundle.mainBundle().loadNibNamed("Card", owner: self, options: nil).first as! CardView card.delegate = self card.frame = (Cards(rawValue: i)?.frame)! card.backgroundColor = randomColor() self.addSubview(card) cards.append(card) } } private func addNewCard() { let card = NSBundle.mainBundle().loadNibNamed("Card", owner: self, options: nil).first as! CardView card.delegate = self card.frame = Cards.BaseCard.frame card.backgroundColor = randomColor() self.insertSubview(card, belowSubview: cards[0]!) cards.insert(card, atIndex: 0) } private func updateCardFrames(changePercent: CGFloat) { // middle to top if let midCard = cards.nthElementFromLast(1) { midCard!.frame = CardViewContainer.middleCardFrame + (CGRect(x: 4, y: 12, width: 8, height: 4) * changePercent) } if let bottomCard = cards.nthElementFromLast(2) { bottomCard!.frame = CardViewContainer.bottomCardFrame + (CGRect(x: 4, y: 12, width: 8, height: 4) * changePercent) } } } extension CardViewContainer: CardSwipeGestureDelegate { func swipeActionHandler(offsetPercentage percent: CGFloat) { guard percent >= 0 && percent <= 1 else { return } updateCardFrames(percent) } func cardRemoved() { print(currentCardIndex) cards.removeLast() if currentCardIndex <= (maxCards - 4) { addNewCard() } currentCardIndex += 1 } }
gpl-3.0
11bd5cac61e29e7928f1b798511911b6
28.037879
126
0.588573
4.57945
false
false
false
false
zhugejunwei/LeetCode
8. String to Integer (atoi).swift
1
2288
import UIKit func myAtoi(str: String) -> Int { var sign: Double = 1 let myStr = str var myInt: Double = 0 var intArray = [Double]() var index = myStr.startIndex if myStr.isEmpty { return 0 } while myStr[index] == " " { index = index.successor() if index == myStr.endIndex { return 0 } while myStr[index] == "0" { index = index.successor() if index == myStr.endIndex { return 0 } } } if myStr[index] == "+" || myStr[index] == "-" || myStr[index] == "0"{ if myStr[index] == "-" { sign = -1 } if index.successor() == myStr.endIndex { return 0 } index = index.successor() while myStr[index] == "0" { index = index.successor() if index == myStr.endIndex { return 0 } } if index == myStr.endIndex { return 0 }else if myStr[index] <= "9" && myStr[index] >= "1" { for i in index..<myStr.endIndex { if myStr[i] <= "9" && myStr[i] >= "0" { let curString = String(myStr[i]) if let curInt = Double(curString) { intArray += [curInt] } }else { break } } } else { return 0 } }else if myStr[index] > "9" || myStr[index] < "1" { return 0 } else { for i in index..<myStr.endIndex { if myStr[i] <= "9" && myStr[i] >= "0" { let curString = String(myStr[i]) if let curInt = Double(curString) { intArray += [curInt] } }else { break } } } for index in intArray { myInt = myInt * 10 + index } myInt = myInt * sign if myInt > Double(Int32.max) { return Int(Int32.max) } else if myInt < Double(Int.min) { return Int.min } else { return Int(myInt) } } myAtoi("2147483648")
mit
58a69ed8ffd910eec5ec9e492f385c89
23.602151
73
0.398164
4.16
false
false
false
false
loiwu/WAI
GuidedTour.playground/Pages/Protocols and Extensions.xcplaygroundpage/Contents.swift
1
2764
//: ## Protocols and Extensions //: //: Use `protocol` to declare a protocol. //: protocol ExampleProtocol { var simpleDescription: String { get } mutating func adjust() } //: Classes, enumerations, and structs can all adopt protocols. //: class SimpleClass: ExampleProtocol { var simpleDescription: String = "A very simple class." var anotherProperty: Float = 19870706.19870305 func adjust() { simpleDescription += " Now 100% adjusted." } } var a = SimpleClass() a.adjust() let aDescription = a.simpleDescription struct SimpleStructure: ExampleProtocol { var simpleDescription: String = "A simple structure" mutating func adjust() { simpleDescription += " (adjusted)" } } var b = SimpleStructure() b.adjust() let bDescription = b.simpleDescription //: > **Experiment**: //: > Write an enumeration that conforms to this protocol. //: //: Notice the use of the `mutating` keyword in the declaration of `SimpleStructure` to mark a method that modifies the structure. The declaration of `SimpleClass` doesn’t need any of its methods marked as mutating because methods on a class can always modify the class. //: //: Use `extension` to add functionality to an existing type, such as new methods and computed properties. You can use an extension to add protocol conformance to a type that is declared elsewhere, or even to a type that you imported from a library or framework. //: extension Int: ExampleProtocol { var simpleDescription: String { return "The number \(self)" } mutating func adjust() { self += 42 } } print(7.simpleDescription) extension Double: ExampleProtocol { var simpleDescription: String { return "The number's absolute value is \(self)" } mutating func adjust() { self = abs(self) } } print((-9.0).simpleDescription) //: > **Experiment**: //: > Write an extension for the `Double` type that adds an `absoluteValue` property. //: //: You can use a protocol name just like any other named type—for example, to create a collection of objects that have different types but that all conform to a single protocol. When you work with values whose type is a protocol type, methods outside the protocol definition are not available. //: let protocolValue: ExampleProtocol = a print(protocolValue.simpleDescription) // print(protocolValue.anotherProperty) // Uncomment to see the error //: Even though the variable `protocolValue` has a runtime type of `SimpleClass`, the compiler treats it as the given type of `ExampleProtocol`. This means that you can’t accidentally access methods or properties that the class implements in addition to its protocol conformance. //: //: [Previous](@previous) | [Next](@next)
mit
f0d93686e2c5c8683168920784a50143
37.305556
294
0.717186
4.551155
false
false
false
false
NordicSemiconductor/IOS-nRF-Toolbox
nRF Toolbox/MainScreen/Cell/ServiceTableViewCell.swift
1
2421
/* * Copyright (c) 2020, Nordic Semiconductor * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ import UIKit class ServiceTableViewCell: UITableViewCell { @IBOutlet private var name: UILabel! @IBOutlet private var icon: UIImageView! @IBOutlet private var code: UILabel! override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) } override func awakeFromNib() { super.awakeFromNib() if #available(iOS 13.0, *) { name.highlightedTextColor = .label code.highlightedTextColor = .secondaryLabel } } required init?(coder: NSCoder) { super.init(coder: coder) } func update(with model: BLEService) { name.text = model.name code.text = model.code icon.image = UIImage(named: model.icon)?.withRenderingMode(.alwaysTemplate) } }
bsd-3-clause
ce67c0e25aec60ba09582bec3ba1ddad
38.048387
84
0.729038
4.756385
false
false
false
false
simorgh3196/GitHubSearchApp
Carthage/Checkouts/Himotoki/Sources/KeyPath.swift
1
1441
// // KeyPath.swift // Himotoki // // Created by Syo Ikeda on 6/5/15. // Copyright (c) 2015 Syo Ikeda. All rights reserved. // public struct KeyPath: Hashable { public let components: [String] public init(_ key: String) { self.init([key]) } public init(_ components: [String]) { self.components = components } public static var empty: KeyPath { return KeyPath([]) } } public func == (lhs: KeyPath, rhs: KeyPath) -> Bool { return lhs.components == rhs.components } public func + (lhs: KeyPath, rhs: KeyPath) -> KeyPath { return KeyPath(lhs.components + rhs.components) } extension KeyPath { public var hashValue: Int { return components.reduce(0) { $0 ^ $1.hashValue } } } extension KeyPath: CustomStringConvertible { public var description: String { return "KeyPath(\(components))" } } extension KeyPath: StringLiteralConvertible { public init(unicodeScalarLiteral value: String) { self.init(value) } public init(extendedGraphemeClusterLiteral value: String) { self.init(value) } public init(stringLiteral value: String) { self.init(value) } } extension KeyPath: ArrayLiteralConvertible { public init(arrayLiteral elements: String...) { self.init(elements) } } extension KeyPath: NilLiteralConvertible { public init(nilLiteral: ()) { self.init([]) } }
mit
ea58675b1ac9a03850dd91732966472f
19.884058
63
0.63567
4.140805
false
false
false
false
MiniKeePass/MiniKeePass
MiniKeePass/Web Browser View/WebBrowserViewController.swift
1
5238
/* * Copyright 2016 Jason Rush and John Flanagan. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import UIKit import WebKit class WebBrowserViewController: UIViewController, WKNavigationDelegate { @IBOutlet weak var progressView: UIProgressView! @IBOutlet weak var backButton: UIBarButtonItem! @IBOutlet weak var forwardButton: UIBarButtonItem! // FIXME Add stop button too fileprivate var webView: WKWebView! @objc var url: URL? @objc var entry: KdbEntry? override func loadView() { super.loadView() webView = WKWebView() webView.allowsBackForwardNavigationGestures = true view.insertSubview(webView, belowSubview: progressView) } override func viewDidLoad() { super.viewDidLoad() // Set the title from the url navigationItem.title = url?.host // Set the buttons disabled by default backButton.isEnabled = false forwardButton.isEnabled = false // Add autolayout constraints for the web view webView.translatesAutoresizingMaskIntoConstraints = false let widthConstraint = NSLayoutConstraint(item: webView, attribute: .width, relatedBy: .equal, toItem: view, attribute: .width, multiplier: 1, constant: 0) let heightConstraint = NSLayoutConstraint(item: webView, attribute: .height, relatedBy: .equal, toItem: view, attribute: .height, multiplier: 1, constant: 0) view.addConstraints([widthConstraint, heightConstraint]) // Configure the delegate and observers webView.navigationDelegate = self webView.addObserver(self, forKeyPath: "loading", options: .new, context: nil) webView.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil) // Load the URL let urlRequest = URLRequest(url:url!) webView!.load(urlRequest) } deinit { webView.removeObserver(self, forKeyPath: "loading") webView.removeObserver(self, forKeyPath: "estimatedProgress") } func autotypeString(_ string: String) { // Escape backslashes & single quotes var escapedString = string escapedString = escapedString.replacingOccurrences(of: "\\", with: "\\\\") escapedString = escapedString.replacingOccurrences(of: "\'", with: "\\'") // Execute a script to set the value of the selected element let script = String(format:"if (document.activeElement) { document.activeElement.value = '%@'; }", escapedString) webView.evaluateJavaScript(script, completionHandler: nil) } // MARK: - NSKeyValueObserving override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if (keyPath == "loading") { backButton.isEnabled = webView.canGoBack forwardButton.isEnabled = webView.canGoForward } else if (keyPath == "estimatedProgress") { progressView.isHidden = webView.estimatedProgress == 1 progressView.setProgress(Float(webView.estimatedProgress), animated: true) } } // MARK: - WKWebView delegate func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { progressView.setProgress(0.0, animated: false) // Update the title navigationItem.title = webView.title } func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) { presentAlertWithTitle(NSLocalizedString("Error", comment: ""), message: error.localizedDescription) } // MARK: - Actions @IBAction func closePressed(_ sender: UIBarButtonItem) { dismiss(animated: true, completion: nil) } @IBAction func pasteUsernamePressed(_ sender: UIBarButtonItem) { autotypeString(entry!.username()) } @IBAction func pastePasswordPressed(_ sender: UIBarButtonItem) { autotypeString(entry!.password()) } @IBAction func backPressed(_ sender: UIBarButtonItem) { webView.goBack() } @IBAction func forwardPressed(_ sender: UIBarButtonItem) { webView.goForward() } @IBAction func reloadPressed(_ sender: UIBarButtonItem) { let request = URLRequest(url:webView.url!) webView.load(request) } @IBAction func actionPressed(_ sender: UIBarButtonItem) { let application = UIApplication.shared application.openURL(webView.url!) } }
gpl-3.0
0445ee5ab5c4f7407e0ae77b601cd266
36.683453
165
0.672585
5.16568
false
false
false
false
getsentry/sentry-swift
Tests/SentryTests/Dynamic/Invocation.swift
1
8883
// // Dynamic // Created by Mhd Hejazi on 4/15/20. // Copyright © 2020 Samabox. All rights reserved. // import Foundation class Invocation: Loggable { public static var loggingEnabled: Bool = false var loggingEnabled: Bool { Self.loggingEnabled } private let target: NSObject private let selector: Selector var invocation: NSObject? var numberOfArguments: Int = 0 var returnLength: Int = 0 var returnType: UnsafePointer<CChar>? var returnTypeString: String? { guard let returnType = returnType else { return nil } return String(cString: returnType) } var returnsObject: Bool { /// `@` is the type encoding for an object returnTypeString == "@" } var returnsAny: Bool { /// `v` is the type encoding for Void returnTypeString != "v" } lazy var returnedObject: AnyObject? = { returnedObjectValue() }() private(set) var isInvoked: Bool = false init(target: NSObject, selector: Selector) throws { self.target = target self.selector = selector log(.start) log("# Invocation") log("[\(type(of: target)) \(selector)]") log("Selector:", selector) try initialize() } private func initialize() throws { /// `NSMethodSignature *methodSignature = [target methodSignatureForSelector: selector]` let methodSignature: NSObject do { let selector = NSSelectorFromString("methodSignatureForSelector:") let signature = (@convention(c)(NSObject, Selector, Selector) -> Any).self let method = unsafeBitCast(target.method(for: selector), to: signature) guard let result = method(target, selector, self.selector) as? NSObject else { let error = InvocationError.unrecognizedSelector(type(of: target), self.selector) log("ERROR:", error) throw error } methodSignature = result } /// `numberOfArguments = methodSignature.numberOfArguments` self.numberOfArguments = methodSignature.value(forKeyPath: "numberOfArguments") as? Int ?? 0 log("NumberOfArguments:", numberOfArguments) /// `methodReturnLength = methodSignature.methodReturnLength` self.returnLength = methodSignature.value(forKeyPath: "methodReturnLength") as? Int ?? 0 log("ReturnLength:", returnLength) /// `methodReturnType = methodSignature.methodReturnType` let methodReturnType: UnsafePointer<CChar> do { let selector = NSSelectorFromString("methodReturnType") let signature = (@convention(c)(NSObject, Selector) -> UnsafePointer<CChar>).self let method = unsafeBitCast(methodSignature.method(for: selector), to: signature) methodReturnType = method(methodSignature, selector) } self.returnType = methodReturnType log("ReturnType:", self.returnTypeString ?? "?") /// `NSInvocation *invocation = [NSInvocation invocationWithMethodSignature: methodSignature]` let invocation: NSObject do { let NSInvocation = NSClassFromString("NSInvocation") as AnyObject let selector = NSSelectorFromString("invocationWithMethodSignature:") let signature = (@convention(c)(AnyObject, Selector, AnyObject) -> AnyObject).self let method = unsafeBitCast(NSInvocation.method(for: selector), to: signature) guard let result = method(NSInvocation, selector, methodSignature) as? NSObject else { let error = InvocationError.unrecognizedSelector(type(of: target), self.selector) log("ERROR:", error) throw error } invocation = result } self.invocation = invocation /// `invocation.selector = selector` do { let selector = NSSelectorFromString("setSelector:") let signature = (@convention(c)(NSObject, Selector, Selector) -> Void).self let method = unsafeBitCast(invocation.method(for: selector), to: signature) method(invocation, selector, self.selector) } /// `[invocation retainArguments]` do { let selector = NSSelectorFromString("retainArguments") let signature = (@convention(c)(NSObject, Selector) -> Void).self let method = unsafeBitCast(invocation.method(for: selector), to: signature) method(invocation, selector) } } func setArgument(_ argument: Any?, at index: NSInteger) { guard let invocation = invocation else { return } log("Argument #\(index - 1):", argument ?? "<nil>") /// `[invocation setArgument:&argument atIndex:i + 2]` let selector = NSSelectorFromString("setArgument:atIndex:") let signature = (@convention(c)(NSObject, Selector, UnsafeRawPointer, Int) -> Void).self let method = unsafeBitCast(invocation.method(for: selector), to: signature) if let valueArgument = argument as? NSValue { /// Get the type byte size let typeSize = UnsafeMutablePointer<Int>.allocate(capacity: 1) defer { typeSize.deallocate() } NSGetSizeAndAlignment(valueArgument.objCType, typeSize, nil) /// Get the actual value let buffer = UnsafeMutablePointer<Int8>.allocate(capacity: typeSize.pointee) defer { buffer.deallocate() } valueArgument.getValue(buffer) method(invocation, selector, buffer, index) } else { withUnsafePointer(to: argument) { pointer in method(invocation, selector, pointer, index) } } } func invoke() { guard let invocation = invocation, !isInvoked else { return } log("Invoking...") isInvoked = true /// `[invocation invokeWithTarget: target]` do { let selector = NSSelectorFromString("invokeWithTarget:") let signature = (@convention(c)(NSObject, Selector, AnyObject) -> Void).self let method = unsafeBitCast(invocation.method(for: selector), to: signature) method(invocation, selector, target) } log(.end) } func getReturnValue<T>(result: inout T) { guard let invocation = invocation else { return } /// `[invocation getReturnValue: returnValue]` do { let selector = NSSelectorFromString("getReturnValue:") let signature = (@convention(c)(NSObject, Selector, UnsafeMutableRawPointer) -> Void).self let method = unsafeBitCast(invocation.method(for: selector), to: signature) withUnsafeMutablePointer(to: &result) { pointer in method(invocation, selector, pointer) } } if NSStringFromSelector(self.selector) == "alloc" { log("getReturnValue() -> <alloc>") } else { log("getReturnValue() ->", result) } } private func returnedObjectValue() -> AnyObject? { guard returnsObject, returnLength > 0 else { return nil } var result: AnyObject? getReturnValue(result: &result) guard let object = result else { return nil } /// Take the ownership of the initialized objects to ensure they're deallocated properly. if isRetainingMethod() { return Unmanaged.passRetained(object).takeRetainedValue() } /// `NSInvocation.getReturnValue()` doesn't give us the ownership of the returned object, but the compiler /// tries to release this object anyway. So, we are retaining it to balance with the compiler's release. return Unmanaged.passRetained(object).takeUnretainedValue() } private func isRetainingMethod() -> Bool { /// Refer to: https://bit.ly/308okXm let selector = NSStringFromSelector(self.selector) return selector == "alloc" || selector.hasPrefix("new") || selector.hasPrefix("copy") || selector.hasPrefix("mutableCopy") } } public enum InvocationError: CustomNSError { case unrecognizedSelector(_ classType: AnyClass, _ selector: Selector) public static var errorDomain: String { String(describing: Invocation.self) } public var errorCode: Int { switch self { case .unrecognizedSelector: return 404 } } public var errorUserInfo: [String: Any] { var message: String switch self { case .unrecognizedSelector(let classType, let selector): message = "'\(String(describing: classType))' doesn't recognize selector '\(selector)'" } return [NSLocalizedDescriptionKey: message] } }
mit
e55b1ddb615c8007cde94da6c8010df8
36.476793
114
0.620243
5.200234
false
false
false
false
skarppi/cavok
CAVOK/Weather/Observation/ObservationDrawerView.swift
1
3994
// // ObservationDrawerView.swift // CAV-OK // // Created by Juho Kolehmainen on 9.11.2019. // Copyright © 2019 Juho Kolehmainen. All rights reserved. // import SwiftUI struct ObservationHeaderView: View { var presentation: ObservationPresentation var obs: Observation var closedAction: (() -> Void) var body: some View { VStack(alignment: .leading) { DrawerTitleView(title: self.obs.station?.name, action: closedAction) AttributedText(obs: obs, presentation: presentation) .fixedSize(horizontal: false, vertical: true) .padding(.top) } } } struct ObservationDetailsView: View { var presentation: ObservationPresentation var observations: Observations var body: some View { VStack(alignment: .leading) { ObservationList( title: "Metar history", observations: observations.metars, presentation: presentation) ObservationList( title: "Taf", observations: observations.tafs, presentation: presentation) }.padding(.horizontal) } } struct ObservationList: View { var title: String var observations: [Observation] var presentation: ObservationPresentation var body: some View { Group { if !observations.isEmpty { Text(title) .font(Font.system(.headline)) .padding(.vertical) ForEach(observations.reversed(), id: \.self) { metar in AttributedText(obs: metar, presentation: self.presentation) .padding(.bottom, 5) } } } } } struct AttributedText: View { var obs: Observation var presentation: ObservationPresentation var data: ObservationPresentationData { presentation.split(observation: obs) } var body: some View { Text(data.start) + Text(data.highlighted).foregroundColor(Color(data.color)) + Text(data.end) } } struct ObservationDrawerView_Previews: PreviewProvider { static let presentation = ObservationPresentation( module: Module(key: ModuleKey.ceiling, title: "ceil", unit: "FL", legend: [:]) ) static let observations = Observations( metars: [ metar("METAR EFHK 091950Z 05006KT 3500 -RADZ BR FEW003 BKN005 05/04 Q1009 NOSIG="), metar("METAR EFHK 091920Z 04006KT 4000 -DZ BR BKN004 05/05 Q1009="), metar("METAR EFHK 091850Z 07004KT 040V130 4000 BR BKN005 05/05 Q1009="), metar("METAR EFHK 091820Z 07003KT 4000 BR BKN005 05/05 Q1009="), metar("EFHK 091750Z 06004KT CAVOK 05/05 Q1009="), metar("METAR EFHK 091720Z 06004KT 6000 BKN006 05/05 Q1009="), metar("METAR EFHK 091650Z 08004KT 7000 SCT004 BKN006 05/05 RMK AO2 SLP135 T01170028 10144 20111 Q1009=") ], tafs: [ taf("TAF EFHK 121430Z 1215/1315 24008KT CAVOK TEMPO 1305/1313 SHRA BKN012 BKN020CB PROB30") ]) static var previews: some View { VStack { ObservationHeaderView(presentation: presentation, obs: observations.metars[0], closedAction: { () in print("Closed")}) ObservationDetailsView(presentation: presentation, observations: observations) } } static func metar(_ raw: String) -> Metar { let metar = Metar() metar.parse(raw: raw) metar.station = Station() metar.station?.name = "Helsinki-Vantaan lentoasema EFHF airport" return metar } static func taf(_ raw: String) -> Taf { let taf = Taf() taf.parse(raw: raw) taf.station = Station() taf.station?.name = "Helsinki-Vantaan lentoasema EFHF airport" return taf } }
mit
d5d53967875eca1c6939d99282aebf6c
30.195313
116
0.589782
4.172414
false
false
false
false
rahulsend89/MemoryGame
MemoryGame/ConcurrentOperation.swift
1
1476
// // ConcurrentOperation.swift // MemoryGame // // Created by Rahul Malik on 7/15/17. // Copyright © 2017 aceenvisage. All rights reserved. // import Foundation class ConcurrentOperation: BlockOperation { var task: URLSessionDataTask? lazy var completion:() -> Void = { self.completeOperation() } func completeOperation() { state = .Finished } enum State: String { case Ready, Executing, Finished fileprivate var keyPath: String { return "is" + rawValue } } var state = State.Ready { willSet { willChangeValue(forKey: newValue.keyPath) willChangeValue(forKey: state.keyPath) } didSet { didChangeValue(forKey: oldValue.keyPath) didChangeValue(forKey: state.keyPath) } } } extension ConcurrentOperation { //: NSOperation Overrides override var isReady: Bool { return super.isReady && state == .Ready } override var isExecuting: Bool { return state == .Executing } override var isFinished: Bool { return state == .Finished } override var isAsynchronous: Bool { return true } override func start() { if isCancelled { state = .Finished return } main() state = .Executing } override func cancel() { state = .Finished self.task?.cancel() } }
mit
c7ce18e37e0bb4728799d76ad124f8a6
19.774648
54
0.573559
4.884106
false
false
false
false
zvonicek/ImageSlideshow
ImageSlideshow/Classes/Core/PageIndicatorPosition.swift
1
2990
// // PageIndicator.swift // ImageSlideshow // // Created by Petr Zvoníček on 04.02.18. // import UIKit /// Describes the configuration of the page indicator position public struct PageIndicatorPosition { public enum Horizontal { case left(padding: CGFloat), center, right(padding: CGFloat) } public enum Vertical { case top, bottom, under, customTop(padding: CGFloat), customBottom(padding: CGFloat), customUnder(padding: CGFloat) } /// Horizontal position of the page indicator var horizontal: Horizontal /// Vertical position of the page indicator var vertical: Vertical /// Creates a new PageIndicatorPosition struct /// /// - Parameters: /// - horizontal: horizontal position of the page indicator /// - vertical: vertical position of the page indicator public init(horizontal: Horizontal = .center, vertical: Vertical = .bottom) { self.horizontal = horizontal self.vertical = vertical } /// Computes the additional padding needed for the page indicator under the ImageSlideshow /// /// - Parameter indicatorSize: size of the page indicator /// - Returns: padding needed under the ImageSlideshow func underPadding(for indicatorSize: CGSize) -> CGFloat { switch vertical { case .under: return indicatorSize.height case .customUnder(let padding): return indicatorSize.height + padding default: return 0 } } /// Computes the page indicator frame /// /// - Parameters: /// - parentFrame: frame of the parent view – ImageSlideshow /// - indicatorSize: size of the page indicator /// - edgeInsets: edge insets of the parent view – ImageSlideshow (used for SafeAreaInsets adjustment) /// - Returns: frame of the indicator by computing the origin and using `indicatorSize` as size func indicatorFrame(for parentFrame: CGRect, indicatorSize: CGSize, edgeInsets: UIEdgeInsets) -> CGRect { var xSize: CGFloat = 0 var ySize: CGFloat = 0 switch horizontal { case .center: xSize = parentFrame.size.width / 2 - indicatorSize.width / 2 case .left(let padding): xSize = padding + edgeInsets.left case .right(let padding): xSize = parentFrame.size.width - indicatorSize.width - padding - edgeInsets.right } switch vertical { case .bottom, .under, .customUnder: ySize = parentFrame.size.height - indicatorSize.height - edgeInsets.bottom case .customBottom(let padding): ySize = parentFrame.size.height - indicatorSize.height - padding - edgeInsets.bottom case .top: ySize = edgeInsets.top case .customTop(let padding): ySize = padding + edgeInsets.top } return CGRect(x: xSize, y: ySize, width: indicatorSize.width, height: indicatorSize.height) } }
mit
1ff001feb0b6800c1d82f26ba0e05304
34.52381
123
0.648794
4.828479
false
false
false
false
jvanlint/Secret-Squirrel
Secret Squirrel/ViewControllers/CategoryDetailTableViewController.swift
1
4844
// // CategoryDetailTableViewController.swift // Secret Squirrel // // Created by Jason van Lint on 14/8/17. // Copyright © 2017 Dead Frog Studios. All rights reserved. // import UIKit class CategoryDetailTableViewController: UITableViewController { var categoryName = "Test" var dataSource = ["Test", "Test2"] let categoryData = CodeWordCategories() override func viewDidLoad() { super.viewDidLoad() // Setup the datasource for the table. self.dataSource = self.categoryData.arrayOfWords(forCategory: self.categoryName) // Set up nav bar items. self.navigationItem.title=categoryName self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Add", style: .plain, target: self, action: #selector(addTapped)) } @objc func addTapped(){ let alertController = UIAlertController(title: "Add Category Item", message: "Please input your new category item:", preferredStyle: .alert) let confirmAction = UIAlertAction(title: "Add", style: .default) { (_) in if let field = alertController.textFields?[0] { // store your data if !(field.text!.isEmpty) { self.dataSource.append(field.text!) // Write code to persist data. self.categoryData.add(word: field.text!, forCategory: self.categoryName) self.tableView.reloadData() } } else { // user did not fill field } } let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (_) in } alertController.addTextField { (textField) in textField.placeholder = "New Category Item" } alertController.addAction(confirmAction) alertController.addAction(cancelAction) self.present(alertController, animated: true, completion: nil) } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return dataSource.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "categoryDetailCell", for: indexPath) // Configure the cell... let label = cell.viewWithTag(100) as! UILabel label.text = dataSource[indexPath.row].capitalized return 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 dataSource.remove(at: indexPath.row) // Delete word from object and resave plist file. self.categoryData.remove(atIndex: indexPath.row, forCategory: self.categoryName) 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
7d59b22c9187e0b417bb348ede6f471a
35.689394
152
0.617799
5.36918
false
false
false
false
becca9808/Hacktech2017
SDK/CognitiveServices/ComputerVision/OCR.swift
1
7202
// OcrComputerVision.swift // // Copyright (c) 2016 Vladimir Danila // // 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 /** RequestObject is the required parameter for the OCR API containing all required information to perform a request - parameter resource: The path or data of the image or - parameter language, detectOrientation: Read more about those [here](https://dev.projectoxford.ai/docs/services/56f91f2d778daf23d8ec6739/operations/56f91f2e778daf14a499e1fa) */ typealias OCRRequestObject = (resource: Any, language: OCR.Langunages, detectOrientation: Bool) /** Title Read text in images Optical Character Recognition (OCR) detects text in an image and extracts the recognized words into a machine-readable character stream. Analyze images to detect embedded text, generate character streams and enable searching. Allow users to take photos of text instead of copying to save time and effort. - You can try OCR here: https://www.microsoft.com/cognitive-services/en-us/computer-vision-api */ class OCR: NSObject { /// The url to perform the requests on let url = "https://api.projectoxford.ai/vision/v1.0/ocr" /// Your private API key. If you havn't changed it yet, go ahead! let key = "9f6fd2c2da4b41dcb7cff000ac81776a" /// Detectable Languages enum Langunages: String { case Automatic = "unk" case ChineseSimplified = "zh-Hans" case ChineseTraditional = "zh-Hant" case Czech = "cs" case Danish = "da" case Dutch = "nl" case English = "en" case Finnish = "fi" case French = "fr" case German = "de" case Greek = "el" case Hungarian = "hu" case Italian = "it" case Japanese = "Ja" case Korean = "ko" case Norwegian = "nb" case Polish = "pl" case Portuguese = "pt" case Russian = "ru" case Spanish = "es" case Swedish = "sv" case Turkish = "tr" } enum RecognizeCharactersErrors: Error { case unknownError case imageUrlWrongFormatted case emptyDictionary } /** Optical Character Recognition (OCR) detects text in an image and extracts the recognized characters into a machine-usable character stream. - parameter requestObject: The required information required to perform a request - parameter language: The languange - parameter completion: Once the request has been performed the response is returend in the completion block. */ func recognizeCharactersWithRequestObject(_ requestObject: OCRRequestObject, completion: @escaping (_ response: [String:AnyObject]? ) -> Void) throws { // Generate the url let requestUrlString = url + "?language=" + requestObject.language.rawValue + "&detectOrientation%20=\(requestObject.detectOrientation)" let requestUrl = URL(string: requestUrlString) var request = URLRequest(url: requestUrl!) request.setValue(key, forHTTPHeaderField: "Ocp-Apim-Subscription-Key") // Request Parameter if let path = requestObject.resource as? String { request.setValue("application/json", forHTTPHeaderField: "Content-Type") request.httpBody = "{\"url\":\"\(path)\"}".data(using: String.Encoding.utf8) } else if let imageData = requestObject.resource as? Data { request.setValue("application/octet-stream", forHTTPHeaderField: "Content-Type") request.httpBody = imageData } request.httpMethod = "POST" let task = URLSession.shared.dataTask(with: request){ data, response, error in if error != nil{ print("Error -> \(error)") completion(nil) return }else{ let results = try! JSONSerialization.jsonObject(with: data!, options: []) as? [String:AnyObject] // Hand dict over DispatchQueue.main.async { completion(results) } } } task.resume() } /** Returns an Array of Strings extracted from the Dictionary generated from `recognizeCharactersOnImageUrl()` - Parameter dictionary: The Dictionary created by `recognizeCharactersOnImageUrl()`. - Returns: An String Array extracted from the Dictionary. */ <<<<<<< HEAD func extractStringsFromDictionary(_ dictionary: [String : AnyObject]) { //originally returned // Get Regions from the dictionary let regions = (dictionary["regions"] as! NSArray).firstObject as? [String:AnyObject] let lines = regions!["lines"] as! NSArray let inLine = lines.enumerated().map{($0.element as? NSDictionary)?["words"] as! [[String : AnyObject]] } /* let regions = (dictionary["regions"] as! NSArray).firstObject as? [String:AnyObject] ======= func extractStringsFromDictionary(_ dictionary: [String : AnyObject]) -> [String] { var text:[String] = [] >>>>>>> f9c0cbfff3ebaf22768c68843c79832418789221 // get regions from dictionary if let regions = dictionary["regions"] as? [[String:AnyObject]] { for region in regions { if let lines = region["lines"] as? [[String:AnyObject]] { for line in lines { var currentLine:String = "" if let words = line["words"] as? [[String:AnyObject]] { for word in words { currentLine += word["text"] as! String currentLine += " " } } text.append(currentLine) } } } } <<<<<<< HEAD //return extractedText */ ======= return text >>>>>>> f9c0cbfff3ebaf22768c68843c79832418789221 } // return one large string composed of the previous array of lines func extractStringFromDictionary(_ dictionary: [String:AnyObject]) -> String { let stringArray = extractStringsFromDictionary(dictionary) let reducedArray = stringArray.enumerated().reduce("", { $0 + $1.element + ($1.offset < stringArray.endIndex-1 ? " " : "") } ) return reducedArray } }
apache-2.0
de3aab9d90122aa45bd8f4520acb98b5
36.123711
305
0.598445
4.728825
false
false
false
false
Aynelgul/finalproject
finalproject/AllTipsViewController.swift
1
2230
// // AllTipsViewController.swift // finalproject // // Created by Aynel Gül on 30-01-17. // Copyright © 2017 Aynel Gül. All rights reserved. // import UIKit import Firebase class AllTipsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { // MARK: - Outlets. @IBOutlet weak var myTipsTableView: UITableView! // MARK: - Variables. var tipRef = FIRDatabase.database().reference(withPath: "tip-items") var tipItems: [Tip] = [] // MARK: - viewDidLoad override func viewDidLoad() { super.viewDidLoad() tipRef.observe(.value, with: { snapshot in var newItems: [Tip] = [] for item in snapshot.children { let tipItem = Tip(snapshot: item as! FIRDataSnapshot) if tipItem.uid == (FIRAuth.auth()?.currentUser?.uid)! { newItems.append(tipItem) } } self.tipItems = newItems self.myTipsTableView.reloadData() }) } // MARK: - Functions. func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tipItems.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "myTipsCell", for: indexPath) as! OwnTipsCell let item = tipItems[indexPath.row] cell.typeLabel.text = item.type cell.descriptionLabel.text = item.description cell.countryLabel.text = item.country cell.cityLabel.text = item.city return cell } func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { let tipItem = self.tipItems[indexPath.row] tipItem.ref?.removeValue() } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
mit
099666706d4fc970188bff5cf040efaf
29.094595
127
0.606646
4.905286
false
false
false
false
hoangdang1449/Spendy
Spendy/AccountDetailViewController.swift
1
9078
// // AccountDetailViewController.swift // Spendy // // Created by Dave Vo on 9/18/15. // Copyright (c) 2015 Cheetah. All rights reserved. // import UIKit class AccountDetailViewController: UIViewController { @IBOutlet weak var tableView: UITableView! var addButton: UIButton? var cancelButton: UIButton? var sampleTransactions: [[Transaction]]! var selectedAccount: Account! var selectedCategory: Category! var transaction: Transaction! override func viewDidLoad() { super.viewDidLoad() selectedCategory = Category.all()!.first transaction = Transaction(kind: Transaction.expenseKind, note: "", amount: 0, category: selectedCategory, account: selectedAccount, date: NSDate()) let dateFormatter = Transaction.dateFormatter dateFormatter.dateFormat = "YYYY-MM-dd" // TODO: this is temporary. need to wait for Category and Account to load first Transaction.loadAll() // create a few sample transactions reloadTransactions() tableView.dataSource = self tableView.delegate = self tableView.tableFooterView = UIView() addBarButton() let downSwipe = UISwipeGestureRecognizer(target: self, action: Selector("handleDownSwipe:")) downSwipe.direction = .Down downSwipe.delegate = self tableView.addGestureRecognizer(downSwipe) if let selectedAccount = selectedAccount { navigationItem.title = selectedAccount.name } } func reloadTransactions() { sampleTransactions = Transaction.listGroupedByMonth(Transaction.all()!) } // reload data after we navigate back from pushed cell override func viewWillAppear(animated: Bool) { print("viewWillAppear", terminator: "\n") reloadTransactions() tableView.reloadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: Button func addBarButton() { addButton = UIButton() Helper.sharedInstance.customizeBarButton(self, button: addButton!, imageName: "Add", isLeft: false) addButton!.addTarget(self, action: "onAddButton:", forControlEvents: UIControlEvents.TouchUpInside) cancelButton = UIButton() Helper.sharedInstance.customizeBarButton(self, button: cancelButton!, imageName: "Cancel", isLeft: true) cancelButton!.addTarget(self, action: "onCancelButton:", forControlEvents: UIControlEvents.TouchUpInside) } func onAddButton(sender: UIButton!) { print("on Add", terminator: "\n") let dvc = self.storyboard?.instantiateViewControllerWithIdentifier("AddVC") as! AddTransactionViewController let nc = UINavigationController(rootViewController: dvc) self.presentViewController(nc, animated: true, completion: nil) } func onCancelButton(sender: UIButton!) { // dismissViewControllerAnimated(true, completion: nil) navigationController?.popViewControllerAnimated(true) } // MARK: Transfer between 2 views override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // let navigationController = segue.destinationViewController as! UINavigationController // // if navigationController.topViewController is AddTransactionViewController { // let addViewController = navigationController.topViewController as! AddTransactionViewController // // var indexPath: AnyObject! // indexPath = tableView.indexPathForCell(sender as! UITableViewCell) // //// addViewController.selectedTransaction = sampleTransactions[indexPath.section][indexPath.row] // } let vc = segue.destinationViewController if vc is AddTransactionViewController { let addTransactionViewController = vc as! AddTransactionViewController var indexPath: AnyObject! indexPath = tableView.indexPathForCell(sender as! UITableViewCell) addTransactionViewController.selectedTransaction = sampleTransactions[indexPath.section][indexPath.row] print("pass selectedTransaction to AddTransactionView: \(addTransactionViewController.selectedTransaction))", terminator: "\n") } } } // MARK: Table view extension AccountDetailViewController: UITableViewDataSource, UITableViewDelegate { func numberOfSectionsInTableView(tableView: UITableView) -> Int { return sampleTransactions.count } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return sampleTransactions[section].count } func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let headerView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: 30)) headerView.backgroundColor = UIColor(netHex: 0xDCDCDC) let monthLabel = UILabel(frame: CGRect(x: 8, y: 2, width: UIScreen.mainScreen().bounds.width - 16, height: 30)) monthLabel.font = UIFont.systemFontOfSize(14) monthLabel.text = sampleTransactions[section][0].monthHeader() // TODO: get date from transaction // let date = NSDate() // var formatter = NSDateFormatter() // formatter.dateFormat = "MMMM, yyyy" // monthLabel.text = formatter.stringFromDate(date) headerView.addSubview(monthLabel) return headerView } func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 34 } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 62 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("TransactionCell", forIndexPath: indexPath) as! TransactionCell // cell.noteLabel.text = sampleTransactions[indexPath.section][indexPath.row].note cell.transaction = sampleTransactions[indexPath.section][indexPath.row] let rightSwipe = UISwipeGestureRecognizer(target: self, action: Selector("handleSwipe:")) rightSwipe.direction = .Right cell.addGestureRecognizer(rightSwipe) let leftSwipe = UISwipeGestureRecognizer(target: self, action: Selector("handleSwipe:")) leftSwipe.direction = .Left cell.addGestureRecognizer(leftSwipe) Helper.sharedInstance.setSeparatorFullWidth(cell) return cell } } // MARK: Handle gestures extension AccountDetailViewController: UIGestureRecognizerDelegate { func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool { return true } func handleSwipe(sender: UISwipeGestureRecognizer) { let selectedCell = sender.view as! TransactionCell let indexPath = tableView.indexPathForCell(selectedCell) if let indexPath = indexPath { switch sender.direction { case UISwipeGestureRecognizerDirection.Left: // Delete transaction sampleTransactions[indexPath.section].removeAtIndex(indexPath.row) tableView.reloadSections(NSIndexSet(index: indexPath.section), withRowAnimation: UITableViewRowAnimation.Automatic) if sampleTransactions[indexPath.section].count == 0 { sampleTransactions.removeAtIndex(indexPath.section) tableView.reloadData() } break case UISwipeGestureRecognizerDirection.Right: // Duplicate transaction to today // var newTransaction = selectedCell.noteLabel.text // TODO: duplicate transaction here // sampleTransactions[0].insert(newTransaction!, atIndex: 0) tableView.reloadSections(NSIndexSet(index: 0), withRowAnimation: UITableViewRowAnimation.Automatic) break default: break } } } func handleDownSwipe(sender: UISwipeGestureRecognizer) { if sender.direction == .Down { let dvc = self.storyboard?.instantiateViewControllerWithIdentifier("QuickVC") as! QuickViewController let nc = UINavigationController(rootViewController: dvc) self.presentViewController(nc, animated: true, completion: nil) } } }
mit
b408e3d57f594543f0abd6c1286eb41e
37.142857
172
0.656202
5.96452
false
false
false
false
shajrawi/swift
stdlib/public/Darwin/ModelIO/ModelIO.swift
1
13074
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// @_exported import ModelIO import simd @available(macOS, introduced: 10.13) @available(iOS, introduced: 11.0) @available(tvOS, introduced: 11.0) extension MDLMatrix4x4Array { @nonobjc public var float4x4Array: [float4x4] { get { let count = elementCount var values = [float4x4](repeating: float4x4(), count: Int(count)) __getFloat4x4Array(&values[0], maxCount: count) return values } set(array) { __setFloat4x4(array, count: array.count) } } @nonobjc public var double4x4Array: [double4x4] { get { let count = elementCount var values = [double4x4](repeating: double4x4(), count: Int(count)) __getDouble4x4Array(&values[0], maxCount: count) return values } set(array) { __setDouble4x4(array, count: array.count) } } } @available(macOS, introduced: 10.13) @available(iOS, introduced: 11.0) @available(tvOS, introduced: 11.0) extension MDLAnimatedValue { @nonobjc public var times: [TimeInterval] { get { var times = [TimeInterval](repeating: 0, count: Int(timeSampleCount)) __getTimes(&times[0], maxCount: timeSampleCount) return times } } } @available(macOS, introduced: 10.13) @available(iOS, introduced: 11.0) @available(tvOS, introduced: 11.0) extension MDLAnimatedScalarArray { @nonobjc public func set(floatArray array:[Float], atTime time: TimeInterval){ __setFloat(array, count: array.count, atTime: time) } @nonobjc public func set(doubleArray array:[Double], atTime time: TimeInterval){ __setDouble(array, count: array.count, atTime: time) } @nonobjc public func floatArray(atTime time: TimeInterval) -> [Float] { var values = [Float](repeating: 0, count: Int(elementCount)) __getFloat(&values[0], maxCount: elementCount, atTime: time) return values } @nonobjc public func doubleArray(atTime time: TimeInterval) -> [Double] { var values = [Double](repeating: 0, count: Int(elementCount)) __getDouble(&values[0], maxCount: elementCount, atTime: time) return values } @nonobjc public func reset(floatArray array:[Float], atTimes times: [TimeInterval]){ __reset(with: array, count: array.count, atTimes: times, count: times.count) } @nonobjc public func reset(doubleArray array:[Double], atTimes times: [TimeInterval]){ __reset(with: array, count: array.count, atTimes: times, count: times.count) } @nonobjc public var floatArray: [Float] { get { let count = elementCount * timeSampleCount var values = [Float](repeating: 0, count: Int(count)) __getFloat(&values[0], maxCount: count) return values } } @nonobjc public var doubleArray: [Double] { get { let count = elementCount * timeSampleCount var values = [Double](repeating: 0, count: Int(count)) __getDouble(&values[0], maxCount: count) return values } } } @available(macOS, introduced: 10.13) @available(iOS, introduced: 11.0) @available(tvOS, introduced: 11.0) extension MDLAnimatedVector3Array { @nonobjc public func set(float3Array array:[SIMD3<Float>], atTime time: TimeInterval){ __setFloat3(array, count: array.count, atTime: time) } @nonobjc public func set(double3Array array:[SIMD3<Double>], atTime time: TimeInterval){ __setDouble3(array, count: array.count, atTime: time) } @nonobjc public func float3Array(atTime time: TimeInterval) -> [SIMD3<Float>] { var values = [SIMD3<Float>](repeating: SIMD3<Float>(), count: Int(elementCount)) __getFloat3Array(&values[0], maxCount: elementCount, atTime: time) return values } @nonobjc public func double3Array(atTime time: TimeInterval) -> [SIMD3<Double>] { var values = [SIMD3<Double>](repeating: SIMD3<Double>(), count: Int(elementCount)) __getDouble3Array(&values[0], maxCount: elementCount, atTime: time) return values } @nonobjc public func reset(float3Array array:[SIMD3<Float>], atTimes times: [TimeInterval]){ __reset(withFloat3Array: array, count: array.count, atTimes: times, count: times.count) } @nonobjc public func reset(double3Array array:[SIMD3<Double>], atTimes times: [TimeInterval]){ __reset(withDouble3Array: array, count: array.count, atTimes: times, count: times.count) } @nonobjc public var float3Array: [SIMD3<Float>] { get { let count = elementCount * timeSampleCount var values = [SIMD3<Float>](repeating: SIMD3<Float>(), count: Int(count)) __getFloat3Array(&values[0], maxCount: count) return values } } @nonobjc public var double3Array: [SIMD3<Double>] { get { let count = elementCount * timeSampleCount var values = [SIMD3<Double>](repeating: SIMD3<Double>(), count: Int(count)) __getDouble3Array(&values[0], maxCount: count) return values } } } @available(macOS, introduced: 10.13) @available(iOS, introduced: 11.0) @available(tvOS, introduced: 11.0) extension MDLAnimatedQuaternionArray { @nonobjc public func set(floatQuaternionArray array:[simd_quatf], atTime time: TimeInterval){ __setFloat(array, count: array.count, atTime: time) } @nonobjc public func set(doubleQuaternionArray array:[simd_quatd], atTime time: TimeInterval){ __setDouble(array, count: array.count, atTime: time) } @nonobjc public func floatQuaternionArray(atTime time: TimeInterval) -> [simd_quatf] { var values = [simd_quatf](repeating: simd_quatf(), count: Int(elementCount)) __getFloat(&values[0], maxCount: elementCount, atTime: time) return values } @nonobjc public func doubleQuaternionArray(atTime time: TimeInterval) -> [simd_quatd] { var values = [simd_quatd](repeating: simd_quatd(), count: Int(elementCount)) __getDouble(&values[0], maxCount: elementCount, atTime: time) return values } @nonobjc public func reset(floatQuaternionArray array:[simd_quatf], atTimes times: [TimeInterval]){ __reset(withFloat: array, count: array.count, atTimes: times, count: times.count) } @nonobjc public func reset(doubleQuaternionArray array:[simd_quatd], atTimes times: [TimeInterval]){ __reset(withDouble: array, count: array.count, atTimes: times, count: times.count) } @nonobjc public var floatQuaternionArray : [simd_quatf] { get { let count = elementCount * timeSampleCount var values = [simd_quatf](repeating: simd_quatf(), count: Int(count)) __getFloat(&values[0], maxCount: count) return values } } @nonobjc public var doubleQuaternionArray: [simd_quatd] { get { let count = elementCount * timeSampleCount var values = [simd_quatd](repeating: simd_quatd(), count: Int(count)) __getDouble(&values[0], maxCount: count) return values } } } @available(macOS, introduced: 10.13) @available(iOS, introduced: 11.0) @available(tvOS, introduced: 11.0) extension MDLAnimatedScalar { @nonobjc public func reset(floatArray array:[Float], atTimes times: [TimeInterval]){ __reset(withFloatArray: array, atTimes: times, count: times.count) } @nonobjc public func reset(doubleArray array:[Double], atTimes times: [TimeInterval]){ __reset(withDoubleArray: array, atTimes: times, count: times.count) } @nonobjc public var floatArray: [Float] { get { var values = [Float](repeating: 0, count: Int(timeSampleCount)) __getFloatArray(&values[0], maxCount: timeSampleCount) return values } } @nonobjc public var doubleArray: [Double] { get { var values = [Double](repeating: 0, count: Int(timeSampleCount)) __getDoubleArray(&values[0], maxCount: timeSampleCount) return values } } } @available(macOS, introduced: 10.13) @available(iOS, introduced: 11.0) @available(tvOS, introduced: 11.0) extension MDLAnimatedVector2 { @nonobjc public func reset(float2Array array:[SIMD2<Float>], atTimes times: [TimeInterval]){ __reset(withFloat2Array: array, atTimes: times, count: times.count) } @nonobjc public func reset(double2Array array:[SIMD2<Double>], atTimes times: [TimeInterval]){ __reset(withDouble2Array: array, atTimes: times, count: times.count) } @nonobjc public var float2Array: [SIMD2<Float>] { get { var values = [SIMD2<Float>](repeating: SIMD2<Float>(), count: Int(timeSampleCount)) __getFloat2Array(&values[0], maxCount: timeSampleCount) return values } } @nonobjc public var double2Array: [SIMD2<Double>] { get { var values = [SIMD2<Double>](repeating: SIMD2<Double>(), count: Int(timeSampleCount)) __getDouble2Array(&values[0], maxCount: timeSampleCount) return values } } } @available(macOS, introduced: 10.13) @available(iOS, introduced: 11.0) @available(tvOS, introduced: 11.0) extension MDLAnimatedVector3 { @nonobjc public func reset(float3Array array:[SIMD3<Float>], atTimes times: [TimeInterval]){ __reset(withFloat3Array: array, atTimes: times, count: times.count) } @nonobjc public func reset(double3Array array:[SIMD3<Double>], atTimes times: [TimeInterval]){ __reset(withDouble3Array: array, atTimes: times, count: times.count) } @nonobjc public var float3Array: [SIMD3<Float>] { get { var values = [SIMD3<Float>](repeating: SIMD3<Float>(), count: Int(timeSampleCount)) __getFloat3Array(&values[0], maxCount: timeSampleCount) return values } } @nonobjc public var double3Array: [SIMD3<Double>] { get { var values = [SIMD3<Double>](repeating: SIMD3<Double>(), count: Int(timeSampleCount)) __getDouble3Array(&values[0], maxCount: timeSampleCount) return values } } } @available(macOS, introduced: 10.13) @available(iOS, introduced: 11.0) @available(tvOS, introduced: 11.0) extension MDLAnimatedVector4 { @nonobjc public func reset(float4Array array:[SIMD4<Float>], atTimes times: [TimeInterval]){ __reset(withFloat4Array: array, atTimes: times, count: times.count) } @nonobjc public func reset(double4Array array:[SIMD4<Double>], atTimes times: [TimeInterval]){ __reset(withDouble4Array: array, atTimes: times, count: times.count) } @nonobjc public var float4Array: [SIMD4<Float>] { get { var values = [SIMD4<Float>](repeating: SIMD4<Float>(), count: Int(timeSampleCount)) __getFloat4Array(&values[0], maxCount: timeSampleCount) return values } } @nonobjc public var double4Array: [SIMD4<Double>] { get { var values = [SIMD4<Double>](repeating: SIMD4<Double>(), count: Int(timeSampleCount)) __getDouble4Array(&values[0], maxCount: timeSampleCount) return values } } } @available(macOS, introduced: 10.13) @available(iOS, introduced: 11.0) @available(tvOS, introduced: 11.0) extension MDLAnimatedMatrix4x4 { @nonobjc public func reset(float4x4Array array:[float4x4], atTimes times: [TimeInterval]){ __reset(withFloat4x4Array: array, atTimes: times, count: times.count) } @nonobjc public func reset(double4Array array:[double4x4], atTimes times: [TimeInterval]){ __reset(withDouble4x4Array: array, atTimes: times, count: times.count) } @nonobjc public var float4x4Array: [float4x4] { get { var values = [float4x4](repeating: float4x4(), count: Int(timeSampleCount)) __getFloat4x4Array(&values[0], maxCount: timeSampleCount) return values } } @nonobjc public var double4x4Array: [double4x4] { get { var values = [double4x4](repeating: double4x4(), count: Int(timeSampleCount)) __getDouble4x4Array(&values[0], maxCount: timeSampleCount) return values } } }
apache-2.0
02854207088d752a7eab35ec54a0272c
35.621849
104
0.626511
4.040173
false
false
false
false
ibm-bluemix-mobile-services/bms-clientsdk-cordova-plugin-core
src/ios/CDVBMSAnalytics.swift
1
11896
/* *     Copyright 2016 IBM Corp. *     Licensed under the Apache License, Version 2.0 (the "License"); *     you may not use this file except in compliance with the License. *     You may obtain a copy of the License at *     http://www.apache.org/licenses/LICENSE-2.0 *     Unless required by applicable law or agreed to in writing, software *     distributed under the License is distributed on an "AS IS" BASIS, *     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *     See the License for the specific language governing permissions and *     limitations under the License. */ import Foundation import BMSCore import BMSAnalytics @objc(CDVBMSAnalytics) @objcMembers class CDVBMSAnalytics : CDVPlugin { func setUserIdentity(_ command: CDVInvokedUrlCommand){ let userIdentity = command.arguments[0] as! String #if swift(>=3.0) self.commandDelegate!.run(inBackground: { Analytics.userIdentity = userIdentity let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: true) // call success callback self.commandDelegate!.send(pluginResult, callbackId: command.callbackId) }) #else self.commandDelegate!.runInBackground({ Analytics.userIdentity = userIdentity let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAsBool: true) // call success callback self.commandDelegate!.sendPluginResult(pluginResult, callbackId: command.callbackId) }) #endif } func enable(_ command: CDVInvokedUrlCommand) { #if swift(>=3.0) self.commandDelegate!.run(inBackground: { Analytics.isEnabled = true let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: true) // call success callback self.commandDelegate!.send(pluginResult, callbackId: command.callbackId) }) #else self.commandDelegate!.runInBackground({ Analytics.isEnabled = true let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAsBool: true) // call success callback self.commandDelegate!.sendPluginResult(pluginResult, callbackId: command.callbackId) }) #endif } func disable(_ command: CDVInvokedUrlCommand) { #if swift(>=3.0) self.commandDelegate!.run(inBackground: { Analytics.isEnabled = false let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: false) // call success callback self.commandDelegate!.send(pluginResult, callbackId: command.callbackId) }) #else self.commandDelegate!.runInBackground({ Analytics.isEnabled = false let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAsBool: false) // call success callback self.commandDelegate!.sendPluginResult(pluginResult, callbackId: command.callbackId) }) #endif } func isEnabled(_ command: CDVInvokedUrlCommand) { // has success, failure callbacks #if swift(>=3.0) self.commandDelegate!.run(inBackground: { let isEnabled = Analytics.isEnabled let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: isEnabled) // call success callback self.commandDelegate!.send(pluginResult, callbackId: command.callbackId) }) #else self.commandDelegate!.runInBackground({ Analytics.isEnabled = false let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAsBool: false) // call success callback self.commandDelegate!.sendPluginResult(pluginResult, callbackId: command.callbackId) }) #endif } func send(_ command: CDVInvokedUrlCommand) { #if swift(>=3.0) self.commandDelegate!.run(inBackground: { Analytics.send(completionHandler: { (response: Response?, error:Error?) in if (error != nil) { let pluginResult = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAs: false) self.commandDelegate!.send(pluginResult, callbackId:command.callbackId) } else { let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: true) self.commandDelegate!.send(pluginResult, callbackId:command.callbackId) } }) }) #else self.commandDelegate!.runInBackground({ Analytics.send(completionHandler: { (response: Response?, error:NSError?) in if (error != nil) { // process the error let pluginResult = CDVPluginResult(status: CDVCommandStatus_ERROR, messageAsBool:false) self.commandDelegate!.sendPluginResult(pluginResult, callbackId:command.callbackId) } else { // process success let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAsBool: true) self.commandDelegate!.sendPluginResult(pluginResult, callbackId:command.callbackId) } }) }) #endif } func initialize(_ command: CDVInvokedUrlCommand){ let appName = command.arguments[0] as! String let clientApiKey = command.arguments[1] as! String let hasUserContext = command.arguments[2] as! Bool var collectLocation = false var events:[Int] if !(command.arguments[4] is NSNull) { collectLocation = command.arguments[3] as! Bool events = command.arguments[4] as! [Int] } else { events = command.arguments[3] as! [Int] } var deviceEvents = [DeviceEvent]() var lifecycleFlag: Bool = false var networkFlag:Bool = false var noneFlag:Bool = false for i in 0..<events.count { switch(events[i]){ case 0: noneFlag = true break; // NONE should not enable any deviceEvents case 1: lifecycleFlag = true; networkFlag = true; break; case 2: lifecycleFlag = true deviceEvents.append(.lifecycle) break case 3: networkFlag = true deviceEvents.append(.network) break default: lifecycleFlag = true deviceEvents.append(.lifecycle) break } } #if swift(>=3.0) self.commandDelegate!.run(inBackground: { if(noneFlag){ Analytics.initialize(appName: appName, apiKey: clientApiKey, hasUserContext: hasUserContext,collectLocation: collectLocation) } else if (lifecycleFlag && networkFlag){ Analytics.initialize(appName: appName, apiKey: clientApiKey, hasUserContext: hasUserContext,collectLocation: collectLocation, deviceEvents: .lifecycle, .network) } else if(networkFlag) { Analytics.initialize(appName: appName, apiKey: clientApiKey, hasUserContext: hasUserContext,collectLocation: collectLocation, deviceEvents: .network) } else if(lifecycleFlag){ Analytics.initialize(appName: appName, apiKey: clientApiKey, hasUserContext: hasUserContext, collectLocation: collectLocation, deviceEvents: .lifecycle) } let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAs:true) self.commandDelegate!.send(pluginResult, callbackId:command.callbackId) }) #else self.commandDelegate!.runInBackground({ if(noneFlag){ Analytics.initialize(appName: appName, apiKey: clientApiKey, hasUserContext: hasUserContext,collectLocation: collectLocation) } else if (lifecycleFlag && networkFlag){ Analytics.initialize(appName: appName, apiKey: clientApiKey, hasUserContext: hasUserContext, collectLocation: collectLocation, deviceEvents: .lifecycle, .network) } else if(lifecycleFlag){ Analytics.initialize(appName: appName, apiKey: clientApiKey, hasUserContext: hasUserContext, collectLocation: collectLocation, deviceEvents: .lifecycle) } else if(networkFlag) { Analytics.initialize(appName: appName, apiKey: clientApiKey, hasUserContext: hasUserContext, collectLocation: collectLocation, deviceEvents: .network) } let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAsBool:true) self.commandDelegate!.sendPluginResult(pluginResult, callbackId:command.callbackId) }) #endif } func log(_ command: CDVInvokedUrlCommand) { let meta = command.arguments[0] as! Dictionary<String, Any> #if swift(>=3.0) self.commandDelegate!.run(inBackground: { Analytics.log(metadata: meta) let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAs:true) self.commandDelegate!.send(pluginResult, callbackId:command.callbackId) }) #else self.commandDelegate!.runInBackground({ Analytics.log(metadata: (meta as? [String: AnyObject])!) let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAsBool:true) self.commandDelegate!.sendPluginResult(pluginResult, callbackId:command.callbackId) }) #endif } func logLocation(_ command: CDVInvokedUrlCommand) { #if swift(>=3.0) // self.commandDelegate!.run(inBackground: { Analytics.logLocation() let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAs:true) self.commandDelegate!.send(pluginResult, callbackId:command.callbackId) // }) #else // self.commandDelegate!.runInBackground({ Analytics.logLocation() let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAsBool:true) self.commandDelegate!.sendPluginResult(pluginResult, callbackId:command.callbackId) // }) #endif } func triggerFeedbackMode(_ command: CDVInvokedUrlCommand){ #if swift(>=3.0) self.commandDelegate!.run(inBackground: { DispatchQueue.main.async { BMSAnalytics.callersUIViewController = self.viewController Analytics.triggerFeedbackMode() } let pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: true) // call success callback self.commandDelegate!.send(pluginResult, callbackId: command.callbackId) }) #endif } }
apache-2.0
270ca5eba1362155b799765cfa83d30d
43.777358
186
0.585201
5.677512
false
false
false
false
honghaoz/CrackingTheCodingInterview
Swift/LeetCode/Array/283_Move Zeroes.swift
1
1261
// 283. Move Zeroes // https://leetcode.com/problems/move-zeroes/ // LeetCode // // Created by Honghao Zhang on 2016-10-24. // Copyright © 2016 Honghaoz. All rights reserved. // //Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. // //For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0]. // //Note: //You must do this in-place without making a copy of the array. //Minimize the total number of operations. import Foundation class Num283_MoveZeros: Solution { func moveZeroes(_ nums: inout [Int]) { guard nums.count > 0 else { return } var lastNonZeroIndex: Int = -1 for i in 0..<nums.count { let num = nums[i] if num == 0 { continue } else { lastNonZeroIndex += 1 nums[lastNonZeroIndex] = num } } while lastNonZeroIndex + 1 < nums.count { lastNonZeroIndex += 1 nums[lastNonZeroIndex] = 0 } } func test() { var nums = [0, 1, 0, 3, 12] moveZeroes(&nums) assert(nums == [1, 3, 12, 0, 0]) } }
mit
64a7cf784b945fa3b0eb36f5975ad895
27
135
0.559524
3.738872
false
false
false
false
AbelSu131/ios-charts
Charts/Classes/Renderers/ChartXAxisRendererHorizontalBarChart.swift
1
10525
// // ChartXAxisRendererHorizontalBarChart.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 ChartXAxisRendererHorizontalBarChart: ChartXAxisRendererBarChart { public override init(viewPortHandler: ChartViewPortHandler, xAxis: ChartXAxis, transformer: ChartTransformer!, chart: BarChartView) { super.init(viewPortHandler: viewPortHandler, xAxis: xAxis, transformer: transformer, chart: chart); } public override func computeAxis(#xValAverageLength: Double, xValues: [String?]) { _xAxis.values = xValues; var longest = _xAxis.getLongestLabel() as NSString; var longestSize = longest.sizeWithAttributes([NSFontAttributeName: _xAxis.labelFont]); _xAxis.labelWidth = floor(longestSize.width + _xAxis.xOffset * 3.5); _xAxis.labelHeight = longestSize.height; } public override func renderAxisLabels(#context: CGContext) { if (!_xAxis.isEnabled || !_xAxis.isDrawLabelsEnabled || _chart.data === nil) { return; } var xoffset = _xAxis.xOffset; if (_xAxis.labelPosition == .Top) { drawLabels(context: context, pos: viewPortHandler.contentRight + xoffset, align: .Left); } else if (_xAxis.labelPosition == .Bottom) { drawLabels(context: context, pos: viewPortHandler.contentLeft - xoffset, align: .Right); } else if (_xAxis.labelPosition == .BottomInside) { drawLabels(context: context, pos: viewPortHandler.contentLeft + xoffset, align: .Left); } else if (_xAxis.labelPosition == .TopInside) { drawLabels(context: context, pos: viewPortHandler.contentRight - xoffset, align: .Right); } else { // BOTH SIDED drawLabels(context: context, pos: viewPortHandler.contentLeft, align: .Left); drawLabels(context: context, pos: viewPortHandler.contentRight, align: .Left); } } /// draws the x-labels on the specified y-position internal func drawLabels(#context: CGContext, pos: CGFloat, align: NSTextAlignment) { var labelFont = _xAxis.labelFont; var labelTextColor = _xAxis.labelTextColor; // pre allocate to save performance (dont allocate in loop) var position = CGPoint(x: 0.0, y: 0.0); var bd = _chart.data as! BarChartData; var step = bd.dataSetCount; for (var i = _minX, maxX = min(_maxX + 1, _xAxis.values.count); i < maxX; i += _xAxis.axisLabelModulus) { var label = _xAxis.values[i]; if (label == nil) { continue; } position.x = 0.0; position.y = CGFloat(i * step) + CGFloat(i) * bd.groupSpace + bd.groupSpace / 2.0; // consider groups (center label for each group) if (step > 1) { position.y += (CGFloat(step) - 1.0) / 2.0; } transformer.pointValueToPixel(&position); if (viewPortHandler.isInBoundsY(position.y)) { ChartUtils.drawText(context: context, text: label!, point: CGPoint(x: pos, y: position.y - _xAxis.labelHeight / 2.0), align: align, attributes: [NSFontAttributeName: labelFont, NSForegroundColorAttributeName: labelTextColor]); } } } private var _gridLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint()); public override func renderGridLines(#context: CGContext) { if (!_xAxis.isEnabled || !_xAxis.isDrawGridLinesEnabled || _chart.data === nil) { return; } CGContextSaveGState(context); 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); } var position = CGPoint(x: 0.0, y: 0.0); var bd = _chart.data as! BarChartData; // take into consideration that multiple DataSets increase _deltaX var step = bd.dataSetCount; for (var i = _minX, maxX = min(_maxX + 1, _xAxis.values.count); i < maxX; i += _xAxis.axisLabelModulus) { position.x = 0.0; position.y = CGFloat(i * step) + CGFloat(i) * bd.groupSpace - 0.5; transformer.pointValueToPixel(&position); if (viewPortHandler.isInBoundsY(position.y)) { _gridLineSegmentsBuffer[0].x = viewPortHandler.contentLeft; _gridLineSegmentsBuffer[0].y = position.y; _gridLineSegmentsBuffer[1].x = viewPortHandler.contentRight; _gridLineSegmentsBuffer[1].y = position.y; CGContextStrokeLineSegments(context, _gridLineSegmentsBuffer, 2); } } CGContextRestoreGState(context); } private var _axisLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint()); public override func renderAxisLine(#context: CGContext) { 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.contentRight; _axisLineSegmentsBuffer[0].y = viewPortHandler.contentTop; _axisLineSegmentsBuffer[1].x = viewPortHandler.contentRight; _axisLineSegmentsBuffer[1].y = viewPortHandler.contentBottom; CGContextStrokeLineSegments(context, _axisLineSegmentsBuffer, 2); } if (_xAxis.labelPosition == .Bottom || _xAxis.labelPosition == .BottomInside || _xAxis.labelPosition == .BothSided) { _axisLineSegmentsBuffer[0].x = viewPortHandler.contentLeft; _axisLineSegmentsBuffer[0].y = viewPortHandler.contentTop; _axisLineSegmentsBuffer[1].x = viewPortHandler.contentLeft; _axisLineSegmentsBuffer[1].y = viewPortHandler.contentBottom; CGContextStrokeLineSegments(context, _axisLineSegmentsBuffer, 2); } CGContextRestoreGState(context); } private var _limitLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint()); public override func renderLimitLines(#context: CGContext) { var limitLines = _xAxis.limitLines; if (limitLines.count == 0) { return; } CGContextSaveGState(context); var trans = transformer.valueToPixelMatrix; var position = CGPoint(x: 0.0, y: 0.0); for (var i = 0; i < limitLines.count; i++) { var l = limitLines[i]; position.x = 0.0; position.y = CGFloat(l.limit); position = CGPointApplyAffineTransform(position, trans); _limitLineSegmentsBuffer[0].x = viewPortHandler.contentLeft; _limitLineSegmentsBuffer[0].y = position.y; _limitLineSegmentsBuffer[1].x = viewPortHandler.contentRight; _limitLineSegmentsBuffer[1].y = position.y; CGContextSetStrokeColorWithColor(context, l.lineColor.CGColor); CGContextSetLineWidth(context, l.lineWidth); if (l.lineDashLengths != nil) { CGContextSetLineDash(context, l.lineDashPhase, l.lineDashLengths!, l.lineDashLengths!.count); } else { CGContextSetLineDash(context, 0.0, nil, 0); } CGContextStrokeLineSegments(context, _limitLineSegmentsBuffer, 2); var label = l.label; // if drawing the limit-value label is enabled if (count(label) > 0) { var labelLineHeight = l.valueFont.lineHeight; let add = CGFloat(4.0); var xOffset: CGFloat = add; var yOffset: CGFloat = l.lineWidth + labelLineHeight / 2.0; if (l.labelPosition == .Right) { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: viewPortHandler.contentRight - xOffset, y: position.y - yOffset - labelLineHeight), align: .Right, attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor]); } else { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: viewPortHandler.contentLeft + xOffset, y: position.y - yOffset - labelLineHeight), align: .Left, attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor]); } } } CGContextRestoreGState(context); } }
apache-2.0
4d970385b5ee7ab2afb2937c61e688cb
36.459075
242
0.566176
5.41967
false
false
false
false
lyp1992/douyu-Swift
YPTV/Pods/Kingfisher/Sources/Filter.swift
7
5298
// // Filter.swift // Kingfisher // // Created by Wei Wang on 2016/08/31. // // Copyright (c) 2018 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import CoreImage import Accelerate // Reuse the same CI Context for all CI drawing. private let ciContext = CIContext(options: nil) /// Transformer method which will be used in to provide a `Filter`. public typealias Transformer = (CIImage) -> CIImage? /// Supply a filter to create an `ImageProcessor`. public protocol CIImageProcessor: ImageProcessor { var filter: Filter { get } } extension CIImageProcessor { public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? { switch item { case .image(let image): return image.kf.apply(filter) case .data(_): return (DefaultImageProcessor.default >> self).process(item: item, options: options) } } } /// Wrapper for a `Transformer` of CIImage filters. public struct Filter { let transform: Transformer public init(tranform: @escaping Transformer) { self.transform = tranform } /// Tint filter which will apply a tint color to images. public static var tint: (Color) -> Filter = { color in Filter { input in let colorFilter = CIFilter(name: "CIConstantColorGenerator")! colorFilter.setValue(CIColor(color: color), forKey: kCIInputColorKey) let colorImage = colorFilter.outputImage let filter = CIFilter(name: "CISourceOverCompositing")! filter.setValue(colorImage, forKey: kCIInputImageKey) filter.setValue(input, forKey: kCIInputBackgroundImageKey) #if swift(>=4.0) return filter.outputImage?.cropped(to: input.extent) #else return filter.outputImage?.cropping(to: input.extent) #endif } } public typealias ColorElement = (CGFloat, CGFloat, CGFloat, CGFloat) /// Color control filter which will apply color control change to images. public static var colorControl: (ColorElement) -> Filter = { arg -> Filter in let (brightness, contrast, saturation, inputEV) = arg return Filter { input in let paramsColor = [kCIInputBrightnessKey: brightness, kCIInputContrastKey: contrast, kCIInputSaturationKey: saturation] let paramsExposure = [kCIInputEVKey: inputEV] #if swift(>=4.0) let blackAndWhite = input.applyingFilter("CIColorControls", parameters: paramsColor) return blackAndWhite.applyingFilter("CIExposureAdjust", parameters: paramsExposure) #else let blackAndWhite = input.applyingFilter("CIColorControls", withInputParameters: paramsColor) return blackAndWhite.applyingFilter("CIExposureAdjust", withInputParameters: paramsExposure) #endif } } } extension Kingfisher where Base: Image { /// Apply a `Filter` containing `CIImage` transformer to `self`. /// /// - parameter filter: The filter used to transform `self`. /// /// - returns: A transformed image by input `Filter`. /// /// - Note: Only CG-based images are supported. If any error happens during transforming, `self` will be returned. public func apply(_ filter: Filter) -> Image { guard let cgImage = cgImage else { assertionFailure("[Kingfisher] Tint image only works for CG-based image.") return base } let inputImage = CIImage(cgImage: cgImage) guard let outputImage = filter.transform(inputImage) else { return base } guard let result = ciContext.createCGImage(outputImage, from: outputImage.extent) else { assertionFailure("[Kingfisher] Can not make an tint image within context.") return base } #if os(macOS) return fixedForRetinaPixel(cgImage: result, to: size) #else return Image(cgImage: result, scale: base.scale, orientation: base.imageOrientation) #endif } }
mit
841014b7006deba7b05ea9bdefda7002
37.671533
118
0.655342
4.865014
false
false
false
false
openbuild-sheffield/jolt
Sources/OpenbuildExtensionPerfect/model.ResponseModel500NoResponseHandler.swift
1
1295
import PerfectLib public class ResponseModel500NoResponseHandler: JSONConvertibleObject, DocumentationProtocol { static let registerName = "responseModel500NoResponseHandler" public var error: Bool = true public var message: String = "Internal server error. This has been logged." public var messages: [String: String] = ["response_handler": "The developer did not provide a response handler."] public override func setJSONValues(_ values: [String : Any]) { self.error = getJSONValue(named: "error", from: values, defaultValue: true) self.message = getJSONValue(named: "message", from: values, defaultValue: "Internal server error. This has been logged.") self.messages = getJSONValue(named: "messages", from: values, defaultValue: ["response_handler": "The developer did not provide a response handler."]) } public override func getJSONValues() -> [String : Any] { return [ JSONDecoding.objectIdentifierKey: ResponseModel500NoResponseHandler.registerName, "error": error, "message": message, "messages": messages ] } public static func describeRAML() -> [String] { //TODO / FIXME return ["ResponseModel500NoResponseHandler TODO / FIXME"] } }
gpl-2.0
653902add4b67d03cc03d6141ce061b8
40.806452
158
0.683398
4.726277
false
false
false
false
wikimedia/wikipedia-ios
Wikipedia/Code/NavigationEventsFunnel.swift
1
4488
import Foundation @objc(WMFNavigationEventsFunnel) final class NavigationEventsFunnel: EventLoggingFunnel, EventLoggingStandardEventProviding { enum Action: String, Codable { case explore case places case saved case savedAll = "saved_all" case savedLists = "saved_lists" case history case search case settingsOpenNav = "setting_open_nav" case settingsOpenExplore = "setting_open_explore" case settingsAccount = "setting_account" case settingsClose = "setting_close" case settingsFundraise = "setting_fundraise" case settingsLanguages = "setting_languages" case settingsSearch = "setting_search" case settingsExploreFeed = "setting_explorefeed" case settingsNotifications = "setting_notifications" case settingsReadPrefs = "setting_read_prefs" case settingsStorageSync = "setting_storagesync" case settingsReadDanger = "setting_read_danger" case settingsClearData = "setting_cleardata" case settingsPrivacy = "setting_privacy" case settingsTOS = "setting_tos" case settingsUsageReports = "setting_usage_reports" case settingsRate = "setting_rate" case settingsHelp = "setting_help" case settingsAbout = "setting_about" } @objc static let shared = NavigationEventsFunnel() private override init() { super.init(schema: "MobileWikiAppiOSNavigationEvents", version: 21426269) } private func event(action: Action) -> [String: Any] { let event: [String: Any] = ["action": action.rawValue, "primary_language": primaryLanguage(), "is_anon": isAnon] return event } override func preprocessData(_ eventData: [AnyHashable: Any]) -> [AnyHashable: Any] { return wholeEvent(with: eventData) } @objc func logTappedExplore() { log(event(action: .explore)) } @objc func logTappedPlaces() { log(event(action: .places)) } @objc func logTappedSaved() { log(event(action: .saved)) } @objc func logTappedHistory() { log(event(action: .history)) } @objc func logTappedSearch() { log(event(action: .search)) } @objc func logTappedSettingsFromTabBar() { log(event(action: .settingsOpenNav)) } @objc func logTappedSettingsFromExplore() { log(event(action: .settingsOpenExplore)) } func logTappedSavedAllArticles() { log(event(action: .savedAll)) } func logTappedSavedReadingLists() { log(event(action: .savedLists)) } @objc func logTappedSettingsCloseButton() { log(event(action: .settingsClose)) } @objc func logTappedSettingsLoginLogout() { log(event(action: .settingsAccount)) } @objc func logTappedSettingsSupportWikipedia() { log(event(action: .settingsFundraise)) } @objc func logTappedSettingsLanguages() { log(event(action: .settingsLanguages)) } @objc func logTappedSettingsSearch() { log(event(action: .settingsSearch)) } @objc func logTappedSettingsExploreFeed() { log(event(action: .settingsExploreFeed)) } @objc func logTappedSettingsNotifications() { log(event(action: .settingsNotifications)) } @objc func logTappedSettingsReadingPreferences() { log(event(action: .settingsReadPrefs)) } @objc func logTappedSettingsArticleStorageAndSyncing() { log(event(action: .settingsStorageSync)) } @objc func logTappedSettingsReadingListDangerZone() { log(event(action: .settingsReadDanger)) } @objc func logTappedSettingsClearCachedData() { log(event(action: .settingsClearData)) } @objc func logTappedSettingsPrivacyPolicy() { log(event(action: .settingsPrivacy)) } @objc func logTappedSettingsTermsOfUse() { log(event(action: .settingsTOS)) } @objc func logTappedSettingsSendUsageReports() { log(event(action: .settingsUsageReports)) } @objc func logTappedSettingsRateTheApp() { log(event(action: .settingsRate)) } @objc func logTappedSettingsHelp() { log(event(action: .settingsHelp)) } @objc func logTappedSettingsAbout() { log(event(action: .settingsAbout)) } }
mit
32d75e04970644beb062651d64bb24d8
28.526316
120
0.635918
4.39569
false
false
false
false
wikimedia/wikipedia-ios
WMF Framework/ArticleCacheController.swift
1
9494
import Foundation public final class ArticleCacheController: CacheController { init(moc: NSManagedObjectContext, imageCacheController: ImageCacheController, session: Session, configuration: Configuration, preferredLanguageDelegate: WMFPreferredLanguageInfoProvider) { let articleFetcher = ArticleFetcher(session: session, configuration: configuration) let imageInfoFetcher = MWKImageInfoFetcher(session: session, configuration: configuration) imageInfoFetcher.preferredLanguageDelegate = preferredLanguageDelegate let cacheFileWriter = CacheFileWriter(fetcher: articleFetcher) let articleDBWriter = ArticleCacheDBWriter(articleFetcher: articleFetcher, cacheBackgroundContext: moc, imageController: imageCacheController, imageInfoFetcher: imageInfoFetcher) super.init(dbWriter: articleDBWriter, fileWriter: cacheFileWriter) } enum ArticleCacheControllerError: Error { case invalidDBWriterType } // syncs already cached resources with mobile-html-offline-resources and media-list endpoints (caches new urls, removes old urls) public func syncCachedResources(url: URL, groupKey: CacheController.GroupKey, groupCompletion: @escaping GroupCompletionBlock) { guard let articleDBWriter = dbWriter as? ArticleCacheDBWriter else { groupCompletion(.failure(error: ArticleCacheControllerError.invalidDBWriterType)) return } articleDBWriter.syncResources(url: url, groupKey: groupKey) { (result) in switch result { case .success(let syncResult): let group = DispatchGroup() var successfulAddKeys: [CacheController.UniqueKey] = [] var failedAddKeys: [(CacheController.UniqueKey, Error)] = [] var successfulRemoveKeys: [CacheController.UniqueKey] = [] var failedRemoveKeys: [(CacheController.UniqueKey, Error)] = [] // add new urls in file system for urlRequest in syncResult.addURLRequests { guard let uniqueKey = self.fileWriter.uniqueFileNameForURLRequest(urlRequest), urlRequest.url != nil else { continue } group.enter() self.fileWriter.add(groupKey: groupKey, urlRequest: urlRequest) { (fileWriterResult) in switch fileWriterResult { case .success(let response, _): self.dbWriter.markDownloaded(urlRequest: urlRequest, response: response) { (dbWriterResult) in defer { group.leave() } switch dbWriterResult { case .success: successfulAddKeys.append(uniqueKey) case .failure(let error): failedAddKeys.append((uniqueKey, error)) } } case .failure(let error): defer { group.leave() } failedAddKeys.append((uniqueKey, error)) } } } // remove old urls in file system for key in syncResult.removeItemKeyAndVariants { guard let uniqueKey = self.fileWriter.uniqueFileNameForItemKey(key.itemKey, variant: key.variant) else { continue } group.enter() self.fileWriter.remove(itemKey: key.itemKey, variant: key.variant) { (fileWriterResult) in switch fileWriterResult { case .success: self.dbWriter.remove(itemAndVariantKey: key) { (dbWriterResult) in defer { group.leave() } switch dbWriterResult { case .success: successfulRemoveKeys.append(uniqueKey) case .failure(let error): failedRemoveKeys.append((uniqueKey, error)) } } case .failure(let error): defer { group.leave() } failedRemoveKeys.append((uniqueKey, error)) } } } group.notify(queue: DispatchQueue.global(qos: .userInitiated)) { if let error = failedAddKeys.first?.1 ?? failedRemoveKeys.first?.1 { groupCompletion(.failure(error: CacheControllerError.atLeastOneItemFailedInSync(error))) return } let successKeys = successfulAddKeys + successfulRemoveKeys groupCompletion(.success(uniqueKeys: successKeys)) } case .failure(let error): groupCompletion(.failure(error: error)) } } } public func cacheFromMigration(desktopArticleURL: URL, content: String, completionHandler: @escaping ((Error?) -> Void)) { // articleURL should be desktopURL guard let articleDBWriter = dbWriter as? ArticleCacheDBWriter else { completionHandler(ArticleCacheControllerError.invalidDBWriterType) return } cacheBundledResourcesIfNeeded(desktopArticleURL: desktopArticleURL) { (cacheBundledError) in articleDBWriter.addMobileHtmlURLForMigration(desktopArticleURL: desktopArticleURL, success: { urlRequest in self.fileWriter.addMobileHtmlContentForMigration(content: content, urlRequest: urlRequest, success: { articleDBWriter.markDownloaded(urlRequest: urlRequest, response: nil) { (result) in switch result { case .success: if cacheBundledError == nil { completionHandler(nil) } else { completionHandler(cacheBundledError) } case .failure(let error): completionHandler(error) } } }) { (error) in completionHandler(error) } }) { (error) in completionHandler(error) } } } private func bundledResourcesAreCached() -> Bool { guard let articleDBWriter = dbWriter as? ArticleCacheDBWriter else { return false } return articleDBWriter.bundledResourcesAreCached() } private func cacheBundledResourcesIfNeeded(desktopArticleURL: URL, completionHandler: @escaping ((Error?) -> Void)) { // articleURL should be desktopURL guard let articleDBWriter = dbWriter as? ArticleCacheDBWriter else { completionHandler(ArticleCacheControllerError.invalidDBWriterType) return } if !articleDBWriter.bundledResourcesAreCached() { articleDBWriter.addBundledResourcesForMigration(desktopArticleURL: desktopArticleURL) { (result) in switch result { case .success(let requests): self.fileWriter.addBundledResourcesForMigration(urlRequests: requests, success: { (_) in let bulkRequests = requests.map { ArticleCacheDBWriter.BulkMarkDownloadRequest(urlRequest: $0, response: nil) } articleDBWriter.markDownloaded(requests: bulkRequests) { (result) in switch result { case .success: completionHandler(nil) case .failure(let error): completionHandler(error) } } }) { (error) in completionHandler(error) } case .failure(let error): completionHandler(error) } } } else { completionHandler(nil) } } }
mit
46054b3dd6d850aaef93470c5b535b4f
44.644231
192
0.484517
6.766928
false
false
false
false
lucasmpaim/EasyRest
Sources/EasyRest/Classes/API/APIBuilder.swift
1
4493
// // APIBuilder.swift // RestClient // // Created by Guizion Labs on 10/03/16. // Copyright © 2016 Guizion Labs. All rights reserved. // import Foundation import Alamofire open class APIBuilder <T> where T: Codable { var path: String var queryParams: [String: String]? var pathParams: [String: Any]? var bodyParams: [String: Any]? var headers: [String: String]? var method: HTTPMethod? var cancelToken: CancelationToken<T>? var logger: Loggable? var interceptors: [Interceptor] = [] let defaultInterceptors: [Interceptor.Type] = [ CurlInterceptor.self, LoggerInterceptor.self ] public init(basePath: String) { self.path = basePath } public init() { self.path = "" //Constante } open func resource(_ resourcePath: String, method: HTTPMethod) -> Self { self.path.append(resourcePath) self.method = method return self } open func cancelToken(token: CancelationToken<T>) -> Self { cancelToken = token return self } open func addInterceptor(_ interceptor: Interceptor) -> Self { interceptors.append(interceptor) return self } open func addInterceptors(_ interceptors: [Interceptor]) -> Self { for interceptor in interceptors { self.interceptors.append(interceptor) } return self } open func logger(_ logger: Logger) -> Self { self.logger = logger return self } open func addQueryParams(_ queryParams : [String: CustomStringConvertible?]) -> Self { if self.queryParams == nil { self.queryParams = [:] } queryParams.forEach { if let value = $1 { self.queryParams![$0] = "\(value)" } } return self } open func addHeaders(_ headers: [String: String]) -> Self{ if self.headers == nil { self.headers = headers return self } for (key, value) in headers { self.headers![key] = value } return self } open func addParameteres(_ parameters: [ParametersType : Any?]) throws { for (type, obj) in parameters { let params = try convertParameters(obj) switch type { case .body, .multiPart: _ = addBodyParameters(params) case .path: self.pathParams = params case .query: if let queryParameters = params as? [String: String] { _ = addQueryParams(queryParameters) } case .header: guard let headers = params as? [String: String] else { return } _ = self.addHeaders(headers) } } } open func addBodyParameters<T: Encodable>(bodyParam: T) -> Self { bodyParams = bodyParam.dictionary return self } open func addBodyParameters(_ bodyParams : [String: Any]) -> Self { if self.bodyParams == nil{ self.bodyParams = bodyParams return self } for (key, value) in bodyParams { self.bodyParams![key] = value } return self } open func build() -> API<T> { assert(method != nil, "method not can be empty") if let pathParams = self.pathParams { self.path = self.path.replacePathLabels(pathParams) } let path = URL(string: self.path) assert(path?.scheme != nil && path?.host != nil, "Invalid URL: \(self.path)") for interceptorType in defaultInterceptors.reversed() { self.interceptors.insert(interceptorType.init(), at: 0) } let api = API<T>(path: path!, method: self.method!, queryParams: queryParams, bodyParams: bodyParams, headers: headers, interceptors: self.interceptors, cancelToken: cancelToken) api.logger = self.logger return api } open func convertParameters(_ obj: Any?) throws -> [String: Any]{ if let _obj = obj as? [String: AnyObject] { return _obj } else if let _obj = obj as? Encodable { return _obj.dictionary! } throw RestError(rawValue: RestErrorType.invalidType.rawValue) } }
mit
588bf048689ee975f920b37f847dc9f9
27.43038
186
0.546972
4.684046
false
false
false
false
philipgreat/b2b-swift-app
B2BSimpleApp/B2BSimpleApp/ContractPrice.swift
1
2265
//Domain B2B/ContractPrice/ import Foundation import ObjectMapper //Use this to generate Object import SwiftyJSON //Use this to verify the JSON Object struct ContractPrice{ var id : String? var contractId : String? var sku : Sku? var price : Int? var review : ContractPriceReview? var approval : ContractPriceApproval? var version : Int? init(){ //lazy load for all the properties //This is good for UI applications as it might saves RAM which is very expensive in mobile devices } static var CLASS_VERSION = "1" //This value is for serializer like message pack to identify the versions match between //local and remote object. } extension ContractPrice: Mappable{ //Confirming to the protocol Mappable of ObjectMapper //Reference on https://github.com/Hearst-DD/ObjectMapper/ init?(_ map: Map){ } mutating func mapping(map: Map) { //Map each field to json fields id <- map["id"] contractId <- map["contractId"] sku <- map["sku"] price <- map["price"] review <- map["review"] approval <- map["approval"] version <- map["version"] } } extension ContractPrice:CustomStringConvertible{ //Confirming to the protocol CustomStringConvertible of Foundation var description: String{ //Need to find out a way to improve this method performance as this method might called to //debug or log, using + is faster than \(var). var result = "contract_price{"; if id != nil { result += "\tid='\(id!)'" } if contractId != nil { result += "\tcontract_id='\(contractId!)'" } if sku != nil { result += "\tsku='\(sku!)'" } if price != nil { result += "\tprice='\(price!)'" } if review != nil { result += "\treview='\(review!)'" } if approval != nil { result += "\tapproval='\(approval!)'" } if version != nil { result += "\tversion='\(version!)'" } result += "}" return result } }
mit
82215a3b6f94d3b2cc3589f679616029
22.354839
100
0.548786
3.787625
false
false
false
false
dtrauger/Charts
Source/Charts/Renderers/AxisRendererBase.swift
1
7077
// // AxisRendererBase.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics @objc(ChartAxisRendererBase) open class AxisRendererBase: Renderer { /// base axis this axis renderer works with open var axis: AxisBase? /// transformer to transform values to screen pixels and return open var transformer: Transformer? public override init() { super.init() } public init(viewPortHandler: ViewPortHandler?, transformer: Transformer?, axis: AxisBase?) { super.init(viewPortHandler: viewPortHandler) self.transformer = transformer self.axis = axis } /// Draws the axis labels on the specified context open func renderAxisLabels(context: CGContext) { fatalError("renderAxisLabels() cannot be called on AxisRendererBase") } /// Draws the grid lines belonging to the axis. open func renderGridLines(context: CGContext) { fatalError("renderGridLines() cannot be called on AxisRendererBase") } /// Draws the line that goes alongside the axis. open func renderAxisLine(context: CGContext) { fatalError("renderAxisLine() cannot be called on AxisRendererBase") } /// Draws the LimitLines associated with this axis to the screen. open func renderLimitLines(context: CGContext) { fatalError("renderLimitLines() cannot be called on AxisRendererBase") } /// Computes the axis values. /// - parameter min: the minimum value in the data object for this axis /// - parameter max: the maximum value in the data object for this axis open func computeAxis(min: Double, max: Double, inverted: Bool) { var min = min, max = max if let transformer = self.transformer { // calculate the starting and entry point of the y-labels (depending on zoom / contentrect bounds) if let viewPortHandler = viewPortHandler { if viewPortHandler.contentWidth > 10.0 && !viewPortHandler.isFullyZoomedOutY { let p1 = transformer.valueForTouchPoint(CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentTop)) let p2 = transformer.valueForTouchPoint(CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentBottom)) if !inverted { min = Double(p2.y) max = Double(p1.y) } else { min = Double(p1.y) max = Double(p2.y) } } } } computeAxisValues(min: min, max: max) } /// Sets up the axis values. Computes the desired number of labels between the two given extremes. open func computeAxisValues(min: Double, max: Double) { guard let axis = self.axis else { return } var yMin = min var yMax = max if yMin.isNaN { yMin = 0 } if yMax.isNaN { yMax = 1 } let labelCount = axis.labelCount let range = abs(yMax - yMin) if labelCount == 0 || range <= 0 || range.isInfinite { axis.entries = [Double]() axis.centeredEntries = [Double]() return } // Find out how much spacing (in y value space) between axis values let rawInterval = range / Double(labelCount) var interval = ChartUtils.roundToNextSignificant(number: Double(rawInterval)) // If granularity is enabled, then do not allow the interval to go below specified granularity. // This is used to avoid repeated values when rounding values for display. if axis.granularityEnabled { interval = interval < axis.granularity ? axis.granularity : interval } // Normalize interval let intervalMagnitude = ChartUtils.roundToNextSignificant(number: pow(10.0, Double(Int(log10(interval))))) let intervalSigDigit = Int(interval / intervalMagnitude) if intervalSigDigit > 5 { // Use one order of magnitude higher, to avoid intervals like 0.9 or 90 interval = floor(10.0 * Double(intervalMagnitude)) } var n = axis.centerAxisLabelsEnabled ? 1 : 0 // force label count if axis.isForceLabelsEnabled { interval = Double(range) / Double(labelCount - 1) // Ensure stops contains at least n elements. axis.entries.removeAll(keepingCapacity: true) axis.entries.reserveCapacity(labelCount) var v = yMin for _ in 0 ..< labelCount { axis.entries.append(v) v += interval } n = labelCount } else { // no forced count var first = interval == 0.0 ? 0.0 : ceil(yMin / interval) * interval if axis.centerAxisLabelsEnabled { first -= interval } let last = interval == 0.0 ? 0.0 : ChartUtils.nextUp(floor(yMax / interval) * interval) if interval != 0.0 && last != first { for _ in stride(from: first, through: last, by: interval) { n += 1 } } // Ensure stops contains at least n elements. axis.entries.removeAll(keepingCapacity: true) axis.entries.reserveCapacity(labelCount) var f = first var i = 0 while i < n { if f == 0.0 { // Fix for IEEE negative zero case (Where value == -0.0, and 0.0 == -0.0) f = 0.0 } axis.entries.append(Double(f)) f += interval i += 1 } } // set decimals if interval < 1 { axis.decimals = Int(ceil(-log10(interval))) } else { axis.decimals = 0 } if axis.centerAxisLabelsEnabled { axis.centeredEntries.reserveCapacity(n) axis.centeredEntries.removeAll() let offset: Double = interval / 2.0 for i in 0 ..< n { axis.centeredEntries.append(axis.entries[i] + offset) } } } }
apache-2.0
7c9810c5f2273a50039529c13204ffbe
30.176211
134
0.523951
5.337104
false
false
false
false
hoowang/WKRefreshDemo
RefreshToolkit/Views/WKArrowActivityAnimationView.swift
1
3013
// // WKArrowActivityAnimationView.swift // WKRefreshDemo // // Created by hooge on 16/5/3. // Copyright © 2016年 hooge. All rights reserved. // import UIKit public enum ArrowDirection { case South case North } public class WKArrowActivityAnimationView: WKAnimationView { private let activityView = UIActivityIndicatorView(activityIndicatorStyle: .Gray) private let arrowImageView = UIImageView() private var arrowTransform:CGAffineTransform = CGAffineTransformMakeRotation(0.000001 - CGFloat(M_PI)) override init(frame: CGRect) { super.init(frame: frame) self.initialize() } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public override func layoutSubviews() { super.layoutSubviews() self.arrowImageView.frame = self.bounds let activityX = (self.wk_Width - 15.0) * 0.5 let activityY = (self.wk_Height - 15.0) * 0.5 self.activityView.frame = CGRectMake(activityX, activityY, 15, 15) } private func initialize() -> (Void){ self.addSubview(self.activityView) self.addSubview(self.arrowImageView) self.arrowImageView.image = UIImage(named: "arrow") } public override func startAnimation() ->(Void) { self.activityView.startAnimating() } public override func stopAnimation() ->(Void) { self.activityView.stopAnimating() } // 这个方法也许是个设计缺陷 专为上拉刷新调用 代码有些匪夷所思 不想搞太多的类 所以取巧了一下 public override func changeArrowDirection(direction:ArrowDirection) -> (Void){ switch direction { case .South: self.arrowImageView.transform = CGAffineTransformMakeRotation(0.000001 - CGFloat(M_PI)) self.arrowTransform = CGAffineTransformIdentity break case .North: self.arrowTransform = CGAffineTransformMakeRotation(0.000001 - CGFloat(M_PI)) break } } public override func changeState(state:AnimationState) ->(Void){ if self.lastAnimationState == state { return } self.lastAnimationState = state switch state { case .Normal: self.arrowImageView.hidden = false self.stopAnimation() break case .WillRefresh: UIView.animateWithDuration(WKAppearance.animationDuration, animations: { [unowned self ] in self.arrowImageView.transform = self.arrowTransform }) break case .StartRefresh: self.arrowImageView.hidden = true self.arrowImageView.transform = CGAffineTransformIdentity self.startAnimation() break default: break } } public override func AnimationViewSize() -> (CGSize) { return CGSizeMake(15, 40) } }
mit
f2fb13ea4fc9caaddac1f0196262b814
30.12766
106
0.62782
4.804598
false
false
false
false
serp1412/LazyTransitions
LazyTransitions.playground/Pages/Multiple scroll views.xcplaygroundpage/Contents.swift
1
3697
/*: # How to add a bouncy effect to scroll view transitions */ import LazyTransitions import UIKit import PlaygroundSupport class LazyViewController: UIViewController { let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout()) override func viewDidLoad() { super.viewDidLoad() /* 1. Become lazy for dismiss transition */ becomeLazy(for: .dismiss) addTransition(forScrollView: collectionView) } /* 2. Add a transition for each scroll view that you want to trigger a transition. In our case each collection view in every RowCell */ func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { let rowCell = cell as! RowCell // **NOTE**: Don't worry calling this function multiple times for the same view, subsequent times will simply be ignored addTransition(forScrollView: rowCell.collectionView) } } /* 3. Run the playground and flick the collection view to the very top or bottom to see how it bounces. Then try scrolling the cells to the very left or very right, keep on scrolling and see how they trigger a transition */ //: [NEXT: Presentation Controller](Presentation%20controller) [PREVIOUS: Bouncy Scroll View Animation](Bouncy%20ScrollView%20animation) /* Oh hey there, didn't expect you to scroll down here. You won't find anything special here, just some setup code ☺️ */ extension LazyViewController: UICollectionViewDelegateFlowLayout { override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(true) collectionView.register(RowCell.self, forCellWithReuseIdentifier: RowCell.identifier) view.addSubview(collectionView) collectionView.bindFrameToSuperviewBounds() collectionView.dataSource = self collectionView.delegate = self collectionView.backgroundColor = .white } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: collectionView.frame.width, height: 120) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return sectionInsets } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return 10 } } extension LazyViewController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 10 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: RowCell.identifier, for: indexPath) as! RowCell cell.backgroundColor = UIColor.white cell.setup() return cell } } let backVC = BackgroundViewController.instantiate(with: LazyViewController.self, action: { presented, presenting in presenting.present(presented, animated: true, completion: nil) }) backVC.view.frame = .iphone6 PlaygroundPage.current.liveView = backVC.view
bsd-2-clause
d58386173ca2a255fb0ad837c1c36ede
25.76087
170
0.689412
5.770313
false
false
false
false
blumareks/2016WoW
LabVisual/Carthage/Checkouts/Starscream/Source/SSLSecurity.swift
3
8792
////////////////////////////////////////////////////////////////////////////////////////////////// // // SSLSecurity.swift // Starscream // // Created by Dalton Cherry on 5/16/15. // Copyright (c) 2014-2015 Dalton Cherry. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ////////////////////////////////////////////////////////////////////////////////////////////////// import Foundation import Security public class SSLCert { var certData: NSData? var key: SecKeyRef? /** Designated init for certificates - parameter data: is the binary data of the certificate - returns: a representation security object to be used with */ public init(data: NSData) { self.certData = data } /** Designated init for public keys - parameter key: is the public key to be used - returns: a representation security object to be used with */ public init(key: SecKeyRef) { self.key = key } } public class SSLSecurity { public var validatedDN = true //should the domain name be validated? var isReady = false //is the key processing done? var certificates: [NSData]? //the certificates var pubKeys: [SecKeyRef]? //the public keys var usePublicKeys = false //use public keys or certificate validation? /** Use certs from main app bundle - parameter usePublicKeys: is to specific if the publicKeys or certificates should be used for SSL pinning validation - returns: a representation security object to be used with */ public convenience init(usePublicKeys: Bool = false) { let paths = NSBundle.mainBundle().pathsForResourcesOfType("cer", inDirectory: ".") let certs = paths.reduce([SSLCert]()) { (certs: [SSLCert], path: String) -> [SSLCert] in var certs = certs if let data = NSData(contentsOfFile: path) { certs.append(SSLCert(data: data)) } return certs } self.init(certs: certs, usePublicKeys: usePublicKeys) } /** Designated init - parameter keys: is the certificates or public keys to use - parameter usePublicKeys: is to specific if the publicKeys or certificates should be used for SSL pinning validation - returns: a representation security object to be used with */ public init(certs: [SSLCert], usePublicKeys: Bool) { self.usePublicKeys = usePublicKeys if self.usePublicKeys { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0)) { let pubKeys = certs.reduce([SecKeyRef]()) { (pubKeys: [SecKeyRef], cert: SSLCert) -> [SecKeyRef] in var pubKeys = pubKeys if let data = cert.certData where cert.key == nil { cert.key = self.extractPublicKey(data) } if let key = cert.key { pubKeys.append(key) } return pubKeys } self.pubKeys = pubKeys self.isReady = true } } else { let certificates = certs.reduce([NSData]()) { (certificates: [NSData], cert: SSLCert) -> [NSData] in var certificates = certificates if let data = cert.certData { certificates.append(data) } return certificates } self.certificates = certificates self.isReady = true } } /** Valid the trust and domain name. - parameter trust: is the serverTrust to validate - parameter domain: is the CN domain to validate - returns: if the key was successfully validated */ public func isValid(trust: SecTrustRef, domain: String?) -> Bool { var tries = 0 while(!self.isReady) { usleep(1000) tries += 1 if tries > 5 { return false //doesn't appear it is going to ever be ready... } } var policy: SecPolicyRef if self.validatedDN { policy = SecPolicyCreateSSL(true, domain) } else { policy = SecPolicyCreateBasicX509() } SecTrustSetPolicies(trust,policy) if self.usePublicKeys { if let keys = self.pubKeys { let serverPubKeys = publicKeyChainForTrust(trust) for serverKey in serverPubKeys as [AnyObject] { for key in keys as [AnyObject] { if serverKey.isEqual(key) { return true } } } } } else if let certs = self.certificates { let serverCerts = certificateChainForTrust(trust) var collect = [SecCertificate]() for cert in certs { collect.append(SecCertificateCreateWithData(nil,cert)!) } SecTrustSetAnchorCertificates(trust,collect) var result: SecTrustResultType = .Unspecified SecTrustEvaluate(trust,&result) if result == .Unspecified || result == .Proceed { var trustedCount = 0 for serverCert in serverCerts { for cert in certs { if cert == serverCert { trustedCount += 1 break } } } if trustedCount == serverCerts.count { return true } } } return false } /** Get the public key from a certificate data - parameter data: is the certificate to pull the public key from - returns: a public key */ func extractPublicKey(data: NSData) -> SecKeyRef? { guard let cert = SecCertificateCreateWithData(nil, data) else { return nil } return extractPublicKeyFromCert(cert, policy: SecPolicyCreateBasicX509()) } /** Get the public key from a certificate - parameter data: is the certificate to pull the public key from - returns: a public key */ func extractPublicKeyFromCert(cert: SecCertificate, policy: SecPolicy) -> SecKeyRef? { var possibleTrust: SecTrust? SecTrustCreateWithCertificates(cert, policy, &possibleTrust) guard let trust = possibleTrust else { return nil } var result: SecTrustResultType = .Unspecified SecTrustEvaluate(trust, &result) return SecTrustCopyPublicKey(trust) } /** Get the certificate chain for the trust - parameter trust: is the trust to lookup the certificate chain for - returns: the certificate chain for the trust */ func certificateChainForTrust(trust: SecTrustRef) -> [NSData] { let certificates = (0..<SecTrustGetCertificateCount(trust)).reduce([NSData]()) { (certificates: [NSData], index: Int) -> [NSData] in var certificates = certificates let cert = SecTrustGetCertificateAtIndex(trust, index) certificates.append(SecCertificateCopyData(cert!)) return certificates } return certificates } /** Get the public key chain for the trust - parameter trust: is the trust to lookup the certificate chain and extract the public keys - returns: the public keys from the certifcate chain for the trust */ func publicKeyChainForTrust(trust: SecTrustRef) -> [SecKeyRef] { let policy = SecPolicyCreateBasicX509() let keys = (0..<SecTrustGetCertificateCount(trust)).reduce([SecKeyRef]()) { (keys: [SecKeyRef], index: Int) -> [SecKeyRef] in var keys = keys let cert = SecTrustGetCertificateAtIndex(trust, index) if let key = extractPublicKeyFromCert(cert!, policy: policy) { keys.append(key) } return keys } return keys } }
mit
bc13b39072376d19ce511adfba9417c2
33.210117
140
0.561761
5.48814
false
false
false
false
gottesmm/swift
benchmark/single-source/LinkedList.swift
10
1308
//===--- LinkedList.swift -------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // This test checks performance of linked lists. It is based on LinkedList from // utils/benchmark, with modifications for performance measuring. import TestsUtils final class Node { var next: Node? var data: Int init(n: Node?, d: Int) { next = n data = d } } @inline(never) public func run_LinkedList(_ N: Int) { let size = 100 var head = Node(n:nil, d:0) for i in 0..<size { head = Node(n:head, d:i) } var sum = 0 let ref_result = size*(size-1)/2 var ptr = head for _ in 1...5000*N { ptr = head sum = 0 while let nxt = ptr.next { sum += ptr.data ptr = nxt } if sum != ref_result { break } } CheckResults(sum == ref_result, "Incorrect results in LinkedList: \(sum) != \(ref_result)") }
apache-2.0
914a55721d8b30073e6471935d35464e
24.647059
80
0.566514
3.904478
false
false
false
false
ivanbruel/SwipeIt
Pods/Kanna/Sources/libxmlHTMLNode.swift
2
7622
/**@file libxmlHTMLNode.swift Kanna Copyright (c) 2015 Atsushi Kiwaki (@_tid_) 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 /** libxmlHTMLNode */ internal final class libxmlHTMLNode: XMLElement { var text: String? { if nodePtr != nil { return libxmlGetNodeContent(nodePtr) } return nil } var toHTML: String? { let buf = xmlBufferCreate() htmlNodeDump(buf, docPtr, nodePtr) let html = String.fromCString(UnsafePointer(buf.memory.content)) xmlBufferFree(buf) return html } var toXML: String? { let buf = xmlBufferCreate() xmlNodeDump(buf, docPtr, nodePtr, 0, 0) let html = String.fromCString(UnsafePointer(buf.memory.content)) xmlBufferFree(buf) return html } var innerHTML: String? { if let html = self.toHTML { let inner = html.stringByReplacingOccurrencesOfString("</[^>]*>$", withString: "", options: .RegularExpressionSearch, range: nil) .stringByReplacingOccurrencesOfString("^<[^>]*>", withString: "", options: .RegularExpressionSearch, range: nil) return inner } return nil } var className: String? { return self["class"] } var tagName: String? { get { if nodePtr != nil { return String.fromCString(UnsafePointer(nodePtr.memory.name)) } return nil } set { if let newValue = newValue { xmlNodeSetName(nodePtr, newValue) } } } var content: String? { get { return text } set { if let newValue = newValue { let v = escape(newValue) xmlNodeSetContent(nodePtr, v) } } } var parent: XMLElement? { get { return libxmlHTMLNode(docPtr: docPtr, node: nodePtr.memory.parent) } set { if let node = newValue as? libxmlHTMLNode { node.addChild(self) } } } private var docPtr: htmlDocPtr = nil private var nodePtr: xmlNodePtr = nil private var isRoot: Bool = false subscript(attributeName: String) -> String? { get { var attr = nodePtr.memory.properties while attr != nil { let mem = attr.memory if let tagName = String.fromCString(UnsafePointer(mem.name)) { if attributeName == tagName { return libxmlGetNodeContent(mem.children) } } attr = attr.memory.next } return nil } set(newValue) { if let newValue = newValue { xmlSetProp(nodePtr, attributeName, newValue) } else { xmlUnsetProp(nodePtr, attributeName) } } } init(docPtr: xmlDocPtr) { self.docPtr = docPtr self.nodePtr = xmlDocGetRootElement(docPtr) self.isRoot = true } init(docPtr: xmlDocPtr, node: xmlNodePtr) { self.docPtr = docPtr self.nodePtr = node } // MARK: Searchable func xpath(xpath: String, namespaces: [String:String]?) -> XPathObject { let ctxt = xmlXPathNewContext(docPtr) if ctxt == nil { return XPathObject.None } ctxt.memory.node = nodePtr if let nsDictionary = namespaces { for (ns, name) in nsDictionary { xmlXPathRegisterNs(ctxt, ns, name) } } let result = xmlXPathEvalExpression(xpath, ctxt) defer { xmlXPathFreeObject(result) } xmlXPathFreeContext(ctxt) if result == nil { return XPathObject.None } return XPathObject(docPtr: docPtr, object: result.memory) } func xpath(xpath: String) -> XPathObject { return self.xpath(xpath, namespaces: nil) } func at_xpath(xpath: String, namespaces: [String:String]?) -> XMLElement? { return self.xpath(xpath, namespaces: namespaces).nodeSetValue.first } func at_xpath(xpath: String) -> XMLElement? { return self.at_xpath(xpath, namespaces: nil) } func css(selector: String, namespaces: [String:String]?) -> XPathObject { if let xpath = CSS.toXPath(selector) { if isRoot { return self.xpath(xpath, namespaces: namespaces) } else { return self.xpath("." + xpath, namespaces: namespaces) } } return XPathObject.None } func css(selector: String) -> XPathObject { return self.css(selector, namespaces: nil) } func at_css(selector: String, namespaces: [String:String]?) -> XMLElement? { return self.css(selector, namespaces: namespaces).nodeSetValue.first } func at_css(selector: String) -> XMLElement? { return self.css(selector, namespaces: nil).nodeSetValue.first } func addPrevSibling(node: XMLElement) { guard let node = node as? libxmlHTMLNode else { return } xmlAddPrevSibling(nodePtr, node.nodePtr) } func addNextSibling(node: XMLElement) { guard let node = node as? libxmlHTMLNode else { return } xmlAddNextSibling(nodePtr, node.nodePtr) } func addChild(node: XMLElement) { guard let node = node as? libxmlHTMLNode else { return } xmlUnlinkNode(node.nodePtr) xmlAddChild(nodePtr, node.nodePtr) } func removeChild(node: XMLElement) { guard let node = node as? libxmlHTMLNode else { return } xmlUnlinkNode(node.nodePtr) xmlFree(node.nodePtr) } } private func libxmlGetNodeContent(nodePtr: xmlNodePtr) -> String? { let content = xmlNodeGetContent(nodePtr) if let result = String.fromCString(UnsafePointer(content)) { content.dealloc(1) return result } content.dealloc(1) return nil } let entities = [ "&": "&amp;", "<" : "&lt;", ">" : "&gt;", ] private func escape(str: String) -> String { var newStr = str for (unesc, esc) in entities { newStr = newStr.stringByReplacingOccurrencesOfString(unesc, withString: esc, options: .RegularExpressionSearch, range: nil) } return newStr }
mit
3254b9c3d66b5d13a007abe2a178bc95
27.871212
141
0.584623
4.542312
false
false
false
false
Hout/DateInRegion
Pod/Classes/DateRegion.swift
1
4288
// // DateRegion.swift // Pods // // Created by Jeroen Houtzager on 09/11/15. // // public class DateRegion: Equatable { /// Calendar to interpret date values. You can alter the calendar to adjust the representation of date to your needs. /// public let calendar: NSCalendar! /// Time zone to interpret date values /// Because the time zone is part of calendar, this is a shortcut to that variable. /// You can alter the time zone to adjust the representation of date to your needs. /// public let timeZone: NSTimeZone! /// Locale to interpret date values /// Because the locale is part of calendar, this is a shortcut to that variable. /// You can alter the locale to adjust the representation of date to your needs. /// public let locale: NSLocale! /// Initialise with a calendar and/or a time zone /// /// - Parameters: /// - calendar: the calendar to work with to assign, default = the current calendar /// - timeZone: the time zone to work with, default is the default time zone /// - locale: the locale to work with, default is the current locale /// - calendarID: the calendar ID to work with to assign, default = the current calendar /// - timeZoneID: the time zone ID to work with, default is the default time zone /// - localeID: the locale ID to work with, default is the current locale /// - region: a region to copy /// /// - Note: parameters higher in the list take precedence over parameters lower in the list. E.g. /// `DateRegion(locale: mylocale, localeID: "en_AU", region)` will copy region and set locale to mylocale, not `en_AU`. /// public init( calendarID: String = "", timeZoneID: String = "", localeID: String = "", calendar aCalendar: NSCalendar? = nil, timeZone aTimeZone: NSTimeZone? = nil, locale aLocale: NSLocale? = nil, region: DateRegion? = nil) { calendar = aCalendar ?? NSCalendar(calendarIdentifier: calendarID) ?? region?.calendar ?? NSCalendar.currentCalendar() timeZone = aTimeZone ?? NSTimeZone(abbreviation: timeZoneID) ?? NSTimeZone(name: timeZoneID) ?? region?.timeZone ?? NSTimeZone.defaultTimeZone() locale = aLocale ?? (localeID != "" ? NSLocale(localeIdentifier: localeID) : nil) ?? region?.locale ?? aCalendar?.locale ?? NSLocale.currentLocale() // Assign calendar fields calendar.timeZone = timeZone calendar.locale = locale } /// Today's date /// /// - Returns: the date of today at midnight (00:00) in the current calendar and default time zone. /// public func today() -> DateInRegion { let components = calendar.components([.Era, .Year, .Month, .Day, .Calendar, .TimeZone], fromDate: NSDate()) let date = calendar.dateFromComponents(components)! return DateInRegion(region: self, date: date) } /// Yesterday's date /// /// - Returns: the date of yesterday at midnight (00:00) in the current calendar and default time zone. /// public func yesterday() -> DateInRegion { return (today() - 1.days)! } /// Tomorrow's date /// /// - Returns: the date of tomorrow at midnight (00:00) in the current calendar and default time zone. /// public func tomorrow() -> DateInRegion { return (today() + 1.days)! } } public func ==(left: DateRegion, right: DateRegion) -> Bool { if left.calendar.calendarIdentifier != right.calendar.calendarIdentifier { return false } if left.timeZone.secondsFromGMT != right.timeZone.secondsFromGMT { return false } if left.locale.localeIdentifier != right.locale.localeIdentifier { return false } return true } extension DateRegion : Hashable { public var hashValue: Int { return calendar.hashValue ^ timeZone.hashValue ^ locale.hashValue } } extension DateRegion : CustomStringConvertible { public var description: String { let timeZoneAbbreviation = timeZone.abbreviation ?? "" return "\(calendar.calendarIdentifier); \(timeZone.name):\(timeZoneAbbreviation); \(locale.localeIdentifier)" } }
mit
7a782abf6539b21b12fbd5662726fdff
36.955752
160
0.643424
4.6058
false
false
false
false
gribozavr/swift
test/SILOptimizer/array_contentof_opt.swift
1
2497
// RUN: %target-swift-frontend -O -sil-verify-all -emit-sil %s | %FileCheck %s // REQUIRES: swift_stdlib_no_asserts,optimized_stdlib // This is an end-to-end test of the array(contentsOf) -> array(Element) optimization // CHECK-LABEL: sil @{{.*}}testInt // CHECK-NOT: apply // CHECK: [[F:%[0-9]+]] = function_ref @$sSa6appendyyxnFSi_Tg5 // CHECK-NOT: apply // CHECK: apply [[F]] // CHECK-NEXT: tuple // CHECK-NEXT: return public func testInt(_ a: inout [Int]) { a += [1] } // CHECK-LABEL: sil @{{.*}}testThreeInts // CHECK-DAG: [[FR:%[0-9]+]] = function_ref @${{(sSa15reserveCapacityyySiFSi_Tg5|sSa16_createNewBuffer)}} // CHECK-DAG: apply [[FR]] // CHECK-DAG: [[F:%[0-9]+]] = function_ref @$sSa6appendyyxnFSi_Tg5 // CHECK-DAG: apply [[F]] // CHECK-DAG: apply [[F]] // CHECK-DAG: apply [[F]] // CHECK: } // end sil function '{{.*}}testThreeInts{{.*}}' public func testThreeInts(_ a: inout [Int]) { a += [1, 2, 3] } // CHECK-LABEL: sil @{{.*}}testTooManyInts // CHECK-NOT: apply // CHECK: [[F:%[0-9]+]] = function_ref @$sSa6append10contentsOfyqd__n_t7ElementQyd__RszSTRd__lFSi_SaySiGTg5Tf4gn_n // CHECK-NOT: apply // CHECK: apply [[F]] // CHECK-NOT: apply // CHECK: return public func testTooManyInts(_ a: inout [Int]) { a += [1, 2, 3, 4, 5, 6, 7] } // CHECK-LABEL: sil @{{.*}}testString // CHECK-NOT: apply // CHECK: [[F:%[0-9]+]] = function_ref @$sSa6appendyyxnFSS_Tg5 // CHECK-NOT: apply // CHECK: apply [[F]] // CHECK-NOT: apply // CHECK: tuple // CHECK-NEXT: return public func testString(_ a: inout [String], s: String) { a += [s] } // This is not supported yet. Just check that we don't crash on this.` public func dontPropagateContiguousArray(_ a: inout ContiguousArray<UInt8>) { a += [4] } // Check if the specialized Array.append<A>(contentsOf:) is reasonably optimized for Array<Int>. // CHECK-LABEL: sil shared {{.*}}@$sSa6append10contentsOfyqd__n_t7ElementQyd__RszSTRd__lFSi_SaySiGTg5 // There should only be a single call to _createNewBuffer or reserveCapacityForAppend/reserveCapacityImpl. // CHECK-NOT: apply // CHECK: [[F:%[0-9]+]] = function_ref @{{.*(_createNewBuffer|reserveCapacity).*}} // CHECK-NEXT: apply [[F]] // CHECK-NOT: apply // The number of basic blocks should not exceed 20 (ideally there are no more than 16 blocks in this function). // CHECK-NOT: bb20: // CHECK: } // end sil function '$sSa6append10contentsOfyqd__n_t7ElementQyd__RszSTRd__lFSi_SaySiGTg5
apache-2.0
9907d653e52165f0d5c44039b4ffc3d3
33.205479
122
0.638767
3.117353
false
true
false
false
lanjing99/iOSByTutorials
iOS 8 by tutorials/Chapter 04 - Adaptive View Controller Hierarchies/KhromaPal-Starter-Xcode-6/KhromaPal/DataLayer/ColorPalette.swift
1
1458
/* * Copyright (c) 2014 Razeware LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import Foundation import UIKit class ColorPalette: PaletteTreeNode, Equatable { var name: String var colors: [UIColor] init(name: String, colors: [UIColor]) { self.name = name self.colors = colors } } // Equatable protocol func ==(lhs: ColorPalette, rhs: ColorPalette) -> Bool { return lhs.name == rhs.name && lhs.colors == rhs.colors }
mit
e3ae1447fea4ba11cbad30e6aacb158d
36.384615
79
0.751715
4.313609
false
false
false
false
ios-ximen/DYZB
斗鱼直播/斗鱼直播/Classes/Tools/Extension/UIBarButtonItem-extension.swift
1
1230
// // UIBarButtonItem-extension.swift // 斗鱼直播 // // Created by niujinfeng on 2017/6/23. // Copyright © 2017年 niujinfeng. All rights reserved. // import Foundation import UIKit extension UIBarButtonItem { /*类封装 class func creatItem(imageName:String, higImageName:String, size:CGSize) -> UIBarButtonItem { //创建btn let btn = UIButton() btn.setImage(UIImage(named:imageName), for: .normal) btn.setImage(UIImage(named:higImageName), for: .highlighted) btn.frame = CGRect(origin: .zero, size: size) return UIBarButtonItem.init(customView: btn) } */ //便利构造函数: 1> convenience开头 2> 在构造函数中必须明确调用一个设计的构造函数(self) convenience init(imageName:String, higImageName:String = "", size:CGSize = .zero) { let btn = UIButton() btn.setImage(UIImage(named:imageName), for: .normal) if higImageName != "" { btn.setImage(UIImage(named:higImageName), for: .highlighted) } if size == .zero { btn.sizeToFit() }else{ btn.frame = CGRect(origin: .zero, size: size) } self.init(customView: btn) } }
mit
f56eaf400ff603ee05e91c47a594c267
29.289474
97
0.622068
3.849498
false
false
false
false
dreamsxin/swift
validation-test/compiler_crashers_fixed/00563-cerror.swift
11
670
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse class func g<T.E == a() -> S<T where g.b = { c: NSManagedObject { var d where I) { return d.e = F>) -> Int = { } struct S<T: Array) { } } return g, f<T! { } typealias h> { func a() { init <T: a = { } } } typealias e = { } } deinit { } protocol A : A.b { func f<T: C) { } func b
apache-2.0
7179a7ea4c54dc76e0136139989088a9
19.9375
78
0.652239
2.938596
false
false
false
false
dreamsxin/swift
validation-test/compiler_crashers_fixed/01376-swift-parser-parsetoken.swift
11
863
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse class a { protocol b = b(Any) { class func c<T) -> { } } let t: U) -> { } var f : NSObject { t: d = b() in return self.h = Swift.e = a<T) { b: b { class func e> { } func g() { c(c : P> { } } var b() { enum A : Range<T, T : T> U) -> Bool { } assert() { if c { i<U -> == c(f() -> { } class a : String) } } protocol b { struct S()) } } } } } protocol a { } class a { protocol c { } protocol a { } func c(T.b { return ".Element>], e(m: A""a! } return { c() }(" func a<S : a)
apache-2.0
572a3e9000753718ec96e80b8838a247
15.283019
78
0.602549
2.647239
false
false
false
false
ben-ng/swift
test/SILGen/if_expr.swift
1
1656
// RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s func fizzbuzz(i: Int) -> String { return i % 3 == 0 ? "fizz" : i % 5 == 0 ? "buzz" : "\(i)" // CHECK: cond_br {{%.*}}, [[OUTER_TRUE:bb[0-9]+]], [[OUTER_FALSE:bb[0-9]+]] // CHECK: [[OUTER_TRUE]]: // CHECK: br [[OUTER_CONT:bb[0-9]+]] // CHECK: [[OUTER_FALSE]]: // CHECK: cond_br {{%.*}}, [[INNER_TRUE:bb[0-9]+]], [[INNER_FALSE:bb[0-9]+]] // CHECK: [[INNER_TRUE]]: // CHECK: br [[INNER_CONT:bb[0-9]+]] // CHECK: [[INNER_FALSE]]: // CHECK: function_ref {{.*}}stringInterpolation // CHECK: br [[INNER_CONT]] // CHECK: [[INNER_CONT]]({{.*}}): // CHECK: br [[OUTER_CONT]] // CHECK: [[OUTER_CONT]]({{.*}}): // CHECK: return } protocol AddressOnly {} struct A : AddressOnly {} struct B : AddressOnly {} func consumeAddressOnly(_: AddressOnly) {} // CHECK: sil hidden @_TF7if_expr19addr_only_ternary_1 func addr_only_ternary_1(x: Bool) -> AddressOnly { // CHECK: bb0([[RET:%.*]] : $*AddressOnly, {{.*}}): // CHECK: [[a:%[0-9]+]] = alloc_box $<τ_0_0> { var τ_0_0 } <AddressOnly>, var, name "a" // CHECK: [[PBa:%.*]] = project_box [[a]] var a : AddressOnly = A() // CHECK: [[b:%[0-9]+]] = alloc_box $<τ_0_0> { var τ_0_0 } <AddressOnly>, var, name "b" // CHECK: [[PBb:%.*]] = project_box [[b]] var b : AddressOnly = B() // CHECK: cond_br {{%.*}}, [[TRUE:bb[0-9]+]], [[FALSE:bb[0-9]+]] // CHECK: [[TRUE]]: // CHECK: copy_addr [[PBa]] to [initialization] [[RET]] // CHECK: br [[CONT:bb[0-9]+]] // CHECK: [[FALSE]]: // CHECK: copy_addr [[PBb]] to [initialization] [[RET]] // CHECK: br [[CONT]] return x ? a : b }
apache-2.0
5cc9aaa66e215500061f2c0019f622da
32.04
89
0.522397
2.944742
false
false
false
false
yichizhang/SubjectiveCPhotoPanner_Swift
SubjectiveCImagePan/SCImagePanScrollBarView.swift
1
1686
// // SCImagePanScrollBarView.swift // SubjectiveCImagePan // // Created by Yichi on 7/03/2015. // Copyright (c) 2015 Sam Page. All rights reserved. // import Foundation import UIKit class SCImagePanScrollBarView : UIView { private var scrollBarLayer = CAShapeLayer() init(frame: CGRect, edgeInsets: UIEdgeInsets) { super.init(frame: frame) let scrollBarPath = UIBezierPath() scrollBarPath.moveToPoint(CGPoint(x: edgeInsets.left, y: bounds.height - edgeInsets.bottom )) scrollBarPath.addLineToPoint(CGPoint(x: bounds.width - edgeInsets.right, y: bounds.height - edgeInsets.bottom )) let scrollBarBackgroundLayer = CAShapeLayer() scrollBarBackgroundLayer.path = scrollBarPath.CGPath scrollBarBackgroundLayer.lineWidth = 1 scrollBarBackgroundLayer.strokeColor = UIColor.whiteColor().colorWithAlphaComponent(0.1).CGColor scrollBarBackgroundLayer.fillColor = UIColor.clearColor().CGColor layer.addSublayer(scrollBarBackgroundLayer) scrollBarLayer.path = scrollBarPath.CGPath scrollBarLayer.lineWidth = 1.0 scrollBarLayer.strokeColor = UIColor.whiteColor().CGColor scrollBarLayer.fillColor = UIColor.clearColor().CGColor scrollBarLayer.actions = [ "strokeStart" : NSNull(), "strokeEnd" : NSNull() ] layer.addSublayer(scrollBarLayer) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func updateWithScrollAmount(scrollAmount: CGFloat, forScrollableWidth scrollableWidth: CGFloat, inScrollableArea scrollableArea: CGFloat) { scrollBarLayer.strokeStart = scrollAmount * scrollableArea scrollBarLayer.strokeEnd = (scrollAmount * scrollableArea) + scrollableWidth } }
mit
edee0001c215a410740090fc529d8f99
32.74
140
0.774021
4.112195
false
false
false
false
bikisDesign/Swift-Essentials
Swift-Essentials/Foundation/Date-Extensions.swift
1
7257
// // Date-Extensions.swift // Radiant Tap Essentials // // Copyright © 2016 Radiant Tap // MIT License · http://choosealicense.com/licenses/mit/ // import Foundation public extension Date { public init(year: Int? = nil, month: Int? = nil, day: Int? = nil, hour: Int? = nil, minute: Int? = nil, second: Int? = nil) { if let year = year, let month = month, let day = day, let hour = hour, let minute = minute, let second=second, year <= 0, month <= 0, day <= 0, hour < 0, minute < 0, second < 0 { fatalError("Can not create date with negative values") } let calendar = Calendar.current var components = DateComponents() components.year = year components.month = month components.day = day components.hour = hour components.minute = minute components.second = second guard let date = calendar.date(from: components) else { fatalError("Could not create date") } self = date } public func beginningOfDay() -> Date { let calendar = Calendar.current let components = calendar.dateComponents(Set(arrayLiteral: Calendar.Component.year, Calendar.Component.month, Calendar.Component.day), from: self) guard let newDate = calendar.date(from: components) else { return self } return newDate } public func endOfDay() -> Date { let calendar = Calendar.current var components = DateComponents() components.day = 1 guard let newDate = calendar.date(byAdding: components, to: self.beginningOfDay()) else { return self } return newDate.addingTimeInterval(-1) } public func beginningOfMonth() -> Date { let calendar = Calendar.current let components = calendar.dateComponents(Set(arrayLiteral: Calendar.Component.year, Calendar.Component.month), from: self) guard let newDate = calendar.date(from: components) else { return self } return newDate } public func endOfMonth() -> Date { let calendar = Calendar.current var components = DateComponents() components.month = 1 guard let newDate = calendar.date(byAdding: components, to: self.beginningOfMonth()) else { return self } return newDate.addingTimeInterval(-1) } } public extension Date { public func day() -> Int { let calendar = Calendar.current let components = calendar.dateComponents(Set(arrayLiteral: Calendar.Component.day), from: self) guard let day = components.day else { return 0 } return day } public func weekday() -> Int { let calendar = Calendar.current let components = calendar.dateComponents(Set(arrayLiteral: Calendar.Component.weekday), from: self) guard let weekDay = components.weekday else { return 0 } return weekDay } public func month() -> Int { let calendar = Calendar.current let components = calendar.dateComponents(Set(arrayLiteral: Calendar.Component.month), from: self) guard let month = components.month else { return 0 } return month } public func year() -> Int { let calendar = Calendar.current let components = calendar.dateComponents(Set(arrayLiteral: Calendar.Component.year), from: self) guard let year = components.year else { return 0 } return year } public var isToday: Bool { if self > Date().endOfDay() { return false } if self < Date().beginningOfDay() { return false } return true } public func isEarlierThan(date: Date) -> Bool { if self.timeIntervalSince1970 < date.timeIntervalSince1970 { return true } return false } public func isLaterThan(date: Date) -> Bool { if self.timeIntervalSince1970 > date.timeIntervalSince1970 { return true } return false } public func isEarlierThanOrEqualTo(date: Date) -> Bool { if self.timeIntervalSince1970 <= date.timeIntervalSince1970 { return true } return false } public func isLaterThanOrEqualTo(date: Date) -> Bool { if self.timeIntervalSince1970 >= date.timeIntervalSince1970 { return true } return false } public func add(minutes: Int) -> Date { let calendar = Calendar.current var components = DateComponents() components.minute = minutes guard let newDate = calendar.date(byAdding: components, to: self) else { return self } return newDate } public func subtract(minutes: Int) -> Date { let calendar = Calendar.current var components = DateComponents() components.minute = -1 * minutes guard let newDate = calendar.date(byAdding: components, to:self) else { return self } return newDate } public func add(hours: Int) -> Date { let calendar = Calendar.current var components = DateComponents() components.hour = hours guard let newDate = calendar.date(byAdding: components, to: self) else { return self } return newDate } public func subtract(hours: Int) -> Date { let calendar = Calendar.current var components = DateComponents() components.hour = -1 * hours guard let newDate = calendar.date(byAdding: components, to:self) else { return self } return newDate } public func add(days: Int) -> Date { let calendar = Calendar.current var components = DateComponents() components.day = days guard let newDate = calendar.date(byAdding: components, to: self) else { return self } return newDate } public func subtract(days: Int) -> Date { let calendar = Calendar.current var components = DateComponents() components.day = -1 * days guard let newDate = calendar.date(byAdding: components, to:self) else { return self } return newDate } public func add(months: Int) -> Date { let calendar = Calendar.current var components = DateComponents() components.month = months guard let newDate = calendar.date(byAdding: components, to: self) else { return self } return newDate } public func subtract(months: Int) -> Date { let calendar = Calendar.current var components = DateComponents() components.month = -1 * months guard let newDate = calendar.date(byAdding: components, to:self) else { return self } return newDate } public func add(years: Int) -> Date { let calendar = Calendar.current var components = DateComponents() components.year = years guard let newDate = calendar.date(byAdding: components, to: self) else { return self } return newDate } public func subtract(years: Int) -> Date { let calendar = Calendar.current var components = DateComponents() components.year = -1 * years guard let newDate = calendar.date(byAdding: components, to:self) else { return self } return newDate } public func daysFrom(date: Date) -> Int { let calendar = Calendar.current let earliest = (self as NSDate).earlierDate(date) let latest = (earliest == self) ? date : self let multiplier = (earliest == self) ? -1 : 1 guard let day = calendar.dateComponents(Set(arrayLiteral: Calendar.Component.day), from: earliest, to: latest).day else { return 0 } return multiplier * day } public func minutesFrom(date: Date) -> Int { let calendar = Calendar.current let earliest = (self as NSDate).earlierDate(date) let latest = (earliest == self) ? date : self let multiplier = (earliest == self) ? -1 : 1 guard let minute = calendar.dateComponents(Set(arrayLiteral: Calendar.Component.minute), from: earliest, to: latest).minute else { return 0 } return multiplier * minute } }
mit
94aae20a8bc6bb6a6e9c3ab07216e60e
19.847701
180
0.700896
3.786534
false
false
false
false
OrdnanceSurvey/search-swift
OSSearch/NumberFormatter.swift
1
608
// // NumberFormatter.swift // Search // // Created by Dave Hardiman on 11/04/2016. // Copyright © 2016 Ordnance Survey. All rights reserved. // import Foundation struct NumberFormatter { private static var formatter: NSNumberFormatter = { let numberFormatter = NSNumberFormatter() numberFormatter.numberStyle = .NoStyle numberFormatter.maximumFractionDigits = 2 numberFormatter.minimumFractionDigits = 0 return numberFormatter }() static func stringFromNumber(number: Double) -> String? { return formatter.stringFromNumber(number) } }
apache-2.0
1fbf095b75cdbfc8d74e37283acab1b0
25.391304
61
0.698517
5.144068
false
false
false
false
mmisesin/particle
Particle/TranslateTableViewCell.swift
1
1250
// // TranslateTableViewCell.swift // Particle // // Created by Artem Misesin on 9/11/17. // Copyright © 2017 Artem Misesin. All rights reserved. // import UIKit class TranslateTableViewCell: UITableViewCell { @IBOutlet private weak var indexLabel: UILabel! @IBOutlet private weak var translationLabel: UILabel! @IBOutlet private weak var genderLabel: UILabel! @IBOutlet private weak var synonimsLabel: UILabel! @IBOutlet weak var addButton: UIButton! override func awakeFromNib() { super.awakeFromNib() } @IBAction func addAction(_ sender: UIButton) { } func setupForTranslation(_ translation: EntireTranslation, atIndexPath indexPath: IndexPath) { indexLabel.text = String(describing: indexPath.row + 1) translationLabel.text = translation.text ?? "Unknown" genderLabel.text = translation.gender ?? "" if let synonyms = translation.synonyms { var tempStrings = [String]() for synonym in synonyms { tempStrings.append(synonym.text ?? "") } synonimsLabel.text = tempStrings.joined(separator: ", ") } else { synonimsLabel.text = "" } } }
mit
3c56f3a988c8a356ab5ace4bc6867724
28.738095
98
0.634908
4.608856
false
false
false
false
TouchInstinct/LeadKit
Sources/Classes/DataLoading/Cursors/StaticCursor.swift
1
2128
// // Copyright (c) 2017 Touch Instinct // // 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 RxSwift /// Stub cursor implementation for array content type public class StaticCursor<Element>: ResettableRxDataSourceCursor { public typealias ResultType = [Element] private let content: [Element] /// Initializer for array content type /// /// - Parameter content: array with elements of Element type public init(content: [Element]) { self.content = content } public required init(resetFrom other: StaticCursor) { self.content = other.content } public private(set) var exhausted = false public private(set) var count = 0 public subscript(index: Int) -> Element { content[index] } public func loadNextBatch() -> Single<[Element]> { Single.deferred { if self.exhausted { return .error(CursorError.exhausted) } self.count = self.content.count self.exhausted = true return .just(self.content) } } }
apache-2.0
cb5c1bb02427f0d8c1764c3d53fb347d
32.25
81
0.68938
4.556745
false
false
false
false
pjocprac/PTPopupWebView
Pod/Classes/PTPopupWebViewController.swift
1
14512
// // PopupWebViewController.swift // PTPopupWebView // // Created by Takeshi Watanabe on 2016/03/19. // Copyright © 2016 Takeshi Watanabe. All rights reserved. // import Foundation import UIKit import WebKit open class PTPopupWebViewController : UIViewController { public enum PTPopupWebViewControllerBackgroundStyle { // blur effect background case blurEffect (UIBlurEffectStyle) // opacity background case opacity (UIColor?) // transparent background case transparent } public enum PTPopupWebViewControllerTransitionStyle { /// Transition without style. case none /// Transition with fade in/out effect. case fade (TimeInterval) /// Transition with slide in/out effect. case slide (PTPopupWebViewEffectDirection, TimeInterval, Bool) /// Transition with spread out/in style case spread (TimeInterval) /// Transition with pop out/in style case pop (TimeInterval, Bool) } public enum PTPopupWebViewEffectDirection { case top, bottom, left, right } @IBOutlet weak fileprivate var contentView : UIView! @IBOutlet weak fileprivate var blurView: UIVisualEffectView! /// PTPopupWebView open fileprivate(set) var popupView = PTPopupWebView().style(PTPopupWebViewControllerStyle()) /// Background Style open fileprivate(set) var backgroundStyle : PTPopupWebViewControllerBackgroundStyle = .blurEffect(.dark) /// Transition Style open fileprivate(set) var transitionStyle : UIModalTransitionStyle = .crossDissolve /// Popup Appear Style open fileprivate(set) var popupAppearStyle : PTPopupWebViewControllerTransitionStyle = .pop(0.3, true) /// Popup Disappear Style open fileprivate(set) var popupDisappearStyle : PTPopupWebViewControllerTransitionStyle = .pop(0.3, true) fileprivate let attributes = [ NSLayoutAttribute.top, NSLayoutAttribute.left, NSLayoutAttribute.bottom, NSLayoutAttribute.right ] fileprivate var constraints : [NSLayoutAttribute : NSLayoutConstraint] = [:] override open func loadView() { let bundle = Bundle(for: type(of: self)) switch backgroundStyle { case .blurEffect(let blurStyle): let nib = UINib(nibName: "PTPopupWebViewControllerBlur", bundle: bundle) view = nib.instantiate(withOwner: self, options: nil).first as! UIView blurView.effect = UIBlurEffect(style: blurStyle) case .opacity(let color): let view = UIView(frame: UIScreen.main.bounds) self.view = view self.contentView = view self.contentView.backgroundColor = color case .transparent: let view = UIView(frame: UIScreen.main.bounds) self.view = view self.contentView = view self.contentView.backgroundColor = .clear } } override open func viewDidLoad() { super.viewDidLoad() popupView.delegate = self self.contentView.addSubview(popupView) popupView.translatesAutoresizingMaskIntoConstraints = false for attribute in attributes { let constraint = NSLayoutConstraint( item : contentView, attribute: attribute, relatedBy: NSLayoutRelation.equal, toItem: popupView, attribute: attribute, multiplier: 1.0, constant: 0.0) contentView.addConstraint(constraint) constraints[attribute] = constraint } } override open func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) switch popupAppearStyle { case .none: popupView.alpha = 1 default : popupView.alpha = 0 } } override open func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) switch popupAppearStyle { case .none: break case .fade (let duration): UIView.animate(withDuration: duration, delay: 0, options: UIViewAnimationOptions(), animations: {self.popupView.alpha = 1}, completion: nil) case .slide(let direction, let duration, let damping): self.popupView.alpha = 1 switch direction { case .top : self.popupView.transform = CGAffineTransform(translationX: 0, y: -self.view.bounds.height) case .bottom: self.popupView.transform = CGAffineTransform(translationX: 0, y: self.view.bounds.height) case .left : self.popupView.transform = CGAffineTransform(translationX: -self.view.bounds.width, y: 0) case .right : self.popupView.transform = CGAffineTransform( translationX: self.view.bounds.width, y: 0) } let animations = { self.popupView.transform = CGAffineTransform(translationX: 0, y: 0) } if damping { UIView.animate(withDuration: duration, delay: 0, usingSpringWithDamping: 0.75, initialSpringVelocity: 0, options: UIViewAnimationOptions(), animations: animations, completion: nil) } else { UIView.animate(withDuration: duration, delay: 0, options: UIViewAnimationOptions(), animations: animations, completion: nil) } case .spread (let duration): popupView.alpha = 1 CATransaction.begin() CATransaction.setCompletionBlock({ self.popupView.layer.mask = nil }) CATransaction.setAnimationTimingFunction(CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)) let maskLayer = CALayer() maskLayer.backgroundColor = UIColor.white.cgColor maskLayer.cornerRadius = popupView.style?.cornerRadius ?? 0 let oldBounds = CGRect.zero let newBounds = popupView.contentView.bounds let revealAnimation = CABasicAnimation(keyPath: "bounds") revealAnimation.fromValue = NSValue(cgRect: oldBounds) revealAnimation.toValue = NSValue(cgRect: newBounds) revealAnimation.duration = duration maskLayer.frame = popupView.contentView.frame popupView.layer.mask = maskLayer maskLayer.add(revealAnimation, forKey: "revealAnimation") CATransaction.commit() case .pop (let duration, let damping): popupView.alpha = 1 popupView.transform = CGAffineTransform(scaleX: 0, y: 0) let animations = { self.popupView.transform = CGAffineTransform(scaleX: 1, y: 1) } if damping { UIView.animate(withDuration: duration, delay: 0, usingSpringWithDamping: 0.75, initialSpringVelocity: 0, options: UIViewAnimationOptions(), animations: animations, completion: nil) } else { UIView.animate(withDuration: duration, delay: 0, options: UIViewAnimationOptions(), animations: animations, completion: nil) } } } /** Set the background style (Default: .BlurEffect(.Dark)) - parameters: - style: PTPopupWebViewControllerBackgroundStyle */ open func backgroundStyle(_ style: PTPopupWebViewControllerBackgroundStyle) -> Self { self.backgroundStyle = style return self } /** Set the tansition style (Default: .CrossDissolve) - parameters: - style: UIModalTransitionStyle */ open func transitionStyle(_ style: UIModalTransitionStyle) -> Self { self.transitionStyle = style return self } /** Set the popup appear style (Default: .None) - parameters: - style: PTPopupWebViewControllerTransitionStyle */ open func popupAppearStyle(_ style: PTPopupWebViewControllerTransitionStyle) -> Self { self.popupAppearStyle = style return self } /** Set the popup disappear style (Default: .None) - parameters: - style: PTPopupWebViewControllerTransitionStyle */ open func popupDisappearStyle(_ style: PTPopupWebViewControllerTransitionStyle) -> Self { self.popupDisappearStyle = style return self } /** Show the popup view. Transition from the ViewController, which is - foreground view controller (without argument) - specified view controller (with argument) - parameters: - presentViewController: transition source ViewController */ open func show(_ presentViewController: UIViewController? = nil) { modalPresentationStyle = UIModalPresentationStyle.overCurrentContext modalTransitionStyle = self.transitionStyle if let presentViewController = presentViewController { presentViewController.present(self, animated: true, completion: nil) } else { var rootViewController = UIApplication.shared.keyWindow?.rootViewController; if rootViewController != nil { while ((rootViewController!.presentedViewController) != nil) { rootViewController = rootViewController!.presentedViewController; } rootViewController!.present(self, animated: true, completion: nil) } } } override open var prefersStatusBarHidden : Bool { return true } } extension PTPopupWebViewController : PTPopupWebViewDelegate { public func close() { let completion:(Bool) -> Void = { completed in self.dismiss(animated: true, completion: nil) } switch popupDisappearStyle { case .none: completion(true) case .fade (let duration): UIView.animate(withDuration: duration, delay: 0, options: UIViewAnimationOptions(), animations: {self.popupView.alpha = 0}, completion: completion) case .slide(let direction, let duration, let damping): let animations = { switch direction { case .top : self.popupView.transform = CGAffineTransform(translationX: 0, y: -self.view.bounds.height) case .bottom: self.popupView.transform = CGAffineTransform(translationX: 0, y: self.view.bounds.height) case .left : self.popupView.transform = CGAffineTransform(translationX: -self.view.bounds.width, y: 0) case .right : self.popupView.transform = CGAffineTransform( translationX: self.view.bounds.width, y: 0) } } if damping { let springAnimations = { switch direction { case .top : self.popupView.transform = CGAffineTransform(translationX: 0, y: self.popupView.bounds.height * 0.05) case .bottom: self.popupView.transform = CGAffineTransform(translationX: 0, y: -self.popupView.bounds.height * 0.05) case .left : self.popupView.transform = CGAffineTransform( translationX: self.popupView.bounds.width * 0.05, y: 0) case .right : self.popupView.transform = CGAffineTransform(translationX: -self.popupView.bounds.width * 0.05, y: 0) } } UIView.animate( withDuration: duration/3, delay: 0, options: UIViewAnimationOptions(), animations: springAnimations, completion: { completed in UIView.animate( withDuration: duration * 2/3, delay: 0, options: UIViewAnimationOptions(), animations: animations, completion: completion) }) } else { UIView.animate(withDuration: duration, delay: 0, options: UIViewAnimationOptions(), animations: animations, completion: nil) } case .spread (let duration): CATransaction.begin() CATransaction.setCompletionBlock({ completion(true) }) CATransaction.setAnimationTimingFunction(CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)) let maskLayer = CALayer() maskLayer.backgroundColor = UIColor.white.cgColor maskLayer.cornerRadius = popupView.style?.cornerRadius ?? 0 let oldBounds = popupView.contentView.bounds let newBounds = CGRect.zero let revealAnimation = CABasicAnimation(keyPath: "bounds") revealAnimation.fromValue = NSValue(cgRect: oldBounds) revealAnimation.toValue = NSValue(cgRect: newBounds) revealAnimation.duration = duration revealAnimation.repeatCount = 0 maskLayer.frame = popupView.contentView.frame maskLayer.bounds = CGRect.zero popupView.layer.mask = maskLayer maskLayer.add(revealAnimation, forKey: "revealAnimation") CATransaction.commit() case .pop (let duration, let damping): if damping { UIView.animate( withDuration: duration/3, delay: 0, options: UIViewAnimationOptions(), animations: { self.popupView.transform = CGAffineTransform(scaleX: 1.05, y: 1.05) }, completion: { completed in UIView.animate( withDuration: duration * 2/3, delay: 0, options: UIViewAnimationOptions(), animations: { self.popupView.transform = CGAffineTransform(scaleX: 0.0000001, y: 0.0000001) // if 0, no animation }, completion: completion) }) } else { UIView.animate( withDuration: duration, delay: 0, options: UIViewAnimationOptions(), animations: { self.popupView.transform = CGAffineTransform(scaleX: 0.0000001, y: 0.0000001) }, completion: completion) } } } }
mit
a4e779b600cdf2adf64b06fa6be3f4f9
39.308333
196
0.604507
5.692821
false
false
false
false
kevinli194/CancerCenterPrototype
CancerInstituteDemo/CancerInstituteDemo/Resources/SupportDetailViewController.swift
1
1000
// // SupportDetailViewController.swift // CancerInstituteDemo // // Created by Anna Benson on 11/9/15. // Copyright © 2015 KAG. All rights reserved. // import UIKit class SupportDetailViewController: UIViewController { var myTitle: String? var myDescription: String? var myImage: String? @IBOutlet weak var curTitle: UILabel! @IBOutlet weak var curDescription: UILabel! @IBOutlet weak var curImage: UIImageView! override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor(patternImage: UIImage(named: "blueGradient.jpg")!) curTitle.text = myTitle curDescription.text = myDescription curImage.image = UIImage(named: myImage!) //make images circular curImage.layer.cornerRadius = curImage.frame.size.width/2 curImage.clipsToBounds = true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
mit
2b7da4a440f28b9e5db08f644f0e3485
25.315789
94
0.667668
4.561644
false
false
false
false
veeman961/Flicks
Flicks/MovieDetailViewController.swift
1
2733
// // DetailViewController.swift // // // Created by Kevin Rajan on 1/12/16. // // import UIKit class MovieDetailViewController: UIViewController { @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var overviewLabel: UILabel! @IBOutlet weak var posterImageView: UIImageView! @IBOutlet weak var scrollView: UIScrollView! @IBOutlet weak var infoView: UIView! @IBOutlet weak var ratingLabel: UILabel! @IBOutlet weak var yearLabel: UILabel! var movie: NSDictionary! override func viewDidLoad() { super.viewDidLoad() self.navigationController?.navigationBar.tintColor = UIColor.orangeColor() scrollView.contentSize = CGSize(width: scrollView.frame.size.width, height: infoView.frame.origin.y + infoView.frame.size.height) let title = movie["title"] as! String let overview = movie["overview"] as! String let baseUrl = "http://image.tmdb.org/t/p/w500/" if let posterPath = movie["poster_path"] as? String { let posterURL = NSURL(string: baseUrl + posterPath) posterImageView.setImageWithURL(posterURL!) } let year = (movie["release_date"] as! NSString).substringWithRange(NSRange(location: 0, length: 4)) let rating = movie["vote_average"] as! Double titleLabel.text = title yearLabel.text = String(year) ratingLabel.text = String(format: "%.1f", rating) ratingColor(ratingLabel, rating: rating) overviewLabel.text = overview overviewLabel.sizeToFit() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func ratingColor(label: UILabel, rating: Double) { if rating > 6 { label.backgroundColor = UIColor.yellowColor() label.textColor = UIColor.blackColor() } else if rating > 4 { label.backgroundColor = UIColor.greenColor() label.textColor = UIColor.whiteColor() } else { label.backgroundColor = UIColor.redColor() label.textColor = UIColor.whiteColor() } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
apache-2.0
588d26214ad3496707587099926ee3bc
31.535714
137
0.628247
4.996344
false
false
false
false
wasabit/bitstampprice
BitstampPriceTests/BitstampTest.swift
1
1588
// // BitstampTest.swift // Bitstamp PriceTests // // Created by Sebas on 08/12/17. // Copyright © 2017 WasabitLabs. All rights reserved. // import XCTest @testable import Bitstamp_Price class BitstampText: XCTestCase { var sut: Bitstamp! override func setUp() { super.setUp() self.sut = Bitstamp() sut.tickerFetcher = FakeFetcher() } func testShowPriceWhite() { sut.showPrice { _ in } sut.showPrice { (price) in XCTAssertEqual(NSColor.white, self.priceColor(price)) } } func testShowPriceGreen() { sut.showPrice { (price) in XCTAssertEqual(NSColor.green, self.priceColor(price)) } } func testShowPriceRed() { let tickerFetcher = sut.tickerFetcher as! FakeFetcher tickerFetcher.last = "-200" sut.showPrice { (price) in XCTAssertEqual(NSColor.red, self.priceColor(price)) } } private func priceColor(_ price: NSAttributedString) -> NSColor { let color = price.attribute(NSAttributedString.Key.foregroundColor, at: 1, effectiveRange: nil) return color as! NSColor } } class FakeFetcher: TickerFetcher { var last = "123" func fetch(block: @escaping (BitstampTicker?) -> ()) { let ticker = BitstampTicker(high: "123", last: last, timestamp: "123", bid: "123", vwap: "123", volume: "123", low: "123", ask: "123", open: 123) block(ticker) } }
mit
e7ad2253481118d18835e942cd10829a
24.596774
78
0.570888
4.122078
false
true
false
false
gu704823/ofo
ofo/time.swift
1
465
// // time.swift // music // // Created by jason on 2017/4/22. // Copyright © 2017年 jason. All rights reserved. // import UIKit class lengthtime { class func length(all:Int)->(String){ var minute:String? let m:Int = all % 60 if m<10{ minute = "0\(m)" }else{ minute = "\(m)" } let s:Int = all/60 let lengthtime:String = "0\(s):\(minute!)" return lengthtime } }
mit
e9857a61ea01b720698392986f5a79e6
18.25
50
0.502165
3.276596
false
false
false
false
RamonGilabert/RamonGilabert
RamonGilabert/RamonGilabert/CustomTipsTransition.swift
1
5857
import UIKit struct PanGestureTranslation { static let SideXTranslation = 120 as CGFloat static let SideYTranslation = 75 as CGFloat static let SideYTranslationTitle = 100 as CGFloat } class CustomTipsTransition: UIPercentDrivenInteractiveTransition, UIViewControllerAnimatedTransitioning, UIViewControllerTransitioningDelegate, UIViewControllerInteractiveTransitioning { private let panGestureRecognizer = UIPanGestureRecognizer() private let soundManager = SoundManager() private var presenting = false private var interactive = false // MARK: Setters var exitViewController: RGTipsViewController! { didSet { self.soundManager.dismissTips self.panGestureRecognizer.addTarget(self, action:"onPanGestureRecognizer:") self.exitViewController.view.addGestureRecognizer(self.panGestureRecognizer) } } // MARK: UIPanGestureHandlers func onPanGestureRecognizer(panGesture: UIPanGestureRecognizer) { let translation = panGesture.translationInView(self.exitViewController.view) switch panGesture.state { case UIGestureRecognizerState.Began: if translation.x < 0 { self.interactive = true self.exitViewController.dismissViewControllerAnimated(true, completion: nil) } break case UIGestureRecognizerState.Changed: self.updateInteractiveTransition((-translation.x + 25)/Constant.Size.DeviceWidth/7.5) break default: self.interactive = false if -translation.x/100 > 1.75 { self.soundManager.dismissTips.play() self.finishInteractiveTransition() } else { self.cancelInteractiveTransition() } } } // MARK: UIViewControllerAnimatedTransitioning protocol methods func animateTransition(transitionContext: UIViewControllerContextTransitioning) { let container = transitionContext.containerView() let screens: (from: UIViewController, to: UIViewController) = (transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)!, transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)!) let mainViewController = !self.presenting ? screens.to as! RGMainViewController : screens.from as! RGMainViewController let tipsViewController = !self.presenting ? screens.from as! RGTipsViewController : screens.to as! RGTipsViewController let menuView = tipsViewController.view let bottomView = mainViewController.view if (self.presenting) { self.offStageMenuController(tipsViewController) } container.addSubview(bottomView) container.addSubview(menuView) let duration = self.transitionDuration(transitionContext) UIView.animateWithDuration(duration, delay: 0.0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.8, options: nil, animations: { if self.presenting { self.onStageMenuController(tipsViewController) } else { self.offStageMenuController(tipsViewController) }}, completion: { finished in if transitionContext.transitionWasCancelled() { transitionContext.completeTransition(false) UIApplication.sharedApplication().keyWindow!.addSubview(screens.from.view) } else { transitionContext.completeTransition(true) UIApplication.sharedApplication().keyWindow!.addSubview(screens.from.view) UIApplication.sharedApplication().keyWindow!.addSubview(screens.to.view) } }) } func offStageMenuController(tipsViewController: RGTipsViewController) { tipsViewController.view.alpha = 0 tipsViewController.swipeSidesIcon.transform = CGAffineTransformMakeTranslation(-400, 0) tipsViewController.swipeSidesLabel.transform = CGAffineTransformMakeTranslation(-400, 0) tipsViewController.scrollDownIcon.transform = CGAffineTransformMakeTranslation(400, 0) tipsViewController.scrollDownLabel.transform = CGAffineTransformMakeTranslation(400, 0) tipsViewController.pinchMenuIcon.transform = CGAffineTransformMakeTranslation(-400, 0) tipsViewController.pinchMenuLabel.transform = CGAffineTransformMakeTranslation(-400, 0) tipsViewController.slideToStartLabel.transform = CGAffineTransformMakeTranslation(0, 200) } func onStageMenuController(tipsViewController: RGTipsViewController) { tipsViewController.view.alpha = 1 for view in tipsViewController.view.subviews as! [UIView] { view.transform = CGAffineTransformIdentity } } // MARK: Delegate methods func interactionControllerForPresentation(animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { return self.interactive ? self : nil } func interactionControllerForDismissal(animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { return self.interactive ? self : nil } func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? { self.presenting = true return self } func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { self.presenting = false return self } func transitionDuration(videoViewController: UIViewControllerContextTransitioning) -> NSTimeInterval { return 0.75 } }
mit
a2be464c9bfba96c3a1372fc02ecf948
41.751825
234
0.715213
6.359392
false
false
false
false
mo3bius/My-Simple-Instagram
My-Simple-Instagram/Database/Image/Image.swift
1
2483
// // Image.swift // My-Simple-Instagram // // Created by Luigi Aiello on 31/10/17. // Copyright © 2017 Luigi Aiello. All rights reserved. // import Foundation import RealmSwift class Image: Object { // MARK: - Properties @objc dynamic var imageId = "" @objc dynamic var userId = "" @objc dynamic var instaLink: String = "" @objc dynamic var creationTime: Date? @objc dynamic var commentsNumber: Int = 0 @objc dynamic var likesNumber: Int = 0 @objc dynamic var userHasLike: Bool = false @objc dynamic var attribution: String? @objc dynamic var highResolution: String = "" @objc dynamic var standardResolution: String = "" @objc dynamic var thumbnailResolution: String = "" @objc dynamic var locationName: String = "" @objc dynamic var coordinate: String = "" var tags = List<String>() var filters = List<String>() var fileTpe: FileType = .image override static func primaryKey() -> String? { return "imageId" } // MARK: - Constructors convenience init(imageId: String, userId: String, instaLink: String, creationTime: Date?, commentsNumber cn: Int, likesNumber ln: Int, userHasLike: Bool, attribution: String?, highResolution: String, standardResolution: String, thumbnailResolution: String, locationName: String?) { self.init() self.imageId = imageId self.userId = userId self.instaLink = instaLink self.creationTime = creationTime self.commentsNumber = cn self.likesNumber = ln self.userHasLike = userHasLike self.attribution = attribution ?? "" self.highResolution = highResolution self.standardResolution = standardResolution self.thumbnailResolution = thumbnailResolution self.locationName = locationName ?? "" } class func getImage(withId id: String) -> Image? { let predicate = NSPredicate(format: "imageId == %@", id) return Database.shared.query(entitiesOfType: Image.self, where: predicate)?.first } class func getAllImages(withUserID id: String) -> [Image] { let predicate = NSPredicate(format: "userId == %@", id) return Object.all(where: predicate) } }
mit
3061f5f86ef577bb3901b3df1e7bb937
32.093333
89
0.59589
4.791506
false
false
false
false
JStack424/CampusTownOrderApp
CSC415/InfoViewController.swift
1
2166
// // InfoViewController.swift // CSC415 // // Created by Joe Stack on 11/1/15. // Copyright © 2015 Articular Multimedia. All rights reserved. // // Name: Joseph Stack // Course: CSC 415 // Semester: Fall 2015 // Instructor: Dr. Pulimood // Project name: Guy // Description: Food ordering software for iOS // Filename: InfoViewController.swift // Description: Controller which manages the view that displays information aout the restaurant // Last modified on: 11/6/15 import UIKit @IBDesignable class InfoViewController: UIViewController { //Interface Builder references to manipulate information in the Info View @IBOutlet weak var restaurantImage: UIImageView! @IBOutlet weak var restaurantInfo: UITextView! @IBOutlet weak var restaurantName: UILabel! //Called every time the view finishes loading override func viewDidLoad() { //Set the restaurant's name and link to image restaurantImage.image = UIImage(named: "restaurant") let theName = "Generic Pizza Place" restaurantName.text = theName //Declare various information about restaurant let theAddress = "1234 Foobar rd. Ewing, NJ 08638" let thePhoneNumber = "(123) 456-7890" let theDescription = "A happy family restaurant where we serve pizza of all different kinds. More info more info more info more info" let theHours = "\n\tMonday 10:00am - 9:00pm\n\tTuesday 10:00am - 10:00pm\n\tWednesday 10:00am - 9:00pm\n\tThursday 10:00am - 9:00pm\n\tFriday 10:00am - 11:00pm\n\tSaturday 12:00pm - 11:00pm\n\tSunday 10:00am - 8:00pm" //Display restaurant's information in UI text box restaurantInfo.text = "Address: \(theAddress)\n\nPhone Number: \(thePhoneNumber)\n\nDescription: \(theDescription)\n\nHours: \(theHours)" //Change font of info section restaurantInfo.font = UIFont(name: UIFont.preferredFontForTextStyle("body").fontName, size: CGFloat(15)) //Always need to call superclass's function super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } }
gpl-2.0
bc5c889f796625d608983e49792e1b58
38.363636
225
0.692379
4.024164
false
false
false
false
BalestraPatrick/TweetsCounter
Carthage/Checkouts/Kingfisher/Tests/KingfisherTests/KingfisherManagerTests.swift
2
27800
// // KingfisherManagerTests.swift // Kingfisher // // Created by Wei Wang on 15/10/22. // // Copyright (c) 2018 Wei Wang <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import XCTest @testable import Kingfisher class KingfisherManagerTests: XCTestCase { var manager: KingfisherManager! override class func setUp() { super.setUp() LSNocilla.sharedInstance().start() } override class func tearDown() { super.tearDown() LSNocilla.sharedInstance().stop() } override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. let uuid = UUID() let downloader = ImageDownloader(name: "test.manager.\(uuid.uuidString)") let cache = ImageCache(name: "test.cache.\(uuid.uuidString)") manager = KingfisherManager(downloader: downloader, cache: cache) } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. LSNocilla.sharedInstance().clearStubs() // cleanDefaultCache() clearCaches([manager.cache]) manager = nil super.tearDown() } func testRetrieveImage() { let expectation = self.expectation(description: "wait for downloading image") let URLString = testKeys[0] _ = stubRequest("GET", URLString).andReturn(200)?.withBody(testImageData) let url = URL(string: URLString)! manager.retrieveImage(with: url, options: nil, progressBlock: nil) { image, error, cacheType, imageURL in XCTAssertNotNil(image) XCTAssertEqual(cacheType, .none) self.manager.retrieveImage(with: url, options: nil, progressBlock: nil) { image, error, cacheType, imageURL in XCTAssertNotNil(image) XCTAssertEqual(cacheType, .memory) self.manager.cache.clearMemoryCache() self.manager.retrieveImage(with: url, options: nil, progressBlock: nil) { image, error, cacheType, imageURL in XCTAssertNotNil(image) XCTAssertEqual(cacheType, .disk) cleanDefaultCache() self.manager.retrieveImage(with: url, options: [.forceRefresh], progressBlock: nil) { image, error, cacheType, imageURL in XCTAssertNotNil(image) XCTAssertEqual(cacheType, CacheType.none) expectation.fulfill() } } } } waitForExpectations(timeout: 5, handler: nil) } func testRetrieveImageWithProcessor() { cleanDefaultCache() let expectation = self.expectation(description: "wait for downloading image") let URLString = testKeys[0] _ = stubRequest("GET", URLString).andReturn(200)?.withBody(testImageData) let url = URL(string: URLString)! let p = RoundCornerImageProcessor(cornerRadius: 20) manager.retrieveImage(with: url, options: [.processor(p)], progressBlock: nil) { image, error, cacheType, imageURL in XCTAssertNotNil(image) XCTAssertEqual(cacheType, .none) self.manager.retrieveImage(with: url, options: nil, progressBlock: nil) { image, error, cacheType, imageURL in XCTAssertNotNil(image) XCTAssertEqual(cacheType, .none, "Need a processor to get correct image. Cannot get from cache, need download again.") self.manager.retrieveImage(with: url, options: [.processor(p)], progressBlock: nil) { image, error, cacheType, imageURL in XCTAssertNotNil(image) XCTAssertEqual(cacheType, .memory) self.manager.cache.clearMemoryCache() self.manager.retrieveImage(with: url, options: [.processor(p)], progressBlock: nil) { image, error, cacheType, imageURL in XCTAssertNotNil(image) XCTAssertEqual(cacheType, .disk) cleanDefaultCache() self.manager.retrieveImage(with: url, options: [.processor(p), .forceRefresh], progressBlock: nil) { image, error, cacheType, imageURL in XCTAssertNotNil(image) XCTAssertEqual(cacheType, CacheType.none) expectation.fulfill() } } } } } waitForExpectations(timeout: 5, handler: nil) } func testRetrieveImageNotModified() { let expectation = self.expectation(description: "wait for downloading image") let URLString = testKeys[0] _ = stubRequest("GET", URLString).andReturn(200)?.withBody(testImageData) let url = URL(string: URLString)! manager.retrieveImage(with: url, options: nil, progressBlock: nil) { image, error, cacheType, imageURL in XCTAssertNotNil(image) XCTAssertEqual(cacheType, CacheType.none) self.manager.cache.clearMemoryCache() _ = stubRequest("GET", URLString).andReturn(304)?.withBody("12345" as NSString) var progressCalled = false self.manager.retrieveImage(with: url, options: [.forceRefresh], progressBlock: { _, _ in progressCalled = true }) { image, error, cacheType, imageURL in XCTAssertNotNil(image) XCTAssertEqual(cacheType, CacheType.disk) XCTAssertTrue(progressCalled, "The progress callback should be called at least once since network connecting happens.") expectation.fulfill() } } waitForExpectations(timeout: 5, handler: nil) } func testSuccessCompletionHandlerRunningOnMainQueueDefaultly() { let progressExpectation = expectation(description: "progressBlock running on main queue") let completionExpectation = expectation(description: "completionHandler running on main queue") let URLString = testKeys[0] _ = stubRequest("GET", URLString).andReturn(200)?.withBody(testImageData) let url = URL(string: URLString)! manager.retrieveImage(with: url, options: nil, progressBlock: { _, _ in XCTAssertTrue(Thread.isMainThread) progressExpectation.fulfill() }, completionHandler: { _, error, _, _ in XCTAssertNil(error) XCTAssertTrue(Thread.isMainThread) completionExpectation.fulfill() }) waitForExpectations(timeout: 5, handler: nil) } func testShouldNotDownloadImageIfCacheOnlyAndNotInCache() { cleanDefaultCache() let expectation = self.expectation(description: "wait for retrieving image cache") let URLString = testKeys[0] _ = stubRequest("GET", URLString).andReturn(200)?.withBody(testImageData) let url = URL(string: URLString)! manager.retrieveImage(with: url, options: [.onlyFromCache], progressBlock: nil, completionHandler: { image, error, _, _ in XCTAssertNil(image) XCTAssertNotNil(error) XCTAssertEqual(error!.code, KingfisherError.notCached.rawValue) expectation.fulfill() }) waitForExpectations(timeout: 5, handler: nil) } func testErrorCompletionHandlerRunningOnMainQueueDefaultly() { let expectation = self.expectation(description: "running on main queue") let URLString = testKeys[0] _ = stubRequest("GET", URLString).andReturn(404) let url = URL(string: URLString)! manager.retrieveImage(with: url, options: nil, progressBlock: { _, _ in //won't be called }, completionHandler: { _, error, _, _ in XCTAssertNotNil(error) XCTAssertTrue(Thread.isMainThread) DispatchQueue.main.async { expectation.fulfill() } }) waitForExpectations(timeout: 5, handler: nil) } func testSucessCompletionHandlerRunningOnCustomQueue() { let progressExpectation = expectation(description: "progressBlock running on custom queue") let completionExpectation = expectation(description: "completionHandler running on custom queue") let URLString = testKeys[0] _ = stubRequest("GET", URLString).andReturn(200)?.withBody(testImageData) let url = URL(string: URLString)! let customQueue = DispatchQueue(label: "com.kingfisher.testQueue") manager.retrieveImage(with: url, options: [.callbackDispatchQueue(customQueue)], progressBlock: { _, _ in XCTAssertTrue(Thread.isMainThread) DispatchQueue.main.async { progressExpectation.fulfill() } }, completionHandler: { _, error, _, _ in XCTAssertNil(error) if #available(iOS 10.0, tvOS 10.0, macOS 10.12, *) { dispatchPrecondition(condition: .onQueue(customQueue)) } DispatchQueue.main.async { completionExpectation.fulfill() } }) waitForExpectations(timeout: 5, handler: nil) } func testErrorCompletionHandlerRunningOnCustomQueue() { let expectation = self.expectation(description: "running on custom queue") let URLString = testKeys[0] _ = stubRequest("GET", URLString).andReturn(404) let url = URL(string: URLString)! let customQueue = DispatchQueue(label: "com.kingfisher.testQueue") manager.retrieveImage(with: url, options: [.callbackDispatchQueue(customQueue)], progressBlock: { _, _ in //won't be called }, completionHandler: { _, error, _, _ in XCTAssertNotNil(error) if #available(iOS 10.0, tvOS 10.0, macOS 10.12, *) { dispatchPrecondition(condition: .onQueue(customQueue)) } DispatchQueue.main.async { expectation.fulfill() } }) waitForExpectations(timeout: 5, handler: nil) } func testDefaultOptionCouldApply() { let expectation = self.expectation(description: "Default options") let URLString = testKeys[0] _ = stubRequest("GET", URLString).andReturn(200)?.withBody(testImageData) let url = URL(string: URLString)! manager.defaultOptions = [.scaleFactor(2)] manager.retrieveImage(with: url, options: nil, progressBlock: nil, completionHandler: { image, _, _, _ in #if !os(macOS) XCTAssertEqual(image!.scale, 2.0) #endif expectation.fulfill() }) waitForExpectations(timeout: 5, handler: nil) } func testOriginalImageCouldBeStored() { let expectation = self.expectation(description: "waiting for cache finished") let URLString = testKeys[0] _ = stubRequest("GET", URLString).andReturn(200)?.withBody(testImageData) let url = URL(string: URLString)! let p = SimpleProcessor() let options: KingfisherOptionsInfo = [.processor(p), .cacheOriginalImage] self.manager.downloadAndCacheImage(with: url, forKey: URLString, retrieveImageTask: RetrieveImageTask(), progressBlock: nil, completionHandler: { (image, error, cacheType, url) in delay(0.1) { var imageCached = self.manager.cache.imageCachedType(forKey: URLString, processorIdentifier: p.identifier) var originalCached = self.manager.cache.imageCachedType(forKey: URLString) XCTAssertEqual(imageCached, .memory) XCTAssertEqual(originalCached, .memory) self.manager.cache.clearMemoryCache() imageCached = self.manager.cache.imageCachedType(forKey: URLString, processorIdentifier: p.identifier) originalCached = self.manager.cache.imageCachedType(forKey: URLString) XCTAssertEqual(imageCached, .disk) XCTAssertEqual(originalCached, .disk) expectation.fulfill() } }, options: options) self.waitForExpectations(timeout: 5, handler: nil) } func testOriginalImageNotBeStoredWithoutOptionSet() { let expectation = self.expectation(description: "waiting for cache finished") let URLString = testKeys[0] _ = stubRequest("GET", URLString).andReturn(200)?.withBody(testImageData) let url = URL(string: URLString)! let p = SimpleProcessor() let options: KingfisherOptionsInfo = [.processor(p)] manager.downloadAndCacheImage(with: url, forKey: URLString, retrieveImageTask: RetrieveImageTask(), progressBlock: nil, completionHandler: { (image, error, cacheType, url) in delay(0.1) { var imageCached = self.manager.cache.imageCachedType(forKey: URLString, processorIdentifier: p.identifier) var originalCached = self.manager.cache.imageCachedType(forKey: URLString) XCTAssertEqual(imageCached, .memory) XCTAssertEqual(originalCached, .none) self.manager.cache.clearMemoryCache() imageCached = self.manager.cache.imageCachedType(forKey: URLString, processorIdentifier: p.identifier) originalCached = self.manager.cache.imageCachedType(forKey: URLString) XCTAssertEqual(imageCached, .disk) XCTAssertEqual(originalCached, .none) expectation.fulfill() } }, options: options) waitForExpectations(timeout: 5, handler: nil) } func testCouldProcessOnOriginalImage() { let expectation = self.expectation(description: "waiting for downloading finished") let URLString = testKeys[0] manager.cache.store(testImage, original: testImageData as Data, forKey: URLString, processorIdentifier: DefaultImageProcessor.default.identifier, cacheSerializer: DefaultCacheSerializer.default, toDisk: true) { let p = SimpleProcessor() let cached = self.manager.cache.imageCachedType(forKey: URLString, processorIdentifier: p.identifier) XCTAssertFalse(cached.cached) // No downloading will happen self.manager.retrieveImage(with: URL(string: URLString)!, options: [.processor(p)], progressBlock: nil) { image, error, cacheType, url in XCTAssertNotNil(image) XCTAssertEqual(cacheType, .none) XCTAssertTrue(p.processed) // The processed image should be cached delay(0.1) { let cached = self.manager.cache.imageCachedType(forKey: URLString, processorIdentifier: p.identifier) XCTAssertTrue(cached.cached) expectation.fulfill() } } } waitForExpectations(timeout: 5, handler: nil) } func testCacheOriginalImageWithOriginalCache() { cleanDefaultCache() let expectation = self.expectation(description: "wait for downloading image") let URLString = testKeys[0] let originalCache = ImageCache(name: "test-originalCache") // Clear original cache first. originalCache.clearMemoryCache() originalCache.clearDiskCache { _ = stubRequest("GET", URLString).andReturn(200)?.withBody(testImageData) let url = URL(string: URLString)! let p = RoundCornerImageProcessor(cornerRadius: 20) self.manager.retrieveImage(with: url, options: [.processor(p), .cacheOriginalImage, .originalCache(originalCache)], progressBlock: nil) { image, error, cacheType, imageURL in delay(0.1) { let originalCached = originalCache.imageCachedType(forKey: URLString) XCTAssertEqual(originalCached, .memory) expectation.fulfill() } } } waitForExpectations(timeout: 5, handler: nil) } func testCouldProcessOnOriginalImageWithOriginalCache() { cleanDefaultCache() let expectation = self.expectation(description: "waiting for downloading finished") let URLString = testKeys[0] let originalCache = ImageCache(name: "test-originalCache") // Clear original cache first. originalCache.clearMemoryCache() originalCache.clearDiskCache { originalCache.store(testImage, original: testImageData as Data, forKey: URLString, processorIdentifier: DefaultImageProcessor.default.identifier, cacheSerializer: DefaultCacheSerializer.default, toDisk: true) { let p = SimpleProcessor() let cached = self.manager.cache.imageCachedType(forKey: URLString, processorIdentifier: p.identifier) XCTAssertFalse(cached.cached) // No downloading will happen self.manager.retrieveImage(with: URL(string: URLString)!, options: [.processor(p), .originalCache(originalCache)], progressBlock: nil) { image, error, cacheType, url in XCTAssertNotNil(image) XCTAssertEqual(cacheType, .none) XCTAssertTrue(p.processed) // The processed image should be cached delay(0.1) { let cached = self.manager.cache.imageCachedType(forKey: URLString, processorIdentifier: p.identifier) XCTAssertTrue(cached.cached) expectation.fulfill() } } } } waitForExpectations(timeout: 5, handler: nil) } func testImageShouldOnlyFromMemoryCacheOrRefreshCanBeGotFromMemory() { let expectation = self.expectation(description: "only from memory cache or refresh") let URLString = testKeys[0] _ = stubRequest("GET", URLString).andReturn(200)?.withBody(testImageData) let url = URL(string: URLString)! delay(0.1) { // Wait for disk cache cleaning self.manager.retrieveImage(with: url, options: [.fromMemoryCacheOrRefresh], progressBlock: nil) { image, _, type, _ in // Can download and cache normally XCTAssertNotNil(image) XCTAssertEqual(type, .none) // Can still be got from memory even when disk cache cleared. self.manager.cache.clearDiskCache { self.manager.retrieveImage(with: url, options: [.fromMemoryCacheOrRefresh], progressBlock: nil) { image, _, type, _ in XCTAssertNotNil(image) XCTAssertEqual(type, .memory) expectation.fulfill() } } } } waitForExpectations(timeout: 5, handler: nil) } func testImageShouldOnlyFromMemoryCacheOrRefreshCanRefreshIfNotInMemory() { let expectation = self.expectation(description: "only from memory cache or refresh") let URLString = testKeys[0] _ = stubRequest("GET", URLString).andReturn(200)?.withBody(testImageData) let url = URL(string: URLString)! manager.retrieveImage(with: url, options: [.fromMemoryCacheOrRefresh], progressBlock: nil) { image, _, type, _ in // Can download and cache normally XCTAssertNotNil(image) XCTAssertEqual(type, .none) XCTAssertEqual(self.manager.cache.imageCachedType(forKey: URLString), .memory) self.manager.cache.clearMemoryCache() XCTAssertEqual(self.manager.cache.imageCachedType(forKey: URLString), .disk) self.manager.retrieveImage(with: url, options: [.fromMemoryCacheOrRefresh], progressBlock: nil) { image, _, type, _ in XCTAssertNotNil(image) XCTAssertEqual(type, .none) XCTAssertEqual(self.manager.cache.imageCachedType(forKey: URLString), .memory) expectation.fulfill() } } waitForExpectations(timeout: 5, handler: nil) } func testShouldDownloadAndCacheProcessedImage() { let expectation = self.expectation(description: "waiting for downloading and cache") let URLString = testKeys[0] _ = stubRequest("GET", URLString).andReturn(200)?.withBody(testImageData) let url = URL(string: URLString)! let size = CGSize(width: 1, height: 1) let processor = ResizingImageProcessor(referenceSize: size) manager.retrieveImage(with: url, options: [.processor(processor)], progressBlock: nil) { image, _, type, _ in // Can download and cache normally XCTAssertNotNil(image) XCTAssertEqual(image!.size, size) XCTAssertEqual(type, .none) self.manager.cache.clearMemoryCache() XCTAssertEqual(self.manager.cache.imageCachedType(forKey: URLString, processorIdentifier: processor.identifier), .disk) self.manager.retrieveImage(with: url, options: [.processor(processor)], progressBlock: nil) { image, _, type, _ in XCTAssertNotNil(image) XCTAssertEqual(image!.size, size) XCTAssertEqual(type, .disk) expectation.fulfill() } } waitForExpectations(timeout: 5, handler: nil) } #if os(iOS) || os(tvOS) || os(watchOS) func testShouldApplyImageModifierWhenDownload() { let expectation = self.expectation(description: "waiting for downloading and cache") let URLString = testKeys[0] _ = stubRequest("GET", URLString).andReturn(200)?.withBody(testImageData) let url = URL(string: URLString)! var modifierCalled = false let modifier = AnyImageModifier { image in modifierCalled = true return image.withRenderingMode(.alwaysTemplate) } manager.retrieveImage(with: url, options: [.imageModifier(modifier)], progressBlock: nil) { image, _, _, _ in XCTAssertTrue(modifierCalled) XCTAssertEqual(image?.renderingMode, .alwaysTemplate) expectation.fulfill() } waitForExpectations(timeout: 5, handler: nil) } func testShouldApplyImageModifierWhenLoadFromMemoryCache() { let expectation = self.expectation(description: "waiting for downloading and cache") let URLString = testKeys[0] let url = URL(string: URLString)! var modifierCalled = false let modifier = AnyImageModifier { image in modifierCalled = true return image.withRenderingMode(.alwaysTemplate) } manager.cache.store(testImage, forKey: URLString) manager.retrieveImage(with: url, options: [.imageModifier(modifier)], progressBlock: nil) { image, _, type, _ in XCTAssertTrue(modifierCalled) XCTAssertEqual(type, .memory) XCTAssertEqual(image?.renderingMode, .alwaysTemplate) expectation.fulfill() } waitForExpectations(timeout: 5, handler: nil) } func testShouldApplyImageModifierWhenLoadFromDiskCache() { let expectation = self.expectation(description: "waiting for downloading and cache") let URLString = testKeys[0] let url = URL(string: URLString)! var modifierCalled = false let modifier = AnyImageModifier { image in modifierCalled = true return image.withRenderingMode(.alwaysTemplate) } manager.cache.store(testImage, forKey: URLString) { self.manager.cache.clearMemoryCache() self.manager.retrieveImage(with: url, options: [.imageModifier(modifier)], progressBlock: nil) { image, _, type, _ in XCTAssertTrue(modifierCalled) XCTAssertEqual(type, .disk) XCTAssertEqual(image?.renderingMode, .alwaysTemplate) expectation.fulfill() } } waitForExpectations(timeout: 5, handler: nil) } #endif } class SimpleProcessor: ImageProcessor { public let identifier = "id" var processed = false /// Initialize a `DefaultImageProcessor` public init() {} /// Process an input `ImageProcessItem` item to an image for this processor. /// /// - parameter item: Input item which will be processed by `self` /// - parameter options: Options when processing the item. /// /// - returns: The processed image. /// /// - Note: See documentation of `ImageProcessor` protocol for more. public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? { processed = true switch item { case .image(let image): return image case .data(let data): return Kingfisher<Image>.image( data: data, scale: options.scaleFactor, preloadAllAnimationData: options.preloadAllAnimationData, onlyFirstFrame: options.onlyLoadFirstFrame) } } }
mit
9f4165f1b0609f9afa7ec091ca2f3ce0
41.24924
153
0.595791
5.524642
false
true
false
false
brendonjustin/FLCLFilmstripsCollectionLayout
FLCLFilmstripsCollectionLayout/FilmstripsCollectionLayout.swift
1
19036
// // FilmstripsCollectionLayout.swift // FilmstripsCollectionLayout // // Created by Brendon Justin on 10/19/14. // Copyright (c) 2014 Naga Softworks, LLC. All rights reserved. // import UIKit /** Collection view layout that shows each section in a film strip, i.e. a horizontally scrolling list. Supports vertical scrolling only. Otherwise similar to a UICollectionViewFlowLayout layout. */ // Including this makes our properties not @IBInspectable in a storyboard, // so skip it as of 11/25/14. //@objc(FLCLFilmstripsCollectionLayout) public class FilmstripsCollectionLayout: UICollectionViewLayout { /// Reusable view type for section headers. Only provided as a convenience; /// matches `UICollectionElementKindSectionHeader`. public class var FilmstripsCollectionElementKindSectionHeader: String { get { return UICollectionElementKindSectionHeader } } /// Inspired by `UICollectionViewFlowLayout`'s `itemSize`. Note that self-sizing cells are unsupported. @IBInspectable public var itemSize: CGSize = CGSizeZero /// Inspired by `UICollectionViewFlowLayout`'s `minimumLineSpacing`. @IBInspectable public var lineSpacing: CGFloat = 0 /// Inspired by `UICollectionViewFlowLayout`'s `minimumInteritemSpacing`. @IBInspectable public var itemSpacing: CGFloat = 0 /// Meant to emulate `UICollectionViewFlowLayout`'s `sectionInset`. /// Each property will be used according to this correspondence with UIEdgeInsets: /// x: left, y: top, width: right, height: bottom. /// Currently only the x coordinate of the origin is used, i.e. the left inset. @IBInspectable public var sectionInset: CGRect = CGRectZero /// Emulates `UICollectionViewFlowLayout`'s `headerReferenceSize` unless set to CGSizeZero. public var headerReferenceSize: CGSize = CGSizeZero /// Dictionary of section numbers to scroll offsets private var cumulativeOffsets: [Int : CGFloat] = [:] private var currentPanOffsets: [Int : CGFloat] = [:] private var sectionDynamicItems: [Int : SectionDynamicItem] = [:] private var sectionDynamicBehaviors: [Int : [UIDynamicBehavior]] = [:] private var springsForFirstItems: [Int : UISnapBehavior] = [:] private var springsForLastItems: [Int : UISnapBehavior] = [:] /// Available as a convenience for when `CGRect` calculations require /// limiting to positive X and Y coordinates. lazy private var positiveRect = CGRect(x: 0, y: 0, width: Int.max, height: Int.max) /// Animator to animate horizontal cell scrolling lazy private var dynamicAnimator: UIDynamicAnimator = UIDynamicAnimator() /// The total height of a single section, including line spacing. private var sectionHeightWithSpacing: CGFloat { get { let size = self.itemSize let lineSpacing = self.lineSpacing let headerSize = self.headerReferenceSize let sectionHeight = headerSize.height + lineSpacing + size.height + lineSpacing return sectionHeight } } /// The total width of a single cell, including cell spacing. private var cellWidthWithSpacing: CGFloat { get { let size = self.itemSize let itemWidth = size.width let layoutWidth = self.collectionView!.frame.width let cellSpacing = self.itemSpacing let widthPlusPaddingPerCell = itemWidth + cellSpacing return widthPlusPaddingPerCell } } // MARK: Collection View Layout override public func prepareForTransitionToLayout(newLayout: UICollectionViewLayout!) { // Stop animating if we're about to do a layout transition self.dynamicAnimator.removeAllBehaviors() self.springsForFirstItems.removeAll(keepCapacity: true) self.springsForLastItems.removeAll(keepCapacity: true) } override public func layoutAttributesForElementsInRect(rect: CGRect) -> [AnyObject]? { let positiveRect = rect.rectByIntersecting(self.positiveRect) let cellWidthWithSpacing = self.cellWidthWithSpacing let sectionsBeforeRect = self.section(forYCoordinate: positiveRect.minY) let lastPossibleSectionInRect = self.section(forYCoordinate: positiveRect.maxY) let totalSections = self.collectionView?.numberOfSections() ?? 0 if totalSections == 0 { return [] } let firstSectionInRect = Int(min(sectionsBeforeRect, totalSections - 1)) let lastSectionInRect = Int(min(totalSections, lastPossibleSectionInRect)) let sectionsInRect = firstSectionInRect..<lastSectionInRect let maxItemsPerSectionInRect = Int(ceil(positiveRect.width / cellWidthWithSpacing)) let leftXInset = self.sectionInset.minX let itemsPerSectionInRect: [Int : [Int]] = { () -> [Int : [Int]] in var itemSectionsAndNumbers = [Int : [Int]]() for section in sectionsInRect { let scrollOffsetForSection = self.totalOffset(forSection: section) let xOffsetForFirstItem: CGFloat = floor(max(positiveRect.minX - leftXInset, 0.0) / ceil(cellWidthWithSpacing)) let itemsInSection = self.collectionView?.numberOfItemsInSection(section) ?? 0 let firstPossibleItemInRect = Int(ceil(positiveRect.minX / max(xOffsetForFirstItem, CGFloat(1)))) let firstItemInRect = Int(min(itemsInSection, firstPossibleItemInRect)) var itemNumbers = [Int]() for itemNumber in firstItemInRect..<itemsInSection { let xOffsetForItemNumber: CGFloat = ceil(cellWidthWithSpacing * CGFloat(itemNumber)) + xOffsetForFirstItem if xOffsetForItemNumber <= positiveRect.maxX { itemNumbers.append(itemNumber) } else { break } } itemSectionsAndNumbers[section] = itemNumbers } return itemSectionsAndNumbers }() var attributes: [UICollectionViewLayoutAttributes] = [] for (section, itemNumbers) in itemsPerSectionInRect { // Assume section headers are present if the header reference size is set. if self.headerReferenceSize != CGSizeZero { attributes.append(self.layoutAttributesForSupplementaryViewOfKind(UICollectionElementKindSectionHeader, atIndexPath: NSIndexPath(forItem: 0, inSection: section))) } for itemNumber in itemNumbers { attributes.append(self.layoutAttributesForItemAtIndexPath(NSIndexPath(forItem: itemNumber, inSection: section))) } } return attributes } override public func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes! { let attributes = UICollectionViewLayoutAttributes(forCellWithIndexPath: indexPath) attributes.frame = { () -> CGRect in let size = self.itemSize let headerSize = self.headerReferenceSize let xOffsetForItemNumber: CGFloat = ceil(self.cellWidthWithSpacing * CGFloat(indexPath.item)) + self.sectionInset.minX let yOffsetForSectionNumber: CGFloat = ceil(self.sectionHeightWithSpacing * CGFloat(indexPath.section)) let section = indexPath.section let frame = CGRect(origin: CGPoint(x: xOffsetForItemNumber + self.totalOffset(forSection: section), y: headerSize.height + yOffsetForSectionNumber), size: size) return frame }() return attributes } override public func layoutAttributesForSupplementaryViewOfKind(elementKind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes! { let attributes = UICollectionViewLayoutAttributes(forSupplementaryViewOfKind: elementKind, withIndexPath: indexPath) attributes.frame = { () -> CGRect in let size = self.headerReferenceSize let yOffsetForSectionNumber: CGFloat = ceil(self.sectionHeightWithSpacing * CGFloat(indexPath.section)) let section = indexPath.section let frame = CGRect(origin: CGPoint(x: 0, y: yOffsetForSectionNumber), size: size) return frame }() return attributes } override public func collectionViewContentSize() -> CGSize { // Find the size needed of the rect that starts at 0,0 and ends at the bottom right // coordinates of the last collection view item. If the size is wider than the collection view's // frame, trim it down, then return it. let numberOfSections = self.collectionView?.numberOfSections() ?? 0 if numberOfSections == 0 { return CGSizeZero } let itemsInLastSection = self.collectionView?.numberOfItemsInSection(numberOfSections - 1) ?? 0 if itemsInLastSection == 0 { return CGSizeZero } var collectionViewFrame = self.collectionView?.frame ?? CGRectZero var cvHeight = collectionViewFrame.height var cvWidth = collectionViewFrame.width let contentHeight = max(CGFloat(numberOfSections) * self.sectionHeightWithSpacing, cvHeight) let contentFrame = CGRect(origin: CGPointZero, size: CGSize(width: cvWidth, height: contentHeight)) let widthLimitingFrame = CGRect(origin: CGPointZero, size: CGSize(width: collectionViewFrame.width, height: CGFloat.max)) let widthLimitedContentFrame = CGRectIntersection(contentFrame, widthLimitingFrame) return widthLimitedContentFrame.size } public override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool { // We do not depend on the collection view's bounds. return false } // MARK: Offset Calculation /** Calculate the total X offset for a single section, taking into account past panning and panning from the current pan gesture, if any. */ private func totalOffset(forSection section: Int) -> CGFloat { let cumulativeOffset = self.cumulativeOffsets[section] ?? 0 let panOffset = self.currentPanOffsets[section] ?? 0 return cumulativeOffset + panOffset } // MARK: Section and Item/Row Calculation /** Find the section number corresponding to a Y-coordinate in the collection view. May be greater than the actual number of sections in the collection view. */ private func section(forYCoordinate coordinate: CGFloat) -> Int { let sectionHeight = self.sectionHeightWithSpacing let sectionForCoordinate = Int(floor(coordinate / sectionHeight)) return sectionForCoordinate } /** Get the item number that should appear at the specified coordinate. :param: forXCoordinate The X coordinate for which to get the item */ private func itemNumber(forXCoordinate coordinate: CGFloat, inSection section: Int) -> Int { let itemForCoordinate = Int(floor(coordinate / self.cellWidthWithSpacing)) return itemForCoordinate } /** Get the index paths corresponding to all items in a section that are currently or are close to being displayed, e.g. the items that are just outside of the frame. */ private func indexPathsCurrentlyDisplayed(inSection section: Int) -> [NSIndexPath] { let xOffset = self.totalOffset(forSection: section) let minXCoordinate = -xOffset let itemWidth = self.itemSize.width let collectionViewWidth = self.collectionView!.frame.width let firstDisplayedItem = self.itemNumber(forXCoordinate: minXCoordinate, inSection: section) let lastDisplayedItem = self.itemNumber(forXCoordinate: minXCoordinate + collectionViewWidth + itemWidth, inSection: section) let lastItemInSection = self.collectionView!.numberOfItemsInSection(section) let firstItem = max(firstDisplayedItem - 1, 0) let lastItem = max(min(lastDisplayedItem + 1, lastItemInSection), firstItem) let paths = (firstItem...lastItem).map { (itemNumber: Int) -> NSIndexPath in return NSIndexPath(forItem: itemNumber, inSection: section) } return paths } /** Get the total width that the cells in a section would fill. */ private func width(ofSection sectionNumber: Int) -> CGFloat { let itemsInSection = self.collectionView!.numberOfItemsInSection(sectionNumber) return CGFloat(itemsInSection) * self.cellWidthWithSpacing } // MARK: Dynamics /** Add "springs" (snap behaviors) to the start and end of a section, as necessary, to snap the first or last cell in a section to the left or right edge of the collection view, respectively. */ private func addSpringsAsNecessary(toDynamicItem sectionDynamicItem: SectionDynamicItem, forOffset offset: CGFloat, inSection sectionNumber: Int) { if (offset > 0) { if let behavior = self.springsForFirstItems[sectionNumber] { // empty } else { let springBehavior = UISnapBehavior(item: sectionDynamicItem, snapToPoint: CGPoint(x: 0, y: sectionDynamicItem.center.y))! springBehavior.damping = 0.75 self.springsForFirstItems[sectionNumber] = springBehavior self.dynamicAnimator.addBehavior(springBehavior) } } let collectionView = self.collectionView! let viewWidth = collectionView.frame.width let widthOfSection = self.width(ofSection: sectionNumber) let rightSideSnapXCoord: CGFloat = { if viewWidth > widthOfSection { return 0 } else { return -(widthOfSection + self.sectionInset.width - collectionView.frame.width) } }() if (offset < rightSideSnapXCoord) { if let behavior = self.springsForLastItems[sectionNumber] { // empty } else { let springBehavior = UISnapBehavior(item: sectionDynamicItem, snapToPoint: CGPoint(x: rightSideSnapXCoord, y: sectionDynamicItem.center.y))! springBehavior.damping = 0.75 self.springsForLastItems[sectionNumber] = springBehavior self.dynamicAnimator.addBehavior(springBehavior) } } } /** Get the existing dynamic item, or create a new one if no item exists, for a section. */ private func dynamicItem(forSection sectionNumber: Int) -> SectionDynamicItem { if let sectionItem = self.sectionDynamicItems[sectionNumber] { return sectionItem } else { let sectionItem = SectionDynamicItem(sectionNumber: sectionNumber) return sectionItem } } // MARK: Pan Gesture Action /** Receive a pan gesture to pan the items in a row. The pan must take place within our collection view's frame. */ @IBAction func pan(recognizer: UIPanGestureRecognizer) { let collectionView = self.collectionView! let translation = recognizer.translationInView(collectionView) let sectionOfPan = { () -> Int in let currentLocation = recognizer.locationInView(collectionView) let startingYCoordinate = currentLocation.y - translation.y let section = self.section(forYCoordinate: startingYCoordinate) return section }() // Update the amount of panning done let currentPanOffset = translation.x self.currentPanOffsets[sectionOfPan] = currentPanOffset let indexPaths = self.indexPathsCurrentlyDisplayed(inSection: sectionOfPan) let context = UICollectionViewLayoutInvalidationContext() context.invalidateItemsAtIndexPaths(indexPaths) self.invalidateLayoutWithContext(context) let newCumulativeOffset = self.totalOffset(forSection: sectionOfPan) let sectionDynamicItem = self.dynamicItem(forSection: sectionOfPan) sectionDynamicItem.center = CGPoint(x: newCumulativeOffset, y: 0) self.sectionDynamicItems[sectionOfPan] = sectionDynamicItem if recognizer.state == .Ended { self.cumulativeOffsets[sectionOfPan] = newCumulativeOffset self.currentPanOffsets[sectionOfPan] = nil let velocity = recognizer.velocityInView(self.collectionView) let xVel = velocity.x sectionDynamicItem.delegate = self // Require a minimum velocity to continue scrolling after the pan is finished. if abs(xVel) < 75 { return } let items = [sectionDynamicItem] let behavior = UIPushBehavior(items: items, mode: .Instantaneous) behavior.pushDirection = CGVector(dx: xVel > 0 ? 1 : -1, dy: 0) behavior.magnitude = abs(xVel) let resistance = UIDynamicItemBehavior(items: items) resistance.resistance = 1 self.dynamicAnimator.addBehavior(behavior) self.dynamicAnimator.addBehavior(resistance) self.sectionDynamicBehaviors[sectionOfPan] = [behavior, resistance] } else { if let behaviors = self.sectionDynamicBehaviors.removeValueForKey(sectionOfPan) { for behavior in behaviors { self.dynamicAnimator.removeBehavior(behavior) } } if let snapbehavior = self.springsForFirstItems.removeValueForKey(sectionOfPan) { self.dynamicAnimator.removeBehavior(snapbehavior) } if let snapbehavior = self.springsForLastItems.removeValueForKey(sectionOfPan) { self.dynamicAnimator.removeBehavior(snapbehavior) } sectionDynamicItem.delegate = nil self.addSpringsAsNecessary(toDynamicItem: sectionDynamicItem, forOffset: newCumulativeOffset, inSection: sectionOfPan) } } } extension FilmstripsCollectionLayout: SectionDynamicItemDelegate { internal func itemDidMove(sectionDynamicItem: SectionDynamicItem) { let newCenter = sectionDynamicItem.center let sectionNumber = sectionDynamicItem.sectionNumber let cumulativeOffset = (self.currentPanOffsets[sectionNumber] ?? 0) + newCenter.x self.cumulativeOffsets[sectionNumber] = cumulativeOffset self.addSpringsAsNecessary(toDynamicItem: sectionDynamicItem, forOffset: cumulativeOffset, inSection: sectionNumber) let indexPaths = self.indexPathsCurrentlyDisplayed(inSection: sectionNumber) let context = UICollectionViewFlowLayoutInvalidationContext() context.invalidateItemsAtIndexPaths(indexPaths) self.invalidateLayoutWithContext(context) } }
mit
1c3a0de8a99424a6d7239d796ef5384b
43.269767
178
0.674617
5.327736
false
false
false
false
kevinup7/S4HeaderExtensions
Sources/S4HeaderExtensions/MessageHeaders/Upgrade.swift
1
2385
import S4 extension Headers { /** The `Upgrade` header field is intended to provide a simple mechanism for transitioning from HTTP/1.1 to some other protocol on the same connection. A client MAY send a list of protocols in the `Upgrade` header field of a request to invite the server to switch to one or more of those protocols, in order of descending preference, before sending the final response. A server MAY ignore a received `Upgrade` header field if it wishes to continue using the current protocol on that connection. `Upgrade` cannot be used to insist on a protocol change. ## Example Headers `Upgrade: HTTP/2.0, SHTTP/1.3, IRC/6.9, RTA/x11` `Upgrade: websocket` ## Examples var request = Request() request.headers.upgrade = [UpgradeProtocol(name: "HTTP", version: "2.0"), UpgradeProtocol(name: "SHTTP", version: "1.3")] var request = Request() request.headers.upgrade = [UpgradeProtocol(name: "websocket")] - seealso: [RFC7230](http://tools.ietf.org/html/rfc7230#section-6.7) */ public var upgrade: [UpgradeProtocol]? { get { return UpgradeProtocol.values(fromHeader: headers["Upgrade"]) } set { headers["Upgrade"] = newValue?.headerValue } } } public struct UpgradeProtocol: Equatable { let name: String let version: String? init(name: String, version: String? = nil) { self.name = name self.version = version } } extension UpgradeProtocol: HeaderValueInitializable { public init?(headerValue: String) { let split = headerValue.components(separatedBy: "/") if split.count == 2 { self = UpgradeProtocol(name: split[0].trim(), version: split[1].trim()) } else if split.count == 1 { self = UpgradeProtocol(name: split[0].trim()) } else { return nil } } } extension UpgradeProtocol: HeaderValueRepresentable { public var headerValue: String { if let version = version { return "\(name)/\(version)" } else { return name } } } public func ==(lhs: UpgradeProtocol, rhs: UpgradeProtocol) -> Bool { return lhs.name == rhs.name && lhs.version == rhs.version }
mit
63786958482a1442f18c1176fd46b831
29.974026
133
0.608805
4.344262
false
false
false
false
zmian/xcore.swift
Sources/Xcore/SwiftUI/Components/Toggle/Toggle+Inits.swift
1
1580
// // Xcore // Copyright © 2021 Xcore // MIT license, see LICENSE file for details // import SwiftUI extension Toggle { /// Creates a toggle that generates its label from a title and subtitle strings. /// /// - Parameters: /// - title: A string that describes the purpose of the toggle. /// - subtitle: A string that provides further information about the toggle. /// - isOn: A binding to a property that determines whether the toggle is on or off. public init<S1, S2>( _ title: S1, subtitle: S2?, isOn: Binding<Bool>, spacing: CGFloat? = nil ) where Label == _XIVTSSV, S1: StringProtocol, S2: StringProtocol { self.init(isOn: isOn) { _XIVTSSV( title: title, subtitle: subtitle, spacing: spacing ) } } /// Creates a toggle that generates its label from a title text and subtitle /// string. /// /// - Parameters: /// - title: A text that describes the purpose of the toggle. /// - subtitle: A string that provides further information about the toggle. /// - isOn: A binding to a property that determines whether the toggle is on or off. public init( _ title: Text, subtitle: Text?, isOn: Binding<Bool>, spacing: CGFloat? = nil ) where Label == _XIVTSSV { self.init(isOn: isOn) { _XIVTSSV( title: title, subtitle: subtitle, spacing: spacing ) } } }
mit
4b58c984f10656bc5548a4b5a301f982
29.365385
90
0.559848
4.373961
false
false
false
false
djschilling/SOPA-iOS
SOPA/JustPlay/JustPlayGameScene.swift
1
6493
// // LevelModeGameScene.swift // SOPA // // Created by Raphael Schilling on 23.04.18. // Copyright © 2018 David Schilling. All rights reserved. // import Foundation import SpriteKit class JustPlayGameScene: GameScene { var restartButton: SpriteButton? var levelChoiceButton: SpriteButton? var start: NSDate? var storeLevelButton: SpriteButton? let levelBackup: Level override init(size: CGSize, proportionSet: ProportionSet, level: Level) { levelBackup = Level(level: level) super.init(size: size, proportionSet: proportionSet, level: level) startCounter() } private func startCounter() { start = NSDate() } private func stopCounter() -> Double { let end = NSDate() let difference: Double = end.timeIntervalSince(start! as Date) print(difference) return difference } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func addButtons() { restartButton = SpriteButton(imageNamed: "restart", onClick: restartLevel) restartButton!.size.height = proportionSet.buttonSize() restartButton!.size.width = proportionSet.buttonSize() restartButton!.position = proportionSet.restartButtonPos() addChild(restartButton!) levelChoiceButton = SpriteButton(imageNamed: "LevelChoice", onClick: loadLevelChoiceScene) levelChoiceButton!.size.height = proportionSet.levelChoiceSize() levelChoiceButton!.size.width = proportionSet.levelChoiceSize() levelChoiceButton!.position = proportionSet.levelChoicePos() addChild(levelChoiceButton!) storeLevelButton = SpriteButton(imageNamed: "restart", onClick: saveLevel) storeLevelButton!.size.height = proportionSet.buttonSize() storeLevelButton!.size.width = proportionSet.buttonSize() storeLevelButton!.position = CGPoint(x: size.width - proportionSet.levelChoiceSize(), y: size.height - proportionSet.levelChoiceSize()) addChild(storeLevelButton!) } func saveLevel() { storeLevelButton!.position = CGPoint(x:-100,y:0) ResourcesManager.getInstance().levelService!.saveLevel(level: levelBackup) } func restartLevel() { //LogFileHandler.logger.write("LevelMode; restart; \(gameService.getLevel().id!); \(super.gameService.getLevel().movesCounter); -1; \(stopCounter()); \(NSDate())\n") ResourcesManager.getInstance().storyService?.reloadJustPlayGameScene(level: levelBackup) } func loadLevelChoiceScene() { //LogFileHandler.logger.write("LevelMode; end; \(gameService.getLevel().id!); \(super.gameService.getLevel().movesCounter); -1; \(stopCounter()); \(NSDate())\n") ResourcesManager.getInstance().storyService?.loadLevelCoiceSceneFromLevelModeScene() } override func onSolvedGame() { let time = stopCounter() let level = gameService.getLevel() let levelService = ResourcesManager.getInstance().levelService let levelResult = levelService!.calculateLevelResult(level: level) levelResult.time = time //LogFileHandler.logger.write("LevelMode; solved; \(levelResult.levelId); \(levelResult.moveCount); \(levelResult.stars); \(time); \(NSDate())\n") DispatchQueue.main.asyncAfter(deadline: .now() + 0.7, execute: { self.animateLevelSolved(levelResult: levelResult) }) } private func animateLevelSolved(levelResult: LevelResult) { let fadeOutGameField: SKAction = SKAction.fadeAlpha(to: 0.0, duration: 0.3) let moveActionLabels = SKAction.move(to: proportionSet.moveLabelsPos2(), duration: 0.5) moveActionLabels.timingMode = SKActionTimingMode.easeInEaseOut gameFieldNode?.run(fadeOutGameField) DispatchQueue.main.asyncAfter(deadline: .now() + 0.2, execute: {self.movesLabels.run(moveActionLabels)}) DispatchQueue.main.asyncAfter(deadline: .now() + 0.6) { self.addStars(levelResult: levelResult) } DispatchQueue.main.asyncAfter(deadline: .now() + 0.6) { self.addNextLevelButton() } } private func addNextLevelButton() { let nextLevelButton = SpriteButton(imageNamed: "NextLevel") { ResourcesManager.getInstance().storyService?.loadNextJustPlayGameScene() } nextLevelButton.size = CGSize(width: proportionSet.buttonSize(), height: proportionSet.buttonSize()) nextLevelButton.alpha = 0.0 nextLevelButton.position.y = proportionSet.restartButtonPos().y nextLevelButton.position.x = size.width - proportionSet.restartButtonPos().x addChild(nextLevelButton) nextLevelButton.run(SKAction.fadeAlpha(to: 1.0, duration: 0.2)) } private func addStars(levelResult: LevelResult) { let starSizeHidden = CGSize(width: 0, height: 0) let star1 = SKSpriteNode(imageNamed: "star_score" ) star1.size = starSizeHidden star1.position = CGPoint(x: proportionSet.starSize().width * proportionSet.starLRX(), y: proportionSet.starLRY()) addChild(star1) let star2 = SKSpriteNode(imageNamed: levelResult.stars >= 2 ? "star_score": "starSW_score") star2.size = starSizeHidden star2.position = CGPoint(x: size.width / 2, y: proportionSet.starMY()) addChild(star2) let star3 = SKSpriteNode(imageNamed: levelResult.stars == 3 ? "star_score": "starSW_score") star3.size = starSizeHidden star3.position = CGPoint(x: size.width - proportionSet.starSize().width * proportionSet.starLRX(), y: proportionSet.starLRY()) addChild(star3) let appearStar = SKAction.resize(toWidth: proportionSet.starSize().width, height: proportionSet.starSize().height, duration: 0.1) star1.run(appearStar) DispatchQueue.main.asyncAfter(deadline: .now() + 0.15) { star2.run(appearStar) } DispatchQueue.main.asyncAfter(deadline: .now() + 0.30) { star3.run(appearStar) } } private func hideButtons() { restartButton!.isUserInteractionEnabled = false restartButton!.isHidden = true levelChoiceButton!.isUserInteractionEnabled = false levelChoiceButton!.isHidden = true } }
apache-2.0
8cae19e6c72f105d211b6426ae821e5c
41.155844
173
0.664356
4.401356
false
false
false
false
pcperini/Thrust
Thrust/Source/Double+ThrustExtensions.swift
1
662
// // Double+ThrustExtensions.swift // Thrust // // Created by Patrick Perini on 8/13/14. // Copyright (c) 2014 pcperini. All rights reserved. // import Foundation // MARK: Operators /// Exponential operator. infix operator ** { associativity left precedence 160 } func **(lhs: Double, rhs: Double) -> Double { return pow(lhs, rhs) } infix operator **= { precedence 90 } func **=(inout lhs: Double, rhs: Double) { lhs = lhs ** rhs } /// Near-equivalence (more-or-less-equal) operator. infix operator ><= {} /// Returns true if both values are equal when rounded. func ><=(lhs: Double, rhs: Double) -> Bool { return round(lhs) == round(rhs) }
mit
d4a42eee3037ec9d34d2ee18694def1b
21.862069
55
0.660121
3.377551
false
false
false
false
chrisjmendez/swift-exercises
Walkthroughs/MyPresentation/Carthage/Checkouts/Presentation/Pod/Tests/Specs/Animations/PopAnimationSpec.swift
8
1622
import Quick import Nimble import Presentation class PopAnimationSpec: QuickSpec { override func spec() { describe("PopAnimation") { var animation: PopAnimation! var view: UIView! var content: Content! var superview: UIView! beforeEach { view = SpecHelper.imageView() content = Content(view: view, position: Position(left: 0.2, bottom: 0.2)) superview = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 300.0, height: 200.0)) animation = PopAnimation(content: content, duration: 0) } describe("#init") { it("hides view") { expect(view.hidden).to(beTrue()) } } describe("#moveWith") { context("with superview") { beforeEach { superview.addSubview(view) } context("with positive offsetRatio") { it("moves view correctly") { let offsetRatio: CGFloat = 0.4 animation.moveWith(offsetRatio) expect(Double(view.alpha)) ≈ Double(0.4) } } context("with negative offsetRatio") { it("moves view correctly") { let offsetRatio: CGFloat = -0.4 animation.moveWith(offsetRatio) expect(Double(view.alpha)) ≈ Double(0.6) } } } context("without superview") { it("doesn't change position") { let offsetRatio: CGFloat = 0.4 animation.moveWith(offsetRatio) expect(Double(view.alpha)) ≈ Double(1.0) } } } } } }
mit
1ffb5c8bc89b4e0951addffe56217f6f
24.650794
86
0.532178
4.43956
false
false
false
false
tlax/GaussSquad
GaussSquad/View/Main/Subclasses/VSpinner.swift
1
807
import UIKit class VSpinner:UIImageView { private let kAnimationDuration:TimeInterval = 0.6 init() { super.init(frame:CGRect.zero) let images:[UIImage] = [ #imageLiteral(resourceName: "assetSpinner0"), #imageLiteral(resourceName: "assetSpinner1"), #imageLiteral(resourceName: "assetSpinner2"), #imageLiteral(resourceName: "assetSpinner3") ] isUserInteractionEnabled = false translatesAutoresizingMaskIntoConstraints = false clipsToBounds = true animationDuration = kAnimationDuration animationImages = images contentMode = UIViewContentMode.center startAnimating() } required init?(coder:NSCoder) { return nil } }
mit
ec5ef6e7e8e0f55597132be102f83151
25.032258
57
0.6171
5.933824
false
false
false
false
iSame7/Panoramic
Panoramic/Panoramic/PanoramaView.swift
1
5956
// // PanoramaView.swift // Panorama Swift // // Created by Sameh Mabrouk on 12/12/14. // Copyright (c) 2014 SMApps. All rights reserved. // import UIKit import CoreMotion class PanoramaView: UIView { //Constatnts let CRMotionViewRotationMinimumThreshold:CGFloat = 0.1 let CRMotionGyroUpdateInterval:NSTimeInterval = 1 / 100 let CRMotionViewRotationFactor:CGFloat = 4.0 // Managing Motion Sensing private var motionManager: CMMotionManager = CMMotionManager() private var motionEnabled: Bool = true private var scrollIndicatorEnabled: Bool = true //Subviews private var viewFrame: CGRect! private var scrollView: UIScrollView! private var imageView: UIImageView! //Managing Motion private var motionRate:CGFloat! private var minimumXOffset:CGFloat! private var maximumXOffset:CGFloat! // The image that will be diplayed. private var image: UIImage! // MARK: - Initialization override init(frame: CGRect) { super.init(frame: frame) viewFrame = CGRectMake(0.0, 0.0, CGRectGetWidth(frame), CGRectGetHeight(frame)) self.commonInit() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Instance methods func commonInit(){ self.scrollView = UIScrollView(frame: self.viewFrame) self.scrollView.userInteractionEnabled = false self.scrollView.alwaysBounceVertical = false self.scrollView.contentSize = CGSizeZero self.addSubview(self.scrollView) self.imageView = UIImageView(frame: self.viewFrame) self.imageView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] self.imageView.backgroundColor = UIColor.blackColor() self.imageView.contentMode = UIViewContentMode.ScaleAspectFit self.scrollView.addSubview(self.imageView) self.minimumXOffset = 0 self.scrollIndicatorEnabled = true self.startMonitoring() } // MARK: - Setters /* set image for the imageview to display it to the reciever. */ func setImage(image:UIImage){ self.image = image let width = self.viewFrame.size.height / self.image.size.height * self.image.size.width self.imageView.frame = CGRectMake(0, 0, width, self.viewFrame.height) self.imageView.backgroundColor = UIColor.blueColor() self.imageView.image = self.image self.scrollView.contentSize = CGSizeMake(self.imageView.frame.size.width, self.scrollView.frame.size.height) self.scrollView.contentOffset = CGPointMake((self.scrollView.contentSize.width - self.scrollView.frame.size.width) / 2, 0) //enable panormama indicator. self.scrollView.enablePanoramaIndicator() self.motionRate = self.image.size.width / self.viewFrame.size.width * CRMotionViewRotationFactor self.maximumXOffset = self.scrollView.contentSize.width - self.scrollView.frame.size.width } /* enable motion and recieving the gyro updates. */ func setMotionEnabled(motionEnabled:Bool){ self.motionEnabled = motionEnabled if self.motionEnabled{ self.startMonitoring() } else{ self.stopMonitoring() } } /* enable or disable the scrolling of the scrolling indicator of PanoramaIndicator. */ func setScrollIndicatorEnabled(scrollIndicatorEnabled:Bool){ self.scrollIndicatorEnabled = scrollIndicatorEnabled if self.scrollIndicatorEnabled{ //enable panormama indicator. self.scrollView.enablePanoramaIndicator() } else{ //disable panormama indicator. self.scrollView.disablePanoramaIndicator() } } // MARK: - Core Motion /* start monitoring the updates of the gyro to rotate the scrollview accoring the device motion rotation rate. */ func startMonitoring(){ self.motionManager.gyroUpdateInterval = CRMotionGyroUpdateInterval if !self.motionManager.gyroActive && self.motionManager.gyroAvailable{ self.motionManager.startGyroUpdatesToQueue(NSOperationQueue.currentQueue()!, withHandler: { (CMGyroData, NSError) -> Void in self.rotateAccordingToDeviceMotionRotationRate(CMGyroData!) }) } else{ print("No Availabel gyro") } } /* this function calculate the rotation of UIScrollview accoring to the device motion rotation rate. */ func rotateAccordingToDeviceMotionRotationRate(gyroData:CMGyroData){ // Why the y value not x or z. /* * y: * Y-axis rotation rate in radians/second. The sign follows the right hand * rule (i.e. if the right hand is wrapped around the Y axis such that the * tip of the thumb points toward positive Y, a positive rotation is one * toward the tips of the other 4 fingers). */ let rotationRate = CGFloat(gyroData.rotationRate.y) if abs(rotationRate) >= CRMotionViewRotationMinimumThreshold{ var offsetX = self.scrollView.contentOffset.x - rotationRate * self.motionRate if offsetX > self.maximumXOffset{ offsetX = self.maximumXOffset } else if offsetX < self.minimumXOffset{ offsetX = self.minimumXOffset } UIView.animateWithDuration(0.3, delay: 0.0, options: [.BeginFromCurrentState, .AllowUserInteraction, .CurveEaseOut], animations: { () -> Void in self.scrollView.setContentOffset(CGPointMake(offsetX, 0), animated: false) }, completion: nil) } } /* Stop gyro updates if reciever set motionEnabled = false */ func stopMonitoring(){ self.motionManager.stopGyroUpdates() } }
mit
0290dd0d47aebf60910970e141bb4118
29.54359
156
0.661014
4.776263
false
false
false
false
ykws/yomblr
yomblr/TumblrAPI/Responses/User.swift
1
1749
// // User.swift // yomblr // // Created by Yoshiyuki Kawashima on 2017/06/24. // Copyright © 2017 ykws. All rights reserved. // /** Tumblr API /user/info - Get a User's Information Responses https://www.tumblr.com/docs/en/api/v2#user-methods */ struct User : JSONDecodable { let following: Int let defaultPostFormat: String let name: String let likes: Int let blogs: [Blog] init(json: Any) throws { guard let dictionary = json as? [String : Any] else { throw JSONDecodeError.invalidFormat(json: json) } guard let user = dictionary["user"] as? [String : Any] else { throw JSONDecodeError.missingValue(key: "user", actualValue: dictionary["user"]) } guard let following = user["following"] as? Int else { throw JSONDecodeError.missingValue(key: "following", actualValue: user["following"]) } guard let defaultPostFormat = user["default_post_format"] as? String else { throw JSONDecodeError.missingValue(key: "default_post_format", actualValue: user["default_post_format"]) } guard let name = user["name"] as? String else { throw JSONDecodeError.missingValue(key: "name", actualValue: user["name"]) } guard let likes = user["likes"] as? Int else { throw JSONDecodeError.missingValue(key: "likes", actualValue: user["likes"]) } guard let blogObjects = user["blogs"] as? [Any] else { throw JSONDecodeError.missingValue(key: "blogs", actualValue: user["blogs"]) } let blogs = try blogObjects.map { return try Blog(json: $0) } self.following = following self.defaultPostFormat = defaultPostFormat self.name = name self.likes = likes self.blogs = blogs } }
mit
7001e71a35e397ff378a025d1ec080c5
28.133333
110
0.652746
3.92809
false
false
false
false
mathewsheets/SwiftLearningExercises
Exercise_12.playground/Sources/Auditing.swift
1
1866
import Foundation public protocol AuditAction { var description: String { get } } public extension AuditAction { public var description: String { return "\(self)" } } public enum AuditDelegateAction: AuditAction { case Open case Debit case Credit case Done } public protocol AuditDelegate { func willPerform(what: AuditAction, customer: Customer, account: Account?) func performing(what: AuditAction, customer: Customer, account: Account?) func didPerform(what: AuditAction, customer: Customer, account: Account?) } extension AuditDelegate { public func willPerform(what: AuditAction, customer: Customer, account: Account?) { if (account != nil) { print("will perform \(what.description) for customer \(customer.name): balance = \(account!.description).") } else { print("will perform \(what.description) for customer \(customer.name).") } } public func performing(what: AuditAction, customer: Customer, account: Account?) { if (account != nil) { print("performing \(what.description) for customer \(customer.name): balance = \(account!.description).") } else { print("performing \(what.description) for customer \(customer.name).") } } public func didPerform(what: AuditAction, customer: Customer, account: Account?) { if (account != nil) { print("did perform \(what.description) for customer \(customer.name): balance = \(account!.description).") } else { print("did perform \(what.description) for customer \(customer.name).") } } } public class AuditDefaultDelegate: AuditDelegate { public init() { } deinit { print("deinit delegate") } }
mit
c26b4ebd4e77938e49b72b091f1bab0d
26.043478
119
0.614148
4.573529
false
false
false
false
IBM-MIL/IBM-Ready-App-for-Venue
iOS/Venue/Controllers/ChallengesViewController.swift
1
2782
/* Licensed Materials - Property of IBM © Copyright IBM Corporation 2015. All Rights Reserved. */ import UIKit /// ViewController to handle leaderboard and badges views class ChallengesViewController: VenueUIViewController { @IBOutlet weak var leaderboardButton: UIButton! @IBOutlet weak var badgesButton: UIButton! /// UIView beneath the top buttons indicating which is selected @IBOutlet weak var indicatorView: UIView! @IBOutlet weak var badgeContainerView: UIView! @IBOutlet weak var leaderboardContainerView: UIView! /// Constant used to animate the movement of the indicator view @IBOutlet weak var indicatorViewLeadingContraint: NSLayoutConstraint! var showingBadges = true override func viewDidLoad() { super.viewDidLoad() setupBindings() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.navigationController?.setNavigationBarHidden(true, animated: true) } /** Setup ReactiveCocoa bindings to UI and data */ func setupBindings() { leaderboardButton.rac_signalForControlEvents(UIControlEvents.TouchUpInside).subscribeNext { [unowned self] _ in self.showingBadges = false self.reloadView() } badgesButton.rac_signalForControlEvents(UIControlEvents.TouchUpInside).subscribeNext { [unowned self] _ in self.showingBadges = true self.reloadView() } } /** Reloads the collection view based on the state of the showingNearest bool */ func reloadView() { leaderboardButton.titleLabel?.font = !showingBadges ? UIFont.latoBlack(14.0) : UIFont.latoRegular(14.0) badgesButton.titleLabel?.font = showingBadges ? UIFont.latoBlack(14.0) : UIFont.latoRegular(14.0) badgeContainerView.hidden = !showingBadges leaderboardContainerView.hidden = showingBadges indicatorViewLeadingContraint.constant = showingBadges ? 0 : view.frame.size.width/2 } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "badgeSegue" { let vc = segue.destinationViewController as? BadgeViewController if vc!.viewModel == nil { vc!.viewModel = BadgeCollectionViewModel() } } else if segue.identifier == "leaderboardSegue" { let vc = segue.destinationViewController as? LeaderboardViewController if vc!.viewModel == nil { vc!.viewModel = LeaderboardViewModel() } } } override func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.LightContent } }
epl-1.0
e8cc8dfc966b8e9896027110df2a20af
34.202532
119
0.669903
5.463654
false
false
false
false
yonadev/yona-app-ios
Yona/Yona/CALayerExtensions.swift
1
1303
// // StringExtensions.swift // Yona // // Created by Chandan Varma on 30/05/16. // Copyright © 2016 Yona. All rights reserved. // import Foundation extension CALayer { func configureGradientBackground(_ height:CGFloat, colors:CGColor...){ let gradient = CAGradientLayer() let maxWidth = max(self.bounds.size.height,self.bounds.size.width) let squareFrame = CGRect(origin: self.bounds.origin, size: CGSize(width: maxWidth, height: height)) gradient.frame = squareFrame gradient.colors = colors // self.addSublayer(gradient) self.insertSublayer(gradient, at: 0) } } func setTableViewBackgroundGradient(_ sender: UITableViewController, _ topColor:UIColor, _ bottomColor:UIColor) { let gradientBackgroundColors = [topColor.cgColor, bottomColor.cgColor] let gradientLocations = [0.0,1.0] let gradientLayer = CAGradientLayer() gradientLayer.colors = gradientBackgroundColors gradientLayer.locations = gradientLocations as [NSNumber]? gradientLayer.frame = sender.tableView.bounds let backgroundView = UIView(frame: sender.tableView.bounds) backgroundView.layer.insertSublayer(gradientLayer, at: 0) sender.tableView.backgroundView = backgroundView }
mpl-2.0
4f25aff201d9ceee3fee6ac73bf5d412
30.756098
113
0.698925
4.600707
false
false
false
false
gabrielfalcao/MusicKit
MusicKit/PitchSet.swift
1
9559
// Copyright (c) 2015 Ben Guo. All rights reserved. import Foundation // MARK: == PitchSet == /// A collection of unique `Pitch` instances ordered by frequency. public struct PitchSet : Equatable { var contents : [Pitch] = [] /// The number of pitches the `PitchSet` contains. public var count: Int { return contents.count } /// Creates an empty `PitchSet` public init() { } /// Creates a new `PitchSet` with the contents of a given sequence of pitches. public init<S : SequenceType where S.Generator.Element == Pitch>(_ sequence: S) { contents = sorted(Array(Set(sequence))) } /// Creates a new `PitchSet` with the given pitches. public init(pitches: Pitch...) { contents = sorted(Array(Set(pitches))) } /// Returns the index of the given `pitch` /// /// :returns: The index of the first instance of `pitch`, or `nil` if `pitch` isn't found. public func indexOf(pitch: Pitch) -> Int? { let index = MKUtil.insertionIndex(contents, pitch) if index == count { return nil } return contents[index] == pitch ? index : nil } /// Returns true iff `pitch` is found in the collection. public func contains(pitch: Pitch) -> Bool { return indexOf(pitch) != nil } /// Returns true iff there are no pitches in the collection public func isEmpty() -> Bool { return count == 0 } /// Returns a new `PitchSet` with the combined contents of `self` and the given pitches. public func merge(pitches: Pitch...) -> PitchSet { return merge(pitches) } /// Returns a new `PitchSet` with the combined contents of `self` and the given sequence of pitches. public func merge<S: SequenceType where S.Generator.Element == Pitch>(pitches: S) -> PitchSet { return PitchSet(contents + pitches) } /// Inserts one or more new pitches into the `PitchSet` in the correct order. public mutating func insert(pitches: Pitch...) { for pitch in pitches { if !contains(pitch) { contents.insert(pitch, atIndex: MKUtil.insertionIndex(contents, pitch)) } } } /// Inserts the contents of a sequence of pitches into the `PitchSet`. public mutating func insert<S: SequenceType where S.Generator.Element == Pitch>(pitches: S) { contents = sorted(Array(Set(contents + pitches))) } /// Removes `pitch` from the `PitchSet` if it exists. /// /// :returns: The given pitch if found, otherwise `nil`. public mutating func remove(pitch: Pitch) -> Pitch? { if let index = indexOf(pitch) { return contents.removeAtIndex(index) } return nil } /// Removes and returns the pitch at `index`. Requires count > 0. public mutating func removeAtIndex(index: Int) -> Pitch { return contents.removeAtIndex(index) } /// Removes all pitches from the `PitchSet`. public mutating func removeAll(keepCapacity: Bool = true) { contents.removeAll(keepCapacity: keepCapacity) } } // MARK: Printable extension PitchSet : Printable { public var description : String { return contents.description } } // MARK: SequenceType extension PitchSet : SequenceType { /// Returns a generator of the elements of the collection. public func generate() -> GeneratorOf<Pitch> { return GeneratorOf(contents.generate()) } } // MARK: CollectionType extension PitchSet : CollectionType { /// The position of the first pitch in the set. (Always zero.) public var startIndex: Int { return 0 } /// One greater than the position of the last pitch in the set. /// Zero when the collection is empty. public var endIndex: Int { return count } /// Accesses the pitch at index `i`. /// Read-only to ensure sorting - use `insert` to add new pitches. public subscript(i: Int) -> Pitch { return contents[i] } } // MARK: ArrayLiteralConvertible extension PitchSet : ArrayLiteralConvertible { public init(arrayLiteral elements: Pitch...) { self.contents = sorted(Array(Set(elements))) } } // MARK: Sliceable extension PitchSet : Sliceable { /// Access the elements in the given range. public subscript(range: Range<Int>) -> PitchSetSlice { return PitchSetSlice(contents[range]) } } // MARK: Equatable public func ==(lhs: PitchSet, rhs: PitchSet) -> Bool { if count(lhs) != count(rhs) { return false } for (lhs, rhs) in zip(lhs, rhs) { if lhs != rhs { return false } } return true } // MARK: Operators public func +(lhs: PitchSet, rhs: PitchSet) -> PitchSet { var lhs = lhs lhs.insert(rhs) return lhs } public func +=(inout lhs: PitchSet, rhs: PitchSet) { lhs.insert(rhs) } public func -(lhs: PitchSet, rhs: PitchSet) -> PitchSet { var lhs = lhs for pitch in rhs { lhs.remove(pitch) } return lhs } public func -=(inout lhs: PitchSet, rhs: PitchSet) { for pitch in rhs { lhs.remove(pitch) } } // MARK: == PitchSetSlice == /// A slice of a `PitchSet`. public struct PitchSetSlice : Printable { private var contents: ArraySlice<Pitch> = [] /// The number of elements the `PitchSetSlice` contains. public var count: Int { return contents.count } /// Creates an empty `PitchSetSlice`. public init() { } /// Creates a new `PitchSetSlice` with the contents of a given sequence. public init<S : SequenceType where S.Generator.Element == Pitch>(_ sequence: S) { contents = ArraySlice(sorted(Array(Set(sequence)))) } /// Creates a new `PitchSetSlice` with the given values. public init(values: Pitch...) { contents = ArraySlice(sorted(Array(Set(values)))) } /// Creates a new `PitchSetSlice` from a sorted slice. private init(sortedSlice: ArraySlice<Pitch>) { contents = sortedSlice } /// Returns the index of the given `pitch` /// /// :returns: The index of the first instance of `pitch`, or `nil` if `pitch` isn't found. public func indexOf(pitch: Pitch) -> Int? { let index = MKUtil.insertionIndex(contents, pitch) if index == count { return nil } return contents[index] == pitch ? index : nil } /// Returns true iff `pitch` is found in the slice. public func contains(pitch: Pitch) -> Bool { return indexOf(pitch) != nil } /// Returns a new `PitchSetSlice` with the combined contents of `self` and the given pitches. public func merge(pitches: Pitch...) -> PitchSetSlice { return merge(pitches) } /// Returns a new `PitchSetSlice` with the combined contents of `self` and the given pitches. public func merge<S: SequenceType where S.Generator.Element == Pitch>(pitches: S) -> PitchSetSlice { return PitchSetSlice(contents + pitches) } /// Inserts one or more new pitches into the slice in the correct order. public mutating func insert(pitches: Pitch...) { for pitch in pitches { if !contains(pitch) { contents.insert(pitch, atIndex: MKUtil.insertionIndex(contents, pitch)) } } } /// Inserts the contents of a sequence into the `PitchSetSlice`. public mutating func insert<S: SequenceType where S.Generator.Element == Pitch>(pitches: S) { contents = ArraySlice(sorted(Array(Set(contents + pitches)))) } /// Removes `pitch` from the slice if it exists. /// /// :returns: The given value if found, otherwise `nil`. public mutating func remove(pitch: Pitch) -> Pitch? { if let index = indexOf(pitch) { return contents.removeAtIndex(index) } return nil } /// Removes and returns the pitch at `index`. Requires count > 0. public mutating func removeAtIndex(index: Int) -> Pitch { return contents.removeAtIndex(index) } /// Removes all pitches from the slice. public mutating func removeAll(keepCapacity: Bool = true) { contents.removeAll(keepCapacity: keepCapacity) } } // MARK: Printable extension PitchSetSlice : Printable { public var description: String { return contents.description } } // MARK: SequenceType extension PitchSetSlice : SequenceType { public func generate() -> GeneratorOf<Pitch> { return GeneratorOf(contents.generate()) } } // MARK: CollectionType extension PitchSetSlice : CollectionType { typealias Index = Int /// The position of the first pitch in the slice. (Always zero.) public var startIndex: Int { return 0 } /// One greater than the position of the last element in the slice. Zero when the slice is empty. public var endIndex: Int { return count } /// Accesses the pitch at index `i`. /// /// Read-only to ensure sorting - use `insert` to add new pitches. public subscript(i: Int) -> Pitch { return contents[i] } } // MARK: ArrayLiteralConvertible extension PitchSetSlice : ArrayLiteralConvertible { public init(arrayLiteral elements: Pitch...) { self.contents = ArraySlice(sorted(Array(Set(elements)))) } } // MARK: Sliceable extension PitchSetSlice : Sliceable { /// Access the elements in the given range. public subscript(range: Range<Int>) -> PitchSetSlice { return PitchSetSlice(contents[range]) } }
mit
4ba98c16e668da677a0cc47a3276a76e
28.778816
104
0.632388
4.205455
false
false
false
false
stripe/stripe-ios
StripePaymentsUI/StripePaymentsUI/UI Components/STPAUBECSDebitFormView.swift
1
23378
// // STPAUBECSDebitFormView.swift // StripePaymentsUI // // Created by Cameron Sabol on 3/4/20. // Copyright © 2020 Stripe, Inc. All rights reserved. // import Foundation @_spi(STP) import StripeCore @_spi(STP) import StripePayments @_spi(STP) import StripeUICore import UIKit /// STPAUBECSDebitFormViewDelegate provides methods for STPAUBECSDebitFormView to inform its delegate /// of when the form has been completed. @objc public protocol STPAUBECSDebitFormViewDelegate: NSObjectProtocol { /// Called when the form transitions from complete to incomplete or vice-versa. /// - Parameters: /// - form: The `STPAUBECSDebitFormView` instance whose completion state has changed /// - complete: Whether the form is considered complete and can generate an `STPPaymentMethodParams` instance. func auBECSDebitForm(_ form: STPAUBECSDebitFormView, didChangeToStateComplete complete: Bool) } /// STPAUBECSDebitFormView is a subclass of UIControl that contains all of the necessary fields and legal text for collecting AU BECS Debit payments. /// For additional customization options - seealso: STPFormTextFieldContainer public class STPAUBECSDebitFormView: STPMultiFormTextField, STPMultiFormFieldDelegate, UITextViewDelegate { private var viewModel: STPAUBECSFormViewModel! private var _nameTextField: STPFormTextField! private var _emailTextField: STPFormTextField! private var _bsbNumberTextField: STPFormTextField! private var _accountNumberTextField: STPFormTextField! private var labeledNameField: STPLabeledFormTextFieldView! private var labeledEmailField: STPLabeledFormTextFieldView! private var labeledBECSField: STPLabeledMultiFormTextFieldView! private var bankIconView: UIImageView! private var bsbLabel: UILabel! private var mandateLabel: UITextView! private var companyName: String /// - Parameter companyName: The name of the company collecting AU BECS Debit payment details information. This will be used to provide the required service agreement text. - seealso: https://stripe.com/au-becs/legal @objc(initWithCompanyName:) public required init( companyName: String ) { self.companyName = companyName super.init(frame: CGRect.zero) viewModel = STPAUBECSFormViewModel() _nameTextField = _buildTextField() _nameTextField.keyboardType = .default _nameTextField.placeholder = .Localized.full_name _nameTextField.accessibilityLabel = _nameTextField.placeholder _nameTextField.textContentType = .name _emailTextField = _buildTextField() _emailTextField.keyboardType = .emailAddress _emailTextField.placeholder = STPLocalizedString( "[email protected]", "Placeholder string for email entry field." ) _emailTextField.accessibilityLabel = String.Localized.email _emailTextField.textContentType = .emailAddress _bsbNumberTextField = _buildTextField() _bsbNumberTextField.placeholder = STPLocalizedString( "BSB", "Placeholder text for BSB Number entry field for BECS Debit." ) _bsbNumberTextField.autoFormattingBehavior = .bsbNumber _bsbNumberTextField.accessibilityLabel = _bsbNumberTextField.placeholder _bsbNumberTextField.leftViewMode = .always bankIconView = UIImageView() bankIconView.contentMode = .center bankIconView.image = viewModel.bankIcon(forInput: nil) bankIconView.translatesAutoresizingMaskIntoConstraints = false let iconContainer = UIView() iconContainer.addSubview(bankIconView) iconContainer.translatesAutoresizingMaskIntoConstraints = false _bsbNumberTextField.leftView = iconContainer _accountNumberTextField = _buildTextField() _accountNumberTextField.placeholder = String.Localized.accountNumber _accountNumberTextField.accessibilityLabel = _accountNumberTextField.placeholder labeledNameField = STPLabeledFormTextFieldView( formLabel: STPAUBECSDebitFormView._nameTextFieldLabel(), textField: _nameTextField ) labeledNameField.formBackgroundColor = formBackgroundColor labeledNameField.translatesAutoresizingMaskIntoConstraints = false addSubview(labeledNameField) labeledEmailField = STPLabeledFormTextFieldView( formLabel: STPAUBECSDebitFormView._emailTextFieldLabel(), textField: _emailTextField ) labeledEmailField.topSeparatorHidden = true labeledEmailField.formBackgroundColor = formBackgroundColor labeledEmailField.translatesAutoresizingMaskIntoConstraints = false addSubview(labeledEmailField) labeledBECSField = STPLabeledMultiFormTextFieldView( formLabel: STPAUBECSDebitFormView._bsbNumberTextFieldLabel(), firstTextField: _bsbNumberTextField, secondTextField: _accountNumberTextField ) labeledBECSField.formBackgroundColor = formBackgroundColor labeledBECSField.translatesAutoresizingMaskIntoConstraints = false addSubview(labeledBECSField) bsbLabel = UILabel() bsbLabel.font = UIFont.preferredFont(forTextStyle: .caption1) bsbLabel.textColor = _defaultBSBLabelTextColor() bsbLabel.translatesAutoresizingMaskIntoConstraints = false addSubview(bsbLabel) let mandateTextLabel = UITextView() mandateTextLabel.isScrollEnabled = false mandateTextLabel.isEditable = false mandateTextLabel.isSelectable = true mandateTextLabel.backgroundColor = UIColor.clear // Get rid of the extra padding added by default to UITextViews mandateTextLabel.textContainerInset = .zero mandateTextLabel.textContainer.lineFragmentPadding = 0.0 mandateTextLabel.delegate = self let mandateText = NSMutableAttributedString( string: "By providing your bank account details and confirming this payment, you agree to this Direct Debit Request and the Direct Debit Request service agreement, and authorise Stripe Payments Australia Pty Ltd ACN 160 180 343 Direct Debit User ID number 507156 (\"Stripe\") to debit your account through the Bulk Electronic Clearing System (BECS) on behalf of \(companyName) (the \"Merchant\") for any amounts separately communicated to you by the Merchant. You certify that you are either an account holder or an authorised signatory on the account listed above." ) let linkRange = (mandateText.string as NSString).range( of: "Direct Debit Request service agreement" ) if linkRange.location != NSNotFound { mandateText.addAttribute( .link, value: "https://stripe.com/au-becs-dd-service-agreement/legal", range: linkRange ) } else { assert(false, "Shouldn't be missing the text to linkify.") } mandateTextLabel.attributedText = mandateText // Set font and textColor after setting the attributedText so they are applied as attributes automatically mandateTextLabel.font = UIFont.preferredFont(forTextStyle: .footnote) if #available(iOS 13.0, *) { mandateTextLabel.textColor = UIColor.secondaryLabel } else { // Fallback on earlier versions mandateTextLabel.textColor = UIColor.darkGray } mandateTextLabel.translatesAutoresizingMaskIntoConstraints = false addSubview(mandateTextLabel) mandateLabel = mandateTextLabel var constraints = [ bankIconView.centerYAnchor.constraint(equalTo: iconContainer.centerYAnchor), bankIconView.topAnchor.constraint(equalTo: iconContainer.topAnchor, constant: 0), bankIconView.leadingAnchor.constraint(equalTo: iconContainer.leadingAnchor), bankIconView.trailingAnchor.constraint( equalTo: iconContainer.trailingAnchor, constant: -8 ), iconContainer.heightAnchor.constraint( greaterThanOrEqualTo: bankIconView.heightAnchor, multiplier: 1.0 ), iconContainer.widthAnchor.constraint( greaterThanOrEqualTo: bankIconView.widthAnchor, multiplier: 1.0 ), labeledNameField.leadingAnchor.constraint(equalTo: leadingAnchor), labeledNameField.trailingAnchor.constraint(equalTo: trailingAnchor), labeledNameField.topAnchor.constraint(equalTo: topAnchor), labeledEmailField.leadingAnchor.constraint(equalTo: leadingAnchor), labeledEmailField.trailingAnchor.constraint(equalTo: trailingAnchor), labeledEmailField.topAnchor.constraint(equalTo: labeledNameField.bottomAnchor), labeledNameField.labelWidthDimension.constraint( equalTo: labeledEmailField.labelWidthDimension ), labeledBECSField.leadingAnchor.constraint(equalTo: leadingAnchor), labeledBECSField.trailingAnchor.constraint(equalTo: trailingAnchor), labeledBECSField.topAnchor.constraint( equalTo: labeledEmailField.bottomAnchor, constant: 4 ), bsbLabel.topAnchor.constraint(equalTo: labeledBECSField.bottomAnchor, constant: 4), // Constrain to bottom of becs details instead of bank name label becuase it is height 0 when no data // has been entered mandateTextLabel.topAnchor.constraint( equalTo: labeledBECSField.bottomAnchor, constant: 40.0 ), bottomAnchor.constraint(equalTo: mandateTextLabel.bottomAnchor), ].compactMap { $0 } constraints.append( contentsOf: [ bsbLabel.leadingAnchor.constraint( equalToSystemSpacingAfter: layoutMarginsGuide.leadingAnchor, multiplier: 1.0 ), layoutMarginsGuide.trailingAnchor.constraint( equalToSystemSpacingAfter: bsbLabel.trailingAnchor, multiplier: 1.0 ), mandateTextLabel.leadingAnchor.constraint( equalToSystemSpacingAfter: layoutMarginsGuide.leadingAnchor, multiplier: 1.0 ), layoutMarginsGuide.trailingAnchor.constraint( equalToSystemSpacingAfter: mandateTextLabel.trailingAnchor, multiplier: 1.0 ), ].compactMap { $0 } ) NSLayoutConstraint.activate(constraints) formTextFields = [ _nameTextField, _emailTextField, _bsbNumberTextField, _accountNumberTextField, ].compactMap { $0 } multiFormFieldDelegate = self } /// Use initWithCompanyName instead. required convenience init?( coder: NSCoder ) { assertionFailure("Use initWithCompanyName instead.") self.init(companyName: "") } /// Use initWithCompanyName instead. override convenience init( frame: CGRect ) { assertionFailure("Use initWithCompanyName instead.") self.init(companyName: "") } /// The background color for the form text fields. Defaults to .systemBackground on iOS 13.0 and later, .white on earlier iOS versions. @objc public var formBackgroundColor: UIColor = { if #available(iOS 13.0, *) { return .systemBackground } else { // Fallback on earlier versions return .white } }() { didSet { labeledNameField.formBackgroundColor = formBackgroundColor labeledEmailField.formBackgroundColor = formBackgroundColor labeledBECSField.formBackgroundColor = formBackgroundColor } } /// The delegate to inform about changes to this STPAUBECSDebitFormView instance. @objc public weak var becsDebitFormDelegate: STPAUBECSDebitFormViewDelegate? /// This property will return a non-nil value if and only if the form is in a complete state. The `STPPaymentMethodParams` instance /// will have it's `auBECSDebit` property populated with the values input in this form. @objc public var paymentMethodParams: STPPaymentMethodParams? { return viewModel.paymentMethodParams } private var _paymentMethodParams: STPPaymentMethodParams? func _buildTextField() -> STPFormTextField { let textField = STPFormTextField(frame: CGRect.zero) textField.keyboardType = .asciiCapableNumberPad textField.textAlignment = .natural textField.font = formFont textField.defaultColor = formTextColor textField.errorColor = formTextErrorColor textField.placeholderColor = formPlaceholderColor textField.keyboardAppearance = formKeyboardAppearance textField.validText = true textField.selectionEnabled = true return textField } class func _nameTextFieldLabel() -> String { return String.Localized.name } class func _emailTextFieldLabel() -> String { return String.Localized.email } class func _bsbNumberTextFieldLabel() -> String { return String.Localized.bank_account } class func _accountNumberTextFieldLabel() -> String { return self._bsbNumberTextFieldLabel() // same label } func _updateValidText(for formTextField: STPFormTextField) { if formTextField == _bsbNumberTextField { formTextField.validText = viewModel.isInputValid( formTextField.text ?? "", for: .BSBNumber, editing: formTextField.isFirstResponder ) } else if formTextField == _accountNumberTextField { formTextField.validText = viewModel.isInputValid( formTextField.text ?? "", for: .accountNumber, editing: formTextField.isFirstResponder ) } else if formTextField == _nameTextField { formTextField.validText = viewModel.isInputValid( formTextField.text ?? "", for: .name, editing: formTextField.isFirstResponder ) } else if formTextField == _emailTextField { formTextField.validText = viewModel.isInputValid( formTextField.text ?? "", for: .email, editing: formTextField.isFirstResponder ) } else { assert( false, "Shouldn't call for text field not managed by \(NSStringFromClass(STPAUBECSDebitFormView.self))" ) } } /// :nodoc: @objc public override func systemLayoutSizeFitting( _ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority ) -> CGSize { // UITextViews don't play nice with autolayout, so we have to add a temporary height constraint // to get this method to account for the full, non-scrollable size of _mandateLabel layoutIfNeeded() let tempConstraint = mandateLabel.heightAnchor.constraint( equalToConstant: mandateLabel.contentSize.height ) tempConstraint.isActive = true let size = super.systemLayoutSizeFitting( targetSize, withHorizontalFittingPriority: horizontalFittingPriority, verticalFittingPriority: verticalFittingPriority ) tempConstraint.isActive = false return size } func _defaultBSBLabelTextColor() -> UIColor { if #available(iOS 13.0, *) { return UIColor.secondaryLabel } else { // Fallback on earlier versions return UIColor.darkGray } } func _updateBSBLabel() { var isErrorString = false bsbLabel.text = viewModel.bsbLabel( forInput: _bsbNumberTextField.text, editing: _bsbNumberTextField.isFirstResponder, isErrorString: &isErrorString ) bsbLabel.textColor = isErrorString ? formTextErrorColor : _defaultBSBLabelTextColor() } // MARK: - STPMultiFormFieldDelegate func formTextFieldDidStartEditing( _ formTextField: STPFormTextField, inMultiForm multiFormField: STPMultiFormTextField ) { _updateValidText(for: formTextField) if formTextField == _bsbNumberTextField { _updateBSBLabel() } } func formTextFieldDidEndEditing( _ formTextField: STPFormTextField, inMultiForm multiFormField: STPMultiFormTextField ) { _updateValidText(for: formTextField) if formTextField == _bsbNumberTextField { _updateBSBLabel() } } func modifiedIncomingTextChange( _ input: NSAttributedString, for formTextField: STPFormTextField, inMultiForm multiFormField: STPMultiFormTextField ) -> NSAttributedString { if formTextField == _bsbNumberTextField { return NSAttributedString( string: viewModel.formattedString(forInput: input.string, in: .BSBNumber), attributes: _bsbNumberTextField.defaultTextAttributes ) } else if formTextField == _accountNumberTextField { return NSAttributedString( string: viewModel.formattedString(forInput: input.string, in: .accountNumber), attributes: _accountNumberTextField.defaultTextAttributes ) } else if formTextField == _nameTextField { return NSAttributedString( string: viewModel.formattedString(forInput: input.string, in: .name), attributes: _nameTextField.defaultTextAttributes ) } else if formTextField == _emailTextField { return NSAttributedString( string: viewModel.formattedString(forInput: input.string, in: .email), attributes: _emailTextField.defaultTextAttributes ) } else { assert( false, "Shouldn't call for text field not managed by \(NSStringFromClass(STPAUBECSDebitFormView.self))" ) return input } } func formTextFieldTextDidChange( _ formTextField: STPFormTextField, inMultiForm multiFormField: STPMultiFormTextField ) { _updateValidText(for: formTextField) let hadCompletePaymentMethod = viewModel.paymentMethodParams != nil if formTextField == _bsbNumberTextField { viewModel.bsbNumber = formTextField.text _updateBSBLabel() bankIconView.image = viewModel.bankIcon(forInput: formTextField.text) // Since BSB number affects validity for the account number as well, we also need to update that field _updateValidText(for: _accountNumberTextField) if viewModel.isFieldComplete( withInput: formTextField.text ?? "", in: .BSBNumber, editing: formTextField.isFirstResponder ) { focusNextForm() } } else if formTextField == _accountNumberTextField { viewModel.accountNumber = formTextField.text if viewModel.isFieldComplete( withInput: formTextField.text ?? "", in: .accountNumber, editing: formTextField.isFirstResponder ) { focusNextForm() } } else if formTextField == _nameTextField { viewModel.name = formTextField.text } else if formTextField == _emailTextField { viewModel.email = formTextField.text } else { assert( false, "Shouldn't call for text field not managed by \(NSStringFromClass(STPAUBECSDebitFormView.self))" ) } let nowHasCompletePaymentMethod = viewModel.paymentMethodParams != nil if hadCompletePaymentMethod != nowHasCompletePaymentMethod { becsDebitFormDelegate?.auBECSDebitForm( self, didChangeToStateComplete: nowHasCompletePaymentMethod ) } } func isFormFieldComplete( _ formTextField: STPFormTextField, inMultiForm multiFormField: STPMultiFormTextField ) -> Bool { if formTextField == _bsbNumberTextField { return viewModel.isFieldComplete( withInput: formTextField.text ?? "", in: .BSBNumber, editing: false ) } else if formTextField == _accountNumberTextField { return viewModel.isFieldComplete( withInput: formTextField.text ?? "", in: .accountNumber, editing: false ) } else if formTextField == _nameTextField { return viewModel.isFieldComplete( withInput: formTextField.text ?? "", in: .name, editing: false ) } else if formTextField == _emailTextField { return viewModel.isFieldComplete( withInput: formTextField.text ?? "", in: .email, editing: false ) } else { assert( false, "Shouldn't call for text field not managed by \(NSStringFromClass(STPAUBECSDebitFormView.self))" ) return false } } // MARK: - UITextViewDelegate /// :nodoc: @objc public func textView( _ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction ) -> Bool { return true } // MARK: - STPFormTextFieldContainer (Overrides) /// :nodoc: @objc public override var formFont: UIFont { get { super.formFont } set { super.formFont = newValue labeledNameField.formLabelFont = newValue labeledEmailField.formLabelFont = newValue } } /// :nodoc: @objc public override var formTextColor: UIColor { get { super.formTextColor } set { super.formTextColor = newValue labeledNameField.formLabelTextColor = newValue labeledEmailField.formLabelTextColor = newValue } } } extension STPAUBECSDebitFormView { func nameTextField() -> STPFormTextField { return _nameTextField } func emailTextField() -> STPFormTextField { return _emailTextField } func bsbNumberTextField() -> STPFormTextField { return _bsbNumberTextField } func accountNumberTextField() -> STPFormTextField { return _accountNumberTextField } }
mit
74fe15004407e6de673036501bd49ec2
38.756803
574
0.643624
5.492716
false
false
false
false
ppraveentr/MobileCore
Tests/CoreComponentsTests/CollectionViewControllerProtocolTests.swift
1
2302
// // CollectionViewControllerProtocolTests.swift // MobileCoreTests // // Created by Praveen P on 30/06/20. // Copyright © 2020 Praveen Prabhakar. All rights reserved. // #if canImport(CoreComponents) import CoreComponents import CoreUtility #endif import UIKit import XCTest private final class MockDefaultCollectionViewContoller: UIViewController, CollectionViewControllerProtocol { // Optional Protocol implementation: intentionally empty } private final class MockCollectionViewContoller: UIViewController, CollectionViewControllerProtocol { let mocklayout = UICollectionViewLayout() let mockestimatedItemSize = CGSize(width: 20.0, height: 20.0) let mocksectionInset = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20) func estimatedItemSize() -> CGSize { mockestimatedItemSize } func sectionInset() -> UIEdgeInsets { mocksectionInset } var flowLayout: UICollectionViewLayout { mocklayout } } final class CollectionViewControllerProtocolTests: XCTestCase { func testDefaultValues() { let viewController = MockDefaultCollectionViewContoller() XCTAssertEqual(viewController.estimatedItemSize(), .zero) XCTAssertEqual(viewController.sectionInset(), .zero) } func testFlowLayout() { let viewController = MockCollectionViewContoller() XCTAssertEqual(viewController.estimatedItemSize(), viewController.mockestimatedItemSize) XCTAssertEqual(viewController.sectionInset(), viewController.mocksectionInset) XCTAssertEqual(viewController.flowLayout, viewController.mocklayout) XCTAssertNotNil(viewController.collectionView) XCTAssertEqual(viewController.collectionView, viewController.collectionViewController.collectionView) } func testCustomCollectionView() { let viewController = MockCollectionViewContoller() let collectionView = UICollectionView(frame: .zero, collectionViewLayout: viewController.flowLayout) viewController.collectionView = collectionView XCTAssertEqual(collectionView, viewController.collectionViewController.collectionView) XCTAssertEqual(viewController.collectionViewController.collectionView.collectionViewLayout, viewController.mocklayout) } }
mit
f2e5684ad08df661ca7f174b2cef12ca
36.112903
126
0.763146
5.854962
false
true
false
false
xdliu002/30SwiftProject
Project1_LoginAnimation/LoginAnimation/ViewController.swift
1
2771
// // ViewController.swift // LoginAnimation // // Created by Harold LIU on 2/16/16. // Copyright © 2016 Tongji Apple Club. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var userName: UITextField! @IBOutlet weak var passWord: UITextField! @IBOutlet weak var centerAlginUserName: NSLayoutConstraint! @IBOutlet weak var centerAlginPassword: NSLayoutConstraint! @IBOutlet weak var loginButton: UIButton! override func viewDidLoad() { super.viewDidLoad() userName.layer.cornerRadius = 5 passWord.layer.cornerRadius = 5 loginButton.layer.cornerRadius = 5 } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) centerAlginPassword.constant -= view.bounds.width centerAlginUserName.constant -= view.bounds.width loginButton.alpha = 0 } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) UIView.animateWithDuration(0.5, delay: 0.00, options: UIViewAnimationOptions.CurveEaseOut, animations: { () -> Void in self.centerAlginPassword.constant += self.view.bounds.width self.view.layoutIfNeeded() }, completion: nil) UIView.animateWithDuration(0.5, delay: 0.10, options: .CurveEaseOut, animations: { () -> Void in self.centerAlginUserName.constant += self.view.bounds.width self.view.layoutIfNeeded() }, completion: nil) UIView.animateWithDuration(0.5, delay: 0.20, options: .CurveEaseOut, animations: { self.loginButton.alpha = 1 }, completion: nil) } override func preferredStatusBarStyle() -> UIStatusBarStyle { return UIStatusBarStyle.LightContent } @IBAction func back(sender: AnyObject) { self.navigationController?.popToRootViewControllerAnimated(true) } @IBAction func Login(sender: AnyObject) { let bounds = self.loginButton.bounds UIView.animateWithDuration(1.0, delay: 0, usingSpringWithDamping: 0.2, initialSpringVelocity: 10, options: .CurveLinear, animations: { () -> Void in self.loginButton.bounds = CGRect(x: bounds.origin.x - 20, y: bounds.origin.y, width: bounds.size.width + 60, height: bounds.size.height) self.loginButton.enabled = false }, completion: nil) } }
mit
eeb3c26ac64ab161ab6fd9e22471346d
28.157895
152
0.587004
5.12963
false
false
false
false
tlax/looper
looper/View/Camera/Filter/BlenderOverlay/VCameraFilterBlenderOverlayPiece.swift
1
3305
import UIKit class VCameraFilterBlenderOverlayPiece:UIView { var intersecting:Bool weak var model:MCameraRecord! weak var layoutTop:NSLayoutConstraint! weak var layoutLeft:NSLayoutConstraint! weak var layoutWidth:NSLayoutConstraint! weak var layoutHeight:NSLayoutConstraint! private weak var imageView:UIImageView! private let draggingMargin2:CGFloat private let kCornerRadius:CGFloat = 10 private let kImageMargin:CGFloat = 3 private let kAnimationDuration:TimeInterval = 1 private let kDraggingAnimationDuration:TimeInterval = 0.3 private let kAlphaDragging:CGFloat = 0.5 private let kAlphaNotDragging:CGFloat = 1 private let kDraggingMargin:CGFloat = 30 init(model:MCameraRecord) { intersecting = false draggingMargin2 = kDraggingMargin + kDraggingMargin super.init(frame:CGRect.zero) isUserInteractionEnabled = false clipsToBounds = true translatesAutoresizingMaskIntoConstraints = false layer.cornerRadius = kCornerRadius self.model = model let imageView:UIImageView = UIImageView() imageView.alpha = 0 imageView.isUserInteractionEnabled = false imageView.translatesAutoresizingMaskIntoConstraints = false imageView.contentMode = UIViewContentMode.scaleAspectFill imageView.clipsToBounds = true imageView.image = model.items.first?.image imageView.layer.cornerRadius = kCornerRadius self.imageView = imageView addSubview(imageView) NSLayoutConstraint.equals( view:imageView, toView:self, margin:kImageMargin) } required init?(coder:NSCoder) { return nil } //MARK: public func animateShow() { intersecting = true UIView.animate( withDuration:kAnimationDuration, animations: { [weak self] in self?.imageView.alpha = 1 }) { [weak self] (done:Bool) in self?.insideBase() } } func insideBase() { intersecting = true backgroundColor = UIColor.genericLight } func outsideBase() { intersecting = false backgroundColor = UIColor(white:0, alpha:0.8) } func startDragging() { alpha = kAlphaDragging layoutTop.constant -= kDraggingMargin layoutLeft.constant -= kDraggingMargin layoutWidth.constant += draggingMargin2 layoutHeight.constant += draggingMargin2 UIView.animate( withDuration:kDraggingAnimationDuration) { [weak self] in self?.superview?.layoutIfNeeded() } } func stopDragging() { alpha = kAlphaNotDragging layoutTop.constant += kDraggingMargin layoutLeft.constant += kDraggingMargin layoutWidth.constant -= draggingMargin2 layoutHeight.constant -= draggingMargin2 UIView.animate( withDuration:kDraggingAnimationDuration) { [weak self] in self?.superview?.layoutIfNeeded() } } }
mit
0aeb93414f62e22c9f76dfc09364de46
26.541667
67
0.617549
5.620748
false
false
false
false
brentdax/swift
test/Migrator/post_fixit_pass.swift
13
635
// RUN: %empty-directory(%t) && %target-swift-frontend -c -update-code -primary-file %s -emit-migrated-file-path %t/post_fixit_pass.swift.result -o /dev/null -F %S/mock-sdk -swift-version 4 // RUN: diff -u %S/post_fixit_pass.swift.expected %t/post_fixit_pass.swift.result #if swift(>=4.2) public struct SomeAttribute: RawRepresentable { public init(rawValue: Int) { self.rawValue = rawValue } public init(_ rawValue: Int) { self.rawValue = rawValue } public var rawValue: Int public typealias RawValue = Int } #else public typealias SomeAttribute = Int #endif func foo(_ d: SomeAttribute) { let i: Int = d }
apache-2.0
685917b7cb58fe965f56bcd5514701e4
34.277778
189
0.696063
3.25641
false
false
false
false
janbiasi/ios-practice
FlickrSearch/FlickrSearch/FlickrSearcher.swift
1
5526
// // FlickrSearcher.swift // flickrSearch // // Created by Richard Turton on 31/07/2014. // Copyright (c) 2014 Razeware. All rights reserved. // import Foundation import UIKit let apiKey = "e8a6ad884f82bd44490a6aa1f546e521" struct FlickrSearchResults { let searchTerm : String let searchResults : [FlickrPhoto] } class FlickrPhoto : Equatable { var thumbnail : UIImage? var largeImage : UIImage? let photoID : String let farm : Int let server : String let secret : String init (photoID:String,farm:Int, server:String, secret:String) { self.photoID = photoID self.farm = farm self.server = server self.secret = secret } func flickrImageURL(size:String = "m") -> NSURL { return NSURL(string: "http://farm\(farm).staticflickr.com/\(server)/\(photoID)_\(secret)_\(size).jpg")! } func loadLargeImage(completion: (flickrPhoto:FlickrPhoto, error: NSError?) -> Void) { let loadURL = flickrImageURL(size: "b") let loadRequest = NSURLRequest(URL:loadURL) NSURLConnection.sendAsynchronousRequest(loadRequest, queue: NSOperationQueue.mainQueue()) { response, data, error in if error != nil { completion(flickrPhoto: self, error: error) return } if data != nil { let returnedImage = UIImage(data: data) self.largeImage = returnedImage completion(flickrPhoto: self, error: nil) return } completion(flickrPhoto: self, error: nil) } } func sizeToFillWidthOfSize(size:CGSize) -> CGSize { if thumbnail == nil { return size } let imageSize = thumbnail!.size var returnSize = size let aspectRatio = imageSize.width / imageSize.height returnSize.height = returnSize.width / aspectRatio if returnSize.height > size.height { returnSize.height = size.height returnSize.width = size.height * aspectRatio } return returnSize } } func == (lhs: FlickrPhoto, rhs: FlickrPhoto) -> Bool { return lhs.photoID == rhs.photoID } class Flickr { let processingQueue = NSOperationQueue() func searchFlickrForTerm(searchTerm: String, completion : (results: FlickrSearchResults?, error : NSError?) -> Void){ let searchURL = flickrSearchURLForSearchTerm(searchTerm) let searchRequest = NSURLRequest(URL: searchURL) NSURLConnection.sendAsynchronousRequest(searchRequest, queue: processingQueue) {response, data, error in if error != nil { completion(results: nil,error: error) return } var JSONError : NSError? let resultsDictionary = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions(0), error: &JSONError) as? NSDictionary if JSONError != nil { completion(results: nil, error: JSONError) return } switch (resultsDictionary!["stat"] as! String) { case "ok": println("Results processed OK") case "fail": let APIError = NSError(domain: "FlickrSearch", code: 0, userInfo: [NSLocalizedFailureReasonErrorKey:resultsDictionary!["message"]!]) completion(results: nil, error: APIError) return default: let APIError = NSError(domain: "FlickrSearch", code: 0, userInfo: [NSLocalizedFailureReasonErrorKey:"Uknown API response"]) completion(results: nil, error: APIError) return } let photosContainer = resultsDictionary!["photos"] as! NSDictionary let photosReceived = photosContainer["photo"] as! [NSDictionary] let flickrPhotos : [FlickrPhoto] = photosReceived.map { photoDictionary in let photoID = photoDictionary["id"] as? String ?? "" let farm = photoDictionary["farm"] as? Int ?? 0 let server = photoDictionary["server"] as? String ?? "" let secret = photoDictionary["secret"] as? String ?? "" let flickrPhoto = FlickrPhoto(photoID: photoID, farm: farm, server: server, secret: secret) let imageData = NSData(contentsOfURL: flickrPhoto.flickrImageURL()) flickrPhoto.thumbnail = UIImage(data: imageData!) return flickrPhoto } dispatch_async(dispatch_get_main_queue(), { completion(results:FlickrSearchResults(searchTerm: searchTerm, searchResults: flickrPhotos), error: nil) }) } } private func flickrSearchURLForSearchTerm(searchTerm:String) -> NSURL { let escapedTerm = searchTerm.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)! let URLString = "https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=\(apiKey)&text=\(escapedTerm)&per_page=20&format=json&nojsoncallback=1" return NSURL(string: URLString)! } }
gpl-2.0
b3d7d0b049aa6817a1cf1ab6c572e7a6
34.883117
170
0.575461
5.272901
false
false
false
false
antonio081014/LeetCode-CodeBase
Swift/find-the-shortest-superstring.swift
2
2747
/** * https://leetcode.com/problems/find-the-shortest-superstring/ * * */ // Date: Wed Aug 18 16:39:57 PDT 2021 class Solution { /// - Reference: /// [Youtube Hua Hua](https://youtu.be/u_Wc4jwrp3Q) /// - Complexity: /// - Time: O(2^n * n^2), n is the length of words array. /// - Space: O(2^n * n), n is the length of words array. func shortestSuperstring(_ words: [String]) -> String { let n = words.count var mask = (1 << n) var cost = Array(repeating: Array(repeating: 0, count: n), count: n) for i in 0 ..< n { for j in 0 ..< n { cost[i][j] = self.distance(words[i], words[j]) } } // Calculate the shortest possible string length with // - mask: indicates the selected/handled words // - index: the index of last word in current shortest solution. var dp = Array(repeating: Array(repeating: Int.max / 2, count: n), count: mask ) var parent = Array(repeating: Array(repeating: -1, count: n), count: mask) for index in 0 ..< n { dp[1 << index][index] = words[index].count } for s in 1 ..< mask { for index in 0 ..< n { if ((1 << index) & s) == 0 { continue } let prev = s - (1 << index) for j in 0 ..< n { if dp[prev][j] + cost[j][index] < dp[s][index] { dp[s][index] = dp[prev][j] + cost[j][index] parent[s][index] = j } } } } var resultIndex = 0 mask -= 1 for index in 1 ..< n { if dp[mask][index] < dp[mask][resultIndex] { resultIndex = index } } var result = words[resultIndex] while resultIndex >= 0 { let p = parent[mask][resultIndex] if p < 0 { return result } result = self.combine(words[p], words[resultIndex], words[resultIndex].count - cost[p][resultIndex]) + result mask -= 1 << resultIndex resultIndex = p } return result } func combine(_ a: String, _ b: String, _ commonLength: Int) -> String { guard a.count - commonLength > 0 else { return "" } let a = Array(a) return String(a[0 ..< (a.count - commonLength)]) } func distance(_ a: String, _ b: String) -> Int { let a = Array(a) let b = Array(b) var result = 0 for k in 1 ... min(a.count, b.count) { if a[(a.count - k) ..< a.count] == b[0 ..< k] { result = k } } return b.count - result } }
mit
af3f542d3a9fbb4de2370a02b31821a5
32.108434
121
0.47288
3.815278
false
false
false
false
filestack/filestack-ios
Sources/Filestack/Internal/Extensions/UIImage+Write.swift
1
934
// // UIImage+write.swift // Filestack // // Created by Mihály Papp on 31/07/2018. // Copyright © 2018 Filestack. All rights reserved. // import UIKit extension UIImage { func with(written text: String, atPoint point: CGPoint) -> UIImage { let textSize = min(size.height, size.width) / 20 let textColor = UIColor.white let textFont = UIFont(name: "Helvetica Bold", size: textSize)! UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale) let textFontAttributes: [NSAttributedString.Key: Any] = [.font: textFont, .foregroundColor: textColor] draw(in: CGRect(origin: CGPoint.zero, size: size)) let rect = CGRect(origin: point, size: size) text.draw(in: rect, withAttributes: textFontAttributes) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage ?? self } }
mit
7602b56682a20a386a680f3858eaaa2c
30.066667
110
0.678112
4.417062
false
false
false
false
zisko/swift
stdlib/public/core/UTF32.swift
1
2605
//===--- UTF32.swift ------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// extension Unicode { @_fixed_layout // FIXME(sil-serialize-all) public enum UTF32 { case _swift3Codec } } extension Unicode.UTF32 : Unicode.Encoding { public typealias CodeUnit = UInt32 public typealias EncodedScalar = CollectionOfOne<UInt32> @_inlineable // FIXME(sil-serialize-all) @_versioned // FIXME(sil-serialize-all) internal static var _replacementCodeUnit: CodeUnit { @inline(__always) get { return 0xFFFD } } @_inlineable // FIXME(sil-serialize-all) public static var encodedReplacementCharacter : EncodedScalar { return EncodedScalar(_replacementCodeUnit) } @_inlineable // FIXME(sil-serialize-all) @inline(__always) public static func _isScalar(_ x: CodeUnit) -> Bool { return true } @_inlineable // FIXME(sil-serialize-all) @inline(__always) public static func decode(_ source: EncodedScalar) -> Unicode.Scalar { return Unicode.Scalar(_unchecked: source.first!) } @_inlineable // FIXME(sil-serialize-all) @inline(__always) public static func encode( _ source: Unicode.Scalar ) -> EncodedScalar? { return EncodedScalar(source.value) } @_fixed_layout // FIXME(sil-serialize-all) public struct Parser { @_inlineable // FIXME(sil-serialize-all) public init() { } } public typealias ForwardParser = Parser public typealias ReverseParser = Parser } extension UTF32.Parser : Unicode.Parser { public typealias Encoding = Unicode.UTF32 /// Parses a single Unicode scalar value from `input`. @_inlineable // FIXME(sil-serialize-all) public mutating func parseScalar<I : IteratorProtocol>( from input: inout I ) -> Unicode.ParseResult<Encoding.EncodedScalar> where I.Element == Encoding.CodeUnit { let n = input.next() if _fastPath(n != nil), let x = n { // Check code unit is valid: not surrogate-reserved and within range. guard _fastPath((x &>> 11) != 0b1101_1 && x <= 0x10ffff) else { return .error(length: 1) } // x is a valid scalar. return .valid(UTF32.EncodedScalar(x)) } return .emptyInput } }
apache-2.0
bf2ef3fe5f9caa071c2740adcedfdf97
30.011905
80
0.650672
4.270492
false
false
false
false
icaksama/Weathersama
WeathersamaDemo/WeathersamaDemo/Utilities/CoreDataStack.swift
1
2650
// // WeatherModel.swift // WeathersamaDemo // // Created by Saiful I. Wicaksana on 10/5/17. // Copyright © 2017 icaksama. All rights reserved. // import Foundation import UIKit import CoreData class CoreDataStack { static var applicationDocumentsDirectory: URL = { let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) return urls[urls.count-1] }() static var managedObjectModel: NSManagedObjectModel = { let modelURL = Bundle(for: CoreDataStack.self).url(forResource: "WeathersamaDemo", withExtension: "momd")! return NSManagedObjectModel(contentsOf: modelURL)! }() static var persistentStoreCoordinator: NSPersistentStoreCoordinator = { let coordinator = NSPersistentStoreCoordinator(managedObjectModel: managedObjectModel) let url = applicationDocumentsDirectory.appendingPathComponent("WeathersamaDemo.xcdatamodeld") var failureReason = "There was an error creating or loading the application's saved data." let options = [NSMigratePersistentStoresAutomaticallyOption: NSNumber(value: true as Bool), NSInferMappingModelAutomaticallyOption: NSNumber(value: true as Bool)] do { try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: options) } catch { var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "http://www.icaksama.com", code: 9999, userInfo: dict) NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)") abort() } return coordinator }() static var managedObjectContext: NSManagedObjectContext = { let coordinator = persistentStoreCoordinator var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support static func saveContext () { if managedObjectContext.hasChanges { do { try managedObjectContext.save() } catch { let nserror = error as NSError NSLog("Unresolved error \(nserror), \(nserror.userInfo)") abort() } } } }
mit
d205cce648cbaded1b8437103af2227c
39.753846
170
0.671952
5.809211
false
false
false
false
bamurph/FeedKit
Tests/DateTests.swift
1
6022
// // DateTests.swift // // Copyright (c) 2016 Nuno Manuel Dias // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import XCTest @testable import FeedKit class DateTests: BaseTestCase { func testRFC822DateFormatter() { // Given let rfc822DateFormatter = RFC822DateFormatter() let dateString = "Tue, 04 Feb 2014 22:03:45 Z" var calendar = Calendar(identifier: Calendar.Identifier.gregorian) calendar.locale = Locale(identifier: "en_US_POSIX") calendar.timeZone = TimeZone(secondsFromGMT: 0)! // When let date = rfc822DateFormatter.date(from: dateString) // Then XCTAssertNotNil(date) let components = calendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date!) XCTAssertEqual(components.day, 4) XCTAssertEqual(components.month, 2) XCTAssertEqual(components.year, 2014) XCTAssertEqual(components.hour, 22) XCTAssertEqual(components.minute, 3) XCTAssertEqual(components.second, 45) } func testRFC3339DateFormatter() { // Given let rfc3339DateFormatter = RFC3339DateFormatter() let dateString = "2016-01-15T15:54:10-01:00" var calendar = Calendar(identifier: Calendar.Identifier.gregorian) calendar.locale = Locale(identifier: "en_US_POSIX") calendar.timeZone = TimeZone(secondsFromGMT: 0)! // When let date = rfc3339DateFormatter.date(from: dateString) // Then XCTAssertNotNil(date) let components = calendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date!) XCTAssertEqual(components.day, 15) XCTAssertEqual(components.month, 1) XCTAssertEqual(components.year, 2016) XCTAssertEqual(components.hour, 16) XCTAssertEqual(components.minute, 54) XCTAssertEqual(components.second, 10) } func testISO8601DateFormatter() { // Given let iso8601DateFormatter = RFC3339DateFormatter() let dateString = "1994-11-05T08:15:30-05:00" var calendar = Calendar(identifier: Calendar.Identifier.gregorian) calendar.locale = Locale(identifier: "en_US_POSIX") calendar.timeZone = TimeZone(secondsFromGMT: 0)! // When let date = iso8601DateFormatter.date(from: dateString) // Then XCTAssertNotNil(date) let components = calendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date!) XCTAssertEqual(components.day, 5) XCTAssertEqual(components.month, 11) XCTAssertEqual(components.year, 1994) XCTAssertEqual(components.hour, 13) XCTAssertEqual(components.minute, 15) XCTAssertEqual(components.second, 30) } func testDateFromRFC822Spec() { // Given let spec = DateSpec.rfc822 let dateStrings = [ "Tue, 04 Feb 2014 22:10:15 Z", "Sun, 05 Jun 2016 08:35:14 Z", "Sun, 05 Jun 2016 08:54 +0000", "Mon, 21 Mar 2016 13:31:23 GMT", "Sat, 04 Jun 2016 16:26:37 EDT", "Sat, 04 Jun 2016 11:55:28 PDT", "Sun, 5 Jun 2016 01:51:07 -0700", "Sun, 5 Jun 2016 01:30:30 -0700", "Thu, 02 June 2016 14:43:37 GMT", "Sun, 5 Jun 2016 01:49:56 -0700", "Fri, 27 May 2016 14:32:19 -0400", "Sun, 05 Jun 2016 01:45:00 -0700", "Sun, 05 Jun 2016 08:32:03 +0000", "Sat, 04 Jun 2016 22:33:02 +0000", "Sun, 05 Jun 2016 01:52:30 -0700", "Thu, 02 Jun 2016 15:24:37 +0000" ] // When let dates = dateStrings.flatMap { (dateString) -> Date? in return dateString.dateFromSpec(spec) } // Then XCTAssertEqual(dateStrings.count, dates.count) } func testDateFromRFC3339Spec() { // Given let spec = DateSpec.rfc3999 let dateStrings = [ "2016-06-05T09:30:01Z", "2016-06-05T03:18:00Z", "2016-06-05T04:30:29Z", "1985-04-12T23:20:50.52Z", "2016-06-02T18:07:16+01:00", "2016-06-05T05:00:03-04:00", "2016-04-30T11:51:54-04:00", "2016-06-03T17:01:48-07:00", "2016-06-05T03:12:10+00:00", "2015-02-22T13:13:48-05:00", "2016-06-03T23:33:00-04:00", "1996-12-19T16:39:57-08:00", ] // When let dates = dateStrings.flatMap { (dateString) -> Date? in return dateString.dateFromSpec(spec) } // Then XCTAssertEqual(dateStrings.count, dates.count) } }
mit
27b7536a2de88f3e25633d26d5d3f859
33.809249
109
0.591996
4.138832
false
true
false
false
lorentey/swift
test/IRGen/exact_self_class_metadata_peephole.swift
6
4716
// RUN: %target-swift-frontend -emit-ir %s | %FileCheck %s --check-prefix=CHECK --check-prefix=ONONE // R/UN: %target-swift-frontend -O -disable-llvm-optzns -emit-ir %s | %FileCheck %s --check-prefix=CHECK --check-prefix=ONONE @_silgen_name("useMetadata") func useMetadata<T>(_: T.Type) // TODO: Although this is not explicitly final, class hierarchy analysis // should figure out that it's effectively final because it has no // subclasses. private class PrivateEffectivelyFinal<T, U, V> { final func butts() { useMetadata(PrivateEffectivelyFinal<T, U, V>.self) useMetadata(PrivateEffectivelyFinal<Int, String, V>.self) } // CHECK-LABEL: define {{.*}}PrivateEffectivelyFinal{{.*}}cfC // CHECK: call {{.*}}@swift_allocObject(%swift.type* %0 } // The class is not final and has subclasses, so we can only peephole // metadata requests in limited circumstances. private class PrivateNonfinal<T, U, V> { // The designated init allocating entry point is always overridden // by subclasses, so it can use the self metadata it was passed. // Methods in general on nonfinal classes cannot use the self metadata as // is. // CHECK-LABEL: define {{.*}}15PrivateNonfinal{{.*}}buttsyyF" @inline(never) final func butts() { // CHECK: [[INSTANTIATED_TYPE_RESPONSE:%.*]] = call {{.*}} @{{.*}}15PrivateNonfinal{{.*}}Ma // CHECK-NEXT: [[INSTANTIATED_TYPE:%.*]] = extractvalue {{.*}} [[INSTANTIATED_TYPE_RESPONSE]] // CHECK-NEXT: call {{.*}} @useMetadata(%swift.type* [[INSTANTIATED_TYPE]], %swift.type* [[INSTANTIATED_TYPE]]) useMetadata(PrivateNonfinal<T, U, V>.self) // CHECK: [[INSTANTIATED_TYPE_RESPONSE:%.*]] = call {{.*}} @{{.*}}15PrivateNonfinal{{.*}}Ma // CHECK-NEXT: [[INSTANTIATED_TYPE:%.*]] = extractvalue {{.*}} [[INSTANTIATED_TYPE_RESPONSE]] // CHECK-NEXT: call {{.*}} @useMetadata(%swift.type* [[INSTANTIATED_TYPE]], %swift.type* [[INSTANTIATED_TYPE]]) useMetadata(PrivateNonfinal<Int, String, V>.self) } // CHECK-LABEL: define {{.*}}15PrivateNonfinal{{.*}}cfC // CHECK: call {{.*}}@swift_allocObject(%swift.type* %0 } // TODO: Although this is not explicitly final, class hierarchy analysis // should figure out that it's effectively final because it has no // subclasses. private class PrivateNonfinalSubclass: PrivateNonfinal<Int, String, Float> { @inline(never) final func borts() { useMetadata(PrivateNonfinalSubclass.self) } // CHECK-LABEL: define {{.*}}PrivateNonfinalSubclass{{.*}}cfC // CHECK: call {{.*}}@swift_allocObject(%swift.type* %0 } final private class FinalPrivateNonfinalSubclass<U>: PrivateNonfinal<U, String, Float> { // The class is final, so we can always form metadata for // FinalPrivateNonfinalSubclass<U> from the self argument. // CHECK-LABEL: define {{.*}}FinalPrivateNonfinalSubclass{{.*}}burts @inline(never) final func burts() { // CHECK: [[TYPE_GEP:%.*]] = getelementptr {{.*}} %0 // CHECK: [[TYPE:%.*]] = load {{.*}} [[TYPE_GEP]] // CHECK: call {{.*}} @useMetadata(%swift.type* [[TYPE]], %swift.type* [[TYPE]]) useMetadata(FinalPrivateNonfinalSubclass<U>.self) // CHECK: [[INSTANTIATED_TYPE:%.*]] = call {{.*}} @__swift_instantiateConcreteTypeFromMangledName({{.*}}FinalPrivateNonfinalSubclass // CHECK: call {{.*}} @useMetadata(%swift.type* [[INSTANTIATED_TYPE]], %swift.type* [[INSTANTIATED_TYPE]]) useMetadata(FinalPrivateNonfinalSubclass<Int>.self) } // CHECK-LABEL: define {{.*}}FinalPrivateNonfinalSubclass{{.*}}cfC" // CHECK: call {{.*}}@swift_allocObject(%swift.type* %0 } final private class PrivateFinal<T, U, V> { // The class is final, so we can always form metadata for // PrivateFinal<T, U, V> from the self argument. // CHECK-LABEL: define {{.*}}PrivateFinal{{.*}}butts func butts() { // CHECK: [[TYPE_GEP:%.*]] = getelementptr {{.*}} %0 // CHECK: [[TYPE:%.*]] = load {{.*}} [[TYPE_GEP]] // CHECK: call {{.*}} @useMetadata(%swift.type* [[TYPE]], %swift.type* [[TYPE]]) useMetadata(PrivateFinal<T, U, V>.self) // CHECK: [[INSTANTIATED_TYPE:%.*]] = call {{.*}} @__swift_instantiateConcreteTypeFromMangledName({{.*}}PrivateFinal // CHECK: call {{.*}} @useMetadata(%swift.type* [[INSTANTIATED_TYPE]], %swift.type* [[INSTANTIATED_TYPE]]) useMetadata(PrivateFinal<Int, String, Float>.self) } // CHECK-LABEL: define {{.*}}PrivateFinal{{.*}}cfC" // CHECK: call {{.*}}@swift_allocObject(%swift.type* %0 } public func useStuff<T, U, V>(_: T, _: U, _: V) { PrivateEffectivelyFinal<T, U, V>().butts() PrivateNonfinal<T, U, V>().butts() PrivateNonfinalSubclass().borts() FinalPrivateNonfinalSubclass<U>().burts() PrivateFinal<T, U, V>().butts() }
apache-2.0
3727c2f5baa95354aeb81a6b57a21f2f
44.346154
136
0.655428
3.690141
false
false
false
false
vnu/YelpMe
YelpMe/BusinessLocation.swift
1
3415
// // BusinessLocation.swift // YelpMe // // Created by Vinu Charanya on 2/10/16. // Copyright © 2016 vnu. All rights reserved. // import UIKit //"location": { // "cross_streets": "Jones St & Leavenworth St", // "city": "San Francisco", // "display_address": [ // "484 Ellis St", // "Tenderloin", // "San Francisco, CA 94102" // ], // "geo_accuracy": 9.5, // "neighborhoods": [ // "Tenderloin" // ], // "postal_code": "94102", // "country_code": "US", // "address": [ // "484 Ellis St" // ], // "coordinate": { // "latitude": 37.7847191, // "longitude": -122.414172 // }, // "state_code": "CA" // } class BusinessLocation: NSObject { let crossStreets: String? let city: String? let displayAddress: String? let geoAccuracy: Double? let neighborhoods: String? let postalCode: String? let countryCode: String? let address: String? let latitude: Double? let longitude: Double? let stateCode: String? init(dictionary: NSDictionary){ self.crossStreets = dictionary["cross_street"] as? String self.city = dictionary["city"] as? String self.geoAccuracy = dictionary["geo_accuracy"] as? Double self.postalCode = dictionary["postal_code"] as? String self.countryCode = dictionary["country_code"] as? String self.stateCode = dictionary["state_code"] as? String var displayAddress = "" if let displayAddressArray = dictionary["display_address"] as? Array<String>{ if displayAddressArray.count > 0{ displayAddress = displayAddressArray.joinWithSeparator(", ") } } self.displayAddress = displayAddress var address = "" if let addressArray = dictionary["address"] as? Array<String>{ if addressArray.count > 0 { address = addressArray.joinWithSeparator(", ") } } self.address = address var neighborhoods = "" if let neighborhoodsArray = dictionary["neighborhoods"] as? Array<String>{ neighborhoods = neighborhoodsArray.joinWithSeparator(", ") } self.neighborhoods = neighborhoods var lat = Double(0) var lng = Double(0) if let coordinates = dictionary["coordinate"] as? NSDictionary{ lat = coordinates["latitude"] as! Double lng = coordinates["longitude"] as! Double } self.latitude = lat self.longitude = lng } // Creates a text representation override var description: String { return "\n\t\t city: \(self.city!)" + // "\n\t\t crossStreets: \(self.crossStreets!)" + "\n\t\t displayAddress: \(self.displayAddress!)" + "\n\t\t geoAccuracy: \(self.geoAccuracy!)" + "\n\t\t neighborhoods: \(self.neighborhoods!)" + "\n\t\t postalCode: \(self.postalCode!)" + "\n\t\t countryCode: \(self.countryCode!)" + "\n\t\t address: \(self.address!)" + "\n\t\t latitude: \(self.latitude!)" + "\n\t\t longitude: \(self.longitude!)" + "\n\t\t statecpde: \(self.stateCode!)" } }
apache-2.0
9d93ad2f4e39649462302a1e684de269
30.045455
85
0.540129
4.035461
false
false
false
false
guarani/Xaddress-iOS-Data-Loader
XaddressLoader/ViewController.swift
1
6580
// // ViewController.swift // XaddressLoader // // Created by Paul Von Schrottky on 10/15/16. // Copyright © 2016 Xaddress. All rights reserved. // import UIKit import SwiftCSV import CoreData class ViewController: UIViewController { @IBOutlet weak var statusLabel: UILabel! var countries: CSV! var states: CSV! var nouns: CSV! var adjectives: CSV! var images: CSV! override func viewDidLoad() { super.viewDidLoad() self.statusLabel.text = "Please wait, creating Core Data database from CSV files..." print(self.statusLabel.text!) dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { let moc = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext // Read the CSV files. do { self.countries = try CSV(name: NSBundle.mainBundle().pathForResource("countries", ofType: "csv")!) self.states = try CSV(name: NSBundle.mainBundle().pathForResource("states", ofType: "csv")!) self.nouns = try CSV(name: NSBundle.mainBundle().pathForResource("en", ofType: "csv")!) self.adjectives = try CSV(name: NSBundle.mainBundle().pathForResource("adj_en", ofType: "csv")!) self.images = try CSV(name: NSBundle.mainBundle().pathForResource("images", ofType: "csv")!) } catch { // Catch } self.images.enumerateAsDict { row in //index,en,es let entity = NSEntityDescription.entityForName("XAImage", inManagedObjectContext: moc) let image = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: moc) as! XAImage image.index = Int(row["index"]!) image.en = row["en"] image.es = row["es"] } self.nouns.enumerateAsDict { row in //word,popularity,code,type let entity = NSEntityDescription.entityForName("XANoun", inManagedObjectContext: moc) let noun = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: moc) as! XANoun noun.word = row["word"] if let popularity = row["popularity"], num = Int32(popularity) { noun.popularity = NSNumber(int: num) } noun.code = row["code"] noun.kind = row["type"] } self.adjectives.enumerateAsDict { row in //word,popularity,code,type let entity = NSEntityDescription.entityForName("XAAdjective", inManagedObjectContext: moc) let adj = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: moc) as! XAAdjective adj.word = row["word"] if let popularity = row["popularity"], num = Int32(popularity) { adj.popularity = NSNumber(int: num) } adj.code = row["code"] adj.kind = row["type"] } self.countries.enumerateAsDict { row in //countryCode,countryName,Nombre,lat,lng,bounds,combinaciones,tipo let entity = NSEntityDescription.entityForName("XACountry", inManagedObjectContext: moc) let country = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: moc) as! XACountry country.code = row["countryCode"] country.name = row["countryName"] country.nameES = row["Nombre"] country.lat = Double(row["lat"]!)! country.lon = Double(row["lng"]!)! country.bounds = row["bounds"] if let totalCombinations = row["combinaciones"], num = Int32(totalCombinations) { country.totalCombinations = NSNumber(int: num) } country.kind = row["tipo"] } self.states.enumerateAsDict { row in //countryCode,stateCode,stateName1,stateName2,stateName3,googleName,googleAdmin,countryName,lat,lng,bounds,combinaciones let entity = NSEntityDescription.entityForName("XAState", inManagedObjectContext: moc) let state = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: moc) as! XAState state.countryCode = row["countryCode"] state.code = row["stateCode"] state.countryName = row["countryName"] state.name1 = row["stateName1"] state.name2 = row["stateName2"] state.name3 = row["stateName3"] state.googleName = row["googleName"] state.googleAdmin = row["googleAdmin"] if let lat = row["lat"], num = Int32(lat) { state.lat = NSNumber(int: num) } if let lon = row["lng"], num = Int32(lon) { state.lon = NSNumber(int: num) } state.bounds = row["bounds"] if let totalCombinations = row["combinaciones"], num = Int32(totalCombinations) { state.totalCombinations = NSNumber(int: num) } } dispatch_async(dispatch_get_main_queue(), { do { try moc.save() self.statusLabel.text = "Created successfully, open the Xcode log for the path to database file." let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as String print("Created successfully in:\n" + path) print("\nCopy the files:\n") let files = try! NSFileManager.defaultManager().contentsOfDirectoryAtPath(path) for file in files { print(file) } print("\ninto the main Xaddress Xcode project.") } catch let error as NSError { self.statusLabel.text = "Could not save \(error), \(error.userInfo)" print(self.statusLabel.text!) } }) }) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() print("MEMORY WARNING") } }
mit
b2aa59e69c4e151529faed2fb49af33b
43.154362
136
0.542636
5.188486
false
false
false
false
mtransitapps/mtransit-for-ios
MonTransit/Source/SQL/SQLObject/StationObject.swift
1
2464
// // StationObject.swift // SidebarMenu // // Created by Thibault on 15-12-17. // Copyright © 2015 Thibault. All rights reserved. // import UIKit import CoreLocation class StationObject: NSObject { private var mId:Int private var mCode:String private var mTitle:String private var mLongitude:Double private var mLatitude:Double private var mDecentOnly:Int private var mIsNearest:Bool override init() { mId = 0 mCode = "" mTitle = "" mLongitude = 0.0 mLatitude = 0.0 mDecentOnly = 0 mIsNearest = false } init(iId:Int, iCode:String, iTitle:String, iLongitude:Double, iLatitude:Double, iDecentOnly:Int) { self.mId = iId self.mCode = iCode self.mTitle = iTitle self.mLongitude = iLongitude self.mLatitude = iLatitude self.mDecentOnly = iDecentOnly self.mIsNearest = false } func getStationId() -> Int{ return self.mId } func getStationCode() -> String{ return self.mCode } func getStationTitle() -> String{ return self.mTitle } func getStationLongitude() -> Double{ return self.mLongitude } func getStationLatitude() -> Double{ return self.mLatitude } func getDecentOnly() -> Int{ return self.mDecentOnly } func setStationNearest(){ return self.mIsNearest = true } func getStationNearest() -> Bool{ return self.mIsNearest } func distanceToUserInMeter(iUserLocation:CLLocation) -> Int { return Int(iUserLocation.coordinate.distanceInMetersFrom(CLLocationCoordinate2D(latitude: self.getStationLatitude(), longitude: self.getStationLongitude()))) } func distanceToUser(iUserLocation:CLLocation) -> String { var wDistanceString = "" var wDistanteTo:Double = iUserLocation.coordinate.distanceInMetersFrom(CLLocationCoordinate2D(latitude: self.getStationLatitude(), longitude: self.getStationLongitude())) if wDistanteTo > 1000{ wDistanteTo = wDistanteTo / 1000 wDistanteTo = wDistanteTo.roundedTwoDigit wDistanceString = String(wDistanteTo) + " km" } else{ wDistanceString = String(Int(wDistanteTo)) + " m" } return wDistanceString } }
apache-2.0
0f97ee651267c614d54190dbb5716726
24.391753
178
0.610637
4.210256
false
false
false
false
mshhmzh/firefox-ios
SharedTests/PhoneNumberFormatterTests.swift
4
5084
/* 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/. */ @testable import Shared import Foundation import XCTest import libPhoneNumber class PhoneNumberFormatterTests: XCTestCase { // MARK: - Country Code Guessing func testUsesCarrierForGuessingCountryCode() { let utilMock = PhoneNumberUtilMock(carrierCountryCode: "DE") let formatter = PhoneNumberFormatter(util: utilMock) XCTAssertEqual(formatter.guessCurrentCountryCode(NSLocale(localeIdentifier: "en_US")), "DE") } func testFallsBackToSpecifiedLocaleForGuessingCountryCode() { let utilMock = PhoneNumberUtilMock(carrierCountryCode: NB_UNKNOWN_REGION) let formatter = PhoneNumberFormatter(util: utilMock) XCTAssertEqual(formatter.guessCurrentCountryCode(NSLocale(localeIdentifier: "en_US")), "US") } // MARK: - Format Selection func testSelectsNationalFormatWithoutCountryCode() { let number = NBPhoneNumber(countryCodeSource: .FROM_DEFAULT_COUNTRY) let formatter = PhoneNumberFormatter() XCTAssertEqual(formatter.formatForNumber(number), NBEPhoneNumberFormat.NATIONAL) } func testSelectsInternationalFormatWithCountryCode() { let number = NBPhoneNumber(countryCodeSource: .FROM_NUMBER_WITH_PLUS_SIGN) let formatter = PhoneNumberFormatter() XCTAssertEqual(formatter.formatForNumber(number), NBEPhoneNumberFormat.INTERNATIONAL) } // MARK: - Formatting func testReturnsInputStringWhenParsingFails() { let utilMock = PhoneNumberUtilMock(failOnParsing: true) let formatter = PhoneNumberFormatter(util: utilMock) let phoneNumber = "123456789" XCTAssertEqual(formatter.formatPhoneNumber(phoneNumber), phoneNumber) XCTAssertTrue(utilMock.didParse) XCTAssertFalse(utilMock.didFormat) } func testReturnsInputStringWhenValidatingFails() { let utilMock = PhoneNumberUtilMock(failOnValidating: true) let formatter = PhoneNumberFormatter(util: utilMock) let phoneNumber = "123456789" XCTAssertEqual(formatter.formatPhoneNumber(phoneNumber), phoneNumber) XCTAssertTrue(utilMock.didParse) XCTAssertTrue(utilMock.didValidate) XCTAssertFalse(utilMock.didFormat) } func testReturnsInputStringWhenFormattingFails() { let utilMock = PhoneNumberUtilMock(failOnFormatting: true) let formatter = PhoneNumberFormatter(util: utilMock) let phoneNumber = "123456789" XCTAssertEqual(formatter.formatPhoneNumber(phoneNumber), phoneNumber) XCTAssertTrue(utilMock.didParse) XCTAssertTrue(utilMock.didValidate) XCTAssertTrue(utilMock.didFormat) } func testFormatsNumber() { let utilMock = PhoneNumberUtilMock() let formatter = PhoneNumberFormatter(util: utilMock) let phoneNumber = "123456789" XCTAssertEqual(formatter.formatPhoneNumber(phoneNumber), utilMock.formattedPhoneNumber) XCTAssertTrue(utilMock.didParse) XCTAssertTrue(utilMock.didValidate) XCTAssertTrue(utilMock.didFormat) } } // MARK: - Mocks & Helpers private class PhoneNumberUtilMock: NBPhoneNumberUtil { let formattedPhoneNumber = "(123) 456789" private let carrierCountryCode: String? private let failOnParsing: Bool private let failOnValidating: Bool private let failOnFormatting: Bool private var didParse = false private var didValidate = false private var didFormat = false init(carrierCountryCode: String? = nil, failOnParsing: Bool = false, failOnValidating: Bool = false, failOnFormatting: Bool = false) { self.carrierCountryCode = carrierCountryCode self.failOnParsing = failOnParsing self.failOnValidating = failOnValidating self.failOnFormatting = failOnFormatting } private override func countryCodeByCarrier() -> String! { return carrierCountryCode ?? NB_UNKNOWN_REGION } private override func parseAndKeepRawInput(numberToParse: String!, defaultRegion: String!) throws -> NBPhoneNumber { didParse = true if failOnParsing { throw NSError(domain: "foo", code: 1, userInfo: nil) } return NBPhoneNumber(countryCodeSource: .FROM_NUMBER_WITH_PLUS_SIGN) } private override func isValidNumber(number: NBPhoneNumber!) -> Bool { didValidate = true return !failOnValidating } private override func format(phoneNumber: NBPhoneNumber!, numberFormat: NBEPhoneNumberFormat) throws -> String { didFormat = true if failOnFormatting { throw NSError(domain: "foo", code: 1, userInfo: nil) } return formattedPhoneNumber } } extension NBPhoneNumber { convenience init(countryCodeSource: NBECountryCodeSource) { self.init() self.countryCodeSource = NSNumber(integer: countryCodeSource.rawValue) } }
mpl-2.0
2346ef8a55ecee17df55e94e68629437
35.57554
138
0.716365
4.860421
false
true
false
false
wyxy2005/SEGSegmentedViewController
SegmentedViewControllerTests/SegmentedViewControllerItemsManagerTests.swift
1
11157
// // SegmentedViewControllerItemsManagerTests.swift // SegmentedViewController // // Created by Thomas Sherwood on 08/09/2014. // Copyright (c) 2014 Thomas Sherwood. All rights reserved. // import Foundation import SegmentedViewController import UIKit import XCTest class SegmentedViewControllerItemsManagerTests: XCTestCase { func testInit() { let manager = SegmentedViewControllerItemsManager() XCTAssertNil(manager.parentController, "Parent view controller should be nil on initialization") XCTAssertEqual(0, manager.numberOfItems, "No items should be in the manager on initialization") } func testEncodeWithCoder() { let manager = SegmentedViewControllerItemsManager() let controller = UIViewController() controller.title = "Title" manager.addController(controller, animated: false) let data = NSMutableData() let encoder = NSKeyedArchiver(forWritingWithMutableData: data) manager.encodeWithCoder(encoder) encoder.finishEncoding() let decoder = NSKeyedUnarchiver(forReadingWithData: data) let items = decoder.decodeObjectForKey(SEGItemsManagerItemsCoderKey) as? [SegmentedViewControllerItem] XCTAssertNotNil(items, "Items not encoded with coder") XCTAssertEqual(1, items!.count, "Items not encoded properly") } func testInitWithCoderWithNoEncodedItems() { let data = NSMutableData() let decoder = NSKeyedUnarchiver(forReadingWithData: data) let manager = SegmentedViewControllerItemsManager(coder: decoder) XCTAssertEqual(0, manager.numberOfItems, "Coder did not possess any items") } func testInitWithCoderWithEncodedItems() { let data = NSMutableData() let encoder = NSKeyedArchiver(forWritingWithMutableData: data) let controller = UIViewController() let title = "Title" controller.title = title let items = [SegmentedViewControllerItem(controller: controller)] encoder.encodeObject(items, forKey: SEGItemsManagerItemsCoderKey) encoder.finishEncoding() let decoder = NSKeyedUnarchiver(forReadingWithData: data) let item = SegmentedViewControllerItemsManager(coder: decoder) XCTAssertEqual(1, item.numberOfItems, "Item in coder not retained by manager") XCTAssertEqual(title, item.itemAtIndex(0)!.viewController!.title!, "Provided item not retained by manager") } func testAddItemNotPreviouslyAdded() { let controller = UIViewController() let manager = SegmentedViewControllerItemsManager() let item = SegmentedViewControllerItem(controller: controller) manager.addItem(item, animated: false) XCTAssertEqual(1, manager.numberOfItems, "Item not added to items manager") XCTAssert(manager.itemAtIndex(0)! === item, "Item provided to addItem:animated: not retained") XCTAssert(manager.itemAtIndex(0)!.delegate === manager, "Manager must assign itself as the delegate of items it retains") } func testAddItemPreviouslyAdded() { let controller = UIViewController() let manager = SegmentedViewControllerItemsManager() let item = SegmentedViewControllerItem(controller: controller) manager.addItem(item, animated: false) manager.addItem(item, animated: false) XCTAssertEqual(1, manager.numberOfItems, "Item should be added to the manager only once") } func testAddItemNotifiesPresenter() { let controller = UIViewController() let manager = SegmentedViewControllerItemsManager() let item = SegmentedViewControllerItem(controller: controller) let presenter = SegmentedViewControllerItemPresenterMock() let animated = true manager.presenter = presenter manager.addItem(item, animated: animated) XCTAssertNotNil(presenter.item, "Item not provided to presenter") XCTAssertNotNil(presenter.index, "Index not provided to presenter") XCTAssertNotNil(presenter.animated, "Animation flag not provided to presenter") XCTAssert(presenter.item === item, "Item not provided to presenter") XCTAssert(presenter.index! == 0, "Index not provided to presenter") XCTAssert(presenter.animated! == animated, "Animation flag not provided to presenter") } func testAddControllerWithNoTitleAddsItemWithEmptyTitle() { let controller = UIViewController() let manager = SegmentedViewControllerItemsManager() manager.addController(controller, animated: false) XCTAssertEqual(1, manager.numberOfItems, "Item not added to items manager") XCTAssertNotNil(manager.itemAtIndex(0)!.text, "No title provided to item") XCTAssertEqual("", manager.itemAtIndex(0)!.text!, "Empty title not provided to item") } func testAddControllerWithTitle() { let controller = UIViewController() let title = "Title" let manager = SegmentedViewControllerItemsManager() manager.addController(controller, withTitle: title, animated: false) XCTAssertEqual(1, manager.numberOfItems, "Item not added to items manager") XCTAssertNotNil(manager.itemAtIndex(0)!.text, "Title not provided to item") XCTAssertEqual(title, manager.itemAtIndex(0)!.text!, "Title not provided to item") } func testAddControllerWithIcon() { let controller = UIViewController() let icon = UIImage() let manager = SegmentedViewControllerItemsManager() manager.addController(controller, withIcon: icon, animated: false) XCTAssertEqual(1, manager.numberOfItems, "Item not added to items manager") XCTAssertNotNil(manager.itemAtIndex(0)!.icon, "Icon not provided to item") XCTAssertEqual(icon.hash, manager.itemAtIndex(0)!.icon!.hash, "Icon not provided to item") } func testItemAtIndexWithNoItems() { let manager = SegmentedViewControllerItemsManager() let item = manager.itemAtIndex(0) XCTAssertNil(item, "No items in manager") } func testItemAtIndexWithNegativeIndex() { let controller = UIViewController() let manager = SegmentedViewControllerItemsManager() manager.addController(controller, animated: false) let item = manager.itemAtIndex(-1) XCTAssertNil(item, "Negative indicies should return nil") } func testItemAtIndexWithIndexGreaterThanCount() { let controller = UIViewController() let manager = SegmentedViewControllerItemsManager() manager.addController(controller, animated: false) let item = manager.itemAtIndex(1) XCTAssertNil(item, "Items out of range should return nil") } func testItemAtIndexWithUISegmentedControlNoSegment() { let controller = UIViewController() let manager = SegmentedViewControllerItemsManager() manager.addController(controller, animated: false) let item = manager.itemAtIndex(UISegmentedControlNoSegment) XCTAssertNil(item, "UISegmentedControlNoSegment should return nil") } func testItemAtIndexLowerEdgeCase() { let controller = UIViewController() let manager = SegmentedViewControllerItemsManager() let addedItem = SegmentedViewControllerItem(controller: controller) manager.addItem(addedItem, animated: false) let item = manager.itemAtIndex(0) XCTAssertNotNil(item, "Item at valid index") XCTAssert(item === addedItem, "Returned itemAtIndex: not expected item") } func testItemAtIndexUpperEdgeCase() { let controllerA = UIViewController() let controllerB = UIViewController() let manager = SegmentedViewControllerItemsManager() let addedItemA = SegmentedViewControllerItem(controller: controllerA) let addedItemB = SegmentedViewControllerItem(controller: controllerB) manager.addItem(addedItemA, animated: false) manager.addItem(addedItemB, animated: false) let item = manager.itemAtIndex(1) XCTAssertNotNil(item, "Item at valid index") XCTAssert(item === addedItemB, "Returned itemAtIndex: not expected item") } func testFindItemWithControllerNoItemsWithController() { let controller = UIViewController() let manager = SegmentedViewControllerItemsManager() let foundItem = manager.findItemWithController(controller) XCTAssertNil(foundItem, "No items possessed the controller") } func testFindItemWithControllerOneItemWithController() { let controller = UIViewController() let manager = SegmentedViewControllerItemsManager() let item = SegmentedViewControllerItem(controller: controller) manager.addItem(item, animated: false) let foundItem = manager.findItemWithController(controller) XCTAssertNotNil(foundItem, "One item possessed the controller") } func testFindItemWithControllerTwoItemsWithController() { let controller = UIViewController() let manager = SegmentedViewControllerItemsManager() let itemA = SegmentedViewControllerItem(controller: controller) let itemB = SegmentedViewControllerItem(controller: controller) manager.addItem(itemA, animated: false) let foundItem = manager.findItemWithController(controller) XCTAssert(foundItem === itemA, "First match should have been returned") } func testSetContentOfControllerToTextWhereControllerNotPreviouslyAdded() { let text = "Text" let controller = UIViewController() let manager = SegmentedViewControllerItemsManager() let didSet = manager.setContentOfController(controller, toText: text, animated: false) XCTAssertFalse(didSet, "Should not have been able to set text for controller not previously added") } func testSetContentOfControllerToTextWhereControllerPreviouslyAdded() { let text = "Text" let controller = UIViewController() let item = SegmentedViewControllerItem(controller: controller) let manager = SegmentedViewControllerItemsManager() manager.addItem(item, animated: false) let didSet = manager.setContentOfController(controller, toText: text, animated: false) XCTAssertTrue(didSet, "Should have been able to set content of added controller") XCTAssertNotNil(item.text, "Text not propgated to item") XCTAssertEqual(text, item.text!, "Text not propgated to item") } func testSetContentOfControllerToIconWhereControllerNotPreviouslyAdded() { let icon = UIImage() let controller = UIViewController() let manager = SegmentedViewControllerItemsManager() let didSet = manager.setContentOfController(controller, toIcon: icon, animated: false) XCTAssertFalse(didSet, "Should not have been able to set text for controller not previously added") } func testSetContentOfControllerToIconWhereControllerPreviouslyAdded() { let icon = UIImage() let controller = UIViewController() let item = SegmentedViewControllerItem(controller: controller) let manager = SegmentedViewControllerItemsManager() manager.addItem(item, animated: false) let didSet = manager.setContentOfController(controller, toIcon: icon, animated: false) XCTAssertTrue(didSet, "Should not have been able to set text for controller not previously added") XCTAssertNotNil(item.icon, "Icon not propgated to item") XCTAssertEqual(icon.hash, item.icon!.hash, "Icon not propgated to item") } func testHasItemsWithEmptyArray() { let manager = SegmentedViewControllerItemsManager() XCTAssertFalse(manager.hasItems, "HasItems should return false when array is empty") } func testHasItemsWithOneItem() { let manager = SegmentedViewControllerItemsManager() let controller = UIViewController() controller.title = "Title" manager.addController(controller, animated: false) XCTAssertTrue(manager.hasItems, "HasItems should return true when array contains one item or more") } }
mit
89606ebc4e5de46a5e942170bffa6362
38.704626
123
0.781931
4.507879
false
true
false
false
adrfer/swift
test/ClangModules/ctypes_parse_union.swift
14
1752
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -parse -verify %s import ctypes func useStructWithUnion(vec: GLKVector4) -> GLKVector4 { var vec = vec _ = vec.v.0 _ = vec.v.1 _ = vec.v.2 _ = vec.v.3 vec.v = (0, 0, 0, 0) } func useUnionIndirectFields(vec: GLKVector4) -> GLKVector4 { // TODO: Make indirect fields from anonymous structs in unions // accessible. // Anonymous indirect fields let x: CFloat = vec.x // expected-error{{}} let y: CFloat = vec.y // expected-error{{}} let z: CFloat = vec.z // expected-error{{}} let w: CFloat = vec.w // expected-error{{}} let r: CFloat = vec.r // expected-error{{}} let g: CFloat = vec.g // expected-error{{}} let b: CFloat = vec.b // expected-error{{}} let a: CFloat = vec.a // expected-error{{}} let s: CFloat = vec.s // expected-error{{}} let t: CFloat = vec.t // expected-error{{}} let p: CFloat = vec.p // expected-error{{}} let q: CFloat = vec.q // expected-error{{}} // Named indirect fields let v0: CFloat = vec.v.0 let v1: CFloat = vec.v.1 let v2: CFloat = vec.v.2 let v3: CFloat = vec.v.3 return vec } func useStructWithNamedUnion(u: NamedUnion) -> NamedUnion { var u1 = NamedUnion() u1.a = u.a u1.b = u.b u1.intfloat = u.intfloat return u1 } func useStructWithAnonymousUnion(u: AnonUnion) -> AnonUnion { // TODO: Make union indirect fields from anonymous structs in unions // accessible. let a: CFloat = u.a // expected-error{{}} let b: CFloat = u.b // expected-error{{}} let c: CFloat = u.c // expected-error{{}} let d: CFloat = u.d // expected-error{{}} let x: CInt = u.x return u } func useStructWithUnnamedUnion(u: UnnamedUnion) -> UnnamedUnion { var u = u u.u.i = 100 u.u.f = 1.0 }
apache-2.0
373b037f71e11130066b9fb3523c3963
25.953846
79
0.628425
3.079086
false
false
false
false
adrfer/swift
test/Constraints/lvalues.swift
2
8277
// RUN: %target-parse-verify-swift func f0(inout x: Int) {} func f1<T>(inout x: T) {} func f2(inout x: X) {} func f2(inout x: Double) {} class Reftype { var property: Double { get {} set {} } } struct X { subscript(i: Int) -> Float { get {} set {} } var property: Double { get {} set {} } func genuflect() {} } struct Y { subscript(i: Int) -> Float { get {} set {} } subscript(f: Float) -> Int { get {} set {} } } var i : Int var f : Float var x : X var y : Y func +=(inout lhs: X, rhs : X) {} func +=(inout lhs: Double, rhs : Double) {} prefix func ++(inout rhs: X) {} postfix func ++(inout lhs: X) {} f0(&i) f1(&i) f1(&x[i]) f1(&x.property) f1(&y[i]) // Missing '&' f0(i) // expected-error{{passing value of type 'Int' to an inout parameter requires explicit '&'}}{{4-4=&}} f1(y[i]) // expected-error{{passing value of type 'Float' to an inout parameter requires explicit '&'}} {{4-4=&}} // Assignment operators x += x ++x var yi = y[i] // Non-settable lvalues // FIXME: better diagnostic! var non_settable_x : X { return x } struct Z { var non_settable_x: X { get {} } var non_settable_reftype: Reftype { get {} } var settable_x : X subscript(i: Int) -> Double { get {} } subscript(_: (i: Int, j: Int)) -> X { get {} } } var z : Z func fz() -> Z {} func fref() -> Reftype {} // non-settable var is non-settable: // - assignment non_settable_x = x // expected-error{{cannot assign to value: 'non_settable_x' is a get-only property}} // - inout (mono) f2(&non_settable_x) // expected-error{{cannot pass immutable value as inout argument: 'non_settable_x' is a get-only property}} // - inout (generic) f1(&non_settable_x) // expected-error{{cannot pass immutable value as inout argument: 'non_settable_x' is a get-only property}} // - inout assignment non_settable_x += x // expected-error{{left side of mutating operator isn't mutable: 'non_settable_x' is a get-only property}} ++non_settable_x // expected-error{{cannot pass immutable value to mutating operator: 'non_settable_x' is a get-only property}} // non-settable property is non-settable: z.non_settable_x = x // expected-error{{cannot assign to property: 'non_settable_x' is a get-only property}} f2(&z.non_settable_x) // expected-error{{cannot pass immutable value as inout argument: 'non_settable_x' is a get-only property}} f1(&z.non_settable_x) // expected-error{{cannot pass immutable value as inout argument: 'non_settable_x' is a get-only property}} z.non_settable_x += x // expected-error{{left side of mutating operator isn't mutable: 'non_settable_x' is a get-only property}} ++z.non_settable_x // expected-error{{cannot pass immutable value to mutating operator: 'non_settable_x' is a get-only property}} // non-settable subscript is non-settable: z[0] = 0.0 // expected-error{{cannot assign through subscript: subscript is get-only}} f2(&z[0]) // expected-error{{cannot pass immutable value as inout argument: subscript is get-only}} f1(&z[0]) // expected-error{{cannot pass immutable value as inout argument: subscript is get-only}} z[0] += 0.0 // expected-error{{left side of mutating operator isn't mutable: subscript is get-only}} ++z[0] // expected-error{{cannot pass immutable value to mutating operator: subscript is get-only}} // settable property of an rvalue value type is non-settable: fz().settable_x = x // expected-error{{cannot assign to property: 'fz' returns immutable value}} f2(&fz().settable_x) // expected-error{{cannot pass immutable value as inout argument: 'fz' returns immutable value}} f1(&fz().settable_x) // expected-error{{cannot pass immutable value as inout argument: 'fz' returns immutable value}} fz().settable_x += x // expected-error{{left side of mutating operator isn't mutable: 'fz' returns immutable value}} ++fz().settable_x // expected-error{{cannot pass immutable value to mutating operator: 'fz' returns immutable value}} // settable property of an rvalue reference type IS SETTABLE: fref().property = 0.0 f2(&fref().property) f1(&fref().property) fref().property += 0.0 fref().property += 1 // settable property of a non-settable value type is non-settable: z.non_settable_x.property = 1.0 // expected-error{{cannot assign to property: 'non_settable_x' is a get-only property}} f2(&z.non_settable_x.property) // expected-error{{cannot pass immutable value as inout argument: 'non_settable_x' is a get-only property}} f1(&z.non_settable_x.property) // expected-error{{cannot pass immutable value as inout argument: 'non_settable_x' is a get-only property}} z.non_settable_x.property += 1.0 // expected-error{{left side of mutating operator isn't mutable: 'non_settable_x' is a get-only property}} ++z.non_settable_x.property // expected-error{{cannot pass immutable value to mutating operator: 'non_settable_x' is a get-only property}} // settable property of a non-settable reference type IS SETTABLE: z.non_settable_reftype.property = 1.0 f2(&z.non_settable_reftype.property) f1(&z.non_settable_reftype.property) z.non_settable_reftype.property += 1.0 z.non_settable_reftype.property += 1 // regressions with non-settable subscripts in value contexts _ = z[0] == 0 var d : Double d = z[0] // regressions with subscripts that return generic types var xs:[X] _ = xs[0].property struct A<T> { subscript(i: Int) -> T { get {} } } struct B { subscript(i: Int) -> Int { get {} } } var a:A<B> _ = a[0][0] // Instance members of struct metatypes. struct FooStruct { func instanceFunc0() {} } func testFooStruct() { FooStruct.instanceFunc0(FooStruct())() } // Don't load from explicit lvalues. func takesInt(x: Int) {} func testInOut(inout arg: Int) { var x : Int takesInt(&x) // expected-error{{'&' used with non-inout argument of type 'Int'}} } // Don't infer inout types. var ir = &i // expected-error{{type 'inout Int' of variable is not materializable}} \ // expected-error{{'&' can only appear immediately in a call argument list}} var ir2 = ((&i)) // expected-error{{type 'inout Int' of variable is not materializable}} \ // expected-error{{'&' can only appear immediately in a call argument list}} // <rdar://problem/17133089> func takeArrayRef(inout x:Array<String>) { } // rdar://22308291 takeArrayRef(["asdf", "1234"]) // expected-error{{contextual type 'inout Array<String>' cannot be used with array literal}} // <rdar://problem/19835413> Reference to value from array changed func rdar19835413() { func f1(p: UnsafeMutablePointer<Void>) {} func f2(a: [Int], i: Int, pi: UnsafeMutablePointer<Int>) { var a = a f1(&a) f1(&a[i]) f1(&a[0]) f1(pi) f1(UnsafeMutablePointer(pi)) } } // <rdar://problem/21877598> Crash when accessing stored property without // setter from constructor protocol Radish { var root: Int { get } } public struct Kale : Radish { public let root : Int public init() { let _ = Kale().root self.root = 0 } } func testImmutableUnsafePointer(p: UnsafePointer<Int>) { p.memory = 1 // expected-error {{cannot assign to property: 'memory' is a get-only property}} p[0] = 1 // expected-error {{cannot assign through subscript: subscript is get-only}} } // <https://bugs.swift.org/browse/SR-7> Inferring closure param type to // inout crashes compiler let g = { x in f0(x) } // expected-error{{passing value of type 'Int' to an inout parameter requires explicit '&'}} {{19-19=&}} // <rdar://problem/17245353> Crash with optional closure taking inout func rdar17245353() { typealias Fn = (inout Int) -> () func getFn() -> Fn? { return nil } let _: (inout UInt, UInt) -> Void = { $0 += $1 } } // <rdar://problem/23131768> Bugs related to closures with inout parameters func rdar23131768() { func f(g: (inout Int) -> Void) { var a = 1; g(&a); print(a) } f { $0 += 1 } // Crashes compiler func f2(g: (inout Int) -> Void) { var a = 1; g(&a); print(a) } f2 { $0 = $0 + 1 } // previously error: Cannot convert value of type '_ -> ()' to expected type '(inout Int) -> Void' func f3(g: (inout Int) -> Void) { var a = 1; g(&a); print(a) } f3 { (inout v: Int) -> Void in v += 1 } } // <rdar://problem/23331567> Swift: Compiler crash related to closures with inout parameter. func r23331567(fn: (inout x: Int) -> Void) { var a = 0 fn(x: &a) } r23331567 { $0 += 1 }
apache-2.0
0104a2c64b39d7377485b1efe877e6b7
34.072034
139
0.673674
3.271542
false
false
false
false
coderLL/DYTV
DYTV/DYTV/Classes/Main/Controller/BaseViewController.swift
1
1773
// // BaseViewController.swift // DYTV // // Created by CodeLL on 2016/10/15. // Copyright © 2016年 coderLL. All rights reserved. // import UIKit class BaseViewController: UIViewController { // MARK:- 定义属性 var baseContentView : UIView? // MARK:- 懒加载属性 fileprivate lazy var animImageView : UIImageView = { [unowned self] in let imageView = UIImageView(image: UIImage(named: "home_header_normal")) imageView.center = self.view.center imageView.animationImages = [UIImage(named: "home_header_normal")!, UIImage(named: "home_header_hot")!] imageView.animationDuration = 0.5 imageView.animationRepeatCount = LONG_MAX imageView.autoresizingMask = [.flexibleTopMargin, .flexibleBottomMargin] return imageView }() // MARK:- 系统回调 override func viewDidLoad() { super.viewDidLoad() self.setupUI() } } // MARK:- 添加UI界面 extension BaseViewController { // MARK:- 设置UI界面 func setupUI() { // 1.先隐藏内容的view self.baseContentView?.isHidden = true // 2.添加执行动画的UIImageView self.view.addSubview(animImageView) // 3.给UIImageView执行动画 self.animImageView.startAnimating() // 4.设置背景颜色 view.backgroundColor = UIColor(r: 250, g: 250, b: 250) } // MARK:- 数据请求完成 func loadDataFinished() { // 1.停止动画 self.animImageView.stopAnimating() // 2.隐藏animImageView self.animImageView.isHidden = true // 3.显示内容的view self.baseContentView?.isHidden = false } }
mit
628aa9d29376017932dc4a9f03c32fd2
23.939394
111
0.602673
4.534435
false
false
false
false
kingcos/Swift-3-Design-Patterns
13-State_Pattern.playground/Contents.swift
1
2010
//: Playground - noun: a place where people can play // Powered by https://maimieng.com from https://github.com/kingcos/Swift-X-Design-Patterns import UIKit // 工作类 class Work { var hour = 0 var state: State = ForenoonState() var isFinish = false func writeProgram() { state.writeProgram(self) } } // 协议 protocol State { func writeProgram(_ work: Work) } // 上午状态 struct ForenoonState: State { func writeProgram(_ work: Work) { if work.hour < 12 { print("\(work.hour) 上午") } else { work.state = NoonState() work.writeProgram() } } } // 中午状态 struct NoonState: State { func writeProgram(_ work: Work) { if work.hour < 13 { print("\(work.hour) 中午") } else { work.state = AfternoonState() work.writeProgram() } } } // 下午状态 struct AfternoonState: State { func writeProgram(_ work: Work) { if work.hour < 17 { print("\(work.hour) 下午") } else { work.state = EveningState() work.writeProgram() } } } // 晚上状态 struct EveningState: State { func writeProgram(_ work: Work) { if work.isFinish { work.state = RestState() work.writeProgram() } else { if work.hour < 21 { print("\(work.hour) 晚上") } else { work.state = SleepingState() work.writeProgram() } } } } // 睡觉状态 struct SleepingState: State { func writeProgram(_ work: Work) { print("\(work.hour) 睡觉") } } // 休息状态 struct RestState: State { func writeProgram(_ work: Work) { print("\(work.hour) 休息") } } let work = Work() for i in stride(from: 9, through: 22, by: 1) { if i == 17 { work.isFinish = true } work.hour = i work.writeProgram() }
apache-2.0
f0350c0bafc298fea2adbe4bda746a29
18.876289
90
0.519191
3.557196
false
false
false
false
ajijoyo/EasyTipView
Source/EasyTipView.swift
1
16957
// // EasyTipView.swift // // Copyright (c) 2015 Teodor Patraş // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit @objc public protocol EasyTipViewDelegate { func easyTipViewDidDismiss(tipView : EasyTipView) } public class EasyTipView: UIView, Printable { // MARK:- Nested types - public enum ArrowPosition { case Top case Bottom } public struct Preferences { public var systemFontSize : CGFloat public var textColor : UIColor public var bubbleColor : UIColor public var arrowPosition : ArrowPosition public var font : UIFont? public var textAlignment : NSTextAlignment public init() { systemFontSize = 15 textColor = UIColor.whiteColor() bubbleColor = UIColor.redColor() arrowPosition = .Bottom textAlignment = .Center } } // MARK:- Constants - private struct Constants { static let arrowHeight : CGFloat = 5 static let arrowWidth : CGFloat = 10 static let bubbleHInset : CGFloat = 10 static let bubbleVInset : CGFloat = 1 static let textHInset : CGFloat = 10 static let textVInset : CGFloat = 5 static let bubbleCornerRadius : CGFloat = 5 static let maxWidth : CGFloat = 200 } // MARK:- Variables - override public var backgroundColor : UIColor? { didSet { if let color = backgroundColor { if color != UIColor.clearColor() { self.preferences.bubbleColor = color backgroundColor = UIColor.clearColor() } } } } override public var description : String { let type = _stdlib_getDemangledTypeName(self).componentsSeparatedByString(".").last! return "<< \(type) with text : '\(self.text)' >>" } private weak var presentingView : UIView? private var arrowTip = CGPointZero private var preferences : Preferences weak var delegate : EasyTipViewDelegate? private let font : UIFont private let text : NSString private lazy var textSize : CGSize = { [unowned self] in var attributes : [NSObject : AnyObject] = [NSFontAttributeName : self.font] var textSize = self.text.boundingRectWithSize(CGSizeMake(EasyTipView.Constants.maxWidth, CGFloat.max), options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: attributes, context: nil).size textSize.width = ceil(textSize.width) textSize.height = ceil(textSize.height) if textSize.width < EasyTipView.Constants.arrowWidth { textSize.width = EasyTipView.Constants.arrowWidth } return textSize }() private lazy var contentSize : CGSize = { [unowned self] in var contentSize = CGSizeMake(self.textSize.width + Constants.textHInset * 2 + Constants.bubbleHInset * 2, self.textSize.height + Constants.textVInset * 2 + Constants.bubbleVInset * 2 + Constants.arrowHeight) return contentSize }() // MARK:- Static preferences - private struct GlobalPreferences { private static var preferences : Preferences = Preferences() } public class func setGlobalPreferences (preferences : Preferences) { GlobalPreferences.preferences = preferences } public class func globalPreferences() -> Preferences { return GlobalPreferences.preferences } // MARK:- Initializer - public init (text : NSString, preferences: Preferences?, delegate : EasyTipViewDelegate?){ self.text = text if let p = preferences { self.preferences = p } else { self.preferences = EasyTipView.GlobalPreferences.preferences } if let font = self.preferences.font { self.font = font }else{ self.font = UIFont.systemFontOfSize(self.preferences.systemFontSize) } self.delegate = delegate super.init(frame : CGRectZero) self.backgroundColor = UIColor.clearColor() NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleRotation", name: UIDeviceOrientationDidChangeNotification, object: nil) } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } func handleRotation () { if let view = self.presentingView, sview = self.superview { UIView.animateWithDuration(0.3, animations: { () -> Void in self.arrangeInSuperview(sview) self.setNeedsDisplay() }) } } /** NSCoding not supported. Use init(text, preferences, delegate) instead! */ required public init(coder aDecoder: NSCoder) { fatalError("NSCoding not supported. Use init(text, preferences, delegate) instead!") } // MARK:- Class functions - public class func showAnimated(animated : Bool, forView view : UIView, withinSuperview superview : UIView?, text : NSString, preferences: Preferences?, delegate : EasyTipViewDelegate?){ var ev = EasyTipView(text: text, preferences : preferences, delegate : delegate) ev.showForView(view, withinSuperview: superview, animated: animated) } public class func showAnimated(animated : Bool, forItem item : UIBarButtonItem, withinSuperview superview : UIView?, text : NSString, preferences: Preferences?, delegate : EasyTipViewDelegate?){ if let view = item.customView { self.showAnimated(animated, forView: view, withinSuperview: superview, text: text, preferences: preferences, delegate: delegate) }else{ if let view = item.valueForKey("view") as? UIView { self.showAnimated(animated, forView: view, withinSuperview: superview, text: text, preferences: preferences, delegate: delegate) } } } // MARK:- Instance methods - public func showForItem(item : UIBarButtonItem, withinSuperView sview : UIView?, animated : Bool) { if let view = item.customView { self.showForView(view, withinSuperview: sview, animated : animated) }else{ if let view = item.valueForKey("view") as? UIView { self.showForView(view, withinSuperview: sview, animated: animated) } } } public func showForView(view : UIView, withinSuperview sview : UIView?, animated : Bool) { if let v = sview { assert(view.hasSuperview(v), "The supplied superview <\(v)> is not a direct nor an indirect superview of the supplied reference view <\(view)>. The superview passed to this method should be a direct or an indirect superview of the reference view. To display the tooltip on the window, pass nil as the superview parameter.") } let superview = sview ?? UIApplication.sharedApplication().windows.last as! UIView self.presentingView = view self.arrangeInSuperview(superview) self.transform = CGAffineTransformMakeScale(0, 0) var tap = UITapGestureRecognizer(target: self, action: "handleTap") self.addGestureRecognizer(tap) superview.addSubview(self) if animated { UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.7, options: UIViewAnimationOptions.CurveEaseOut, animations: { () -> Void in self.transform = CGAffineTransformIdentity }, completion: nil) }else{ self.transform = CGAffineTransformIdentity } } private func arrangeInSuperview(superview : UIView) { let position = self.preferences.arrowPosition let refViewOrigin = self.presentingView!.originWithinDistantSuperView(superview) let refViewSize = self.presentingView!.frame.size let refViewCenter = CGPointMake(refViewOrigin.x + refViewSize.width / 2, refViewOrigin.y + refViewSize.height / 2) let xOrigin = refViewCenter.x - self.contentSize.width / 2 let yOrigin = position == .Bottom ? refViewOrigin.y - self.contentSize.height : refViewOrigin.y + refViewSize.height var frame = CGRectMake(xOrigin, yOrigin, self.contentSize.width, self.contentSize.height) if frame.origin.x < 0 { frame.origin.x = 0 } else if CGRectGetMaxX(frame) > CGRectGetWidth(superview.frame){ frame.origin.x = superview.frame.width - CGRectGetWidth(frame) } if position == .Top { if CGRectGetMaxY(frame) > CGRectGetHeight(superview.frame){ self.preferences.arrowPosition = .Bottom frame.origin.y = refViewOrigin.y - self.contentSize.height } }else{ if CGRectGetMinY(frame) < 0 { self.preferences.arrowPosition = .Top frame.origin.y = refViewOrigin.y + refViewSize.height } } var arrowTipXOrigin : CGFloat if CGRectGetWidth(frame) < refViewSize.width { arrowTipXOrigin = self.contentSize.width / 2 } else { arrowTipXOrigin = abs(frame.origin.x - refViewOrigin.x) + refViewSize.width / 2 } self.arrowTip = CGPointMake(arrowTipXOrigin, self.preferences.arrowPosition == .Top ? Constants.bubbleVInset : self.contentSize.height - Constants.bubbleVInset) self.frame = frame } public func dismissWithCompletion(completion : ((finished : Bool) -> Void)?){ UIView.animateWithDuration(0.2, animations: { () -> Void in self.transform = CGAffineTransformMakeScale(0.3, 0.3) self.alpha = 0 }) { (finished) -> Void in completion?(finished: finished) self.removeFromSuperview() } } // MARK:- Callbacks - public func handleTap () { self.dismissWithCompletion { (finished) -> Void in self.delegate?.easyTipViewDidDismiss(self) } } // MARK:- Drawing - override public func drawRect(rect: CGRect) { let bubbleWidth = self.contentSize.width - 2 * Constants.bubbleHInset let bubbleHeight = self.contentSize.height - 2 * Constants.bubbleVInset - Constants.arrowHeight let arrowPosition = self.preferences.arrowPosition let bubbleXOrigin = Constants.bubbleHInset let bubbleYOrigin = arrowPosition == .Bottom ? Constants.bubbleVInset : Constants.bubbleVInset + Constants.arrowHeight let context = UIGraphicsGetCurrentContext() CGContextSaveGState (context) var contourPath = CGPathCreateMutable() CGPathMoveToPoint(contourPath, nil, self.arrowTip.x, self.arrowTip.y) CGPathAddLineToPoint(contourPath, nil, self.arrowTip.x - Constants.arrowWidth / 2, self.arrowTip.y + (arrowPosition == .Bottom ? -1 : 1) * Constants.arrowHeight) if arrowPosition == .Top { CGPathAddArcToPoint(contourPath, nil, bubbleXOrigin, bubbleYOrigin, bubbleXOrigin, bubbleYOrigin + bubbleHeight, Constants.bubbleCornerRadius) CGPathAddArcToPoint(contourPath, nil, bubbleXOrigin, bubbleYOrigin + bubbleHeight, bubbleXOrigin + bubbleWidth, bubbleYOrigin + bubbleHeight, Constants.bubbleCornerRadius) CGPathAddArcToPoint(contourPath, nil, bubbleXOrigin + bubbleWidth, bubbleYOrigin + bubbleHeight, bubbleXOrigin + bubbleWidth, bubbleYOrigin, Constants.bubbleCornerRadius) CGPathAddArcToPoint(contourPath, nil, bubbleXOrigin + bubbleWidth, bubbleYOrigin, bubbleXOrigin, bubbleYOrigin, Constants.bubbleCornerRadius) } else { CGPathAddArcToPoint(contourPath, nil, bubbleXOrigin, bubbleYOrigin + bubbleHeight, bubbleXOrigin, bubbleYOrigin, Constants.bubbleCornerRadius) CGPathAddArcToPoint(contourPath, nil, bubbleXOrigin, bubbleYOrigin, bubbleXOrigin + bubbleWidth, bubbleYOrigin, Constants.bubbleCornerRadius) CGPathAddArcToPoint(contourPath, nil, bubbleXOrigin + bubbleWidth, bubbleYOrigin, bubbleXOrigin + bubbleWidth, bubbleYOrigin + bubbleHeight, Constants.bubbleCornerRadius) CGPathAddArcToPoint(contourPath, nil, bubbleXOrigin + bubbleWidth, bubbleYOrigin + bubbleHeight, bubbleXOrigin, bubbleYOrigin + bubbleHeight, Constants.bubbleCornerRadius) } CGPathAddLineToPoint(contourPath, nil, self.arrowTip.x + Constants.arrowWidth / 2, self.arrowTip.y + (arrowPosition == .Bottom ? -1 : 1) * Constants.arrowHeight) CGPathCloseSubpath(contourPath) CGContextAddPath(context, contourPath) CGContextClip(context) CGContextSetFillColorWithColor(context, self.preferences.bubbleColor.CGColor) CGContextFillRect(context, self.bounds) var paragraphStyle = NSMutableParagraphStyle() paragraphStyle.alignment = self.preferences.textAlignment paragraphStyle.lineBreakMode = NSLineBreakMode.ByWordWrapping var textRect = CGRectMake(bubbleXOrigin + (bubbleWidth - self.textSize.width) / 2, bubbleYOrigin + (bubbleHeight - self.textSize.height) / 2, textSize.width, textSize.height) self.text.drawInRect(textRect, withAttributes: [NSFontAttributeName : self.font, NSForegroundColorAttributeName : self.preferences.textColor, NSParagraphStyleAttributeName : paragraphStyle]) CGContextRestoreGState(context) } } // MARK:- UIView extension - private extension UIView { func originWithinDistantSuperView (superview : UIView?) -> CGPoint { if self.superview != nil { return viewOriginInSuperview(self.superview!, subviewOrigin: self.frame.origin, refSuperview : superview) }else{ return self.frame.origin } } func hasSuperview (superview : UIView) -> Bool{ return viewHasSuperview(self, superview: superview) } func viewHasSuperview (view : UIView, superview : UIView) -> Bool { if let sview = view.superview { if sview === superview { return true }else{ return viewHasSuperview(sview, superview: superview) } }else{ return false } } func viewOriginInSuperview(sview : UIView, subviewOrigin sorigin: CGPoint, refSuperview : UIView?) -> CGPoint { if let superview = sview.superview { if let ref = refSuperview { if sview === ref { return sorigin }else{ return viewOriginInSuperview(superview, subviewOrigin: CGPointMake(sview.frame.origin.x + sorigin.x, sview.frame.origin.y + sorigin.y), refSuperview: ref) } }else{ return viewOriginInSuperview(superview, subviewOrigin: CGPointMake(sview.frame.origin.x + sorigin.x, sview.frame.origin.y + sorigin.y), refSuperview: nil) } }else{ return CGPointMake(sview.frame.origin.x + sorigin.x, sview.frame.origin.y + sorigin.y) } } }
mit
e2cf3aec823c40d6f6bc4e0089e5c3de
40.157767
335
0.63016
5.535749
false
false
false
false
overtake/TelegramSwift
packages/TGUIKit/Sources/ProgressModal.swift
1
13532
// // ProgressModal.swift // TGUIKit // // Created by keepcoder on 09/11/2016. // Copyright © 2016 Telegram. All rights reserved. // import Cocoa import SwiftSignalKit import AppKit import ColorPalette private final class ProgressModalView : NSVisualEffectView { private let progressView = ProgressIndicator(frame: NSMakeRect(0, 0, 32, 32)) override init(frame frameRect: NSRect) { super.init(frame: frameRect) self.wantsLayer = true self.layer?.cornerRadius = 10.0 self.autoresizingMask = [] self.autoresizesSubviews = false self.addSubview(self.progressView) self.material = presentation.colors.isDark ? .dark : .light self.blendingMode = .withinWindow self.state = .active } override func setFrameSize(_ newSize: NSSize) { super.setFrameSize(NSMakeSize(80, 80)) } required init?(coder decoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layout() { super.layout() self.progressView.center() self.center() } } class ProgressModalController: ModalViewController { private var progressView:ProgressIndicator? override var background: NSColor { return .clear } override var contentBelowBackground: Bool { return true } override func becomeFirstResponder() -> Bool? { return nil } override func close(animationType: ModalAnimationCloseBehaviour = .common) { super.close(animationType: animationType) disposable.dispose() } override var containerBackground: NSColor { return .clear } override func viewClass() -> AnyClass { return ProgressModalView.self } override func viewDidResized(_ size: NSSize) { super.viewDidResized(size) } override func viewDidLoad() { super.viewDidLoad() readyOnce() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } deinit { disposable.dispose() } fileprivate let disposable: Disposable init(_ disposable: Disposable) { self.disposable = disposable super.init(frame:NSMakeRect(0,0,80,80)) self.bar = .init(height: 0) } } private final class SuccessModalView : NSVisualEffectView { private let imageView:ImageView = ImageView() private let textView: TextView = TextView() required override init(frame frameRect: NSRect) { super.init(frame: frameRect) addSubview(textView) addSubview(imageView) self.wantsLayer = true self.layer?.cornerRadius = 10.0 self.autoresizingMask = [] self.autoresizesSubviews = false self.material = presentation.colors.isDark ? .dark : .light self.blendingMode = .withinWindow } override func layout() { super.layout() if !textView.isHidden { imageView.centerY(x: 20) textView.centerY(x: imageView.frame.maxX + 20) } else { imageView.center() } } required public init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func updateIcon(icon: CGImage, text: TextViewLayout?) { imageView.image = icon imageView.sizeToFit() textView.isSelectable = false textView.isHidden = text == nil textView.update(text) needsLayout = true } } class SuccessModalController : ModalViewController { override var background: NSColor { return .clear } override var contentBelowBackground: Bool { return true } override var containerBackground: NSColor { return .clear } override func viewClass() -> AnyClass { return SuccessModalView.self } private var genericView: SuccessModalView { return self.view as! SuccessModalView } override var redirectMouseAfterClosing: Bool { return true } override func viewDidResized(_ size: NSSize) { super.viewDidResized(size) } override func viewDidLoad() { super.viewDidLoad() genericView.updateIcon(icon: icon, text: text) readyOnce() } // override var handleEvents: Bool { // return false // } // override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } private let icon: CGImage private let text: TextViewLayout? private let _backgroundColor: NSColor init(_ icon: CGImage, text: TextViewLayout? = nil, background: NSColor) { self.icon = icon self.text = text self._backgroundColor = background super.init(frame:NSMakeRect(0, 0, text != nil ? 100 + text!.layoutSize.width : 80, text != nil ? max(icon.backingSize.height + 20, text!.layoutSize.height + 20) : 80)) self.bar = .init(height: 0) } } public func showModalProgress<T, E>(signal:Signal<T,E>, for window:Window, disposeAfterComplete: Bool = true) -> Signal<T,E> { return Signal { subscriber in var signal = signal |> deliverOnMainQueue let beforeDisposable:DisposableSet = DisposableSet() let modal = ProgressModalController(beforeDisposable) let beforeModal:Signal<Void,Void> = .single(Void()) |> delay(0.25, queue: Queue.mainQueue()) beforeDisposable.add(beforeModal.start(completed: { showModal(with: modal, for: window, animationType: .scaleCenter) })) signal = signal |> afterDisposed { modal.close() } beforeDisposable.add(signal.start(next: { next in subscriber.putNext(next) }, error: { error in subscriber.putError(error) if disposeAfterComplete { beforeDisposable.dispose() } modal.close() }, completed: { subscriber.putCompletion() if disposeAfterComplete { beforeDisposable.dispose() } modal.close() })) return beforeDisposable } } public func showModalSuccess(for window: Window, icon: CGImage, text: TextViewLayout? = nil, background: NSColor = presentation.colors.background, delay _delay: Double) -> Signal<Void, NoError> { let modal = SuccessModalController(icon, text: text, background: background) showModal(with: modal, for: window, animationType: .scaleCenter) return Signal<Void, NoError>({ [weak modal] _ -> Disposable in return ActionDisposable { modal?.close() } }) |> timeout(_delay, queue: Queue.mainQueue(), alternate: Signal<Void, NoError>({ [weak modal] _ -> Disposable in modal?.close() return EmptyDisposable })) } private final class TextAndLabelModalView : View { private let textView: TextView = TextView() private var titleView: TextView? private let visualEffectView = NSVisualEffectView(frame: NSZeroRect) required init(frame frameRect: NSRect) { super.init(frame: frameRect) self.visualEffectView.material = .ultraDark self.visualEffectView.blendingMode = .withinWindow self.visualEffectView.state = .active self.visualEffectView.wantsLayer = true addSubview(self.visualEffectView) //self.backgroundColor = NSColor.black.withAlphaComponent(0.9) self.textView.disableBackgroundDrawing = true self.textView.isSelectable = false self.textView.userInteractionEnabled = true addSubview(self.textView) layer?.cornerRadius = .cornerRadius } required public init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func update(text: String, title: String?, callback: ((String)->Void)?, maxSize: NSSize) -> NSSize { if let title = title { self.titleView = TextView() addSubview(self.titleView!) self.titleView?.disableBackgroundDrawing = true self.titleView?.isSelectable = false self.titleView?.userInteractionEnabled = false let titleLayout = TextViewLayout(.initialize(string: title, color: .white, font: .medium(.title)), maximumNumberOfLines: 1) titleLayout.measure(width: min(400, maxSize.width - 80)) self.titleView?.update(titleLayout) } let attr = parseMarkdownIntoAttributedString(text, attributes: MarkdownAttributes(body: MarkdownAttributeSet(font: .normal(.text), textColor: .white), bold: MarkdownAttributeSet(font: .bold(.text), textColor: .white), link: MarkdownAttributeSet(font: .normal(.title), textColor: nightAccentPalette.link), linkAttribute: { contents in return (NSAttributedString.Key.link.rawValue, contents) })) let textLayout = TextViewLayout(attr) textLayout.interactions = .init(processURL: { contents in if let string = contents as? String { callback?(string) } }) textLayout.measure(width: min(400, maxSize.width - 80)) self.textView.update(textLayout) var size: NSSize = .zero if let titleView = self.titleView { size.width = max(textView.frame.width, titleView.frame.width) + 20 size.height = textView.frame.height + titleView.frame.height + 5 + 20 } else { size.width = textView.frame.width + 20 size.height = textView.frame.height + 20 } return size } override func layout() { super.layout() visualEffectView.frame = bounds if let titleView = titleView { titleView.setFrameOrigin(NSMakePoint(10, 10)) textView.setFrameOrigin(NSMakePoint(10, titleView.frame.maxY + 5)) } else { textView.center() } } } class TextAndLabelModalController: ModalViewController { override var background: NSColor { return .clear } override var redirectMouseAfterClosing: Bool { return true } override func becomeFirstResponder() -> Bool? { return nil } override var contentBelowBackground: Bool { return true } override var containerBackground: NSColor { return .clear } override func viewClass() -> AnyClass { return TextAndLabelModalView.self } override func viewDidResized(_ size: NSSize) { super.viewDidResized(size) } private var genericView: TextAndLabelModalView { return self.view as! TextAndLabelModalView } override func viewDidLoad() { super.viewDidLoad() let size = self.genericView.update(text: text, title: title, callback: self.callback, maxSize: windowSize) self.modal?.resize(with: size, animated: false) readyOnce() } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } override var responderPriority: HandlerPriority { return .modal } override var redirectUserInterfaceCalls: Bool { return true } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) } override var canBecomeResponder: Bool { return false } override func firstResponder() -> NSResponder? { return nil } deinit { } private let text: String private let title: String? private let windowSize: NSSize private let callback:((String)->Void)? init(text: String, title: String?, callback:((String)->Void)?, windowSize: NSSize) { self.text = text self.windowSize = windowSize self.title = title self.callback = callback super.init(frame:NSMakeRect(0, 0, 80, 80)) self.bar = .init(height: 0) } } public func showModalText(for window: Window, text: String, title: String? = nil, callback:((String)->Void)? = nil) { let modal = TextAndLabelModalController(text: text, title: title, callback: callback, windowSize: window.frame.size) showModal(with: modal, for: window, animationType: .scaleCenter) let words = (text + " " + (title ?? "")).trimmingCharacters(in: CharacterSet.alphanumerics.inverted) let msPerChar: TimeInterval = 60 / 180 / 6 let showTime = max(min(msPerChar * TimeInterval(words.length), 10), 3.5) let signal = Signal<Void, NoError>({ _ -> Disposable in return ActionDisposable { } }) |> timeout(showTime, queue: Queue.mainQueue(), alternate: Signal<Void, NoError>({ [weak modal] _ -> Disposable in modal?.close() return EmptyDisposable })) _ = signal.start() }
gpl-2.0
fad1dc492657af8cabaa5c0f88af0f15
27.974304
341
0.623162
4.860273
false
false
false
false