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
noppoMan/aws-sdk-swift
Sources/Soto/Services/CognitoIdentity/CognitoIdentity_Error.swift
1
4391
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import SotoCore /// Error enum for CognitoIdentity public struct CognitoIdentityErrorType: AWSErrorType { enum Code: String { case concurrentModificationException = "ConcurrentModificationException" case developerUserAlreadyRegisteredException = "DeveloperUserAlreadyRegisteredException" case externalServiceException = "ExternalServiceException" case internalErrorException = "InternalErrorException" case invalidIdentityPoolConfigurationException = "InvalidIdentityPoolConfigurationException" case invalidParameterException = "InvalidParameterException" case limitExceededException = "LimitExceededException" case notAuthorizedException = "NotAuthorizedException" case resourceConflictException = "ResourceConflictException" case resourceNotFoundException = "ResourceNotFoundException" case tooManyRequestsException = "TooManyRequestsException" } private let error: Code public let context: AWSErrorContext? /// initialize CognitoIdentity public init?(errorCode: String, context: AWSErrorContext) { guard let error = Code(rawValue: errorCode) else { return nil } self.error = error self.context = context } internal init(_ error: Code) { self.error = error self.context = nil } /// return error code string public var errorCode: String { self.error.rawValue } /// Thrown if there are parallel requests to modify a resource. public static var concurrentModificationException: Self { .init(.concurrentModificationException) } /// The provided developer user identifier is already registered with Cognito under a different identity ID. public static var developerUserAlreadyRegisteredException: Self { .init(.developerUserAlreadyRegisteredException) } /// An exception thrown when a dependent service such as Facebook or Twitter is not responding public static var externalServiceException: Self { .init(.externalServiceException) } /// Thrown when the service encounters an error during processing the request. public static var internalErrorException: Self { .init(.internalErrorException) } /// Thrown if the identity pool has no role associated for the given auth type (auth/unauth) or if the AssumeRole fails. public static var invalidIdentityPoolConfigurationException: Self { .init(.invalidIdentityPoolConfigurationException) } /// Thrown for missing or bad input parameter(s). public static var invalidParameterException: Self { .init(.invalidParameterException) } /// Thrown when the total number of user pools has exceeded a preset limit. public static var limitExceededException: Self { .init(.limitExceededException) } /// Thrown when a user is not authorized to access the requested resource. public static var notAuthorizedException: Self { .init(.notAuthorizedException) } /// Thrown when a user tries to use a login which is already linked to another account. public static var resourceConflictException: Self { .init(.resourceConflictException) } /// Thrown when the requested resource (for example, a dataset or record) does not exist. public static var resourceNotFoundException: Self { .init(.resourceNotFoundException) } /// Thrown when a request is throttled. public static var tooManyRequestsException: Self { .init(.tooManyRequestsException) } } extension CognitoIdentityErrorType: Equatable { public static func == (lhs: CognitoIdentityErrorType, rhs: CognitoIdentityErrorType) -> Bool { lhs.error == rhs.error } } extension CognitoIdentityErrorType: CustomStringConvertible { public var description: String { return "\(self.error.rawValue): \(self.message ?? "")" } }
apache-2.0
997fccc7f8b6cd1f85a1d5e928b07478
49.471264
124
0.721931
5.454658
false
false
false
false
SandcastleApps/partyup
Pods/SwiftDate/Sources/SwiftDate/DateFormatter.swift
1
18055
// // SwiftDate, an handy tool to manage date and timezones in swift // Created by: Daniele Margutti // Main contributors: Jeroen Houtzager // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation // MARK: - DateFormatter Supporting Data - // swiftlint:disable file_length /** Constants for specifying how to spell out unit names. - Positional A style that uses the position of a unit to identify its value and commonly used for time values where components are separated by colons (“1:10:00”) - Abbreviated The abbreviated style represents the shortest spelling for unit values (ie. “1h 10m”) - Short A style that uses the short spelling for units (ie. “1hr 10min”) - Full A style that spells out the units fully (ie. “1 hour, 10 minutes”) - Colloquial For some relevant intervals this style print out a more colloquial string representation (ie last moth */ public enum DateFormatterComponentsStyle { case Positional case Abbreviated case Short case Full case Colloquial public var localizedCode: String { switch self { case .Positional: return "positional" case .Abbreviated: return "abbreviated" case .Short: return "short" case .Full: return "full" case .Colloquial: return "colloquial" } } internal func toNSDateFormatterStyle() -> NSDateComponentsFormatterUnitsStyle? { switch self { case .Positional: return .Positional case .Abbreviated: return .Abbreviated case .Short: return .Short case .Full: return .Full case .Colloquial: return nil } } } /** * Define how the formatter must work when values contain zeroes. */ public struct DateZeroBehavior: OptionSetType { public let rawValue: Int public init(rawValue: Int) { self.rawValue = rawValue } // None, it does not remove components with zero values static let None = DateZeroBehavior(rawValue:1) // Units whose values are 0 are dropped starting at the beginning of the sequence until the // first non-zero component static var DropLeading = DateZeroBehavior(rawValue:3) // Units whose values are 0 are dropped from anywhere in the middle of a sequence. static var DropMiddle = DateZeroBehavior(rawValue:4) // Units whose value is 0 are dropped starting at the end of the sequence back to the first // non-zero component static var DropTrailing = DateZeroBehavior(rawValue:5) // This behavior drops all units whose values are 0. For example, when days, hours, // minutes, and seconds are allowed, the abbreviated version of one hour is displayed as “1h”. static var DropAll: DateZeroBehavior = [DropLeading, DropMiddle, DropTrailing] } //MARK: - DateFormatter Class - /// The DateFormatter class is used to get a string representation of a time interval between two /// dates or a relative representation of a date public class DateFormatter { /// Described the style in which each unit will be printed out. Default is `.Full` public var unitsStyle: DateFormatterComponentsStyle = .Full /// This describe the separator string between each component when you print data in non /// colloquial format. Default is `,` public var unitsSeparator: String = "," /// Tell what kind of time units should be part of the output. Allowed values are a subset of /// the NSCalendarUnit mask /// .Year, .Month, .Day, .Hour, .Minute, .Second are supported (default values enable all of /// them) public var allowedUnits: NSCalendarUnit = [.Year, .Month, .Day, .Hour, .Minute, .Second] /// Number of units to print from the higher to the lower. Default is unlimited, all values /// could be part of the output public var maxUnitCount: Int? /// How the formatter threat zero components. Default implementation drop all zero values from /// the output string public var zeroBehavior: DateZeroBehavior = .DropAll /// If .unitStyle is .Colloquial you can include relevant date/time formatting to append after /// the colloquial representation /// For years it may print the month, for weeks or days it may print the hour:minute of the /// date. Default is false. public var includeRelevantTime: Bool = false /// For interval less than 5 minutes if this value is true the equivalent of 'just now' is /// printed in the output string public var fallbackToNow: Bool = false /// This is the bundle where the localized data is placed private lazy var bundle: NSBundle? = { var frameworkBundle = NSBundle(identifier: "com.danielemagutti.SwiftDate") if frameworkBundle == nil { frameworkBundle = NSBundle.mainBundle() } if frameworkBundle == nil { return nil } let path = NSURL(fileURLWithPath: frameworkBundle!.resourcePath!).URLByAppendingPathComponent("SwiftDate.bundle") let bundle = NSBundle(URL: path!) return bundle }() public init(unitsStyle style: DateFormatterComponentsStyle = .Full) { self.unitsStyle = style } /** Print the string representation of the interval amount (in seconds) since/to now. It supports both negative and positive values. - parameter interval: interval of time in seconds - returns: output string representation of the interval */ public func toString(interval: NSTimeInterval) -> String? { let region_utc = Region(timeZoneName: TimeZoneName.Gmt) let fromDate = DateInRegion(absoluteTime: NSDate(timeIntervalSinceNow: -interval), region: region_utc) let toDate = DateInRegion(absoluteTime: NSDate(), region: region_utc) return self.toString(fromDate: fromDate, toDate: toDate) } /** Print the representation of the interval between two dates. - parameter fromDate: source date - parameter toDate: end date - returns: output string representation of the interval */ public func toString(fromDate fromDate: DateInRegion, toDate: DateInRegion) -> String? { guard fromDate.calendar.calendarIdentifier == toDate.calendar.calendarIdentifier else { return nil } if unitsStyle == .Colloquial { return toColloquialString(fromDate: fromDate, toDate: toDate) } else { return toComponentsString(fromDate: fromDate, toDate: toDate) } } //MARK: Private Methods /** This method output the colloquial representation of the interval between two dates. You will not call it from the extern. - parameter fromDate: source date - parameter toDate: end date - returns: output string representation of the interval */ // swiftlint:disable:next function_body_length private func toColloquialString(fromDate fromDate: DateInRegion, toDate: DateInRegion) -> String? { // Get the components of the date. Date must have the same parent calendar type in // order to be compared let cal = fromDate.calendar let opt = NSCalendarOptions(rawValue: 0) let components = cal.components(allowedUnits, fromDate: fromDate.absoluteTime, toDate: toDate.absoluteTime, options: opt) let isFuture = fromDate > toDate if components.year != 0 { // Years difference let value = abs(components.year) let relevant_str = relevantTimeForUnit(.Year, date: fromDate, value: value) return colloquialString(.Year, isFuture: isFuture, value: value, relevantStr: relevant_str, args: fromDate.year) } if components.month != 0 { // Months difference let value = abs(components.month) let relevant_str = relevantTimeForUnit(.Month, date: fromDate, value: value) return colloquialString(.Month, isFuture: isFuture, value: value, relevantStr: relevant_str, args: value) } // Weeks difference let daysInWeek = fromDate.calendar.rangeOfUnit(.Day, inUnit: .WeekOfMonth, forDate: fromDate.absoluteTime).length if components.day >= daysInWeek { let weeksNumber = abs(components.day / daysInWeek) let relevant_str = relevantTimeForUnit(.WeekOfYear, date: fromDate, value: weeksNumber) return colloquialString(.WeekOfYear, isFuture: isFuture, value: weeksNumber, relevantStr: relevant_str, args: weeksNumber) } if components.day != 0 { // Days difference let value = abs(components.day) let relevant_str = relevantTimeForUnit(.Day, date: fromDate, value: value) return colloquialString(.Day, isFuture: isFuture, value: value, relevantStr: relevant_str, args: value) } if components.hour != 0 { // Hours difference let value = abs(components.hour) let relevant_str = relevantTimeForUnit(.Hour, date: fromDate, value: value) return colloquialString(.Hour, isFuture: isFuture, value: value, relevantStr: relevant_str, args: value) } if components.minute != 0 { // Minutes difference let value = abs(components.minute) let relevant_str = relevantTimeForUnit(.Minute, date: fromDate, value: value) if self.fallbackToNow == true && components.minute < 5 { // Less than 5 minutes ago is 'just now' return sd_localizedString("colloquial_now", arguments: []) } return colloquialString(.Minute, isFuture: isFuture, value: value, relevantStr: relevant_str, args: value) } if components.second != 0 { // Seconds difference return sd_localizedString("colloquial_now", arguments: []) } // Fallback to components output return self.toComponentsString(fromDate: fromDate, toDate: toDate) } /** String representation between two dates by printing difference in term of each time unit component - parameter fromDate: from date - parameter toDate: to date - returns: representation string */ private func toComponentsString(fromDate fDate: DateInRegion, toDate tDate: DateInRegion) -> String? { let cal = fDate.calendar let cmps = cal.components(allowedUnits, fromDate: fDate.absoluteTime, toDate: tDate.absoluteTime, options: NSCalendarOptions(rawValue: 0)) let unitFlags: [NSCalendarUnit] = [.Year, .Month, .Day, .Hour, .Minute, .Second] var outputUnits: [String] = [] var nonZeroUnitFound: Int = 0 var isNegative: Bool? = nil for unit in unitFlags { let unitValue = cmps.valueForComponent(unit) if isNegative == nil && unitValue < 0 { isNegative = true } // Drop zero (all, leading, middle) let shouldDropZero = (unitValue == 0 && (zeroBehavior == .DropAll || zeroBehavior == .DropLeading && nonZeroUnitFound == 0 || zeroBehavior == .DropMiddle)) if shouldDropZero == false { let cmp = NSDateComponents() cmp.setValue( abs(unitValue), forComponent: unit) let str = NSDateComponentsFormatter.localizedStringFromDateComponents(cmp, unitsStyle: unitsStyle.toNSDateFormatterStyle()!)! outputUnits.append(str) } nonZeroUnitFound += (unitValue != 0 ? 1 : 0) // limit the number of values to show if maxUnitCount != nil && nonZeroUnitFound == maxUnitCount! { break } } return (isNegative == true ? "-" : "") + outputUnits.joinWithSeparator(self.unitsSeparator) } /** Return the colloquial string representation of a time unit - parameters: - unit: unit of time - fromDate: target date to use - value: value of the unit - relevantStr: relevant time string to append at the end of the ouput - args: arguments to add into output string placeholders - returns: value */ private func colloquialString(unit: NSCalendarUnit, isFuture: Bool, value: Int, relevantStr: String?, args: CVarArgType...) -> String { guard let bundle = self.bundle else { return "" } let unit_id = unit.localizedCode(value) let locale_time_id = (isFuture ? "f" : "p") let identifier = "colloquial_\(locale_time_id)_\(unit_id)" let localized_date = withVaList(args) { (pointer: CVaListPointer) -> NSString in let localized = NSLocalizedString(identifier, tableName: "SwiftDate", bundle: bundle, value: "", comment: "") return NSString(format: localized, arguments: pointer) } return (relevantStr != nil ? "\(localized_date) \(relevantStr!)" : localized_date) as String } /** Get the relevant time string to append for a specified time unit difference - parameter unit: unit of time - parameter date: target date - parameter value: value of the unit - returns: relevant time string */ private func relevantTimeForUnit(unit: NSCalendarUnit, date: DateInRegion, value: Int) -> String? { if !self.includeRelevantTime { return nil } guard let bundle = self.bundle else { return String() } let unit_id = unit.localizedCode(value) let id_relative = "relevanttime_\(unit_id)" let relative_localized = NSLocalizedString(id_relative, tableName: "SwiftDate", bundle: bundle, value: "", comment: "") if (relative_localized as NSString).length == 0 { return nil } let relevant_time = date.toString(DateFormat.Custom(relative_localized)) return relevant_time } /** Get the localized string for a specified identifier string - parameter identifier: string to search in localized bundles - parameter arguments: arguments to add (or [] if no arguments are needed) - returns: localized string with optional arguments values filled */ private func sd_localizedString(identifier: String, arguments: CVarArgType...) -> String { guard let frameworkBundle = NSBundle(identifier: "com.danielemagutti.SwiftDate") else { return "" } let path = NSURL(fileURLWithPath: frameworkBundle.resourcePath!) .URLByAppendingPathComponent("SwiftDate.bundle") guard let bundle = NSBundle(URL: path!) else { return "" } var localized_str = NSLocalizedString(identifier, tableName: "SwiftDate", bundle: bundle, comment: "") localized_str = String(format: localized_str, arguments: arguments) return localized_str } } //MARK: - NSCalendarUnit Extension - extension NSCalendarUnit { /** Return the localized symbols for each time unit. Singular form is 'X', plural variant is 'XX' - parameter value: value of the unit unit (used to get the singular/plural variant) - returns: code in localization table */ public func localizedCode(value: Int) -> String { switch self { case NSCalendarUnit.Year: return (value == 1 ? "y" : "yy") case NSCalendarUnit.Month: return (value == 1 ? "m" : "mm") case NSCalendarUnit.WeekOfYear: return (value == 1 ? "w" : "ww") case NSCalendarUnit.Day: return (value == 1 ? "d" : "dd") case NSCalendarUnit.Hour: return (value == 1 ? "h" : "hh") case NSCalendarUnit.Minute: return (value == 1 ? "M" : "MM") case NSCalendarUnit.Second: return (value == 1 ? "s" : "ss") default: return "" } } } //MARK: - Supporting Structures - /** * This struct encapulate the information about the difference between two dates for a specified * unit of time. */ private struct DateFormatterValue: CustomStringConvertible { private var name: String private var value: Int private var separator: String private var description: String { return "\(value)\(separator)\(name)" } }
mit
40a38e72248083a6be518404ff8f9926
39.803167
100
0.63094
4.791445
false
false
false
false
SamirTalwar/advent-of-code
2018/AOC_15_2.swift
1
9463
let startingHitPoints = 200 typealias HitPoints = Int typealias Route = [Position] struct Position: Equatable, Comparable, Hashable, CustomStringConvertible { let x: Int let y: Int var description: String { return "(\(x), \(y))" } static func < (lhs: Position, rhs: Position) -> Bool { if lhs.y != rhs.y { return lhs.y < rhs.y } else { return lhs.x < rhs.x } } func distance(from other: Position) -> Int { return abs(x - other.x) + abs(y - other.y) } var neighbors: [Position] { return [ Position(x: x, y: y - 1), Position(x: x - 1, y: y), Position(x: x + 1, y: y), Position(x: x, y: y + 1), ] } } enum CaveSquare { case openCavern case wall } extension CaveSquare: CustomStringConvertible { var description: String { switch self { case .openCavern: return "." case .wall: return "#" } } } struct Cave: CustomStringConvertible { private let cave: [[CaveSquare]] init(_ cave: [[CaveSquare]]) { self.cave = cave } var description: String { return cave.map { row in row.map { cell in cell.description }.joined() }.joined(separator: "\n") } func description(with warriors: [Warrior]) -> String { let warriorsByPosition = Dictionary(uniqueKeysWithValues: warriors.map { warrior in (warrior.position, warrior) }) return cave.enumerated().map { row in row.element.enumerated().map { cell in warriorsByPosition[Position(x: cell.offset, y: row.offset)]?.race.symbol ?? cell.element.description }.joined() + "\n" }.joined() } subscript(position: Position) -> CaveSquare { return cave[position.y][position.x] } func route(from start: Position, to end: Position, excluding blocked: Set<Position>) -> Route? { if blocked.contains(end) || !isOpen(position: end) { return nil } return BreadthFirstSearch<Position>( neighbors: neighbors(excluding: blocked) ).shortestPath(from: start, to: end) } private func neighbors(excluding blocked: Set<Position>) -> (Position) -> [Position] { return { position in position.neighbors.filter { neighbor in !blocked.contains(neighbor) && self.isOpen(position: neighbor) } } } private func isOpen(position: Position) -> Bool { return position.y >= 0 && position.y < cave.count && position.x >= 0 && position.x < cave[0].count && cave[position.y][position.x] == .openCavern } } enum Race: CustomStringConvertible { case elf case goblin var description: String { switch self { case .elf: return "Elf" case .goblin: return "Goblin" } } var symbol: String { switch self { case .elf: return "E" case .goblin: return "G" } } } struct Warrior { let race: Race let position: Position var hitPoints: HitPoints func isInRange(of aggressor: Warrior) -> Bool { return aggressor.position.distance(from: position) <= 1 } func findTargets(in warriors: [Warrior]) -> [(offset: Int, element: Warrior)] { return warriors.enumerated() .filter { warrior in warrior.element.race != race } .sorted(by: comparing { target in target.element.position }) .sorted(by: comparing { target in target.element.hitPoints }) } func move(along route: Route) -> Warrior { return Warrior(race: race, position: route.first!, hitPoints: hitPoints) } } enum AttackError: Error { case elfDied } func main() { let caveSquaresAndWarriors = StdIn().enumerated().map { line in line.element.enumerated().map { character in parseCave(position: Position(x: character.offset, y: line.offset), character: character.element) } } let cave = Cave(caveSquaresAndWarriors.map { row in row.map { caveSquare, _ in caveSquare } }) var attackPower = [ Race.elf: 3, Race.goblin: 3, ] while true { do { var warriors = caveSquaresAndWarriors.flatMap { row in row.compactMap { _, warrior in warrior } } // print(cave.description(with: warriors)) func attack(attackPower: Int, offset: Int, i: inout Int) throws { warriors[offset].hitPoints -= attackPower if warriors[offset].hitPoints <= 0 { if warriors[offset].race == .elf { throw AttackError.elfDied } warriors.remove(at: offset) if offset < i { i -= 1 } } } var rounds = 0 while true { warriors.sort(by: comparing { warriors in warriors.position }) var i = 0 var roundWasCompleted = true while i < warriors.count { let targets = warriors[i].findTargets(in: warriors) if targets.isEmpty { roundWasCompleted = false break } if let target = targets.first(where: { target in target.element.isInRange(of: warriors[i]) }) { try attack(attackPower: attackPower[warriors[i].race]!, offset: target.offset, i: &i) } else { let blocked = Set(warriors.map { warrior in warrior.position }) let optimisticDistances = Set(targets.flatMap { target in target.element.position.neighbors }) .map { position in (position, position.distance(from: warriors[i].position)) } .sorted(by: comparing { position, _ in position }) .sorted(by: comparing { _, distance in distance }) var bestRoute: (Position, Route)? for (position, optimisticDistance) in optimisticDistances { if let (_, chosenRoute) = bestRoute { if optimisticDistance > chosenRoute.count { break } } if let route = cave.route(from: warriors[i].position, to: position, excluding: blocked) { switch bestRoute { case .none: bestRoute = (position, route) case let .some(chosenPosition, chosenRoute): if route.count < chosenRoute.count || (route.count == chosenRoute.count && position < chosenPosition) { bestRoute = (position, route) } } } } if let (_, route) = bestRoute { warriors[i] = warriors[i].move(along: route) let targets = warriors[i].findTargets(in: warriors) if let target = targets.first(where: { target in target.element.isInRange(of: warriors[i]) }) { try attack(attackPower: attackPower[warriors[i].race]!, offset: target.offset, i: &i) } } } i += 1 } if !roundWasCompleted { // print("Round \(rounds) was not completed.") // for warrior in warriors.sorted(by: comparing({ warriors in warriors.position })) { // print(warrior) // } // print(cave.description(with: warriors)) break } rounds += 1 // print(rounds) // for warrior in warriors.sorted(by: comparing({ warriors in warriors.position })) { // print(warrior) // } // print(cave.description(with: warriors)) } let totalHitPoints = warriors.map { warrior in warrior.hitPoints }.reduce(0, +) print("Elf Attack Power = \(attackPower[.elf]!)") print("Outcome = \(rounds) * \(totalHitPoints) = \(rounds * totalHitPoints)") break } catch AttackError.elfDied { attackPower[.elf]! += 1 } catch { fatalError("\(error)") } } } func parseCave(position: Position, character: Character) -> (CaveSquare, Warrior?) { switch character { case ".": return (.openCavern, nil) case "#": return (.wall, nil) case "E": return (.openCavern, Warrior(race: .elf, position: position, hitPoints: startingHitPoints)) case "G": return (.openCavern, Warrior(race: .goblin, position: position, hitPoints: startingHitPoints)) default: preconditionFailure("\"\(character)\" is an invalid cave square.") } }
mit
b2ef926fc9acc3e5d1f7beac5e5c63b6
33.536496
139
0.506605
4.584787
false
false
false
false
FuckBoilerplate/RxCache
watchOS/Pods/RxSwift/RxSwift/Observables/Implementations/ShareReplay1.swift
6
2704
// // ShareReplay1.swift // Rx // // Created by Krunoslav Zaher on 10/10/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation // optimized version of share replay for most common case final class ShareReplay1<Element> : Observable<Element> , ObserverType , SynchronizedUnsubscribeType { typealias DisposeKey = Bag<AnyObserver<Element>>.KeyType private let _source: Observable<Element> private var _lock = NSRecursiveLock() private var _connection: SingleAssignmentDisposable? private var _element: Element? private var _stopped = false private var _stopEvent = nil as Event<Element>? private var _observers = Bag<AnyObserver<Element>>() init(source: Observable<Element>) { self._source = source } override func subscribe<O : ObserverType>(_ observer: O) -> Disposable where O.E == E { _lock.lock(); defer { _lock.unlock() } return _synchronized_subscribe(observer) } func _synchronized_subscribe<O : ObserverType>(_ observer: O) -> Disposable where O.E == E { if let element = self._element { observer.on(.next(element)) } if let stopEvent = self._stopEvent { observer.on(stopEvent) return Disposables.create() } let initialCount = self._observers.count let disposeKey = self._observers.insert(AnyObserver(observer)) if initialCount == 0 { let connection = SingleAssignmentDisposable() _connection = connection connection.setDisposable(self._source.subscribe(self)) } return SubscriptionDisposable(owner: self, key: disposeKey) } func synchronizedUnsubscribe(_ disposeKey: DisposeKey) { _lock.lock(); defer { _lock.unlock() } _synchronized_unsubscribe(disposeKey) } func _synchronized_unsubscribe(_ disposeKey: DisposeKey) { // if already unsubscribed, just return if self._observers.removeKey(disposeKey) == nil { return } if _observers.count == 0 { _connection?.dispose() _connection = nil } } func on(_ event: Event<E>) { _lock.lock(); defer { _lock.unlock() } _synchronized_on(event) } func _synchronized_on(_ event: Event<E>) { if _stopped { return } switch event { case .next(let element): _element = element case .error, .completed: _stopEvent = event _stopped = true _connection?.dispose() _connection = nil } _observers.on(event) } }
mit
e9273a566f11812c5355657350252e00
25.762376
96
0.598594
4.660345
false
false
false
false
adelinofaria/Buildasaur
BuildaGitServer/GitHubEndpoints.swift
2
5350
// // GitHubURLFactory.swift // Buildasaur // // Created by Honza Dvorsky on 13/12/2014. // Copyright (c) 2014 Honza Dvorsky. All rights reserved. // import Foundation import XcodeServerSDK public class GitHubEndpoints { public enum Endpoint { case Users case Repos case PullRequests case Issues case Branches case Commits case Statuses case IssueComments case Merges } public enum MergeResult { case Success(NSDictionary) case NothingToMerge case Conflict case Missing(String) } private let baseURL: String private let token: String? public init(baseURL: String, token: String?) { self.baseURL = baseURL self.token = token } private func endpointURL(endpoint: Endpoint, params: [String: String]? = nil) -> String { switch endpoint { case .Users: if let user = params?["user"] { return "/users/\(user)" } else { return "/user" } //FYI - repo must be in its full name, e.g. czechboy0/Buildasaur, not just Buildasaur case .Repos: if let repo = params?["repo"] { return "/repos/\(repo)" } else { let user = self.endpointURL(.Users, params: params) return "\(user)/repos" } case .PullRequests: assert(params?["repo"] != nil, "A repo must be specified") let repo = self.endpointURL(.Repos, params: params) let pulls = "\(repo)/pulls" if let pr = params?["pr"] { return "\(pulls)/\(pr)" } else { return pulls } case .Issues: assert(params?["repo"] != nil, "A repo must be specified") let repo = self.endpointURL(.Repos, params: params) let issues = "\(repo)/issues" if let issue = params?["issue"] { return "\(issues)/\(issue)" } else { return issues } case .Branches: let repo = self.endpointURL(.Repos, params: params) let branches = "\(repo)/branches" if let branch = params?["branch"] { return "\(branches)/\(branch)" } else { return branches } case .Commits: let repo = self.endpointURL(.Repos, params: params) let commits = "\(repo)/commits" if let commit = params?["commit"] { return "\(commits)/\(commit)" } else { return commits } case .Statuses: let sha = params!["sha"]! let method = params?["method"] if let method = method { if method == HTTP.Method.POST.rawValue { //POST, we need slightly different url let repo = self.endpointURL(.Repos, params: params) return "\(repo)/statuses/\(sha)" } } //GET, default let commits = self.endpointURL(.Commits, params: params) return "\(commits)/\(sha)/statuses" case .IssueComments: let issues = self.endpointURL(.Issues, params: params) let comments = "\(issues)/comments" if let comment = params?["comment"] { return "\(comments)/\(comment)" } else { return comments } case .Merges: assert(params?["repo"] != nil, "A repo must be specified") let repo = self.endpointURL(.Repos, params: params) return "\(repo)/merges" default: assertionFailure("Unsupported endpoint") } } public func createRequest(method:HTTP.Method, endpoint:Endpoint, params: [String : String]? = nil, query: [String : String]? = nil, body:NSDictionary? = nil) -> NSMutableURLRequest? { let endpointURL = self.endpointURL(endpoint, params: params) let queryString = HTTP.stringForQuery(query) let wholePath = "\(self.baseURL)\(endpointURL)\(queryString)" let url = NSURL(string: wholePath)! var request = NSMutableURLRequest(URL: url) request.HTTPMethod = method.rawValue if let token = self.token { request.setValue("token \(token)", forHTTPHeaderField:"Authorization") } if let body = body { var error: NSError? let data = NSJSONSerialization.dataWithJSONObject(body, options: .allZeros, error: &error) if let error = error { //parsing error Log.error("Parsing error \(error.description)") return nil } request.HTTPBody = data } return request } }
mit
5a07b185b526adeb87f3db9b3e913ab8
29.225989
187
0.479813
5.46476
false
false
false
false
Alecrim/AlecrimCoreData
Sources/Core/Persistent Container/ManagedObject.swift
1
1262
// // ManagedObject.swift // AlecrimCoreData // // Created by Vanderlei Martinelli on 11/03/18. // Copyright © 2018 Alecrim. All rights reserved. // import Foundation import CoreData // MARK: - public typealias ManagedObject = NSManagedObject // MARK:- extension ManagedObject { public final func inContext(_ otherContext: ManagedObjectContext) throws -> Self { if self.managedObjectContext === otherContext { return self } if self.objectID.isTemporaryID { try otherContext.obtainPermanentIDs(for: [self]) } let otherManagedObject = try otherContext.existingObject(with: self.objectID) return unsafeDowncast(otherManagedObject, to: type(of: self)) } } // MARK:- extension ManagedObject { public final func delete() { precondition(self.managedObjectContext != nil) self.managedObjectContext!.delete(self) } public final func refresh(mergeChanges: Bool = true) { precondition(self.managedObjectContext != nil) self.managedObjectContext!.refresh(self, mergeChanges: mergeChanges) } } // MARK: - extension ManagedObject { public subscript(key: String) -> Any? { return self.value(forKey: key) } }
mit
7bc6bff1dd8de641d952d32bf06eb703
19.672131
86
0.668517
4.519713
false
false
false
false
net-a-porter-mobile/XCTest-Gherkin
Example/XCTest-Gherkin_ExampleUITests/StepDefinitions/UITestStepDefinitions.swift
1
2320
// // UITestStepDefinitions.swift // XCTest-Gherkin // // Created by Sam Dean on 6/3/16. // Copyright © 2016 CocoaPods. All rights reserved. // import Foundation import XCTest import XCTest_Gherkin final class UIStepDefiner: StepDefiner { override func defineSteps() { step("I have launched the app") { XCUIApplication().launch() } step("I tap the (.*) button") { (matches: [String]) in XCTAssert(matches.count > 0, "Should have been a match") let identifier = matches.first! XCUIApplication().buttons[identifier].firstMatch.tap() } } } final class InitialScreenStepDefiner: StepDefiner { override func defineSteps() { step("I press Push Me button") { InitialScreenPageObject().pressPushMe() } } } final class InitialScreenPageObject: PageObject { private let app = XCUIApplication() class override var name: String { return "Initial Screen" } override func isPresented() -> Bool { return tryWaitFor(element: app.buttons["PushMe"].firstMatch, withState: .exists) } func pressPushMe() { app.buttons["PushMe"].firstMatch.tap() } } final class ModalScreenStepDefiner: StepDefiner { override func defineSteps() { step("I press Close Me button") { ModalScreen().pressCloseMe() } } } final class ModalScreen: PageObject { private let app = XCUIApplication() override func isPresented() -> Bool { return tryWaitFor(element: app.buttons["CloseMe"].firstMatch, withState: .exists) } func pressCloseMe() { app.buttons["CloseMe"].firstMatch.tap() } } extension PageObject { func tryWaitFor(element: XCUIElement, withState state: String, waiting timeout: TimeInterval = 5.0) -> Bool { let predicate = NSPredicate(format: state) guard predicate.evaluate(with: element) == false else { return true } let expectation = XCTNSPredicateExpectation(predicate: predicate, object: element) let result = XCTWaiter().wait(for: [expectation], timeout: timeout) == .completed return result } } extension String { fileprivate static let exists = "exists == true" }
apache-2.0
c1098d5612b8984093fe84594c290ec3
22.907216
113
0.628288
4.425573
false
false
false
false
zhangxigithub/ZXTools_Swift
Tools/ZXMacro.swift
1
384
import UIKit public struct ZXMacroStruct{ public let UUID = UIDevice.current.identifierForVendor!.uuidString public let ScreenWidth = UIScreen.main.bounds.size.width public let ScreenHeight = UIScreen.main.bounds.size.height public let SystemVersion = (UIDevice.current.systemVersion as NSString).floatValue } public let ZXMacro = ZXMacroStruct()
apache-2.0
e853007573e153ee33f9abc83dd33f83
28.538462
86
0.75
4.682927
false
false
false
false
imgflo/ImgFlo.swift
ImgFlo/Color.swift
2
489
#if os(iOS) import UIKit public typealias Color = UIColor #elseif os(OSX) import AppKit public typealias Color = NSColor #endif extension Color { func toHexString() -> String { var red: CGFloat = 0 var green: CGFloat = 0 var blue: CGFloat = 0 var alpha: CGFloat = 0 getRed(&red, green: &green, blue: &blue, alpha: &alpha) return String(format: "#%02x%02x%02x", Int(red * 255), Int(green * 255), Int(blue * 255)) } }
mit
20fb7dce1d49790d529d5bfd0f0e5488
26.166667
97
0.593047
3.676692
false
false
false
false
mklbtz/finch
Sources/finch/RemoveCommand.swift
1
997
import Commandant import Foundation import TaskManagement import Result struct RemoveCommand: CommandProtocol { let verb = "rm" let function = "Remove tasks by ID" var manager: () throws -> TaskManager init(manager: @autoclosure @escaping () throws -> TaskManager) { self.manager = manager } func run(_ options: Options) -> Result<Void, String> { return Result { var manager = try self.manager() let tasks: [Task] if options.removeAll { tasks = try manager.removeAll() } else { tasks = try manager.remove(ids: options.ids) } tasks.forEach { print($0) } } } struct Options: OptionsProtocol { let ids: [Int] let removeAll: Bool static func evaluate(_ m: CommandMode) -> Result<Options, CommandantError<String>> { return curry(Options.init) <*> m <| Argument<[Int]>(usage: "A list of task IDs") <*> m <| Switch(flag: "a", key: "all", usage: "Remove all tasks") } } }
mit
02cc0543041b2dccdf82fba069a95365
23.317073
88
0.616851
4.069388
false
false
false
false
kingwangboss/OneJWeiBo
OneJWeiBo/OneJWeiBo/Classes/Home(首页)/UIPopover/HomeModel/Status.swift
1
1280
// // Status.swift // OneJWeiBo // // Created by One'J on 16/4/8. // Copyright © 2016年 One'J. All rights reserved. // import UIKit class Status: NSObject { // MARK:- 属性 var created_at : String? //微博创建时间 var source : String? //微博来源 var text : String? // 微博的正文 var mid : Int = 0 // 微博的ID var user : User? //用户模型 var pic_urls : [[String : String]]? // 微博的配图 var retweeted_status : Status? //微博对应的转发微博 // MARK:- 自定义构造函数 init(dict : [String : AnyObject]) { super.init() setValuesForKeysWithDictionary(dict) //将字典转为user模型 if let userDict = dict["user"] as? [String:AnyObject] { user = User(dict:userDict) } //将转发微博字典转成模型 if let retweetedStatusDict = dict["retweeted_status"] as? [String : AnyObject] { retweeted_status = Status(dict: retweetedStatusDict) } } override func setValue(value: AnyObject?, forUndefinedKey key: String) { } }
apache-2.0
7727b028cee1e71ba6ae794fb4c94836
25.159091
88
0.50391
4.216117
false
false
false
false
neoneye/SwiftyFORM
Source/Util/KeyboardHandler.swift
1
5022
// MIT license. Copyright (c) 2021 SwiftyFORM. All rights reserved. import UIKit /// Adjusts bottom insets when keyboard is shown and makes sure the keyboard doesn't obscure the cell. /// /// Resets insets when the keyboard is hidden. public class KeyboardHandler { private let tableView: UITableView private var innerKeyboardVisible: Bool = false init(tableView: UITableView) { self.tableView = tableView } var keyboardVisible: Bool { innerKeyboardVisible } /// Start listening for changes to keyboard visibility so that we can adjust the scroll view accordingly. func addObservers() { /* I listen to UIKeyboardWillShowNotification. I don't listen to UIKeyboardWillChangeFrameNotification Explanation: UIKeyboardWillChangeFrameNotification vs. UIKeyboardWillShowNotification The notifications behave the same on iPhone. However there is a big difference on iPad. On iPad with a split keyboard or a non-docked keyboard. When you make a textfield first responder and the keyboard appears, then UIKeyboardWillShowNotification is not invoked. only UIKeyboardWillChangeFrameNotification is invoked. The user has chosen actively to manually position the keyboard. In this case it's non-trivial to scroll to the textfield. It's not something I will support for now. */ let notificationCenter = NotificationCenter.default notificationCenter.addObserver(self, selector: #selector(KeyboardHandler.keyboardWillShow(_:)), name: UIWindow.keyboardWillShowNotification, object: nil) notificationCenter.addObserver(self, selector: #selector(KeyboardHandler.keyboardWillHide(_:)), name: UIWindow.keyboardWillHideNotification, object: nil) } /// Stop listening to keyboard visibility changes func removeObservers() { let notificationCenter = NotificationCenter.default notificationCenter.removeObserver(self, name: UIWindow.keyboardWillShowNotification, object: nil) notificationCenter.removeObserver(self, name: UIWindow.keyboardWillHideNotification, object: nil) } /// The keyboard will appear, scroll content so it's not covered by the keyboard. @objc func keyboardWillShow(_ notification: Notification) { // SwiftyFormLog("show\n\n\n\n\n\n\n\n") innerKeyboardVisible = true guard let cell = tableView.form_firstResponder()?.form_cell() else { return } guard let indexPath = tableView.indexPath(for: cell) else { return } let rectForRow = tableView.rectForRow(at: indexPath) // SwiftyFormLog("rectForRow \(NSStringFromCGRect(rectForRow))") guard let userInfo: [AnyHashable: Any] = notification.userInfo else { return } guard let window: UIWindow = tableView.window else { return } let keyboardFrameEnd = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue // SwiftyFormLog("keyboardFrameEnd \(NSStringFromCGRect(keyboardFrameEnd))") let keyboardFrame = window.convert(keyboardFrameEnd, to: tableView.superview) // SwiftyFormLog("keyboardFrame \(keyboardFrame)") let convertedRectForRow = window.convert(rectForRow, from: tableView) // SwiftyFormLog("convertedRectForRow \(NSStringFromCGRect(convertedRectForRow))") // SwiftyFormLog("tableView.frame \(NSStringFromCGRect(tableView.frame))") var scrollToVisible = false var scrollToRect = CGRect.zero let spaceBetweenCellAndKeyboard: CGFloat = 36 let y0 = convertedRectForRow.maxY + spaceBetweenCellAndKeyboard let y1 = keyboardFrameEnd.minY let obscured = y0 > y1 // SwiftyFormLog("values \(y0) \(y1) \(obscured)") if obscured { SwiftyFormLog("cell is obscured by keyboard, we are scrolling") scrollToVisible = true scrollToRect = rectForRow scrollToRect.size.height += spaceBetweenCellAndKeyboard } else { SwiftyFormLog("cell is fully visible, no need to scroll") } let inset: CGFloat = tableView.frame.maxY - keyboardFrame.origin.y //SwiftyFormLog("inset \(inset)") var contentInset: UIEdgeInsets = tableView.contentInset var scrollIndicatorInsets: UIEdgeInsets = tableView.scrollIndicatorInsets contentInset.bottom = inset scrollIndicatorInsets.bottom = inset // Adjust insets and scroll to the selected row tableView.contentInset = contentInset tableView.scrollIndicatorInsets = scrollIndicatorInsets if scrollToVisible { tableView.scrollRectToVisible(scrollToRect, animated: false) } } /// The keyboard will disappear, restore content insets. @objc func keyboardWillHide(_ notification: Notification) { // SwiftyFormLog("\n\n\n\nhide") innerKeyboardVisible = false var contentInset: UIEdgeInsets = tableView.contentInset var scrollIndicatorInsets: UIEdgeInsets = tableView.scrollIndicatorInsets contentInset.bottom = 0 scrollIndicatorInsets.bottom = 0 // SwiftyFormLog("contentInset \(NSStringFromUIEdgeInsets(contentInset))") // SwiftyFormLog("scrollIndicatorInsets \(NSStringFromUIEdgeInsets(scrollIndicatorInsets))") // Restore insets tableView.contentInset = contentInset tableView.scrollIndicatorInsets = scrollIndicatorInsets } }
mit
f0cac81e9ba1fddab5db16bb7718c47d
35.656934
155
0.776583
4.495971
false
false
false
false
superk589/DereGuide
DereGuide/Card/Controller/SignImageController.swift
2
2447
// // CardSignImageController.swift // DereGuide // // Created by zzk on 2017/1/22. // Copyright © 2017 zzk. All rights reserved. // import UIKit extension CGSSCard { var signImageURL: URL? { if self.rarityType == .ssr || self.rarityType == . ssrp { return URL.images.appendingPathComponent("/sign/\(seriesId!).png") } else { return nil } } } class CardSignImageController: BaseViewController { var card: CGSSCard! var imageView: BannerView! var item: UIBarButtonItem! override func viewDidLoad() { super.viewDidLoad() imageView = BannerView() view.addSubview(imageView) imageView.snp.makeConstraints { (make) in make.width.lessThanOrEqualToSuperview() make.top.greaterThanOrEqualTo(topLayoutGuide.snp.bottom) make.bottom.lessThanOrEqualTo(bottomLayoutGuide.snp.top) make.height.equalTo(imageView.snp.width).multipliedBy(504.0 / 630.0) make.center.equalToSuperview() } imageView.style = .custom prepareToolbar() if let url = card.signImageURL { imageView.sd_setImage(with: url, completed: { (image, error, cache, url) in self.item.isEnabled = true }) } // Do any additional setup after loading the view. } func prepareToolbar() { item = UIBarButtonItem.init(image: #imageLiteral(resourceName: "702-share-toolbar"), style: .plain, target: self, action: #selector(shareAction(item:))) item.isEnabled = false toolbarItems = [item] } @objc func shareAction(item: UIBarButtonItem) { if imageView.image == nil { return } let urlArray = [imageView.image!] let activityVC = UIActivityViewController.init(activityItems: urlArray, applicationActivities: nil) activityVC.popoverPresentationController?.barButtonItem = item // activityVC.popoverPresentationController?.sourceRect = CGRect(x: item.width / 2, y: 0, width: 0, height: 0) // 需要屏蔽的模块 let cludeActivitys:[UIActivity.ActivityType] = [] // 排除活动类型 activityVC.excludedActivityTypes = cludeActivitys // 呈现分享界面 self.present(activityVC, animated: true, completion: nil) } }
mit
42242e28377faccb2f9f9fafb8b781ea
29.871795
160
0.612126
4.648649
false
false
false
false
MaximKotliar/Bindy
Sources/ObservableArray.swift
1
7547
// // ObservableArray.swift // Bindy // // Created by Maxim Kotliar on 10/31/17. // Copyright © 2017 Maxim Kotliar. All rights reserved. // import Foundation extension Array { subscript (safe index: Int) -> Element? { guard index < self.count else { return nil } return self[index] } } extension Range { @discardableResult public func intersect(_ other: Range) -> Range { guard upperBound > other.lowerBound else { return upperBound..<upperBound } guard other.upperBound > lowerBound else { return lowerBound..<lowerBound } let lower = other.lowerBound > upperBound ? other.lowerBound : lowerBound let upper = other.upperBound < upperBound ? other.upperBound : upperBound return lower..<upper } } public struct ArrayUpdate { public enum Event { case insert case delete case replace } public let event: Event public let indexes: [Int] public init(_ type: Event, _ indexes: [Int]) { self.event = type self.indexes = indexes } } public final class ObservableArray<T: Equatable>: ObservableValueHolder<[T]>, Collection, MutableCollection, CustomStringConvertible, CustomDebugStringConvertible, ExpressibleByArrayLiteral, RangeReplaceableCollection { public typealias Element = T public let updates = Signal<[ArrayUpdate]>() public init() { super.init([], options: nil) } override public var value: [T] { didSet { guard oldValue != value else { return } fireBindings(with: .oldValueNewValue(oldValue, value)) } } public var startIndex: Int { return value.startIndex } public var endIndex: Int { return value.endIndex } public func index(after i: Int) -> Int { return value.index(after: i) } public func index(before i: Int) -> Int { return value.index(before: i) } public var description: String { return value.description } public var debugDescription: String { return value.debugDescription } public required init(arrayLiteral elements: T...) { super.init(elements, options: nil) } public required init(_ value: [T], options: [ObservableValueHolderOptionKey: Any]?) { super.init(value, options: options) } // Subscripts public subscript(index: Int) -> T { get { return value[index] } set { value[index] = newValue if index == value.count { updates.send([ArrayUpdate(.insert, [index])]) } else { updates.send([ArrayUpdate(.replace, [index])]) } } } public subscript(bounds: Range<Int>) -> ArraySlice<Element> { get { return value[bounds] } set { value[bounds] = newValue let first = bounds.lowerBound updates.send([ArrayUpdate(.insert, Array(first..<first + newValue.count)), ArrayUpdate(.delete, Array(bounds.lowerBound..<bounds.upperBound))]) } } // Insertions public func insert(_ newElement: T, at i: Index) { value.insert(newElement, at: i) updates.send([ArrayUpdate(.insert, [i])]) } public func insert<C>(contentsOf newElements: C, at i: Int) where C : Collection, T == C.Element { guard !newElements.isEmpty else { return } let oldCount = value.count value.insert(contentsOf: newElements, at: i) let insertedCount = value.count - oldCount updates.send([ArrayUpdate(.insert, Array(i..<i + insertedCount))]) } public func append(_ newElement: T) { value.append(newElement) updates.send([ArrayUpdate(.insert, [value.count - 1])]) } public func append<S>(contentsOf newElements: S) where S : Sequence, T == S.Element { let end = value.count value.append(contentsOf: newElements) guard end != value.count else { return } updates.send([ArrayUpdate(.insert, Array(end..<value.count))]) } // Deletions public func removeLast() -> Element { let element = value.removeLast() updates.send([ArrayUpdate(.delete, [value.count])]) return element } @discardableResult public func remove(at position: Int) -> Element { let element = value.remove(at: position) updates.send([ArrayUpdate(.delete, [position])]) return element } public func removeAll(keepingCapacity keepCapacity: Bool) { guard !value.isEmpty else { return } let oldCount = value.count value.removeAll(keepingCapacity: keepCapacity) updates.send([ArrayUpdate(.delete, Array(0..<oldCount))]) } // Subrange replacements public func replaceSubrange<C>(_ subrange: Range<Index>, with newElements: C) where C: Collection, C.Iterator.Element == T { let oldCount = value.count value.replaceSubrange(subrange, with: newElements) let first = subrange.lowerBound let newCount = value.count let end = first + (newCount - oldCount) + subrange.count updates.send([ArrayUpdate(.insert, Array(first..<end)), ArrayUpdate(.delete, Array(subrange.lowerBound..<subrange.upperBound))]) } public func replaceAll(with new: [T]) { let old = value let maxCount = Swift.max(old.count, new.count) var replacements: [Index] = [] var insertions: [Index] = [] var deletions: [Index] = [] for index in 0...maxCount { let left = old[safe: index] let right = new[safe: index] switch (left, right) { case (.some(let l), .some(let r)): guard l != r else { continue } replacements.append(index) case (.none, .some): insertions.append(index) case (.some, .none): deletions.append(index) case (.none, .none): break } } var updates: [ArrayUpdate] = [] if !replacements.isEmpty { updates.append(ArrayUpdate(.replace, replacements)) } if !insertions.isEmpty { updates.append(ArrayUpdate(.insert, insertions)) } if !deletions.isEmpty { updates.append(ArrayUpdate(.delete, deletions)) } value = new if !updates.isEmpty { self.updates.send(updates) } } } public extension ObservableArray { func transform<U: Equatable>(_ transform: @escaping ([T]) -> U) -> Observable<U> { let transformedObserver = Observable<U>(transform(value), options: nil) observe(self) { [unowned self] (value) in transformedObserver.value = transform(self.value) } return transformedObserver } func transform<U: Equatable>(_ transform: @escaping ([T]) -> [U]) -> ObservableArray<U> { let transformedObserver = ObservableArray<U>(transform(value)) observe(self) { [unowned self] (value) in transformedObserver.value = transform(self.value) } return transformedObserver } }
mit
b32fb54abe1d75c60f06308036d7174e
30.181818
219
0.573549
4.722153
false
false
false
false
mssun/pass-ios
pass/Controllers/RawPasswordViewController.swift
2
655
// // RawPasswordViewController.swift // pass // // Created by Mingshen Sun on 31/3/2017. // Copyright © 2017 Bob Sun. All rights reserved. // import passKit import UIKit class RawPasswordViewController: UIViewController { @IBOutlet var rawPasswordTextView: UITextView! var password: Password? override func viewDidLoad() { super.viewDidLoad() navigationItem.title = password?.name rawPasswordTextView.textContainer.lineFragmentPadding = 0 rawPasswordTextView.textContainerInset = .zero rawPasswordTextView.text = password?.plainText rawPasswordTextView.textColor = Colors.label } }
mit
dda149891fc34db31a254db20ce6e2a9
26.25
65
0.718654
4.671429
false
false
false
false
zhao765882596/XImagePickerController
XImagePickerController/Classes/XMLocationManager.swift
1
1729
// // XMLocationManager.swift // channel_sp // // Created by ming on 2017/10/18. // Copyright © 2017年 TiandaoJiran. All rights reserved. // import Foundation import CoreLocation class XMLocationManager: NSObject, CLLocationManagerDelegate { public static let manager = XMLocationManager() private lazy var locationManager = CLLocationManager() private var success: ((CLLocation) -> Void)? private var failure: ((Error) -> Void)? private var geocode: ((Array<CLPlacemark>) -> Void)? override init() { super.init() locationManager.delegate = self locationManager.requestWhenInUseAuthorization() } public func startLocation(success: ((_ location: CLLocation) -> Void)? = nil, failure: ((_ error: Error) -> Void)? = nil, geocode: ((_ geocoderArray: Array<CLPlacemark>) -> Void)? ) { locationManager.startUpdatingLocation() self.success = success self.failure = failure self.geocode = geocode } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { if success != nil && locations.count > 0 { success!(locations[0]) } if geocode != nil && locations.count > 0 { let geocoder = CLGeocoder() geocoder.reverseGeocodeLocation(locations[0], completionHandler: { [weak self](placemarks, error) in if let geocoderPlacemarks = placemarks { self?.geocode!(geocoderPlacemarks) } }) } } func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { if failure != nil { failure!(error) } } }
mit
1ed589d3bfb12c6ba89b0c30222f6a9d
29.280702
187
0.622827
5.002899
false
false
false
false
MintiV/CustomInputTextField
Demo/Demo/ViewController.swift
1
2758
// // ViewController.swift // Demo // // Created by Mayank Vyas on 16/05/16. // Copyright © 2016 MoonShine. All rights reserved. // import UIKit class ViewController: UIViewController { // MARK: - IBProperties @IBOutlet weak var userEmailField: CustomInputTextField! @IBOutlet weak var passwordField: CustomInputTextField! @IBOutlet weak var userDetailTxtView: CustomInputTextView! // MARK: - override func viewDidLoad() { super.viewDidLoad() userEmailField.textValidationType = TextValidation.Email let passwordPredicate = NSPredicate(format:"self.length > 8") passwordField.customPredicate = passwordPredicate passwordField.textValidationType = TextValidation.Custom userDetailTxtView.textValidationType = TextValidation.Email } // MARK: - IBAction @IBAction func goBtnAction(sender: AnyObject) { self.view.endEditing(true) var check: Bool = true check = userEmailField.validateText() check = passwordField.validateText() check = userDetailTxtView.validateText() if check == true { let controller: UIAlertController = UIAlertController(title: "Success", message: "", preferredStyle: UIAlertControllerStyle.Alert) let action: UIAlertAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil) controller.addAction(action) self.presentViewController(controller, animated: true, completion: nil) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } // MARK: - UITextField Delegates extension ViewController: UITextFieldDelegate { func textFieldShouldBeginEditing(textField: UITextField) -> Bool { (textField as! CustomInputTextField).hideValidation() return true } func textFieldShouldReturn(textField: UITextField) -> Bool { (textField as! CustomInputTextField).validateText() textField.resignFirstResponder() return true } } // MARK: - UITextView Delegates extension ViewController: UITextViewDelegate { func textViewShouldBeginEditing(textView: UITextView) -> Bool { (textView as! CustomInputTextView).hideValidation() return true } func textViewShouldEndEditing(textView: UITextView) -> Bool { (textView as! CustomInputTextView).validateText() textView.resignFirstResponder() return true } }
mit
063b0bb4097d0999e7e68ad9ddf05469
26.029412
142
0.640551
5.580972
false
false
false
false
goyuanfang/SXSwiftWeibo
103 - swiftWeibo/103 - swiftWeibo/Classes/BusinessModel/AccessToken.swift
1
2237
// // AccessToken.swift // 103 - swiftWeibo // // Created by 董 尚先 on 15/3/3. // Copyright (c) 2015年 shangxianDante. All rights reserved. // import UIKit class AccessToken:NSObject,NSCoding{ var access_token:String? /// token过期日期 var expiresDate: NSDate? var remind_in: NSNumber? var expires_in :NSNumber?{ didSet{ expiresDate = NSDate(timeIntervalSinceNow: expires_in!.doubleValue) println("过期时间为--:\(expiresDate)") } } var isExpired:Bool{ // 判断过期时间和系统时间,如果后面比较结果是升序,那就是当前日期比过期时间大。就是过期 return expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedAscending } var uid : Int = 0 /// 传入字典的构造方法 init(dict:NSDictionary){ super.init() self.setValuesForKeysWithDictionary(dict as [NSObject:AnyObject]) } /// 将数据保存到沙盒 func saveAccessToken(){ NSKeyedArchiver.archiveRootObject(self, toFile: AccessToken.tokenPath()) println("accesstoken地址是" + AccessToken.tokenPath()) } /// 从沙盒读取 token 数据 class func loadAccessToken() -> AccessToken? { return NSKeyedUnarchiver.unarchiveObjectWithFile(tokenPath()) as? AccessToken } /// 返回保存的沙盒路径 class func tokenPath() -> String { var path = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last as!String path = path.stringByAppendingPathComponent("SXWeiboToken.plist") return path } /// 普通的构造方法 override init() {} func encodeWithCoder(encode: NSCoder) { encode.encodeObject(access_token) encode.encodeObject(expiresDate) encode.encodeInteger(uid, forKey: "uid") } required init(coder decoder:NSCoder){ access_token = decoder.decodeObject() as?String expiresDate = decoder.decodeObject() as?NSDate uid = decoder.decodeIntegerForKey("uid") } }
mit
228c32093b083ced23c7a7b58a7698f2
24.5
155
0.631682
4.644647
false
false
false
false
kostiakoval/PiList
PiList/PiList/PiList/Tokenizer.swift
1
2182
// // Tokenizer.swift // PiList // // Created by Kostiantyn Koval on 08/11/15. // Copyright © 2015 Kostiantyn Koval. All rights reserved. //- enum Error: ErrorType { case Error } struct Tokenizer { private struct Key { private static let openSign = "<" private static let closeSign = ">" private static let openClosingToken = "</" } //MARK:- Open Token static func openToken(x: String) -> String? { return find(x, open: Key.openSign, close: Key.closeSign) } static func openToken(content: String, token: String) -> (content: String, range: Range<String.Index>)? { guard let range = openTokenRange(content, token: token) else { return nil } return (content[range], range) } static func openTokenName(x: String) -> String? { guard var characters = openToken(x)?.characters else { return nil } characters.removeFirst() characters.removeLast() return String(characters) } //MARK:- Close Token static func closeToken(x: String) -> String? { return find(x, open: Key.openClosingToken, close: Key.closeSign) } static func closeToken(content: String, token: String) -> (content: String, range: Range<String.Index>)? { guard let range = closeTokenRange(content, token: token) else { return nil } return (content[range], range) } } //MARK: - Private private extension Tokenizer { static func find(x: String, open: String, close: String) -> String? { let range = findRange(x, open: open, close: close) return range.map { x[$0] } } static func findRange(x: String, open: String, close: String) -> Range<String.Index>? { guard let openRange = x.rangeOf(open), closeRange = x.rangeOf(close, starFrom: openRange.endIndex) else { return nil } return openRange.startIndex..<closeRange.endIndex } //MARK:- Open Token private static func openTokenRange(x: String, token: String) -> Range<String.Index>? { return findRange(x, open: "<\(token)", close: Key.closeSign) } //MARK:- Close Token private static func closeTokenRange(x: String, token: String) -> Range<String.Index>? { return findRange(x, open: "</\(token)", close: Key.closeSign) } }
mit
8b3b0f4784005074507353fa65e9f98c
25.277108
108
0.670335
3.647157
false
false
false
false
mozilla/SwiftKeychainWrapper
SwiftKeychainWrapper/KeychainWrapper.swift
1
5901
// // KeychainWrapper.swift // KeychainWrapper // // Created by Jason Rendel on 9/23/14. // Copyright (c) 2014 jasonrendel. All rights reserved. // import Foundation let SecMatchLimit: String! = kSecMatchLimit as String let SecReturnData: String! = kSecReturnData as String let SecValueData: String! = kSecValueData as String let SecAttrAccessible: String! = kSecAttrAccessible as String let SecClass: String! = kSecClass as String let SecAttrService: String! = kSecAttrService as String let SecAttrGeneric: String! = kSecAttrGeneric as String let SecAttrAccount: String! = kSecAttrAccount as String public class KeychainWrapper { private struct internalVars { static var serviceName: String = "" } // MARK: Public Properties /*! @var serviceName @abstract Used for the kSecAttrService property to uniquely identify this keychain accessor. @discussion Service Name will default to the app's bundle identifier if it can */ public class var serviceName: String { get { if internalVars.serviceName.isEmpty { internalVars.serviceName = NSBundle.mainBundle().bundleIdentifier ?? "SwiftKeychainWrapper" } return internalVars.serviceName } set(newServiceName) { internalVars.serviceName = newServiceName } } // MARK: Public Methods public class func hasValueForKey(key: String) -> Bool { var keychainData: NSData? = self.dataForKey(key) if let data = keychainData { return true } else { return false } } // MARK: Getting Values public class func stringForKey(keyName: String) -> String? { var keychainData: NSData? = self.dataForKey(keyName) var stringValue: String? if let data = keychainData { stringValue = NSString(data: data, encoding: NSUTF8StringEncoding) as String? } return stringValue } public class func objectForKey(keyName: String) -> NSCoding? { let dataValue: NSData? = self.dataForKey(keyName) var objectValue: NSCoding? if let data = dataValue { objectValue = NSKeyedUnarchiver.unarchiveObjectWithData(data) as NSCoding? } return objectValue; } public class func dataForKey(keyName: String) -> NSData? { var keychainQueryDictionary = self.setupKeychainQueryDictionaryForKey(keyName) var result: AnyObject? // Limit search results to one keychainQueryDictionary[SecMatchLimit] = kSecMatchLimitOne // Specify we want NSData/CFData returned keychainQueryDictionary[SecReturnData] = kCFBooleanTrue // Search let status = withUnsafeMutablePointer(&result) { SecItemCopyMatching(keychainQueryDictionary, UnsafeMutablePointer($0)) } return status == noErr ? result as? NSData : nil } // MARK: Setting Values public class func setString(value: String, forKey keyName: String) -> Bool { if let data = value.dataUsingEncoding(NSUTF8StringEncoding) { return self.setData(data, forKey: keyName) } else { return false } } public class func setObject(value: NSCoding, forKey keyName: String) -> Bool { let data = NSKeyedArchiver.archivedDataWithRootObject(value) return self.setData(data, forKey: keyName) } public class func setData(value: NSData, forKey keyName: String) -> Bool { var keychainQueryDictionary: NSMutableDictionary = self.setupKeychainQueryDictionaryForKey(keyName) keychainQueryDictionary[SecValueData] = value // Protect the keychain entry so it's only valid when the device is unlocked keychainQueryDictionary[SecAttrAccessible] = kSecAttrAccessibleWhenUnlocked let status: OSStatus = SecItemAdd(keychainQueryDictionary, nil) if status == errSecSuccess { return true } else if status == errSecDuplicateItem { return self.updateData(value, forKey: keyName) } else { return false } } // MARK: Removing Values public class func removeObjectForKey(keyName: String) -> Bool { let keychainQueryDictionary: NSMutableDictionary = self.setupKeychainQueryDictionaryForKey(keyName) // Delete let status: OSStatus = SecItemDelete(keychainQueryDictionary); if status == errSecSuccess { return true } else { return false } } // MARK: Private Methods private class func updateData(value: NSData, forKey keyName: String) -> Bool { let keychainQueryDictionary: NSMutableDictionary = self.setupKeychainQueryDictionaryForKey(keyName) let updateDictionary = [SecValueData:value] // Update let status: OSStatus = SecItemUpdate(keychainQueryDictionary, updateDictionary) if status == errSecSuccess { return true } else { return false } } private class func setupKeychainQueryDictionaryForKey(keyName: String) -> NSMutableDictionary { // Setup dictionary to access keychain and specify we are using a generic password (rather than a certificate, internet password, etc) var keychainQueryDictionary: NSMutableDictionary = [SecClass:kSecClassGenericPassword] // Uniquely identify this keychain accessor keychainQueryDictionary[SecAttrService] = KeychainWrapper.serviceName // Uniquely identify the account who will be accessing the keychain var encodedIdentifier: NSData? = keyName.dataUsingEncoding(NSUTF8StringEncoding) keychainQueryDictionary[SecAttrGeneric] = encodedIdentifier keychainQueryDictionary[SecAttrAccount] = encodedIdentifier return keychainQueryDictionary } }
mit
e19e824c0d1e99c18886ebace060c9a1
32.913793
142
0.675818
5.408799
false
false
false
false
SuperAwesomeLTD/sa-mobile-sdk-ios-demo
AwesomeAdsDemo/CompaniesController.swift
1
2036
// // CompaniesController.swift // AwesomeAdsDemo // // Created by Gabriel Coman on 10/07/2017. // Copyright © 2017 Gabriel Coman. All rights reserved. // import UIKit import RxSwift import RxCocoa class CompaniesController: SABaseViewController { @IBOutlet weak var pageTitle: UILabel! @IBOutlet weak var tableView: UITableView! @IBOutlet weak var searchField: UISearchBar! @IBOutlet weak var activityIndicator: UIActivityIndicatorView! var viewModel = CompaniesViewModel () var dataSource = CompaniesDataSource () override func viewDidLoad() { super.viewDidLoad() pageTitle.text = "page_companies_title".localized searchField.placeholder = "page_comapanies_search_placeholder".localized dataSource.delegate = self tableView.dataSource = dataSource tableView.delegate = dataSource } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) store.dispatch(Event.LoadingCompanies) store.dispatch(Event.loadCompanies(forJwtToken: store.jwtToken)) } @IBAction func backAction(_ sender: Any) { didSelect(company: store.company) } override func handle(_ state: AppState) { let companiesState = state.companiesState viewModel.data = companiesState.filtered dataSource.data = viewModel.viewModels tableView.reloadData() activityIndicator.isHidden = !companiesState.isLoading tableView.isHidden = companiesState.isLoading } } extension CompaniesController: CompaniesDataSourceDelegate { func didSelect(company comp: Company) { store?.dispatch(Event.SelectCompany(company: comp)) self.navigationController?.popViewController(animated: true) } } extension CompaniesController: UISearchBarDelegate { func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { store?.dispatch(Event.FilterCompanies(withSearchTerm: searchText)) } }
apache-2.0
6a90aad0f64e06f7cc59a9664f844d5c
29.833333
80
0.703194
5.0875
false
false
false
false
v2panda/DaysofSwift
swift2.3/My-SnapchatMenu/My-SnapchatMenu/CameraViewController.swift
1
4281
// // CameraViewController.swift // My-SnapchatMenu // // Created by Panda on 16/2/19. // Copyright © 2016年 v2panda. All rights reserved. // import UIKit import AVFoundation class CameraViewController: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate { @IBOutlet weak var cameraView: UIView! @IBOutlet weak var tempImageView: UIImageView! var captureSession : AVCaptureSession? var stillImageOutput : AVCaptureStillImageOutput? var previewLayer : AVCaptureVideoPreviewLayer? override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) previewLayer?.frame = cameraView.bounds } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) captureSession = AVCaptureSession() captureSession?.sessionPreset = AVCaptureSessionPreset1920x1080 let backCamera = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo) var error : NSError? var input : AVCaptureDeviceInput! do{ input = try AVCaptureDeviceInput(device: backCamera)} catch let error1 as NSError{ error = error1 input = nil } if(error == nil && captureSession?.canAddInput(input) != nil){ captureSession?.addInput(input) stillImageOutput = AVCaptureStillImageOutput() stillImageOutput?.outputSettings = [AVVideoCodecKey : AVVideoCodecJPEG] if(captureSession?.canAddOutput(stillImageOutput) != nil){ captureSession?.addOutput(stillImageOutput) previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) previewLayer?.videoGravity = AVLayerVideoGravityResizeAspect previewLayer?.connection.videoOrientation = AVCaptureVideoOrientation.Portrait cameraView.layer.addSublayer(previewLayer!) captureSession?.startRunning() } } } func didPressTakePhoto(){ if let videoConnection = stillImageOutput?.connectionWithMediaType(AVMediaTypeVideo){ videoConnection.videoOrientation = AVCaptureVideoOrientation.Portrait stillImageOutput?.captureStillImageAsynchronouslyFromConnection(videoConnection, completionHandler: { (sampleBuffer, error) in if sampleBuffer != nil{ var imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer) var dataProvider = CGDataProviderCreateWithCFData(imageData) var cgImageRef = CGImageCreateWithJPEGDataProvider(dataProvider, nil, true, CGColorRenderingIntent.RenderingIntentDefault) var image = UIImage(CGImage: cgImageRef!, scale: 1.0, orientation: UIImageOrientation.Right) self.tempImageView.image = image self.tempImageView.hidden = false } }) } } var didTakePhoto = Bool() func didPressTakeAnother(){ if didTakePhoto == true{ tempImageView.hidden = true didTakePhoto = false } else{ captureSession?.startRunning() didTakePhoto = true didPressTakePhoto() } } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { didPressTakeAnother() } /* // 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. } */ }
mit
fa410ba94e02cd05b70878e47b9b6b9b
33.224
142
0.627396
6.632558
false
false
false
false
Egibide-DAM/swift
02_ejemplos/07_ciclo_vida/03_arc/02_referencias_ciclicas.playground/Contents.swift
1
574
class Person { let name: String init(name: String) { self.name = name } var apartment: Apartment? deinit { print("\(name) is being deinitialized") } } class Apartment { let unit: String init(unit: String) { self.unit = unit } var tenant: Person? deinit { print("Apartment \(unit) is being deinitialized") } } var john: Person? var unit4A: Apartment? john = Person(name: "John Appleseed") unit4A = Apartment(unit: "4A") john!.apartment = unit4A unit4A!.tenant = john john = nil unit4A = nil // No se muestran los mensajes de los deinit()
apache-2.0
7eaa551e125ec1121af4fcc3a67888c4
21.076923
64
0.665505
3.28
false
false
false
false
ryuichis/swift-lint
Sources/Lint/Rule/NoForceCastRule.swift
2
1902
/* Copyright 2015 Ryuichi Laboratories and the Yanagiba project contributors 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 AST class NoForceCastRule: RuleBase, ASTVisitorRule { let name = "No Force Cast" var description: String? { return """ Force casting `as!` should be avoided, because it could crash the program when the type casting fails. Although it is arguable that, in rare cases, having crashes may help developers identify issues easier, we recommend using a `guard` statement with optional casting and then handle the failed castings gently. """ } var examples: [String]? { return [ """ let cell = tableView.dequeueReusableCell(withIdentifier: "CellIdentifier", for: indexPath) as! MyCustomCell // guard let cell = // tableView.dequeueReusableCell(withIdentifier: "CellIdentifier", for: indexPath) as? MyCustomCell // else { // print("Failed in casting to MyCustomCell.") // return UITableViewCell() // } return cell """, ] } let category = Issue.Category.badPractice func visit(_ typeCasting: TypeCastingOperatorExpression) throws -> Bool { if case .forcedCast = typeCasting.kind { emitIssue( typeCasting.sourceRange, description: "having forced type casting is dangerous") } return true } }
apache-2.0
20cf1dce437940e40ff7555c91d30cfe
30.7
113
0.699264
4.743142
false
false
false
false
kean/Nuke
Sources/Nuke/Caching/Cache.swift
1
5554
// The MIT License (MIT) // // Copyright (c) 2015-2022 Alexander Grebenyuk (github.com/kean). import Foundation #if os(iOS) || os(tvOS) import UIKit.UIApplication #endif // Internal memory-cache implementation. final class Cache<Key: Hashable, Value>: @unchecked Sendable { // Can't use `NSCache` because it is not LRU struct Configuration { var costLimit: Int var countLimit: Int var ttl: TimeInterval? var entryCostLimit: Double } var conf: Configuration { get { lock.sync { _conf } } set { lock.sync { _conf = newValue } } } private var _conf: Configuration { didSet { _trim() } } var totalCost: Int { lock.sync { _totalCost } } var totalCount: Int { lock.sync { map.count } } private var _totalCost = 0 private var map = [Key: LinkedList<Entry>.Node]() private let list = LinkedList<Entry>() private let lock = NSLock() private let memoryPressure: DispatchSourceMemoryPressure private var notificationObserver: AnyObject? init(costLimit: Int, countLimit: Int) { self._conf = Configuration(costLimit: costLimit, countLimit: countLimit, ttl: nil, entryCostLimit: 0.1) self.memoryPressure = DispatchSource.makeMemoryPressureSource(eventMask: [.warning, .critical], queue: .main) self.memoryPressure.setEventHandler { [weak self] in self?.removeAll() } self.memoryPressure.resume() #if os(iOS) || os(tvOS) self.registerForEnterBackground() #endif #if TRACK_ALLOCATIONS Allocations.increment("Cache") #endif } deinit { memoryPressure.cancel() #if TRACK_ALLOCATIONS Allocations.decrement("Cache") #endif } #if os(iOS) || os(tvOS) private func registerForEnterBackground() { notificationObserver = NotificationCenter.default.addObserver(forName: UIApplication.didEnterBackgroundNotification, object: nil, queue: nil) { [weak self] _ in self?.clearCacheOnEnterBackground() } } #endif func value(forKey key: Key) -> Value? { lock.lock() defer { lock.unlock() } guard let node = map[key] else { return nil } guard !node.value.isExpired else { _remove(node: node) return nil } // bubble node up to make it last added (most recently used) list.remove(node) list.append(node) return node.value.value } func set(_ value: Value, forKey key: Key, cost: Int = 0, ttl: TimeInterval? = nil) { lock.lock() defer { lock.unlock() } // Take care of overflow or cache size big enough to fit any // reasonable content (and also of costLimit = Int.max). let sanitizedEntryLimit = max(0, min(_conf.entryCostLimit, 1)) guard _conf.costLimit > 2147483647 || cost < Int(sanitizedEntryLimit * Double(_conf.costLimit)) else { return } let ttl = ttl ?? _conf.ttl let expiration = ttl.map { Date() + $0 } let entry = Entry(value: value, key: key, cost: cost, expiration: expiration) _add(entry) _trim() // _trim is extremely fast, it's OK to call it each time } @discardableResult func removeValue(forKey key: Key) -> Value? { lock.lock() defer { lock.unlock() } guard let node = map[key] else { return nil } _remove(node: node) return node.value.value } private func _add(_ element: Entry) { if let existingNode = map[element.key] { _remove(node: existingNode) } map[element.key] = list.append(element) _totalCost += element.cost } private func _remove(node: LinkedList<Entry>.Node) { list.remove(node) map[node.value.key] = nil _totalCost -= node.value.cost } func removeAll() { lock.lock() defer { lock.unlock() } map.removeAll() list.removeAll() _totalCost = 0 } private dynamic func clearCacheOnEnterBackground() { // Remove most of the stored items when entering background. // This behavior is similar to `NSCache` (which removes all // items). This feature is not documented and may be subject // to change in future Nuke versions. lock.lock() defer { lock.unlock() } _trim(toCost: Int(Double(_conf.costLimit) * 0.1)) _trim(toCount: Int(Double(_conf.countLimit) * 0.1)) } private func _trim() { _trim(toCost: _conf.costLimit) _trim(toCount: _conf.countLimit) } func trim(toCost limit: Int) { lock.sync { _trim(toCost: limit) } } private func _trim(toCost limit: Int) { _trim(while: { _totalCost > limit }) } func trim(toCount limit: Int) { lock.sync { _trim(toCount: limit) } } private func _trim(toCount limit: Int) { _trim(while: { map.count > limit }) } private func _trim(while condition: () -> Bool) { while condition(), let node = list.first { // least recently used _remove(node: node) } } private struct Entry { let value: Value let key: Key let cost: Int let expiration: Date? var isExpired: Bool { guard let expiration = expiration else { return false } return expiration.timeIntervalSinceNow < 0 } } }
mit
6d662c7cc7dff13fc8e43298e6e304b6
26.22549
168
0.588225
4.141685
false
false
false
false
jie-cao/CJImageUtils
CJImageUtilsDemo/ImageCollectionViewController.swift
1
5467
// // ImageCollectionViewController.swift // CJImageUtilsDemo // // Created by Jie Cao on 11/20/15. // Copyright © 2015 JieCao. All rights reserved. // import UIKit private let reuseIdentifier = "ImageCell" class ImageCollectionViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout { @IBOutlet weak var collectionView: UICollectionView! var dataSource = [] override func viewDidLoad() { super.viewDidLoad() self.dataSource = [["text":"cat", "url":"http://www.fndvisions.org/img/cutecat.jpg"], ["text":"cat", "url":"http://www.mycatnames.com/wp-content/uploads/2015/09/Great-Ideas-for-cute-cat-names-2.jpg"], ["text":"cat", "url":"http://cdn.cutestpaw.com/wp-content/uploads/2011/11/cute-cat.jpg"], ["text":"cat", "url":"http://buzzneacom.c.presscdn.com/wp-content/uploads/2015/02/cute-cat-l.jpg"], ["text":"cat", "url":"http://images.fanpop.com/images/image_uploads/CUTE-CAT-cats-625629_689_700.jpg"], ["text":"cat", "url":"http://cl.jroo.me/z3/m/a/z/e/a.baa-Very-cute-cat-.jpg"], ["text":"cat", "url":"http://www.cancats.net/wp-content/uploads/2014/10/cute-cat-pictures-the-cutest-cat-ever.jpg"], ["text":"cat", "url":"https://catloves9.files.wordpress.com/2012/05/cute-cat-20.jpg"], ["text":"cat", "url":"https://s-media-cache-ak0.pinimg.com/736x/8c/99/e3/8c99e3483387df6395da674a6b5dee4c.jpg"], ["text":"cat", "url":"http://youne.com/wp-content/uploads/2013/09/cute-cat.jpg"], ["text":"cat", "url":"http://www.lovefotos.com/wp-content/uploads/2011/06/cute-cat1.jpg"], ["text":"cat", "url":"http://cutecatsrightmeow.com/wp-content/uploads/2015/10/heres-looking-at-you-kid.jpg"]] // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Register cell classes //self.collectionView!.registerClass(ImageCollectionCell.self, forCellWithReuseIdentifier: reuseIdentifier) self.collectionView.dataSource = self self.collectionView.delegate = self self.collectionView.backgroundColor = UIColor.whiteColor() self.collectionView.alwaysBounceVertical = true // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ // MARK: UICollectionViewDataSource func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of items return self.dataSource.count } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let data = self.dataSource[indexPath.row] as! [String :String] let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! ImageCollectionCell if let imageUrl = NSURL(string: data["url"]!){ cell.imageView?.imageWithURL(imageUrl) cell.imageView?.contentMode = .ScaleAspectFill } // Configure the cell return cell } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { return CGSizeMake(100, 100) } // MARK: UICollectionViewDelegate /* // Uncomment this method to specify if the specified item should be highlighted during tracking override func collectionView(collectionView: UICollectionView, shouldHighlightItemAtIndexPath indexPath: NSIndexPath) -> Bool { return true } */ /* // Uncomment this method to specify if the specified item should be selected override func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool { return true } */ /* // Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item override func collectionView(collectionView: UICollectionView, shouldShowMenuForItemAtIndexPath indexPath: NSIndexPath) -> Bool { return false } override func collectionView(collectionView: UICollectionView, canPerformAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) -> Bool { return false } override func collectionView(collectionView: UICollectionView, performAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) { } */ }
mit
2c3e30c32b7bdac62a7183ab22521e7f
45.322034
185
0.697402
4.663823
false
false
false
false
joshc89/DeclarativeLayout
DeclarativeLayout/Protocols/Layout.swift
1
2575
// // Layout.swift // DeclarativeLayout // // Created by Josh Campion on 16/07/2016. // Copyright © 2016 Josh Campion. All rights reserved. // import Foundation /// Protocol defining the requirements for objects to provide a declarative layout using Auto Layout. public protocol Layout { /// The `AnchoredObject` that should be used to position this `Layout` amongst others. var boundary: AnchoredObject { get } /// An array of sub-`Layout` objects that make up this `Layout`. These will be added to a `UIView` in the order they are given in this array in `add(layout: _:)` var elements: [Layout] { get } /// The constraints required to internally position this `Layout`. These should be activated once the `elements` of this `Layout` has been added to a super view. You should remember to add the constraints of any child Layouts in `elements`. var constraints: [NSLayoutConstraint] { get } } public extension Layout { /// Sets all of the nested `UIView`s' `isHidden` property. public func hide(_ isHidden: Bool) { if let view = self as? UIView { print("hiding \(isHidden ? "Y" : "N"): \(view)") if let stack = view as? UIStackView { print(stack.arrangedSubviews.map { "\t\($0.isHidden)" }) } view.isHidden = isHidden } for layout in elements { layout.hide(isHidden) } } var constraints: [NSLayoutConstraint] { return [] } /// Convenience function returning the `constraints` for laying out `self` and all of the `constraints` for each `Layout` in `elements`, recursively generating them for all children. public func combinedConstraints() -> [NSLayoutConstraint] { return self.constraints + elements.reduce([], { $0 + $1.combinedConstraints() }) } /// Recursive function updating all the child `UIView`s in `elements` to have `translatesAutoresizingMaskIntoConstraints` to `false`. public func useInAutoLayout() { if let view = self as? UIView { view.translatesAutoresizingMaskIntoConstraints = false } for layout in elements { if let view = layout as? UIView { view.translatesAutoresizingMaskIntoConstraints = false } else if layout is UILayoutGuide { // do nothing } else { // iterate sub layouts layout.useInAutoLayout() } } } }
mit
f391f623f13b26e493919d4d4602e2b8
35.771429
244
0.614608
4.931034
false
false
false
false
swift-montevideo/HelloZewo
Sources/Database.swift
1
1359
import PostgreSQL struct Database { //The host where the database server is running. It can be an IP address or //a valid DNS name private let host: String init(host: String) { self.host = host } func getAll() throws -> [Todo] { let connection = Connection(host: self.host, databaseName: "postgres", username: "postgres") defer { connection.close() } try connection.open() return try connection.execute("SELECT * FROM TODOS") .map { row in let id: Int = try row.value("id") let text: String = try row.value("text") return Todo(id: id, text: text) } } func add(withText text: String) throws { let connection = Connection(host: host, databaseName: "postgres", username: "postgres") defer { connection.close() } try connection.open() try connection.execute("INSERT INTO TODOS(text) VALUES(%@)", parameters: text) } func remove(withId id: Int) throws { let connection = Connection(host: host, databaseName: "postgres", username: "postgres") defer { connection.close() } try connection.open() try connection.execute("DELETE FROM TODOS WHERE id = %@", parameters: id) } }
mit
601b8ce8e8d979268597d0cadf401812
25.647059
100
0.569536
4.412338
false
false
false
false
WushuputiGH/Developing-iOS-9-Apps-with-Swift-FaceIt
FaceIt/FaceIt/FaceView.swift
1
6013
// // FaceView.swift // FaceIt // // Created by lanou on 16/6/4. // Copyright © 2016年 an. All rights reserved. // import UIKit @IBDesignable class FaceView: UIView { @IBInspectable var scale: CGFloat = 0.9 { didSet { setNeedsDisplay() } } // mouthCurvature 用来设置微笑的曲率 @IBInspectable var mouthCurvature: Double = 0.8 { didSet { setNeedsDisplay() } } // 用来判读眼睛睁开还是闭合 @IBInspectable var eyesOpen:Bool = true { didSet { setNeedsDisplay() } } // @IBInspectable var eyeBrowTilt: Double = -0.5 { didSet { setNeedsDisplay() } } @IBInspectable var color:UIColor = UIColor.blueColor() { didSet { setNeedsDisplay() } } @IBInspectable var lineWidth: CGFloat = 5.0 { didSet { setNeedsDisplay() } } func changeScale(recodnizer: UIPinchGestureRecognizer) { switch recodnizer.state { case .Changed, .Ended: scale *= recodnizer.scale recodnizer.scale = 1.0 default: break } } // 计算属性 private var skullRadiue: CGFloat{ /* get{ return min(bounds.size.width, bounds.size.height)/2 } 如果只有getter方法, 可以不写get{} */ return min(bounds.size.width, bounds.size.height) / 2 * scale } private var skullCenter: CGPoint{ return CGPointMake(bounds.midX, bounds.midY) } // 设置眼睛与头部大小的约束 private struct Ratios{ static let SkullRadiuToEyeOffset: CGFloat = 3 static let SkullRadiuToEyeRadius: CGFloat = 10 static let SkullRadiuToMouthWidth: CGFloat = 1 static let SkullRadiuToMouthHeight: CGFloat = 3 static let SkullRadiuToMouthOffset: CGFloat = 3 static let SkullRadiuToBrowOffset: CGFloat = 5 } private enum Eye { case Left case Right } private func pathForCircleCenteredAtPoint(midPoint: CGPoint, withRadius radius: CGFloat) -> UIBezierPath { let path = UIBezierPath( arcCenter: midPoint, radius: radius, startAngle: 0.0, endAngle: CGFloat(2*M_PI), clockwise: false ) path.lineWidth = lineWidth return path } private func getEyeCenter(eye: Eye) -> CGPoint { let eyeOffset = skullRadiue / Ratios.SkullRadiuToEyeOffset var eyeCenter = skullCenter eyeCenter.y -= eyeOffset switch eye { case .Left: eyeCenter.x -= eyeOffset case .Right: eyeCenter.x += eyeOffset } return eyeCenter } private func pathForEye(eye: Eye) -> UIBezierPath { let eyeRadius = skullRadiue / Ratios.SkullRadiuToEyeRadius let eyeCenter = getEyeCenter(eye) if eyesOpen{ return pathForCircleCenteredAtPoint(eyeCenter, withRadius: eyeRadius) } else{ let start = CGPoint(x: eyeCenter.x - eyeRadius, y: eyeCenter.y) let end = CGPoint(x: eyeCenter.x + eyeRadius, y: eyeCenter.y) let path = UIBezierPath() path.moveToPoint(start) path.addLineToPoint(end) path.lineWidth = lineWidth return path; } } private func pathForMouth() -> UIBezierPath { let mouthWidth = skullRadiue / Ratios.SkullRadiuToMouthWidth let mouthHeight = skullRadiue / Ratios.SkullRadiuToMouthHeight let mouthOffet = skullRadiue / Ratios.SkullRadiuToMouthOffset let mouthRect = CGRect(x: skullCenter.x - mouthWidth/2, y: skullCenter.y + mouthOffet, width: mouthWidth, height: mouthHeight) let smileOffset = CGFloat(max(-1, min(mouthCurvature, 1))) * mouthRect.height let start = CGPoint(x: mouthRect.minX, y: mouthRect.minY) let end = CGPoint(x: mouthRect.maxX, y: mouthRect.minY) let cp1 = CGPoint(x: mouthRect.minX + mouthRect.width / 3, y: mouthRect.minY + smileOffset) let cp2 = CGPoint(x: mouthRect.maxX - mouthRect.width / 3 , y: mouthRect.minY + smileOffset) let path = UIBezierPath() path.moveToPoint(start) path.addCurveToPoint(end, controlPoint1: cp1, controlPoint2: cp2) path.lineWidth = lineWidth return path } private func pathForBrow(eye: Eye) -> UIBezierPath { var tilt = eyeBrowTilt; switch eye{ case .Left: tilt *= -1.0; case .Right: break } var browCenter = getEyeCenter(eye) browCenter.y -= skullRadiue / Ratios.SkullRadiuToBrowOffset let eyeRadius = skullRadiue / Ratios.SkullRadiuToEyeRadius let tiltOffset = CGFloat(max(-1, min(tilt, 1))) * eyeRadius / 2 let browStart = CGPoint(x: browCenter.x - eyeRadius, y: browCenter.y - tiltOffset) let browEnd = CGPoint(x: browCenter.x + eyeRadius, y: browCenter.y + tiltOffset) let path = UIBezierPath() path.moveToPoint(browStart) path.addLineToPoint(browEnd) path.lineWidth = lineWidth return path } override func drawRect(rect: CGRect) { color.set() pathForCircleCenteredAtPoint(skullCenter, withRadius: skullRadiue).stroke() pathForEye(.Left).stroke() pathForEye(.Right).stroke() pathForMouth().stroke() pathForBrow(.Left).stroke() pathForBrow(.Right).stroke() /* let width = bounds.size.width let height = bounds.size.height let skullRadiue = min(width, height) / 2 // let skullCenter = convertPoint(center, fromView: superview) let skullCenter = CGPointMake(bounds.midX, bounds.midY); let skull = UIBezierPath(arcCenter: skullCenter, radius: skullRadiue, startAngle: 0.0, endAngle: CGFloat(2*M_PI), clockwise: false) */ } }
apache-2.0
2d4b9e886067a2b24391f73ff76e3ce4
30.468085
139
0.60497
4.054832
false
false
false
false
clarenceji/Clarence-Ji
Clarence Ji/CJImageView.swift
1
745
// // CJImageView.swift // Clarence Ji // // Created by Clarence Ji on 4/20/15. // Copyright (c) 2015 Clarence Ji. All rights reserved. // import UIKit class CJImageView: UIImageView { override init(image: UIImage?) { super.init(image: image) self.contentMode = .scaleAspectFill self.resize(image) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } func resize(_ image: UIImage!) { let screenWidth = UIScreen.main.bounds.width let imageRatio = image.size.height / image.size.width let imageViewHeight = screenWidth * imageRatio self.frame = CGRect(x: 0, y: 0, width: screenWidth, height: imageViewHeight) } }
gpl-3.0
24e6ce83198ddaf90100d95aabfb00f7
24.689655
84
0.62953
3.921053
false
false
false
false
niekang/WeiBo
WeiBo/Class/View/Message/View/WBMessageCellTableViewCell.swift
1
730
// // WBMessageCellTableViewCell.swift // WeiBo // // Created by 聂康 on 2019/9/9. // Copyright © 2019 com.nk. All rights reserved. // import UIKit class WBMessageCellTableViewCell: UITableViewCell { @IBOutlet weak var iconView: UIImageView! @IBOutlet weak var titleLabel: UILabel! @IBOutlet weak var desLabel: UILabel! var model: WBMessage? { didSet { guard let model = self.model else { return } if let image = model.icon { self.iconView.image = UIImage(named: image) } self.titleLabel.text = model.title self.desLabel.text = model.detail } } }
apache-2.0
8e51b13f576b1fee3d5da7bff0a92ecb
20.969697
59
0.56
4.393939
false
false
false
false
Cin316/X-Schedule
X Schedule/DonorsViewController.swift
1
3922
// // DonorsViewController.swift // X Schedule // // Created by Nicholas Reichert on 3/13/15. // Copyright (c) 2015 Nicholas Reichert. // import UIKit class DonorsViewController: UIViewController { @IBOutlet weak var mainTextView: UITextView! private var donorsPath: String = Bundle.main.path(forResource: "donors", ofType: "txt")! private var editedDonorsPath: String = URL(fileURLWithPath: DonorsViewController.documentsDirectory()).appendingPathComponent("editedDonors.txt").relativePath private var onlineDonorsURL: URL = URL(string: "https://raw.githubusercontent.com/Cin316/X-Schedule/develop/donors.txt")! override func viewDidAppear(_ animated: Bool) { mainTextView.flashScrollIndicators() } override func viewDidLoad() { super.viewDidLoad() displayStoredFiles() updateStoredDonors() fixTextClippingBug() } private func displayStoredFiles() { //Read path from editedDonors.txt and display it if it exists. if (fileExists(editedDonorsPath)) { displayContentsOfFile(editedDonorsPath) } else { //If it doesn't, read donors.txt in the read-only app bundle and display it. displayContentsOfFile(donorsPath) } } private func updateStoredDonors() { //Attempt to download donors from website and update saved donors.txt. let session = downloadSession() let postSession = session.downloadTask(with: onlineDonorsURL, completionHandler: { (url: URL?, response: URLResponse?, error: Error?) -> Void in //If the request was successful... if let realURL = url { //Get text of download. let fileText = try? String(contentsOf: realURL, encoding: String.Encoding.utf8) if let realFileText = fileText { //Save to editedDonors.txt. self.saveEditedDonorsText(realFileText) //Display in GUI DispatchQueue.main.async { self.displayStoredFiles() } } } } ) postSession.resume() } private func downloadSession() -> URLSession { let config: URLSessionConfiguration = URLSessionConfiguration.default let session: URLSession = URLSession(configuration: config) return session } private func saveEditedDonorsText(_ downloadedText: String) { do { try downloadedText.write(toFile: self.editedDonorsPath, atomically: false, encoding: String.Encoding.utf8) } catch _ { } } private func displayDonors(_ donorListText: String?) { //Displays the list of donors in a center aligned text view. if let donorList = donorListText { mainTextView.text = donorList } } private func displayContentsOfFile(_ filePath: String) { let fileContents: String? = try? String(contentsOfFile: filePath, encoding: String.Encoding.utf8) displayDonors(fileContents) } private class func documentsDirectory() -> String { let directories: [String] = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.allDomainsMask, true) let documentsDirectory: String = directories[0] return documentsDirectory } private func fileExists(_ filePath: String) -> Bool { let manager: FileManager = FileManager.default let exists: Bool = manager.fileExists(atPath: filePath) return exists } private func fixTextClippingBug() { mainTextView.isScrollEnabled = false mainTextView.isScrollEnabled = true } }
mit
50b0bfef72bc06994a491d95e3fd3148
37.07767
178
0.626211
5.03466
false
false
false
false
creatubbles/ctb-api-swift
CreatubblesAPIClient/Sources/DAO/BatchFetch/Galleries/FeaturedGalleriesBatchFetchOperation.swift
1
2236
// // FeaturedGalleriesBatchFetchOperation.swift // CreatubblesAPIClient // // Copyright (c) 2017 Creatubbles Pte. Ltd. // // 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. // class FeaturedGalleriesBatchFetchOperation: ConcurrentOperation { private let requestSender: RequestSender let pagingData: PagingData private(set) var galleries: Array<Gallery>? private var requestHandler: RequestHandler? init(requestSender: RequestSender, pagingData: PagingData, complete: OperationCompleteClosure?) { self.requestSender = requestSender self.pagingData = pagingData super.init(complete: complete) } override func main() { guard isCancelled == false else { return } let request = FeaturedGalleriesRequest(page: pagingData.page, perPage: pagingData.pageSize) let handler = GalleriesResponseHandler { [weak self](galleries, _, error) -> (Void) in self?.galleries = galleries self?.finish(error) } requestHandler = requestSender.send(request, withResponseHandler: handler) } override func cancel() { requestHandler?.cancel() super.cancel() } }
mit
67c3db9dca2e570769655ae999c3fd60
39.654545
101
0.718247
4.648649
false
false
false
false
immustard/MSTTools_Swift
MSTTools_Swift/Categories/UIViewMST.swift
1
5205
// // UIViewMST.swift // MSTTools_Swift // // Created by 张宇豪 on 2017/6/7. // Copyright © 2017年 张宇豪. All rights reserved. // import UIKit // MARK: - Frame extension UIView { public var mst_top: CGFloat { get { return frame.origin.y } set { frame.origin.y = newValue } } public var mst_left: CGFloat { get { return frame.origin.x } set { frame.origin.x = newValue } } public var mst_right: CGFloat { get { return mst_left + mst_width } set { mst_left = newValue - mst_width } } public var mst_bottom: CGFloat { get { return mst_top + mst_width } set { mst_top = newValue - mst_height } } public var mst_width: CGFloat { get { return frame.size.width } set { frame.size.width = newValue } } public var mst_height: CGFloat { get { return frame.size.height } set { frame.size.height = newValue } } public var mst_mstCenterX: CGFloat { get { return center.x } set { center.x = newValue } } public var mst_mstCenterY: CGFloat { get { return center.y } set { center.y = newValue } } public var mst_origin: CGPoint { get { return frame.origin } set { frame.origin = newValue } } public var mst_size: CGSize { get { return frame.size } set { frame.size = newValue } } } // MARK: - Subview extension UIView { /// 根据 tag 获得子视图 public func mst_subview(tag: Int) -> UIView? { return self.viewWithTag(tag) } /// 删除所有子视图 public func mst_removeAllSubviews() { while subviews.count > 0 { let subview = subviews.first subview?.removeFromSuperview() } } /// 根据 tag 删除子视图 public func mst_removeSubview(tag: Int) { guard tag != 0 else { return } let subview = mst_subview(tag: tag) subview?.removeFromSuperview() } /// 根据 tags 删除多个子视图 public func mst_removeSubviews(tags: Array<Int>) { for tag in tags { mst_removeSubview(tag: tag) } } /// 删除比该 tag 小的视图 public func mst_removeSubviewLessThan(tag: Int) { var views: Array<UIView> = [] for subview in subviews { if subview.tag != 0 && subview.tag < tag { views.append(subview) } } mp_removeSubviews(views: views) } /// 删除比该 tag 大的视图 public func mst_removeSubviewGreaterThan(tag: Int) { var views: Array<UIView> = [] for subview in subviews { if subview.tag != 0 && subview.tag > tag { views.append(subview) } } mp_removeSubviews(views: views) } private func mp_removeSubviews(views: Array<UIView>) { for view in views { view.removeFromSuperview() } } } // MARK: - View Controller extension UIView { /// 得到该视图所在的视图控制器 public func mst_responderViewController() -> UIViewController? { var next:UIView? = self repeat { if let nextResponder = next?.next, nextResponder.isKind(of: UIViewController.self) { return (nextResponder as! UIViewController) } next = next?.superview } while next != nil return nil } } // MARK: - Draw Rect extension UIView { /// 设置圆形 public func mst_circular() { mst_cornerRadius(radius: mst_width/2.0) } /// 设置圆角 public func mst_cornerRadius(radius: CGFloat) { layer.cornerRadius = radius layer.masksToBounds = true } /// 设置某几个角为圆角 public func mst_corners(_ corners: UIRectCorner, radius: CGFloat) { let maskPath: UIBezierPath = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius)) let maskLayer: CAShapeLayer = CAShapeLayer() maskLayer.frame = bounds maskLayer.path = maskPath.cgPath layer.mask = maskLayer } /// 设置圆角线框 public func mst_addBorder(radius: CGFloat, lineWidth width: CGFloat, lineColor color: UIColor) { mst_cornerRadius(radius: radius) layer.borderWidth = width layer.borderColor = color.cgColor } } // MARK: - Gesture extension UIView { public func mst_addTapGesture(target: Any?, action: Selector?) { let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: target, action: action) self.addGestureRecognizer(tap) } }
mit
7cdc6e6e4881f6fbacaf283ec0768cdd
22.055046
150
0.525667
4.314163
false
false
false
false
darkdong/DarkSwift
Source/Extension/String.swift
1
2661
// // String.swift // DarkSwift // // Created by Dark Dong on 2017/3/28. // Copyright © 2017年 Dark Dong. All rights reserved. // import Foundation public extension String { var version: OperatingSystemVersion { let versions = components(separatedBy: ".") var major = 0 if versions.count > 0 { major = (versions[0] as NSString).integerValue } var minor = 0 if versions.count > 1 { minor = (versions[1] as NSString).integerValue } var patch = 0 if versions.count > 2 { patch = (versions[2] as NSString).integerValue } return OperatingSystemVersion(majorVersion: major, minorVersion: minor, patchVersion: patch) } func hash(algorithm: Data.DigestAlgorithm, lowercase: Bool = true) -> String { return data(using: .utf8)!.hash(algorithm: algorithm, lowercase: lowercase) } func hmac(algorithm: Data.DigestAlgorithm, key: String, lowercase: Bool = true) -> String { return data(using: .utf8)!.hmac(algorithm: algorithm, keyData: key.data(using: .utf8)!, lowercase: lowercase) } func attributedString(font: UIFont? = nil, color: UIColor? = nil) -> NSMutableAttributedString { var attributes = [NSAttributedString.Key: Any]() if let font = font { attributes[.font] = font } if let color = color { attributes[.foregroundColor] = color } return NSMutableAttributedString(string: self, attributes: attributes) } } public extension NSMutableAttributedString { @discardableResult func addUnderline(style: NSUnderlineStyle, color: UIColor) -> Self { let range = totalRange addAttribute(.underlineStyle, value: style.rawValue, range: range) addAttribute(.underlineColor, value: color, range: range) return self } @discardableResult func addStrikethrough(style: NSUnderlineStyle, color: UIColor) -> Self { let range = totalRange addAttribute(.baselineOffset, value: 0, range: range) addAttribute(.strikethroughStyle, value: style.rawValue, range: range) addAttribute(.strikethroughColor, value: color, range: range) return self } @discardableResult func addParagraghStyle(_ paragraphStyle: NSParagraphStyle) -> Self { let range = totalRange addAttribute(.paragraphStyle, value: paragraphStyle, range: range) return self } private var totalRange: NSRange { return NSRange(location: 0, length: length) } }
mit
ac5a32ea086170849c95671aad1ca4c2
31.414634
117
0.627916
4.823956
false
false
false
false
Tarovk/Mundus_Client
Mundus_ios/Mundus.swift
1
4433
// // Requests.swift // Mundus_ios // // Created by Team Aldo on 10/01/2017. // Copyright (c) 2017 Team Aldo. All rights reserved. // import UIKit import Starscream import Aldo /// Specific URI commands for Expedition Mundus. public enum MundusRequestURI: String { case REQUEST_QUESTION = "/Aldo/question" case REQUEST_PUBLICATIONS = "/Aldo/publications" case REQUEST_ASSIGNED = "/Aldo/assigned" case REQUEST_PLAYER_PUBLICATIONS = "/Aldo/players" case REQUEST_SUBMIT_ANSWER = "/Aldo/question/%@/answer" case REQUEST_GET_SUBMITTED = "/Aldo/submitted" case REQUEST_REVIEW = "/Aldo/question/%@/review" } /// Class containing static methods to send Mundus specific /// requests using the Aldo Client Library. public class Mundus { /** Sends a request to retrieve all submitted answers in a session. - Parameter callback: A realization of the Callback protocol to be called when a response is returned from the Aldo Framework. */ public class func getSubmittedQuestions(callback: Callback? = nil) { Aldo.request(uri: MundusRequestURI.REQUEST_GET_SUBMITTED.rawValue, method: .get, parameters: [:], callback: callback) } /** Sends a request to submit an answer. - Parameter callback: A realization of the Callback protocol to be called when a response is returned from the Aldo Framework. */ public class func submitQuestion(callback: Callback? = nil, answer: String, questionId: String) { let command: String = String(format: MundusRequestURI.REQUEST_SUBMIT_ANSWER.rawValue, questionId) Aldo.request(uri: command, method: .post, parameters: ["answer": answer], callback: callback) } /** Sends a request to retrieve a question. - Parameter callback: A realization of the Callback protocol to be called when a response is returned from the Aldo Framework. */ public class func getQuestion(callback: Callback? = nil) { Aldo.request(uri: MundusRequestURI.REQUEST_QUESTION.rawValue, method: .get, parameters: [:], callback: callback) } /** Sends a request to retrieve all publications in a session. - Parameter callback: A realization of the Callback protocol to be called when a response is returned from the Aldo Framework. */ public class func getPublications(callback: Callback? = nil) { Aldo.request(uri: MundusRequestURI.REQUEST_PUBLICATIONS.rawValue, method: .get, parameters: [:], callback: callback) } /** Sends a request to retrieve all assigned questions. - Parameter callback: A realization of the Callback protocol to be called when a response is returned from the Aldo Framework. */ public class func getAssignedQuestions(callback: Callback? = nil) { Aldo.request(uri: MundusRequestURI.REQUEST_ASSIGNED.rawValue, method: .get, parameters: [:], callback: callback) } /** Sends a request to retrieve all players including their publications. - Parameter callback: A realization of the Callback protocol to be called when a response is returned from the Aldo Framework. */ public class func getPubPlayers(callback: Callback? = nil) { Aldo.request(uri: MundusRequestURI.REQUEST_PLAYER_PUBLICATIONS.rawValue, method: .get, parameters: [:], callback: callback) } /** Sends a request to update the review status of a question answered by a user. - Parameters: - callback: A realization of the Callback protocol to be called when a response is returned from the Aldo Framework. - review: The new status of the question. - questionId: The id of the question. */ public class func reviewQuestion(callback: Callback? = nil, review: String, questionId: String) { let command: String = String(format: MundusRequestURI.REQUEST_REVIEW.rawValue, questionId) Aldo.request(uri: command, method: .put, parameters: ["reviewed": review], callback: callback) } }
mit
ce01c6a294a806b702844a0f3e390ca2
37.885965
119
0.633206
4.651626
false
false
false
false
ben-ng/swift
stdlib/public/core/ManagedBuffer.swift
1
20930
//===--- ManagedBuffer.swift - variable-sized buffer of aligned memory ----===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftShims /// A class whose instances contain a property of type `Header` and raw /// storage for an array of `Element`, whose size is determined at /// instance creation. /// /// Note that the `Element` array is suitably-aligned **raw memory**. /// You are expected to construct and---if necessary---destroy objects /// there yourself, using the APIs on `UnsafeMutablePointer<Element>`. /// Typical usage stores a count and capacity in `Header` and destroys /// any live elements in the `deinit` of a subclass. /// - Note: Subclasses must not have any stored properties; any storage /// needed should be included in `Header`. open class ManagedBuffer<Header, Element> { /// Create a new instance of the most-derived class, calling /// `factory` on the partially-constructed object to generate /// an initial `Header`. public final class func create( minimumCapacity: Int, makingHeaderWith factory: ( ManagedBuffer<Header, Element>) throws -> Header ) rethrows -> ManagedBuffer<Header, Element> { let p = Builtin.allocWithTailElems_1( self, minimumCapacity._builtinWordValue, Element.self) let initHeaderVal = try factory(p) p.headerAddress.initialize(to: initHeaderVal) // The _fixLifetime is not really needed, because p is used afterwards. // But let's be conservative and fix the lifetime after we use the // headerAddress. _fixLifetime(p) return p } /// The actual number of elements that can be stored in this object. /// /// This header may be nontrivial to compute; it is usually a good /// idea to store this information in the "header" area when /// an instance is created. public final var capacity: Int { let storageAddr = UnsafeMutableRawPointer(Builtin.bridgeToRawPointer(self)) let endAddr = storageAddr + _swift_stdlib_malloc_size(storageAddr) let realCapacity = endAddr.assumingMemoryBound(to: Element.self) - firstElementAddress return realCapacity } internal final var firstElementAddress: UnsafeMutablePointer<Element> { return UnsafeMutablePointer(Builtin.projectTailElems(self, Element.self)) } internal final var headerAddress: UnsafeMutablePointer<Header> { return UnsafeMutablePointer<Header>(Builtin.addressof(&header)) } /// Call `body` with an `UnsafeMutablePointer` to the stored /// `Header`. /// /// - Note: This pointer is valid only for the duration of the /// call to `body`. public final func withUnsafeMutablePointerToHeader<R>( _ body: (UnsafeMutablePointer<Header>) throws -> R ) rethrows -> R { return try withUnsafeMutablePointers { (v, e) in return try body(v) } } /// Call `body` with an `UnsafeMutablePointer` to the `Element` /// storage. /// /// - Note: This pointer is valid only for the duration of the /// call to `body`. public final func withUnsafeMutablePointerToElements<R>( _ body: (UnsafeMutablePointer<Element>) throws -> R ) rethrows -> R { return try withUnsafeMutablePointers { return try body($0.1) } } /// Call `body` with `UnsafeMutablePointer`s to the stored `Header` /// and raw `Element` storage. /// /// - Note: These pointers are valid only for the duration of the /// call to `body`. public final func withUnsafeMutablePointers<R>( _ body: (UnsafeMutablePointer<Header>, UnsafeMutablePointer<Element>) throws -> R ) rethrows -> R { defer { _fixLifetime(self) } return try body(headerAddress, firstElementAddress) } /// The stored `Header` instance. /// /// During instance creation, in particular during /// `ManagedBuffer.create`'s call to initialize, `ManagedBuffer`'s /// `header` property is as-yet uninitialized, and therefore /// reading the `header` property during `ManagedBuffer.create` is undefined. public final var header: Header //===--- internal/private API -------------------------------------------===// /// Make ordinary initialization unavailable internal init(_doNotCallMe: ()) { _sanityCheckFailure("Only initialize these by calling create") } } /// Contains a buffer object, and provides access to an instance of /// `Header` and contiguous storage for an arbitrary number of /// `Element` instances stored in that buffer. /// /// For most purposes, the `ManagedBuffer` class works fine for this /// purpose, and can simply be used on its own. However, in cases /// where objects of various different classes must serve as storage, /// `ManagedBufferPointer` is needed. /// /// A valid buffer class is non-`@objc`, with no declared stored /// properties. Its `deinit` must destroy its /// stored `Header` and any constructed `Element`s. /// /// Example Buffer Class /// -------------------- /// /// class MyBuffer<Element> { // non-@objc /// typealias Manager = ManagedBufferPointer<(Int, String), Element> /// deinit { /// Manager(unsafeBufferObject: self).withUnsafeMutablePointers { /// (pointerToHeader, pointerToElements) -> Void in /// pointerToElements.deinitialize(count: self.count) /// pointerToHeader.deinitialize() /// } /// } /// /// // All properties are *computed* based on members of the Header /// var count: Int { /// return Manager(unsafeBufferObject: self).header.0 /// } /// var name: String { /// return Manager(unsafeBufferObject: self).header.1 /// } /// } /// @_fixed_layout public struct ManagedBufferPointer<Header, Element> : Equatable { /// Create with new storage containing an initial `Header` and space /// for at least `minimumCapacity` `element`s. /// /// - parameter bufferClass: The class of the object used for storage. /// - parameter minimumCapacity: The minimum number of `Element`s that /// must be able to be stored in the new buffer. /// - parameter factory: A function that produces the initial /// `Header` instance stored in the buffer, given the `buffer` /// object and a function that can be called on it to get the actual /// number of allocated elements. /// /// - Precondition: `minimumCapacity >= 0`, and the type indicated by /// `bufferClass` is a non-`@objc` class with no declared stored /// properties. The `deinit` of `bufferClass` must destroy its /// stored `Header` and any constructed `Element`s. public init( bufferClass: AnyClass, minimumCapacity: Int, makingHeaderWith factory: (_ buffer: AnyObject, _ capacity: (AnyObject) -> Int) throws -> Header ) rethrows { self = ManagedBufferPointer( bufferClass: bufferClass, minimumCapacity: minimumCapacity) // initialize the header field try withUnsafeMutablePointerToHeader { $0.initialize(to: try factory( self.buffer, { ManagedBufferPointer(unsafeBufferObject: $0).capacity })) } // FIXME: workaround for <rdar://problem/18619176>. If we don't // access header somewhere, its addressor gets linked away _ = header } /// Manage the given `buffer`. /// /// - Precondition: `buffer` is an instance of a non-`@objc` class whose /// `deinit` destroys its stored `Header` and any constructed `Element`s. public init(unsafeBufferObject buffer: AnyObject) { ManagedBufferPointer._checkValidBufferClass(type(of: buffer)) self._nativeBuffer = Builtin.castToNativeObject(buffer) } /// Internal version for use by _ContiguousArrayBuffer where we know that we /// have a valid buffer class. /// This version of the init function gets called from /// _ContiguousArrayBuffer's deinit function. Since 'deinit' does not get /// specialized with current versions of the compiler, we can't get rid of the /// _debugPreconditions in _checkValidBufferClass for any array. Since we know /// for the _ContiguousArrayBuffer that this check must always succeed we omit /// it in this specialized constructor. @_versioned internal init(_uncheckedUnsafeBufferObject buffer: AnyObject) { ManagedBufferPointer._sanityCheckValidBufferClass(type(of: buffer)) self._nativeBuffer = Builtin.castToNativeObject(buffer) } /// The stored `Header` instance. public var header: Header { addressWithNativeOwner { return (UnsafePointer(_headerPointer), _nativeBuffer) } mutableAddressWithNativeOwner { return (_headerPointer, _nativeBuffer) } } /// Returns the object instance being used for storage. public var buffer: AnyObject { return Builtin.castFromNativeObject(_nativeBuffer) } /// The actual number of elements that can be stored in this object. /// /// This value may be nontrivial to compute; it is usually a good /// idea to store this information in the "header" area when /// an instance is created. public var capacity: Int { return (_capacityInBytes &- _My._elementOffset) / MemoryLayout<Element>.stride } /// Call `body` with an `UnsafeMutablePointer` to the stored /// `Header`. /// /// - Note: This pointer is valid only /// for the duration of the call to `body`. public func withUnsafeMutablePointerToHeader<R>( _ body: (UnsafeMutablePointer<Header>) throws -> R ) rethrows -> R { return try withUnsafeMutablePointers { (v, e) in return try body(v) } } /// Call `body` with an `UnsafeMutablePointer` to the `Element` /// storage. /// /// - Note: This pointer is valid only for the duration of the /// call to `body`. public func withUnsafeMutablePointerToElements<R>( _ body: (UnsafeMutablePointer<Element>) throws -> R ) rethrows -> R { return try withUnsafeMutablePointers { return try body($0.1) } } /// Call `body` with `UnsafeMutablePointer`s to the stored `Header` /// and raw `Element` storage. /// /// - Note: These pointers are valid only for the duration of the /// call to `body`. public func withUnsafeMutablePointers<R>( _ body: (UnsafeMutablePointer<Header>, UnsafeMutablePointer<Element>) throws -> R ) rethrows -> R { defer { _fixLifetime(_nativeBuffer) } return try body(_headerPointer, _elementPointer) } /// Returns `true` iff `self` holds the only strong reference to its buffer. /// /// See `isUniquelyReferenced` for details. public mutating func isUniqueReference() -> Bool { return _isUnique(&_nativeBuffer) } //===--- internal/private API -------------------------------------------===// /// Create with new storage containing space for an initial `Header` /// and at least `minimumCapacity` `element`s. /// /// - parameter bufferClass: The class of the object used for storage. /// - parameter minimumCapacity: The minimum number of `Element`s that /// must be able to be stored in the new buffer. /// /// - Precondition: `minimumCapacity >= 0`, and the type indicated by /// `bufferClass` is a non-`@objc` class with no declared stored /// properties. The `deinit` of `bufferClass` must destroy its /// stored `Header` and any constructed `Element`s. internal init( bufferClass: AnyClass, minimumCapacity: Int ) { ManagedBufferPointer._checkValidBufferClass(bufferClass, creating: true) _precondition( minimumCapacity >= 0, "ManagedBufferPointer must have non-negative capacity") self.init( _uncheckedBufferClass: bufferClass, minimumCapacity: minimumCapacity) } /// Internal version for use by _ContiguousArrayBuffer.init where we know that /// we have a valid buffer class and that the capacity is >= 0. @_versioned internal init( _uncheckedBufferClass: AnyClass, minimumCapacity: Int ) { ManagedBufferPointer._sanityCheckValidBufferClass(_uncheckedBufferClass, creating: true) _sanityCheck( minimumCapacity >= 0, "ManagedBufferPointer must have non-negative capacity") let totalSize = _My._elementOffset + minimumCapacity * MemoryLayout<Element>.stride let newBuffer: AnyObject = _swift_bufferAllocate( bufferType: _uncheckedBufferClass, size: totalSize, alignmentMask: _My._alignmentMask) self._nativeBuffer = Builtin.castToNativeObject(newBuffer) } /// Manage the given `buffer`. /// /// - Note: It is an error to use the `header` property of the resulting /// instance unless it has been initialized. internal init(_ buffer: ManagedBuffer<Header, Element>) { _nativeBuffer = Builtin.castToNativeObject(buffer) } internal typealias _My = ManagedBufferPointer internal static func _checkValidBufferClass( _ bufferClass: AnyClass, creating: Bool = false ) { _debugPrecondition( _class_getInstancePositiveExtentSize(bufferClass) == MemoryLayout<_HeapObject>.size || ( (!creating || bufferClass is ManagedBuffer<Header, Element>.Type) && _class_getInstancePositiveExtentSize(bufferClass) == _headerOffset + MemoryLayout<Header>.size), "ManagedBufferPointer buffer class has illegal stored properties" ) _debugPrecondition( _usesNativeSwiftReferenceCounting(bufferClass), "ManagedBufferPointer buffer class must be non-@objc" ) } internal static func _sanityCheckValidBufferClass( _ bufferClass: AnyClass, creating: Bool = false ) { _sanityCheck( _class_getInstancePositiveExtentSize(bufferClass) == MemoryLayout<_HeapObject>.size || ( (!creating || bufferClass is ManagedBuffer<Header, Element>.Type) && _class_getInstancePositiveExtentSize(bufferClass) == _headerOffset + MemoryLayout<Header>.size), "ManagedBufferPointer buffer class has illegal stored properties" ) _sanityCheck( _usesNativeSwiftReferenceCounting(bufferClass), "ManagedBufferPointer buffer class must be non-@objc" ) } /// The required alignment for allocations of this type, minus 1 internal static var _alignmentMask: Int { return max( MemoryLayout<_HeapObject>.alignment, max(MemoryLayout<Header>.alignment, MemoryLayout<Element>.alignment)) &- 1 } /// The actual number of bytes allocated for this object. internal var _capacityInBytes: Int { return _swift_stdlib_malloc_size(_address) } /// The address of this instance in a convenient pointer-to-bytes form internal var _address: UnsafeMutableRawPointer { return UnsafeMutableRawPointer(Builtin.bridgeToRawPointer(_nativeBuffer)) } /// Offset from the allocated storage for `self` to the stored `Header` internal static var _headerOffset: Int { _onFastPath() return _roundUp( MemoryLayout<_HeapObject>.size, toAlignment: MemoryLayout<Header>.alignment) } /// An **unmanaged** pointer to the storage for the `Header` /// instance. Not safe to use without _fixLifetime calls to /// guarantee it doesn't dangle internal var _headerPointer: UnsafeMutablePointer<Header> { _onFastPath() return (_address + _My._headerOffset).assumingMemoryBound( to: Header.self) } /// An **unmanaged** pointer to the storage for `Element`s. Not /// safe to use without _fixLifetime calls to guarantee it doesn't /// dangle. internal var _elementPointer: UnsafeMutablePointer<Element> { _onFastPath() return (_address + _My._elementOffset).assumingMemoryBound( to: Element.self) } /// Offset from the allocated storage for `self` to the `Element` storage internal static var _elementOffset: Int { _onFastPath() return _roundUp( _headerOffset + MemoryLayout<Header>.size, toAlignment: MemoryLayout<Element>.alignment) } internal var _nativeBuffer: Builtin.NativeObject } public func == <Header, Element>( lhs: ManagedBufferPointer<Header, Element>, rhs: ManagedBufferPointer<Header, Element> ) -> Bool { return lhs._address == rhs._address } // FIXME: when our calling convention changes to pass self at +0, // inout should be dropped from the arguments to these functions. /// Returns a Boolean value indicating whether the given object is a /// class instance known to have a single strong reference. /// /// The `isKnownUniquelyReferenced(_:)` function is useful for implementing /// the copy-on-write optimization for the deep storage of value types: /// /// mutating func modifyMe(_ arg: X) { /// if isKnownUniquelyReferenced(&myStorage) { /// myStorage.modifyInPlace(arg) /// } else { /// myStorage = self.createModified(myStorage, arg) /// } /// } /// /// Weak references do not affect the result of this function. /// /// This function is safe to use for mutating functions in multithreaded code /// because a false positive implies that there is already a user-level data /// race on the value being mutated. /// /// - Parameter object: An instance of a class. This function does *not* modify /// `object`; the use of `inout` is an implementation artifact. /// - Returns: `true` if `object` is a known to have a /// single strong reference; otherwise, `false`. public func isKnownUniquelyReferenced<T : AnyObject>(_ object: inout T) -> Bool { return _isUnique(&object) } internal func _isKnownUniquelyReferencedOrPinned<T : AnyObject>(_ object: inout T) -> Bool { return _isUniqueOrPinned(&object) } /// Returns a Boolean value indicating whether the given object is a /// class instance known to have a single strong reference. /// /// The `isKnownUniquelyReferenced(_:)` function is useful for implementing /// the copy-on-write optimization for the deep storage of value types: /// /// mutating func modifyMe(_ arg: X) { /// if isKnownUniquelyReferenced(&myStorage) { /// myStorage.modifyInPlace(arg) /// } else { /// myStorage = self.createModified(myStorage, arg) /// } /// } /// /// Weak references do not affect the result of this function. /// /// This function is safe to use for mutating functions in multithreaded code /// because a false positive implies that there is already a user-level data /// race on the value being mutated. /// /// - Parameter object: An instance of a class. This function does *not* modify /// `object`; the use of `inout` is an implementation artifact. /// - Returns: `true` if `object` is a known to have a /// single strong reference; otherwise, `false`. If `object` is `nil`, the /// return value is `false`. public func isKnownUniquelyReferenced<T : AnyObject>( _ object: inout T? ) -> Bool { return _isUnique(&object) } @available(*, unavailable, renamed: "ManagedBuffer") public typealias ManagedProtoBuffer<Header, Element> = ManagedBuffer<Header, Element> extension ManagedBuffer { @available(*, unavailable, renamed: "create(minimumCapacity:makingHeaderWith:)") public final class func create( _ minimumCapacity: Int, initialValue: (ManagedBuffer<Header, Element>) -> Header ) -> ManagedBuffer<Header, Element> { Builtin.unreachable() } } extension ManagedBufferPointer { @available(*, unavailable, renamed: "init(bufferClass:minimumCapacity:makingHeaderWith:)") public init( bufferClass: AnyClass, minimumCapacity: Int, initialValue: (_ buffer: AnyObject, _ allocatedCount: (AnyObject) -> Int) -> Header ) { Builtin.unreachable() } @available(*, unavailable, renamed: "capacity") public var allocatedElementCount: Int { Builtin.unreachable() } @available(*, unavailable, renamed: "isUniqueReference") public mutating func holdsUniqueReference() -> Bool { Builtin.unreachable() } @available(*, unavailable, message: "this API is no longer available") public mutating func holdsUniqueOrPinnedReference() -> Bool { Builtin.unreachable() } } @available(*, unavailable, renamed: "isKnownUniquelyReferenced") public func isUniquelyReferenced<T>( _ object: inout T ) -> Bool { Builtin.unreachable() } @available(*, unavailable, message: "use isKnownUniquelyReferenced instead") public class NonObjectiveCBase {} @available(*, unavailable, renamed: "isKnownUniquelyReferenced") public func isUniquelyReferencedNonObjC<T : AnyObject>( _ object: inout T ) -> Bool { Builtin.unreachable() } @available(*, unavailable, renamed: "isKnownUniquelyReferenced") public func isUniquelyReferencedNonObjC<T : AnyObject>( _ object: inout T? ) -> Bool { Builtin.unreachable() }
apache-2.0
33d4847f0fad3cf5c8764e28ec3a6fab
35.590909
92
0.686383
4.719278
false
false
false
false
julienbodet/wikipedia-ios
Wikipedia/Code/TextSizeChangeExampleViewController.swift
1
1719
import UIKit class TextSizeChangeExampleViewController: UIViewController { fileprivate var theme = Theme.standard @IBOutlet weak var textSizeChangeExampleLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() apply(theme: self.theme) textSizeChangeExampleLabel.text = WMFLocalizedString("appearance-settings-text-sizing-example-text", value: "Drag the slider above to change the article text sizing. Utilize your system text size to resize other text areas in the app.", comment: "Example text of the the Adjust article text sizing section in Appearance settings") NotificationCenter.default.addObserver(self, selector: #selector(self.textSizeChanged(notification:)), name: NSNotification.Name(rawValue: FontSizeSliderViewController.WMFArticleFontSizeUpdatedNotification), object: nil) } deinit { NotificationCenter.default.removeObserver(self) NSObject.cancelPreviousPerformRequests(withTarget: self) } @objc func textSizeChanged(notification: Notification) { if let multiplier = notification.userInfo?[FontSizeSliderViewController.WMFArticleFontSizeMultiplierKey] as? NSNumber { textSizeChangeExampleLabel.font = textSizeChangeExampleLabel.font.withSize(15*CGFloat(truncating: multiplier)/100) } } } extension TextSizeChangeExampleViewController: Themeable { public func apply(theme: Theme) { self.theme = theme guard viewIfLoaded != nil else { return } view.backgroundColor = theme.colors.paperBackground textSizeChangeExampleLabel.textColor = theme.colors.primaryText } }
mit
42b93aaa0702d85c02e2a40d0c838e99
39.928571
338
0.72135
5.40566
false
false
false
false
to4iki/Try
Try/Try.swift
3
3414
// // Try.swift // Try // // Created by Le VanNghia on 6/11/15. // Copyright © 2015 Le Van Nghia. All rights reserved. // import Foundation import Foundation public enum Try<T> { case Success(T) case Failure(ErrorType) // MARK: Constructors // Init with the given success value public init(value: T) { self = .Success(value) } // Init with the given error public init(error: ErrorType) { self = .Failure(error) } // Init with the given throws method public init(@autoclosure _ f: () throws -> T) { do { self = .Success(try f()) } catch { self = .Failure(error) } } // MAKR: Getters // Returns the value when `Success`, otherwise returns nil public var value: T? { if case .Success(let value) = self { return value } return nil } // Returns the error when `Failure`, otherwise returns nil public var error: ErrorType? { if case .Failure(let error) = self { return error } return nil } // MARK: Higher-order functions // map | you can also use `<^>` operator // Creates a new Try by applying a function to the successful result of this Try. // If this Try is completed with an error then the new Try will also contain this error. public func map<U>(f: T -> U) -> Try<U> { switch self { case .Success(let value): return .Success(f(value)) case .Failure(let error): return .Failure(error) } } // flatMap | you can also use `>>-` operator // Creates a new Try by applying a function to the successful result of this Try, // and returns the result of the function as the new Try. // If this Try is completed with an error then the new Try will also contain this error. public func flatMap<U>(f: T throws -> Try<U>) -> Try<U> { switch self { case .Success(let value): do { return try f(value) } catch { return .Failure(error) } case .Failure(let error): return .Failure(error) } } // flatMap without throws | you can also use `>>-` operator // Creates a new Try by applying a function to the successful result of this Try, // and returns the result of the function as the new Try. // If this Try is completed with an error then the new Try will also contain this error. public func flatMap<U>(f: T -> Try<U>) -> Try<U> { switch self { case .Success(let value): return f(value) case .Failure(let error): return .Failure(error) } } // TODO: // recover // recoverWith } // MARK: Operators infix operator <^> { // Left associativity associativity left // Precedence precedence 150 } infix operator >>- { // Left associativity associativity left // Using the same `precedence` value in antitypical/Result precedence 120 } // Operator for `map` public func <^> <T, U> (t: Try<T>, f: T -> U) -> Try<U> { return t.map(f) } // Operator for `flatMap` public func >>- <T, U> (t: Try<T>, f: T -> Try<U>) -> Try<U> { return t.flatMap(f) } public func >>- <T, U> (t: Try<T>, f: T throws -> Try<U>) -> Try<U> { return t.flatMap(f) }
mit
30cd1b1eca3f0f8ff71fc58a701d66f8
24.470149
92
0.566071
3.982497
false
false
false
false
andresbrun/UIKonf_2015
FriendsGlue/FriendsGlue/APIClient.swift
1
6635
// // APIClient.swift // FriendsGlue // // Created by Romain Boulay on 20/05/15. // Copyright (c) 2015 Andres Brun Moreno. All rights reserved. // import Foundation class APIClient { let appToken = "eb3244b31222c1c6c13c9fb1cdd4e29d" var sessionToken: String? static let sharedInstance = APIClient() // DO NOT USE func createTestUser(success: (() -> Void), failure: ((AnyObject)? -> Void)?) { let parameters = [ "user_name": "FriendsGlue", "first_name": "John", "last_name": "Smith", "email": "[email protected]", "password": "password" ] let urlRequest = authenticatedMutableURLRequest("https://api.tapglue.com/0.2/users?withLogin=true", parameters: parameters, httpMethod: "POST") self.request(urlRequest, success: { [unowned self] (json, response) -> Void in if let jsonValue = json as? Dictionary<String, AnyObject> { if let session = jsonValue["session_token"] as? String { self.sessionToken = session println("token \(self.sessionToken)") } else { println("no token...") } } success() }, failure: failure) } func requestSessionToken(success: (() -> Void), failure: ((AnyObject)? -> Void)?) { let parameters = [ "email": "[email protected]", "password": "password" ] let urlRequest = authenticatedMutableURLRequest("https://api.tapglue.com/0.2/user/login", parameters: parameters, httpMethod: "POST") self.request(urlRequest, success: { [unowned self] (json, response) -> Void in if let jsonValue = json as? Dictionary<String, AnyObject> { if let session = jsonValue["session_token"] as? String { self.sessionToken = session println("token \(self.sessionToken)") } else { println("no token...") } } success() }, failure: failure) } func createEvent(event: Event, success: ((event: Event?) -> Void), failure: ((AnyObject)? -> Void)?) { let urlRequest = authenticatedMutableURLRequest("https://api.tapglue.com/0.2/user/events", parameters: event.tapGlueDistantDictionary(), httpMethod: "POST") request(urlRequest, success: { [unowned self] (json, response) -> Void in if let jsonValue = json as? Dictionary<String, AnyObject> { let e = Event.eventFrom(json: jsonValue) dispatch_async(dispatch_get_main_queue(), { () -> Void in success(event: e) }) } else { dispatch_async(dispatch_get_main_queue(), { () -> Void in success(event: nil) }) }}, failure: failure) } func listEvents(success: ((events: [Event]) -> Void), failure: ((AnyObject)? -> Void)?) { let urlRequest = authenticatedMutableURLRequest("https://api.tapglue.com/0.2/user/events", parameters: nil) request(urlRequest, success: { [unowned self] (json, response) -> Void in var events = [Event]() if let eventsJSON = json as? [Dictionary<String, AnyObject>] { for eventJSON in eventsJSON { events.append(Event.eventFrom(json: eventJSON)) } success(events: events) } else { success(events: events) }}, failure: failure) } private func request(request: NSURLRequest, success: ((json: AnyObject?, response: NSHTTPURLResponse?) -> Void)?, failure: ((AnyObject)? -> Void)?) { let session = NSURLSession.sharedSession() let dataTask = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in var parseError: NSError? var parsedObject: AnyObject? parsedObject = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error:&parseError) if let httpResponse = response as? NSHTTPURLResponse { println("httpResponse") println(httpResponse) if (httpResponse.statusCode >= 100 && httpResponse.statusCode < 300) { println("success") if let successBlock = success { successBlock(json: parsedObject, response: httpResponse) } return } } println("failure") if let failureBlock = failure { if (error != nil) { println("failure error: \(error)") failureBlock(error) } else { println("failure parsedObject: \(parsedObject)") failureBlock(parsedObject) } } }) dataTask.resume() } private func authenticatedMutableURLRequest(urlString: String, parameters: AnyObject?, httpMethod: String = "GET") -> NSMutableURLRequest { var basicAuthString = appToken + ":" if let sessionTokenValue = sessionToken { basicAuthString += sessionTokenValue } let basicAuthData = basicAuthString.dataUsingEncoding(NSUTF8StringEncoding) let base64EncodedCredential = basicAuthData!.base64EncodedStringWithOptions(nil) let authString = "Basic \(base64EncodedCredential)" let headers = [ "accept": "application/json", "content-type": "application/json", "authorization": authString ] println("headers: \(headers)") var request = NSMutableURLRequest(URL: NSURL(string: urlString)!, cachePolicy: .UseProtocolCachePolicy, timeoutInterval: 10.0) if let parametersValue = parameters { println("parameters: \(parametersValue)") let postData = NSJSONSerialization.dataWithJSONObject(parametersValue, options: nil, error: nil) request.HTTPBody = postData } request.HTTPMethod = httpMethod request.allHTTPHeaderFields = headers return request } }
mit
e4ae174e72e4b8c0770f95c6a6c2c31e
38.5
164
0.541824
5.261697
false
false
false
false
lenglengiOS/BuDeJie
百思不得姐/Pods/Charts/Charts/Classes/Highlight/CombinedHighlighter.swift
35
2146
// // CombinedHighlighter.swift // Charts // // Created by Daniel Cohen Gindi on 26/7/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 internal class CombinedHighlighter: ChartHighlighter { internal init(chart: CombinedChartView) { super.init(chart: chart) } /// Returns a list of SelectionDetail object corresponding to the given xIndex. /// - parameter xIndex: /// - returns: internal override func getSelectionDetailsAtIndex(xIndex: Int) -> [ChartSelectionDetail] { var vals = [ChartSelectionDetail]() if let data = _chart?.data as? CombinedChartData { // get all chartdata objects var dataObjects = data.allData var pt = CGPoint() for var i = 0; i < dataObjects.count; i++ { for var j = 0; j < dataObjects[i].dataSetCount; j++ { let dataSet = dataObjects[i].getDataSetByIndex(j) // dont include datasets that cannot be highlighted if !dataSet.isHighlightEnabled { continue } // extract all y-values from all DataSets at the given x-index let yVal = dataSet.yValForXIndex(xIndex) if yVal.isNaN { continue } pt.y = CGFloat(yVal) _chart!.getTransformer(dataSet.axisDependency).pointValueToPixel(&pt) if !pt.y.isNaN { vals.append(ChartSelectionDetail(value: Double(pt.y), dataSetIndex: j, dataSet: dataSet)) } } } } return vals } }
apache-2.0
eedf1250621f5605ceb5e888f348cc99
28.805556
113
0.49068
5.530928
false
false
false
false
m-schmidt/Refracto
Refracto/RefractionInputLayout.swift
1
4298
// RefractionInputLayout.swift import UIKit let verticalPickerCellWidth: CGFloat = 100.0 let verticalPickerCellHeight: CGFloat = 11.0 let verticalPickerCellSpacing: CGFloat = 0.0 let verticalPickerCellInset: CGFloat = 2.0 let verticalPickerSupplementaryViewWidth: CGFloat = 22.0 let verticalPickerSupplementaryViewHeight: CGFloat = 16.0 let verticalPickerSupplementaryViewInset: CGFloat = 55.0 class RefractionInputLayout: UICollectionViewFlowLayout { let alignment: RefractionPickerAlignment var headerYPositions: [CGFloat] = [] init(alignment: RefractionPickerAlignment) { self.alignment = alignment super.init() self.itemSize = CGSize(width: verticalPickerCellWidth, height: verticalPickerCellHeight) self.minimumLineSpacing = verticalPickerCellSpacing self.headerReferenceSize = .zero } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func prepare() { guard let collectionView = self.collectionView, let dataSource = collectionView.dataSource else { fatalError() } self.minimumInteritemSpacing = ceil(collectionView.bounds.width - verticalPickerCellWidth); let numOfSections = dataSource.numberOfSections?(in: collectionView) ?? 1 headerYPositions.removeAll(keepingCapacity: true) headerYPositions.reserveCapacity(numOfSections) var y: CGFloat = 0 for section in 0..<numOfSections { headerYPositions.append(rint(y + verticalPickerCellHeight/2)) y += verticalPickerCellHeight * CGFloat(dataSource.collectionView(collectionView, numberOfItemsInSection: section)) } } override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { guard let collectionView = self.collectionView, let superAttributes = super.layoutAttributesForElements(in: rect) else { return nil } var result: [UICollectionViewLayoutAttributes] = [] for attributes in superAttributes { let alignedX = (self.alignment == .left) ? verticalPickerCellInset : collectionView.bounds.width - attributes.frame.width - verticalPickerCellInset let alignedAttributes = attributes.copy() as! UICollectionViewLayoutAttributes alignedAttributes.frame.origin.x = alignedX alignedAttributes.zIndex = 0 result.append(alignedAttributes) } for (section, y) in headerYPositions.enumerated() { let headerRect = CGRect(x: 0, y: y, width: collectionView.bounds.width, height: verticalPickerSupplementaryViewHeight) if headerRect.intersects(rect) { if let a = self.layoutAttributesForSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, at: IndexPath(row: 0, section: section)) { result.append(a) } } } return result } override func layoutAttributesForSupplementaryView(ofKind elementKind: String, at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { guard let collectionView = self.collectionView else { return nil } let alignedAttributes = UICollectionViewLayoutAttributes(forSupplementaryViewOfKind: elementKind, with: indexPath) let alignedX = (self.alignment == .left) ? verticalPickerSupplementaryViewInset : collectionView.bounds.width - verticalPickerSupplementaryViewWidth - verticalPickerSupplementaryViewInset alignedAttributes.frame = CGRect(x: alignedX, y: headerYPositions[indexPath.section], width: verticalPickerSupplementaryViewWidth, height: verticalPickerSupplementaryViewHeight) alignedAttributes.zIndex = 1 return alignedAttributes; } override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint { guard let vc = self.collectionView?.delegate as? RefractionInput, let inset = self.collectionView?.contentInset else { return proposedContentOffset } return vc.contentOffset(for: vc.indexPath(for: proposedContentOffset, contentInset: inset), contentInset: inset) } }
bsd-3-clause
17dedf8ba869be2f03d4accab276c0a1
43.309278
195
0.717078
5.468193
false
false
false
false
CodeEagle/SSPhotoKit
Example/Pods/SSImageBrowser/Source/SSImageBrowser.swift
1
48557
// // SSImageBrowser.swift // Pods // // Created by LawLincoln on 15/7/10. // // import UIKit import pop // MARK: - SSImageBrowserDelegate @objc public protocol SSImageBrowserDelegate: class { optional func photoBrowser(photoBrowser: SSImageBrowser, didShowPhotoAtIndex index: Int) optional func photoBrowser(photoBrowser: SSImageBrowser, didDismissAtPageIndex index: Int) optional func photoBrowser(photoBrowser: SSImageBrowser, willDismissAtPageIndex index: Int) optional func photoBrowser(photoBrowser: SSImageBrowser, captionViewForPhotoAtIndex index: Int) -> SSCaptionView! optional func photoBrowser(photoBrowser: SSImageBrowser, didDismissActionSheetWithButtonIndex index: Int, photoIndex: Int) } public let UIApplicationSaveImageToCameraRoll = "UIApplicationSaveImageToCameraRoll" // MARK: - SSImageBrowser public class SSImageBrowser: UIViewController { // MARK: - public public weak var delegate: SSImageBrowserDelegate! public lazy var displayToolbar = true public lazy var displayCounterLabel = true public lazy var displayArrowButton = true public lazy var displayActionButton = true public lazy var displayDoneButton = true public lazy var useWhiteBackgroundColor = false public lazy var arrowButtonsChangePhotosAnimated = true public lazy var forceHideStatusBar = false public lazy var usePopAnimation = true public lazy var disableVerticalSwipe = false public lazy var actionButtonTitles = [String]() public lazy var backgroundScaleFactor: CGFloat = 1 public lazy var animationDuration: CGFloat = 0.28 public weak var leftArrowImage: UIImage! public weak var leftArrowSelectedImage: UIImage! public weak var rightArrowImage: UIImage! public weak var rightArrowSelectedImage: UIImage! public weak var doneButtonImage: UIImage! public weak var scaleImage: UIImage! public weak var trackTintColor: UIColor! public weak var progressTintColor: UIColor! // MARK: - Private private lazy var photos: [SSPhoto]! = [SSPhoto]() private lazy var pagingScrollView = UIScrollView() private lazy var pageIndexBeforeRotation: UInt = 0 private lazy var currentPageIndex = 0 private lazy var initalPageIndex = 0 private var statusBarOriginallyHidden = false private var performingLayout = false private var rotating = false private var viewIsActive = false private var autoHide = true private var isdraggingPhoto = false private lazy var visiblePages: Set<SSZoomingScrollView>! = Set<SSZoomingScrollView>() private lazy var recycledPages: Set<SSZoomingScrollView>! = Set<SSZoomingScrollView>() private var panGesture: UIPanGestureRecognizer! private var doneButton: UIButton! private var toolbar: UIToolbar! private var previousButton: UIBarButtonItem! private var nextButton: UIBarButtonItem! private var actionButton: UIBarButtonItem! private var counterButton: UIBarButtonItem! private var counterLabel: UILabel! private var actionsSheet: UIAlertController! private var activityViewController: UIActivityViewController! private weak var senderViewForAnimation: UIView! private var senderViewOriginalFrame: CGRect! private var applicationWindow: UIWindow! private var applicationTopViewController: UIViewController! private var firstX: CGFloat = 0 private var firstY: CGFloat = 0 private var hideTask: CancelableTask! private func areControlsHidden() -> Bool { if let t = toolbar { return t.alpha == 0 } return true } deinit { pagingScrollView.delegate = nil NSNotificationCenter.defaultCenter().removeObserver(self) releaseAllUnderlyingPhotos() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } init() { super.init(nibName: nil, bundle: nil) // Defaults initialize() } private func initialize() { view.tintColor = UIColor(red:0.369, green:0.549, blue:0.310, alpha:1) hidesBottomBarWhenPushed = true automaticallyAdjustsScrollViewInsets = false modalPresentationStyle = UIModalPresentationStyle.Custom modalTransitionStyle = UIModalTransitionStyle.CrossDissolve modalPresentationCapturesStatusBarAppearance = true applicationWindow = UIApplication.sharedApplication().delegate?.window! // Listen for IDMPhoto notifications NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("handleSSPhotoLoadingDidEndNotification:"), name: SSPHOTO_LOADING_DID_END_NOTIFICATION, object: nil) } // MARK: - SSPhoto Loading Notification func handleSSPhotoLoadingDidEndNotification(notification: NSNotification) { dispatch_async(dispatch_get_main_queue(), { () -> Void in if let photo = notification.object as? SSPhoto { if let page = self.pageDisplayingPhoto(photo) { if photo.underlyingImage() != nil { page.displayImage() self.loadAdjacentPhotosIfNecessary(photo) } else { page.displayImageFailure() } } } }) } } // MARK: - Init extension SSImageBrowser { public convenience init(aPhotos: [SSPhoto], animatedFromView view: UIView! = nil) { self.init() photos = aPhotos senderViewForAnimation = view performPresentAnimation() } public convenience init(aURLs: [NSURL], animatedFromView view: UIView! = nil) { self.init() let aPhotos = SSPhoto.photosWithURLs(aURLs) photos = aPhotos senderViewForAnimation = view performPresentAnimation() } } // MARK: - Life Cycle extension SSImageBrowser { override public func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor(white: useWhiteBackgroundColor ? 1 : 0, alpha: 1) view.clipsToBounds = true // Setup paging scrolling view let pagingScrollViewFrame = frameForPagingScrollView() pagingScrollView = UIScrollView(frame: pagingScrollViewFrame) pagingScrollView.pagingEnabled = true pagingScrollView.delegate = self pagingScrollView.showsHorizontalScrollIndicator = false pagingScrollView.showsVerticalScrollIndicator = false pagingScrollView.backgroundColor = UIColor.clearColor() pagingScrollView.contentSize = contentSizeForPagingScrollView() view.addSubview(pagingScrollView) // // Transition animation // performPresentAnimation() let currentOrientation = UIApplication.sharedApplication().statusBarOrientation // Toolbar toolbar = UIToolbar(frame: frameForToolbarAtOrientation(currentOrientation)) toolbar.backgroundColor = UIColor.clearColor() toolbar.clipsToBounds = true toolbar.translucent = true toolbar.setBackgroundImage(UIImage(), forToolbarPosition: .Any, barMetrics: UIBarMetrics.Default) // Close Button doneButton = UIButton(type: .Custom) doneButton.frame = frameForDoneButtonAtOrientation(currentOrientation) doneButton.alpha = 1.0 doneButton.addTarget(self, action: Selector("doneButtonPressed"), forControlEvents: .TouchUpInside) if doneButtonImage == nil { doneButton.setTitleColor(UIColor(white: 0.9, alpha: 0.9), forState:[.Normal, .Highlighted]) doneButton.setTitle(SSPhotoBrowserLocalizedStrings("X"), forState: .Normal) doneButton.titleLabel?.font = UIFont.boldSystemFontOfSize(11) doneButton.backgroundColor = UIColor(white: 0.1, alpha: 0.5) doneButton.sizeToFit() doneButton.layer.cornerRadius = doneButton.bounds.size.width/2 } else { doneButton.setBackgroundImage(doneButtonImage, forState: .Normal) doneButton.contentMode = .ScaleAspectFit } let bundle = NSBundle(forClass: SSImageBrowser.self) var imageBundle: NSBundle? if let path = bundle.pathForResource("IDMPhotoBrowser", ofType: "bundle") { imageBundle = NSBundle(path: path) } let scale = Int(UIScreen.mainScreen().scale) var leftOff = leftArrowImage if let path = imageBundle?.pathForResource("images/left\(scale)x", ofType: "png") where leftArrowImage == nil { leftOff = UIImage(contentsOfFile: path)?.imageWithRenderingMode(.AlwaysTemplate) } var rightOff = rightArrowImage if let path = imageBundle?.pathForResource("images/right\(scale)x", ofType: "png") where rightArrowImage == nil { rightOff = UIImage(contentsOfFile: path)?.imageWithRenderingMode(.AlwaysTemplate) } let leftOn = leftArrowSelectedImage ?? leftOff let rightOn = rightArrowSelectedImage ?? rightOff // Arrows previousButton = UIBarButtonItem(customView:customToolbarButtonImage(leftOff, imageSelected: leftOn!, action: Selector("gotoPreviousPage"))) nextButton = UIBarButtonItem(customView:customToolbarButtonImage(rightOff, imageSelected: rightOn!, action: Selector("gotoNextPage"))) // Counter Label counterLabel = UILabel(frame: CGRectMake(0, 0, 95, 40)) counterLabel.textAlignment = .Center counterLabel.backgroundColor = UIColor.clearColor() counterLabel.font = UIFont(name: "Helvetica", size: 17) if !useWhiteBackgroundColor { counterLabel.textColor = UIColor.whiteColor() counterLabel.shadowColor = UIColor.darkTextColor() counterLabel.shadowOffset = CGSizeMake(0, 1) } else { counterLabel.textColor = UIColor.blackColor() } // Counter Button counterButton = UIBarButtonItem(customView: counterLabel) // Action Button actionButton = UIBarButtonItem(barButtonSystemItem: .Action, target: self, action: Selector("actionButtonPressed:")) // Gesture panGesture = UIPanGestureRecognizer(target:self, action: Selector("panGestureRecognized:")) panGesture.minimumNumberOfTouches = 1 panGesture.maximumNumberOfTouches = 1 } public override func viewWillAppear(animated: Bool) { reloadData() super.viewWillAppear(animated) // Status Bar statusBarOriginallyHidden = UIApplication.sharedApplication().statusBarHidden // Update UI hideControlsAfterDelay() } public override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) viewIsActive = true } public override func viewWillLayoutSubviews() { // Flag performingLayout = true let currentOrientation = UIApplication.sharedApplication().statusBarOrientation // Toolbar toolbar.frame = frameForToolbarAtOrientation(currentOrientation) // Done button doneButton.frame = frameForDoneButtonAtOrientation(currentOrientation) // Remember index let indexPriorToLayout = currentPageIndex // Get paging scroll view frame to determine if anything needs changing let pagingScrollViewFrame = frameForPagingScrollView() // Frame needs changing pagingScrollView.frame = pagingScrollViewFrame // Recalculate contentSize based on current orientation pagingScrollView.contentSize = contentSizeForPagingScrollView() // Adjust frames and configuration of each visible page for page in visiblePages { let index = PAGE_INDEX(page) page.frame = frameForPageAtIndex(index) if let captionView = page.captionView { captionView.frame = frameForCaptionView(captionView, atIndex: index) } page.setMaxMinZoomScalesForCurrentBounds() } // Adjust contentOffset to preserve page location based on values collected prior to location pagingScrollView.contentOffset = contentOffsetForPageAtIndex(indexPriorToLayout) didStartViewingPageAtIndex(currentPageIndex) // initial // Reset currentPageIndex = indexPriorToLayout performingLayout = false // Super super.viewWillLayoutSubviews() } override public func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() releaseAllUnderlyingPhotos() recycledPages.removeAll(keepCapacity: false) } public override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) NSNotificationCenter.defaultCenter().postNotificationName("stopAllRequest", object: nil) } } // MARK: - Public Func extension SSImageBrowser { public func reloadData() { releaseAllUnderlyingPhotos() performLayout() self.view.setNeedsLayout() } public func setInitialPageIndex(var index: Int) { let count = numberOfPhotos() if index >= count { index = count - 1 } initalPageIndex = index currentPageIndex = index if self.isViewLoaded() { jumpToPageAtIndex(index) if !viewIsActive { tilePages() } } } public func photoAtIndex(index: Int) -> SSPhoto { return photos[index] } // MARK: - Status Bar public override func preferredStatusBarStyle() -> UIStatusBarStyle { return useWhiteBackgroundColor ? .Default : .LightContent } public override func prefersStatusBarHidden() -> Bool { if forceHideStatusBar { return true } if isdraggingPhoto { if statusBarOriginallyHidden { return true } else { return false } } else { return areControlsHidden() } } public override func preferredStatusBarUpdateAnimation() -> UIStatusBarAnimation { return .Fade } } // MARK: - UIScrollViewDelegate extension SSImageBrowser: UIScrollViewDelegate { public func scrollViewDidScroll(scrollView: UIScrollView) { if !viewIsActive || performingLayout || rotating { return } setControlsHidden(true, animated: false, permanent: false) tilePages() let visibleBounds = pagingScrollView.bounds let x = CGRectGetMidX(visibleBounds) let width = CGRectGetWidth(visibleBounds) let f = x / width var index = Int(floor(f)) if index < 0 { index = 0 } let count = numberOfPhotos() - 1 if index > count { index = count } let previousCurrentPage = currentPageIndex currentPageIndex = index if currentPageIndex != previousCurrentPage { didStartViewingPageAtIndex(index) if arrowButtonsChangePhotosAnimated { updateToolbar() } } } public func scrollViewWillBeginDragging(scrollView: UIScrollView) { // Hide controls when dragging begins setControlsHidden(true, animated: true, permanent: false) } public func scrollViewDidEndDecelerating(scrollView: UIScrollView) { // Update toolbar when page changes if !arrowButtonsChangePhotosAnimated { updateToolbar() } } } // MARK: - Private Func extension SSImageBrowser { // MARK: - Pan Gesture func panGestureRecognized(sender: UIPanGestureRecognizer) { // Initial Setup let scrollView = pageDisplayedAtIndex(currentPageIndex) if scrollView == nil { return } let viewHeight = scrollView.frame.size.height let viewHalfHeight = viewHeight/2 var translatedPoint = sender.translationInView(view) // Gesture Began if sender.state == .Began { setControlsHidden(true, animated: true, permanent: true) firstX = scrollView.center.x firstY = scrollView.center.y senderViewForAnimation?.hidden = currentPageIndex == initalPageIndex isdraggingPhoto = true setNeedsStatusBarAppearanceUpdate() } translatedPoint = CGPointMake(firstX, firstY+translatedPoint.y) scrollView.center = translatedPoint let newY = scrollView.center.y - viewHalfHeight let newAlpha = 1 - fabs(newY)/viewHeight//abs(newY)/viewHeight * 1.8 view.opaque = true view.backgroundColor = UIColor(white: useWhiteBackgroundColor ? 1 : 0, alpha: newAlpha) // Gesture Ended if sender.state == .Ended { if scrollView.center.y > viewHalfHeight + 40 || scrollView.center.y < viewHalfHeight - 40 { if senderViewForAnimation != nil && currentPageIndex == initalPageIndex { performCloseAnimationWithScrollView(scrollView) return } let finalX = firstX var finalY: CGFloat = 0 let windowsHeigt = applicationWindow.frame.size.height if scrollView.center.y > viewHalfHeight+30 { finalY = windowsHeigt*2 } else { finalY = -viewHalfHeight } UIView.animateWithDuration(NSTimeInterval(animationDuration), animations: { scrollView.center = CGPointMake(finalX, finalY) self.view.backgroundColor = UIColor.clearColor() }) UIView.animateWithDuration(NSTimeInterval(animationDuration), delay: 0, options: UIViewAnimationOptions.CurveEaseIn, animations: { scrollView.center = CGPointMake(finalX, finalY) }, completion: { (b) -> Void in }) dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.35 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) {[weak self] in guard let sself = self else { return } sself.doneButtonPressed() } } else { isdraggingPhoto = false setNeedsStatusBarAppearanceUpdate() view.backgroundColor = UIColor(white: useWhiteBackgroundColor ? 1 : 0, alpha: 1) let velocityY = sender.velocityInView(view).y*0.35 let finalX = firstX let finalY = viewHalfHeight let animationDuration = abs(velocityY) * 0.0002 + 0.2 UIView.animateWithDuration( NSTimeInterval(animationDuration), delay: 0, options: .CurveEaseOut, animations: { scrollView.center = CGPointMake(finalX, finalY) }, completion: nil) } } } // MARK: - Control Hiding / Showing func cancelControlHiding() { // If a timer exists then cancel and release cancel(hideTask) } func hideControlsAfterDelay() { if !areControlsHidden() { cancelControlHiding() hideTask = delay(5, work: {[weak self] in guard let sself = self else { return } sself.hideControls() }) } } private func setControlsHidden(hidden: Bool, animated: Bool, permanent: Bool) { // Cancel any timers cancelControlHiding() // Captions var captionViews = Set<SSCaptionView>() for page in visiblePages { if page.captionView != nil { captionViews.insert(page.captionView) } } // Hide/show bars UIView.animateWithDuration(animated ? 0.1 : 0, animations: { let alpha: CGFloat = hidden ? 0 : 1 self.navigationController?.navigationBar.alpha = alpha self.toolbar.alpha = alpha self.doneButton.alpha = alpha for v in captionViews { v.alpha = alpha } }) // Control hiding timer // Will cancel existing timer but only begin hiding if they are visible if !permanent { hideControlsAfterDelay() } setNeedsStatusBarAppearanceUpdate() } private func hideControls() { if autoHide { setControlsHidden(true, animated: true, permanent: false) } } func toggleControls () { setControlsHidden(!areControlsHidden(), animated: true, permanent: false) } // MARK: - NSObject private func releaseAllUnderlyingPhotos() { for obj in photos { obj.unloadUnderlyingImage() } } // MARK: - Data private func numberOfPhotos() -> Int { return photos.count } private func captionViewForPhotoAtIndex(index: Int) -> SSCaptionView! { var captionView:SSCaptionView! = delegate?.photoBrowser?(self, captionViewForPhotoAtIndex: index) if captionView == nil { let photo = photoAtIndex(index) if let _ = photo.caption() { captionView = SSCaptionView(aPhoto: photo) captionView.alpha = areControlsHidden() ? 0 : 1 } }else{ captionView.alpha = areControlsHidden() ? 0 : 1 } return captionView } func imageForPhoto(photo: SSPhoto!) -> UIImage! { if photo != nil{ // Get image or obtain in background if photo.underlyingImage() != nil { return photo.underlyingImage() } else { photo.loadUnderlyingImageAndNotify() if let img = photo.placeholderImage() { return img } } } return nil } private func loadAdjacentPhotosIfNecessary(photo :SSPhoto) { if let page = pageDisplayingPhoto(photo) { let pageIndex = PAGE_INDEX(page) if currentPageIndex == pageIndex { if pageIndex > 0 { let photo = photoAtIndex(pageIndex - 1) if photo.underlyingImage() == nil { photo.loadUnderlyingImageAndNotify() } } let count = numberOfPhotos() if pageIndex < count - 1 { let photo = photoAtIndex(pageIndex + 1) if photo.underlyingImage() == nil { photo.loadUnderlyingImageAndNotify() } } } } } // MARK: - General private func prepareForClosePhotoBrowser() { // Gesture applicationWindow.removeGestureRecognizer(panGesture) autoHide = false // Controls NSObject.cancelPreviousPerformRequestsWithTarget(self) } private func dismissPhotoBrowserAnimated(animated: Bool) { modalTransitionStyle = .CrossDissolve delegate?.photoBrowser?(self, willDismissAtPageIndex: currentPageIndex) dismissViewControllerAnimated(animated, completion: {[weak self] in guard let sself = self else { return } sself.delegate?.photoBrowser?(sself, didDismissAtPageIndex: sself.currentPageIndex) }) } private func getImageFromView(view: UIView) -> UIImage { UIGraphicsBeginImageContext(view.frame.size) if let context = UIGraphicsGetCurrentContext() { view.layer.renderInContext(context) } let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } private func customToolbarButtonImage(image:UIImage, imageSelected selectedImage:UIImage, action: Selector) -> UIButton { let button = UIButton(type: .Custom) button.setBackgroundImage(image, forState: .Normal) button.setBackgroundImage(selectedImage, forState: .Disabled) button.addTarget(self, action: action, forControlEvents: .TouchUpInside) button.contentMode = .Center button.frame = CGRectMake(0,0, image.size.width/2, image.size.height/2) return button } private func topviewController() -> UIViewController! { var topviewController = UIApplication.sharedApplication().keyWindow?.rootViewController while topviewController?.presentedViewController != nil { topviewController = topviewController?.presentedViewController } return topviewController } // MARK: - Animation private func rotateImageToCurrentOrientation(image: UIImage) -> UIImage? { let o = UIApplication.sharedApplication().statusBarOrientation if UIInterfaceOrientationIsLandscape(o) { let orientation = o == .LandscapeLeft ? UIImageOrientation.Left : UIImageOrientation.Right guard let cgImage = image.CGImage else { return nil } let rotatedImage = UIImage(CGImage: cgImage, scale: 1.0, orientation: orientation) return rotatedImage } return image } private func performPresentAnimation() { view.alpha = 0.0 pagingScrollView.alpha = 0.0 if nil != senderViewForAnimation { var imageFromView = scaleImage != nil ? scaleImage : getImageFromView(senderViewForAnimation) imageFromView = rotateImageToCurrentOrientation(imageFromView) senderViewOriginalFrame = senderViewForAnimation.superview?.convertRect(senderViewForAnimation.frame, toView: nil) let screenBound = UIScreen.mainScreen().bounds let screenWidth = screenBound.size.width let screenHeight = screenBound.size.height let fadeView = UIView(frame:CGRectMake(0, 0, screenWidth, screenHeight)) fadeView.backgroundColor = UIColor.clearColor() applicationWindow.addSubview(fadeView) let resizableImageView = UIImageView(image:imageFromView) resizableImageView.frame = senderViewOriginalFrame resizableImageView.clipsToBounds = true resizableImageView.contentMode = .ScaleAspectFit resizableImageView.backgroundColor = UIColor(white: useWhiteBackgroundColor ? 1 : 0, alpha:1) applicationWindow.addSubview(resizableImageView) senderViewForAnimation?.hidden = true typealias Completion = ()->() let completion: Completion = {[weak self] in guard let sself = self else { return } sself.view.alpha = 1.0 sself.pagingScrollView.alpha = 1.0 resizableImageView.backgroundColor = UIColor(white: sself.useWhiteBackgroundColor ? 1 : 0, alpha:1) fadeView.removeFromSuperview() resizableImageView.removeFromSuperview() } UIView.animateWithDuration(NSTimeInterval(animationDuration), animations: { () -> Void in fadeView.backgroundColor = self.useWhiteBackgroundColor ? UIColor.whiteColor() : UIColor.blackColor() }) let scaleFactor = (imageFromView != nil ? imageFromView.size.width : screenWidth) / screenWidth let finalImageViewFrame = CGRectMake(0, (screenHeight/2)-((imageFromView.size.height / scaleFactor)/2), screenWidth, imageFromView.size.height / scaleFactor) if usePopAnimation { animateView(resizableImageView, toFrame: finalImageViewFrame, completion: completion) } else { UIView.animateWithDuration(NSTimeInterval(animationDuration), animations: { () -> Void in resizableImageView.layer.frame = finalImageViewFrame }, completion: { (b) -> Void in if b { completion() } }) } }else{ view.alpha = 1.0 pagingScrollView.alpha = 1.0 } } private func performCloseAnimationWithScrollView(scrollView: SSZoomingScrollView) { let fadeAlpha = 1 - fabs(scrollView.frame.origin.y)/scrollView.frame.size.height var imageFromView = scrollView.photo.underlyingImage() if imageFromView == nil { imageFromView = scrollView.photo.placeholderImage() } typealias Completion = ()->() let completion: Completion = {[weak self] in guard let sself = self else { return } sself.senderViewForAnimation?.hidden = false sself.senderViewForAnimation = nil sself.scaleImage = nil sself.prepareForClosePhotoBrowser() sself.dismissPhotoBrowserAnimated(false) } if imageFromView == nil { completion() return } //imageFromView = [self rotateImageToCurrentOrientation:imageFromView] let screenBound = UIScreen.mainScreen().bounds let screenWidth = screenBound.size.width let screenHeight = screenBound.size.height let scaleFactor = imageFromView.size.width / screenWidth let fadeView = UIView(frame:CGRectMake(0, 0, screenWidth, screenHeight)) fadeView.backgroundColor = self.useWhiteBackgroundColor ? UIColor.whiteColor() : UIColor.blackColor() fadeView.alpha = fadeAlpha applicationWindow.addSubview(fadeView) let resizableImageView = UIImageView(image:imageFromView) resizableImageView.frame = imageFromView != nil ? CGRectMake(0, (screenHeight/2)-((imageFromView.size.height / scaleFactor)/2)+scrollView.frame.origin.y, screenWidth, imageFromView.size.height / scaleFactor) : CGRectZero resizableImageView.contentMode = UIViewContentMode.ScaleAspectFit resizableImageView.backgroundColor = UIColor.clearColor() resizableImageView.clipsToBounds = true applicationWindow.addSubview(resizableImageView) self.view.hidden = true let bcompletion: Completion = {[weak self] in guard let sself = self else { return } sself.senderViewForAnimation?.hidden = false sself.senderViewForAnimation = nil sself.scaleImage = nil fadeView.removeFromSuperview() resizableImageView.removeFromSuperview() sself.prepareForClosePhotoBrowser() sself.dismissPhotoBrowserAnimated(false) } UIView.animateWithDuration(NSTimeInterval(animationDuration), animations: { () -> Void in fadeView.alpha = 0 self.view.backgroundColor = UIColor.clearColor() }) if usePopAnimation { let edge = UIScreen.mainScreen().bounds.height debugPrint("senderViewOriginalFrame:\(senderViewOriginalFrame)") let fromFrame = senderViewOriginalFrame ?? CGRectOffset(resizableImageView.frame, 0, edge) animateView(resizableImageView, toFrame: fromFrame, completion: bcompletion) } else { UIView.animateWithDuration(NSTimeInterval(animationDuration), animations: { () -> Void in resizableImageView.layer.frame = self.senderViewOriginalFrame }, completion: { (b) -> Void in if b { bcompletion() } }) } } // MARK: - Layout private func performLayout() { performingLayout = true let photosCount = numberOfPhotos() visiblePages?.removeAll(keepCapacity: false) recycledPages?.removeAll(keepCapacity: false) if displayToolbar { view.addSubview(toolbar) } else { toolbar.removeFromSuperview() } if displayDoneButton && self.navigationController?.navigationBar == nil { view.addSubview(doneButton) } let fixedLeftSpace = UIBarButtonItem(barButtonSystemItem: .FixedSpace, target: self, action: nil) fixedLeftSpace.width = 32 let flexSpace = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: self, action: nil) var items = [UIBarButtonItem]() if displayActionButton { items.append(fixedLeftSpace) } items.append(flexSpace) if photosCount > 1 && displayArrowButton { items.append(previousButton) } if displayCounterLabel { items.append(flexSpace) items.append(counterButton) } items.append(flexSpace) if photosCount > 1 && displayArrowButton { items.append(nextButton) } items.append(flexSpace) if displayActionButton { items.append(actionButton) } toolbar.items = items updateToolbar() pagingScrollView.contentOffset = contentOffsetForPageAtIndex(currentPageIndex) tilePages() performingLayout = false if !disableVerticalSwipe { view.addGestureRecognizer(panGesture) } } // MARK: - Toolbar private func updateToolbar() { // Counter let count = numberOfPhotos() if count > 1 { counterLabel.text = "\(currentPageIndex + 1) "+SSPhotoBrowserLocalizedStrings("of")+" \(count)" } else { counterLabel.text = nil } // Buttons previousButton.enabled = currentPageIndex > 0 nextButton.enabled = currentPageIndex < count - 1 } private func jumpToPageAtIndex(index: Int) { // Change page let count = numberOfPhotos() if index < count { let pageFrame = frameForPageAtIndex(index) if arrowButtonsChangePhotosAnimated { pagingScrollView.setContentOffset(CGPointMake(pageFrame.origin.x - PADDING, 0), animated: true) } else { pagingScrollView.contentOffset = CGPointMake(pageFrame.origin.x - PADDING, 0) updateToolbar() } } // Update timer to give more time hideControlsAfterDelay() } func gotoPreviousPage() { jumpToPageAtIndex(currentPageIndex - 1) } func gotoNextPage() { jumpToPageAtIndex(currentPageIndex + 1) } // MARK: - Frame Calculations private func isLandscape(orientation: UIInterfaceOrientation) -> Bool { return UIInterfaceOrientationIsLandscape(orientation) } private func frameForToolbarAtOrientation(orientation: UIInterfaceOrientation) -> CGRect{ var height: CGFloat = 44 if isLandscape(orientation) { height = 32 } return CGRectMake(0, view.bounds.size.height - height, view.bounds.size.width, height) } private func frameForDoneButtonAtOrientation(orientation: UIInterfaceOrientation) -> CGRect { let screenBound = view.bounds let screenWidth = screenBound.size.width return CGRectMake(screenWidth - 75, 30, 55, 26) } private func frameForCaptionView(captionView: SSCaptionView, atIndex index: Int) -> CGRect { let pageFrame = frameForPageAtIndex(index) let captionSize = captionView.sizeThatFits(CGSizeMake(pageFrame.size.width, 0)) let captionFrame = CGRectMake(pageFrame.origin.x, pageFrame.size.height - captionSize.height - (toolbar.superview != nil ?toolbar.frame.size.height:0), pageFrame.size.width, captionSize.height) return captionFrame } private func frameForPageAtIndex(index: Int) -> CGRect { // We have to use our paging scroll view's bounds, not frame, to calculate the page placement. When the device is in // landscape orientation, the frame will still be in portrait because the pagingScrollView is the root view controller's // view, so its frame is in window coordinate space, which is never rotated. Its bounds, however, will be in landscape // because it has a rotation transform applied. let bounds = pagingScrollView.bounds var pageFrame = bounds pageFrame.size.width -= (2 * PADDING) pageFrame.origin.x = (bounds.size.width * CGFloat(index)) + PADDING return pageFrame } private func contentSizeForPagingScrollView() -> CGSize{ // We have to use the paging scroll view's bounds to calculate the contentSize, for the same reason outlined above. let bounds = pagingScrollView.bounds let count = numberOfPhotos() return CGSizeMake(bounds.size.width * CGFloat(count), bounds.size.height) } private func frameForPagingScrollView() -> CGRect { var frame = view.bounds frame.origin.x -= PADDING frame.size.width += 2 * PADDING return frame } private func contentOffsetForPageAtIndex(index: Int) -> CGPoint{ let pageWidth = pagingScrollView.bounds.size.width let newOffset = CGFloat(index) * pageWidth return CGPointMake(newOffset, 0) } // MARK: - Paging private func pageDisplayedAtIndex(index: Int) -> SSZoomingScrollView! { for page in visiblePages { if PAGE_INDEX(page) == index { return page } } return nil } private func pageDisplayingPhoto(photo: SSPhoto) -> SSZoomingScrollView! { var aPage: SSZoomingScrollView! for page in visiblePages { if let bPhoto = page.photo { if bPhoto == photo { aPage = page } } } return aPage } private func isDisplayingPageForIndex(index: Int) -> Bool { for page in visiblePages { let pageIndex = PAGE_INDEX(page) if pageIndex == index { return true } } return false } private func configurePage(page: SSZoomingScrollView, forIndex index: Int) { page.frame = frameForPageAtIndex(index) page.tag = PAGE_INDEX_TAG_OFFSET + index page.setAPhoto(photoAtIndex(index)) page.photo?.progressUpdateBlock = {[unowned page] (progress) -> Void in dispatch_async(dispatch_get_main_queue(), { () -> Void in page.setProgress(progress, forPhoto: page.photo) }) } } private func dequeueRecycledPage() -> SSZoomingScrollView! { let page = recycledPages.first if page != nil { recycledPages.remove(page!) } return page } private func didStartViewingPageAtIndex(index: Int) { // Load adjacent images if needed and the photo is already // loaded. Also called after photo has been loaded in background let currentPhoto = photoAtIndex(index) if currentPhoto.underlyingImage() != nil { // photo loaded so load ajacent now loadAdjacentPhotosIfNecessary(currentPhoto) } delegate?.photoBrowser?(self, didShowPhotoAtIndex: index) } private func tilePages() { let visibleBounds = pagingScrollView.bounds var iFirstIndex = Int(floor((CGRectGetMinX(visibleBounds)+PADDING*2) / CGRectGetWidth(visibleBounds))) var iLastIndex = Int(floor((CGRectGetMaxX(visibleBounds)-PADDING*2-1) / CGRectGetWidth(visibleBounds))) let phototCount = numberOfPhotos() if iFirstIndex < 0 { iFirstIndex = 0 } if iFirstIndex > phototCount - 1 { iFirstIndex = phototCount - 1 } if iLastIndex < 0 { iLastIndex = 0 } if iLastIndex > phototCount - 1 { iLastIndex = phototCount - 1 } // Recycle no longer needed pages var pageIndex: Int = 0 for page in visiblePages { pageIndex = PAGE_INDEX(page) if pageIndex < iFirstIndex || pageIndex > iLastIndex { recycledPages.insert(page) page.prepareForReuse() page.removeFromSuperview() } } let _ = visiblePages.exclusiveOr(recycledPages) var pages = Set<SSZoomingScrollView>() if recycledPages.count > 2 { let array = Array(recycledPages) pages.insert(array[0]) pages.insert(array[1]) } else { pages = recycledPages }// Only keep 2 recycled pages recycledPages = pages // Add missing pages for index in iFirstIndex...iLastIndex { if !isDisplayingPageForIndex(index) { let page = SSZoomingScrollView(aPhotoBrowser: self) page.backgroundColor = UIColor.clearColor() page.opaque = true configurePage(page, forIndex: index) visiblePages.insert(page) pagingScrollView.addSubview(page) if let captionView = captionViewForPhotoAtIndex(index) { captionView.frame = frameForCaptionView(captionView, atIndex: index) pagingScrollView.addSubview(captionView) page.captionView = captionView } } } } // MARK: - Buttons func doneButtonPressed() { if senderViewForAnimation != nil && currentPageIndex == initalPageIndex { let scrollView = pageDisplayedAtIndex(currentPageIndex) performCloseAnimationWithScrollView(scrollView) } else { senderViewForAnimation?.hidden = false prepareForClosePhotoBrowser() dismissPhotoBrowserAnimated(true) } } func actionButtonPressed(sender:AnyObject) { let photo = photoAtIndex(currentPageIndex) let count = self.numberOfPhotos() if count > 0 && photo.underlyingImage() != nil { if actionButtonTitles.count == 0 { if let image = photo.underlyingImage() { var activityItems: [AnyObject] = [image] if let caption = photo.caption() { activityItems.append(caption) } activityViewController = UIActivityViewController(activityItems: activityItems, applicationActivities: nil) activityViewController.completionWithItemsHandler = {[weak self] (activityType, completed, returnedItems, activityError) -> Void in guard let sself = self else { return } sself.hideControlsAfterDelay() if activityType == "com.apple.UIKit.activity.SaveToCameraRoll" { NSNotificationCenter.defaultCenter().postNotificationName(UIApplicationSaveImageToCameraRoll, object: sself) } sself.activityViewController = nil } presentViewController(activityViewController, animated: true, completion: nil) } }else{ // Action sheet actionsSheet = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet) for (index, atitle) in actionButtonTitles.enumerate() { let action = UIAlertAction(title: atitle, style: UIAlertActionStyle.Default, handler:{[weak self] (aAction) -> Void in guard let sself = self else { return } sself.actionsSheet = nil sself.delegate?.photoBrowser?(sself, didDismissActionSheetWithButtonIndex: index, photoIndex: sself.currentPageIndex) sself.hideControlsAfterDelay() }) actionsSheet.addAction(action) } let action = UIAlertAction(title: SSPhotoBrowserLocalizedStrings("Cancel"), style: UIAlertActionStyle.Cancel, handler:{[weak self] (aAction) -> Void in guard let sself = self else { return } sself.actionsSheet = nil sself.hideControlsAfterDelay() }) actionsSheet.addAction(action) presentViewController(actionsSheet, animated: true, completion: nil) } } setControlsHidden(false, animated: true, permanent: true) } // MARK: - pop Animation private func animateView(view: UIView, toFrame frame: CGRect, completion: (()->())! ) { let ainamtion = POPSpringAnimation(propertyNamed: kPOPViewFrame) ainamtion.springBounciness = 6 ainamtion.dynamicsMass = 1 ainamtion.toValue = NSValue(CGRect: frame) view.pop_addAnimation(ainamtion, forKey: nil) ainamtion.completionBlock = { (aniamte,finish) in completion?() } } } extension SSImageBrowser { typealias CancelableTask = (cancel: Bool) -> Void func delay(time: NSTimeInterval, work: dispatch_block_t) -> CancelableTask? { var finalTask: CancelableTask? let cancelableTask: CancelableTask = { cancel in if cancel { finalTask = nil // key } else { dispatch_async(dispatch_get_main_queue(), work) } } finalTask = cancelableTask dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(time * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { if let task = finalTask { task(cancel: false) } } return finalTask } func cancel(cancelableTask: CancelableTask?) { cancelableTask?(cancel: true) } }
mit
633c66a55d73c0ca72245f95f8101679
37.263987
228
0.593756
5.808948
false
false
false
false
Finb/V2ex-Swift
Controller/SettingsTableViewController.swift
1
4351
// // SettingsTableViewController.swift // V2ex-Swift // // Created by huangfeng on 2/23/16. // Copyright © 2016 Fin. All rights reserved. // import UIKit class SettingsTableViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() self.title = NSLocalizedString("viewOptions") self.tableView.separatorStyle = .none if #available(iOS 15.0, *) { tableView.sectionHeaderTopPadding = 0.0 } regClass(self.tableView, cell: BaseDetailTableViewCell.self) regClass(self.tableView, cell: FontSizeSliderTableViewCell.self) regClass(self.tableView, cell: FontDisplayTableViewCell.self) self.themeChangedHandler = {[weak self] (style) -> Void in self?.view.backgroundColor = V2EXColor.colors.v2_backgroundColor self?.tableView.reloadData() } } override func numberOfSections(in tableView: UITableView) -> Int { return 2 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return [3,3][section] } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 44 } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let label = UILabel() label.text = [NSLocalizedString("viewOptionThemeSet") ,NSLocalizedString("viewOptionTextSize") ][section] label.textColor = V2EXColor.colors.v2_TopicListUserNameColor label.font = v2Font(12) label.backgroundColor = V2EXColor.colors.v2_backgroundColor return label } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if indexPath.section == 0 { if indexPath.row == 0 { if #available(iOS 13.0, *) { return 44 } else{ return 0 } } return 44 } else { return [70,25,185][indexPath.row] } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if indexPath.section == 0 { let cell = getCell(tableView, cell: BaseDetailTableViewCell.self, indexPath: indexPath) cell.clipsToBounds = true cell.titleLabel.text = [NSLocalizedString("followSystem"), NSLocalizedString("default"), NSLocalizedString("dark")][indexPath.row] var index:Int = ([V2EXColor.V2EXColorStyleDefault,V2EXColor.V2EXColorStyleDark] .firstIndex{ $0 == V2EXColor.sharedInstance.style } ?? 0) + 1 if V2EXColor.sharedInstance.isFollowSystem { index = 0 } cell.detailLabel.text = index == indexPath.row ? NSLocalizedString("current") : "" return cell } else { if indexPath.row == 0 { let cell = getCell(tableView, cell: FontSizeSliderTableViewCell.self, indexPath: indexPath) return cell } else if indexPath.row == 1 { let cell = getCell(tableView, cell: BaseDetailTableViewCell.self, indexPath: indexPath) cell.backgroundColor = V2EXColor.colors.v2_backgroundColor cell.detailMarkHidden = true return cell } else{ let cell = getCell(tableView, cell: FontDisplayTableViewCell.self, indexPath: indexPath) return cell } } } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if indexPath.section == 0 { if indexPath.row == 0 { //跟随系统 V2EXColor.sharedInstance.isFollowSystem = true } else{ V2EXColor.sharedInstance.isFollowSystem = false V2EXColor.sharedInstance.setStyleAndSave( [V2EXColor.V2EXColorStyleDefault, V2EXColor.V2EXColorStyleDark][indexPath.row - 1]) } } } }
mit
5abce26da5f40ee57fcb30dc5524033e
36.111111
109
0.585444
5.084309
false
false
false
false
guidomb/Portal
Example/Views/DefaultScreen.swift
1
788
// // DefaultScreen.swift // PortalExample // // Created by Guido Marucci Blas on 6/10/17. // Copyright © 2017 Guido Marucci Blas. All rights reserved. // import Portal enum DefaultScreen { typealias Action = Portal.Action<Route, Message> typealias View = Portal.View<Route, Message, Navigator> static func view() -> View { return View( navigator: .main, root: .simple, component: container( children: [], style: styleSheet() { $0.backgroundColor = .red }, layout: layout() { $0.flex = flex() { $0.grow = .one } } ) ) } }
mit
6fb9ead8fcbf46248ae9cb002cf9ac14
22.147059
61
0.458704
4.684524
false
false
false
false
MadAppGang/SmartLog
iOS/Pods/Charts/Source/Charts/Data/Implementations/Standard/BarChartDataEntry.swift
32
6760
// // BarChartDataEntry.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation open class BarChartDataEntry: ChartDataEntry { /// the values the stacked barchart holds fileprivate var _yVals: [Double]? /// the ranges for the individual stack values - automatically calculated fileprivate var _ranges: [Range]? /// the sum of all negative values this entry (if stacked) contains fileprivate var _negativeSum: Double = 0.0 /// the sum of all positive values this entry (if stacked) contains fileprivate var _positiveSum: Double = 0.0 public required init() { super.init() } /// Constructor for normal bars (not stacked). public override init(x: Double, y: Double) { super.init(x: x, y: y) } /// Constructor for normal bars (not stacked). public override init(x: Double, y: Double, data: AnyObject?) { super.init(x: x, y: y, data: data) } /// Constructor for normal bars (not stacked). public override init(x: Double, y: Double, icon: NSUIImage?) { super.init(x: x, y: y, icon: icon) } /// Constructor for normal bars (not stacked). public override init(x: Double, y: Double, icon: NSUIImage?, data: AnyObject?) { super.init(x: x, y: y, icon: icon, data: data) } /// Constructor for stacked bar entries. public init(x: Double, yValues: [Double]) { super.init(x: x, y: BarChartDataEntry.calcSum(values: yValues)) self._yVals = yValues calcPosNegSum() calcRanges() } /// This constructor is misleading, please use the `data` argument instead of `label`. @available(*, deprecated: 1.0, message: "Use `data` argument instead of `label`.") public init(x: Double, yValues: [Double], label: String) { super.init(x: x, y: BarChartDataEntry.calcSum(values: yValues), data: label as AnyObject?) self._yVals = yValues calcPosNegSum() calcRanges() } /// Constructor for stacked bar entries. One data object for whole stack public init(x: Double, yValues: [Double], data: AnyObject?) { super.init(x: x, y: BarChartDataEntry.calcSum(values: yValues), data: data) self._yVals = yValues calcPosNegSum() calcRanges() } /// Constructor for stacked bar entries. One data object for whole stack public init(x: Double, yValues: [Double], icon: NSUIImage?, data: AnyObject?) { super.init(x: x, y: BarChartDataEntry.calcSum(values: yValues), icon: icon, data: data) self._yVals = yValues calcPosNegSum() calcRanges() } /// Constructor for stacked bar entries. One data object for whole stack public init(x: Double, yValues: [Double], icon: NSUIImage?) { super.init(x: x, y: BarChartDataEntry.calcSum(values: yValues), icon: icon) self._yVals = yValues calcPosNegSum() calcRanges() } open func sumBelow(stackIndex :Int) -> Double { if _yVals == nil { return 0 } var remainder: Double = 0.0 var index = _yVals!.count - 1 while (index > stackIndex && index >= 0) { remainder += _yVals![index] index -= 1 } return remainder } /// - returns: The sum of all negative values this entry (if stacked) contains. (this is a positive number) open var negativeSum: Double { return _negativeSum } /// - returns: The sum of all positive values this entry (if stacked) contains. open var positiveSum: Double { return _positiveSum } open func calcPosNegSum() { if _yVals == nil { _positiveSum = 0.0 _negativeSum = 0.0 return } var sumNeg: Double = 0.0 var sumPos: Double = 0.0 for f in _yVals! { if f < 0.0 { sumNeg += -f } else { sumPos += f } } _negativeSum = sumNeg _positiveSum = sumPos } /// Splits up the stack-values of the given bar-entry into Range objects. /// - parameter entry: /// - returns: open func calcRanges() { let values = yValues if values?.isEmpty != false { return } if _ranges == nil { _ranges = [Range]() } else { _ranges?.removeAll() } _ranges?.reserveCapacity(values!.count) var negRemain = -negativeSum var posRemain: Double = 0.0 for i in 0 ..< values!.count { let value = values![i] if value < 0 { _ranges?.append(Range(from: negRemain, to: negRemain - value)) negRemain -= value } else { _ranges?.append(Range(from: posRemain, to: posRemain + value)) posRemain += value } } } // MARK: Accessors /// the values the stacked barchart holds open var isStacked: Bool { return _yVals != nil } /// the values the stacked barchart holds open var yValues: [Double]? { get { return self._yVals } set { self.y = BarChartDataEntry.calcSum(values: newValue) self._yVals = newValue calcPosNegSum() calcRanges() } } /// - returns: The ranges of the individual stack-entries. Will return null if this entry is not stacked. open var ranges: [Range]? { return _ranges } // MARK: NSCopying open override func copyWithZone(_ zone: NSZone?) -> AnyObject { let copy = super.copyWithZone(zone) as! BarChartDataEntry copy._yVals = _yVals copy.y = y copy._negativeSum = _negativeSum return copy } /// Calculates the sum across all values of the given stack. /// /// - parameter vals: /// - returns: fileprivate static func calcSum(values: [Double]?) -> Double { guard let values = values else { return 0.0 } var sum = 0.0 for f in values { sum += f } return sum } }
mit
f56c59d6f7f35b73d1f495f2ea217442
25.303502
111
0.535651
4.509673
false
false
false
false
squaremeals/squaremeals-ios-app
SquareMeals/Coordinator/AuthenticationCoordinator.swift
1
1926
// // AuthenticationCoordinator.swift // SquareMeals // // Created by Zachary Shakked on 10/24/17. // Copyright © 2017 Shakd, LLC. All rights reserved. // import UIKit public protocol AuthenticationCoordinatorDelegate: class { func authenticationCoordinatorSucceeded(service: CloudKitService) } public final class AuthenticationCoordinator: Coordinator, LoadingViewControllerDelegate { public weak var delegate: AuthenticationCoordinatorDelegate? fileprivate let rootViewController: UIViewController public init(rootViewController: UIViewController, delegate: AuthenticationCoordinatorDelegate) { self.rootViewController = rootViewController self.delegate = delegate } public func start() { let loadingViewController = LoadingViewController() loadingViewController.delegate = self rootViewController.present(loadingViewController, animated: true, completion: nil) } //MARK:- LoadingViewControllerDelegate public func loadingViewControllerDidLoad(controller: LoadingViewController) { attemptCloudKitAuthentication(loadingViewController: controller) } public func loadingViewControllerTryAgainButtonPressed(controller: LoadingViewController) { attemptCloudKitAuthentication(loadingViewController: controller) } func attemptCloudKitAuthentication(loadingViewController: LoadingViewController) { loadingViewController.state = .loading CloudKitService.create { (succeeded, error, service) in DispatchQueue.main.async { guard let service = service, error == nil else { loadingViewController.state = .iCloudError return } self.delegate?.authenticationCoordinatorSucceeded(service: service) } } } }
mit
abbfab84c1f33cc41180dc0e24fa9900
32.77193
100
0.696623
6.270358
false
false
false
false
Rivukis/Parlance
Parlance/WelcomeModule/WelcomeViewController.swift
1
2444
// // WelcomeViewController.swift // Parlance // // Created by Brian Radebaugh on 1/24/17. // Copyright © 2017 Brian Radebaugh. All rights reserved. // import UIKit class WelcomeViewController: UIViewController { let parlance = WelcomeParlance() var sessionsCount = 0 let alertControllerBuilder = AlertControllerBuilder(parlance: ReusableUIParlance()) @IBOutlet weak var welcomeLabel: UILabel! { didSet { welcomeLabel.text = welcomeLabelText() } } @IBOutlet weak var sessionCountLabel: UILabel! { didSet { sessionCountLabel.text = parlance.t(.sessionsCount(sessionsCount)) } } @IBOutlet weak var signInButton: UIButton! { didSet { signInButton.layer.cornerRadius = 5 let title = parlance.t(.signInButtonText) signInButton.setTitle(title, for: .normal) } } @IBOutlet weak var signOutButton: UIButton! { didSet { signOutButton.layer.cornerRadius = 5 let title = parlance.t(.signOutButtonText) signOutButton.setTitle(title, for: .normal) } } // MARK: Lifecycle override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) refresh() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let signInViewController = segue.destination as? SignInViewController { signInViewController.delegate = self } } // MARK: Actions @IBAction func signOutTapped(_ sender: Any) { if let _ = User.currentUser { User.currentUser = nil sessionsCount = 0 let signedOutAlertController = alertControllerBuilder.alertController(withType: .signedOut) present(signedOutAlertController, animated: true) refresh() } } // MARK: Helper func refresh() { welcomeLabel.text = welcomeLabelText() sessionCountLabel.text = parlance.t(.sessionsCount(sessionsCount)) } func welcomeLabelText() -> String { if let user = User.currentUser { return parlance.t(.welcomeMessage(name: user.name)) } return parlance.t(.genericWelcomeMessage) } } extension WelcomeViewController: SignInViewControllerDelegate { func didSignIn() { sessionsCount += 1 } }
mit
d7aa6d588e3d1bb0382c73c3c5b6cf0f
27.406977
103
0.618093
5.026749
false
false
false
false
aquarchitect/MyKit
Sources/iOS/Extensions/UIKit/UITableView+.swift
1
2813
// // UITableView+.swift // MyKit // // Created by Hai Nguyen. // Copyright (c) 2015 Hai Nguyen. // import UIKit // MARK: - Miscellaneous /// :nodoc: public extension UITableView { @available(*, deprecated) var estimatedNumberOfVisibleRows: Int { if self.estimatedRowHeight == 0 { return Int(self.bounds.height/self.rowHeight) } else { return Int(self.bounds.height/self.estimatedRowHeight) } } @available(*, deprecated) var estimatedRangeOfVisibleRows: CountableRange<Int> { let lowerBound = self.indexPathsForVisibleRows?.first?.row ?? 0 return lowerBound ..< (lowerBound + estimatedNumberOfVisibleRows) } final func hasSection(section: Int) -> Bool { return 0..<self.numberOfSections ~= section } } // MARK: - Transform IndexPath public extension UITableView { final func indexPath(after indexPath: IndexPath) -> IndexPath? { if indexPath.row < self.numberOfRows(inSection: indexPath.section) - 1 { return IndexPath(row: indexPath.row + 1, section: indexPath.section) } else if indexPath.section < self.numberOfSections - 1 { return IndexPath(row: 0, section: indexPath.section + 1) } else { return nil } } final func indexPath(before indexPath: IndexPath) -> IndexPath? { if indexPath.row > 0 { return IndexPath(row: indexPath.row - 1, section: indexPath.section) } else if indexPath.section > 0 { let section = indexPath.section - 1 let row = self.numberOfRows(inSection: section) - 1 return IndexPath(row: row, section: section) } else { return nil } } final func index(bySerializing indexPath: IndexPath) -> Int { return (0..<indexPath.section) .map(self.numberOfRows(inSection:)) .lazy .reduce(indexPath.row, +) } final func indexPath(byDeserializing index: Int) -> IndexPath { var (section, count) = (0, 0) while case let rows = self.numberOfRows(inSection: section), count + rows < index { count += rows section += 1 } return IndexPath(row: index - count, section: section) } } public extension UITableView { var firstIndexPath: IndexPath? { guard let section = (0..<self.numberOfSections).first, let row = (0..<self.numberOfRows(inSection: section)).first else { return nil } return [section, row] } var lastIndexPath: IndexPath? { guard let section = (0..<self.numberOfSections).last, let row = (0..<self.numberOfRows(inSection: section)).last else { return nil } return [section, row] } }
mit
a24470fd82a7ad3b55624e5918529c99
28.302083
80
0.604692
4.559157
false
false
false
false
algolia/algoliasearch-client-swift
Sources/AlgoliaSearchClient/Models/Search/Response/SearchResponse/Auxiliary/Highlighting/TaggedString.swift
1
5254
// // TaggedString.swift // // // Created by Vladislav Fitc on 13.03.2020. // import Foundation /// Structure embedding the calculation of tagged substring in the input string public struct TaggedString { /// Input string public let input: String /// Opening tag public let preTag: String /// Closing tag public let postTag: String /// String comparison options for tags parsing public let options: String.CompareOptions private lazy var storage: (String, [Range<String.Index>]) = TaggedString.computeRanges(for: input, preTag: preTag, postTag: postTag, options: options) /// Output string cleansed of the opening and closing tags public private(set) lazy var output: String = { storage.0 }() /// List of ranges of tagged substrings in the output string public private(set) lazy var taggedRanges: [Range<String.Index>] = { storage.1 }() /// List of ranges of untagged substrings in the output string public private(set) lazy var untaggedRanges: [Range<String.Index>] = TaggedString.computeInvertedRanges(for: output, with: taggedRanges) /** - Parameters: - string: Input string - preTag: Opening tag - postTag: Closing tag - options: String comparison options for tags parsing */ public init(string: String, preTag: String, postTag: String, options: String.CompareOptions = []) { // This string reconstruction is here to avoid a potential problems due to string encoding // Check unit test TaggedStringTests -> testWithDecodedString let string = String(string.indices.map { string[$0] }) self.input = string self.preTag = preTag self.postTag = postTag self.options = options } /// - Returns: The list of tagged substrings of the output string public mutating func taggedSubstrings() -> [Substring] { return taggedRanges.map { output[$0] } } /// - Returns: The list of untagged substrings of the output string public mutating func untaggedSubstrings() -> [Substring] { return untaggedRanges.map { output[$0] } } private static func computeRanges(for string: String, preTag: String, postTag: String, options: String.CompareOptions) -> (output: String, ranges: [Range<String.Index>]) { var output = string var preStack: [Range<String.Index>] = [] var rangesToHighlight = [Range<String.Index>]() enum Tag { case pre(Range<String.Index>), post(Range<String.Index>) } func nextTag(in string: String) -> Tag? { switch (string.range(of: preTag, options: options), string.range(of: postTag, options: options)) { case (.some(let pre), .some(let post)) where pre.lowerBound < post.lowerBound: return .pre(pre) case (.some, .some(let post)): return .post(post) case (.some(let pre), .none): return .pre(pre) case (.none, .some(let post)): return .post(post) case (.none, .none): return nil } } while let nextTag = nextTag(in: output) { switch nextTag { case .pre(let preRange): preStack.append(preRange) output.removeSubrange(preRange) case .post(let postRange): if let lastPre = preStack.last { preStack.removeLast() rangesToHighlight.append(.init(uncheckedBounds: (lastPre.lowerBound, postRange.lowerBound))) } output.removeSubrange(postRange) } } return (output, mergeOverlapping(rangesToHighlight)) } private static func computeInvertedRanges(for string: String, with ranges: [Range<String.Index>]) -> [Range<String.Index>] { if ranges.isEmpty { return ([string.startIndex..<string.endIndex]) } var lowerBound = string.startIndex var invertedRanges: [Range<String.Index>] = [] for range in ranges where range.lowerBound >= lowerBound { if lowerBound != range.lowerBound { let invertedRange = lowerBound..<range.lowerBound invertedRanges.append(invertedRange) } lowerBound = range.upperBound } if lowerBound != string.endIndex, lowerBound != string.startIndex { invertedRanges.append(lowerBound..<string.endIndex) } return invertedRanges } private static func mergeOverlapping<T: Comparable>(_ input: [Range<T>]) -> [Range<T>] { var output: [Range<T>] = [] let sortedRanges = input.sorted(by: { $0.lowerBound < $1.lowerBound }) guard let head = sortedRanges.first else { return output } let tail = sortedRanges.suffix(from: sortedRanges.index(after: sortedRanges.startIndex)) var (lower, upper) = (head.lowerBound, head.upperBound) for range in tail { if range.lowerBound <= upper { if range.upperBound > upper { upper = range.upperBound } else { continue } } else { output.append(.init(uncheckedBounds: (lower: lower, upper: upper))) (lower, upper) = (range.lowerBound, range.upperBound) } } output.append(.init(uncheckedBounds: (lower: lower, upper: upper))) return output } } extension TaggedString: Hashable { public func hash(into hasher: inout Hasher) { input.hash(into: &hasher) preTag.hash(into: &hasher) postTag.hash(into: &hasher) } }
mit
c55460a4f42018eb707e5549253653a2
30.842424
173
0.660449
4.130503
false
false
false
false
Connecthings/sdk-tutorial
ios/SWIFT/Zone/2-Notification/Starter/Notification/AppDelegate.swift
1
2471
// // AppDelegate.swift // Complete // // Created by Connecthings on 26/01/2017. // Copyright © 2017 R&D connecthings. All rights reserved. // import UIKit import ConnectPlaceActions import HerowConnection import HerowLocationDetection import UserNotifications @UIApplicationMain class AppDelegate: NSObject, UIApplicationDelegate, HerowReceiveNotificationContentDelegate { private let notificationIdentifier: String = "INVITE_CATEGORY" var window: UIWindow? var herowInitializer: HerowInitializer? var herowDetectionManager: HerowDetectionManager? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { herowInitializer = HerowInitializer.shared herowInitializer?.configPlatform(Platform.prod) .configApp(identifier: "__IDENTIFIER__", sdkKey: "__SDK_KEY__") .synchronize() herowDetectionManager = HerowDetectionManager.shared herowDetectionManager?.registerReceiveNotificatonContentDelegate(self) if #available(iOS 10.0, *) { let center = UNUserNotificationCenter.current() //The request can be done as well in a viewController which allows to display a message if the user refuse the receive notifications center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in if (error == nil) { NSLog("request authorization succeeded!"); } } } else if(UIApplication.instancesRespond(to: #selector(UIApplication.registerUserNotificationSettings(_:)))){ UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings (types: [.alert, .sound], categories: nil)) } return true } func application(_ application: UIApplication, didReceive notification: UILocalNotification) { herowDetectionManager?.didReceivePlaceNotification(notification.userInfo) } func didReceivePlaceNotification(_ placeNotification: HerowPlaceNotification) { NSLog("open a controller with a place notification") //Quick way to notify controller let placeContentUserInfo:[String: PlaceNotification] = ["placeNotification": placeNotification] NotificationCenter.default.post(name: NSNotification.Name("placeNotification"), object:nil, userInfo: placeContentUserInfo) } }
apache-2.0
d0e9d1fe6add88c52c1db3266d2e2c61
42.333333
145
0.71336
5.289079
false
false
false
false
PopcornTimeTV/PopcornTimeTV
PopcornKit/Managers/WatchlistManager.swift
1
4109
import Foundation import ObjectMapper private struct Static { static var movieInstance: WatchlistManager<Movie>? = nil static var showInstance: WatchlistManager<Show>? = nil } typealias jsonArray = [[String : Any]] /// Class for managing a users watchlist. open class WatchlistManager<N: Media> { private let currentType: Trakt.MediaType /// Creates new instance of WatchlistManager class with type of Shows. public class var show: WatchlistManager<Show> { DispatchQueue.once(token: "ShowWatchlist") { Static.showInstance = WatchlistManager<Show>() } return Static.showInstance! } /// Creates new instance of WatchlistManager class with type of Movies. public class var movie: WatchlistManager<Movie> { DispatchQueue.once(token: "MovieWatchlist") { Static.movieInstance = WatchlistManager<Movie>() } return Static.movieInstance! } private init?() { switch N.self { case is Movie.Type: currentType = .movies case is Show.Type: currentType = .shows default: return nil } } /** Toggles media in users watchlist and syncs with Trakt if available. - Parameter media: The media to add or remove. */ open func toggle(_ media: N) { isAdded(media) ? remove(media): add(media) } /** Adds media to users watchlist and syncs with Trakt if available. - Parameter media: The media to add. */ open func add(_ media: N) { TraktManager.shared.add(media.id, toWatchlistOfType: currentType) var array = UserDefaults.standard.object(forKey: "\(currentType.rawValue)Watchlist") as? jsonArray ?? jsonArray() array.append(Mapper<N>().toJSON(media)) UserDefaults.standard.set(array, forKey: "\(currentType.rawValue)Watchlist") } /** Removes media from users watchlist and syncs with Trakt if available. - Parameter media: The media to remove. */ open func remove(_ media: N) { TraktManager.shared.remove(media.id, fromWatchlistOfType: currentType) if var array = UserDefaults.standard.object(forKey: "\(currentType.rawValue)Watchlist") as? jsonArray, let index = Mapper<N>().mapArray(JSONArray: array).firstIndex(where: { $0.id == media.id }) { array.remove(at: index) UserDefaults.standard.set(array, forKey: "\(currentType.rawValue)Watchlist") } } /** Checks media is in the watchlist. - Parameter media: The media. - Returns: Boolean indicating if media is in the users watchlist. */ open func isAdded(_ media: N) -> Bool { if let array = UserDefaults.standard.object(forKey: "\(currentType.rawValue)Watchlist") as? jsonArray { return Mapper<N>().mapArray(JSONArray: array).contains(where: {$0.id == media.id}) } return false } /** Gets watchlist locally first and then from Trakt if available. - Parameter completion: If Trakt is available, completion will be called with a more up-to-date watchlist that will replace the locally stored one and should be reloaded for the user. - Returns: Locally stored watchlist (may be out of date if user has authenticated with trakt). */ @discardableResult open func getWatchlist(_ completion: (([N]) -> Void)? = nil) -> [N] { let array = UserDefaults.standard.object(forKey: "\(currentType.rawValue)Watchlist") as? jsonArray ?? jsonArray() DispatchQueue.global(qos: .background).async { TraktManager.shared.getWatchlist(forMediaOfType: N.self) { [unowned self] (medias, error) in guard error == nil else {return} UserDefaults.standard.set(Mapper<N>().toJSONArray(medias), forKey: "\(self.currentType.rawValue)Watchlist") completion?(medias) } } return Mapper<N>().mapArray(JSONArray: array) } }
gpl-3.0
d8e853e97f448ce50aba2990f3fcb792
35.04386
188
0.629107
4.437365
false
false
false
false
freak4pc/netfox
netfox/Core/NFXImageBodyDetailsController.swift
1
941
// // NFXImageBodyDetailsController.swift // netfox // // Copyright © 2016 netfox. All rights reserved. // #if os(iOS) import Foundation import UIKit class NFXImageBodyDetailsController: NFXGenericBodyDetailsController { var imageView: UIImageView = UIImageView() override func viewDidLoad() { super.viewDidLoad() self.title = "Image preview" self.imageView.frame = CGRect(x: 10, y: 10, width: self.view.frame.width - 2*10, height: self.view.frame.height - 2*10) self.imageView.autoresizingMask = [.flexibleWidth, .flexibleHeight] self.imageView.contentMode = .scaleAspectFit let data = Data.init(base64Encoded: self.selectedModel.getResponseBody() as String, options: NSData.Base64DecodingOptions.ignoreUnknownCharacters) self.imageView.image = UIImage(data: data!) self.view.addSubview(self.imageView) } } #endif
mit
e8c92241cc9f3af666ee0e5d2fbf6044
25.857143
154
0.681915
4.253394
false
false
false
false
iOS-Swift-Developers/Swift
基础语法/while/main.swift
1
1408
// // main.swift // while // // Created by 韩俊强 on 2017/6/8. // Copyright © 2017年 HaRi. All rights reserved. // import Foundation /* while循环 格式:while(循环保持条件){需要执行的语句} OC: int i = 0; int sum = 0; while (i <= 10) { sum = i++; } while (i <= 10) sum = i++; NSLog(@"%d", sum); 如果只有一条指令while后面的大括号可以省略 Swift: 0.while后的圆括号可以省略 1.只能以bool作为条件语句 2.如果只有条指令while后面的大括号不可以省略 */ var i:Int = 0 var sum:Int = 0 while (i <= 5) { i += 1 sum = i } print("\(sum)") var i1:Int = 0 var sum1:Int = 0 while i1 <= 10 { i1 += 1 sum1 = i1 } print(sum1) /* do while循环 格式:do while(循环保持条件) {需要执行的语句} OC: int i = 0; int sum = 0; do { sum = i++; } while (i <= 10); NSLog(@"%d", sum); int i = 0; int sum = 0; do sum = i++; while (i <= 10); NSLog(@"%d", sum); 如果只有一条指令if后面的大括号可以省略 Swift2.0之后变为 repeat while, do用于捕捉异常 0.while后的圆括号可以省略 1.只能以bool作为条件语句 2.如果只有条指令do后面的大括号不可以省略 */ var i2:Int = 0 var sum2:Int = 0 repeat{ i2 += 1 sum2 = i2 }while(i2 <= 10) print(sum2) var i3:Int = 0 var sum3:Int = 0 repeat{ i3 += 1 sum3 = i3 }while i3 <= 10 print(sum3)
mit
a7c8dbff9ef79471e777801aea7e0839
10.060606
48
0.579909
2.230143
false
false
false
false
Stitch7/mclient
mclient/PrivateMessages/Cells/InitialsImageView.swift
1
7361
// // InitialsImageView.swift // // // Created by Tom Bachant on 1/28/17. // // import UIKit let kFontResizingProportion: CGFloat = 0.4 let kColorMinComponent: Int = 30 let kColorMaxComponent: Int = 214 public typealias GradientColors = (top: UIColor, bottom: UIColor) typealias HSVOffset = (hue: CGFloat, saturation: CGFloat, brightness: CGFloat, alpha: CGFloat) let kGradientTopOffset: HSVOffset = (hue: -0.025, saturation: 0.05, brightness: 0, alpha: 0) let kGradientBotomOffset: HSVOffset = (hue: 0.025, saturation: -0.05, brightness: 0, alpha: 0) extension UIImageView { public func setImageForName(_ string: String, backgroundColor: UIColor? = nil, circular: Bool, textAttributes: [NSAttributedString.Key: AnyObject]?, gradient: Bool = false) { setImageForName(string, backgroundColor: backgroundColor, circular: circular, textAttributes: textAttributes, gradient: gradient, gradientColors: nil) } public func setImageForName(_ string: String, gradientColors: GradientColors, circular: Bool, textAttributes: [NSAttributedString.Key: AnyObject]?) { setImageForName(string, backgroundColor: nil, circular: circular, textAttributes: textAttributes, gradient: true, gradientColors: gradientColors) } private func setImageForName(_ string: String, backgroundColor: UIColor?, circular: Bool, textAttributes: [NSAttributedString.Key: AnyObject]?, gradient: Bool = false, gradientColors: GradientColors?) { let initials: String = initialsFromString(string: string) let color: UIColor = (backgroundColor != nil) ? backgroundColor! : randomColor(for: string) let gradientColors = gradientColors ?? topAndBottomColors(for: color) let attributes: [NSAttributedString.Key: AnyObject] = (textAttributes != nil) ? textAttributes! : [ NSAttributedString.Key.font: self.fontForFontName(name: nil), NSAttributedString.Key.foregroundColor: UIColor.white ] self.image = imageSnapshot(text: initials, backgroundColor: color, circular: circular, textAttributes: attributes, gradient: gradient, gradientColors: gradientColors) } private func fontForFontName(name: String?) -> UIFont { let fontSize = self.bounds.width * kFontResizingProportion; if name != nil { return UIFont(name: name!, size: fontSize)! } else { return UIFont.systemFont(ofSize: fontSize) } } private func imageSnapshot(text imageText: String, backgroundColor: UIColor, circular: Bool, textAttributes: [NSAttributedString.Key : AnyObject], gradient: Bool, gradientColors: GradientColors) -> UIImage { let scale: CGFloat = UIScreen.main.scale var size: CGSize = self.bounds.size if (self.contentMode == .scaleToFill || self.contentMode == .scaleAspectFill || self.contentMode == .scaleAspectFit || self.contentMode == .redraw) { size.width = (size.width * scale) / scale size.height = (size.height * scale) / scale } UIGraphicsBeginImageContextWithOptions(size, false, scale) let context: CGContext = UIGraphicsGetCurrentContext()! if circular { // Clip context to a circle let path: CGPath = CGPath(ellipseIn: self.bounds, transform: nil) context.addPath(path) context.clip() } if gradient { // Draw a gradient from the top to the bottom let baseSpace = CGColorSpaceCreateDeviceRGB() let colors = [gradientColors.top.cgColor, gradientColors.bottom.cgColor] let gradient = CGGradient(colorsSpace: baseSpace, colors: colors as CFArray, locations: nil)! let startPoint = CGPoint(x: self.bounds.midX, y: self.bounds.minY) let endPoint = CGPoint(x: self.bounds.midX, y: self.bounds.maxY) context.drawLinearGradient(gradient, start: startPoint, end: endPoint, options: CGGradientDrawingOptions(rawValue: 0)) } else { // Fill background of context context.setFillColor(backgroundColor.cgColor) context.fill(CGRect(x: 0, y: 0, width: size.width, height: size.height)) } // Draw text in the context let textSize: CGSize = imageText.size(withAttributes: textAttributes) let bounds: CGRect = self.bounds imageText.draw(in: CGRect(x: bounds.midX - textSize.width / 2, y: bounds.midY - textSize.height / 2, width: textSize.width, height: textSize.height), withAttributes: textAttributes) let snapshot: UIImage = UIGraphicsGetImageFromCurrentImageContext()!; UIGraphicsEndImageContext(); return snapshot; } } private func initialsFromString(string: String) -> String { var nameComponents = string.uppercased().components(separatedBy: CharacterSet.alphanumerics.inverted) // var nameComponents = string.uppercased().components(separatedBy: CharacterSet.letters.inverted) nameComponents.removeAll(where: {$0.isEmpty}) let firstInitial = nameComponents.first?.first let lastInitial = nameComponents.count > 1 ? nameComponents.last?.first : nameComponents.first?[1] return (firstInitial != nil ? "\(firstInitial!)" : "") + (lastInitial != nil ? "\(lastInitial!)" : "") } private func randomColorComponent() -> Int { let limit = kColorMaxComponent - kColorMinComponent return kColorMinComponent + Int(drand48() * Double(limit)) } private func randomColor(for string: String) -> UIColor { srand48(string.hashValue) let red = CGFloat(randomColorComponent()) / 255.0 let green = CGFloat(randomColorComponent()) / 255.0 let blue = CGFloat(randomColorComponent()) / 255.0 return UIColor(red: red, green: green, blue: blue, alpha: 1.0) } private func clampColorComponent(_ value: CGFloat) -> CGFloat { return min(max(value, 0), 1) } private func correctColorComponents(of color: UIColor, withHSVOffset offset: HSVOffset) -> UIColor { var hue = CGFloat(0) var saturation = CGFloat(0) var brightness = CGFloat(0) var alpha = CGFloat(0) if color.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) { hue = clampColorComponent(hue + offset.hue) saturation = clampColorComponent(saturation + offset.saturation) brightness = clampColorComponent(brightness + offset.brightness) alpha = clampColorComponent(alpha + offset.alpha) return UIColor(hue: hue, saturation: saturation, brightness: brightness, alpha: alpha) } return color } private func topAndBottomColors(for color: UIColor, withTopHSVOffset topHSVOffset: HSVOffset = kGradientTopOffset, withBottomHSVOffset bottomHSVOffset: HSVOffset = kGradientBotomOffset) -> GradientColors { let topColor = correctColorComponents(of: color, withHSVOffset: topHSVOffset) let bottomColor = correctColorComponents(of: color, withHSVOffset: bottomHSVOffset) return (top: topColor, bottom: bottomColor) }
mit
126682f3d7ae13f9546eeae45f2284c8
43.343373
211
0.664855
4.752098
false
false
false
false
TonnyTao/HowSwift
Funny Swift.playground/Pages/PersistentContainer_iOS10.xcplaygroundpage/Contents.swift
1
1991
//: [Previous](@previous) import Foundation import CoreData //: easy CoreData in iOS10 final class CoreDataStack { static let shared = CoreDataStack() private init() {} var errorHandler: (Error) -> Void = {err in debugPrint("CoreData error \(err)") } lazy var container: NSPersistentContainer = { let container = NSPersistentContainer(name: "Model") container.loadPersistentStores(completionHandler: { [weak self](storeDescription, error) in if let error = error { self?.errorHandler(error) } }) return container }() lazy var viewContext: NSManagedObjectContext = { let context = self.container.viewContext context.automaticallyMergesChangesFromParent = true return context }() lazy var backgroundContext: NSManagedObjectContext = { return self.container.newBackgroundContext() }() } extension CoreDataStack { static func performForegroundTask(_ block: @escaping (NSManagedObjectContext) -> Void) { let ctx = self.shared.viewContext ctx.perform { [unowned ctx] in block(ctx) } } static func performBackgroundTask(_ block: @escaping (NSManagedObjectContext) -> Void) { self.shared.container.performBackgroundTask(block) } } func dashatize(_ number: Int) -> String { return String(number).reduce("") { (result, char) -> String in if char == "-" { //negative return result } let string = String(char) if Int(String(char))! % 2 == 0 { //even return result + string }else { //odd if result.hasSuffix("-") { return result + string + "-" }else { return result + "-" + string + "-" } } } }
mit
50c46049451034ccb8fd89cd6d5e0917
23.580247
99
0.547464
5.410326
false
false
false
false
BlurredSoftware/BSWFoundation
Sources/BSWFoundation/Parse/JSONParser.swift
1
5723
// // Created by Pierluigi Cifani. // Copyright (c) 2016 TheLeftBit SL. All rights reserved. // import Foundation import Task; import Deferred public enum JSONParser { private static let queue = DispatchQueue(label: "com.bswfoundation.JSONParser") public static let jsonDecoder = JSONDecoder() public static let Options: JSONSerialization.ReadingOptions = [.allowFragments] public static func parseData<T: Decodable>(_ data: Data) -> Task<T> { let task: Task<T> = Task.async(upon: queue, onCancel: Error.canceled) { let result: Task<T>.Result = self.parseData(data) return try result.extract() } return task } public static func dataIsNull(_ data: Data) -> Bool { guard let j = try? JSONSerialization.jsonObject(with: data, options: JSONParser.Options) else { return false } guard let _ = j as? NSNull else { return false } return true } public static func parseDataAsJSONPrettyPrint(_ data: Data) -> String? { guard let json = try? JSONSerialization.jsonObject(with: data, options: JSONParser.Options) else { return nil } let options: JSONSerialization.WritingOptions = { if #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) { return [.fragmentsAllowed,.withoutEscapingSlashes] } else { return [.fragmentsAllowed] } }() guard let prettyPrintedData = try? JSONSerialization.data(withJSONObject: json, options: options) else { return nil } return String(data: prettyPrintedData, encoding: .utf8) } public static func errorMessageFromData(_ data: Data) -> String? { guard let j = try? JSONSerialization.jsonObject(with: data, options: JSONParser.Options) else { return nil } guard let dictionary = j as? [String: String] else { return nil } return dictionary["error"] } static public func parseData<T: Decodable>(_ data: Data) -> Task<T>.Result { guard T.self != VoidResponse.self else { let response = VoidResponse.init() as! T return .success(response) } /// Turns out that on iOS 12, parsing basic types using /// Swift's `Decodable` is failing for some unknown /// reasons. To lazy to file a radar... /// So here we're instead using the good and trusted /// `NSJSONSerialization` class if T.self == Bool.self || T.self == Int.self || T.self == String.self { if let output = try? JSONSerialization.jsonObject(with: data, options: JSONParser.Options) as? T { return .success(output) } else { return .failure(Error.malformedJSON) } } if let provider = T.self as? DateDecodingStrategyProvider.Type { jsonDecoder.dateDecodingStrategy = .formatted(provider.dateDecodingStrategy) } else { jsonDecoder.dateDecodingStrategy = .formatted(iso8601DateFormatter) } let result: Task<T>.Result do { let output: T = try jsonDecoder.decode(T.self, from: data) result = .success(output) } catch let decodingError as DecodingError { switch decodingError { case .keyNotFound(let missingKey, let context): print("*ERROR* decoding, key \"\(missingKey)\" is missing, Context: \(context)") result = .failure(Error.malformedSchema) case .typeMismatch(let type, let context): print("*ERROR* decoding, type \"\(type)\" mismatched, context: \(context)") result = .failure(Error.malformedSchema) case .valueNotFound(let type, let context): print("*ERROR* decoding, value not found \"\(type)\", context: \(context)") result = .failure(Error.malformedSchema) case .dataCorrupted(let context): print("*ERROR* Data Corrupted \"\(context)\")") if let string = NSString(data: data, encoding: String.Encoding.utf8.rawValue) { print("*ERROR* incoming JSON: \(string)") } result = .failure(Error.malformedJSON) @unknown default: result = .failure(Error.unknownError) } } catch { result = .failure(Error.unknownError) } return result } //MARK: Error public enum Error: Swift.Error { case malformedJSON case malformedSchema case unknownError case canceled } } #if canImport(Combine) @available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) public extension JSONParser { static func parseData<T: Decodable>(_ data: Data) -> CombineTask<T> { let task: Task<T> = self.parseData(data) return task.future } static func parseData<T: Decodable>(_ data: Data) -> Swift.Result<T, Swift.Error> { return parseData(data).swiftResult } } #endif public protocol DateDecodingStrategyProvider { static var dateDecodingStrategy: DateFormatter { get } } private var iso8601DateFormatter: DateFormatter { let formatter = DateFormatter() formatter.locale = Locale(identifier: "en_US_POSIX") formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ" return formatter } extension Array: DateDecodingStrategyProvider where Element: DateDecodingStrategyProvider { public static var dateDecodingStrategy: DateFormatter { return Element.dateDecodingStrategy } }
mit
958667835820d8ff46458a93869df7a2
35.452229
125
0.605452
4.761231
false
false
false
false
rsmoz/swift-package-manager
Sources/swift-build/usage.swift
1
8804
/* This source file is part of the Swift.org open source project Copyright 2015 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import struct dep.BuildParameters func usage(print: (String) -> Void = { print($0) }) { //.........10.........20.........30.........40.........50.........60.........70.. print("OVERVIEW: Build sources into binary products") print("") print("USAGE: swift build [options]") print("") print("MODES:") print(" --configuration <value> Build with configuration (debug|release) [-c]") print(" --clean[=<mode>] Delete all build intermediaries and products [-k]") print(" <mode> is one of:") print(" build - Build intermediaries and products") print(" dist - All of 'build' plus downloaded packages") print(" If no mode is given, 'build' is the default.") print("") print("OPTIONS:") print(" --chdir <value> Change working directory before any other operation [-C]") print(" -v[v] Increase verbosity of informational output") print(" -Xcc <flag> Pass flag through to all compiler instantiations") print(" -Xlinker <flag> Pass flag through to all linker instantiations") } enum CleanMode: String { case Build = "build" case Dist = "dist" } enum Mode { case Build(BuildParameters.Configuration) case Clean(CleanMode) case Usage case Version } enum CommandLineError: ErrorType { enum UsageMode { case Print, Imply } case InvalidUsage(String, UsageMode) } struct Options { var chdir: String? = nil var verbosity: Int = 0 var Xcc: [String] = [] var Xlinker: [String] = [] } func parse(commandLineArguments args: [String]) throws -> (Mode, Options) { var opts = Options() var mode: Mode? //TODO refactor var skipNext = false var cruncher = Cruncher(args: args.flatMap { arg -> [String] in if skipNext { skipNext = false return [arg] } if arg == "-Xcc" || arg == "-Xlinker" { skipNext = true return [arg] } // split short form arguments so Cruncher can work with them, // eg. -vv is split into -v -v if arg.hasPrefix("-") && !arg.hasPrefix("--") { return arg.characters.dropFirst().map{ "-" + String($0) } } // split applicative arguments so Cruncher can work with them, // eg. --mode=value splits into --mode =value let argParts = arg.characters.split{ $0 == "=" }.map{ String($0) } if argParts.count > 1 { return argParts } return [arg] }) while cruncher.shouldContinue { switch try cruncher.pop() { case .Mode(let newMode): switch (mode, newMode) { case (let a?, let b) where a == b: break case (.Usage?, let ignoredArgument): throw CommandLineError.InvalidUsage("Both --help and \(ignoredArgument) specified", .Print) case (let ignoredArgument?, .Usage): throw CommandLineError.InvalidUsage("Both --help and \(ignoredArgument) specified", .Print) case (let oldMode?, let newMode): throw CommandLineError.InvalidUsage("Multiple modes specified: \(oldMode), \(newMode)", .Imply) case (nil, .Build): switch try cruncher.peek() { case .Name("debug")?: mode = .Build(.Debug) cruncher.postPeekPop() case .Name("release")?: mode = .Build(.Release) cruncher.postPeekPop() case .Name(let name)?: throw CommandLineError.InvalidUsage("Unknown build configuration: \(name)", .Imply) default: break } case (nil, .Usage): mode = .Usage case (nil, .Clean): mode = .Clean(.Build) switch try cruncher.peek() { case .Name("build")?: cruncher.postPeekPop() case .Name("dist")?: mode = .Clean(.Dist) cruncher.postPeekPop() case .Name(let name)?: throw CommandLineError.InvalidUsage("Unknown clean mode: \(name)", .Imply) default: break } case (nil, .Version): mode = .Version } case .Switch(.Chdir): switch try cruncher.peek() { case .Name(let name)?: cruncher.postPeekPop() opts.chdir = name default: throw CommandLineError.InvalidUsage("Option `--chdir' requires subsequent directory argument", .Imply) } case .Switch(.Verbose): opts.verbosity += 1 case .Name(let name): throw CommandLineError.InvalidUsage("Unknown argument: \(name)", .Imply) case .Switch(.Xcc): opts.Xcc.append(try cruncher.rawPop()) case .Switch(.Xlinker): opts.Xlinker.append(try cruncher.rawPop()) } } return (mode ?? .Build(.Debug), opts) } extension CleanMode: CustomStringConvertible { var description: String { return "=\(self.rawValue)" } } extension Mode: CustomStringConvertible { var description: String { //FIXME shouldn't be necessary! switch self { case .Build(let conf): return "--build \(conf)" case .Clean(let cleanMode): return "--clean=\(cleanMode)" case .Usage: return "--help" case .Version: return "--version" } } } private struct Cruncher { enum Crunch { enum TheMode: String { case Build = "--configuration" case Clean = "--clean" case Usage = "--help" case Version = "--version" init?(rawValue: String) { switch rawValue { case Build.rawValue, "-c": self = .Build case Clean.rawValue, "-k": self = .Clean case Usage.rawValue: self = .Usage case Version.rawValue: self = .Version default: return nil } } } enum TheSwitch: String { case Chdir = "--chdir" case Verbose = "--verbose" case Xcc = "-Xcc" case Xlinker = "-Xlinker" init?(rawValue: String) { switch rawValue { case Chdir.rawValue, "-C": self = .Chdir case Verbose.rawValue, "-v": self = .Verbose case Xcc.rawValue: self = .Xcc case Xlinker.rawValue: self = .Xlinker default: return nil } } } case Mode(TheMode) case Switch(TheSwitch) case Name(String) } var args: [String] var shouldContinue: Bool { return !args.isEmpty } func parse(arg: String) throws -> Crunch { if let mode = Crunch.TheMode(rawValue: arg) { return .Mode(mode) } if let theSwitch = Crunch.TheSwitch(rawValue: arg) { return .Switch(theSwitch) } guard !arg.hasPrefix("-") else { throw CommandLineError.InvalidUsage("unknown argument: \(arg)", .Imply) } return .Name(arg) } mutating func rawPop() throws -> String { guard args.count > 0 else { throw CommandLineError.InvalidUsage("expected argument", .Imply) } return args.removeFirst() } mutating func pop() throws -> Crunch { return try parse(args.removeFirst()) } mutating func postPeekPop() { args.removeFirst() } func peek() throws -> Crunch? { guard let arg = args.first else { return nil } return try parse(arg) } } private func ==(lhs: Mode, rhs: Cruncher.Crunch.TheMode) -> Bool { switch lhs { case .Build: return rhs == .Build case .Clean: return rhs == .Clean case .Version: return rhs == .Version case .Usage: return rhs == .Usage } }
apache-2.0
e0e1d96c53a45ce3e2c8a3fe282009a1
30.109541
118
0.514652
4.628812
false
false
false
false
ZeeQL/ZeeQL3
Sources/ZeeQL/Access/Entity.swift
1
19709
// // Entity.swift // ZeeQL // // Created by Helge Hess on 18/02/2017. // Copyright © 2017-2021 ZeeZide GmbH. All rights reserved. // /** * Entity objects usually represent a database table or view. Entity objects * are contained in Model objects and are usually looked up by name. To work * on the entity (fetch objects, insert/update/delete objects etc) you retrieve * an ActiveDataSource for some Database object (which in turn has a * pointer to the Model). * * Entity objects can be 'pattern' objects. That is, they can be incomplete and * may need to be 'filled' by querying the database information schema. This can * involve incomplete attribute sets or a pattern name. */ public protocol Entity: AnyObject, EquatableType, SmartDescription { var name : String { get } var externalName : String? { get } var schemaName : String? { get } var isReadOnly : Bool { get } var isPattern : Bool { get } /// Whether a row should be fetched right after it got inserted. This is /// useful to capture default values in the SQL schema (or modifications done /// by insert triggers). var shouldRefetchOnInsert : Bool { get } // MARK: - Attributes & Relationships var attributes : [ Attribute ] { get } var relationships : [ Relationship ] { get } var primaryKeyAttributeNames : [ String ]? { get } /** * Returns the names of class property attributes and relationships. Those are * attributes which are exposed as a part of the database object. * * The class properties are a subset of the attributes and relship arrays. Eg * in an application you would not want to expose database specific details * like primary and foreign keys as class properties. */ var classPropertyNames : [ String ]? { get } /** * Returns the attributes which are used for optimistic locking. Those are * checked for changes when an UPDATE is attempted in the database. For * example in OGo we only need the 'objectVersion' as a change marker. */ var attributesUsedForLocking : [ Attribute ]? { get } subscript(attribute n: String) -> Attribute? { get } subscript(columnName n: String) -> Attribute? { get } subscript(relationship n: String) -> Relationship? { get } func connectRelationships(in model: Model) func disconnectRelationships() // MARK: - Fetch Specifications var restrictingQualifier : Qualifier? { get } subscript(fetchSpecification n: String) -> FetchSpecification? { get } subscript(adaptorOperation n: String) -> AdaptorOperation? { get } // MARK: - Attached Type var className : String? { get } var objectType : DatabaseObject.Type? { get } } public extension Entity { // default imp var externalName : String? { return nil } var schemaName : String? { return nil } var isReadOnly : Bool { return false } var shouldRefetchOnInsert : Bool { return true } var className : String? { if let t = objectType { return "\(t)" } return nil } var objectType : DatabaseObject.Type? { return nil } var primaryKeyAttributeNames : [ String ]? { return lookupPrimaryKeyAttributeNames() } func lookupPrimaryKeyAttributeNames() -> [ String ]? { // FancyModelMaker also has a `assignPrimaryKeyIfMissing` guard !attributes.isEmpty else { return nil } // plain names, like 'CREATE TABLE pets ( id INT NOT NULL, name ... )' let autoAttributeNames = [ "id", "pkey" ] for attr in attributes { if autoAttributeNames.contains(attr.name) { return [ attr.name ] } } // e.g. table 'company', id 'company_id' if let tableName = externalName { let pkeyName = tableName + "_id" var hadColumnNames = false for attr in attributes { if let columnName = attr.columnName { hadColumnNames = true if columnName == pkeyName { return [ pkeyName ] } } } if !hadColumnNames { // scan regular names for attr in attributes { if attr.name == pkeyName { return [ pkeyName ] } } } } return nil } // MARK: - GlobalIDs func globalIDForRow(_ row: AdaptorRecord?) -> GlobalID? { guard let row = row else { return nil } guard let pkeys = primaryKeyAttributeNames, !pkeys.isEmpty else { return nil } let pkeyValues = pkeys.map { row[$0] } return KeyGlobalID.make(entityName: name, values: pkeyValues) } func globalIDForRow(_ row: AdaptorRow?) -> GlobalID? { guard let row = row else { return nil } guard let pkeys = primaryKeyAttributeNames, !pkeys.isEmpty else { return nil } let pkeyValues = pkeys.map { row[$0] ?? nil } return KeyGlobalID.make(entityName: name, values: pkeyValues) } func globalIDForRow(_ row: Any?) -> GlobalID? { guard let row = row else { return nil } guard let pkeys = primaryKeyAttributeNames, !pkeys.isEmpty else { return nil } let pkeyValues = pkeys.map { KeyValueCoding.value(forKey: $0, inObject: row) } return KeyGlobalID.make(entityName: name, values: pkeyValues) } func qualifierForGlobalID(_ globalID: GlobalID) -> Qualifier { guard let kglobalID = globalID as? KeyGlobalID else { globalZeeQLLogger.warn("globalID is not a KeyGlobalID:", globalID, type(of: globalID)) assertionFailure("attempt to use an unsupported globalID \(globalID)") return BooleanQualifier.falseQualifier } guard kglobalID.keyCount != 0 else { globalZeeQLLogger.warn("globalID w/o keys:", globalID) assertionFailure("globalID w/o keys: \(globalID)") return BooleanQualifier.falseQualifier } guard let pkeys = primaryKeyAttributeNames, pkeys.count == kglobalID.keyCount else { return BooleanQualifier.falseQualifier } if kglobalID.keyCount == 1 { return KeyValueQualifier(pkeys[0], .EqualTo, kglobalID[0]) } var qualifiers = [ Qualifier ]() qualifiers.reserveCapacity(kglobalID.keyCount) for i in 0..<kglobalID.keyCount { qualifiers.append(KeyValueQualifier(pkeys[i], .EqualTo, kglobalID[i])) } return CompoundQualifier(qualifiers: qualifiers, op: .And) } // MARK: - Attributes & Relationships subscript(attribute n: String) -> Attribute? { for attr in attributes { if attr.name == n { return attr } } return nil } subscript(columnName n: String) -> Attribute? { for attr in attributes { if attr.columnName == n { return attr } } return nil } subscript(relationship n: String) -> Relationship? { for rel in relationships { if rel.name == n { return rel } } return nil } func attributesWithNames(_ names: [ String ]) -> [ Attribute ] { guard !names.isEmpty else { return [] } var attributes = [ Attribute ]() for name in names { if let a = self[attribute: name] { attributes.append(a) } } return attributes } func keyForAttributeWith(name: String) -> Key { guard let attr = self[attribute: name] else { return StringKey(name) } return AttributeKey(attr, entity: self) } func keyForAttributeWith(name: String, requireLookup: Bool) -> Key? { guard let attr = self[attribute: name] else { return requireLookup ? nil : StringKey(name) } return AttributeKey(attr, entity: self) } func connectRelationships(in model : Model) { for relship in relationships { relship.connectRelationships(in: model, entity: self) } } func disconnectRelationships() { for relship in relationships { relship.disconnectRelationships() } } var classPropertyNames : [ String ]? { if attributes.isEmpty && relationships.isEmpty { return nil } var names = [ String ]() names.reserveCapacity(attributes.count + relationships.count) for attr in attributes { names.append(attr.name) } for rs in relationships { names.append(rs.name) } return names } var attributesUsedForLocking : [ Attribute ]? { return nil } // MARK: - Fetch Specifications var restrictingQualifier: Qualifier? { return nil } subscript(fetchSpecification n: String) -> FetchSpecification? { return nil } subscript(adaptorOperation n: String) -> AdaptorOperation? { return nil } // MARK: - Description func appendToDescription(_ ms: inout String) { if isPattern { ms += " pattern" } ms += " \(name)" if let cn = externalName { if let sn = schemaName { ms += "[\(sn).\(cn)]" } else { ms += "[\(cn)]" } } if let ot = objectType { ms += " \(ot)" } else if let cn = className { ms += " '\(cn)'" } if isReadOnly { ms += " r/o" } if let pkeys = primaryKeyAttributeNames, !pkeys.isEmpty { if pkeys.count == 1 { ms += " pkey=" + pkeys[0] } else { ms += " pkeys=" ms += pkeys.joined(separator: ",") } } ms += " #attrs=\(attributes.count)" if relationships.count > 0 { ms += " #rel=\(relationships.count)" } // TODO: restrictingQualifier, fetchspecs } } public extension Entity { // keypath attribute lookup subscript(keyPath path: String) -> Attribute? { let parts = path.components(separatedBy: ".") let count = parts.count guard count > 1 else { return self[attribute: path] } var cursor : Entity? = self for i in 0..<(count - 1) { let part = parts[i] guard let relship = cursor?[relationship: part] else { return nil } guard let entity = relship.destinationEntity else { return nil } cursor = entity } return cursor?[attribute: parts[count - 1]] } } public extension Entity { // primary keys /** * Extracts the primary key values contained in the given row (usually a * Dictionary). * * - parameter row: a row * - returns: a Dictionary containing the keys/values of the primary keys */ func primaryKeyForRow(_ row: Any?) -> Snapshot? { /* we do KVC on the row, so it can be any kind of object */ guard let row = row else { globalZeeQLLogger.warn("got no row to calculate primary key!") return nil } guard let pkeysNames = primaryKeyAttributeNames else { globalZeeQLLogger.warn("got no pkeys to calculate pkey:", self) return nil } let pkey = KeyValueCoding.values(forKeys: pkeysNames, inObject: row) guard !pkey.isEmpty else { globalZeeQLLogger.trace("could not calculate primary key:", pkeysNames, "from row:", row) return nil } return pkey } /** * Extracts the primary key values contained in the given object and returns * a qualifier to match those. * * - parameter row: a database object (or snapshot) * - returns: a `Qualifier` matching the keys/values of the primary keys */ func qualifierForPrimaryKey(_ row: Any?) -> Qualifier? { guard let row = row else { return nil } /* we do KVC on the row, so it can be any kind of object */ guard let pkey = primaryKeyForRow(row) else { return nil } return qualifierToMatchAllValues(pkey) } } public extension Entity { func isEqual(to object: Any?) -> Bool { guard let other = object as? Entity else { return false } return other.isEqual(to: self) } func isEqual(to other: Entity) -> Bool { if other === self { return true } guard name == other.name else { return false } guard externalName == other.externalName else { return false } guard className == other.className else { return false } guard objectType == other.objectType else { return false } guard schemaName == other.schemaName else { return false } guard isReadOnly == other.isReadOnly else { return false } guard isPattern == other.isPattern else { return false } guard attributes.count == other.attributes.count else { return false } guard relationships.count == other.relationships.count else { return false } guard attributesUsedForLocking?.count == other.attributesUsedForLocking?.count else { return false } guard shouldRefetchOnInsert == other.shouldRefetchOnInsert else { return false } guard primaryKeyAttributeNames == other.primaryKeyAttributeNames else { return false } guard classPropertyNames == other.classPropertyNames else { return false } guard eq(restrictingQualifier, other.restrictingQualifier) else { return false } for attr in attributes { guard let other = other[attribute: attr.name] else { return false } guard attr.isEqual(to: other) else { return false } } if let v = attributesUsedForLocking, let ov = other.attributesUsedForLocking { let mn = Set(v .lazy.map { $0.name }) let on = Set(ov.lazy.map { $0.name }) guard mn == on else { return false } } for rs in relationships { guard let other = other[relationship: rs.name] else { return false } guard rs.isEqual(to: other) else { return false } } return true } static func ==(lhs: Entity, rhs: Entity) -> Bool { return lhs.isEqual(to: rhs) } } /** * An Entity description which stores the info as variables. * * Suitable for use with models loaded from XML, or models fetched from a * database. */ open class ModelEntity : Entity, Equatable { /* * When adding ivars remember to clone them in: * cloneForExternalName() * resolveEntityPatternWithModel() */ public final var name : String public final var externalName : String? public final var schemaName : String? public final var className : String? // TBD: Hm. public final var dataSourceClassName : String? public final var isReadOnly = false public final var attributes = [ Attribute ]() public final var relationships = [ Relationship ]() public final var primaryKeyAttributeNames : [ String ]? = nil public final var codeGenerationType : String? public final var userData = [ String : Any ]() /// A persistent ID used to track renaming when doing model-to-model /// migrations. public final var elementID : String? /** * Returns the attributes which are used for optimistic locking. Those are * checked for changes when an UPDATE is attempted in the database. For * example in OGo we only need the 'objectVersion' as a change marker. */ public final var attributesUsedForLocking : [ Attribute ]? = nil public final var restrictingQualifier : Qualifier? public final var fetchSpecifications = [ String : FetchSpecification ]() public final var adaptorOperations = [ String : AdaptorOperation ]() /** * Returns the names of class property attributes and relationships. Those are * attributes which are exposed as a part of the database object. * * The class properties are a subset of the attributes and relship arrays. Eg * in an application you would not want to expose database specific details * like primary and foreign keys as class properties. */ public final var classPropertyNames : [ String ]? { set { _classPropertyNames = newValue } get { if let cpn = _classPropertyNames { return cpn } if attributes.isEmpty && relationships.isEmpty { return nil } // Note: threading, cannot push into _classPropertyNames var names = [ String ]() names.reserveCapacity(attributes.count + relationships.count) for attr in attributes { names.append(attr.name) } for rs in relationships { names.append(rs.name) } return names } } final var _classPropertyNames : [ String ]? /* patterns */ public final var isExternalNamePattern = false public init(name: String, table: String? = nil) { self.name = name self.externalName = table } public init(entity: Entity, deep: Bool = false) { self.name = entity.name self.externalName = entity.externalName self.schemaName = entity.schemaName self.className = entity.className self.isReadOnly = entity.isReadOnly self.primaryKeyAttributeNames = entity.primaryKeyAttributeNames // TBD: does this need a copy? self.restrictingQualifier = entity.restrictingQualifier if deep { var nameToNewAttribute = [ String : Attribute ]() attributes.reserveCapacity(entity.attributes.count) for attr in entity.attributes { let newAttr = ModelAttribute(attribute: attr) nameToNewAttribute[attr.name] = newAttr attributes.append(newAttr) } if let lockAttrs = entity.attributesUsedForLocking { attributesUsedForLocking = [ Attribute ]() attributesUsedForLocking?.reserveCapacity(lockAttrs.count) for attr in lockAttrs { attributesUsedForLocking?.append(nameToNewAttribute[attr.name]!) } } } else { self.attributes = entity.attributes self.attributesUsedForLocking = entity.attributesUsedForLocking } if let me = entity as? ModelEntity { self.codeGenerationType = me.codeGenerationType self.userData = me.userData self.elementID = me.elementID self.isExternalNamePattern = me.isExternalNamePattern self.dataSourceClassName = me.dataSourceClassName self._classPropertyNames = me._classPropertyNames if deep { for (key, value) in me.fetchSpecifications { fetchSpecifications[key] = ModelFetchSpecification(fetchSpecification: value) } // TODO: deep support self.adaptorOperations = me.adaptorOperations } else { // TBD: those may refer to the entity? self.fetchSpecifications = me.fetchSpecifications self.adaptorOperations = me.adaptorOperations } } // Relationships refer to their entity, hence we always need to copy // them. self.relationships = entity.relationships.map { ModelRelationship(relationship: $0, newEntity: self, disconnect: true) } } public subscript(fetchSpecification n: String) -> FetchSpecification? { return fetchSpecifications[n] } public subscript(adaptorOperation n: String) -> AdaptorOperation? { return adaptorOperations[n] } public var isPattern : Bool { if isExternalNamePattern { return true } for attribute in attributes { if attribute.isPattern { return true } } for relship in relationships { if relship.isPattern { return true } } return false } // MARK: - Equatable public static func ==(lhs: ModelEntity, rhs: ModelEntity) -> Bool { return lhs.isEqual(to: rhs) } } /// Commonly used within the framework, but should not be public API extension Entity { var externalNameOrName : String { return externalName ?? name } }
apache-2.0
c1a89003b54900b39dff2ec2eecbb2c0
32.178451
80
0.631114
4.379556
false
false
false
false
roecrew/AudioKit
AudioKit/Common/Playgrounds/Effects.playground/Pages/Distortion.xcplaygroundpage/Contents.swift
1
4711
//: ## Distortion //: This thing is a beast. //: import XCPlayground import AudioKit let file = try AKAudioFile(readFileName: processingPlaygroundFiles[0], baseDir: .Resources) let player = try AKAudioPlayer(file: file) player.looping = true var distortion = AKDistortion(player) distortion.delay = 0.1 distortion.decay = 1.0 distortion.delayMix = 0.5 distortion.linearTerm = 0.5 distortion.squaredTerm = 0.5 distortion.cubicTerm = 50 distortion.polynomialMix = 0.5 distortion.softClipGain = -6 distortion.finalMix = 0.5 AudioKit.output = AKBooster(distortion, gain: 0.1) AudioKit.start() player.play() //: User Interface Set up class PlaygroundView: AKPlaygroundView { var delaySlider: AKPropertySlider? var decaySlider: AKPropertySlider? var delayMixSlider: AKPropertySlider? var linearTermSlider: AKPropertySlider? var squaredTermSlider: AKPropertySlider? var cubicTermSlider: AKPropertySlider? var polynomialMixSlider: AKPropertySlider? var softClipGainSlider: AKPropertySlider? var finalMixSlider: AKPropertySlider? override func setup() { addTitle("Distortion") addSubview(AKResourcesAudioFileLoaderView( player: player, filenames: processingPlaygroundFiles)) addSubview(AKBypassButton(node: distortion)) delaySlider = AKPropertySlider( property: "Delay", format: "%0.3f ms", value: distortion.delay, minimum: 0.1, maximum: 500, color: AKColor.greenColor() ) { sliderValue in distortion.delay = sliderValue } addSubview(delaySlider!) decaySlider = AKPropertySlider( property: "Decay Rate", value: distortion.decay, minimum: 0.1, maximum: 50, color: AKColor.greenColor() ) { sliderValue in distortion.decay = sliderValue } addSubview(decaySlider!) delayMixSlider = AKPropertySlider( property: "Delay Mix", value: distortion.delayMix, color: AKColor.greenColor() ) { sliderValue in distortion.delayMix = sliderValue } addSubview(delayMixSlider!) linearTermSlider = AKPropertySlider( property: "Linear Term", value: distortion.linearTerm, color: AKColor.greenColor() ) { sliderValue in distortion.linearTerm = sliderValue } addSubview(linearTermSlider!) squaredTermSlider = AKPropertySlider( property: "Squared Term", value: distortion.squaredTerm, color: AKColor.greenColor() ) { sliderValue in distortion.squaredTerm = sliderValue } addSubview(squaredTermSlider!) cubicTermSlider = AKPropertySlider( property: "Cubic Term", value: distortion.cubicTerm, color: AKColor.greenColor() ) { sliderValue in distortion.cubicTerm = sliderValue } addSubview(cubicTermSlider!) polynomialMixSlider = AKPropertySlider( property: "Polynomial Mix", value: distortion.polynomialMix, color: AKColor.greenColor() ) { sliderValue in distortion.polynomialMix = sliderValue } addSubview(polynomialMixSlider!) softClipGainSlider = AKPropertySlider( property: "Soft Clip Gain", format: "%0.3f dB", value: distortion.softClipGain, minimum: -80, maximum: 20, color: AKColor.greenColor() ) { sliderValue in distortion.softClipGain = sliderValue } addSubview(softClipGainSlider!) finalMixSlider = AKPropertySlider( property: "Final Mix", value: distortion.finalMix, color: AKColor.greenColor() ) { sliderValue in distortion.finalMix = sliderValue } addSubview(finalMixSlider!) } func updateUI() { delaySlider?.value = distortion.delay decaySlider?.value = distortion.decay delayMixSlider?.value = distortion.delayMix linearTermSlider?.value = distortion.linearTerm squaredTermSlider?.value = distortion.squaredTerm cubicTermSlider?.value = distortion.cubicTerm polynomialMixSlider?.value = distortion.polynomialMix softClipGainSlider?.value = distortion.softClipGain finalMixSlider?.value = distortion.finalMix } } XCPlaygroundPage.currentPage.needsIndefiniteExecution = true XCPlaygroundPage.currentPage.liveView = PlaygroundView()
mit
28159d00f2a80562f9db568d576805c5
30.61745
70
0.634473
5.28139
false
false
false
false
roambotics/swift
test/SILGen/interface_type_mangling.swift
27
13168
// RUN: %target-swift-emit-silgen -Xllvm -sil-full-demangle %s | %FileCheck %s protocol P { associatedtype Assoc1 associatedtype Assoc2 } protocol PP: P {} protocol PQ: P { associatedtype Assoc1: A } protocol Q { associatedtype Assoc0: A } protocol A { associatedtype Assoc } class Base: Q, A { typealias Assoc = Base typealias Assoc0 = Base } // CHECK-LABEL: interface_type_mangling.f1 // CHECK: [[F_SIGNATURE:<A where A: interface_type_mangling.PP, A: interface_type_mangling.PQ>\(A\) -> \(\)]] func f1<T>(_ x: T) where T: PP, T: PQ {} // CHECK: interface_type_mangling.f2[[F_SIGNATURE]] func f2<T>(_ x: T) where T: PQ, T: PP {} // CHECK: interface_type_mangling.f3[[F_SIGNATURE]] func f3<T>(_ x: T) where T: PQ, T: PP, T: P {} // CHECK-LABEL: interface_type_mangling.g1 // CHECK: [[G_SIGNATURE:<A, B where A: interface_type_mangling.PP, B: interface_type_mangling.PQ>\(_: B, y: A\) -> \(\)]] func g1<U, T>(_ x: T, y: U) where T: PQ, U: PP {} // CHECK: interface_type_mangling.g2[[G_SIGNATURE]] func g2<U, T>(_ x: T, y: U) where T: PQ, T.Assoc1: A, U: PP {} // CHECK: interface_type_mangling.g3[[G_SIGNATURE]] func g3<U, T>(_ x: T, y: U) where U: PP, T: PQ, T.Assoc1: A {} // CHECK-LABEL: interface_type_mangling.h1 // CHECK: [[H_SIGNATURE:<A where A: interface_type_mangling.Base, A: interface_type_mangling.P>\(A\) -> \(\)]] func h1<T>(_ x: T) where T: Base, T: P {} // CHECK: interface_type_mangling.h2[[H_SIGNATURE]] func h2<T>(_ x: T) where T: P, T: Base {} // CHECK: interface_type_mangling.h3[[H_SIGNATURE]] func h3<T>(_ x: T) where T: P, T: Base, T: AnyObject {} // CHECK: interface_type_mangling.h4[[H_SIGNATURE]] func h4<T>(_ x: T) where T: P, T: Base, T: Q {} // CHECK: interface_type_mangling.h5[[H_SIGNATURE]] func h5<T>(_ x: T) where T: P, T: Base, T: Q /* TODO: same type constraints , T.Assoc0 == Base*/ {} // CHECK-LABEL: interface_type_mangling.i1 // CHECK: [[I_SIGNATURE:<A where A: interface_type_mangling.P, A: interface_type_mangling.Q, A.interface_type_mangling.Q.Assoc0: interface_type_mangling.Q, A.interface_type_mangling.P.Assoc1: interface_type_mangling.P>\(A\) -> \(\)]] func i1<T>(_ x: T) where T: P, T: Q, T.Assoc1: P, T.Assoc0: Q {} // CHECK: interface_type_mangling.i2[[I_SIGNATURE]] func i2<T>(_ x: T) where T: P, T: Q, T.Assoc0: Q, T.Assoc1: P {} // CHECK-LABEL: interface_type_mangling.j01 // CHECK: [[J_SIGNATURE:<A where A: interface_type_mangling.P, A: interface_type_mangling.Q, A.interface_type_mangling.Q.Assoc0 == A.interface_type_mangling.P.Assoc1, A.interface_type_mangling.P.Assoc1 == A.interface_type_mangling.P.Assoc2>\(A\) -> \(\)]] func j01<T>(_ x: T) where T: P, T: Q, T.Assoc0 == T.Assoc1, T.Assoc1 == T.Assoc2 {} // CHECK: interface_type_mangling.j02[[J_SIGNATURE]] func j02<T>(_ x: T) where T: P, T: Q, T.Assoc0 == T.Assoc2, T.Assoc1 == T.Assoc2 {} // CHECK: interface_type_mangling.j03[[J_SIGNATURE]] func j03<T>(_ x: T) where T: P, T: Q, T.Assoc0 == T.Assoc2, T.Assoc1 == T.Assoc0 {} // CHECK: interface_type_mangling.j04[[J_SIGNATURE]] func j04<T>(_ x: T) where T: P, T: Q, T.Assoc1 == T.Assoc0, T.Assoc1 == T.Assoc2 {} // CHECK: interface_type_mangling.j05[[J_SIGNATURE]] func j05<T>(_ x: T) where T: P, T: Q, T.Assoc2 == T.Assoc0, T.Assoc1 == T.Assoc2 {} // CHECK: interface_type_mangling.j06[[J_SIGNATURE]] func j06<T>(_ x: T) where T: P, T: Q, T.Assoc2 == T.Assoc0, T.Assoc1 == T.Assoc0 {} // CHECK: interface_type_mangling.j07[[J_SIGNATURE]] func j07<T>(_ x: T) where T: P, T: Q, T.Assoc1 == T.Assoc0, T.Assoc2 == T.Assoc1 {} // CHECK: interface_type_mangling.j08[[J_SIGNATURE]] func j08<T>(_ x: T) where T: P, T: Q, T.Assoc2 == T.Assoc0, T.Assoc2 == T.Assoc1 {} // CHECK: interface_type_mangling.j09[[J_SIGNATURE]] func j09<T>(_ x: T) where T: P, T: Q, T.Assoc2 == T.Assoc0, T.Assoc0 == T.Assoc1 {} // CHECK: interface_type_mangling.j10[[J_SIGNATURE]] func j10<T>(_ x: T) where T: P, T: Q, T.Assoc1 == T.Assoc2, T.Assoc0 == T.Assoc1 {} // CHECK: interface_type_mangling.j11[[J_SIGNATURE]] func j11<T>(_ x: T) where T: P, T: Q, T.Assoc1 == T.Assoc2, T.Assoc0 == T.Assoc2 {} // CHECK: interface_type_mangling.j12[[J_SIGNATURE]] func j12<T>(_ x: T) where T: P, T: Q, T.Assoc1 == T.Assoc0, T.Assoc0 == T.Assoc2 {} // CHECK: interface_type_mangling.j13[[J_SIGNATURE]] func j13<T>(_ x: T) where T: P, T: Q, T.Assoc1 == T.Assoc2, T.Assoc1 == T.Assoc0 {} // CHECK: interface_type_mangling.j14[[J_SIGNATURE]] func j14<T>(_ x: T) where T: P, T: Q, T.Assoc1 == T.Assoc2, T.Assoc2 == T.Assoc0 {} // CHECK: interface_type_mangling.j15[[J_SIGNATURE]] func j15<T>(_ x: T) where T: P, T: Q, T.Assoc1 == T.Assoc0, T.Assoc2 == T.Assoc0 {} // CHECK: interface_type_mangling.j16[[J_SIGNATURE]] func j16<T>(_ x: T) where T: P, T: Q, T.Assoc2 == T.Assoc1, T.Assoc1 == T.Assoc0 {} // CHECK: interface_type_mangling.j17[[J_SIGNATURE]] func j17<T>(_ x: T) where T: P, T: Q, T.Assoc2 == T.Assoc1, T.Assoc2 == T.Assoc0 {} // CHECK: interface_type_mangling.j18[[J_SIGNATURE]] func j18<T>(_ x: T) where T: P, T: Q, T.Assoc0 == T.Assoc1, T.Assoc2 == T.Assoc0 {} struct S {} struct G<X> {} // CHECK-LABEL: interface_type_mangling.k01 // CHECK: [[K_SIGNATURE:<A where A: interface_type_mangling.P, A.Assoc1 == interface_type_mangling.S, A.Assoc2 == interface_type_mangling.S>\(A\) -> \(\)]] func k01<T>(_ x: T) where T: P, S == T.Assoc1, T.Assoc1 == T.Assoc2 {} // CHECK: interface_type_mangling.k02[[K_SIGNATURE]] func k02<T>(_ x: T) where T: P, S == T.Assoc2, T.Assoc1 == T.Assoc2 {} // CHECK: interface_type_mangling.k03[[K_SIGNATURE]] func k03<T>(_ x: T) where T: P, S == T.Assoc2, T.Assoc1 == S {} // CHECK: interface_type_mangling.k04[[K_SIGNATURE]] func k04<T>(_ x: T) where T: P, T.Assoc1 == S, T.Assoc1 == T.Assoc2 {} // CHECK: interface_type_mangling.k05[[K_SIGNATURE]] func k05<T>(_ x: T) where T: P, T.Assoc2 == S, T.Assoc1 == T.Assoc2 {} // CHECK: interface_type_mangling.k06[[K_SIGNATURE]] func k06<T>(_ x: T) where T: P, T.Assoc2 == S, T.Assoc1 == S {} // CHECK: interface_type_mangling.k07[[K_SIGNATURE]] func k07<T>(_ x: T) where T: P, T.Assoc1 == S, T.Assoc2 == T.Assoc1 {} // CHECK: interface_type_mangling.k08[[K_SIGNATURE]] func k08<T>(_ x: T) where T: P, T.Assoc2 == S, T.Assoc2 == T.Assoc1 {} // CHECK: interface_type_mangling.k09[[K_SIGNATURE]] func k09<T>(_ x: T) where T: P, T.Assoc2 == S, S == T.Assoc1 {} // CHECK: interface_type_mangling.k10[[K_SIGNATURE]] func k10<T>(_ x: T) where T: P, T.Assoc1 == T.Assoc2, S == T.Assoc1 {} // CHECK: interface_type_mangling.k11[[K_SIGNATURE]] func k11<T>(_ x: T) where T: P, T.Assoc1 == T.Assoc2, S == T.Assoc2 {} // CHECK: interface_type_mangling.k12[[K_SIGNATURE]] func k12<T>(_ x: T) where T: P, T.Assoc1 == S, S == T.Assoc2 {} // CHECK: interface_type_mangling.k13[[K_SIGNATURE]] func k13<T>(_ x: T) where T: P, T.Assoc1 == T.Assoc2, T.Assoc1 == S {} // CHECK: interface_type_mangling.k14[[K_SIGNATURE]] func k14<T>(_ x: T) where T: P, T.Assoc1 == T.Assoc2, T.Assoc2 == S {} // CHECK: interface_type_mangling.k15[[K_SIGNATURE]] func k15<T>(_ x: T) where T: P, T.Assoc1 == S, T.Assoc2 == S {} // CHECK: interface_type_mangling.k16[[K_SIGNATURE]] func k16<T>(_ x: T) where T: P, T.Assoc2 == T.Assoc1, T.Assoc1 == S {} // CHECK: interface_type_mangling.k17[[K_SIGNATURE]] func k17<T>(_ x: T) where T: P, T.Assoc2 == T.Assoc1, T.Assoc2 == S {} // CHECK: interface_type_mangling.k18[[K_SIGNATURE]] func k18<T>(_ x: T) where T: P, S == T.Assoc1, T.Assoc2 == S {} // CHECK-LABEL: interface_type_mangling.L01 // CHECK: [[L_SIGNATURE:<A where A: interface_type_mangling.P, A.Assoc1 == interface_type_mangling.G<A>, A.Assoc2 == interface_type_mangling.G<A>>\(A\) -> \(\)]] func L01<T>(_ x: T) where T: P, G<T> == T.Assoc1, T.Assoc1 == T.Assoc2 {} // CHECK: interface_type_mangling.L02[[L_SIGNATURE]] func L02<T>(_ x: T) where T: P, G<T> == T.Assoc2, T.Assoc1 == T.Assoc2 {} // CHECK: interface_type_mangling.L03[[L_SIGNATURE]] func L03<T>(_ x: T) where T: P, G<T> == T.Assoc2, T.Assoc1 == G<T> {} // CHECK: interface_type_mangling.L04[[L_SIGNATURE]] func L04<T>(_ x: T) where T: P, T.Assoc1 == G<T>, T.Assoc1 == T.Assoc2 {} // CHECK: interface_type_mangling.L05[[L_SIGNATURE]] func L05<T>(_ x: T) where T: P, T.Assoc2 == G<T>, T.Assoc1 == T.Assoc2 {} // CHECK: interface_type_mangling.L06[[L_SIGNATURE]] func L06<T>(_ x: T) where T: P, T.Assoc2 == G<T>, T.Assoc1 == G<T> {} // CHECK: interface_type_mangling.L07[[L_SIGNATURE]] func L07<T>(_ x: T) where T: P, T.Assoc1 == G<T>, T.Assoc2 == T.Assoc1 {} // CHECK: interface_type_mangling.L08[[L_SIGNATURE]] func L08<T>(_ x: T) where T: P, T.Assoc2 == G<T>, T.Assoc2 == T.Assoc1 {} // CHECK: interface_type_mangling.L09[[L_SIGNATURE]] func L09<T>(_ x: T) where T: P, T.Assoc2 == G<T>, G<T> == T.Assoc1 {} // CHECK: interface_type_mangling.L10[[L_SIGNATURE]] func L10<T>(_ x: T) where T: P, T.Assoc1 == T.Assoc2, G<T> == T.Assoc1 {} // CHECK: interface_type_mangling.L11[[L_SIGNATURE]] func L11<T>(_ x: T) where T: P, T.Assoc1 == T.Assoc2, G<T> == T.Assoc2 {} // CHECK: interface_type_mangling.L12[[L_SIGNATURE]] func L12<T>(_ x: T) where T: P, T.Assoc1 == G<T>, G<T> == T.Assoc2 {} // CHECK: interface_type_mangling.L13[[L_SIGNATURE]] func L13<T>(_ x: T) where T: P, T.Assoc1 == T.Assoc2, T.Assoc1 == G<T> {} // CHECK: interface_type_mangling.L14[[L_SIGNATURE]] func L14<T>(_ x: T) where T: P, T.Assoc1 == T.Assoc2, T.Assoc2 == G<T> {} // CHECK: interface_type_mangling.L15[[L_SIGNATURE]] func L15<T>(_ x: T) where T: P, T.Assoc1 == G<T>, T.Assoc2 == G<T> {} // CHECK: interface_type_mangling.L16[[L_SIGNATURE]] func L16<T>(_ x: T) where T: P, T.Assoc2 == T.Assoc1, T.Assoc1 == G<T> {} // CHECK: interface_type_mangling.L17[[L_SIGNATURE]] func L17<T>(_ x: T) where T: P, T.Assoc2 == T.Assoc1, T.Assoc2 == G<T> {} // CHECK: interface_type_mangling.L18[[L_SIGNATURE]] func L18<T>(_ x: T) where T: P, G<T> == T.Assoc1, T.Assoc2 == G<T> {} struct X {}; struct Y {} // CHECK-LABEL: interface_type_mangling.m1 // CHECK: [[M_SIGNATURE:<A, B where A: interface_type_mangling.A, B: interface_type_mangling.A, A.Assoc == interface_type_mangling.X, B.Assoc == interface_type_mangling.Y>\(_: A, y: B\) -> \(\)]] func m1<T: A, U: A>(_ x: T, y: U) where T.Assoc == X, U.Assoc == Y {} // CHECK: interface_type_mangling.m2[[M_SIGNATURE]] func m2<T: A, U: A>(_ x: T, y: U) where U.Assoc == Y, T.Assoc == X {} // CHECK: interface_type_mangling.m3[[M_SIGNATURE]] func m3<T, U>(_ x: T, y: U) where T: A, U: A, U.Assoc == Y, T.Assoc == X {} protocol GenericWitnessTest { associatedtype Tee func closureInGenericContext<X>(_ b: X) var closureInGenericPropertyContext: Tee { get } func twoParamsAtDepth<Y, Z>(_ x: Y, y: Z) } struct GenericTypeContext<T>: GenericWitnessTest { typealias Tee = T var a: T // CHECK-LABEL: sil private [ossa] @$s23interface_type_mangling18GenericTypeContextV09closureIndF0yyqd__lF3fooL_yyx_qd__tr__lF func closureInGenericContext<U>(_ b: U) { func foo(_ x: T, _ y: U) { } foo(a, b) } // CHECK-LABEL: sil private [ossa] @$s23interface_type_mangling18GenericTypeContextV09closureInd8PropertyF0xvg3fooL_xylF var closureInGenericPropertyContext: T { func foo() -> T { } return foo() } // FIXME: Demangling for generic params at depth is wrong. // CHECK-LABEL: twoParamsAtDepth<A, B>(_: A1, y: B1) -> () // CHECK-LABEL: sil hidden [ossa] @$s23interface_type_mangling18GenericTypeContextV16twoParamsAtDepth_1yyqd___qd_0_tr0_lF func twoParamsAtDepth<A, B>(_ x: A, y: B) {} } // CHECK-LABEL: protocol witness for interface_type_mangling.GenericWitnessTest.closureInGenericContext<A>(A1) -> () in conformance interface_type_mangling.GenericTypeContext<A> : interface_type_mangling.GenericWitnessTest in interface_type_mangling // CHECK-LABEL: @$s23interface_type_mangling18GenericTypeContextVyxGAA0D11WitnessTestA2aEP09closureIndF0yyqd__lFTW // CHECK-LABEL: protocol witness for interface_type_mangling.GenericWitnessTest.closureInGenericPropertyContext.getter : A.Tee in conformance interface_type_mangling.GenericTypeContext<A> : interface_type_mangling.GenericWitnessTest in interface_type_mangling // CHECK-LABEL: @$s23interface_type_mangling18GenericTypeContextVyxGAA0D11WitnessTestA2aEP09closureInd8PropertyF03TeeQzvgTW // CHECK-LABEL: protocol witness for interface_type_mangling.GenericWitnessTest.twoParamsAtDepth<A, B>(_: A1, y: B1) -> () in conformance interface_type_mangling.GenericTypeContext<A> : interface_type_mangling.GenericWitnessTest in interface_type_mangling // CHECK-LABEL: @$s23interface_type_mangling18GenericTypeContextVyxGAA0D11WitnessTestA2aEP16twoParamsAtDepth_1yyqd___qd_0_tr0_lFTW
apache-2.0
c55c51c31ec2525c6a8b4a219c83b063
57.785714
288
0.622874
2.721786
false
false
false
false
asurinsaka/swift_examples_2.1
SpriteKit/SpriteKit/ViewController.swift
1
2816
// // ViewController.swift // SpriteKit // // Created by larryhou on 5/18/15. // Copyright (c) 2015 larryhou. All rights reserved. // import UIKit import SpriteKit class ViewController: UIViewController, XMLReaderDelegate { private var _actions:[NinjaActionInfo]! private var _scene:SKScene! private var _ninja:NinjaPresenter! private var _assets:[String]! private var _index:Int = 0 override func viewDidLoad() { super.viewDidLoad() var skView = SKView(frame: self.view.frame) skView.frameInterval = 2 skView.showsNodeCount = true skView.showsFPS = true _scene = SKScene(size: skView.frame.size) _scene.backgroundColor = UIColor.grayColor() _scene.anchorPoint = CGPointMake(0.5, 0.5) _scene.scaleMode = SKSceneScaleMode.ResizeFill skView.presentScene(_scene) _assets = ["10000101", "10000201", "10000301", "10000501", "11000141", "11000171"] _index = 0 self.view.addSubview(skView) var tap:UITapGestureRecognizer tap = UITapGestureRecognizer() tap.addTarget(self, action: "playNextNinjaAction") view.addGestureRecognizer(tap) tap = UITapGestureRecognizer() tap.numberOfTapsRequired = 2 tap.addTarget(self, action: "changeToAnotherNinja") view.addGestureRecognizer(tap) changeToAnotherNinja() } func playNextNinjaAction() { _ninja.playNextAction() } func changeToAnotherNinja() { let url = NSBundle.mainBundle().URLForResource(_assets[_index], withExtension: "xml") if url != nil { XMLReader().read(NSData(contentsOfURL: url!)!, delegate: self) } _index++ } func readerDidFinishDocument(reader: XMLReader, data: NSDictionary, elapse: NSTimeInterval) { _actions = [] let rawActions = (data.valueForKeyPath("actions.action") as! NSArray)[0] as! NSArray for i in 0..<rawActions.count { let item = rawActions[i] as! NSDictionary var action = NinjaActionInfo(index: _actions.count, name: item["name"] as! String) action.decode(item) _actions.append(action) } if _ninja != nil { _ninja.removeAllChildren() _ninja.removeFromParent() _ninja = nil } _ninja = NinjaPresenter(atlas: SKTextureAtlas(named: _assets[_index]), actionInfos: _actions) _ninja.play(_actions[0].name) _scene.addChild(_ninja) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
mit
038f10c609d50a284541c22cc230b986
26.339806
101
0.588068
4.578862
false
false
false
false
PJayRushton/stats
Stats/GamesViewController.swift
1
12845
// // GamesViewController.swift // Stats // // Created by Parker Rushton on 4/17/17. // Copyright © 2017 AppsByPJ. All rights reserved. // import UIKit import Presentr class GamesViewController: Component, AutoStoryboardInitializable { // MARK: - IBOutlets @IBOutlet var calendarButton: UIBarButtonItem! @IBOutlet weak var tableView: UITableView! @IBOutlet var emptyStateView: UIView! @IBOutlet weak var emptyStateLabel: UILabel! // MARK: - Properties var new = false fileprivate var isReadyToShowNewGame = true fileprivate var isReadytoShowStats = true fileprivate var ongoingGames = [Game]() fileprivate var regularSeasonGames = [Game]() fileprivate var postSeasonGames = [Game]() fileprivate var tableIsEmpty = false fileprivate var hasPostSeason = false fileprivate let tapper = UISelectionFeedbackGenerator() // MARK: - ViewController Lifecycle override func viewDidLoad() { super.viewDidLoad() tapper.prepare() tableView.rowHeight = UITableViewAutomaticDimension tableView.estimatedRowHeight = 90 emptyStateLabel.text = NSLocalizedString("ooh your first game!\nHow exciting!", comment: "The player is about to create their first game. And that's awesome") } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.setNavigationBarHidden(false, animated: animated) navigationController?.navigationBar.barTintColor = .mainAppColor isReadyToShowNewGame = true isReadytoShowStats = true if new { new = false presentNewGameVC() } core.fire(event: StatGameUpdated(game: nil)) core.fire(command: ProcessGamesForCalendar(from: self)) } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) core.fire(event: NewGameReadyToShow(ready: false)) } // MARK: - IBActions @IBAction func createNewGame() { tapper.selectionChanged() presentNewGameVC() } @IBAction func emptyStateNewGamePressed(_ sender: UIButton) { tapper.selectionChanged() createNewGame() } @IBAction func calendarButtonPressed(_ sender: Any) { if CalendarService.hasCalendarPermission, let processedGames = core.state.gameState.processedGames { showCalendarResponseAlert(saveGames: processedGames.gamesToSave, dirtyGames: processedGames.gamesToEdit) } else { CalendarService.requestCalendarAccess(completion: { granted in self.core.fire(command: ProcessGamesForCalendar(from: self, completion: { calendarGames in self.showCalendarResponseAlert(saveGames: calendarGames.gamesToSave, dirtyGames: calendarGames.gamesToEdit) })) }) } } // MARK: - Subscriber override func update(with state: AppState) { let gameState = state.gameState ongoingGames = gameState.currentOngoingGames.sortedByDate() regularSeasonGames = gameState.currentGames(regularSeason: true).sortedByDate() postSeasonGames = gameState.currentGames(regularSeason: false).sortedByDate() hasPostSeason = !postSeasonGames.isEmpty tableIsEmpty = gameState.currentGames.isEmpty let hasCalendarAction = !CalendarService.hasCalendarPermission || state.gameState.processedGames?.hasSavableGames == true navigationItem.rightBarButtonItem = hasCalendarAction ? calendarButton : nil tableView.backgroundView = tableIsEmpty ? emptyStateView : nil tableView.reloadData() if core.state.newGameState.isReadyToShow && isReadyToShowNewGame { isReadyToShowNewGame = false pushDetail() } if let recentlyCompletedGame = state.gameState.recentlyCompletedGame, isReadytoShowStats { isReadytoShowStats = false core.fire(event: UpdateRecentlyCompletedGame(game: nil)) core.fire(event: StatGameUpdated(game: recentlyCompletedGame)) pushStats() } } } // MARK: Fileprivate extension GamesViewController { fileprivate func presentNewGameVC() { let newGameVC = GameCreationViewController.initializeFromStoryboard().embededInNavigationController newGameVC.modalPresentationStyle = .overFullScreen present(newGameVC, animated: true, completion: nil) } fileprivate func pushDetail() { tapper.selectionChanged() let gameVC = GameViewController.initializeFromStoryboard() navigationController?.pushViewController(gameVC, animated: true) } fileprivate func presentOptionsAlert(for game: Game) { let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet) alert.addAction(UIAlertAction(title: "Show Game", style: .default, handler: { _ in self.pushDetail() })) alert.addAction(UIAlertAction(title: "Show Stats", style: .default, handler: { _ in self.pushStats(for: game) })) alert.addAction(UIAlertAction(title: "Dismiss", style: .cancel, handler: nil)) present(alert, animated: true, completion: nil) } fileprivate func pushStats(for game: Game? = nil) { let statsVC = StatsViewController.initializeFromStoryboard() navigationController?.pushViewController(statsVC, animated: true) if let game = game { saveStatsIfNeeded(for: game) } } fileprivate func saveStatsIfNeeded(for game: Game) { core.fire(command: UpdateTrophies(for: game)) if core.state.statState.stats(for: game.id) == nil { core.fire(command: SaveGameStats(for: game)) } } fileprivate func showCalendarResponseAlert(saveGames: [Game], dirtyGames: [Game]) { if saveGames.isEmpty && dirtyGames.isEmpty { showCalendarUpToDateAlert() return } var message = "I found " let hasGamesToSave = !saveGames.isEmpty let hasDirtyGames = !dirtyGames.isEmpty if hasGamesToSave { message += "\(saveGames.count) new games to add" } if hasDirtyGames { if !saveGames.isEmpty { message += " & " } message += "\(dirtyGames.count) games that need to be updated" } let alert = UIAlertController(title: "Calendar updates", message: message, preferredStyle: .actionSheet) if hasGamesToSave { alert.addAction(UIAlertAction(title: "Save \(saveGames.count) New Games", style: .default, handler: { _ in self.core.fire(command: AddGamesToCalendar(saveGames)) self.showSuccessAlert() })) } if hasDirtyGames { alert.addAction(UIAlertAction(title: "Update \(dirtyGames.count) games", style: .default, handler: { _ in self.core.fire(command: EditCalendarEventForGames(dirtyGames)) self.showSuccessAlert() })) } if hasGamesToSave && hasDirtyGames { alert.addAction(UIAlertAction(title: "Save & Update All", style: .default, handler: { _ in self.core.fire(command: AddGamesToCalendar(saveGames)) self.core.fire(command: EditCalendarEventForGames(dirtyGames)) self.showSuccessAlert() })) } guard !alert.actions.isEmpty else { return } alert.addAction(UIAlertAction.cancel) present(alert, animated: true, completion: nil) } fileprivate func showCalendarUpToDateAlert() { let alert = UIAlertController(title: "You're good to go!", message: "All these games are already in your calendar", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "😎", style: .cancel, handler: nil)) present(alert, animated: true, completion: nil) } fileprivate func showSuccessAlert() { let alert = UIAlertController(title: "Success!", message: "Games were successfully saved to your default calendar", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "👍", style: .cancel, handler: { _ in self.core.fire(command: ProcessGamesForCalendar(from: self)) })) present(alert, animated: true, completion: nil) } } // MARK: - TableView DataSource extension GamesViewController: UITableViewDataSource { enum SectionType { case ongoing case postSeason case regularSeason var headerTitle: String { switch self { case .ongoing: return NSLocalizedString("In Progress", comment: "Followed by the list of games that are still being played") case .postSeason: return NSLocalizedString("Post Season", comment: "Followed by the list of games completed during season following the regular season e.g playoffs, tournament etc.") case .regularSeason: return NSLocalizedString("Regular Season", comment: "Followed by the list of games completed during the regular season") } } } func sectionType(for section: Int) -> SectionType { switch section { case 0: if !ongoingGames.isEmpty { return .ongoing } else if hasPostSeason { return .postSeason } else { return .regularSeason } case 1: if !ongoingGames.isEmpty { return hasPostSeason ? .postSeason : .regularSeason } else { fallthrough } default: return .regularSeason } } func record(for section: Int) -> TeamRecord? { switch sectionType(for: section) { case .ongoing: return nil case .postSeason: return core.state.gameState.currentGames(regularSeason: false).record case .regularSeason: return core.state.gameState.currentGames(regularSeason: true).record } } func games(for section: Int) -> [Game] { switch sectionType(for: section) { case .ongoing: return ongoingGames case .postSeason: return postSeasonGames case .regularSeason: return regularSeasonGames } } func game(at indexPath: IndexPath) -> Game { return games(for: indexPath.section)[indexPath.row] } func numberOfSections(in tableView: UITableView) -> Int { var count = 0 for gamesArray in [ongoingGames, postSeasonGames, regularSeasonGames] { if !gamesArray.isEmpty { count += 1 } } return count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return games(for: section).count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: GameCell.reuseIdentifier) as! GameCell let gameAtIndex = game(at: indexPath) cell.update(with: gameAtIndex) cell.accessoryType = sectionType(for: indexPath.section) == .ongoing ? .disclosureIndicator : .none return cell } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { guard !tableIsEmpty else { return nil } let headerCell = tableView.dequeueReusableCell(withIdentifier: GamesHeaderCell.reuseIdentifier) as! GamesHeaderCell let title = sectionType(for: section).headerTitle let seasonRecord = record(for: section) headerCell.update(withTitle: title, record: seasonRecord) return headerCell } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return tableIsEmpty ? 0 : 34 } } // MARK: - TableView Delegate extension GamesViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let selectedGame = game(at: indexPath) core.fire(event: Selected<Game>(selectedGame)) core.fire(event: StatGameUpdated(game: selectedGame)) if sectionType(for: indexPath.section) == .ongoing { pushDetail() } else { presentOptionsAlert(for: selectedGame) } } }
mit
b3a7ac1845c8ffa102b9a1e46765d52b
34.860335
180
0.632653
5.020727
false
false
false
false
iOSWizards/AwesomeMedia
Example/Pods/AwesomeConstants/AwesomeConstants/Classes/Extensions/DateExtensions.swift
1
5907
// // Date+Formatting.swift // Quests // // Created by Evandro Harrison Hoffmann on 1/26/17. // Copyright © 2017 Mindvalley. All rights reserved. // import Foundation extension Date { public func toString(format: String) -> String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = format return dateFormatter.string(from: self) } public func days(toDate date: Date) -> Int { // Replace the hour (time) of both dates with 00:00 let date1 = Calendar.current.startOfDay(for: self) let date2 = Calendar.current.startOfDay(for: date) let components = Calendar.current.dateComponents([Calendar.Component.day], from: date1, to: date2) if let days = components.day { return days } return 0 } public func hours(toDate date: Date) -> Int { let components = Calendar.current.dateComponents([Calendar.Component.hour], from: self, to: date) if let hours = components.hour { return hours } return 0 } public func minutes(toDate date: Date) -> Int { let components = Calendar.current.dateComponents([Calendar.Component.minute], from: self, to: date) if let minutes = components.minute { return minutes } return 0 } public var lapseString: String { let daysAgo = self.days(toDate: Date()) let hoursAgo = self.hours(toDate: Date()) let minutesAgo = self.minutes(toDate: Date()) if daysAgo > 1 { return self.toString(format: "MMM dd").appendingFormat(" %@ %@", "at".localized, self.toString(format: "h:mm a").lowercased()) } else if daysAgo == 1 { return "yesterday".localized } else if hoursAgo > 1 { return String(format: "%d %@", hoursAgo, "hours_ago".localized) } else if hoursAgo == 1 { return "1_hour_ago".localized } else if minutesAgo > 1 { return String(format: "%d %@", minutesAgo, "minutes_ago".localized) } else { return "now".localized } } public func years(from date: Date) -> Int { return Calendar.current.dateComponents([.year], from: date, to: self).year ?? 0 } public func months(from date: Date) -> Int { return Calendar.current.dateComponents([.month], from: date, to: self).month ?? 0 } public func weeks(from date: Date) -> Int { return Calendar.current.dateComponents([.weekOfYear], from: date, to: self).weekOfYear ?? 0 } public func days(from date: Date) -> Int { return Calendar.current.dateComponents([.day], from: date, to: self).day ?? 0 } public func hours(from date: Date) -> Int { return Calendar.current.dateComponents([.hour], from: date, to: self).hour ?? 0 } public func minutes(from date: Date) -> Int { return Calendar.current.dateComponents([.minute], from: date, to: self).minute ?? 0 } public func seconds(from date: Date) -> Int { return Calendar.current.dateComponents([.second], from: date, to: self).second ?? 0 } public func offset(from date: Date) -> String { if years(from: date) == 1 { return "\(years(from: date)) \("year".localized) \("ago".localized)" } if years(from: date) > 1 { return "\(years(from: date)) \("years".localized) \("ago".localized)" } if months(from: date) == 1 { return "\(months(from: date)) \("month".localized) \("ago".localized)" } if months(from: date) > 1 { return "\(months(from: date)) \("months".localized) \("ago".localized)" } if weeks(from: date) == 1 { return "\(weeks(from: date)) \("week".localized) \("ago".localized)" } if weeks(from: date) > 1 { return "\(weeks(from: date)) \("weeks".localized) \("ago".localized)" } if days(from: date) == 1 { return "\(days(from: date)) \("day".localized) \("ago".localized)" } if days(from: date) > 1 { return "\(days(from: date)) \("days".localized) \("ago".localized)" } if hours(from: date) == 1 { return "\(hours(from: date)) \("hour".localized) \("ago".localized)" } if hours(from: date) > 1 { return "\(hours(from: date)) \("hours".localized) \("ago".localized)" } if minutes(from: date) == 1 { return "\(minutes(from: date)) \("minute".localized) \("ago".localized)" } if minutes(from: date) > 1 { return "\(minutes(from: date)) \("minutes".localized) \("ago".localized)" } if seconds(from: date) == 1 { return "\(seconds(from: date)) \("second".localized) \("ago".localized)" } if seconds(from: date) > 1 { return "\(seconds(from: date)) \("seconds".localized) \("ago".localized)" } return "Just now".localized } public func withTime(_ time: String, format: String = "HH:mm") -> Date { let date = self.toString(format: "yyyy/MM/dd") return date.appending(" \(time)").toDate(format: "yyyy/MM/dd \(format)") } public static var tomorrow: Date? { let today = Date() return Calendar.current.date(byAdding: .day, value: 1, to: today) } public func getElapsedInterval() -> String { let interval = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: self, to: Date()) return "\(interval.year ?? 0) years, \(interval.month ?? 0) months, \(interval.day ?? 0) days, \(interval.hour ?? 0) hours, \(interval.minute ?? 0) minutes, \(interval.second ?? 0) seconds" } } extension NSDate { public static func toString(withFormat format: String = "yyyy-MM-dd HH:mm:ss") -> String { let date = Date(timeIntervalSinceReferenceDate: self.timeIntervalSinceReferenceDate) let dateFormatter = DateFormatter() dateFormatter.dateFormat = format return dateFormatter.string(from: date) } }
mit
bc356faf0b61f0d356d43844b2199fac
40.013889
197
0.600068
3.982468
false
false
false
false
wonderkiln/WKAwesomeMenu
WKAwesomeMenu/WKAwesomeMenu.swift
2
12188
// // WKAwesomeMenu.swift // WKAwesomeMenu // // Created by Adrian Mateoaea on 30.01.2016. // Copyright © 2016 Wonderkiln. All rights reserved. // import UIKit open class WKAwesomeMenu: UIViewController { // MARK: - Private Variables fileprivate var rootViewController: UIViewController! fileprivate var menuViewController: UIViewController! fileprivate var rootView: UIView! // TODO: fix no user interaction while menu is open fileprivate var menuView: UIView! fileprivate var shadowView: UIView = UIView() fileprivate var canSlide: Bool = false fileprivate var lastTranslation = CGPoint.zero fileprivate var lightStatusBar: Bool = false { didSet { self.setNeedsStatusBarAppearanceUpdate() } } // MARK: - Public Variables var options = WKAwesomeMenuOptions.defaultOptions() var isClosed: Bool = true { didSet { self.lightStatusBar = !self.isClosed self.rootView?.isUserInteractionEnabled = self.isClosed } } // MARK: - Initialization public convenience init(rootViewController root: UIViewController, menuViewController menu: UIViewController, options: WKAwesomeMenuOptions? = nil) { self.init() if let options = options { self.options = options } self.rootViewController = root self.menuViewController = menu self.rootView = root.view self.menuView = menu.view self.addChildViewController(root) self.addChildViewController(menu) root.didMove(toParentViewController: self) menu.didMove(toParentViewController: self) // Disable top to scroll up for the menu // in order to scroll the root view controller (menu as? UITableViewController)?.tableView.scrollsToTop = false self.setupUI() let pan = UIPanGestureRecognizer(target: self, action: #selector(WKAwesomeMenu.pan(_:))) pan.minimumNumberOfTouches = 1 pan.maximumNumberOfTouches = 1 self.view.addGestureRecognizer(pan) let tap = UITapGestureRecognizer(target: self, action: #selector(WKAwesomeMenu.closeMenu)) self.shadowView.addGestureRecognizer(tap) } func setupUI() { if self.options.backgroundImage != nil { let background = UIImageView(image: self.options.backgroundImage) self.view.addSubview(background) background.translatesAutoresizingMaskIntoConstraints = false self.view.addConstraint(NSLayoutConstraint(item: background, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.top, multiplier: 1, constant: 0)) self.view.addConstraint(NSLayoutConstraint(item: background, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.bottom, multiplier: 1, constant: 0)) self.view.addConstraint(NSLayoutConstraint(item: background, attribute: NSLayoutAttribute.leading, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.leading, multiplier: 1, constant: 0)) self.view.addConstraint(NSLayoutConstraint(item: background, attribute: NSLayoutAttribute.trailing, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.trailing, multiplier: 1, constant: 0)) } self.menuView.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(self.menuView) self.view.addConstraint(NSLayoutConstraint(item: self.menuView, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.top, multiplier: 1, constant: 0)) self.view.addConstraint(NSLayoutConstraint(item: self.menuView, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.bottom, multiplier: 1, constant: 0)) self.view.addConstraint(NSLayoutConstraint(item: self.menuView, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: self.options.menuWidth)) self.shadowView.clipsToBounds = true self.shadowView.backgroundColor = self.options.shadowColor self.shadowView.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(self.shadowView) self.view.addConstraint(NSLayoutConstraint(item: self.shadowView, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.top, multiplier: 1, constant: 0)) self.view.addConstraint(NSLayoutConstraint(item: self.shadowView, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.bottom, multiplier: 1, constant: 0)) self.view.addConstraint(NSLayoutConstraint(item: self.shadowView, attribute: NSLayoutAttribute.leading, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.leading, multiplier: 1, constant: 0)) self.view.addConstraint(NSLayoutConstraint(item: self.shadowView, attribute: NSLayoutAttribute.trailing, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.trailing, multiplier: 1, constant: 0)) self.setupRootViewUI() } func setupRootViewUI() { self.rootView.clipsToBounds = true self.rootView.translatesAutoresizingMaskIntoConstraints = false self.view.addSubview(self.rootView) self.view.addConstraint(NSLayoutConstraint(item: self.rootView, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.top, multiplier: 1, constant: 0)) self.view.addConstraint(NSLayoutConstraint(item: self.rootView, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.bottom, multiplier: 1, constant: 0)) self.view.addConstraint(NSLayoutConstraint(item: self.rootView, attribute: NSLayoutAttribute.leading, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.leading, multiplier: 1, constant: 0)) self.view.addConstraint(NSLayoutConstraint(item: self.rootView, attribute: NSLayoutAttribute.trailing, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.trailing, multiplier: 1, constant: 0)) } // MARK: - Internal func pan(_ pan: UIPanGestureRecognizer) { let translation = pan.translation(in: self.view) let velocity = pan.velocity(in: self.view) let locationX = max(0, min(translation.x, self.options.menuWidth)) let shouldClose = locationX + velocity.x / 2 < self.options.menuWidth / 2 switch pan.state { case UIGestureRecognizerState.began: self.canSlide = pan.location(in: self.view).x <= self.options.menuGripWidth || !self.isClosed if !self.canSlide { break } self.lightStatusBar = true pan.setTranslation(self.lastTranslation, in: self.view) case UIGestureRecognizerState.ended: if !self.canSlide { break } self.isClosed = shouldClose self.lastTranslation = CGPoint(x: shouldClose ? 0 : self.options.menuWidth, y: 0) let duration = Double(min(0.5, self.options.menuWidth / abs(velocity.x))) let percentage = locationX / self.options.menuWidth ProgressTimer.createWithDuration(duration, from: percentage, inverse: shouldClose, callback: { (p) -> Void in self.invalidateRootViewWithPercentage(p) }) case UIGestureRecognizerState.changed: if !self.canSlide { break } self.invalidateRootViewWithPercentage(locationX / self.options.menuWidth) self.lastTranslation = translation default: break } } func invalidateRootViewWithPercentage(_ percentage: CGFloat) { let radius = self.options.cornerRadius * percentage let scale = 1 - (1 - self.options.rootScale) * percentage let translate = CGPoint(x: self.options.menuWidth * percentage, y: 0) var transform = CGAffineTransform(scaleX: scale, y: scale) transform = transform.translatedBy(x: translate.x, y: translate.y) self.rootView.transform = transform self.rootView.layer.cornerRadius = radius self.menuView.transform = CGAffineTransform(translationX: self.options.menuParallax * (1 - percentage), y: 0) let scale2 = scale * self.options.shadowScale let translate2 = CGPoint( x: translate.x + self.options.shadowOffset.x * percentage, y: translate.y + self.options.shadowOffset.y * percentage) var transform2 = CGAffineTransform(scaleX: scale2, y: scale2) transform2 = transform2.translatedBy(x: translate2.x, y: translate2.y) self.shadowView.transform = transform2 self.shadowView.layer.cornerRadius = radius } // MARK: - Public func changeRootViewController(_ vc: UIViewController, withAnimationDuration duration: TimeInterval = 0.2) { let transform = self.rootView?.transform ?? CGAffineTransform.identity let radius = self.rootView?.layer.cornerRadius ?? 0 let lastVC = self.rootViewController self.rootViewController = vc self.rootView = vc.view self.addChildViewController(vc) vc.didMove(toParentViewController: self) self.setupRootViewUI() self.rootView.layer.cornerRadius = radius self.rootView.transform = transform self.rootView.alpha = 0 UIView.animate(withDuration: duration, animations: { () -> Void in self.rootView.alpha = 1 }) { [weak lastVC] (complete) -> Void in lastVC?.view?.removeFromSuperview() lastVC?.removeFromParentViewController() self.closeMenu() } } open func openMenu() { self.openMenuWithDuration(0.2) } open func openMenuWithDuration(_ duration: TimeInterval) { if !self.isClosed { return } self.isClosed = false self.lightStatusBar = true self.lastTranslation = CGPoint(x: self.options.menuWidth, y: 0) ProgressTimer.createWithDuration(duration, callback: { (p) -> Void in self.invalidateRootViewWithPercentage(p) }) } open func closeMenu() { self.closeMenuWithDuration(0.2) } open func closeMenuWithDuration(_ duration: TimeInterval) { if self.isClosed { return } self.isClosed = true self.lightStatusBar = false self.lastTranslation = CGPoint.zero ProgressTimer.createWithDuration(duration, from: 1, inverse: true, callback: { (p) -> Void in self.invalidateRootViewWithPercentage(p) }) } // MARK: - Override override open var preferredStatusBarStyle: UIStatusBarStyle { return self.lightStatusBar ? UIStatusBarStyle.lightContent : self.rootViewController.preferredStatusBarStyle } override open var preferredStatusBarUpdateAnimation: UIStatusBarAnimation { return self.rootViewController.preferredStatusBarUpdateAnimation } override open var prefersStatusBarHidden: Bool { return self.rootViewController.prefersStatusBarHidden } }
mit
6d56d5584da92dc6084415c83087541d
43.641026
153
0.668171
5.212575
false
false
false
false
xivol/Swift-CS333
playgrounds/persistence/notes-archive/notes-archive/MasterViewController.swift
2
4664
// // MasterViewController.swift // notes-archive // // Created by Илья Лошкарёв on 18.03.17. // Copyright © 2017 Илья Лошкарёв. All rights reserved. // import UIKit class MasterViewController: UITableViewController { var detailViewController: DetailViewController? = nil var notes = [Note]() { didSet { // Update reference if let app = UIApplication.shared.delegate as? AppDelegate { app.storage = notes as NSCoding } } } override func viewDidLoad() { super.viewDidLoad() self.navigationItem.leftBarButtonItem = self.editButtonItem let addButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(insertNewObject(_:))) self.navigationItem.rightBarButtonItem = addButton if let split = self.splitViewController { let controllers = split.viewControllers self.detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController } // Unarchive from file if let app = UIApplication.shared.delegate as? AppDelegate { if let storedNotes = app.unarchiveStorage(atPath: nil) as? [Note] { notes = storedNotes // strong reference } app.storage = notes as NSCoding } } override func viewWillAppear(_ animated: Bool) { self.clearsSelectionOnViewWillAppear = self.splitViewController!.isCollapsed super.viewWillAppear(animated) } func insertNewObject(_ sender: Any) { let input = UIAlertController(title: "New Note", message: "", preferredStyle: .alert) input.addTextField { textField in textField.placeholder = "What's up?" } let ok = UIAlertAction(title: "OK", style: .default) { [weak input, weak self] action in if let text = input?.textFields?.first?.text { let note = Note(content: text) self?.notes.insert(note, at: 0) let indexPath = IndexPath(row: 0, section: 0) self?.tableView.insertRows(at: [indexPath], with: .automatic) } else { print("no valid input") } } let cancel = UIAlertAction(title: "Cancel", style: .destructive, handler: nil) input.addAction(cancel) input.addAction(ok) present(input, animated: true) } // MARK: - Segues override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "showDetail" { if let indexPath = self.tableView.indexPathForSelectedRow { let note = notes[indexPath.row] let controller = (segue.destination as! UINavigationController).topViewController as! DetailViewController controller.detailItem = note controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem controller.navigationItem.leftItemsSupplementBackButton = true } } } // MARK: - Table View override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return notes.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) let note = notes[indexPath.row] cell.textLabel!.text = note.content cell.detailTextLabel!.text = Note.dateFormatter.string(from: note.date) cell.backgroundColor = note.color return cell } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { notes.remove(at: indexPath.row) tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view. print("insert") } } }
mit
d2e7ec400d14fa8ebed9a65ee73f7b77
34.412214
144
0.619315
5.350634
false
false
false
false
fellipecaetano/Democracy-iOS
Pods/RandomKit/Sources/RandomKit/Types/RandomGenerator/XorshiftStar.swift
1
4096
// // XorshiftStar.swift // RandomKit // // The MIT License (MIT) // // Copyright (c) 2015-2017 Nikolai Vazquez // // 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. // /// A generator that uses the [Xorshift1024*][1] algorithm. /// /// [1]: http://xoroshiro.di.unimi.it/xorshift1024star.c public struct XorshiftStar: RandomBytesGenerator, Seedable, SeedableFromRandomGenerator { /// The seed type. public typealias Seed = ( UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64 ) private typealias _State = _Array16<UInt64> /// A default global instance seeded with `DeviceRandom.default`. public static var `default` = seeded /// A default global instance that reseeds itself with `DeviceRandom.default`. public static var defaultReseeding = reseeding private var _state: _State private var _index: Int /// Creates an instance from `seed`. public init(seed: Seed) { _state = seed _index = 0 } /// Creates an instance seeded with `randomGenerator`. public init<R: RandomGenerator>(seededWith randomGenerator: inout R) { var seed: Seed = _zero16() func isZero() -> Bool { let contents = _contents(of: &seed) for i in 0 ..< 16 where contents[i] != 0 { return false } return true } repeat { randomGenerator.randomize(value: &seed) } while isZero() self.init(seed: seed) } /// Returns random `Bytes`. public mutating func randomBytes() -> UInt64 { let contents = _contents(of: &_state) let s0 = contents[_index] _index = (_index &+ 1) & 15 var s1 = contents[_index] s1 ^= s1 << 31 contents[_index] = s1 ^ s0 ^ (s1 >> 11) ^ (s0 >> 30) return contents[_index] &* 1181783497276652981 } /// Advances the generator 2^512 calls forward. public mutating func jump() { var jump: _State = ( 0x84242F96ECA9C41D, 0xA3C65B8776F96855, 0x5B34A39F070B5837, 0x4489AFFCE4F31A1E, 0x2FFEEB0A48316F40, 0xDC2D9891FE68C022, 0x3659132BB12FEA70, 0xAAC17D8EFA43CAB8, 0xC4CB815590989B13, 0x5EE975283D71C93B, 0x691548C86C1BD540, 0x7910C41D10A1E6A5, 0x0B5FC64563B3E2A8, 0x047F7684E9FC949D, 0xB99181F2D8F685CA, 0x284600E3F30E38C3 ) var table: _State = _zero16() let statePtr = _contents(of: &_state) let tablePtr = _contents(of: &table) let jumpPtr = _contents(of: &jump) for i in 0 ..< 16 { for b: UInt64 in 0 ..< 64 { if (jumpPtr[i] & 1) << b != 0 { for j in 0 ..< 16 { tablePtr[j] ^= statePtr[(j &+ _index) & 15] } } _ = randomBytes() } } for j in 0 ..< 16 { statePtr[(j &+ _index) & 15] = tablePtr[j] } } }
mit
008fb3cab006b453548856507135e452
35.247788
91
0.61792
3.621574
false
false
false
false
mhmiles/YouTubeInMP3Client
Carthage/Checkouts/Fuzi/FuziDemo/FuziDemo/main.swift
2
2800
// main.swift // Copyright (c) 2015 Ce Zheng // // 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. // This example does exactly the same thing as Ono's example // https://github.com/mattt/Ono/blob/master/Example/main.m // Comparing the two may help migrating your code from Ono import Fuzi let filePath = ((__FILE__ as NSString).stringByDeletingLastPathComponent as NSString).stringByAppendingPathComponent("nutrition.xml") do { let data = NSData(contentsOfFile: filePath)! let document = try XMLDocument(data: data) if let root = document.root { print("Root Element: \(root.tag)") print("\nDaily values:") for element in root.firstChild(tag: "daily-values")?.children ?? [] { let nutrient = element.tag let amount = element.numberValue let unit = element["units"] print("- \(amount!)\(unit!) \(nutrient!)") } print("\n") var xpath = "//food/name" print("XPath Search: \(xpath)") for element in document.xpath(xpath) { print("\(element)") } print("\n") let css = "food > serving[units]" var blockElement:XMLElement? = nil print("CSS Search: \(css)") for (index, element) in document.css(css).enumerate() { if index == 1 { blockElement = element break } } print("Second element: \(blockElement!)\n") xpath = "//food/name" print("XPath Search: \(xpath)") let firstElement = document.firstChild(xpath: xpath)! print("First element: \(firstElement)") } } catch let error as XMLError { switch error { case .NoError: print("wth this should not appear") case .ParserFailure, .InvalidData: print(error) case .LibXMLError(let code, let message): print("libxml error code: \(code), message: \(message)") } }
mit
96cd74a8f3c4f13bd3a78630b07536c8
36.837838
133
0.688929
4.248862
false
false
false
false
luinily/hOme
hOme/Scenes/CreateDevice/CreateDeviceRouter.swift
1
2066
// // CreateDeviceRouter.swift // hOme // // Created by Coldefy Yoann on 2016/05/21. // Copyright (c) 2016年 YoannColdefy. All rights reserved. // // This file was generated by the Clean Swift Xcode Templates so you can apply // clean architecture to your iOS and Mac projects, see http://clean-swift.com // import UIKit protocol CreateDeviceRouterInput { func navigateToSomewhere() } class CreateDeviceRouter: CreateDeviceRouterInput { weak var viewController: CreateDeviceViewController! // MARK: Navigation func navigateToSomewhere() { // NOTE: Teach the router how to navigate to another scene. Some examples follow: // 1. Trigger a storyboard segue // viewController.performSegueWithIdentifier("ShowSomewhereScene", sender: nil) // 2. Present another view controller programmatically // viewController.presentViewController(someWhereViewController, animated: true, completion: nil) // 3. Ask the navigation controller to push another view controller onto the stack // viewController.navigationController?.pushViewController(someWhereViewController, animated: true) // 4. Present a view controller from a different storyboard // let storyboard = UIStoryboard(name: "OtherThanMain", bundle: nil) // let someWhereViewController = storyboard.instantiateInitialViewController() as! SomeWhereViewController // viewController.navigationController?.pushViewController(someWhereViewController, animated: true) } // MARK: Communication func passDataToNextScene(_ segue: UIStoryboardSegue) { // NOTE: Teach the router which scenes it can communicate with if segue.identifier == "ShowSomewhereScene" { passDataToSomewhereScene(segue) } } func passDataToSomewhereScene(_ segue: UIStoryboardSegue) { // NOTE: Teach the router how to pass data to the next scene // let someWhereViewController = segue.destinationViewController as! SomeWhereViewController // someWhereViewController.output.name = viewController.output.name } }
mit
f3c72800bb5f5c4abeddb5d9960f7202
35.210526
110
0.746124
5.389034
false
false
false
false
PureSwift/Bluetooth
Sources/BluetoothHCI/HCIWritePageScanType.swift
1
1517
// // HCIWritePageScanType.swift // Bluetooth // // Created by Carlos Duclos on 8/16/18. // Copyright © 2018 PureSwift. All rights reserved. // import Foundation // MARK: - Method public extension BluetoothHostControllerInterface { /// Write Page Scan Type Command /// /// This command writes the Page Scan Type configuration parameter of the local BR/EDR Controller. func writePageScanType(pageScanType: HCIWritePageScanType.PageScanType, timeout: HCICommandTimeout = .default) async throws { let command = HCIWritePageScanType(pageScanType: pageScanType) return try await deviceRequest(command, timeout: timeout) } } // MARK: - Command /// Write Page Scan Type Command /// /// This command writes the Page Scan Type configuration parameter of the local BR/EDR Controller. @frozen public struct HCIWritePageScanType: HCICommandParameter { public static let command = HostControllerBasebandCommand.writePageScanType public var pageScanType: PageScanType public init(pageScanType: PageScanType) { self.pageScanType = pageScanType } public var data: Data { return Data([pageScanType.rawValue]) } } extension HCIWritePageScanType { public enum PageScanType: UInt8 { /// Mandatory: Standard Scan (default) case mandatory = 0x00 /// Optional: Interlaced Scan case optional = 0x01 } }
mit
b9009789ebd87a9d5d18f947bbf2dd57
24.266667
102
0.663588
4.445748
false
false
false
false
heigong/Shared
iOS/UIBehaviorsDemo/UIBehaviorsDemo/PushBehaviorViewController.swift
1
2251
// // PushBehaviorViewController.swift // UIBehaviorsDemo // // Created by Di Chen on 8/4/15. // Copyright (c) 2015 Di Chen. All rights reserved. // import Foundation import UIKit class PushBehaviorViewController: UIViewController { var squareView: UIView! var animator: UIDynamicAnimator! var pushBehavior: UIPushBehavior! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) createGestureRecognizer() createSmallSquareView() createAnimatorAndBehaviors() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func createSmallSquareView(){ squareView = UIView(frame: CGRectMake(0, 0, 80, 80)) squareView.backgroundColor = UIColor.greenColor() squareView.center = view.center view.addSubview(squareView) } func createGestureRecognizer(){ let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: "handleTap:") view.addGestureRecognizer(tapGestureRecognizer) } func createAnimatorAndBehaviors(){ animator = UIDynamicAnimator(referenceView: view) let collision = UICollisionBehavior(items: [squareView]) collision.translatesReferenceBoundsIntoBoundary = true pushBehavior = UIPushBehavior(items: [squareView], mode: .Continuous) animator.addBehavior(collision) animator.addBehavior(pushBehavior) } func handleTap(tap: UITapGestureRecognizer){ let tapPoint = tap.locationInView(view) let squareViewCenterPoint = self.squareView.center let deltaX = tapPoint.x - squareViewCenterPoint.x let deltaY = tapPoint.y - squareViewCenterPoint.y let angle = atan2(deltaY, deltaX) pushBehavior.angle = angle let distance = sqrt(pow(deltaX, 2.0) + pow(deltaY, 2.0)) pushBehavior.magnitude = distance/200.0 } }
mit
10e1c807d4b2ea193409fc643bb75a4b
28.618421
93
0.653932
5.259346
false
false
false
false
kaizeiyimi/XAutoLayout
XAutoLayout/codes/Anchor.swift
1
5424
// // XAutoLayout // // Created by kaizei on 15/10/11. // Copyright © 2015年 kaizeiyimi. All rights reserved. // import UIKit /** cannot extension NSLayoutAnchor in swift4 with normal func. WTF: "Extension of a generic Objective-C class cannot access the class's generic parameters at runtime". guard the Anchor protocol to be used only in this framework. */ /// just a guard to protect Anchor protocol. public final class __Placeholder__ {} // MARK: - Anchor public protocol Anchor: AnyObject { associatedtype AnchorType: AnyObject func __placeholder__() -> __Placeholder__ } // MARK: - NSLayoutAnchor extension workaround extension Anchor where Self: NSObject { public func c(_ constant: CGFloat) -> Self { let anchor = makeAnchorContainer() anchor.xConstant = constant return anchor } public func p(_ priority: UILayoutPriority) -> Self { let anchor = makeAnchorContainer() anchor.xPriority = priority return anchor } public func p(_ priority: Float) -> Self { let anchor = makeAnchorContainer() anchor.xPriority = UILayoutPriority(priority) return anchor } @available(iOS 11, *) public func useSystemSpace(m: CGFloat) -> Self { let anchor = makeAnchorContainer() (anchor.xMultiplier, anchor.useSystemSpace) = (m, true) return anchor } fileprivate func makeAnchorContainer() -> Self { if let _ = origin { return self } else { let anchor: Self = { switch self { case is NSLayoutXAxisAnchor: return UIView().leadingAnchor as! Self case is NSLayoutYAxisAnchor: return UIView().topAnchor as! Self case is NSLayoutDimension: return UIView().widthAnchor as! Self default: fatalError("maybe new anchor class?") } }() anchor.origin = self anchor.isNumDimension = self.isNumDimension if self.isNumDimension { anchor.xConstant = self.xConstant } return anchor } } } extension NSLayoutDimension { public func m(_ multiplier: CGFloat) -> Self { let anchor = makeAnchorContainer() anchor.xMultiplier = multiplier return anchor } } // NOTICE: iOS9 says '[NSLayoutAnchor init] doesn't work yet.' // so to support iOS9 I have to do so... public func Num<T>(_ number: T) -> NSLayoutDimension where T: Numeric { let anchor = UIView().widthAnchor anchor.isNumDimension = true anchor.xConstant = CGFloat(("\(number)" as NSString).doubleValue) return anchor } // NOTICE: when iOS9 can be dropped, will switch to these impl. //public final class Num: NSLayoutDimension { // #if swift(>=3.2) // public init<T>(_ number: T) where T: Numeric { // super.init() // constant = CGFloat(("\(number)" as NSString).doubleValue) // } // #else // public init<T>(_ number: T) where T: SignedNumber { // super.init() // constant = CGFloat(("\(number)" as NSString).doubleValue) // } // // public init<T>(_ number: T) where T: UnsignedInteger { // super.init() // constant = CGFloat(("\(number)" as NSString).doubleValue) // } // #endif //} extension NSLayoutXAxisAnchor: Anchor { public typealias AnchorType = NSLayoutXAxisAnchor public func __placeholder__() -> __Placeholder__ { return __Placeholder__() } } extension NSLayoutYAxisAnchor: Anchor { public typealias AnchorType = NSLayoutYAxisAnchor public func __placeholder__() -> __Placeholder__ { return __Placeholder__() } } extension NSLayoutDimension: Anchor { public typealias AnchorType = NSLayoutDimension public func __placeholder__() -> __Placeholder__ { return __Placeholder__() } } extension NSObject { private static var dictKey = "XAutoLayout.NSObject.AssociatedDict.Key" var __associatedDict__: [String: Any] { get { if let dict = objc_getAssociatedObject(self, &NSObject.dictKey) as? [String: Any] { return dict } return [:] } set { objc_setAssociatedObject(self, &NSObject.dictKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } var xConstant: CGFloat { get { return __associatedDict__["constant"] as? CGFloat ?? 0 } set { __associatedDict__["constant"] = newValue } } var xMultiplier: CGFloat { get { return __associatedDict__["multiplier"] as? CGFloat ?? 1 } set { __associatedDict__["multiplier"] = newValue } } var xPriority: UILayoutPriority { get { return __associatedDict__["priority"] as? UILayoutPriority ?? .required } set { __associatedDict__["priority"] = newValue } } var useSystemSpace: Bool { get { return __associatedDict__["useSystemSpace"] as? Bool ?? false } set { __associatedDict__["useSystemSpace"] = newValue } } // var origin: Any? { get { return __associatedDict__["origin"] } set { __associatedDict__["origin"] = newValue } } var isNumDimension: Bool { get { return __associatedDict__["isNumDimension"] as? Bool ?? false } set { __associatedDict__["isNumDimension"] = newValue } } }
mit
6238b840d03a8be09eacfaf453f615c3
29.455056
107
0.606161
4.498755
false
false
false
false
Vostro162/VaporTelegram
Sources/App/Message.swift
1
2194
// // Message.swift // VaporTelegramBot // // Created by Marius Hartig on 08.05.17. // // import Foundation public typealias MessageId = Int public typealias InlineMessageId = String // This object represents a message. public struct Message { // Unique message identifier inside this chat public let messageId: MessageId // Date the message public let date: Date // Conversation the message belongs to public let chat: Chat // Optional. For text messages, special entities like usernames, URLs, bot commands, etc. that appear in the text public let entities: [MessageEntity] // Attachments can be are audio, document, game, sticker, video, voice, contact, location, venue or photos public let messageAttachment: MessageAttachment // Optional. Sender, empty for messages sent to channelss public let from: User? // Optional. Use this Object when the message has been forwarded public let forwardMessage: ForwardMessage? // Optional. Automatic Message from Applications/Client public let chatAction: Chat.Action? // Optional. Date the message was last edited public let editDate: Date? // Optional. For text messages public let text: String? // Optional. Caption for the document, photo or video, 0-200 characters public let caption: String? // ToDo //let replyToMessage: Message? //let pinnedMessage: Message? public init(messageId: Int, date: Date, chat: Chat, entities: [MessageEntity] = [MessageEntity](), messageAttachment: MessageAttachment = MessageAttachment(), from: User? = nil, forwardMessage: ForwardMessage? = nil, chatAction: Chat.Action? = nil, editDate: Date? = nil, text: String? = nil, caption: String? = nil) { self.messageId = messageId self.date = date self.chat = chat self.entities = entities self.messageAttachment = messageAttachment self.from = from self.forwardMessage = forwardMessage self.chatAction = chatAction self.editDate = editDate self.text = text self.caption = caption } }
mit
d88fe17dc7c877a9cbea4cb26d7693eb
29.901408
322
0.671376
4.589958
false
false
false
false
ello/ello-ios
Sources/Model/Notification.swift
1
5281
//// /// Notification.swift // let NotificationVersion = 1 @objc(Notification) final class Notification: Model, Authorable { let activity: Activity var author: User? // if postId is present, this notification is opened using "PostDetailViewController" var postId: String? var createdAt: Date { return activity.createdAt } var subject: Model? { willSet { attributedTitleStore = nil } } // notification specific var textRegion: TextRegion? var imageRegion: ImageRegion? private var attributedTitleStore: NSAttributedString? var hasImage: Bool { return self.imageRegion != nil } var canReplyToComment: Bool { switch activity.kind { case .postMentionNotification, .commentNotification, .commentMentionNotification, .commentOnOriginalPostNotification, .commentOnRepostNotification: return true default: return false } } var canBackFollow: Bool { return false // activity.kind == .newFollowerPost } var isValidKind: Bool { return activity.kind != .unknown } init(activity: Activity) { self.activity = activity if let post = activity.subject as? Post { self.author = post.author self.postId = post.id } else if let comment = activity.subject as? ElloComment { self.author = comment.author self.postId = comment.postId } else if let user = activity.subject as? User { self.author = user } else if let submission = activity.subject as? CategoryPost, let featuredBy = submission.featuredBy { self.author = featuredBy } else if let submission = activity.subject as? CategoryUser { switch submission.role { case .featured: self.author = submission.featuredBy case .curator: self.author = submission.curatorBy case .moderator: self.author = submission.moderatorBy case .unspecified: break } } else if let actionable = activity.subject as? PostActionable, let user = actionable.user { self.postId = actionable.postId self.author = user } super.init(version: NotificationVersion) var postSummary: [Regionable]? var postParentSummary: [Regionable]? if let post = activity.subject as? Post { postSummary = post.summary } else if let submission = activity.subject as? CategoryPost, let post = submission.post { postSummary = post.summary } else if let comment = activity.subject as? ElloComment { let content = !comment.summary.isEmpty ? comment.summary : comment.content let parentSummary = comment.parentPost?.summary postSummary = content postParentSummary = parentSummary } else if let post = (activity.subject as? PostActionable)?.post { postSummary = post.summary } if let postSummary = postSummary { assignRegionsFromContent(postSummary, parentSummary: postParentSummary) } subject = activity.subject } required init(coder: NSCoder) { let decoder = Coder(coder) self.activity = decoder.decodeKey("activity") self.author = decoder.decodeOptionalKey("author") super.init(coder: coder) } override func encode(with encoder: NSCoder) { let coder = Coder(encoder) coder.encodeObject(activity, forKey: "activity") coder.encodeObject(author, forKey: "author") super.encode(with: coder.coder) } private func assignRegionsFromContent( _ content: [Regionable], parentSummary: [Regionable]? = nil ) { // assign textRegion and imageRegion from the post content - finds // the first of both kinds of regions var textContent: [String] = [] var parentImage: ImageRegion? var contentImage: ImageRegion? if let parentSummary = parentSummary { for region in parentSummary { if let newTextRegion = region as? TextRegion { textContent.append(newTextRegion.content) } else if let newImageRegion = region as? ImageRegion, parentImage == nil { parentImage = newImageRegion } } } for region in content { if let newTextRegion = region as? TextRegion { textContent.append(newTextRegion.content) } else if let newImageRegion = region as? ImageRegion, contentImage == nil { contentImage = newImageRegion } } imageRegion = contentImage ?? parentImage textRegion = TextRegion(content: textContent.joined(separator: "<br/>")) } } extension Notification: JSONSaveable { var uniqueId: String? { return "Notification-\(activity.id)" } var tableId: String? { return activity.id } }
mit
880b5be725bee37309964b52b37d233c
31.006061
89
0.593638
5.039122
false
false
false
false
tcamin/CustomCoreImageFilteringDemo
CustomCoreImageFilteringDemo/ViewController.swift
1
2478
// // ViewController.swift // CustomCoreImageFilteringDemo // // Created by Xcode on 12/10/15. // Copyright © 2015 Tomas Camin. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var resultImageView: UIImageView! @IBOutlet weak var benchResult: UILabel! var sourceImage: UIImage! = nil override func viewDidLoad() { super.viewDidLoad() OneColorFocusCoreImageFilter.preload() } private func prepareSourceImage() { sourceImage = UIImage(named: "tstimage-large.jpg")! } @IBAction func runCPUTapped(sender: AnyObject) { prepareSourceImage() var elapsedTime = CFAbsoluteTimeGetCurrent() let filter = OneColorFocusCPUFilter(image: sourceImage, focusColorRed: 10, focusColorGreen: 10, focusColorBlue: 10) let filteredImage = filter.createOneColorFocusImage()! self.resultImageView.image = filteredImage elapsedTime = (CFAbsoluteTimeGetCurrent() - elapsedTime) * 1000.0 self.benchResult.text = String(format: "CPU: %.3fms", elapsedTime) print(self.benchResult.text!) } @IBAction func runCoreImageTapped(sender: AnyObject) { prepareSourceImage() var elapsedTime = CFAbsoluteTimeGetCurrent() let filter = OneColorFocusCoreImageFilter(image: sourceImage, focusColorRed: 10, focusColorGreen: 10, focusColorBlue: 10) let filteredImage = filter.outputUIImage() self.resultImageView.image = filteredImage elapsedTime = (CFAbsoluteTimeGetCurrent() - elapsedTime) * 1000.0 self.benchResult.text = String(format: "CoreImage: %.3fms", elapsedTime) print(self.benchResult.text!) } @IBAction func runNeonTapped(sender: AnyObject) { prepareSourceImage() var elapsedTime = CFAbsoluteTimeGetCurrent() let filter = OneColorFocusNeonFilter(image: sourceImage, focusColorRed: 10, focusColorGreen: 10, focusColorBlue: 10) let filteredImage = filter.createOneColorFocusImage() self.resultImageView.image = filteredImage elapsedTime = (CFAbsoluteTimeGetCurrent() - elapsedTime) * 1000.0 self.benchResult.text = String(format: "Neon: %.3fms", elapsedTime) print(self.benchResult.text!) } }
mit
96c3b71a3376613a56b7cd82dcb7b95c
30.75641
129
0.644328
4.875984
false
false
false
false
dfuerle/kuroo
kuroo/EmptyStateViewController.swift
1
764
// // EmptyStateViewController.swift // kuroo // // Copyright © 2016 Dmitri Fuerle. All rights reserved. // import UIKit class EmptyStateViewController: UIViewController, SupportsContext { @IBOutlet weak var boxView: UIView! @IBOutlet weak var messageLabel: UILabel! var context: Context! var message: String? { didSet { if let message = message { messageLabel.text = message } } } // MARK: - Overrides override func viewDidLoad() { super.viewDidLoad() debugPrint("viewDidLoad \(self)") if let message = message { messageLabel.text = message } boxView.backgroundColor = context.kuLightGreen } }
gpl-2.0
7731d8073bb009987ca400e9249a30e8
22.121212
67
0.589777
4.922581
false
false
false
false
macemmi/HBCI4Swift
HBCI4Swift/HBCI4Swift/Source/Orders/HBCICamtStatementsOrder.swift
1
6107
// // HBCICamtStatementsOrder.swift // HBCI4Swift // // Created by Frank Emminghaus on 01.07.20. // Copyright © 2020 Frank Emminghaus. All rights reserved. // import Foundation open class HBCICamtStatementsOrder: HBCIOrder { public let account:HBCIAccount; open var statements:Array<HBCIStatement> open var dateFrom:Date? open var dateTo:Date? var offset:String? var camtFormat:String? var bookedPart:Data? var isPartial = false; var partNumber = 1; public init?(message: HBCICustomMessage, account:HBCIAccount) { self.account = account; self.statements = Array<HBCIStatement>(); super.init(name: "CamtStatements", message: message); if self.segment == nil { return nil; } } open func enqueue() ->Bool { // check if order is supported if !user.parameters.isOrderSupportedForAccount(self, number: account.number, subNumber: account.subNumber) { logInfo(self.name + " is not supported for account " + account.number); return false; } var values = Dictionary<String,Any>(); // check if SEPA version is supported (only globally for bank - // later we check if account supports this as well if account.iban == nil || account.bic == nil { logInfo("Account has no IBAN or BIC information"); return false; } values = ["KTV.bic":account.bic!, "KTV.iban":account.iban!, "KTV.number":account.number, "KTV.KIK.country":"280", "KTV.KIK.blz":account.bankCode, "allaccounts":false]; if var date = dateFrom { if let maxdays = user.parameters.maxStatementDays() { let currentDate = Date(); let minDate = currentDate.addingTimeInterval((Double)((maxdays-1) * 24 * 3600 * -1)); if minDate > date { date = minDate; } } values["startdate"] = date; } if let date = dateTo { values["enddate"] = date; } if let ofs = offset { values["offset"] = ofs; } let formats = user.parameters.camtFormats(); guard formats.count > 0 else { logInfo("No supported camt formats"); return false; } for format in formats { if format.hasSuffix("052.001.02") || format.hasSuffix("052.001.08") { camtFormat = format; //break; } else { logDebug("Camt format "+format+" is not supported"); } } guard let format = camtFormat else { logInfo("No supported Camt formats found"); return false; } values["format"] = format; if !segment.setElementValues(values) { logInfo("CamtStatements Order values could not be set"); return false; } // add to message return msg.addOrder(self); } func getOutstandingPart(_ offset:String) ->Data? { do { if let msg = HBCICustomMessage.newInstance(msg.dialog) { if let order = HBCICamtStatementsOrder(message: msg, account: self.account) { order.dateFrom = self.dateFrom; order.dateTo = self.dateTo; order.offset = offset; order.isPartial = true; order.partNumber = self.partNumber + 1; if !order.enqueue() { return nil; } _ = try msg.send(); return order.bookedPart; } } } catch { // we don't do anything in case of errors } return nil; } override open func updateResult(_ result: HBCIResultMessage) { var parser:HBCICamtParser! super.updateResult(result); // check whether result is incomplete self.offset = nil; for response in result.segmentResponses { if response.code == "3040" && response.parameters.count > 0 { self.offset = response.parameters[0]; } } if camtFormat!.hasSuffix("052.001.02") { parser = HBCICamtParser_052_001_02(); } else { parser = HBCICamtParser_052_001_08(); } // now parse statements self.statements.removeAll(); for seg in resultSegments { if let booked_list = seg.elementValuesForPath("booked.statement") as? [Data] { for var booked in booked_list { // check whether result is incomplete if let offset = self.offset { if partNumber >= 100 { // we stop here - too many statement parts logInfo("Too many statement parts but we still get response 3040 - we stop here") } else { if let part2 = getOutstandingPart(offset) { booked.append(part2); } } } // check if we are a part or the original order if isPartial { self.bookedPart = booked; } else { if let statements = parser.parse(account, data: booked, isPreliminary: false) { self.statements.append(contentsOf: statements); } } } } if let notbooked = seg.elementValueForPath("notbooked") as? Data { if let statements = parser.parse(account, data: notbooked, isPreliminary: true) { self.statements.append(contentsOf: statements); } } } } }
gpl-2.0
f27f04e4efe19877a5ee815b07208e7d
33.891429
175
0.504586
4.811663
false
false
false
false
sdhjl2000/swiftdialog
SwiftDialogExample/AppDelegate.swift
1
3777
// // AppDelegate.swift // OAuthSwift // // Created by Dongri Jin on 6/21/14. // Copyright (c) 2014 Dongri Jin. All rights reserved. // import UIKit import OAuthSwift @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UIWebViewDelegate { var window: UIWindow? var clienttoken:String? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool { // Override point for customization after application launch. self.window = UIWindow(frame: UIScreen.mainScreen().bounds) let viewController: ViewController = ViewController() let naviController: UINavigationController = UINavigationController(rootViewController: viewController) self.window!.rootViewController = naviController self.window!.makeKeyAndVisible() 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:. } func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject?) -> Bool { println(url) if (url.host == "oauth-callback") { if (url.path!.hasPrefix("/twitter") || url.path!.hasPrefix("/flickr") || url.path!.hasPrefix("/fitbit") || url.path!.hasPrefix("/withings") || url.path!.hasPrefix("/linkedin") || url.path!.hasPrefix("/bitbucket") || url.path!.hasPrefix("/smugmug") || url.path!.hasPrefix("/intuit") || url.path!.hasPrefix("/zaim") || url.path!.hasPrefix("/tumblr")) { OAuth1Swift.handleOpenURL(url) } if ( url.path!.hasPrefix("/github" ) || url.path!.hasPrefix("/instagram" ) || url.path!.hasPrefix("/foursquare") || url.path!.hasPrefix("/dropbox") || url.path!.hasPrefix("/dribbble") || url.path!.hasPrefix("/salesforce") || url.path!.hasPrefix("/google") || url.path!.hasPrefix("/linkedin2")) { OAuth2Swift.handleOpenURL(url) } } else { // Google provider is the only one wuth your.bundle.id url schema. OAuth2Swift.handleOpenURL(url) } return true } }
apache-2.0
b31a96984e1a834ed6829396c77b238f
52.197183
307
0.694731
5.152797
false
false
false
false
mobilabsolutions/jenkins-ios
JenkinsiOS/Service/AppearanceManager.swift
1
2020
// // AppearanceManager.swift // JenkinsiOS // // Created by Robert on 15.12.16. // Copyright © 2016 MobiLab Solutions. All rights reserved. // import UIKit class AppearanceManager { func setGlobalAppearance() { manageFonts() } private func manageFonts() { let fontName = Constants.UI.defaultLabelFont UILabel.appearance().updateFontName(to: fontName) var navigationTitleAttributes = getTitleTextAttributes(font: fontName, qualifier: .bold, size: 20) navigationTitleAttributes[.foregroundColor] = Constants.UI.greyBlue UINavigationBar.appearance().titleTextAttributes = navigationTitleAttributes UIBarButtonItem.appearance().setTitleTextAttributes(getTitleTextAttributes(font: fontName, qualifier: .regular, size: 20), for: .normal) UINavigationBar.appearance().backgroundColor = Constants.UI.paleGreyColor // Remove shadow below UINavigationBar UINavigationBar.appearance().shadowImage = UIImage() } private func getTitleTextAttributes(font: String, qualifier: UIFont.FontTypeQualifier, size: CGFloat) -> [NSAttributedString.Key: Any] { return [ NSAttributedString.Key.font: UIFont.font(name: font, qualifier: qualifier, size: size) as Any, ] } } extension UIFont { static func defaultFont(ofSize size: CGFloat) -> UIFont { return UIFont.font(name: Constants.UI.defaultLabelFont, qualifier: .regular, size: size) ?? UIFont.systemFont(ofSize: size) } static func boldDefaultFont(ofSize size: CGFloat) -> UIFont { return UIFont.font(name: Constants.UI.defaultLabelFont, qualifier: .bold, size: size) ?? UIFont.boldSystemFont(ofSize: size) } fileprivate enum FontTypeQualifier: String { case regular = "Regular" case bold = "Bold" } fileprivate static func font(name: String, qualifier: FontTypeQualifier, size: CGFloat) -> UIFont? { return UIFont(name: "\(name)-\(qualifier.rawValue)", size: size) } }
mit
464cd76f10f4918cca78bc3de0b0c6ea
36.388889
144
0.699356
4.662818
false
false
false
false
SmallElephant/FESwiftDemo
9-SaveData/9-SaveData/Order.swift
1
830
// // Order.swift // 9-SaveData // // Created by FlyElephant on 17/3/23. // Copyright © 2017年 FlyElephant. All rights reserved. // import Foundation class Order:NSObject,NSCoding { var orderName:String = "" var userName:String = "" init(orderName:String, userName:String) { self.orderName = orderName self.userName = userName super.init() } required init?(coder aDecoder: NSCoder) { super.init() self.orderName = aDecoder.decodeObject(forKey: "OrderName") as! String self.userName = aDecoder.decodeObject(forKey: "UserName") as! String } func encode(with aCoder: NSCoder) { aCoder.encode(self.orderName, forKey:"OrderName") aCoder.encode(self.userName, forKey: "UserName") } }
mit
d450743964dc81302ca08f413edab6cd
21.972222
78
0.610641
4.053922
false
false
false
false
jakub-tucek/fit-checker-2.0
fit-checker/networking/operations/ReadCourseClassificationOperation.swift
1
2029
// // ReadCourseClassificationOperation.swift // fit-checker // // Created by Josef Dolezal on 13/01/2017. // Copyright © 2017 Josef Dolezal. All rights reserved. // import Foundation import Alamofire /// Downloads HTML page for course classification. class ReadCourseClassificationOperation: BaseOperation, ResponseType { /// Edux course id private let courseId: String /// Student username private let student: String /// Database context manager private let contextManager: ContextManager init(courseId: String, student: String, sessionManager: SessionManager, contextManager: ContextManager) { self.courseId = courseId self.student = student self.contextManager = contextManager super.init(sessionManager: sessionManager) } override func start() { _ = sessionManager.request(EduxRouter.courseClassification( courseId: courseId, student: student)) .validate() .validate(EduxValidators.authorizedHTML) .responseString(completionHandler: handle) } /// Classification request success callback /// /// - Parameter result: Downloaded HTML func success(result: String) { let parser = ClassificationParser() let tables = parser.parse(html: result).tables.map { table -> CourseTable in let classification = table.rows.map({ row in return ClassificationRecord(name: row.name, score: row.value) }) return CourseTable(name: table.name, courseId: courseId, classification: classification) } do { let realm = try contextManager.createContext() let oldTables = realm.objects(CourseTable.self) .filter("courseId = %@", courseId) try realm.write { realm.delete(oldTables) realm.add(tables) } } catch { self.error = error } } }
mit
3df2139baa607d83f882e89046c90122
27.971429
84
0.621795
5.121212
false
false
false
false
Liuyingao/SwiftRepository
Subscripts.swift
1
1449
//Int型的subscript struct TimesTable{ let multiplier: Int subscript(index: Int) -> Int { get { return multiplier * index } } } var a = TimesTable(multiplier : 5) print(a[3]) print("-----------------------------------------") //String型的subscript struct StringArray{ var index : Int var arrayList : [String] init(index : Int){ self.arrayList = Array(count : index, repeatedValue : "") self.index = self.arrayList.count } func indexIsValidForArray(index : Int) -> Bool { return index < self.index && index >= 0 } subscript(index : Int) -> String { get { assert(indexIsValidForArray(index), "Index out of range") return arrayList[index] } set { assert(indexIsValidForArray(index), "Index out of range") self.arrayList[index] = newValue } } } var b = StringArray(index: 5) var count = 0 for i in 0..<b.index{ b[i] = String(++count) } print(b[4]) print("-----------------------------------------") //Any struct ObjectArray<T>{ var arrayList : Array<T> = Array<T>() mutating func append(item : T){ arrayList.append(item) } mutating func remove(index : Int){ arrayList.removeAtIndex(index) } subscript(index : Int) -> T { get { return arrayList[index] } set { arrayList[index] = newValue } } } var c = ObjectArray<String>() c.append("123") c.append("456") c.append("789") print(c[0]) print(c[1]) print(c[2]) c.remove(1) print(c.arrayList) c[1] = "ERRR" print(c.arrayList)
gpl-2.0
34744fae2e246436da122925407e1f40
17.240506
60
0.616933
2.934827
false
false
false
false
lugearma/LAMenuBar
LAMenuBar/Classes/LAMenuView.swift
1
3443
// // LAMenuView.swift // LAMenuBar // // Created by Luis Arias on 8/8/17. // import UIKit // MARK: - MenuBarPosition public enum MenuBarPosition { case top case bottom } // MARK: - LAMenuViewDelegate @available(iOS 9.0, *) public protocol LAMenuViewDelegate: class { func menuView(_ view: LAMenuView, didScrollWithIndex index: IndexPath) func menuView(_ view: LAMenuView, didSelectMenuItemAtIndex index: IndexPath) } // MARK: - LAMenuView @available(iOS 9.0, *) public class LAMenuView: UIView { public weak var delegate: LAMenuViewDelegate? private var model: LAMenuModel var stackSubviews: (UIView, UIView) { switch model.menuBarPosition { case .top: return (menuBar, menuContentContainer) case .bottom: return (menuContentContainer, menuBar) } } fileprivate lazy var containerStackView: UIStackView = { let stackView = UIStackView() stackView.axis = .vertical stackView.translatesAutoresizingMaskIntoConstraints = false stackView.addArrangedSubviews(self.stackSubviews.0, self.stackSubviews.1) return stackView }() fileprivate lazy var menuBar: LAMenuBar = { let frame = CGRect(x: 0, y: 0, width: self.frame.width, height: 50) let menuBar = LAMenuBar(frame: frame, model: self.model) menuBar.translatesAutoresizingMaskIntoConstraints = false menuBar.heightAnchor.constraint(equalToConstant: 50).isActive = true menuBar.delegate = self return menuBar }() fileprivate lazy var menuContentContainer: LAMenuContentContainer = { let frame = CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height) let menuContentContainer = LAMenuContentContainer(frame: frame, model: self.model) menuContentContainer.contentContainerDelegate = self return menuContentContainer }() public init(frame: CGRect, model: LAMenuModel) { self.model = model super.init(frame: frame) setupViews() } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupViews() { addSubview(containerStackView) containerStackView.topAnchor.constraint(equalTo: topAnchor).isActive = true containerStackView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true containerStackView.leftAnchor.constraint(equalTo: leftAnchor).isActive = true containerStackView.rightAnchor.constraint(equalTo: rightAnchor).isActive = true } } // MARK: - LAMenuContentContainerDelegate @available(iOS 9.0, *) extension LAMenuView: LAMenuContentContainerDelegate { func didScroll(scrollView: UIScrollView) { menuBar.updateWhenScrollView(scrollView) } func didEndScrollWithIndex(index: IndexPath) { menuBar.updateWhenFinishScrollAtIndex(index) delegate?.menuView(self, didScrollWithIndex: index) } func didAddViewController(viewController: UIViewController) { guard let parentViewController = delegate as? UIViewController else { preconditionFailure() } parentViewController.addChildViewController(viewController) viewController.didMove(toParentViewController: parentViewController) } } // MARK: - LAMenuBarDelegate @available(iOS 9.0, *) extension LAMenuView: LAMenuBarDelegate { func didSelectItemAt(indexPath: IndexPath) { menuContentContainer.updateWhenSelectItemAtIndex(indexPath) delegate?.menuView(self, didSelectMenuItemAtIndex: indexPath) } }
mit
0b464176f0b102b38dd7e5234b1fc00c
28.42735
86
0.743828
4.572377
false
false
false
false
hhcszgd/cszgdCode
weibo1/Pods/SnapKit/Source/Constraint.swift
26
20959
// // SnapKit // // Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if os(iOS) || os(tvOS) import UIKit #else import AppKit #endif /** Used to expose API's for a Constraint */ public class Constraint { public func install() -> [LayoutConstraint] { fatalError("Must be implemented by Concrete subclass.") } public func uninstall() -> Void { fatalError("Must be implemented by Concrete subclass.") } public func activate() -> Void { fatalError("Must be implemented by Concrete subclass.") } public func deactivate() -> Void { fatalError("Must be implemented by Concrete subclass.") } public func updateOffset(amount: Float) -> Void { fatalError("Must be implemented by Concrete subclass.") } public func updateOffset(amount: Double) -> Void { fatalError("Must be implemented by Concrete subclass.") } public func updateOffset(amount: CGFloat) -> Void { fatalError("Must be implemented by Concrete subclass.") } public func updateOffset(amount: Int) -> Void { fatalError("Must be implemented by Concrete subclass.") } public func updateOffset(amount: UInt) -> Void { fatalError("Must be implemented by Concrete subclass.") } public func updateOffset(amount: CGPoint) -> Void { fatalError("Must be implemented by Concrete subclass.") } public func updateOffset(amount: CGSize) -> Void { fatalError("Must be implemented by Concrete subclass.") } public func updateOffset(amount: EdgeInsets) -> Void { fatalError("Must be implemented by Concrete subclass.") } public func updateInsets(amount: EdgeInsets) -> Void { fatalError("Must be implemented by Concrete subclass.") } public func updatePriority(priority: Float) -> Void { fatalError("Must be implemented by Concrete subclass.") } public func updatePriority(priority: Double) -> Void { fatalError("Must be implemented by Concrete subclass.") } public func updatePriority(priority: CGFloat) -> Void { fatalError("Must be implemented by Concrete subclass.") } public func updatePriority(priority: UInt) -> Void { fatalError("Must be implemented by Concrete subclass.") } public func updatePriority(priority: Int) -> Void { fatalError("Must be implemented by Concrete subclass.") } public func updatePriorityRequired() -> Void { fatalError("Must be implemented by Concrete subclass.") } public func updatePriorityHigh() -> Void { fatalError("Must be implemented by Concrete subclass.") } public func updatePriorityMedium() -> Void { fatalError("Must be implemented by Concrete subclass.") } public func updatePriorityLow() -> Void { fatalError("Must be implemented by Concrete subclass.") } internal var makerFile: String = "Unknown" internal var makerLine: UInt = 0 } /** Used internally to implement a ConcreteConstraint */ internal class ConcreteConstraint: Constraint { internal override func updateOffset(amount: Float) -> Void { self.constant = amount } internal override func updateOffset(amount: Double) -> Void { self.updateOffset(Float(amount)) } internal override func updateOffset(amount: CGFloat) -> Void { self.updateOffset(Float(amount)) } internal override func updateOffset(amount: Int) -> Void { self.updateOffset(Float(amount)) } internal override func updateOffset(amount: UInt) -> Void { self.updateOffset(Float(amount)) } internal override func updateOffset(amount: CGPoint) -> Void { self.constant = amount } internal override func updateOffset(amount: CGSize) -> Void { self.constant = amount } internal override func updateOffset(amount: EdgeInsets) -> Void { self.constant = amount } internal override func updateInsets(amount: EdgeInsets) -> Void { self.constant = EdgeInsets(top: amount.top, left: amount.left, bottom: -amount.bottom, right: -amount.right) } internal override func updatePriority(priority: Float) -> Void { self.priority = priority } internal override func updatePriority(priority: Double) -> Void { self.updatePriority(Float(priority)) } internal override func updatePriority(priority: CGFloat) -> Void { self.updatePriority(Float(priority)) } internal override func updatePriority(priority: UInt) -> Void { self.updatePriority(Float(priority)) } internal override func updatePriority(priority: Int) -> Void { self.updatePriority(Float(priority)) } internal override func updatePriorityRequired() -> Void { self.updatePriority(Float(1000.0)) } internal override func updatePriorityHigh() -> Void { self.updatePriority(Float(750.0)) } internal override func updatePriorityMedium() -> Void { #if os(iOS) || os(tvOS) self.updatePriority(Float(500.0)) #else self.updatePriority(Float(501.0)) #endif } internal override func updatePriorityLow() -> Void { self.updatePriority(Float(250.0)) } internal override func install() -> [LayoutConstraint] { return self.installOnView(updateExisting: false, file: self.makerFile, line: self.makerLine) } internal override func uninstall() -> Void { self.uninstallFromView() } internal override func activate() -> Void { guard self.installInfo != nil else { self.install() return } #if SNAPKIT_DEPLOYMENT_LEGACY guard #available(iOS 8.0, OSX 10.10, *) else { self.install() return } #endif let layoutConstraints = self.installInfo!.layoutConstraints.allObjects as! [LayoutConstraint] if layoutConstraints.count > 0 { NSLayoutConstraint.activateConstraints(layoutConstraints) } } internal override func deactivate() -> Void { guard self.installInfo != nil else { return } #if SNAPKIT_DEPLOYMENT_LEGACY guard #available(iOS 8.0, OSX 10.10, *) else { return } #endif let layoutConstraints = self.installInfo!.layoutConstraints.allObjects as! [LayoutConstraint] if layoutConstraints.count > 0 { NSLayoutConstraint.deactivateConstraints(layoutConstraints) } } private let fromItem: ConstraintItem private let toItem: ConstraintItem private let relation: ConstraintRelation private let multiplier: Float private var constant: Any { didSet { if let installInfo = self.installInfo { for layoutConstraint in installInfo.layoutConstraints.allObjects as! [LayoutConstraint] { let attribute = (layoutConstraint.secondAttribute == .NotAnAttribute) ? layoutConstraint.firstAttribute : layoutConstraint.secondAttribute layoutConstraint.constant = attribute.snp_constantForValue(self.constant) } } } } private var priority: Float { didSet { if let installInfo = self.installInfo { for layoutConstraint in installInfo.layoutConstraints.allObjects as! [LayoutConstraint] { layoutConstraint.priority = self.priority } } } } private var installInfo: ConcreteConstraintInstallInfo? = nil internal init(fromItem: ConstraintItem, toItem: ConstraintItem, relation: ConstraintRelation, constant: Any, multiplier: Float, priority: Float) { self.fromItem = fromItem self.toItem = toItem self.relation = relation self.constant = constant self.multiplier = multiplier self.priority = priority } internal func installOnView(updateExisting updateExisting: Bool = false, file: String? = nil, line: UInt? = nil) -> [LayoutConstraint] { var installOnView: View? = nil if self.toItem.view != nil { installOnView = closestCommonSuperviewFromView(self.fromItem.view, toView: self.toItem.view) if installOnView == nil { NSException(name: "Cannot Install Constraint", reason: "No common superview between views (@\(self.makerFile)#\(self.makerLine))", userInfo: nil).raise() return [] } } else { if self.fromItem.attributes.isSubsetOf(ConstraintAttributes.Width.union(.Height)) { installOnView = self.fromItem.view } else { installOnView = self.fromItem.view?.superview if installOnView == nil { NSException(name: "Cannot Install Constraint", reason: "Missing superview (@\(self.makerFile)#\(self.makerLine))", userInfo: nil).raise() return [] } } } if let installedOnView = self.installInfo?.view { if installedOnView != installOnView { NSException(name: "Cannot Install Constraint", reason: "Already installed on different view. (@\(self.makerFile)#\(self.makerLine))", userInfo: nil).raise() return [] } return self.installInfo?.layoutConstraints.allObjects as? [LayoutConstraint] ?? [] } var newLayoutConstraints = [LayoutConstraint]() let layoutFromAttributes = self.fromItem.attributes.layoutAttributes let layoutToAttributes = self.toItem.attributes.layoutAttributes // get layout from let layoutFrom: View? = self.fromItem.view // get layout relation let layoutRelation: NSLayoutRelation = self.relation.layoutRelation for layoutFromAttribute in layoutFromAttributes { // get layout to attribute let layoutToAttribute = (layoutToAttributes.count > 0) ? layoutToAttributes[0] : layoutFromAttribute // get layout constant let layoutConstant: CGFloat = layoutToAttribute.snp_constantForValue(self.constant) // get layout to #if os(iOS) || os(tvOS) var layoutTo: AnyObject? = self.toItem.view ?? self.toItem.layoutSupport #else var layoutTo: AnyObject? = self.toItem.view #endif if layoutTo == nil && layoutToAttribute != .Width && layoutToAttribute != .Height { layoutTo = installOnView } // create layout constraint let layoutConstraint = LayoutConstraint( item: layoutFrom!, attribute: layoutFromAttribute, relatedBy: layoutRelation, toItem: layoutTo, attribute: layoutToAttribute, multiplier: CGFloat(self.multiplier), constant: layoutConstant) // set priority layoutConstraint.priority = self.priority // set constraint layoutConstraint.snp_constraint = self newLayoutConstraints.append(layoutConstraint) } // special logic for updating if updateExisting { // get existing constraints for this view let existingLayoutConstraints = layoutFrom!.snp_installedLayoutConstraints.reverse() // array that will contain only new layout constraints to keep var newLayoutConstraintsToKeep = [LayoutConstraint]() // begin looping for layoutConstraint in newLayoutConstraints { // layout constraint that should be updated var updateLayoutConstraint: LayoutConstraint? = nil // loop through existing and check for match for existingLayoutConstraint in existingLayoutConstraints { if existingLayoutConstraint == layoutConstraint { updateLayoutConstraint = existingLayoutConstraint break } } // if we have existing one lets just update the constant if updateLayoutConstraint != nil { updateLayoutConstraint!.constant = layoutConstraint.constant } // otherwise add this layout constraint to new keep list else { newLayoutConstraintsToKeep.append(layoutConstraint) } } // set constraints to only new ones newLayoutConstraints = newLayoutConstraintsToKeep } // add constraints #if SNAPKIT_DEPLOYMENT_LEGACY && !os(OSX) if #available(iOS 8.0, *) { NSLayoutConstraint.activateConstraints(newLayoutConstraints) } else { installOnView!.addConstraints(newLayoutConstraints) } #else NSLayoutConstraint.activateConstraints(newLayoutConstraints) #endif // set install info self.installInfo = ConcreteConstraintInstallInfo(view: installOnView, layoutConstraints: NSHashTable.weakObjectsHashTable()) // store which layout constraints are installed for this constraint for layoutConstraint in newLayoutConstraints { self.installInfo!.layoutConstraints.addObject(layoutConstraint) } // store the layout constraints against the layout from view layoutFrom!.snp_installedLayoutConstraints += newLayoutConstraints // return the new constraints return newLayoutConstraints } internal func uninstallFromView() { if let installInfo = self.installInfo, let installedLayoutConstraints = installInfo.layoutConstraints.allObjects as? [LayoutConstraint] { if installedLayoutConstraints.count > 0 { // remove the constraints from the UIView's storage #if SNAPKIT_DEPLOYMENT_LEGACY && !os(OSX) if #available(iOS 8.0, *) { NSLayoutConstraint.deactivateConstraints(installedLayoutConstraints) } else if let installedOnView = installInfo.view { installedOnView.removeConstraints(installedLayoutConstraints) } #else NSLayoutConstraint.deactivateConstraints(installedLayoutConstraints) #endif // remove the constraints from the from item view if let fromView = self.fromItem.view { fromView.snp_installedLayoutConstraints = fromView.snp_installedLayoutConstraints.filter { return !installedLayoutConstraints.contains($0) } } } } self.installInfo = nil } } private struct ConcreteConstraintInstallInfo { weak var view: View? = nil let layoutConstraints: NSHashTable } private extension NSLayoutAttribute { private func snp_constantForValue(value: Any?) -> CGFloat { // Float if let float = value as? Float { return CGFloat(float) } // Double else if let double = value as? Double { return CGFloat(double) } // UInt else if let int = value as? Int { return CGFloat(int) } // Int else if let uint = value as? UInt { return CGFloat(uint) } // CGFloat else if let float = value as? CGFloat { return float } // CGSize else if let size = value as? CGSize { if self == .Width { return size.width } else if self == .Height { return size.height } } // CGPoint else if let point = value as? CGPoint { #if os(iOS) || os(tvOS) switch self { case .Left, .CenterX, .LeftMargin, .CenterXWithinMargins: return point.x case .Top, .CenterY, .TopMargin, .CenterYWithinMargins, .Baseline, .FirstBaseline: return point.y case .Right, .RightMargin: return point.x case .Bottom, .BottomMargin: return point.y case .Leading, .LeadingMargin: return point.x case .Trailing, .TrailingMargin: return point.x case .Width, .Height, .NotAnAttribute: return CGFloat(0) } #else switch self { case .Left, .CenterX: return point.x case .Top, .CenterY, .Baseline: return point.y case .Right: return point.x case .Bottom: return point.y case .Leading: return point.x case .Trailing: return point.x case .Width, .Height, .NotAnAttribute: return CGFloat(0) case .FirstBaseline: return point.y } #endif } // EdgeInsets else if let insets = value as? EdgeInsets { #if os(iOS) || os(tvOS) switch self { case .Left, .CenterX, .LeftMargin, .CenterXWithinMargins: return insets.left case .Top, .CenterY, .TopMargin, .CenterYWithinMargins, .Baseline, .FirstBaseline: return insets.top case .Right, .RightMargin: return insets.right case .Bottom, .BottomMargin: return insets.bottom case .Leading, .LeadingMargin: return (Config.interfaceLayoutDirection == .LeftToRight) ? insets.left : -insets.right case .Trailing, .TrailingMargin: return (Config.interfaceLayoutDirection == .LeftToRight) ? insets.right : -insets.left case .Width, .Height, .NotAnAttribute: return CGFloat(0) } #else switch self { case .Left, .CenterX: return insets.left case .Top, .CenterY, .Baseline: return insets.top case .Right: return insets.right case .Bottom: return insets.bottom case .Leading: return (Config.interfaceLayoutDirection == .LeftToRight) ? insets.left : -insets.right case .Trailing: return (Config.interfaceLayoutDirection == .LeftToRight) ? insets.right : -insets.left case .Width, .Height, .NotAnAttribute: return CGFloat(0) case .FirstBaseline: return insets.bottom } #endif } return CGFloat(0); } } private func closestCommonSuperviewFromView(fromView: View?, toView: View?) -> View? { var views = Set<View>() var fromView = fromView var toView = toView repeat { if let view = toView { if views.contains(view) { return view } views.insert(view) toView = view.superview } if let view = fromView { if views.contains(view) { return view } views.insert(view) fromView = view.superview } } while (fromView != nil || toView != nil) return nil } private func ==(left: ConcreteConstraint, right: ConcreteConstraint) -> Bool { return (left.fromItem == right.fromItem && left.toItem == right.toItem && left.relation == right.relation && left.multiplier == right.multiplier && left.priority == right.priority) }
apache-2.0
938f2504d881c289806db5510a8ef7b1
41.256048
172
0.606565
5.40459
false
false
false
false
alirsamar/BiOS
RobotMaze2/Maze/WallLocations.swift
1
1954
// // WallLocations.swift // Maze // // Created by Gabrielle Miller-Messner on 12/1/15. // Copyright © 2015 Udacity, Inc. All rights reserved. // import Foundation extension ControlCenter { func isFacingWall(robot: ComplexRobotObject, direction: MazeDirection) -> Bool { let cell = mazeController.currentCell(robot) var isWall: Bool = false switch(direction) { case .Up: isWall = cell.top case .Down: isWall = cell.bottom case .Left: isWall = cell.left case .Right: isWall = cell.right } return isWall } func checkWalls(robot:ComplexRobotObject) -> (up: Bool, right: Bool, down: Bool, left: Bool, numberOfWalls: Int) { var numberOfWalls = 0 let cell = mazeController.currentCell(robot) // Check is there is a wall at the top of the current cell let isWallUp = cell.top if isWallUp { numberOfWalls += 1 } // Check if there is a wall to the right of the current cell let isWallRight = cell.right if isWallRight { numberOfWalls += 1 } // Step 2.1a // TODO: Check if there is a wall at the bottom of the current cell let isWallLeft = cell.left if isWallLeft { numberOfWalls += 1 } // TODO: Check if there is a wall to the left of the current cell let isWallBottom = cell.bottom if isWallBottom { numberOfWalls += 1 } // Step 2.1b // TODO: Test the checkWalls function. // TODO: Return a tuple representing the bools for top, right, down & left, and the number of walls // This tuple is a placeholder return (isWallUp, isWallRight, isWallBottom, isWallLeft, numberOfWalls) } }
mit
af431fd122972adcb937f0f56c3c1c2d
27.318841
118
0.558116
4.311258
false
false
false
false
gbuela/kanjiryokucha
KanjiRyokucha/LoginRequest.swift
1
897
// // LoginRequest.swift // KanjiRyokucha // // Created by German Buela on 12/3/16. // Copyright © 2016 German Buela. All rights reserved. // import Foundation struct NoModel: Decodable { } struct LoginRequest: KoohiiRequest { typealias ModelType = NoModel typealias InputType = NoInput let apiMethod = "/login" let useEndpoint = false let sendApiKey = false let method = RequestMethod.post let contentType = ContentType.form let username: String let password: String var postParams: ParamSet { return [ "username" : username, "password" : password, "referer" : "@homepage", "commit" : "Login" ] } var headers: ParamSet { return [ "Host" : backendDomain, "Origin" : backendHost, "Referer" : backendHost + apiMethod ] } }
mit
4fd57d98ef5adf76d8c5ce4d218d7b66
22.578947
55
0.591518
4.266667
false
false
false
false
cockscomb/HUDKit
HUDKit/Classes/HUDPresentationController.swift
1
7163
// The MIT License (MIT) // // Copyright (c) 2016 Hiroki Kato // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit public class HUDPresentationController: UIPresentationController { /// Color of dimming public var dimmingColor = UIColor(white: 0.0, alpha: 0.4) // TODO: Use positive values /// Content insets public var contentInsets: UIEdgeInsets = UIEdgeInsets(top: 8.0, left: 8.0, bottom: 8.0, right: 8.0) /// Corner radius public var cornerRadius: CGFloat = 8.0 /// Visual effect of HUD background public var HUDVisualEffect: UIVisualEffect = UIBlurEffect(style: .ExtraLight) /// Dismiss when dimming tapped public var dismissWhenTapped: Bool = false private lazy var dimmingView: UIView = { let view = UIView(frame: self.containerView?.bounds ?? CGRect.zero) view.backgroundColor = self.dimmingColor view.alpha = 0.0 let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: "dismiss:") view.addGestureRecognizer(tapGestureRecognizer) return view }() private lazy var HUDView: UIVisualEffectView = { let visualEffectView = UIVisualEffectView() visualEffectView.frame = self.frameOfPresentedViewInContainerView() visualEffectView.layer.cornerRadius = self.cornerRadius visualEffectView.layer.masksToBounds = self.cornerRadius != 0.0 let contentView = self.presentedViewController.view contentView.translatesAutoresizingMaskIntoConstraints = false visualEffectView.contentView.addSubview(contentView) let contentSize = self.presentedViewController.preferredContentSize let constraints: [NSLayoutConstraint] = NSLayoutConstraint.constraintsWithVisualFormat("H:|-left-[contentView]-right-|", options: [], metrics: [ "left" : self.contentInsets.left , "right" : self.contentInsets.right ], views: [ "contentView" : contentView ]) + NSLayoutConstraint.constraintsWithVisualFormat("V:|-top-[contentView]-bottom-|", options: [], metrics: [ "top" : self.contentInsets.top , "bottom" : self.contentInsets.bottom ], views: [ "contentView" : contentView ]) + [ NSLayoutConstraint(item: visualEffectView, attribute: .CenterX, relatedBy: .Equal, toItem: contentView, attribute: .CenterX, multiplier: 1.0, constant: 0.0), NSLayoutConstraint(item: visualEffectView, attribute: .CenterY, relatedBy: .Equal, toItem: contentView, attribute: .CenterY, multiplier: 1.0, constant: 0.0), ] NSLayoutConstraint.activateConstraints(constraints) return visualEffectView }() func dismiss(sender: AnyObject?) { if dismissWhenTapped { presentingViewController.dismissViewControllerAnimated(true, completion: nil) } } // MARK: - Override public override func presentedView() -> UIView? { return HUDView } public override func presentationTransitionWillBegin() { dimmingView.translatesAutoresizingMaskIntoConstraints = false containerView?.insertSubview(dimmingView, atIndex: 0) let constraints: [NSLayoutConstraint] = NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[view]-0-|", options: [], metrics: nil, views: [ "view" : dimmingView ]) + NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[view]-0-|", options: [], metrics: nil, views: [ "view" : dimmingView ]) NSLayoutConstraint.activateConstraints(constraints) presentingViewController.transitionCoordinator()?.animateAlongsideTransition({ context in self.HUDView.effect = self.HUDVisualEffect self.dimmingView.alpha = 1.0 self.presentingViewController.view.tintAdjustmentMode = .Dimmed }, completion: nil) } public override func dismissalTransitionWillBegin() { presentingViewController.transitionCoordinator()?.animateAlongsideTransition({ context in if #available(iOS 9.0, *) { self.HUDView.effect = nil } else { // UIVisualEffectView.effect animation isn't available in iOS 8 } self.dimmingView.alpha = 0.0 self.presentingViewController.view.tintAdjustmentMode = .Automatic }, completion: nil) } public override func dismissalTransitionDidEnd(completed: Bool) { if completed { dimmingView.removeFromSuperview() } } public override func frameOfPresentedViewInContainerView() -> CGRect { let containerRect = containerView?.bounds ?? CGRect.zero var rect = containerRect rect.size = sizeForChildContentContainer(presentedViewController, withParentContainerSize: containerView?.bounds.size ?? CGSize.zero) rect.origin.x = (containerRect.width - rect.width) / 2.0 rect.origin.y = (containerRect.height - rect.height) / 2.0 return UIEdgeInsetsInsetRect(rect, UIEdgeInsetsMake(-contentInsets.top, -contentInsets.left, -contentInsets.bottom, -contentInsets.right)) } public override func shouldPresentInFullscreen() -> Bool { return true } // MARK: UIContentContainer public override func containerViewWillLayoutSubviews() { presentedView()?.frame = frameOfPresentedViewInContainerView() } public override func sizeForChildContentContainer(container: UIContentContainer, withParentContainerSize parentSize: CGSize) -> CGSize { let preferredSize = presentedViewController.preferredContentSize let bounds = CGRectInset(containerView?.bounds ?? CGRect.zero, contentInsets.left + contentInsets.right, contentInsets.top + contentInsets.bottom) return CGRectIntersection(bounds, CGRect(origin: CGPointZero, size: preferredSize)).size } public override func preferredContentSizeDidChangeForChildContentContainer(container: UIContentContainer) { if container === presentedViewController && containerView != nil { presentedView()?.frame = frameOfPresentedViewInContainerView() } } }
mit
623df7856e9a345227a8e1974161b3a5
47.073826
231
0.704733
5.385714
false
false
false
false
vermont42/Conjugar
Conjugar/TenseCell.swift
1
1265
// // TenseCell.swift // Conjugar // // Created by Joshua Adams on 5/7/17. // Copyright © 2017 Josh Adams. All rights reserved. // import UIKit class TenseCell: UITableViewCell { static let identifier = "TenseCell" @UsesAutoLayout var tense: UILabel = { let label = UILabel() label.textColor = Colors.red label.font = Fonts.regularCell label.textAlignment = .center label.adjustsFontSizeToFitWidth = true return label }() required init?(coder aDecoder: NSCoder) { NSCoder.fatalErrorNotImplemented() } override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) backgroundColor = Colors.black selectionStyle = .none addSubview(tense) accessibilityTraits = accessibilityTraits.union(.header) NSLayoutConstraint.activate([ tense.leadingAnchor.constraint(equalTo: leadingAnchor, constant: Layout.defaultSpacing), tense.trailingAnchor.constraint(equalTo: trailingAnchor, constant: Layout.defaultSpacing * -1.0), tense.centerYAnchor.constraint(equalTo: centerYAnchor) ]) } func configure(tense: String) { self.tense.text = tense self.tense.setAccessibilityLabelInSpanish(tense) } }
agpl-3.0
40a6871e1f76b16371ea8d090b4c5b58
26.478261
103
0.723101
4.450704
false
false
false
false
basheersubei/swift-t
stc/tests/424-forloops-5.swift
4
450
import assert; import stats; main { int A[]; for (int i = 1; i <= 10; i = i + 1) { int B[]; for (int j = 1; j <= i; j = j + 1) { trace(i, j); B[j] = j; } A[i] = sum_integer(B); assertEqual(sum_integer(B), ((i + i*i)%/2) , "i=" + fromint(i) + " sum B"); } trace(sum_integer(A)); assertEqual(sum_integer(A), 220, "sum(A)"); }
apache-2.0
393463d15f9f248d676f6c2433699243
21.5
50
0.375556
2.941176
false
false
false
false
alexcomu/swift3-tutorial
12-webRequest/12-webRequest/Forecast.swift
1
2064
// // Forecast.swift // 12-webRequest // // Created by Alex Comunian on 20/01/17. // Copyright © 2017 Alex Comunian. All rights reserved. // import UIKit import Alamofire class Forecast{ var _date: String! var _weatherType: String! var _highTemp: String! var _lowTemp: String! var date: String!{ if _date == nil{ _date = "" } return _date } var weatherType: String!{ if _weatherType == nil{ _weatherType = "" } return _weatherType } var highTemp: String!{ if _highTemp == nil{ _highTemp = "" } return _highTemp } var lowTemp: String!{ if _lowTemp == nil{ _lowTemp = "" } return _lowTemp } init(weatherDict: Dictionary<String, AnyObject>){ if let temp = weatherDict["temp"] as? Dictionary<String, AnyObject>{ if let minTemp = temp["min"] as? Double{ self._lowTemp = "\(Double(round((1000*(minTemp-273))/1000)))" } if let maxTemp = temp["max"] as? Double{ self._highTemp = "\(Double(round((1000*(maxTemp-273))/1000)))" } } if let weather = weatherDict["weather"] as? [Dictionary<String, AnyObject>]{ if let wtype = weather[0]["main"] as? String{ self._weatherType = wtype } } if let date = weatherDict["dt"] as? Double{ let unixConvertedDate = Date(timeIntervalSince1970: date) let dateFormatter = DateFormatter() dateFormatter.dateStyle = .full dateFormatter.dateFormat = "EEEE" dateFormatter.timeStyle = .none self._date = unixConvertedDate.dayOfTheWeek() } } } extension Date{ func dayOfTheWeek() -> String{ let dateFormatter = DateFormatter() dateFormatter.dateFormat = "EEEE" return dateFormatter.string(from: self) } }
mit
48272745db3b051ff675e608d7ec166b
22.179775
84
0.524479
4.398721
false
false
false
false
sazae657/FuckingGarbageMac
FuckingGarbage/AssDelegate.swift
1
4778
// // AssDelegate.swift // FuckingGarbage // // Copyright © 2016年 sazae657 All rights reserved. // import Cocoa @NSApplicationMain class Swiftとかいうクソ言語で嫌々書いたクラス: NSObject, NSApplicationDelegate { @IBOutlet weak var window: NSWindow! var ステータスアイテムとかいうクソみたいなネーミングやめろよ : NSStatusItem! var 濃いも : NSImage! var 薄いも : NSImage! var 有象無象 : Bool = true var Macはゴミだってはっきりわかんだね : UnsafeMutablePointer<FuckingGarbage_MAC>! func セキュリティとプライバシー<この表記揺れひどい>() { NSWorkspace.shared.open(NSURL.fileURL(withPath: "/System/Library/PreferencePanes/Security.prefPane") as URL) } let レガシーコードの逆襲: @convention(c) (Int32) -> Void = { (数) in if (37564 == 数) { // スクリーンセーバー起動!! NSWorkspace.shared.open( NSURL.fileURL(withPath: "/System/Library/Frameworks/ScreenSaver.framework/Resources/ScreenSaverEngine.app") as URL) } } func applicationDidFinishLaunching(_ aNotification: Notification) { Macはゴミだってはっきりわかんだね = Weird(レガシーコードの逆襲) let v = Stupid(Macはゴミだってはっきりわかんだね, 0) if (0 != v) { let 世界の警察 = NSAlert() 世界の警察.messageText = "エラー" 世界の警察.informativeText = "セキュリティとプライバシー > プライバシーを開いて\n<アクセシビリティ>にコレを追加してちょ" 世界の警察.runModal() セキュリティとプライバシー<この表記揺れひどい>() NSApp.terminate(self) } 濃いも = NSImage(named: NSImage.Name(rawValue: "有効状態")) 薄いも = NSImage(named: NSImage.Name(rawValue: "無効状態")) ステータスアイテムとかいうクソみたいなネーミングやめろよ = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength) ステータスアイテムとかいうクソみたいなネーミングやめろよ.image = 濃いも let Mac特有の押すと下品に垂れ下がるやつ = NSMenu() // デフォ有効なのでラベルは無効 有象無象 = true let 切り替えメニュー = NSMenuItem(title:"無効にする", action:#selector( Swiftとかいうクソ言語で嫌々書いたクラス.Macの腐ったマウスポインターが有効無効を触った(汚物:)), keyEquivalent:"") 切り替えメニュー.target = self let 終了メニュー = NSMenuItem(title:"終了", action:#selector( Swiftとかいうクソ言語で嫌々書いたクラス.Macを破壊して終了したいがぐっとこらえてプログラムを終了してやる(汚物:)), keyEquivalent:"") 終了メニュー.target = self Mac特有の押すと下品に垂れ下がるやつ.addItem(切り替えメニュー) Mac特有の押すと下品に垂れ下がるやつ.addItem(終了メニュー) ステータスアイテムとかいうクソみたいなネーミングやめろよ.menu = Mac特有の押すと下品に垂れ下がるやつ } @objc func Macの腐ったマウスポインターが有効無効を触った(汚物 : NSMenuItem) { 汚物.title = 有象無象 ? "有効にする" : "無効にする" 有象無象 = !有象無象 ステータスアイテムとかいうクソみたいなネーミングやめろよ.image = 有象無象 ? 濃いも : 薄いも let v = Stupid(Macはゴミだってはっきりわかんだね, 有象無象 ? 0 : 1) if(0 != v) { let 世界の警察 = NSAlert() 世界の警察.messageText = "エラー" 世界の警察.informativeText = "これはひどいエラーですね" 世界の警察.runModal() NSApp.terminate(self) } } @objc func Macを破壊して終了したいがぐっとこらえてプログラムを終了してやる(汚物 : NSMenuItem) { NSApp.terminate(self) } func applicationWillTerminate(_ aNotification: Notification) { Stupid(Macはゴミだってはっきりわかんだね, 1) Disgusting(Macはゴミだってはっきりわかんだね) } }
gpl-3.0
49f853772ed5df667c628133b612c918
29.528846
127
0.619528
2.001892
false
false
false
false
mshhmzh/firefox-ios
Providers/NSUserDefaultsPrefs.swift
4
5078
/* 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 public class NSUserDefaultsPrefs: Prefs { private let prefixWithDot: String private let userDefaults: NSUserDefaults public func getBranchPrefix() -> String { return self.prefixWithDot } init(prefix: String, userDefaults: NSUserDefaults) { self.prefixWithDot = prefix + (prefix.endsWith(".") ? "" : ".") self.userDefaults = userDefaults } init(prefix: String) { self.prefixWithDot = prefix + (prefix.endsWith(".") ? "" : ".") self.userDefaults = NSUserDefaults(suiteName: AppInfo.sharedContainerIdentifier())! } public func branch(branch: String) -> Prefs { let prefix = self.prefixWithDot + branch + "." return NSUserDefaultsPrefs(prefix: prefix, userDefaults: self.userDefaults) } // Preferences are qualified by the profile's local name. // Connecting a profile to a Firefox Account, or changing to another, won't alter this. private func qualifyKey(key: String) -> String { return self.prefixWithDot + key } public func setInt(value: Int32, forKey defaultName: String) { // Why aren't you using userDefaults.setInteger? // Because userDefaults.getInteger returns a non-optional; it's impossible // to tell whether there's a value set, and you thus can't distinguish // between "not present" and zero. // Yeah, NSUserDefaults is meant to be used for storing "defaults", not data. setObject(NSNumber(int: value), forKey: defaultName) } public func setTimestamp(value: Timestamp, forKey defaultName: String) { setLong(value, forKey: defaultName) } public func setLong(value: UInt64, forKey defaultName: String) { setObject(NSNumber(unsignedLongLong: value), forKey: defaultName) } public func setLong(value: Int64, forKey defaultName: String) { setObject(NSNumber(longLong: value), forKey: defaultName) } public func setString(value: String, forKey defaultName: String) { setObject(value, forKey: defaultName) } public func setObject(value: AnyObject?, forKey defaultName: String) { userDefaults.setObject(value, forKey: qualifyKey(defaultName)) } public func stringForKey(defaultName: String) -> String? { // stringForKey converts numbers to strings, which is almost always a bug. return userDefaults.objectForKey(qualifyKey(defaultName)) as? String } public func setBool(value: Bool, forKey defaultName: String) { setObject(NSNumber(bool: value), forKey: defaultName) } public func boolForKey(defaultName: String) -> Bool? { // boolForKey just returns false if the key doesn't exist. We need to // distinguish between false and non-existent keys, so use objectForKey // and cast the result instead. let number = userDefaults.objectForKey(qualifyKey(defaultName)) as? NSNumber return number?.boolValue } private func nsNumberForKey(defaultName: String) -> NSNumber? { return userDefaults.objectForKey(qualifyKey(defaultName)) as? NSNumber } public func unsignedLongForKey(defaultName: String) -> UInt64? { return nsNumberForKey(defaultName)?.unsignedLongLongValue } public func timestampForKey(defaultName: String) -> Timestamp? { return unsignedLongForKey(defaultName) } public func longForKey(defaultName: String) -> Int64? { return nsNumberForKey(defaultName)?.longLongValue } public func objectForKey<T: AnyObject>(defaultName: String) -> T? { return userDefaults.objectForKey(qualifyKey(defaultName)) as? T } public func intForKey(defaultName: String) -> Int32? { return nsNumberForKey(defaultName)?.intValue } public func stringArrayForKey(defaultName: String) -> [String]? { let objects = userDefaults.stringArrayForKey(qualifyKey(defaultName)) if let strings = objects { return strings } return nil } public func arrayForKey(defaultName: String) -> [AnyObject]? { return userDefaults.arrayForKey(qualifyKey(defaultName)) } public func dictionaryForKey(defaultName: String) -> [String : AnyObject]? { return userDefaults.dictionaryForKey(qualifyKey(defaultName)) } public func removeObjectForKey(defaultName: String) { userDefaults.removeObjectForKey(qualifyKey(defaultName)) } public func clearAll() { // TODO: userDefaults.removePersistentDomainForName() has no effect for app group suites. // iOS Bug? Iterate and remove each manually for now. for key in userDefaults.dictionaryRepresentation().keys { if key.startsWith(prefixWithDot) { userDefaults.removeObjectForKey(key) } } } }
mpl-2.0
19360e53da0149006b2f3f28e8b7bb70
36.338235
97
0.679992
4.958984
false
false
false
false
benlangmuir/swift
test/ClangImporter/experimental_diagnostics_cmacros.swift
7
7439
// RUN: not %target-swift-frontend(mock-sdk: %clang-importer-sdk) -typecheck %s 2>&1 | %FileCheck %s --strict-whitespace import macros _ = INVALID_INTEGER_LITERAL_2 // CHECK: experimental_diagnostics_cmacros.swift:{{[0-9]+}}:{{[0-9]+}}: error: cannot find 'INVALID_INTEGER_LITERAL_2' in scope // CHECK-NEXT: _ = INVALID_INTEGER_LITERAL_2 // CHECK-NEXT: ^~~~~~~~~~~~~~~~~~~~~~~~~ // CHECK-NEXT: macros.h:{{[0-9]+}}:9: note: macro 'INVALID_INTEGER_LITERAL_2' not imported // CHECK-NEXT: #define INVALID_INTEGER_LITERAL_2 10abc // CHECK-NEXT: {{^}} ^ // CHECK-NEXT: macros.h:{{[0-9]+}}:35: note: invalid numeric literal // CHECK-NEXT: #define INVALID_INTEGER_LITERAL_2 10abc // CHECK-NEXT: {{^}} ^ _ = FUNC_LIKE_MACRO() // CHECK: experimental_diagnostics_cmacros.swift:{{[0-9]+}}:{{[0-9]+}}: error: cannot find 'FUNC_LIKE_MACRO' in scope // CHECK-NEXT: _ = FUNC_LIKE_MACRO() // CHECK-NEXT: ^~~~~~~~~~~~~~~ // CHECK-NEXT: macros.h:{{[0-9]+}}:9: note: macro 'FUNC_LIKE_MACRO' not imported: function like macros not supported // CHECK-NEXT: #define FUNC_LIKE_MACRO() 0 // CHECK-NEXT: {{^}} ^ _ = FUNC_LIKE_MACRO() // CHECK: experimental_diagnostics_cmacros.swift:{{[0-9]+}}:{{[0-9]+}}: error: cannot find 'FUNC_LIKE_MACRO' in scope // CHECK-NEXT: _ = FUNC_LIKE_MACRO() // CHECK-NEXT: ^~~~~~~~~~~~~~~ // CHECK-NEXT: macros.h:{{[0-9]+}}:9: note: macro 'FUNC_LIKE_MACRO' not imported: function like macros not supported // CHECK-NEXT: #define FUNC_LIKE_MACRO() 0 // CHECK-NEXT: {{^}} ^ _ = INVALID_ARITHMETIC_1 // CHECK: experimental_diagnostics_cmacros.swift:{{[0-9]+}}:{{[0-9]+}}: error: cannot find 'INVALID_ARITHMETIC_1' in scope // CHECK-NEXT: _ = INVALID_ARITHMETIC_1 // CHECK-NEXT: ^~~~~~~~~~~~~~~~~~~~ // CHECK-NEXT: macros.h:{{[0-9]+}}:9: note: macro 'INVALID_ARITHMETIC_1' not imported: structure not supported // CHECK-NEXT: #define INVALID_ARITHMETIC_1 5 + INVALID_INTEGER_LITERAL_1 // CHECK-NEXT: {{^}} ^ _ = INVALID_ARITHMETIC_2 // CHECK: experimental_diagnostics_cmacros.swift:{{[0-9]+}}:{{[0-9]+}}: error: cannot find 'INVALID_ARITHMETIC_2' in scope // CHECK-NEXT: _ = INVALID_ARITHMETIC_2 // CHECK-NEXT: ^~~~~~~~~~~~~~~~~~~~ // CHECK-NEXT: macros.h:{{[0-9]+}}:9: note: macro 'INVALID_ARITHMETIC_2' not imported: structure not supported // CHECK-NEXT: #define INVALID_ARITHMETIC_2 INVALID_INTEGER_LITERAL_1 + ADD_TWO // CHECK-NEXT: {{^}} ^ _ = INVALID_ARITHMETIC_3 // CHECK: experimental_diagnostics_cmacros.swift:{{[0-9]+}}:{{[0-9]+}}: error: cannot find 'INVALID_ARITHMETIC_3' in scope // CHECK-NEXT: _ = INVALID_ARITHMETIC_3 // CHECK-NEXT: ^~~~~~~~~~~~~~~~~~~~ // CHECK-NEXT: macros.h:{{[0-9]+}}:9: note: macro 'INVALID_ARITHMETIC_3' not imported: structure not supported // CHECK-NEXT: #define INVALID_ARITHMETIC_3 ADD_TWO + INVALID_INTEGER_LITERAL_1 // CHECK-NEXT: {{^}} ^ _ = INVALID_ARITHMETIC_4 // CHECK: experimental_diagnostics_cmacros.swift:{{[0-9]+}}:{{[0-9]+}}: error: cannot find 'INVALID_ARITHMETIC_4' in scope // CHECK-NEXT: _ = INVALID_ARITHMETIC_4 // CHECK-NEXT: ^~~~~~~~~~~~~~~~~~~~ // CHECK-NEXT: macros.h:{{[0-9]+}}:9: note: macro 'INVALID_ARITHMETIC_4' not imported: structure not supported // CHECK-NEXT: #define INVALID_ARITHMETIC_4 \ // CHECK-NEXT: {{^}} ^ _ = INVALID_ARITHMETIC_5 // CHECK: experimental_diagnostics_cmacros.swift:{{[0-9]+}}:{{[0-9]+}}: error: cannot find 'INVALID_ARITHMETIC_5' in scope // CHECK-NEXT: _ = INVALID_ARITHMETIC_5 // CHECK-NEXT: ^~~~~~~~~~~~~~~~~~~~ // CHECK-NEXT: macros.h:{{[0-9]+}}:9: note: macro 'INVALID_ARITHMETIC_5' not imported: structure not supported // CHECK-NEXT: #define INVALID_ARITHMETIC_5 1 + VERSION_STRING // CHECK-NEXT: {{^}} ^ _ = INVALID_ARITHMETIC_6 // CHECK: experimental_diagnostics_cmacros.swift:{{[0-9]+}}:{{[0-9]+}}: error: cannot find 'INVALID_ARITHMETIC_6' in scope // CHECK-NEXT: _ = INVALID_ARITHMETIC_6 // CHECK-NEXT: ^~~~~~~~~~~~~~~~~~~~ // CHECK-NEXT: macros.h:{{[0-9]+}}:9: note: macro 'INVALID_ARITHMETIC_6' not imported: structure not supported // CHECK-NEXT: #define INVALID_ARITHMETIC_6 1 + 'c' // CHECK-NEXT: {{^}} ^ _ = INVALID_ARITHMETIC_7 // CHECK: experimental_diagnostics_cmacros.swift:{{[0-9]+}}:{{[0-9]+}}: error: cannot find 'INVALID_ARITHMETIC_7' in scope // CHECK-NEXT: _ = INVALID_ARITHMETIC_7 // CHECK-NEXT: ^~~~~~~~~~~~~~~~~~~~ // CHECK-NEXT: macros.h:{{[0-9]+}}:9: note: macro 'INVALID_ARITHMETIC_7' not imported // CHECK-NEXT: #define INVALID_ARITHMETIC_7 3 % 2 // CHECK-NEXT: {{^}} ^ // CHECK-NEXT: macros.h:{{[0-9]+}}:32: note: operator '%' not supported in macro arithmetic // CHECK-NEXT: #define INVALID_ARITHMETIC_7 3 % 2 // CHECK-NEXT: {{^}} ^ _ = CHAR_LITERAL // CHECK: experimental_diagnostics_cmacros.swift:{{[0-9]+}}:{{[0-9]+}}: error: cannot find 'CHAR_LITERAL' in scope // CHECK-NEXT: _ = CHAR_LITERAL // CHECK-NEXT: ^~~~~~~~~~~~ // CHECK-NEXT: macros.h:{{[0-9]+}}:9: note: macro 'CHAR_LITERAL' not imported // CHECK-NEXT: #define CHAR_LITERAL 'a' // CHECK-NEXT: {{^}} ^ // CHECK-NEXT: macros.h:{{[0-9]+}}:22: note: only numeric and string macro literals supported // CHECK-NEXT: #define CHAR_LITERAL 'a' // CHECK-NEXT: {{^}} ^ UNSUPPORTED_1 // CHECK: experimental_diagnostics_cmacros.swift:{{[0-9]+}}:{{[0-9]+}}: error: cannot find 'UNSUPPORTED_1' in scope // CHECK-NEXT: UNSUPPORTED_1 // CHECK-NEXT: ^~~~~~~~~~~~~ // CHECK-NEXT: macros.h:{{[0-9]+}}:9: note: macro 'UNSUPPORTED_1' not imported: structure not supported // CHECK-NEXT: #define UNSUPPORTED_1 FUNC_LIKE_MACRO() // CHECK-NEXT: {{^}} ^ UNSUPPORTED_2 // CHECK: experimental_diagnostics_cmacros.swift:{{[0-9]+}}:{{[0-9]+}}: error: cannot find 'UNSUPPORTED_2' in scope // CHECK-NEXT: UNSUPPORTED_2 // CHECK-NEXT: ^~~~~~~~~~~~~ // CHECK-NEXT: macros.h:{{[0-9]+}}:9: note: macro 'UNSUPPORTED_2' not imported: structure not supported // CHECK-NEXT: #define UNSUPPORTED_2 FUNC_LIKE_MACRO_2(1) // CHECK-NEXT: {{^}} ^ UNSUPPORTED_3 // CHECK: experimental_diagnostics_cmacros.swift:{{[0-9]+}}:{{[0-9]+}}: error: cannot find 'UNSUPPORTED_3' in scope // CHECK-NEXT: UNSUPPORTED_3 // CHECK-NEXT: ^~~~~~~~~~~~~ // CHECK-NEXT: macros.h:{{[0-9]+}}:9: note: macro 'UNSUPPORTED_3' not imported: structure not supported // CHECK-NEXT: #define UNSUPPORTED_3 1 + FUNC_LIKE_MACRO_2(1) // CHECK-NEXT: {{^}} ^ UNSUPPORTED_4 // CHECK: experimental_diagnostics_cmacros.swift:{{[0-9]+}}:{{[0-9]+}}: error: cannot find 'UNSUPPORTED_4' in scope // CHECK-NEXT: UNSUPPORTED_4 // CHECK-NEXT: ^~~~~~~~~~~~~ // CHECK-NEXT: macros.h:{{[0-9]+}}:9: note: macro 'UNSUPPORTED_4' not imported: structure not supported // CHECK-NEXT: #define UNSUPPORTED_4 \ // CHECK-NEXT: {{^}} ^ UNSUPPORTED_5 // CHECK: experimental_diagnostics_cmacros.swift:{{[0-9]+}}:{{[0-9]+}}: error: cannot find 'UNSUPPORTED_5' in scope // CHECK-NEXT: UNSUPPORTED_5 // CHECK-NEXT: ^~~~~~~~~~~~~ // CHECK-NEXT: macros.h:{{[0-9]+}}:9: note: macro 'UNSUPPORTED_5' not imported: structure not supported // CHECK-NEXT: #define UNSUPPORTED_5 1 + 1 + 1 // CHECK-NEXT: {{^}} ^
apache-2.0
9bde237d64f4ac5d63a209a8bfdcb1d5
51.387324
132
0.5943
3.145455
false
false
false
false
onmyway133/Github.swift
Sources/Classes/Commit/GitCommit.swift
1
2668
// // GitCommit.swift // GithubSwift // // Created by Khoa Pham on 20/04/16. // Copyright © 2016 Fantageek. All rights reserved. // import Foundation import Tailor import Sugar // A git commit. public class GitCommit: Object { // The commit URL for this commit. public private(set) var commitURL: NSURL? // The commit message for this commit. public private(set) var message: String = "" // The SHA for this commit. public private(set) var SHA: String = "" // The committer of this commit. public private(set) var committer: User? // The author of this commit. public private(set) var author: User? // The date the author signed the commit. public private(set) var commitDate: NSDate? // The number of changes made in the commit. // This property is only set when fetching a full commit. public private(set) var countOfChanges: Int = 0 // The number of additions made in the commit. // This property is only set when fetching a full commit. public private(set) var countOfAdditions: Int = 0 // The number of deletions made in the commit. // This property is only set when fetching a full commit. public private(set) var countOfDeletions: Int = 0 // The OCTGitCommitFile objects changed in the commit. // This property is only set when fetching a full commit. public private(set) var files: [GitCommitFile] = [] // The authors git user.name property. This is only useful if the // author does not have a GitHub login. Otherwise, author should // be used. public private(set) var authorName: String = "" // The committer's git user.name property. This is only useful if the // committer does not have a GitHub login. Otherwise, committer should // be used. public private(set) var committerName: String = "" public required init(_ map: JSONDictionary) { super.init(map) let commit = map.dictionary("commit") let author = commit?.dictionary("author") let stats = map.dictionary("stats") self.commitURL <- map.transform("url", transformer: NSURL.init(string: )) self.message <- commit?.property("message") self.SHA <- map.property("sha") self.committer <- map.relation("committer") self.author <- map.relation("author") self.commitDate <- author?.transform("date", transformer: Transformer.stringToDate) self.countOfAdditions <- stats?.property("additions") self.countOfDeletions <- stats?.property("deletions") self.countOfChanges <- stats?.property("total") self.files <- map.relations("files") self.authorName <- author?.property("name") self.committerName <- commit?.dictionary("committer")?.property("name") } }
mit
66f6c02f340796374eea564861295549
32.3375
87
0.700787
4.047041
false
false
false
false
agrizzo/Double_asFraction
Double_asFraction/Double_asFraction.swift
1
4987
// // Double_AsFraction.swift // Double_AsFraction // // Created by Tony Rizzo on 8/21/16. // Copyright © 2016 Koteray. All rights reserved. // import Foundation extension Double { /** Logic to round values * Round: Follows Apple's logic: When equidistant, round away from zero * Up: Towards positive infinity * Down: Towards negative infinity */ enum RoundLogic { case round case up case down } /// The number to the right of the decimal point. (Always positive) var decimal: Double { get { return fabs(self) - floor(fabs(self)) } } /** Helper function that rounds the Double to the Integer closest to zero For example: * 2.7 -> 2 * 1.0 -> 1 * -2.9 -> -2 */ func roundTowardZero() -> Int { if !(self.sign == .minus) { return Int(floor(self)) } else { return Int(ceil(self)) } } /** Returns the string representation of the fraction closest to self from the array of fractions - returns: String - Parameters: - fractions: Array of Fractions. Must be sorted in ascending order. - roundLogic: Rounding technique */ func asFraction(_ fractions: [Fraction], roundLogic: RoundLogic) -> String { let bestGuess = Int(floor(decimal * Double(fractions.count))) return findNearest(bestGuess, fractions: fractions, roundLogic: roundLogic) } /** Find the nearest entry in the array - returns: String - parameter bestGuess: Index value most likely to have answer - parameter fractions: Array of Fractions. Must be sorted in ascending order - parameter roundLogic: Rounding technique */ fileprivate func findNearest(_ bestGuess: Int, fractions: [Fraction], roundLogic: RoundLogic) -> String { switch true { // most likely scenerio case self.decimal > fractions[bestGuess].value && self.decimal < fractions[bestGuess + 1].value: if !(self.sign == .minus) { switch roundLogic { case .down: return showAnswer(fractions[bestGuess]) case .up: return showAnswer(fractions[bestGuess + 1]) case .round: if (self.decimal - fractions[bestGuess].value) < (fractions[bestGuess + 1].value - self.decimal) { return showAnswer(fractions[bestGuess]) } else { return showAnswer(fractions[bestGuess+1]) } } } else { switch roundLogic { case .down: return showAnswer(fractions[bestGuess + 1]) case .up: return showAnswer(fractions[bestGuess]) case .round: if (self.decimal - fractions[bestGuess].value) < (fractions[bestGuess + 1].value - self.decimal) { return showAnswer(fractions[bestGuess]) } else { return showAnswer(fractions[bestGuess+1]) } } } // Exact match case self.decimal == fractions[bestGuess].value: return showAnswer(fractions[bestGuess]) // Outside the range case self.decimal <= fractions[0].value: return showAnswer(fractions[0]) case self.decimal >= fractions[fractions.count - 1].value: return showAnswer(fractions[fractions.count - 1]) // These need to be re-adjusted case self.decimal < fractions[bestGuess].value && bestGuess>0: return findNearest(bestGuess-1, fractions: fractions, roundLogic: roundLogic) case self.decimal > fractions[bestGuess].value && bestGuess+1<fractions.count-1: return findNearest(bestGuess+1, fractions: fractions, roundLogic: roundLogic) // These get processed when the array doesn't lead with a zero value or end with a one value case self.decimal < fractions[bestGuess].value: // Redundant to add: && !(bestGuess>0): return showAnswer(fractions[bestGuess]) case self.decimal > fractions[bestGuess].value: // Redundant to add: && !(bestGuess+1<fractions.count-1): return showAnswer(fractions[bestGuess + 1]) default: fatalError("Default case Not sure how we got here") } } fileprivate func showAnswer(_ fraction: Fraction) -> String { let offset: Int = !(self.sign == .minus) ? fraction.adder : fraction.adder * -1 return "\(self.roundTowardZero() + offset) \(fraction.displayAs)".trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) } }
mit
b50b519a6dfe15bfe85c016f2795006d
34.614286
133
0.56438
4.717124
false
false
false
false
cuappdev/podcast-ios
old/Podcast/UserAuthEndpointRequests.swift
1
2956
// // UserAuthEndpointRequests.swift // Podcast // // Created by Jack Thompson on 8/27/18. // Copyright © 2018 Cornell App Development. All rights reserved. // import Foundation import SwiftyJSON class UpdateSessionEndpointRequest: EndpointRequest { var updateToken: String init(updateToken: String) { self.updateToken = updateToken super.init() path = "/sessions/update/" requiresAuthenticatedUser = true httpMethod = .post queryParameters = ["update_token": updateToken] } override func processResponseJSON(_ json: JSON) { let userJSON = json["data"]["user"] let user = User(json: userJSON) let sessionJSON = json["data"]["session"] let session = Session(json: sessionJSON) processedResponseValue = ["user": user, "session": session] } } enum SignInType { case facebook case google var url: String { switch self { case .facebook: return "/users/facebook_sign_in/" case .google: return "/users/google_sign_in/" } } } class AuthenticateUserEndpointRequest: EndpointRequest { var accessToken: String var signInType: SignInType init(signInType: SignInType, accessToken: String) { self.accessToken = accessToken self.signInType = signInType super.init() path = signInType.url requiresAuthenticatedUser = false httpMethod = .post bodyParameters = ["access_token": accessToken] } override func processResponseJSON(_ json: JSON) { let userJSON = json["data"]["user"] let user = User(json: userJSON) let isNewUser = json["data"]["is_new_user"].boolValue let sessionJSON = json["data"]["session"] let session = Session(json: sessionJSON) processedResponseValue = ["user": user, "session": session, "is_new_user": isNewUser] } } class MergeUserAccountsEndpointRequest: EndpointRequest { var accessToken: String var signInType: SignInType init(signInType: SignInType, accessToken: String) { self.accessToken = accessToken self.signInType = signInType super.init() path = "/users/merge/" httpMethod = .post queryParameters = ["platform": String(describing: signInType).lowercased()] if signInType == .facebook, let facebookAccessToken = Authentication.sharedInstance.facebookAccessToken { headers = ["AccessToken": facebookAccessToken] } else if let googleAccessToken = Authentication.sharedInstance.googleAccessToken { headers = ["AccessToken": googleAccessToken] } } override func processResponseJSON(_ json: JSON) { processedResponseValue = User(json: json["data"]["user"]) } }
mit
0c83d4482dede921e2143c1a02e2919e
27.142857
113
0.615567
4.908638
false
false
false
false
ahoppen/swift
test/Frontend/supplementary-output-support.swift
4
3211
// Checks what happens when trying to emit various supplementary outputs from // modes that don't support them. This isn't critical because the driver should // never ask the frontend to do this, but it's nice for people writing tests. // RUN: not %target-swift-frontend -typecheck -emit-module %s 2>&1 | %FileCheck -check-prefix=PARSE_NO_MODULE %s // PARSE_NO_MODULE: error: this mode does not support emitting modules{{$}} // RUN: not %target-swift-frontend -parse -emit-dependencies %s 2>&1 | %FileCheck -check-prefix=PARSE_NO_DEPS %s // PARSE_NO_DEPS: error: this mode does not support emitting dependency files{{$}} // RUN: not %target-swift-frontend -dump-ast -emit-dependencies %s 2>&1 | %FileCheck -check-prefix=DUMP_NO_DEPS %s // DUMP_NO_DEPS: error: this mode does not support emitting dependency files{{$}} // RUN: not %target-swift-frontend -parse -emit-reference-dependencies %s 2>&1 | %FileCheck -check-prefix=PARSE_NO_REFERENCE_DEPS %s // PARSE_NO_REFERENCE_DEPS: error: this mode does not support emitting reference dependency files{{$}} // RUN: not %target-swift-frontend -dump-ast -emit-reference-dependencies %s 2>&1 | %FileCheck -check-prefix=DUMP_NO_REFERENCE_DEPS %s // DUMP_NO_REFERENCE_DEPS: error: this mode does not support emitting reference dependency files{{$}} // RUN: not %target-swift-frontend -resolve-imports -emit-reference-dependencies %s 2>&1 | %FileCheck -check-prefix=RESOLVE_IMPORTS_NO_REFERENCE_DEPS %s // RESOLVE_IMPORTS_NO_REFERENCE_DEPS: error: this mode does not support emitting reference dependency files{{$}} // RUN: not %target-swift-frontend -parse -emit-objc-header %s 2>&1 | %FileCheck -check-prefix=PARSE_NO_OBJC_HEADER %s // PARSE_NO_OBJC_HEADER: error: this mode does not support emitting Objective-C or C++ headers{{$}} // RUN: not %target-swift-frontend -dump-ast -emit-objc-header %s 2>&1 | %FileCheck -check-prefix=DUMP_NO_OBJC_HEADER %s // DUMP_NO_OBJC_HEADER: error: this mode does not support emitting Objective-C or C++ headers{{$}} // RUN: not %target-swift-frontend -resolve-imports -emit-objc-header %s 2>&1 | %FileCheck -check-prefix=RESOLVE_IMPORTS_NO_OBJC_HEADER %s // RESOLVE_IMPORTS_NO_OBJC_HEADER: error: this mode does not support emitting Objective-C or C++ headers{{$}} // RUN: not %target-swift-frontend -parse -emit-module-interface-path %t %s 2>&1 | %FileCheck -check-prefix=PARSE_NO_INTERFACE %s // PARSE_NO_INTERFACE: error: this mode does not support emitting module interface files{{$}} // RUN: not %target-swift-frontend -emit-silgen -emit-module-interface-path %t %s 2>&1 | %FileCheck -check-prefix=SILGEN_NO_INTERFACE %s // SILGEN_NO_INTERFACE: error: this mode does not support emitting module interface files{{$}} // RUN: not %target-swift-frontend -parse -emit-private-module-interface-path %t %s 2>&1 | %FileCheck -check-prefix=PARSE_NO_PRIVATE_INTERFACE %s // PARSE_NO_PRIVATE_INTERFACE: error: this mode does not support emitting module interface files{{$}} // RUN: not %target-swift-frontend -emit-silgen -emit-private-module-interface-path %t %s 2>&1 | %FileCheck -check-prefix=SILGEN_NO_PRIVATE_INTERFACE %s // SILGEN_NO_PRIVATE_INTERFACE: error: this mode does not support emitting module interface files{{$}}
apache-2.0
af988ea0c63ed05a71c41697edd1fb01
90.742857
152
0.740891
3.54415
false
false
false
false
antlr/antlr4
runtime/Swift/Sources/Antlr4/atn/LexerCustomAction.swift
7
3408
/// /// Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. /// Use of this file is governed by the BSD 3-clause license that /// can be found in the LICENSE.txt file in the project root. /// /// /// Executes a custom lexer action by calling _org.antlr.v4.runtime.Recognizer#action_ with the /// rule and action indexes assigned to the custom action. The implementation of /// a custom action is added to the generated code for the lexer in an override /// of _org.antlr.v4.runtime.Recognizer#action_ when the grammar is compiled. /// /// This class may represent embedded actions created with the {...} /// syntax in ANTLR 4, as well as actions created for lexer commands where the /// command argument could not be evaluated when the grammar was compiled. /// /// - Sam Harwell /// - 4.2 /// public final class LexerCustomAction: LexerAction { fileprivate let ruleIndex: Int fileprivate let actionIndex: Int /// /// Constructs a custom lexer action with the specified rule and action /// indexes. /// /// - parameter ruleIndex: The rule index to use for calls to /// _org.antlr.v4.runtime.Recognizer#action_. /// - parameter actionIndex: The action index to use for calls to /// _org.antlr.v4.runtime.Recognizer#action_. /// public init(_ ruleIndex: Int, _ actionIndex: Int) { self.ruleIndex = ruleIndex self.actionIndex = actionIndex } /// /// Gets the rule index to use for calls to _org.antlr.v4.runtime.Recognizer#action_. /// /// - returns: The rule index for the custom action. /// public func getRuleIndex() -> Int { return ruleIndex } /// /// Gets the action index to use for calls to _org.antlr.v4.runtime.Recognizer#action_. /// /// - returns: The action index for the custom action. /// public func getActionIndex() -> Int { return actionIndex } /// /// /// /// - returns: This method returns _org.antlr.v4.runtime.atn.LexerActionType#CUSTOM_. /// public override func getActionType() -> LexerActionType { return LexerActionType.custom } /// /// Gets whether the lexer action is position-dependent. Position-dependent /// actions may have different semantics depending on the _org.antlr.v4.runtime.CharStream_ /// index at the time the action is executed. /// /// Custom actions are position-dependent since they may represent a /// user-defined embedded action which makes calls to methods like /// _org.antlr.v4.runtime.Lexer#getText_. /// /// - returns: This method returns `true`. /// override public func isPositionDependent() -> Bool { return true } /// /// /// /// Custom actions are implemented by calling _org.antlr.v4.runtime.Lexer#action_ with the /// appropriate rule and action indexes. /// override public func execute(_ lexer: Lexer) throws { try lexer.action(nil, ruleIndex, actionIndex) } public override func hash(into hasher: inout Hasher) { hasher.combine(ruleIndex) hasher.combine(actionIndex) } } public func ==(lhs: LexerCustomAction, rhs: LexerCustomAction) -> Bool { if lhs === rhs { return true } return lhs.ruleIndex == rhs.ruleIndex && lhs.actionIndex == rhs.actionIndex }
bsd-3-clause
b69b1d4f7b4b72ed6afbda649c0d17f7
30.555556
95
0.64554
4.30847
false
false
false
false
salesawagner/wascar
Sources/Core/AppDelegate.swift
1
973
// // AppDelegate.swift // wascar // // Created by Wagner Sales on 23/11/16. // Copyright © 2016 Wagner Sales. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Attributes let titleAtributes = [ NSForegroundColorAttributeName: UIColor.white, NSFontAttributeName: UIFont.WCARnavigationBarFont() ] // Navigation bar appearance let navAppearance = UINavigationBar.appearance() navAppearance.barTintColor = UIColor.WCARBlueColor() navAppearance.titleTextAttributes = titleAtributes navAppearance.isTranslucent = false // Navigation bar button appearance let barButtonAppearance = UIBarButtonItem.appearance() barButtonAppearance.setTitleTextAttributes(titleAtributes, for: UIControlState()) return true } }
mit
15867630b660298113fe06aea4b59572
29.375
141
0.781893
4.606635
false
false
false
false
jianwoo/ios-charts
Charts/Classes/Components/ChartLimitLine.swift
1
1676
// // ChartLimitLine.swift // Charts // // Created by Daniel Cohen Gindi on 23/2/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 UIKit public class ChartLimitLine: ChartComponentBase { @objc public enum LabelPosition: Int { case Left case Right } public var limit = Float(0.0) private var _lineWidth = CGFloat(2.0) public var lineColor = UIColor(red: 237.0/255.0, green: 91.0/255.0, blue: 91.0/255.0, alpha: 1.0) public var lineDashPhase = CGFloat(0.0) public var lineDashLengths: [CGFloat]? public var valueTextColor = UIColor.blackColor() public var valueFont = UIFont.systemFontOfSize(13.0) public var label = "" public var labelPosition = LabelPosition.Right public override init() { super.init(); } public init(limit: Float) { super.init(); self.limit = limit; } public init(limit: Float, label: String) { super.init(); self.limit = limit; self.label = label; } /// set the line width of the chart (min = 0.2f, max = 12f); default 2f public var lineWidth: CGFloat { get { return _lineWidth; } set { _lineWidth = newValue; if (_lineWidth < 0.2) { _lineWidth = 0.2; } if (_lineWidth > 12.0) { _lineWidth = 12.0; } } } }
apache-2.0
986f220dd23f486bbd0c5f46f6ef7755
21.065789
101
0.546539
4.058111
false
false
false
false