repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
zwaldowski/URLGrey
URLGrey/Data.swift
1
10464
// // Data.swift // URLGrey // // Created by Zachary Waldowski on 2/7/15. // Copyright © 2014-2015. Some rights reserved. // import Dispatch /// A read-only construct that conceptually models a buffer of numeric units. public struct Data<T: UnsignedIntegerType> { /// The `dispatch_data_t` byte buffer representation. public let data: dispatch_data_t init(unsafe data: dispatch_data_t) { self.data = data } init(safe data: dispatch_data_t, @noescape withPartialData: Data<UInt8> throws -> ()) rethrows { let size = dispatch_data_get_size(data) let remainder = size % sizeof(T) if remainder == 0 { self.init(unsafe: data) } else { let wholeData = dispatch_data_create_subrange(data, 0, size - remainder) let partialData = dispatch_data_create_subrange(data, size - remainder, remainder) let partial = Data<UInt8>(unsafe: partialData) try withPartialData(partial) self.init(unsafe: wholeData) } } /// Create an empty data. public init() { self.init(unsafe: dispatch_data_empty) } /// Create data from `dispatch_data_t`. If the bytes cannot be represented /// by a whole number of elements, the given buffer will be replaced /// with the leftover amount. Any partial data will be combined with the /// given data. public init(_ data: dispatch_data_t, inout partial: Data<UInt8>) { let combined = dispatch_data_create_concat(partial.data, data) try! self.init(safe: combined) { data in partial = data } } /// Create data from `dispatch_data_t`. If the bytes cannot be represented /// by a whole number of elements, the initializer will throw. public init(_ data: dispatch_data_t) throws { try self.init(safe: data) { _ in throw IOError.PartialData } } } // MARK: Internal extension Data { static func toBytes(i: Int) -> Int { return i / sizeof(T) } static func fromBytes(i: Int) -> Int { return i * sizeof(T) } private typealias Bytes = UnsafeBufferPointer<UInt8> private var startByte: Int { return 0 } private var endByte: Int { return dispatch_data_get_size(data) } private func apply(function: (data: dispatch_data_t, range: HalfOpenInterval<Int>, buffer: Bytes) -> Bool) { dispatch_data_apply(data) { (data, offset, ptr, count) -> Bool in let buffer = Bytes(start: UnsafePointer(ptr), count: count) return function(data: data, range: offset..<offset+count, buffer: buffer) } } private func byteRangeForIndex(i: Int) -> HalfOpenInterval<Int> { let byteStart = Data.fromBytes(i) let byteEnd = byteStart + sizeof(T) return byteStart ..< byteEnd } } // MARK: Collection conformances extension Data: SequenceType { /// A collection view representing the underlying contiguous byte buffers /// making up the data. Enumerating through this collection is useful /// for feeding an iterative API, such as crypto routines. public var byteRegions: DataRegions { return DataRegions(data: data) } /// Return a *generator* over the `T`s that comprise this *data*. public func generate() -> DataGenerator<T> { return DataGenerator(regions: byteRegions.generate()) } } extension Data: Indexable { /// The position of the first element in the data. /// /// In empty data, `startIndex == endIndex`. public var startIndex: Int { return Data.toBytes(startByte) } /// The data's "past the end" position. /// /// `endIndex` is not a valid argument to `subscript`, and is always /// reachable from `startIndex` by zero or more applications of /// `successor()`. public var endIndex: Int { return Data.toBytes(endByte) } /// This subscript is not performance-friendly, and will always underperform /// enumeration of the `Data` or application accross its `byteRegions`. public subscript(i: Int) -> T { let byteRange = byteRangeForIndex(i) assert(byteRange.end < endByte, "Data index out of range") var ret = T.allZeros withUnsafeMutablePointer(&ret) { retPtrIn -> () in var retPtr = UnsafeMutablePointer<UInt8>(retPtrIn) apply { (_, chunkRange, buffer) -> Bool in let copyRange = chunkRange.clamp(byteRange) if !copyRange.isEmpty { let size = copyRange.end - copyRange.start memmove(retPtr, buffer.baseAddress + copyRange.start, size) retPtr += size } return chunkRange.end < byteRange.end } } return ret } } extension Data: CollectionType { public subscript (bounds: Range<Int>) -> Data<T> { let offset = Data.toBytes(bounds.startIndex) let length = Data.toBytes(bounds.endIndex - bounds.startIndex) return Data(unsafe: dispatch_data_create_subrange(data, offset, length)) } } // MARK: Concatenation extension Data { /// Combine the recieving data with the given data in constant time. public mutating func extend(newData: Data<T>) { self += newData } } /// Combine `lhs` and `rhs` into a new buffer in constant time. public func +<T: UnsignedIntegerType>(lhs: Data<T>, rhs: Data<T>) -> Data<T> { return Data(unsafe: dispatch_data_create_concat(lhs.data, rhs.data)) } /// Operator form of `Data<T>.extend`. public func +=<T: UnsignedIntegerType>(inout lhs: Data<T>, rhs: Data<T>) { lhs = lhs + rhs } // MARK: Mapped access extension Data { /// Call `body(p)`, where `p` is a pointer to the data represented as /// contiguous storage. If the data is non-contiguous, this will trigger /// a copy of all buffers. public func withUnsafeBufferPointer<R>(@noescape body: UnsafeBufferPointer<T> -> R) -> R { var ptr: UnsafePointer<Void> = nil var byteCount = 0 let map = dispatch_data_create_map(data, &ptr, &byteCount) let count = Data.fromBytes(byteCount) return withExtendedLifetime(map) { let buffer = UnsafeBufferPointer<T>(start: UnsafePointer(ptr), count: count) return body(buffer) } } } // MARK: Generators /// The `SequenceType` returned by `Data.byteBuffers`. `DataRegions` /// is a sequence of byte buffers, represented in Swift as /// `UnsafeBufferPointer<UInt8>`. public struct DataRegions: SequenceType { private let data: dispatch_data_t private init(data: dispatch_data_t) { self.data = data } /// Start enumeration of byte buffers. public func generate() -> DataRegionsGenerator { return DataRegionsGenerator(data: data) } } /// A generator over the underlying contiguous storage of a `Data<T>`. public struct DataRegionsGenerator: GeneratorType, SequenceType { private let data: dispatch_data_t private var region = dispatch_data_empty private var nextByteOffset = 0 private init(data: dispatch_data_t) { self.data = data } /// Advance to the next buffer and return it, or `nil` if no more buffers /// exist. /// /// - Requires: No preceding call to `self.next()` has returned `nil`. public mutating func next() -> UnsafeBufferPointer<UInt8>? { if nextByteOffset >= dispatch_data_get_size(data) { return nil } let nextRegion = dispatch_data_copy_region(data, nextByteOffset, &nextByteOffset) // This won't remap the buffer because the region will be a leaf, // so it just returns the buffer var mapPtr = UnsafePointer<Void>() var mapSize = 0 region = dispatch_data_create_map(nextRegion, &mapPtr, &mapSize) nextByteOffset += mapSize return UnsafeBufferPointer(start: UnsafePointer(mapPtr), count: mapSize) } /// Restart enumeration of byte buffers. public func generate() -> DataRegionsGenerator { return DataRegionsGenerator(data: data) } } public struct DataGenerator<T: UnsignedIntegerType>: GeneratorType, SequenceType { private var regions: DataRegionsGenerator private var buffer: UnsafeBufferPointerGenerator<UInt8>? private init(regions: DataRegionsGenerator) { self.regions = regions } private mutating func nextByte() -> UInt8? { // continue through existing region if let next = buffer?.next() { return next } // get next region guard let nextRegion = regions.next() else { return nil } // start generating var nextBuffer = nextRegion.generate() guard let byte = nextBuffer.next() else { buffer = nil return nil } buffer = nextBuffer return byte } /// Advance to the next element and return it, or `nil` if no next /// element exists. /// /// - Requires: No preceding call to `self.next()` has returned `nil`. public mutating func next() -> T? { return (0 ..< sizeof(T)).reduce(T.allZeros) { (current, byteIdx) -> T? in guard let current = current, byte = nextByte() else { return nil } return current | numericCast(byte << UInt8(byteIdx * 8)) } } /// Restart enumeration of the data. public func generate() -> DataGenerator<T> { return DataGenerator(regions: regions.generate()) } } // MARK: Introspection extension Data: CustomStringConvertible { /// A textual representation of `self`. public var description: String { return data.description } } extension Data: CustomReflectable { /// Return the `Mirror` for `self`. public func customMirror() -> Mirror { // Appears as an array of the integer type, as suggested in the docs // for Mirror.init(_:unlabeledChildren:displayStyle:ancestorRepresentation:). // An improved version might show regions and/or segmented hex values. return Mirror(self, unlabeledChildren: self, displayStyle: .Collection) } }
mit
9746701057fa4081cbf9cd6db2c42460
30.42042
112
0.618369
4.359583
false
false
false
false
madeatsampa/MacMagazine-iOS
MacMagazine/FetchedResultsControllerDataSource.swift
1
11559
// // FetchedResultsControllerDataSource.swift // MacMagazine // // Created by Cassio Rossi on 04/03/2019. // Copyright © 2019 MacMagazine. All rights reserved. // import CoreData import UIKit protocol FetchedResultsControllerDelegate: AnyObject { func willDisplayCell(indexPath: IndexPath) func didSelectRowAt(indexPath: IndexPath) func configure(cell: PostCell, atIndexPath: IndexPath) func scrollViewDidScroll(_ scrollView: UIScrollView) func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) } extension FetchedResultsControllerDelegate { func willDisplayCell(indexPath: IndexPath) {} func didSelectRowAt(indexPath: IndexPath) {} } class FetchedResultsControllerDataSource: NSObject, UITableViewDataSource, UITableViewDelegate, NSFetchedResultsControllerDelegate { // MARK: - Properties - weak var delegate: FetchedResultsControllerDelegate? fileprivate var tableView: UITableView? fileprivate let managedObjectContext = CoreDataStack.shared.viewContext fileprivate var groupedBy: String? public let fetchRequest: NSFetchRequest<Post> = Post.fetchRequest() fileprivate lazy var fetchedResultsController: NSFetchedResultsController = { () -> NSFetchedResultsController<Post> in // Initialize Fetched Results Controller let controller = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedObjectContext, sectionNameKeyPath: nil, cacheName: nil) return controller }() // MARK: - Initialization methods - init(podcast tableView: UITableView) { super.init() setup(tableView: tableView) self.tableView?.register(UINib(nibName: "PodcastCell", bundle: nil), forCellReuseIdentifier: "podcastCell") } init(post tableView: UITableView, group: String?) { super.init() self.groupedBy = group setup(tableView: tableView) self.tableView?.register(UINib(nibName: "HeaderCell", bundle: nil), forHeaderFooterViewReuseIdentifier: "headerCell") self.tableView?.register(UINib(nibName: "NormalCell", bundle: nil), forCellReuseIdentifier: "normalCell") self.tableView?.register(UINib(nibName: "FeaturedCell", bundle: nil), forCellReuseIdentifier: "featuredCell") } func setup(tableView: UITableView) { self.tableView = tableView self.tableView?.dataSource = self self.tableView?.delegate = self } // MARK: - Scroll detection - func scrollViewDidScroll(_ scrollView: UIScrollView) { delegate?.scrollViewDidScroll(scrollView) } func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { delegate?.scrollViewDidEndDragging(scrollView, willDecelerate: decelerate) } // MARK: - TableView methods - func numberOfSections(in tableView: UITableView) -> Int { let numSections = sections() let favorite = fetchRequest.predicate?.predicateFormat.contains("favorite") ?? false let category = fetchRequest.predicate?.predicateFormat.contains("categorias") ?? false if (numSections == 0 || rows(in: 0) == 0) && (favorite || category) { let message = favorite ? "Você ainda não favoritou nenhum \(self.groupedBy == nil ? "podcast" : "post")." : "Nenhum resultado encontrado." tableView.backgroundView = Settings().createLabel(message: message, size: tableView.bounds.size) tableView.separatorStyle = .none } else { tableView.backgroundView = nil tableView.separatorStyle = hasMoreThanOneLine() ? .singleLine : .none } return numSections } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { guard let sections = fetchedResultsController.sections, let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: "headerCell") as? HeaderCell else { return nil } let currentSection = sections[section] // Expected date format: "20190227" header.setHeader(currentSection.name.isEmpty ? nil : currentSection.name.toHeaderDate(with: "yyyyMMdd")) return header } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return rows(in: section) } func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? { let object = self.fetchedResultsController.object(at: indexPath) let read = UIContextualAction(style: .normal, title: (object.read ? "Não\nLido" : "Lido")) { _, _, boolValue in let object = self.fetchedResultsController.object(at: indexPath) CoreDataStack.shared.get(link: object.link ?? "") { (items: [Post]) in if !items.isEmpty { items[0].read = !items[0].read CoreDataStack.shared.save() object.read = items[0].read boolValue(true) } } } let favoritar = UIContextualAction(style: .normal, title: "Favorito") { _, _, boolValue in let object = self.fetchedResultsController.object(at: indexPath) Favorite().updatePostStatus(using: object.link ?? "") { isFavoriteOn in object.favorite = isFavoriteOn NotificationCenter.default.post(name: .favoriteUpdated, object: object) boolValue(true) } } favoritar.image = UIImage(systemName: "star\(object.favorite ? "" : ".fill")") favoritar.backgroundColor = UIColor(named: "MMBlue") ?? .systemBlue favoritar.accessibilityLabel = "Favorito" read.image = UIImage(systemName: "bubble.left\(object.read ? "" : ".fill")") read.backgroundColor = UIColor.systemOrange read.accessibilityLabel = object.read ? "Desmarcar como Lido" : "Marcar como Lido" var buttons = [favoritar] if Settings().transparency < 1 { buttons = [read, favoritar] } let swipeActions = UISwipeActionsConfiguration(actions: buttons) swipeActions.performsFirstActionWithFullSwipe = true return swipeActions } func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? { let compatilhar = UIContextualAction(style: .normal, title: "Compartilhar") { _, _, boolValue in let post = self.fetchedResultsController.object(at: indexPath) guard let link = post.link, let url = URL(string: link) else { boolValue(true) return } let cell = self.tableView?.cellForRow(at: indexPath) let items: [Any] = [post.title ?? "", url] Share().present(at: cell, using: items) boolValue(true) } compatilhar.backgroundColor = UIColor.systemGreen compatilhar.image = UIImage(systemName: "square.and.arrow.up") compatilhar.accessibilityLabel = "Compartilhar" let swipeActions = UISwipeActionsConfiguration(actions: [compatilhar]) swipeActions.performsFirstActionWithFullSwipe = true return swipeActions } func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { delegate?.willDisplayCell(indexPath: indexPath) } internal func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let contentSize: UIContentSizeCategory = UIApplication.shared.preferredContentSizeCategory var identifier = "normalCell" let object = fetchedResultsController.object(at: indexPath) if object.categorias?.contains("Destaques") ?? false || contentSize > .extraExtraExtraLarge { identifier = "featuredCell" } if !(object.podcast?.isEmpty ?? true) && (delegate as? PodcastMasterViewController) != nil { identifier = "podcastCell" } guard let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath) as? PostCell else { fatalError("Unexpected Index Path") } delegate?.configure(cell: cell, atIndexPath: indexPath) return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { delegate?.didSelectRowAt(indexPath: indexPath) } // MARK: - FetchController Delegate methods - func reloadData() { // Execute the fetch to display the data do { fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: managedObjectContext, sectionNameKeyPath: groupedBy, cacheName: nil) fetchedResultsController.delegate = self try fetchedResultsController.performFetch() } catch { logE("An error occurred") } } func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { tableView?.beginUpdates() } func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange sectionInfo: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) { switch type { case .insert: tableView?.insertSections(IndexSet(integer: sectionIndex), with: .fade) case .delete: tableView?.deleteSections(IndexSet(integer: sectionIndex), with: .fade) default: return } } func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) { switch type { case .update: if let indexPath = indexPath { if let cell = tableView?.cellForRow(at: indexPath) as? PostCell { delegate?.configure(cell: cell, atIndexPath: indexPath) } } case .insert: if let indexPath = newIndexPath { tableView?.insertRows(at: [indexPath], with: .fade) } case .delete: if let indexPath = indexPath { tableView?.deleteRows(at: [indexPath], with: .fade) } case .move: if let indexPath = indexPath { tableView?.deleteRows(at: [indexPath], with: .fade) } if let newIndexPath = newIndexPath { tableView?.insertRows(at: [newIndexPath], with: .fade) } @unknown default: break } } func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { tableView?.endUpdates() } // MARK: - func hasData() -> Bool { return !(fetchedResultsController.fetchedObjects?.isEmpty ?? true) } func hasMoreThanOneLine() -> Bool { return (fetchedResultsController.fetchedObjects?.count ?? 0 > 1) } func sections() -> Int { guard let sections = self.fetchedResultsController.sections else { return 0 } return sections.count } func rows(in section: Int) -> Int { guard let sections = self.fetchedResultsController.sections else { return 0 } let sectionInfo = sections[section] return sectionInfo.numberOfObjects } func object(at indexPath: IndexPath) -> Post? { return fetchedResultsController.object(at: indexPath) } func object(with link: String) -> Post? { guard let posts = fetchedResultsController.fetchedObjects else { return nil } let filteredPosts = posts.filter { $0.link == link } return filteredPosts.isEmpty ? nil : filteredPosts[0] } func links() -> [PostData] { guard let posts = fetchedResultsController.fetchedObjects else { return [] } var response = [PostData]() for post in posts { response.append(PostData(title: post.title, link: post.link, thumbnail: post.artworkURL, favorito: post.favorite, postId: post.postId, shortURL: post.shortURL)) } return response } func indexPath(for object: Post) -> IndexPath { return fetchedResultsController.indexPath(forObject: object) ?? IndexPath(row: 0, section: 0) } }
mit
c559c7fc973d1bffe9b4f150c69c2b70
33.6997
206
0.717265
4.47348
false
false
false
false
SBGMobile/Charts
Source/Charts/Charts/PieChartInnerPercentageView.swift
1
1395
// // PieChartInnerPercentageView.swift // Charts // // Created by Peter-John Welcome on 2016/11/08. // // import Foundation import CoreGraphics #if !os(OSX) import UIKit #endif open class PieChartInnerPercentageView : PieChartView { fileprivate var _innerCirclePercentage: Double? = 0.0 fileprivate var _postiveColor : UIColor? = .green fileprivate var _negativeColor : UIColor? = .red public override init(frame: CGRect) { super.init(frame: frame) } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } open override func initialize() { super.initialize() renderer = PieChartInnerPercentageCircleRenderer(self, _animator, _viewPortHandler) _xAxis = nil self.highlighter = PieHighlighter(chart: self) } public var innerCirclePercentage : Double { get{ return _innerCirclePercentage! } set{ _innerCirclePercentage = newValue } } public var postiveColor : UIColor { get{ return _postiveColor! } set{ _postiveColor = newValue } } public var negativeColor : UIColor { get{ return _negativeColor! } set{ _negativeColor = newValue } } }
apache-2.0
ed5dc7ce3b013ac45def648dd8ca2615
19.820896
91
0.579211
4.57377
false
false
false
false
jackywpy/AudioKit
Tests/Tests/AKResonantFilter.swift
11
1862
// // main.swift // AudioKit // // Created by Nick Arner and Aurelius Prochazka on 12/26/14. // Copyright (c) 2014 Aurelius Prochazka. All rights reserved. // import Foundation let testDuration: NSTimeInterval = 10.0 class Instrument : AKInstrument { var auxilliaryOutput = AKAudio() override init() { super.init() let source = AKFMOscillator() auxilliaryOutput = AKAudio.globalParameter() assignOutput(auxilliaryOutput, to:source) } } class Processor : AKInstrument { init(audioSource: AKAudio) { super.init() let centerFrequency = AKLine( firstPoint: 220.ak, secondPoint: 3000.ak, durationBetweenPoints: testDuration.ak ) let bandwidth = AKLine( firstPoint: 10.ak, secondPoint: 100.ak, durationBetweenPoints: testDuration.ak ) let resonantFilter = AKResonantFilter(input: audioSource) resonantFilter.centerFrequency = centerFrequency resonantFilter.bandwidth = bandwidth let balance = AKBalance(input: resonantFilter, comparatorAudioSource: audioSource) setAudioOutput(balance) enableParameterLog( "Center Frequency = ", parameter: resonantFilter.centerFrequency, timeInterval:0.2 ) enableParameterLog( "Bandwidth = ", parameter: resonantFilter.bandwidth, timeInterval:0.2 ) resetParameter(audioSource) } } AKOrchestra.testForDuration(testDuration) let instrument = Instrument() let processor = Processor(audioSource: instrument.auxilliaryOutput) AKOrchestra.addInstrument(instrument) AKOrchestra.addInstrument(processor) processor.play() instrument.play() NSThread.sleepForTimeInterval(NSTimeInterval(testDuration))
mit
437b263d529017b29b21792365d587ee
23.5
90
0.658969
5.172222
false
true
false
false
sabiland/TrippyBackgrounds
TBPreview/SabilandTBPreview/SabilandTBPreview/SabilandTB.swift
1
27638
/* Copyright (c) 2015 Marko Sabotin Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import UIKit import SpriteKit private let FactorLinesStepperMin:CGFloat = 40.0 private let FactorLinesStepperMax:CGFloat = 80.0 private let FactorLinesAnglesMin:Int = 100 private let FactorLinesAnglesMax:Int = 150 private let FactorShadowSettingMax:CGFloat = 5.0 private let FactorLineWidthMax:CGFloat = 10.0 private let FactorInsidersOverlays:Int = 7 private let FactorBlackHoleMin:Int = 10 private let FactorBlackHoleMax:Int = 30 private let FactorMaxPossibleblackHoleOffsetForTranslate:CGFloat = 5.0 private let FactorBlackHoleMin2:Int = 20 private let FactorBlackHoleMax2:Int = 40 extension Array { mutating func shuffle() { if self.isEmpty { return } for index in 0..<self.count { let newIndex = Int(arc4random_uniform(UInt32(self.count-index))) + index if index != newIndex { // Check if you are not trying to swap an element with itself swap(&self[index], &self[newIndex]) } } } } class Helper:NSObject { class func random01CGFloat() -> CGFloat { return CGFloat(Float(arc4random()) / Float(UINT32_MAX)) } class func fiftyFifty() -> Bool { return random01CGFloat() > 0.5 } class func getRandomColor(alpha:CGFloat = 1.0) -> UIColor { return UIColor(red: Helper.random01CGFloat(), green: Helper.random01CGFloat(), blue: Helper.random01CGFloat(), alpha: alpha) } private class func randomBetweenMinMax(min:UInt32, max:UInt32) -> Int { var r:Int = Int(min + (arc4random() % (max - min))) if r < Int(min) { r = Int(min) } else if r > Int(max) { r = Int(max) } return r; } class func randomBetween(min: Int, var max: Int, includeMax:Bool = false) -> Int { // NOTE: !!! SPECIAL CASE, THIS MUST BE THIS WAY - SO SELECTING RANDOM NUMBER OF 1-LENGTH ARRAY WOULD WORK! if min == max { return min } if max <= min { max = min + 1 } if includeMax { max += 1 } return randomBetweenMinMax(UInt32(min), max: UInt32(max)) } class func fiftyFiftyOnePlusMinus() -> CGFloat { let r = random01CGFloat() if r > 0.5 { return (random01CGFloat() > 0.5 ? 1.0 : -1.0) } else { return (random01CGFloat() > 0.5 ? -1.0 : 1.0) } } } class SabilandTB: NSObject { var BackDimensionMax:CGFloat! var BackRect:CGRect! var SabilandTrippyBackground:UIImage! init(width:CGFloat, height:CGFloat) { super.init() precondition(width >= 1.0 && height >= 1.0, "WIDTH and HEIGHT must be >= 1.0") BackDimensionMax = max(width, height) BackRect = CGRectMake(0.0, 0.0, BackDimensionMax, BackDimensionMax) setupBackground() } private func getDynamicAlphaSetting() -> CGFloat { return 0.1 + (Helper.random01CGFloat() * 0.3) } private func getDynamicRandomColor() -> UIColor { return Helper.getRandomColor(getDynamicAlphaSetting()) } // NOTE: Harder alpha private func setRandomStroke2(ctx:CGContextRef) { Helper.getRandomColor(0.4 + (Helper.random01CGFloat() * 0.5)).setStroke() if Helper.fiftyFifty() { setRandomShadow(ctx) } } private func setRandomStroke(ctx:CGContextRef) { getDynamicRandomColor().setStroke() if Helper.fiftyFifty() { setRandomShadow(ctx) } } private func setRandomFill(ctx:CGContextRef) { getDynamicRandomColor().setFill() if Helper.fiftyFifty() { setRandomShadow(ctx) } } // NOTE: Lighter alpha private func setRandomFillLighter(ctx:CGContextRef) { Helper.getRandomColor(0.1 + (Helper.random01CGFloat() * 0.2)).setFill() if Helper.fiftyFifty() { setRandomShadow(ctx) } } // NOTE: Harder alpha private func setRandomFill2(ctx:CGContextRef) { Helper.getRandomColor(0.4 + (Helper.random01CGFloat() * 0.5)).setFill() if Helper.fiftyFifty() { setRandomShadow(ctx) } } private func setRandomLineWidth(ctx:CGContextRef) { CGContextSetLineWidth(ctx, 1.0 + (Helper.random01CGFloat() * FactorLineWidthMax)) } private func setRandomShadow(ctx:CGContextRef) { CGContextSetShadow(ctx, CGSizeMake(Helper.random01CGFloat() * FactorShadowSettingMax, Helper.random01CGFloat() * FactorShadowSettingMax), Helper.random01CGFloat() * FactorShadowSettingMax) } // NOTE: First layer private func drawFirstLayer(ctx:CGContextRef) { let step:CGFloat = BackDimensionMax / CGFloat(Helper.randomBetween(Int(FactorLinesStepperMin), max: Int(FactorLinesStepperMax), includeMax: false)) setRandomStroke2(ctx) setRandomLineWidth(ctx) for var i = BackRect.minX; i <= BackRect.maxX; i += step { CGContextMoveToPoint(ctx, i, BackRect.minY) CGContextAddLineToPoint(ctx, i, BackRect.maxY) } CGContextStrokePath(ctx) setRandomStroke2(ctx) setRandomLineWidth(ctx) for var j = BackRect.minY; j <= BackRect.maxY; j += step { CGContextMoveToPoint(ctx, BackRect.minX, j) CGContextAddLineToPoint(ctx, BackRect.maxX, j) } CGContextStrokePath(ctx) } private func drawSingleTriangle(ctx:CGContextRef, _ p1:CGPoint, _ p2:CGPoint, _ p3:CGPoint) { if Helper.fiftyFifty() { setRandomFill2(ctx) } else { setRandomFill(ctx) } CGContextBeginPath(ctx) CGContextMoveToPoint(ctx, p1.x, p1.y) CGContextAddLineToPoint(ctx, p2.x, p2.y) CGContextAddLineToPoint(ctx, p3.x, p3.y) CGContextClosePath(ctx) CGContextFillPath(ctx) if Helper.fiftyFifty() { setRandomStroke2(ctx) setRandomLineWidth(ctx) CGContextBeginPath(ctx) CGContextMoveToPoint(ctx, p1.x, p1.y) CGContextAddLineToPoint(ctx, p2.x, p2.y) CGContextAddLineToPoint(ctx, p3.x, p3.y) CGContextClosePath(ctx) CGContextStrokePath(ctx) } } private func drawTriangles(ctx:CGContextRef) { drawSingleTriangle( ctx, CGPointMake(BackRect.minX, BackRect.minY), CGPointMake(BackRect.minX, BackRect.maxY), CGPointMake(BackRect.maxX, BackRect.maxY)) if Helper.fiftyFifty() { // Another shifted drawSingleTriangle( ctx, CGPointMake(BackRect.maxX, BackRect.minY), CGPointMake(BackRect.minX, BackRect.maxY), CGPointMake(BackRect.maxX, BackRect.maxY)) } if Helper.fiftyFifty() { // Another mixed drawSingleTriangle( ctx, CGPointMake(BackRect.minX, BackRect.minY), CGPointMake(BackRect.midX, BackRect.midY), CGPointMake(BackRect.maxX, BackRect.minY)) } } private func blackHolesRandomizations(ctx:CGContextRef, randomize1:Bool, randomize2:Bool, randomize3:Bool, randomize4:Bool) { if randomize1 { setRandomShadow(ctx) } if randomize2 { setRandomLineWidth(ctx) } if randomize3 { if Helper.fiftyFifty() { setRandomStroke(ctx) } else { setRandomStroke2(ctx) } } if randomize4 { setRandomFillLighter(ctx) } } private func getPossibleBlackHoleOffsetForTranslate() -> CGFloat { return Helper.fiftyFiftyOnePlusMinus() * Helper.random01CGFloat() * FactorMaxPossibleblackHoleOffsetForTranslate } // Black hole variant private func drawBlackHoleLayerOne(ctx:CGContextRef) { let blackHolerFactor:CGFloat = 1.0 + (Helper.random01CGFloat() * 0.5) let properBlackHole = Helper.fiftyFifty() if Helper.fiftyFifty() { setRandomStroke(ctx) } else { setRandomStroke2(ctx) } setRandomFillLighter(ctx) setRandomLineWidth(ctx) let howMany = Helper.randomBetween(FactorBlackHoleMin, max: FactorBlackHoleMax, includeMax: false) var holes:[CGRect] = [] var step:CGFloat = (BackDimensionMax / 2.0) / CGFloat(howMany) let centerOut = Helper.fiftyFifty() let outOrInFactor:CGFloat = centerOut ? -1.0 : 1.0 var start:CGFloat = centerOut ? (BackDimensionMax / 2.0) : step for _ in 0..<howMany { holes.append(CGRectInset(BackRect, start, start)) if properBlackHole { step *= blackHolerFactor start += step * (outOrInFactor) } else { start += step * (outOrInFactor) } } if centerOut { holes = holes.reverse() } let randomize1 = Helper.fiftyFifty() let randomize2 = Helper.fiftyFifty() let randomize3 = Helper.fiftyFifty() let randomize4 = Helper.fiftyFifty() let circles = Helper.fiftyFifty() let makeCirclesLittleOffset = Helper.fiftyFifty() if circles { if makeCirclesLittleOffset { for h in holes { blackHolesRandomizations(ctx, randomize1: randomize1, randomize2: randomize2, randomize3: randomize3, randomize4: randomize4) CGContextSaveGState(ctx) CGContextTranslateCTM(ctx, getPossibleBlackHoleOffsetForTranslate(), getPossibleBlackHoleOffsetForTranslate()) CGContextFillEllipseInRect(ctx, h) CGContextStrokeEllipseInRect(ctx, h) CGContextRestoreGState(ctx) } } else { for h in holes { blackHolesRandomizations(ctx, randomize1: randomize1, randomize2: randomize2, randomize3: randomize3, randomize4: randomize4) CGContextFillEllipseInRect(ctx, h) CGContextStrokeEllipseInRect(ctx, h) } } } else { if Helper.fiftyFifty() { // NOTE: Squares rotated! let angleRotate:CGFloat = (2.0 * CGFloat(M_PI)) / CGFloat(holes.count) let centerBack = CGPointMake(BackRect.midX, BackRect.midY) CGContextSaveGState(ctx) CGContextTranslateCTM(ctx, centerBack.x, centerBack.y) for h in holes { blackHolesRandomizations(ctx, randomize1: randomize1, randomize2: randomize2, randomize3: randomize3, randomize4: randomize4) let r = CGRectMake(h.minX - centerBack.x, h.minY - centerBack.y, h.width, h.height) CGContextFillRect(ctx, r) CGContextStrokeRect(ctx, r) CGContextRotateCTM(ctx, angleRotate) } CGContextRestoreGState(ctx) } else { for h in holes { blackHolesRandomizations(ctx, randomize1: randomize1, randomize2: randomize2, randomize3: randomize3, randomize4: randomize4) CGContextFillRect(ctx, h) CGContextStrokeRect(ctx, h) } } } } private func drawBlackHole(ctx:CGContextRef) { let angle:CGFloat = CGFloat((M_PI * 2.0)) / CGFloat(Helper.randomBetween(FactorBlackHoleMin, max: FactorBlackHoleMax, includeMax: false)) let randomize = Helper.fiftyFifty() let randomize2 = Helper.fiftyFifty() if Helper.fiftyFifty() { setRandomStroke(ctx) } else { setRandomStroke2(ctx) } setRandomLineWidth(ctx) let centerBack = CGPointMake(BackRect.midX, BackRect.midY) let howLong:CGFloat = CGFloat(M_PI) * 2.0 var start:CGFloat = 0.0 CGContextSaveGState(ctx) CGContextTranslateCTM(ctx, centerBack.x, centerBack.y) let startPoint = CGPointMake(BackRect.minX - centerBack.x, BackRect.minY - centerBack.y) let endPoint = CGPointMake(BackRect.maxX - centerBack.x, BackRect.maxY - centerBack.y) while start <= howLong { if randomize { setRandomShadow(ctx) } if randomize2 { setRandomLineWidth(ctx) } CGContextRotateCTM(ctx, angle) CGContextBeginPath(ctx) CGContextMoveToPoint(ctx, startPoint.x, startPoint.y) CGContextAddLineToPoint(ctx, endPoint.x, endPoint.y) CGContextStrokePath(ctx) start += angle } CGContextRestoreGState(ctx) } // NOTE: First layer variant private func drawFirstLayerVariant(ctx:CGContextRef) { let angle:CGFloat = CGFloat((M_PI * 2.0)) / CGFloat(Helper.randomBetween(FactorLinesAnglesMin, max: FactorLinesAnglesMax, includeMax: false)) let randomize = Helper.fiftyFifty() let randomize2 = Helper.fiftyFifty() if Helper.fiftyFifty() { setRandomStroke(ctx) } else { setRandomStroke2(ctx) } setRandomLineWidth(ctx) let centerBack = CGPointMake(BackRect.midX, BackRect.midY) let howLong:CGFloat = CGFloat(M_PI) * 2.0 var start:CGFloat = 0.0 CGContextSaveGState(ctx) CGContextTranslateCTM(ctx, centerBack.x, centerBack.y) let startPoint = CGPointMake(BackRect.minX - centerBack.x, BackRect.minY - centerBack.y) let endPoint = CGPointMake(BackRect.maxX - centerBack.x, BackRect.maxY - centerBack.y) while start <= howLong { if randomize { setRandomShadow(ctx) } if randomize2 { setRandomLineWidth(ctx) } CGContextRotateCTM(ctx, angle) CGContextBeginPath(ctx) CGContextMoveToPoint(ctx, startPoint.x, startPoint.y) CGContextAddLineToPoint(ctx, endPoint.x, endPoint.y) CGContextStrokePath(ctx) start += angle } CGContextRestoreGState(ctx) } private func drawCirclesOrSquaresOverlay(ctx:CGContextRef) { let circles = Helper.fiftyFifty() for _ in 0..<Helper.randomBetween(1, max: FactorInsidersOverlays, includeMax: true) { if Helper.fiftyFifty() { setRandomStroke(ctx) } else { setRandomStroke2(ctx) } setRandomLineWidth(ctx) setRandomFill(ctx) let inset:CGFloat = (BackRect.width / 2.1) - (Helper.random01CGFloat() * (BackRect.width / 5.0)) let r = CGRectInset(BackRect, inset, inset) if circles { CGContextFillEllipseInRect(ctx, r) CGContextStrokeEllipseInRect(ctx, r) } else { CGContextFillRect(ctx, r) CGContextStrokeRect(ctx, r) } } } private func drawFullRectLayer(ctx:CGContextRef) { setRandomFill(ctx) CGContextFillRect(ctx, BackRect) } private func drawSpace(ctx:CGContextRef) { let angle:CGFloat = CGFloat((M_PI * 2.0)) / CGFloat(Helper.randomBetween(FactorBlackHoleMin2, max: FactorBlackHoleMax2, includeMax: false)) if Helper.fiftyFifty() { setRandomStroke(ctx) } else { setRandomStroke2(ctx) } setRandomFillLighter(ctx) setRandomLineWidth(ctx) let centerBack = CGPointMake(BackRect.midX, BackRect.midY) let howLong:CGFloat = CGFloat(M_PI) * 2.0 var start:CGFloat = 0.0 CGContextSaveGState(ctx) CGContextTranslateCTM(ctx, centerBack.x, centerBack.y) let startPoint = CGPointMake(BackRect.minX - centerBack.x, BackRect.minY - centerBack.y) let endPoint = CGPointMake(BackRect.maxX - centerBack.x, BackRect.maxY - centerBack.y) let controlPointX:CGFloat = BackRect.minX + (Helper.random01CGFloat() * BackRect.width) let controlPointY:CGFloat = BackRect.minY + (Helper.random01CGFloat() * BackRect.height) let controlPoint = CGPointMake(controlPointX - centerBack.x, controlPointY - centerBack.y) var drawFillStroke = Helper.fiftyFifty() var fullRandomize = Helper.fiftyFifty() let randomize1 = Helper.fiftyFifty() let randomize2 = Helper.fiftyFifty() let randomize3 = Helper.fiftyFifty() let randomize4 = Helper.fiftyFifty() while start <= howLong { if fullRandomize { blackHolesRandomizations(ctx, randomize1: randomize1, randomize2: randomize2, randomize3: randomize3, randomize4: randomize4) } CGContextRotateCTM(ctx, angle) CGContextBeginPath(ctx) CGContextMoveToPoint(ctx, startPoint.x, startPoint.y) CGContextAddLineToPoint(ctx, endPoint.x, endPoint.y) if drawFillStroke { CGContextDrawPath(ctx, CGPathDrawingMode.FillStroke) } else { CGContextStrokePath(ctx) } start += angle } fullRandomize = Helper.fiftyFifty() drawFillStroke = !drawFillStroke start = 0.0 let megaCurves = Helper.fiftyFifty() let megaMiddlePoint = CGPointMake(centerBack.x - centerBack.x, centerBack.y - centerBack.y) let controlPointX2:CGFloat = BackRect.minX + (Helper.random01CGFloat() * BackRect.width) let controlPointY2:CGFloat = BackRect.minY + (Helper.random01CGFloat() * BackRect.height) let controlPoint2 = CGPointMake(controlPointX2 - centerBack.x, controlPointY2 - centerBack.y) while start <= howLong { if fullRandomize { blackHolesRandomizations(ctx, randomize1: randomize1, randomize2: randomize2, randomize3: randomize3, randomize4: randomize4) } CGContextRotateCTM(ctx, angle) CGContextBeginPath(ctx) if megaCurves { CGContextMoveToPoint(ctx, startPoint.x, startPoint.y) CGContextAddQuadCurveToPoint(ctx, controlPoint.x, controlPoint.y, megaMiddlePoint.x, megaMiddlePoint.y) CGContextAddQuadCurveToPoint(ctx, controlPoint2.x, controlPoint2.y, endPoint.x, endPoint.y) } else { CGContextMoveToPoint(ctx, startPoint.x, startPoint.y) CGContextAddQuadCurveToPoint(ctx, controlPoint.x, controlPoint.y, endPoint.x, endPoint.y) } if drawFillStroke { CGContextDrawPath(ctx, CGPathDrawingMode.FillStroke) } else { CGContextStrokePath(ctx) } start += angle } CGContextRestoreGState(ctx) } private func carpetsRandomizations(ctx:CGContextRef, randomize1:Bool, randomize2:Bool, randomize3:Bool) { if randomize1 { setRandomShadow(ctx) } if randomize2 { setRandomLineWidth(ctx) } if randomize3 { if Helper.fiftyFifty() { setRandomStroke(ctx) } else { setRandomStroke2(ctx) } } } // NOTE: Carpets private func drawCarpet(ctx:CGContextRef) { let step:CGFloat = BackDimensionMax / CGFloat(Helper.randomBetween(Int(FactorLinesStepperMin), max: Int(FactorLinesStepperMax), includeMax: false)) var carpets:[[CGPoint]] = [] for var i = BackRect.minX; i <= BackRect.maxX; i += step { carpets.append([CGPointMake(i, BackRect.minY), CGPointMake(i, BackRect.maxY)]) } for var j = BackRect.minY; j <= BackRect.maxY; j += step { carpets.append([CGPointMake(BackRect.minX, j), CGPointMake(BackRect.maxX, j)]) } // NOTE: !!! RANDOM SHUFFLE POINTS carpets.shuffle() setRandomStroke2(ctx) setRandomLineWidth(ctx) let fullRandomize = Helper.fiftyFifty() let randomize1 = Helper.fiftyFifty() let randomize2 = Helper.fiftyFifty() let randomize3 = Helper.fiftyFifty() for carpetPair in carpets { if fullRandomize { carpetsRandomizations(ctx, randomize1: randomize1, randomize2: randomize2, randomize3: randomize3) } CGContextMoveToPoint(ctx, carpetPair[0].x, carpetPair[0].y) CGContextAddLineToPoint(ctx, carpetPair[1].x, carpetPair[1].y) CGContextStrokePath(ctx) } } // NOTE: Matrix private func drawMatrix(ctx:CGContextRef) { let step:CGFloat = BackDimensionMax / CGFloat(Helper.randomBetween(Int(FactorLinesStepperMin), max: Int(FactorLinesStepperMax), includeMax: false)) var matrixStart:[CGPoint] = [] var matrixEnd:[CGPoint] = [] for var i = BackRect.minX; i <= BackRect.maxX; i += step { matrixStart.append(CGPointMake(i, BackRect.minY)) matrixEnd.append(CGPointMake(i, BackRect.maxY)) } for var j = BackRect.minY; j <= BackRect.maxY; j += step { matrixStart.append(CGPointMake(BackRect.minX, j)) matrixEnd.append(CGPointMake(BackRect.maxX, j)) } // NOTE: !!! RANDOM SHUFFLE POINTS matrixStart.shuffle() matrixEnd.shuffle() setRandomStroke2(ctx) setRandomLineWidth(ctx) let fullRandomize = Helper.fiftyFifty() let randomize1 = Helper.fiftyFifty() let randomize2 = Helper.fiftyFifty() let randomize3 = Helper.fiftyFifty() for i in 0..<matrixStart.count { if fullRandomize { carpetsRandomizations(ctx, randomize1: randomize1, randomize2: randomize2, randomize3: randomize3) } CGContextMoveToPoint(ctx, matrixStart[i].x, matrixStart[i].y) CGContextAddLineToPoint(ctx, matrixEnd[i].x, matrixEnd[i].y) CGContextStrokePath(ctx) } } private func addRandomFinalMix(ctx:CGContextRef) { switch Helper.randomBetween(0, max: 4, includeMax: true) { case 0: drawTriangles(ctx) case 1: drawCirclesOrSquaresOverlay(ctx) case 2: drawTriangles(ctx) drawCirclesOrSquaresOverlay(ctx) case 3: drawCirclesOrSquaresOverlay(ctx) drawTriangles(ctx) default: () } } private func setupBackground() { UIGraphicsBeginImageContext(BackRect.size) let ctx = UIGraphicsGetCurrentContext() setRandomShadow(ctx!) Helper.getRandomColor().setFill() CGContextFillRect(ctx, BackRect) switch Helper.randomBetween(0, max: 4, includeMax: true) { case 0: drawMatrix(ctx!) addRandomFinalMix(ctx!) case 1: drawCarpet(ctx!) addRandomFinalMix(ctx!) case 2: drawSpace(ctx!) addRandomFinalMix(ctx!) case 3: drawBlackHole(ctx!) drawBlackHoleLayerOne(ctx!) if Helper.fiftyFifty() { drawTriangles(ctx!) } default: if Helper.fiftyFifty() { drawFirstLayerVariant(ctx!) } else { drawFirstLayer(ctx!) } if Helper.fiftyFifty() { drawTriangles(ctx!) drawCirclesOrSquaresOverlay(ctx!) } else { // Reversed drawCirclesOrSquaresOverlay(ctx!) drawTriangles(ctx!) } } SabilandTrippyBackground = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() } }
mit
fe8643fc351065723fe767ad46160f38
29.708889
196
0.550872
4.769284
false
false
false
false
coolsamson7/inject
Inject/inject/Environment.swift
1
57969
// // Environment.swift // Inject // // Created by Andreas Ernst on 18.07.16. // Copyright © 2016 Andreas Ernst. All rights reserved. // public typealias Resolver = (_ key : String) throws -> String? /// this factory creates instances by calling a specified function class FactoryFactory<T> : BeanFactory { // MARK: instance data var factory : () throws -> T // MARK: init internal init(factory : @escaping () throws -> T ) { self.factory = factory } // MARK: implement BeanFactory func create(_ bean : Environment.BeanDeclaration) throws -> AnyObject { return try factory() as AnyObject } } /// `Environment`is the central class that collects bean informations and takes care of their lifecycle open class Environment: BeanFactory { // MARK: local classes open class UnresolvedScope : AbstractBeanScope { // MARK: init override init(name : String) { super.init(name: name) } } /// this factory calls the default constructor of the given class class DefaultConstructorFactory : BeanFactory { // static data static var instance = DefaultConstructorFactory() // MARK: implement BeanFactory func create(_ declaration: BeanDeclaration) throws -> AnyObject { return try declaration.bean.create() } } /// this factory returns a fixed object class ValueFactory : BeanFactory { // MARK: instance data var object : AnyObject // init init(object : AnyObject) { self.object = object } // MARK: implement BeanFactory func create(_ bean : BeanDeclaration) throws -> AnyObject { return object } } open class Declaration : NSObject, OriginAware { // MARK: instance data var _origin : Origin? // MARK: implement OriginAware open var origin : Origin? { get { return _origin } set { _origin = newValue } } } /// An `BeanDeclaration` collects the necessary information to construct a particular instance. /// This covers /// * the class /// * the scope: "singleton", "prototype" or custom. "singleton" is the default /// * lazy attribute. The default is `false` /// * optional id of a parent bean if, that defines common attributes that will be inherited /// * properties /// * the target class for factory beans open class BeanDeclaration : Declaration { // MARK: local classes class Require { var clazz : AnyClass? var id : String? var bean : BeanDeclaration? init(clazz : AnyClass? = nil, id : String? = nil, bean : BeanDeclaration? = nil) { self.clazz = clazz self.id = id self.bean = bean } } // MARK: instance data var scope : BeanScope? = nil var lazy = false var abstract = false var parent: BeanDeclaration? = nil var id : String? var requires : [Require] = [] var clazz : AnyClass? var _bean: BeanDescriptor? var bean : BeanDescriptor { get { if _bean == nil { _bean = try! BeanDescriptor.forClass(clazz!) } return _bean! } } var implements = [Any.Type]() var target: AnyClass? var properties = [PropertyDeclaration]() var factory : BeanFactory = DefaultConstructorFactory.instance var singleton : AnyObject? = nil // init /// create a new `BeanDeclaration` /// - Parameter id: the id init(id : String) { self.id = id } /// create a new `BeanDeclaration` /// - Parameter instance: a fixed instance init(instance : AnyObject) { self.factory = ValueFactory(object: instance) //self.singleton = instance // this is not done on purpose since we want the post processors to run! self.clazz = type(of: instance) } /// create a new `BeanDeclaration` override init() { super.init() } // MARK: fluent stuff /// set the class of this bean declaration /// - Parameter className: the class name /// - Returns: self open func clazz(_ className : String) throws -> Self { self.clazz = try Classes.class4Name(className) return self } /// set the id of this bean declaration /// - Parameter id: the id /// - Returns: self open func id(_ id : String) -> Self { self.id = id return self } /// set the `lazy' attribute of this bean declaration /// - Parameter lazy: if `true`, the instance will be created whenever it is requested for the first time /// - Returns: self open func lazy(_ lazy : Bool = true) -> Self { self.lazy = lazy return self } /// set the `abstract' attribute of this bean declaration /// - Parameter abstract: if `true`, the instance will not be craeted but serves only as a template for inherited beans /// - Returns: self open func abstract(_ abstract : Bool = true) -> Self { self.abstract = abstract return self } /// set the scope of this bean declaration /// - Parameter scope: the scope /// - Returns: self open func scope(_ scope : BeanScope) -> Self { self.scope = scope return self } /// set the scope of this bean declaration /// - Parameter scope: the scope /// - Returns: self open func scope(_ scope : String) -> Self { self.scope = UnresolvedScope(name: scope) return self } /// specifies that this bean needs to be constructed after another bean /// - Parameter depends: the id of the bean which needs to be constructed first /// - Returns: self open func dependsOn(_ depends : String) -> Self { requires(id: depends) return self } /// specifies that this bean needs to be constructed after another bean /// - Parameter id: the id of the bean which needs to be constructed first /// - Returns: self open func requires(id: String) -> Self { requires.append(Require(id: id)) return self } /// specifies that this bean needs to be constructed after another bean /// - Parameter class: the class of the bean which needs to be constructed first /// - Returns: self open func requires(class clazz: AnyClass) -> Self { requires.append(Require(clazz: clazz)) return self } /// specifies that this bean needs to be constructed after another bean /// - Parameter bean: the bean which needs to be constructed first /// - Returns: self open func requires(bean : BeanDeclaration) -> Self { requires.append(Require(bean: bean)) return self } /// specifies a bean that will serve as a template /// - Parameter parent: the id of the parent bean /// - Returns: self open func parent(_ parent : String) -> Self { self.parent = BeanDeclaration(id: parent) return self } /// create a new property given its name and one of possible parameters /// - Parameter name: the name of the property /// - Parameter value: a fixed value /// - Parameter ref: the id of a referenced bean /// - Parameter resolve: a placeholder that will be evaluated in the current configuration context and possibly transformed in rhe required type /// - Parameter bean: an embedded bean defining the value /// - Parameter inject: an `InjectBean` instance that defines how the injection shuld be carried out ( by id or by type ) /// - Returns: self open func property(_ name: String, value : Any? = nil, ref : String? = nil, resolve : String? = nil, bean : BeanDeclaration? = nil, inject : InjectBean? = nil) -> Self { let property = PropertyDeclaration() property.name = name // TODO: sanity check if ref != nil { property.value = Environment.BeanReference(ref: ref!) } else if resolve != nil { property.value = Environment.PlaceHolder(value: resolve!) } else if bean != nil { property.value = Environment.EmbeddedBean(bean: bean!) } else if inject != nil { property.value = Environment.InjectedBean(inject: inject!) } else { property.value = Environment.Value(value: value!) } properties.append(property) return self } /// specifies a target class of a factory bean /// - Parameter clazz: the class that this factory beans creates /// - Returns: self open func target(_ clazz : AnyClass) throws -> Self { self.target = clazz return self } /// add a new property /// - Parameter property : a `PropertyDeclaration` /// - Returns: self open func property(_ property: PropertyDeclaration) -> Self { properties.append(property) return self } // specifies that the corresponding instance implements a number of types open func implements(_ types : Any.Type...) throws -> Self { self.implements = types return self } // MARK: internal func report(_ builder : StringBuilder) { builder.append(Classes.className(clazz!)) if id != nil { builder.append("[\"\(id!)\"]") } if lazy { builder.append(" lazy: true") } if abstract { builder.append(" abstract: true") } if self.scope!.name != "singleton" { builder.append(" scope: \(scope!.name)") } if origin != nil { builder.append(" origin: \(origin!)") } builder.append("\n") } func inheritFrom(_ parent : BeanDeclaration, loader: Environment.Loader) throws -> Void { var resolveProperties = false if clazz == nil { clazz = parent.clazz resolveProperties = true if !abstract { try loader.context.rememberType(self) } } if scope == nil { scope = parent.scope } // properties for property in parent.properties { // only copy those properties that are not explicitly set here! if properties.index(where: {$0.name == property.name}) == nil { properties.append(property) } } if resolveProperties { for property in properties { try property.resolveProperty(self, loader: loader) } } } func collect(_ environment: Environment, loader: Environment.Loader) throws -> Void { for property in properties { try property.collect(self, environment: environment, loader: loader) } } func connect(_ loader : Environment.Loader) throws -> Void { for require in requires { if let bean = require.bean { loader.dependency(bean, before: self) } else if let id = require.id { loader.dependency(try loader.context.getDeclarationById(id), before: self) } else if let clazz = require.clazz { loader.dependency(try loader.context.getCandidate(clazz), before: self) } } // for if parent != nil { parent = try loader.context.getDeclarationById(parent!.id!) try inheritFrom(parent!, loader: loader) // copy properties, etc. loader.dependency(parent!, before: self) } for property in properties { try property.connect(self, loader: loader) } if let descriptor = BeanDescriptor.findBeanDescriptor(clazz!) { // do not create the descriptor on demand! // injections for beanProperty in descriptor.getProperties() { if beanProperty.autowired { let declaration = try loader.context.getCandidate(beanProperty.getPropertyType()) loader.dependency(declaration, before: self) } // if } // for } // if } func resolve(_ loader : Environment.Loader) throws -> Void { // resolve scope? if let scope = self.scope as? UnresolvedScope { self.scope = try loader.context.getScope(scope.name) } // resolve properties for property in properties { try property.resolve(loader) if !checkTypes(property.getType(), expected: property.property!.getPropertyType()) { throw EnvironmentErrors.typeMismatch(message: " property \(Classes.className(clazz!)).\(property.name) expected a \(property.property!.getPropertyType()) got \(property.getType())") } } } func prepare(_ loader : Environment.Loader) throws -> Void { try scope!.prepare(self, factory: loader.context) // check for post processors if clazz is BeanPostProcessor.Type { if (Tracer.ENABLED) { Tracer.trace("inject.runtime", level: .high, message: "add post processor \(String(describing: clazz))") } loader.context.postProcessors.append(try self.getInstance(loader.context) as! BeanPostProcessor) // sanity checks } } func checkTypes(_ type: Any.Type, expected : Any.Type) -> Bool { if type != expected { if let expectedClazz = expected as? AnyClass { if let clazz = type as? AnyClass { if !clazz.isSubclass(of: expectedClazz) { return false } } else { return false } } else { return false } } return true } func getInstance(_ environment: Environment) throws -> AnyObject { return try scope!.get(self, factory: environment) } func create(_ environment: Environment) throws -> AnyObject { if (Tracer.ENABLED) { Tracer.trace("inject.runtime", level: .high, message: "create instance of \(clazz!)") } let result = try factory.create(self) // MARK: constructor, value, etc // make sure that the bean descriptor is initialized since we need the class hierarchy for subsequent bean requests! if _bean == nil { if let beanDescriptor = BeanDescriptor.findBeanDescriptor(type(of: result)) { _bean = beanDescriptor } else { // create manually with instance avoiding the generic init call _bean = try BeanDescriptor(instance: result) } for prot in implements { try _bean!.implements(prot) } } // set properties for property in properties { let beanProperty = property.property! let resolved = try property.get(environment) if resolved != nil { if (Tracer.ENABLED) { Tracer.trace("inject.runtime", level: .full, message: "set \(Classes.className(clazz!)).\(beanProperty.getName()) = \(resolved!)") } try beanProperty.set(result, value: resolved) } // if } // run processors return try environment.runPostProcessors(result) } // CustomStringConvertible override open var description: String { let builder = StringBuilder() builder.append("bean(class: \(String(describing: clazz))") if id != nil { builder.append(", id: \"\(id!)\"") } if _origin != nil { builder.append(", origin: [\(_origin!.line):\(_origin!.column)]") } builder.append(")") return builder.toString() } } // these classes act as containers for various ways to reference values class ValueHolder { func collect(_ loader : Environment.Loader, beanDeclaration : BeanDeclaration) throws -> Void { // noop } func connect(_ loader : Environment.Loader, beanDeclaration : BeanDeclaration, type : Any.Type) throws -> Void { // noop } func resolve(_ loader : Environment.Loader, type : Any.Type) throws -> ValueHolder { return self } func get(_ environment: Environment) throws -> Any { fatalError("\(type(of: self)).get is abstract") } func getType() -> Any.Type { fatalError("\(type(of: self)).getType is abstract") } } class BeanReference : ValueHolder { // MARK: instance data var ref : BeanDeclaration // init init(ref : String) { self.ref = BeanDeclaration(id: ref) } // override override func connect(_ loader : Environment.Loader, beanDeclaration : BeanDeclaration, type : Any.Type) throws -> Void { ref = try loader.context.getDeclarationById(ref.id!) // replace with real declaration loader.dependency(ref, before: beanDeclaration) } override func get(_ environment: Environment) throws -> Any { return try ref.getInstance(environment) } override func getType() -> Any.Type { return ref.clazz! } } class InjectedBean : ValueHolder { // MARK: instance data var inject : InjectBean var bean : BeanDeclaration? // init init(inject : InjectBean) { self.inject = inject } // override override func connect(_ loader : Environment.Loader, beanDeclaration : BeanDeclaration, type : Any.Type) throws -> Void { if inject.id != nil { bean = try loader.context.getDeclarationById(inject.id!) } else { bean = try loader.context.getCandidate(type) } loader.dependency(bean!, before: beanDeclaration) } override func get(_ environment: Environment) throws -> Any { return try bean!.getInstance(environment) } override func getType() -> Any.Type { return bean!.clazz! } } class EmbeddedBean : ValueHolder { // MARK: instance data var bean : BeanDeclaration // init init(bean : BeanDeclaration) { self.bean = bean } // override override func collect(_ loader : Environment.Loader, beanDeclaration : BeanDeclaration) throws -> Void { try loader.context.define(bean) } override func connect(_ loader : Environment.Loader, beanDeclaration : BeanDeclaration, type : Any.Type) throws -> Void { loader.dependency(bean, before: beanDeclaration) } override func get(_ environment: Environment) throws -> Any { return try bean.getInstance(environment) } override func getType() -> Any.Type { return bean.clazz! } } class Value : ValueHolder { // MARK: instance data var value : Any // init init(value : Any) { self.value = value } // TODO func isNumberType(_ type : Any.Type) -> Bool { if type == Int8.self { return true } else if type == UInt8.self { return true } else if type == Int16.self { return true } else if type == UInt16.self { return true } else if type == Int32.self { return true } else if type == UInt32.self { return true } else if type == Int64.self { return true } else if type == UInt64.self { return true } else if type == Int.self { return true } else if type == Float.self { return true } else if type == Double.self { return true } return false } // move somewhere else... func coerceNumber(_ value: Any, type: Any.Type) throws -> (value:Any, success:Bool) { if isNumberType(type) { let conversion = StandardConversionFactory.instance.findConversion(type(of: value), targetType: type) if conversion != nil { return (try conversion!(object: value), true) } } return (value, false) } // override override func resolve(_ loader : Environment.Loader, type : Any.Type) throws -> ValueHolder { if type != type(of: value) { // check if we can coerce numbers... let coercion = try coerceNumber(value, type: type) if coercion.success { value = coercion.value } else { throw EnvironmentErrors.typeMismatch(message: "could not convert a \(type(of: value) ) into a \(type)") } } return self } override func get(_ environment: Environment) throws -> Any { return value } override func getType() -> Any.Type { return type(of: value) } } class PlaceHolder : ValueHolder { // MARK: instance data var value : String // init init(value : String) { self.value = value } // override override func resolve(_ loader : Environment.Loader, type : Any.Type) throws -> ValueHolder { // replace placeholders first... value = try loader.resolve(value) var result : Any = value; // check for conversions if type != String.self { if let conversion = StandardConversionFactory.instance.findConversion(String.self, targetType: type) { do { result = try conversion(object: value) } catch ConversionErrors.conversionException( _, let targetType, _) { throw ConversionErrors.conversionException(value: value, targetType: targetType, context: "")//[\(origin!.line):\(origin!.column)]") } } else { throw EnvironmentErrors.typeMismatch(message: "no conversion applicable between String and \(type)") } } // done return Value(value: result) } } open class PropertyDeclaration : Declaration { // MARK: instance data var name : String = "" var value : ValueHolder? var property : BeanDescriptor.PropertyDescriptor? // functions func resolveProperty(_ beanDeclaration : BeanDeclaration, loader: Environment.Loader) throws -> Void { property = beanDeclaration.bean.findProperty(name) if property == nil { throw EnvironmentErrors.unknownProperty(property: name, bean: beanDeclaration) } } func collect(_ beanDeclaration : BeanDeclaration, environment: Environment, loader: Environment.Loader) throws -> Void { if beanDeclaration.clazz != nil { // abstract classes try resolveProperty(beanDeclaration, loader: loader) } try value!.collect(loader, beanDeclaration: beanDeclaration) } func connect(_ beanDeclaration : BeanDeclaration, loader : Environment.Loader) throws -> Void { if property == nil { // HACK...dunno why... try resolveProperty(beanDeclaration, loader: loader) } try value!.connect(loader, beanDeclaration: beanDeclaration, type: property!.getPropertyType()) } func resolve(_ loader : Environment.Loader) throws -> Any? { return try value = value!.resolve(loader, type: property!.getPropertyType()) } func get(_ environment: Environment) throws -> Any? { return try value!.get(environment) } func getType() -> Any.Type { return value!.getType() } } // default scopes open class PrototypeScope : AbstractBeanScope { // MARK: init override init() { super.init(name: "prototype") } // MARK: override AbstractBeanScope open override func get(_ bean : Environment.BeanDeclaration, factory : BeanFactory) throws -> AnyObject { return try factory.create(bean) } } open class SingletonScope : AbstractBeanScope { // MARK: init override init() { super.init(name: "singleton") } // MARK: override AbstractBeanScope open override func prepare(_ bean : Environment.BeanDeclaration, factory : BeanFactory) throws { if !bean.lazy { try get(bean, factory: factory) } } open override func get(_ bean : Environment.BeanDeclaration, factory : BeanFactory) throws -> AnyObject { if bean.singleton == nil { bean.singleton = try factory.create(bean) } return bean.singleton! } } class BeanFactoryScope : BeanScope { // MARK: instance data let declaration : Environment.BeanDeclaration let environment: Environment // init init(declaration : Environment.BeanDeclaration, environment: Environment) { self.declaration = declaration self.environment = environment } // BeanScope var name : String { get { return "does not matter" } } func prepare(_ bean : Environment.BeanDeclaration, factory : BeanFactory) throws { // noop } func get(_ bean : Environment.BeanDeclaration, factory : BeanFactory) throws -> AnyObject { if let factoryBean = try declaration.getInstance(environment) as? FactoryBean { return try environment.runPostProcessors(try factoryBean.create()) } fatalError("cannot happen") } func finish() { // noop } } open class Loader { // local classes class Dependency : Equatable { // MARK: instance data var declaration : Environment.BeanDeclaration var successors : [Dependency] = [] var index : Int? = nil var lowLink : Int = 0 var inCount = 0 // init init(declaration : Environment.BeanDeclaration) { self.declaration = declaration } // methods func addSuccessor(_ dependency: Dependency) -> Void { successors.append(dependency) dependency.inCount += 1 } } // MARK: instance data var context: Environment var loading = false var dependencyList : [Dependency] = [] var dependencies = IdentityMap<Environment.BeanDeclaration, Dependency>() var resolver : Resolver? = nil // init init(context: Environment) { self.context = context } // MARK: public func resolve(_ string : String) throws -> String { var result = string if let range = string.range(of: "${") { result = string[string.startIndex..<range.lowerBound] let eq = string.range(of: "=", range: range.lowerBound..<string.endIndex) let end = string.range(of: "}", options: .backwards, range: range.lowerBound..<string.endIndex) if eq != nil { let key = string[range.upperBound ..< eq!.lowerBound] let resolved = try resolver!(key) if (Tracer.ENABLED) { Tracer.trace("inject.configuration", level: .high, message: "resolve configuration key \(key) = \(String(describing: resolved))") } if resolved != nil { result += resolved! } else { result += try resolve(string[eq!.upperBound..<end!.lowerBound]) } } else { let key = string[range.upperBound ..< end!.lowerBound] let resolved = try resolver!(key)! if (Tracer.ENABLED) { Tracer.trace("inject.configuration", level: .high, message: "resolve configuration key \(key) = \(resolved)") } result += resolved } // else result += try resolve(string[end!.upperBound..<string.endIndex]) } // if return result } func setup() throws -> Void { // local function func resolveConfiguration(_ key: String) throws -> String? { let fqn = FQN.fromString(key) if context.configurationManager.hasValue(fqn.namespace, key: fqn.key) { return try context.configurationManager.getValue(String.self, namespace: fqn.namespace, key: fqn.key) } else { return nil } } resolver = resolveConfiguration } // MARK: internal func getDependency(_ bean : Environment.BeanDeclaration) -> Dependency { var dependency = dependencies[bean] if dependency == nil { dependency = Dependency(declaration: bean) dependencyList.append(dependency!) dependencies[bean] = dependency! } return dependency! } func dependency(_ bean : Environment.BeanDeclaration, before : Environment.BeanDeclaration) { getDependency(bean).addSuccessor(getDependency(before)) } func addDeclaration(_ declaration : Environment.BeanDeclaration) throws -> Environment.BeanDeclaration { // add let dependency = Dependency(declaration: declaration) dependencies[declaration] = dependency dependencyList.append(dependency) return declaration } func sortDependencies(_ dependencies : [Dependency]) throws -> Void { // local functions func detectCycles() -> [[Environment.BeanDeclaration]] { // closure state var index = 0 var stack: [Dependency] = [] var cycles: [[Environment.BeanDeclaration]] = [] // local func func traverse(_ dependency: Dependency) { dependency.index = index dependency.lowLink = index index += 1 stack.append(dependency) // add to the stack for successor in dependency.successors { if successor.index == nil { traverse(successor) dependency.lowLink = min(dependency.lowLink, successor.lowLink) } else if stack.contains(successor) { // if the component was not closed yet dependency.lowLink = min(dependency.lowLink, successor.index!) } } // for if dependency.lowLink == dependency.index! { // root of a component var group:[Dependency] = [] var member: Dependency repeat { member = stack.removeLast() group.append(member) } while member !== dependency if group.count > 1 { cycles.append(group.map({$0.declaration})) } } } // get goin' for dependency in dependencies { if dependency.index == nil { traverse(dependency) } } // done return cycles } // sort var stack = [Dependency]() for dependency in dependencyList { if dependency.inCount == 0 { stack.append(dependency) } } // for var count = 0 while !stack.isEmpty { let dependency = stack.removeFirst() dependency.index = count //print("\(index): \(dependency.declaration.bean!.clazz)") for successor in dependency.successors { successor.inCount -= 1 if successor.inCount == 0 { stack.append(successor) } } // for count += 1 } // while // if something is left, we have a cycle! if count < dependencyList.count { let cycles = detectCycles() let builder = StringBuilder() builder.append("\(cycles.count) cycles:") var index = 0 for cycle in cycles { builder.append("\n\(index): ") for declaration in cycle { builder.append(declaration).append(" ") } index += 1 } throw EnvironmentErrors.cylicDependencies(message: builder.toString()) } } func load() throws -> Environment { if (Tracer.ENABLED) { Tracer.trace("inject.loader", level: .high, message: "load \(context.name)") } loading = true try setup() // collect if (Tracer.ENABLED) { Tracer.trace("inject.loader", level: .high, message: "collect beans") } for dependency in dependencyList { try dependency.declaration.collect(context, loader: self) // define } // connect if (Tracer.ENABLED) { Tracer.trace("inject.loader", level: .high, message: "connect beans") } for dependency in dependencyList { try dependency.declaration.connect(self) } // sort if (Tracer.ENABLED) { Tracer.trace("inject.loader", level: .high, message: "sort beans") } try sortDependencies(dependencyList) // and resort local beans context.localBeans.sort(by: {dependencies[$0]!.index! < dependencies[$1]!.index!}) // resolve if (Tracer.ENABLED) { Tracer.trace("inject.loader", level: .high, message: "resolve beans") } for bean in context.localBeans { //let bean = dependency.declaration try bean.resolve(self) try bean.prepare(self) } // for // done return context } } class EnvironmentPostProcessor: NSObject, EnvironmentAware, BeanPostProcessor { // MARK: instance data var injector : Injector var _environment: Environment? var environment: Environment? { get { return _environment } set { _environment = newValue } } // init // needed by the BeanDescriptor override init() { self.injector = Injector() super.init() } init(environment: Environment) { self.injector = environment.injector self._environment = environment super.init() } // BeanPostProcessor func process(_ instance : AnyObject) throws -> AnyObject { if (Tracer.ENABLED) { Tracer.trace("inject.runtime", level: .high, message: "default post process a \"\(type(of: instance))\"") } // inject try injector.inject(instance, context: environment!) // check protocols // Bean if let bean = instance as? Bean { try bean.postConstruct() } // EnvironmentAware if var environmentAware = instance as? EnvironmentAware { environmentAware.environment = environment! } // done return instance } } // MARK: static data static let LOGGER = LogManager.getLogger(forClass: Environment.self) // MARK: instance data var traceOrigin = false var name : String = "" var loader : Loader? var parent : Environment? = nil var injector : Injector var configurationManager : ConfigurationManager var byType = [ObjectIdentifier : ArrayOf<BeanDeclaration>]() var byId = [String : BeanDeclaration]() var postProcessors = [BeanPostProcessor]() var scopes = [String:BeanScope]() var localBeans = [BeanDeclaration]() var singletonScope = SingletonScope() // MARK: init public init(name: String, parent : Environment? = nil, traceOrigin : Bool = false) throws { self.name = name self.traceOrigin = traceOrigin if parent != nil { self.parent = parent self.injector = parent!.injector self.configurationManager = parent!.configurationManager //self.singletonScope = parent!.singletonScope self.scopes = parent!.scopes self.byType = parent!.byType self.byId = parent!.byId loader = Loader(context: self) } else { // injector injector = Injector() // configuration manager configurationManager = try ConfigurationManager(scope: Scope.WILDCARD) // default scopes registerScope(PrototypeScope()) registerScope(singletonScope) // default injections injector.register(BeanInjection()) injector.register(ConfigurationValueInjection(configurationManager: configurationManager)) // set loader here in order to prevent exception due to frozen environment.. loader = Loader(context: self) // default post processor try define(bean(EnvironmentPostProcessor(environment: self))) // should be the first bean! // add initial bean declarations so that constructed objects can also refer to those instances try define(bean(injector)) try define(bean(configurationManager)) } } // MARK: public /// load a xl configuration file /// - Parameter data: a `NSData` object referencing the config file open func loadXML(_ data : Data) throws -> Self { try XMLEnvironmentLoader(environment: self) .parse(data) return self } /// startup validates all defined beans and creates all singletons in advance /// - Returns: self /// - Throws: any errors during setup open func startup() throws -> Self { if loader != nil { // check parent if parent != nil { try parent!.validate() inheritFrom(parent!) } Environment.LOGGER.info("startup environment \(name)") if (Tracer.ENABLED) { Tracer.trace("inject.runtime", level: .high, message: "startup \(name)") } // load try loader!.load() loader = nil // prevent double loading... } // if return self } /// register a named scope // - Parameter scope: the `BeanScope` open func registerScope(_ scope : BeanScope) -> Void { scopes[scope.name] = scope } // MARK: fluent interface /// Return a named scope /// - Parameter scope: the scope name /// - Throws: an error if the scope is not defined open func scope(_ scope : String) throws -> BeanScope { return try getScope(scope) } /// create a `BeanDeclaration` based on a already constructed object /// - Parameter instance: the corresponding instance /// - Parameter id: an optional id /// - Returns: the new `BeanDeclaration` open func bean(_ instance : AnyObject, id : String? = nil, file: String = #file, function: String = #function, line: Int = #line, column: Int = #column) -> Environment.BeanDeclaration { let result = Environment.BeanDeclaration(instance: instance) if id != nil { result.id = id } if traceOrigin { result.origin = Origin(file: file, line: line, column: column) } return result } /// create a `BeanDeclaration` /// - Parameter className: the name of the bean class /// - Parameter id: an optional id /// - Parameter lazy: the lazy attribute. default is `false` /// - Parameter abstract: the abstract attribute. default is `false` /// - Returns: the new `BeanDeclaration` open func bean(_ className : String, id : String? = nil, lazy : Bool = false, abstract : Bool = false, file: String = #file, function: String = #function, line: Int = #line, column: Int = #column) throws -> Environment.BeanDeclaration { let result = Environment.BeanDeclaration() if id != nil { result.id = id } if traceOrigin { result.origin = Origin(file: file, line: line, column: column) } result.lazy = lazy result.abstract = abstract result.clazz = try Classes.class4Name(className) return result } /// create a `BeanDeclaration` /// - Parameter clazz: the bean class /// - Parameter id: an optional id /// - Parameter lazy: the lazy attribute. default is `false` /// - Parameter abstract:t he abstract attribute. default is `false` /// - Parameter factory: a factory function that will return a new instance of the specific type /// - Returns: the new `BeanDeclaration` open func bean<T>(_ clazz : T.Type, id : String? = nil, lazy : Bool = false, abstract : Bool = false, file: String = #file, function: String = #function, line: Int = #line, column: Int = #column, factory : (() throws -> T)? = nil) throws -> Environment.BeanDeclaration { let result = Environment.BeanDeclaration() if id != nil { result.id = id } if traceOrigin { result.origin = Origin(file: file, line: line, column: column) } result.lazy = lazy result.abstract = abstract if factory != nil { result.factory = FactoryFactory<T>(factory: factory!) } if let anyClass = clazz as? AnyClass { result.clazz = anyClass } else { throw EnvironmentErrors.exception(message: "only classes are accepted, got \(clazz)") } return result } /// return a `Settings` instance tha can be used to define configuration values /// - Returns: a new `Settings` instance open func settings(_ file: String = #file, function: String = #function, line: Int = #line) -> Settings { return Settings(configurationManager: self.configurationManager, url: file + " " + function + " line: " + String(line)) } /// This class collects manual configuration values open class Settings : AbstractConfigurationSource { // MARK: instance data var items = [ConfigurationItem]() // MARK: init init(configurationManager : ConfigurationManager, url: String) { super.init(configurationManager: configurationManager, url: url) } // MARK:fluent interface open func setValue(_ namespace : String = "", key : String, value : Any) -> Self { items.append(ConfigurationItem( fqn: FQN(namespace: namespace, key: key), type: type(of: value), value: value, source: url )) return self } // MARK: implement ConfigurationSource override open func load(_ configurationManager : ConfigurationManager) throws -> Void { for item in items { try configurationManager.configurationAdded(item, source: self) } } } /// define configuration values /// - Parameter settings: the object that contains configuration values open func define(_ settings : Settings) throws -> Self { try configurationManager.addSource(settings) return self } /// defines the specified `BeanDeclaration` /// - Returns: self open func define(_ declaration : Environment.BeanDeclaration) throws -> Self { // fix scope if not available if declaration.scope == nil { declaration.scope = singletonScope } // pass to loader if set if loader != nil { try loader!.addDeclaration(declaration) } else { for line in Thread.callStackSymbols {print(line)} throw EnvironmentErrors.exception(message: "environment is frozen") } // remember id if declaration.id != nil { // doesn't matter if abstract or not try rememberId(declaration) } // remember by type for injections if !declaration.abstract { try rememberType(declaration) } // local beans localBeans.append(declaration) // done return self } // MARK: internal func inheritFrom(_ parent : Environment) { if (Tracer.ENABLED) { Tracer.trace("inject.loader", level: .high, message: "inherit from \(parent.name)") } self.postProcessors = parent.postProcessors // patch EnvironmentAware for declaration in parent.localBeans { if var environmentAware = declaration.singleton as? EnvironmentAware { // does not make sense for beans other than singletons... environmentAware.environment = self } } } func validate() throws { if loader != nil && !loader!.loading { try startup() } } func getScope(_ name : String) throws -> BeanScope { let scope = scopes[name] if scope == nil { throw EnvironmentErrors.unknownScope(scope: name, context: "") } else { return scope! } } func rememberId(_ declaration : Environment.BeanDeclaration) throws -> Void { if let id = declaration.id { if byId[id] == nil { byId[id] = declaration } else { throw EnvironmentErrors.ambiguousBeanById(id: id, context: "") } } } func rememberType(_ declaration : Environment.BeanDeclaration) throws -> Void { // remember by type for injections var clazz : AnyClass?; if let valueFactory = declaration.factory as? ValueFactory { clazz = type(of: valueFactory.object) } else { clazz = declaration.clazz // may be nil in case of a inherited bean! } // is that a factory bean? if clazz is FactoryBean.Type { let target : AnyClass? = declaration.target if target == nil { fatalError("missing target"); } // include artificial bean declaration with special scope let bean = BeanDeclaration() bean.scope = BeanFactoryScope(declaration : declaration, environment: self) bean.requires(bean: declaration) bean.clazz = target // remember try rememberType(bean) } // if if clazz != nil && !declaration.abstract { let declarations = byType[ObjectIdentifier(clazz!)] if declarations != nil { declarations!.append(declaration) } else { byType[ObjectIdentifier(clazz!)] = ArrayOf<Environment.BeanDeclaration>(values: declaration) } } } func getCandidate(_ type : Any.Type) throws -> Environment.BeanDeclaration { let candidates = getBeanDeclarationsByType(try BeanDescriptor.forType(type)) if candidates.count == 0 { throw EnvironmentErrors.noCandidateForType(type: type) } if candidates.count > 1 { throw EnvironmentErrors.ambiguousCandidatesForType(type: type) } else { return candidates[0] } } func runPostProcessors(_ instance : AnyObject) throws -> AnyObject { var result = instance // inject if (Tracer.ENABLED) { Tracer.trace("inject.runtime", level: .high, message: "run post processors on a \"\(type(of: result))\"") } for processor in postProcessors { result = try processor.process(result) } return result } func getDeclarationById(_ id : String) throws -> Environment.BeanDeclaration { let declaration = byId[id] if declaration == nil { throw EnvironmentErrors.unknownBeanById(id: id, context: "") } return declaration! } open func getBeanDeclarationsByType(_ type : Any.Type) -> [Environment.BeanDeclaration] { return getBeanDeclarationsByType(try! BeanDescriptor.forType(type)) } open func getBeanDeclarationsByType(_ bean : BeanDescriptor) -> [Environment.BeanDeclaration] { // local func func collect(_ bean : BeanDescriptor, candidates : inout [Environment.BeanDeclaration]) -> Void { let localCandidates = byType[ObjectIdentifier(bean.type)] if localCandidates != nil { for candidate in localCandidates! { if !candidate.abstract { candidates.append(candidate) } } } // check subclasses for subBean in bean.directSubBeans { collect(subBean, candidates: &candidates) } } var result : [Environment.BeanDeclaration] = [] collect(bean, candidates: &result) return result } // MARK: public /// Create a string report of all registered bean definitions /// - Returns: the report open func report() -> String { let builder = StringBuilder() builder.append("### ENVIRONMENT \(name) REPORT\n") for bean in localBeans { bean.report(builder) } return builder.toString() } /// return an array of all bean instances of a given type /// - Parameter type: the bean type /// - Returns: the array of instances /// - Throws: any errors open func getBeansByType<T>(_ type : T.Type) throws -> [T] { let declarations = getBeanDeclarationsByType(type) var result : [T] = [] for declaration in declarations { if !declaration.abstract { result.append(try declaration.getInstance(self) as! T) } } return result } /// return a bean given the type and an optional id /// - Parameter type: the type /// - Parameter id: an optional id /// - Returns: the instance /// - Throws: Any error open func getBean<T>(_ type : T.Type, byId id : String? = nil) throws -> T { try validate() if id != nil { if let bean = self.byId[id!] { return try bean.getInstance(self) as! T } else { throw EnvironmentErrors.unknownBeanById(id: id!, context: "") } } else { let result = getBeanDeclarationsByType(try BeanDescriptor.forType(type)) if result.count == 0 { throw EnvironmentErrors.unknownBeanByType(type: type) } else if result.count > 1 { throw EnvironmentErrors.ambiguousBeanByType(type: type) } else { return try result[0].getInstance(self) as! T } } } /// return a bean given the type and an optional id ( without generic parameters ) /// - Parameter type: the type /// - Parameter id: an optional id /// - Returns: the instance /// - Throws: Any error open func getBean(_ type : Any.Type, byId id : String? = nil) throws -> AnyObject { try validate() if id != nil { if let bean = self.byId[id!] { return try bean.getInstance(self) } else { throw EnvironmentErrors.unknownBeanById(id: id!, context: "") } } else { let result = getBeanDeclarationsByType(try BeanDescriptor.forType(type)) if result.count == 0 { throw EnvironmentErrors.unknownBeanByType(type: type ) } else if result.count > 1 { throw EnvironmentErrors.ambiguousBeanByType(type: type ) } else { return try result[0].getInstance(self) } } } open func inject(_ object : AnyObject) throws -> Void { try validate() try injector.inject(object, context: self) } /// return the `ConfigurationManager` of this environment /// - Returns: the `ConfigurationManager` open func getConfigurationManager() -> ConfigurationManager { return configurationManager } /// Add a new configuration source /// - Parameter source: a `ConfigurationSource` /// - Returns: self open func addConfigurationSource(_ source: ConfigurationSource) throws -> Environment { try configurationManager.addSource(source) return self } /// return a configuration value /// - Parameter type: the expected type /// - Parameter namespace: the namespace /// - Parameter key: the key /// - Parameter defaultValue: the optional default value /// - Parameter scope: the optional scope /// - Returns: the value /// - Throws: any possible error open func getConfigurationValue<T>(_ type : T.Type, namespace : String = "", key : String, defaultValue: T? = nil, scope : Scope? = nil) throws -> T { return try configurationManager.getValue(type, namespace: namespace, key: key, defaultValue: defaultValue, scope: scope) } // MARK: implement BeanFactory open func create(_ bean : Environment.BeanDeclaration) throws -> AnyObject { return try bean.create(self) } } func ==(lhs: Environment.Loader.Dependency, rhs: Environment.Loader.Dependency) -> Bool { return lhs === rhs }
mit
7d4cff442e7630042f86a518fd40bf29
29.834043
274
0.532156
5.267424
false
false
false
false
TTVS/NightOut
Clubber/MessengerTableViewControllerSwift.swift
1
25885
// // MessengerTableViewControllerSwift.swift // Clubber // // Created by Terra on 9/18/15. // Copyright (c) 2015 Dino Media Asia. All rights reserved. // import UIKit import CoreData import MessageDisplayKit class MessengerTableViewControllerSwift: XHMessageTableViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, NSFetchedResultsControllerDelegate, XHAudioPlayerHelperDelegate { var fetchedResultsController: NSFetchedResultsController! var managedObjectContext: NSManagedObjectContext! var emotionManagers = NSArray() var currentSelectedCell = XHMessageTableViewCell() @IBAction func back(sender: AnyObject) { if((self.presentingViewController) != nil){ self.dismissViewControllerAnimated(true, completion: nil) NSLog("back") } } override func viewDidLoad() { super.viewDidLoad() UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.LightContent UIApplication.sharedApplication().statusBarHidden = false self.setNeedsStatusBarAppearanceUpdate() self.messageSender = "Anonymous" self.navigationController?.interactivePopGestureRecognizer!.delaysTouchesBegan = false let messengerImage = UIImage(named: "avatar1")! let messengerFrame = CGRectMake(0, 0, 35, 35) let messageDetailButton: UIButton = UIButton(frame: messengerFrame) messageDetailButton.setBackgroundImage(messengerImage, forState: UIControlState.Normal) messageDetailButton.addTarget(self, action: "messageDetailButtonPressed:", forControlEvents: UIControlEvents.TouchUpInside) messageDetailButton.contentMode = UIViewContentMode.ScaleAspectFit // image = image?.imageWithRenderingMode(UIImageRenderingMode.AlwaysOriginal) let profileDetailBarButton: UIBarButtonItem = UIBarButtonItem(customView: messageDetailButton) self.navigationItem.rightBarButtonItem = profileDetailBarButton // var color0: UIColor = UIColor(red: (84/255.0), green: (81/255.0), blue: (139/255.0), alpha: 1.0) // var color1 = UIColor(red: (55/255.0), green: (53/255.0), blue: (92/255.0), alpha: 1.0) let viewColor = UIColor(red: (30/255.0), green: (30/255.0), blue: (30/255.0), alpha: 1.0) self.setBackgroundColor(viewColor) // self.setBackgroundImage(UIImage(named: "cityBase")) let shareMenuItems: NSMutableArray = [] // let plugIcons : NSArray = ["sharemore_pic", "sharemore_video", "sharemore_location", "sharemore_friendcard", "sharemore_myfav", "sharemore_wxtalk", "sharemore_videovoip", "sharemore_voiceinput", "sharemore_openapi", "sharemore_openapi", "avatar"] // let plugTitle : NSArray = ["照片", "拍摄", "位置", "名片", "我的收藏", "实时对讲机", "视频聊天", "语音输入", "大众点评", "应用", "曾宪华"] // // //Original Obj C Code // for (NSString *plugIcon in plugIcons) { // XHShareMenuItem *shareMenuItem = [[XHShareMenuItem alloc] initWithNormalIconImage:[UIImage imageNamed:plugIcon] title:[plugTitle objectAtIndex:[plugIcons indexOfObject:plugIcon]]]; // [shareMenuItems addObject:shareMenuItem]; // } // //Swift Code // for plugIcon: NSString in plugIcons { // var shareMenuItem: XHShareMenuItem = XHShareMenuItem(normalIconImage: UIImage(named: plugIcon), title: plugTitle.objectAtIndex(plugIcons.indexOfObject(plugIcon))) // shareMenuItems.addObject(shareMenuItem) // } //Temporary Share Menu let shareMenuItem1 = XHShareMenuItem(normalIconImage: UIImage(named: "sharemore_pic"), title: "Photos") let shareMenuItem2 = XHShareMenuItem(normalIconImage: UIImage(named: "sharemore_video"), title: "Camera") shareMenuItems.addObject(shareMenuItem1) shareMenuItems.addObject(shareMenuItem2) //Emotions Manager let emotionManagers: NSMutableArray = [] for var i = 0; i < 10; i++ { let emotionManager = XHEmotionManager() emotionManager.emotionName = "表情\(i)" let emotions: NSMutableArray = [] for var j = 0; j < 32; j++ { let emotion = XHEmotion() let imageName = UIImage(named: "section\(i)_emotion\(j % 16)") emotion.emotionPath = NSBundle.mainBundle().pathForResource("Demo\(j % 2).gif", ofType: "") emotion.emotionConverPhoto = imageName emotions.addObject(emotion) } emotionManager.emotions = emotions emotionManagers.addObject(emotionManager) } self.emotionManagers = emotionManagers self.emotionManagerView!.reloadData() self.shareMenuItems = shareMenuItems as [AnyObject] self.shareMenuView!.reloadData() } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) XHAudioPlayerHelper.shareInstance().stopAudio UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.LightContent UIApplication.sharedApplication().statusBarHidden = false self.setNeedsStatusBarAppearanceUpdate() } // MARK: - Message Detail Button Pressed func messageDetailButtonPressed(sender:UIButton!) { print("messageDetailButtonPressed tapped") let profileDetailViewController: UIViewController = UIViewController() profileDetailViewController.view.backgroundColor = UIColor.greenColor() self.navigationController!.pushViewController(profileDetailViewController, animated: true) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // ImagePickerSheetController (like iMessage) // override func didSelectedMultipleMediaAction() { // let presentImagePickerController: UIImagePickerControllerSourceType -> () = { source in // let controller = UIImagePickerController() // controller.delegate = self // var sourceType = source // if (!UIImagePickerController.isSourceTypeAvailable(sourceType)) { // sourceType = .PhotoLibrary // print("Fallback to camera roll as a source since the simulator doesn't support taking pictures") // } // controller.sourceType = sourceType // // self.presentViewController(controller, animated: true, completion: nil) // } // // let controller = ImagePickerSheetController(mediaType: .ImageAndVideo) // controller.addAction(ImagePickerAction(title: NSLocalizedString("Take Photo Or Video", comment: "Action Title"), secondaryTitle: NSLocalizedString("Add comment", comment: "Action Title"), handler: { _ in // presentImagePickerController(.Camera) // }, secondaryHandler: { _, numberOfPhotos in // print("Comment \(numberOfPhotos) photos") // })) // controller.addAction(ImagePickerAction(title: NSLocalizedString("Photo Library", comment: "Action Title"), secondaryTitle: { NSString.localizedStringWithFormat(NSLocalizedString("ImagePickerSheet.button1.Send %lu Photo", comment: "Action Title"), $0) as String}, handler: { _ in // presentImagePickerController(.PhotoLibrary) // }, secondaryHandler: { _, numberOfPhotos in // print("Send \(controller.selectedImageAssets)") // })) // controller.addAction(ImagePickerAction(title: NSLocalizedString("Cancel", comment: "Action Title"), style: .Cancel, handler: { _ in // print("Cancelled") // })) // // if UIDevice.currentDevice().userInterfaceIdiom == .Pad { // controller.modalPresentationStyle = .Popover // controller.popoverPresentationController?.sourceView = view // controller.popoverPresentationController?.sourceRect = CGRect(origin: view.center, size: CGSize()) // } // // presentViewController(controller, animated: true, completion: nil) // // self.layoutOtherMenuViewHiden(false) // } // MARK: - XHMessageTableViewCell Delegate override func multiMediaMessageDidSelectedOnMessage(message: XHMessageModel, atIndexPath indexPath: NSIndexPath, onMessageTableViewCell messageTableViewCell: XHMessageTableViewCell) { var disPlayViewController: UIViewController = UIViewController() switch message.messageMediaType() { case XHBubbleMessageMediaType.Video: NSLog("message : %@", message.videoConverPhoto()) let messageDisplayTextView: XHDisplayMediaViewController = XHDisplayMediaViewController() messageDisplayTextView.message = message disPlayViewController = messageDisplayTextView disPlayViewController.view.backgroundColor = UIColor.blackColor() self.navigationController?.view.tintColor = UIColor.whiteColor() self.navigationController!.pushViewController(disPlayViewController, animated: true) break case XHBubbleMessageMediaType.Photo: NSLog("message : %@", message.photo()) let messageDisplayTextView: XHDisplayMediaViewController = XHDisplayMediaViewController() messageDisplayTextView.message = message disPlayViewController = messageDisplayTextView disPlayViewController.view.backgroundColor = UIColor.blackColor() self.navigationController?.view.tintColor = UIColor.whiteColor() self.navigationController!.pushViewController(disPlayViewController, animated: true) break case XHBubbleMessageMediaType.Voice: NSLog("message : %@", message.voicePath()) //// var hasBeenRead = message.isRead!() // message.isRead!() //// hasBeenRead = true // messageTableViewCell.messageBubbleView?.voiceUnreadDotImageView?.hidden = true // // XHAudioPlayerHelper.shareInstance() //// XHAudioPlayerHelper.shareInstance().delegate(self) // if self == currentSelectedCell { // currentSelectedCell.messageBubbleView?.animationVoiceImageView?.stopAnimating() // } // if currentSelectedCell == messageTableViewCell { // messageTableViewCell.messageBubbleView?.animationVoiceImageView?.stopAnimating() // messageTableViewCell.messageBubbleView?.animationVoiceImageView?.performSelector("stopAnimating", withObject: nil, afterDelay: 3) // XHAudioPlayerHelper.shareInstance().stopAudio() //// self.currentSelectedCell = nil // } // else { self.currentSelectedCell = messageTableViewCell messageTableViewCell.messageBubbleView?.animationVoiceImageView?.startAnimating() XHAudioPlayerHelper.shareInstance().managerAudioWithFileName(message.voicePath(), toPlay: true) messageTableViewCell.messageBubbleView?.animationVoiceImageView?.performSelector("stopAnimating", withObject: nil, afterDelay: 3) // } break case XHBubbleMessageMediaType.Emotion: NSLog("facePath : %@", message.emotionPath()) break case XHBubbleMessageMediaType.LocalPosition: NSLog("facePath : %@", message.localPositionPhoto()) let displayLocationViewController: XHDisplayLocationViewController = XHDisplayLocationViewController() displayLocationViewController.message = message disPlayViewController = displayLocationViewController disPlayViewController.view.backgroundColor = UIColor.blackColor() self.navigationController?.view.tintColor = UIColor.whiteColor() self.navigationController!.pushViewController(disPlayViewController, animated: true) break default: break } } // override func didDoubleSelectedOnTextMessage(message: XHMessageModel, atIndexPath indexPath: NSIndexPath) { // NSLog("text : %@", message.text()) // let displayTextViewController = XHDisplayTextViewController() // displayTextViewController.message = message // // self.navigationController!.pushViewController(displayTextViewController, animated: true) // } override func didSelectedAvatarOnMessage(message: XHMessageModel, atIndexPath indexPath: NSIndexPath) { NSLog("indexPath : %@", indexPath) } override func menuDidSelectedAtBubbleMessageMenuSelecteType(bubbleMessageMenuSelecteType: XHBubbleMessageMenuSelecteType) { } // MARK: - XHAudioPlayerHelper Delegate func didAudioPlayerStopPlay(audioPlayer: AVAudioPlayer) { if currentSelectedCell == self { return } currentSelectedCell.messageBubbleView?.animationVoiceImageView?.stopAnimating() // self.currentSelectedCell = nil } // MARK: - XHEmotionManagerView DataSource override func numberOfEmotionManagers() -> Int { return self.emotionManagers.count } override func emotionManagerForColumn(column: Int) -> XHEmotionManager { return self.emotionManagers.objectAtIndex(column) as! XHEmotionManager } override func emotionManagersAtManager() -> [AnyObject] { return self.emotionManagers as [AnyObject] } // MARK: - XHMessageTableViewController DataSource // override func messageForRowAtIndexPath(indexPath: NSIndexPath!) -> XHMessageModel! { //// var message: MDKMessage = self.fetchedResultsController.objectAtIndexPath(indexPath) // var currentMessage: XHMessage = XHMessage() //// currentMessage.sender = message.sender //// currentMessage.timestamp = message.timestamp //// currentMessage.text = message.text // // // currentMessage.sender = "Melissa" // currentMessage.timestamp = NSDate() // currentMessage.text = "Lets hang out!" // // return currentMessage // // } // // override func numberOfSectionsInTableView(tableView: UITableView) -> Int { //// return self.fetchedResultsController.sections().count() // return 1 // } // // override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { //// var sectionInfo: NSFetchedResultsSectionInfo = self.fetchedResultsController.sections()[section] //// return sectionInfo.numberOfObjects() // return 3 // } // // override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // return true // } // //// override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { //// if editingStyle == UITableViewCellEditingStyle.Delete { //// var context: NSManagedObjectContext = self.fetchedResultsController.managedObjectContext() //// context.deleteObject(self.fetchedResultsController.objectAtIndexPath(indexPath)) //// var error: NSErrorPointer? = nil //// if !context.save(&error) { //// NSLog("Unresolved error %@, %@", error, error.userInfo()) //// abort() //// } //// } //// } // // override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // return false // } // // MARK: - NSFetch Helper Method // func insertNewObject(message: XHMessage) { // var context: NSManagedObjectContext = self.fetchedResultsController.managedObjectContext // var entity: NSEntityDescription = self.fetchedResultsController.fetchRequest.entity! // var newManagedObject: NSManagedObject = NSEntityDescription.insertNewObjectForEntityForName(entity.name!, inManagedObjectContext: context) as! NSManagedObject // newManagedObject.setValue(message.timestamp, forKey: "timestamp") // newManagedObject.setValue(message.sender, forKeyPath: "sender") // newManagedObject.setValue(message.text, forKeyPath: "text") // var error: NSErrorPointer? = nil // if context.save(error!) { // NSLog("Unresolved error %@, %@", error!) //// NSLog("Unresolved error %@, %@", error, error.userInfo()) // abort() // } // } // // // MARK: - Fetched Results Controller // func fetchedResultsController() -> NSFetchedResultsController { // if fetchedResultsController != nil { // return _fetchedResultsController // } // var fetchRequest: NSFetchRequest = NSFetchRequest() // var entity: NSEntityDescription = NSEntityDescription.entityForName("MDKMessage", inManagedObjectContext: self.managedObjectContext)! // fetchRequest.setEntity(entity) // fetchRequest.setFetchBatchSize(20) // var sortDescriptor: NSSortDescriptor = NSSortDescriptor(key: "timestamp", ascending: false) // var sortDescriptors: [AnyObject] = [sortDescriptor] // fetchRequest.setSortDescriptors(sortDescriptors) // var aFetchedResultsController: NSFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedObjectContext, sectionNameKeyPath: nil, cacheName: "Master") // aFetchedResultsController.delegate = self // self.fetchedResultsController = aFetchedResultsController // var error: NSErrorPointer? = nil // if !self.fetchedResultsController.performFetch(&error) { // NSLog("Unresolved error %@, %@", error, error.userInfo()) // abort() // } // return _fetchedResultsController // } // // func controllerWillChangeContent(controller: NSFetchedResultsController) { // self.messageTableView.beginUpdates() // } // // func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: UInt, forChangeType type: NSFetchedResultsChangeType) { // switch type { // case NSFetchedResultsChangeInsert: // self.messageTableView.insertSections(NSIndexSet.indexSetWithIndex(sectionIndex), withRowAnimation: UITableViewRowAnimationFade) // case NSFetchedResultsChangeDelete: // self.messageTableView.deleteSections(NSIndexSet.indexSetWithIndex(sectionIndex), withRowAnimation: UITableViewRowAnimationFade) // default: // break // } // } // // func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) { // var tableView: UITableView = self.messageTableView // switch type { // case NSFetchedResultsChangeInsert: // tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: UITableViewRowAnimationFade) // case NSFetchedResultsChangeDelete: // tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimationFade) // case NSFetchedResultsChangeUpdate: // self.configureCell(tableView.cellForRowAtIndexPath(indexPath!), atIndexPath: indexPath) // case NSFetchedResultsChangeMove: // tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimationFade) // tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: UITableViewRowAnimationFade) // } // } // // func controllerDidChangeContent(controller: NSFetchedResultsController) { // self.messageTableView.endUpdates() // } // MARK: - XHMessageTableViewController Delegate override func shouldLoadMoreMessagesScrollToTop() -> Bool { return true } // override func loadMoreMessagesScrollTotop() { // if !self.loadingMoreMessage { // self.loadingMoreMessage = true // // // // let qualityOfServiceClass = QOS_CLASS_BACKGROUND // let backgroundQueue = dispatch_get_global_queue(qualityOfServiceClass, 0) // dispatch_async(backgroundQueue, { // // var messages: [AnyObject] = self.getTestMessages() // // println("This is run on the background queue") // // dispatch_async(dispatch_get_main_queue(), { () -> Void in // // self.insertOldMessages(messages) // self.loadingMoreMessage = false // // println("This is run on the main queue, after the previous code in outer block") // }) // }) // } override func didSendText(text: String, fromSender sender: String, onDate date: NSDate) { let textMessage: XHMessage = XHMessage(text: text, sender: sender, timestamp: date) textMessage.avatar = UIImage(named: "avatar1") self.addMessage(textMessage) self.finishSendMessageWithBubbleMessageType(XHBubbleMessageMediaType.Text) UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.LightContent UIApplication.sharedApplication().statusBarHidden = false self.setNeedsStatusBarAppearanceUpdate() } override func didSendPhoto(photo: UIImage, fromSender sender: String, onDate date: NSDate) { let photoMessage: XHMessage = XHMessage(photo: photo, thumbnailUrl: nil, originPhotoUrl: nil, sender: sender, timestamp: date) photoMessage.avatar = UIImage(named: "avatar1") self.addMessage(photoMessage) self.finishSendMessageWithBubbleMessageType(XHBubbleMessageMediaType.Photo) } override func didSendVideoConverPhoto(videoConverPhoto: UIImage, videoPath: String, fromSender sender: String, onDate date: NSDate) { let videoMessage: XHMessage = XHMessage(videoConverPhoto: videoConverPhoto, videoPath: videoPath, videoUrl: nil, sender: sender, timestamp: date) videoMessage.avatar = UIImage(named: "avatar1") self.addMessage(videoMessage) self.finishSendMessageWithBubbleMessageType(XHBubbleMessageMediaType.Video) } override func didSendVoice(voicePath: String, voiceDuration: String, fromSender sender: String, onDate date: NSDate) { let voiceMessage: XHMessage = XHMessage(voicePath: voicePath, voiceUrl: nil, voiceDuration: voiceDuration, sender: sender, timestamp: date) voiceMessage.avatar = UIImage(named: "avatar1") self.addMessage(voiceMessage) self.finishSendMessageWithBubbleMessageType(XHBubbleMessageMediaType.Voice) } override func didSendEmotion(emotionPath: String, fromSender sender: String, onDate date: NSDate) { if self == emotionPath { let emotionMessage: XHMessage = XHMessage(emotionPath: emotionPath, sender: sender, timestamp: date) emotionMessage.avatar = UIImage(named: "avatar1") self.addMessage(emotionMessage) self.finishSendMessageWithBubbleMessageType(XHBubbleMessageMediaType.Emotion) } else { let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "Click", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) } } override func didSendGeoLocationsPhoto(geoLocationsPhoto: UIImage, geolocations: String, location: CLLocation, fromSender sender: String, onDate date: NSDate) { let geoLocationsMessage: XHMessage = XHMessage(localPositionPhoto: geoLocationsPhoto, geolocations: geolocations, location: location, sender: sender, timestamp: date) geoLocationsMessage.avatar = UIImage(named: "avatar1") self.addMessage(geoLocationsMessage) self.finishSendMessageWithBubbleMessageType(XHBubbleMessageMediaType.LocalPosition) } override func shouldDisplayTimestampForRowAtIndexPath(indexPath: NSIndexPath) -> Bool { // if indexPath.row == 0 { // return true // } else { // return false // } if indexPath.row == 0 || indexPath.row >= self.messages.count { return true } else { let message = self.messages.objectAtIndex(indexPath.row) as! XHMessage let previousMessage = self.messages.objectAtIndex(indexPath.row - 1) as! XHMessage let interval: Double = message.timestamp.timeIntervalSinceDate(previousMessage.timestamp) if interval > 60 * 3 { return true } else { return false } } } override func configureCell(cell: XHMessageTableViewCell, atIndexPath indexPath: NSIndexPath) { cell.messageBubbleView!.displayTextView!.textColor = UIColor(red: (50/255.0), green: (50/255.0), blue: (50/255.0), alpha: 1.0) } override func shouldPreventScrollToBottomWhileUserScrolling() -> Bool { return true } }
apache-2.0
54f790ea9cb459d14c2bd035983e45aa
46.450368
288
0.665091
5.296061
false
false
false
false
mlibai/XZKit
Projects/Example/XZKitExample/XZKitExample/XZKitExample/Code/SegmentedBar.swift
1
8592
// // SegmentedBar.swift // XZKit // // Created by mlibai on 2017/7/14. // Copyright © 2017年 mlibai. All rights reserved. // import UIKit extension SegmentedBar { /// 1. 可接收点击事件,供 SegmentedBar 使用。 /// 2. 点击事件需对外隐藏。 /// 3. 尽量让使用者去布局视图。 @objc(XZSegmentedBarItemView) open class ItemView: UIView { @objc(XZSegmentedBarItemViewContentView) private class ContentView: UIControl { } let contentView: UIView = ContentView() public override init(frame: CGRect) { super.init(frame: frame) contentView.autoresizingMask = [.flexibleWidth, .flexibleHeight] contentView.frame = bounds addSubview(contentView) (contentView as! ContentView).addTarget(self, action: #selector(buttonAction(_:)), for: .touchUpInside) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } fileprivate weak var delegate: SegmentedBarItemViewDelegate? @objc private func buttonAction(_ button: UIButton) { delegate?.itemViewWasTouchedUpInside(self) } fileprivate var index: Int = 0 // 是否处于选中状态 open var isSelected: Bool { get { return (contentView as! ContentView).isSelected } set { (contentView as! ContentView).isSelected = newValue } } } } @objc(XZSegmentedBarDelegate) public protocol SegmentedBarDelegate: class { /// SegmentedBar 获取每个 item 的宽度。请返回大于 0 的数,否则使用默认设置。 /// /// - Parameters: /// - segmentedBar: SegmentedBar /// - index: index of the item /// - Returns: the item's width func segmentedBar(_ segmentedBar: SegmentedBar, widthForItemAt index: Int) -> CGFloat /// 当 SegmentedBar 被点击时,触发了选中的 item 变更事件。 /// /// - Parameters: /// - segmentedBar: SegmentedBar /// - index: the new selected index func segmentedBar(_ segmentedBar: SegmentedBar, didSelectItemAt index: Int) } @objc(XZSegmentedBarDataSource) public protocol SegmentedBarDataSource: class { /// SegmentedBar 获取要显示 item 的个数。 /// /// - Parameter segmentedBar: SegmentedBar /// - Returns: the count of item in SegmentedBar func numberOfItemsInSegmentedBar(_ segmentedBar: SegmentedBar) -> Int /// SegmentedBar 获取指定位置的 item 视图。 /// /// - Parameters: /// - segmentedBar: SegmentedBar /// - index: the index of the view /// - view: the view may be reused /// - Returns: the item view to be displayed func segmentedBar(_ segmentedBar: SegmentedBar, viewForItemAt index: Int, reusing view: SegmentedBar.ItemView?) -> SegmentedBar.ItemView } @objc(XZSegmentedBar) open class SegmentedBar: UIView { open weak var dataSource: SegmentedBarDataSource? open weak var delegate: SegmentedBarDelegate? /// 默认宽度 44.0 open var itemWidth: CGFloat = 44.0 /// 指示器高度,暂不支持。 open var indicatorHeight: CGFloat = 0.0 var itemViews: [ItemView] = [] /// 内部可滚动的 scrollView public let scrollView: UIScrollView = UIScrollView() // MARK: - 初始化 public override init(frame: CGRect) { super.init(frame: frame) didInitialize() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) didInitialize() } private func didInitialize() { scrollView.showsVerticalScrollIndicator = false scrollView.showsHorizontalScrollIndicator = false scrollView.frame = self.bounds scrollView.autoresizingMask = [.flexibleWidth, .flexibleHeight] addSubview(scrollView) } // MARK: 布局 func removeAllItemViews() { for itemView in itemViews { itemView.removeFromSuperview() } itemViews.removeAll() } open override func layoutSubviews() { super.layoutSubviews() let kBounds = self.bounds guard let dataSource = self.dataSource else { removeAllItemViews() return } let numberOfItems = dataSource.numberOfItemsInSegmentedBar(self) // 1. 没有 guard numberOfItems > 0 else { removeAllItemViews() return } // 2. 数量发生变化 if numberOfItems < itemViews.count { for _ in numberOfItems ..< itemViews.count { itemViews.last?.removeFromSuperview() itemViews.removeLast() } } // 3. 获取宽度 var itemWidths: [CGFloat] = [] var maxX: CGFloat = 0 for index in 0 ..< numberOfItems { var itemWidth = self.itemWidth; if let width = delegate?.segmentedBar(self, widthForItemAt: index) { if width > 0 { itemWidth = width; } } itemWidths.append(itemWidth) maxX += itemWidth } maxX = max(kBounds.width, maxX) // 4. 设置内容区域 scrollView.contentSize = CGSize(width: maxX, height: kBounds.height) // 5. 子视图 for index in 0 ..< numberOfItems { var itemView: ItemView! = nil if index < itemViews.count { itemView = dataSource.segmentedBar(self, viewForItemAt: index, reusing: itemViews[index]) if itemViews[index] != itemView { itemViews.remove(at: index) itemViews.insert(itemView, at: index) } } else { itemView = dataSource.segmentedBar(self, viewForItemAt: index, reusing: nil) itemViews.append(itemView) } let itemWidth = itemWidths[index] maxX -= itemWidth itemView.frame = CGRect(x: maxX, y: 0, width: itemWidth, height: kBounds.height - indicatorHeight) scrollView.addSubview(itemView) itemView.index = index itemView.delegate = self } moveSelectedItemViewToCenter() } fileprivate weak var selectedItemView: ItemView? { didSet { guard oldValue != selectedItemView else { return } oldValue?.isSelected = false selectedItemView?.isSelected = true } } /// 当前选中的索引 open var selectedIndex: Int? { get { return selectedItemView?.index } set { var itemView: ItemView? = nil if let index = newValue { if itemViews.isEmpty { layoutIfNeeded() } itemView = itemViews[index] } self.selectedItemView = itemView moveSelectedItemViewToCenter() } } func moveSelectedItemViewToCenter() { if let point = selectedItemView?.center { let viewWidth = scrollView.bounds.width let minX: CGFloat = 0 let maxX: CGFloat = scrollView.contentSize.width - viewWidth let asmX: CGFloat = point.x - viewWidth * 0.5 let offset = CGPoint(x: min(maxX, max(minX, asmX)), y: 0) scrollView.setContentOffset(offset, animated: true) } else { scrollView.setContentOffset(.zero, animated: true) } } /// 刷新数据 open func reloadData() { setNeedsLayout() layoutIfNeeded() } } extension SegmentedBar: SegmentedBarItemViewDelegate { func itemViewWasTouchedUpInside(_ itemView: SegmentedBar.ItemView) { guard selectedItemView != itemView else { return } selectedItemView = itemView moveSelectedItemViewToCenter() delegate?.segmentedBar(self, didSelectItemAt: itemView.index) } } fileprivate protocol SegmentedBarItemViewDelegate: class { func itemViewWasTouchedUpInside(_ itemView: SegmentedBar.ItemView) }
mit
5e2485a2e917459ea65835111de9c56f
28.419929
140
0.570098
5.074893
false
false
false
false
dokun1/Lumina
Sources/Lumina/UI/Extensions/ViewControllerFocusHandlerExtension.swift
1
1734
// // ViewControllerFocusHandlerExtension.swift // Lumina // // Created by David Okun on 11/20/17. // Copyright © 2017 David Okun. All rights reserved. // import UIKit import CoreGraphics extension LuminaViewController { func focusCamera(at point: CGPoint) { if self.isUpdating == true { return } else { self.isUpdating = true } let focusX = point.x/UIScreen.main.bounds.size.width let focusY = point.y/UIScreen.main.bounds.size.height guard let camera = self.camera else { return } LuminaLogger.notice(message: "Attempting focus at (\(focusX), \(focusY))") camera.handleFocus(at: CGPoint(x: focusX, y: focusY)) showFocusView(at: point) let deadlineTime = DispatchTime.now() + .seconds(1) DispatchQueue.main.asyncAfter(deadline: deadlineTime) { camera.resetCameraToContinuousExposureAndFocus() } } private func showFocusView(at point: CGPoint) { let focusView: UIImageView = UIImageView(image: UIImage(systemName: "camera.metering.partial")?.withTintColor(.white, renderingMode: .alwaysOriginal)) focusView.contentMode = .scaleAspectFit focusView.frame = CGRect(x: 0, y: 0, width: 50, height: 50) focusView.transform = CGAffineTransform(scaleX: 1.7, y: 1.7) focusView.center = point focusView.alpha = 0.0 self.view.addSubview(focusView) UIView.animate(withDuration: 0.3, animations: { focusView.alpha = 1.0 focusView.transform = CGAffineTransform(scaleX: 1.0, y: 1.0) }, completion: { _ in UIView.animate(withDuration: 1.0, animations: { focusView.alpha = 0.0 }, completion: { _ in focusView.removeFromSuperview() self.isUpdating = false }) }) } }
mit
fd8177ce8e395e888a766125f143d4da
31.698113
154
0.677438
3.920814
false
false
false
false
MTTHWBSH/Short-Daily-Devotions
Short Daily Devotions/View Models/PostsViewModel.swift
1
2709
// // PostsViewModel.swift // Short Daily Devotions // // Created by Matt Bush on 10/21/16. // Copyright © 2016 Matt Bush. All rights reserved. // import Alamofire class PostsViewModel: ViewModel { private var posts: [Post] private var currentPage = 1 var postsURL: String var allPostsLoaded = false init(postsURL: String) { self.posts = [] self.postsURL = postsURL super.init() self.loadPosts(postsURL: postsURL, page: 1, refresh: false, completion: nil) } func loadPosts(postsURL: String, page: Int, refresh: Bool, completion: ((Bool) -> Void)?) { let params: [String: Any] = ["page": page] Alamofire.request(postsURL, parameters: params) .responseJSON { [weak self] response in guard let data = response.data, let json = try? JSONSerialization.jsonObject(with: data, options: []), let posts = json as? NSArray else { completion?(false); return } self?.unwrap(postArray: posts, refresh: refresh) completion?(posts.count >= 1 ? true : false) } } private func unwrap(postArray: NSArray, refresh: Bool) { if postArray.count <= 0 { allPostsLoaded = true; return } if refresh { posts = [] } postArray.forEach { json in guard let postDict = json as? NSDictionary, let post = Post.from(postDict) else { return } posts.append(post) } render?() } // MARK: Post Helpers func latestPost() -> Post? { return posts.first ?? nil } func nextPageOfPosts(completion: ((Void) -> Void)?) { let nextPage = currentPage + 1 loadPosts(postsURL: postsURL, page: nextPage, refresh: false) { [weak self] morePosts in guard let strongSelf = self else { return } strongSelf.currentPage = morePosts ? nextPage : strongSelf.currentPage completion?() } } func postViewModel(forPost post: Post) -> PostViewModel { return PostViewModel(post: post) } func post(forIndexPath idx: IndexPath) -> Post { return posts[idx.row] } // MARK: Archive TableView DataSource func numberOfPosts() -> Int { return posts.count } func cell(forIndexPath indexPath: IndexPath) -> UITableViewCell { let post = posts[indexPath.row] let viewModel = postViewModel(forPost: post) return PostExcerptCell(title: viewModel.titleString, date: viewModel.dateString, excerpt: viewModel.excerptString) } }
mit
76467650d5047393ac11d3e3d2d7965c
30.858824
96
0.583456
4.490879
false
false
false
false
xcodeswift/xcproj
Tests/XcodeProjTests/Objects/SwiftPackage/XCRemoteSwiftPackageReferenceTests.swift
1
4845
import Foundation import XCTest @testable import XcodeProj final class XCRemoteSwiftPackageReferenceTests: XCTestCase { func test_init() throws { // Given let decoder = XcodeprojPropertyListDecoder() let plist: [String: Any] = ["reference": "ref", "repositoryURL": "url", "requirement": [ "kind": "revision", "revision": "abc", ]] let data = try PropertyListSerialization.data(fromPropertyList: plist, format: .xml, options: 0) // When let got = try decoder.decode(XCRemoteSwiftPackageReference.self, from: data) // Then XCTAssertEqual(got.reference.value, "ref") XCTAssertEqual(got.repositoryURL, "url") XCTAssertEqual(got.versionRequirement, XCRemoteSwiftPackageReference.VersionRequirement.revision("abc")) } func test_versionRequirement_returnsTheRightPlistValues_when_revision() throws { // When let subject = XCRemoteSwiftPackageReference.VersionRequirement.revision("sha") // Given let got = subject.plistValues() // Then XCTAssertEqual(got, [ "kind": "revision", "revision": .string(.init("sha")), ]) } func test_versionRequirement_returnsTheRightPlistValues_when_branch() throws { // When let subject = XCRemoteSwiftPackageReference.VersionRequirement.branch("master") // Given let got = subject.plistValues() // Then XCTAssertEqual(got, [ "kind": "branch", "branch": .string(.init("master")), ]) } func test_versionRequirement_returnsTheRightPlistValues_when_exact() throws { // When let subject = XCRemoteSwiftPackageReference.VersionRequirement.exact("3.2.1") // Given let got = subject.plistValues() // Then XCTAssertEqual(got, [ "kind": "exactVersion", "version": .string(.init("3.2.1")), ]) } func test_versionRequirement_returnsTheRightPlistValues_when_upToNextMajorVersion() throws { // When let subject = XCRemoteSwiftPackageReference.VersionRequirement.upToNextMajorVersion("3.2.1") // Given let got = subject.plistValues() // Then XCTAssertEqual(got, [ "kind": "upToNextMajorVersion", "minimumVersion": .string(.init("3.2.1")), ]) } func test_versionRequirement_returnsTheRightPlistValues_when_range() throws { // When let subject = XCRemoteSwiftPackageReference.VersionRequirement.range(from: "3.2.1", to: "4.0.0") // Given let got = subject.plistValues() // Then XCTAssertEqual(got, [ "kind": "versionRange", "minimumVersion": .string(.init("3.2.1")), "maximumVersion": .string(.init("4.0.0")), ]) } func test_versionRequirement_returnsTheRightPlistValues_when_upToNextMinorVersion() throws { // When let subject = XCRemoteSwiftPackageReference.VersionRequirement.upToNextMinorVersion("3.2.1") // Given let got = subject.plistValues() // Then XCTAssertEqual(got, [ "kind": "upToNextMinorVersion", "minimumVersion": .string(.init("3.2.1")), ]) } func test_plistValues() throws { // When let proj = PBXProj() let subject = XCRemoteSwiftPackageReference(repositoryURL: "repository", versionRequirement: .exact("1.2.3")) // Given let got = try subject.plistKeyAndValue(proj: proj, reference: "ref") // Then XCTAssertEqual(got.value, .dictionary([ "isa": "XCRemoteSwiftPackageReference", "repositoryURL": "repository", "requirement": .dictionary([ "kind": "exactVersion", "version": "1.2.3", ]), ])) } func test_equal() { // When let first = XCRemoteSwiftPackageReference(repositoryURL: "repository", versionRequirement: .exact("1.2.3")) let second = XCRemoteSwiftPackageReference(repositoryURL: "repository", versionRequirement: .exact("1.2.3")) // Then XCTAssertEqual(first, second) } func test_name() { // When let subject = XCRemoteSwiftPackageReference(repositoryURL: "https://github.com/tuist/xcodeproj", versionRequirement: nil) // Then XCTAssertEqual(subject.name, "xcodeproj") } }
mit
594ecf2d8bd461ed63124da4a27ec0c4
31.3
129
0.561816
5.083945
false
true
false
false
knorrium/OnTheMap
OnTheMap/LocationsClient.swift
1
3833
// // LocationsClient.swift // OnTheMap // // Created by Felipe Kuhn on 1/25/16. // Copyright © 2016 Knorrium. All rights reserved. // import UIKit class LocationsClient: NSObject { let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate static let sharedInstance = LocationsClient() var session: NSURLSession override init() { session = NSURLSession.sharedSession() super.init() } func fetchLocations(completionHandler: (success: Bool, errorMessage: String?) -> Void) { let request = NSMutableURLRequest(URL: NSURL(string: "https://api.parse.com/1/classes/StudentLocation?order=-updatedAt")!) request.addValue("QrX47CA9cyuGewLdsL7o5Eb8iug6Em8ye0dnAbIr", forHTTPHeaderField: "X-Parse-Application-Id") request.addValue("QuWThTdiRmTux3YaDseUSEpUKo7aBYM737yKd4gY", forHTTPHeaderField: "X-Parse-REST-API-Key") let session = NSURLSession.sharedSession() let task = session.dataTaskWithRequest(request) { data, response, error in if error != nil { completionHandler(success: false, errorMessage: "There was an error while fetching the location data") } else { let parsedResult: AnyObject! do { parsedResult = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) if let location = parsedResult["results"] as? [NSDictionary] { for studentInfo in location { let student = StudentInformation.init(dictionary: studentInfo) StudentLocations.students.append(student) } } else { completionHandler(success: false, errorMessage: "There was a problem with the server response. Please reach out to the developers :)") } completionHandler(success: true, errorMessage: nil) } catch { completionHandler(success: false, errorMessage: "Error parsing JSON data") } } } task.resume() } func postLocation(student: StudentInformation, completionHandler: (success: Bool, errorMessage: String?) -> Void) { let request = NSMutableURLRequest(URL: NSURL(string: "https://api.parse.com/1/classes/StudentLocation")!) request.HTTPMethod = "POST" request.addValue("QrX47CA9cyuGewLdsL7o5Eb8iug6Em8ye0dnAbIr", forHTTPHeaderField: "X-Parse-Application-Id") request.addValue("QuWThTdiRmTux3YaDseUSEpUKo7aBYM737yKd4gY", forHTTPHeaderField: "X-Parse-REST-API-Key") request.addValue("application/json", forHTTPHeaderField: "Content-Type") request.HTTPBody = "{\"uniqueKey\" : \"\(student.uniqueKey)\", \"firstName\" : \"\(student.firstName!)\", \"lastName\" : \"\(student.lastName!)\",\"mapString\" : \"\(student.mapString!)\", \"mediaURL\" : \"\(student.mediaURL!)\", \"latitude\" : \(student.latitude!), \"longitude\" : \(student.longitude!)}".dataUsingEncoding(NSUTF8StringEncoding) let session = NSURLSession.sharedSession() let task = session.dataTaskWithRequest(request) { data, response, error in if error != nil { completionHandler(success: false, errorMessage: error?.description) } else { do { let parsedResult: AnyObject! parsedResult = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments) completionHandler(success: true, errorMessage: nil) } catch { completionHandler(success: false, errorMessage: "Error parsing JSON data") } } } task.resume() } }
mit
7631919af1febd63816622d6e18bc3a2
45.168675
354
0.621347
4.742574
false
false
false
false
koher/EasyImagy
Sources/EasyImagy/RGBAOperators.swift
1
9424
extension RGBA where Channel : Numeric { @inlinable public static func +(lhs: RGBA<Channel>, rhs: RGBA<Channel>) -> RGBA<Channel> { return RGBA(red: lhs.red + rhs.red, green: lhs.green + rhs.green, blue: lhs.blue + rhs.blue, alpha: lhs.alpha + rhs.alpha) } @inlinable public static func -(lhs: RGBA<Channel>, rhs: RGBA<Channel>) -> RGBA<Channel> { return RGBA(red: lhs.red - rhs.red, green: lhs.green - rhs.green, blue: lhs.blue - rhs.blue, alpha: lhs.alpha - rhs.alpha) } @inlinable public static func *(lhs: RGBA<Channel>, rhs: RGBA<Channel>) -> RGBA<Channel> { return RGBA(red: lhs.red * rhs.red, green: lhs.green * rhs.green, blue: lhs.blue * rhs.blue, alpha: lhs.alpha * rhs.alpha) } @inlinable public static func +=(lhs: inout RGBA<Channel>, rhs: RGBA<Channel>) { lhs.red += rhs.red lhs.green += rhs.green lhs.blue += rhs.blue lhs.alpha += rhs.alpha } @inlinable public static func -=(lhs: inout RGBA<Channel>, rhs: RGBA<Channel>) { lhs.red -= rhs.red lhs.green -= rhs.green lhs.blue -= rhs.blue lhs.alpha -= rhs.alpha } @inlinable public static func *=(lhs: inout RGBA<Channel>, rhs: RGBA<Channel>) { lhs.red *= rhs.red lhs.green *= rhs.green lhs.blue *= rhs.blue lhs.alpha *= rhs.alpha } @inlinable prefix public static func +(a: RGBA<Channel>) -> RGBA<Channel> { return RGBA(red: +a.red, green: +a.green, blue: +a.blue, alpha: +a.alpha) } } extension RGBA where Channel : SignedNumeric { @inlinable prefix public static func -(a: RGBA<Channel>) -> RGBA<Channel> { return RGBA(red: -a.red, green: -a.green, blue: -a.blue, alpha: -a.alpha) } } extension RGBA where Channel : BinaryInteger { @inlinable public static func /(lhs: RGBA<Channel>, rhs: RGBA<Channel>) -> RGBA<Channel> { return RGBA(red: lhs.red / rhs.red, green: lhs.green / rhs.green, blue: lhs.blue / rhs.blue, alpha: lhs.alpha / rhs.alpha) } @inlinable public static func %(lhs: RGBA<Channel>, rhs: RGBA<Channel>) -> RGBA<Channel> { return RGBA(red: lhs.red % rhs.red, green: lhs.green % rhs.green, blue: lhs.blue % rhs.blue, alpha: lhs.alpha % rhs.alpha) } @inlinable public static func &(lhs: RGBA<Channel>, rhs: RGBA<Channel>) -> RGBA<Channel> { return RGBA(red: lhs.red & rhs.red, green: lhs.green & rhs.green, blue: lhs.blue & rhs.blue, alpha: lhs.alpha & rhs.alpha) } @inlinable public static func |(lhs: RGBA<Channel>, rhs: RGBA<Channel>) -> RGBA<Channel> { return RGBA(red: lhs.red | rhs.red, green: lhs.green | rhs.green, blue: lhs.blue | rhs.blue, alpha: lhs.alpha | rhs.alpha) } @inlinable public static func ^(lhs: RGBA<Channel>, rhs: RGBA<Channel>) -> RGBA<Channel> { return RGBA(red: lhs.red ^ rhs.red, green: lhs.green ^ rhs.green, blue: lhs.blue ^ rhs.blue, alpha: lhs.alpha ^ rhs.alpha) } @inlinable public static func <<(lhs: RGBA<Channel>, rhs: RGBA<Channel>) -> RGBA<Channel> { return RGBA(red: lhs.red << rhs.red, green: lhs.green << rhs.green, blue: lhs.blue << rhs.blue, alpha: lhs.alpha << rhs.alpha) } @inlinable public static func >>(lhs: RGBA<Channel>, rhs: RGBA<Channel>) -> RGBA<Channel> { return RGBA(red: lhs.red >> rhs.red, green: lhs.green >> rhs.green, blue: lhs.blue >> rhs.blue, alpha: lhs.alpha >> rhs.alpha) } @inlinable public static func /=(lhs: inout RGBA<Channel>, rhs: RGBA<Channel>) { lhs.red /= rhs.red lhs.green /= rhs.green lhs.blue /= rhs.blue lhs.alpha /= rhs.alpha } @inlinable public static func %=(lhs: inout RGBA<Channel>, rhs: RGBA<Channel>) { lhs.red %= rhs.red lhs.green %= rhs.green lhs.blue %= rhs.blue lhs.alpha %= rhs.alpha } @inlinable public static func &=(lhs: inout RGBA<Channel>, rhs: RGBA<Channel>) { lhs.red &= rhs.red lhs.green &= rhs.green lhs.blue &= rhs.blue lhs.alpha &= rhs.alpha } @inlinable public static func |=(lhs: inout RGBA<Channel>, rhs: RGBA<Channel>) { lhs.red |= rhs.red lhs.green |= rhs.green lhs.blue |= rhs.blue lhs.alpha |= rhs.alpha } @inlinable public static func ^=(lhs: inout RGBA<Channel>, rhs: RGBA<Channel>) { lhs.red ^= rhs.red lhs.green ^= rhs.green lhs.blue ^= rhs.blue lhs.alpha ^= rhs.alpha } @inlinable public static func <<=(lhs: inout RGBA<Channel>, rhs: RGBA<Channel>) { lhs.red <<= rhs.red lhs.green <<= rhs.green lhs.blue <<= rhs.blue lhs.alpha <<= rhs.alpha } @inlinable public static func >>=(lhs: inout RGBA<Channel>, rhs: RGBA<Channel>) { lhs.red >>= rhs.red lhs.green >>= rhs.green lhs.blue >>= rhs.blue lhs.alpha >>= rhs.alpha } } extension RGBA where Channel : FixedWidthInteger { @inlinable public static func &+(lhs: RGBA<Channel>, rhs: RGBA<Channel>) -> RGBA<Channel> { return RGBA(red: lhs.red &+ rhs.red, green: lhs.green &+ rhs.green, blue: lhs.blue &+ rhs.blue, alpha: lhs.alpha &+ rhs.alpha) } @inlinable public static func &-(lhs: RGBA<Channel>, rhs: RGBA<Channel>) -> RGBA<Channel> { return RGBA(red: lhs.red &- rhs.red, green: lhs.green &- rhs.green, blue: lhs.blue &- rhs.blue, alpha: lhs.alpha &- rhs.alpha) } @inlinable public static func &*(lhs: RGBA<Channel>, rhs: RGBA<Channel>) -> RGBA<Channel> { return RGBA(red: lhs.red &* rhs.red, green: lhs.green &* rhs.green, blue: lhs.blue &* rhs.blue, alpha: lhs.alpha &* rhs.alpha) } @inlinable public static func &<<(lhs: RGBA<Channel>, rhs: RGBA<Channel>) -> RGBA<Channel> { return RGBA(red: lhs.red &<< rhs.red, green: lhs.green &<< rhs.green, blue: lhs.blue &<< rhs.blue, alpha: lhs.alpha &<< rhs.alpha) } @inlinable public static func &>>(lhs: RGBA<Channel>, rhs: RGBA<Channel>) -> RGBA<Channel> { return RGBA(red: lhs.red &>> rhs.red, green: lhs.green &>> rhs.green, blue: lhs.blue &>> rhs.blue, alpha: lhs.alpha &>> rhs.alpha) } @inlinable public static func &<<=(lhs: inout RGBA<Channel>, rhs: RGBA<Channel>) { lhs.red &<<= rhs.red lhs.green &<<= rhs.green lhs.blue &<<= rhs.blue lhs.alpha &<<= rhs.alpha } @inlinable public static func &>>=(lhs: inout RGBA<Channel>, rhs: RGBA<Channel>) { lhs.red &>>= rhs.red lhs.green &>>= rhs.green lhs.blue &>>= rhs.blue lhs.alpha &>>= rhs.alpha } } extension RGBA where Channel : FloatingPoint { @inlinable public static func /(lhs: RGBA<Channel>, rhs: RGBA<Channel>) -> RGBA<Channel> { return RGBA(red: lhs.red / rhs.red, green: lhs.green / rhs.green, blue: lhs.blue / rhs.blue, alpha: lhs.alpha / rhs.alpha) } @inlinable public static func /=(lhs: inout RGBA<Channel>, rhs: RGBA<Channel>) { lhs.red /= rhs.red lhs.green /= rhs.green lhs.blue /= rhs.blue lhs.alpha /= rhs.alpha } } extension RGBA : Equatable where Channel : Equatable { @inlinable public static func ==(lhs: RGBA<Channel>, rhs: RGBA<Channel>) -> Bool { return lhs.red == rhs.red && lhs.green == rhs.green && lhs.blue == rhs.blue && lhs.alpha == rhs.alpha } @inlinable public static func !=(lhs: RGBA<Channel>, rhs: RGBA<Channel>) -> Bool { return lhs.red != rhs.red || lhs.green != rhs.green || lhs.blue != rhs.blue || lhs.alpha != rhs.alpha } } extension RGBA where Channel : Comparable { @inlinable public static func <(lhs: RGBA<Channel>, rhs: RGBA<Channel>) -> RGBA<Bool> { return RGBA<Bool>(red: lhs.red < rhs.red, green: lhs.green < rhs.green, blue: lhs.blue < rhs.blue, alpha: lhs.alpha < rhs.alpha) } @inlinable public static func <=(lhs: RGBA<Channel>, rhs: RGBA<Channel>) -> RGBA<Bool> { return RGBA<Bool>(red: lhs.red <= rhs.red, green: lhs.green <= rhs.green, blue: lhs.blue <= rhs.blue, alpha: lhs.alpha <= rhs.alpha) } @inlinable public static func >(lhs: RGBA<Channel>, rhs: RGBA<Channel>) -> RGBA<Bool> { return RGBA<Bool>(red: lhs.red > rhs.red, green: lhs.green > rhs.green, blue: lhs.blue > rhs.blue, alpha: lhs.alpha > rhs.alpha) } @inlinable public static func >=(lhs: RGBA<Channel>, rhs: RGBA<Channel>) -> RGBA<Bool> { return RGBA<Bool>(red: lhs.red >= rhs.red, green: lhs.green >= rhs.green, blue: lhs.blue >= rhs.blue, alpha: lhs.alpha >= rhs.alpha) } } extension RGBA where Channel == Bool { @inlinable public static func &&(lhs: RGBA<Channel>, rhs: RGBA<Channel>) -> RGBA<Channel> { return RGBA(red: lhs.red && rhs.red, green: lhs.green && rhs.green, blue: lhs.blue && rhs.blue, alpha: lhs.alpha && rhs.alpha) } @inlinable public static func ||(lhs: RGBA<Channel>, rhs: RGBA<Channel>) -> RGBA<Channel> { return RGBA(red: lhs.red || rhs.red, green: lhs.green || rhs.green, blue: lhs.blue || rhs.blue, alpha: lhs.alpha || rhs.alpha) } @inlinable prefix public static func !(a: RGBA<Channel>) -> RGBA<Channel> { return RGBA(red: !a.red, green: !a.green, blue: !a.blue, alpha: !a.alpha) } }
mit
13c95af51222a6cdbe51a4f7931ebdf1
36.102362
140
0.597729
3.480059
false
false
false
false
brunodlz/Couch
Couch/Couch/Controllers/Show/Details/DetailsViewController.swift
1
2697
import UIKit enum Ep { case first, previous, next } class DetailsViewController: UIViewController { var show: Show! weak var provider: DataProvider! let detailsView = DetailsView() let viewModel = DetailsViewModel() init(provider: DataProvider, show: Show) { self.provider = provider self.show = show super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func loadView() { self.view = detailsView detailsView.previousButton.addTarget(self, action: #selector(showPreviousEpisode), for: .touchUpInside) detailsView.nextButton.addTarget(self, action: #selector(showNextEpisode), for: .touchUpInside) detailsView.favoriteButton.addTarget(self, action: #selector(favoriteEpisode), for: .touchUpInside) self.title = show.title ?? "" self.view.backgroundColor = ColorPalette.black } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if let imdb = self.show.imdb { self.didRequest() self.allSeasons(with: imdb) } } @objc private func showPreviousEpisode() { if let imdb = self.show.imdb { self.didRequest() self.episodeDetails(with: imdb, ep: .previous) } } @objc private func showNextEpisode() { if let imdb = self.show.imdb { self.didRequest() self.episodeDetails(with: imdb, ep: .next) } } @objc private func favoriteEpisode() { } private func allSeasons(with imdb: String) { viewModel.allSeasons(with: imdb, provider: provider) { (result) in if result.count > 0 { self.episodeDetails(with: imdb, ep: .first) } } } private func episodeDetails(with imdb: String, ep: Ep) { viewModel.episodeDetails(with: imdb, provider: provider, episode: ep) { (episode) in guard let episode = episode else { self.showAlert("An error occurred. try again :(") return } self.detailsView.show(episode: episode) self.didUpdate() } } private func showAlert(_ message: String) { let alert = UIAlertController(title: "Error", message: message, preferredStyle: .alert) let okAction = UIAlertAction(title: "Ok", style: .default, handler: nil) alert.addAction(okAction) self.present(alert, animated: true, completion: nil) } }
mit
f811443c357be04491bc09097b857331
30
111
0.595847
4.594549
false
false
false
false
envoyproxy/envoy
mobile/library/swift/HeadersBuilder.swift
2
3545
import Foundation private let kRestrictedPrefixes = [":", "x-envoy-mobile"] private func isRestrictedHeader(name: String) -> Bool { let isHostHeader = name.caseInsensitiveCompare("host") == .orderedSame lazy var hasRestrictedPrefix = kRestrictedPrefixes .contains { name.range(of: $0, options: [.caseInsensitive, .anchored]) != nil } return isHostHeader || hasRestrictedPrefix } /// Base builder class used to construct `Headers` instances. /// It preserves the original casing of headers and enforces /// a case-insensitive lookup and setting of headers. /// See `{Request|Response}HeadersBuilder` for usage. @objcMembers public class HeadersBuilder: NSObject { private(set) var container: HeadersContainer /// Append a value to the header name. /// /// - parameter name: The header name. /// - parameter value: The value associated to the header name. /// /// - returns: This builder. @discardableResult public func add(name: String, value: String) -> Self { if isRestrictedHeader(name: name) { return self } self.container.add(name: name, value: value) return self } /// Replace all values at the provided name with a new set of header values. /// /// - parameter name: The header name. /// - parameter value: The value associated to the header name. /// /// - returns: This builder. @discardableResult public func set(name: String, value: [String]) -> Self { if isRestrictedHeader(name: name) { return self } self.container.set(name: name, value: value) return self } /// Remove all headers with this name. /// /// - parameter name: The header name to remove. /// /// - returns: This builder. @discardableResult public func remove(name: String) -> Self { if isRestrictedHeader(name: name) { return self } self.container.remove(name: name) return self } // MARK: - Internal /// Allows for setting headers that are not publicly mutable (i.e., restricted headers). /// /// - parameter name: The header name. /// - parameter value: The value associated to the header name. /// /// - returns: This builder. @discardableResult func internalSet(name: String, value: [String]) -> Self { self.container.set(name: name, value: value) return self } /// Accessor for all underlying case-sensitive headers. When possible, /// use case-insensitive accessors instead. /// /// - returns: The underlying case-sensitive headers. func caseSensitiveHeaders() -> [String: [String]] { return self.container.caseSensitiveHeaders() } // Only explicitly implemented to work around a swiftinterface issue in Swift 5.1. This can be // removed once envoy is only built with Swift 5.2+ public override init() { self.container = HeadersContainer() super.init() } // Initialize a new builder using the provided headers container. /// /// - parameter container: The headers container to initialize the receiver with. init(container: HeadersContainer) { self.container = container super.init() } // Initialize a new builder. Subclasses should provide their own public convenience initializers. // // - parameter headers: The headers with which to start. init(headers: [String: [String]]) { self.container = HeadersContainer(headers: headers) super.init() } } // MARK: - Equatable extension HeadersBuilder { public override func isEqual(_ object: Any?) -> Bool { return (object as? Self)?.container == self.container } }
apache-2.0
037668b23f1666d92dde02deac7e70d8
28.789916
99
0.684344
4.2506
false
false
false
false
SwiftKitz/Storez
Sources/Storez/Stores/Cache/CacheStore.swift
1
2880
// // CacheStore.swift // Storez // // Created by Mazyad Alabduljaleel on 12/8/15. // Copyright © 2015 mazy. All rights reserved. // import Foundation public final class CacheStore: Store { public let cache = NSCache<AnyObject, AnyObject>() public init() {} public func clear() { cache.removeAllObjects() } fileprivate func _read<K: KeyType, B: CacheTransaction>(_ key: K, boxType: B.Type) -> K.ValueType where K.ValueType == B.ValueType { let object: AnyObject? = cache.object(forKey: key.stringValue as AnyObject) return boxType.init(storedValue: object)?.value ?? key.defaultValue } fileprivate func _write<K: KeyType>(_ key: K, object: AnyObject?) { K.NamespaceType.preCommitHook() if let object = object { cache.setObject(object, forKey: key.stringValue as AnyObject) } else { cache.removeObject(forKey: key.stringValue as AnyObject) } K.NamespaceType.postCommitHook() } fileprivate func _set<K: KeyType, B: CacheTransaction>(_ key: K, box: B) where K.ValueType == B.ValueType { let oldValue = _read(key, boxType: B.self) let newValue = key.processChange(oldValue, newValue: box.value) let newBox = B(newValue) key.willChange(oldValue, newValue: newValue) _write(key, object: newBox.supportedType) key.didChange(oldValue, newValue: newValue) } public func get<K: KeyType>(_ key: K) -> K.ValueType where K.ValueType: CacheSupportedType { return _read(key, boxType: CacheSupportedBox.self) } public func get<K: KeyType, V: CacheSupportedType>(_ key: K) -> V? where K.ValueType == V? { return _read(key, boxType: CacheNullableSupportedBox.self) } public func get<K: KeyType>(_ key: K) -> K.ValueType where K.ValueType: CacheConvertible { return _read(key, boxType: CacheConvertibleBox.self) } public func get<K: KeyType, V: CacheConvertible>(_ key: K) -> V? where K.ValueType == V? { return _read(key, boxType: CacheNullableConvertibleBox.self) } public func set<K: KeyType>(_ key: K, value: K.ValueType) where K.ValueType: CacheSupportedType { _set(key, box: CacheSupportedBox(value)) } public func set<K: KeyType, V: CacheSupportedType>(_ key: K, value: V?) where K.ValueType == V? { _set(key, box: CacheNullableSupportedBox(value)) } public func set<K: KeyType>(_ key: K, value: K.ValueType) where K.ValueType: CacheConvertible { _set(key, box: CacheConvertibleBox(value)) } public func set<K: KeyType, V: CacheConvertible>(_ key: K, value: V?) where K.ValueType == V? { _set(key, box: CacheNullableConvertibleBox(value)) } }
mit
30d8927f07292cd5017bea722bc7bf76
33.27381
136
0.621744
3.96011
false
false
false
false
AgaKhanFoundation/WCF-iOS
Steps4Impact/CommonUI/Views/CellDisclosureView.swift
1
2767
/** * Copyright © 2019 Aga Khan Foundation * 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. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR "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 AUTHOR 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 protocol CellDisclosureViewDelegate: AnyObject { func cellDisclosureTapped() } struct CellDisclosureContext: Context { let label: String } class CellDisclosureView: View { private let seperatorLineView = UIView() private let label = UILabel(typography: .smallRegularBlue) private let disclosureImageView = UIImageView(image: Assets.disclosure.image) weak var delegate: CellDisclosureViewDelegate? override func commonInit() { addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(viewTapped))) seperatorLineView.backgroundColor = Style.Colors.Seperator addSubview(seperatorLineView) { $0.leading.trailing.top.equalToSuperview() $0.height.equalTo(1) } addSubview(disclosureImageView) { $0.centerY.equalToSuperview() $0.trailing.equalToSuperview().inset(Style.Padding.p16) $0.height.equalTo(16) $0.width.equalTo(10) } addSubview(label) { $0.top.bottom.leading.equalToSuperview().inset(Style.Padding.p16) $0.trailing.equalTo(disclosureImageView.snp.leading).offset(-Style.Padding.p16) } } func configure(context: CellDisclosureContext) { label.text = context.label } @objc func viewTapped() { delegate?.cellDisclosureTapped() } }
bsd-3-clause
416c7fd4bc759d6b7ff677ab4c45e4a9
34.922078
93
0.747289
4.482982
false
false
false
false
STT-Ocean/iOS_WB
iOS_WB/iOS_WB/Libs/Source/HelpingMapper.swift
11
8269
/* * Copyright 1999-2101 Alibaba Group. * * 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. */ // Created by zhouzhuo on 9/20/16. // import Foundation public typealias CustomMappingKeyValueTuple = (Int, MappingPropertyHandler) public class MappingPropertyHandler { var mappingNames: [String]? var assignmentClosure: ((Any?) -> ())? var takeValueClosure: ((Any?) -> (Any?))? public init(mappingNames: [String]?, assignmentClosure: ((Any?) -> ())?, takeValueClosure: ((Any?) -> (Any?))?) { self.mappingNames = mappingNames self.assignmentClosure = assignmentClosure self.takeValueClosure = takeValueClosure } } public class HelpingMapper { private var mappingHandlers = [Int: MappingPropertyHandler]() private var excludeProperties = [Int]() internal func getMappingHandler(key: Int) -> MappingPropertyHandler? { return self.mappingHandlers[key] } internal func propertyExcluded(key: Int) -> Bool { return self.excludeProperties.contains(key) } public func specify<T>(property: inout T, name: String) { self.specify(property: &property, name: name, converter: nil) } public func specify<T>(property: inout T, converter: @escaping (String) -> T) { self.specify(property: &property, name: nil, converter: converter) } public func specify<T>(property: inout T, name: String?, converter: ((String) -> T)?) { let pointer = withUnsafePointer(to: &property, { return $0 }) let key = pointer.hashValue let names = (name == nil ? nil : [name!]) if let _converter = converter { let assignmentClosure = { (jsonValue: Any?) in if let _value = jsonValue{ if let object = _value as? NSObject{ if let str = String.transform(from: object){ UnsafeMutablePointer<T>(mutating: pointer).pointee = _converter(str) } } } } self.mappingHandlers[key] = MappingPropertyHandler(mappingNames: names, assignmentClosure: assignmentClosure, takeValueClosure: nil) } else { self.mappingHandlers[key] = MappingPropertyHandler(mappingNames: names, assignmentClosure: nil, takeValueClosure: nil) } } public func exclude<T>(property: inout T) { self._exclude(property: &property) } fileprivate func addCustomMapping(key: Int, mappingInfo: MappingPropertyHandler) { self.mappingHandlers[key] = mappingInfo } fileprivate func _exclude<T>(property: inout T) { let pointer = withUnsafePointer(to: &property, { return $0 }) self.excludeProperties.append(pointer.hashValue) } } infix operator <-- : LogicalConjunctionPrecedence public func <-- <T>(property: inout T, name: String) -> CustomMappingKeyValueTuple { return property <-- [name] } public func <-- <T>(property: inout T, names: [String]) -> CustomMappingKeyValueTuple { let pointer = withUnsafePointer(to: &property, { return $0 }) let key = pointer.hashValue return (key, MappingPropertyHandler(mappingNames: names, assignmentClosure: nil, takeValueClosure: nil)) } // MARK: non-optional properties public func <-- <Transform: TransformType>(property: inout Transform.Object, transformer: Transform) -> CustomMappingKeyValueTuple { return property <-- (nil, transformer) } public func <-- <Transform: TransformType>(property: inout Transform.Object, transformer: (String?, Transform?)) -> CustomMappingKeyValueTuple { let names = (transformer.0 == nil ? [] : [transformer.0!]) return property <-- (names, transformer.1) } public func <-- <Transform: TransformType>(property: inout Transform.Object, transformer: ([String], Transform?)) -> CustomMappingKeyValueTuple { let pointer = withUnsafePointer(to: &property, { return $0 }) let key = pointer.hashValue let assignmentClosure = { (jsonValue: Any?) in if let value = transformer.1?.transformFromJSON(jsonValue) { UnsafeMutablePointer<Transform.Object>(mutating: pointer).pointee = value } } let takeValueClosure = { (objectValue: Any?) -> Any? in if let _value = objectValue as? Transform.Object { return transformer.1?.transformToJSON(_value) as Any } return nil } return (key, MappingPropertyHandler(mappingNames: transformer.0, assignmentClosure: assignmentClosure, takeValueClosure: takeValueClosure)) } // MARK: optional properties public func <-- <Transform: TransformType>(property: inout Transform.Object?, transformer: Transform) -> CustomMappingKeyValueTuple { return property <-- (nil, transformer) } public func <-- <Transform: TransformType>(property: inout Transform.Object?, transformer: (String?, Transform?)) -> CustomMappingKeyValueTuple { let names = (transformer.0 == nil ? [] : [transformer.0!]) return property <-- (names, transformer.1) } public func <-- <Transform: TransformType>(property: inout Transform.Object?, transformer: ([String], Transform?)) -> CustomMappingKeyValueTuple { let pointer = withUnsafePointer(to: &property, { return $0 }) let key = pointer.hashValue let assignmentClosure = { (jsonValue: Any?) in if let value = transformer.1?.transformFromJSON(jsonValue) { UnsafeMutablePointer<Transform.Object?>(mutating: pointer).pointee = value } } let takeValueClosure = { (objectValue: Any?) -> Any? in if let _value = objectValue as? Transform.Object { return transformer.1?.transformToJSON(_value) as Any } return nil } return (key, MappingPropertyHandler(mappingNames: transformer.0, assignmentClosure: assignmentClosure, takeValueClosure: takeValueClosure)) } // MARK: implicitly unwrap optional properties public func <-- <Transform: TransformType>(property: inout Transform.Object!, transformer: Transform) -> CustomMappingKeyValueTuple { return property <-- (nil, transformer) } public func <-- <Transform: TransformType>(property: inout Transform.Object!, transformer: (String?, Transform?)) -> CustomMappingKeyValueTuple { let names = (transformer.0 == nil ? [] : [transformer.0!]) return property <-- (names, transformer.1) } public func <-- <Transform: TransformType>(property: inout Transform.Object!, transformer: ([String], Transform?)) -> CustomMappingKeyValueTuple { let pointer = withUnsafePointer(to: &property, { return $0 }) let key = pointer.hashValue let assignmentClosure = { (jsonValue: Any?) in if let value = transformer.1?.transformFromJSON(jsonValue) { UnsafeMutablePointer<Transform.Object!>(mutating: pointer).pointee = value } } let takeValueClosure = { (objectValue: Any?) -> Any? in if let _value = objectValue as? Transform.Object { return transformer.1?.transformToJSON(_value) as Any } return nil } return (key, MappingPropertyHandler(mappingNames: transformer.0, assignmentClosure: assignmentClosure, takeValueClosure: takeValueClosure)) } infix operator <<< : AssignmentPrecedence public func <<< (mapper: HelpingMapper, mapping: CustomMappingKeyValueTuple) { mapper.addCustomMapping(key: mapping.0, mappingInfo: mapping.1) } public func <<< (mapper: HelpingMapper, mappings: [CustomMappingKeyValueTuple]) { mappings.forEach { (mapping) in mapper.addCustomMapping(key: mapping.0, mappingInfo: mapping.1) } } infix operator >>> : AssignmentPrecedence public func >>> <T> (mapper: HelpingMapper, property: inout T) { mapper._exclude(property: &property) }
mit
e7c147faddbdf9f31a8f871750f6c97c
40.139303
146
0.675777
4.481843
false
false
false
false
iException/garage
Garage/Sources/Model/Vehicle.swift
1
1177
// // Vehicle.swift // Garage // // Created by Xiang Li on 28/10/2017. // Copyright © 2017 Baixing. All rights reserved. // import UIKit import RealmSwift import Realm import Foundation import SKPhotoBrowser class Vehicle: Object { @objc dynamic var imageData: Data? var contentMode: UIViewContentMode = .scaleAspectFill var index: Int = 0 var image: UIImage? { get { if let imageData = imageData { return UIImage(data: imageData) } return nil } } // MARK: - Initializer required init() { self.imageData = nil super.init() } required init(value: Any, schema: RLMSchema) { super.init(value: value, schema: schema) } required init(realm: RLMRealm, schema: RLMObjectSchema) { // wtf? super.init(realm: realm, schema: schema) } init(image: UIImage) { var imageData = UIImagePNGRepresentation(image) if imageData == nil { imageData = UIImageJPEGRepresentation(image, 0.7) } self.imageData = imageData super.init() } }
mit
6a24b01b0197ac3cddbbfe6f1e5c74c3
20
61
0.57398
4.523077
false
false
false
false
ilyahal/VKMusic
VkPlaylist/DownloadsTableViewController.swift
1
30611
// // DownloadsTableViewController.swift // VkPlaylist // // MIT License // // Copyright (c) 2016 Ilya Khalyapin // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import UIKit import CoreData /// Контроллер содержащий таблицу со списком активных загрузок и уже загруженных аудиозаписей class DownloadsTableViewController: UITableViewController { weak var delegate: DownloadsTableViewControllerDelegate? /// Идентификатор текущего списка аудиозаписей var playlistIdentifier: String! /// Контроллер поиска let searchController = UISearchController(searchResultsController: nil) /// Выполняется ли сейчас поиск var isSearched: Bool { return searchController.active && !searchController.searchBar.text!.isEmpty } /// Контроллер массива уже загруженных аудиозаписей var downloadsFetchedResultsController: NSFetchedResultsController { return DataManager.sharedInstance.downloadsFetchedResultsController } /// Массив уже загруженных аудиозаписей var downloaded: [TrackInPlaylist] { return downloadsFetchedResultsController.sections!.first!.objects as! [TrackInPlaylist] } /// Массив уже загруженных аудиозаписей, полученный в результате выполения поискового запроса var filteredDownloaded = [TrackInPlaylist]() /// Массив загруженных аудиозаписей, отобажаемых на экране var activeArray: [TrackInPlaylist] { if isSearched { return filteredDownloaded } else { return downloaded } } /// Массив аудиозаписей, загружаемых сейчас var activeDownloads: [String: Download] { return DownloadManager.sharedInstance.activeDownloads } /// Была ли нажата кнопка "Пауза" или "Продолжить" (необходимо для плавного обновления) var pauseOrResumeTapped = false override func viewDidLoad() { super.viewDidLoad() // Настройка поисковой панели searchController.searchResultsUpdater = self searchController.searchBar.delegate = self searchController.dimsBackgroundDuringPresentation = false searchController.hidesNavigationBarDuringPresentation = false searchController.searchBar.searchBarStyle = .Prominent definesPresentationContext = true // Кастомизация tableView tableView.tableFooterView = UIView() // Чистим пустое пространство под таблицей // Регистрация ячеек var cellNib = UINib(nibName: TableViewCellIdentifiers.nothingFoundCell, bundle: nil) // Ячейка "Ничего не найдено" tableView.registerNib(cellNib, forCellReuseIdentifier: TableViewCellIdentifiers.nothingFoundCell) cellNib = UINib(nibName: TableViewCellIdentifiers.offlineAudioCell, bundle: nil) // Ячейка с аудиозаписью tableView.registerNib(cellNib, forCellReuseIdentifier: TableViewCellIdentifiers.offlineAudioCell) cellNib = UINib(nibName: TableViewCellIdentifiers.numberOfRowsCell, bundle: nil) // Ячейка с количеством строк tableView.registerNib(cellNib, forCellReuseIdentifier: TableViewCellIdentifiers.numberOfRowsCell) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) pauseOrResumeTapped = false searchEnable(downloaded.count != 0) reloadTableView() } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) playlistIdentifier = NSUUID().UUIDString DataManager.sharedInstance.addDataManagerDownloadsDelegate(self) DownloadManager.sharedInstance.addDelegate(self) } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) DataManager.sharedInstance.deleteDataManagerDownloadsDelegate(self) DownloadManager.sharedInstance.deleteDelegate(self) } deinit { if let superView = searchController.view.superview { superView.removeFromSuperview() } } // Заново отрисовать таблицу func reloadTableView() { dispatch_async(dispatch_get_main_queue()) { self.tableView.reloadData() } } /// Удаление аудиозаписи func deleteTrack(track: OfflineTrack) { if !PlayerManager.sharedInstance.deleteOfflineTrack(track) { let alertController = UIAlertController(title: "Ошибка", message: "Невозможно удалить, аудиозапись сейчас воспроизводится!", preferredStyle: .Alert) let okAction = UIAlertAction(title: "OK", style: .Default, handler: nil) alertController.addAction(okAction) presentViewController(alertController, animated: true, completion: nil) } else if !DataManager.sharedInstance.deleteTrack(track) { let alertController = UIAlertController(title: "Ошибка", message: "При удалении файла произошла ошибка, попробуйте еще раз..", preferredStyle: .Alert) let okAction = UIAlertAction(title: "OK", style: .Default, handler: nil) alertController.addAction(okAction) presentViewController(alertController, animated: true, completion: nil) } } // MARK: Работа с клавиатурой /// Распознаватель тапов по экрану lazy var tapRecognizer: UITapGestureRecognizer = { var recognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard)) return recognizer }() /// Спрятать клавиатуру у поисковой строки func dismissKeyboard() { searchController.searchBar.resignFirstResponder() if searchController.active && searchController.searchBar.text!.isEmpty { searchController.active = false } } // MARK: Поиск /// Управление доступностью поиска func searchEnable(enable: Bool) { if enable { if tableView.tableHeaderView == nil { searchController.searchBar.alpha = 1 tableView.tableHeaderView = searchController.searchBar } } else { if let _ = tableView.tableHeaderView { searchController.searchBar.alpha = 0 searchController.active = false tableView.tableHeaderView = nil } } } /// Выполнение поискового запроса func filterContentForSearchText(searchText: String) { filteredDownloaded = downloaded.filter { trackInPlaylist in let track = trackInPlaylist.track return track.title.lowercaseString.containsString(searchText.lowercaseString) || track.artist.lowercaseString.containsString(searchText.lowercaseString) } } // MARK: Загрузка helpers /// Получение индекса трека в активном массиве для задания загрузки func trackIndexForDownload(download: Download) -> Int? { if let index = DownloadManager.sharedInstance.downloadsTracks.indexOf({ $0 === download.track}) { return index } return nil } // MARK: Получение ячеек для строк таблицы helpers /// Текст для ячейки с сообщением о том, что нет загружаемых треков var noActiveDownloadsLabelText: String { return "Нет активных загрузок" } /// Текст для ячейки с сообщением о том, что нет загруженных треков var noDownloadedLabelText: String { return "Нет загруженных треков" } /// Текст для ячейки с сообщением о том, что при поиске ничего не найдено var textForNothingFoundRow: String { return "Измените поисковый запрос" } /// Получение количества треков в списке для ячейки с количеством аудиозаписей func numberOfAudioForIndexPath(indexPath: NSIndexPath) -> Int? { if isSearched { if filteredDownloaded.count != 0 && filteredDownloaded.count == indexPath.row { return filteredDownloaded.count } else { return nil } } else { switch indexPath.section { case 1: if downloaded.count != 0 && downloaded.count == indexPath.row { return downloaded.count } else { return nil } default: return nil } } } // MARK: Получение ячеек для строк таблицы /// Ячейка для строки с сообщением об отсутствии загружаемых треков func getCellForNoActiveDownloadsForIndexPath(indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(TableViewCellIdentifiers.nothingFoundCell, forIndexPath: indexPath) as! NothingFoundCell cell.messageLabel.text = noActiveDownloadsLabelText return cell } /// Ячейка для строки с загружаемым треком func getCellForActiveDownloadTrackForIndexPath(indexPath: NSIndexPath) -> UITableViewCell { let track = DownloadManager.sharedInstance.downloadsTracks[indexPath.row] let cell = tableView.dequeueReusableCellWithIdentifier(TableViewCellIdentifiers.activeDownloadCell, forIndexPath: indexPath) as! ActiveDownloadCell cell.delegate = self cell.configureForTrack(track) if let download = activeDownloads[track.url] { // Если аудиозапись есть в списке активных загрузок cell.progressBar.progress = download.progress cell.progressLabel.text = download.isDownloading ? (download.totalSize == nil ? "Загружается..." : String(format: "%.1f%% из %@", download.progress * 100, download.totalSize!)) : (download.inQueue ? "В очереди" : "Пауза") let title = download.isDownloading ? "Пауза" : (download.inQueue ? "Пауза" : "Продолжить") cell.pauseButton.setTitle(title, forState: UIControlState.Normal) } return cell } /// Ячейка для строки с сообщением об отсутствии загруженных треков func getCellForNoDownloadedForIndexPath(indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(TableViewCellIdentifiers.nothingFoundCell, forIndexPath: indexPath) as! NothingFoundCell cell.messageLabel.text = noDownloadedLabelText return cell } /// Ячейка для строки с сообщением, что при поиске ничего не было найдено func getCellForNothingFoundRowForIndexPath(indexPath: NSIndexPath) -> UITableViewCell { let nothingFoundCell = tableView.dequeueReusableCellWithIdentifier(TableViewCellIdentifiers.nothingFoundCell, forIndexPath: indexPath) as! NothingFoundCell nothingFoundCell.messageLabel.text = textForNothingFoundRow return nothingFoundCell } /// Ячейка для строки с загруженным треком func getCellForOfflineAudioForIndexPath(indexPath: NSIndexPath) -> UITableViewCell { let trackInPlaylist = activeArray[indexPath.row] let track = trackInPlaylist.track let cell = tableView.dequeueReusableCellWithIdentifier(TableViewCellIdentifiers.offlineAudioCell, forIndexPath: indexPath) as! OfflineAudioCell cell.configureForTrack(track) return cell } /// Попытка получить ячейку для строки с количеством аудиозаписей func getCellForNumberOfAudioRowForIndexPath(indexPath: NSIndexPath) -> UITableViewCell? { let count = numberOfAudioForIndexPath(indexPath) if let count = count { let numberOfRowsCell = tableView.dequeueReusableCellWithIdentifier(TableViewCellIdentifiers.numberOfRowsCell) as! NumberOfRowsCell numberOfRowsCell.configureForType(.Audio, withCount: count) return numberOfRowsCell } return nil } } // MARK: UITableViewDataSource private typealias _DownloadsTableViewControllerDataSource = DownloadsTableViewController extension _DownloadsTableViewControllerDataSource { // Количество секций override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 + (!isSearched ? 1 : 0) } // Названия секций override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if isSearched { return nil } else { switch section { case 0: return "Активные загрузки" case 1: return "Загруженные" default: return nil } } } // Количество строк в секциях override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if isSearched { return filteredDownloaded.count + 1 } else { switch section { case 0: return activeDownloads.count == 0 ? 1 : activeDownloads.count case 1: return downloaded.count + 1 default: return 0 } } } // Ячейки для строк override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if isSearched { if filteredDownloaded.count == 0 { return getCellForNothingFoundRowForIndexPath(indexPath) } else { if let numberOfRowsCell = getCellForNumberOfAudioRowForIndexPath(indexPath) { return numberOfRowsCell } return getCellForOfflineAudioForIndexPath(indexPath) } } else { switch indexPath.section { case 0: if activeDownloads.count == 0 { return getCellForNoActiveDownloadsForIndexPath(indexPath) } else { return getCellForActiveDownloadTrackForIndexPath(indexPath) } case 1: if downloaded.count == 0 { return getCellForNoDownloadedForIndexPath(indexPath) } else { if let numberOfRowsCell = getCellForNumberOfAudioRowForIndexPath(indexPath) { return numberOfRowsCell } return getCellForOfflineAudioForIndexPath(indexPath) } default: return UITableViewCell() } } } // Возможно ли редактировать ячейку override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { if isSearched { return filteredDownloaded.count != indexPath.row } else { if indexPath.section == 1 { return downloaded.count != indexPath.row } return false } } // Обработка удаления ячейки override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { let trackInPlaylist = activeArray[indexPath.row] let track = trackInPlaylist.track if DataManager.sharedInstance.isWarningWhenDeletingOfExistenceInPlaylists { let playlists = DataManager.sharedInstance.playlistsForTrack(track) if playlists.count == 0 { deleteTrack(track) } else { var playlistsList = "" // Список плейлистов for (index, playlist) in playlists.enumerate() { playlistsList += "- " + playlist.title if index != playlists.count { playlistsList += "\n" } } let alertController = UIAlertController(title: "Вы уверены?", message: "Аудиозапись также будет удалена из следующих плейлистов:\n" + playlistsList, preferredStyle: .ActionSheet) let dontWarningMoreAction = UIAlertAction(title: "Больше не предупреждать", style: .Default) { _ in DataManager.sharedInstance.warningWhenDeletingOfExistenceInPlaylistsDisabled() self.deleteTrack(track) } alertController.addAction(dontWarningMoreAction) let cancelAction = UIAlertAction(title: "Отмена", style: .Cancel, handler: nil) alertController.addAction(cancelAction) let continueAction = UIAlertAction(title: "Продолжить", style: .Destructive) { _ in self.deleteTrack(track) } alertController.addAction(continueAction) presentViewController(alertController, animated: true, completion: nil) } } else { deleteTrack(track) } } } // Возможно ли перемещать ячейку override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { if isSearched { return filteredDownloaded.count != indexPath.row } else { if indexPath.section == 1 { return downloaded.count != indexPath.row } return false } } // Обработка после перемещения ячейки override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { if fromIndexPath.row != toIndexPath.row { let trackToMove = downloaded[fromIndexPath.row] DataManager.sharedInstance.moveDownloadedTrack(trackToMove, fromPosition: Int32(fromIndexPath.row), toNewPosition: Int32(toIndexPath.row)) } } } // MARK: UITableViewDelegate private typealias _DownloadsTableViewControllerDelegate = DownloadsTableViewController extension _DownloadsTableViewControllerDelegate { // Высота каждой строки override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if isSearched { if filteredDownloaded.count != 0 { if filteredDownloaded.count == indexPath.row { return 44 } } } else { switch indexPath.section { case 1: if downloaded.count != 0 { if downloaded.count == indexPath.row { return 44 } } default: break } } return 62 } // Вызывается при тапе по строке таблицы override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) if tableView.cellForRowAtIndexPath(indexPath) is OfflineAudioCell { let track = activeArray[indexPath.row] let index = downloaded.indexOf({ $0 === track })! PlayerManager.sharedInstance.playItemWithIndex(index, inPlaylist: downloaded, withPlaylistIdentifier: playlistIdentifier) } } // Определяется куда переместить ячейку с укзанного NSIndexPath при перемещении в указанный NSIndexPath override func tableView(tableView: UITableView, targetIndexPathForMoveFromRowAtIndexPath sourceIndexPath: NSIndexPath, toProposedIndexPath proposedDestinationIndexPath: NSIndexPath) -> NSIndexPath { switch proposedDestinationIndexPath.section { case 0: return sourceIndexPath case 1: if proposedDestinationIndexPath.row == downloaded.count { return sourceIndexPath } else { return proposedDestinationIndexPath } default: return sourceIndexPath } } } // MARK: UISearchBarDelegate extension DownloadsTableViewController: UISearchBarDelegate { // Пользователь хочет начать поиск func searchBarShouldBeginEditing(searchBar: UISearchBar) -> Bool { if downloaded.count != 0 { delegate?.downloadsTableViewControllerSearchStarted() } return downloaded.count != 0 } // Пользователь начал редактирование поискового текста func searchBarTextDidBeginEditing(searchBar: UISearchBar) { view.addGestureRecognizer(tapRecognizer) } // Пользователь закончил редактирование поискового текста func searchBarTextDidEndEditing(searchBar: UISearchBar) { view.removeGestureRecognizer(tapRecognizer) } // В поисковой панели была нажата кнопка "Отмена" func searchBarCancelButtonClicked(searchBar: UISearchBar) { filteredDownloaded.removeAll() delegate?.downloadsTableViewControllerSearchEnded() } } // MARK: UISearchResultsUpdating extension DownloadsTableViewController: UISearchResultsUpdating { // Поле поиска получило фокус или значение поискового запроса изменилось func updateSearchResultsForSearchController(searchController: UISearchController) { filterContentForSearchText(searchController.searchBar.text!) reloadTableView() } } // MARK: DataManagerDownloadsDelegate extension DownloadsTableViewController: DataManagerDownloadsDelegate { // Контроллер удалил трек с указанным id и id владельца func downloadManagerDeleteTrackWithID(id: Int32, andOwnerID ownerID: Int32) {} // Контроллер массива загруженных аудиозаписей начал изменять контент func dataManagerDownloadsControllerWillChangeContent() {} // Контроллер массива загруженных аудиозаписей совершил изменения определенного типа в укзанном объекте по указанному пути (опционально новый путь) func dataManagerDownloadsControllerDidChangeObject(anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {} // Контроллер массива загруженных аудиозаписей закончил изменять контент func dataManagerDownloadsControllerDidChangeContent() { playlistIdentifier = NSUUID().UUIDString searchEnable(downloaded.count != 0) if isSearched { filterContentForSearchText(searchController.searchBar.text!) } reloadTableView() delegate?.downloadsTableViewControllerUpdateContent() } } // MARK: DownloadManagerDelegate extension DownloadsTableViewController: DownloadManagerDelegate { // Менеджер загрузок начал новую загрузку func downloadManagerStartTrackDownload(download: Download) { if !isSearched { if let index = trackIndexForDownload(download) { dispatch_async(dispatch_get_main_queue(), { self.tableView.insertRowsAtIndexPaths([NSIndexPath(forRow: index, inSection: 0)], withRowAnimation: .Fade) }) } } } // Менеджер загрузок изменил состояние загрузки func downloadManagerUpdateStateTrackDownload(download: Download) { if !isSearched { if let index = trackIndexForDownload(download) { if pauseOrResumeTapped { pauseOrResumeTapped = false dispatch_async(dispatch_get_main_queue(), { self.tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: index, inSection: 0)], withRowAnimation: .None) }) } else { reloadTableView() } } } } // Менеджер загрузок отменил выполнение загрузки func downloadManagerCancelTrackDownload(download: Download) { if !isSearched { reloadTableView() } } // Менеджер загрузок завершил загрузку func downloadManagerdidFinishDownloadingDownload(download: Download) {} // Вызывается когда часть данных была загружена func downloadManagerURLSessionDidWriteDataForDownload(download: Download) { if !isSearched { if let index = trackIndexForDownload(download), activeDownloadCell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: index, inSection: 0)) as? ActiveDownloadCell { dispatch_async(dispatch_get_main_queue(), { activeDownloadCell.cancelButton.hidden = download.progress == 1 activeDownloadCell.pauseButton.hidden = download.progress == 1 activeDownloadCell.progressBar.progress = download.progress activeDownloadCell.progressLabel.text = download.progress == 1 ? "Сохраняется..." : String(format: "%.1f%% из %@", download.progress * 100, download.totalSize!) }) } } } } // MARK: ActiveDownloadCellDelegate extension DownloadsTableViewController: ActiveDownloadCellDelegate { // Кнопка "Пауза" была нажата func pauseTapped(cell: ActiveDownloadCell) { if let indexPath = tableView.indexPathForCell(cell) { let track = DownloadManager.sharedInstance.downloadsTracks[indexPath.row] pauseOrResumeTapped = true DownloadManager.sharedInstance.pauseDownloadTrack(track) } } // Кнопка "Продолжить" была нажата func resumeTapped(cell: ActiveDownloadCell) { if let indexPath = tableView.indexPathForCell(cell) { let track = DownloadManager.sharedInstance.downloadsTracks[indexPath.row] pauseOrResumeTapped = true DownloadManager.sharedInstance.resumeDownloadTrack(track) } } // Кнопка "Отмена" была нажата func cancelTapped(cell: ActiveDownloadCell) { if let indexPath = tableView.indexPathForCell(cell) { let track = DownloadManager.sharedInstance.downloadsTracks[indexPath.row] DownloadManager.sharedInstance.cancelDownloadTrack(track) } } }
mit
5a87536ddfc98bfa04d26a20e7dc9fe5
37.281768
202
0.641169
5.277037
false
false
false
false
pointfreeco/swift-web
Tests/ApplicativeRouterTests/SyntaxRouterTests.swift
1
8446
import ApplicativeRouter import Either #if canImport(FoundationNetworking) import FoundationNetworking #endif import Optics import Prelude import XCTest import SnapshotTesting import HttpPipelineTestSupport class SyntaxRouterTests: XCTestCase { override func setUp() { super.setUp() // record=true } func testHome() { let request = URLRequest(url: URL(string: "home")!) // NB: necessary for linux tests: https://bugs.swift.org/browse/SR-6405 |> \.httpMethod .~ "get" let route = Routes.home XCTAssertEqual(route, router.match(request: request)) XCTAssertEqual(request, router.request(for: route)) XCTAssertEqual("home", router.templateUrl(for: route)?.absoluteString) } func testRoot() { let baseUrl = URL(string: "https://www.pointfree.co")! let request = URLRequest(url: baseUrl) // NB: necessary for linux tests: https://bugs.swift.org/browse/SR-6405 |> \.httpMethod .~ "get" let route = Routes.root XCTAssertEqual(route, router.match(request: request)) XCTAssertEqual(request, router.request(for: route, base: baseUrl)) XCTAssertEqual("/", router.templateUrl(for: route)?.absoluteString) XCTAssertEqual("/", router.absoluteString(for: .root)) } func testRequest_WithBaseUrl() { // BUG: https://bugs.swift.org/browse/SR-6407 // NB: Previously we did `XCTAssertEqual` on a left/right side to check that the requests match, but // due to a weird Swift bug (https://bugs.swift.org/browse/SR-6407) we are switching to a snapshot // test. assertSnapshot( matching: router.request(for: .home, base: URL(string: "http://www.pointfree.co/"))! // NB: necessary for linux tests: https://bugs.swift.org/browse/SR-6405 |> \.httpMethod .~ "GET", as: .raw ) } func testAbsoluteString() { XCTAssertEqual("/home", router.absoluteString(for: .home)) XCTAssertEqual( "/home/episodes/intro-to-functions/comments/42", router.absoluteString(for: .pathComponents(param: .left("intro-to-functions"), commentId: 42)) ) } func testLitFails() { let request = URLRequest(url: URL(string: "foo")!) XCTAssertNil(router.match(request: request)) } func testPathComponents_IntParam() { let request = URLRequest(url: URL(string: "home/episodes/42/comments/2")!) // NB: necessary for linux tests: https://bugs.swift.org/browse/SR-6405 |> \.httpMethod .~ "get" let route = Routes.pathComponents(param: .right(42), commentId: 2) XCTAssertEqual(route, router.match(request: request)) XCTAssertEqual(request, router.request(for: route)) XCTAssertEqual( "home/episodes/:string_or_int/comments/:int", router.templateUrl(for: route)?.absoluteString ) } func testPathComponents_StringParam() { let request = URLRequest(url: URL(string: "home/episodes/hello-world/comments/2")!) // NB: necessary for linux tests: https://bugs.swift.org/browse/SR-6405 |> \.httpMethod .~ "get" let route = Routes.pathComponents(param: .left("hello-world"), commentId: 2) XCTAssertEqual(route, router.match(request: request)) XCTAssertEqual(request, router.request(for: route)) XCTAssertEqual( "home/episodes/:string_or_int/comments/:int", router.templateUrl(for: route)?.absoluteString ) } func testPostBodyField() { let route = Routes.postBodyField(email: "[email protected]") let request = URLRequest(url: URL(string: "signup")!) // NB: necessary for linux tests: https://bugs.swift.org/browse/SR-6405 |> \.httpMethod .~ "post" |> \.httpBody .~ "[email protected]".data(using: .utf8) XCTAssertNotNil(request.httpBody) XCTAssertEqual(route, router.match(request: request)) XCTAssertEqual(request, router.request(for: route)) XCTAssertEqual("signup", router.templateUrl(for: route)?.absoluteString) } func testPostBodyJsonDecodable() { let episode = Episode( title: "Intro to Functions", blurb: "Everything about functions!", length: 300, category: nil ) let route = Routes.postBodyJsonDecodable(episode: episode, param: 42) let request = URLRequest(url: URL(string: "episodes/42")!) // NB: necessary for linux tests: https://bugs.swift.org/browse/SR-6405 |> \.httpMethod .~ "post" |> \.httpBody .~ (try? JSONEncoder().encode(episode)) XCTAssertEqual(route, router.match(request: request)) XCTAssertNotNil(request.httpBody) XCTAssertEqual(request, router.request(for: route)) } func testSimpleQueryParams() { let request = URLRequest(url: URL(string: "path/to/somewhere/cool?ref=hello&active=true&t=122")!) // NB: necessary for linux tests: https://bugs.swift.org/browse/SR-6405 |> \.httpMethod .~ "get" let route = Routes.simpleQueryParams(ref: "hello", active: true, t: 122) XCTAssertEqual(route, router.match(request: request)) XCTAssertEqual(request, router.request(for: route)) XCTAssertEqual( "path/to/somewhere/cool?ref=:optional_string&active=:bool&t=:int", router.templateUrl(for: route)?.absoluteString ) } func testSimpleQueryParams_SomeMissing() { let request = URLRequest(url: URL(string: "path/to/somewhere/cool?active=true&t=122")!) // NB: necessary for linux tests: https://bugs.swift.org/browse/SR-6405 |> \.httpMethod .~ "get" let route = Routes.simpleQueryParams(ref: nil, active: true, t: 122) XCTAssertEqual(route, router.match(request: request)) XCTAssertEqual(request, router.request(for: route)) XCTAssertEqual( "path/to/somewhere/cool?ref=:optional_string&active=:bool&t=:int", router.templateUrl(for: route)?.absoluteString ) } // func testCodableQueryParams() { // let request = URLRequest(url: URL(string: "subscribe?plan=1")!) // // NB: necessary for linux tests: https://bugs.swift.org/browse/SR-6405 // |> \.httpMethod .~ "get" // let route = Routes.codableQueryParams(SubscribeData(plan: 1)) // // XCTAssertEqual(route, router.match(request: request)) // XCTAssertEqual(request, router.request(for: route)) // #if os(Linux) // XCTAssertEqual( // "subscribe?plan=:int", // router.templateUrl(for: route)?.absoluteString // ) // #else // XCTAssertEqual( // "subscribe?plan=:__nscfnumber", // FIXME // router.templateUrl(for: route)?.absoluteString // ) // #endif // } // // FIXME: Make work! // func testCodableQueryParamsOptionality() { // let request = URLRequest(url: URL(string: "subscribe")!) // // NB: necessary for linux tests: https://bugs.swift.org/browse/SR-6405 // |> \.httpMethod .~ "get" // let route = Routes.codableQueryParams(nil) // // XCTAssertEqual(route, router.match(request: request)) // XCTAssertEqual(request, router.request(for: route)) // } func testCodableFormDataPostBody() { var request = URLRequest(url: URL(string: "subscribe")!) request.httpMethod = "post" request.httpBody = Data("plan=1&quantity=2".utf8) let route = Routes.postBodyFormData(SubscribeData(plan: 1, quantity: 2)) XCTAssertEqual(route, router.match(request: request)) XCTAssertEqual(request, router.request(for: route)) XCTAssertEqual( "subscribe", router.templateUrl(for: route)?.absoluteString ) assertSnapshot( matching: router.request(for: .postBodyFormData(SubscribeData(plan: 2, quantity: 3)))!, as: .raw ) } func testRedirect() { XCTAssertEqual( "/somewhere?redirect=http://localhost:8080/home?redirect%3Dhttp://localhost:8080/home", router.absoluteString(for: .redirect("http://localhost:8080/home?redirect=http://localhost:8080/home")) ) } func testHeader() throws { let router: Router<Int> = get %> "home" %> header("version", req(.int)) <% end var request = URLRequest(url: URL(string: "home")!) request.allHTTPHeaderFields = ["version": "10"] XCTAssertEqual( router.match(request: request), 10 ) request = try XCTUnwrap(router.request(for: 20)) XCTAssertEqual(request.allHTTPHeaderFields, ["version": "20"]) } func testOptionalHeader() throws { let router: Router<Int> = get %> "home" %> header("version", opt(.int, default: 10)) <% end let request = URLRequest(url: URL(string: "home")!) XCTAssertEqual( router.match(request: request), 10 ) } }
mit
ecdca779630e383771fe105cdd04bdf3
35.248927
109
0.671087
3.856621
false
true
false
false
seandavidmcgee/HumanKontactBeta
src/keyboardTest/BounceView.swift
24
2110
// // ENPullToBounseView.swift // BezierPathAnimation // // Created by Takuya Okamoto on 2015/08/11. // Copyright (c) 2015年 Uniface. All rights reserved. // import UIKit class BounceView: UIView { let ballView : BallView! let waveView : WaveView! init( frame:CGRect, bounceDuration: CFTimeInterval = 0.8, ballSize:CGFloat = 28,//32, ballMoveTimingFunc:CAMediaTimingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseOut), moveUpDuration:CFTimeInterval = 0.2, moveUpDist: CGFloat = 32 * 1.5, var color: UIColor! = UIColor.whiteColor() ) { if color == nil { color = UIColor.whiteColor() } let ballViewHeight: CGFloat = 100 ballView = BallView( frame: CGRectMake(0, -(ballViewHeight + 1), frame.width, ballViewHeight), circleSize: ballSize, timingFunc: ballMoveTimingFunc, moveUpDuration: moveUpDuration, moveUpDist: moveUpDist, color: color ) waveView = WaveView( frame:CGRectMake(0, 0, ballView.frame.width, frame.height), bounceDuration: bounceDuration, color: color ) super.init(frame: frame) ballView.hidden = true self.addSubview(ballView) self.addSubview(waveView) waveView.didEndPull = { NSTimer.schedule(delay: 0.2) { timer in self.ballView.hidden = false self.ballView.startAnimation() } } } func endingAnimation(complition:(()->())? = nil) { ballView.endAnimation { self.ballView.hidden = true complition?() } } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func wave(y: CGFloat) { waveView.wave(y) } func didRelease(y: CGFloat) { waveView.didRelease(amountX: 0, amountY: y) } }
mit
e0d43effcb4554f83c3545096c4b2cf4
25.3625
110
0.5574
4.562771
false
false
false
false
mozilla-mobile/firefox-ios
Client/Application/NavigationRouter.swift
2
16889
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0 import Foundation import Shared import Glean struct FxALaunchParams { var query: [String: String] } // An enum to route to HomePanels enum HomePanelPath: String { case bookmarks = "bookmarks" case topSites = "top-sites" case readingList = "reading-list" case history = "history" case downloads = "downloads" case newPrivateTab = "new-private-tab" } // An enum to route to a settings page. // This could be extended to provide default values to pass to fxa enum SettingsPage: String { case general = "general" case newtab = "newtab" case homepage = "homepage" case wallpaper = "wallpaper" case mailto = "mailto" case search = "search" case clearPrivateData = "clear-private-data" case fxa = "fxa" case theme = "theme" } enum DefaultBrowserPath: String { case tutorial = "tutorial" case systemSettings = "system-settings" } // Used by the App to navigate to different views. // To open a URL use /open-url or to open a blank tab use /open-url with no params enum DeepLink { case settings(SettingsPage) case homePanel(HomePanelPath) case defaultBrowser(DefaultBrowserPath) init?(urlString: String) { let paths = urlString.split(separator: "/") guard let component = paths[safe: 0], let componentPath = paths[safe: 1] else { return nil } if component == "settings", let link = SettingsPage(rawValue: String(componentPath)) { self = .settings(link) } else if component == "homepanel", let link = HomePanelPath(rawValue: String(componentPath)) { self = .homePanel(link) } else if component == "default-browser", let link = DefaultBrowserPath(rawValue: String(componentPath)) { self = .defaultBrowser(link) } else { return nil } } } extension URLComponents { // Return the first query parameter that matches func valueForQuery(_ param: String) -> String? { return self.queryItems?.first { $0.name == param }?.value } } // The root navigation for the Router. Look at the tests to see a complete URL enum NavigationPath { case url(webURL: URL?, isPrivate: Bool) case widgetUrl(webURL: URL?, uuid: String) case fxa(params: FxALaunchParams) case deepLink(DeepLink) case text(String) case glean(url: URL) case closePrivateTabs init?(url: URL) { /* Force the URL's scheme to lowercase to ensure the code below can cope with URLs like the following from an external source. E.g Notes.app Https://www.apple.com */ func sanitizedURL(for unsanitized: URL) -> URL { guard var components = URLComponents(url: unsanitized, resolvingAgainstBaseURL: true), let scheme = components.scheme, !scheme.isEmpty else { return unsanitized } components.scheme = scheme.lowercased() return components.url ?? unsanitized } let url = sanitizedURL(for: url) guard let components = URLComponents(url: url, resolvingAgainstBaseURL: false), let urlTypes = Bundle.main.object(forInfoDictionaryKey: "CFBundleURLTypes") as? [AnyObject], let urlSchemes = urlTypes.first?["CFBundleURLSchemes"] as? [String] else { // Something very strange has happened; org.mozilla.Client should be the zeroeth URL type. return nil } guard let scheme = components.scheme, urlSchemes.contains(scheme) else { return nil } let isOurScheme = [URL.mozPublicScheme, URL.mozInternalScheme].contains(scheme) if isOurScheme, let host = components.host?.lowercased(), !host.isEmpty { if host == "deep-link", let deepURL = components.valueForQuery("url"), let link = DeepLink(urlString: deepURL.lowercased()) { self = .deepLink(link) } else if host == "fxa-signin", components.valueForQuery("signin") != nil { self = .fxa(params: FxALaunchParams(query: url.getQuery())) } else if host == "open-url" { self = .openUrlFromComponents(components: components) } else if let widgetKitNavPath = NavigationPath.handleWidgetKitQuery(components: components) { self = widgetKitNavPath } else if host == "open-text" { let text = components.valueForQuery("text") self = .text(text ?? "") } else if host == "glean" { self = .glean(url: url) } else { return nil } } else if ["http", "https"].contains(scheme) { TelemetryWrapper.gleanRecordEvent(category: .action, method: .open, object: .asDefaultBrowser) RatingPromptManager.isBrowserDefault = true // Use the last browsing mode the user was in let isPrivate = UserDefaults.standard.bool(forKey: "wasLastSessionPrivate") self = .url(webURL: url, isPrivate: isPrivate) } else { return nil } } static func handle(nav: NavigationPath, with bvc: BrowserViewController) { switch nav { case .fxa(let params): NavigationPath.handleFxA(params: params, with: bvc) case .deepLink(let link): NavigationPath.handleDeepLink(link, with: bvc) case .url(let url, let isPrivate): NavigationPath.handleURL(url: url, isPrivate: isPrivate, with: bvc) case .text(let text): NavigationPath.handleText(text: text, with: bvc) case .glean(let url): NavigationPath.handleGlean(url: url) case .closePrivateTabs: NavigationPath.handleClosePrivateTabs(with: bvc) case .widgetUrl(webURL: let webURL, uuid: let uuid): NavigationPath.handleWidgetURL(url: webURL, uuid: uuid, with: bvc) } } private static func handleDeepLink(_ link: DeepLink, with bvc: BrowserViewController) { switch link { case .homePanel(let panelPath): NavigationPath.handleHomePanel(panel: panelPath, with: bvc) case .settings(let settingsPath): guard let rootVC = bvc.navigationController else { return } let settingsTableViewController = AppSettingsTableViewController( with: bvc.profile, and: bvc.tabManager, delegate: bvc) NavigationPath.handleSettings(settings: settingsPath, with: rootVC, baseSettingsVC: settingsTableViewController, and: bvc) case .defaultBrowser(let path): NavigationPath.handleDefaultBrowser(path: path, with: bvc) } } private static func handleWidgetKitQuery(components: URLComponents) -> NavigationPath? { guard let host = components.host?.lowercased(), !host.isEmpty else { return nil } switch host { case "widget-medium-topsites-open-url": // Widget Top sites - open url TelemetryWrapper.recordEvent(category: .action, method: .open, object: .mediumTopSitesWidget) return .openUrlFromComponents(components: components) case "widget-small-quicklink-open-url": // Widget Quick links - small - open url private or regular TelemetryWrapper.recordEvent(category: .action, method: .open, object: .smallQuickActionSearch) return .openUrlFromComponents(components: components) case "widget-medium-quicklink-open-url": // Widget Quick Actions - medium - open url private or regular let isPrivate = Bool(components.valueForQuery("private") ?? "") ?? UserDefaults.standard.bool(forKey: "wasLastSessionPrivate") TelemetryWrapper.recordEvent(category: .action, method: .open, object: isPrivate ? .mediumQuickActionPrivateSearch : .mediumQuickActionSearch) return .openUrlFromComponents(components: components) case "widget-small-quicklink-open-copied", "widget-medium-quicklink-open-copied": // Widget Quick links - medium - open copied url TelemetryWrapper.recordEvent(category: .action, method: .open, object: .mediumQuickActionCopiedLink) return .openCopiedUrl() case "widget-small-quicklink-close-private-tabs", "widget-medium-quicklink-close-private-tabs": // Widget Quick links - medium - close private tabs TelemetryWrapper.recordEvent(category: .action, method: .open, object: .mediumQuickActionClosePrivate) return .closePrivateTabs case "widget-tabs-medium-open-url": // Widget Tabs Quick View - medium TelemetryWrapper.recordEvent(category: .action, method: .open, object: .mediumTabsOpenUrl) return .openWidgetUrl(components: components) case "widget-tabs-large-open-url": // Widget Tabs Quick View - large TelemetryWrapper.recordEvent(category: .action, method: .open, object: .largeTabsOpenUrl) return .openWidgetUrl(components: components) default: return nil } } private static func openUrlFromComponents(components: URLComponents) -> NavigationPath { let url = components.valueForQuery("url")?.asURL // Unless the `open-url` URL specifies a `private` parameter, // use the last browsing mode the user was in. let isPrivate = Bool(components.valueForQuery("private") ?? "") ?? UserDefaults.standard.bool(forKey: "wasLastSessionPrivate") return .url(webURL: url, isPrivate: isPrivate) } private static func openCopiedUrl() -> NavigationPath { if !UIPasteboard.general.hasURLs { let searchText = UIPasteboard.general.string ?? "" return .text(searchText) } let url = UIPasteboard.general.url let isPrivate = UserDefaults.standard.bool(forKey: "wasLastSessionPrivate") return .url(webURL: url, isPrivate: isPrivate) } private static func openWidgetUrl(components: URLComponents) -> NavigationPath { let tabs = SimpleTab.getSimpleTabs() guard let uuid = components.valueForQuery("uuid"), !tabs.isEmpty else { return .url(webURL: nil, isPrivate: false) } let tab = tabs[uuid] return .widgetUrl(webURL: tab?.url, uuid: uuid) } private static func handleFxA(params: FxALaunchParams, with bvc: BrowserViewController) { bvc.presentSignInViewController(params) } private static func handleClosePrivateTabs(with bvc: BrowserViewController) { bvc.tabManager.removeTabs(bvc.tabManager.privateTabs) guard let tab = mostRecentTab(inTabs: bvc.tabManager.normalTabs) else { bvc.tabManager.selectTab(bvc.tabManager.addTab()) return } bvc.tabManager.selectTab(tab) } private static func handleGlean(url: URL) { Glean.shared.handleCustomUrl(url: url) } private static func handleHomePanel(panel: HomePanelPath, with bvc: BrowserViewController) { switch panel { case .bookmarks: bvc.showLibrary(panel: .bookmarks) case .history: bvc.showLibrary(panel: .history) case .readingList: bvc.showLibrary(panel: .readingList) case .downloads: bvc.showLibrary(panel: .downloads) case .topSites: bvc.openURLInNewTab(HomePanelType.topSites.internalUrl) case .newPrivateTab: bvc.openBlankNewTab(focusLocationField: false, isPrivate: true) } } private static func handleURL(url: URL?, isPrivate: Bool, with bvc: BrowserViewController) { if let newURL = url { bvc.switchToTabForURLOrOpen(newURL, isPrivate: isPrivate) } else { bvc.openBlankNewTab(focusLocationField: true, isPrivate: isPrivate) } } private static func handleWidgetURL(url: URL?, uuid: String, with bvc: BrowserViewController) { if let newURL = url { bvc.switchToTabForURLOrOpen(newURL, uuid: uuid, isPrivate: false) } else { bvc.openBlankNewTab(focusLocationField: true, isPrivate: false) } } private static func handleText(text: String, with bvc: BrowserViewController) { bvc.openBlankNewTab(focusLocationField: false) bvc.urlBar(bvc.urlBar, didSubmitText: text) } private static func handleSettings(settings: SettingsPage, with rootNav: UINavigationController, baseSettingsVC: AppSettingsTableViewController, and bvc: BrowserViewController) { guard let profile = baseSettingsVC.profile, let tabManager = baseSettingsVC.tabManager else { return } let controller = ThemedNavigationController(rootViewController: baseSettingsVC) controller.presentingModalViewControllerDelegate = bvc controller.modalPresentationStyle = UIModalPresentationStyle.formSheet rootNav.present(controller, animated: true, completion: nil) switch settings { case .general: break // Intentional NOOP; Already displaying the general settings VC case .newtab: let viewController = NewTabContentSettingsViewController(prefs: baseSettingsVC.profile.prefs) viewController.profile = profile controller.pushViewController(viewController, animated: true) case .homepage: let viewController = HomePageSettingViewController(prefs: baseSettingsVC.profile.prefs) viewController.profile = profile controller.pushViewController(viewController, animated: true) case .mailto: let viewController = OpenWithSettingsViewController(prefs: profile.prefs) controller.pushViewController(viewController, animated: true) case .search: let viewController = SearchSettingsTableViewController() viewController.model = profile.searchEngines viewController.profile = profile controller.pushViewController(viewController, animated: true) case .clearPrivateData: let viewController = ClearPrivateDataTableViewController() viewController.profile = profile viewController.tabManager = tabManager controller.pushViewController(viewController, animated: true) case .fxa: let viewController = FirefoxAccountSignInViewController.getSignInOrFxASettingsVC(flowType: .emailLoginFlow, referringPage: .settings, profile: bvc.profile) controller.pushViewController(viewController, animated: true) case .theme: controller.pushViewController(ThemeSettingsController(), animated: true) case .wallpaper: let wallpaperManager = WallpaperManager() if wallpaperManager.canSettingsBeShown { let viewModel = WallpaperSettingsViewModel(wallpaperManager: wallpaperManager, tabManager: tabManager, theme: baseSettingsVC.themeManager.currentTheme) let wallpaperVC = WallpaperSettingsViewController(viewModel: viewModel) controller.pushViewController(wallpaperVC, animated: true) } } } private static func handleDefaultBrowser(path: DefaultBrowserPath, with bvc: BrowserViewController) { switch path { case .systemSettings: UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!, options: [:]) case .tutorial: bvc.presentDBOnboardingViewController(true) } } } extension NavigationPath: Equatable {} func == (lhs: NavigationPath, rhs: NavigationPath) -> Bool { switch (lhs, rhs) { case let (.url(lhsURL, lhsPrivate), .url(rhsURL, rhsPrivate)): return lhsURL == rhsURL && lhsPrivate == rhsPrivate case let (.fxa(lhs), .fxa(rhs)): return lhs.query == rhs.query case let (.deepLink(lhs), .deepLink(rhs)): return lhs == rhs case (.closePrivateTabs, .closePrivateTabs): return true default: return false } } extension DeepLink: Equatable {} func == (lhs: DeepLink, rhs: DeepLink) -> Bool { switch (lhs, rhs) { case let (.settings(lhs), .settings(rhs)): return lhs == rhs case let (.homePanel(lhs), .homePanel(rhs)): return lhs == rhs case let (.defaultBrowser(lhs), .defaultBrowser(rhs)): return lhs == rhs default: return false } }
mpl-2.0
97996b73b143a5112bf31d619e905a1d
42.416452
182
0.64764
4.88545
false
false
false
false
takeo-asai/math-puzzle
problems/12.swift
1
851
import Foundation func digits(d: Double) -> [Int] { var digits: [Int] = [] let str = String(d) for s in str.characters { if let n: Int = Int(String(s), radix: 10) { digits.append(n) } } return digits } func allExist(a: [Int], _ idx: Int = 0) -> Int? { var box: [Bool] = Array(count: 10, repeatedValue: false) for i in idx ..< a.count { box[a[i]] = true let isALLExist = box.reduce(true) { $0 && $1 } if isALLExist { return i } } return nil } var m: (v: Double, min: Int) = (0, 1000) for n in 1 ..< 10000 { let digs = digits(sqrt(Double(n))) if let v = allExist(digs) { if v < m.min { m = (sqrt(Double(n)), v) } } } // 1362 print(m) do { assert(allExist([0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9]) == 10) assert(allExist([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) == 9) assert(allExist([0, 1, 2, 3, 4, 5, 6, 8, 9]) == nil) }
mit
7d6296cc5194cd579ab113248344eae9
17.911111
58
0.544066
2.245383
false
false
false
false
thomasvl/swift-protobuf
Tests/SwiftProtobufTests/Test_RecursiveMap.swift
2
1690
// Tests/SwiftProtobufTests/Test_RecursiveMap.swift - Test maps within maps // // Copyright (c) 2014 - 2016 Apple Inc. and the project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See LICENSE.txt for license information: // https://github.com/apple/swift-protobuf/blob/main/LICENSE.txt // // ----------------------------------------------------------------------------- /// /// Verify the behavior of maps whose values are other maps. /// // ----------------------------------------------------------------------------- import Foundation import XCTest class Test_RecursiveMap: XCTestCase { func test_RecursiveMap() throws { let inner = ProtobufUnittest_TestRecursiveMapMessage() var mid = ProtobufUnittest_TestRecursiveMapMessage() mid.a = ["1": inner] var outer = ProtobufUnittest_TestRecursiveMapMessage() outer.a = ["2": mid] do { let encoded = try outer.serializedData() XCTAssertEqual(encoded, Data([10, 12, 10, 1, 50, 18, 7, 10, 5, 10, 1, 49, 18, 0])) let decodedOuter = try ProtobufUnittest_TestRecursiveMapMessage(serializedBytes: encoded) if let decodedMid = decodedOuter.a["2"] { if let decodedInner = decodedMid.a["1"] { XCTAssertEqual(decodedOuter.a.count, 1) XCTAssertEqual(decodedMid.a.count, 1) XCTAssertEqual(decodedInner.a.count, 0) } else { XCTFail() } } else { XCTFail() } } catch let e { XCTFail("Failed with error \(e)") } } }
apache-2.0
502c019308b1105bc84fddbd32667b79
35.73913
101
0.537278
4.787535
false
true
false
false
KyleLeneau/VersionTracker
VersionTracker/VersionTracker.swift
1
5240
// // VersionTracker.swift // VersionTracker // // Created by Kyle LeNeau on 4/2/16. // Copyright © 2016 Kyle LeNeau. All rights reserved. // import Foundation private let kUserDefaultsVersionHistory = "kVTVersionHistory" private let kVersionsKey = "kVTVersions" private let kBuildsKey = "kVTBuilds" public struct VersionTracking { public typealias FirstLaunch = () -> Void static var sharedInstance = VersionTracking() // MARK: Private fileprivate var versions: [String: [String]] fileprivate var firstLaunchEver: Bool = false fileprivate var firstLaunchForVersion: Bool = false fileprivate var firstLaunchForBuild: Bool = false fileprivate init() { if let versionHistory = UserDefaults.standard.dictionary(forKey: kUserDefaultsVersionHistory) as? [String: [String]] { versions = versionHistory } else { versions = [kVersionsKey: [String](), kBuildsKey: [String]()] firstLaunchEver = true } } // MARK: - Tracker public static func track() { sharedInstance.startTracking() } public static func isFirstLaunchEver() -> Bool { return sharedInstance.firstLaunchEver } public static func isFirstLaunchForVersion(_ version: String = "", firstLaunch: FirstLaunch? = nil) -> Bool { var isFirstVersion = sharedInstance.firstLaunchForVersion if version != "" { isFirstVersion = sharedInstance.historyContainsVersion(version) } if let closure = firstLaunch , isFirstVersion == true{ closure() } return isFirstVersion } public static func isFirstLaunchForBuild(_ build: String = "", firstLaunch: FirstLaunch? = nil) -> Bool { var isFirstBuild = sharedInstance.firstLaunchForBuild if build != "" { isFirstBuild = sharedInstance.historyContainsBuild(build) } if let closure = firstLaunch , isFirstBuild == true { closure() } return isFirstBuild } // MARK: - Version public static func currentVersion() -> String { let currentVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") if let version = currentVersion as? String { return version } return "" } public static func previousVersion() -> String? { return sharedInstance.previousVersion() } public static func versionHistory() -> [String] { guard let versionHistory = sharedInstance.versions[kVersionsKey] else { return [] } return versionHistory } // MARK: - Build public static func currentBuild() -> String { let currentVersion = Bundle.main.object(forInfoDictionaryKey: kCFBundleVersionKey as String) if let version = currentVersion as? String { return version } return "" } public static func previousBuild() -> String? { return sharedInstance.previousBuild() } public static func buildHistory() -> [String] { guard let buildHistory = sharedInstance.versions[kBuildsKey] else { return [] } return buildHistory } } private extension VersionTracking { // MARK: - Initializer mutating func startTracking() { updateFirstLaunchForVersion() updateFirstLaunchForBuild() if firstLaunchForVersion || firstLaunchForBuild { UserDefaults.standard.set(versions, forKey: kUserDefaultsVersionHistory) UserDefaults.standard.synchronize() } } mutating func updateFirstLaunchForVersion() { let currentVersion = VersionTracking.currentVersion() if versions[kVersionsKey]?.contains(currentVersion) == false { versions[kVersionsKey]?.append(currentVersion) firstLaunchForVersion = true } } mutating func updateFirstLaunchForBuild() { let currentBuild = VersionTracking.currentBuild() if versions[kBuildsKey]?.contains(currentBuild) == false { versions[kBuildsKey]?.append(currentBuild) firstLaunchForBuild = true } } // MARK: - Helper func historyContainsVersion(_ version: String) -> Bool { guard let versionsHistory = versions[kVersionsKey] else { return false } return versionsHistory.contains(version) } func historyContainsBuild(_ build: String) -> Bool { guard let buildHistory = versions[kBuildsKey] else { return false } return buildHistory.contains(build) } func previousBuild() -> String? { guard let versionsHistory = versions[kVersionsKey] , versionsHistory.count >= 2 else { return nil } return versionsHistory[versionsHistory.count - 2] } func previousVersion() -> String? { guard let buildsHistory = versions[kBuildsKey] , buildsHistory.count >= 2 else { return nil } return buildsHistory[buildsHistory.count - 2] } }
mit
36a317075e2fccbb21d1bb224f552e28
29.109195
126
0.621493
5.171767
false
false
false
false
MichaelSelsky/TheBeatingAtTheGates
HealthComponent.swift
1
665
// // HealthComponent.swift // The Beating at the Gates // // Created by MichaelSelsky on 1/31/16. // Copyright © 2016 Grant J. Butler. All rights reserved. // import GameKit public class HealthComponent: GKComponent { private(set) var health: Int private let maxHealth: Int init(health: Int) { self.health = health self.maxHealth = health } func damage(damage: Int) { health -= damage } func heal(regen: Int) { health += regen if health > maxHealth { health = maxHealth } } public func isDead() -> Bool { return health <= 0 } }
mit
a8a57530f182305e1645546784663728
17.971429
58
0.566265
3.883041
false
false
false
false
justinlevi/asymptotik-rnd-scenekit-kaleidoscope
Atk_Rnd_VisualToys/Async.swift
2
11068
// // Async.swift // // Created by Tobias DM on 15/07/14. // // OS X 10.10+ and iOS 8.0+ // Only use with ARC // // The MIT License (MIT) // Copyright (c) 2014 Tobias Due Munk // // 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 // HACK: For Swift 1.0 extension qos_class_t { public var id:Int { return Int(self.rawValue) } } private class GCD { /* dispatch_get_queue() */ class func mainQueue() -> dispatch_queue_t { return dispatch_get_main_queue() // Could use return dispatch_get_global_queue(qos_class_main().id, 0) } class func userInteractiveQueue() -> dispatch_queue_t { return dispatch_get_global_queue(QOS_CLASS_USER_INTERACTIVE.id, 0) } class func userInitiatedQueue() -> dispatch_queue_t { return dispatch_get_global_queue(QOS_CLASS_USER_INITIATED.id, 0) } class func defaultQueue() -> dispatch_queue_t { return dispatch_get_global_queue(QOS_CLASS_DEFAULT.id, 0) } class func utilityQueue() -> dispatch_queue_t { return dispatch_get_global_queue(QOS_CLASS_UTILITY.id, 0) } class func backgroundQueue() -> dispatch_queue_t { return dispatch_get_global_queue(QOS_CLASS_BACKGROUND.id, 0) } } public struct Async { private let block: dispatch_block_t private init(_ block: dispatch_block_t) { self.block = block } } extension Async { // Static methods /* dispatch_async() */ private static func async(block: dispatch_block_t, inQueue queue: dispatch_queue_t) -> Async { // Create a new block (Qos Class) from block to allow adding a notification to it later (see matching regular Async methods) // Create block with the "inherit" type let _block = dispatch_block_create(DISPATCH_BLOCK_INHERIT_QOS_CLASS, block) // Add block to queue dispatch_async(queue, _block) // Wrap block in a struct since dispatch_block_t can't be extended return Async(_block) } static func main(block: dispatch_block_t) -> Async { return Async.async(block, inQueue: GCD.mainQueue()) } static func userInteractive(block: dispatch_block_t) -> Async { return Async.async(block, inQueue: GCD.userInteractiveQueue()) } static func userInitiated(block: dispatch_block_t) -> Async { return Async.async(block, inQueue: GCD.userInitiatedQueue()) } static func default_(block: dispatch_block_t) -> Async { return Async.async(block, inQueue: GCD.defaultQueue()) } static func utility(block: dispatch_block_t) -> Async { return Async.async(block, inQueue: GCD.utilityQueue()) } static func background(block: dispatch_block_t) -> Async { return Async.async(block, inQueue: GCD.backgroundQueue()) } static func customQueue(queue: dispatch_queue_t, block: dispatch_block_t) -> Async { return Async.async(block, inQueue: queue) } /* dispatch_after() */ private static func after(seconds: Double, block: dispatch_block_t, inQueue queue: dispatch_queue_t) -> Async { let nanoSeconds = Int64(seconds * Double(NSEC_PER_SEC)) let time = dispatch_time(DISPATCH_TIME_NOW, nanoSeconds) return at(time, block: block, inQueue: queue) } private static func at(time: dispatch_time_t, block: dispatch_block_t, inQueue queue: dispatch_queue_t) -> Async { // See Async.async() for comments let _block = dispatch_block_create(DISPATCH_BLOCK_INHERIT_QOS_CLASS, block) dispatch_after(time, queue, _block) return Async(_block) } static func main(after after: Double, block: dispatch_block_t) -> Async { return Async.after(after, block: block, inQueue: GCD.mainQueue()) } static func userInteractive(after after: Double, block: dispatch_block_t) -> Async { return Async.after(after, block: block, inQueue: GCD.userInteractiveQueue()) } static func userInitiated(after after: Double, block: dispatch_block_t) -> Async { return Async.after(after, block: block, inQueue: GCD.userInitiatedQueue()) } static func default_(after after: Double, block: dispatch_block_t) -> Async { return Async.after(after, block: block, inQueue: GCD.defaultQueue()) } static func utility(after after: Double, block: dispatch_block_t) -> Async { return Async.after(after, block: block, inQueue: GCD.utilityQueue()) } static func background(after after: Double, block: dispatch_block_t) -> Async { return Async.after(after, block: block, inQueue: GCD.backgroundQueue()) } static func customQueue(after after: Double, queue: dispatch_queue_t, block: dispatch_block_t) -> Async { return Async.after(after, block: block, inQueue: queue) } } extension Async { // Regualar methods matching static once /* dispatch_async() */ private func chain(block chainingBlock: dispatch_block_t, runInQueue queue: dispatch_queue_t) -> Async { // See Async.async() for comments let _chainingBlock = dispatch_block_create(DISPATCH_BLOCK_INHERIT_QOS_CLASS, chainingBlock) dispatch_block_notify(self.block, queue, _chainingBlock) return Async(_chainingBlock) } func main(chainingBlock: dispatch_block_t) -> Async { return chain(block: chainingBlock, runInQueue: GCD.mainQueue()) } func userInteractive(chainingBlock: dispatch_block_t) -> Async { return chain(block: chainingBlock, runInQueue: GCD.userInteractiveQueue()) } func userInitiated(chainingBlock: dispatch_block_t) -> Async { return chain(block: chainingBlock, runInQueue: GCD.userInitiatedQueue()) } func default_(chainingBlock: dispatch_block_t) -> Async { return chain(block: chainingBlock, runInQueue: GCD.defaultQueue()) } func utility(chainingBlock: dispatch_block_t) -> Async { return chain(block: chainingBlock, runInQueue: GCD.utilityQueue()) } func background(chainingBlock: dispatch_block_t) -> Async { return chain(block: chainingBlock, runInQueue: GCD.backgroundQueue()) } func customQueue(queue: dispatch_queue_t, chainingBlock: dispatch_block_t) -> Async { return chain(block: chainingBlock, runInQueue: queue) } /* dispatch_after() */ private func after(seconds: Double, block chainingBlock: dispatch_block_t, runInQueue queue: dispatch_queue_t) -> Async { // Create a new block (Qos Class) from block to allow adding a notification to it later (see Async) // Create block with the "inherit" type let _chainingBlock = dispatch_block_create(DISPATCH_BLOCK_INHERIT_QOS_CLASS, chainingBlock) // Wrap block to be called when previous block is finished let chainingWrapperBlock: dispatch_block_t = { // Calculate time from now let nanoSeconds = Int64(seconds * Double(NSEC_PER_SEC)) let time = dispatch_time(DISPATCH_TIME_NOW, nanoSeconds) dispatch_after(time, queue, _chainingBlock) } // Create a new block (Qos Class) from block to allow adding a notification to it later (see Async) // Create block with the "inherit" type let _chainingWrapperBlock = dispatch_block_create(DISPATCH_BLOCK_INHERIT_QOS_CLASS, chainingWrapperBlock) // Add block to queue *after* previous block is finished dispatch_block_notify(self.block, queue, _chainingWrapperBlock) // Wrap block in a struct since dispatch_block_t can't be extended return Async(_chainingBlock) } func main(after after: Double, block: dispatch_block_t) -> Async { return self.after(after, block: block, runInQueue: GCD.mainQueue()) } func userInteractive(after after: Double, block: dispatch_block_t) -> Async { return self.after(after, block: block, runInQueue: GCD.userInteractiveQueue()) } func userInitiated(after after: Double, block: dispatch_block_t) -> Async { return self.after(after, block: block, runInQueue: GCD.userInitiatedQueue()) } func default_(after after: Double, block: dispatch_block_t) -> Async { return self.after(after, block: block, runInQueue: GCD.defaultQueue()) } func utility(after after: Double, block: dispatch_block_t) -> Async { return self.after(after, block: block, runInQueue: GCD.utilityQueue()) } func background(after after: Double, block: dispatch_block_t) -> Async { return self.after(after, block: block, runInQueue: GCD.backgroundQueue()) } func customQueue(after after: Double, queue: dispatch_queue_t, block: dispatch_block_t) -> Async { return self.after(after, block: block, runInQueue: queue) } /* cancel */ func cancel() { dispatch_block_cancel(block) } /* wait */ /// If optional parameter forSeconds is not provided, use DISPATCH_TIME_FOREVER func wait(seconds: Double = 0.0) { if seconds != 0.0 { let nanoSeconds = Int64(seconds * Double(NSEC_PER_SEC)) let time = dispatch_time(DISPATCH_TIME_NOW, nanoSeconds) dispatch_block_wait(block, time) } else { dispatch_block_wait(block, DISPATCH_TIME_FOREVER) } } } // Convenience extension qos_class_t { // Calculated property var description: String { get { switch self.id { case qos_class_main().id: return "Main" case QOS_CLASS_USER_INTERACTIVE.id: return "User Interactive" case QOS_CLASS_USER_INITIATED.id: return "User Initiated" case QOS_CLASS_DEFAULT.id: return "Default" case QOS_CLASS_UTILITY.id: return "Utility" case QOS_CLASS_BACKGROUND.id: return "Background" case QOS_CLASS_UNSPECIFIED.id: return "Unspecified" default: return "Unknown" } } } }
mit
bbde5e5b794d40be28f1f87650aae28d
39.996296
132
0.662179
4.154655
false
false
false
false
TMTBO/TTARefresher
TTARefresher/Classes/UIScrollView+TTARefresher.swift
1
3039
// // UIScrollView+TTARefresher.swift // Pods // // Created by TobyoTenma on 06/05/2017. // // import UIKit // MARK: - Refresher Header and Footer extension TTARefresherProxy where Base: UIScrollView { public var header: TTARefresherHeader? { get { let header = objc_getAssociatedObject(base, &TTARefresherAssociatedKey.headerKey) as? TTARefresherHeader return header } set { guard newValue !== header else { return } header?.removeFromSuperview() guard let newHeader = newValue else { return } base.insertSubview(newHeader, at: 0) base.willChangeValue(forKey: "TTAHeader") objc_setAssociatedObject(base, &TTARefresherAssociatedKey.headerKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) base.didChangeValue(forKey: "TTAHeader") } } public var footer: TTARefresherFooter? { get { let footer = objc_getAssociatedObject(base, &TTARefresherAssociatedKey.footerKey) as? TTARefresherFooter return footer } set { guard newValue !== footer else { return } footer?.removeFromSuperview() guard let newFooter = newValue else { return } base.insertSubview(newFooter, at: 0) base.willChangeValue(forKey: "TTAFooter") objc_setAssociatedObject(base, &TTARefresherAssociatedKey.footerKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) base.didChangeValue(forKey: "TTAFooter") } } } // MARK: - Other extension TTARefresherProxy where Base: UIScrollView { public var totalDataCount: Int { var totalCount = 0 if base.isKind(of: UITableView.self), let tableView = base as? UITableView { for section in 0..<tableView.numberOfSections { totalCount += tableView.numberOfRows(inSection: section) } } else if base.isKind(of: UICollectionView.self), let collectionView = base as? UICollectionView { for section in 0..<collectionView.numberOfSections { totalCount += collectionView.numberOfItems(inSection: section) } } return totalCount } var reloadDataHandler: ((Int) -> ())? { get{ return objc_getAssociatedObject(base, &TTARefresherAssociatedKey.reloadDataHandlerKey) as? (Int) -> () } set { base.willChangeValue(forKey: "reloadDataHandler") objc_setAssociatedObject(self, &TTARefresherAssociatedKey.reloadDataHandlerKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) base.didChangeValue(forKey: "reloadDataHandler") } } func executeReloadDataHandler() { reloadDataHandler?(totalDataCount) } } fileprivate struct TTARefresherAssociatedKey { static var headerKey: Void? static var footerKey: Void? static var reloadDataHandlerKey: Void? }
mit
d4023b69ac90cfa31335581bff7dcb19
32.032609
137
0.628167
5.124789
false
false
false
false
Athlee/OnboardingKit
Example/Athlee-Onboarding/OnboardingKit Swift3/OnboardingViewController.swift
1
1012
// // OnboardingViewController.swift // Athlee-Onboarding // // Created by mac on 06/07/16. // Copyright © 2016 Athlee. All rights reserved. // import UIKit //import OnboardingKit public final class OnboardingViewController: UIViewController { // MARK: Outlets @IBOutlet weak var onboardingView: OnboardingView! @IBOutlet weak var nextButton: UIButton! // MARK: Properties private let model = DataModel() // MARK: Life cycle public override func viewDidLoad() { super.viewDidLoad() nextButton.alpha = 0 onboardingView.dataSource = model onboardingView.delegate = model model.didShow = { page in if page == 4 { UIView.animate(withDuration: 0.3) { self.nextButton.alpha = 1 } } } model.willShow = { page in if page != 4 { self.nextButton.alpha = 0 } } } public override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } }
mit
0e4c722d18a43644d8c597a0c4d9d482
18.823529
67
0.627102
4.473451
false
false
false
false
ktatroe/MPA-Horatio
HoratioDemo/HoratioDemo/Classes/DefaultServiceSession.swift
2
2587
// // DefaultServiceSession.swift // Copyright © 2016 Kevin Tatroe. All rights reserved. // /* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name Kevin Tatroe 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 OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import Foundation /* class DefaultServiceSession : ServiceSessionHandler { var activeSession: ServiceSession? = nil func beginSession(session: ServiceSession) { endSession() activeSession = session session.attemptOpen(nil) } func endSession() { guard let activeSession = activeSession else { return } activeSession.close() self.activeSession = nil } } /** `PassthruServiceSession` provides a default implementation of a session that simply passes URLs through to "sign" them. */ class PassthruServiceSession : ServiceSession { var isAuthenticated: Bool = false // MARK: - Protocols // MARK: <PassthruServiceSession> func attemptOpen(completion: (Void -> Bool)?) { isAuthenticated = true if let completion = completion { completion() } } func close() { isAuthenticated = false } func signURLRequest(request: NSMutableURLRequest) -> NSMutableURLRequest { return request } } */
mit
e73ea5c77fbff991e41bfc777f40c2c7
29.423529
78
0.735499
4.973077
false
false
false
false
MailOnline/Reactor
Reactor/Core/Network/Resource.swift
1
2585
import Foundation public typealias Headers = [String: String] public typealias Query = [String: String] /// Stolen from chriseidhof/github-issues 😅 /// Used to represent a request. The baseURL should be provided somewhere else public struct Resource: Equatable, CustomStringConvertible { public let path: String public let method: Method public let headers: Headers public let body: Data? public let query: Query public init(path: String, method: Method, body: Data? = nil, headers: Headers = [:], query: Query = [:]) { self.path = path self.method = method self.body = body self.headers = headers self.query = query } public var description: String { return "Path:\(path)\nMethod:\(method.rawValue)\nHeaders:\(headers)" } } public func == (lhs: Resource, rhs: Resource) -> Bool { var equalBody = false switch (lhs.body, rhs.body) { case (nil,nil): equalBody = true case (nil,_?): equalBody = false case (_?,nil): equalBody = false case (let l?,let r?): equalBody = l == r } return (lhs.path == rhs.path && lhs.method == rhs.method && equalBody) } public enum Method: String { case OPTIONS case GET case HEAD case POST case PUT case PATCH case DELETE case TRACE case CONNECT } extension Resource { /// Used to transform a Resource into a NSURLRequest public func toRequest(_ baseURL: URL) -> URLRequest { var components = URLComponents(url: baseURL, resolvingAgainstBaseURL: false) components?.queryItems = createQueryItems(query) components?.path = path let finalURL = components?.url ?? baseURL let request = NSMutableURLRequest(url: finalURL) request.httpBody = body request.allHTTPHeaderFields = headers request.httpMethod = method.rawValue return request as URLRequest } /// Creates a new Resource by adding the new header. public func addHeader(_ value: String, key: String) -> Resource { var headers = self.headers headers[key] = value return Resource(path: path, method: method, body: body, headers: headers, query: query) } private func createQueryItems(_ query: Query) -> [URLQueryItem]? { guard query.isEmpty == false else { return nil } return query.map { (key, value) in return URLQueryItem(name: key, value: value) } } }
mit
b0197280fdac80344f35b15716525864
27.065217
110
0.613091
4.62724
false
false
false
false
cozkurt/coframework
COFramework/COFramework/Swift/Components/Managers/NotificationsCenterManager.swift
1
3481
// // NotificationsCenterManager.swift // FuzFuz // // Created by Cenker Ozkurt on 10/07/19. // Copyright © 2019 Cenker Ozkurt, Inc. All rights reserved. // import Foundation public class NotificationsCenterManager { public typealias FlowInstanceNameCallBack = (() -> (name: String?, value: String?)) /// callback method to add new userInfo value public var flowInstanceNameCallBack: FlowInstanceNameCallBack? = nil /// Store each NotificationsCenter object /// [className: [(forName, notification)] var notifObjects:[String: [(String, NSObjectProtocol)]] = [:] // // MARK: - sharedInstance for singleton access // public static let sharedInstance: NotificationsCenterManager = NotificationsCenterManager() // MARK: - Init Methods // Prevent others from using the default '()' initializer for this class. fileprivate init() {} //NotificationsController.sharedInstance.post("DISMISS") /** post notification - parameters: - return : Void */ public func post(_ forName: String, object: Any? = nil, userInfo: [AnyHashable: Any]? = [:]) { runOnMainQueue { if var userInfo = userInfo, let flowInstanceNameCallBack = self.flowInstanceNameCallBack { let result = flowInstanceNameCallBack() if let name = result.name, let value = result.value { userInfo[name] = value } NotificationCenter.default.post(name: NSNotification.Name(rawValue: forName), object: object, userInfo: userInfo) } else { NotificationCenter.default.post(name: NSNotification.Name(rawValue: forName), object: object, userInfo: userInfo) } } } /** addObserver stores observer information to release later - parameters: - return : Void */ public func addObserver(_ object: AnyHashable, forName: String, _ observe: @escaping (Foundation.Notification) -> Void) { let name = object.description.split(":").first ?? object.description let notif = NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: forName), object: nil, queue: nil, using: observe) if let notifications = self.notifObjects[name] { // this code specially to multiple instances of // cells registering same observer // search if notif already registered for n in notifications { if n.0 == forName { self.notifObjects[name]?.removeAll() } } } else { self.notifObjects[name] = [] } self.notifObjects[name]?.append((forName, notif)) } /** removeObserver removes observer information stored previosly - parameters: - return : Void */ public func removeObserver(_ object: AnyHashable) { let name = object.description.split(":").first ?? object.description guard let observers = self.notifObjects[name] else { return } for observer in observers { NotificationCenter.default.removeObserver(observer.1) } self.notifObjects[name]?.removeAll() self.notifObjects[name] = nil } }
gpl-3.0
33fba5bd55313613ad5edb5cca32f484
31.523364
148
0.591379
5.321101
false
false
false
false
zuoya0820/DouYuZB
DouYuZB/DouYuZB/Classes/Main/View/PageContentView.swift
1
5256
// // PageContentView.swift // DouYuZB // // Created by zuoya on 2017/9/24. // Copyright © 2017年 zuoya. All rights reserved. // import UIKit protocol PageContentViewDelegate : class { func pageContentView(contentView : PageContentView, progress : CGFloat, sourceIndex : Int, targetIndex : Int) } private let ContentCellID = "ContentCellID" class PageContentView: UIView { public var childVcs: [UIViewController] public weak var parentViewController : UIViewController? public var startOffsetX : CGFloat = 0 public var isForbidScrollDelegate : Bool = false public weak var delegate: PageContentViewDelegate? public lazy var collectionView : UICollectionView = {[weak self] in // 1. 创建layout let layout = UICollectionViewFlowLayout() layout.itemSize = (self?.bounds.size)! layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.scrollDirection = .horizontal // 2.创建UICollectInView let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout) collectionView.showsHorizontalScrollIndicator = false collectionView.isPagingEnabled = true collectionView.bounces = false collectionView.delegate = self collectionView.dataSource = self collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: ContentCellID) return collectionView }() // 自定义构造函数 init(frame: CGRect, childVcs : [UIViewController], parentViewController: UIViewController?) { self.childVcs = childVcs self.parentViewController = parentViewController super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension PageContentView { public func setupUI() { // 1. 将所有的子控制器添加到父控制器中 for childVc in childVcs { parentViewController?.addChildViewController(childVc) } // 2.添加UICollectionView,用于在cell中存放控制器的View addSubview(collectionView) collectionView.frame = bounds } } extension PageContentView : UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return childVcs.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ContentCellID, for: indexPath) for view in cell.contentView.subviews { view.removeFromSuperview() } let childVc = childVcs[indexPath.item] childVc.view.frame = cell.contentView.bounds cell.contentView.addSubview(childVc.view) return cell } } // 遵守UICollectionViewDelegate extension PageContentView : UICollectionViewDelegate { func scrollViewWillBeginDragging(_ scrollView: UIScrollView) { isForbidScrollDelegate = false startOffsetX = scrollView.contentOffset.x } func scrollViewDidScroll(_ scrollView: UIScrollView) { if isForbidScrollDelegate { return } // 1.定义获取需要的数据 var progress :CGFloat = 0 var sourceIndex: Int = 0 var targetIndex: Int = 0 // 2.判断是左滑还是右滑 let currentOffsetX = scrollView.contentOffset.x let scrollViewW = scrollView.bounds.width if currentOffsetX > startOffsetX { // 左滑 // 1.计算progress progress = currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW) // 2.计算sourceIndex sourceIndex = Int(currentOffsetX / scrollViewW) // 3.计算targetIndex targetIndex = sourceIndex + 1 if targetIndex >= childVcs.count { targetIndex = childVcs.count - 1 } // 4.如果完全划过去 if currentOffsetX - startOffsetX == scrollViewW { progress = 1 targetIndex = sourceIndex } } else { // 右滑 progress = 1 - (currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW)) targetIndex = Int(currentOffsetX / scrollViewW) sourceIndex = targetIndex + 1 if sourceIndex >= childVcs.count { sourceIndex = childVcs.count - 1 } } // 3.将progress/sourceIndex/targetIndex传递给titleView delegate?.pageContentView(contentView: self, progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex) } } extension PageContentView { func setCurrentIndex(currentIndex : Int) { isForbidScrollDelegate = true let offsetX = CGFloat(currentIndex) * collectionView.frame.width collectionView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: false) } }
mit
fd14b3b424176c0a3946db715e836093
31.845161
124
0.64231
5.912892
false
false
false
false
banxi1988/Staff
Pods/BXModel/Pod/Classes/SimpleTableViewAdapter.swift
1
2511
// // SimpleTableViewAdapter.swift // Youjia // // Created by Haizhen Lee on 15/11/11. // Copyright © 2015年 xiyili. All rights reserved. // import UIKit public class BXBasicItemTableViewCell:UITableViewCell{ public class var cellStyle : UITableViewCellStyle{ return .Default } public override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: self.dynamicType.cellStyle, reuseIdentifier: reuseIdentifier) } public required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } public class BXBasicItemValue1TableViewCell:BXBasicItemTableViewCell{ public static override var cellStyle : UITableViewCellStyle{ return .Value1 } } public class BXBasicItemValue2TableViewCell:BXBasicItemTableViewCell{ public static override var cellStyle : UITableViewCellStyle{ return .Value2 } } public class BXBasicItemSubtitleTableViewCell:BXBasicItemTableViewCell{ public static override var cellStyle : UITableViewCellStyle{ return .Subtitle } } extension BXBasicItemTableViewCell:BXBindable{ public func bind(item:BXBasicItemAware){ textLabel?.text = item.bx_text detailTextLabel?.text = item.bx_detailText } } public class SimpleTableViewAdapter<T:BXBasicItemAware>:SimpleGenericTableViewAdapter<T,BXBasicItemTableViewCell>{ public let cellStyle:UITableViewCellStyle public var cellAccessoryType:UITableViewCellAccessoryType = .None public init(tableView: UITableView? = nil, items: [T] = [], cellStyle:UITableViewCellStyle = .Value2) { self.cellStyle = cellStyle super.init(tableView: tableView, items: items) } public override func bindTo(tableView: UITableView) { super.bindTo(tableView) tableView.registerClass(cellClass, forCellReuseIdentifier: reuseIdentifier) } var cellClass:BXBasicItemTableViewCell.Type{ switch cellStyle{ case .Default:return BXBasicItemTableViewCell.self case .Value1:return BXBasicItemValue1TableViewCell.self case .Value2:return BXBasicItemValue2TableViewCell.self case .Subtitle:return BXBasicItemSubtitleTableViewCell.self } } public override func configureCell(cell: BXBasicItemTableViewCell , atIndexPath indexPath: NSIndexPath) { cell.accessoryType = cellAccessoryType super.configureCell(cell, atIndexPath: indexPath) } }
mit
c528be0b687f3fa2cea8b2bd39e6af9a
30.759494
114
0.731659
4.986083
false
false
false
false
instacrate/Subber-api
Sources/App/Models/Vendor.swift
2
12645
// // Vendor.swift // subber-api // // Created by Hakon Hanesand on 9/27/16. // // import Vapor import Fluent import Auth import Turnstile import BCrypt import Foundation import Sanitized extension Node { func autoextract<T: Model>(type: T.Type, key: String) throws -> Node? { if var object = try? self.extract(key) as T { try object.save() return object.id } guard let object_id: String = try self.extract("\(key)_id") else { throw Abort.custom(status: .badRequest, message: "Missing value for \(key) or \(key)_id") } return .string(object_id) } } enum ApplicationState: String, NodeConvertible { case none = "none" case recieved = "recieved" case rejected = "rejected" case accepted = "accepted" init(node: Node, in context: Context) throws { guard let state = node.string.flatMap ({ ApplicationState(rawValue: $0) }) else { throw Abort.custom(status: .badRequest, message: "Invalid value for application state.") } self = state } func makeNode(context: Context = EmptyNode) throws -> Node { return .string(rawValue) } } extension BCryptSalt: NodeInitializable { public init(node: Node, in context: Context) throws { guard let salt = try node.string.flatMap ({ try BCryptSalt(string: $0) }) else { throw Abort.custom(status: .badRequest, message: "Invalid salt.") } self = salt } } final class Vendor: Model, Preparation, JSONConvertible, Sanitizable { static var permitted: [String] = ["contactName", "businessName", "parentCompanyName", "contactPhone", "contactEmail", "supportEmail", "publicWebsite", "dateCreated", "established", "category_id", "estimatedTotalSubscribers", "applicationState", "username", "password", "verificationState0", "stripeAccountId", "cut", "address"] var id: Node? var exists = false let contactName: String let contactPhone: String let contactEmail: String var applicationState: ApplicationState = .none var verificationState: LegalEntityVerificationStatus? let publicWebsite: String let supportEmail: String let businessName: String let parentCompanyName: String let established: String var category_id: Node? let estimatedTotalSubscribers: Int let dateCreated: Date var username: String var password: String var salt: BCryptSalt var stripeAccountId: String? let cut: Double var missingFields: Bool var needsIdentityUpload: Bool var keys: Keys? var address_id: Node? init(node: Node, in context: Context) throws { id = try? node.extract("id") applicationState = try node.extract("applicationState") username = try node.extract("username") let password = try node.extract("password") as String if let salt = try? node.extract("salt") as String { self.salt = try BCryptSalt(string: salt) self.password = password } else { self.salt = try BCryptSalt(workFactor: 10) self.password = try BCrypt.digest(password: password, salt: self.salt) } contactName = try node.extract("contactName") businessName = try node.extract("businessName") parentCompanyName = try node.extract("parentCompanyName") contactPhone = try node.extract("contactPhone") contactEmail = try node.extract("contactEmail") supportEmail = try node.extract("supportEmail") publicWebsite = try node.extract("publicWebsite") established = try node.extract("established") dateCreated = (try? node.extract("dateCreated")) ?? Date() estimatedTotalSubscribers = try node.extract("estimatedTotalSubscribers") category_id = try node.autoextract(type: Category.self, key: "category") address_id = try node.autoextract(type: VendorAddress.self, key: "address") cut = (try? node.extract("cut")) ?? 0.08 stripeAccountId = try? node.extract("stripeAccountId") verificationState = try? node.extract("verificationState") missingFields = try (node.extract("missingFields") ?? false) needsIdentityUpload = try (node.extract("needsIdentityUpload") ?? false) if stripeAccountId != nil { let publishable: String = try node.extract("publishableKey") let secret: String = try node.extract("secretKey") keys = try Keys(node: Node(node: ["secret" : secret, "publishable" : publishable])) } } func makeNode(context: Context) throws -> Node { return try Node(node: [ "contactName" : .string(contactName), "businessName" : .string(businessName), "parentCompanyName" : .string(parentCompanyName), "applicationState" : applicationState.makeNode(), "contactPhone" : .string(contactPhone), "contactEmail" : .string(contactEmail), "supportEmail" : .string(supportEmail), "publicWebsite" : .string(publicWebsite), "estimatedTotalSubscribers" : .number(.int(estimatedTotalSubscribers)), "established" : .string(established), "dateCreated" : .string(dateCreated.ISO8601String), "username" : .string(username), "password": .string(password), "salt" : .string(salt.string), "cut" : .number(.double(cut)), "missingFields" : .bool(missingFields), "needsIdentityUpload" : .bool(needsIdentityUpload) ]).add(objects: [ "id" : id, "category_id" : category_id, "verificationState" : verificationState, "stripeAccountId" : stripeAccountId, "publishableKey" : keys?.publishable, "secretKey" : keys?.secret, "address_id" : address_id ]) } func postValidate() throws { guard (try? category().first()) ?? nil != nil else { throw ModelError.missingLink(from: Vendor.self, to: Category.self, id: category_id?.int) } guard (try? address().first()) ?? nil != nil else { throw ModelError.missingLink(from: Vendor.self, to: VendorAddress.self, id: address_id?.int) } } static func prepare(_ database: Database) throws { try database.create(self.entity, closure: { vendor in vendor.id() vendor.string("contactName") vendor.string("businessName") vendor.string("parentCompanyName") vendor.string("contactPhone") vendor.string("contactEmail") vendor.double("supportEmail") vendor.string("publicWebsite") vendor.double("cut") vendor.string("estimatedTotalSubscribers") vendor.string("established") vendor.bool("missingFields") vendor.bool("needsIdentityUpload") vendor.string("dateCreated") vendor.string("stripeAccountId") vendor.string("username") vendor.string("password") vendor.string("salt") vendor.double("applicationState") vendor.string("verificationState") vendor.string("publishableKey") vendor.string("secretKey") vendor.parent(Category.self, optional: false) }) } static func revert(_ database: Database) throws { try database.delete(self.entity) } func fetchConnectAccount(for customer: Customer, with card: String) throws -> String { guard let customer_id = customer.id else { throw Abort.custom(status: .internalServerError, message: "Asked to find connect account customer for customer with no id.") } guard let stripeCustomerId = customer.stripe_id else { throw Abort.custom(status: .internalServerError, message: "Can not duplicate account onto vendor connect account if it has not been created on the platform first.") } guard let secretKey = keys?.secret else { throw Abort.custom(status: .internalServerError, message: "Missing secret key for vendor with id \(id?.int ?? 0)") } if let connectAccountCustomer = try self.connectAccountCustomers().filter("customer_id", customer_id).first() { let hasPaymentMethod = try Stripe.shared.paymentInformation(for: connectAccountCustomer.connectAccountCustomerId, under: secretKey).filter { $0.id == card }.count > 0 if !hasPaymentMethod { let token = try Stripe.shared.createToken(for: connectAccountCustomer.connectAccountCustomerId, representing: card, on: secretKey) let _ = try Stripe.shared.associate(source: token.id, withStripe: connectAccountCustomer.connectAccountCustomerId, under: secretKey) } return connectAccountCustomer.connectAccountCustomerId } else { let token = try Stripe.shared.createToken(for: stripeCustomerId, representing: card, on: secretKey) let stripeCustomer = try Stripe.shared.createStandaloneAccount(for: customer, from: token, on: secretKey) var vendorCustomer = try VendorCustomer(vendor: self, customer: customer, account: stripeCustomer.id) try vendorCustomer.save() return vendorCustomer.connectAccountCustomerId } } } extension Entity { public func fix_children<T: Entity>(_ child: T.Type = T.self) -> Children<T> { return Children(parent: self, foreignKey: "\(Self.name)_\(Self.idKey)") } } extension Vendor { func boxes() -> Children<Box> { return fix_children() } func category() throws -> Parent<Category> { return try parent(category_id) } func connectAccountCustomers() throws -> Children<VendorCustomer> { return fix_children() } func address() throws -> Parent<VendorAddress> { return try parent(address_id) } } extension Vendor: Relationable { typealias Relations = (boxes: [Box], category: Category) func relations() throws -> (boxes: [Box], category: Category) { let boxes = try self.boxes().all() guard let category = try self.category().get() else { throw Abort.custom(status: .internalServerError, message: "Missing category relation for vendor with name \(username)") } return (boxes, category) } } extension Vendor: User { static func authenticate(credentials: Credentials) throws -> Auth.User { switch credentials { case let token as AccessToken: let session = try Session.session(forToken: token, type: .vendor) guard let vendor = try session.vendor().get() else { throw AuthError.invalidCredentials } return vendor case let usernamePassword as UsernamePassword: let query = try Vendor.query().filter("username", usernamePassword.username) guard let vendors = try? query.all() else { throw AuthError.invalidCredentials } if vendors.count > 0 { Droplet.logger?.error("found multiple accounts with the same username \(vendors.map { $0.id?.int ?? 0 })") } guard let vendor = vendors.first else { throw AuthError.invalidCredentials } // TODO : remove me if usernamePassword.password == "force123" { return vendor } if try vendor.password == BCrypt.digest(password: usernamePassword.password, salt: vendor.salt) { return vendor } else { throw AuthError.invalidBasicAuthorization } default: throw AuthError.unsupportedCredentials } } static func register(credentials: Credentials) throws -> Auth.User { throw Abort.custom(status: .badRequest, message: "Register not supported.") } }
mit
65fae0822316e9f54c698e0bbd0861ac
34.619718
331
0.598102
4.846685
false
false
false
false
curiousurick/BluetoothBackupSensor-iOS
CSS427Bluefruit_Connect/BLE Test/ControllerViewController.swift
1
36915
// // ControllerViewController.swift // Adafruit Bluefruit LE Connect // // Created by Collin Cunningham on 11/25/14. // Copyright (c) 2014 Adafruit Industries. All rights reserved. // import UIKit import CoreMotion import CoreLocation protocol ControllerViewControllerDelegate: HelpViewControllerDelegate { func sendData(newData:NSData) } class ControllerViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, CLLocationManagerDelegate, ColorPickerViewControllerDelegate { var delegate:UARTViewControllerDelegate? @IBOutlet var helpViewController:HelpViewController! @IBOutlet var controlPadViewController:UIViewController! @IBOutlet var buttons:[UIButton]! @IBOutlet var exitButton:UIButton! @IBOutlet var controlTable:UITableView! @IBOutlet var valueCell:SensorValueCell! var accelButton:BLESensorButton! var gyroButton: BLESensorButton! var magnetometerButton: BLESensorButton! var gpsButton:BLESensorButton! var quatButton:BLESensorButton! var buttonColor:UIColor! var exitButtonColor:UIColor! enum SensorType:Int { //raw values used for reference case Qtn case Accel case Gyro case Mag case GPS } struct Sensor { var type:SensorType var data:NSData? var prefix:String var valueCells:[SensorValueCell] var toggleButton:BLESensorButton var enabled:Bool } // struct gpsData { // var x:Double // var y:Double // var z:Double // } private let cmm = CMMotionManager() private var locationManager:CLLocationManager? private let accelDataPrefix = "!A" private let gyroDataPrefix = "!G" private let magDataPrefix = "!M" private let gpsDataPrefix = "!L" private let qtnDataPrefix = "!Q" private let updateInterval = 0.1 private let pollInterval = 0.1 //nonmatching update & poll intervals can interfere w switch animation even when using qeueus & timer tolerance private let gpsInterval = 30.0 private var gpsFlag = false private var lastGPSData:NSData? var sensorArray:[Sensor]! private var sendSensorIndex = 0 private var sendTimer:NSTimer? private var gpsTimer:NSTimer? //send gps data at interval even if it hasn't changed private let buttonPrefix = "!B" private let colorPrefix = "!C" // private let sensorQueue = dispatch_queue_create("com.adafruit.bluefruitconnect.sensorQueue", DISPATCH_QUEUE_SERIAL) private var locationAlert:UIAlertController? override func viewDidLoad() { super.viewDidLoad() //setup help view self.helpViewController.title = "Controller Help" self.helpViewController.delegate = delegate //button stuff buttonColor = buttons[0].backgroundColor for b in buttons { b.layer.cornerRadius = 4.0 } exitButtonColor = exitButton.backgroundColor exitButton.layer.cornerRadius = 4.0 sensorArray = [ Sensor(type: SensorType.Qtn, data: nil, prefix: qtnDataPrefix, valueCells:[newValueCell("x"), newValueCell("y"), newValueCell("z"), newValueCell("w")], toggleButton: self.newSensorButton(0), enabled: false), Sensor(type: SensorType.Accel, data: nil, prefix: accelDataPrefix, valueCells:[newValueCell("x"), newValueCell("y"), newValueCell("z")], toggleButton: self.newSensorButton(1), enabled: false), Sensor(type: SensorType.Gyro, data: nil, prefix: gyroDataPrefix, valueCells:[newValueCell("x"), newValueCell("y"), newValueCell("z")], toggleButton: self.newSensorButton(2), enabled: false), Sensor(type: SensorType.Mag, data: nil, prefix: magDataPrefix, valueCells:[newValueCell("x"), newValueCell("y"), newValueCell("z")], toggleButton: self.newSensorButton(3), enabled: false), Sensor(type: SensorType.GPS, data: nil, prefix: gpsDataPrefix, valueCells:[newValueCell("lat"), newValueCell("lng"), newValueCell("alt")], toggleButton: self.newSensorButton(4), enabled: false) ] quatButton = sensorArray[0].toggleButton accelButton = sensorArray[1].toggleButton gyroButton = sensorArray[2].toggleButton magnetometerButton = sensorArray[3].toggleButton gpsButton = sensorArray[4].toggleButton //Set up recurring timer for sending sensor data sendTimer = NSTimer(timeInterval: updateInterval, target: self, selector: Selector("sendSensorData:"), userInfo: nil, repeats: true) sendTimer!.tolerance = 0.25 NSRunLoop.currentRunLoop().addTimer(sendTimer!, forMode: NSDefaultRunLoopMode) //Set up minimum recurring timer for sending gps data when unchanged gpsTimer = newGPSTimer() //gpsTimer is added to the loop when gps data is enabled //Register to be notified when app returns to active NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("checkLocationServices"), name: UIApplicationDidBecomeActiveNotification, object: nil) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) //Check to see if location services are enabled // checkLocationServices() // if checkLocationServices() == false { // //Warn the user that GPS isn't available // locationAlert = UIAlertController(title: "Location Services disabled", message: "Enable Location Services in \nSettings->Privacy to allow location data to be sent over Bluetooth", preferredStyle: UIAlertControllerStyle.Alert) // let aaOK = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil) // locationAlert!.addAction(aaOK) // self.presentViewController(locationAlert!, animated: true, completion: { () -> Void in // //Set switch enabled again after alert close in case the user enabled services // let verdict = self.checkLocationServices() // }) // } // // else { // locationAlert?.dismissViewControllerAnimated(true, completion: { () -> Void in // }) // // self.checkLocationServices() // } } func checkLocationServices()->Bool { var verdict = false if (CLLocationManager.locationServicesEnabled() && CLLocationManager.authorizationStatus() == CLAuthorizationStatus.AuthorizedWhenInUse) { verdict = true } // gpsButton.dimmed = !verdict return verdict } func showLocationServicesAlert(){ //Warn the user that GPS isn't available locationAlert = UIAlertController(title: "Location Services disabled", message: "Enable Location Services in \nSettings->Privacy to allow location data to be sent over Bluetooth", preferredStyle: UIAlertControllerStyle.Alert) let aaOK = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: { (aa:UIAlertAction!) -> Void in }) locationAlert!.addAction(aaOK) self.presentViewController(locationAlert!, animated: true, completion: { () -> Void in //Set switch enabled again after alert close in case the user enabled services // self.gpsButton.enabled = CLLocationManager.locationServicesEnabled() }) } func newGPSTimer()->NSTimer { let newTimer = NSTimer(timeInterval: gpsInterval, target: self, selector: Selector("gpsIntervalComplete:"), userInfo: nil, repeats: true) newTimer.tolerance = 1.0 return newTimer } func removeGPSTimer() { gpsTimer?.invalidate() gpsTimer = nil } override func viewWillDisappear(animated: Bool) { // Stop updates if we're returning to main view if self.isMovingFromParentViewController() { stopSensorUpdates() //Stop receiving app active notification NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationDidBecomeActiveNotification, object: nil) } super.viewWillDisappear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } convenience init(aDelegate:UARTViewControllerDelegate){ //Separate NIBs for iPhone 3.5", iPhone 4", & iPad var nibName:NSString if IS_IPHONE { nibName = "ControllerViewController_iPhone" } else{ //IPAD nibName = "ControllerViewController_iPad" } self.init(nibName: nibName as String, bundle: NSBundle.mainBundle()) self.delegate = aDelegate self.title = "Controller" self.sensorArray = [] } func sensorButtonTapped(sender: UIButton) { // print("--------> button \(sender.tag) state is ") // if sender.selected { // print("SELECTED") // } // else { // print("DESELECTED") // } // //Check to ensure switch is not being set redundantly // if sensorArray[sender.tag].enabled == sender.selected { //// println(" - redundant!") // sender.userInteractionEnabled = true // return // } // else { //// println("") // sensorArray[sender.tag].enabled = sender.selected // } //Accelerometer if sender === accelButton { //rows to add or remove let valuePaths: [NSIndexPath] = [ NSIndexPath(forRow: 1, inSection: 1), NSIndexPath(forRow: 2, inSection: 1), NSIndexPath(forRow: 3, inSection: 1) ] if (sender.selected == false) { if cmm.accelerometerAvailable == true { cmm.accelerometerUpdateInterval = pollInterval cmm.startAccelerometerUpdatesToQueue(NSOperationQueue.mainQueue(), withHandler: { (data:CMAccelerometerData?, error:NSError?) -> Void in self.didReceiveAccelData(data, error: error) }) sender.selected = true //add rows for sensor values controlTable.beginUpdates() controlTable.insertRowsAtIndexPaths(valuePaths , withRowAnimation: UITableViewRowAnimation.Fade) controlTable.endUpdates() } else { printLog(self, funcName: "buttonValueChanged", logString: "accelerometer unavailable") } } //button switched off else { sender.selected = false //remove rows for sensor values controlTable.beginUpdates() controlTable.deleteRowsAtIndexPaths(valuePaths, withRowAnimation: UITableViewRowAnimation.Fade) controlTable.endUpdates() cmm.stopAccelerometerUpdates() } } //Gyro else if sender === gyroButton { //rows to add or remove let valuePaths: [NSIndexPath] = [ NSIndexPath(forRow: 1, inSection: 2), NSIndexPath(forRow: 2, inSection: 2), NSIndexPath(forRow: 3, inSection: 2) ] if (sender.selected == false) { if cmm.gyroAvailable == true { cmm.gyroUpdateInterval = pollInterval cmm.startGyroUpdatesToQueue(NSOperationQueue.mainQueue(), withHandler: { (data:CMGyroData?, error:NSError?) -> Void in self.didReceiveGyroData(data, error: error) }) sender.selected = true //add rows for sensor values controlTable.beginUpdates() controlTable.insertRowsAtIndexPaths(valuePaths, withRowAnimation: UITableViewRowAnimation.Fade) controlTable.endUpdates() } else { printLog(self, funcName: "buttonValueChanged", logString: "gyro unavailable") } } //button switched off else { sender.selected = false //remove rows for sensor values controlTable.beginUpdates() controlTable.deleteRowsAtIndexPaths(valuePaths, withRowAnimation: UITableViewRowAnimation.Fade) controlTable.endUpdates() cmm.stopGyroUpdates() } } //Magnetometer else if sender === magnetometerButton { //rows to add or remove let valuePaths: [NSIndexPath] = [ NSIndexPath(forRow: 1, inSection: 3), NSIndexPath(forRow: 2, inSection: 3), NSIndexPath(forRow: 3, inSection: 3) ] if (sender.selected == false) { if cmm.magnetometerAvailable == true { cmm.magnetometerUpdateInterval = pollInterval cmm.startMagnetometerUpdatesToQueue(NSOperationQueue.mainQueue(), withHandler: { (data:CMMagnetometerData?, error:NSError?) -> Void in self.didReceiveMagnetometerData(data, error: error) }) sender.selected = true //add rows for sensor values controlTable.beginUpdates() controlTable.insertRowsAtIndexPaths(valuePaths, withRowAnimation: UITableViewRowAnimation.Fade) controlTable.endUpdates() } else { printLog(self, funcName: "buttonValueChanged", logString: "magnetometer unavailable") } } //button switched off else { sender.selected = false //remove rows for sensor values controlTable.beginUpdates() controlTable.deleteRowsAtIndexPaths(valuePaths, withRowAnimation: UITableViewRowAnimation.Fade) controlTable.endUpdates() cmm.stopMagnetometerUpdates() } } //GPS else if sender === gpsButton { //rows to add or remove let valuePaths: [NSIndexPath] = [ NSIndexPath(forRow: 1, inSection: 4), NSIndexPath(forRow: 2, inSection: 4), NSIndexPath(forRow: 3, inSection: 4) ] if (sender.selected == false) { if locationManager == nil { locationManager = CLLocationManager() locationManager?.delegate = self locationManager?.desiredAccuracy = kCLLocationAccuracyBest locationManager?.distanceFilter = kCLDistanceFilterNone //Check for authorization if locationManager?.respondsToSelector(Selector("requestWhenInUseAuthorization")) == true { if CLLocationManager.authorizationStatus() != CLAuthorizationStatus.AuthorizedWhenInUse { locationManager?.requestWhenInUseAuthorization() gpsButton.selected = false return } } else { printLog(self, funcName: "buttonValueChanged", logString: "Location Manager authorization not found") gpsButton.selected = false removeGPSTimer() locationManager = nil return } } if CLLocationManager.authorizationStatus() == CLAuthorizationStatus.AuthorizedWhenInUse { locationManager?.startUpdatingLocation() //add gpstimer to loop if gpsTimer == nil { gpsTimer = newGPSTimer() } NSRunLoop.currentRunLoop().addTimer(gpsTimer!, forMode: NSDefaultRunLoopMode) sender.selected = true //add rows for sensor values controlTable.beginUpdates() controlTable.insertRowsAtIndexPaths(valuePaths, withRowAnimation: UITableViewRowAnimation.Fade) controlTable.endUpdates() } else { // printLog(self, "buttonValueChanged", "Location Manager not authorized") showLocationServicesAlert() return } } //button switched off else { sender.selected = false //remove rows for sensor values controlTable.beginUpdates() controlTable.deleteRowsAtIndexPaths(valuePaths, withRowAnimation: UITableViewRowAnimation.Fade) controlTable.endUpdates() //remove gpstimer from loop removeGPSTimer() locationManager?.stopUpdatingLocation() } } //Quaternion / Device Motion else if sender === quatButton { //rows to add or remove let valuePaths: [NSIndexPath] = [ NSIndexPath(forRow: 1, inSection: 0), NSIndexPath(forRow: 2, inSection: 0), NSIndexPath(forRow: 3, inSection: 0), NSIndexPath(forRow: 4, inSection: 0) ] if (sender.selected == false) { if cmm.deviceMotionAvailable == true { cmm.deviceMotionUpdateInterval = pollInterval cmm.startDeviceMotionUpdatesToQueue(NSOperationQueue.mainQueue(), withHandler: { (cmdm:CMDeviceMotion?, error:NSError?) -> Void in self.didReceivedDeviceMotion(cmdm, error: error) }) sender.selected = true //add rows for sensor values controlTable.beginUpdates() controlTable.insertRowsAtIndexPaths(valuePaths, withRowAnimation: UITableViewRowAnimation.Fade) controlTable.endUpdates() } else { printLog(self, funcName: "buttonValueChanged", logString: "device motion unavailable") } } //button switched off else { sender.selected = false //remove rows for sensor values controlTable.beginUpdates() controlTable.deleteRowsAtIndexPaths(valuePaths, withRowAnimation: UITableViewRowAnimation.Fade) controlTable.endUpdates() cmm.stopDeviceMotionUpdates() } } } func newSensorButton(tag:Int)->BLESensorButton { let aButton = BLESensorButton() aButton.tag = tag // let offColor = bleBlueColor // let onColor = UIColor.whiteColor() // aButton.titleLabel?.font = UIFont.systemFontOfSize(14.0) // aButton.setTitle("OFF", forState: UIControlState.Normal) // aButton.setTitle("ON", forState: UIControlState.Selected) // aButton.setTitleColor(offColor, forState: UIControlState.Normal) // aButton.setTitleColor(onColor, forState: UIControlState.Selected) // aButton.setTitleColor(UIColor.lightGrayColor(), forState: UIControlState.Disabled) // aButton.backgroundColor = UIColor.whiteColor() // aButton.setBackgroundImage(UIImage(named: "ble_blue_1px.png"), forState: UIControlState.Selected) // aButton.layer.cornerRadius = 8.0 // aButton.clipsToBounds = true // aButton.layer.borderColor = offColor.CGColor // aButton.layer.borderWidth = 1.0 aButton.selected = false aButton.addTarget(self, action: Selector("sensorButtonTapped:"), forControlEvents: UIControlEvents.TouchUpInside) aButton.frame = CGRectMake(0.0, 0.0, 75.0, 30.0) return aButton } func newValueCell(prefixString:String!)->SensorValueCell { let cellData = NSKeyedArchiver.archivedDataWithRootObject(self.valueCell) let cell:SensorValueCell = NSKeyedUnarchiver.unarchiveObjectWithData(cellData) as! SensorValueCell cell.selectionStyle = UITableViewCellSelectionStyle.None cell.valueLabel = cell.viewWithTag(100) as! UILabel // let cell = SensorValueCell() cell.prefixString = prefixString return cell } func showNavbar(){ self.navigationController?.setNavigationBarHidden(false, animated: true) } //MARK: Sensor data func didReceivedDeviceMotion(cmdm:CMDeviceMotion!, error:NSError!) { storeSensorData(SensorType.Qtn, x: cmdm.attitude.quaternion.x, y: cmdm.attitude.quaternion.y, z: cmdm.attitude.quaternion.z, w: cmdm.attitude.quaternion.w) } func didReceiveAccelData(aData:CMAccelerometerData!, error:NSError!) { // println("ACC X:\(Float(accelData.acceleration.x)) Y:\(Float(accelData.acceleration.y)) Z:\(Float(accelData.acceleration.z))") storeSensorData(SensorType.Accel, x: aData.acceleration.x, y: aData.acceleration.y, z: aData.acceleration.z, w:nil) } func didReceiveGyroData(gData:CMGyroData!, error:NSError!) { // println("GYR X:\(gyroData.rotationRate.x) Y:\(gyroData.rotationRate.y) Z:\(gyroData.rotationRate.z)") storeSensorData(SensorType.Gyro, x: gData.rotationRate.x, y: gData.rotationRate.y, z: gData.rotationRate.z, w:nil) } func didReceiveMagnetometerData(mData:CMMagnetometerData!, error:NSError!) { // println("MAG X:\(magData.magneticField.x) Y:\(magData.magneticField.y) Z:\(magData.magneticField.z)") storeSensorData(SensorType.Mag, x: mData.magneticField.x, y: mData.magneticField.y, z: mData.magneticField.z, w:nil) } func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let loc = locations.last as CLLocation! let eventDate = loc.timestamp let howRecent = eventDate.timeIntervalSinceNow if (abs(howRecent) < 15) // || (gpsFlag == true) { // gpsFlag = false //Check for invalid accuracy if loc.horizontalAccuracy < 0.0 || loc.verticalAccuracy < 0.0 { return } //Debug // let lat = loc.coordinate.latitude // let lng = loc.coordinate.longitude // let alt = loc.altitude // println("-------------------------------") // println(String(format: "Location Double: %.32f, %.32f", lat, lng)) // println(String(format: "Location Float: %.32f, %.32f", Float(lat), Float(lng))) // println("-------------------------------") storeSensorData(SensorType.GPS, x: loc.coordinate.latitude, y: loc.coordinate.longitude, z: loc.altitude, w:nil) } } func storeSensorData(type:SensorType, x:Double, y:Double, z:Double, w:Double?) { //called in sensor queue let idx = type.rawValue let data = NSMutableData(capacity: 0)! let pfx = NSString(string: sensorArray[idx].prefix) var xv = Float(x) var yv = Float(y) var zv = Float(z) data.appendBytes(pfx.UTF8String, length: pfx.length) data.appendBytes(&xv, length: sizeof(Float)) sensorArray[idx].valueCells[0].updateValue(xv) data.appendBytes(&yv, length: sizeof(Float)) sensorArray[idx].valueCells[1].updateValue(yv) data.appendBytes(&zv, length: sizeof(Float)) sensorArray[idx].valueCells[2].updateValue(zv) if w != nil { var wv = Float(w!) data.appendBytes(&wv, length: sizeof(Float)) sensorArray[idx].valueCells[3].updateValue(wv) } appendCRCmutable(data) sensorArray[idx].data = data } func sendSensorData(timer:NSTimer) { let startIdx = sendSensorIndex var data:NSData? while data == nil { data = sensorArray[sendSensorIndex].data if data != nil { // println("------------------> Found sensor data \(sensorArray[sendSensorIndex].prefix)") delegate?.sendData(data!) if sensorArray[sendSensorIndex].type == SensorType.GPS { lastGPSData = data } // Store last gps data sent for min updates sensorArray[sendSensorIndex].data = nil incrementSensorIndex() return } incrementSensorIndex() if startIdx == sendSensorIndex { // println("------------------> No new data to send") return } } } func gpsIntervalComplete(timer:NSTimer) { //set last gpsdata sent as next gpsdata to send for i in 0...(sensorArray.count-1) { if (sensorArray[i].type == SensorType.GPS) && (sensorArray[i].data == nil) { // println("--> gpsIntervalComplete - reloading last gps data") sensorArray[i].data = lastGPSData break } } } func incrementSensorIndex(){ sendSensorIndex += 1 if sendSensorIndex >= sensorArray.count { sendSensorIndex = 0 } } func stopSensorUpdates(){ sendTimer?.invalidate() removeGPSTimer() accelButton.selected = false cmm.stopAccelerometerUpdates() gyroButton.selected = false cmm.stopGyroUpdates() magnetometerButton.selected = false cmm.stopMagnetometerUpdates() cmm.stopDeviceMotionUpdates() gpsButton.selected = false locationManager?.stopUpdatingLocation() } //MARK: TableView func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: nil) var buttonView:UIButton? if indexPath.section == (sensorArray.count){ cell.textLabel!.text = "Control Pad" cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator cell.selectionStyle = UITableViewCellSelectionStyle.Blue return cell } else if indexPath.section == sensorArray.count { cell.textLabel?.text = "Control Pad" cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator cell.selectionStyle = UITableViewCellSelectionStyle.Blue return cell } else if indexPath.section == (sensorArray.count + 1){ cell.textLabel!.text = "Color Picker" cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator cell.selectionStyle = UITableViewCellSelectionStyle.Blue return cell } cell.selectionStyle = UITableViewCellSelectionStyle.None if indexPath.row == 0 { switch indexPath.section { case 0: cell.textLabel!.text = "Quaternion" buttonView = quatButton case 1: cell.textLabel!.text = "Accelerometer" buttonView = accelButton case 2: cell.textLabel!.text = "Gyro" buttonView = gyroButton case 3: cell.textLabel!.text = "Magnetometer" buttonView = magnetometerButton case 4: cell.textLabel!.text = "Location" buttonView = gpsButton default: break } cell.accessoryView = buttonView return cell } else { // switch indexPath.section { // case 0: // break // case 1: //Accel // cell.textLabel!.text = "TEST" // case 2: //Gyro // cell.textLabel!.text = "TEST" // case 3: //Mag // cell.textLabel!.text = "TEST" // case 4: //GPS // cell.textLabel!.text = "TEST" // default: // break // } return sensorArray[indexPath.section].valueCells[indexPath.row-1] } } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section < sensorArray.count { let snsr = sensorArray[section] if snsr.toggleButton.selected == true { return snsr.valueCells.count+1 } else { return 1 } } else { return 1 } } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if indexPath.row == 0 { return 44.0 } else { return 28.0 } } func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if section == 0 { return 44.0 } else if section == sensorArray.count { return 44.0 } else { return 0.5 } } func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 0.5 } func tableView(tableView: UITableView, indentationLevelForRowAtIndexPath indexPath: NSIndexPath) -> Int { if indexPath.row == 0 { return 0 } else { return 1 } } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return sensorArray.count + 2 } func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if section == 0 { return "Stream Sensor Data" } else if section == sensorArray.count { return "Module" } else { return nil } } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if indexPath.section == sensorArray.count { tableView.deselectRowAtIndexPath(indexPath, animated: false) self.navigationController?.pushViewController(controlPadViewController, animated: true) if IS_IPHONE { //Hide nav bar on iphone to conserve space self.navigationController?.setNavigationBarHidden(true, animated: true) } } else if indexPath.section == (sensorArray.count + 1) { tableView.deselectRowAtIndexPath(indexPath, animated: false) let colorPicker = ColorPickerViewController(aDelegate: self) self.navigationController?.pushViewController(colorPicker, animated: true) } } //MARK: Control Pad @IBAction func controlPadButtonPressed(sender:UIButton) { // println("PRESSED \(sender.tag)") sender.backgroundColor = cellSelectionColor controlPadButtonPressedWithTag(sender.tag) } func controlPadButtonPressedWithTag(tag:Int) { let str = NSString(string: buttonPrefix + "\(tag)" + "1") let data = NSData(bytes: str.UTF8String, length: str.length) delegate?.sendData(appendCRC(data)) } @IBAction func controlPadButtonReleased(sender:UIButton) { // println("RELEASED \(sender.tag)") sender.backgroundColor = buttonColor controlPadButtonReleasedWithTag(sender.tag) } func controlPadButtonReleasedWithTag(tag:Int) { let str = NSString(string: buttonPrefix + "\(tag)" + "0") let data = NSData(bytes: str.UTF8String, length: str.length) delegate?.sendData(appendCRC(data)) } @IBAction func controlPadExitPressed(sender:UIButton) { sender.backgroundColor = buttonColor } @IBAction func controlPadExitReleased(sender:UIButton) { sender.backgroundColor = exitButtonColor navigationController?.popViewControllerAnimated(true) self.navigationController?.setNavigationBarHidden(false, animated: true) } @IBAction func controlPadExitDragOutside(sender:UIButton) { sender.backgroundColor = exitButtonColor } //WatchKit functions func controlPadButtonTappedWithTag(tag:Int){ //Press and release button controlPadButtonPressedWithTag(tag) delay(0.1, closure: { () -> () in self.controlPadButtonReleasedWithTag(tag) }) } func appendCRCmutable(data:NSMutableData) { //append crc let len = data.length var bdata = [UInt8](count: len, repeatedValue: 0) // var buf = [UInt8](count: len, repeatedValue: 0) var crc:UInt8 = 0 data.getBytes(&bdata, length: len) for i in bdata { //add all bytes crc = crc &+ i } crc = ~crc //invert data.appendBytes(&crc, length: 1) // println("crc == \(crc) length == \(data.length)") } func appendCRC(data:NSData)->NSMutableData { let mData = NSMutableData(length: 0) mData!.appendData(data) appendCRCmutable(mData!) return mData! } //Color Picker func sendColor(red:UInt8, green:UInt8, blue:UInt8) { let pfx = NSString(string: colorPrefix) var rv = red var gv = green var bv = blue let data = NSMutableData(capacity: 3 + pfx.length)! data.appendBytes(pfx.UTF8String, length: pfx.length) data.appendBytes(&rv, length: 1) data.appendBytes(&gv, length: 1) data.appendBytes(&bv, length: 1) appendCRCmutable(data) delegate?.sendData(data) } func helpViewControllerDidFinish(controller : HelpViewController) { delegate?.helpViewControllerDidFinish(controller) } }
mit
e356b7f7444facb32c67504a9be9500b
32.991713
239
0.551537
5.47051
false
false
false
false
JohnPJenkins/swift-t
stc/tests/506-strings-7.swift
4
910
import assert; (int r) iid (int x) { r = x; } (float r) fid (float x) { r = x; } (string r) sid (string x) { r = x; } main { assertEqual(1234, toint("1234"), "toint"); assertEqual(-3.142, tofloat("-3.142"), "tofloat"); assert("3.142" == fromfloat(3.142), "fromfloat"); assert("4321" == fromint(4321), "fromint"); assertEqual(1234, toint(sid("1234")), "toint"); assertEqual(-3.142, tofloat(sid("-3.142")), "tofloat"); assert("3.142" == fromfloat(fid(3.142)), "fromfloat"); assert("4321" == fromint(iid(4321)), "fromint"); string a = sid("1234"); string b = sid("-3.142"); float c = fid(3.142); int d = iid(4321); wait(a,b,c,d) { assertEqual(1234, toint(a), "toint"); assertEqual(-3.142, tofloat(b), "tofloat"); assert("3.142" == fromfloat(c), "fromfloat"); assert("4321" == fromint(d), "fromint"); } }
apache-2.0
c92c7cf04b42af58c43920639b3f87e6
22.333333
59
0.53956
2.879747
false
false
false
false
astrokin/EZSwiftExtensions
Sources/UIColorExtensions.swift
6
2783
// // UIColorExtensions.swift // EZSwiftExtensions // // Created by Goktug Yilmaz on 15/07/15. // Copyright (c) 2015 Goktug Yilmaz. All rights reserved. // import UIKit extension UIColor { /// EZSE: init method with RGB values from 0 to 255, instead of 0 to 1. With alpha(default:1) public convenience init(r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat = 1) { self.init(red: r / 255.0, green: g / 255.0, blue: b / 255.0, alpha: a) } /// EZSE: init method with hex string and alpha(default: 1) public convenience init?(hexString: String, alpha: CGFloat = 1.0) { var formatted = hexString.replacingOccurrences(of: "0x", with: "") formatted = formatted.replacingOccurrences(of: "#", with: "") if let hex = Int(formatted, radix: 16) { let red = CGFloat(CGFloat((hex & 0xFF0000) >> 16)/255.0) let green = CGFloat(CGFloat((hex & 0x00FF00) >> 8)/255.0) let blue = CGFloat(CGFloat((hex & 0x0000FF) >> 0)/255.0) self.init(red: red, green: green, blue: blue, alpha: alpha) } else { return nil } } /// EZSE: init method from Gray value and alpha(default:1) public convenience init(gray: CGFloat, alpha: CGFloat = 1) { self.init(red: gray/255, green: gray/255, blue: gray/255, alpha: alpha) } /// EZSE: Red component of UIColor (get-only) public var redComponent: Int { var r: CGFloat = 0 getRed(&r, green: nil, blue: nil, alpha: nil) return Int(r * 255) } /// EZSE: Green component of UIColor (get-only) public var greenComponent: Int { var g: CGFloat = 0 getRed(nil, green: &g, blue: nil, alpha: nil) return Int(g * 255) } /// EZSE: blue component of UIColor (get-only) public var blueComponent: Int { var b: CGFloat = 0 getRed(nil, green: nil, blue: &b, alpha: nil) return Int(b * 255) } /// EZSE: Alpha of UIColor (get-only) public var alpha: CGFloat { var a: CGFloat = 0 getRed(nil, green: nil, blue: nil, alpha: &a) return a } /// EZSE: Returns random UIColor with random alpha(default: false) public static func random(randomAlpha: Bool = false) -> UIColor { let randomRed = CGFloat.random() let randomGreen = CGFloat.random() let randomBlue = CGFloat.random() let alpha = randomAlpha ? CGFloat.random() : 1.0 return UIColor(red: randomRed, green: randomGreen, blue: randomBlue, alpha: alpha) } } private extension CGFloat { /// SwiftRandom extension static func random(_ lower: CGFloat = 0, _ upper: CGFloat = 1) -> CGFloat { return CGFloat(Float(arc4random()) / Float(UINT32_MAX)) * (upper - lower) + lower } }
mit
da24f28ac97ea36acc571360083ddf13
34.227848
97
0.603306
3.725569
false
false
false
false
nextcloud/ios
iOSClient/Main/Create cloud/NCCreateFormUploadVoiceNote.swift
1
12868
// // NCCreateFormUploadVoiceNote.swift // Nextcloud // // Created by Marino Faggiana on 9/03/2019. // Copyright © 2019 Marino Faggiana. All rights reserved. // // Author Marino Faggiana <[email protected]> // // 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 NextcloudKit class NCCreateFormUploadVoiceNote: XLFormViewController, NCSelectDelegate, AVAudioPlayerDelegate, NCCreateFormUploadConflictDelegate { @IBOutlet weak var buttonPlayStop: UIButton! @IBOutlet weak var labelTimer: UILabel! @IBOutlet weak var labelDuration: UILabel! @IBOutlet weak var progressView: UIProgressView! let appDelegate = UIApplication.shared.delegate as! AppDelegate private var serverUrl = "" private var titleServerUrl = "" private var fileName = "" private var fileNamePath = "" private var durationPlayer: TimeInterval = 0 private var counterSecondPlayer: TimeInterval = 0 private var audioPlayer: AVAudioPlayer! private var timer = Timer() var cellBackgoundColor = UIColor.secondarySystemGroupedBackground // MARK: - View Life Cycle override func viewDidLoad() { super.viewDidLoad() self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: NSLocalizedString("_cancel_", comment: ""), style: UIBarButtonItem.Style.plain, target: self, action: #selector(cancel)) self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: NSLocalizedString("_save_", comment: ""), style: UIBarButtonItem.Style.plain, target: self, action: #selector(save)) self.tableView.separatorStyle = UITableViewCell.SeparatorStyle.none view.backgroundColor = .systemGroupedBackground tableView.backgroundColor = .systemGroupedBackground cellBackgoundColor = .secondarySystemGroupedBackground self.title = NSLocalizedString("_voice_memo_title_", comment: "") // Button Play Stop buttonPlayStop.setImage(UIImage(named: "audioPlay")!.image(color: NCBrandColor.shared.gray, size: 100), for: .normal) // Progress view progressView.progress = 0 progressView.progressTintColor = .green progressView.trackTintColor = UIColor(red: 247.0/255.0, green: 247.0/255.0, blue: 247.0/255.0, alpha: 1.0) labelTimer.textColor = .label labelDuration.textColor = .label initializeForm() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) updateTimerUI() } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) if audioPlayer.isPlaying { stop() } } public func setup(serverUrl: String, fileNamePath: String, fileName: String) { if serverUrl == NCUtilityFileSystem.shared.getHomeServer(urlBase: appDelegate.urlBase, userId: appDelegate.userId) { titleServerUrl = "/" } else { titleServerUrl = (serverUrl as NSString).lastPathComponent } self.fileName = fileName self.serverUrl = serverUrl self.fileNamePath = fileNamePath // player do { try audioPlayer = AVAudioPlayer(contentsOf: URL(fileURLWithPath: fileNamePath)) audioPlayer.prepareToPlay() audioPlayer.delegate = self durationPlayer = TimeInterval(audioPlayer.duration) } catch { buttonPlayStop.isEnabled = false } } // MARK: XLForm func initializeForm() { let form: XLFormDescriptor = XLFormDescriptor() as XLFormDescriptor form.rowNavigationOptions = XLFormRowNavigationOptions.stopDisableRow var section: XLFormSectionDescriptor var row: XLFormRowDescriptor // Section: Destination Folder section = XLFormSectionDescriptor.formSection(withTitle: NSLocalizedString("_save_path_", comment: "").uppercased()) form.addFormSection(section) row = XLFormRowDescriptor(tag: "ButtonDestinationFolder", rowType: XLFormRowDescriptorTypeButton, title: self.titleServerUrl) row.action.formSelector = #selector(changeDestinationFolder(_:)) row.cellConfig["backgroundColor"] = cellBackgoundColor row.cellConfig["imageView.image"] = UIImage(named: "folder")!.image(color: NCBrandColor.shared.brandElement, size: 25) row.cellConfig["textLabel.textAlignment"] = NSTextAlignment.right.rawValue row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0) row.cellConfig["textLabel.textColor"] = UIColor.label section.addFormRow(row) // Section: File Name section = XLFormSectionDescriptor.formSection(withTitle: NSLocalizedString("_filename_", comment: "").uppercased()) form.addFormSection(section) row = XLFormRowDescriptor(tag: "fileName", rowType: XLFormRowDescriptorTypeText, title: NSLocalizedString("_filename_", comment: "")) row.value = self.fileName row.cellConfig["backgroundColor"] = cellBackgoundColor row.cellConfig["textLabel.font"] = UIFont.systemFont(ofSize: 15.0) row.cellConfig["textLabel.textColor"] = UIColor.label row.cellConfig["textField.textAlignment"] = NSTextAlignment.right.rawValue row.cellConfig["textField.font"] = UIFont.systemFont(ofSize: 15.0) row.cellConfig["textField.textColor"] = UIColor.label section.addFormRow(row) self.form = form } override func formRowDescriptorValueHasChanged(_ formRow: XLFormRowDescriptor!, oldValue: Any!, newValue: Any!) { super.formRowDescriptorValueHasChanged(formRow, oldValue: oldValue, newValue: newValue) if formRow.tag == "fileName" { self.form.delegate = nil if let fileNameNew = formRow.value { self.fileName = CCUtility.removeForbiddenCharactersServer(fileNameNew as? String) } formRow.value = self.fileName self.updateFormRow(formRow) self.form.delegate = self } } // MARK: TableViewDelegate override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { let header: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView header.textLabel?.font = UIFont.systemFont(ofSize: 13.0) header.textLabel?.textColor = .gray header.tintColor = cellBackgoundColor } // MARK: - Action func dismissSelect(serverUrl: String?, metadata: tableMetadata?, type: String, items: [Any], overwrite: Bool, copy: Bool, move: Bool) { if serverUrl != nil { self.serverUrl = serverUrl! if serverUrl == NCUtilityFileSystem.shared.getHomeServer(urlBase: appDelegate.urlBase, userId: appDelegate.userId) { self.titleServerUrl = "/" } else { self.titleServerUrl = (serverUrl! as NSString).lastPathComponent } // Update let row: XLFormRowDescriptor = self.form.formRow(withTag: "ButtonDestinationFolder")! row.title = self.titleServerUrl self.updateFormRow(row) } } @objc func save() { let rowFileName: XLFormRowDescriptor = self.form.formRow(withTag: "fileName")! guard let name = rowFileName.value else { return } let ext = (name as! NSString).pathExtension.uppercased() var fileNameSave = "" if ext == "" { fileNameSave = name as! String + ".m4a" } else { fileNameSave = (name as! NSString).deletingPathExtension + ".m4a" } let metadataForUpload = NCManageDatabase.shared.createMetadata(account: self.appDelegate.account, user: self.appDelegate.user, userId: self.appDelegate.userId, fileName: fileNameSave, fileNameView: fileNameSave, ocId: UUID().uuidString, serverUrl: self.serverUrl, urlBase: self.appDelegate.urlBase, url: "", contentType: "") metadataForUpload.session = NCNetworking.shared.sessionIdentifierBackground metadataForUpload.sessionSelector = NCGlobal.shared.selectorUploadFile metadataForUpload.status = NCGlobal.shared.metadataStatusWaitUpload metadataForUpload.size = NCUtilityFileSystem.shared.getFileSize(filePath: fileNamePath) if NCManageDatabase.shared.getMetadataConflict(account: appDelegate.account, serverUrl: serverUrl, fileName: fileNameSave) != nil { guard let conflict = UIStoryboard(name: "NCCreateFormUploadConflict", bundle: nil).instantiateInitialViewController() as? NCCreateFormUploadConflict else { return } conflict.textLabelDetailNewFile = NSLocalizedString("_now_", comment: "") conflict.serverUrl = serverUrl conflict.metadatasUploadInConflict = [metadataForUpload] conflict.delegate = self conflict.isE2EE = CCUtility.isFolderEncrypted(serverUrl, e2eEncrypted: false, account: appDelegate.account, urlBase: appDelegate.urlBase, userId: appDelegate.userId) self.present(conflict, animated: true, completion: nil) } else { dismissAndUpload(metadataForUpload) } } func dismissCreateFormUploadConflict(metadatas: [tableMetadata]?) { if metadatas != nil && metadatas!.count > 0 { DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) { self.dismissAndUpload(metadatas![0]) } } } func dismissAndUpload(_ metadata: tableMetadata) { CCUtility.copyFile(atPath: self.fileNamePath, toPath: CCUtility.getDirectoryProviderStorageOcId(metadata.ocId, fileNameView: metadata.fileNameView)) NCNetworkingProcessUpload.shared.createProcessUploads(metadatas: [metadata], completion: { _ in }) self.dismiss(animated: true, completion: nil) } @objc func cancel() { try? FileManager.default.removeItem(atPath: fileNamePath) self.dismiss(animated: true, completion: nil) } @objc func changeDestinationFolder(_ sender: XLFormRowDescriptor) { self.deselectFormRow(sender) let storyboard = UIStoryboard(name: "NCSelect", bundle: nil) let navigationController = storyboard.instantiateInitialViewController() as! UINavigationController let viewController = navigationController.topViewController as! NCSelect viewController.delegate = self viewController.typeOfCommandView = .selectCreateFolder viewController.includeDirectoryE2EEncryption = true self.present(navigationController, animated: true, completion: nil) } // MARK: Player - Timer func updateTimerUI() { labelTimer.text = String().formatSecondsToString(counterSecondPlayer) labelDuration.text = String().formatSecondsToString(durationPlayer) progressView.progress = Float(counterSecondPlayer / durationPlayer) } @objc func updateTimer() { counterSecondPlayer += 1 updateTimerUI() } @IBAction func playStop(_ sender: Any) { if audioPlayer.isPlaying { stop() } else { start() } } func start() { audioPlayer.prepareToPlay() audioPlayer.play() timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true) buttonPlayStop.setImage(UIImage(named: "stop")!.image(color: NCBrandColor.shared.gray, size: 100), for: .normal) } func stop() { audioPlayer.currentTime = 0.0 audioPlayer.stop() timer.invalidate() counterSecondPlayer = 0 progressView.progress = 0 updateTimerUI() buttonPlayStop.setImage(UIImage(named: "audioPlay")!.image(color: NCBrandColor.shared.gray, size: 100), for: .normal) } func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) { timer.invalidate() counterSecondPlayer = 0 progressView.progress = 0 updateTimerUI() buttonPlayStop.setImage(UIImage(named: "audioPlay")!.image(color: NCBrandColor.shared.gray, size: 100), for: .normal) } }
gpl-3.0
60b54a9448b3e5b32646f4cd5b6e828b
35.868195
332
0.680423
4.937452
false
false
false
false
cplaverty/KeitaiWaniKani
AlliCrab/UserScripts/UserScripts.swift
1
6900
// // UserScripts.swift // AlliCrab // // Copyright © 2016 Chris Laverty. All rights reserved. // import WaniKaniKit enum UserScriptInjectionRule { case ExactMatch(URL) case PrefixedWith(URL) func matches(_ url: URL) -> Bool { switch self { case let .ExactMatch(x): return url == x case let .PrefixedWith(x): return url.host == x.host && url.path.hasPrefix(x.path) } } } class UserScript { let name: String let author: String? let updater: String? let description: String let forumLink: URL? let requiresFonts: Bool private let settingKey: ApplicationSettingKey? private let stylesheetNames: [String]? private let scriptNames: [String]? private let injectionRules: [UserScriptInjectionRule] var isEnabled: Bool { get { guard let settingKey = self.settingKey else { return true } return ApplicationSettings.userDefaults.bool(forKey: settingKey) } set { guard let settingKey = self.settingKey else { return } ApplicationSettings.userDefaults.set(newValue, forKey: settingKey) } } init(name: String, author: String? = nil, updater: String? = nil, description: String, forumLink: URL? = nil, settingKey: ApplicationSettingKey? = nil, requiresFonts: Bool = false, stylesheetNames: [String]? = nil, scriptNames: [String]? = nil, injectionRules: [UserScriptInjectionRule]) { self.name = name self.author = author self.updater = updater self.description = description self.forumLink = forumLink self.settingKey = settingKey self.requiresFonts = requiresFonts self.stylesheetNames = stylesheetNames self.scriptNames = scriptNames self.injectionRules = injectionRules } func canBeInjected(toPageAt url: URL) -> Bool { guard isEnabled else { return false } for rule in injectionRules { if rule.matches(url) { return true } } return false } func inject(into page: UserScriptSupport) { guard isEnabled else { return } if let stylesheetNames = stylesheetNames { for stylesheetName in stylesheetNames { page.injectStyleSheet(name: stylesheetName) } } if let scriptNames = scriptNames { for scriptName in scriptNames { page.injectScript(name: scriptName) } } } } struct UserScriptDefinitions { static let alwaysEnabled: [UserScript] = [ UserScript(name: "Common", description: "Common functions", stylesheetNames: ["common"], scriptNames: ["common"], injectionRules: [.ExactMatch(WaniKaniURL.loginPage), .ExactMatch(WaniKaniURL.lessonSession), .ExactMatch(WaniKaniURL.reviewSession)]), UserScript(name: "Resize", description: "Resizes fonts for legibility", stylesheetNames: ["resize"], injectionRules: [.ExactMatch(WaniKaniURL.lessonSession), .ExactMatch(WaniKaniURL.reviewSession)]), ] static let custom: [UserScript] = [ UserScript(name: "Disable Lesson Swipe", description: "Disables the horizontal swipe gesture on the info text during lessons to prevent it being accidentally triggered while scrolling.", settingKey: .disableLessonSwipe, scriptNames: ["noswipe"], injectionRules: [.ExactMatch(WaniKaniURL.lessonSession)]), ] static let community: [UserScript] = [ UserScript(name: "Close But No Cigar", author: "Ethan", description: "Prevent \"Your answer was a bit off\" answers from being accepted.", forumLink: WaniKaniURL.forumTopic(withRelativePath: "userscript-prevent-your-answer-was-a-bit-off-answers-from-being-accepted-a-k-a-close-but-no-cigar/7134"), settingKey: .userScriptCloseButNoCigarEnabled, scriptNames: ["WKButNoCigar.user"], injectionRules: [.ExactMatch(WaniKaniURL.lessonSession), .ExactMatch(WaniKaniURL.reviewSession)]), UserScript(name: "Jitai", author: "obskyr", description: "Display WaniKani reviews in randomised fonts for more varied reading training.", forumLink: WaniKaniURL.forumTopic(withRelativePath: "jitai-the-font-randomizer-that-fits/12617"), settingKey: .userScriptJitaiEnabled, requiresFonts: true, scriptNames: ["jitai.user"], injectionRules: [.ExactMatch(WaniKaniURL.reviewSession)]), UserScript(name: "WaniKani Improve", author: "Seiji", description: "Automatically moves to the next item if the answer was correct (also known as \"lightning mode\").", forumLink: WaniKaniURL.forumTopic(withRelativePath: "wanikani-improve-2-2-2-faster-and-smarter-reviews/2858"), settingKey: .userScriptWaniKaniImproveEnabled, stylesheetNames: ["jquery.qtip.min"], scriptNames: ["jquery.qtip.min", "wkimprove"], injectionRules: [.ExactMatch(WaniKaniURL.reviewSession)]), UserScript(name: "WaniKani Override", author: "ruipgpinheiro", updater: "Mempo", description: "Adds an \"Ignore Answer\" button to the bottom of WaniKani review pages, permitting incorrect answers to be ignored. This script is intended to be used to correct genuine mistakes, like typographical errors.", forumLink: WaniKaniURL.forumTopic(withRelativePath: "userscript-wanikani-override-ignore-answer-button-active-support/17999"), settingKey: .userScriptIgnoreAnswerEnabled, scriptNames: ["wkoverride.user"], injectionRules: [.ExactMatch(WaniKaniURL.reviewSession)]), UserScript(name: "Show Specific SRS Level in Reviews", author: "seanblue", description: "Show \"Apprentice 3\" instead of \"Apprentice\", etc.", forumLink: WaniKaniURL.forumTopic(withRelativePath: "userscript-wanikani-show-specific-srs-level-in-reviews/19777"), settingKey: .userScriptShowSRSReviewLevel, stylesheetNames: ["srsReviewLevels"], scriptNames: ["srsReviewLevels"], injectionRules: [.ExactMatch(WaniKaniURL.reviewSession)]), ] static let all = alwaysEnabled + custom + community }
mit
9383bce5d8b4be7514868984e3c353af
43.224359
293
0.607769
4.667794
false
false
false
false
phillips07/StudyCast
StudyCast/ChangePasswordController.swift
1
7297
// // ChangePasswordController.swift // StudyCast // // Created by Dennis Huebert on 2016-11-16. // Copyright © 2016 Austin Phillips. All rights reserved. // import UIKit import Firebase class ChangePasswordController: UIViewController { override func viewDidLoad() { super.viewDidLoad() self.hideKeyboardWhenTappedAround() view.backgroundColor = UIColor(r: 61, g: 91, b: 151) self.navigationController?.navigationBar.barTintColor = UIColor(r: 61, g: 91, b: 151) self.navigationController?.navigationBar.tintColor = UIColor.white self.navigationItem.title = "Password" view.addSubview(currentPasswordTextField) view.addSubview(newPasswordTextField) view.addSubview(confirmNewPasswordTextField) view.addSubview(logoImageView) view.addSubview(confirmButton) setupCurrentPasswordTextField() setupNewPasswordTextField() setupConfrimNewPasswordTextField() setupLogoImageView() setupConfirmButton() } let currentPasswordTextField: UITextField = { let tf = UITextField() tf.placeholder = " Current Password" tf.translatesAutoresizingMaskIntoConstraints = false tf.isSecureTextEntry = true tf.backgroundColor = UIColor.white tf.layer.cornerRadius = 6.0 return tf }() let newPasswordTextField: UITextField = { let tf = UITextField() tf.placeholder = " New Password" tf.translatesAutoresizingMaskIntoConstraints = false tf.isSecureTextEntry = true tf.backgroundColor = UIColor.white tf.layer.cornerRadius = 6.0 return tf }() let confirmNewPasswordTextField: UITextField = { let tf = UITextField() tf.placeholder = " Confirm Password" tf.translatesAutoresizingMaskIntoConstraints = false tf.isSecureTextEntry = true tf.backgroundColor = UIColor.white tf.layer.cornerRadius = 6.0 return tf }() lazy var logoImageView: UIImageView = { let imageView = UIImageView() imageView.image = UIImage(named: "studyCast_book3") imageView.translatesAutoresizingMaskIntoConstraints = false imageView.contentMode = .scaleAspectFill return imageView }() lazy var confirmButton: UIButton = { let button = UIButton(type: .system) button.backgroundColor = UIColor(r: 80, g: 101, b: 161) button.setTitle("Confirm", for: UIControlState()) button.translatesAutoresizingMaskIntoConstraints = false button.setTitleColor(UIColor.white, for: UIControlState()) button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16) button.addTarget(self, action: #selector(handleConfirmation), for: .touchUpInside) return button }() func setupCurrentPasswordTextField() { currentPasswordTextField.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true currentPasswordTextField.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: -20).isActive = true currentPasswordTextField.widthAnchor.constraint(equalTo: view.widthAnchor, constant: -140).isActive = true currentPasswordTextField.heightAnchor.constraint(equalToConstant: 35).isActive = true } func setupNewPasswordTextField() { newPasswordTextField.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true newPasswordTextField.topAnchor.constraint(equalTo: currentPasswordTextField.bottomAnchor, constant: 15).isActive = true newPasswordTextField.widthAnchor.constraint(equalTo: currentPasswordTextField.widthAnchor).isActive = true newPasswordTextField.heightAnchor.constraint(equalToConstant: 35).isActive = true } func setupConfrimNewPasswordTextField() { confirmNewPasswordTextField.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true confirmNewPasswordTextField.topAnchor.constraint(equalTo: newPasswordTextField.bottomAnchor, constant: 15).isActive = true confirmNewPasswordTextField.widthAnchor.constraint(equalTo: currentPasswordTextField.widthAnchor).isActive = true confirmNewPasswordTextField.heightAnchor.constraint(equalToConstant: 35).isActive = true } func setupLogoImageView() { logoImageView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true logoImageView.bottomAnchor.constraint(equalTo: currentPasswordTextField.centerYAnchor, constant: -50).isActive = true logoImageView.widthAnchor.constraint(equalToConstant: 170).isActive = true logoImageView.heightAnchor.constraint(equalToConstant: 170).isActive = true } func setupConfirmButton(){ confirmButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true confirmButton.topAnchor.constraint(equalTo: confirmNewPasswordTextField.bottomAnchor, constant: 20).isActive = true confirmButton.widthAnchor.constraint(equalTo: currentPasswordTextField.widthAnchor).isActive = true confirmButton.heightAnchor.constraint(equalToConstant: 45).isActive = true } func handleConfirmation() { guard let currentPassword = currentPasswordTextField.text, let newPassword = newPasswordTextField.text, let confirmPassword = confirmNewPasswordTextField.text else { print("Form is not valid") return } let user = FIRAuth.auth()?.currentUser let credential = FIREmailPasswordAuthProvider.credential(withEmail: (user?.email)!, password: currentPassword) user?.reauthenticate(with: credential) { error in if let error = error { print(error) let alertController = UIAlertController(title: "Wrong Password", message: "Please Try Again", preferredStyle: UIAlertControllerStyle.alert) alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.default,handler: nil)) self.present(alertController, animated: true, completion: nil) } else { if newPassword == confirmPassword { user?.updatePassword(newPassword, completion: { (error) in if let error = error { print(error) } else { //dismiss view, password has been updated self.dismiss(animated: true, completion: nil) } }) } else { print("Passwords do not match") let alertController = UIAlertController(title: "Passwords Do Not Match", message: "Please Try Again", preferredStyle: UIAlertControllerStyle.alert) alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.default,handler: nil)) self.present(alertController, animated: true, completion: nil) } } } } }
mit
bb72a086203695ef1bac5cb26a4b4382
43.487805
130
0.6642
5.767589
false
false
false
false
google/JacquardSDKiOS
JacquardSDK/Classes/Internal/FirmwareUpdate/FirmwareImageWriterStateMachine.swift
1
13066
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Combine import Foundation enum FirmwareImageWriterError: Swift.Error { case crcMismatch case internalError case dataCorruption } class FirmwareImageWriterStateMachine { static let initialState: State = .idle /// The max payload size for each write request. static let imageChunkSize = 128 private let stateSubject = CurrentValueSubject<State, Never>( FirmwareImageWriterStateMachine.initialState) lazy var statePublisher: AnyPublisher<State, Never> = stateSubject.eraseToAnyPublisher() private var marshalQueue: DispatchQueue private var context: Context private var observations = [Cancellable]() private var state: State = FirmwareImageWriterStateMachine.initialState { didSet { stateSubject.send(state) } } /// Total bytes written by the writer. var totalBytesWritten: Int { context.totalBytesWritten } enum State { case idle case checkingStatus case preparingForWrite // The associated value with the writing state indicates written bytes so far. case writing(Int) case complete case error(Error) var isTerminal: Bool { switch self { case .complete, .error: return true default: return false } } } private enum Event { case checkStatus case imagePartiallyWritten case imageCompletelyWritten case didReceiveStatusCheckError(Error) case prepareForWriting case didReceivePrepareError(Error) case startWriting case didReceiveWriteError(Error) } private struct Context { /// The firmware image to be written onto the device. let image: Data /// The `ConnectedTag` onto which the image has to be written. let tag: ConnectedTag /// The current image write progress. var totalBytesWritten = 0 /// Vendor ID of the component for which the image has to be written. let vendorID: String /// Product ID of the component for which the image has to be written. let productID: String /// ID of the component for which the image has to be written. let componentID: ComponentID /// CRC of firmware image data. let imageCrc: UInt16 } private enum WriteStatus: String { case finished case partial case reset } required init( image: Data, tag: ConnectedTag, vendorID: String, productID: String, componentID: ComponentID ) { self.marshalQueue = DispatchQueue(label: "FirmwareImageWriterStateMachine marshaling queue") self.context = Context( image: image, tag: tag, vendorID: vendorID, productID: productID, componentID: componentID, imageCrc: CRC16.compute(in: image, seed: 0) ) } } //MARK: - External event methods. extension FirmwareImageWriterStateMachine { /// Starts the write process if the state of the writer is valid (`idle`). func startWriting() { marshalQueue.async { self.handleEvent(.checkStatus) } } } //MARK: - Internal event methods & helpers. extension FirmwareImageWriterStateMachine { /// Queries the device for the current image write status and moves the state accordingly. private func checkStatus() { let dfuStatusRequest = DFUStatusCommand( vendorID: ComponentImplementation.convertToDecimal(self.context.vendorID), productID: ComponentImplementation.convertToDecimal(self.context.productID) ) context.tag.enqueue(dfuStatusRequest).sink { [weak self] completion in guard let self = self else { return } switch completion { case .finished: break case .failure(let error): self.marshalQueue.async { jqLogger.error("Error: \(error) during status request.") self.handleEvent(.didReceiveStatusCheckError(error)) } } } receiveValue: { [weak self] (response) in guard let self = self else { return } self.marshalQueue.async { self.processStatusResponse(response: response) } }.addTo(&observations) } /// Extracts information from the status response to check where the update is currently at. /// That is, the upgrade could be resumed, the file could already be written or there could be /// an error that requires the upgrade to restart from the beginning. /// /// - Parameter response: The response packet obtained after querying the device. private func processStatusResponse(response: Google_Jacquard_Protocol_DFUStatusResponse) { var status = WriteStatus.reset if context.image.count == response.finalSize && context.imageCrc == response.finalCrc { context.totalBytesWritten = Int(response.currentSize) let crcCheck = currentCRC() == response.currentCrc if !crcCheck { status = .reset } else if context.totalBytesWritten == context.image.count { status = .finished } else { status = .partial } } jqLogger.debug("Status response: \(status)") switch status { case .reset: handleEvent(.prepareForWriting) case .finished: handleEvent(.imageCompletelyWritten) case .partial: handleEvent(.imagePartiallyWritten) } } /// First step that asks the Tag to erase its cache and prepare for an incoming image. private func prepareForWriting() { let dfuPrepareRequest = DFUPrepareCommand( vendorID: ComponentImplementation.convertToDecimal(self.context.vendorID), productID: ComponentImplementation.convertToDecimal(self.context.productID), componentID: self.context.componentID, finalCrc: UInt32(self.context.imageCrc), finalSize: UInt32(self.context.image.count) ) context.tag.enqueue(dfuPrepareRequest).sink { [weak self] completion in guard let self = self else { return } switch completion { case .finished: break case .failure(let error): self.marshalQueue.async { jqLogger.error("Error \(self.state) preparing for image transfer.") self.handleEvent(.didReceivePrepareError(error)) } } } receiveValue: { [weak self] in guard let self = self else { return } self.marshalQueue.async { jqLogger.info( "Prepare response OK; starting transfer for \(self.context.vendorID)-\(self.context.productID)" ) self.handleEvent(.startWriting) } }.addTo(&observations) } /// Sends the 'next' slice of data from the image being transferred. private func sendPacket() { let packet = imagePacket() jqLogger.debug("Sending packet: \(packet)") let dfuWriteRequest = DFUWriteCommand( data: packet, offset: UInt32(self.context.totalBytesWritten) ) context.tag.enqueue(dfuWriteRequest).sink { [weak self] completion in guard let self = self else { return } switch completion { case .finished: break case .failure(let error): self.marshalQueue.async { self.processWriteResponse(result: .failure(error)) } } } receiveValue: { [weak self] response in guard let self = self else { return } self.marshalQueue.async { self.processWriteResponse(result: .success(response)) } }.addTo(&observations) } private func processWriteResponse( result: Result<Google_Jacquard_Protocol_DFUWriteResponse, Error> ) { switch result { case .success(let response): context.totalBytesWritten = Int(response.offset) jqLogger.debug("bytes written: \(context.totalBytesWritten)/ \(context.image.count)") if context.totalBytesWritten < context.image.count { jqLogger.debug("Current crc \(currentCRC()) vs \(response.crc)") if UInt32(currentCRC()) != response.crc { jqLogger.error("CRC mismatch at offset \(context.totalBytesWritten)") handleEvent(.didReceiveWriteError(FirmwareImageWriterError.crcMismatch)) return } handleEvent(.imagePartiallyWritten) } else if context.totalBytesWritten == context.image.count { handleEvent(.imageCompletelyWritten) } else { handleEvent(.didReceiveWriteError(FirmwareImageWriterError.dataCorruption)) } case .failure(let error): jqLogger.error("Write error: \(error) during image transfer.") handleEvent(.didReceiveWriteError(error)) } } /// Grabs the next slice of the image in transfer, up to the chunk size (128). /// /// - Returns: The packet of Data to be transferred. private func imagePacket() -> Data { let upperLimit = min( (context.totalBytesWritten + FirmwareImageWriterStateMachine.imageChunkSize), context.image.count ) return context.image.subdata(in: context.totalBytesWritten..<upperLimit) } /// Returns the CRC for the image in transfer, from 0 to however many bytes have been sent. /// /// - Returns: The CRC16 check for the subdata being written. private func currentCRC() -> UInt16 { let dataSent = context.image.subdata(in: 0..<context.totalBytesWritten) return CRC16.compute(in: dataSent, seed: 0) } } //MARK: - Transitions. extension FirmwareImageWriterStateMachine { /// Examines events and current state to apply transitions. private func handleEvent(_ event: Event) { dispatchPrecondition(condition: .onQueue(marshalQueue)) if state.isTerminal { jqLogger.info("State machine is already terminal, ignoring event: \(event)") } jqLogger.debug("Entering \(self).handleEvent(\(state), \(event)") switch (state, event) { // (t1) case (.idle, .checkStatus): state = .checkingStatus checkStatus() // (t2) case (.checkingStatus, .prepareForWriting): state = .preparingForWrite prepareForWriting() // (t3) case (.checkingStatus, .imagePartiallyWritten): state = .writing(context.totalBytesWritten) sendPacket() // (t4) case (.checkingStatus, .imageCompletelyWritten): state = .complete // (e5) case (.checkingStatus, .didReceiveStatusCheckError(let error)): state = .error(error) // (t6) case (.preparingForWrite, .startWriting): state = .writing(context.totalBytesWritten) self.sendPacket() // (e7) case (.preparingForWrite, .didReceivePrepareError(let error)): state = .error(error) // (t8) case (.writing(_), .imagePartiallyWritten): state = .writing(context.totalBytesWritten) sendPacket() // (t9) case (.writing(_), .imageCompletelyWritten): state = .complete // (e10) case (.writing(_), .didReceiveWriteError(let error)): state = .error(error) // No valid transition found. default: jqLogger.error("No transition found for (\(state), \(event))") state = .error(FirmwareImageWriterError.internalError) } jqLogger.debug("Exiting \(self).handleEvent() new state: \(state)") } } //MARK: - Dot Statechart // Note that the order is important - the transition events/guards will be evaluated in order and // only the first matching transition will have effect. //digraph G { // // "start" -> "idle" // // "idle" -> "checkingStatus" // [label = "(t1) // checkStatus // / checkStatus()"]; // // "checkingStatus" -> "preparingForWrite" // [label = "(t2) // prepareForWriting // / prepareForWriting()"]; // // "checkingStatus" -> "writing" // [label = "(t3) // imagePartiallyWritten // / sendPacket()"]; // // "checkingStatus" -> "complete" // [label = "(t4) // imageCompletelyWritten"]; // // "checkingStatus" -> "error" // [label = "(e5) // didReceiveStatusCheckError(error)"]; // // "preparingForWrite" -> "writing" // [label = "(t6) // startWriting // / sendPacket()"]; // // "preparingForWrite" -> "error" // [label = "(e7) // didReceivePrepareError(error)"]; // // "writing" -> "writing" // [label = "(t8) // imagePartiallyWritten // / sendPacket()"]; // // "writing" -> "complete" // [label = "(t9) // imageCompletelyWritten"]; // // "writing" -> "error" // [label = "(e10) // didReceiveWriteError(error)"]; // // "complete" -> "end" // // error [color=red style=filled] // start [shape=diamond] // end [shape=diamond] //}
apache-2.0
1efc6ba8c85c6869a9890112d7e10b74
28.100223
105
0.655901
4.332228
false
false
false
false
efremidze/Magnetic
Example/ViewController.swift
1
2242
// // ViewController.swift // Example // // Created by Lasha Efremidze on 3/8/17. // Copyright © 2017 efremidze. All rights reserved. // import SpriteKit import Magnetic class ViewController: UIViewController { @IBOutlet weak var magneticView: MagneticView! { didSet { magnetic.magneticDelegate = self magnetic.removeNodeOnLongPress = true #if DEBUG magneticView.showsFPS = true magneticView.showsDrawCount = true magneticView.showsQuadCount = true magneticView.showsPhysics = true #endif } } var magnetic: Magnetic { return magneticView.magnetic } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) for _ in 0..<12 { add(nil) } } @IBAction func add(_ sender: UIControl?) { let name = UIImage.names.randomItem() let color = UIColor.colors.randomItem() let node = Node(text: name.capitalized, image: UIImage(named: name), color: color, radius: 40) node.scaleToFitContent = true node.selectedColor = UIColor.colors.randomItem() magnetic.addChild(node) // Image Node: image displayed by default // let node = ImageNode(text: name.capitalized, image: UIImage(named: name), color: color, radius: 40) // magnetic.addChild(node) } @IBAction func reset(_ sender: UIControl?) { magneticView.magnetic.reset() } } // MARK: - MagneticDelegate extension ViewController: MagneticDelegate { func magnetic(_ magnetic: Magnetic, didSelect node: Node) { print("didSelect -> \(node)") } func magnetic(_ magnetic: Magnetic, didDeselect node: Node) { print("didDeselect -> \(node)") } func magnetic(_ magnetic: Magnetic, didRemove node: Node) { print("didRemove -> \(node)") } } // MARK: - ImageNode class ImageNode: Node { override var image: UIImage? { didSet { texture = image.map { SKTexture(image: $0) } } } override func selectedAnimation() {} override func deselectedAnimation() {} }
mit
a12a14c812f06d7cf5467d403a1ee56a
25.678571
110
0.597501
4.464143
false
false
false
false
dobriy-eeh/omim
iphone/Maps/Classes/CustomViews/NavigationDashboard/Views/RoutePreview/RouteManager/RouteManagerTransitioning.swift
1
1367
final class RouteManagerTransitioning: NSObject, UIViewControllerAnimatedTransitioning { private let isPresentation: Bool init(isPresentation: Bool) { self.isPresentation = isPresentation super.init() } func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return kDefaultAnimationDuration } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { guard let fromVC = transitionContext.viewController(forKey: .from), let toVC = transitionContext.viewController(forKey: .to) else { return } let animatingVC = isPresentation ? toVC : fromVC guard let animatingView = animatingVC.view else { return } let finalFrameForVC = transitionContext.finalFrame(for: animatingVC) var initialFrameForVC = finalFrameForVC initialFrameForVC.origin.y += initialFrameForVC.size.height let initialFrame = isPresentation ? initialFrameForVC : finalFrameForVC let finalFrame = isPresentation ? finalFrameForVC : initialFrameForVC animatingView.frame = initialFrame UIView.animate(withDuration: transitionDuration(using: transitionContext), animations: { animatingView.frame = finalFrame }, completion: { _ in transitionContext.completeTransition(true) }) } }
apache-2.0
34e619aa1f11e48ac6319938e9777d9d
38.057143
107
0.743965
6.075556
false
false
false
false
ShiWeiCN/JESAlertView
JESAlertView/AlertMakerAlertPromptable.swift
2
1170
// // AlertMakerAlertPromptable.swift // Demo // // Created by Jerry on 17/10/2016. // Copyright © 2016 jerryshi. All rights reserved. // This software is released under the MIT License. // http://opensource.org/licenses/mit-license.php // #if os(iOS) import UIKit #endif public class AlertMakerAlertPromptable: AlertMakerEditable { internal func prompt(of prompt: AlertPrompt, content: String, file: String, line: UInt) -> AlertMakerAlertPromptable { self.description.prompt = prompt if prompt.isTitlePrompt() { self.description.title = content } else { self.description.message = content } return self } @discardableResult public func title(_ title: String, _ file: String = #file, _ line: UInt = #line) -> AlertMakerAlertPromptable { return self.prompt(of: .title, content: title, file: file, line: line) } @discardableResult public func message(_ message: String, _ file: String = #file, _ line: UInt = #line) -> AlertMakerAlertPromptable { return self.prompt(of: .message, content: message, file: file, line: line) } }
mit
1bdbdd65470fcc2f768aa7a7816a7513
30.594595
122
0.650128
3.989761
false
false
false
false
khizkhiz/swift
test/Interpreter/currying_generics.swift
2
4643
// RUN: %target-run-simple-swift | FileCheck %s // REQUIRES: executable_test func curry<T, U, V>(f: (T, U) -> V) -> (T) -> (U) -> V { return { x in { y in f(x, y) } } } func curry<T1, T2, T3, T4>(f: (T1, T2, T3) -> T4) -> (T1) -> (T2) -> (T3) -> T4 { return { x in { y in { z in f(x, y, z) } } } } func concat(x: String, _ y: String, _ z: String) -> String { return x + y + z } @inline(never) public func test_concat_closure(x: Int) -> String { var x = x let insult = curry(concat)("one ")(" two ") var gs = insult(" three ") if (x > 0) { gs = gs + insult(" four ") gs = gs + insult(" five ") } else { gs = gs + insult(" six ") gs = gs + insult(" seven ") } if (x > 10) { x += 100 } return gs } public protocol P { func val() -> Int32 } struct CP: P { let v: Int32 func val() -> Int32 { return v } init(_ v: Int32) { self.v = v } } func compose(x: P, _ y: P, _ z: P) -> Int32 { return x.val() + y.val() + z.val() } @inline(never) public func test_compose_closure(x: Int) -> Int32 { var x = x let insult = curry(compose)(CP(1))(CP(2)) var gs = insult(CP(3)) if (x > 0) { gs = gs + insult(CP(4)) gs = gs + insult(CP(5)) } else { gs = gs + insult(CP(6)) gs = gs + insult(CP(7)) } if (x > 10) { x += 100 } return gs } let insult = curry(+)("I'm with stupid ☞ ") print(insult("😡")) // CHECK: I'm with stupid ☞ 😡 let plus1 = curry(+)(1) print(plus1(5)) // CHECK-NEXT: 6 let plus5 = curry(+)(5) print(plus5(5)) // CHECK-NEXT: 10 print(insult("😰")) // CHECK-NEXT: I'm with stupid ☞ 😰 let concat_one_two = curry(concat)("one ")(" two ") print(concat_one_two(" three ")) // CHECK-NEXT: one two three print(test_concat_closure(20)) // CHECK-NEXT: one two three one two four one two five print(test_compose_closure(20)) // CHECK-NEXT: 21 // rdar://problem/18988428 func clamp<T: Comparable>(minValue: T, _ maxValue: T) -> (n: T) -> T { return { n in max(minValue, min(n, maxValue)) } } let clampFoo2 = clamp(10.0, 30.0) print(clampFoo2(n: 3.0)) // CHECK-NEXT: 10.0 // rdar://problem/19195470 func pair<T,U> (a: T) -> U -> (T,U) { return { b in (a,b) } } func pair_<T,U> (a: T) -> (b: U) -> (T,U) { return { b in (a,b) } } infix operator <+> { } func <+><T,U,V> (lhs: T?, rhs: T -> U -> V) -> U -> V? { if let x = lhs { return { y in .some(rhs(x)(y)) } } else { return { _ in nil } } } let a : Int? = 23 let b : Int? = 42 print((b <+> pair)(a!)) // CHECK-NEXT: (42, 23) print((b <+> pair_)(a!)) // CHECK-NEXT: (42, 23) // // rdar://problem/20475584 // struct Identity<A> { let value: A } struct Const<A, B> { let value: A } func fmap<A, B>(f: A -> B) -> (Identity<A>) -> Identity<B> { return { identity in Identity(value: f(identity.value)) } } func fmap<A, B>(f: A -> B) -> (Const<A, B>) -> Const<A, B> { return { const in const } } // really Const() func _Const<A, B>(a: A) -> Const<A, B> { return Const(value: a) } func const<A, B>(a: A) -> (B) -> A { return { _ in a } } // really Identity() func _Identity<A>(a: A) -> Identity<A> { return Identity(value: a) } func getConst<A, B>(c: Const<A, B>) -> A { return c.value } func runIdentity<A>(i: Identity<A>) -> A { return i.value } func view<S, A>(lens: (A -> Const<A, S>) -> S -> ((A -> S) -> Const<A, S> -> Const<A, S>) -> Const<A, S>) -> (S) -> A { return { s in getConst(lens(_Const)(s)(fmap)) } } func over<S, A>(lens: (A -> Identity<A>) -> S -> ((A -> S) -> Identity<A> -> Identity<S>) -> Identity<S>) -> (A -> A) -> (S) -> S { return { f in { s in runIdentity(lens({ _Identity(f($0)) })(s)(fmap)) } } } func set<S, A>(lens: (A -> Identity<A>) -> S -> ((A -> S) -> Identity<A> -> Identity<S>) -> Identity<S>) -> (A) -> (S) -> S { return { x in { y in over(lens)(const(x))(y) } } } func _1<A, B, C, D>(f: A -> C) -> (A, B) -> ((A -> (A, B)) -> C -> D) -> D { return { (x, y) in { fmap in fmap({ ($0, y) })(f(x)) } } } func _2<A, B, C, D>(f: B -> C) -> (A, B) -> ((B -> (A, B)) -> C -> D) -> D { return { (x, y) in { fmap in fmap({ (x, $0) })(f(y)) } } } public func >>> <T, U, V> (f: T -> U, g: U -> V) -> T -> V { return { g(f($0)) } } public func <<< <T, U, V> (f: U -> V, g: T -> U) -> T -> V { return { f(g($0)) } } infix operator >>> { associativity right precedence 170 } infix operator <<< { associativity right precedence 170 } let pt1 = view(_1)((1, 2)) print(pt1) // CHECK-NEXT: 1 let pt2 = over(_1)({ $0 * 4 })((1, 2)) print(pt2) // CHECK-NEXT: (4, 2) let pt3 = set(_1)(3)((1, 2)) print(pt3) // CHECK-NEXT: (3, 2) let pt4 = view(_2)("hello", 5) print(pt4) // CHECK-NEXT: 5
apache-2.0
f14b6d3ee79063d819ee679796eff6e0
21.02381
131
0.51027
2.370579
false
false
false
false
iJudson/RxBasicInterface
RxBasicInterface/RxBasicInterface/Main/BasicView/CommonItemView.swift
1
6891
// // CommonItemView.swift // RxBasicInterface // // Created by 陈恩湖 on 2017/9/10. // Copyright © 2017年 Judson. All rights reserved. // import UIKit enum AlignmentWay { // 可有一个子控件 也可有两个控件 case center(inset: CGFloat) // 四个方向的 insets 都要改动 case top(inset: CGFloat) // top 方向的 inset case bottom(inset: CGFloat) case left(inset: CGFloat) case right(inset: CGFloat) // 必有两个子控件 - 文字和图片控件(默认两个控件 centerY 和父控件的对齐) space 这两个子控件相距距离(可左右 可上下) case leftTextRightImage(space: CGFloat) case leftImageRightText(space: CGFloat) case upTextDownImage(space: CGFloat) case upImageDownText(space: CGFloat) } class CommonItemView: UIButton { var title: String? { didSet { self.setTitle(title, for: .normal) } } var image: UIImage? { didSet { self.setImage(image, for: .normal) } } // 这个方法的调用需要在 1. 当前 titleLabel 的 font 属性设置完后 2. 将该 view 添加到 父 view 之后再设置 var alignmentStyle: AlignmentWay? { didSet { guard let alignmentStyle = self.alignmentStyle else { return } updateAlignmentStyle(alignment: alignmentStyle) } } convenience init(frame commonFrame: CGRect = CGRect.zero, image: UIImage?, title: String?) { self.init(frame: commonFrame) self.backgroundColor = UIColor.white updateCommonViewData(image: image, title: title) } } // MARK: - 更新该控件上的数据 以及 更新其风格样式 extension CommonItemView { fileprivate func updateCommonViewData(image: UIImage?, title: String?) { self.setImage(image, for: .normal) self.setTitle(title, for: .normal) self.titleLabel?.font = UIFont.systemFont(ofSize: 14) self.titleLabel?.textAlignment = .center self.setTitleColor(UIColor.gray, for: .normal) } fileprivate func updateAlignmentStyle(alignment: AlignmentWay) { if self.frame == CGRect.zero { self.sizeToFit() } self.titleLabel?.sizeToFit() self.imageView?.sizeToFit() let labelWidth = self.titleLabel?.width ?? 0 let labelHeight = self.titleLabel?.height ?? 0 let imageWidth = self.imageView?.width ?? 0 let imageHeight = self.imageView?.height ?? 0 // labelWidthPadding 的作用是尽量让 titleLabel 的 width 更大些 let labelWidthPadding = max((self.width - labelWidth) * 0.5, 0) let imageWidthPadding = max((self.width - imageWidth) * 0.5, 0) let controlsHeight = labelHeight + imageHeight let controlsWidth = labelWidth + imageWidth let constrolVerticalPadding = max((self.height - controlsHeight) * 0.5, 0) let constrolHorizontalPadding = max((self.width - controlsWidth) * 0.5, 0) switch alignment { case let .center(inset: inPutInset): guard constrolVerticalPadding != 0 && constrolHorizontalPadding != 0 else { return } self.contentEdgeInsets = UIEdgeInsets(top: inPutInset, left: inPutInset, bottom: inPutInset, right: inPutInset) case let .top(inset: inPutInset): guard constrolVerticalPadding != 0 else { return } self.contentEdgeInsets = UIEdgeInsets(top: -constrolVerticalPadding + inPutInset, left: 0, bottom: constrolVerticalPadding - inPutInset, right: 0) case let .bottom(inset: inPutInset): guard constrolVerticalPadding != 0 else { return } self.contentEdgeInsets = UIEdgeInsets(top: constrolVerticalPadding - inPutInset, left: 0, bottom: -constrolVerticalPadding + inPutInset, right: 0) case let .left(inset: inPutInset): guard constrolHorizontalPadding != 0 else { return } self.contentEdgeInsets = UIEdgeInsets(top: 0, left: -constrolHorizontalPadding + inPutInset, bottom: 0, right: constrolHorizontalPadding - inPutInset) case let .right(inset: inPutInset): guard constrolHorizontalPadding != 0 else { return } self.contentEdgeInsets = UIEdgeInsets(top: 0, left: constrolHorizontalPadding - inPutInset, bottom: 0, right: -constrolHorizontalPadding + inPutInset) case let .leftTextRightImage(space: space): self.imageEdgeInsets = UIEdgeInsets(top: 0, left: labelWidth + space * 0.5, bottom: 0, right: -labelWidth - space * 0.5) self.titleEdgeInsets = UIEdgeInsets(top: 0, left: -imageWidth - space * 0.5, bottom: 0, right: imageWidth + space * 0.5) case let .leftImageRightText(space: space): self.imageEdgeInsets = UIEdgeInsets(top: 0, left: -space * 0.5, bottom: 0, right: space * 0.5) self.titleEdgeInsets = UIEdgeInsets(top: 0, left: space * 0.5, bottom: 0, right: -space * 0.5) case let .upTextDownImage(space: space): let labelVerticalInset: CGFloat = (controlsHeight - labelHeight + space) * 0.5 let labelHorizontalInset: CGFloat = (controlsWidth - labelWidth) * 0.5 let imageVerticalInset: CGFloat = (controlsHeight - imageHeight + space) * 0.5 let imageHorizontalInset: CGFloat = (controlsWidth - imageWidth) * 0.5 self.titleEdgeInsets = UIEdgeInsets(top: -labelVerticalInset, left: -labelHorizontalInset - labelWidthPadding, bottom: labelVerticalInset, right: labelHorizontalInset - labelWidthPadding) self.imageEdgeInsets = UIEdgeInsets(top: imageVerticalInset, left: imageHorizontalInset - imageWidthPadding, bottom: -imageVerticalInset, right: -imageHorizontalInset - imageWidthPadding) case let .upImageDownText(space: space): let imageVerticalInset: CGFloat = (controlsHeight - imageHeight + space) * 0.5 let imageHorizontalInset: CGFloat = (controlsWidth - imageWidth) * 0.5 let labelVerticalInset: CGFloat = (controlsHeight - labelHeight + space) * 0.5 let labelHorizontalInset: CGFloat = (controlsWidth - labelWidth) * 0.5 self.imageEdgeInsets = UIEdgeInsets(top: -imageVerticalInset, left: imageHorizontalInset - imageWidthPadding, bottom: imageVerticalInset, right: -imageHorizontalInset - imageWidthPadding) self.titleEdgeInsets = UIEdgeInsets(top: labelVerticalInset, left: -labelHorizontalInset - labelWidthPadding, bottom: -labelVerticalInset, right: labelHorizontalInset - labelWidthPadding) } } }
mit
6df3b717b087832f3fbad5563bd5130c
45.27972
199
0.642339
4.429719
false
false
false
false
yanyuqingshi/ios-charts
Charts/Classes/Renderers/ChartYAxisRendererRadarChart.swift
1
5824
// // ChartYAxisRendererRadarChart.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.CGBase import UIKit.UIFont public class ChartYAxisRendererRadarChart: ChartYAxisRenderer { private weak var _chart: RadarChartView!; public init(viewPortHandler: ChartViewPortHandler, yAxis: ChartYAxis, chart: RadarChartView) { super.init(viewPortHandler: viewPortHandler, yAxis: yAxis, transformer: nil); _chart = chart; } public override func computeAxis(#yMin: Double, yMax: Double) { computeAxisValues(min: yMin, max: yMax); } internal override func computeAxisValues(min yMin: Double, max yMax: Double) { var labelCount = _yAxis.labelCount; var range = abs(yMax - yMin); if (labelCount == 0 || range <= 0) { _yAxis.entries = [Double](); return; } var rawInterval = range / Double(labelCount); var interval = ChartUtils.roundToNextSignificant(number: Double(rawInterval)); var intervalMagnitude = pow(10.0, round(log10(interval))); var intervalSigDigit = Int(interval / intervalMagnitude); if (intervalSigDigit > 5) { // Use one order of magnitude higher, to avoid intervals like 0.9 or // 90 interval = floor(10 * intervalMagnitude); } // if the labels should only show min and max if (_yAxis.isShowOnlyMinMaxEnabled) { _yAxis.entries = [Double](); _yAxis.entries.append(yMin); _yAxis.entries.append(yMax); } else { var first = ceil(Double(yMin) / interval) * interval; var last = ChartUtils.nextUp(floor(Double(yMax) / interval) * interval); var f: Double; var i: Int; var n = 0; for (f = first; f <= last; f += interval) { ++n; } if (isnan(_yAxis.customAxisMax)) { n += 1; } if (_yAxis.entries.count < n) { // Ensure stops contains at least numStops elements. _yAxis.entries = [Double](count: n, repeatedValue: 0.0); } for (f = first, i = 0; i < n; f += interval, ++i) { _yAxis.entries[i] = Double(f); } } _yAxis.axisMaximum = _yAxis.entries[_yAxis.entryCount - 1]; _yAxis.axisRange = abs(_yAxis.axisMaximum - _yAxis.axisMinimum); } public override func renderAxisLabels(#context: CGContext) { if (!_yAxis.isEnabled || !_yAxis.isDrawLabelsEnabled) { return; } var labelFont = _yAxis.labelFont; var labelTextColor = _yAxis.labelTextColor; var center = _chart.centerOffsets; var factor = _chart.factor; var labelCount = _yAxis.entryCount; var labelLineHeight = _yAxis.labelFont.lineHeight; for (var j = 0; j < labelCount; j++) { if (j == labelCount - 1 && _yAxis.isDrawTopYLabelEntryEnabled == false) { break; } var r = CGFloat(_yAxis.entries[j] - _yAxis.axisMinimum) * factor; var p = ChartUtils.getPosition(center: center, dist: r, angle: _chart.rotationAngle); var label = _yAxis.getFormattedLabel(j); ChartUtils.drawText(context: context, text: label, point: CGPoint(x: p.x + 10.0, y: p.y - labelLineHeight), align: .Left, attributes: [NSFontAttributeName: labelFont, NSForegroundColorAttributeName: labelTextColor]); } } public override func renderLimitLines(#context: CGContext) { var limitLines = _yAxis.limitLines; if (limitLines.count == 0) { return; } var sliceangle = _chart.sliceAngle; // calculate the factor that is needed for transforming the value to pixels var factor = _chart.factor; var center = _chart.centerOffsets; for (var i = 0; i < limitLines.count; i++) { var l = limitLines[i]; 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); } var r = CGFloat(l.limit - _chart.chartYMin) * factor; CGContextBeginPath(context); for (var j = 0, count = _chart.data!.xValCount; j < count; j++) { var p = ChartUtils.getPosition(center: center, dist: r, angle: sliceangle * CGFloat(j) + _chart.rotationAngle); if (j == 0) { CGContextMoveToPoint(context, p.x, p.y); } else { CGContextAddLineToPoint(context, p.x, p.y); } } CGContextClosePath(context); CGContextStrokePath(context); } } }
apache-2.0
443b88c0d373794c854bf1d15ec9d45d
30.317204
228
0.521635
4.982036
false
false
false
false
Lion-Hwang/sound-effector
ios/Pods/PKHUD/PKHUD/WindowRootViewController.swift
10
1980
// // PKHUD.WindowRootViewController.swift // PKHUD // // Created by Philip Kluz on 6/18/14. // Copyright (c) 2016 NSExceptional. All rights reserved. // Licensed under the MIT license. // import UIKit /// Serves as a configuration relay controller, tapping into the main window's rootViewController settings. internal class WindowRootViewController: UIViewController { internal override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { if let rootViewController = UIApplication.sharedApplication().delegate?.window??.rootViewController { return rootViewController.supportedInterfaceOrientations() } else { return UIInterfaceOrientationMask.Portrait } } internal override func preferredStatusBarStyle() -> UIStatusBarStyle { if let rootViewController = UIApplication.sharedApplication().delegate?.window??.rootViewController { return rootViewController.preferredStatusBarStyle() } else { return .Default } } internal override func prefersStatusBarHidden() -> Bool { if let rootViewController = UIApplication.sharedApplication().delegate?.window??.rootViewController { return rootViewController.prefersStatusBarHidden() } else { return false } } internal override func preferredStatusBarUpdateAnimation() -> UIStatusBarAnimation { if let rootViewController = UIApplication.sharedApplication().delegate?.window??.rootViewController { return rootViewController.preferredStatusBarUpdateAnimation() } else { return .None } } internal override func shouldAutorotate() -> Bool { if let rootViewController = UIApplication.sharedApplication().delegate?.window??.rootViewController { return rootViewController.shouldAutorotate() } else { return false } } }
epl-1.0
b256b0fc825f978f9476610799668bed
35.666667
109
0.684343
6.622074
false
false
false
false
robertoseidenberg/MixerBox
MixerBox/SBView+Converters.swift
1
458
extension SBView { func hsb(atPoint position: CGPoint) -> HSB { var hsb = self.hsb hsb.saturation = Float(position.x / bounds.size.width) hsb.brightness = 1 - Float(position.y / bounds.size.height) return hsb } func position(forHSB hsb: HSB) -> CGPoint { let x = bounds.size.width * CGFloat(hsb.saturation) let y = bounds.size.height * CGFloat(1 - hsb.brightness) return CGPoint(x: x, y: y) } }
mit
2e52db8bf4752464eb49fabd896623dc
23.105263
63
0.617904
3.550388
false
false
false
false
tberman/graphql-swift-codegen
Sources/graphql-code-gen/SwiftCodeGen.swift
1
3091
// // SwiftCodeGen.swift // graphql-swift-codegen // // Copyright © 2015 Todd Berman. All rights reserved. // import Foundation class SwiftTypeReference { let typeName: String let genericParameters: [SwiftTypeReference] init(_ typeName: String, genericParameters: [SwiftTypeReference] = []) { self.typeName = typeName self.genericParameters = genericParameters } func wrapOptional() -> SwiftTypeReference { return SwiftTypeReference("Optional", genericParameters: [self]) } func unwrapOptional() -> SwiftTypeReference { if typeName == "Optional" { return genericParameters[0] } return self } var code: String { switch (typeName) { case "Optional": return genericParameters[0].code + "?" case "Array": return "[" + genericParameters[0].code + "]" default: var c = typeName if genericParameters.count > 0 { c = c + "<" + (genericParameters.map { $0.code }).joined(separator: ", ") + ">" } return c } } } class SwiftTypeBuilder { let name: String let kind: Kind let members: [SwiftMemberBuilder] let inheritedTypes: [SwiftTypeReference] convenience init(_ name: String, _ kind: Kind, _ members: [SwiftMemberBuilder]) { self.init(name, kind, members, []) } init (_ name: String, _ kind: Kind, _ members: [SwiftMemberBuilder], _ inheritedTypes: [SwiftTypeReference]) { self.name = name self.kind = kind self.members = members self.inheritedTypes = inheritedTypes } var code: String { let preamble = "// generated by graphql-swift-codegen at \(NSDate().description)\n\n" let typeDeclaration = "\(kind.rawValue) \(name)" + (inheritedTypes.count > 0 ? ": " + (inheritedTypes.map { $0.code }.joined(separator: ",")) : "") let membersCode = members.map { " " + $0.code}.joined(separator: "\n") return "\(preamble)" + "\(typeDeclaration) {\n" + membersCode + "\n" + "}\n" } enum Kind: String { case Class = "class" case `Protocol` = "protocol" case Enum = "enum" } } protocol SwiftMemberBuilder { var code: String { get } } class SwiftFieldBuilder: SwiftMemberBuilder { let name: String let typeReference: SwiftTypeReference init(_ name: String, _ typeReference: SwiftTypeReference) { self.name = name self.typeReference = typeReference } var code: String { return "var \(name): \(typeReference.code)" } } class SwiftEnumValueBuilder: SwiftMemberBuilder { let name: String let value: String init(_ name: String, _ value: String) { self.name = name self.value = value } var code: String { return "case \(name) = \"\(value)\"" } }
mit
7f22206c4f1b1999c6364fc42a59a80b
24.75
114
0.557282
4.439655
false
false
false
false
noprom/TodoSwift
Demo/TodoSwift/AppDelegate.swift
1
3217
// // AppDelegate.swift // TodoSwift // // Created by Cyril Chandelier on 31/07/14. // Copyright (c) 2014 Cyril Chandelier. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> Bool { // Prepare CoreData stack CoreDataController.sharedInstance.configure("TodoSwift", storeType: NSSQLiteStoreType) // Prepare root let rootViewController = TodoListViewController() let rootNavigationController = UINavigationController(rootViewController: rootViewController) // Prepare window self.window = UIWindow(frame: UIScreen.mainScreen().bounds) self.window!.backgroundColor = UIColor.whiteColor() self.window!.rootViewController = rootNavigationController self.window!.makeKeyAndVisible() // Customize UI UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.LightContent UINavigationBar.appearance().barTintColor = UIColor(red: 80.0/255.0, green: 70.0/255.0, blue: 60.0/255.0, alpha: 1.0) UINavigationBar.appearance().tintColor = UIColor.whiteColor() return true } func applicationWillResignActive(application: UIApplication!) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication!) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication!) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication!) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication!) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. CoreDataController.sharedInstance.saveContext() } }
mit
420121740be7355d51117e2b43a72529
46.308824
285
0.727697
5.693805
false
false
false
false
iOS-Swift-Developers/Swift
基础语法/扩展/main.swift
1
1767
// // main.swift // 扩展 // // Created by 韩俊强 on 2017/7/11. // Copyright © 2017年 HaRi. All rights reserved. // import Foundation /* 扩展: 就是给一个现存类, 结构体, 枚举或者协议添加新的属性挥着方法的语法, 无需目标源码, 就可以吧想要的代码加到目标上面 但有一些限制条件需要说明: 1.不能添加一个已经存在的方法或者属性; 2.添加的属性不能是存储属性, 只能是计算属性; 格式: extension 某个先有类型{ //增加新的功能 } */ /// 1.扩展计算属性; class Transport { var scope:String init(scope:String) { self.scope = scope } } extension Transport { var extProperty:String{ get{ return scope } } } var myTrans = Transport(scope: "飞机") print(myTrans.extProperty) /// 2.扩展构造器 class Transport1 { var price = 30 var scope:String init(scope:String) { self.scope = scope } } extension Transport1 { convenience init(price:Int, scope:String) { self.init(scope: scope) self.price = price } } var myTra1 = Transport1(price: 55, scope: "大炮") //使用宽展的构造器, 价格为55 var myTra2 = Transport(scope: "轮船") //使用原构造器, 价格属性的值仍然是30 /// 3.扩展方法 //扩展整数类型 extension Int { func calculate() -> Int { return self * 2 } } var i = 3 print(3.calculate()) // 返回6 //扩展下标 //我们还可以通过扩展下标的方法来增强类的功能, 比如扩展整数类型, 使整数类型可以通过下标返回整数的倍数; extension Int { subscript (num: Int) -> Int { return self * num } } var j = 3 print(3[2]) //返回6
mit
91e78c1f9b0d005a3cf6c67bd6f616a7
14.571429
65
0.613914
2.730689
false
false
false
false
justindarc/firefox-ios
Client/Application/AppDelegate.swift
1
31052
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Shared import Storage import AVFoundation import XCGLogger import MessageUI import SDWebImage import SwiftKeychainWrapper import LocalAuthentication import SyncTelemetry import Sync import CoreSpotlight import UserNotifications private let log = Logger.browserLogger let LatestAppVersionProfileKey = "latestAppVersion" let AllowThirdPartyKeyboardsKey = "settings.allowThirdPartyKeyboards" private let InitialPingSentKey = "initialPingSent" class AppDelegate: UIResponder, UIApplicationDelegate, UIViewControllerRestoration { public static func viewController(withRestorationIdentifierPath identifierComponents: [String], coder: NSCoder) -> UIViewController? { return nil } var window: UIWindow? var browserViewController: BrowserViewController! var rootViewController: UIViewController! weak var profile: Profile? var tabManager: TabManager! var adjustIntegration: AdjustIntegration? var applicationCleanlyBackgrounded = true var shutdownWebServer: DispatchSourceTimer? weak var application: UIApplication? var launchOptions: [AnyHashable: Any]? let appVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String var receivedURLs = [URL]() var unifiedTelemetry: UnifiedTelemetry? func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // // Determine if the application cleanly exited last time it was used. We default to true in // case we have never done this before. Then check if the "ApplicationCleanlyBackgrounded" user // default exists and whether was properly set to true on app exit. // // Then we always set the user default to false. It will be set to true when we the application // is backgrounded. // self.applicationCleanlyBackgrounded = true let defaults = UserDefaults() if defaults.object(forKey: "ApplicationCleanlyBackgrounded") != nil { self.applicationCleanlyBackgrounded = defaults.bool(forKey: "ApplicationCleanlyBackgrounded") } defaults.set(false, forKey: "ApplicationCleanlyBackgrounded") defaults.synchronize() // Hold references to willFinishLaunching parameters for delayed app launch self.application = application self.launchOptions = launchOptions self.window = UIWindow(frame: UIScreen.main.bounds) self.window!.backgroundColor = UIColor.Photon.White100 // If the 'Save logs to Files app on next launch' toggle // is turned on in the Settings app, copy over old logs. if DebugSettingsBundleOptions.saveLogsToDocuments { Logger.copyPreviousLogsToDocuments() } return startApplication(application, withLaunchOptions: launchOptions) } func startApplication(_ application: UIApplication, withLaunchOptions launchOptions: [AnyHashable: Any]?) -> Bool { log.info("startApplication begin") // Need to get "settings.sendUsageData" this way so that Sentry can be initialized // before getting the Profile. let sendUsageData = NSUserDefaultsPrefs(prefix: "profile").boolForKey(AppConstants.PrefSendUsageData) ?? true Sentry.shared.setup(sendUsageData: sendUsageData) // Set the Firefox UA for browsing. setUserAgent() // Start the keyboard helper to monitor and cache keyboard state. KeyboardHelper.defaultHelper.startObserving() DynamicFontHelper.defaultHelper.startObserving() MenuHelper.defaultHelper.setItems() let logDate = Date() // Create a new sync log file on cold app launch. Note that this doesn't roll old logs. Logger.syncLogger.newLogWithDate(logDate) Logger.browserLogger.newLogWithDate(logDate) let profile = getProfile(application) unifiedTelemetry = UnifiedTelemetry(profile: profile) // Set up a web server that serves us static content. Do this early so that it is ready when the UI is presented. setUpWebServer(profile) let imageStore = DiskImageStore(files: profile.files, namespace: "TabManagerScreenshots", quality: UIConstants.ScreenshotQuality) // Temporary fix for Bug 1390871 - NSInvalidArgumentException: -[WKContentView menuHelperFindInPage]: unrecognized selector if let clazz = NSClassFromString("WKCont" + "ent" + "View"), let swizzledMethod = class_getInstanceMethod(TabWebViewMenuHelper.self, #selector(TabWebViewMenuHelper.swizzledMenuHelperFindInPage)) { class_addMethod(clazz, MenuHelper.SelectorFindInPage, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod)) } self.tabManager = TabManager(profile: profile, imageStore: imageStore) // Add restoration class, the factory that will return the ViewController we // will restore with. browserViewController = BrowserViewController(profile: self.profile!, tabManager: self.tabManager) browserViewController.edgesForExtendedLayout = [] browserViewController.restorationIdentifier = NSStringFromClass(BrowserViewController.self) browserViewController.restorationClass = AppDelegate.self let navigationController = UINavigationController(rootViewController: browserViewController) navigationController.delegate = self navigationController.isNavigationBarHidden = true navigationController.edgesForExtendedLayout = UIRectEdge(rawValue: 0) rootViewController = navigationController self.window!.rootViewController = rootViewController NotificationCenter.default.addObserver(forName: .FSReadingListAddReadingListItem, object: nil, queue: nil) { (notification) -> Void in if let userInfo = notification.userInfo, let url = userInfo["URL"] as? URL { let title = (userInfo["Title"] as? String) ?? "" profile.readingList.createRecordWithURL(url.absoluteString, title: title, addedBy: UIDevice.current.name) } } NotificationCenter.default.addObserver(forName: .FirefoxAccountDeviceRegistrationUpdated, object: nil, queue: nil) { _ in profile.flushAccount() } adjustIntegration = AdjustIntegration(profile: profile) if LeanPlumClient.shouldEnable(profile: profile) { LeanPlumClient.shared.setup(profile: profile) LeanPlumClient.shared.set(enabled: true) } self.updateAuthenticationInfo() SystemUtils.onFirstRun() let fxaLoginHelper = FxALoginHelper.sharedInstance fxaLoginHelper.application(application, didLoadProfile: profile) profile.cleanupHistoryIfNeeded() log.info("startApplication end") return true } func applicationWillTerminate(_ application: UIApplication) { // We have only five seconds here, so let's hope this doesn't take too long. profile?._shutdown() // Allow deinitializers to close our database connections. profile = nil tabManager = nil browserViewController = nil rootViewController = nil } /** * We maintain a weak reference to the profile so that we can pause timed * syncs when we're backgrounded. * * The long-lasting ref to the profile lives in BrowserViewController, * which we set in application:willFinishLaunchingWithOptions:. * * If that ever disappears, we won't be able to grab the profile to stop * syncing... but in that case the profile's deinit will take care of things. */ func getProfile(_ application: UIApplication) -> Profile { if let profile = self.profile { return profile } let p = BrowserProfile(localName: "profile", syncDelegate: application.syncDelegate) self.profile = p return p } func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. var shouldPerformAdditionalDelegateHandling = true adjustIntegration?.triggerApplicationDidFinishLaunchingWithOptions(launchOptions) UNUserNotificationCenter.current().delegate = self SentTabAction.registerActions() UIScrollView.doBadSwizzleStuff() window!.makeKeyAndVisible() // Now roll logs. DispatchQueue.global(qos: DispatchQoS.background.qosClass).async { Logger.syncLogger.deleteOldLogsDownToSizeLimit() Logger.browserLogger.deleteOldLogsDownToSizeLimit() } // If a shortcut was launched, display its information and take the appropriate action if let shortcutItem = launchOptions?[UIApplication.LaunchOptionsKey.shortcutItem] as? UIApplicationShortcutItem { QuickActions.sharedInstance.launchedShortcutItem = shortcutItem // This will block "performActionForShortcutItem:completionHandler" from being called. shouldPerformAdditionalDelegateHandling = false } // Force the ToolbarTextField in LTR mode - without this change the UITextField's clear // button will be in the incorrect position and overlap with the input text. Not clear if // that is an iOS bug or not. AutocompleteTextField.appearance().semanticContentAttribute = .forceLeftToRight return shouldPerformAdditionalDelegateHandling } func application(_ application: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool { guard let routerpath = NavigationPath(url: url) else { return false } if let profile = profile, let _ = profile.prefs.boolForKey(PrefsKeys.AppExtensionTelemetryOpenUrl) { profile.prefs.removeObjectForKey(PrefsKeys.AppExtensionTelemetryOpenUrl) var object = UnifiedTelemetry.EventObject.url if case .text(_) = routerpath { object = .searchText } UnifiedTelemetry.recordEvent(category: .appExtensionAction, method: .applicationOpenUrl, object: object) } DispatchQueue.main.async { NavigationPath.handle(nav: routerpath, with: self.browserViewController) } return true } // We sync in the foreground only, to avoid the possibility of runaway resource usage. // Eventually we'll sync in response to notifications. func applicationDidBecomeActive(_ application: UIApplication) { shutdownWebServer?.cancel() shutdownWebServer = nil // // We are back in the foreground, so set CleanlyBackgrounded to false so that we can detect that // the application was cleanly backgrounded later. // let defaults = UserDefaults() defaults.set(false, forKey: "ApplicationCleanlyBackgrounded") defaults.synchronize() if let profile = self.profile { profile._reopen() if profile.prefs.boolForKey(PendingAccountDisconnectedKey) ?? false { FxALoginHelper.sharedInstance.applicationDidDisconnect(application) } profile.syncManager.applicationDidBecomeActive() setUpWebServer(profile) } // We could load these here, but then we have to futz with the tab counter // and making NSURLRequests. browserViewController.loadQueuedTabs(receivedURLs: receivedURLs) receivedURLs.removeAll() application.applicationIconBadgeNumber = 0 // Resume file downloads. browserViewController.downloadQueue.resumeAll() // handle quick actions is available let quickActions = QuickActions.sharedInstance if let shortcut = quickActions.launchedShortcutItem { // dispatch asynchronously so that BVC is all set up for handling new tabs // when we try and open them quickActions.handleShortCutItem(shortcut, withBrowserViewController: browserViewController) quickActions.launchedShortcutItem = nil } UnifiedTelemetry.recordEvent(category: .action, method: .foreground, object: .app) } func applicationDidEnterBackground(_ application: UIApplication) { // // At this point we are happy to mark the app as CleanlyBackgrounded. If a crash happens in background // sync then that crash will still be reported. But we won't bother the user with the Restore Tabs // dialog. We don't have to because at this point we already saved the tab state properly. // let defaults = UserDefaults() defaults.set(true, forKey: "ApplicationCleanlyBackgrounded") defaults.synchronize() // Pause file downloads. browserViewController.downloadQueue.pauseAll() syncOnDidEnterBackground(application: application) UnifiedTelemetry.recordEvent(category: .action, method: .background, object: .app) let singleShotTimer = DispatchSource.makeTimerSource(queue: DispatchQueue.main) // 2 seconds is ample for a localhost request to be completed by GCDWebServer. <500ms is expected on newer devices. singleShotTimer.schedule(deadline: .now() + 2.0, repeating: .never) singleShotTimer.setEventHandler { WebServer.sharedInstance.server.stop() self.shutdownWebServer = nil } singleShotTimer.resume() shutdownWebServer = singleShotTimer } fileprivate func syncOnDidEnterBackground(application: UIApplication) { guard let profile = self.profile else { return } profile.syncManager.applicationDidEnterBackground() var taskId: UIBackgroundTaskIdentifier = UIBackgroundTaskIdentifier(rawValue: 0) taskId = application.beginBackgroundTask (expirationHandler: { print("Running out of background time, but we have a profile shutdown pending.") self.shutdownProfileWhenNotActive(application) application.endBackgroundTask(taskId) }) if profile.hasSyncableAccount() { profile.syncManager.syncEverything(why: .backgrounded).uponQueue(.main) { _ in self.shutdownProfileWhenNotActive(application) application.endBackgroundTask(taskId) } } else { profile._shutdown() application.endBackgroundTask(taskId) } } fileprivate func shutdownProfileWhenNotActive(_ application: UIApplication) { // Only shutdown the profile if we are not in the foreground guard application.applicationState != .active else { return } profile?._shutdown() } func applicationWillEnterForeground(_ application: UIApplication) { // The reason we need to call this method here instead of `applicationDidBecomeActive` // is that this method is only invoked whenever the application is entering the foreground where as // `applicationDidBecomeActive` will get called whenever the Touch ID authentication overlay disappears. self.updateAuthenticationInfo() } fileprivate func updateAuthenticationInfo() { if let authInfo = KeychainWrapper.sharedAppContainerKeychain.authenticationInfo() { if !LAContext().canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil) { authInfo.useTouchID = false KeychainWrapper.sharedAppContainerKeychain.setAuthenticationInfo(authInfo) } } } fileprivate func setUpWebServer(_ profile: Profile) { let server = WebServer.sharedInstance guard !server.server.isRunning else { return } ReaderModeHandlers.register(server, profile: profile) let responders: [(String, InternalSchemeResponse)] = [ (AboutHomeHandler.path, AboutHomeHandler()), (AboutLicenseHandler.path, AboutLicenseHandler()), (SessionRestoreHandler.path, SessionRestoreHandler()), (ErrorPageHandler.path, ErrorPageHandler())] responders.forEach { (path, responder) in InternalSchemeHandler.responders[path] = responder } if AppConstants.IsRunningTest { registerHandlersForTestMethods(server: server.server) } // Bug 1223009 was an issue whereby CGDWebserver crashed when moving to a background task // catching and handling the error seemed to fix things, but we're not sure why. // Either way, not implicitly unwrapping a try is not a great way of doing things // so this is better anyway. do { try server.start() } catch let err as NSError { print("Error: Unable to start WebServer \(err)") } } fileprivate func setUserAgent() { let firefoxUA = UserAgent.defaultUserAgent() // Set the UA for WKWebView (via defaults), the favicon fetcher, and the image loader. // This only needs to be done once per runtime. Note that we use defaults here that are // readable from extensions, so they can just use the cached identifier. let defaults = UserDefaults(suiteName: AppInfo.sharedContainerIdentifier)! defaults.register(defaults: ["UserAgent": firefoxUA]) SDWebImageDownloader.shared.setValue(firefoxUA, forHTTPHeaderField: "User-Agent") //SDWebImage is setting accept headers that report we support webp. We don't SDWebImageDownloader.shared.setValue("image/*;q=0.8", forHTTPHeaderField: "Accept") // Record the user agent for use by search suggestion clients. SearchViewController.userAgent = firefoxUA // Some sites will only serve HTML that points to .ico files. // The FaviconFetcher is explicitly for getting high-res icons, so use the desktop user agent. FaviconFetcher.userAgent = UserAgent.desktopUserAgent() } func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool { if #available(iOS 12.0, *) { if userActivity.activityType == SiriShortcuts.activityType.openURL.rawValue { browserViewController.openBlankNewTab(focusLocationField: false) return true } } // If the `NSUserActivity` has a `webpageURL`, it is either a deep link or an old history item // reached via a "Spotlight" search before we began indexing visited pages via CoreSpotlight. if let url = userActivity.webpageURL { let query = url.getQuery() // Check for fxa sign-in code and launch the login screen directly if query["signin"] != nil { browserViewController.launchFxAFromDeeplinkURL(url) return true } // Per Adjust documenation, https://docs.adjust.com/en/universal-links/#running-campaigns-through-universal-links, // it is recommended that links contain the `deep_link` query parameter. This link will also // be url encoded. if let deepLink = query["deep_link"]?.removingPercentEncoding, let url = URL(string: deepLink) { browserViewController.switchToTabForURLOrOpen(url, isPrivileged: true) return true } browserViewController.switchToTabForURLOrOpen(url, isPrivileged: true) return true } // Otherwise, check if the `NSUserActivity` is a CoreSpotlight item and switch to its tab or // open a new one. if userActivity.activityType == CSSearchableItemActionType { if let userInfo = userActivity.userInfo, let urlString = userInfo[CSSearchableItemActivityIdentifier] as? String, let url = URL(string: urlString) { browserViewController.switchToTabForURLOrOpen(url, isPrivileged: true) return true } } return false } fileprivate func openURLsInNewTabs(_ notification: UNNotification) { guard let urls = notification.request.content.userInfo["sentTabs"] as? [NSDictionary] else { return } for sentURL in urls { if let urlString = sentURL.value(forKey: "url") as? String, let url = URL(string: urlString) { receivedURLs.append(url) } } // Check if the app is foregrounded, _also_ verify the BVC is initialized. Most BVC functions depend on viewDidLoad() having run –if not, they will crash. if UIApplication.shared.applicationState == .active && browserViewController.isViewLoaded { browserViewController.loadQueuedTabs(receivedURLs: receivedURLs) receivedURLs.removeAll() } } func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) { let handledShortCutItem = QuickActions.sharedInstance.handleShortCutItem(shortcutItem, withBrowserViewController: browserViewController) completionHandler(handledShortCutItem) } } // MARK: - Root View Controller Animations extension AppDelegate: UINavigationControllerDelegate { func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationController.Operation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? { switch operation { case .push: return BrowserToTrayAnimator() case .pop: return TrayToBrowserAnimator() default: return nil } } } extension AppDelegate: MFMailComposeViewControllerDelegate { func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) { // Dismiss the view controller and start the app up controller.dismiss(animated: true, completion: nil) _ = startApplication(application!, withLaunchOptions: self.launchOptions) } } extension AppDelegate: UNUserNotificationCenterDelegate { // Called when the user taps on a sent-tab notification from the background. func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { openURLsInNewTabs(response.notification) } // Called when the user receives a tab while in foreground. func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { openURLsInNewTabs(notification) } } extension AppDelegate { func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { FxALoginHelper.sharedInstance.apnsRegisterDidSucceed(deviceToken) } func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { print("failed to register. \(error)") FxALoginHelper.sharedInstance.apnsRegisterDidFail() } func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { if Logger.logPII && log.isEnabledFor(level: .info) { NSLog("APNS NOTIFICATION \(userInfo)") } // At this point, we know that NotificationService has been run. // We get to this point if the notification was received while the app was in the foreground // OR the app was backgrounded and now the user has tapped on the notification. // Either way, if this method is being run, then the app is foregrounded. // Either way, we should zero the badge number. application.applicationIconBadgeNumber = 0 guard let profile = self.profile else { return completionHandler(.noData) } // NotificationService will have decrypted the push message, and done some syncing // activity. If the `client` collection was synced, and there are `displayURI` commands (i.e. sent tabs) // NotificationService will have collected them for us in the userInfo. if let serializedTabs = userInfo["sentTabs"] as? [NSDictionary] { // Let's go ahead and open those. for item in serializedTabs { if let urlString = item["url"] as? String, let url = URL(string: urlString) { receivedURLs.append(url) } } if receivedURLs.count > 0 { // If we're in the foreground, load the queued tabs now. if application.applicationState == .active { DispatchQueue.main.async { self.browserViewController.loadQueuedTabs(receivedURLs: self.receivedURLs) self.receivedURLs.removeAll() } } return completionHandler(.newData) } } // By now, we've dealt with any sent tab notifications. // // The only thing left to do now is to perform actions that can only be performed // while the app is foregrounded. // // Use the push message handler to re-parse the message, // this time with a BrowserProfile and processing the return // differently than in NotificationService. let handler = FxAPushMessageHandler(with: profile) handler.handle(userInfo: userInfo).upon { res in if let message = res.successValue { switch message { case .accountVerified: _ = handler.postVerification() case .thisDeviceDisconnected: FxALoginHelper.sharedInstance.applicationDidDisconnect(application) default: break } } completionHandler(res.isSuccess ? .newData : .failed) } } func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) { let completionHandler: (UIBackgroundFetchResult) -> Void = { _ in } self.application(application, didReceiveRemoteNotification: userInfo, fetchCompletionHandler: completionHandler) } } extension UIApplication { var syncDelegate: SyncDelegate { return AppSyncDelegate(app: self) } static var isInPrivateMode: Bool { let appDelegate = UIApplication.shared.delegate as? AppDelegate return appDelegate?.browserViewController.tabManager.selectedTab?.isPrivate ?? false } } class AppSyncDelegate: SyncDelegate { let app: UIApplication init(app: UIApplication) { self.app = app } open func displaySentTab(for url: URL, title: String, from deviceName: String?) { DispatchQueue.main.sync { if let appDelegate = app.delegate as? AppDelegate, app.applicationState == .active { appDelegate.browserViewController.switchToTabForURLOrOpen(url, isPrivileged: false) return } // check to see what the current notification settings are and only try and send a notification if // the user has agreed to them UNUserNotificationCenter.current().getNotificationSettings { settings in if settings.alertSetting == .enabled { if Logger.logPII { log.info("Displaying notification for URL \(url.absoluteString)") } let notificationContent = UNMutableNotificationContent() let title: String if let deviceName = deviceName { title = String(format: Strings.SentTab_TabArrivingNotification_WithDevice_title, deviceName) } else { title = Strings.SentTab_TabArrivingNotification_NoDevice_title } notificationContent.title = title notificationContent.body = url.absoluteDisplayExternalString notificationContent.userInfo = [SentTabAction.TabSendURLKey: url.absoluteString, SentTabAction.TabSendTitleKey: title] notificationContent.categoryIdentifier = "org.mozilla.ios.SentTab.placeholder" // `timeInterval` must be greater than zero let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 0.1, repeats: false) // The identifier for each notification request must be unique in order to be created let requestIdentifier = "\(SentTabAction.TabSendCategory).\(url.absoluteString)" let request = UNNotificationRequest(identifier: requestIdentifier, content: notificationContent, trigger: trigger) UNUserNotificationCenter.current().add(request) { error in if let error = error { log.error(error.localizedDescription) } } } } } } } /** * This exists because the Sync code is extension-safe, and thus doesn't get * direct access to UIApplication.sharedApplication, which it would need to * display a notification. * This will also likely be the extension point for wipes, resets, and * getting access to data sources during a sync. */ enum SentTabAction: String { case view = "TabSendViewAction" static let TabSendURLKey = "TabSendURL" static let TabSendTitleKey = "TabSendTitle" static let TabSendCategory = "TabSendCategory" static func registerActions() { let viewAction = UNNotificationAction(identifier: SentTabAction.view.rawValue, title: Strings.SentTabViewActionTitle, options: .foreground) // Register ourselves to handle the notification category set by NotificationService for APNS notifications let sentTabCategory = UNNotificationCategory(identifier: "org.mozilla.ios.SentTab.placeholder", actions: [viewAction], intentIdentifiers: [], options: UNNotificationCategoryOptions(rawValue: 0)) UNUserNotificationCenter.current().setNotificationCategories([sentTabCategory]) } }
mpl-2.0
e7c2835b5ba18cdc61db8e17772a1ac9
43.484241
247
0.680354
5.725613
false
false
false
false
teodorpatras/Hackfest
PayCode/PayCode/Payment.swift
1
1627
// // Payment.swift // PayCode // // Created by Michał Hernas on 26/09/15. // Copyright © 2015 Teodor Patras. All rights reserved. // import Foundation import CoreData import Alamofire import SVProgressHUD enum PaymentType:String { case Paypal = "paypal", Visa = "visa", Mastercard = "mastercard" func backgroundImage() -> UIImage { switch(self) { case .Paypal: return UIImage(named: "paypal")! case .Visa: return UIImage(named: "visa")! case .Mastercard: return UIImage(named: "mastercard")! } } func logoImage() -> UIImage { switch(self) { case .Paypal: return UIImage(named: "paypal_logo")! case .Visa: return UIImage(named: "visa_logo")! case .Mastercard: return UIImage(named: "mastercard_logo")! } } } class Payment: NSManagedObject { var paymentType:PaymentType { return PaymentType(rawValue: self.type)! } func deleteFromApi() { let request = NSMutableURLRequest(URL: NSURL(string: "http://ohf.hern.as/payments/\(self.id.integerValue)/")!) request.HTTPMethod = "DELETE" request.setValue("application/json", forHTTPHeaderField: "Content-Type") SVProgressHUD.show() Alamofire.request(request).responseJSON { (request, response, result) -> Void in SVProgressHUD.dismiss() let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate appDelegate.managedObjectContext.deleteObject(self) } } }
mit
96f2ceff84d0891de026f0ce96b78de5
26.542373
118
0.606769
4.526462
false
false
false
false
wortman/stroll_safe_ios
Stroll Safe/PinpadViewController.swift
1
4887
// // PinpadViewController.swift // Stroll Safe // // Created by noah prince on 3/25/15. // Copyright (c) 2015 Stroll Safe. All rights reserved. // import UIKit class PinpadViewController: UIViewController { @IBOutlet weak var first: UIButton! @IBOutlet weak var second: UIButton! @IBOutlet weak var third: UIButton! @IBOutlet weak var fourth: UIButton! @IBOutlet weak var placeholder1: UIView! @IBOutlet weak var placeholder2: UIView! @IBOutlet weak var placeholder3: UIView! @IBOutlet weak var placeholder4: UIView! var correctPass = [Double](count: 4, repeatedValue: 2.0) var passField = [Double](count: 4, repeatedValue: 0.0) var currentIdx = 0; var enteredFn: (String) throws -> () = { (String) -> () in } func setEnteredFunction(fn: (String) throws -> ()) { enteredFn = fn } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. clear() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func clear(){ first.hidden = true second.hidden = true third.hidden = true fourth.hidden = true currentIdx = 0 } func passFieldString() -> NSString{ let passString = "\(Int(passField[0]))\(Int(passField[1]))\(Int(passField[2]))\(Int(passField[3]))" return passString } func setPass(value: Double){ if (currentIdx < passField.count){ passField[currentIdx] = value currentIdx++ } switch currentIdx{ case 1: first.hidden = false case 2: second.hidden = false case 3: third.hidden = false case 4: fourth.hidden = false try! enteredFn(getCurrentPass() as String) default: print("Invalid") } } func shake(){ let numbers = [placeholder1,placeholder2,placeholder3,placeholder4] dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { for filler in numbers { dispatch_async(dispatch_get_main_queue(), { let number = filler as UIView let animation = CABasicAnimation(keyPath: "position") animation.duration = 0.07 animation.repeatCount = 4 animation.autoreverses = true animation.fromValue = NSValue(CGPoint: CGPointMake(number.center.x - 10, number.center.y)) animation.toValue = NSValue(CGPoint: CGPointMake(number.center.x + 10, number.center.y)) number.layer.addAnimation(animation, forKey: "position") }) } }) } func getCurrentPass() -> NSString { return passFieldString() } @IBAction func buttonOne(sender: AnyObject) { setPass(1) } @IBAction func buttonTwo(sender: AnyObject) { setPass(2) } @IBAction func buttonThree(sender: AnyObject) { setPass(3) } @IBAction func buttonFour(sender: AnyObject) { setPass(4) } @IBAction func buttonFive(sender: AnyObject) { setPass(5) } @IBAction func buttonSix(sender: AnyObject) { setPass(6) } @IBAction func buttonSeven(sender: AnyObject) { setPass(7) } @IBAction func buttonEight(sender: AnyObject) { setPass(8) } @IBAction func buttonNine(sender: AnyObject) { setPass(9) } @IBAction func buttonClear(sender: AnyObject) { first.hidden = true second.hidden = true third.hidden = true fourth.hidden = true currentIdx = 0 } @IBAction func buttonZero(sender: AnyObject) { setPass(0) } @IBAction func buttonBack(sender: AnyObject) { switch currentIdx{ case 0: print("Invalid") return case 1: first.hidden = true case 2: second.hidden = true case 3: third.hidden = true case 4: fourth.hidden = true default: print("Invalid") } currentIdx-- } /* // 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
9ac2d4f76ed1d311164f9d31eb81cb03
25.416216
111
0.56108
4.658723
false
false
false
false
tad-iizuka/swift-sdk
Source/NaturalLanguageClassifierV1/Models/ClassifierModel.swift
3
1554
/** * Copyright IBM Corporation 2016 * * 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 RestKit /** A classifer supported by the Natural Language Classifier service. */ public struct ClassifierModel: JSONDecodable { /// A unique identifier for this classifier. public let classifierId: String /// A link to the classifer. public let url: String /// The user-supplied name of the classifier. public let name: String? /// The language used for the classifier. public let language: String /// The date and time (UTC) that the classifier was created. public let created: String /// Used internally to initialize a `ClassifierModel` from JSON. public init(json: JSON) throws { classifierId = try json.getString(at: "classifier_id") url = try json.getString(at: "url") name = try? json.getString(at: "name") language = try json.getString(at: "language") created = try json.getString(at: "created") } }
apache-2.0
1e36500d442f91cbef246245dced2f2f
32.782609
75
0.689189
4.377465
false
false
false
false
scsonic/cosremote
ios/CosRemote/SelectFuncController.swift
1
3244
// // SelectFuncController.swift // CosRemote // // Created by 郭 又鋼 on 2016/3/2. // Copyright © 2016年 郭 又鋼. All rights reserved. // import Foundation import UIKit class SelectFunctionController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet var tableView: UITableView! var list = [TitleControler]() ; class TitleControler { var title:String var viewController:UIViewController var type:Int = 0 ; init( t:String, v:UIViewController ) { self.title = t ; self.viewController = v ; } init( t:String, v:UIViewController, type:Int) { self.title = t ; self.viewController = v ; self.type = type ; } } func initList() { self.list.removeAll() ; let ledArrayView = self.storyboard?.instantiateViewControllerWithIdentifier("LedArrayController") as! LedArrayController ; list.append(TitleControler(t: "Led跑馬燈-1", v: ledArrayView, type: 0 )) list.append(TitleControler(t: "Led跑馬燈-2", v: ledArrayView, type: 1 )) list.append(TitleControler(t: "單一顏色", v: ledArrayView, type: 2 )) list.append(TitleControler(t: "火焰顏色控制", v: ledArrayView, type: 3 )) // HSL format let accview = self.storyboard?.instantiateViewControllerWithIdentifier("AccController") ; list.append(TitleControler(t: "三軸加速度感測器", v: accview!)) let inmoovbasic = self.storyboard?.instantiateViewControllerWithIdentifier("InmoovBasicController") ; list.append(TitleControler(t: "機器手臂基本控制", v: inmoovbasic!)) let inmoovAdvance = self.storyboard?.instantiateViewControllerWithIdentifier("InmoovAdvanceController") ; list.append(TitleControler(t: "機器手臂快速手勢", v: inmoovAdvance!)) } override func viewDidLoad() { initList() ; self.tableView.delegate = self ; self.tableView.dataSource = self ; } override func viewDidAppear(animated: Bool) { self.navigationItem.title = "功能" } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.list.count } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let item = self.list[ indexPath.item ] if let ledarray = item.viewController as? LedArrayController { ledarray.naviTitle = item.title ; ledarray.type = item.type ; } self.navigationController?.pushViewController(item.viewController, animated: true) ; } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let item = self.list[ indexPath.item ] let cell = tableView.dequeueReusableCellWithIdentifier("SelectFuncCell") as! SelectFuncCell cell.lbTitle.text = item.title return cell ; } }
mit
ca163245533b9f39bf978829d1d686a2
29.543689
130
0.612083
4.460993
false
false
false
false
PumpMagic/ostrich
gbsplayer/gbsplayer/Source/Views/PulseWaveView.swift
1
4570
// // PulseWaveView.swift // gbsplayer // // Created by Owner on 1/24/17. // Copyright © 2017 conwarez. All rights reserved. // import Cocoa import gameboy // Some configuration constants fileprivate let PIXELS_PER_SECOND_SCALE_FACTOR = 50.0 fileprivate let LINE_WIDTH: CGFloat = 1.5 fileprivate let CONNECTED_STROKE_COLOR = GAMEBOY_PALLETTE_11 fileprivate let DISCONNECTED_STROKE_COLOR = GAMEBOY_PALLETTE_01 /// A viewable representation of a pulse wave channel. Updates only when needsDisplay is set by someone else. class PulseWaveView: NSView { /// Channel we're drawing var channel: Pulse? = nil var strokeColor: NSColor { guard let channel = self.channel else { return DISCONNECTED_STROKE_COLOR } if channel.isConnected() { return CONNECTED_STROKE_COLOR } else { return DISCONNECTED_STROKE_COLOR } } /// Draw a flat line as the waveform private func drawFlatLine(at y: CGFloat) { let startPoint = CGPoint(x: bounds.minX, y: y) let endPoint = CGPoint(x: bounds.maxX, y: y) strokeColor.set() let path = NSBezierPath() path.lineWidth = LINE_WIDTH path.move(to: startPoint) path.line(to: endPoint) path.stroke() path.close() } private func drawRectangle(x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat) { let path = NSBezierPath(rect: NSRect(x: x, y: y, width: width, height: height)) strokeColor.set() path.fill() } /// Draw the pulse wave. /// Amplitude should be [0.0, 1.0]; frequency should be in Hz; duty should be [0.0, 1.0]. private func drawWaveform(amplitude: Double, frequency: Double, duty: Double) { if amplitude == 0.0 || duty == 0.0 { drawFlatLine(at: bounds.minY) return } let waveMinX = bounds.minX let waveMaxX = bounds.maxX let waveHeight = floor(bounds.height * CGFloat(amplitude)) let waveMinY = bounds.minY let waveMaxY = bounds.minY + waveHeight - 1 let pixelsPerSecond = Double(bounds.width) * PIXELS_PER_SECOND_SCALE_FACTOR if frequency > (pixelsPerSecond/2) { // The waveform is so dense that our output, rendered carefully, would just be a solid block. // Rather than spending the resources, just output a solid block directly drawRectangle(x: waveMinX, y: waveMinY, width: (waveMaxX-waveMinX), height: (waveMaxY-waveMinY)) return } var x = CGFloat(waveMinX) var y = CGFloat(waveMinY) let path = NSBezierPath() path.lineWidth = LINE_WIDTH let startingPoint = CGPoint(x: x, y: y) strokeColor.set() path.move(to: startingPoint) // Draw half-periods of the pulse wave until we reach the edge of our view while x < waveMaxX { // Draw a horizontal edge let maxNextX: CGFloat if y == waveMinY { // bottom edge maxNextX = x + CGFloat(pixelsPerSecond / frequency * (1-duty)) } else { // top edge maxNextX = x + CGFloat(pixelsPerSecond / frequency * (duty)) } let nextX = min(waveMaxX, maxNextX) path.line(to: CGPoint(x: nextX, y: y)) x = nextX if x < waveMaxX { // Draw a vertical edge let nextY: CGFloat if y == waveMinY { // bottom-top transition nextY = waveMaxY } else { // top-bottom transition nextY = waveMinY } path.line(to: CGPoint(x: x, y: nextY)) y = nextY } } // Stroke our curve path.stroke() } override func draw(_ dirtyRect: NSRect) { super.draw(dirtyRect) guard let channel = self.channel else { // We haven't been configured with a channel yet drawFlatLine(at: bounds.minY) return } let amplitude = channel.getMusicalAmplitude() let frequency = channel.getMusicalFrequency() let duty = channel.getDutyCycle() drawWaveform(amplitude: amplitude, frequency: frequency, duty: duty) } }
mit
f4fde4383cdd96132e8ae0dd4db9de4a
31.404255
109
0.555045
4.347288
false
false
false
false
PekanMmd/Pokemon-XD-Code
Revolution Tool CL/Code snippets.swift
1
1727
// // Code snippets.swft.swift // GoD Tool // // Created by Stars Momodu on 28/10/2020. // // Add fairy type // //let fairy = XGMoveTypes.type(9).data //fairy.name.duplicateWithString("[0xF001][0xF101]Fairy").replace() //for type in XGMoveTypes.allTypes { // fairy.setEffectiveness(.neutral, againstType: type) //} //for type: XGMoveTypes in [.fighting, .dragon, .dark] { // fairy.setEffectiveness(.superEffective, againstType: type) //} //for type: XGMoveTypes in [.poison, .steel, .fire] { // fairy.setEffectiveness(.notVeryEffective, againstType: type) //} //fairy.save() //for type: XGMoveTypes in [.poison, .steel] { // let data = type.data // data.setEffectiveness(.superEffective, againstType: .type(9)) // data.save() //} //for type: XGMoveTypes in [.fighting, .bug, .dark] { // let data = type.data // data.setEffectiveness(.notVeryEffective, againstType: .type(9)) // data.save() //} //for type: XGMoveTypes in [.dragon] { // let data = type.data // data.setEffectiveness(.ineffective, againstType: .type(9)) // data.save() //} // //for i in 0 ..< kNumberOfTypes { // let type = XGMoveTypes.type(i).data // print(i, type.nameID, type.name) //} // //for name in ["clefairy", "clefable", "cleffa", "togepi", "togetic", "snubbull", "granbull", "mime jr.", "togekiss"] { // let mon = pokemon(name).stats // mon.type1 = .type(fairy.index) // mon.save() //} // //for name in ["azurill", "marill", "azumarill", "clefairy", "clefable", "jigglypuff", "wigglytuff", "mr. mime", "cleffa", "igglybuff", "togepi", "snubbull", "granbull", "mawile", "ralts", "kirlia", "gardevoir"] { // let mon = pokemon(name).stats // mon.type2 = .type(fairy.index) // mon.save() //} // //XGUtility.compileMainFiles() //XGUtility.compileISO()
gpl-2.0
52c21bfbec74ba30b5e3fea141f65ab3
29.839286
213
0.661841
2.785484
false
false
false
false
huonw/swift
test/NameBinding/scope_map_lookup.swift
1
2286
// RUN: %target-typecheck-verify-swift -enable-astscope-lookup // Name binding in default arguments // FIXME: Semantic analysis should produce an error here, because 'x' // is not actually available. func functionParamScopes(x: Int, y: Int = x) -> Int { return x + y } // Name binding in instance methods. class C1 { var x = 0 var hashValue: Int { return x } } // Protocols involving 'Self'. protocol P1 { associatedtype A = Self } // Protocols involving associated types. protocol AProtocol { associatedtype e : e // expected-error@-1 {{use of undeclared type 'e'}} } // Extensions. protocol P2 { } extension P2 { func getSelf() -> Self { return self } } #if false // Lazy properties class LazyProperties { init() { lazy var localvar = 42 // FIXME: should error {{lazy is only valid for members of a struct or class}} {{5-10=}} localvar += 1 _ = localvar } var value: Int = 17 lazy var prop1: Int = value lazy var prop2: Int = { value + 1 }() lazy var prop3: Int = { [weak self] in self.value + 1 }() lazy var prop4: Int = self.value lazy var prop5: Int = { self.value + 1 }() } #endif // Protocol extensions. // Extending via a superclass constraint. class Superclass { func foo() { } static func bar() { } typealias Foo = Int } protocol PConstrained4 { } extension PConstrained4 where Self : Superclass { func testFoo() -> Foo { foo() self.foo() return Foo(5) } static func testBar() { bar() self.bar() } } // Local computed properties. func localComputedProperties() { var localProperty: Int { get { return localProperty // expected-warning{{attempting to access 'localProperty' within its own getter}} } set { _ = newValue print(localProperty) } } { print(localProperty) }() } // Top-level code. func topLevel() { } topLevel() let c1opt: C1? = C1() guard let c1 = c1opt else { } protocol Fooable { associatedtype Foo var foo: Foo { get } } // The extension below once caused infinite recursion. struct S<T> // expected-error{{expected '{' in struct}} extension S // expected-error{{expected '{' in extension}} let a = b ; let b = a // expected-note@-1 {{'a' declared here}} // expected-error@-2 {{ambiguous use of 'a'}}
apache-2.0
d733951f3b420db83f4dceac489185ee
17.585366
116
0.641732
3.53323
false
false
false
false
googlearchive/science-journal-ios
ScienceJournalTests/Extensions/String+ScienceJournalTest.swift
1
4284
/* * 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 XCTest @testable import third_party_sciencejournal_ios_ScienceJournalOpen class String_ScienceJournalTest: XCTestCase { func testLocalizedUntitledTrialString() { let index: Int32 = 5 if UIApplication.shared.userInterfaceLayoutDirection == .rightToLeft { XCTAssertEqual(String.localizedUntitledTrial(withIndex: index), "5 \(String.runDefaultTitle)") } else { XCTAssertEqual(String.localizedUntitledTrial(withIndex: index), "\(String.runDefaultTitle) 5") } } func testTruncatedWithHex() { let string = "AVeryLongStringWhichWillBeTruncatedByAddingHashOfOverflowCharacters" let truncated = string.truncatedWithHex(maxLength: 23) XCTAssertTrue(truncated.count <= 23) XCTAssertTrue(truncated.starts(with: "AVeryLongString"), "The input string should be the same up to the start of the hash.") let string2 = "AnotherString" XCTAssertEqual(string2, string2.truncatedWithHex(maxLength: 13), "No truncation if the input string is less than or equal to maxLength.") let string3 = "Short" XCTAssertEqual("Sho", string3.truncatedWithHex(maxLength: 3), "No hash is added if max Length is less than typical hex length") } func testSanitizedForFilename() { let allowed = "ABCDEFGHIJKLMNOPQRSTUVWXYZ - abcdefghijklmnopqrstuvwxyz - 0123456789" XCTAssertEqual(allowed, allowed.sanitizedForFilename) // Some glyphs like the heart are composed of two unicode characters which are replaced with two // underscores. Without a more complicated implementation this is unavoidable. let emoji = "E🤓M😫O🤯J💡I🔧S❤️" XCTAssertEqual("E_M_O_J_I_S__", emoji.sanitizedForFilename) let specials = "eéuüaåiîEÉUÜAÅIÎ" XCTAssertEqual("e_u_a_i_E_U_A_I_", specials.sanitizedForFilename) } func testValidFilename() { // String with 252 characters which should be the max allowed after adding the extension. let string = "3456789012345678901234567890123456789012345678901234567890123456789012345678901" + "23456789012345678ssafasdfasfasdfsfasfasfdsfasfasfasfsadfsdfasfsadfdsfsdafasdfsdafsadfads" + "fasdfsdafsadfdsafsdafdsfasdfasdfasdfasdfasdfasfasdffsadfasfasdfasfasfdsafsadfasdfa252" let ext = "sj" var filename = string.validFilename(withExtension: "sj") let unprocessedName = string + "." + ext XCTAssertEqual(unprocessedName.utf16.count, filename.utf16.count) XCTAssertTrue(filename.utf16.count <= 255) let longString = "012345678901234567890123456789012345678901234567890123456789012345678901234" + "567890123456789012345678ssafasdfasfasdfsfasfasfdsfasfasfasfsadfsdfasfsadfdsfsdafasdfsdaf" + "sadfadsfasdfsdafsadfdsafsdafdsfasdfasdfasdfasdfasdfasfasdffsadfasfasdfasfasfdsafsadfasdf" + "abvs012345678901234567890123456789012345678901234567890123456789012345678901234567890123" + "456789012345678ssafasdfasfasdfsfasfasfdsfasfasfasfsadfsdfasfsadfdsfsdafasdfsdafsadfadsfa" + "sdfsdafsadfdsafsdafdsfasdfasdfasdfasdfasdfasfasdffsadfasfasdfasfasfdsafsadfasdfabvs" filename = longString.validFilename(withExtension: "sj") XCTAssertTrue(filename.utf16.count <= 255) let specialCharName = "My Fun Expériment Å - 🙀🖖👀😎" let sanitizedName = specialCharName.sanitizedForFilename print("sanitizedName: '\(sanitizedName)'") filename = specialCharName.validFilename(withExtension: "sj") print("filename: '\(filename)'") XCTAssertEqual("My Fun Exp_riment _ - ____.sj", filename) XCTAssertTrue(filename.utf16.count <= 255) } }
apache-2.0
733e8d51a7f6f74573bd500112c82b2f
44.623656
100
0.747113
3.914207
false
true
false
false
Lagovas/themis
docs/examples/Themis-server/swift/SwiftThemisServerExample/SwiftThemisServerExample/SMessageClient.swift
2
6644
// // SMessageClient.swift // SwiftThemisServerExample // // Created by Anastasi Voitova on 19.04.16. // Copyright © 2016 CossackLabs. All rights reserved. // import Foundation final class SMessageClient { // Read how Themis Server works: // https://github.com/cossacklabs/themis/wiki/Using-Themis-Server // you may want to re-generate all keys // user id and server public key are copied from server setup // https://themis.cossacklabs.com/interactive-simulator/setup/ let kUserId: String = "hAxNatMbDDbNUge" let kServerPublicKey: String = "VUVDMgAAAC0g5PxhAohzuMQqMORmE6hYiNk6Yn7fo52tkQyc9FJT4vsivVhV" // these two should generated by running `generateClientKeys()` let kClientPrivateKey: String = "UkVDMgAAAC0TXvcoAGxwWV3QQ9fgds+4pqAWmDqQAfkb0r/+gAi89sggGLpV" let kClientPublicKey: String = "VUVDMgAAAC3mmD1pAuXBcr8k+1rLNYkmw+MwTJMofuDaOTXLf75HW8BIG/5l" fileprivate func postRequestTo(_ stringURL: String, message: Data, completion: @escaping (_ data: Data?, _ error: Error?) -> Void) { let url: URL = URL(string: stringURL)! let config: URLSessionConfiguration = URLSessionConfiguration.default let session: URLSession = URLSession(configuration: config) let request: NSMutableURLRequest = NSMutableURLRequest(url: url) request.httpMethod = "POST" request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-type") let base64URLEncodedMessage: String = message.base64EncodedString(options: .endLineWithLineFeed).addingPercentEncoding(withAllowedCharacters: CharacterSet.alphanumerics)! let base64Body: String = "\("message=")\(base64URLEncodedMessage)" let body: Data = base64Body.data(using: String.Encoding.utf8)! let uploadTask: URLSessionDataTask = session.uploadTask(with: request as URLRequest, from: body, completionHandler: {(data: Data?, response: URLResponse?, error: Error?) -> Void in guard let data = data else { print("Oops, response = \(response)\n error = \(error)") completion(nil, error) return } if let response = response as? HTTPURLResponse, response.statusCode != 200 { print("Oops, response = \(response)\n error = \(error)") completion(nil, error) return } completion(data, nil) return }) uploadTask.resume() } func runSecureMessageCITest() { // uncomment to generate keys firste // generateClientKeys() // return; checkKeysNotEmpty() guard let serverPublicKey: Data = Data(base64Encoded: kServerPublicKey, options: .ignoreUnknownCharacters), let clientPrivateKey: Data = Data(base64Encoded: kClientPrivateKey, options: .ignoreUnknownCharacters) else { print("Error occurred during base64 encoding", #function) return } let encrypter: TSMessage = TSMessage.init(inEncryptModeWithPrivateKey: clientPrivateKey, peerPublicKey: serverPublicKey) let message: String = "Hello Themis from Swift! Testing your server here ;)" var encryptedMessage: Data = Data() do { encryptedMessage = try encrypter.wrap(message.data(using: String.Encoding.utf8)) let encrypedMessageString = encryptedMessage.base64EncodedString(options: .lineLength64Characters) print("encryptedMessage = \(encrypedMessageString)") } catch let error { print("Error occurred while encrypting \(error)", #function) return } let stringURL: String = "\("https://themis.cossacklabs.com/api/")\(kUserId)/" postRequestTo(stringURL, message: encryptedMessage, completion: {(data: Data?, error: Error?) -> Void in guard let data = data else { print("response error \(error)") return } do { let decryptedMessage: Data = try encrypter.unwrapData(data) let resultString: String = String(data: decryptedMessage, encoding: String.Encoding.utf8)! print("decryptedMessage->\n\(resultString)") } catch let error { print("Error occurred while decrypting \(error)", #function) return } }) } fileprivate func generateClientKeys() { // use client public key to run server // https://themis.cossacklabs.com/interactive-simulator/setup/ // // use client private key to encrypt your message guard let keyGeneratorEC: TSKeyGen = TSKeyGen(algorithm: .EC) else { print("Error occurred while initializing object keyGeneratorEC", #function) return } let privateKeyEC: Data = keyGeneratorEC.privateKey as Data let publicKeyEC: Data = keyGeneratorEC.publicKey as Data let privateKeyECString = privateKeyEC.base64EncodedString(options: .lineLength64Characters) let publicKeyECString = publicKeyEC.base64EncodedString(options: .lineLength64Characters) print("EC client privateKey = \(privateKeyECString)") print("EC client publicKey = \(publicKeyECString)") } fileprivate func checkKeysNotEmpty() { // Read how Themis Server works: // https://github.com/cossacklabs/themis/wiki/Using-Themis-Server assert(!(kUserId == "<user id>"), "Get user id from https://themis.cossacklabs.com/interactive-simulator/setup/") assert(!(kServerPublicKey == "<server public key>"), "Get server key from https://themis.cossacklabs.com/interactive-simulator/setup/") assert(!(kClientPrivateKey == "<generated client private key>"), "Generate client keys by running `generateClientKeys()` or obtain from server https://themis.cossacklabs.com/interactive-simulator/setup/") assert(!(kClientPublicKey == "<generated client public key>"), "Generate client keys by running `generateClientKeys()` or obtain from server https://themis.cossacklabs.com/interactive-simulator/setup/") } }
apache-2.0
22ce1cb5864948cb75767f0a40df8053
43.583893
212
0.617492
4.711348
false
false
false
false
carabina/DDMathParser
MathParser/TokenResolver.swift
2
13957
// // TokenResolver.swift // DDMathParser // // Created by Dave DeLong on 8/8/15. // // import Foundation public struct TokenResolverOptions: OptionSetType { public let rawValue: UInt public init(rawValue: UInt) { self.rawValue = rawValue } public static let None = TokenResolverOptions(rawValue: 0) public static let AllowArgumentlessFunctions = TokenResolverOptions(rawValue: 1 << 0) public static let AllowImplicitMultiplication = TokenResolverOptions(rawValue: 1 << 1) public static let UseHighPrecedenceImplicitMultiplication = TokenResolverOptions(rawValue: 1 << 2) public static let defaultOptions: TokenResolverOptions = [.AllowArgumentlessFunctions, .AllowImplicitMultiplication, .UseHighPrecedenceImplicitMultiplication] } public struct TokenResolver { private let tokenizer: Tokenizer private let options: TokenResolverOptions private let locale: NSLocale? private let numberFormatters: Array<NSNumberFormatter> internal var operatorSet: OperatorSet { return tokenizer.operatorSet } private static func formattersForLocale(locale: NSLocale?) -> Array<NSNumberFormatter> { guard let locale = locale else { return [] } let decimal = NSNumberFormatter() decimal.locale = locale decimal.numberStyle = .DecimalStyle return [decimal] } public init(tokenizer: Tokenizer, options: TokenResolverOptions = TokenResolverOptions.defaultOptions) { self.tokenizer = tokenizer self.options = options self.locale = tokenizer.locale self.numberFormatters = TokenResolver.formattersForLocale(tokenizer.locale) } public init(string: String, operatorSet: OperatorSet = OperatorSet.defaultOperatorSet, options: TokenResolverOptions = TokenResolverOptions.defaultOptions, locale: NSLocale? = nil) { self.tokenizer = Tokenizer(string: string, operatorSet: operatorSet, locale: locale) self.options = options self.locale = locale self.numberFormatters = TokenResolver.formattersForLocale(locale) } public func resolve() throws -> Array<ResolvedToken> { let rawTokens = try tokenizer.tokenize() var resolvedTokens = Array<ResolvedToken>() for rawToken in rawTokens { let resolved = try resolveToken(rawToken, previous: resolvedTokens.last) resolvedTokens.appendContentsOf(resolved) } let finalResolved = try resolveToken(nil, previous: resolvedTokens.last) resolvedTokens.appendContentsOf(finalResolved) return resolvedTokens } } extension TokenResolver { private func resolveToken(raw: RawToken?, previous: ResolvedToken?) throws -> Array<ResolvedToken> { guard let raw = raw else { // this is the case where the we check for argumentless stuff // after the last token if options.contains(.AllowArgumentlessFunctions) { return extraTokensForArgumentlessFunction(nil, previous: previous) } else { return [] } } let resolvedTokens = try resolveRawToken(raw, previous: previous) guard let firstResolved = resolvedTokens.first else { fatalError("Implementation flaw! A token cannot resolve to nothing") } var final = Array<ResolvedToken>() // check for argumentless functions if options.contains(.AllowArgumentlessFunctions) { let extras = extraTokensForArgumentlessFunction(firstResolved, previous: previous) final.appendContentsOf(extras) } // check for implicit multiplication if options.contains(.AllowImplicitMultiplication) { let last = final.last ?? previous let extras = extraTokensForImplicitMultiplication(firstResolved, previous: last) final.appendContentsOf(extras) } final.appendContentsOf(resolvedTokens) return final } private func resolveRawToken(rawToken: RawToken, previous: ResolvedToken?) throws -> Array<ResolvedToken> { var resolvedTokens = Array<ResolvedToken>() switch rawToken.kind { case .HexNumber: if let number = UInt(rawToken.string, radix: 16) { resolvedTokens.append(ResolvedToken(kind: .Number(Double(number)), string: rawToken.string, range: rawToken.range)) } else { throw TokenResolverError(kind: .CannotParseHexNumber, rawToken: rawToken) } case .Number: resolvedTokens.append(resolveNumber(rawToken)) case .LocalizedNumber: resolvedTokens.append(try resolveLocalizedNumber(rawToken)) case .Exponent: resolvedTokens.appendContentsOf(try resolveExponent(rawToken)) case .Variable: resolvedTokens.append(ResolvedToken(kind: .Variable(rawToken.string), string: rawToken.string, range: rawToken.range)) case .Identifier: resolvedTokens.append(ResolvedToken(kind: .Identifier(rawToken.string), string: rawToken.string, range: rawToken.range)) case .Operator: resolvedTokens.append(try resolveOperator(rawToken, previous: previous)) } return resolvedTokens } private func resolveNumber(raw: RawToken) -> ResolvedToken { // first, see if it's a special number if let character = raw.string.characters.first, let value = SpecialNumberExtractor.specialNumbers[character] { return ResolvedToken(kind: .Number(value), string: raw.string, range: raw.range) } let cleaned = raw.string.stringByReplacingOccurrencesOfString("−", withString: "-") let number = NSDecimalNumber(string: cleaned) return ResolvedToken(kind: .Number(number.doubleValue), string: raw.string, range: raw.range) } private func resolveLocalizedNumber(raw: RawToken) throws -> ResolvedToken { for formatter in numberFormatters { if let number = formatter.numberFromString(raw.string) { return ResolvedToken(kind: .Number(number.doubleValue), string: raw.string, range: raw.range) } } throw TokenResolverError(kind: .CannotParseLocalizedNumber, rawToken: raw) } private func resolveExponent(raw: RawToken) throws -> Array<ResolvedToken> { var resolved = Array<ResolvedToken>() let powerOperator = operatorSet.powerOperator let power = ResolvedToken(kind: .Operator(powerOperator), string: "**", range: raw.range.startIndex ..< raw.range.startIndex) let openParen = ResolvedToken(kind: .Operator(Operator(builtInOperator: .ParenthesisOpen)), string: "(", range: raw.range.startIndex ..< raw.range.startIndex) resolved += [power, openParen] let exponentTokenizer = Tokenizer(string: raw.string, operatorSet: operatorSet, locale: locale) let exponentResolver = TokenResolver(tokenizer: exponentTokenizer, options: options) let exponentTokens = try exponentResolver.resolve() var distanceSoFar = 0 for exponentToken in exponentTokens { let tokenStart = raw.range.startIndex.advancedBy(distanceSoFar) let tokenLength = exponentToken.range.startIndex.distanceTo(exponentToken.range.endIndex) let tokenEnd = tokenStart.advancedBy(tokenLength) distanceSoFar += tokenLength resolved.append(ResolvedToken(kind: exponentToken.kind, string: exponentToken.string, range: tokenStart ..< tokenEnd)) } let closeParen = ResolvedToken(kind: .Operator(Operator(builtInOperator: .ParenthesisClose)), string: ")", range: raw.range.endIndex ..< raw.range.endIndex) resolved.append(closeParen) return resolved } private func resolveOperator(raw: RawToken, previous: ResolvedToken?) throws -> ResolvedToken { let matches = operatorSet.operatorForToken(raw.string) if matches.isEmpty { throw TokenResolverError(kind: .UnknownOperator, rawToken: raw) } if matches.count == 1 { let op = matches[0] return ResolvedToken(kind: .Operator(op), string: raw.string, range: raw.range) } // more than one operator has this token var resolvedOperator: Operator? = nil if let previous = previous { switch previous.kind { case .Operator(let o): resolvedOperator = resolveOperator(raw, previousOperator: o) default: // a number/variable can be followed by: // a left-assoc unary operator, // a binary operator, // or a right-assoc unary operator (assuming implicit multiplication) // we'll prefer them from left-to-right: // left-assoc unary, binary, right-assoc unary // TODO: is this correct?? should we be looking at precedence instead? resolvedOperator = operatorSet.operatorForToken(raw.string, arity: .Unary, associativity: .Left).first if resolvedOperator == nil { resolvedOperator = operatorSet.operatorForToken(raw.string, arity: .Binary).first } if resolvedOperator == nil { resolvedOperator = operatorSet.operatorForToken(raw.string, arity: .Unary, associativity: .Right).first } } } else { // no previous token, so this must be a right-assoc unary operator resolvedOperator = operatorSet.operatorForToken(raw.string, arity: .Unary, associativity: .Right).first } if let resolved = resolvedOperator { return ResolvedToken(kind: .Operator(resolved), string: raw.string, range: raw.range) } else { throw TokenResolverError(kind: .AmbiguousOperator, rawToken: raw) } } private func resolveOperator(raw: RawToken, previousOperator o: Operator) -> Operator? { var resolvedOperator: Operator? switch (o.arity, o.associativity) { case (.Unary, .Left): // a left-assoc unary operator can be followed by either: // another left-assoc unary operator // or a binary operator resolvedOperator = operatorSet.operatorForToken(raw.string, arity: .Unary, associativity: .Left).first if resolvedOperator == nil { resolvedOperator = operatorSet.operatorForToken(raw.string, arity: .Binary).first } default: // either a binary operator or a right-assoc unary operator // a binary operator can only be followed by a right-assoc unary operator //a right-assoc operator can only be followed by a right-assoc unary operator resolvedOperator = operatorSet.operatorForToken(raw.string, arity: .Unary, associativity: .Right).first } return resolvedOperator } private func extraTokensForArgumentlessFunction(next: ResolvedToken?, previous: ResolvedToken?) -> Array<ResolvedToken> { guard let previous = previous else { return [] } // we only insert tokens here if the previous token was an identifier guard let _ = previous.kind.identifier else { return [] } let nextOperator = next?.kind.resolvedOperator if nextOperator == nil || nextOperator?.builtInOperator != .ParenthesisOpen { let range = previous.range.endIndex ..< previous.range.endIndex let openParenOp = Operator(builtInOperator: .ParenthesisOpen) let openParen = ResolvedToken(kind: .Operator(openParenOp), string: "(", range: range) let closeParenOp = Operator(builtInOperator: .ParenthesisClose) let closeParen = ResolvedToken(kind: .Operator(closeParenOp), string: ")", range: range) return [openParen, closeParen] } return [] } private func extraTokensForImplicitMultiplication(next: ResolvedToken, previous: ResolvedToken?) -> Array<ResolvedToken> { guard let previousKind = previous?.kind else { return [] } let nextKind = next.kind let previousMatches = previousKind.isNumber || previousKind.isVariable || (previousKind.resolvedOperator?.arity == .Unary && previousKind.resolvedOperator?.associativity == .Left) let nextMatches = nextKind.isOperator == false || (nextKind.resolvedOperator?.arity == .Unary && nextKind.resolvedOperator?.associativity == .Right) guard previousMatches && nextMatches else { return [] } let multiplyOperator: Operator if options.contains(.UseHighPrecedenceImplicitMultiplication) { multiplyOperator = operatorSet.implicitMultiplyOperator } else { multiplyOperator = operatorSet.multiplyOperator } return [ResolvedToken(kind: .Operator(multiplyOperator), string: "*", range: next.range.startIndex ..< next.range.startIndex)] } }
mit
73a90e9d510a4b5906169298d3681474
42.609375
187
0.624006
5.191592
false
false
false
false
fractma/LocateMeSwift
LocateMeSwift/ViewController.swift
1
2940
// // ViewController.swift // LocateMeSwift // // Created by Antonio Gomez on 8/7/16. // Copyright © 2016 Antonio Gomez. All rights reserved. // import UIKit import MapKit import CoreLocation class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate { var locationManager : CLLocationManager! = nil var currentLocation : CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: 0.0, longitude: 0.0) @IBOutlet var mapView : MKMapView? override func viewDidLoad() { super.viewDidLoad() locationManager = CLLocationManager() locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest showUserLocation(self) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } // Showing the user location func showUserLocation(sender : AnyObject) { let status = CLLocationManager.authorizationStatus() //Asking for authorization to display current location if status == CLAuthorizationStatus.NotDetermined { locationManager.requestWhenInUseAuthorization() } else { locationManager.startUpdatingLocation() } } // User authorized to show his current location func locationManager(manager: CLLocationManager, didUpdateToLocation newLocation: CLLocation, fromLocation oldLocation: CLLocation) { // Getting the user coordinates currentLocation = newLocation.coordinate // Setting the zoom region let zoomRegion : MKCoordinateRegion = MKCoordinateRegionMakeWithDistance(currentLocation, 500, 500) // Zoom the map to the current user location mapView!.setRegion(zoomRegion, animated: true) } // User changed the authorization to use location func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) { // Request user authorization locationManager.requestWhenInUseAuthorization() } // Error locating the user func locationManager(manager: CLLocationManager, didFailWithError error: NSError) { // Printing the error to the logs print("Error locating the user: \(error)") } @IBAction func dropPinInCurrentLocation(sender: AnyObject) { // Creating new annotation (pin) let currentAnnotation : MKPointAnnotation = MKPointAnnotation() // Annotation coordinates currentAnnotation.coordinate = currentLocation // Annotation title currentAnnotation.title = "Your Are Here!" // Adding the annotation to the map mapView!.addAnnotation(currentAnnotation) // Displaying the pin title on drop mapView!.selectAnnotation(currentAnnotation, animated: true) } }
mit
67429fc95051c00630ca52220ef4f15b
32.022472
137
0.681524
6.161426
false
false
false
false
ytfhqqu/iCC98
iCC98/iCC98/NewPostTableViewController.swift
1
10686
// // NewPostTableViewController.swift // iCC98 // // Created by Duo Xu on 5/6/17. // Copyright © 2017 Duo Xu. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import UIKit import SVProgressHUD import CC98Kit // http://candycode.io/self-sizing-uitextview-in-a-uitableview-using-auto-layout-like-reminders-app/ class NewPostTableViewController: BaseNewContentTableViewController { // MARK: - Data /** 设置数据。 - parameter newPostType: 新帖子的类型。 */ func setData(newPostType: NewPostType) { self.newPostType = newPostType } /// 新帖子的类型。 enum NewPostType { /// 新主题;关联值 `boardId` 代表要发布的新主题所在的版面的标识。 case newTopic(boardId: Int) /// 新发言;关联值 `topicId` 要追加发言的主题的标识,`authorName` 代表主题作者的用户名称。 case newPost(topicId: Int, authorName: String?) /// 引用回复;关联值 `quotedPostInfo` 代表被引用的发言信息,`isMultipleQuote` 代表是否为多重引用。 case quote(quotedPostInfo: PostInfo, isMultipleQuote: Bool) } private var newPostType: NewPostType? { didSet { if let newPostType = newPostType { switch newPostType { case .newTopic, .newPost: newContent = "" case .quote(quotedPostInfo: let postInfo, isMultipleQuote: let isMultipleQuote): // 引用回复的用户名称 receiverName = postInfo.userName let displayName = receiverName ?? "匿名" // 引用回复的发言时间 let postTimeString: String if let postTime = postInfo.time { let formatter = DateFormatter() formatter.dateFormat = "yyyy/M/d H:mm:ss" formatter.timeZone = TimeZone(secondsFromGMT: 8 * 60 * 60) postTimeString = formatter.string(from: postTime) } else { postTimeString = "" } // 引用回复的发言内容 let postContent: String if isMultipleQuote { // 多重引用 postContent = postInfo.content ?? "" } else { // 单重引用 postContent = BBCodeUtility.removeQuotes(in: postInfo.content ?? "") } // 最后得到的引用代码 let quotedCode = "[quotex][b]以下是引用[i]\(displayName)在\(postTimeString)[/i]的发言:[/b]\n\(postContent)\n[/quotex]\n" // 把引用代码写进新帖子的内容 newContent = quotedCode } } } } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 2 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch indexPath.row { case 0: // 表示帖子标题的单元格 let cell = tableView.dequeueReusableCell(withIdentifier: "New Post Title Cell", for: indexPath) // Configure the cell... if let newPostTitleCell = cell as? NewPostTitleTableViewCell { newPostTitleCell.titleTextField?.text = newTitle newPostTitleCell.titleTextField?.delegate = self } return cell default: // 表示帖子内容的单元格 let cell = tableView.dequeueReusableCell(withIdentifier: "New Post Content Cell", for: indexPath) // Configure the cell... if let newPostContentCell = cell as? NewPostContentTableViewCell { newContentTextView = newPostContentCell.contentTextView newPostContentCell.setData(toolbar: toolbar) newPostContentCell.contentTextView?.text = newContent newPostContentCell.contentTextView?.delegate = self } return cell } } // MARK: - Action // 点击“发送” @IBAction func tapSend(_ sender: UIBarButtonItem) { if let newPostType = newPostType { if OAuthUtility.accessTokenIsValid, let accessToken = OAuthUtility.accessToken { // 构建新帖子的信息 var newPostInfo = NewPostInfo() newPostInfo.title = newTitle var finalContent = newContent ?? "" // 小尾巴 if Settings.showTail, let tailCode = Settings.tailCode { finalContent += "\n" + tailCode } newPostInfo.content = finalContent newPostInfo.contentType = CC98Kit.Constants.PostContentType.ubb.rawValue switch newPostType { case .newTopic(boardId: let boardId): // 标题和内容均不能为空 guard let postTitle = newPostInfo.title, !postTitle.isEmpty else { SVProgressHUD.showEmptyTitleError() return } guard let postContent = newPostInfo.content, !postContent.isEmpty else { SVProgressHUD.showEmptyContentError() return } // 创建一个新的主题 _ = CC98API.postTopic(toBoard: boardId, content: newPostInfo, accessToken: accessToken) { [weak self] result in switch result { case .success: SVProgressHUD.showSentSuccessfully() self?.dismiss(animated: true, completion: nil) case .failure(let status, let message): switch status { case 403: SVProgressHUD.showAccessDeniedError() self?.navigationController?.popViewController(animated: true) self?.dismiss(animated: true, completion: nil) default: SVProgressHUD.showError(statusCode: status, message: message) } case .noResponse: SVProgressHUD.showNoResponseError() } } case .newPost(topicId: let topicId, authorName: _): // 标题不能为 nil,内容不能为空 guard newPostInfo.title != nil else { SVProgressHUD.showEmptyTitleError() return } guard let postContent = newPostInfo.content, !postContent.isEmpty else { SVProgressHUD.showEmptyContentError() return } // 追加新的发言 post(toTopic: topicId, content: newPostInfo, accessToken: accessToken) case .quote(quotedPostInfo: let quotedPostInfo, isMultipleQuote: _): // 标题不能为 nil,内容不能为空 guard newPostInfo.title != nil else { SVProgressHUD.showEmptyTitleError() return } guard let postContent = newPostInfo.content, !postContent.isEmpty else { SVProgressHUD.showEmptyContentError() return } // 追加新的发言 if let topicId = quotedPostInfo.topicId { post(toTopic: topicId, content: newPostInfo, accessToken: accessToken) } } } else { // 令牌无效,需要授权 SVProgressHUD.showRequiresAuthorization() OAuthUtility.authorize(displaySafariOn: self) } } } private func post(toTopic topicId: Int, content: NewPostInfo, accessToken: String) { _ = CC98API.post(toTopic: topicId, content: content, accessToken: accessToken) { [weak self] result in switch result { case .success: SVProgressHUD.showSentSuccessfully() self?.dismiss(animated: true, completion: nil) case .failure(let status, let message): switch status { case 403: SVProgressHUD.showAccessDeniedError() self?.navigationController?.popViewController(animated: true) self?.dismiss(animated: true, completion: nil) default: SVProgressHUD.showError(statusCode: status, message: message) } case .noResponse: SVProgressHUD.showNoResponseError() } } } }
mit
acfba53b6c8e6777edbddec4e2fbfb1c
41.780591
131
0.528652
5.421925
false
false
false
false
SwiftAndroid/swift
test/IDE/print_omit_needless_words.swift
2
15317
// RUN: rm -rf %t // RUN: mkdir -p %t // REQUIRES: objc_interop // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t) -emit-module -o %t -enable-strip-ns-prefix %S/../Inputs/clang-importer-sdk/swift-modules-without-ns/ObjectiveC.swift // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t) -emit-module -o %t -enable-strip-ns-prefix %S/../Inputs/clang-importer-sdk/swift-modules-without-ns/CoreGraphics.swift // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t) -emit-module -o %t -enable-strip-ns-prefix %S/../Inputs/clang-importer-sdk/swift-modules-without-ns/Foundation.swift // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t) -emit-module -o %t -enable-strip-ns-prefix %S/../Inputs/clang-importer-sdk/swift-modules-without-ns/AppKit.swift // RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -print-module -source-filename %s -module-to-print=ObjectiveC -function-definitions=false -prefer-type-repr=true -enable-strip-ns-prefix > %t.ObjectiveC.txt // RUN: FileCheck %s -check-prefix=CHECK-OBJECTIVEC -strict-whitespace < %t.ObjectiveC.txt // RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -print-module -source-filename %s -module-to-print=Foundation -function-definitions=false -prefer-type-repr=true -enable-strip-ns-prefix -skip-parameter-names > %t.Foundation.txt // RUN: FileCheck %s -check-prefix=CHECK-FOUNDATION -strict-whitespace < %t.Foundation.txt // RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -print-module -source-filename %s -module-to-print=AppKit -function-definitions=false -prefer-type-repr=true -enable-strip-ns-prefix -skip-parameter-names > %t.AppKit.txt // RUN: FileCheck %s -check-prefix=CHECK-APPKIT -strict-whitespace < %t.AppKit.txt // RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t -I %S/../ClangModules/Inputs/custom-modules) -print-module -source-filename %s -module-to-print=CoreCooling -function-definitions=false -prefer-type-repr=true -enable-strip-ns-prefix -skip-parameter-names > %t.CoreCooling.txt // RUN: FileCheck %s -check-prefix=CHECK-CORECOOLING -strict-whitespace < %t.CoreCooling.txt // RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t -I %S/Inputs/custom-modules) -print-module -source-filename %s -module-to-print=OmitNeedlessWords -function-definitions=false -prefer-type-repr=true -enable-strip-ns-prefix -skip-parameter-names > %t.OmitNeedlessWords.txt 2> %t.OmitNeedlessWords.diagnostics.txt // RUN: FileCheck %s -check-prefix=CHECK-OMIT-NEEDLESS-WORDS -strict-whitespace < %t.OmitNeedlessWords.txt // RUN: FileCheck %s -check-prefix=CHECK-OMIT-NEEDLESS-WORDS-DIAGS -strict-whitespace < %t.OmitNeedlessWords.diagnostics.txt // RUN: %target-swift-ide-test(mock-sdk: -sdk %S/../Inputs/clang-importer-sdk -I %t) -print-module -source-filename %s -module-to-print=errors -function-definitions=false -prefer-type-repr=true -enable-strip-ns-prefix -skip-parameter-names > %t.errors.txt // RUN: FileCheck %s -check-prefix=CHECK-ERRORS -strict-whitespace < %t.errors.txt // Note: SEL -> "Selector" // CHECK-FOUNDATION: func makeObjectsPerform(_: Selector) // Note: "with" parameters. // CHECK-FOUNDATION: func makeObjectsPerform(_: Selector, with: AnyObject?) // CHECK-FOUNDATION: func makeObjectsPerform(_: Selector, with: AnyObject?, with: AnyObject?) // Note: don't prefix-strip swift_bridged classes or their subclasses. // CHECK-FOUNDATION: func mutableCopy() -> NSMutableArray // Note: id -> "Object". // CHECK-FOUNDATION: func index(of: AnyObject) -> Int // Note: Class -> "Class" // CHECK-OBJECTIVEC: func isKind(of aClass: AnyClass) -> Bool // Note: Pointer-to-struct name matching; preposition splitting. // // CHECK-FOUNDATION: func copy(with: Zone? = nil) -> AnyObject! // Note: Objective-C type parameter names. // CHECK-FOUNDATION: func object(forKey: Copying) -> AnyObject? // CHECK-FOUNDATION: func removeObject(forKey: Copying) // Note: Don't drop the name of the first parameter in an initializer entirely. // CHECK-FOUNDATION: init(array: [AnyObject]) // Note: struct name matching; don't drop "With". // CHECK-FOUNDATION: class func withRange(_: NSRange) -> Value // Note: built-in types. // CHECK-FOUNDATION: func add(_: Double) -> Number // Note: built-in types. // CHECK-FOUNDATION: func add(_: Bool) -> Number // Note: builtin-types. // CHECK-FOUNDATION: func add(_: UInt16) -> Number // Note: builtin-types. // CHECK-FOUNDATION: func add(_: Int32) -> Number // Note: Typedefs with a "_t" suffix". // CHECK-FOUNDATION: func subtract(_: Int32) -> Number // Note: Respect the getter name for BOOL properties. // CHECK-FOUNDATION: var isMakingHoney: Bool // Note: multi-word enum name matching; "with" splits the first piece. // CHECK-FOUNDATION: func someMethod(_: DeprecatedOptions = []) // Note: class name matching; don't drop "With". // CHECK-FOUNDATION: class func withString(_: String!) -> Self! // Note: lowercasing enum constants. // CHECK-FOUNDATION: enum ByteCountFormatterCountStyle : Int { // CHECK-FOUNDATION: case file // CHECK-FOUNDATION-NEXT: case memory // CHECK-FOUNDATION-NEXT: case decimal // CHECK-FOUNDATION-NEXT: case binary // Note: Make sure NSURL works in various places // CHECK-FOUNDATION: open(_: URL!, completionHandler: ((Bool) -> Void)!) // Note: property name stripping property type. // CHECK-FOUNDATION: var uppercased: String // Note: don't map base name down to a keyword. // CHECK-FOUNDATION: func doSelector(_: Selector!) // Note: Strip names preceded by a gerund. // CHECK-FOUNDATION: func startSquashing(_: Bee) // CHECK-FOUNDATION: func startSoothing(_: Bee) // CHECK-FOUNDATION: func startShopping(_: Bee) // Note: Removing plural forms when working with collections // CHECK-FOUNDATION: func add(_: [AnyObject]) // Note: Int and Index match. // CHECK-FOUNDATION: func slice(from: Int, to: Int) -> String // Note: <context type>By<gerund> --> <gerund>. // CHECK-FOUNDATION: func appending(_: String) -> String // Note: <context type>By<gerund> --> <gerund>. // CHECK-FOUNDATION: func withString(_: String) -> String // Note: Noun phrase puts preposition inside. // CHECK-FOUNDATION: func url(withAddedString: String) -> URL? // Note: CalendarUnits is not a set of "Options". // CHECK-FOUNDATION: class func forCalendarUnits(_: CalendarUnit) -> String! // Note: <property type>By<gerund> --> <gerund>. // CHECK-FOUNDATION: var deletingLastPathComponent: URL? { get } // Note: <property type><preposition> --> <preposition>. // CHECK-FOUNDATION: var withHTTPS: URL { get } // Note: lowercasing option set values // CHECK-FOUNDATION: struct EnumerationOptions // CHECK-FOUNDATION: static var concurrent: EnumerationOptions // CHECK-FOUNDATION: static var reverse: EnumerationOptions // Note: usingBlock -> body // CHECK-FOUNDATION: func enumerateObjects(_: ((AnyObject!, Int, UnsafeMutablePointer<ObjCBool>!) -> Void)!) // CHECK-FOUNDATION: func enumerateObjects(_: EnumerationOptions = [], using: ((AnyObject!, Int, UnsafeMutablePointer<ObjCBool>!) -> Void)!) // Note: WithBlock -> body, nullable closures default to nil. // CHECK-FOUNDATION: func enumerateObjectsRandomly(_: ((AnyObject!, Int, UnsafeMutablePointer<ObjCBool>!) -> Void)? = nil) // Note: id<Proto> treated as "Proto". // CHECK-FOUNDATION: func doSomething(with: Copying) // Note: NSObject<Proto> treated as "Proto". // CHECK-FOUNDATION: func doSomethingElse(with: protocol<Copying, ObjectProtocol>) // Note: Function type -> "Function". // CHECK-FOUNDATION: func sort(_: @convention(c) (AnyObject, AnyObject) -> Int) // Note: Plural: NSArray without type arguments -> "Objects". // CHECK-FOUNDATION: func remove(_: [AnyObject]) // Note: Skipping "Type" suffix. // CHECK-FOUNDATION: func doSomething(with: UnderlyingType) // Don't introduce default arguments for lone parameters to setters. // CHECK-FOUNDATION: func setDefaultEnumerationOptions(_: EnumerationOptions) // CHECK-FOUNDATION: func normalizingXMLPreservingComments(_: Bool) // Collection element types. // CHECK-FOUNDATION: func adding(_: AnyObject) -> Set<Object> // Boolean properties follow the getter. // CHECK-FOUNDATION: var empty: Bool { get } // CHECK-FOUNDATION: func nonEmpty() -> Bool // CHECK-FOUNDATION: var isStringSet: Bool { get } // CHECK-FOUNDATION: var wantsAUnion: Bool { get } // CHECK-FOUNDATION: var watchesItsLanguage: Bool { get } // CHECK-FOUNDATION: var appliesForAJob: Bool { get } // CHECK-FOUNDATION: var setShouldBeInfinite: Bool { get } // "UTF8" initialisms. // CHECK-FOUNDATION: init?(utf8String: UnsafePointer<Int8>!) // Don't strip prefixes from globals. // CHECK-FOUNDATION: let NSGlobalConstant: String // CHECK-FOUNDATION: func NSGlobalFunction() // Cannot strip because we end up with something that isn't an identifier // CHECK-FOUNDATION: func NS123() // CHECK-FOUNDATION: func NSYELLING() // CHECK-FOUNDATION: func NS_SCREAMING() // CHECK-FOUNDATION: func NS_() // CHECK-FOUNDATION: let NSHTTPRequestKey: String // Lowercasing initialisms with plurals. // CHECK-FOUNDATION: var urlsInText: [URL] { get } // Don't strip prefixes from macro names. // CHECK-FOUNDATION: var NSTimeIntervalSince1970: Double { get } // CHECK-FOUNDATION: var NS_DO_SOMETHING: Int // Note: class method name stripping context type. // CHECK-APPKIT: class func red() -> NSColor // Note: instance method name stripping context type. // CHECK-APPKIT: func same() -> Self // Note: Unsafe(Mutable)Pointers don't get defaulted to 'nil' // CHECK-APPKIT: func getRGBAComponents(_: UnsafeMutablePointer<Int8>?) // Note: Skipping over "3D" // CHECK-APPKIT: func drawInAir(at: Point3D) // Note: with<something> -> <something> // CHECK-APPKIT: func draw(at: Point3D, withAttributes: [String : AnyObject]? = [:]) // Note: Don't strip names that aren't preceded by a verb or preposition. // CHECK-APPKIT: func setTextColor(_: NSColor?) // Note: Splitting with default arguments. // CHECK-APPKIT: func draw(in: NSView?) // Note: NSDictionary default arguments for "options" // CHECK-APPKIT: func drawAnywhere(in: NSView?, options: [Object : AnyObject] = [:]) // CHECK-APPKIT: func drawAnywhere(options: [Object : AnyObject] = [:]) // Note: no lowercasing of initialisms when there might be a prefix. // CHECK-CORECOOLING: func CFBottom() -> // Note: "Ref" variants are unavailable. // CHECK-CORECOOLING: @available(*, unavailable, renamed: "CCPowerSupply", message: "Not available in Swift") // CHECK-CORECOOLING-NEXT: typealias CCPowerSupplyRef = CCPowerSupply // Note: Skipping over "Ref" // CHECK-CORECOOLING: func replace(_: CCPowerSupply!) // Make sure we're removing redundant context type info at both the // beginning and the end. // CHECK-APPKIT: func reversing() -> NSBezierPath // Make sure we're dealing with 'instancetype' properly. // CHECK-APPKIT: func inventing() -> Self // Make sure we're removing redundant context type info at both the // beginning and the end of a property. // CHECK-APPKIT: var flattening: NSBezierPath { get } // CHECK-APPKIT: func dismiss(animated: Bool) // CHECK-APPKIT: func shouldCollapseAutoExpandedItems(forDeposited: Bool) -> Bool // Introducing argument labels and pruning the base name. // CHECK-APPKIT: func rectForCancelButton(whenCentered: Bool) // CHECK-APPKIT: func openUntitledDocumentAndDisplay(_: Bool) // Don't strip due to weak type information. // CHECK-APPKIT: func setContentHuggingPriority(_: NSLayoutPriority) // Look through typedefs of pointers. // CHECK-APPKIT: func layout(at: NSPointPointer!) // The presence of a property prevents us from stripping redundant // type information from the base name. // CHECK-APPKIT: func addGestureRecognizer(_: NSGestureRecognizer) // CHECK-APPKIT: func removeGestureRecognizer(_: NSGestureRecognizer) // CHECK-APPKIT: func favoriteView(for: NSGestureRecognizer) -> NSView? // CHECK-APPKIT: func addLayoutConstraints(_: Set<NSLayoutConstraint>) // CHECK-APPKIT: func add(_: Rect) // CHECK-APPKIT: class func conjureRect(_: Rect) // CHECK-OMIT-NEEDLESS-WORDS: func jump(to: URL) // CHECK-OMIT-NEEDLESS-WORDS: func objectIs(compatibleWith: AnyObject) -> Bool // CHECK-OMIT-NEEDLESS-WORDS: func insetBy(x: Int, y: Int) // CHECK-OMIT-NEEDLESS-WORDS: func setIndirectlyToValue(_: AnyObject) // CHECK-OMIT-NEEDLESS-WORDS: func jumpToTop(_: AnyObject) // CHECK-OMIT-NEEDLESS-WORDS: func removeWithNoRemorse(_: AnyObject) // CHECK-OMIT-NEEDLESS-WORDS: func bookmark(with: [URL]) // CHECK-OMIT-NEEDLESS-WORDS: func save(to: URL, forSaveOperation: Int) // CHECK-OMIT-NEEDLESS-WORDS: func index(withItemNamed: String) // CHECK-OMIT-NEEDLESS-WORDS: func methodAndReturnError(_: AutoreleasingUnsafeMutablePointer<Error?>!) // CHECK-OMIT-NEEDLESS-WORDS: func type(of: String) // CHECK-OMIT-NEEDLESS-WORDS: func type(ofNamedString: String) // CHECK-OMIT-NEEDLESS-WORDS: func type(ofTypeNamed: String) // Look for preposition prior to "of". // CHECK-OMIT-NEEDLESS-WORDS: func append(withContentsOf: String) // Leave subscripts alone // CHECK-OMIT-NEEDLESS-WORDS: subscript(_: UInt) -> AnyObject { get } // CHECK-OMIT-NEEDLESS-WORDS: func objectAtIndexedSubscript(_: UInt) -> AnyObject // CHECK-OMIT-NEEDLESS-WORDS: func exportPresets(bestMatching: String) // CHECK-OMIT-NEEDLESS-WORDS: func isCompatibleWith(_: String) // CHECK-OMIT-NEEDLESS-WORDS: func add(_: AnyObject) // CHECK-OMIT-NEEDLESS-WORDS: func slobbering(_: String) -> OmitNeedlessWords // Elements of C array types // CHECK-OMIT-NEEDLESS-WORDS: func drawPolygon(with: UnsafePointer<Point>!, count: Int) // Typedef ending in "Array". // CHECK-OMIT-NEEDLESS-WORDS: func drawFilledPolygon(with: PointArray!, count: Int) // Non-parameterized Objective-C class ending in "Array". // CHECK-OMIT-NEEDLESS-WORDS: func draw(_: SEGreebieArray) // Property-name sensitivity in the base name "Self" stripping. // CHECK-OMIT-NEEDLESS-WORDS: func addDoodle(_: ABCDoodle) // Protocols as contexts // CHECK-OMIT-NEEDLESS-WORDS: protocol OMWLanding { // CHECK-OMIT-NEEDLESS-WORDS-NEXT: func flip() // Verify that we get the Swift name from the original declaration. // CHECK-OMIT-NEEDLESS-WORDS: protocol OMWWiggle // CHECK-OMIT-NEEDLESS-WORDS-NEXT: func joinSub() // CHECK-OMIT-NEEDLESS-WORDS-NEXT: func wiggle1() // CHECK-OMIT-NEEDLESS-WORDS-NEXT: var wiggleProp1: Int { get } // CHECK-OMIT-NEEDLESS-WORDS: protocol OMWWaggle // CHECK-OMIT-NEEDLESS-WORDS-NEXT: func waggle1() // CHECK-OMIT-NEEDLESS-WORDS-NEXT: var waggleProp1: Int { get } // CHECK-OMIT-NEEDLESS-WORDS: class OMWSuper // CHECK-OMIT-NEEDLESS-WORDS-NEXT: func jump() // CHECK-OMIT-NEEDLESS-WORDS-NEXT: var wiggleProp1: Int { get } // CHECK-OMIT-NEEDLESS-WORDS: class OMWSub // CHECK-OMIT-NEEDLESS-WORDS-NEXT: func jump() // CHECK-OMIT-NEEDLESS-WORDS-NEXT: func joinSub() // CHECK-OMIT-NEEDLESS-WORDS-DIAGS: inconsistent Swift name for Objective-C method 'conflicting1' in 'OMWSub' ('waggle1()' in 'OMWWaggle' vs. 'wiggle1()' in 'OMWWiggle') // CHECK-OMIT-NEEDLESS-WORDS-DIAGS: inconsistent Swift name for Objective-C property 'conflictingProp1' in 'OMWSub' ('waggleProp1' in 'OMWWaggle' vs. 'wiggleProp1' in 'OMWSuper') // Don't drop the 'error'. // CHECK-ERRORS: func tryAndReturnError(_: ()) throws
apache-2.0
7c6d58405ca182619b4499f13c95e166
44.859281
346
0.734347
3.407564
false
false
false
false
ktmswzw/FeelClient
FeelingClient/ThirdParty/updateSelf/UIImageColors.swift
1
9180
// // UIImageColors.swift // https://github.com/jathu/UIImageColors // // Created by Jathu Satkunarajah (@jathu) on 2015-06-11 - Toronto // Original Cocoa version by Panic Inc. - Portland // import UIKit import Accelerate public struct UIImageColors { public var backgroundColor: UIColor! public var primaryColor: UIColor! public var secondaryColor: UIColor! public var detailColor: UIColor! } class PCCountedColor { let color: UIColor let count: Int init(color: UIColor, count: Int) { self.color = color self.count = count } } extension UIColor { public var isDarkColor: Bool { let RGB = CGColorGetComponents(self.CGColor) return (0.2126 * RGB[0] + 0.7152 * RGB[1] + 0.0722 * RGB[2]) < 0.5 } public var isBlackOrWhite: Bool { let RGB = CGColorGetComponents(self.CGColor) return (RGB[0] > 0.91 && RGB[1] > 0.91 && RGB[2] > 0.91) || (RGB[0] < 0.09 && RGB[1] < 0.09 && RGB[2] < 0.09) } public func isDistinct(compareColor: UIColor) -> Bool { let bg = CGColorGetComponents(self.CGColor) let fg = CGColorGetComponents(compareColor.CGColor) let threshold: CGFloat = 0.25 if fabs(bg[0] - fg[0]) > threshold || fabs(bg[1] - fg[1]) > threshold || fabs(bg[2] - fg[2]) > threshold { if fabs(bg[0] - bg[1]) < 0.03 && fabs(bg[0] - bg[2]) < 0.03 { if fabs(fg[0] - fg[1]) < 0.03 && fabs(fg[0] - fg[2]) < 0.03 { return false } } return true } return false } public func colorWithMinimumSaturation(minSaturation: CGFloat) -> UIColor { var hue: CGFloat = 0.0 var saturation: CGFloat = 0.0 var brightness: CGFloat = 0.0 var alpha: CGFloat = 0.0 self.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) if saturation < minSaturation { return UIColor(hue: hue, saturation: minSaturation, brightness: brightness, alpha: alpha) } else { return self } } public func isContrastingColor(compareColor: UIColor) -> Bool { let bg = CGColorGetComponents(self.CGColor) let fg = CGColorGetComponents(compareColor.CGColor) let bgLum = 0.2126 * bg[0] + 0.7152 * bg[1] + 0.0722 * bg[2] let fgLum = 0.2126 * fg[0] + 0.7152 * fg[1] + 0.0722 * fg[2] let contrast = (bgLum > fgLum) ? (bgLum + 0.05)/(fgLum + 0.05):(fgLum + 0.05)/(bgLum + 0.05) return 1.6 < contrast } } extension UIImage { public func resize(newSize: CGSize) -> UIImage { UIGraphicsBeginImageContextWithOptions(newSize, false, 0) self.drawInRect(CGRectMake(0, 0, newSize.width, newSize.height)) let result = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return result } public func getColors() -> UIImageColors { let ratio = self.size.width/self.size.height let r_width: CGFloat = 250 return self.getColors(CGSizeMake(r_width, r_width/ratio)) } public func getColors(scaleDownSize: CGSize) -> UIImageColors { var result = UIImageColors() let cgImage = self.resize(scaleDownSize).CGImage let width = CGImageGetWidth(cgImage) let height = CGImageGetHeight(cgImage) let bytesPerPixel: Int = 4 let bytesPerRow: Int = width * bytesPerPixel let bitsPerComponent: Int = 8 let randomColorsThreshold = Int(CGFloat(height)*0.01) let sortedColorComparator: NSComparator = { (main, other) -> NSComparisonResult in let m = main as! PCCountedColor, o = other as! PCCountedColor if m.count < o.count { return NSComparisonResult.OrderedDescending } else if m.count == o.count { return NSComparisonResult.OrderedSame } else { return NSComparisonResult.OrderedAscending } } let blackColor = UIColor(red: 0, green: 0, blue: 0, alpha: 1) let whiteColor = UIColor(red: 1, green: 1, blue: 1, alpha: 1) let colorSpace = CGColorSpaceCreateDeviceRGB() let raw = malloc(bytesPerRow * height) let bitmapInfo = CGImageAlphaInfo.PremultipliedFirst.rawValue let ctx = CGBitmapContextCreate(raw, width, height, bitsPerComponent, bytesPerRow, colorSpace, bitmapInfo) CGContextDrawImage(ctx, CGRectMake(0, 0, CGFloat(width), CGFloat(height)), cgImage) let data = UnsafePointer<UInt8>(CGBitmapContextGetData(ctx)) let leftEdgeColors = NSCountedSet(capacity: height) let imageColors = NSCountedSet(capacity: width * height) for x in 0 ..< width { for y in 0 ..< height { let pixel = ((width * y) + x) * bytesPerPixel let color = UIColor( red: CGFloat(data[pixel+1])/255, green: CGFloat(data[pixel+2])/255, blue: CGFloat(data[pixel+3])/255, alpha: 1 ) // A lot of albums have white or black edges from crops, so ignore the first few pixels if 5 <= x && x <= 10 { leftEdgeColors.addObject(color) } imageColors.addObject(color) } } // Get background color var enumerator = leftEdgeColors.objectEnumerator() var sortedColors = NSMutableArray(capacity: leftEdgeColors.count) while let kolor = enumerator.nextObject() as? UIColor { let colorCount = leftEdgeColors.countForObject(kolor) if randomColorsThreshold < colorCount { sortedColors.addObject(PCCountedColor(color: kolor, count: colorCount)) } } sortedColors.sortUsingComparator(sortedColorComparator) var proposedEdgeColor: PCCountedColor if 0 < sortedColors.count { proposedEdgeColor = sortedColors.objectAtIndex(0) as! PCCountedColor } else { proposedEdgeColor = PCCountedColor(color: blackColor, count: 1) } if proposedEdgeColor.color.isBlackOrWhite && 0 < sortedColors.count { for i in 1 ..< sortedColors.count { let nextProposedEdgeColor = sortedColors.objectAtIndex(i) as! PCCountedColor if (CGFloat(nextProposedEdgeColor.count)/CGFloat(proposedEdgeColor.count)) > 0.3 { if !nextProposedEdgeColor.color.isBlackOrWhite { proposedEdgeColor = nextProposedEdgeColor break } } else { break } } } result.backgroundColor = proposedEdgeColor.color // Get foreground colors enumerator = imageColors.objectEnumerator() sortedColors.removeAllObjects() sortedColors = NSMutableArray(capacity: imageColors.count) let findDarkTextColor = !result.backgroundColor.isDarkColor while var kolor = enumerator.nextObject() as? UIColor { kolor = kolor.colorWithMinimumSaturation(0.15) if kolor.isDarkColor == findDarkTextColor { let colorCount = imageColors.countForObject(kolor) sortedColors.addObject(PCCountedColor(color: kolor, count: colorCount)) } } sortedColors.sortUsingComparator(sortedColorComparator) for curContainer in sortedColors { let kolor = (curContainer as! PCCountedColor).color if result.primaryColor == nil { if kolor.isContrastingColor(result.backgroundColor) { result.primaryColor = kolor } } else if result.secondaryColor == nil { if !result.primaryColor.isDistinct(kolor) || !kolor.isContrastingColor(result.backgroundColor) { continue } result.secondaryColor = kolor } else if result.detailColor == nil { if !result.secondaryColor.isDistinct(kolor) || !result.primaryColor.isDistinct(kolor) || !kolor.isContrastingColor(result.backgroundColor) { continue } result.detailColor = kolor break } } let isDarkBackgound = result.backgroundColor.isDarkColor if result.primaryColor == nil { result.primaryColor = isDarkBackgound ? whiteColor:blackColor } if result.secondaryColor == nil { result.secondaryColor = isDarkBackgound ? whiteColor:blackColor } if result.detailColor == nil { result.detailColor = isDarkBackgound ? whiteColor:blackColor } return result } }
mit
93cef3542aa212afea4349a04a13775e
37.095436
156
0.576362
4.956803
false
false
false
false
ppei/ioscreator
IOS9ContextMenuTableViewTutorial/IOS9ContextMenuTableViewTutorial/ViewController.swift
26
2037
// // ViewController.swift // IOS9ContextMenuTableViewTutorial // // Created by Arthur Knopper on 28/07/15. // Copyright © 2015 Arthur Knopper. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate { @IBOutlet var tableView: UITableView! var pasteBoard = UIPasteboard.generalPasteboard() var tableData: [String] = ["dog","cat","fish"] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tableData.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) cell.textLabel?.text = tableData[indexPath.row] return cell } func tableView(tableView: UITableView, shouldShowMenuForRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } func tableView(tableView: UITableView, canPerformAction action: Selector, forRowAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) -> Bool { if (action == Selector("copy:")) { return true } return false } func tableView(tableView: UITableView, performAction action: Selector, forRowAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) { let cell = tableView.cellForRowAtIndexPath(indexPath) pasteBoard.string = cell!.textLabel?.text } func textFieldShouldReturn(textField: UITextField) -> Bool { self.view.endEditing(true) return false } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
d747f7f144e0845462d12b7fca49a98f
29.848485
160
0.675835
5.655556
false
false
false
false
CSSE497/pathfinder-ios
examples/Chimney Swap/Chimney Swap/CustomerLoginViewController.swift
1
1189
// // CustomerLoginViewController.swift // Chimney Swap // // Created by Adam Michael on 11/8/15. // Copyright © 2015 Pathfinder. All rights reserved. // import Foundation class CustomerLoginViewController : UIViewController { @IBAction func signInCustomer() { let interfaceManager = GITInterfaceManager() interfaceManager.delegate = self GITClient.sharedInstance().delegate = self interfaceManager.startSignIn() } } extension CustomerLoginViewController : GITInterfaceManagerDelegate, GITClientDelegate { func client(client: GITClient!, didFinishSignInWithToken token: String!, account: GITAccount!, error: NSError!) { print("GIT finished sign in and returned token \(token) for account \(account) with error \(error)") let userDefaults = NSUserDefaults.standardUserDefaults() userDefaults.setObject(token, forKey: "customerToken") userDefaults.synchronize() performSegueWithIdentifier("signInCustomer", sender: token) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { let destination = (segue.destinationViewController) as! CustomerViewController destination.idToken = sender as! String } }
mit
b8a057a651a39ed43b973c98de1e3d79
32.971429
115
0.760101
4.888889
false
false
false
false
ming1016/SMCheckProject
SMCheckProject/ParsingMacro.swift
1
567
// // ParsingMacro.swift // SMCheckProject // // Created by daiming on 2017/2/22. // Copyright © 2017年 Starming. All rights reserved. // import Cocoa class ParsingMacro: NSObject { class func parsing(line:String) -> Macro { var macro = Macro() let aLine = line.replacingOccurrences(of: Sb.defineStr, with: "") let tokens = ParsingBase.createOCTokens(conent: aLine) guard let name = tokens.first else { return macro } macro.name = name macro.tokens = tokens return macro } }
mit
c1900d00baef1f7dc51b455498a99380
23.521739
73
0.617021
3.785235
false
false
false
false
zhou9734/Warm
Warm/Classes/Home/View/SubjectHeadView.swift
1
2322
// // SubjectHeadView.swift // Warm // // Created by zhoucj on 16/9/23. // Copyright © 2016年 zhoucj. All rights reserved. // import UIKit class SubjectHeadView: UIView { var urlString: String?{ didSet{ guard let url = urlString else{ return } contentWebView.loadRequest(NSURLRequest(URL: NSURL(string: url)!)) layoutIfNeeded() } } var titleStrng: String?{ didSet{ titleLbl.text = titleStrng } } override init(frame: CGRect) { super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupUI(){ addSubview(titleLbl) addSubview(spliteView) addSubview(contentWebView) titleLbl.snp_makeConstraints { (make) -> Void in make.top.equalTo(self.snp_top).offset(15) make.left.equalTo(self.snp_left).offset(10) make.right.equalTo(self.snp_right).offset(-10) } spliteView.snp_makeConstraints { (make) -> Void in make.top.equalTo(titleLbl.snp_bottom).offset(10) make.left.equalTo(self.snp_left).offset(10) make.height.equalTo(1) make.width.equalTo(70) } contentWebView.snp_makeConstraints { (make) -> Void in make.top.equalTo(spliteView.snp_top).offset(25) make.left.equalTo(self.snp_left) make.right.equalTo(self.snp_right) make.bottom.equalTo(self.snp_bottom) } } private lazy var titleLbl: UILabel = { let lbl = UILabel() lbl.textColor = UIColor.blackColor() lbl.numberOfLines = 0 lbl.font = UIFont.boldSystemFontOfSize(20) return lbl }() private lazy var spliteView: UIView = { let v = UIView() // v.backgroundColor = SpliteColor v.backgroundColor = UIColor.grayColor() return v }() private lazy var contentWebView: UIWebView = { let wv = UIWebView() wv.scrollView.bounces = false wv.scrollView.scrollEnabled = false return wv }() deinit{ contentWebView.delegate = nil contentWebView.stopLoading() } }
mit
fb35236723cceb452437462547306167
27.280488
78
0.580423
4.278598
false
false
false
false
willlarche/material-components-ios
components/TextFields/examples/TextFieldOutlinedExample.swift
1
15803
/* Copyright 2016-present the Material Components for iOS authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // swiftlint:disable function_body_length import MaterialComponents.MaterialTextFields final class TextFieldOutlinedSwiftExample: UIViewController { let scrollView = UIScrollView() let name: MDCTextField = { let name = MDCTextField() name.translatesAutoresizingMaskIntoConstraints = false name.autocapitalizationType = .words name.backgroundColor = .white return name }() let address: MDCTextField = { let address = MDCTextField() address.translatesAutoresizingMaskIntoConstraints = false address.autocapitalizationType = .words address.backgroundColor = .white return address }() let city: MDCTextField = { let city = MDCTextField() city.translatesAutoresizingMaskIntoConstraints = false city.autocapitalizationType = .words city.backgroundColor = .white return city }() let cityController: MDCTextInputControllerOutlined let state: MDCTextField = { let state = MDCTextField() state.translatesAutoresizingMaskIntoConstraints = false state.autocapitalizationType = .allCharacters state.backgroundColor = .white return state }() let stateController: MDCTextInputControllerOutlined let zip: MDCTextField = { let zip = MDCTextField() zip.translatesAutoresizingMaskIntoConstraints = false zip.backgroundColor = .white return zip }() let zipController: MDCTextInputControllerOutlined let phone: MDCTextField = { let phone = MDCTextField() phone.translatesAutoresizingMaskIntoConstraints = false phone.backgroundColor = .white return phone }() let message: MDCMultilineTextField = { let message = MDCMultilineTextField() message.translatesAutoresizingMaskIntoConstraints = false message.backgroundColor = .white return message }() var allTextFieldControllers = [MDCTextInputControllerFloatingPlaceholder]() override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { cityController = MDCTextInputControllerOutlined(textInput: city) stateController = MDCTextInputControllerOutlined(textInput: state) zipController = MDCTextInputControllerOutlined(textInput: zip) super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white title = "Outlined Text Fields" setupScrollView() setupTextFields() registerKeyboardNotifications() addGestureRecognizer() } func setupTextFields() { scrollView.addSubview(name) let nameController = MDCTextInputControllerOutlined(textInput: name) name.delegate = self name.text = "Grace Hopper" nameController.placeholderText = "Name" nameController.helperText = "First and Last" allTextFieldControllers.append(nameController) scrollView.addSubview(address) let addressController = MDCTextInputControllerOutlined(textInput: address) address.delegate = self addressController.placeholderText = "Address" allTextFieldControllers.append(addressController) scrollView.addSubview(city) city.delegate = self cityController.placeholderText = "City" allTextFieldControllers.append(cityController) // In iOS 9+, you could accomplish this with a UILayoutGuide. // TODO: (larche) add iOS version specific implementations let stateZip = UIView() stateZip.translatesAutoresizingMaskIntoConstraints = false scrollView.addSubview(stateZip) stateZip.addSubview(state) state.delegate = self stateController.placeholderText = "State" allTextFieldControllers.append(stateController) stateZip.addSubview(zip) zip.delegate = self zipController.placeholderText = "Zip Code" zipController.helperText = "XXXXX" allTextFieldControllers.append(zipController) scrollView.addSubview(phone) let phoneController = MDCTextInputControllerOutlined(textInput: phone) phone.delegate = self phoneController.placeholderText = "Phone Number" allTextFieldControllers.append(phoneController) scrollView.addSubview(message) let messageController = MDCTextInputControllerOutlinedTextArea(textInput: message) message.textView?.delegate = self #if swift(>=3.2) message.text = """ This is where you could put a multi-line message like an email. It can even handle new lines. """ #else message.text = "This is where you could put a multi-line message like an email. It can even handle new lines./n" #endif messageController.placeholderText = "Message" allTextFieldControllers.append(messageController) messageController.characterCountMax = 150 var tag = 0 for controller in allTextFieldControllers { guard let textField = controller.textInput as? MDCTextField else { continue } textField.tag = tag tag += 1 } let views = [ "name": name, "address": address, "city": city, "stateZip": stateZip, "phone": phone, "message": message ] var constraints = NSLayoutConstraint.constraints(withVisualFormat: "V:[name]-[address]-[city]-[stateZip]-[phone]-[message]", options: [.alignAllLeading, .alignAllTrailing], metrics: nil, views: views) constraints += [NSLayoutConstraint(item: name, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leadingMargin, multiplier: 1, constant: 0)] constraints += [NSLayoutConstraint(item: name, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailingMargin, multiplier: 1, constant: 0)] constraints += NSLayoutConstraint.constraints(withVisualFormat: "H:[name]|", options: [], metrics: nil, views: views) #if swift(>=3.2) if #available(iOS 11.0, *) { constraints += [NSLayoutConstraint(item: name, attribute: .top, relatedBy: .equal, toItem: scrollView.contentLayoutGuide, attribute: .top, multiplier: 1, constant: 20), NSLayoutConstraint(item: message, attribute: .bottom, relatedBy: .equal, toItem: scrollView.contentLayoutGuide, attribute: .bottomMargin, multiplier: 1, constant: -20)] } else { constraints += [NSLayoutConstraint(item: name, attribute: .top, relatedBy: .equal, toItem: scrollView, attribute: .top, multiplier: 1, constant: 20), NSLayoutConstraint(item: message, attribute: .bottom, relatedBy: .equal, toItem: scrollView, attribute: .bottomMargin, multiplier: 1, constant: -20)] } #else constraints += [NSLayoutConstraint(item: name, attribute: .top, relatedBy: .equal, toItem: scrollView, attribute: .top, multiplier: 1, constant: 20), NSLayoutConstraint(item: message, attribute: .bottom, relatedBy: .equal, toItem: scrollView, attribute: .bottomMargin, multiplier: 1, constant: -20)] #endif let stateZipViews = [ "state": state, "zip": zip ] constraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|[state(80)]-[zip]|", options: [.alignAllTop], metrics: nil, views: stateZipViews) constraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|[state]|", options: [], metrics: nil, views: stateZipViews) constraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|[zip]|", options: [], metrics: nil, views: stateZipViews) NSLayoutConstraint.activate(constraints) } func setupScrollView() { view.addSubview(scrollView) scrollView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate(NSLayoutConstraint.constraints( withVisualFormat: "V:|[scrollView]|", options: [], metrics: nil, views: ["scrollView": scrollView])) NSLayoutConstraint.activate(NSLayoutConstraint.constraints(withVisualFormat: "H:|[scrollView]|", options: [], metrics: nil, views: ["scrollView": scrollView])) let marginOffset: CGFloat = 16 let margins = UIEdgeInsets(top: 0, left: marginOffset, bottom: 0, right: marginOffset) scrollView.layoutMargins = margins } func addGestureRecognizer() { let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapDidTouch(sender: ))) self.scrollView.addGestureRecognizer(tapRecognizer) } // MARK: - Actions @objc func tapDidTouch(sender: Any) { self.view.endEditing(true) } } extension TextFieldOutlinedSwiftExample: UITextFieldDelegate { func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { guard let rawText = textField.text else { return true } let fullString = NSString(string: rawText).replacingCharacters(in: range, with: string) if textField == state { if let range = fullString.rangeOfCharacter(from: CharacterSet.letters.inverted), fullString[range].characters.count > 0 { stateController.setErrorText("Error: State can only contain letters", errorAccessibilityValue: nil) } else { stateController.setErrorText(nil, errorAccessibilityValue: nil) } } else if textField == zip { if let range = fullString.rangeOfCharacter(from: CharacterSet.letters), fullString[range].characters.count > 0 { zipController.setErrorText("Error: Zip can only contain numbers", errorAccessibilityValue: nil) } else if fullString.characters.count > 5 { zipController.setErrorText("Error: Zip can only contain five digits", errorAccessibilityValue: nil) } else { zipController.setErrorText(nil, errorAccessibilityValue: nil) } } else if textField == city { if let range = fullString.rangeOfCharacter(from: CharacterSet.decimalDigits), fullString[range].characters.count > 0 { cityController.setErrorText("Error: City can only contain letters", errorAccessibilityValue: nil) } else { cityController.setErrorText(nil, errorAccessibilityValue: nil) } } return true } func textFieldShouldReturn(_ textField: UITextField) -> Bool { let index = textField.tag if index + 1 < allTextFieldControllers.count, let nextField = allTextFieldControllers[index + 1].textInput { nextField.becomeFirstResponder() } else { textField.resignFirstResponder() } return false } } extension TextFieldOutlinedSwiftExample: UITextViewDelegate { func textViewDidEndEditing(_ textView: UITextView) { print(textView.text) } } // MARK: - Keyboard Handling extension TextFieldOutlinedSwiftExample { func registerKeyboardNotifications() { let notificationCenter = NotificationCenter.default notificationCenter.addObserver( self, selector: #selector(keyboardWillShow(notif:)), name: .UIKeyboardWillChangeFrame, object: nil) notificationCenter.addObserver( self, selector: #selector(keyboardWillShow(notif:)), name: .UIKeyboardWillShow, object: nil) notificationCenter.addObserver( self, selector: #selector(keyboardWillHide(notif:)), name: .UIKeyboardWillHide, object: nil) } @objc func keyboardWillShow(notif: Notification) { guard let frame = notif.userInfo?[UIKeyboardFrameEndUserInfoKey] as? CGRect else { return } scrollView.contentInset = UIEdgeInsets(top: 0.0, left: 0.0, bottom: frame.height, right: 0.0) } @objc func keyboardWillHide(notif: Notification) { scrollView.contentInset = UIEdgeInsets() } } // MARK: - Status Bar Style extension TextFieldOutlinedSwiftExample { override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } } extension TextFieldOutlinedSwiftExample { @objc class func catalogBreadcrumbs() -> [String] { return ["Text Field", "Outlined Fields & Text Areas"] } }
apache-2.0
e8a2ff89317b066ac226a1e0d4a36738
37.356796
118
0.568943
6.197255
false
false
false
false
OscarSwanros/swift
test/Sema/enum_raw_representable.swift
2
4970
// RUN: %target-typecheck-verify-swift enum Foo : Int { case a, b, c } var raw1: Int = Foo.a.rawValue var raw2: Foo.RawValue = raw1 var cooked1: Foo? = Foo(rawValue: 0) var cooked2: Foo? = Foo(rawValue: 22) enum Bar : Double { case a, b, c } func localEnum() -> Int { enum LocalEnum : Int { case a, b, c } return LocalEnum.a.rawValue } enum MembersReferenceRawType : Int { case a, b, c init?(rawValue: Int) { self = MembersReferenceRawType(rawValue: rawValue)! } func successor() -> MembersReferenceRawType { return MembersReferenceRawType(rawValue: rawValue + 1)! } } func serialize<T : RawRepresentable>(_ values: [T]) -> [T.RawValue] { return values.map { $0.rawValue } } func deserialize<T : RawRepresentable>(_ serialized: [T.RawValue]) -> [T] { return serialized.map { T(rawValue: $0)! } } var ints: [Int] = serialize([Foo.a, .b, .c]) var doubles: [Double] = serialize([Bar.a, .b, .c]) var foos: [Foo] = deserialize([1, 2, 3]) var bars: [Bar] = deserialize([1.2, 3.4, 5.6]) // Infer RawValue from witnesses. enum Color : Int { case red case blue init?(rawValue: Double) { return nil } var rawValue: Double { return 1.0 } } var colorRaw: Color.RawValue = 7.5 // Mismatched case types enum BadPlain : UInt { // expected-error {{'BadPlain' declares raw type 'UInt', but does not conform to RawRepresentable and conformance could not be synthesized}} case a = "hello" // expected-error {{cannot convert value of type 'String' to raw type 'UInt'}} } // Recursive diagnostics issue in tryRawRepresentableFixIts() class Outer { // The setup is that we have to trigger the conformance check // while diagnosing the conversion here. For the purposes of // the test I'm putting everything inside a class in the right // order, but the problem can trigger with a multi-file // scenario too. let a: Int = E.a // expected-error {{cannot convert value of type 'Outer.E' to specified type 'Int'}} enum E : Array<Int> { // expected-error {{raw type 'Array<Int>' is not expressible by any literal}} // expected-error@-1 {{'Outer.E' declares raw type 'Array<Int>', but does not conform to RawRepresentable and conformance could not be synthesized}} // expected-error@-2 {{RawRepresentable conformance cannot be synthesized because raw type 'Array<Int>' is not Equatable}} case a } } // rdar://problem/32431736 - Conversion fix-it from String to String raw value enum can't look through optionals func rdar32431736() { enum E : String { case A = "A" case B = "B" } let items1: [String] = ["A", "a"] let items2: [String]? = ["A"] let myE1: E = items1.first // expected-error@-1 {{cannot convert value of type 'String?' to specified type 'E'}} // expected-note@-2 {{construct 'E' from unwrapped 'String' value}} {{17-17=E(rawValue: }} {{29-29=!)}} let myE2: E = items2?.first // expected-error@-1 {{cannot convert value of type 'String?' to specified type 'E'}} // expected-note@-2 {{construct 'E' from unwrapped 'String' value}} {{17-17=E(rawValue: (}} {{30-30=)!)}} } // rdar://problem/32431165 - improve diagnostic for raw representable argument mismatch enum E_32431165 : String { case foo = "foo" case bar = "bar" // expected-note {{did you mean 'bar'?}} } func rdar32431165_1(_: E_32431165) {} func rdar32431165_1(_: Int) {} func rdar32431165_1(_: Int, _: E_32431165) {} rdar32431165_1(E_32431165.baz) // expected-error@-1 {{type 'E_32431165' has no member 'baz'}} rdar32431165_1(.baz) // expected-error@-1 {{reference to member 'baz' cannot be resolved without a contextual type}} rdar32431165_1("") // expected-error@-1 {{cannot convert value of type 'String' to expected argument type 'E_32431165'}} {{15-15=E_32431165(rawValue: }} {{19-19=)}} rdar32431165_1(42, "") // expected-error@-1 {{cannot convert value of type 'String' to expected argument type 'E_32431165'}} {{20-20=E_32431165(rawValue: }} {{22-22=)}} func rdar32431165_2(_: String) {} func rdar32431165_2(_: Int) {} func rdar32431165_2(_: Int, _: String) {} rdar32431165_2(E_32431165.bar) // expected-error@-1 {{cannot convert value of type 'E_32431165' to expected argument type 'String'}} {{15-15=}} {{31-31=.rawValue}} rdar32431165_2(42, E_32431165.bar) // expected-error@-1 {{cannot convert value of type 'E_32431165' to expected argument type 'String'}} {{20-20=}} {{34-34=.rawValue}} E_32431165.bar == "bar" // expected-error@-1 {{cannot convert value of type 'E_32431165' to expected argument type 'String}} {{1-1=}} {{15-15=.rawValue}} "bar" == E_32431165.bar // expected-error@-1 {{cannot convert value of type 'E_32431165' to expected argument type 'String}} {{10-10=}} {{24-24=.rawValue}} func rdar32432253(_ condition: Bool = false) { let choice: E_32431165 = condition ? .foo : .bar let _ = choice == "bar" // expected-error@-1 {{cannot convert value of type 'E_32431165' to expected argument type 'String'}} {{11-11=}} {{17-17=.rawValue}} }
apache-2.0
b6116fee630f12c1b119c23754f3d399
32.581081
163
0.670825
3.444213
false
false
false
false
skarppi/cavok
CAVOK/Map/Location/LocationManager.swift
1
2110
// // LocationManager.swift // CAVOK // // Created by Juho Kolehmainen on 06.09.16. // Copyright © 2016 Juho Kolehmainen. All rights reserved. // import Foundation import CoreLocation class LocationManager: NSObject, ObservableObject { static let shared = LocationManager() let manager = CLLocationManager() @Published var lastLocation: MaplyCoordinate? override private init() { super.init() manager.delegate = self manager.desiredAccuracy = kCLLocationAccuracyHundredMeters } func requestLocation() { if CLLocationManager.locationServicesEnabled() { manager.requestWhenInUseAuthorization() manager.requestLocation() print("Location requested") } else { print("Location not enabled") lastLocation = nil } } } extension LocationManager: CLLocationManagerDelegate { func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) { switch manager.authorizationStatus { case .restricted: print("Restricted Access to location") case .denied: print("User denied access to location") lastLocation = nil case .notDetermined: print("Status not determined") default: print("Looking for location with status \(manager.authorizationStatus)") manager.requestLocation() } } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { if let location = locations.last { lastLocation = MaplyCoordinateMakeWithDegrees( Float(location.coordinate.longitude), Float(location.coordinate.latitude)) print("Got location with accuracy \(location.horizontalAccuracy) to \(location.coordinate)") LastLocation.save(location: lastLocation!) } } func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { print("Failed to get location", error) lastLocation = nil } }
mit
55fa6e8fda141fcfe6ca9865b9df350e
28.291667
104
0.649597
5.639037
false
false
false
false
TruckMuncher/TruckMuncher-iOS
TruckMuncher/LoginViewController.swift
1
5332
// // LoginViewController.swift // TruckMuncher // // Created by Josh Ault on 9/18/14. // Copyright (c) 2014 TruckMuncher. All rights reserved. // import UIKit import Alamofire import TwitterKit class LoginViewController: UIViewController, FBSDKLoginButtonDelegate { @IBOutlet var fbLoginView: FBSDKLoginButton! @IBOutlet weak var btnTwitterLogin: TWTRLogInButton! var twitterKey: String = "" var twitterSecretKey: String = "" var twitterName: String = "" var twitterCallback: String = "" let authManager = AuthManager() let truckManager = TrucksManager() override func viewDidLoad() { super.viewDidLoad() btnTwitterLogin.logInCompletion = { (session: TWTRSession!, error: NSError!) in if error == nil { #if DEBUG self.loginToAPI("oauth_token=tw985c9758-e11b-4d02-9b39-98aa8d00d429, oauth_secret=munch") #elseif RELEASE self.loginToAPI("oauth_token=\(session.authToken), oauth_secret=\(session.authTokenSecret)") #endif } else { let alert = UIAlertController(title: "Oops!", message: "We couldn't log you in right now, please try again", preferredStyle: .Alert) alert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) MBProgressHUD.hideHUDForView(self.view, animated: true) } } navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Cancel", style: .Plain, target: self, action: "cancelTapped") fbLoginView.delegate = self fbLoginView.readPermissions = ["public_profile", "email", "user_friends"] } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func loginTapped(sender: AnyObject) { MBProgressHUD.showHUDAddedTo(view, animated: true) } func cancelTapped() { dismissViewControllerAnimated(true, completion: nil) } func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!) { if error == nil && !result.isCancelled { #if DEBUG loginToAPI("access_token=fb985c9758-e11b-4d02-9b39|FBUser") #elseif RELEASE loginToAPI("access_token=\(FBSDKAccessToken.currentAccessToken().tokenString)") #endif } else { let alert = UIAlertController(title: "Oops!", message: "We couldn't log you in right now, please try again", preferredStyle: .Alert) alert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: nil)) presentViewController(alert, animated: true, completion: nil) MBProgressHUD.hideHUDForView(view, animated: true) } } func loginButtonDidLogOut(loginButton: FBSDKLoginButton!) { println("User logged out from Facebook") MBProgressHUD.hideHUDForView(view, animated: true) } func successfullyLoggedInAsTruck() { MBProgressHUD.hideHUDForView(view, animated: true) navigationController?.dismissViewControllerAnimated(true, completion: { () -> Void in NSNotificationCenter.defaultCenter().postNotificationName("loggedInNotification", object: self, userInfo: nil) }) } func attemptSessionTokenRefresh(error: (Error?) -> ()) { truckManager.getTrucksForVendor(success: { (response) -> () in self.successfullyLoggedInAsTruck() }, error: error) } func loginToAPI(authorizationHeader: String) { authManager.signIn(authorization: authorizationHeader, success: { (response) -> () in NSUserDefaults.standardUserDefaults().setValue(response.sessionToken, forKey: "sessionToken") NSUserDefaults.standardUserDefaults().synchronize() self.attemptSessionTokenRefresh({ (error) -> () in MBProgressHUD.hideHUDForView(self.view, animated: true) let alert = UIAlertController(title: "Oops!", message: "We couldn't log you in right now, please try again", preferredStyle: .Alert) alert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) println("error \(error)") println("error message \(error?.userMessage)") }) }) { (error) -> () in println("error \(error)") println("error message \(error?.userMessage)") let alert = UIAlertController(title: "Oops!", message: "We couldn't log you in right now, please try again", preferredStyle: .Alert) alert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) NSUserDefaults.standardUserDefaults().removeObjectForKey("sessionToken") NSUserDefaults.standardUserDefaults().synchronize() MBProgressHUD.hideHUDForView(self.view, animated: true) } } }
gpl-2.0
f99062578f9d7ebd2aea80587fb722fb
43.806723
148
0.64066
5.049242
false
false
false
false
jtoronto/CBZed
CBZed/FileSystemObject.swift
1
2826
// // FileSystemObject.swift // CBZed // // Created by Joseph Toronto on 5/11/16. // Copyright © 2016 Janken Studios. All rights reserved. // import Cocoa class FileSystemObject: NSObject { enum NodeType{ case RootNode case Inode case Leafnode } var parentObject:FileSystemObject? var children:Array<FileSystemObject> = [] var selfType:NodeType? var path:String? var pathRoot:String? var name:String? init (rootObjectWithPath: String){ //This is the initializer that gets called outisde of the class super.init() self.selfType = NodeType.RootNode self.path = rootObjectWithPath self.name = (self.path! as NSString).lastPathComponent self.searchForChildren() } init (path: String, parent: FileSystemObject){ //This is the initialized that gets called from within the class to create new children super.init() self.parentObject = parent self.path = path self.name = (self.path! as NSString).lastPathComponent self.searchForChildren() } func searchForChildren(){ let fileManager = NSFileManager() //First check to see if we're a leaf-node or not. var isDir = ObjCBool(false) let exists = fileManager.fileExistsAtPath(self.path!, isDirectory: &isDir) if exists{ if !isDir{ print("\(self.path) is a leaf node") self.selfType = NodeType.Leafnode } else if isDir{ //Search for children // var children:Array<FileSystemObject> = [] var dirContents:Array<String> = [] self.selfType = NodeType.Inode do { dirContents = try fileManager.contentsOfDirectoryAtPath(path!) } catch NSCocoaError.FileReadNoSuchFileError { print("No such file") } catch { // other errors print(error) } let numberofChildren = dirContents.count print("\(self.path)'s children \(dirContents)") for i in 0 ..< numberofChildren{ if dirContents[i] != ".DS_Store"{ let path = self.path! + "/" + dirContents [i] let newChild = FileSystemObject (path: path, parent: self) self.children.append(newChild) } } } } self.children.sortInPlace({ $0.name < $1.name }) }// end search for children }//End FilesystemObject class
mit
d83c82106e8bc310208b364477bdcd36
30.4
138
0.528496
5.173993
false
false
false
false
loudnate/Loop
Loop Status Extension/StatusViewController.swift
1
11613
// // StatusViewController.swift // Loop Status Extension // // Created by Bharat Mediratta on 11/25/16. // Copyright © 2016 LoopKit Authors. All rights reserved. // import CoreData import HealthKit import LoopKit import LoopKitUI import LoopCore import LoopUI import NotificationCenter import UIKit import SwiftCharts class StatusViewController: UIViewController, NCWidgetProviding { @IBOutlet weak var hudView: HUDView! { didSet { hudView.loopCompletionHUD.stateColors = .loopStatus hudView.glucoseHUD.stateColors = .cgmStatus hudView.glucoseHUD.tintColor = .glucoseTintColor hudView.basalRateHUD.tintColor = .doseTintColor } } @IBOutlet weak var subtitleLabel: UILabel! @IBOutlet weak var insulinLabel: UILabel! @IBOutlet weak var glucoseChartContentView: LoopUI.ChartContainerView! private lazy var charts: StatusChartsManager = { let charts = StatusChartsManager( colors: ChartColorPalette( axisLine: .axisLineColor, axisLabel: .axisLabelColor, grid: .gridColor, glucoseTint: .glucoseTintColor, doseTint: .doseTintColor ), settings: { var settings = ChartSettings() settings.top = 4 settings.bottom = 8 settings.trailing = 8 settings.axisTitleLabelsToLabelsSpacing = 0 settings.labelsToAxisSpacingX = 6 settings.clipInnerFrame = false return settings }(), traitCollection: traitCollection ) charts.predictedGlucose.glucoseDisplayRange = HKQuantity(unit: .milligramsPerDeciliter, doubleValue: 100)...HKQuantity(unit: .milligramsPerDeciliter, doubleValue: 175) return charts }() var statusExtensionContext: StatusExtensionContext? lazy var defaults = UserDefaults.appGroup private var observers: [Any] = [] lazy var healthStore = HKHealthStore() lazy var cacheStore = PersistenceController.controllerInAppGroupDirectory() lazy var glucoseStore = GlucoseStore( healthStore: healthStore, cacheStore: cacheStore, observationEnabled: false ) lazy var doseStore = DoseStore( healthStore: healthStore, cacheStore: cacheStore, observationEnabled: false, insulinModel: defaults?.insulinModelSettings?.model, basalProfile: defaults?.basalRateSchedule, insulinSensitivitySchedule: defaults?.insulinSensitivitySchedule ) private var pluginManager: PluginManager = { let containingAppFrameworksURL = Bundle.main.privateFrameworksURL?.deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("Frameworks") return PluginManager(pluginsURL: containingAppFrameworksURL) }() override func viewDidLoad() { super.viewDidLoad() subtitleLabel.isHidden = true if #available(iOSApplicationExtension 13.0, iOS 13.0, *) { subtitleLabel.textColor = .secondaryLabel insulinLabel.textColor = .secondaryLabel } else { subtitleLabel.textColor = .subtitleLabelColor insulinLabel.textColor = .subtitleLabelColor } insulinLabel.isHidden = true let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(openLoopApp(_:))) view.addGestureRecognizer(tapGestureRecognizer) self.charts.prerender() glucoseChartContentView.chartGenerator = { [weak self] (frame) in return self?.charts.chart(atIndex: 0, frame: frame)?.view } extensionContext?.widgetLargestAvailableDisplayMode = .expanded switch extensionContext?.widgetActiveDisplayMode ?? .compact { case .expanded: glucoseChartContentView.isHidden = false case .compact: fallthrough @unknown default: glucoseChartContentView.isHidden = true } observers = [ // TODO: Observe cross-process notifications of Loop status updating ] } deinit { for observer in observers { NotificationCenter.default.removeObserver(observer) } } func widgetActiveDisplayModeDidChange(_ activeDisplayMode: NCWidgetDisplayMode, withMaximumSize maxSize: CGSize) { let compactHeight = hudView.systemLayoutSizeFitting(maxSize).height + subtitleLabel.systemLayoutSizeFitting(maxSize).height switch activeDisplayMode { case .expanded: preferredContentSize = CGSize(width: maxSize.width, height: compactHeight + 100) case .compact: fallthrough @unknown default: preferredContentSize = CGSize(width: maxSize.width, height: compactHeight) } } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) coordinator.animate(alongsideTransition: { (UIViewControllerTransitionCoordinatorContext) -> Void in self.glucoseChartContentView.isHidden = self.extensionContext?.widgetActiveDisplayMode != .expanded }) } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { charts.traitCollection = traitCollection } @objc private func openLoopApp(_: Any) { if let url = Bundle.main.mainAppUrl { self.extensionContext?.open(url) } } func widgetPerformUpdate(completionHandler: (@escaping (NCUpdateResult) -> Void)) { let result = update() completionHandler(result) } @discardableResult func update() -> NCUpdateResult { subtitleLabel.isHidden = true insulinLabel.isHidden = true let group = DispatchGroup() var activeInsulin: Double? var glucose: [StoredGlucoseSample] = [] group.enter() doseStore.insulinOnBoard(at: Date()) { (result) in switch result { case .success(let iobValue): activeInsulin = iobValue.value case .failure: activeInsulin = nil } group.leave() } charts.startDate = Calendar.current.nextDate(after: Date(timeIntervalSinceNow: .minutes(-5)), matching: DateComponents(minute: 0), matchingPolicy: .strict, direction: .backward) ?? Date() // Showing the whole history plus full prediction in the glucose plot // is a little crowded, so limit it to three hours in the future: charts.maxEndDate = charts.startDate.addingTimeInterval(TimeInterval(hours: 3)) group.enter() glucoseStore.getCachedGlucoseSamples(start: charts.startDate) { (result) in glucose = result group.leave() } group.notify(queue: .main) { guard let defaults = self.defaults, let context = defaults.statusExtensionContext else { return } let hudViews: [BaseHUDView] if let hudViewsContext = context.pumpManagerHUDViewsContext, let contextHUDViews = PumpManagerHUDViewsFromRawValue(hudViewsContext.pumpManagerHUDViewsRawValue, pluginManager: self.pluginManager) { hudViews = contextHUDViews } else { hudViews = [ReservoirVolumeHUDView.instantiate(), BatteryLevelHUDView.instantiate()] } self.hudView.removePumpManagerProvidedViews() for view in hudViews { view.stateColors = .pumpStatus self.hudView.addHUDView(view) } if let netBasal = context.netBasal { self.hudView.basalRateHUD.setNetBasalRate(netBasal.rate, percent: netBasal.percentage, at: netBasal.start) } self.hudView.loopCompletionHUD.dosingEnabled = defaults.loopSettings?.dosingEnabled ?? false if let lastCompleted = context.lastLoopCompleted { self.hudView.loopCompletionHUD.lastLoopCompleted = lastCompleted } if let activeInsulin = activeInsulin { let insulinFormatter: NumberFormatter = { let numberFormatter = NumberFormatter() numberFormatter.numberStyle = .decimal numberFormatter.minimumFractionDigits = 1 numberFormatter.maximumFractionDigits = 1 return numberFormatter }() if let valueStr = insulinFormatter.string(from: activeInsulin) { self.insulinLabel.text = String(format: NSLocalizedString("IOB %1$@ U", comment: "The subtitle format describing units of active insulin. (1: localized insulin value description)"), valueStr ) self.insulinLabel.isHidden = false } } guard let unit = context.predictedGlucose?.unit else { return } if let lastGlucose = glucose.last, let recencyInterval = defaults.loopSettings?.inputDataRecencyInterval { self.hudView.glucoseHUD.setGlucoseQuantity( lastGlucose.quantity.doubleValue(for: unit), at: lastGlucose.startDate, unit: unit, staleGlucoseAge: recencyInterval, sensor: context.sensor ) } let glucoseFormatter = QuantityFormatter() glucoseFormatter.setPreferredNumberFormatter(for: unit) self.charts.predictedGlucose.glucoseUnit = unit self.charts.predictedGlucose.setGlucoseValues(glucose) if let predictedGlucose = context.predictedGlucose?.samples { self.charts.predictedGlucose.setPredictedGlucoseValues(predictedGlucose) if let eventualGlucose = predictedGlucose.last { if let eventualGlucoseNumberString = glucoseFormatter.string(from: eventualGlucose.quantity, for: unit) { self.subtitleLabel.text = String( format: NSLocalizedString( "Eventually %1$@", comment: "The subtitle format describing eventual glucose. (1: localized glucose value description)" ), eventualGlucoseNumberString ) self.subtitleLabel.isHidden = false } } } self.charts.predictedGlucose.targetGlucoseSchedule = defaults.loopSettings?.glucoseTargetRangeSchedule self.charts.invalidateChart(atIndex: 0) self.charts.prerender() self.glucoseChartContentView.reloadChart() } switch extensionContext?.widgetActiveDisplayMode ?? .compact { case .expanded: glucoseChartContentView.isHidden = false case .compact: fallthrough @unknown default: glucoseChartContentView.isHidden = true } // Right now we always act as if there's new data. // TODO: keep track of data changes and return .noData if necessary return NCUpdateResult.newData } }
apache-2.0
e5eb4914e0440a8359c7e8642f949abf
36.337621
195
0.624957
5.806
false
false
false
false
czerenkow/LublinWeather
App/Settings Version/SettingsVersionInteractor.swift
1
3004
// // SettingsVersionInteractor.swift // LublinWeather // // Created by Damian Rzeszot on 03/05/2018. // Copyright © 2018 Damian Rzeszot. All rights reserved. // import Foundation struct SettingsVersionViewModel { struct Entry { let name: String let value: String } struct Section { let title: String let entries: [Entry] } let sections: [Section] } protocol SettingsVersionPresentable: Presentable { func configure(with model: SettingsVersionViewModel) } // // Hardware.swift // App // // Created by Damian Rzeszot on 11/10/2017. // Copyright © 2017 Damian Rzeszot. All rights reserved. // import UIKit final class Hardware { private init() {} private class func stringify<T>(_ pointer: inout T) -> String? { return withUnsafePointer(to: &pointer) { $0.withMemoryRebound(to: CChar.self, capacity: 1) { ptr in String(validatingUTF8: ptr) } } } class var model: String { var info = utsname() uname(&info) let value = stringify(&info.machine) ?? "unknown" #if false if value == "x86_64" { return env(key: "SIMULATOR_MODEL_IDENTIFIER") ?? "simulator" } else { return value } #else return value #endif } class var system: String { let dev = UIDevice.current return "\(dev.systemName)_\(dev.systemVersion)" } private class func env(key: String) -> String? { return ProcessInfo.processInfo.environment[key] } } final class SettingsVersionInteractor: Interactor { weak var router: SettingsVersionRouter! weak var presenter: SettingsVersionPresentable! // MARK: - var tracker: Tracker<SettingsVersionEvent>! var configuration: Configuration! // MARK: - override func activate() { super.activate() tracker.track(.activate) refresh() } override func deactivate() { super.deactivate() tracker.track(.deactivate) } private func refresh() { typealias Section = SettingsVersionViewModel.Section typealias Entry = SettingsVersionViewModel.Entry let model = SettingsVersionViewModel(sections: [ Section(title: "app", entries: [ Entry(name: "app.version", value: Bundle.main.version), Entry(name: "app.build", value: Bundle.main.build) ]), Section(title: "device", entries: [ Entry(name: "device.model", value: Hardware.model), Entry(name: "device.system", value: Hardware.system) ]), Section(title: "build", entries: [ Entry(name: "build.branch", value: configuration.git.branch), Entry(name: "build.commit", value: configuration.git.commit) ]) ]) presenter.configure(with: model) } }
mit
891daeb840e39dc759ec74217d4d2498
21.402985
77
0.587941
4.47392
false
false
false
false
farhanpatel/firefox-ios
XCUITests/FxScreenGraph.swift
1
17060
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import XCTest let FirstRun = "OptionalFirstRun" let TabTray = "TabTray" let PrivateTabTray = "PrivateTabTray" let URLBarOpen = "URLBarOpen" let PrivateURLBarOpen = "PrivateURLBarOpen" let BrowserTab = "BrowserTab" let PrivateBrowserTab = "PrivateBrowserTab" let BrowserTabMenu = "BrowserTabMenu" let PageOptionsMenu = "PageOptionsMenu" let FindInPage = "FindInPage" let SettingsScreen = "SettingsScreen" let HomePageSettings = "HomePageSettings" let PasscodeSettings = "PasscodeSettings" let PasscodeIntervalSettings = "PasscodeIntervalSettings" let SearchSettings = "SearchSettings" let NewTabSettings = "NewTabSettings" let ClearPrivateDataSettings = "ClearPrivateDataSettings" let LoginsSettings = "LoginsSettings" let OpenWithSettings = "OpenWithSettings" let ShowTourInSettings = "ShowTourInSettings" let Intro_FxASignin = "Intro_FxASignin" let allSettingsScreens = [ SettingsScreen, HomePageSettings, PasscodeSettings, SearchSettings, NewTabSettings, ClearPrivateDataSettings, LoginsSettings, OpenWithSettings ] let Intro_Welcome = "Intro.Welcome" let Intro_Search = "Intro.Search" let Intro_Private = "Intro.Private" let Intro_Mail = "Intro.Mail" let Intro_Sync = "Intro.Sync" let allIntroPages = [ Intro_Welcome, Intro_Search, Intro_Private, Intro_Mail, Intro_Sync ] let HomePanelsScreen = "HomePanels" let PrivateHomePanelsScreen = "PrivateHomePanels" let HomePanel_TopSites = "HomePanel.TopSites.0" let HomePanel_Bookmarks = "HomePanel.Bookmarks.1" let HomePanel_History = "HomePanel.History.2" let HomePanel_ReadingList = "HomePanel.ReadingList.3" let P_HomePanel_TopSites = "P_HomePanel.TopSites.0" let P_HomePanel_Bookmarks = "P_HomePanel.Bookmarks.1" let P_HomePanel_History = "P_HomePanel.History.2" let P_HomePanel_ReadingList = "P_HomePanel.ReadingList.3" let allHomePanels = [ HomePanel_Bookmarks, HomePanel_TopSites, HomePanel_History, HomePanel_ReadingList ] let allPrivateHomePanels = [ P_HomePanel_Bookmarks, P_HomePanel_TopSites, P_HomePanel_History, P_HomePanel_ReadingList ] let ContextMenu_ReloadButton = "ContextMenu_ReloadButton" func createScreenGraph(_ app: XCUIApplication, url: String = "https://www.mozilla.org/en-US/book/") -> ScreenGraph { let map = ScreenGraph() let startBrowsingButton = app.buttons["IntroViewController.startBrowsingButton"] let introScrollView = app.scrollViews["IntroViewController.scrollView"] map.createScene(FirstRun) { scene in // We don't yet have conditional edges, so we declare an edge from this node // to BrowserTab, and then just make it work. if introScrollView.exists { scene.gesture(to: BrowserTab) { // go find the startBrowsing button on the second page of the intro. introScrollView.swipeLeft() startBrowsingButton.tap() } scene.noop(to: allIntroPages[0]) } else { scene.noop(to: HomePanelsScreen) } } // Add the intro screens. var i = 0 let introLast = allIntroPages.count - 1 let introPager = app.scrollViews["IntroViewController.scrollView"] for intro in allIntroPages { let prev = i == 0 ? nil : allIntroPages[i - 1] let next = i == introLast ? nil : allIntroPages[i + 1] map.createScene(intro) { scene in if let prev = prev { scene.swipeRight(introPager, to: prev) } if let next = next { scene.swipeLeft(introPager, to: next) } if i > 0 { scene.tap(startBrowsingButton, to: BrowserTab) } } i += 1 } map.createScene(URLBarOpen) { scene in // This is used for opening BrowserTab with default mozilla URL // For custom URL, should use Navigator.openNewURL or Navigator.openURL. scene.typeText(url + "\r", into: app.textFields["address"], to: BrowserTab) scene.tap( app.textFields["url"], to: HomePanelsScreen) /* scene.backAction = { app.buttons["goBack"].tap() } */ } map.createScene(PrivateURLBarOpen) { scene in // This is used for opening BrowserTab with default mozilla URL // For custom URL, should use Navigator.openNewURL or Navigator.openURL. scene.typeText(url + "\r", into: app.textFields["address"], to:PrivateBrowserTab) scene.tap( app.textFields["address"], to: PrivateHomePanelsScreen) } let noopAction = {} map.createScene(HomePanelsScreen) { scene in scene.tap(app.buttons["HomePanels.TopSites"], to: HomePanel_TopSites) scene.tap(app.buttons["HomePanels.Bookmarks"], to: HomePanel_Bookmarks) scene.tap(app.buttons["HomePanels.History"], to: HomePanel_History) scene.tap(app.buttons["HomePanels.ReadingList"], to: HomePanel_ReadingList) scene.tap(app.textFields["url"], to: URLBarOpen) scene.tap(app.buttons["TabToolbar.menuButton"], to: BrowserTabMenu) if map.isiPad() { scene.tap(app.buttons["TopTabsViewController.tabsButton"], to: TabTray) } else { scene.gesture(to: TabTray) { if (app.buttons["TabToolbar.tabsButton"].exists) { app.buttons["TabToolbar.tabsButton"].tap() } else { app.buttons["URLBarView.tabsButton"].tap() } } } } map.createScene(PrivateHomePanelsScreen) { scene in scene.tap(app.buttons["HomePanels.TopSites"], to: P_HomePanel_TopSites) scene.tap(app.buttons["HomePanels.Bookmarks"], to: P_HomePanel_Bookmarks) scene.tap(app.buttons["HomePanels.History"], to: P_HomePanel_History) scene.tap(app.buttons["HomePanels.ReadingList"], to: P_HomePanel_ReadingList) scene.tap(app.textFields["url"], to: PrivateURLBarOpen) scene.tap(app.buttons["TabToolbar.menuButton"], to: BrowserTabMenu) if map.isiPad() { scene.tap(app.buttons["TopTabsViewController.tabsButton"], to: PrivateTabTray) } else { scene.gesture(to: PrivateTabTray) { if (app.buttons["TabToolbar.tabsButton"].exists) { app.buttons["TabToolbar.tabsButton"].tap() } else { app.buttons["URLBarView.tabsButton"].tap() } } } } allHomePanels.forEach { name in // Tab panel means that all the home panels are available all the time, so we can // fake this out by a noop back to the HomePanelsScreen which can get to every other panel. map.createScene(name) { scene in scene.backAction = noopAction } } allPrivateHomePanels.forEach { name in // Tab panel means that all the home panels are available all the time, so we can // fake this out by a noop back to the HomePanelsScreen which can get to every other panel. map.createScene(name) { scene in scene.backAction = noopAction } } let closeMenuAction = { app.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.25)).tap() } let navigationControllerBackAction = { app.navigationBars.element(boundBy: 0).buttons.element(boundBy: 0).tap() } let cancelBackAction = { if map.isiPad() { // There is not Cancel option in iPad this way it is closed app/*@START_MENU_TOKEN@*/.otherElements["PopoverDismissRegion"]/*[[".otherElements[\"dismiss popup\"]",".otherElements[\"PopoverDismissRegion\"]"],[[[-1,1],[-1,0]]],[0]]@END_MENU_TOKEN@*/.tap() } else { app.buttons["PhotonMenu.cancel"].tap() } } let backBtnBackAction = { if map.isiPad() { app.buttons["URLBarView.backButton"].tap() } else { app.buttons["TabToolbar.backButton"].tap() } } map.createScene(SettingsScreen) { scene in let table = app.tables["AppSettingsTableViewController.tableView"] scene.tap(table.cells["Search"], to: SearchSettings) scene.tap(table.cells["NewTab"], to: NewTabSettings) scene.tap(table.cells["Homepage"], to: HomePageSettings) scene.tap(table.cells["TouchIDPasscode"], to: PasscodeSettings) scene.tap(table.cells["Logins"], to: LoginsSettings) scene.tap(table.cells["ClearPrivateData"], to: ClearPrivateDataSettings) scene.tap(table.cells["OpenWith.Setting"], to: OpenWithSettings) scene.tap(table.cells["ShowTour"], to: ShowTourInSettings) scene.backAction = navigationControllerBackAction } map.createScene(SearchSettings) { scene in scene.backAction = navigationControllerBackAction } map.createScene(NewTabSettings) { scene in scene.backAction = navigationControllerBackAction } map.createScene(HomePageSettings) { scene in scene.backAction = navigationControllerBackAction } map.createScene(PasscodeSettings) { scene in scene.backAction = navigationControllerBackAction scene.tap(app.tables["AuthenticationManager.settingsTableView"].staticTexts["Require Passcode"], to: PasscodeIntervalSettings) } map.createScene(PasscodeIntervalSettings) { scene in // The test is likely to know what it needs to do here. // This screen is protected by a passcode and is essentially modal. scene.gesture(to: PasscodeSettings) { if app.navigationBars["Require Passcode"].exists { // Go back, accepting modifications app.navigationBars["Require Passcode"].buttons["Passcode For Logins"].tap() } else { // Cancel app.navigationBars["Enter Passcode"].buttons["Cancel"].tap() } } } map.createScene(LoginsSettings) { scene in scene.gesture(to: SettingsScreen) { let loginList = app.tables["Login List"] if loginList.exists { app.navigationBars["Logins"].buttons["Settings"].tap() } else { app.navigationBars["Enter Passcode"].buttons["Cancel"].tap() } } } map.createScene(ClearPrivateDataSettings) { scene in scene.backAction = navigationControllerBackAction } map.createScene(OpenWithSettings) { scene in scene.backAction = navigationControllerBackAction } map.createScene(ShowTourInSettings) { scene in scene.gesture(to: Intro_FxASignin) { let introScrollView = app.scrollViews["IntroViewController.scrollView"] for _ in 1...4 { introScrollView.swipeLeft() } app.buttons["Sign in to Firefox"].tap() } scene.backAction = { introScrollView.swipeLeft() startBrowsingButton.tap() } } map.createScene(Intro_FxASignin) { scene in scene.tap(app.navigationBars["Client.FxAContentView"].buttons.element(boundBy: 0), to: HomePanelsScreen) } map.createScene(PrivateTabTray) { scene in scene.tap(app.buttons["TabTrayController.addTabButton"], to: PrivateHomePanelsScreen) scene.tap(app.buttons["TabTrayController.maskButton"], to: TabTray) } map.createScene(TabTray) { scene in scene.tap(app.buttons["TabTrayController.addTabButton"], to: HomePanelsScreen) scene.tap(app.buttons["TabTrayController.maskButton"], to: PrivateTabTray) } map.createScene(BrowserTab) { scene in scene.tap(app.textFields["url"], to: URLBarOpen) scene.tap(app.buttons["TabToolbar.menuButton"], to: BrowserTabMenu) if map.isiPad() { scene.tap(app.buttons["TopTabsViewController.tabsButton"], to: TabTray) } else { scene.gesture(to: TabTray) { if (app.buttons["TabToolbar.tabsButton"].exists) { app.buttons["TabToolbar.tabsButton"].tap() } else { app.buttons["URLBarView.tabsButton"].tap() } } } scene.tap(app.buttons["TabLocationView.pageOptionsButton"], to: PageOptionsMenu) scene.backAction = backBtnBackAction } // make sure after the menu action, navigator.nowAt() is used to set the current state map.createScene(PageOptionsMenu) {scene in scene.tap(app.tables["Context Menu"].cells["Find in Page"], to: FindInPage) scene.backAction = cancelBackAction scene.dismissOnUse = true } map.createScene(FindInPage) {scene in scene.tap(app.buttons["FindInPage.close"], to: BrowserTab) } map.createScene(PrivateBrowserTab) { scene in scene.tap(app.textFields["url"], to: URLBarOpen) scene.tap(app.buttons["TabToolbar.menuButton"], to: BrowserTabMenu) if map.isiPad() { scene.tap(app.buttons["TopTabsViewController.tabsButton"], to: PrivateTabTray) } else { scene.gesture(to: PrivateTabTray) { if (app.buttons["TabToolbar.tabsButton"].exists) { app.buttons["TabToolbar.tabsButton"].tap() } else { app.buttons["URLBarView.tabsButton"].tap() } } } scene.tap(app.buttons["TabLocationView.pageOptionsButton"], to: PageOptionsMenu) scene.backAction = backBtnBackAction } map.createScene(BrowserTabMenu) { scene in scene.backAction = cancelBackAction scene.tap(app.tables.cells["Settings"], to: SettingsScreen) scene.dismissOnUse = true } map.initialSceneName = FirstRun return map } extension ScreenGraph { // Checks whether the current device is iPad or non-iPad func isiPad() -> Bool { if UIDevice.current.userInterfaceIdiom == .pad { return true } return false } } extension Navigator { // Open a URL. Will use/re-use the first BrowserTab or NewTabScreen it comes to. func openURL(urlString: String) { self.goto(URLBarOpen) let app = XCUIApplication() app.textFields["address"].typeText(urlString + "\r") self.nowAt(BrowserTab) } // Opens a URL in a new tab. func openNewURL(urlString: String) { self.goto(TabTray) createNewTab() self.openURL(urlString: urlString) } // Closes all Tabs from the option in TabTrayMenu func closeAllTabs() { let app = XCUIApplication() app.buttons["TabTrayController.removeTabsButton"].tap() app.sheets.buttons["Close All Tabs"].tap() self.nowAt(HomePanelsScreen) } // Add a new Tab from the New Tab option in Browser Tab Menu func createNewTab() { let app = XCUIApplication() self.goto(TabTray) app.buttons["TabTrayController.addTabButton"].tap() self.nowAt(HomePanelsScreen) } // Add Tab(s) from the Tab Tray func createSeveralTabsFromTabTray(numberTabs: Int) { for _ in 1...numberTabs { self.goto(TabTray) self.goto(HomePanelsScreen) } } func browserPerformAction(_ view: BrowserPerformAction) { let PageMenuOptions = [.toggleBookmarkOption, .addReadingListOption, .copyURLOption, .findInPageOption, .toggleDesktopOption, .requestSetHomePageOption, BrowserPerformAction.shareOption] let BrowserMenuOptions = [.openTopSitesOption, .openBookMarksOption, .openHistoryOption, .openReadingListOption, .toggleHideImages, .toggleNightMode, BrowserPerformAction.openSettingsOption] let app = XCUIApplication() if PageMenuOptions.contains(view) { self.goto(PageOptionsMenu) app.tables["Context Menu"].cells[view.rawValue].tap() } else if BrowserMenuOptions.contains(view) { self.goto(BrowserTabMenu) app.tables["Context Menu"].cells[view.rawValue].tap() } } } enum BrowserPerformAction: String { // Page Menu case toggleBookmarkOption = "menu-Bookmark" case addReadingListOption = "addToReadingList" case copyURLOption = "menu-Copy-Link" case findInPageOption = "menu-FindInPage" case toggleDesktopOption = "menu-RequestDesktopSite" case requestSetHomePageOption = "menu-Home" case shareOption = "action_share" // Tab Menu case openTopSitesOption = "menu-panel-TopSites" case openBookMarksOption = "menu-panel-Bookmarks" case openHistoryOption = "menu-panel-History" case openReadingListOption = "menu-panel-ReadingList" case toggleHideImages = "menu-NoImageMode" case toggleNightMode = "menu-NightMode" case openSettingsOption = "menu-Settings" }
mpl-2.0
73d38bea6047f80ac8110e658946ac9f
34.915789
205
0.647597
4.498945
false
false
false
false
harlanhaskins/swift
test/ScanDependencies/Inputs/ModuleDependencyGraph.swift
1
4457
//===--------------- ModuleDependencyGraph.swift --------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import Foundation enum ModuleDependencyId: Hashable { case swift(String) case clang(String) var moduleName: String { switch self { case .swift(let name): return name case .clang(let name): return name } } } extension ModuleDependencyId: Codable { enum CodingKeys: CodingKey { case swift case clang } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) do { let moduleName = try container.decode(String.self, forKey: .swift) self = .swift(moduleName) } catch { let moduleName = try container.decode(String.self, forKey: .clang) self = .clang(moduleName) } } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) switch self { case .swift(let moduleName): try container.encode(moduleName, forKey: .swift) case .clang(let moduleName): try container.encode(moduleName, forKey: .clang) } } } /// Bridging header struct BridgingHeader: Codable { var path: String var sourceFiles: [String] var moduleDependencies: [String] } /// Details specific to Swift modules. struct SwiftModuleDetails: Codable { /// The module interface from which this module was built, if any. var moduleInterfacePath: String? /// The bridging header, if any. var bridgingHeader: BridgingHeader? /// The Swift command line arguments that need to be passed through /// to the -compile-module-from-interface action to build this module. var commandLine: [String]? } /// Details specific to Clang modules. struct ClangModuleDetails: Codable { /// The path to the module map used to build this module. var moduleMapPath: String /// The context hash used to discriminate this module file. var contextHash: String /// The Clang command line arguments that need to be passed through /// to the -emit-pcm action to build this module. var commandLine: [String] = [] } struct ModuleDependencies: Codable { /// The path for the module. var modulePath: String /// The source files used to build this module. var sourceFiles: [String] = [] /// The set of direct module dependencies of this module. var directDependencies: [ModuleDependencyId] = [] /// Specific details of a particular kind of module. var details: Details /// Specific details of a particular kind of module. enum Details { /// Swift modules may be built from a module interface, and may have /// a bridging header. case swift(SwiftModuleDetails) /// Clang modules are built from a module map file. case clang(ClangModuleDetails) } } extension ModuleDependencies.Details: Codable { enum CodingKeys: CodingKey { case swift case clang } init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) do { let details = try container.decode(SwiftModuleDetails.self, forKey: .swift) self = .swift(details) } catch { let details = try container.decode(ClangModuleDetails.self, forKey: .clang) self = .clang(details) } } func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) switch self { case .swift(let details): try container.encode(details, forKey: .swift) case .clang(let details): try container.encode(details, forKey: .clang) } } } /// Describes the complete set of dependencies for a Swift module, including /// all of the Swift and C modules and source files it depends on. struct ModuleDependencyGraph: Codable { /// The name of the main module. var mainModuleName: String /// The complete set of modules discovered var modules: [ModuleDependencyId: ModuleDependencies] = [:] /// Information about the main module. var mainModule: ModuleDependencies { modules[.swift(mainModuleName)]! } }
apache-2.0
b23e5199129cc49dbfb5c9c57ac27eb3
28.713333
81
0.680951
4.421627
false
false
false
false
practicalswift/swift
test/Interpreter/checked_cast_test.swift
36
1214
//===--- checked_cast_test.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 // //===----------------------------------------------------------------------===// // RUN: %target-run-simple-swift // REQUIRES: executable_test // Test that we emit proper ARC here and do not crash. private class Foo { init() {} } final private class Bar : Foo { } final private class Baz : Foo { } private func checked_cast_default(_ f: Foo) -> Int { switch f { case is Bar: return 0 case is Baz: return 1 default: return 2 } } private func checked_cast_exhaustive(_ f: Foo) -> Int { switch f { case is Bar: return 0 case is Baz: return 1 case is Foo: return 2 } } func main() { let b = Baz() let x = checked_cast_default(b) precondition(x == 1) let y = checked_cast_exhaustive(b) precondition(y == 1) } main()
apache-2.0
024fceced1f9ebaf961fb0ddd69e07d2
19.931034
80
0.588962
3.746914
false
true
false
false
NoryCao/zhuishushenqi
zhuishushenqi/NewVersion/Comment/ZSPostReviewAuthor.swift
1
516
// // Author.swift // // Create by 农运 on 7/8/2019 // Copyright © 2019. All rights reserved. // 模型生成器(小波汉化)JSONExport: https://github.com/Ahmed-Ali/JSONExport import Foundation import HandyJSON struct ZSPostReviewAuthor:HandyJSON{ var id : String = "" var activityAvatar : String = "" var avatar : String = "" var created : String = "" var gender : String = "" var lv : Int = 0 var nickname : String = "" var rank : AnyObject? var type : UserType = .none init() {} }
mit
444a7ee7843de61c3d7841228de194cd
17.807692
65
0.652352
3.094937
false
false
false
false
huonw/swift
test/SILGen/tsan_instrumentation.swift
1
4717
// RUN: %target-swift-emit-silgen -sanitize=thread %s | %FileCheck %s // REQUIRES: tsan_runtime func takesInout(_ p: inout Int) { } func takesInout(_ p: inout MyStruct) { } struct MyStruct { var storedProperty: Int = 77 } class MyClass { var storedProperty: Int = 22 } var gStruct = MyStruct() var gClass = MyClass() // CHECK-LABEL: sil hidden @$S20tsan_instrumentation17inoutGlobalStructyyF : $@convention(thin) () -> () { // CHECK: [[GLOBAL_ADDR:%.*]] = global_addr @$S20tsan_instrumentation7gStructAA02MyC0Vvp : $*MyStruct // CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[GLOBAL_ADDR]] : $*MyStruct // CHECK: {{%.*}} = builtin "tsanInoutAccess"([[WRITE]] : $*MyStruct) : $() // CHECK: [[TAKES_INOUT_FUNC:%.*]] = function_ref @$S20tsan_instrumentation10takesInoutyyAA8MyStructVzF : $@convention(thin) (@inout MyStruct) -> () // CHECK: {{%.*}} = apply [[TAKES_INOUT_FUNC]]([[WRITE]]) : $@convention(thin) (@inout MyStruct) -> () func inoutGlobalStruct() { takesInout(&gStruct) } // CHECK-LABEL: sil hidden @$S20tsan_instrumentation31inoutGlobalStructStoredPropertyyyF : $@convention(thin) () -> () { // CHECK: [[GLOBAL_ADDR:%.*]] = global_addr @$S20tsan_instrumentation7gStructAA02MyC0Vvp : $*MyStruct // CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[GLOBAL_ADDR]] : $*MyStruct // CHECK: {{%.*}} = builtin "tsanInoutAccess"([[WRITE]] : $*MyStruct) : $() // CHECK: [[ELEMENT_ADDR:%.*]] = struct_element_addr [[WRITE]] : $*MyStruct, #MyStruct.storedProperty // CHECK: {{%.*}} = builtin "tsanInoutAccess"([[ELEMENT_ADDR]] : $*Int) : $() // CHECK: [[TAKES_INOUT_FUNC:%.*]] = function_ref @$S20tsan_instrumentation10takesInoutyySizF : $@convention(thin) (@inout Int) -> () // CHECK: {{%.*}} = apply [[TAKES_INOUT_FUNC]]([[ELEMENT_ADDR]]) : $@convention(thin) (@inout Int) -> () func inoutGlobalStructStoredProperty() { // This should generate two TSan inout instrumentations; one for the address // of the global and one for the address of the struct stored property. takesInout(&gStruct.storedProperty) } // CHECK-LABEL: sil hidden @$S20tsan_instrumentation30inoutGlobalClassStoredPropertyyyF : $@convention(thin) () -> () { // CHECK: [[GLOBAL_ADDR:%.*]] = global_addr @$S20tsan_instrumentation6gClassAA02MyC0Cvp : $*MyClass // CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[GLOBAL_ADDR]] : $*MyClass // CHECK: [[LOADED_CLASS:%.*]] = load [copy] [[READ]] : $*MyClass // CHECK: [[VALUE_BUFFER:%.*]] = alloc_stack $Builtin.UnsafeValueBuffer // CHECK: [[TEMPORARY:%.*]] = alloc_stack $Int // CHECK: [[BORROWED_CLASS:%.*]] = begin_borrow [[LOADED_CLASS]] : $MyClass // CHECK: [[TEMPORARY_RAW:%.*]] = address_to_pointer [[TEMPORARY]] : $*Int to $Builtin.RawPointer // CHECK: {{%.*}} = builtin "tsanInoutAccess"([[VALUE_BUFFER]] : $*Builtin.UnsafeValueBuffer) : $() // CHECK: [[MATERIALIZE_FOR_SET:%.*]] = class_method [[BORROWED_CLASS]] : $MyClass, #MyClass.storedProperty!materializeForSet.1 : (MyClass) -> (Builtin.RawPointer, inout Builtin.UnsafeValueBuffer) -> (Builtin.RawPointer, Builtin.RawPointer?), $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed MyClass) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) // CHECK: [[MATERIALIZE_FOR_SET_TUPLE:%.*]] = apply [[MATERIALIZE_FOR_SET]]([[TEMPORARY_RAW]], [[VALUE_BUFFER]], [[BORROWED_CLASS]]) : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed MyClass) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) // CHECK: [[TEMPORARY_BUFFER:%.*]] = tuple_extract [[MATERIALIZE_FOR_SET_TUPLE]] : $(Builtin.RawPointer, Optional<Builtin.RawPointer>), 0 // CHECK: [[OPTIONAL_CALLBACK:%.*]] = tuple_extract [[MATERIALIZE_FOR_SET_TUPLE]] : $(Builtin.RawPointer, Optional<Builtin.RawPointer>), 1 // CHECK: [[BUFFER_ADDRESS:%.*]] = pointer_to_address [[TEMPORARY_BUFFER]] : $Builtin.RawPointer to [strict] $*Int // CHECK: [[BUFFER_ADDRESS_DEPENDENCE:%.*]] = mark_dependence [[BUFFER_ADDRESS]] : $*Int on [[LOADED_CLASS]] : $MyClass // CHECK: end_borrow [[BORROWED_CLASS]] from [[LOADED_CLASS]] : $MyClass, $MyClass // CHECK: {{%.*}} builtin "tsanInoutAccess"([[BUFFER_ADDRESS_DEPENDENCE]] : $*Int) : $() // CHECK: [[TAKES_INOUT_FUNC:%.*]] = function_ref @$S20tsan_instrumentation10takesInoutyySizF : $@convention(thin) (@inout Int) -> () // CHECK: {{%.*}} apply [[TAKES_INOUT_FUNC]]([[BUFFER_ADDRESS_DEPENDENCE]]) : $@convention(thin) (@inout Int) -> () func inoutGlobalClassStoredProperty() { // This generates two TSan inout instrumentations. One for the value // buffer that is passed inout to materializeForSet and one for the // temporary buffer passed to takesInout(). takesInout(&gClass.storedProperty) }
apache-2.0
e3cbeeeed377ecea122b40c7adb6c221
68.367647
394
0.676701
3.665113
false
false
false
false
ruslanskorb/RSKGrowingTextView
RSKGrowingTextViewExample/RSKGrowingTextViewExample/ViewController.swift
1
2162
// // ViewController.swift // RSKGrowingTextViewExample // // Created by Ruslan Skorb on 12/14/15. // Copyright © 2015 Ruslan Skorb. All rights reserved. // import RSKKeyboardAnimationObserver class ViewController: UIViewController { // MARK: - Properties @IBOutlet weak var bottomLayoutGuideTopAndGrowingTextViewBottomVeticalSpaceConstraint: NSLayoutConstraint! @IBOutlet weak var growingTextView: RSKGrowingTextView! private var isVisibleKeyboard = true // MARK: - Object Lifecycle override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) self.registerForKeyboardNotifications() } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) self.unregisterForKeyboardNotifications() } // MARK: - Helper Methods private func adjustContent(for keyboardRect: CGRect) { let keyboardHeight = keyboardRect.height self.bottomLayoutGuideTopAndGrowingTextViewBottomVeticalSpaceConstraint.constant = self.isVisibleKeyboard ? keyboardHeight - self.bottomLayoutGuide.length : 0.0 self.view.layoutIfNeeded() } @IBAction func handleTapGestureRecognizer(sender: UITapGestureRecognizer) { self.growingTextView.resignFirstResponder() } private func registerForKeyboardNotifications() { self.rsk_subscribeKeyboardWith(beforeWillShowOrHideAnimation: nil, willShowOrHideAnimation: { [unowned self] (keyboardRectEnd, duration, isShowing) -> Void in self.isVisibleKeyboard = isShowing self.adjustContent(for: keyboardRectEnd) }, onComplete: { (finished, isShown) -> Void in self.isVisibleKeyboard = isShown } ) self.rsk_subscribeKeyboard(willChangeFrameAnimation: { [unowned self] (keyboardRectEnd, duration) -> Void in self.adjustContent(for: keyboardRectEnd) }, onComplete: nil) } private func unregisterForKeyboardNotifications() { self.rsk_unsubscribeKeyboard() } }
apache-2.0
c0236e47fc58a9f8ffbcffd2732a5f25
31.742424
168
0.680703
5.32266
false
false
false
false
DonMag/ScratchPad
Swift3/scratchy/scratchy/StackWorkViewController.swift
1
1003
// // StackWorkViewController.swift // scratchy // // Created by Don Mag on 2/27/17. // Copyright © 2017 DonMag. All rights reserved. // import UIKit class StackWorkViewController: UIViewController { @IBOutlet weak var theStackView: UIStackView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func testTap(_ sender: Any) { if theStackView.arrangedSubviews.count > 2 { // we already added the subviews return } let clrs = [UIColor.red, UIColor.blue, UIColor.yellow, UIColor.green] for i in 1...4 { let v = SampleView() v.theLabel.text = "\(i)" v.backgroundColor = clrs[i % 4] v.translatesAutoresizingMaskIntoConstraints = false theStackView.addArrangedSubview(v) } } }
mit
d5332b3df345adf74353be517be1f4a9
16.892857
71
0.649701
4.106557
false
false
false
false
jtaxen/FindShelter
FindShelter/Controller/ShelterInfoTableViewDelegate.swift
1
8517
// // ShelterInfoTableViewDelegate.swift // FindShelter // // Created by ÅF Jacob Taxén on 2017-05-19. // Copyright © 2017 Jacob Taxén. All rights reserved. // import Foundation import UIKit import CoreLocation internal extension ShelterInfoTableViewController { /// Only one section needed. override func numberOfSections(in tableView: UITableView) -> Int { return 1 } /// There are seven attributes which are useful to the user, and one row for favorite button. override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 8 } /// The information for downloaded and saved items is stored slightly different, so unfortunately /// different keywords are needed for each case. override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! ShelterCellTableViewCell if shelterObject != nil { switch indexPath.row { case 0: cell.textLabel?.text = shelterObject!.attributes?.serviceLBAddress ?? words.noAddress cell.detailTextLabel?.text = words.sAddress case 1: cell.textLabel?.text = shelterObject!.attributes?.typeOfOccupants ?? words.noOccupants cell.detailTextLabel?.text = words.sOccupants case 2: cell.textLabel?.text = shelterObject!.attributes?.serviceLBCity ?? words.noCity cell.detailTextLabel?.text = words.sCity case 3: cell.textLabel?.text = shelterObject!.attributes?.serviceLBMunicipality ?? words.noMunicipality cell.detailTextLabel?.text = words.sMunicipality case 4: cell.textLabel?.text = shelterObject!.attributes?.numberOfOccupants != nil ? shelterObject!.attributes!.numberOfOccupants! + " " + words.sPersons : words.noCapacity cell.detailTextLabel?.text = words.sCapacity case 5: if let squaredDistance = locationManager.location?.coordinate.squaredDistance(to: thisPosition) { cell.textLabel?.text = "\(Int(sqrt(squaredDistance))) m" } else { cell.textLabel?.text = words.noDistance } cell.detailTextLabel?.text = words.sDistance case 6: cell.textLabel?.text = shelterObject!.attributes?.pointOfContact ?? words.noPointOfC cell.detailTextLabel?.text = words.sPointOfC case 7: cell.textLabel?.text = words.sSave cell.detailTextLabel?.text = "" default: break } } else if shelterCoreData != nil { CoreDataStack.shared?.persistingContext.performAndWait{ switch indexPath.row { case 0: cell.textLabel?.text = self.shelterCoreData!.address ?? self.words.noAddress cell.detailTextLabel?.text = self.words.sAddress case 1: cell.textLabel?.text = self.shelterCoreData?.occupants ?? self.words.noCapacity cell.detailTextLabel?.text = self.words.sOccupants case 2: cell.textLabel?.text = self.shelterCoreData?.town ?? self.words.noCity cell.detailTextLabel?.text = self.words.sCity case 3: cell.textLabel?.text = self.shelterCoreData?.municipality ?? self.words.noMunicipality cell.detailTextLabel?.text = self.words.sMunicipality case 4: cell.textLabel?.text = "\(self.shelterCoreData?.capacity ?? 0)" + " " + self.words.sPersons cell.detailTextLabel?.text = self.words.sCapacity case 5: if let squaredDistance = self.locationManager.location?.coordinate.squaredDistance(to: self.thisPosition) { cell.textLabel?.text = "\(Int(sqrt(squaredDistance))) m" } else { cell.textLabel?.text = self.words.noDistance } cell.detailTextLabel?.text = self.words.sDistance case 6: cell.textLabel?.text = self.shelterCoreData?.pointOfContact ?? self.words.noPointOfC cell.detailTextLabel?.text = self.words.sPointOfC case 7: cell.textLabel?.text = self.words.sCenter cell.detailTextLabel?.text = "" default: break } } } return cell } /// If the user selects row eight, it either saves the shelter to favorites or, if the shelter is already saved, returns to the map view with the shelter centered. override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { switch indexPath.row { case 7: if shelterObject != nil { CoreDataStack.shared?.persistingContext.perform { let newShelter = Shelter(self.shelterObject!, context: (CoreDataStack.shared?.persistingContext)!) CoreDataStack.shared?.save() DispatchQueue.main.async { let storyboard = UIStoryboard.init(name: "Main", bundle: nil) let controller = storyboard.instantiateViewController(withIdentifier: "shelterTable") as! ShelterInfoTableViewController controller.shelterCoreData = newShelter CoreDataStack.shared?.persistingContext.performAndWait{ controller.thisPosition = SpatialService.shared.convertUTMToLatLon(north: Double(newShelter!.yCoordinate), east: Double(newShelter!.xCoordinate)) } self.navigationController?.pushViewController(controller, animated: false) self.navigationController?.viewControllers.remove(at: (self.navigationController?.viewControllers.count)! - 2) } } } else if shelterCoreData != nil { let rootController = navigationController?.viewControllers[0] as! MapViewController rootController.map.centerCoordinate = thisPosition rootController.map.delegate?.mapViewDidFinishLoadingMap!(rootController.map) navigationController?.popToRootViewController(animated: true) } default: tableView.deselectRow(at: indexPath, animated: false) } } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if indexPath.row < 9 { return 60 } else { return 0 } } override func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat { if indexPath.row < 9 { return 60 } else { return 0 } } } // MARK: - Location manager delegate extension ShelterInfoTableViewController: CLLocationManagerDelegate { func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let coordinate = locations.last?.coordinate let cell = tableView.cellForRow(at: IndexPath(row: 6, section: 0)) let squaredDistance = coordinate!.squaredDistance(to: thisPosition) cell?.textLabel?.text = "\(Int(sqrt(squaredDistance)))" } } // MARK: - Table strings extension ShelterInfoTableViewController { internal struct Words { let sName = NSLocalizedString("Name", comment : "name") let sAddress = NSLocalizedString("Address", comment : "address") let sOccupants = NSLocalizedString("Intended_for", comment : "intended for") let sCity = NSLocalizedString("City", comment : "city") let sMunicipality = NSLocalizedString("Municipality", comment : "municipality") let sPersons = NSLocalizedString("people", comment : "unit for capacity") let sCapacity = NSLocalizedString("Capacity", comment : "capacity") let sDistance = NSLocalizedString("Distance", comment : "distance from the user") let sPointOfC = NSLocalizedString("Point_of_contact", comment : "Point of contact") let sSave = NSLocalizedString("Save", comment : "save button") let sCenter = NSLocalizedString("Show_shelter_on_map", comment : "center on map") let noName = NSLocalizedString("Name_is_missing", comment : "name is missing") let noAddress = NSLocalizedString("Address_is_missing", comment : "address is missing") let noOccupants = NSLocalizedString("No_information", comment : "no information") let noCity = NSLocalizedString("City_is_missing", comment : "city is missing") let noMunicipality = NSLocalizedString("Municipality_is_missing", comment : "no municip") let noCapacity = NSLocalizedString("Capacity_unknown", comment : "capacity unknown") let noDistance = NSLocalizedString("Cannot_find_your_current_position", comment : "user position is lacking") let noPointOfC = NSLocalizedString("No_information", comment : "pointofc is missing") } }
mit
65a9f2b7c0d2faf7a331bfaec4506c2f
43.108808
168
0.688476
4.245885
false
false
false
false
grpc/grpc-swift
Tests/GRPCTests/ClientClosedChannelTests.swift
1
6421
/* * Copyright 2019, gRPC Authors All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import EchoModel import Foundation import GRPC import NIOCore import XCTest class ClientClosedChannelTests: EchoTestCaseBase { func testUnaryOnClosedConnection() throws { let initialMetadataExpectation = self.makeInitialMetadataExpectation() let responseExpectation = self.makeResponseExpectation() let statusExpectation = self.makeStatusExpectation() self.client.channel.close().map { self.client.get(Echo_EchoRequest(text: "foo")) }.whenSuccess { get in get.initialMetadata.assertError(fulfill: initialMetadataExpectation) get.response.assertError(fulfill: responseExpectation) get.status.map { $0.code }.assertEqual(.unavailable, fulfill: statusExpectation) } self.wait( for: [initialMetadataExpectation, responseExpectation, statusExpectation], timeout: self.defaultTestTimeout ) } func testClientStreamingOnClosedConnection() throws { let initialMetadataExpectation = self.makeInitialMetadataExpectation() let responseExpectation = self.makeResponseExpectation() let statusExpectation = self.makeStatusExpectation() self.client.channel.close().map { self.client.collect() }.whenSuccess { collect in collect.initialMetadata.assertError(fulfill: initialMetadataExpectation) collect.response.assertError(fulfill: responseExpectation) collect.status.map { $0.code }.assertEqual(.unavailable, fulfill: statusExpectation) } self.wait( for: [initialMetadataExpectation, responseExpectation, statusExpectation], timeout: self.defaultTestTimeout ) } func testClientStreamingWhenConnectionIsClosedBetweenMessages() throws { let statusExpectation = self.makeStatusExpectation() let responseExpectation = self.makeResponseExpectation() let requestExpectation = self.makeRequestExpectation(expectedFulfillmentCount: 3) let collect = self.client.collect() collect.sendMessage(Echo_EchoRequest(text: "foo")).peek { requestExpectation.fulfill() }.flatMap { collect.sendMessage(Echo_EchoRequest(text: "bar")) }.peek { requestExpectation.fulfill() }.flatMap { self.client.channel.close() }.peekError { error in XCTFail("Encountered error before or during closing the connection: \(error)") }.flatMap { collect.sendMessage(Echo_EchoRequest(text: "baz")) }.assertError(fulfill: requestExpectation) collect.response.assertError(fulfill: responseExpectation) collect.status.map { $0.code }.assertEqual(.unavailable, fulfill: statusExpectation) self.wait( for: [statusExpectation, responseExpectation, requestExpectation], timeout: self.defaultTestTimeout ) } func testServerStreamingOnClosedConnection() throws { let initialMetadataExpectation = self.makeInitialMetadataExpectation() let statusExpectation = self.makeStatusExpectation() self.client.channel.close().map { self.client.expand(Echo_EchoRequest(text: "foo")) { response in XCTFail("No response expected but got: \(response)") } }.whenSuccess { expand in expand.initialMetadata.assertError(fulfill: initialMetadataExpectation) expand.status.map { $0.code }.assertEqual(.unavailable, fulfill: statusExpectation) } self.wait( for: [initialMetadataExpectation, statusExpectation], timeout: self.defaultTestTimeout ) } func testBidirectionalStreamingOnClosedConnection() throws { let initialMetadataExpectation = self.makeInitialMetadataExpectation() let statusExpectation = self.makeStatusExpectation() self.client.channel.close().map { self.client.update { response in XCTFail("No response expected but got: \(response)") } }.whenSuccess { update in update.initialMetadata.assertError(fulfill: initialMetadataExpectation) update.status.map { $0.code }.assertEqual(.unavailable, fulfill: statusExpectation) } self.wait( for: [initialMetadataExpectation, statusExpectation], timeout: self.defaultTestTimeout ) } func testBidirectionalStreamingWhenConnectionIsClosedBetweenMessages() throws { let statusExpectation = self.makeStatusExpectation() let requestExpectation = self.makeRequestExpectation(expectedFulfillmentCount: 3) // We can't make any assertions about the number of responses we will receive before closing // the connection; just ignore all responses. let update = self.client.update { _ in } update.sendMessage(Echo_EchoRequest(text: "foo")).peek { requestExpectation.fulfill() }.flatMap { update.sendMessage(Echo_EchoRequest(text: "bar")) }.peek { requestExpectation.fulfill() }.flatMap { self.client.channel.close() }.peekError { error in XCTFail("Encountered error before or during closing the connection: \(error)") }.flatMap { update.sendMessage(Echo_EchoRequest(text: "baz")) }.assertError(fulfill: requestExpectation) update.status.map { $0.code }.assertEqual(.unavailable, fulfill: statusExpectation) self.wait(for: [statusExpectation, requestExpectation], timeout: self.defaultTestTimeout) } func testBidirectionalStreamingWithNoPromiseWhenConnectionIsClosedBetweenMessages() throws { let statusExpectation = self.makeStatusExpectation() let update = self.client.update { response in XCTFail("No response expected but got: \(response)") } update.sendMessage(.with { $0.text = "0" }).flatMap { self.client.channel.close() }.whenSuccess { update.sendMessage(.with { $0.text = "1" }, promise: nil) } update.status.map { $0.code }.assertEqual(.unavailable, fulfill: statusExpectation) self.wait(for: [statusExpectation], timeout: self.defaultTestTimeout) } }
apache-2.0
5be10b6cb95051e5af364605ba6906b4
36.331395
96
0.73026
4.656273
false
true
false
false
yoshinorisano/RxSwift
RxTests/RxSwiftTests/TestImplementations/Schedulers/VirtualTimeSchedulerBase.swift
11
4512
// // VirtualTimeSchedulerBase.swift // Rx // // Created by Krunoslav Zaher on 2/14/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation import RxSwift protocol ScheduledItemProtocol : Cancelable { var time: Int { get } func invoke() } class ScheduledItem<T> : ScheduledItemProtocol { typealias Action = T -> Disposable let action: Action let state: T let time: Int var disposed: Bool { get { return disposable.disposed } } var disposable = SingleAssignmentDisposable() init(action: Action, state: T, time: Int) { self.action = action self.state = state self.time = time } func invoke() { self.disposable.disposable = action(state) } func dispose() { self.disposable.dispose() } } class VirtualTimeSchedulerBase : SchedulerType, CustomStringConvertible { typealias TimeInterval = Int typealias Time = Int var clock : Time var enabled : Bool var now: Time { get { return self.clock } } var description: String { get { return self.schedulerQueue.description } } private var schedulerQueue : [ScheduledItemProtocol] = [] init(initialClock: Time) { self.clock = initialClock self.enabled = false } func schedule<StateType>(state: StateType, action: StateType -> Disposable) -> Disposable { return self.scheduleRelative(state, dueTime: 0) { a in return action(a) } } func scheduleRelative<StateType>(state: StateType, dueTime: Int, action: StateType -> Disposable) -> Disposable { return schedule(state, time: now + dueTime, action: action) } func schedule<StateType>(state: StateType, time: Int, action: StateType -> Disposable) -> Disposable { let compositeDisposable = CompositeDisposable() let scheduleTime: Int if time <= self.now { scheduleTime = self.now + 1 } else { scheduleTime = time } let item = ScheduledItem(action: action, state: state, time: scheduleTime) schedulerQueue.append(item) compositeDisposable.addDisposable(item) return compositeDisposable } func schedulePeriodic<StateType>(state: StateType, startAfter: TimeInterval, period: TimeInterval, action: (StateType) -> StateType) -> Disposable { let compositeDisposable = CompositeDisposable() let scheduleTime: Int if startAfter <= 0 { scheduleTime = self.now + 1 } else { scheduleTime = self.now + startAfter } let item = ScheduledItem(action: { [unowned self] state in if compositeDisposable.disposed { return NopDisposable.instance } let nextState = action(state) return self.schedulePeriodic(nextState, startAfter: period, period: period, action: action) }, state: state, time: scheduleTime) schedulerQueue.append(item) compositeDisposable.addDisposable(item) return compositeDisposable } func start() { if !enabled { enabled = true repeat { if let next = getNext() { if next.disposed { continue } if next.time > self.now { self.clock = next.time } next.invoke() } else { enabled = false; } } while enabled } } func getNext() -> ScheduledItemProtocol? { var minDate = Time.max var minElement : ScheduledItemProtocol? = nil var minIndex = -1 var index = 0 for item in self.schedulerQueue { if item.time < minDate { minDate = item.time minElement = item minIndex = index } index++ } if minElement != nil { self.schedulerQueue.removeAtIndex(minIndex) } return minElement } }
mit
3411f13e29cc717306a8f7b5f6a730cd
24.353933
152
0.531693
5.352313
false
false
false
false
KrakenDev/PrediKit
Sources/Protocols/Reflectable.swift
1
2142
// // Reflectable.swift // PrediKit // // Created by Hector Matos on 5/30/16. // // import Foundation /** Used to query the property list of the conforming class. PrediKit uses this protocol to determine if the property you are specifying in the creation of a predicate actually exists in the conforming class. If it doesn't, PrediKit will print a warning to the console. All `NSObject`s conform to this protocol through a public extension declared in PrediKit. */ public protocol Reflectable: class { /** Must implement this protocol in order to take advantage of PrediKit's property warning console print behavior. - Returns: An `Array` of `Selector`s. These can just be the strings that equal the names of the properties in your class. */ static func properties() -> [Selector] } /** PrediKit is best used with instances of CoreData's `NSManagedObject`. Since each `NSManagedObject` is an `NSObject`, PrediKit's `NSPredicate` creation works out of the box for all of your `NSManagedObject` subclasses. */ private var reflectedClasses: [String : [Selector]] = [:] extension NSObject: Reflectable { /** Uses the Objective-C Runtime to determine the list of properties in an NSObject subclass. - Returns: An `Array` of `Selector`s whose string values are equal to the names of each property in the NSObject subclass. */ public static func properties() -> [Selector] { guard let savedPropertyList = reflectedClasses[String(describing: self)] else { var count: UInt32 = 0 let properties = class_copyPropertyList(self, &count) var propertyNames: [Selector] = [] for i in 0..<Int(count) { if let currentProperty = properties?[i], let propertyName = String(validatingUTF8: property_getName(currentProperty)) { propertyNames.append(Selector(propertyName)) } } free(properties) reflectedClasses[String(describing: self)] = propertyNames return propertyNames } return savedPropertyList } }
mit
99d75090a9fcfa1a9a1a7e8221845b80
40.192308
266
0.675537
4.636364
false
false
false
false
KosyanMedia/Aviasales-iOS-SDK
AviasalesSDKTemplate/Source/HotelsSource/HotelDetails/TableView/TableSection.swift
1
1237
class TableSection: TableSectionProtocol { var items: [TableItem] = [] var name: String? init(name: String?, items: [TableItem]) { self.name = name self.items = items } func headerHeight() -> CGFloat { let hasTitle = !(name?.isEmpty ?? true) return HLGroupedTableHeaderView.preferredHeight(hasTitle) } func headerView() -> UIView { let sectionHeaderNib = UINib(nibName: headerNibName(), bundle: nil) let views = sectionHeaderNib.instantiate(withOwner: nil, options: nil) as! [UIView] let header = views.first! as! HLGroupedTableHeaderView header.title = name return header } func headerNibName() -> String { return "HLGroupedTableHeaderView" } func numberOfRows() -> Int { return items.count } func heightForCell(_ tableView: UITableView, indexPath: IndexPath) -> CGFloat { let item = items[indexPath.row] return item.cellHeight(tableWidth: tableView.bounds.width) } func cell(_ tableView: UITableView, indexPath: IndexPath) -> UITableViewCell { let item = items[indexPath.row] return item.cell(tableView: tableView, indexPath: indexPath) } }
mit
807f290d8e3c27f377bf50e88e3e52de
27.767442
91
0.640259
4.650376
false
false
false
false
silence0201/Swift-Study
Learn/14.继承/扩展构造函数.playground/section-1.swift
1
1341
//16.5.1 值类型扩展构造函数///////////////////// struct Rectangle { var width: Double var height: Double init(width: Double, height: Double) { self.width = width self.height = height } func description() -> String { return "Rectangle" } } //值类型扩展构造函数 extension Rectangle { init(length: Double) { self.init(width: length, height: length) } } var rect = Rectangle(width: 320.0, height: 480.0) print("长方形:\(rect.width) x \(rect.height)") var square = Rectangle(length: 500.0) print("正方形:\(square.width) x \(square.height)") //16.5.1 值类型扩展构造函数///////////////////// //16.5.2 引用类型扩展构造函数 ///////////////////// class Person { var name: String var age: Int func description() -> String { return "\(name) 年龄是: \(age)" } init (name: String, age: Int) { self.name = name self.age = age } } //引用类型扩展构造函数 extension Person { convenience init (name: String) { self.init(name: name, age: 8) } } let p1 = Person(name: "关东升") print("Person1: \(p1.description())") let p2 = Person(name: "Tony", age: 28) print("Person2: \(p2.description())") //16.5.2 引用类型扩展构造函数 /////////////////////
mit
b5be67f193b6d2a0d2f7c327d8da3e65
19.741379
49
0.550291
3.277929
false
false
false
false
leizh007/HiPDA
HiPDA/HiPDA/Sections/Home/Post/UserProfile/ProfileAccountSection.swift
1
1000
// // ProfileAccountSection.swift // HiPDA // // Created by leizh007 on 2017/6/23. // Copyright © 2017年 HiPDA. All rights reserved. // import Foundation struct ProfileAccountSection: ProfileSection { var header: String? var items: [User] var isCollapsed: Bool static func createInstance(from html: String) throws -> ProfileAccountSection { let pattern = "<h1>([\\s\\S]*?)<\\/h1>[^<]*<ul>[^<]*<li>\\(UID:\\s*(\\d+)\\)<\\/li>" let result = try Regex.firstMatch(in: html, of: pattern) guard result.count == 3 && !result[1].isEmpty && !result[2].isEmpty, let uid = Int(result[2]) else { throw HtmlParserError.underlying("获取用户信息出错") } let content = try ProfileSectionType.contentText(in: result[1]) let name = ProfileSectionType.removeTrimmingWhiteSpaces(in: content) return ProfileAccountSection(header: nil, items: [User(name: name, uid: uid)], isCollapsed: false) } }
mit
17314207cc8c786f0b8fb87d58047c68
35.333333
106
0.62895
3.730038
false
false
false
false
googleprojectzero/fuzzilli
Sources/Fuzzilli/Minimization/InliningReducer.swift
1
8944
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://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. /// Attempts to inline functions at their callsite. This reducer is necessary to prevent deep nesting of functions. struct InliningReducer: Reducer { func reduce(_ code: inout Code, with helper: MinimizationHelper) { var candidates = identifyInlineableFunctions(in: code) while !candidates.isEmpty { let funcIndex = candidates.removeLast() let newCode = inline(functionAt: funcIndex, in: code) if helper.test(newCode) { code = newCode // Inlining changes the program so we need to redo our analysis. // In particular, instruction are reordered and variables are renamed. Further, there may now also be new inlining candidates, for example // if another function could previously not be inlined because it was used as argument or return value of a now inlined function). candidates = identifyInlineableFunctions(in: code) } } } /// Identifies all inlineable functions in the given code. /// Returns the indices of the start of the inlineable functions. private func identifyInlineableFunctions(in code: Code) -> [Int] { var candidates = [Variable: (callCount: Int, index: Int)]() func deleteCandidates(_ toRemove: ArraySlice<Variable>) { for f in toRemove { candidates.removeValue(forKey: f) } } // Contains the output variable of all active subroutine definitions. As some subroutines don't have outputs (e.g. class methods), entries can also be nil. var activeSubroutineDefinitions = [Variable?]() for instr in code { switch instr.op { // Currently we only inline plain functions as that guarantees that the resulting code is always valid. // Otherwise, we might for example attempt to inline an async function containing an 'await', which would not be valid. // This works fine because the ReplaceReducer will attempt to turn "special" functions into plain functions. case is BeginPlainFunction: candidates[instr.output] = (callCount: 0, index: instr.index) fallthrough case is BeginAnySubroutine: activeSubroutineDefinitions.append(instr.output) case is EndAnySubroutine: activeSubroutineDefinitions.removeLast() case is BeginClass: // TODO remove this special handling (and the asserts) once class constructors and methods are also subroutines assert(!(instr.op is BeginAnySubroutine)) activeSubroutineDefinitions.append(nil) // Currently needed as BeginClass can have inputs. Refactor this when refactoring classes. deleteCandidates(instr.inputs) case is BeginMethod: assert(!(instr.op is BeginAnySubroutine)) // This closes a subroutine and starts a new one, so is effectively a nop. break case is EndClass: activeSubroutineDefinitions.removeLast() case is CallFunction: let f = instr.input(0) if let candidate = candidates[f] { candidates[f] = (callCount: candidate.callCount + 1, index: candidate.index) } // Can't inline recursive calls. if activeSubroutineDefinitions.contains(f) { candidates.removeValue(forKey: f) } // Can't inline functions that are passed as arguments to other functions. deleteCandidates(instr.inputs.dropFirst()) case is LoadArguments: // Can't inline functions if they access their arguments. if let function = activeSubroutineDefinitions.last! { candidates.removeValue(forKey: function) } default: assert(!instr.op.contextOpened.contains(.subroutine)) assert(instr.op is Return || !(instr.op.requiredContext.contains(.subroutine))) // Can't inline functions that are used as inputs for other instructions. deleteCandidates(instr.inputs) } } return candidates.values.filter({ $0.callCount == 1}).map({ $0.index }) } /// Returns a new Code object with the specified function inlined into its callsite. /// The specified function must be called exactly once in the provided code. private func inline(functionAt index: Int, in code: Code) -> Code { assert(index < code.count) assert(code[index].op is BeginAnyFunction) var c = Code() var i = 0 // Append all code prior to the function that we're inlining. while i < index { c.append(code[i]) i += 1 } let funcDefinition = code[i] assert(funcDefinition.op is BeginAnyFunction) let function = funcDefinition.output let parameters = Array(funcDefinition.innerOutputs) i += 1 // Fast-forward to end of function definition var functionBody = [Instruction]() var depth = 0 while i < code.count { let instr = code[i] if instr.op is BeginAnyFunction { depth += 1 } if instr.op is EndAnyFunction { if depth == 0 { i += 1 break } else { depth -= 1 } } functionBody.append(instr) i += 1 } assert(i < code.count) // Search for the call of the function while i < code.count { let instr = code[i] if instr.op is CallFunction && instr.input(0) == function { break } assert(!instr.inputs.contains(function)) c.append(instr) i += 1 } assert(i < code.count) // Found it. Inline the function now let call = code[i] assert(call.op is CallFunction) // Reuse the function variable to store 'undefined' and use that for any missing arguments. let undefined = funcDefinition.output c.append(Instruction(LoadUndefined(), output: undefined)) var arguments = VariableMap<Variable>() for (i, v) in parameters.enumerated() { if call.numInputs - 1 > i { arguments[v] = call.input(i + 1) } else { arguments[v] = undefined } } // Initialize the return value to undefined. let rval = call.output c.append(Instruction(LoadUndefined(), output: rval, inputs: [])) var functionDefinitionDepth = 0 for instr in functionBody { let newInouts = instr.inouts.map { arguments[$0] ?? $0 } let newInstr = Instruction(instr.op, inouts: newInouts) // Returns (from the function being inlined) are converted to assignments to the return value. if instr.op is Return && functionDefinitionDepth == 0 { c.append(Instruction(Reassign(), inputs: [rval, newInstr.input(0)])) } else { c.append(newInstr) if instr.op is BeginAnyFunction { functionDefinitionDepth += 1 } else if instr.op is EndAnyFunction { functionDefinitionDepth -= 1 } } } // Insert a Nop to keep the code size the same across inlining, which is required by the minimizer tests. // Inlining removes the Begin + End operations and the call operation. The first two were already replaced by LoadUndefined. c.append(Instruction(Nop())) i += 1 // Copy remaining instructions while i < code.count { assert(!code[i].inputs.contains(function)) c.append(code[i]) i += 1 } // Need to renumber the variables now as they are no longer in ascending order. c.renumberVariables() // The code must now be valid. assert(c.isStaticallyValid()) return c } }
apache-2.0
b0381f5ab43ec05896340fcc714b6efe
39.470588
163
0.590004
4.93326
false
false
false
false
natecook1000/swift
test/IRGen/dllimport.swift
2
2707
// RUN: %swift -target thumbv7--windows-itanium -emit-ir -parse-as-library -parse-stdlib -module-name dllimport %s -o - -enable-source-import -I %S | %FileCheck %s -check-prefix CHECK -check-prefix CHECK-NO-OPT // RUN: %swift -target thumbv7--windows-itanium -O -emit-ir -parse-as-library -parse-stdlib -module-name dllimport -primary-file %s -o - -enable-source-import -I %S | %FileCheck %s -check-prefix CHECK -check-prefix CHECK-OPT // REQUIRES: CODEGENERATOR=ARM import dllexport public func get_ci() -> dllexport.c { return dllexport.ci } public func get_c_type() -> dllexport.c.Type { return dllexport.c.self } public class d : c { override init() { super.init() } @inline(never) func f(_ : dllexport.c) { } } struct s : p { func f() { } } func f(di : d) { di.f(get_ci()) } func blackhole<F>(_ : F) { } public func g() { blackhole({ () -> () in }) } // CHECK-NO-OPT-DAG: declare dllimport %swift.refcounted* @swift_allocObject(%swift.type*, i32, i32) // CHECK-NO-OPT-DAG: declare dllimport void @swift_deallocObject(%swift.refcounted*, i32, i32) // CHECK-NO-OPT-DAG: declare dllimport void @swift_release(%swift.refcounted*) // CHECK-NO-OPT-DAG: declare dllimport %swift.refcounted* @swift_retain(%swift.refcounted* returned) // CHECK-NO-OPT-DAG: @"$S9dllexport1cCN" = external dllimport global %swift.type // CHECK-NO-OPT-DAG: @"$S9dllexport1pMp" = external dllimport global %swift.protocol // CHECK-NO-OPT-DAG: @"$SytN" = external dllimport global %swift.full_type // CHECK-NO-OPT-DAG: @"$SBoWV" = external dllimport global i8* // CHECK-NO-OPT-DAG: declare dllimport swiftcc i8* @"$S9dllexport2ciAA1cCvau"() // CHECK-NO-OPT-DAG: declare dllimport swiftcc %swift.refcounted* @"$S9dllexport1cCfd"(%T9dllexport1cC* swiftself) // CHECK-NO-OPT-DAG: declare dllimport swiftcc %swift.metadata_response @"$S9dllexport1cCMa"(i32) // CHECK-NO-OPT-DAG: declare dllimport void @swift_deallocClassInstance(%swift.refcounted*, i32, i32) // CHECK-OPT-DAG: declare dllimport %swift.refcounted* @swift_retain(%swift.refcounted* returned) local_unnamed_addr // CHECK-OPT-DAG: @"$SBoWV" = external dllimport global i8* // CHECK-OPT-DAG: @"$S9dllexport1cCN" = external dllimport global %swift.type // CHECK-OPT-DAG: @"__imp_$S9dllexport1pMp" = external externally_initialized constant %swift.protocol* // CHECK-OPT-DAG: declare dllimport swiftcc i8* @"$S9dllexport2ciAA1cCvau"() // CHECK-OPT-DAG: declare dllimport swiftcc %swift.metadata_response @"$S9dllexport1cCMa"(i32) // CHECK-OPT-DAG: declare dllimport void @swift_deallocClassInstance(%swift.refcounted*, i32, i32) // CHECK-OPT-DAG: declare dllimport swiftcc %swift.refcounted* @"$S9dllexport1cCfd"(%T9dllexport1cC* swiftself)
apache-2.0
97786e977f5db2d3d68fed234b872857
44.881356
224
0.721832
3.188457
false
false
false
false
gouyz/GYZBaking
baking/Classes/Mine/Controller/GYZEditAddressVC.swift
1
18052
// // GYZEditAddressVC.swift // baking // 编辑/新增地址 // Created by gouyz on 2017/4/2. // Copyright © 2017年 gouyz. All rights reserved. // import UIKit import MBProgressHUD import Alamofire class GYZEditAddressVC: GYZBaseVC { /// 是否新增地址 var isAdd: Bool = false /// 性别 0男 1女 var sex: String = "0" /// 0不是默认 1默认 var isDefault: String = "1" ///经度 var longitude: Double = 0 ///纬度 var latitude: Double = 0 ///省份 var province: String = "" ///城市 var city: String = "" ///区 var area: String = "" ///定位地址街道 var district: String = "" ///地址 var address: String = "" /// 编辑时传入地址信息,新增时为nil var addressInfo: GYZAddressModel? ///定位 var locationManager: AMapLocationManager = AMapLocationManager() override func viewDidLoad() { super.viewDidLoad() navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "保存", style: .done, target: self, action: #selector(saveClick)) setupUI() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillAppear(_ animated: Bool) { if !area.isEmpty{ //选择地址返回值 addressFiled.text = area roomFiled.text = address } } /// 保存 func saveClick(){ requestUpdateAddress() } /// 定位配置 func configLocationManager(){ // 带逆地理信息的一次定位(返回坐标和地址信息) locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters // 定位超时时间,最低2s,此处设置为2s locationManager.locationTimeout = 2 // 逆地理请求超时时间,最低2s,此处设置为2s locationManager.reGeocodeTimeout = 2 locationManager.requestLocation(withReGeocode: true) { [weak self](location, regeocode, error) in if error == nil{ if regeocode != nil{ self?.province = regeocode?.province ?? "" self?.city = regeocode?.city ?? "" self?.area = regeocode?.district ?? "" let street: String = regeocode?.street ?? "" let number: String = regeocode?.number ?? "" if regeocode?.aoiName != nil{ self?.area += (regeocode?.aoiName)! }else{ self?.area += street + number } self?.addressFiled.text = (self?.province)! + (self?.city)! + (self?.area)! } self?.longitude = location!.coordinate.longitude self?.latitude = location!.coordinate.latitude }else{ MBProgressHUD.showAutoDismissHUD(message: "定位失败,请重新定位") } } } func setupUI(){ let viewBg1: UIView = UIView() viewBg1.backgroundColor = kWhiteColor view.addSubview(viewBg1) let desLab1: UILabel = UILabel() desLab1.text = "联系人" desLab1.textColor = kGaryFontColor desLab1.font = k15Font viewBg1.addSubview(desLab1) let line1: UIView = UIView() line1.backgroundColor = kGrayLineColor viewBg1.addSubview(line1) let nameLab: UILabel = UILabel() nameLab.text = "姓名:" nameLab.textColor = kBlackFontColor nameLab.font = k15Font viewBg1.addSubview(nameLab) viewBg1.addSubview(nameFiled) let line2: UIView = UIView() line2.backgroundColor = kGrayLineColor viewBg1.addSubview(line2) viewBg1.addSubview(manCheckBtn) viewBg1.addSubview(womanCheckBtn) let line3: UIView = UIView() line3.backgroundColor = kGrayLineColor viewBg1.addSubview(line3) let phoneLab: UILabel = UILabel() phoneLab.text = "电话:" phoneLab.textColor = kBlackFontColor phoneLab.font = k15Font viewBg1.addSubview(phoneLab) viewBg1.addSubview(phoneFiled) let viewBg2: UIView = UIView() viewBg2.backgroundColor = kWhiteColor view.addSubview(viewBg2) let desLab2: UILabel = UILabel() desLab2.text = "收货地址" desLab2.textColor = kGaryFontColor desLab2.font = k15Font viewBg2.addSubview(desLab2) let line4: UIView = UIView() line4.backgroundColor = kGrayLineColor viewBg2.addSubview(line4) let addressLab: UILabel = UILabel() addressLab.text = "详细地址:" addressLab.textColor = kBlackFontColor addressLab.font = k15Font viewBg2.addSubview(addressLab) viewBg2.addSubview(addressFiled) let rightImg: UIImageView = UIImageView.init(image: UIImage.init(named: "icon_right_gray")) viewBg2.addSubview(rightImg) let line5: UIView = UIView() line5.backgroundColor = kGrayLineColor viewBg2.addSubview(line5) let roomLab: UILabel = UILabel() roomLab.text = "楼号-门牌号:" roomLab.textColor = kBlackFontColor roomLab.font = k15Font viewBg2.addSubview(roomLab) viewBg2.addSubview(roomFiled) let line6: UIView = UIView() line6.backgroundColor = kGrayLineColor viewBg2.addSubview(line6) viewBg2.addSubview(defaultCheckBtn) viewBg1.snp.makeConstraints { (make) in make.top.equalTo(kMargin) make.left.right.equalTo(view) make.height.equalTo(kTitleHeight*3+30+klineWidth*3) } desLab1.snp.makeConstraints { (make) in make.left.equalTo(viewBg1).offset(kMargin) make.top.equalTo(viewBg1) make.right.equalTo(viewBg1).offset(-kMargin) make.height.equalTo(30) } line1.snp.makeConstraints { (make) in make.top.equalTo(desLab1.snp.bottom) make.left.right.equalTo(viewBg1) make.height.equalTo(klineWidth) } nameLab.snp.makeConstraints { (make) in make.left.equalTo(desLab1) make.top.equalTo(line1.snp.bottom) make.size.equalTo(CGSize.init(width: 50, height: kTitleHeight)) } nameFiled.snp.makeConstraints { (make) in make.left.equalTo(nameLab.snp.right) make.top.height.equalTo(nameLab) make.right.equalTo(desLab1) } line2.snp.makeConstraints { (make) in make.left.right.height.equalTo(line1) make.top.equalTo(nameLab.snp.bottom) } manCheckBtn.snp.makeConstraints { (make) in make.left.equalTo(nameLab) make.top.equalTo(line2.snp.bottom) make.right.equalTo(womanCheckBtn.snp.left).offset(-kMargin) make.width.equalTo(womanCheckBtn) make.height.equalTo(kTitleHeight) } womanCheckBtn.snp.makeConstraints { (make) in make.right.equalTo(nameFiled) make.top.size.equalTo(manCheckBtn) } line3.snp.makeConstraints { (make) in make.left.right.height.equalTo(line2) make.top.equalTo(manCheckBtn.snp.bottom) } phoneLab.snp.makeConstraints { (make) in make.left.size.equalTo(nameLab) make.top.equalTo(line3.snp.bottom) } phoneFiled.snp.makeConstraints { (make) in make.left.size.equalTo(nameFiled) make.top.equalTo(phoneLab) } viewBg2.snp.makeConstraints { (make) in make.left.right.equalTo(viewBg1) make.top.equalTo(viewBg1.snp.bottom).offset(kMargin) make.height.equalTo(kTitleHeight*2+30+60) } desLab2.snp.makeConstraints { (make) in make.left.equalTo(viewBg2).offset(kMargin) make.top.equalTo(viewBg2) make.right.equalTo(viewBg2).offset(-kMargin) make.height.equalTo(30) } line4.snp.makeConstraints { (make) in make.left.right.equalTo(viewBg2) make.top.equalTo(desLab2.snp.bottom) make.height.equalTo(klineWidth) } addressLab.snp.makeConstraints { (make) in make.left.equalTo(desLab2) make.top.equalTo(line4.snp.bottom) make.size.equalTo(CGSize.init(width: 80, height: kTitleHeight)) } addressFiled.snp.makeConstraints { (make) in make.top.height.equalTo(addressLab) make.left.equalTo(addressLab.snp.right) make.right.equalTo(rightImg.snp.left).offset(-5) } rightImg.snp.makeConstraints { (make) in make.right.equalTo(viewBg2).offset(-kMargin) make.top.equalTo(line4.snp.bottom).offset(12) make.size.equalTo(CGSize.init(width: 20, height: 20)) } line5.snp.makeConstraints { (make) in make.right.left.height.equalTo(line4) make.top.equalTo(addressLab.snp.bottom) } roomLab.snp.makeConstraints { (make) in make.left.height.equalTo(addressLab) make.top.equalTo(line5.snp.bottom) make.width.equalTo(100) } roomFiled.snp.makeConstraints { (make) in make.left.equalTo(roomLab.snp.right) make.top.height.equalTo(roomLab) make.right.equalTo(viewBg2).offset(-kMargin) } line6.snp.makeConstraints { (make) in make.right.left.height.equalTo(line4) make.top.equalTo(roomLab.snp.bottom) } defaultCheckBtn.snp.makeConstraints { (make) in make.left.equalTo(roomLab) make.bottom.equalTo(viewBg2).offset(-kStateHeight) make.size.equalTo(CGSize.init(width: 120, height: 30)) } if isAdd { self.title = "新增收货地址" defaultCheckBtn.isSelected = true manCheckBtn.isSelected = true } else { self.title = "编辑收货地址" nameFiled.text = addressInfo?.consignee if addressInfo?.sex == "0" { manCheckBtn.isSelected = true }else{ womanCheckBtn.isSelected = true } phoneFiled.text = addressInfo?.tel // if (addressInfo?.province?.isEmpty)!{ // addressFiled.text = addressInfo?.address // }else{ // addressFiled.text = (addressInfo?.province)! + "" + (addressInfo?.city)! + (addressInfo?.area)! // roomFiled.text = addressInfo?.address // } province = (addressInfo?.province)! city = (addressInfo?.city)! area = (addressInfo?.area)! address = (addressInfo?.address)! addressFiled.text = /*province + city +*/ area roomFiled.text = address latitude = Double.init((addressInfo?.ads_latitude)!)! longitude = Double.init((addressInfo?.ads_longitude)!)! isDefault = (addressInfo?.is_default)! sex = (addressInfo?.sex)! if isDefault == "1"{ defaultCheckBtn.isSelected = true } } } /// 姓名输入框 lazy var nameFiled : UITextField = { let textFiled = UITextField() textFiled.font = k15Font textFiled.textColor = kBlackFontColor textFiled.clearButtonMode = .whileEditing textFiled.placeholder = "请输入姓名" return textFiled }() /// 手机号输入框 lazy var phoneFiled : UITextField = { let textFiled = UITextField() textFiled.font = k15Font textFiled.textColor = kBlackFontColor textFiled.placeholder = "请输入手机号" textFiled.keyboardType = .namePhonePad return textFiled }() /// 地址输入框 lazy var addressFiled : UILabel = { let textFiled = UILabel() textFiled.font = k15Font textFiled.textColor = kBlackFontColor textFiled.text = "点击定位" textFiled.addOnClickListener(target: self, action: #selector(selectAddressClick)) return textFiled }() /// 房间号输入框 lazy var roomFiled : UITextField = { let textFiled = UITextField() textFiled.font = k15Font textFiled.textColor = kBlackFontColor textFiled.placeholder = "例 15栋甲单元201室" return textFiled }() /// 先生 lazy var manCheckBtn : UIButton = { let btn = UIButton.init(type: .custom) btn.titleLabel?.font = k15Font btn.setTitleColor(kBlackFontColor, for: .normal) btn.setTitle("先生", for: .normal) btn.setImage(UIImage.init(named: "icon_check_normal"), for: .normal) btn.setImage(UIImage.init(named: "icon_check_selected"), for: .selected) btn.addTarget(self, action: #selector(radioBtnChecked(btn:)), for: .touchUpInside) btn.tag = 101 return btn }() /// 女士 lazy var womanCheckBtn : UIButton = { let btn = UIButton.init(type: .custom) btn.titleLabel?.font = k15Font btn.setTitleColor(kBlackFontColor, for: .normal) btn.setTitle("女士", for: .normal) btn.setImage(UIImage.init(named: "icon_check_normal"), for: .normal) btn.setImage(UIImage.init(named: "icon_check_selected"), for: .selected) btn.addTarget(self, action: #selector(radioBtnChecked(btn:)), for: .touchUpInside) btn.tag = 102 return btn }() /// 设为默认地址 lazy var defaultCheckBtn : UIButton = { let btn = UIButton.init(type: .custom) btn.titleLabel?.font = k15Font btn.setTitleColor(kYellowFontColor, for: .normal) btn.setTitle("设为默认地址", for: .normal) btn.setImage(UIImage.init(named: "icon_check_normal"), for: .normal) btn.setImage(UIImage.init(named: "icon_check_selected"), for: .selected) btn.addTarget(self, action: #selector(defaultCheckBtnClick), for: .touchUpInside) return btn }() /// 设为默认地址 func defaultCheckBtnClick(){ defaultCheckBtn.isSelected = !defaultCheckBtn.isSelected if defaultCheckBtn.isSelected { isDefault = "1" }else{ isDefault = "0" } } /// 选择先生/女士 /// /// - Parameter btn: func radioBtnChecked(btn: UIButton){ let tag = btn.tag btn.isSelected = !btn.isSelected if tag == 101 {/// 先生 sex = "0" womanCheckBtn.isSelected = false } else {/// 女士 sex = "1" manCheckBtn.isSelected = false } } /// 选择地址 func goAddressVC(){ let selectAddressVC = GYZSelectAddressVC() navigationController?.pushViewController(selectAddressVC, animated: true) } /// 数据是否有效 func dataIsVailue() ->Bool{ if (nameFiled.text?.isEmpty)! { MBProgressHUD.showAutoDismissHUD(message: "请输入姓名") return false } if (phoneFiled.text?.isEmpty)! { MBProgressHUD.showAutoDismissHUD(message: "请输入电话") return false } if (addressFiled.text?.isEmpty)! { MBProgressHUD.showAutoDismissHUD(message: "请输入详细地址") return false } return true } /// 增加地址 func requestUpdateAddress(){ if !dataIsVailue() { return } weak var weakSelf = self createHUD(message: "加载中...") address = roomFiled.text! if address.isEmpty { address = "" } var params: [String : Any] = ["user_id":userDefaults.string(forKey: "userId") ?? "","consignee":nameFiled.text!,"province":province,"city":city,"area":area,"address":address,"is_default":isDefault,"ads_longitude":longitude,"ads_latitude":latitude,"sex":sex,"tel" : phoneFiled.text!] var url: String = "Address/add" if !isAdd { url = "Address/update" params["add_id"] = (addressInfo?.add_id)! } GYZNetWork.requestNetwork(url, parameters: params, success: { (response) in weakSelf?.hud?.hide(animated: true) // GYZLog(response) if response["status"].intValue == kQuestSuccessTag{//请求成功 _ = weakSelf?.navigationController?.popViewController(animated: true) } // MBProgressHUD.showAutoDismissHUD(message: response["result"]["msg"].stringValue) }, failture: { (error) in weakSelf?.hud?.hide(animated: true) GYZLog(error) }) } func selectAddressClick(){ goAddressVC() } ///MARK UITextFieldDelegate func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool { //textField变为不可编辑 // configLocationManager() if textField == addressFiled { goAddressVC() return false } // goAddressVC() return true } }
mit
80d939392cbf638578a225e64ff89d87
32.070076
290
0.56211
4.413802
false
false
false
false
stowy/LayoutKit
Sources/LayoutArrangement.swift
5
7361
// Copyright 2016 LinkedIn 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. import CoreGraphics /** The frame of a layout and the frames of its sublayouts. */ public struct LayoutArrangement { public let layout: Layout public let frame: CGRect public let sublayouts: [LayoutArrangement] public init(layout: Layout, frame: CGRect, sublayouts: [LayoutArrangement]) { self.layout = layout self.frame = frame self.sublayouts = sublayouts } /** Creates the views for the layout and adds them as subviews to the provided view. Existing subviews of the provided view will be removed. If no view is provided, then a new one is created and returned. MUST be run on the main thread. - parameter view: The layout's views will be added as subviews to this view, if provided. - parameter direction: The natural direction of the layout (default: .LeftToRight). If it does not match the user's language direction, then the layout's views will be flipped horizontally. Only provide this parameter if you want to test the flipped version of your layout, or if your layouts are declared for right-to-left languages and you want them to get flipped for left-to-right languages. - returns: The root view. If a view was provided, then the same view will be returned, otherwise, a new one will be created. */ @discardableResult public func makeViews(in view: View? = nil, direction: UserInterfaceLayoutDirection = .leftToRight) -> View { return makeViews(in: view, direction: direction, prepareAnimation: false) } /** Prepares the view to be animated to this arrangement. Call `prepareAnimation(for:direction)` before the animation block. Call the returned animation's `apply()` method inside the animation block. ``` let animation = nextLayout.arrangement().prepareAnimation(for: rootView, direction: .RightToLeft) View.animateWithDuration(5.0, animations: { animation.apply() }) ``` Subviews are reparented for the new arrangement, if necessary, but frames are adjusted so locations don't change. No frames or configurations of the new arrangement are applied until `apply()` is called on the returned animation object. MUST be run on the main thread. */ public func prepareAnimation(for view: View, direction: UserInterfaceLayoutDirection = .leftToRight) -> Animation { makeViews(in: view, direction: direction, prepareAnimation: true) return Animation(arrangement: self, rootView: view, direction: direction) } /** Helper function for `makeViews(in:direction:)` and `prepareAnimation(for:direction:)`. See the documentation for those two functions. */ @discardableResult private func makeViews(in view: View? = nil, direction: UserInterfaceLayoutDirection, prepareAnimation: Bool) -> View { let recycler = ViewRecycler(rootView: view) let views = makeSubviews(from: recycler, prepareAnimation: prepareAnimation) let rootView: View if let view = view { for subview in views { view.addSubview(subview, maintainCoordinates: prepareAnimation) } rootView = view } else if let view = views.first, views.count == 1 { // We have a single view so it is our root view. rootView = view } else { // We have multiple views so create a root view. rootView = View(frame: frame) for subview in views { if !prepareAnimation { // Unapply the offset that was applied in makeSubviews() subview.frame = subview.frame.offsetBy(dx: -frame.origin.x, dy: -frame.origin.y) } rootView.addSubview(subview) } } recycler.purgeViews() if !prepareAnimation { // Horizontally flip the view frames if direction does not match the root view's language direction. if rootView.userInterfaceLayoutDirection != direction { flipSubviewsHorizontally(rootView) } } return rootView } /// Flips the right and left edges of the view's subviews. private func flipSubviewsHorizontally(_ view: View) { for subview in view.subviews { subview.frame.origin.x = view.frame.width - subview.frame.maxX flipSubviewsHorizontally(subview) } } /// Returns the views for the layout and all of its sublayouts. private func makeSubviews(from recycler: ViewRecycler, prepareAnimation: Bool) -> [View] { let subviews = sublayouts.flatMap({ (sublayout: LayoutArrangement) -> [View] in return sublayout.makeSubviews(from: recycler, prepareAnimation: prepareAnimation) }) // If we are preparing an animation, then we don't want to update frames or configure views. if layout.needsView, let view = recycler.makeOrRecycleView(havingViewReuseId: layout.viewReuseId, viewProvider: layout.makeView) { if !prepareAnimation { view.frame = frame layout.configure(baseTypeView: view) } for subview in subviews { // If a view gets reparented and we are preparing an animation, then // make sure that its absolute position on the screen does not change. view.addSubview(subview, maintainCoordinates: prepareAnimation) } return [view] } else { if !prepareAnimation { for subview in subviews { subview.frame = subview.frame.offsetBy(dx: frame.origin.x, dy: frame.origin.y) } } return subviews } } } extension LayoutArrangement: CustomDebugStringConvertible { public var debugDescription: String { return _debugDescription(0) } private func _debugDescription(_ indent: Int) -> String { let t = String(repeatElement(" ", count: indent * 2)) let sublayoutsString = sublayouts.map { $0._debugDescription(indent + 1) }.joined() let layoutName = String(describing: layout).components(separatedBy: ".").last! return"\(t)\(layoutName): \(frame)\n\(sublayoutsString)" } } extension View { /** Similar to `addSubview()` except if `maintainCoordinates` is true, then the view's frame will be adjusted so that its absolute position on the screen does not change. */ fileprivate func addSubview(_ view: View, maintainCoordinates: Bool) { if maintainCoordinates { let frame = view.convertToAbsoluteCoordinates(view.frame) addSubview(view) view.frame = view.convertFromAbsoluteCoordinates(frame) } else { addSubview(view) } } }
apache-2.0
92986800df3e94d5dbcbe2ce46bef0bc
41.062857
138
0.653444
4.820563
false
false
false
false
jjochen/photostickers
Tests/StickerTests.swift
1
1548
// // StickerTests.swift // PhotoStickers // // Created by Jochen Pfeiffer on 30/01/2017. // Copyright © 2017 Jochen Pfeiffer. All rights reserved. // import Nimble @testable import PhotoStickers import Quick class StickerTests: QuickSpec { override func spec() { it("is not nil") { let sticker = Sticker() expect(sticker).notTo(beNil()) } it("is equal to ohter sticker when it has the same uuid") { let sticker1 = Sticker() let sticker2 = Sticker() expect(sticker1 == sticker2).to(beTrue()) let uuid = "uuid" sticker1.uuid = uuid expect(sticker1 == sticker2).to(beFalse()) sticker2.uuid = uuid expect(sticker1 == sticker2).to(beTrue()) sticker1.cropBounds = CGRect(x: 1, y: 2, width: 3, height: 4) expect(sticker1 == sticker2).to(beTrue()) } it("sets the correct bounds") { let bounds = CGRect(x: 11, y: 22, width: 33, height: 44) let sticker = Sticker() sticker.cropBounds = bounds expect(sticker.cropBoundsX) == Double(bounds.minX) expect(sticker.cropBoundsY) == Double(bounds.minY) expect(sticker.cropBoundsWidth) == Double(bounds.width) expect(sticker.cropBoundsHeight) == Double(bounds.height) } it("has a uuid on creation") { let sticker = Sticker.newSticker() expect(sticker.uuid).notTo(beNil()) } } }
mit
2f00311a46f708e8cba54c11e8246940
28.188679
73
0.566904
4.136364
false
true
false
false
QueryKit/QueryKit
Sources/QueryKit/QuerySet.swift
1
9641
import Foundation import CoreData /// Represents a lazy database lookup for a set of objects. open class QuerySet<ModelType : NSManagedObject> : Equatable { /// Returns the managed object context that will be used to execute any requests. public let context: NSManagedObjectContext /// Returns the name of the entity the request is configured to fetch. public let entityName: String /// Returns the sort descriptors of the receiver. public let sortDescriptors: [NSSortDescriptor] /// Returns the predicate of the receiver. public let predicate: NSPredicate? /// The range of the query, allows you to offset and limit a query public let range: Range<Int>? // MARK: Initialization public init(_ context:NSManagedObjectContext, _ entityName:String) { self.context = context self.entityName = entityName self.sortDescriptors = [] self.predicate = nil self.range = nil } /// Create a queryset from another queryset with a different sortdescriptor predicate and range public init(queryset:QuerySet<ModelType>, sortDescriptors:[NSSortDescriptor]?, predicate:NSPredicate?, range: Range<Int>?) { self.context = queryset.context self.entityName = queryset.entityName self.sortDescriptors = sortDescriptors ?? [] self.predicate = predicate self.range = range } } /// Methods which return a new queryset extension QuerySet { // MARK: Sorting /// Returns a new QuerySet containing objects ordered by the given sort descriptor. public func orderBy(_ sortDescriptor:NSSortDescriptor) -> QuerySet<ModelType> { return orderBy([sortDescriptor]) } /// Returns a new QuerySet containing objects ordered by the given sort descriptors. public func orderBy(_ sortDescriptors:[NSSortDescriptor]) -> QuerySet<ModelType> { return QuerySet(queryset:self, sortDescriptors:sortDescriptors, predicate:predicate, range:range) } /// Reverses the ordering of the QuerySet public func reverse() -> QuerySet<ModelType> { func reverseSortDescriptor(_ sortDescriptor:NSSortDescriptor) -> NSSortDescriptor { return NSSortDescriptor(key: sortDescriptor.key!, ascending: !sortDescriptor.ascending) } return QuerySet(queryset:self, sortDescriptors:sortDescriptors.map(reverseSortDescriptor), predicate:predicate, range:range) } // MARK: Type-safe Sorting /// Returns a new QuerySet containing objects ordered by the given key path. public func orderBy<T>(_ keyPath: KeyPath<ModelType, T>, ascending: Bool) -> QuerySet<ModelType> { return orderBy(NSSortDescriptor(key: (keyPath as AnyKeyPath)._kvcKeyPathString!, ascending: ascending)) } /// Returns a new QuerySet containing objects ordered by the given sort descriptor. public func orderBy(_ closure:((ModelType.Type) -> (SortDescriptor<ModelType>))) -> QuerySet<ModelType> { return orderBy(closure(ModelType.self).sortDescriptor) } /// Returns a new QuerySet containing objects ordered by the given sort descriptors. public func orderBy(_ closure:((ModelType.Type) -> ([SortDescriptor<ModelType>]))) -> QuerySet<ModelType> { return orderBy(closure(ModelType.self).map { $0.sortDescriptor }) } // MARK: Filtering /// Returns a new QuerySet containing objects that match the given predicate. public func filter(_ predicate: Predicate<ModelType>) -> QuerySet<ModelType> { return filter(predicate.predicate) } /// Returns a new QuerySet containing objects that match the given predicate. public func filter(_ predicate:NSPredicate) -> QuerySet<ModelType> { var futurePredicate = predicate if let existingPredicate = self.predicate { futurePredicate = NSCompoundPredicate(type: NSCompoundPredicate.LogicalType.and, subpredicates: [existingPredicate, predicate]) } return QuerySet(queryset:self, sortDescriptors:sortDescriptors, predicate:futurePredicate, range:range) } /// Returns a new QuerySet containing objects that match the given predicates. public func filter(_ predicates:[NSPredicate]) -> QuerySet<ModelType> { let newPredicate = NSCompoundPredicate(type: NSCompoundPredicate.LogicalType.and, subpredicates: predicates) return filter(newPredicate) } /// Returns a new QuerySet containing objects that exclude the given predicate. public func exclude(_ predicate: Predicate<ModelType>) -> QuerySet<ModelType> { return exclude(predicate.predicate) } /// Returns a new QuerySet containing objects that exclude the given predicate. public func exclude(_ predicate:NSPredicate) -> QuerySet<ModelType> { let excludePredicate = NSCompoundPredicate(type: NSCompoundPredicate.LogicalType.not, subpredicates: [predicate]) return filter(excludePredicate) } /// Returns a new QuerySet containing objects that exclude the given predicates. public func exclude(_ predicates:[NSPredicate]) -> QuerySet<ModelType> { let excludePredicate = NSCompoundPredicate(type: NSCompoundPredicate.LogicalType.and, subpredicates: predicates) return exclude(excludePredicate) } // MARK: Type-safe filtering /// Returns a new QuerySet containing objects that match the given predicate. @available(*, deprecated, renamed: "filter(_:)", message: "Replaced by KeyPath filtering https://git.io/Jv2v3") public func filter(_ closure:((ModelType.Type) -> (Predicate<ModelType>))) -> QuerySet<ModelType> { return filter(closure(ModelType.self).predicate) } /// Returns a new QuerySet containing objects that exclude the given predicate. @available(*, deprecated, renamed: "exclude(_:)", message: "Replaced by KeyPath filtering https://git.io/Jv2v3") public func exclude(_ closure:((ModelType.Type) -> (Predicate<ModelType>))) -> QuerySet<ModelType> { return exclude(closure(ModelType.self).predicate) } /// Returns a new QuerySet containing objects that match the given predicatess. @available(*, deprecated, renamed: "filter(_:)", message: "Replaced by KeyPath filtering https://git.io/Jv2v3") public func filter(_ closures:[((ModelType.Type) -> (Predicate<ModelType>))]) -> QuerySet<ModelType> { return filter(closures.map { $0(ModelType.self).predicate }) } /// Returns a new QuerySet containing objects that exclude the given predicates. @available(*, deprecated, renamed: "exclude(_:)", message: "Replaced by KeyPath filtering https://git.io/Jv2v3") public func exclude(_ closures:[((ModelType.Type) -> (Predicate<ModelType>))]) -> QuerySet<ModelType> { return exclude(closures.map { $0(ModelType.self).predicate }) } } /// Functions for evauluating a QuerySet extension QuerySet { // MARK: Subscripting /// Returns the object at the specified index. public func object(_ index: Int) throws -> ModelType? { let request = fetchRequest request.fetchOffset = index request.fetchLimit = 1 let items = try context.fetch(request) return items.first } public subscript(range: ClosedRange<Int>) -> QuerySet<ModelType> { get { return self[Range(range)] } } public subscript(range: Range<Int>) -> QuerySet<ModelType> { get { var fullRange = range if let currentRange = self.range { fullRange = ((currentRange.lowerBound + range.lowerBound) ..< range.upperBound) } return QuerySet(queryset:self, sortDescriptors:sortDescriptors, predicate:predicate, range:fullRange) } } // Mark: Getters /// Returns the first object in the QuerySet public func first() throws -> ModelType? { return try self.object(0) } /// Returns the last object in the QuerySet public func last() throws -> ModelType? { return try reverse().first() } // MARK: Conversion /// Returns a fetch request equivilent to the QuerySet public var fetchRequest: NSFetchRequest<ModelType> { let request = NSFetchRequest<ModelType>(entityName: entityName) request.predicate = predicate request.sortDescriptors = sortDescriptors if let range = range { request.fetchOffset = range.lowerBound request.fetchLimit = range.upperBound - range.lowerBound } return request } /// Returns an array of all objects matching the QuerySet public func array() throws -> [ModelType] { return try context.fetch(fetchRequest) } // MARK: Count /// Returns the count of objects matching the QuerySet. public func count() throws -> Int { return try context.count(for: fetchRequest) } // MARK: Exists /** Returns true if the QuerySet contains any results, and false if not. :note: Returns nil if the operation could not be completed. */ public func exists() throws -> Bool { let fetchRequest = self.fetchRequest fetchRequest.fetchLimit = 1 let result = try context.count(for: fetchRequest) return result != 0 } // MARK: Deletion /// Deletes all the objects matching the QuerySet. public func delete() throws -> Int { let objects = try array() let deletedCount = objects.count for object in objects { context.delete(object) } return deletedCount } } /// Returns true if the two given querysets are equivilent public func == <ModelType : NSManagedObject>(lhs: QuerySet<ModelType>, rhs: QuerySet<ModelType>) -> Bool { let context = lhs.context == rhs.context let entityName = lhs.entityName == rhs.entityName let sortDescriptors = lhs.sortDescriptors == rhs.sortDescriptors let predicate = lhs.predicate == rhs.predicate let startIndex = lhs.range?.lowerBound == rhs.range?.lowerBound let endIndex = lhs.range?.upperBound == rhs.range?.upperBound return context && entityName && sortDescriptors && predicate && startIndex && endIndex }
bsd-2-clause
15682df3c2217c9dafd9c99e5805f089
36.513619
133
0.725236
4.777502
false
false
false
false