repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
bolom/fastlane | fastlane/swift/Runner.swift | 4 | 9271 | // Runner.swift
// Copyright (c) 2021 FastlaneTools
//
// ** NOTE **
// This file is provided by fastlane and WILL be overwritten in future updates
// If you want to add extra functionality to this project, create a new file in a
// new group so that it won't be marked for upgrade
//
import Foundation
let logger: Logger = {
Logger()
}()
let runner: Runner = {
Runner()
}()
func desc(_: String) {
// no-op, this is handled in fastlane/lane_list.rb
}
class Runner {
private var thread: Thread!
private var socketClient: SocketClient!
private let dispatchGroup = DispatchGroup()
private var returnValue: String? // lol, so safe
private var currentlyExecutingCommand: RubyCommandable?
private var shouldLeaveDispatchGroupDuringDisconnect = false
private var executeNext: [String: Bool] = [:]
func executeCommand(_ command: RubyCommandable) -> String {
dispatchGroup.enter()
currentlyExecutingCommand = command
socketClient.send(rubyCommand: command)
let secondsToWait = DispatchTimeInterval.seconds(SocketClient.defaultCommandTimeoutSeconds)
// swiftformat:disable:next redundantSelf
let timeoutResult = Self.waitWithPolling(self.executeNext[command.id], toEventually: { $0 == true }, timeout: SocketClient.defaultCommandTimeoutSeconds)
executeNext.removeValue(forKey: command.id)
let failureMessage = "command didn't execute in: \(SocketClient.defaultCommandTimeoutSeconds) seconds"
let success = testDispatchTimeoutResult(timeoutResult, failureMessage: failureMessage, timeToWait: secondsToWait)
guard success else {
log(message: "command timeout")
preconditionFailure()
}
if let _returnValue = returnValue {
return _returnValue
} else {
return ""
}
}
static func waitWithPolling<T>(_ expression: @autoclosure @escaping () throws -> T, toEventually predicate: @escaping (T) -> Bool, timeout: Int, pollingInterval: DispatchTimeInterval = .milliseconds(4)) -> DispatchTimeoutResult {
func memoizedClosure<T>(_ closure: @escaping () throws -> T) -> (Bool) throws -> T {
var cache: T?
return { withoutCaching in
if withoutCaching || cache == nil {
cache = try closure()
}
guard let cache = cache else {
preconditionFailure()
}
return cache
}
}
let runLoop = RunLoop.current
let timeoutDate = Date(timeInterval: TimeInterval(timeout), since: Date())
var fulfilled: Bool = false
let _expression = memoizedClosure(expression)
repeat {
do {
let exp = try _expression(true)
fulfilled = predicate(exp)
} catch {
fatalError("Error raised \(error.localizedDescription)")
}
if !fulfilled {
runLoop.run(until: Date(timeIntervalSinceNow: pollingInterval.timeInterval))
} else {
break
}
} while Date().compare(timeoutDate) == .orderedAscending
if fulfilled {
return .success
} else {
return .timedOut
}
}
}
// Handle threading stuff
extension Runner {
func startSocketThread(port: UInt32) {
let secondsToWait = DispatchTimeInterval.seconds(SocketClient.connectTimeoutSeconds)
dispatchGroup.enter()
socketClient = SocketClient(port: port, commandTimeoutSeconds: timeout, socketDelegate: self)
thread = Thread(target: self, selector: #selector(startSocketComs), object: nil)
guard let thread = thread else {
preconditionFailure("Thread did not instantiate correctly")
}
thread.name = "socket thread"
thread.start()
let connectTimeout = DispatchTime.now() + secondsToWait
let timeoutResult = dispatchGroup.wait(timeout: connectTimeout)
let failureMessage = "couldn't start socket thread in: \(SocketClient.connectTimeoutSeconds) seconds"
let success = testDispatchTimeoutResult(timeoutResult, failureMessage: failureMessage, timeToWait: secondsToWait)
guard success else {
log(message: "socket thread timeout")
preconditionFailure()
}
}
func disconnectFromFastlaneProcess() {
shouldLeaveDispatchGroupDuringDisconnect = true
dispatchGroup.enter()
socketClient.sendComplete()
let connectTimeout = DispatchTime.now() + 2
_ = dispatchGroup.wait(timeout: connectTimeout)
}
@objc func startSocketComs() {
guard let socketClient = self.socketClient else {
return
}
socketClient.connectAndOpenStreams()
dispatchGroup.leave()
}
private func testDispatchTimeoutResult(_ timeoutResult: DispatchTimeoutResult, failureMessage: String, timeToWait _: DispatchTimeInterval) -> Bool {
switch timeoutResult {
case .success:
return true
case .timedOut:
log(message: "timeout: \(failureMessage)")
return false
}
}
}
extension Runner: SocketClientDelegateProtocol {
func commandExecuted(serverResponse: SocketClientResponse, completion: (SocketClient) -> Void) {
switch serverResponse {
case let .success(returnedObject, closureArgumentValue):
verbose(message: "command executed")
returnValue = returnedObject
if let command = currentlyExecutingCommand as? RubyCommand {
if let closureArgumentValue = closureArgumentValue, !closureArgumentValue.isEmpty {
command.performCallback(callbackArg: closureArgumentValue, socket: socketClient) {
self.executeNext[command.id] = true
}
} else {
executeNext[command.id] = true
}
}
dispatchGroup.leave()
completion(socketClient)
case .clientInitiatedCancelAcknowledged:
verbose(message: "server acknowledged a cancel request")
dispatchGroup.leave()
if let command = currentlyExecutingCommand as? RubyCommand {
executeNext[command.id] = true
}
completion(socketClient)
case .alreadyClosedSockets, .connectionFailure, .malformedRequest, .malformedResponse, .serverError:
log(message: "error encountered while executing command:\n\(serverResponse)")
dispatchGroup.leave()
if let command = currentlyExecutingCommand as? RubyCommand {
executeNext[command.id] = true
}
completion(socketClient)
case let .commandTimeout(timeout):
log(message: "Runner timed out after \(timeout) second(s)")
}
}
func connectionsOpened() {
DispatchQueue.main.async {
verbose(message: "connected!")
}
}
func connectionsClosed() {
DispatchQueue.main.async {
if let thread = self.thread {
thread.cancel()
}
self.thread = nil
self.socketClient.closeSession()
self.socketClient = nil
verbose(message: "connection closed!")
if self.shouldLeaveDispatchGroupDuringDisconnect {
self.dispatchGroup.leave()
}
exit(0)
}
}
}
class Logger {
enum LogMode {
init(logMode: String) {
switch logMode {
case "normal", "default":
self = .normal
case "verbose":
self = .verbose
default:
logger.log(message: "unrecognized log mode: \(logMode), defaulting to 'normal'")
self = .normal
}
}
case normal
case verbose
}
public static var logMode: LogMode = .normal
func log(message: String) {
let timestamp = NSDate().timeIntervalSince1970
print("[\(timestamp)]: \(message)")
}
func verbose(message: String) {
if Logger.logMode == .verbose {
let timestamp = NSDate().timeIntervalSince1970
print("[\(timestamp)]: \(message)")
}
}
}
func log(message: String) {
logger.log(message: message)
}
func verbose(message: String) {
logger.verbose(message: message)
}
private extension DispatchTimeInterval {
var timeInterval: TimeInterval {
var result: TimeInterval = 0
switch self {
case let .seconds(value):
result = TimeInterval(value)
case let .milliseconds(value):
result = TimeInterval(value) * 0.001
case let .microseconds(value):
result = TimeInterval(value) * 0.000_001
case let .nanoseconds(value):
result = TimeInterval(value) * 0.000_000_001
case .never:
fatalError()
}
return result
}
}
// Please don't remove the lines below
// They are used to detect outdated files
// FastlaneRunnerAPIVersion [0.9.2]
| mit | e63400671e5e5279594e0407ed00b550 | 32.712727 | 233 | 0.608133 | 5.141986 | false | false | false | false |
jrendel/SwiftKeychainWrapper | SwiftKeychainWrapper/KeychainWrapper.swift | 1 | 25308 | //
// KeychainWrapper.swift
// KeychainWrapper
//
// Created by Jason Rendel on 9/23/14.
// Copyright (c) 2014 Jason Rendel. All rights reserved.
//
// The MIT License (MIT)
//
// 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
private let SecMatchLimit: String! = kSecMatchLimit as String
private let SecReturnData: String! = kSecReturnData as String
private let SecReturnPersistentRef: String! = kSecReturnPersistentRef as String
private let SecValueData: String! = kSecValueData as String
private let SecAttrAccessible: String! = kSecAttrAccessible as String
private let SecClass: String! = kSecClass as String
private let SecAttrService: String! = kSecAttrService as String
private let SecAttrGeneric: String! = kSecAttrGeneric as String
private let SecAttrAccount: String! = kSecAttrAccount as String
private let SecAttrAccessGroup: String! = kSecAttrAccessGroup as String
private let SecReturnAttributes: String = kSecReturnAttributes as String
private let SecAttrSynchronizable: String = kSecAttrSynchronizable as String
/// KeychainWrapper is a class to help make Keychain access in Swift more straightforward. It is designed to make accessing the Keychain services more like using NSUserDefaults, which is much more familiar to people.
open class KeychainWrapper {
@available(*, deprecated, message: "KeychainWrapper.defaultKeychainWrapper is deprecated since version 2.2.1, use KeychainWrapper.standard instead")
public static let defaultKeychainWrapper = KeychainWrapper.standard
/// Default keychain wrapper access
public static let standard = KeychainWrapper()
/// ServiceName is used for the kSecAttrService property to uniquely identify this keychain accessor. If no service name is specified, KeychainWrapper will default to using the bundleIdentifier.
private (set) public var serviceName: String
/// AccessGroup is used for the kSecAttrAccessGroup property to identify which Keychain Access Group this entry belongs to. This allows you to use the KeychainWrapper with shared keychain access between different applications.
private (set) public var accessGroup: String?
private static let defaultServiceName: String = {
return Bundle.main.bundleIdentifier ?? "SwiftKeychainWrapper"
}()
private convenience init() {
self.init(serviceName: KeychainWrapper.defaultServiceName)
}
/// Create a custom instance of KeychainWrapper with a custom Service Name and optional custom access group.
///
/// - parameter serviceName: The ServiceName for this instance. Used to uniquely identify all keys stored using this keychain wrapper instance.
/// - parameter accessGroup: Optional unique AccessGroup for this instance. Use a matching AccessGroup between applications to allow shared keychain access.
public init(serviceName: String, accessGroup: String? = nil) {
self.serviceName = serviceName
self.accessGroup = accessGroup
}
// MARK:- Public Methods
/// Checks if keychain data exists for a specified key.
///
/// - parameter forKey: The key to check for.
/// - parameter withAccessibility: Optional accessibility to use when retrieving the keychain item.
/// - parameter isSynchronizable: A bool that describes if the item should be synchronizable, to be synched with the iCloud. If none is provided, will default to false
/// - returns: True if a value exists for the key. False otherwise.
open func hasValue(forKey key: String, withAccessibility accessibility: KeychainItemAccessibility? = nil, isSynchronizable: Bool = false) -> Bool {
if let _ = data(forKey: key, withAccessibility: accessibility, isSynchronizable: isSynchronizable) {
return true
} else {
return false
}
}
open func accessibilityOfKey(_ key: String) -> KeychainItemAccessibility? {
var keychainQueryDictionary = setupKeychainQueryDictionary(forKey: key)
// Remove accessibility attribute
keychainQueryDictionary.removeValue(forKey: SecAttrAccessible)
// Limit search results to one
keychainQueryDictionary[SecMatchLimit] = kSecMatchLimitOne
// Specify we want SecAttrAccessible returned
keychainQueryDictionary[SecReturnAttributes] = kCFBooleanTrue
// Search
var result: AnyObject?
let status = SecItemCopyMatching(keychainQueryDictionary as CFDictionary, &result)
guard status == noErr, let resultsDictionary = result as? [String:AnyObject], let accessibilityAttrValue = resultsDictionary[SecAttrAccessible] as? String else {
return nil
}
return KeychainItemAccessibility.accessibilityForAttributeValue(accessibilityAttrValue as CFString)
}
/// Get the keys of all keychain entries matching the current ServiceName and AccessGroup if one is set.
open func allKeys() -> Set<String> {
var keychainQueryDictionary: [String:Any] = [
SecClass: kSecClassGenericPassword,
SecAttrService: serviceName,
SecReturnAttributes: kCFBooleanTrue!,
SecMatchLimit: kSecMatchLimitAll,
]
if let accessGroup = self.accessGroup {
keychainQueryDictionary[SecAttrAccessGroup] = accessGroup
}
var result: AnyObject?
let status = SecItemCopyMatching(keychainQueryDictionary as CFDictionary, &result)
guard status == errSecSuccess else { return [] }
var keys = Set<String>()
if let results = result as? [[AnyHashable: Any]] {
for attributes in results {
if let accountData = attributes[SecAttrAccount] as? Data,
let key = String(data: accountData, encoding: String.Encoding.utf8) {
keys.insert(key)
} else if let accountData = attributes[kSecAttrAccount] as? Data,
let key = String(data: accountData, encoding: String.Encoding.utf8) {
keys.insert(key)
}
}
}
return keys
}
// MARK: Public Getters
open func integer(forKey key: String, withAccessibility accessibility: KeychainItemAccessibility? = nil, isSynchronizable: Bool = false) -> Int? {
guard let numberValue = object(forKey: key, withAccessibility: accessibility, isSynchronizable: isSynchronizable) as? NSNumber else {
return nil
}
return numberValue.intValue
}
open func float(forKey key: String, withAccessibility accessibility: KeychainItemAccessibility? = nil, isSynchronizable: Bool = false) -> Float? {
guard let numberValue = object(forKey: key, withAccessibility: accessibility, isSynchronizable: isSynchronizable) as? NSNumber else {
return nil
}
return numberValue.floatValue
}
open func double(forKey key: String, withAccessibility accessibility: KeychainItemAccessibility? = nil, isSynchronizable: Bool = false) -> Double? {
guard let numberValue = object(forKey: key, withAccessibility: accessibility, isSynchronizable: isSynchronizable) as? NSNumber else {
return nil
}
return numberValue.doubleValue
}
open func bool(forKey key: String, withAccessibility accessibility: KeychainItemAccessibility? = nil, isSynchronizable: Bool = false) -> Bool? {
guard let numberValue = object(forKey: key, withAccessibility: accessibility, isSynchronizable: isSynchronizable) as? NSNumber else {
return nil
}
return numberValue.boolValue
}
/// Returns a string value for a specified key.
///
/// - parameter forKey: The key to lookup data for.
/// - parameter withAccessibility: Optional accessibility to use when retrieving the keychain item.
/// - parameter isSynchronizable: A bool that describes if the item should be synchronizable, to be synched with the iCloud. If none is provided, will default to false
/// - returns: The String associated with the key if it exists. If no data exists, or the data found cannot be encoded as a string, returns nil.
open func string(forKey key: String, withAccessibility accessibility: KeychainItemAccessibility? = nil, isSynchronizable: Bool = false) -> String? {
guard let keychainData = data(forKey: key, withAccessibility: accessibility, isSynchronizable: isSynchronizable) else {
return nil
}
return String(data: keychainData, encoding: String.Encoding.utf8) as String?
}
/// Returns an object that conforms to NSCoding for a specified key.
///
/// - parameter forKey: The key to lookup data for.
/// - parameter withAccessibility: Optional accessibility to use when retrieving the keychain item.
/// - parameter isSynchronizable: A bool that describes if the item should be synchronizable, to be synched with the iCloud. If none is provided, will default to false
/// - returns: The decoded object associated with the key if it exists. If no data exists, or the data found cannot be decoded, returns nil.
open func object(forKey key: String, withAccessibility accessibility: KeychainItemAccessibility? = nil, isSynchronizable: Bool = false) -> NSCoding? {
guard let keychainData = data(forKey: key, withAccessibility: accessibility, isSynchronizable: isSynchronizable) else {
return nil
}
return NSKeyedUnarchiver.unarchiveObject(with: keychainData) as? NSCoding
}
/// Returns a Data object for a specified key.
///
/// - parameter forKey: The key to lookup data for.
/// - parameter withAccessibility: Optional accessibility to use when retrieving the keychain item.
/// - parameter isSynchronizable: A bool that describes if the item should be synchronizable, to be synched with the iCloud. If none is provided, will default to false
/// - returns: The Data object associated with the key if it exists. If no data exists, returns nil.
open func data(forKey key: String, withAccessibility accessibility: KeychainItemAccessibility? = nil, isSynchronizable: Bool = false) -> Data? {
var keychainQueryDictionary = setupKeychainQueryDictionary(forKey: key, withAccessibility: accessibility, isSynchronizable: isSynchronizable)
// Limit search results to one
keychainQueryDictionary[SecMatchLimit] = kSecMatchLimitOne
// Specify we want Data/CFData returned
keychainQueryDictionary[SecReturnData] = kCFBooleanTrue
// Search
var result: AnyObject?
let status = SecItemCopyMatching(keychainQueryDictionary as CFDictionary, &result)
return status == noErr ? result as? Data : nil
}
/// Returns a persistent data reference object for a specified key.
///
/// - parameter forKey: The key to lookup data for.
/// - parameter withAccessibility: Optional accessibility to use when retrieving the keychain item.
/// - parameter isSynchronizable: A bool that describes if the item should be synchronizable, to be synched with the iCloud. If none is provided, will default to false
/// - returns: The persistent data reference object associated with the key if it exists. If no data exists, returns nil.
open func dataRef(forKey key: String, withAccessibility accessibility: KeychainItemAccessibility? = nil, isSynchronizable: Bool = false) -> Data? {
var keychainQueryDictionary = setupKeychainQueryDictionary(forKey: key, withAccessibility: accessibility, isSynchronizable: isSynchronizable)
// Limit search results to one
keychainQueryDictionary[SecMatchLimit] = kSecMatchLimitOne
// Specify we want persistent Data/CFData reference returned
keychainQueryDictionary[SecReturnPersistentRef] = kCFBooleanTrue
// Search
var result: AnyObject?
let status = SecItemCopyMatching(keychainQueryDictionary as CFDictionary, &result)
return status == noErr ? result as? Data : nil
}
// MARK: Public Setters
@discardableResult open func set(_ value: Int, forKey key: String, withAccessibility accessibility: KeychainItemAccessibility? = nil, isSynchronizable: Bool = false) -> Bool {
return set(NSNumber(value: value), forKey: key, withAccessibility: accessibility, isSynchronizable: isSynchronizable)
}
@discardableResult open func set(_ value: Float, forKey key: String, withAccessibility accessibility: KeychainItemAccessibility? = nil, isSynchronizable: Bool = false) -> Bool {
return set(NSNumber(value: value), forKey: key, withAccessibility: accessibility, isSynchronizable: isSynchronizable)
}
@discardableResult open func set(_ value: Double, forKey key: String, withAccessibility accessibility: KeychainItemAccessibility? = nil, isSynchronizable: Bool = false) -> Bool {
return set(NSNumber(value: value), forKey: key, withAccessibility: accessibility, isSynchronizable: isSynchronizable)
}
@discardableResult open func set(_ value: Bool, forKey key: String, withAccessibility accessibility: KeychainItemAccessibility? = nil, isSynchronizable: Bool = false) -> Bool {
return set(NSNumber(value: value), forKey: key, withAccessibility: accessibility, isSynchronizable: isSynchronizable)
}
/// Save a String value to the keychain associated with a specified key. If a String value already exists for the given key, the string will be overwritten with the new value.
///
/// - parameter value: The String value to save.
/// - parameter forKey: The key to save the String under.
/// - parameter withAccessibility: Optional accessibility to use when setting the keychain item.
/// - parameter isSynchronizable: A bool that describes if the item should be synchronizable, to be synched with the iCloud. If none is provided, will default to false
/// - returns: True if the save was successful, false otherwise.
@discardableResult open func set(_ value: String, forKey key: String, withAccessibility accessibility: KeychainItemAccessibility? = nil, isSynchronizable: Bool = false) -> Bool {
if let data = value.data(using: .utf8) {
return set(data, forKey: key, withAccessibility: accessibility, isSynchronizable: isSynchronizable)
} else {
return false
}
}
/// Save an NSCoding compliant object to the keychain associated with a specified key. If an object already exists for the given key, the object will be overwritten with the new value.
///
/// - parameter value: The NSCoding compliant object to save.
/// - parameter forKey: The key to save the object under.
/// - parameter withAccessibility: Optional accessibility to use when setting the keychain item.
/// - parameter isSynchronizable: A bool that describes if the item should be synchronizable, to be synched with the iCloud. If none is provided, will default to false
/// - returns: True if the save was successful, false otherwise.
@discardableResult open func set(_ value: NSCoding, forKey key: String, withAccessibility accessibility: KeychainItemAccessibility? = nil, isSynchronizable: Bool = false) -> Bool {
let data = NSKeyedArchiver.archivedData(withRootObject: value)
return set(data, forKey: key, withAccessibility: accessibility, isSynchronizable: isSynchronizable)
}
/// Save a Data object to the keychain associated with a specified key. If data already exists for the given key, the data will be overwritten with the new value.
///
/// - parameter value: The Data object to save.
/// - parameter forKey: The key to save the object under.
/// - parameter withAccessibility: Optional accessibility to use when setting the keychain item.
/// - parameter isSynchronizable: A bool that describes if the item should be synchronizable, to be synched with the iCloud. If none is provided, will default to false
/// - returns: True if the save was successful, false otherwise.
@discardableResult open func set(_ value: Data, forKey key: String, withAccessibility accessibility: KeychainItemAccessibility? = nil, isSynchronizable: Bool = false) -> Bool {
var keychainQueryDictionary: [String:Any] = setupKeychainQueryDictionary(forKey: key, withAccessibility: accessibility, isSynchronizable: isSynchronizable)
keychainQueryDictionary[SecValueData] = value
if let accessibility = accessibility {
keychainQueryDictionary[SecAttrAccessible] = accessibility.keychainAttrValue
} else {
// Assign default protection - Protect the keychain entry so it's only valid when the device is unlocked
keychainQueryDictionary[SecAttrAccessible] = KeychainItemAccessibility.whenUnlocked.keychainAttrValue
}
let status: OSStatus = SecItemAdd(keychainQueryDictionary as CFDictionary, nil)
if status == errSecSuccess {
return true
} else if status == errSecDuplicateItem {
return update(value, forKey: key, withAccessibility: accessibility, isSynchronizable: isSynchronizable)
} else {
return false
}
}
@available(*, deprecated, message: "remove is deprecated since version 2.2.1, use removeObject instead")
@discardableResult open func remove(key: String, withAccessibility accessibility: KeychainItemAccessibility? = nil, isSynchronizable: Bool = false) -> Bool {
return removeObject(forKey: key, withAccessibility: accessibility, isSynchronizable: isSynchronizable)
}
/// Remove an object associated with a specified key. If re-using a key but with a different accessibility, first remove the previous key value using removeObjectForKey(:withAccessibility) using the same accessibilty it was saved with.
///
/// - parameter forKey: The key value to remove data for.
/// - parameter withAccessibility: Optional accessibility level to use when looking up the keychain item.
/// - parameter isSynchronizable: A bool that describes if the item should be synchronizable, to be synched with the iCloud. If none is provided, will default to false
/// - returns: True if successful, false otherwise.
@discardableResult open func removeObject(forKey key: String, withAccessibility accessibility: KeychainItemAccessibility? = nil, isSynchronizable: Bool = false) -> Bool {
let keychainQueryDictionary: [String:Any] = setupKeychainQueryDictionary(forKey: key, withAccessibility: accessibility, isSynchronizable: isSynchronizable)
// Delete
let status: OSStatus = SecItemDelete(keychainQueryDictionary as CFDictionary)
if status == errSecSuccess {
return true
} else {
return false
}
}
/// Remove all keychain data added through KeychainWrapper. This will only delete items matching the currnt ServiceName and AccessGroup if one is set.
@discardableResult open func removeAllKeys() -> Bool {
// Setup dictionary to access keychain and specify we are using a generic password (rather than a certificate, internet password, etc)
var keychainQueryDictionary: [String:Any] = [SecClass:kSecClassGenericPassword]
// Uniquely identify this keychain accessor
keychainQueryDictionary[SecAttrService] = serviceName
// Set the keychain access group if defined
if let accessGroup = self.accessGroup {
keychainQueryDictionary[SecAttrAccessGroup] = accessGroup
}
let status: OSStatus = SecItemDelete(keychainQueryDictionary as CFDictionary)
if status == errSecSuccess {
return true
} else {
return false
}
}
/// Remove all keychain data, including data not added through keychain wrapper.
///
/// - Warning: This may remove custom keychain entries you did not add via SwiftKeychainWrapper.
///
open class func wipeKeychain() {
deleteKeychainSecClass(kSecClassGenericPassword) // Generic password items
deleteKeychainSecClass(kSecClassInternetPassword) // Internet password items
deleteKeychainSecClass(kSecClassCertificate) // Certificate items
deleteKeychainSecClass(kSecClassKey) // Cryptographic key items
deleteKeychainSecClass(kSecClassIdentity) // Identity items
}
// MARK:- Private Methods
/// Remove all items for a given Keychain Item Class
///
///
@discardableResult private class func deleteKeychainSecClass(_ secClass: AnyObject) -> Bool {
let query = [SecClass: secClass]
let status: OSStatus = SecItemDelete(query as CFDictionary)
if status == errSecSuccess {
return true
} else {
return false
}
}
/// Update existing data associated with a specified key name. The existing data will be overwritten by the new data.
private func update(_ value: Data, forKey key: String, withAccessibility accessibility: KeychainItemAccessibility? = nil, isSynchronizable: Bool = false) -> Bool {
var keychainQueryDictionary: [String:Any] = setupKeychainQueryDictionary(forKey: key, withAccessibility: accessibility, isSynchronizable: isSynchronizable)
let updateDictionary = [SecValueData:value]
// on update, only set accessibility if passed in
if let accessibility = accessibility {
keychainQueryDictionary[SecAttrAccessible] = accessibility.keychainAttrValue
}
// Update
let status: OSStatus = SecItemUpdate(keychainQueryDictionary as CFDictionary, updateDictionary as CFDictionary)
if status == errSecSuccess {
return true
} else {
return false
}
}
/// Setup the keychain query dictionary used to access the keychain on iOS for a specified key name. Takes into account the Service Name and Access Group if one is set.
///
/// - parameter forKey: The key this query is for
/// - parameter withAccessibility: Optional accessibility to use when setting the keychain item. If none is provided, will default to .WhenUnlocked
/// - parameter isSynchronizable: A bool that describes if the item should be synchronizable, to be synched with the iCloud. If none is provided, will default to false
/// - returns: A dictionary with all the needed properties setup to access the keychain on iOS
private func setupKeychainQueryDictionary(forKey key: String, withAccessibility accessibility: KeychainItemAccessibility? = nil, isSynchronizable: Bool = false) -> [String:Any] {
// Setup default access as generic password (rather than a certificate, internet password, etc)
var keychainQueryDictionary: [String:Any] = [SecClass:kSecClassGenericPassword]
// Uniquely identify this keychain accessor
keychainQueryDictionary[SecAttrService] = serviceName
// Only set accessibiilty if its passed in, we don't want to default it here in case the user didn't want it set
if let accessibility = accessibility {
keychainQueryDictionary[SecAttrAccessible] = accessibility.keychainAttrValue
}
// Set the keychain access group if defined
if let accessGroup = self.accessGroup {
keychainQueryDictionary[SecAttrAccessGroup] = accessGroup
}
// Uniquely identify the account who will be accessing the keychain
let encodedIdentifier: Data? = key.data(using: String.Encoding.utf8)
keychainQueryDictionary[SecAttrGeneric] = encodedIdentifier
keychainQueryDictionary[SecAttrAccount] = encodedIdentifier
keychainQueryDictionary[SecAttrSynchronizable] = isSynchronizable ? kCFBooleanTrue : kCFBooleanFalse
return keychainQueryDictionary
}
}
| mit | aaeb3bc470bc0309d965748e999c6c9f | 54.017391 | 239 | 0.708195 | 5.370968 | false | false | false | false |
mapsme/omim | iphone/Maps/UI/BottomMenu/Presentation/BottomMenuTransitioning.swift | 5 | 1371 | final class BottomMenuTransitioning: NSObject, UIViewControllerAnimatedTransitioning {
private let isPresentation: Bool
init(isPresentation: Bool) {
self.isPresentation = isPresentation
super.init()
}
func transitionDuration(using _: UIViewControllerContextTransitioning?) -> TimeInterval {
return kDefaultAnimationDuration
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
guard let fromVC = transitionContext.viewController(forKey: .from),
let toVC = transitionContext.viewController(forKey: .to) else { return }
let animatingVC = isPresentation ? toVC : fromVC
guard let animatingView = animatingVC.view else { return }
let finalFrameForVC = transitionContext.finalFrame(for: animatingVC)
var initialFrameForVC = finalFrameForVC
initialFrameForVC.origin.y += initialFrameForVC.size.height
let initialFrame = isPresentation ? initialFrameForVC : finalFrameForVC
let finalFrame = isPresentation ? finalFrameForVC : initialFrameForVC
animatingView.frame = initialFrame
UIView.animate(withDuration: transitionDuration(using: transitionContext),
animations: { animatingView.frame = finalFrame },
completion: { _ in
transitionContext.completeTransition(true)
})
}
}
| apache-2.0 | d2c5607e34baecd7c5eaea0cb247d45a | 38.171429 | 91 | 0.727936 | 6.120536 | false | false | false | false |
prolificinteractive/Yoshi | Yoshi/Yoshi/View Controllers/Debug View Controller/DebugViewController.swift | 1 | 8374 | //
// DebugViewController.swift
// Yoshi
//
// Created by Christopher Jones on 2/8/16.
// Copyright © 2016 Prolific Interactive. All rights reserved.
//
typealias VoidCompletionBlock = () -> Void
/// A debug menu.
final class DebugViewController: UIViewController {
var completionHandler: ((_ completed: VoidCompletionBlock? ) -> Void)?
/// Configures navigation bar and table view header for root Yoshi menu
private let isRootYoshiMenu: Bool
private let tableView = UITableView()
private let options: [YoshiGenericMenu]
private let dateFormatter: DateFormatter = DateFormatter()
init(options: [YoshiGenericMenu], isRootYoshiMenu: Bool, completion: ((VoidCompletionBlock?) -> Void)?) {
self.options = options
self.completionHandler = completion
self.isRootYoshiMenu = isRootYoshiMenu
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func loadView() {
view = UIView()
setupNavigationController()
setupTableView()
}
override func viewDidLoad() {
super.viewDidLoad()
setupDateFormatter()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tableView.reloadData()
}
private func setupTableView() {
view.addSubview(tableView)
tableView.translatesAutoresizingMaskIntoConstraints = false
let topConstraint = NSLayoutConstraint(item: tableView, attribute: .top,
relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1.0, constant: 0.0)
let leadingConstraint = NSLayoutConstraint(item: tableView, attribute: .leading,
relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1.0, constant: 0.0)
let trailingConstraint = NSLayoutConstraint(item: tableView, attribute: .trailing,
relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1.0, constant: 0.0)
let bottomConstraint = NSLayoutConstraint(item: tableView, attribute: .bottom,
relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1.0, constant: 0.0)
view.addConstraints([topConstraint, leadingConstraint, trailingConstraint, bottomConstraint])
tableView.dataSource = self
tableView.delegate = self
if isRootYoshiMenu {
tableView.tableHeaderView = tableViewHeader()
}
registerCellClasses(options: options)
}
private func registerCellClasses(options: [YoshiGenericMenu]) {
var registeredCells = Set<String>()
// Register for each reuse Identifer for once
options.forEach { option in
let reuseIdentifier = type(of:option.cellSource).reuseIdentifier
if let registeredNib = type(of:option.cellSource).nib, !registeredCells.contains(reuseIdentifier) {
registeredCells.insert(reuseIdentifier)
tableView.register(registeredNib, forCellReuseIdentifier: reuseIdentifier)
}
}
}
private func tableViewHeader() -> UIView {
let view = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: 160))
let imageView = UIImageView(image: AppBundleUtility.icon())
view.addSubview(imageView)
imageView.translatesAutoresizingMaskIntoConstraints = false
let centerXConstraint = NSLayoutConstraint(item: imageView, attribute: .centerX,
relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1.0, constant: 0.0)
let topConstraint = NSLayoutConstraint(item: imageView, attribute: .top, relatedBy: .equal,
toItem: view, attribute: .top, multiplier: 1.0, constant: 38.0)
view.addConstraints([centerXConstraint, topConstraint])
let versionLabel = UILabel()
versionLabel.text = AppBundleUtility.appVersionText()
versionLabel.textColor = Color(105, 105, 105).toUIColor()
versionLabel.font = UIFont.systemFont(ofSize: 12)
versionLabel.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(versionLabel)
let labelCenterXConstraint = NSLayoutConstraint(item: versionLabel, attribute: .centerX,
relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1.0, constant: 0.0)
let labelTopConstraint = NSLayoutConstraint(item: versionLabel, attribute: .top, relatedBy: .equal,
toItem: imageView, attribute: .bottom, multiplier: 1.0, constant: 8.0)
view.addConstraints([labelCenterXConstraint, labelTopConstraint])
let separatorLine = UIView()
separatorLine.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(separatorLine)
separatorLine.backgroundColor = tableView.separatorColor
let lineBottomConstraint = NSLayoutConstraint(item: separatorLine, attribute: .bottom,
relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1.0, constant: 0.0)
let lineWidthConstraint = NSLayoutConstraint(item: separatorLine, attribute: .width,
relatedBy: .equal, toItem: view, attribute: .width, multiplier: 1.0, constant: 0.0)
let lineHeightConstraint = NSLayoutConstraint(item: separatorLine, attribute: .height,
relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 0.5)
view.addConstraints([lineBottomConstraint, lineWidthConstraint, lineHeightConstraint])
return view
}
private func setupNavigationController() {
guard isRootYoshiMenu else {
/// Non-root Yoshi menus keep default back button
return
}
let closeButton = UIBarButtonItem(title: "Close",
style: .plain,
target: self,
action: #selector(DebugViewController.close(_:)))
navigationItem.leftBarButtonItem = closeButton
navigationItem.title = AppBundleUtility.appDisplayName()
}
private func setupDateFormatter() {
dateFormatter.dateStyle = .medium
dateFormatter.timeStyle = .short
}
@objc private func close(_ sender: UIBarButtonItem) {
if let completionHandler = completionHandler {
completionHandler(nil)
}
}
private func passCompletionHandler(to viewController: UIViewController) {
if let debugViewController = viewController as? DebugViewController,
let completionHandler = completionHandler,
debugViewController.completionHandler == nil {
debugViewController.completionHandler = completionHandler
}
}
}
extension DebugViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return options.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let option = options[(indexPath as NSIndexPath).row]
let cell = option.cellSource.cellFor(tableView: tableView)
cell.setupCopyToClipBoard()
return cell
}
}
extension DebugViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 64
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let selectedOption = options[(indexPath as NSIndexPath).row]
switch selectedOption.execute() {
case .push(let viewController):
passCompletionHandler(to: viewController)
navigationController?.pushViewController(viewController, animated: true)
case .present(let viewController):
passCompletionHandler(to: viewController)
navigationController?.present(viewController, animated: true)
case .asyncAfterDismissing(let asyncAction):
completionHandler?(asyncAction)
case .pop:
navigationController?.popViewController(animated: true)
default:
return
}
}
}
| mit | 00d87b4e01bddbec40368a1154fe1b70 | 38.871429 | 111 | 0.672877 | 5.312817 | false | false | false | false |
twilio/video-quickstart-swift | ReplayKitExample/ReplayKitExample/ReplayKitVideoSource.swift | 1 | 19853 | //
// ReplayKitVideoSource.swift
// ReplayKitExample
//
// Copyright © 2018-2019 Twilio. All rights reserved.
//
import Accelerate
import CoreMedia
import CoreVideo
import Dispatch
import ReplayKit
import TwilioVideo
class ReplayKitVideoSource: NSObject, VideoSource {
enum TelecineOptions {
/// The source delivers all of the frames that it receives. Format requests might drop frames and limit the encoded frame rate.
case disabled
/// Remove duplicate frames that result when video is drawn directly to the screen and captured using RPBroadcastSampleHandler.
case p30to24or25
/// Remove duplicate frames that result when video is drawn directly to the screen and captured using RPScreenRecorder.
case p60to24or25or30
}
// In order to save memory, the handler may request that the source downscale its output.
static let kDownScaledMaxWidthOrHeight = UInt(886)
static let kDownScaledMaxWidthOrHeightSimulcast = UInt(1280)
// Maximum bitrate (in kbps) used to send video.
static let kMaxVideoBitrate = UInt(1440)
// The simulcast encoder allocates bits for each layer.
static let kMaxVideoBitrateSimulcast = UInt(1180)
static let kMaxScreenshareBitrate = UInt(1600)
// Maximum frame rate to send video at.
static let kMaxVideoFrameRate = UInt(15)
/*
* Streaming video content at 30 fps or lower is ideal, especially in variable network conditions.
* In order to improve the quality of screen sharing, these constants optimize for specific use cases:
*
* 1. App content: Stream at 15 fps to ensure fine details (spatial resolution) are maintained.
* 2. Video content: Attempt to match the natural video cadence between kMinSyncFrameRate <= fps <= kMaxSyncFrameRate.
* 3. Telecined Video content: Some apps perform a telecine by drawing to the screen using more vsyncs than are needed.
* When this occurs, ReplayKit generates duplicate frames, decimating the content further to 30 Hz.
* Duplicate video frames reduce encoder performance, increase cpu usage and lower the quality of the video stream.
* When the source detects telecined content, it attempts an inverse telecine to restore the natural cadence.
*/
static let kMaxSyncFrameRate = UInt(27)
static let kMinSyncFrameRate = UInt(22)
static let kFrameHistorySize = 16
// The minimum average delivery frame rate where IVTC is attempted. Add leeway due to 24 in 30 in 60 case.
static let kInverseTelecineMinimumFrameRate = 23
/*
* Enable retransmission of the last sent frame. This feature consumes some memory, CPU, and bandwidth but it ensures
* that your most recent frame eventually reaches subscribers, and that the publisher has a reasonable bandwidth estimate
* for the next time a new frame is captured.
*/
static let retransmitLastFrame = true
static let kFrameRetransmitIntervalMs = Int(250)
static let kFrameRetransmitTimeInterval = CMTime(value: CMTimeValue(kFrameRetransmitIntervalMs),
timescale: CMTimeScale(1000))
static let kFrameRetransmitDispatchInterval = DispatchTimeInterval.milliseconds(kFrameRetransmitIntervalMs)
static let kFrameRetransmitDispatchLeeway = DispatchTimeInterval.milliseconds(20)
private var telecine: InverseTelecine?
private var telecineInputFrameRate: UInt32
private var screencastUsage: Bool = false
weak var sink: VideoSink?
private var videoFormat: VideoFormat?
private var frameSync: Bool = false
private var frameSyncRestorableFrameRate: UInt?
private var averageDelivered = UInt32(0)
private var recentDelivered = UInt32(0)
// Used to detect a sequence of video frames that have 3:2 pulldown applied
private var lastDeliveredTimestamp: CMTime?
private var recentDeliveredFrameDeltas: [CMTime] = []
private var lastInputTimestamp: CMTime?
private var recentInputFrameDeltas: [CMTime] = []
private var videoQueue: DispatchQueue?
private var timerSource: DispatchSourceTimer?
private var lastTransmitTimestamp: CMTime?
private var lastFrameStorage: VideoFrame?
// ReplayKit reuses the underlying CVPixelBuffer if you release the CMSampleBuffer back to their pool.
// Holding on to the last frame is a poor-man's workaround to prevent image corruption.
private var lastSampleBuffer: CMSampleBuffer?
init(isScreencast: Bool, telecineOptions: TelecineOptions) {
screencastUsage = isScreencast
// The minimum average input frame rate where IVTC is attempted.
switch telecineOptions {
case .p60to24or25or30:
telecine = InverseTelecine60p()
telecineInputFrameRate = 58
break
case .p30to24or25:
telecine = InverseTelecine30p()
telecineInputFrameRate = 28
break
case .disabled:
telecineInputFrameRate = 0
break
}
super.init()
}
public var isScreencast: Bool {
get {
return screencastUsage
}
}
func requestOutputFormat(_ outputFormat: VideoFormat) {
videoFormat = outputFormat
if let sink = sink {
sink.onVideoFormatRequest(videoFormat)
}
}
static private func formatRequestToDownscale(maxWidthOrHeight: UInt, maxFrameRate: UInt) -> VideoFormat {
let outputFormat = VideoFormat()
var screenSize = UIScreen.main.bounds.size
screenSize.width *= UIScreen.main.nativeScale
screenSize.height *= UIScreen.main.nativeScale
if maxWidthOrHeight > 0 {
let downscaledTarget = CGSize(width: Int(maxWidthOrHeight),
height: Int(maxWidthOrHeight))
let fitRect = AVMakeRect(aspectRatio: screenSize,
insideRect: CGRect(origin: CGPoint.zero, size: downscaledTarget)).integral
let outputSize = fitRect.size
outputFormat.dimensions = CMVideoDimensions(width: Int32(outputSize.width), height: Int32(outputSize.height))
} else {
outputFormat.dimensions = CMVideoDimensions(width: Int32(screenSize.width), height: Int32(screenSize.height))
}
outputFormat.frameRate = maxFrameRate
return outputFormat;
}
/// Gets the recommended EncodingParameters and VideoFormat for a specific use case.
///
/// - Parameters:
/// - codec: The video codec that will be preferred to send ReplayKit video frames.
/// - isScreencast: If the content is a screencast or not.
/// - telecineOptions: The options used to process the input frames.
/// - Returns: The EncodingParameters and VideoFormat that are appropriate for the use case.
static public func getParametersForUseCase(codec: VideoCodec, isScreencast: Bool, telecineOptions: TelecineOptions) -> (EncodingParameters, VideoFormat) {
let audioBitrate = UInt(0)
var videoBitrate = kMaxVideoBitrate
var maxWidthOrHeight = isScreencast ? UInt(0) : kDownScaledMaxWidthOrHeight
// TODO: IVTC in broadcast
let maxFrameRate = isScreencast ? kMaxVideoFrameRate : UInt(30)
if let vp8Codec = codec as? Vp8Codec {
videoBitrate = vp8Codec.isSimulcast ? kMaxVideoBitrateSimulcast : kMaxVideoBitrate
if (!isScreencast) {
maxWidthOrHeight = vp8Codec.isSimulcast ? kDownScaledMaxWidthOrHeightSimulcast : kDownScaledMaxWidthOrHeight
}
}
return (EncodingParameters(audioBitrate: audioBitrate, videoBitrate: videoBitrate),
formatRequestToDownscale(maxWidthOrHeight: maxWidthOrHeight, maxFrameRate: maxFrameRate))
}
deinit {
// Perform teardown and free memory on the video queue to ensure that the resources will not be resurrected.
if let captureQueue = self.videoQueue {
captureQueue.sync {
self.timerSource?.cancel()
self.timerSource = nil
self.lastSampleBuffer = nil
}
}
}
/// Provide a frame to the source for processing. This operation might result in the frame being delivered to the sink,
/// dropped, and/or remapped.
///
/// - Parameter sampleBuffer: The new CMSampleBuffer input to process.
public func processFrame(sampleBuffer: CMSampleBuffer) {
guard let sink = self.sink else {
return
}
guard let sourcePixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else {
assertionFailure("SampleBuffer did not have an ImageBuffer")
return
}
// The source only supports NV12 (full-range) buffers.
let pixelFormat = CVPixelBufferGetPixelFormatType(sourcePixelBuffer);
if (pixelFormat != kCVPixelFormatType_420YpCbCr8BiPlanarFullRange) {
assertionFailure("Extension assumes the incoming frames are of type NV12")
return
}
// Discover the dispatch queue that ReplayKit is operating on.
if videoQueue == nil {
videoQueue = ExampleCoreAudioDeviceGetCurrentQueue()
}
var timestamp = CMSampleBufferGetPresentationTimeStamp(sampleBuffer)
// A frame might be dropped if it is a duplicate. This method updates a history and might issue a format request.
if !screencastUsage {
let (result, adjustedTimestamp) = processFrameInput(sampleBuffer: sampleBuffer)
if result == .dropFrame {
return
} else {
timestamp = adjustedTimestamp
}
}
/*
* Check rotation tags. Extensions see these tags, but `RPScreenRecorder` does not appear to set them.
* On iOS 12.0 and 13.0 rotation tags (other than up) are set by extensions.
*/
var videoOrientation = VideoOrientation.up
if let sampleOrientation = CMGetAttachment(sampleBuffer, key: RPVideoSampleOrientationKey as CFString, attachmentModeOut: nil),
let coreSampleOrientation = sampleOrientation.uint32Value {
videoOrientation
= ReplayKitVideoSource.imageOrientationToVideoOrientation(imageOrientation: CGImagePropertyOrientation(rawValue: coreSampleOrientation)!)
}
/*
* Return the original pixel buffer without any downscaling or cropping applied.
* You may use a format request to crop and/or scale the buffers produced by this class.
*/
deliverFrame(to: sink,
timestamp: timestamp,
buffer: sourcePixelBuffer,
orientation: videoOrientation,
forceReschedule: false)
// Hold on to the previous sample buffer to prevent tearing.
lastSampleBuffer = sampleBuffer
}
/// Process a frame, deciding if it should be dropped and remapping the timestamp if needed.
///
/// - Parameter sampleBuffer: A CMSampleBuffer containing a single CVPixelBuffer sample.
/// - Returns: The result of the frame processing, and a frame timestamp that may have been remapped.
private func processFrameInput(sampleBuffer: CMSampleBuffer) -> (TelecineResult, CMTime) {
let currentTimestamp = CMSampleBufferGetPresentationTimeStamp(sampleBuffer)
guard let lastTimestamp = lastInputTimestamp else {
lastInputTimestamp = currentTimestamp
return (.deliverFrame, currentTimestamp)
}
lastInputTimestamp = currentTimestamp
let delta = CMTimeSubtract(currentTimestamp, lastTimestamp)
// Update input stats.
if recentInputFrameDeltas.count == ReplayKitVideoSource.kFrameHistorySize {
recentInputFrameDeltas.removeFirst()
}
recentInputFrameDeltas.append(delta)
var total = CMTime.zero
for dataPoint in recentInputFrameDeltas {
total = CMTimeAdd(total, dataPoint)
}
let averageInput = Int32(round(Double(recentInputFrameDeltas.count) / total.seconds))
if frameSync == false,
averageDelivered >= ReplayKitVideoSource.kMinSyncFrameRate,
averageDelivered <= ReplayKitVideoSource.kMaxSyncFrameRate,
recentDelivered >= ReplayKitVideoSource.kMinSyncFrameRate,
recentDelivered <= ReplayKitVideoSource.kMaxSyncFrameRate,
videoFormat?.frameRate ?? ReplayKitVideoSource.kMaxSyncFrameRate < ReplayKitVideoSource.kMaxSyncFrameRate {
frameSync = true
if let format = videoFormat {
frameSyncRestorableFrameRate = format.frameRate
format.frameRate = UInt(ReplayKitVideoSource.kMaxSyncFrameRate + 1)
requestOutputFormat(format)
}
print("Frame sync detected at rate: \(averageDelivered)")
} else if frameSync,
averageDelivered < ReplayKitVideoSource.kMinSyncFrameRate || averageDelivered > ReplayKitVideoSource.kMaxSyncFrameRate {
frameSync = false
if let format = videoFormat {
format.frameRate = frameSyncRestorableFrameRate ?? ReplayKitVideoSource.kMaxVideoFrameRate
requestOutputFormat(format)
frameSyncRestorableFrameRate = nil
}
print("Frame sync stopped at rate: \(averageDelivered)")
}
if let telecine = telecine,
averageInput >= telecineInputFrameRate {
if let lastSample = lastSampleBuffer {
return telecine.process(input: sampleBuffer, last: lastSample)
}
}
return (.deliverFrame, currentTimestamp)
}
private func deliverFrame(to: VideoSink, timestamp: CMTime, buffer: CVPixelBuffer, orientation: VideoOrientation, forceReschedule: Bool) {
guard let frame = VideoFrame(timestamp: timestamp,
buffer: buffer,
orientation: orientation) else {
assertionFailure("Couldn't create a VideoFrame with a valid CVPixelBuffer.")
return
}
to.onVideoFrame(frame)
// Frame retransmission logic.
if (ReplayKitVideoSource.retransmitLastFrame) {
lastFrameStorage = frame
lastTransmitTimestamp = CMClockGetTime(CMClockGetHostTimeClock())
dispatchRetransmissions(forceReschedule: forceReschedule)
}
// Update delivery stats
if let lastTimestamp = lastDeliveredTimestamp,
!screencastUsage {
let delta = CMTimeSubtract(timestamp, lastTimestamp)
if recentDeliveredFrameDeltas.count == ReplayKitVideoSource.kFrameHistorySize {
recentDeliveredFrameDeltas.removeFirst()
}
recentDeliveredFrameDeltas.append(delta)
var total = CMTime.zero
for dataPoint in recentDeliveredFrameDeltas {
total = CMTimeAdd(total, dataPoint)
}
// Frames with older timestamps might be delivered by ReplayKit causing the result to be negative.
averageDelivered = UInt32(abs(round(Double(recentDeliveredFrameDeltas.count) / total.seconds)))
var recent = CMTime.zero
if recentDeliveredFrameDeltas.count >= 4 {
recent = CMTimeAdd(recent, recentDeliveredFrameDeltas.last!)
recent = CMTimeAdd(recent, recentDeliveredFrameDeltas[recentDeliveredFrameDeltas.count - 2])
recent = CMTimeAdd(recent, recentDeliveredFrameDeltas[recentDeliveredFrameDeltas.count - 3])
recent = CMTimeAdd(recent, recentDeliveredFrameDeltas[recentDeliveredFrameDeltas.count - 4])
recentDelivered = UInt32( abs(round(Double(4) / recent.seconds)))
}
}
lastDeliveredTimestamp = timestamp
}
private func dispatchRetransmissions(forceReschedule: Bool) {
if let source = timerSource,
source.isCancelled == false,
forceReschedule == false {
// No work to do, wait for the next timer to fire and re-evaluate.
return
}
// We require a queue to create a timer source.
guard let currentQueue = videoQueue else {
return
}
let source = DispatchSource.makeTimerSource(flags: DispatchSource.TimerFlags.strict,
queue: currentQueue)
timerSource = source
// Generally, this timer is invoked in kFrameRetransmitDispatchInterval when no frames are sent.
source.setEventHandler(handler: {
if let frame = self.lastFrameStorage,
let sink = self.sink,
let lastHostTimestamp = self.lastTransmitTimestamp {
let currentTimestamp = CMClockGetTime(CMClockGetHostTimeClock())
let delta = CMTimeSubtract(currentTimestamp, lastHostTimestamp)
if delta >= ReplayKitVideoSource.kFrameRetransmitTimeInterval {
#if DEBUG
print("Delivering frame since send delta is greather than threshold. delta=", delta.seconds)
#endif
// Reconstruct a new timestamp, advancing by our relative read of host time.
self.deliverFrame(to: sink,
timestamp: CMTimeAdd(frame.timestamp, delta),
buffer: frame.imageBuffer,
orientation: frame.orientation,
forceReschedule: true)
} else {
// Reschedule for when the next retransmission might be required.
let remaining = ReplayKitVideoSource.kFrameRetransmitTimeInterval.seconds - delta.seconds
let deadline = DispatchTime.now() + DispatchTimeInterval.milliseconds(Int(remaining * 1000.0))
self.timerSource?.schedule(deadline: deadline, leeway: ReplayKitVideoSource.kFrameRetransmitDispatchLeeway)
}
}
})
// Thread safe cleanup of temporary storage, in case of cancellation. Normally, we reschedule.
source.setCancelHandler(handler: {
self.lastFrameStorage = nil
})
// Schedule a first time source for the full interval.
let deadline = DispatchTime.now() + ReplayKitVideoSource.kFrameRetransmitDispatchInterval
source.schedule(deadline: deadline, leeway: ReplayKitVideoSource.kFrameRetransmitDispatchLeeway)
source.activate()
}
private static func imageOrientationToVideoOrientation(imageOrientation: CGImagePropertyOrientation) -> VideoOrientation {
let videoOrientation: VideoOrientation
// Note: The source does not attempt to "undo" mirroring. So far I have not encountered mirrored tags from ReplayKit sources.
switch imageOrientation {
case .up:
videoOrientation = VideoOrientation.up
case .upMirrored:
videoOrientation = VideoOrientation.up
case .left:
videoOrientation = VideoOrientation.left
case .leftMirrored:
videoOrientation = VideoOrientation.left
case .right:
videoOrientation = VideoOrientation.right
case .rightMirrored:
videoOrientation = VideoOrientation.right
case .down:
videoOrientation = VideoOrientation.down
case .downMirrored:
videoOrientation = VideoOrientation.down
}
return videoOrientation
}
}
| mit | 7f3df4655f89218b4df7490faaf9a99a | 44.220957 | 158 | 0.660336 | 5.268577 | false | false | false | false |
icanzilb/EasyAnimation | EasyAnimation/EasyAnimation.swift | 1 | 22413 | //
// EasyAnimation.swift
//
// Created by Marin Todorov on 4/11/15.
// Copyright (c) 2015-present Underplot ltd. All rights reserved.
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import ObjectiveC
// MARK: EA private structures
private struct PendingAnimation {
let layer: CALayer
let keyPath: String
let fromValue: Any
}
private class AnimationContext {
var duration: TimeInterval = 1.0
var currentTime: TimeInterval = {CACurrentMediaTime()}()
var delay: TimeInterval = 0.0
var options: UIView.AnimationOptions? = nil
var pendingAnimations = [PendingAnimation]()
//spring additions
var springDamping: CGFloat = 0.0
var springVelocity: CGFloat = 0.0
var nrOfUIKitAnimations: Int = 0
}
private class CompletionBlock {
var context: AnimationContext
var completion: ((Bool) -> Void)
var nrOfExecutions: Int = 0
init(context c: AnimationContext, completion cb: @escaping (Bool) -> Void) {
context = c
completion = cb
}
func wrapCompletion(_ completed: Bool) {
// if no uikit animations uikit calls completion immediately
nrOfExecutions+=1
if context.nrOfUIKitAnimations > 0 ||
//if no layer animations DO call completion
context.pendingAnimations.count == 0 ||
//skip every other call if no uikit and there are layer animations
//(e.g. jump over the first immediate uikit call to completion)
nrOfExecutions % 2 == 0 {
completion(completed)
}
}
}
@objc public class EasyAnimation: NSObject {
static fileprivate var activeAnimationContexts = [AnimationContext]()
@discardableResult
override init() { }
public static func enable() {
_ = swizzle
}
static private let swizzle: Void = {
UIView.replaceAnimationMethods()
CALayer.replaceAnimationMethods()
}()
}
// MARK: EA animatable properties
private let vanillaLayerKeys = [
"anchorPoint", "backgroundColor", "borderColor", "borderWidth", "bounds",
"contentsRect", "cornerRadius",
"opacity", "position",
"shadowColor", "shadowOffset", "shadowOpacity", "shadowRadius",
"sublayerTransform", "transform", "zPosition"
]
private let specializedLayerKeys: [String: [String]] = [
CAEmitterLayer.self.description(): ["emitterPosition", "emitterZPosition", "emitterSize", "spin", "velocity", "birthRate", "lifetime"],
CAGradientLayer.self.description(): ["colors", "locations", "endPoint", "startPoint"],
CAReplicatorLayer.self.description(): ["instanceDelay", "instanceTransform", "instanceColor", "instanceRedOffset", "instanceGreenOffset", "instanceBlueOffset", "instanceAlphaOffset"],
CAShapeLayer.self.description(): ["path", "fillColor", "lineDashPhase", "lineWidth", "miterLimit", "strokeColor", "strokeStart", "strokeEnd"],
CATextLayer.self.description(): ["fontSize", "foregroundColor"]
]
public extension UIView.AnimationOptions {
//CA Fill modes
static let fillModeNone = UIView.AnimationOptions(rawValue: 0)
static let fillModeForwards = UIView.AnimationOptions(rawValue: 1024)
static let fillModeBackwards = UIView.AnimationOptions(rawValue: 2048)
static let fillModeBoth = UIView.AnimationOptions(rawValue: 1024 + 2048)
//CA Remove on completion
static let isRemovedOnCompletion = UIView.AnimationOptions(rawValue: 0)
static let isNotRemovedOnCompletion = UIView.AnimationOptions(rawValue: 16384)
}
/**
A `UIView` extension that adds super powers to animateWithDuration:animations: and the like.
Check the README for code examples of what features this extension adds.
*/
extension UIView {
// MARK: UIView animation & action methods
fileprivate static func replaceAnimationMethods() {
//replace actionForLayer...
if
let origMethod = class_getInstanceMethod(self, #selector(UIView.action(for:forKey:))),
let eaMethod = class_getInstanceMethod(self, #selector(UIView.EA_actionForLayer(_:forKey:))) {
method_exchangeImplementations(origMethod, eaMethod)
}
//replace animateWithDuration...
if
let origMethod = class_getClassMethod(self, #selector(UIView.animate(withDuration:animations:))),
let eaMethod = class_getClassMethod(self, #selector(UIView.EA_animate(withDuration:animations:))) {
method_exchangeImplementations(origMethod, eaMethod)
}
if
let origMethod = class_getClassMethod(self, #selector(UIView.animate(withDuration:animations:completion:))),
let eaMethod = class_getClassMethod(self, #selector(UIView.EA_animate(withDuration:animations:completion:))) {
method_exchangeImplementations(origMethod, eaMethod)
}
if
let origMethod = class_getClassMethod(self, #selector(UIView.animate(withDuration:delay:options:animations:completion:))),
let eaMethod = class_getClassMethod(self, #selector(UIView.EA_animate(withDuration:delay:options:animations:completion:))) {
method_exchangeImplementations(origMethod, eaMethod)
}
if
let origMethod = class_getClassMethod(self, #selector(UIView.animate(withDuration:delay:usingSpringWithDamping:initialSpringVelocity:options:animations:completion:))),
let eaMethod = class_getClassMethod(self, #selector(UIView.EA_animate(withDuration:delay:usingSpringWithDamping:initialSpringVelocity:options:animations:completion:))) {
method_exchangeImplementations(origMethod, eaMethod)
}
}
@objc
func EA_actionForLayer(_ layer: CALayer!, forKey key: String!) -> CAAction! {
let result = EA_actionForLayer(layer, forKey: key)
if let activeContext = EasyAnimation.activeAnimationContexts.last {
if let _ = result as? NSNull {
if vanillaLayerKeys.contains(key) ||
(specializedLayerKeys[layer.classForCoder.description()] != nil && specializedLayerKeys[layer.classForCoder.description()]!.contains(key)) {
var currentKeyValue = layer.value(forKey: key)
//exceptions
if currentKeyValue == nil && key.hasSuffix("Color") {
currentKeyValue = UIColor.clear.cgColor
}
//found an animatable property - add the pending animation
if let currentKeyValue = currentKeyValue {
activeContext.pendingAnimations.append(
PendingAnimation(layer: layer, keyPath: key, fromValue: currentKeyValue)
)
}
}
} else {
activeContext.nrOfUIKitAnimations+=1
}
}
return result
}
@objc
class func EA_animate(withDuration duration: TimeInterval, delay: TimeInterval, usingSpringWithDamping dampingRatio: CGFloat, initialSpringVelocity velocity: CGFloat, options: UIView.AnimationOptions, animations: () -> Void, completion: ((Bool) -> Void)?) {
//create context
let context = AnimationContext()
context.duration = duration
context.delay = delay
context.options = options
context.springDamping = dampingRatio
context.springVelocity = velocity
//push context
EasyAnimation.activeAnimationContexts.append(context)
//enable layer actions
CATransaction.begin()
CATransaction.setDisableActions(false)
var completionBlock: CompletionBlock? = nil
//spring animations
if let completion = completion {
//wrap a completion block
completionBlock = CompletionBlock(context: context, completion: completion)
EA_animate(withDuration: duration, delay: delay, usingSpringWithDamping: dampingRatio, initialSpringVelocity: velocity, options: options, animations: animations, completion: completionBlock!.wrapCompletion)
} else {
//simply schedule the animation
EA_animate(withDuration: duration, delay: delay, usingSpringWithDamping: dampingRatio, initialSpringVelocity: velocity, options: options, animations: animations, completion: nil)
}
//pop context
EasyAnimation.activeAnimationContexts.removeLast()
//run pending animations
for anim in context.pendingAnimations {
anim.layer.add(EA_animation(anim, context: context), forKey: nil)
}
CATransaction.commit()
}
@objc
class func EA_animate(withDuration duration: TimeInterval, delay: TimeInterval, options: UIView.AnimationOptions, animations: () -> Void, completion: ((Bool) -> Void)?) {
//create context
let context = AnimationContext()
context.duration = duration
context.delay = delay
context.options = options
//push context
EasyAnimation.activeAnimationContexts.append(context)
//enable layer actions
CATransaction.begin()
CATransaction.setDisableActions(false)
var completionBlock: CompletionBlock? = nil
//animations
if let completion = completion {
//wrap a completion block
completionBlock = CompletionBlock(context: context, completion: completion)
EA_animate(withDuration: duration, delay: delay, options: options, animations: animations, completion: completionBlock!.wrapCompletion)
} else {
//simply schedule the animation
EA_animate(withDuration: duration, delay: delay, options: options, animations: animations, completion: nil)
}
//pop context
EasyAnimation.activeAnimationContexts.removeLast()
//run pending animations
for anim in context.pendingAnimations {
//print("pending: \(anim.keyPath) from \(anim.fromValue) to \(anim.layer.value(forKeyPath: anim.keyPath))")
anim.layer.add(EA_animation(anim, context: context), forKey: nil)
}
//try a timer now, than see about animation delegate
if let completionBlock = completionBlock, context.nrOfUIKitAnimations == 0, context.pendingAnimations.count > 0 {
Timer.scheduledTimer(timeInterval: context.duration, target: self, selector: #selector(UIView.EA_wrappedCompletionHandler(_:)), userInfo: completionBlock, repeats: false)
}
CATransaction.commit()
}
@objc
class func EA_animate(withDuration duration: TimeInterval, animations: @escaping () -> Void, completion: ((Bool) -> Void)?) {
animate(withDuration: duration, delay: 0.0, options: [], animations: animations, completion: completion)
}
@objc
class func EA_animate(withDuration duration: TimeInterval, animations: @escaping () -> Void) {
animate(withDuration: duration, animations: animations, completion: nil)
}
@objc
class func EA_wrappedCompletionHandler(_ timer: Timer) {
if let completionBlock = timer.userInfo as? CompletionBlock {
completionBlock.wrapCompletion(true)
}
}
// MARK: create CA animation
private class func EA_animation(_ pending: PendingAnimation, context: AnimationContext) -> CAAnimation {
let anim: CAAnimation
if (context.springDamping > 0.0) {
//create a layer spring animation
if #available(iOS 9, *) { // iOS9!
anim = CASpringAnimation(keyPath: pending.keyPath)
if let anim = anim as? CASpringAnimation {
anim.fromValue = pending.fromValue
anim.toValue = pending.layer.value(forKey: pending.keyPath)
let epsilon = 0.001
anim.damping = CGFloat(-2.0 * log(epsilon) / context.duration)
anim.stiffness = CGFloat(pow(anim.damping, 2)) / CGFloat(pow(context.springDamping * 2, 2))
anim.mass = 1.0
anim.initialVelocity = 0.0
}
} else {
anim = RBBSpringAnimation(keyPath: pending.keyPath)
if let anim = anim as? RBBSpringAnimation {
anim.from = pending.fromValue
anim.to = pending.layer.value(forKey: pending.keyPath)
//TODO: refine the spring animation setup
//lotta magic numbers to mimic UIKit springs
let epsilon = 0.001
anim.damping = -2.0 * log(epsilon) / context.duration
anim.stiffness = Double(pow(anim.damping, 2)) / Double(pow(context.springDamping * 2, 2))
anim.mass = 1.0
anim.velocity = 0.0
}
}
} else {
//create property animation
anim = CABasicAnimation(keyPath: pending.keyPath)
(anim as! CABasicAnimation).fromValue = pending.fromValue
(anim as! CABasicAnimation).toValue = pending.layer.value(forKey: pending.keyPath)
}
anim.duration = context.duration
if context.delay > 0.0 {
anim.beginTime = context.currentTime + context.delay
anim.fillMode = CAMediaTimingFillMode.backwards
}
//options
if let options = context.options?.rawValue {
if options & UIView.AnimationOptions.beginFromCurrentState.rawValue == 0 { //only repeat if not in a chain
anim.autoreverses = (options & UIView.AnimationOptions.autoreverse.rawValue == UIView.AnimationOptions.autoreverse.rawValue)
anim.repeatCount = (options & UIView.AnimationOptions.repeat.rawValue == UIView.AnimationOptions.repeat.rawValue) ? Float.infinity : 0
}
//easing
var timingFunctionName = CAMediaTimingFunctionName.easeInEaseOut
if options & UIView.AnimationOptions.curveLinear.rawValue == UIView.AnimationOptions.curveLinear.rawValue {
//first check for linear (it's this way to take up only 2 bits)
timingFunctionName = CAMediaTimingFunctionName.linear
} else if options & UIView.AnimationOptions.curveEaseIn.rawValue == UIView.AnimationOptions.curveEaseIn.rawValue {
timingFunctionName = CAMediaTimingFunctionName.easeIn
} else if options & UIView.AnimationOptions.curveEaseOut.rawValue == UIView.AnimationOptions.curveEaseOut.rawValue {
timingFunctionName = CAMediaTimingFunctionName.easeOut
}
anim.timingFunction = CAMediaTimingFunction(name: timingFunctionName)
//fill mode
if options & UIView.AnimationOptions.fillModeBoth.rawValue == UIView.AnimationOptions.fillModeBoth.rawValue {
//both
anim.fillMode = CAMediaTimingFillMode.both
} else if options & UIView.AnimationOptions.fillModeForwards.rawValue == UIView.AnimationOptions.fillModeForwards.rawValue {
//forward
anim.fillMode = (anim.fillMode == CAMediaTimingFillMode.backwards) ? CAMediaTimingFillMode.both : CAMediaTimingFillMode.forwards
} else if options & UIView.AnimationOptions.fillModeBackwards.rawValue == UIView.AnimationOptions.fillModeBackwards.rawValue {
//backwards
anim.fillMode = CAMediaTimingFillMode.backwards
}
//is removed on completion
if options & UIView.AnimationOptions.isNotRemovedOnCompletion.rawValue == UIView.AnimationOptions.isNotRemovedOnCompletion.rawValue {
anim.isRemovedOnCompletion = false
} else {
anim.isRemovedOnCompletion = true
}
}
return anim
}
// MARK: chain animations
/**
Creates and runs an animation which allows other animations to be chained to it and to each other.
:param: duration The animation duration in seconds
:param: delay The delay before the animation starts
:param: options A UIViewAnimationOptions bitmask (check UIView.animationWithDuration:delay:options:animations:completion: for more info)
:param: animations Animation closure
:param: completion Completion closure of type (Bool)->Void
:returns: The created request.
*/
public class func animateAndChain(withDuration duration: TimeInterval, delay: TimeInterval, options: UIView.AnimationOptions, animations: @escaping () -> Void, completion: ((Bool) -> Void)?) -> EAAnimationFuture {
let currentAnimation = EAAnimationFuture()
currentAnimation.duration = duration
currentAnimation.delay = delay
currentAnimation.options = options
currentAnimation.animations = animations
currentAnimation.completion = completion
currentAnimation.nextDelayedAnimation = EAAnimationFuture()
currentAnimation.nextDelayedAnimation!.prevDelayedAnimation = currentAnimation
currentAnimation.run()
EAAnimationFuture.animations.append(currentAnimation)
return currentAnimation.nextDelayedAnimation!
}
/**
Creates and runs an animation which allows other animations to be chained to it and to each other.
:param: duration The animation duration in seconds
:param: delay The delay before the animation starts
:param: usingSpringWithDamping the spring damping
:param: initialSpringVelocity initial velocity of the animation
:param: options A UIViewAnimationOptions bitmask (check UIView.animationWithDuration:delay:options:animations:completion: for more info)
:param: animations Animation closure
:param: completion Completion closure of type (Bool)->Void
:returns: The created request.
*/
public class func animateAndChain(withDuration duration: TimeInterval, delay: TimeInterval, usingSpringWithDamping dampingRatio: CGFloat, initialSpringVelocity velocity: CGFloat, options: UIView.AnimationOptions, animations: @escaping () -> Void, completion: ((Bool) -> Void)?) -> EAAnimationFuture {
let currentAnimation = EAAnimationFuture()
currentAnimation.duration = duration
currentAnimation.delay = delay
currentAnimation.options = options
currentAnimation.animations = animations
currentAnimation.completion = completion
currentAnimation.springDamping = dampingRatio
currentAnimation.springVelocity = velocity
currentAnimation.nextDelayedAnimation = EAAnimationFuture()
currentAnimation.nextDelayedAnimation!.prevDelayedAnimation = currentAnimation
currentAnimation.run()
EAAnimationFuture.animations.append(currentAnimation)
return currentAnimation.nextDelayedAnimation!
}
}
extension CALayer {
// MARK: CALayer animations
fileprivate static func replaceAnimationMethods() {
//replace actionForKey
if
let origMethod = class_getInstanceMethod(self, #selector(CALayer.action(forKey:))),
let eaMethod = class_getInstanceMethod(self, #selector(CALayer.EA_action(forKey:))) {
method_exchangeImplementations(origMethod, eaMethod)
}
}
@objc
public func EA_action(forKey key: String!) -> CAAction! {
//check if the layer has a view-delegate
if let _ = delegate as? UIView {
return EA_action(forKey: key) // -> this passes the ball to UIView.actionForLayer:forKey:
}
//create a custom easy animation and add it to the animation stack
if let activeContext = EasyAnimation.activeAnimationContexts.last,
vanillaLayerKeys.contains(key) ||
(specializedLayerKeys[self.classForCoder.description()] != nil &&
specializedLayerKeys[self.classForCoder.description()]!.contains(key)) {
var currentKeyValue = value(forKey: key)
//exceptions
if currentKeyValue == nil && key.hasSuffix("Color") {
currentKeyValue = UIColor.clear.cgColor
}
//found an animatable property - add the pending animation
if let currentKeyValue = currentKeyValue {
activeContext.pendingAnimations.append(
PendingAnimation(layer: self, keyPath: key, fromValue: currentKeyValue
)
)
}
}
return nil
}
}
| mit | 18a72ae6ddb02f181a2d3c31ea0b2f56 | 43.207101 | 304 | 0.639941 | 5.483974 | false | false | false | false |
nicolaslangley/blackfoot-dictionary-ios | BlackfootDictionary/Controllers/ResultViewController.swift | 1 | 1188 | //
// ResultViewController.swift
// BlackfootDictionary
//
// Created by Nicolas Langley on 1/4/16.
// Copyright © 2016 Hierarchy. All rights reserved.
//
import UIKit
class ResultViewController: UIViewController {
// MARK: Properties
@IBOutlet weak var blackfootWordLabel: UILabel!
@IBOutlet weak var englishGlossTextView: UITextView!
@IBOutlet weak var ipaStringTextView: UITextView!
var blackfootWord: String = ""
var englishGloss: String = ""
var ipaString: String = ""
override func viewDidLoad() {
super.viewDidLoad()
ipaString = TranslationEngineWrapper.convertToIPA(blackfootWord)
englishGlossTextView.text = englishGloss
ipaStringTextView.text = ipaString
blackfootWordLabel.text = blackfootWord
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any!) {
// Action to perform for moving to another view
}
}
| mit | d40ea2d858365738a21a00d8f5ff6a5a | 28.675 | 80 | 0.684078 | 4.78629 | false | false | false | false |
quilnib/zugzug | Zug Zug/Character.swift | 1 | 1483 | //
// Character.swift
// Zug Zug
//
// Created by Timothy Walsh on 2/9/15.
// Copyright (c) 2015 com.ClassicTim. All rights reserved.
//
import Foundation
import UIKit
struct Character {
var affiliation: String?
var icon: UIImage?
var name: String?
var soundsArray: [String] = []
init(index: Int) {
let allCharacterDictionary = AllCharactersDictionary()
let characterDictionary = allCharacterDictionary.characterList[index]
self.affiliation = characterDictionary["affiliation"] as String!
let iconName = characterDictionary["icon"] as String!
self.icon = UIImage(named: iconName)
self.name = characterDictionary["characterName"] as String!
self.soundsArray += characterDictionary["soundsArray"] as [String]
}
init(#affiliation: String, #icon: String, #name: String, soundsArray: [String] )// allow characters to be created without having to reference AllCharactersDictionary
{
self.affiliation = affiliation
self.icon = UIImage(named: icon)
self.name = name
self.soundsArray += soundsArray
}
func returnRandomSound() -> String {
var soundCount = UInt32(soundsArray.count)
var unsignedRandomNumber = arc4random_uniform(soundCount)
var randomNumber = Int(unsignedRandomNumber)
return soundsArray[randomNumber]
}
}
| mit | 0f56b55b768df5123633e1d8aef62672 | 27.519231 | 169 | 0.636548 | 4.619938 | false | false | false | false |
csnu17/My-Blognone-apps | myblognone/Modules/NewsList/User Interface/View/NewsListTableViewCell.swift | 1 | 1056 | //
// NewsListTableViewCell.swift
// myblognone
//
// Created by Kittisak Phetrungnapha on 12/21/2559 BE.
// Copyright © 2559 Kittisak Phetrungnapha. All rights reserved.
//
import UIKit
class NewsListTableViewCell: UITableViewCell {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var creatorLabel: UILabel!
@IBOutlet weak var dateTimeLabel: UILabel!
static let identifier = "NewsListTableViewCell"
override func awakeFromNib() {
super.awakeFromNib()
titleLabel.font = UIFont.fontForNewsTitle()
creatorLabel.font = UIFont.fontForNewsCreator()
dateTimeLabel.font = UIFont.fontForNewsPubDate()
let bgColorView = UIView(frame: frame)
bgColorView.backgroundColor = UIColor(hexString: UIColor.highLightNewsListCellBackground)
selectedBackgroundView = bgColorView
}
func setup(with news: News) {
titleLabel.text = news.title
creatorLabel.text = news.creator
dateTimeLabel.text = news.pubDate
}
}
| mit | 860264a0881c9d601a5faecb099c6fd5 | 27.513514 | 97 | 0.68436 | 4.773756 | false | false | false | false |
apple/swift-algorithms | Tests/SwiftAlgorithmsTests/UniqueTests.swift | 1 | 1783 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Algorithms open source project
//
// Copyright (c) 2020 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
//
//===----------------------------------------------------------------------===//
import XCTest
import Algorithms
final class UniqueTests: XCTestCase {
func testUnique() {
let a = repeatElement(1...10, count: 15).joined().shuffled()
let b = a.uniqued()
XCTAssertEqual(b.sorted(), Set(a).sorted())
XCTAssertEqual(10, Array(b).count)
let c: [Int] = []
XCTAssertEqualSequences(c.uniqued(), [])
let d = Array(repeating: 1, count: 10)
XCTAssertEqualSequences(d.uniqued(), [1])
}
func testUniqueOn() {
let a = ["Albemarle", "Abeforth", "Astrology", "Brandywine", "Beatrice", "Axiom"]
let b = a.uniqued(on: { $0.first })
XCTAssertEqual(["Albemarle", "Brandywine"], b)
let c: [Int] = []
XCTAssertEqual(c.uniqued(on: { $0.bitWidth }), [])
let d = Array(repeating: "Andromeda", count: 10)
XCTAssertEqualSequences(d.uniqued(on: { $0.first }), ["Andromeda"])
}
func testLazyUniqueOn() {
let a = ["Albemarle", "Abeforth", "Astrology", "Brandywine", "Beatrice", "Axiom"]
let b = a.lazy.uniqued(on: { $0.first })
XCTAssertEqualSequences(b, ["Albemarle", "Brandywine"])
XCTAssertLazySequence(b)
let c: [Int] = []
XCTAssertEqualSequences(c.lazy.uniqued(on: { $0.bitWidth }), [])
let d = Array(repeating: "Andromeda", count: 10)
XCTAssertEqualSequences(d.lazy.uniqued(on: { $0.first }), ["Andromeda"])
}
}
| apache-2.0 | 735083429174559a849b8f3526961968 | 32.641509 | 85 | 0.579361 | 3.69917 | false | true | false | false |
wefiftytwo/xcrmsimdup | xcrmsimdup/main.swift | 1 | 8332 | //
// main.swift
// xcrmsimdup
//
// Created by Dmitry Victorov on 09/08/15.
// Copyright (c) 2015 fiftytwo. All rights reserved.
//
import Foundation
// MARK: Data types
struct Section
{
var name: String
var rangeTitle: Range<String.Index>
var rangeData: Range<String.Index>
}
struct Device
{
var name: String
var id: String
var status: String
}
// MARK: Functions
func printUsage()
{
println(
"Usage: xcrmsimdup [options]\n" +
"\n" +
"Find duplicated simulator records from the active developer directory listed\n" +
"by command `xcrun simctl list` and remove duplicates using\n" +
"`xcrun simctl delete`.\n" +
"\n" +
"The active developer directory can be set using `xcode-select`, or via the\n" +
"DEVELOPER_DIR environment variable. See the xcrun and xcode-select manual\n" +
"pages for more information.\n" +
"\n" +
"Options:\n" +
" -h, --help show this help message and exit\n" +
" -d, --delete delete duplicates\n" +
" -s, --show just show duplicates, but don't touch them"
);
}
func executeWithBash(command: String) -> (status: Int32, output: String)
{
var task = NSTask()
var outputPipe = NSPipe()
var outputFileHandle = outputPipe.fileHandleForReading
task.launchPath = "/bin/bash"
task.arguments = ["-c", command]
task.standardOutput = outputPipe
task.standardError = outputPipe
task.launch()
var outputData = outputFileHandle.readDataToEndOfFile()
task.waitUntilExit()
var output = NSString(data: outputData, encoding: NSUTF8StringEncoding) as! String
return (task.terminationStatus, output)
}
func sectionsFromString(string: String, prefix: String, suffix: String, range: Range<String.Index>? = nil) -> Array<Section>?
{
var startIndex: String.Index
var endIndex: String.Index
if range == nil
{
startIndex = string.startIndex
endIndex = string.endIndex
}
else
{
startIndex = range!.startIndex
endIndex = range!.endIndex
}
var sections = [Section]()
while let prefixFound = string.rangeOfString(prefix, range: startIndex..<endIndex)
{
if let suffixFound = string.rangeOfString(suffix, range: prefixFound.endIndex..<endIndex)
{
var section = Section(
name: string.substringWithRange(prefixFound.endIndex..<suffixFound.startIndex),
rangeTitle: prefixFound.startIndex..<suffixFound.endIndex,
rangeData: suffixFound.endIndex..<endIndex
)
sections.append(section)
startIndex = suffixFound.endIndex;
}
else
{
return nil;
}
}
for var i = sections.count - 2; i >= 0; i--
{
sections[i].rangeData.endIndex = sections[i + 1].rangeTitle.startIndex
}
return sections
}
func intFromStringIndex(string: String, index: String.Index) -> Int
{
let utf16 = string.utf16;
let utf16Index = index.samePositionIn(utf16)
return distance(utf16.startIndex, utf16Index)
}
func NSRangeFromStringRange(string: String, range: Range<String.Index>) -> NSRange
{
let utf16Start = intFromStringIndex(string, range.startIndex)
let utf16End = intFromStringIndex(string, range.endIndex)
let utf16length = distance(utf16Start, utf16End)
return NSRange(location: utf16Start, length: utf16length)
}
func stringIndexFromInt(string: String, index: Int) -> String.Index?
{
let utf16 = string.utf16
let utf16Index = advance(utf16.startIndex, index, utf16.endIndex)
return utf16Index.samePositionIn(string)
}
func stringRangeFromNSRange(string: String, nsRange: NSRange) -> Range<String.Index>?
{
if nsRange.location == NSNotFound
{
return nil
}
if let start = stringIndexFromInt(string, nsRange.location),
end = stringIndexFromInt(string, nsRange.location + nsRange.length)
{
return start..<end
}
return nil
}
func devicesFromRuntimeSection(string: String, runtimeSection: Section) -> Dictionary< String, Array<Device> >
{
var devices = [String: Array<Device>]();
let regexPattern = "^ +(.+?) \\(([0-9a-fA-F\\-]{36})\\) \\((.+?)\\)$"
var regex = NSRegularExpression(pattern: regexPattern, options: .AnchorsMatchLines, error: nil)!
var nsRange = NSRangeFromStringRange(string, runtimeSection.rangeData)
var matches = regex.matchesInString(string, options: nil, range: nsRange)
for match in matches
{
if let nameRange = stringRangeFromNSRange(string, match.rangeAtIndex(1)),
idRange = stringRangeFromNSRange(string, match.rangeAtIndex(2)),
statusRange = stringRangeFromNSRange(string, match.rangeAtIndex(3))
{
let device = Device(
name: string.substringWithRange(nameRange),
id: string.substringWithRange(idRange),
status: string.substringWithRange(statusRange))
if var devicesList = devices[device.name]
{
devicesList.append(device);
devices[device.name] = devicesList;
}
else
{
devices[device.name] = [device];
}
}
}
return devices;
}
func processDuplicatesInSection(string: String, section: Section, isShowOnly: Bool) -> Bool
{
if let runtimes = sectionsFromString(string, "-- ", " --\n", range: section.rangeData)
{
for runtime in runtimes
{
let devices = devicesFromRuntimeSection(string, runtime)
println("Processing environment \(runtime.name)")
for device in devices
{
if device.1.count < 1
{
println(" No device records found for \(device.0), probably bug in parser")
}
else if device.1.count == 1
{
println(" No duplicats found for \(device.1[0].name) (\(device.1[0].id))")
}
else
{
println(" Duplicates found for \(device.1[0].name) (\(device.1[0].id))")
for var i = 1; i < device.1.count; i++
{
if isShowOnly
{
println(" \(device.1[i].id)")
}
else
{
let deleteStatus = executeWithBash("xcrun simctl delete " + device.1[i].id)
if deleteStatus.status == 0
{
println(" \(device.1[i].id) DELETED")
}
else
{
println(" \(device.1[i].id) NOT DELETED, error code \(deleteStatus.status)")
}
}
}
}
}
}
}
else
{
println("Can't enumerate runtimes in section \(section.name)")
return false;
}
return true
}
// MARK: Execution starts here
if Process.argc != 2
{
println("Invalid options count")
printUsage();
exit(1)
}
var isShowOnlyMode: Bool;
switch Process.arguments[1]
{
case "-h", "--help":
printUsage()
exit(1)
case "-d", "--delete":
isShowOnlyMode = false;
case "-s", "--show":
isShowOnlyMode = true;
default:
println("Unknown option \(Process.arguments[1])")
printUsage()
exit(1)
}
var simulatorsList = executeWithBash("xcrun simctl list")
if simulatorsList.status != 0
{
println("'xcrun simctl list' execution failed with code \(simulatorsList.status)")
exit(1)
}
var sections = sectionsFromString(simulatorsList.output, "== ", " ==\n")
if sections == nil
{
println("Can't parse output of 'xcrun simctl list'")
exit(1);
}
for section in sections!
{
if section.name == "Devices"
{
if processDuplicatesInSection(simulatorsList.output, section, isShowOnlyMode)
{
break
}
exit(1);
}
}
| mit | 865fe0e5b9fc3a404c0c5a1e130e22b8 | 23.871642 | 125 | 0.572372 | 4.323819 | false | false | false | false |
nwjs/chromium.src | ios/chrome/browser/ui/omnibox/popup/shared/popup_match_row_view.swift | 7 | 8567 | // Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import SwiftUI
import ios_chrome_common_ui_colors_swift
/// PreferenceKey to listen to changes of a view's size.
struct PopupMatchRowSizePreferenceKey: PreferenceKey {
static var defaultValue = CGSize.zero
// This function determines how to combine the preference values for two
// child views. In the absence of any better combination method, just use the
// second value.
static func reduce(value: inout CGSize, nextValue: () -> CGSize) {
value = nextValue()
}
}
struct PopupMatchRowView: View {
enum Colors {
static let highlightingColor = Color(
red: 26 / 255, green: 115 / 255, blue: 232 / 255, opacity: 1)
static let highlightingGradient = Gradient(colors: [
highlightingColor.opacity(0.85), highlightingColor,
])
}
enum Dimensions {
static let actionButtonOffset = CGSize(width: -5, height: 0)
static let actionButtonOuterPadding = EdgeInsets(top: 2, leading: 0, bottom: 2, trailing: 0)
static let minHeight: CGFloat = 58
enum VariationOne {
static let padding = EdgeInsets(top: 9, leading: 0, bottom: 9, trailing: 0)
}
enum VariationTwo {
static let padding = EdgeInsets(top: 9, leading: 0, bottom: 9, trailing: 10)
}
}
@Environment(\.popupUIVariation) var uiVariation: PopupUIVariation
@Environment(\.popupPasteButtonVariation) var pasteButtonVariation: PopupPasteButtonVariation
@Environment(\.horizontalSizeClass) var sizeClass
let match: PopupMatch
let isHighlighted: Bool
let toolbarConfiguration: ToolbarConfiguration
let selectionHandler: () -> Void
let trailingButtonHandler: () -> Void
let uiConfiguration: PopupUIConfiguration
@State var isPressed = false
@State var childView = CGSize.zero
@State var currentSize = CGSize.zero
var button: some View {
let button =
Button(action: selectionHandler) {
Color.clear.contentShape(Rectangle())
}
.buttonStyle(PressedPreferenceKeyButtonStyle())
.onPreferenceChange(PressedPreferenceKey.self) { isPressed in
self.isPressed = isPressed
}
.accessibilityElement()
.accessibilityLabel(match.text.string)
.accessibilityValue(match.detailText?.string ?? "")
if match.isAppendable || match.isTabMatch {
let trailingActionAccessibilityTitle =
match.isTabMatch
? L10NUtils.string(forMessageId: IDS_IOS_OMNIBOX_POPUP_SWITCH_TO_OPEN_TAB)
: L10NUtils.string(forMessageId: IDS_IOS_OMNIBOX_POPUP_APPEND)
return
button
.accessibilityAction(
named: trailingActionAccessibilityTitle!, trailingButtonHandler
)
} else {
return button
}
}
/// Enable this to tell the row it should display its own custom separator at the bottom.
let shouldDisplayCustomSeparator: Bool
var customSeparatorColor: Color {
uiVariation == .one ? .separator : .grey200
}
@ViewBuilder
var customSeparator: some View {
HStack(spacing: 0) {
Spacer().frame(
width: leadingMarginForRowContent + spaceBetweenRowContentLeadingEdgeAndSuggestionText)
customSeparatorColor.frame(height: 0.5)
}
}
@Environment(\.layoutDirection) var layoutDirection: LayoutDirection
var leadingMarginForRowContent: CGFloat {
switch uiVariation {
case .one:
return uiConfiguration.omniboxLeadingSpace + 7
case .two:
return 8
}
}
var trailingMarginForRowContent: CGFloat {
switch uiVariation {
case .one:
return uiConfiguration.safeAreaTrailingSpace + kExpandedLocationBarLeadingMarginRefreshedPopup
case .two:
return 0
}
}
var spaceBetweenRowContentLeadingEdgeAndCenterOfSuggestionImage: CGFloat {
switch uiVariation {
case .one:
return uiConfiguration.omniboxLeadingImageLeadingSpace
case .two:
return 30
}
}
var spaceBetweenTextAndImage: CGFloat {
switch uiVariation {
case .one:
return 14
case .two:
return 15
}
}
var spaceBetweenRowContentLeadingEdgeAndSuggestionText: CGFloat {
switch uiVariation {
case .one:
return uiConfiguration.omniboxTextFieldLeadingSpace
case .two:
return 59
}
}
var body: some View {
ZStack {
// This hides system separators when disabling them is not possible.
backgroundColor.notifyOnSizeChange { size in
currentSize = size
}
if shouldDisplayCustomSeparator {
VStack {
Spacer()
customSeparator
}
}
if isHighlighted {
LinearGradient(gradient: Colors.highlightingGradient, startPoint: .top, endPoint: .bottom)
} else if self.isPressed {
Color.updatedTertiaryBackground
}
button
let highlightColor = isHighlighted ? Color.white : nil
// The content is in front of the button, for proper hit testing.
HStack(alignment: .center, spacing: 0) {
Color.clear.frame(width: leadingMarginForRowContent)
match.image
.map { image in
PopupMatchImageView(
image: image, highlightColor: highlightColor
)
.accessibilityHidden(true)
.clipShape(RoundedRectangle(cornerRadius: 7, style: .continuous))
}
Color.clear.frame(width: spaceBetweenTextAndImage)
VStack(alignment: .leading, spacing: 0) {
VStack(alignment: .leading, spacing: 0) {
GradientTextView(match.text, highlightColor: highlightColor)
.lineLimit(1)
.accessibilityHidden(true)
if let subtitle = match.detailText, !subtitle.string.isEmpty {
if match.hasAnswer {
OmniboxText(subtitle, highlightColor: highlightColor)
.font(.footnote)
.lineLimit(match.numberOfLines)
.accessibilityHidden(true)
} else {
GradientTextView(
subtitle, highlightColor: highlightColor
)
.font(.footnote)
.lineLimit(1)
.accessibilityHidden(true)
}
}
}
.allowsHitTesting(false)
}
Spacer(minLength: 0)
if match.isAppendable || match.isTabMatch {
PopupMatchTrailingButton(match: match, action: trailingButtonHandler)
.foregroundColor(isHighlighted ? highlightColor : .chromeBlue)
} else if match.isClipboardMatch {
// Clipboard matches are never appendable or tab matches.
#if __IPHONE_16_0
if #available(iOS 16.0, *) {
let pasteButton: PasteButton = PasteButton(
// The clipboard suggestion row is only going to appear for these
// types of clipboard content.
supportedContentTypes: [.text, .image, .url],
payloadAction: { _ in
DispatchQueue.main.async {
// The clipboard content will be retrieved in a later stage by the
// clipboard provider. After the tap on `PasteButton`, later request
// on the same clipboard content won't trigger the permission popup.
selectionHandler()
}
}
)
switch pasteButtonVariation {
case .icon:
pasteButton
.labelStyle(.iconOnly)
.buttonBorderShape(.capsule)
case .iconText:
pasteButton
.labelStyle(.titleAndIcon)
.buttonBorderShape(.capsule)
}
}
#endif // __IPHONE_16_0
}
Color.clear.frame(width: trailingMarginForRowContent)
}
.padding(
uiVariation == .one ? Dimensions.VariationOne.padding : Dimensions.VariationTwo.padding
)
.environment(\.layoutDirection, layoutDirection)
}
.frame(maxWidth: .infinity, minHeight: Dimensions.minHeight)
.preference(key: PopupMatchRowSizePreferenceKey.self, value: self.currentSize)
}
var backgroundColor: Color {
switch uiVariation {
case .one:
return Color(toolbarConfiguration.backgroundColor)
case .two:
return .groupedSecondaryBackground
}
}
}
struct PopupMatchRowView_Previews: PreviewProvider {
static var previews: some View = PopupView_Previews.previews
}
| bsd-3-clause | caa7f19f21bbd91e5e289af4a59bfaf5 | 30.966418 | 100 | 0.640598 | 4.881481 | false | false | false | false |
codercd/xmppChat | Chat/Classes/Discover/DiscoverTableViewController.swift | 1 | 3801 | //
// DiscoverTableViewController.swift
// Chat
//
// Created by LiChendi on 16/3/23.
// Copyright © 2016年 lcd. All rights reserved.
//
import UIKit
class DiscoverTableViewController: UITableViewController {
let discoverCellIdentifier = "discoverCell"
var jsonArray:Array<Array<String>> = [ [""] ]
override func viewDidLoad() {
super.viewDidLoad()
let dic = NSDictionary(contentsOfFile: NSBundle.mainBundle().pathForResource("MenuJson", ofType: "plist")!)
jsonArray = dic!["Discover"] as! Array<Array<String>>
print(jsonArray)
tableView.registerNib(UINib(nibName: "DetailTableViewCell", bundle: nil), forCellReuseIdentifier: discoverCellIdentifier)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return jsonArray.count
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
// let array = jsonArray[section] as Array<String>
return 1
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 80
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(discoverCellIdentifier, forIndexPath: indexPath) as! DetailTableViewCell
cell.accessoryType = .DisclosureIndicator
cell.IconImageView.image = UIImage(named: "ihead_007")
// cell.nameLabel.text = jsonArray[indexPath.section][indexPath.row]
// Configure the cell...
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| apache-2.0 | 078247d0524d5003641622fb2515b02a | 33.527273 | 157 | 0.682991 | 5.456897 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/ViewRelated/Stats/Today Widgets/Data/ThisWeekWidgetStats.swift | 1 | 4169 | import Foundation
import WordPressKit
/// This struct contains data for 'Views This Week' stats to be displayed in the corresponding widget.
/// The data is stored in a plist for the widget to access.
///
struct ThisWeekWidgetStats: Codable {
let days: [ThisWeekWidgetDay]
init(days: [ThisWeekWidgetDay]? = []) {
self.days = days ?? []
}
}
struct ThisWeekWidgetDay: Codable, Hashable {
let date: Date
let viewsCount: Int
let dailyChangePercent: Float
init(date: Date, viewsCount: Int, dailyChangePercent: Float) {
self.date = date
self.viewsCount = viewsCount
self.dailyChangePercent = dailyChangePercent
}
}
extension ThisWeekWidgetStats {
static var maxDaysToDisplay: Int {
return 7
}
static func loadSavedData() -> ThisWeekWidgetStats? {
guard let sharedDataFileURL = dataFileURL,
FileManager.default.fileExists(atPath: sharedDataFileURL.path) == true else {
DDLogError("ThisWeekWidgetStats: data file '\(dataFileName)' does not exist.")
return nil
}
let decoder = PropertyListDecoder()
do {
let data = try Data(contentsOf: sharedDataFileURL)
return try decoder.decode(ThisWeekWidgetStats.self, from: data)
} catch {
DDLogError("Failed loading ThisWeekWidgetStats data: \(error.localizedDescription)")
return nil
}
}
static func clearSavedData() {
guard let dataFileURL = ThisWeekWidgetStats.dataFileURL else {
return
}
do {
try FileManager.default.removeItem(at: dataFileURL)
}
catch {
DDLogError("ThisWeekWidgetStats: failed deleting data file '\(dataFileName)': \(error.localizedDescription)")
}
}
func saveData() {
guard let dataFileURL = ThisWeekWidgetStats.dataFileURL else {
return
}
let encoder = PropertyListEncoder()
encoder.outputFormat = .xml
do {
let data = try encoder.encode(self)
try data.write(to: dataFileURL)
} catch {
DDLogError("Failed saving ThisWeekWidgetStats data: \(error.localizedDescription)")
}
}
static func daysFrom(summaryData: [StatsSummaryData]) -> [ThisWeekWidgetDay] {
var days = [ThisWeekWidgetDay]()
for index in 0..<maxDaysToDisplay {
guard index + 1 <= summaryData.endIndex else {
break
}
let currentDay = summaryData[index]
let previousDayCount = summaryData[index + 1].viewsCount
let difference = currentDay.viewsCount - previousDayCount
let dailyChangePercent: Float = {
if previousDayCount > 0 {
return (Float(difference) / Float(previousDayCount))
}
return 0
}()
let widgetData = ThisWeekWidgetDay(date: currentDay.periodStartDate,
viewsCount: currentDay.viewsCount,
dailyChangePercent: dailyChangePercent)
days.append(widgetData)
}
return days
}
private static var dataFileName = AppConfiguration.Widget.StatsToday.thisWeekFilename
private static var dataFileURL: URL? {
guard let url = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: WPAppGroupName) else {
DDLogError("ThisWeekWidgetStats: unable to get file URL for \(WPAppGroupName).")
return nil
}
return url.appendingPathComponent(dataFileName)
}
}
extension ThisWeekWidgetStats: Equatable {
static func == (lhs: ThisWeekWidgetStats, rhs: ThisWeekWidgetStats) -> Bool {
return lhs.days.elementsEqual(rhs.days)
}
}
extension ThisWeekWidgetDay: Equatable {
static func == (lhs: ThisWeekWidgetDay, rhs: ThisWeekWidgetDay) -> Bool {
return lhs.date == rhs.date &&
lhs.viewsCount == rhs.viewsCount &&
lhs.dailyChangePercent == rhs.dailyChangePercent
}
}
| gpl-2.0 | 776fef78d32052194747bbe80a0f8a68 | 30.345865 | 121 | 0.616455 | 5.022892 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/ViewRelated/Reader/Filter/FilterProvider.swift | 1 | 11193 | import WordPressFlux
class FilterProvider: Observable, FilterTabBarItem {
enum State {
case loading
case ready([TableDataItem])
case error(Error)
var isReady: Bool {
switch self {
case .ready:
return true
case .error, .loading:
return false
}
}
}
var title: String {
return titleFunc(state)
}
var state: State = .loading {
didSet {
emitChange()
}
}
var items: [TableDataItem] {
switch state {
case .loading, .error:
return []
case .ready(let items):
return FilterProvider.filterItems(items, siteType: siteType)
}
}
typealias Provider = (@escaping (Result<[TableDataItem], Error>) -> Void) -> Void
let accessibilityIdentifier: String
let cellClass: UITableViewCell.Type
let reuseIdentifier: String
let emptyTitle: String
let emptyActionTitle: String
let section: ReaderManageScenePresenter.TabbedSection
let siteType: SiteOrganizationType?
private let titleFunc: (State?) -> String
private let provider: Provider
let changeDispatcher = Dispatcher<Void>()
init(title: @escaping (State?) -> String,
accessibilityIdentifier: String,
cellClass: UITableViewCell.Type,
reuseIdentifier: String,
emptyTitle: String,
emptyActionTitle: String,
section: ReaderManageScenePresenter.TabbedSection,
provider: @escaping Provider,
siteType: SiteOrganizationType? = nil) {
titleFunc = title
self.accessibilityIdentifier = accessibilityIdentifier
self.cellClass = cellClass
self.reuseIdentifier = reuseIdentifier
self.emptyTitle = emptyTitle
self.emptyActionTitle = emptyActionTitle
self.section = section
self.provider = provider
self.siteType = siteType
}
func refresh() {
state = .loading
provider() { [weak self] result in
switch result {
case .success(let items):
self?.state = .ready(items)
case .failure(let error):
self?.state = .error(error)
}
}
}
}
extension FilterProvider {
func showAdd(on presenterViewController: UIViewController, sceneDelegate: ScenePresenterDelegate?) {
let presenter = ReaderManageScenePresenter(selected: section, sceneDelegate: sceneDelegate)
presenter.present(on: presenterViewController, animated: true, completion: nil)
}
static func filterItems(_ items: [TableDataItem], siteType: SiteOrganizationType?) -> [TableDataItem] {
// If a site type is specified, filter items by it.
// Otherwise, just return all items.
guard let siteType = siteType else {
return items
}
var filteredItems = [TableDataItem]()
for item in items {
if let topic = item.topic as? ReaderSiteTopic,
topic.organizationType == siteType {
filteredItems.append(item)
}
}
return filteredItems
}
}
extension ReaderSiteTopic {
static func filterProvider(for siteType: SiteOrganizationType?) -> FilterProvider {
let titleFunction: (FilterProvider.State?) -> String = { state in
switch state {
case .loading, .error, .none:
return NSLocalizedString("Sites", comment: "Sites Filter Tab Title")
case .ready(let items):
let filteredItems = FilterProvider.filterItems(items, siteType: siteType)
return String(format: NSLocalizedString("Sites (%lu)", comment: "Sites Filter Tab Title with Count"), filteredItems.count)
}
}
let emptyTitle = NSLocalizedString("Add a site", comment: "No Tags View Button Label")
let emptyActionTitle = NSLocalizedString("You can follow posts on a specific site by following it.", comment: "No Sites View Label")
return FilterProvider(title: titleFunction,
accessibilityIdentifier: "SitesFilterTab",
cellClass: SiteTableViewCell.self,
reuseIdentifier: "Sites",
emptyTitle: emptyTitle,
emptyActionTitle: emptyActionTitle,
section: .sites,
provider: tableProvider,
siteType: siteType)
}
private static func tableProvider(completion: @escaping (Result<[TableDataItem], Error>) -> Void) {
let completionBlock: (Result<[ReaderSiteTopic], Error>) -> Void = { result in
let itemResult = result.map { sites in
sites.map { topic in
return TableDataItem(topic: topic, configure: { cell in
cell.textLabel?.text = topic.title
cell.detailTextLabel?.text = topic.siteURL
addUnseenPostCount(topic, with: cell)
})
}
}
completion(itemResult)
}
fetchStoredFollowedSites(completion: completionBlock)
fetchFollowedSites(completion: completionBlock)
}
/// Fetch sites from remote service
///
private static func fetchFollowedSites(completion: @escaping (Result<[ReaderSiteTopic], Error>) -> Void) {
let siteService = ReaderTopicService(managedObjectContext: ContextManager.sharedInstance().mainContext)
siteService.fetchFollowedSites(success: {
completion(.success(siteService.allSiteTopics()))
}, failure: { error in
DDLogError("Could not sync sites: \(String(describing: error))")
let remoteServiceError = NSError(domain: WordPressComRestApiErrorDomain, code: -1, userInfo: nil)
completion(.failure(error ?? remoteServiceError))
})
}
/// Fetch sites from Core Data
///
private static func fetchStoredFollowedSites(completion: @escaping (Result<[ReaderSiteTopic], Error>) -> Void) {
let siteService = ReaderTopicService(managedObjectContext: ContextManager.sharedInstance().mainContext)
let sites = siteService.allSiteTopics() ?? []
completion(.success(sites))
}
/// Adds a custom accessory view displaying the unseen post count.
///
private static func addUnseenPostCount(_ topic: ReaderSiteTopic, with cell: UITableViewCell) {
// Always reset first.
cell.accessoryView = nil
guard topic.unseenCount > 0 else {
return
}
// Create background view
let unseenCountView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: UnseenCountConstants.viewSize))
unseenCountView.layer.cornerRadius = UnseenCountConstants.cornerRadius
unseenCountView.backgroundColor = .tertiaryFill
// Create count label
let countLabel = UILabel()
countLabel.font = WPStyleGuide.subtitleFont()
countLabel.textColor = .text
countLabel.backgroundColor = .clear
countLabel.text = topic.unseenCount.abbreviatedString()
let accessibilityFormat = topic.unseenCount == 1 ? UnseenCountConstants.singularUnseen : UnseenCountConstants.pluralUnseen
countLabel.accessibilityLabel = String(format: accessibilityFormat, topic.unseenCount)
countLabel.sizeToFit()
// Resize views
unseenCountView.frame.size.width = max(countLabel.frame.width + UnseenCountConstants.labelPadding, UnseenCountConstants.viewSize)
countLabel.center = unseenCountView.center
// Display in cell's accessory view
unseenCountView.addSubview(countLabel)
cell.accessoryView = unseenCountView
}
private struct UnseenCountConstants {
static let cornerRadius: CGFloat = 15
static let viewSize: CGFloat = 30
static let labelPadding: CGFloat = 20
static let singularUnseen = NSLocalizedString("%1$d unseen post", comment: "Format string for single unseen post count. The %1$d is a placeholder for the count.")
static let pluralUnseen = NSLocalizedString("%1$d unseen posts", comment: "Format string for plural unseen posts count. The %1$d is a placeholder for the count.")
}
}
extension ReaderTagTopic {
static func filterProvider() -> FilterProvider {
let titleFunction: (FilterProvider.State?) -> String = { state in
switch state {
case .loading, .error, .none:
return NSLocalizedString("Topics", comment: "Topics Filter Tab Title")
case .ready(let items):
return String(format: NSLocalizedString("Topics (%lu)", comment: "Topics Filter Tab Title with Count"), items.count)
}
}
let emptyTitle = NSLocalizedString("Add a topic", comment: "No Topics View Button Label")
let emptyActionTitle = NSLocalizedString("You can follow posts on a specific subject by adding a topic.", comment: "No Topics View Label")
return FilterProvider(title: titleFunction,
accessibilityIdentifier: "TagsFilterTab",
cellClass: UITableViewCell.self,
reuseIdentifier: "Tags",
emptyTitle: emptyTitle,
emptyActionTitle: emptyActionTitle,
section: .tags,
provider: tableProvider)
}
private static func tableProvider(completion: @escaping (Result<[TableDataItem], Error>) -> Void) {
fetchFollowedTags(completion: { result in
let itemResult = result.map { tags in
tags.map { topic in
return TableDataItem(topic: topic, configure: { (cell) in
cell.textLabel?.text = topic.slug
})
}
}
completion(itemResult)
})
}
static var tagsFetchRequest: NSFetchRequest<NSFetchRequestResult> {
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "ReaderTagTopic")
// Only show following tags, even if the user is logged out
fetchRequest.predicate = NSPredicate(format: "following == YES AND showInMenu == YES AND type == 'tag'")
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "title", ascending: true, selector: #selector(NSString.localizedCaseInsensitiveCompare))]
return fetchRequest
}
private static func fetchFollowedTags(completion: @escaping (Result<[ReaderTagTopic], Error>) -> Void) {
do {
guard let topics = try ContextManager.sharedInstance().mainContext.fetch(tagsFetchRequest) as? [ReaderTagTopic] else {
return
}
completion(.success(topics))
} catch {
DDLogError("There was a problem fetching followed tags." + error.localizedDescription)
completion(.failure(error))
}
}
}
| gpl-2.0 | e2f9e721bb68f1e15e46d07e9c926e05 | 37.864583 | 170 | 0.617082 | 5.287199 | false | false | false | false |
zhiquan911/SwiftChatKit | Example/SwiftChatKit/IndexViewController.swift | 1 | 2750 | //
// IndexViewController.swift
// SwiftChatKit
//
// Created by 麦志泉 on 15/9/12.
// Copyright (c) 2015年 CocoaPods. All rights reserved.
//
import UIKit
import AVOSCloudIM
import SVProgressHUD
class IndexViewController: UIViewController {
var enableDBCache = true
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
// MARK: - 按钮方法
extension IndexViewController: AVIMClientDelegate {
func loginHuanxin() {
SVProgressHUD.show()
let enterBlock = {
() -> Void in
NSLog("登录环信成功")
let vc = self.storyboard!.instantiateViewControllerWithIdentifier(
"ChatForHuanxinViewController") as! ChatForHuanxinViewController
vc.userId = "client"
vc.userName = "麦志泉"
vc.chatToId = "zhiquan911"
vc.chatToName = "客服"
self.navigationController?.pushViewController(vc, animated: true)
}
//同时登录环信
if EaseMob.sharedInstance().chatManager.isLoggedIn {
enterBlock()
}
EaseMob.sharedInstance().chatManager.asyncLoginWithUsername(
"client",
password: "123456",
completion: {
(loginInfo, error) -> Void in
SVProgressHUD.dismiss()
if loginInfo != nil {
enterBlock()
} else {
NSLog("error = \(error.description)")
}
},
onQueue: nil)
}
@IBAction func handleChatButtonPress(sender: AnyObject?) {
let button = sender as? UIButton
let vc = self.storyboard!.instantiateViewControllerWithIdentifier(
"ChatViewController") as! ChatViewController
vc.enableDBCache = self.enableDBCache
if button?.tag == 1 {
//我是李雷
vc.userId = "1"
vc.userName = "李雷"
vc.chatToId = "2"
vc.chatToName = "韩梅梅"
} else {
//我是韩梅梅
vc.userId = "2"
vc.userName = "韩梅梅"
vc.chatToId = "1"
vc.chatToName = "李雷"
}
self.navigationController?.pushViewController(vc, animated: true)
}
@IBAction func handleEnterHuanxin(sender: AnyObject?) {
self.loginHuanxin()
}
@IBAction func handleSwitchChange(switchDB: UISwitch) {
self.enableDBCache = switchDB.on
}
}
| mit | df5778436ce8d5605daaba410de4f184 | 26.163265 | 80 | 0.545455 | 4.645724 | false | false | false | false |
apple/swift-nio | Sources/NIOCore/ChannelHandler.swift | 1 | 19303 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
/// Base protocol for handlers that handle I/O events or intercept an I/O operation.
///
/// All methods are called from within the `EventLoop` that is assigned to the `Channel` itself.
//
/// You should _never_ implement this protocol directly. Please implement one of its sub-protocols.
public protocol ChannelHandler: AnyObject {
/// Called when this `ChannelHandler` is added to the `ChannelPipeline`.
///
/// - parameters:
/// - context: The `ChannelHandlerContext` which this `ChannelHandler` belongs to.
func handlerAdded(context: ChannelHandlerContext)
/// Called when this `ChannelHandler` is removed from the `ChannelPipeline`.
///
/// - parameters:
/// - context: The `ChannelHandlerContext` which this `ChannelHandler` belongs to.
func handlerRemoved(context: ChannelHandlerContext)
}
/// Untyped `ChannelHandler` which handles outbound I/O events or intercept an outbound I/O operation.
///
/// Despite the fact that `write` is one of the methods on this `protocol`, you should avoid assuming that "outbound" events are to do with
/// writing to channel sources. Instead, "outbound" events are events that are passed *to* the channel source (e.g. a socket): that is, things you tell
/// the channel source to do. That includes `write` ("write this data to the channel source"), but it also includes `read` ("please begin attempting to read from
/// the channel source") and `bind` ("please bind the following address"), which have nothing to do with sending data.
///
/// We _strongly_ advise against implementing this protocol directly. Please implement `ChannelOutboundHandler`.
public protocol _ChannelOutboundHandler: ChannelHandler {
/// Called to request that the `Channel` register itself for I/O events with its `EventLoop`.
/// This should call `context.register` to forward the operation to the next `_ChannelOutboundHandler` in the `ChannelPipeline` or
/// complete the `EventLoopPromise` to let the caller know that the operation completed.
///
/// - parameters:
/// - context: The `ChannelHandlerContext` which this `ChannelHandler` belongs to.
/// - promise: The `EventLoopPromise` which should be notified once the operation completes, or nil if no notification should take place.
func register(context: ChannelHandlerContext, promise: EventLoopPromise<Void>?)
/// Called to request that the `Channel` bind to a specific `SocketAddress`.
///
/// This should call `context.bind` to forward the operation to the next `_ChannelOutboundHandler` in the `ChannelPipeline` or
/// complete the `EventLoopPromise` to let the caller know that the operation completed.
///
/// - parameters:
/// - context: The `ChannelHandlerContext` which this `ChannelHandler` belongs to.
/// - to: The `SocketAddress` to which this `Channel` should bind.
/// - promise: The `EventLoopPromise` which should be notified once the operation completes, or nil if no notification should take place.
func bind(context: ChannelHandlerContext, to: SocketAddress, promise: EventLoopPromise<Void>?)
/// Called to request that the `Channel` connect to a given `SocketAddress`.
///
/// This should call `context.connect` to forward the operation to the next `_ChannelOutboundHandler` in the `ChannelPipeline` or
/// complete the `EventLoopPromise` to let the caller know that the operation completed.
///
/// - parameters:
/// - context: The `ChannelHandlerContext` which this `ChannelHandler` belongs to.
/// - to: The `SocketAddress` to which the the `Channel` should connect.
/// - promise: The `EventLoopPromise` which should be notified once the operation completes, or nil if no notification should take place.
func connect(context: ChannelHandlerContext, to: SocketAddress, promise: EventLoopPromise<Void>?)
/// Called to request a write operation. The write operation will write the messages through the
/// `ChannelPipeline`. Those are then ready to be flushed to the actual `Channel` when
/// `Channel.flush` or `ChannelHandlerContext.flush` is called.
///
/// This should call `context.write` to forward the operation to the next `_ChannelOutboundHandler` in the `ChannelPipeline` or
/// complete the `EventLoopPromise` to let the caller know that the operation completed.
///
/// - parameters:
/// - context: The `ChannelHandlerContext` which this `ChannelHandler` belongs to.
/// - data: The data to write through the `Channel`, wrapped in a `NIOAny`.
/// - promise: The `EventLoopPromise` which should be notified once the operation completes, or nil if no notification should take place.
func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise<Void>?)
/// Called to request that the `Channel` flush all pending writes. The flush operation will try to flush out all previous written messages
/// that are pending.
///
/// This should call `context.flush` to forward the operation to the next `_ChannelOutboundHandler` in the `ChannelPipeline` or just
/// discard it if the flush should be suppressed.
///
/// - parameters:
/// - context: The `ChannelHandlerContext` which this `ChannelHandler` belongs to.
func flush(context: ChannelHandlerContext)
/// Called to request that the `Channel` perform a read when data is ready. The read operation will signal that we are ready to read more data.
///
/// This should call `context.read` to forward the operation to the next `_ChannelOutboundHandler` in the `ChannelPipeline` or just
/// discard it if the read should be suppressed.
///
/// - parameters:
/// - context: The `ChannelHandlerContext` which this `ChannelHandler` belongs to.
func read(context: ChannelHandlerContext)
/// Called to request that the `Channel` close itself down`.
///
/// This should call `context.close` to forward the operation to the next `_ChannelOutboundHandler` in the `ChannelPipeline` or
/// complete the `EventLoopPromise` to let the caller know that the operation completed.
///
/// - parameters:
/// - context: The `ChannelHandlerContext` which this `ChannelHandler` belongs to.
/// - mode: The `CloseMode` to apply
/// - promise: The `EventLoopPromise` which should be notified once the operation completes, or nil if no notification should take place.
func close(context: ChannelHandlerContext, mode: CloseMode, promise: EventLoopPromise<Void>?)
/// Called when an user outbound event is triggered.
///
/// This should call `context.triggerUserOutboundEvent` to forward the operation to the next `_ChannelOutboundHandler` in the `ChannelPipeline` or
/// complete the `EventLoopPromise` to let the caller know that the operation completed.
///
/// - parameters:
/// - context: The `ChannelHandlerContext` which this `ChannelHandler` belongs to.
/// - event: The triggered event.
/// - promise: The `EventLoopPromise` which should be notified once the operation completes, or nil if no notification should take place.
func triggerUserOutboundEvent(context: ChannelHandlerContext, event: Any, promise: EventLoopPromise<Void>?)
}
/// Untyped `ChannelHandler` which handles inbound I/O events.
///
/// Despite the fact that `channelRead` is one of the methods on this `protocol`, you should avoid assuming that "inbound" events are to do with
/// reading from channel sources. Instead, "inbound" events are events that originate *from* the channel source (e.g. the socket): that is, events that the
/// channel source tells you about. This includes things like `channelRead` ("there is some data to read"), but it also includes things like
/// `channelWritabilityChanged` ("this source is no longer marked writable").
///
/// We _strongly_ advise against implementing this protocol directly. Please implement `ChannelInboundHandler`.
public protocol _ChannelInboundHandler: ChannelHandler {
/// Called when the `Channel` has successfully registered with its `EventLoop` to handle I/O.
///
/// This should call `context.fireChannelRegistered` to forward the operation to the next `_ChannelInboundHandler` in the `ChannelPipeline` if you want to allow the next handler to also handle the event.
///
/// - parameters:
/// - context: The `ChannelHandlerContext` which this `ChannelHandler` belongs to.
func channelRegistered(context: ChannelHandlerContext)
/// Called when the `Channel` has unregistered from its `EventLoop`, and so will no longer be receiving I/O events.
///
/// This should call `context.fireChannelUnregistered` to forward the operation to the next `_ChannelInboundHandler` in the `ChannelPipeline` if you want to allow the next handler to also handle the event.
///
/// - parameters:
/// - context: The `ChannelHandlerContext` which this `ChannelHandler` belongs to.
func channelUnregistered(context: ChannelHandlerContext)
/// Called when the `Channel` has become active, and is able to send and receive data.
///
/// This should call `context.fireChannelActive` to forward the operation to the next `_ChannelInboundHandler` in the `ChannelPipeline` if you want to allow the next handler to also handle the event.
///
/// - parameters:
/// - context: The `ChannelHandlerContext` which this `ChannelHandler` belongs to.
func channelActive(context: ChannelHandlerContext)
/// Called when the `Channel` has become inactive and is no longer able to send and receive data`.
///
/// This should call `context.fireChannelInactive` to forward the operation to the next `_ChannelInboundHandler` in the `ChannelPipeline` if you want to allow the next handler to also handle the event.
///
/// - parameters:
/// - context: The `ChannelHandlerContext` which this `ChannelHandler` belongs to.
func channelInactive(context: ChannelHandlerContext)
/// Called when some data has been read from the remote peer.
///
/// This should call `context.fireChannelRead` to forward the operation to the next `_ChannelInboundHandler` in the `ChannelPipeline` if you want to allow the next handler to also handle the event.
///
/// - parameters:
/// - context: The `ChannelHandlerContext` which this `ChannelHandler` belongs to.
/// - data: The data read from the remote peer, wrapped in a `NIOAny`.
func channelRead(context: ChannelHandlerContext, data: NIOAny)
/// Called when the `Channel` has completed its current read loop, either because no more data is available to read from the transport at this time, or because the `Channel` needs to yield to the event loop to process other I/O events for other `Channel`s.
/// If `ChannelOptions.autoRead` is `false` no further read attempt will be made until `ChannelHandlerContext.read` or `Channel.read` is explicitly called.
///
/// This should call `context.fireChannelReadComplete` to forward the operation to the next `_ChannelInboundHandler` in the `ChannelPipeline` if you want to allow the next handler to also handle the event.
///
/// - parameters:
/// - context: The `ChannelHandlerContext` which this `ChannelHandler` belongs to.
func channelReadComplete(context: ChannelHandlerContext)
/// The writability state of the `Channel` has changed, either because it has buffered more data than the writability high water mark, or because the amount of buffered data has dropped below the writability low water mark.
/// You can check the state with `Channel.isWritable`.
///
/// This should call `context.fireChannelWritabilityChanged` to forward the operation to the next `_ChannelInboundHandler` in the `ChannelPipeline` if you want to allow the next handler to also handle the event.
///
/// - parameters:
/// - context: The `ChannelHandlerContext` which this `ChannelHandler` belongs to.
func channelWritabilityChanged(context: ChannelHandlerContext)
/// Called when a user inbound event has been triggered.
///
/// This should call `context.fireUserInboundEventTriggered` to forward the operation to the next `_ChannelInboundHandler` in the `ChannelPipeline` if you want to allow the next handler to also handle the event.
///
/// - parameters:
/// - context: The `ChannelHandlerContext` which this `ChannelHandler` belongs to.
/// - event: The event.
func userInboundEventTriggered(context: ChannelHandlerContext, event: Any)
/// An error was encountered earlier in the inbound `ChannelPipeline`.
///
/// This should call `context.fireErrorCaught` to forward the operation to the next `_ChannelInboundHandler` in the `ChannelPipeline` if you want to allow the next handler to also handle the error.
///
/// - parameters:
/// - context: The `ChannelHandlerContext` which this `ChannelHandler` belongs to.
/// - error: The `Error` that was encountered.
func errorCaught(context: ChannelHandlerContext, error: Error)
}
// Default implementations for the ChannelHandler protocol
extension ChannelHandler {
/// Do nothing by default.
public func handlerAdded(context: ChannelHandlerContext) {
}
/// Do nothing by default.
public func handlerRemoved(context: ChannelHandlerContext) {
}
}
/// Provides default implementations for all methods defined by `_ChannelOutboundHandler`.
///
/// These default implementations will just call `context.methodName` to forward to the next `_ChannelOutboundHandler` in
/// the `ChannelPipeline` until the operation is handled by the `Channel` itself.
extension _ChannelOutboundHandler {
public func register(context: ChannelHandlerContext, promise: EventLoopPromise<Void>?) {
context.register(promise: promise)
}
public func bind(context: ChannelHandlerContext, to address: SocketAddress, promise: EventLoopPromise<Void>?) {
context.bind(to: address, promise: promise)
}
public func connect(context: ChannelHandlerContext, to address: SocketAddress, promise: EventLoopPromise<Void>?) {
context.connect(to: address, promise: promise)
}
public func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise<Void>?) {
context.write(data, promise: promise)
}
public func flush(context: ChannelHandlerContext) {
context.flush()
}
public func read(context: ChannelHandlerContext) {
context.read()
}
public func close(context: ChannelHandlerContext, mode: CloseMode, promise: EventLoopPromise<Void>?) {
context.close(mode: mode, promise: promise)
}
public func triggerUserOutboundEvent(context: ChannelHandlerContext, event: Any, promise: EventLoopPromise<Void>?) {
context.triggerUserOutboundEvent(event, promise: promise)
}
}
/// Provides default implementations for all methods defined by `_ChannelInboundHandler`.
///
/// These default implementations will just `context.fire*` to forward to the next `_ChannelInboundHandler` in
/// the `ChannelPipeline` until the operation is handled by the `Channel` itself.
extension _ChannelInboundHandler {
public func channelRegistered(context: ChannelHandlerContext) {
context.fireChannelRegistered()
}
public func channelUnregistered(context: ChannelHandlerContext) {
context.fireChannelUnregistered()
}
public func channelActive(context: ChannelHandlerContext) {
context.fireChannelActive()
}
public func channelInactive(context: ChannelHandlerContext) {
context.fireChannelInactive()
}
public func channelRead(context: ChannelHandlerContext, data: NIOAny) {
context.fireChannelRead(data)
}
public func channelReadComplete(context: ChannelHandlerContext) {
context.fireChannelReadComplete()
}
public func channelWritabilityChanged(context: ChannelHandlerContext) {
context.fireChannelWritabilityChanged()
}
public func userInboundEventTriggered(context: ChannelHandlerContext, event: Any) {
context.fireUserInboundEventTriggered(event)
}
public func errorCaught(context: ChannelHandlerContext, error: Error) {
context.fireErrorCaught(error)
}
}
/// A `RemovableChannelHandler` is a `ChannelHandler` that can be dynamically removed from a `ChannelPipeline` whilst
/// the `Channel` is operating normally.
/// A `RemovableChannelHandler` is required to remove itself from the `ChannelPipeline` (using
/// `ChannelHandlerContext.removeHandler`) as soon as possible.
///
/// - note: When a `Channel` gets torn down, every `ChannelHandler` in the `Channel`'s `ChannelPipeline` will be
/// removed from the `ChannelPipeline`. Those removals however happen synchronously and are not going through
/// the methods of this protocol.
public protocol RemovableChannelHandler: ChannelHandler {
/// Ask the receiving `RemovableChannelHandler` to remove itself from the `ChannelPipeline` as soon as possible.
/// The receiving `RemovableChannelHandler` may elect to remove itself sometime after this method call, rather than
/// immediately, but if it does so it must take the necessary precautions to handle events arriving between the
/// invocation of this method and the call to `ChannelHandlerContext.removeHandler` that triggers the actual
/// removal.
///
/// - note: Like the other `ChannelHandler` methods, this method should not be invoked by the user directly. To
/// remove a `RemovableChannelHandler` from the `ChannelPipeline`, use `ChannelPipeline.remove`.
///
/// - parameters:
/// - context: The `ChannelHandlerContext` of the `RemovableChannelHandler` to be removed from the `ChannelPipeline`.
/// - removalToken: The removal token to hand to `ChannelHandlerContext.removeHandler` to trigger the actual
/// removal from the `ChannelPipeline`.
func removeHandler(context: ChannelHandlerContext, removalToken: ChannelHandlerContext.RemovalToken)
}
extension RemovableChannelHandler {
// Implements the default behaviour which is to synchronously remove the handler from the pipeline. Thanks to this,
// stateless `ChannelHandler`s can just use `RemovableChannelHandler` as a marker-protocol and declare themselves
// as removable without writing any extra code.
public func removeHandler(context: ChannelHandlerContext, removalToken: ChannelHandlerContext.RemovalToken) {
precondition(context.handler === self)
context.leavePipeline(removalToken: removalToken)
}
}
| apache-2.0 | 331f83ec432200e6e4c3399a3add78e9 | 54.950725 | 260 | 0.71735 | 4.860992 | false | false | false | false |
castial/Quick-Start-iOS | Pods/HYAlertController/HYAlertController/HYShareView.swift | 1 | 7366 | //
// HYShareView.swift
// Quick-Start-iOS
//
// Created by work on 2016/11/4.
// Copyright © 2016年 hyyy. All rights reserved.
//
import UIKit
protocol HYShareViewDelegate {
// 点击分享item事件
func clickedShareItemHandler()
}
class HYShareView: UIView {
lazy var shareTable: UITableView = {
let tableView: UITableView = UITableView (frame: CGRect.zero, style: .plain)
tableView.isScrollEnabled = false
return tableView
}()
lazy var cancelButton: UIButton = {
let button: UIButton = UIButton (type: UIButtonType.custom)
button.frame = CGRect (x: 0, y: 0, width: HY_Constants.ScreenWidth, height: 44)
button.setTitle("取消", for: .normal)
button.setTitleColor(UIColor.darkText, for: .normal)
button.titleLabel?.font = UIFont.systemFont(ofSize: 14)
button.addTarget(self, action: #selector (clickedCancelBtnHandler), for: .touchUpInside)
return button
}()
lazy var titleView: HYTitleView = {
let view: HYTitleView = HYTitleView (frame: CGRect.zero)
return view
}()
var shareTitle: String = String ()
var shareMessage: String = String ()
var delegate: HYShareViewDelegate?
fileprivate var shareDataArray: NSArray = NSArray ()
fileprivate var cancelDataArray: NSArray = NSArray ()
/// 存储各个collectionView的偏移量
fileprivate var contentOffsetDictionary: NSMutableDictionary = NSMutableDictionary ()
override init(frame: CGRect) {
super.init(frame: frame)
initUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: - LifeCycle
extension HYShareView {
fileprivate func initUI() {
self.shareTable.delegate = self
self.shareTable.dataSource = self
self.shareTable.tableFooterView = self.cancelButton
self.addSubview(self.shareTable)
}
override func layoutSubviews() {
super.layoutSubviews()
self.shareTable.frame = self.bounds
if self.shareTitle.characters.count > 0 || self.shareMessage.characters.count > 0 {
self.titleView.refrenshTitleView(title: self.shareTitle,
message: self.shareMessage)
self.titleView.frame = CGRect (x: 0,
y: 0,
width: self.bounds.size.width,
height: HYTitleView.titleViewHeight(title: self.shareTitle,
message: self.shareMessage,
width: self.bounds.size.width))
self.shareTable.tableHeaderView = self.titleView
}else {
self.shareTable.tableHeaderView = UIView ()
}
}
}
// MARK: - Public Methods
extension HYShareView {
open func refreshDate(dataArray: NSArray, cancelArray: NSArray, title: String, message: String) {
self.shareDataArray = dataArray
self.cancelDataArray = cancelArray
self.shareTable.reloadData()
}
}
// MARK: - UITableViewDataSource
extension HYShareView: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.shareDataArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: HYShareTableViewCell = HYShareTableViewCell.cellWithTableView(tableView: tableView)
return cell
}
}
// MARK: - UITableViewDelegate
extension HYShareView: UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 0.1
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 0.1
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return HYShareTableViewCell.cellHeight()
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
let shareCell: HYShareTableViewCell = cell as! HYShareTableViewCell
shareCell.setCollectionViewDataSourceDelegate(collectionDataSource: self, collectionDelegate: self, indexPath: indexPath as NSIndexPath)
let index: Int = shareCell.collectionView.tag
if let horizontalOffset: CGFloat = self.contentOffsetDictionary.object(forKey: index) as? CGFloat {
shareCell.collectionView.contentOffset = CGPoint (x: horizontalOffset, y: 0)
}
}
func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
let shareCell: HYShareTableViewCell = cell as! HYShareTableViewCell
let index: Int = shareCell.collectionView.tag
let horizontalOffset: CGFloat = shareCell.collectionView.contentOffset.x
self.contentOffsetDictionary.setObject(horizontalOffset, forKey: index as NSCopying)
}
}
// MARK: - UICollectionViewDelegate
extension HYShareView: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let collectionDataArray: NSArray = self.shareDataArray.object(at: collectionView.tag) as! NSArray
let action: HYAlertAction = collectionDataArray.object(at: indexPath.row) as! HYAlertAction
action.myHandler(action)
delegate?.clickedShareItemHandler()
}
}
// MARK: - UICollectionViewDataSource
extension HYShareView: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
let collectionDataArray: NSArray = self.shareDataArray.object(at: section) as! NSArray
return collectionDataArray.count
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell: HYShareCollectionCell = collectionView.dequeueReusableCell(withReuseIdentifier: HYShareCollectionCell.ID(), for: indexPath) as! HYShareCollectionCell
let collectionDataArray: NSArray = self.shareDataArray.object(at: collectionView.tag) as! NSArray
let action: HYAlertAction = collectionDataArray.object(at: indexPath.row) as! HYAlertAction
cell.cellIcon.image = action.image
cell.titleView.text = action.title
return cell
}
}
// MARK: - Events
extension HYShareView {
@objc fileprivate func clickedCancelBtnHandler() {
if self.cancelDataArray.count > 0 {
let action: HYAlertAction = self.cancelDataArray.object(at: 0) as! HYAlertAction
action.myHandler(action)
}
delegate?.clickedShareItemHandler()
}
}
| mit | e3f6cce38ef31dbae14c9d1a50f7bbe9 | 36.984456 | 167 | 0.660074 | 5.155415 | false | false | false | false |
apple/swift-protobuf | Sources/SwiftProtobufPluginLibrary/SwiftProtobufInfo.swift | 2 | 2003 | // Sources/SwiftProtobufPluginLibrary/LibraryInfo.swift - Helpers info about the SwiftProtobuf library
//
// Copyright (c) 2014 - 2017 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/main/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// Helpers for info about the SwiftProtobuf library itself.
///
// -----------------------------------------------------------------------------
import Foundation
import SwiftProtobuf
/// Helpers about the library.
public enum SwiftProtobufInfo {
/// Proto Files that ship with the library.
public static let bundledProtoFiles: Set<String> = [
"google/protobuf/any.proto",
"google/protobuf/api.proto",
// Even though descriptor.proto is *not* a WKT, it is included in the
// library so developers trying to compile .proto files with message,
// field, or file extensions don't have to generate it.
"google/protobuf/descriptor.proto",
"google/protobuf/duration.proto",
"google/protobuf/empty.proto",
"google/protobuf/field_mask.proto",
"google/protobuf/source_context.proto",
"google/protobuf/struct.proto",
"google/protobuf/timestamp.proto",
"google/protobuf/type.proto",
"google/protobuf/wrappers.proto",
]
/// Checks if a `Google_Protobuf_FileDescriptorProto` is a library bundled proto file.
@available(*, deprecated, message: "Use the version that takes a FileDescriptor instead.")
public static func isBundledProto(file: Google_Protobuf_FileDescriptorProto) -> Bool {
return file.package == "google.protobuf" && bundledProtoFiles.contains(file.name)
}
/// Checks if a `FileDescriptor` is a library bundled proto file.
public static func isBundledProto(file: FileDescriptor) -> Bool {
return file.package == "google.protobuf" && bundledProtoFiles.contains(file.name)
}
}
| apache-2.0 | 6514f843a133e03f3fd2258eb0a34a9f | 40.729167 | 102 | 0.674488 | 4.441242 | false | false | false | false |
congncif/SiFUtilities | UIKit/UITextField++.swift | 1 | 830 | //
// UITextField++.swift
// Pods-SiFUtilities_Example
//
// Created by FOLY on 4/6/18.
//
import Foundation
// @IBDesignable
extension UITextField {
@IBInspectable open var leftPadding: CGFloat {
get {
return leftView?.frame.size.width ?? 0
}
set {
let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: newValue, height: frame.size.height))
leftView = paddingView
leftViewMode = .always
}
}
@IBInspectable open var rightPadding: CGFloat {
get {
return rightView?.frame.size.width ?? 0
}
set {
let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: newValue, height: frame.size.height))
rightView = paddingView
rightViewMode = .always
}
}
}
| mit | ae647c66014c8fa41d76fc90763851c1 | 24.151515 | 107 | 0.563855 | 4.213198 | false | false | false | false |
blocktree/BitcoinSwift | BitcoinSwift/BitcoinSwiftTests/BTCKey_Tests.swift | 1 | 4812 | //
// BitcoinSwiftIOSTests.swift
// BitcoinSwiftIOSTests
//
// Created by Chance on 2017/4/8.
//
//
import XCTest
@testable import BitcoinSwift
class BTCKey_Tests: XCTestCase {
override func setUp() {
super.setUp()
print("//////////////////// 测试开始 ////////////////////\n")
}
override func tearDown() {
print("//////////////////// 测试结束 ////////////////////\n")
super.tearDown()
}
/// 测试创建钥匙对
func testCreateKeys() {
/// 随机生成
guard let key = BTCKey() else {
XCTAssert(false)
return
}
print("随机私钥 wif = " + key.wif)
//已有数据初始化私钥
let hex = "c4bbcb1fbec99d65bf59d85c8cb62ee2db963f0fe106f483d9afa73bd4e39a8a"
guard let privatekey = hex.hexData else {
XCTAssert(false)
return
}
guard let key2 = BTCKey(privateKey: privatekey) else {
XCTAssert(false)
return
}
//key2.publicKeyCompressed = true
XCTAssert("5KJvsngHeMpm884wtkJNzQGaCErckhHJBGFsvd3VyK5qMZXj3hS" == key2.wif, "wif == \(key2.wif)")
//导出公钥
let pubkey = key2.publicKey
print("输出公钥 = \(pubkey.hex)")
print("输出公钥地址 = \(key2.address!.string)")
//采用压缩方案
guard let key3 = BTCKey(privateKey: privatekey, compressed: true) else {
XCTAssert(false)
return
}
print("输出压缩公钥 = \(key3.publicKey.hex)")
print("输出压缩公钥地址 = \(key3.address!.string)")
XCTAssert("L3p8oAcQTtuokSCRHQ7i4MhjWc9zornvpJLfmg62sYpLRJF9woSu" == key3.wif, "wif == \(key3.wif)")
}
/// 测试比特币消息认证
func testBitcoinSignedMessage() {
do {
//测试compactSignature
let keyhex = "0000000000000000000000000000000000000000000000000000000000000001"
let messagehex = "foo".data(using: String.Encoding.utf8)!.sha256()
let key = BTCKey(privateKey: keyhex.hexData!, compressed: true)!
guard let signature = key.compactSignature(for: messagehex) else {
XCTAssert(false, "signature failed")
return
}
print("input: messagehex = \(messagehex.hex)")
print("output: signature = \(signature.hex)")
XCTAssert("1f13e87558947c03ea88aa2b1f8d25a73f654f70fd2678dfb788d62a62bf8d761104950459102450c70f1dba0b499678bc300f841c97f4d2e29c7b6c6124676d82" == signature.hex, "signature not correct")
}
do {
//测试bitcoinMessage签名
let keyhex = "c4bbcb1fbec99d65bf59d85c8cb62ee2db963f0fe106f483d9afa73bd4e39a8a"
let message = "My name is Chance, and I am a bitcoinSwift developer."
let key = BTCKey(privateKey: keyhex.hexData!, compressed: false)!
guard let signature = key.signature(for: message) else {
XCTAssert(false, "signature failed")
return
}
print("input: address = \(key.address!.string)")
print("input: message = \(message)")
print("output: base64 = \(signature.hex)")
XCTAssert("HCFFin9nZaSKr57I5+UVrEwkYIYHrk8x/QPjuumWrFUTUrf0xzzF7Rx3x6FVEA1ABYXTmCrEpslJMn/smAL1My0=" == signature.base64EncodedString(), "signature not correct")
//恢复公钥s
guard let publicKey = BTCKey(compactSig: signature, message: message) else {
XCTAssert(false, "recovery publickey failed")
return
}
print("output: recovery publickey = \(publicKey.address!.string)")
XCTAssert(publicKey.publicKeyAddress?.string == key.address?.string, "publickey not same as the sign key")
let result = key.isValid(signature: signature, message: message)
XCTAssert(result, "Valid Signature and message failed")
}
}
/// 测试验证比特币消息认证功能
func testVerifyBitcoinSignedMessage() {
// let signature = "1c21458a7f6765a48aaf9ec8e7e515ac4c24608607ae4f31fd03e3bae996ac551352b7f4c73cc5ed1c77c7a155100d400585d3982ac4a6c949327fec9802f5332d".hexData!
// let message = "My name is Chance, and I am a bitcoinSwift developer."
// guard let publickey = BTCKey.verify(signature: signature, message: message) else {
// XCTAssert(false, "Valid Signature and message failed")
// return
// }
}
}
| mit | e5947bee54a27b10e8f1299f2647de1d | 32.941176 | 197 | 0.571274 | 3.707631 | false | true | false | false |
nessBautista/iOSBackup | iOSNotebook/Pods/RxSwift/RxSwift/Disposables/SerialDisposable.swift | 18 | 2195 | //
// SerialDisposable.swift
// RxSwift
//
// Created by Krunoslav Zaher on 3/12/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
/// Represents a disposable resource whose underlying disposable resource can be replaced by another disposable resource, causing automatic disposal of the previous underlying disposable resource.
public final class SerialDisposable : DisposeBase, Cancelable {
private var _lock = SpinLock()
// state
private var _current = nil as Disposable?
private var _isDisposed = false
/// - returns: Was resource disposed.
public var isDisposed: Bool {
return _isDisposed
}
/// Initializes a new instance of the `SerialDisposable`.
override public init() {
super.init()
}
/**
Gets or sets the underlying disposable.
Assigning this property disposes the previous disposable object.
If the `SerialDisposable` has already been disposed, assignment to this property causes immediate disposal of the given disposable object.
*/
public var disposable: Disposable {
get {
return _lock.calculateLocked {
return _current ?? Disposables.create()
}
}
set (newDisposable) {
let disposable: Disposable? = _lock.calculateLocked {
if _isDisposed {
return newDisposable
}
else {
let toDispose = _current
_current = newDisposable
return toDispose
}
}
if let disposable = disposable {
disposable.dispose()
}
}
}
/// Disposes the underlying disposable as well as all future replacements.
public func dispose() {
_dispose()?.dispose()
}
private func _dispose() -> Disposable? {
_lock.lock(); defer { _lock.unlock() }
if _isDisposed {
return nil
}
else {
_isDisposed = true
let current = _current
_current = nil
return current
}
}
}
| cc0-1.0 | 5b475f44bb1db01274b1b930a3085b68 | 28.253333 | 196 | 0.567001 | 5.55443 | false | false | false | false |
StupidTortoise/personal | iOS/Swift/Dictionary_test.swift | 1 | 532 |
// Swift Dictionary test
let constFruit = ["Apple":1, "Pear":3, "Banana":4]
println( constFruit["Pear"]! )
println( constFruit.count )
if constFruit.isEmpty {
println( "constFruit is empty!" )
} else {
println( "constFruit is not empty!" )
}
for (key, value) in constFruit {
println( "\(key) = \(value)" )
}
println( "============================================" )
var varFruit = [String:Int]()
varFruit["Potato"] = 13
varFruit["Tomato"] = 9
for (key, value) in varFruit {
println( "\(key) = \(value)" )
}
| gpl-2.0 | bdb242277babe578996404a12bdba171 | 18 | 57 | 0.56203 | 3.166667 | false | false | false | false |
SusanDoggie/Doggie | Sources/DoggieGPU/CoreImage/MorphologyKernel.swift | 1 | 7245 | //
// MorphologyKernel.swift
//
// The MIT License
// Copyright (c) 2015 - 2022 Susan Cheng. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#if canImport(CoreImage) && canImport(MetalPerformanceShaders)
extension CIImage {
private class AreaMinKernel: CIImageProcessorKernel {
override class var synchronizeInputs: Bool {
return false
}
override class func roi(forInput input: Int32, arguments: [String: Any]?, outputRect: CGRect) -> CGRect {
guard let radius = arguments?["radius"] as? Size else { return outputRect }
let insetX = -ceil(abs(radius.width))
let insetY = -ceil(abs(radius.height))
return outputRect.insetBy(dx: CGFloat(insetX), dy: CGFloat(insetY))
}
override class func process(with inputs: [CIImageProcessorInput]?, arguments: [String: Any]?, output: CIImageProcessorOutput) throws {
guard let commandBuffer = output.metalCommandBuffer else { return }
guard let source = inputs?[0].metalTexture else { return }
guard let source_region = inputs?[0].region else { return }
guard let destination = output.metalTexture else { return }
guard let radius = arguments?["radius"] as? Size else { return }
let kernelWidth = Int(round(abs(radius.width))) << 1 + 1
let kernelHeight = Int(round(abs(radius.height))) << 1 + 1
guard let offset_x = Int(exactly: output.region.minX - source_region.minX) else { return }
guard let offset_y = Int(exactly: source_region.maxY - output.region.maxY) else { return }
let kernel = MPSImageAreaMin(device: commandBuffer.device, kernelWidth: kernelWidth, kernelHeight: kernelHeight)
kernel.offset.x = offset_x
kernel.offset.y = offset_y
kernel.encode(commandBuffer: commandBuffer, sourceTexture: source, destinationTexture: destination)
}
}
public func areaMin(_ radius: Size) -> CIImage {
if extent.isEmpty { return .empty() }
if #available(macOS 10.15, iOS 13.0, tvOS 13.0, *) {
let areaMin = CIFilter.morphologyRectangleMinimum()
areaMin.width = Float(abs(radius.width) * 2)
areaMin.height = Float(abs(radius.height) * 2)
areaMin.inputImage = self
return areaMin.outputImage ?? .empty()
} else {
let extent = self.extent.insetBy(dx: CGFloat(ceil(abs(radius.width))), dy: CGFloat(ceil(abs(radius.height))))
if extent.isEmpty { return .empty() }
let _extent = extent.isInfinite ? extent : extent.insetBy(dx: .random(in: -1..<0), dy: .random(in: -1..<0))
var rendered = try? AreaMinKernel.apply(withExtent: _extent, inputs: [self], arguments: ["radius": radius])
if !extent.isInfinite {
rendered = rendered?.cropped(to: extent)
}
return rendered ?? .empty()
}
}
}
extension CIImage {
private class AreaMaxKernel: CIImageProcessorKernel {
override class var synchronizeInputs: Bool {
return false
}
override class func roi(forInput input: Int32, arguments: [String: Any]?, outputRect: CGRect) -> CGRect {
guard let radius = arguments?["radius"] as? Size else { return outputRect }
let insetX = -ceil(abs(radius.width))
let insetY = -ceil(abs(radius.height))
return outputRect.insetBy(dx: CGFloat(insetX), dy: CGFloat(insetY))
}
override class func process(with inputs: [CIImageProcessorInput]?, arguments: [String: Any]?, output: CIImageProcessorOutput) throws {
guard let commandBuffer = output.metalCommandBuffer else { return }
guard let source = inputs?[0].metalTexture else { return }
guard let source_region = inputs?[0].region else { return }
guard let destination = output.metalTexture else { return }
guard let radius = arguments?["radius"] as? Size else { return }
let kernelWidth = Int(round(abs(radius.width))) << 1 + 1
let kernelHeight = Int(round(abs(radius.height))) << 1 + 1
guard let offset_x = Int(exactly: output.region.minX - source_region.minX) else { return }
guard let offset_y = Int(exactly: source_region.maxY - output.region.maxY) else { return }
let kernel = MPSImageAreaMax(device: commandBuffer.device, kernelWidth: kernelWidth, kernelHeight: kernelHeight)
kernel.offset.x = offset_x
kernel.offset.y = offset_y
kernel.encode(commandBuffer: commandBuffer, sourceTexture: source, destinationTexture: destination)
}
}
public func areaMax(_ radius: Size) -> CIImage {
if extent.isEmpty { return .empty() }
if #available(macOS 10.15, iOS 13.0, tvOS 13.0, *) {
let areaMax = CIFilter.morphologyRectangleMaximum()
areaMax.width = Float(abs(radius.width) * 2)
areaMax.height = Float(abs(radius.height) * 2)
areaMax.inputImage = self
return areaMax.outputImage ?? .empty()
} else {
let extent = self.extent.insetBy(dx: CGFloat(-ceil(abs(radius.width))), dy: CGFloat(-ceil(abs(radius.height))))
let _extent = extent.isInfinite ? extent : extent.insetBy(dx: .random(in: -1..<0), dy: .random(in: -1..<0))
var rendered = try? AreaMaxKernel.apply(withExtent: _extent, inputs: [self], arguments: ["radius": radius])
if !extent.isInfinite {
rendered = rendered?.cropped(to: extent)
}
return rendered ?? .empty()
}
}
}
#endif
| mit | 5c2096ef3be8a7fd03804701e91f59bb | 43.176829 | 142 | 0.599586 | 4.570978 | false | false | false | false |
likers/MathLayout | MathLayout/ViewController.swift | 1 | 943 | //
// ViewController.swift
// MathLayout
//
// Created by Jinhuan Li on 1/2/16.
// Copyright © 2016 likers33. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
let topView = UIView()
let botView = UIView()
override func viewDidLoad() {
super.viewDidLoad()
topView.backgroundColor = UIColor.blueColor()
self.view.addSubview(topView)
botView.backgroundColor = UIColor.greenColor()
self.view.addSubview(botView)
topView.top ==== self.view.top + 50
topView.left ==== self.view.left
topView.width ==== 100
topView.height ==== 100
botView.centerXY ==== self.view.centerXY - 50
botView.width ==== 2*topView.width + 50
botView.height ==== topView.height - 50
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| mit | 730a385d8f4953e07694d0eac193163c | 22.55 | 54 | 0.597665 | 4.464455 | false | false | false | false |
hongqingWang/HQSwiftMVVM | HQSwiftMVVM/HQSwiftMVVM/Classes/View/A/Cell/HQACellPictureView.swift | 1 | 2544 | //
// HQACellPictureView.swift
// HQSwiftMVVM
//
// Created by 王红庆 on 2017/9/5.
// Copyright © 2017年 王红庆. All rights reserved.
//
import UIKit
class HQACellPictureView: UIView {
/// 配图视图的数组
var urls: [HQStatusPicture]? {
didSet {
// 隐藏所有的`ImageView`
for v in subviews {
v.isHidden = true
}
// 遍历`urls`数组,顺序设置图像
var index = 0
// for url in urls ?? [] {
//
// // 获得对应索引的`ImageView`
// let iv = subviews[index] as! UIImageView
//
// // 设置图像
//// iv.hq_setImage(urlString: url.thumbnail_pic, placeholderImage: nil)
////
//// // 显示图像
//// iv.isHidden = false
//
// index += 1
// }
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: - UI
extension HQACellPictureView {
fileprivate func setupUI() {
// 超出边界不显示
clipsToBounds = true
backgroundColor = UIColor.hq_randomColor()
/*
- `cell`中所有的控件都是提前准备好
- 设置的时候,根据数据决定是否显示
- 不要动态创建控件
*/
let count = 3
let rect = CGRect(x: 0,
y: HQStatusPictureViewOutterMargin,
width: HQStatusPictureItemWidth,
height: HQStatusPictureItemWidth)
for i in 0..<count * count {
let imageView = UIImageView()
imageView.backgroundColor = UIColor.red
// 行 -> Y
let row = CGFloat(i / count)
// 列 -> X
let col = CGFloat(i % count)
let xOffset = col * (HQStatusPictureItemWidth + HQStatusPictureViewInnerMargin)
let yOffset = row * (HQStatusPictureItemWidth + HQStatusPictureViewInnerMargin)
imageView.frame = rect.offsetBy(dx: xOffset, dy: yOffset)
addSubview(imageView)
}
}
}
| mit | 0b02c003fc982a031a45a4110e82d84d | 24.159574 | 91 | 0.4537 | 4.619141 | false | false | false | false |
ScoutHarris/WordPress-iOS | WordPressShared/WordPressSharedTests/GravatarTest.swift | 2 | 2456 | import XCTest
@testable import WordPressShared
class GravatarTest: XCTestCase {
func testUnknownGravatarUrlMatchesURLWithSubdomainAndQueryParameters() {
let url = URL(string: "https://0.gravatar.com/avatar/ad516503a11cd5ca435acc9bb6523536?s=256&r=G")!
let gravatar = Gravatar(url)
XCTAssertNil(gravatar)
}
func testUnknownGravatarUrlMatchesURLWithoutSubdomains() {
let url = URL(string: "https://0.gravatar.com/avatar/ad516503a11cd5ca435acc9bb6523536")!
let gravatar = Gravatar(url)
XCTAssertNil(gravatar)
}
func testIsUnknownGravatarUrlMatchesURLWithHttpSchema() {
let url = URL(string: "http://0.gravatar.com/avatar/ad516503a11cd5ca435acc9bb6523536")!
let gravatar = Gravatar(url)
XCTAssertNil(gravatar)
}
func testGravatarRejectsIncorrectPath() {
let url = URL(string: "http://0.gravatar.com/5b415e3c9c245e557af9f580eeb8760a")!
let gravatar = Gravatar(url)
XCTAssertNil(gravatar)
}
func testGravatarRejectsIncorrectHost() {
let url = URL(string: "http://0.argvatar.com/avatar/5b415e3c9c245e557af9f580eeb8760a")!
let gravatar = Gravatar(url)
XCTAssertNil(gravatar)
}
func testGravatarRemovesQueryParameters() {
let url = URL(string: "https://secure.gravatar.com/avatar/5b415e3c9c245e557af9f580eeb8760a?d=http://0.gravatar.com/5b415e3c9c245e557af9f580eeb8760a")!
let expected = URL(string: "https://secure.gravatar.com/avatar/5b415e3c9c245e557af9f580eeb8760a")!
let gravatar = Gravatar(url)
XCTAssertNotNil(gravatar)
XCTAssertEqual(gravatar!.canonicalURL, expected)
}
func testGravatarForcesHTTPS() {
let url = URL(string: "http://0.gravatar.com/avatar/5b415e3c9c245e557af9f580eeb8760a")!
let expected = URL(string: "https://secure.gravatar.com/avatar/5b415e3c9c245e557af9f580eeb8760a")!
let gravatar = Gravatar(url)
XCTAssertNotNil(gravatar)
XCTAssertEqual(gravatar!.canonicalURL, expected)
}
func testGravatarAppendsSizeQuery() {
let url = URL(string: "http://0.gravatar.com/avatar/5b415e3c9c245e557af9f580eeb8760a")!
let expected = URL(string: "https://secure.gravatar.com/avatar/5b415e3c9c245e557af9f580eeb8760a?s=128&d=404")!
let gravatar = Gravatar(url)
XCTAssertNotNil(gravatar)
XCTAssertEqual(gravatar!.urlWithSize(128), expected)
}
}
| gpl-2.0 | e31d6cd1e97baf62878c43390be0f6aa | 41.344828 | 158 | 0.708062 | 3.449438 | false | true | false | false |
syxc/ZhihuDaily | Pods/ObjectMapper/ObjectMapper/Core/Mapper.swift | 7 | 14349 | //
// Mapper.swift
// ObjectMapper
//
// Created by Tristan Himmelman on 2014-10-09.
//
// The MIT License (MIT)
//
// Copyright (c) 2014-2015 Hearst
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
public enum MappingType {
case FromJSON
case ToJSON
}
/// The Mapper class provides methods for converting Model objects to JSON and methods for converting JSON to Model objects
public final class Mapper<N: Mappable> {
public var context: MapContext?
public init(context: MapContext? = nil){
self.context = context
}
// MARK: Mapping functions that map to an existing object toObject
/// Maps a JSON object to an existing Mappable object if it is a JSON dictionary, or returns the passed object as is
public func map(JSON: AnyObject?, toObject object: N) -> N {
if let JSON = JSON as? [String : AnyObject] {
return map(JSON, toObject: object)
}
return object
}
/// Map a JSON string onto an existing object
public func map(JSONString: String, toObject object: N) -> N {
if let JSON = Mapper.parseJSONDictionary(JSONString) {
return map(JSON, toObject: object)
}
return object
}
/// Maps a JSON dictionary to an existing object that conforms to Mappable.
/// Usefull for those pesky objects that have crappy designated initializers like NSManagedObject
public func map(JSONDictionary: [String : AnyObject], toObject object: N) -> N {
var mutableObject = object
let map = Map(mappingType: .FromJSON, JSONDictionary: JSONDictionary, toObject: true, context: context)
mutableObject.mapping(map)
return mutableObject
}
//MARK: Mapping functions that create an object
/// Map an optional JSON string to an object that conforms to Mappable
public func map(JSONString: String?) -> N? {
if let JSONString = JSONString {
return map(JSONString)
}
return nil
}
/// Map a JSON string to an object that conforms to Mappable
public func map(JSONString: String) -> N? {
if let JSON = Mapper.parseJSONDictionary(JSONString) {
return map(JSON)
}
return nil
}
/// Map a JSON NSString to an object that conforms to Mappable
public func map(JSONString: NSString) -> N? {
return map(JSONString as String)
}
/// Maps a JSON object to a Mappable object if it is a JSON dictionary or NSString, or returns nil.
public func map(JSON: AnyObject?) -> N? {
if let JSON = JSON as? [String : AnyObject] {
return map(JSON)
}
return nil
}
/// Maps a JSON dictionary to an object that conforms to Mappable
public func map(JSONDictionary: [String : AnyObject]) -> N? {
let map = Map(mappingType: .FromJSON, JSONDictionary: JSONDictionary, context: context)
// check if object is StaticMappable
if let klass = N.self as? StaticMappable.Type {
if var object = klass.objectForMapping(map) as? N {
object.mapping(map)
return object
}
}
// fall back to using init? to create N
if var object = N(map) {
object.mapping(map)
return object
}
return nil
}
// MARK: Mapping functions for Arrays and Dictionaries
/// Maps a JSON array to an object that conforms to Mappable
public func mapArray(JSONString: String) -> [N]? {
let parsedJSON: AnyObject? = Mapper.parseJSONString(JSONString)
if let objectArray = mapArray(parsedJSON) {
return objectArray
}
// failed to parse JSON into array form
// try to parse it into a dictionary and then wrap it in an array
if let object = map(parsedJSON) {
return [object]
}
return nil
}
/// Maps a optional JSON String into an array of objects that conforms to Mappable
public func mapArray(JSONString: String?) -> [N]? {
if let JSONString = JSONString {
return mapArray(JSONString)
}
return nil
}
/// Maps a JSON object to an array of Mappable objects if it is an array of JSON dictionary, or returns nil.
public func mapArray(JSON: AnyObject?) -> [N]? {
if let JSONArray = JSON as? [[String : AnyObject]] {
return mapArray(JSONArray)
}
return nil
}
/// Maps an array of JSON dictionary to an array of Mappable objects
public func mapArray(JSONArray: [[String : AnyObject]]) -> [N]? {
// map every element in JSON array to type N
let result = JSONArray.flatMap(map)
return result
}
/// Maps a JSON object to a dictionary of Mappable objects if it is a JSON dictionary of dictionaries, or returns nil.
public func mapDictionary(JSONString: String) -> [String : N]? {
let parsedJSON: AnyObject? = Mapper.parseJSONString(JSONString)
return mapDictionary(parsedJSON)
}
/// Maps a JSON object to a dictionary of Mappable objects if it is a JSON dictionary of dictionaries, or returns nil.
public func mapDictionary(JSON: AnyObject?) -> [String : N]? {
if let JSONDictionary = JSON as? [String : [String : AnyObject]] {
return mapDictionary(JSONDictionary)
}
return nil
}
/// Maps a JSON dictionary of dictionaries to a dictionary of Mappble objects
public func mapDictionary(JSONDictionary: [String : [String : AnyObject]]) -> [String : N]? {
// map every value in dictionary to type N
let result = JSONDictionary.filterMap(map)
if result.isEmpty == false {
return result
}
return nil
}
/// Maps a JSON object to a dictionary of Mappable objects if it is a JSON dictionary of dictionaries, or returns nil.
public func mapDictionary(JSON: AnyObject?, toDictionary dictionary: [String : N]) -> [String : N] {
if let JSONDictionary = JSON as? [String : [String : AnyObject]] {
return mapDictionary(JSONDictionary, toDictionary: dictionary)
}
return dictionary
}
/// Maps a JSON dictionary of dictionaries to an existing dictionary of Mappble objects
public func mapDictionary(JSONDictionary: [String : [String : AnyObject]], toDictionary dictionary: [String : N]) -> [String : N] {
var mutableDictionary = dictionary
for (key, value) in JSONDictionary {
if let object = dictionary[key] {
map(value, toObject: object)
} else {
mutableDictionary[key] = map(value)
}
}
return mutableDictionary
}
/// Maps a JSON object to a dictionary of arrays of Mappable objects
public func mapDictionaryOfArrays(JSON: AnyObject?) -> [String : [N]]? {
if let JSONDictionary = JSON as? [String : [[String : AnyObject]]] {
return mapDictionaryOfArrays(JSONDictionary)
}
return nil
}
///Maps a JSON dictionary of arrays to a dictionary of arrays of Mappable objects
public func mapDictionaryOfArrays(JSONDictionary: [String : [[String : AnyObject]]]) -> [String : [N]]? {
// map every value in dictionary to type N
let result = JSONDictionary.filterMap {
mapArray($0)
}
if result.isEmpty == false {
return result
}
return nil
}
/// Maps an 2 dimentional array of JSON dictionaries to a 2 dimentional array of Mappable objects
public func mapArrayOfArrays(JSON: AnyObject?) -> [[N]]? {
if let JSONArray = JSON as? [[[String : AnyObject]]] {
var objectArray = [[N]]()
for innerJSONArray in JSONArray {
if let array = mapArray(innerJSONArray){
objectArray.append(array)
}
}
if objectArray.isEmpty == false {
return objectArray
}
}
return nil
}
// MARK: Utility functions for converting strings to JSON objects
/// Convert a JSON String into a Dictionary<String, AnyObject> using NSJSONSerialization
public static func parseJSONDictionary(JSON: String) -> [String : AnyObject]? {
let parsedJSON: AnyObject? = Mapper.parseJSONString(JSON)
return Mapper.parseJSONDictionary(parsedJSON)
}
/// Convert a JSON Object into a Dictionary<String, AnyObject> using NSJSONSerialization
public static func parseJSONDictionary(JSON: AnyObject?) -> [String : AnyObject]? {
if let JSONDict = JSON as? [String : AnyObject] {
return JSONDict
}
return nil
}
/// Convert a JSON String into an Object using NSJSONSerialization
public static func parseJSONString(JSON: String) -> AnyObject? {
let data = JSON.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
if let data = data {
let parsedJSON: AnyObject?
do {
parsedJSON = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments)
} catch let error {
print(error)
parsedJSON = nil
}
return parsedJSON
}
return nil
}
}
extension Mapper {
// MARK: Functions that create JSON from objects
///Maps an object that conforms to Mappable to a JSON dictionary <String : AnyObject>
public func toJSON(object: N) -> [String : AnyObject] {
var mutableObject = object
let map = Map(mappingType: .ToJSON, JSONDictionary: [:], context: context)
mutableObject.mapping(map)
return map.JSONDictionary
}
///Maps an array of Objects to an array of JSON dictionaries [[String : AnyObject]]
public func toJSONArray(array: [N]) -> [[String : AnyObject]] {
return array.map {
// convert every element in array to JSON dictionary equivalent
self.toJSON($0)
}
}
///Maps a dictionary of Objects that conform to Mappable to a JSON dictionary of dictionaries.
public func toJSONDictionary(dictionary: [String : N]) -> [String : [String : AnyObject]] {
return dictionary.map { k, v in
// convert every value in dictionary to its JSON dictionary equivalent
return (k, self.toJSON(v))
}
}
///Maps a dictionary of Objects that conform to Mappable to a JSON dictionary of dictionaries.
public func toJSONDictionaryOfArrays(dictionary: [String : [N]]) -> [String : [[String : AnyObject]]] {
return dictionary.map { k, v in
// convert every value (array) in dictionary to its JSON dictionary equivalent
return (k, self.toJSONArray(v))
}
}
/// Maps an Object to a JSON string with option of pretty formatting
public func toJSONString(object: N, prettyPrint: Bool = false) -> String? {
let JSONDict = toJSON(object)
return Mapper.toJSONString(JSONDict, prettyPrint: prettyPrint)
}
/// Maps an array of Objects to a JSON string with option of pretty formatting
public func toJSONString(array: [N], prettyPrint: Bool = false) -> String? {
let JSONDict = toJSONArray(array)
return Mapper.toJSONString(JSONDict, prettyPrint: prettyPrint)
}
/// Converts an Object to a JSON string with option of pretty formatting
public static func toJSONString(JSONObject: AnyObject, prettyPrint: Bool) -> String? {
let options: NSJSONWritingOptions = prettyPrint ? .PrettyPrinted : []
if let JSON = Mapper.toJSONData(JSONObject, options: options) {
return String(data: JSON, encoding: NSUTF8StringEncoding)
}
return nil
}
/// Converts an Object to JSON data with options
public static func toJSONData(JSONObject: AnyObject, options: NSJSONWritingOptions) -> NSData? {
if NSJSONSerialization.isValidJSONObject(JSONObject) {
let JSONData: NSData?
do {
JSONData = try NSJSONSerialization.dataWithJSONObject(JSONObject, options: options)
} catch let error {
print(error)
JSONData = nil
}
return JSONData
}
return nil
}
}
extension Mapper where N: Hashable {
/// Maps a JSON array to an object that conforms to Mappable
public func mapSet(JSONString: String) -> Set<N>? {
let parsedJSON: AnyObject? = Mapper.parseJSONString(JSONString)
if let objectArray = mapArray(parsedJSON) {
return Set(objectArray)
}
// failed to parse JSON into array form
// try to parse it into a dictionary and then wrap it in an array
if let object = map(parsedJSON) {
return Set([object])
}
return nil
}
/// Maps a JSON object to an Set of Mappable objects if it is an array of JSON dictionary, or returns nil.
public func mapSet(JSON: AnyObject?) -> Set<N>? {
if let JSONArray = JSON as? [[String : AnyObject]] {
return mapSet(JSONArray)
}
return nil
}
/// Maps an Set of JSON dictionary to an array of Mappable objects
public func mapSet(JSONArray: [[String : AnyObject]]) -> Set<N> {
// map every element in JSON array to type N
return Set(JSONArray.flatMap(map))
}
///Maps a Set of Objects to a Set of JSON dictionaries [[String : AnyObject]]
public func toJSONSet(set: Set<N>) -> [[String : AnyObject]] {
return set.map {
// convert every element in set to JSON dictionary equivalent
self.toJSON($0)
}
}
/// Maps a set of Objects to a JSON string with option of pretty formatting
public func toJSONString(set: Set<N>, prettyPrint: Bool = false) -> String? {
let JSONDict = toJSONSet(set)
return Mapper.toJSONString(JSONDict, prettyPrint: prettyPrint)
}
}
extension Dictionary {
internal func map<K: Hashable, V>(@noescape f: Element -> (K, V)) -> [K : V] {
var mapped = [K : V]()
for element in self {
let newElement = f(element)
mapped[newElement.0] = newElement.1
}
return mapped
}
internal func map<K: Hashable, V>(@noescape f: Element -> (K, [V])) -> [K : [V]] {
var mapped = [K : [V]]()
for element in self {
let newElement = f(element)
mapped[newElement.0] = newElement.1
}
return mapped
}
internal func filterMap<U>(@noescape f: Value -> U?) -> [Key : U] {
var mapped = [Key : U]()
for (key, value) in self {
if let newValue = f(value) {
mapped[key] = newValue
}
}
return mapped
}
}
| mit | 3820901c9ba0b350a045b5e25a0459b1 | 30.193478 | 135 | 0.69754 | 3.96053 | false | false | false | false |
agilewalker/SwiftyChardet | SwiftyChardet/escsm.swift | 1 | 10443 | /*
######################## BEGIN LICENSE BLOCK ########################
# The Original Code is mozilla.org code.
#
# The Initial Developer of the Original Code is
# Netscape Communications Corporation.
# Portions created by the Initial Developer are Copyright (C) 1998
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
# Wu Hui Yuan - port to Swift
# Mark Pilgrim - port to Python
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
# 02110-1301 USA
######################### END LICENSE BLOCK #########################
*/
let HZ_CLS: [Int] = [
1, 0, 0, 0, 0, 0, 0, 0, // 00 - 07
0, 0, 0, 0, 0, 0, 0, 0, // 08 - 0f
0, 0, 0, 0, 0, 0, 0, 0, // 10 - 17
0, 0, 0, 1, 0, 0, 0, 0, // 18 - 1f
0, 0, 0, 0, 0, 0, 0, 0, // 20 - 27
0, 0, 0, 0, 0, 0, 0, 0, // 28 - 2f
0, 0, 0, 0, 0, 0, 0, 0, // 30 - 37
0, 0, 0, 0, 0, 0, 0, 0, // 38 - 3f
0, 0, 0, 0, 0, 0, 0, 0, // 40 - 47
0, 0, 0, 0, 0, 0, 0, 0, // 48 - 4f
0, 0, 0, 0, 0, 0, 0, 0, // 50 - 57
0, 0, 0, 0, 0, 0, 0, 0, // 58 - 5f
0, 0, 0, 0, 0, 0, 0, 0, // 60 - 67
0, 0, 0, 0, 0, 0, 0, 0, // 68 - 6f
0, 0, 0, 0, 0, 0, 0, 0, // 70 - 77
0, 0, 0, 4, 0, 5, 2, 0, // 78 - 7f
1, 1, 1, 1, 1, 1, 1, 1, // 80 - 87
1, 1, 1, 1, 1, 1, 1, 1, // 88 - 8f
1, 1, 1, 1, 1, 1, 1, 1, // 90 - 97
1, 1, 1, 1, 1, 1, 1, 1, // 98 - 9f
1, 1, 1, 1, 1, 1, 1, 1, // a0 - a7
1, 1, 1, 1, 1, 1, 1, 1, // a8 - af
1, 1, 1, 1, 1, 1, 1, 1, // b0 - b7
1, 1, 1, 1, 1, 1, 1, 1, // b8 - bf
1, 1, 1, 1, 1, 1, 1, 1, // c0 - c7
1, 1, 1, 1, 1, 1, 1, 1, // c8 - cf
1, 1, 1, 1, 1, 1, 1, 1, // d0 - d7
1, 1, 1, 1, 1, 1, 1, 1, // d8 - df
1, 1, 1, 1, 1, 1, 1, 1, // e0 - e7
1, 1, 1, 1, 1, 1, 1, 1, // e8 - ef
1, 1, 1, 1, 1, 1, 1, 1, // f0 - f7
1, 1, 1, 1, 1, 1, 1, 1, // f8 - ff
]
let HZ_ST: [MachineState] = [
.start, .error, ._3, .start, .start, .start, .error, .error, // 00-07
.error, .error, .error, .error, .its_me, .its_me, .its_me, .its_me, // 08-0f
.its_me, .its_me, .error, .error, .start, .start, ._4, .error, // 10-17
._5, .error, ._6, .error, ._5, ._5, ._4, .error, // 18-1f
._4, .error, ._4, ._4, ._4, .error, ._4, .error, // 20-27
._4, .its_me, .start, .start, .start, .start, .start, .start, // 28-2f
]
let HZ_CHAR_LEN_TABLE = [0, 0, 0, 0, 0, 0]
let HZ_SM_MODEL = (
class_table: HZ_CLS,
class_factor: 6,
state_table: HZ_ST,
char_len_table: HZ_CHAR_LEN_TABLE,
name: "HZ-GB-2312")
let ISO2022CN_CLS: [Int] = [
2, 0, 0, 0, 0, 0, 0, 0, // 00 - 07
0, 0, 0, 0, 0, 0, 0, 0, // 08 - 0f
0, 0, 0, 0, 0, 0, 0, 0, // 10 - 17
0, 0, 0, 1, 0, 0, 0, 0, // 18 - 1f
0, 0, 0, 0, 0, 0, 0, 0, // 20 - 27
0, 3, 0, 0, 0, 0, 0, 0, // 28 - 2f
0, 0, 0, 0, 0, 0, 0, 0, // 30 - 37
0, 0, 0, 0, 0, 0, 0, 0, // 38 - 3f
0, 0, 0, 4, 0, 0, 0, 0, // 40 - 47
0, 0, 0, 0, 0, 0, 0, 0, // 48 - 4f
0, 0, 0, 0, 0, 0, 0, 0, // 50 - 57
0, 0, 0, 0, 0, 0, 0, 0, // 58 - 5f
0, 0, 0, 0, 0, 0, 0, 0, // 60 - 67
0, 0, 0, 0, 0, 0, 0, 0, // 68 - 6f
0, 0, 0, 0, 0, 0, 0, 0, // 70 - 77
0, 0, 0, 0, 0, 0, 0, 0, // 78 - 7f
2, 2, 2, 2, 2, 2, 2, 2, // 80 - 87
2, 2, 2, 2, 2, 2, 2, 2, // 88 - 8f
2, 2, 2, 2, 2, 2, 2, 2, // 90 - 97
2, 2, 2, 2, 2, 2, 2, 2, // 98 - 9f
2, 2, 2, 2, 2, 2, 2, 2, // a0 - a7
2, 2, 2, 2, 2, 2, 2, 2, // a8 - af
2, 2, 2, 2, 2, 2, 2, 2, // b0 - b7
2, 2, 2, 2, 2, 2, 2, 2, // b8 - bf
2, 2, 2, 2, 2, 2, 2, 2, // c0 - c7
2, 2, 2, 2, 2, 2, 2, 2, // c8 - cf
2, 2, 2, 2, 2, 2, 2, 2, // d0 - d7
2, 2, 2, 2, 2, 2, 2, 2, // d8 - df
2, 2, 2, 2, 2, 2, 2, 2, // e0 - e7
2, 2, 2, 2, 2, 2, 2, 2, // e8 - ef
2, 2, 2, 2, 2, 2, 2, 2, // f0 - f7
2, 2, 2, 2, 2, 2, 2, 2, // f8 - ff
]
let ISO2022CN_ST: [MachineState] = [
.start, ._3, .error, .start, .start, .start, .start, .start, // 00-07
.start, .error, .error, .error, .error, .error, .error, .error, // 08-0f
.error, .error, .its_me, .its_me, .its_me, .its_me, .its_me, .its_me, // 10-17
.its_me, .its_me, .its_me, .error, .error, .error, ._4, .error, // 18-1f
.error, .error, .error, .its_me, .error, .error, .error, .error, // 20-27
._5, ._6, .error, .error, .error, .error, .error, .error, // 28-2f
.error, .error, .error, .its_me, .error, .error, .error, .error, // 30-37
.error, .error, .error, .error, .error, .its_me, .error, .start, // 38-3f
]
let ISO2022CN_CHAR_LEN_TABLE = [0, 0, 0, 0, 0, 0, 0, 0, 0]
let ISO2022CN_SM_MODEL = (
class_table: ISO2022CN_CLS,
class_factor: 9,
state_table: ISO2022CN_ST,
char_len_table: ISO2022CN_CHAR_LEN_TABLE,
name: "ISO-2022-CN")
let ISO2022JP_CLS: [Int] = [
2, 0, 0, 0, 0, 0, 0, 0, // 00 - 07
0, 0, 0, 0, 0, 0, 2, 2, // 08 - 0f
0, 0, 0, 0, 0, 0, 0, 0, // 10 - 17
0, 0, 0, 1, 0, 0, 0, 0, // 18 - 1f
0, 0, 0, 0, 7, 0, 0, 0, // 20 - 27
3, 0, 0, 0, 0, 0, 0, 0, // 28 - 2f
0, 0, 0, 0, 0, 0, 0, 0, // 30 - 37
0, 0, 0, 0, 0, 0, 0, 0, // 38 - 3f
6, 0, 4, 0, 8, 0, 0, 0, // 40 - 47
0, 9, 5, 0, 0, 0, 0, 0, // 48 - 4f
0, 0, 0, 0, 0, 0, 0, 0, // 50 - 57
0, 0, 0, 0, 0, 0, 0, 0, // 58 - 5f
0, 0, 0, 0, 0, 0, 0, 0, // 60 - 67
0, 0, 0, 0, 0, 0, 0, 0, // 68 - 6f
0, 0, 0, 0, 0, 0, 0, 0, // 70 - 77
0, 0, 0, 0, 0, 0, 0, 0, // 78 - 7f
2, 2, 2, 2, 2, 2, 2, 2, // 80 - 87
2, 2, 2, 2, 2, 2, 2, 2, // 88 - 8f
2, 2, 2, 2, 2, 2, 2, 2, // 90 - 97
2, 2, 2, 2, 2, 2, 2, 2, // 98 - 9f
2, 2, 2, 2, 2, 2, 2, 2, // a0 - a7
2, 2, 2, 2, 2, 2, 2, 2, // a8 - af
2, 2, 2, 2, 2, 2, 2, 2, // b0 - b7
2, 2, 2, 2, 2, 2, 2, 2, // b8 - bf
2, 2, 2, 2, 2, 2, 2, 2, // c0 - c7
2, 2, 2, 2, 2, 2, 2, 2, // c8 - cf
2, 2, 2, 2, 2, 2, 2, 2, // d0 - d7
2, 2, 2, 2, 2, 2, 2, 2, // d8 - df
2, 2, 2, 2, 2, 2, 2, 2, // e0 - e7
2, 2, 2, 2, 2, 2, 2, 2, // e8 - ef
2, 2, 2, 2, 2, 2, 2, 2, // f0 - f7
2, 2, 2, 2, 2, 2, 2, 2, // f8 - ff
]
let ISO2022JP_ST: [MachineState] = [
.start, ._3, .error, .start, .start, .start, .start, .start, // 00-07
.start, .start, .error, .error, .error, .error, .error, .error, // 08-0f
.error, .error, .error, .error, .its_me, .its_me, .its_me, .its_me, // 10-17
.its_me, .its_me, .its_me, .its_me, .its_me, .its_me, .error, .error, // 18-1f
.error, ._5, .error, .error, .error, ._4, .error, .error, // 20-27
.error, .error, .error, ._6, .its_me, .error, .its_me, .error, // 28-2f
.error, .error, .error, .error, .error, .error, .its_me, .its_me, // 30-37
.error, .error, .error, .its_me, .error, .error, .error, .error, // 38-3f
.error, .error, .error, .error, .its_me, .error, .start, .start, // 40-47
]
let ISO2022JP_CHAR_LEN_TABLE = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
let ISO2022JP_SM_MODEL = (
class_table: ISO2022JP_CLS,
class_factor: 10,
state_table: ISO2022JP_ST,
char_len_table: ISO2022JP_CHAR_LEN_TABLE,
name: "ISO-2022-JP")
let ISO2022KR_CLS: [Int] = [
2, 0, 0, 0, 0, 0, 0, 0, // 00 - 07
0, 0, 0, 0, 0, 0, 0, 0, // 08 - 0f
0, 0, 0, 0, 0, 0, 0, 0, // 10 - 17
0, 0, 0, 1, 0, 0, 0, 0, // 18 - 1f
0, 0, 0, 0, 3, 0, 0, 0, // 20 - 27
0, 4, 0, 0, 0, 0, 0, 0, // 28 - 2f
0, 0, 0, 0, 0, 0, 0, 0, // 30 - 37
0, 0, 0, 0, 0, 0, 0, 0, // 38 - 3f
0, 0, 0, 5, 0, 0, 0, 0, // 40 - 47
0, 0, 0, 0, 0, 0, 0, 0, // 48 - 4f
0, 0, 0, 0, 0, 0, 0, 0, // 50 - 57
0, 0, 0, 0, 0, 0, 0, 0, // 58 - 5f
0, 0, 0, 0, 0, 0, 0, 0, // 60 - 67
0, 0, 0, 0, 0, 0, 0, 0, // 68 - 6f
0, 0, 0, 0, 0, 0, 0, 0, // 70 - 77
0, 0, 0, 0, 0, 0, 0, 0, // 78 - 7f
2, 2, 2, 2, 2, 2, 2, 2, // 80 - 87
2, 2, 2, 2, 2, 2, 2, 2, // 88 - 8f
2, 2, 2, 2, 2, 2, 2, 2, // 90 - 97
2, 2, 2, 2, 2, 2, 2, 2, // 98 - 9f
2, 2, 2, 2, 2, 2, 2, 2, // a0 - a7
2, 2, 2, 2, 2, 2, 2, 2, // a8 - af
2, 2, 2, 2, 2, 2, 2, 2, // b0 - b7
2, 2, 2, 2, 2, 2, 2, 2, // b8 - bf
2, 2, 2, 2, 2, 2, 2, 2, // c0 - c7
2, 2, 2, 2, 2, 2, 2, 2, // c8 - cf
2, 2, 2, 2, 2, 2, 2, 2, // d0 - d7
2, 2, 2, 2, 2, 2, 2, 2, // d8 - df
2, 2, 2, 2, 2, 2, 2, 2, // e0 - e7
2, 2, 2, 2, 2, 2, 2, 2, // e8 - ef
2, 2, 2, 2, 2, 2, 2, 2, // f0 - f7
2, 2, 2, 2, 2, 2, 2, 2, // f8 - ff
]
let ISO2022KR_ST: [MachineState] = [
.start, ._3, .error, .start, .start, .start, .error, .error, // 00-07
.error, .error, .error, .error, .its_me, .its_me, .its_me, .its_me, // 08-0f
.its_me, .its_me, .error, .error, .error, ._4, .error, .error, // 10-17
.error, .error, .error, .error, ._5, .error, .error, .error, // 18-1f
.error, .error, .error, .its_me, .start, .start, .start, .start, // 20-27
]
let ISO2022KR_CHAR_LEN_TABLE = [0, 0, 0, 0, 0, 0]
let ISO2022KR_SM_MODEL = (
class_table: ISO2022KR_CLS,
class_factor: 6,
state_table: ISO2022KR_ST,
char_len_table: ISO2022KR_CHAR_LEN_TABLE,
name: "ISO-2022-KR")
| lgpl-2.1 | cd01258708d3f6c6336329d05a0412fa | 41.45122 | 108 | 0.406205 | 2.212969 | false | false | false | false |
sammy0025/SST-Announcer | SST Announcer/AppDelegate.swift | 1 | 5963 | //
// AppDelegate.swift
// SST Announcer
//
// Created by Pan Ziyue on 19/11/16.
// Copyright © 2016 FourierIndustries. All rights reserved.
//
import UIKit
import OneSignal
import Fabric
import Crashlytics
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
// swiftlint:disable line_length
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
Fabric.with([Crashlytics.self, Answers.self])
let appId = "76349b34-5515-4dbe-91bd-3dff5ca1e780"
OneSignal.initWithLaunchOptions(launchOptions, appId: appId) { result in
guard let result = result else {
AnnouncerError(type: .unwrapError, errorDescription: "Unable to unwrap push result!").relayTelemetry()
Logger.shared.log.debug("[SEVERE]: Unable to unwrap result!")
return
}
let payload = result.notification.payload
guard let title = payload?.title else {
AnnouncerError(type: .unwrapError, errorDescription: "Unable to unwrap payload title!").relayTelemetry()
Logger.shared.log.debug("[SEVERE]: Unable to unwrap payload's title!")
return
}
guard let fullMessage = payload?.body else {
AnnouncerError(type: .unwrapError, errorDescription: "Unable to unwrap fullMessage!").relayTelemetry()
Logger.shared.log.debug("[SEVERE]: Unable to unwrap fullMessage!")
return
}
guard let splitViewController = self.window!.rootViewController as? SplitViewController else {
Logger.shared.log.debug("[SEVERE]: Unable to unwrap SplitViewController!")
return
}
// Check if this is a "New Post!" type of message
if title == "New Post!" {
guard let additionalData = payload?.additionalData else {
Logger.shared.log.debug("[SEVERE]: Unable to unwrap additional data dictionary from payload")
return
}
guard let link = additionalData["link"] as? String else {
Logger.shared.log.debug("[SEVERE]: Unable to unwrap link from additionalData array")
return
}
let payloadFeedItem = FeedItem()
payloadFeedItem.title = fullMessage
payloadFeedItem.link = link
/*
Please take note: there is a complicated chain of data passing here and I will explain it here
This is the messaging mechanism for passing data from the push notification to the
MainTableViewController
AppDelegate > SplitViewController > SplitViewControllerPushDelegate > MainTableViewController
Reason: This piece of code is run on a seperate thread that is different from the Main Thread.
As a result, I cannot synchronously pass the data by setting some global property
(which is bad practice in the first place)
As such, a more complex messaging system was devised, based mostly on property observers and
protocol/delegates was made to ensure relative robustness compaired to a global state.
Steps:
1. AppDelegate retrieves the feed item, assigns it as a property of the SplitViewController <-
2. SplitViewController has a property observer on pushedFeedItem, which triggers a delegate call
3. The MainTableViewController receives this delegate call, and initiates the segue
*/
splitViewController.pushedFeedItem = payloadFeedItem
} else if title == "Notice" {
// Notice type push notifications, which shows a UIAlertController instead
let alertView = UIAlertController(title: title, message: fullMessage, preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "Okay", style: .cancel, handler: nil)
alertView.addAction(cancelAction)
splitViewController.present(alertView, animated: true, completion: nil)
} else {
// Handle other types of push notifications here in the future
Logger.shared.log.debug("[DEBUG]: An unknown push notification type was opened")
}
}
return true
}
// swiftlint:enable line_length
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 invalidate graphics rendering
// callbacks.
// Games should use this method to pause the game.
UserDefaults.standard.synchronize()
}
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 active 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:.
}
}
| gpl-2.0 | 5c57a4c69a484fee4ac50d34d15ce62a | 45.578125 | 142 | 0.711506 | 5.157439 | false | false | false | false |
GrandCentralBoard/GrandCentralBoard | GrandCentralBoard/Widgets/WebsiteAnalytics/PageViewsSource.swift | 2 | 2270 | //
// GoogleAnalyticsSource.swift
// GrandCentralBoard
//
// Created by Michał Laskowski on 18.04.2016.
// Copyright © 2016 Oktawian Chojnacki. All rights reserved.
//
import GCBCore
enum GoogleAnalyticsSourceError: ErrorType, HavingMessage {
case DateFormattingError(fromDate: NSDate, daysDifference: Int)
var message: String {
switch self {
case .DateFormattingError:
return NSLocalizedString("Failed to format date", comment: "")
}
}
}
final class PageViewsSource: Asynchronous {
private let dataProvider: AnalyticsDataProviding
private let daysInReport: Int
private let validPathPrefix: String?
let interval: NSTimeInterval
typealias ResultType = Result<[PageViewsRowReport]>
var sourceType: SourceType {
return .Momentary
}
init(dataProvider: AnalyticsDataProviding, daysInReport: Int, refreshInterval: NSTimeInterval = 5*60, validPathPrefix: String?) {
self.dataProvider = dataProvider
self.interval = refreshInterval
self.daysInReport = daysInReport
self.validPathPrefix = validPathPrefix
}
func read(closure: (ResultType) -> Void) {
let now = NSDate()
guard let reportStartTime = now.dateWith(hour: 0, minute: 0, second: 0)?.dateMinusDays(daysInReport) else {
closure(.Failure(GoogleAnalyticsSourceError.DateFormattingError(fromDate: now, daysDifference: daysInReport)))
return
}
let validPathPrefix = self.validPathPrefix
dataProvider.pageViewsReportFromDate(reportStartTime, toDate: now) { result in
switch result {
case .Success(let report):
let pageViews = report.rows.flatMap { row -> PageViewsRowReport? in
let pageViewsReport = PageViewsRowReport(analyticsReportRow:row)
if let pageViewsReport = pageViewsReport, prefix = validPathPrefix where !pageViewsReport.hasTitleWithPrefix(prefix) {
return nil
}
return pageViewsReport
}
closure(.Success(pageViews))
case .Failure(let error):
closure(.Failure(error))
}
}
}
}
| gpl-3.0 | 546f8ac265dfe2b489eb3406bd302fe1 | 32.352941 | 138 | 0.646825 | 5.131222 | false | false | false | false |
alexbredy/ABBadgeButton | Example/ABBadgeButton/ViewController.swift | 1 | 2457 | //
// ViewController.swift
// ABBadgeButton
//
// Created by Alexander Bredy on 11/08/2016.
// Copyright (c) 2016 Alexander Bredy. All rights reserved.
//
import UIKit
import ABBadgeButton
class ViewController: UIViewController {
@IBOutlet weak var chatButton: ABBadgeButton!
@IBOutlet weak var imageButton: ABBadgeButton!
@IBOutlet weak var textButton: ABBadgeButton!
override func viewDidLoad() {
super.viewDidLoad()
title = "BADGE BUTTON DEMO"
/*Basic usage of the button - gets displayed by setting the badgeValue property*/
textButton.badgeValue = "1"
textButton.badgeBackgroundColor = UIColor.blue
/* Works with icon fonts as well. In this example we are also overriding the badge origin offset in order to position the badge where we want
*/
chatButton.titleLabel?.font = UIFont(name: "IcoMoon-Free", size: 30)
chatButton.setTitle("\u{e96d}", for: .normal)
chatButton.badgeValue = "5"
chatButton.setTitleColor(UIColor.white, for: .normal)
chatButton.badgeOriginOffset = CGPoint(x: -5, y: 5)
/* This example illustrates setting the badge button when an image is used for the button instead of text. We are also setting a border width and a border color.
*/
imageButton.badgeValue = "10"
imageButton.badgeBorderColor = UIColor.white.cgColor
imageButton.badgeOriginOffset = CGPoint(x: 0, y: 12)
imageButton.badgeFont = UIFont.systemFont(ofSize: 20)
imageButton.badgeBorderWidth = 2
imageButton.badgeBackgroundColor = UIColor.purple
/* This last example showcases the usage of ABBadgeButton inside a UINavigationBar bar button
*/
let smileyButton = ABBadgeButton(type: .system)
smileyButton.frame = CGRect(x: 0, y: 0, width: 24, height: 24)
smileyButton.titleLabel?.font = UIFont(name: "IcoMoon-Free", size: 24)
smileyButton.setTitle("\u{e9e9}", for: .normal)
smileyButton.setTitleColor(UIColor.white, for: .normal)
smileyButton.badgeValue = "9"
smileyButton.addTarget(self, action: #selector(didSelectBarButton), for: .touchUpInside)
let barButton = UIBarButtonItem(customView: smileyButton)
navigationItem.rightBarButtonItem = barButton
}
func didSelectBarButton(){
print("button clicked")
}
}
| mit | ed2bb21b80051f3df2c1e92baf06acfb | 37.390625 | 169 | 0.668702 | 4.459165 | false | false | false | false |
object-kazu/JabberwockProtoType | JabberWock/JabberWockTests/HTML_TEST/bistrongTest.swift | 1 | 3210 | //
// bistrongTest.swift
// JabberWock
//
// Created by kazuyuki shimizu on 2016/12/20.
// Copyright © 2016年 momiji-mac. All rights reserved.
//
import XCTest
class bistrongTest: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
// <b>
func test_b (){
let bb = B()
bb.content = "bold"
//bb.press()
XCTAssertEqual(bb.tgStr(), "<b>bold</b>")
/* answer
<b>bold</b>
*/
}
func test_b_init () {
let bb = B(content: "bold")
//bb.press()
XCTAssertEqual(bb.tgStr(), "<b>bold</b>")
/* answer
<b>bold</b>
*/
}
func test_b_id (){
let bb = B(content: "bold")
bb.setID(id: "test")
//bb.press()
XCTAssertEqual(bb.tgStr(), "<b id=\"test\">bold</b>")
/* answer
<B id="test">bold</B>
*/
}
func test_b_tSt (){
let test = "bold string"
let ans = "<b>bold string</b>"
let bb = B(content: test)
let t = bb.tgStr()
XCTAssertNotEqual(test, t)
XCTAssertEqual(ans, t)
}
// <i>
func test_i () {
let ii = I()
ii.content = "italic test"
let ans = ii.press()
XCTAssertEqual(ans, "<i>italic test</i>")
/* answer
<i>italic test</i>
*/
}
func test_i_init (){
let ii = I(content: "italic")
ii.press()
/* answer
<i>italic</i>
*/
}
//<strong>
func test_strong () {
let st = STRONG()
st.content = "strong"
let ans = st.press()
XCTAssertEqual(ans, "<strong>strong</strong>")
/* answer
<strong>strong</strong>
*/
}
func test_strong_init () {
let st = STRONG(content: "stronger")
st.press()
/* answer
<strong>stronger</strong>
*/
}
// </br>
func test_br () {
let br = BR()
br.content = "this is br testing"
XCTAssertEqual(br.tgStr(), "this is br testing<br>")
//br.press()
/* answer
this is br testing<br>
*/
}
// func test_p_and_br () {
// let br = BR(content: "this is test")
// let p = P()
// p.contents = ["test1", "test2" + br.tgStr() + "yes!" , "test3"]
// p.press()
// /* answer
// <p>test1</p>
// <p>test2this is test<br>yes!</p>
// <p>test3</p>
//
// */
//
// }
//
// // <backquote>
// func test_backquote () {
// let bq = BLOCKQUOTE()
// bq.content = "test"
// bq.press()
//
// /* answer
//
// <blockquote>test</blockquote>
//
// */
//
// }
}
| mit | da692f14a53f971666fd18d2b539c160 | 19.297468 | 111 | 0.434986 | 3.636054 | false | true | false | false |
ytfhqqu/iCC98 | CC98Kit/CC98Kit/Deprecated/ConstantsExt.swift | 1 | 2394 | //
// ConstantsExt.swift
// CC98Kit
//
// Created by Duo Xu on 12/25/17.
// Copyright © 2017 Duo Xu. All rights reserved.
//
extension Constants {
// MARK: - Deprecated
/**
表示主题的保存和精华状态。
- seealso: [Page](http://api.cc98.org/Help/ResourceModel?modelName=TopicBestState)
*/
public enum TopicBestState: Int {
/// 主题不是保存或者精华主题。
case normal = 0
/// 主题是精华主题。
case best = 1
/// 主题是保存主题。
case reserved = 2
}
/**
表示主题的固顶状态。
- seealso: [Page](http://api.cc98.org/Help/ResourceModel?modelName=TopicTopState)
*/
public enum TopicTopState: Int {
/// 主题未固顶。
case none = 0
/// 主题被临时固顶。CC98 论坛未使用该功能。
case temporaryTop = 1
/// 主题被版面固顶。
case boardTop = 2
/// 主题被区域固顶。
case areaTop = 3
/// 主题被全站固顶。
case siteTop = 4
}
/**
表示发言的内容格式类型。
- seealso: [Page](http://api.cc98.org/Help/ResourceModel?modelName=PostContentType)
*/
public enum PostContentType: Int {
/// 内容使用 UBB 格式。
case ubb = 0
/// 内容使用 Markdown 格式。
case markdown = 1
}
/**
表示用户的性别。
- seealso: [Page](http://api.cc98.org/Help/ResourceModel?modelName=UserGender)
*/
public enum UserGender: Int {
/// 女性。
case female = 0
/// 男性。
case male = 1
}
/**
表示在获取消息时需要应用的筛选器类型。
- seealso: [Page](http://api.cc98.org/Help/ResourceModel?modelName=MessageFilterType)
*/
public enum MessageFilterType: Int {
/// 不获取任何消息。此项目仅用于满足类库完整性要求,请不要使用此标识。
case none = 0
/// 当前用户发出的消息。
case send = 1
/// 当前用户接收的消息。
case receive = 2
/// 同时包含当前用户发送和接收的消息。
case both = 3
}
}
| mit | 482da935656747443a21ad10a552650f | 19.827957 | 90 | 0.498709 | 3.515426 | false | false | false | false |
mitchtreece/Spider | Spider/Classes/Core/SSE/Events/EventProtocol.swift | 1 | 1544 | //
// EventProtocol.swift
// Spider-Web
//
// Created by Mitch Treece on 10/6/20.
//
import Foundation
/// Protocol describing the characteristics of a server-side-event.
public protocol EventProtocol {
/// The event's unique id.
var id: String? { get }
/// The event's type (or name).
var type: String? { get }
/// The event's data payload.
var data: String? { get }
/// The event's retry time.
var retryTime: Int? { get }
}
public extension EventProtocol /* JSON data */ {
/// A `JSON` representation of the event data.
var jsonData: JSON? {
guard let string = self.data,
let data = string.data(using: .utf8) else { return nil }
return try? JSONSerialization.jsonObject(
with: data,
options: []
) as? JSON
}
/// A `[JSON]` representation of the event data.
var jsonArrayData: [JSON]? {
guard let string = self.data,
let data = string.data(using: .utf8) else { return nil }
return try? JSONSerialization.jsonObject(
with: data,
options: []
) as? [JSON]
}
}
internal extension EventProtocol /* Retry */ {
var isRetry: Bool {
let hasAnyValue = (self.id == nil || self.type == nil || self.data == nil)
if let _ = self.retryTime, !hasAnyValue {
return true
}
return false
}
}
| mit | 4913610d88d19c11d84a3a24e2cd48f8 | 20.746479 | 82 | 0.522021 | 4.288889 | false | false | false | false |
bitboylabs/selluv-ios | selluv-ios/selluv-ios/Classes/Base/Vender/CircleMenu/CircleThumb.swift | 1 | 9286 | /**
The MIT License (MIT)
Copyright (c) 2016 Shoaib Ahmed / Sufi-Al-Hussaini
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.
*/
//
// CircleThumb.swift
// CircleMenu
//
// Created by Shoaib Ahmed on 11/25/16.
// Copyright © 2016 Shoaib Ahmed / Sufi-Al-Hussaini. All rights reserved.
//
import UIKit
protocol CircleThumbDelegate {
func circleThumbTouch(_ tag: Int, thumb: CircleThumb)
}
class CircleThumb: UIView {
enum CGGradientPosition {
case vertical
case horizontal
}
static let kIconViewWidth: CGFloat = 51
static let kIconViewHeight: CGFloat = 51
private var numberOfSegments: CGFloat
// private var bigArcHeight: CGFloat
// private var smallArcWidth: CGFloat
public let sRadius: CGFloat
public let lRadius: CGFloat
// public let yydifference: CGFloat?
public var arc: UIBezierPath?
public var separatorColor: UIColor?
public var separatorStyle: Circle.ThumbSeparatorStyle
public var centerPoint: CGPoint?
public var colorsLocations: Array<CGFloat>?
public var isGradientFill: Bool
public var gradientColors = [UIColor.black.cgColor, UIColor.gray.cgColor]
public var arcColor: UIColor?
public var iconView: CircleIconView!
public var delegate: CircleThumbDelegate?
required init(with shortRadius: CGFloat, longRadius: CGFloat, numberOfSegments sNumber: Int, iconWidth: CGFloat = kIconViewWidth, iconHeight: CGFloat = kIconViewHeight) {
var frame: CGRect?
var width: CGFloat
var height: CGFloat
let fstartAngle: CGFloat = CGFloat(270 - ((360/sNumber)/2))
let fendAngle: CGFloat = CGFloat(270 + ((360/sNumber)/2))
let startAngle: CGFloat = CircleThumb.radiansFrom(degrees: fstartAngle)
let endAngle: CGFloat = CircleThumb.radiansFrom(degrees: fendAngle)
let bigArc = UIBezierPath(arcCenter: CGPoint(x: longRadius, y: longRadius), radius:longRadius, startAngle:startAngle, endAngle:endAngle, clockwise: true)
let smallArc = UIBezierPath(arcCenter: CGPoint(x: longRadius, y: longRadius), radius:shortRadius, startAngle:startAngle, endAngle:endAngle, clockwise: true)
// Start of calculations
if ((fendAngle - fstartAngle) <= 180) {
width = bigArc.bounds.size.width
height = smallArc.currentPoint.y
frame = CGRect(x: 0, y: 0, width: width, height: height)
}
if ((fendAngle - fstartAngle) > 269) {
frame = CGRect(x: 0, y: 0, width: bigArc.bounds.size.width, height: bigArc.bounds.size.height)
}
//End of calculations
numberOfSegments = CGFloat(sNumber)
sRadius = shortRadius
lRadius = longRadius
separatorStyle = .none
isGradientFill = false
super.init(frame: frame!)
self.isOpaque = false
self.backgroundColor = UIColor.clear
self.isUserInteractionEnabled = true
let y: CGFloat = (lRadius - sRadius)/2.00
let xi: CGFloat = 0.5
let yi: CGFloat = y/frame!.size.height
self.layer.anchorPoint = CGPoint(x: xi, y: yi)
self.isGradientFill = false
self.arcColor = UIColor.green
self.centerPoint = CGPoint(x: self.bounds.midX, y: y)
self.iconView = CircleIconView(frame: CGRect(x: frame!.midX, y: y, width: iconWidth, height: iconHeight))
self.iconView!.center = CGPoint(x: frame!.midX, y: y)
self.addSubview(self.iconView!)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func draw(_ rect: CGRect) {
// Drawing code
super.draw(rect)
arcColor?.setStroke()
arcColor?.setFill()
//Angles
let clockwiseStartAngle = CircleThumb.radiansFrom(degrees: (270 - ((360/numberOfSegments)/2)))
let clockwiseEndAngle = CircleThumb.radiansFrom(degrees: (270 + ((360/numberOfSegments)/2)))
let nonClockwiseStartAngle = clockwiseEndAngle
let nonClockwiseEndAngle = clockwiseStartAngle
let center = CGPoint(x: rect.midX, y: lRadius)
arc = UIBezierPath(arcCenter: center, radius: lRadius, startAngle: clockwiseStartAngle, endAngle: clockwiseEndAngle, clockwise: true)
let f = arc?.currentPoint
arc?.addArc(withCenter: center, radius: sRadius, startAngle: nonClockwiseStartAngle, endAngle: nonClockwiseEndAngle, clockwise: false)
let e = arc?.currentPoint
arc?.close()
let context = UIGraphicsGetCurrentContext()
if !self.isGradientFill {
arc?.fill()
}
else {
// Gradient color code
var la = [CGFloat]()
let path = arc?.cgPath
if (gradientColors.count == 2) {
la.insert(0.00, at: 0)
la.insert(1.00, at: 1)
}
else
{
if colorsLocations == nil {
for var i in (0..<gradientColors.count) {
let fi = gradientColors.count-1
let point = CGFloat(1.00)/CGFloat(fi)
la.insert(point*CGFloat(i), at: i)
i+=1
}
}
else {
for var i in (0..<colorsLocations!.count) {
la.insert(colorsLocations![i], at: i)
i+=1
}
}
}
drawLinearGradient(context: context!, path: path!, colors: gradientColors as CFArray, position: .horizontal, locations: la, rect: rect)
}
UIColor.lightGray.setStroke()
UIColor.lightGray.setFill()
if (self.separatorStyle != .none) {
let line = UIBezierPath()
if (separatorStyle == .basic) {
line.lineWidth = 1.0;
}
line.move(to: f!)
line.addLine(to: CGPoint(x: f!.x - e!.x, y: e!.y))
separatorColor?.setStroke()
separatorColor?.setFill()
line.stroke(with: .copy, alpha: 1.00)
line.fill(with: .copy, alpha: 1.00)
}
}
override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
// log.debug("touchPoint : \(point)")
// log.debug("thumb : \(self)")
// log.debug("thumb tag : \(self.tag)")
// log.debug("thumb iconView tag : \(self.iconView.tag)")
// log.debug("transform -> \(self.transform)")
// if self.delegate != nil {
// self.delegate!.circleThumbTouch(self.iconView.tag, thumb: self)
// }
return false
}
static func radiansFrom(degrees: CGFloat) -> CGFloat {
return (CGFloat(M_PI) * (degrees) / 180.0)
}
static func degreesFrom(radians: CGFloat) -> CGFloat {
return ((radians) / CGFloat(M_PI) * 180)
}
func drawLinearGradient(context: CGContext, path: CGPath, colors: CFArray, position: CGGradientPosition, locations: [CGFloat], rect: CGRect) {
let colorSpace = CGColorSpaceCreateDeviceRGB()
let gradient = CGGradient(colorsSpace: colorSpace, colors: colors, locations: locations)
var startPoint: CGPoint
var endPoint: CGPoint
switch (position) {
case .horizontal:
startPoint = CGPoint(x: rect.midX, y: rect.minY)
endPoint = CGPoint(x: rect.midX, y: rect.maxY)
case .vertical:
startPoint = CGPoint(x: rect.minX, y: rect.midY)
endPoint = CGPoint(x: rect.maxX, y: rect.midY)
}
context.saveGState()
context.addPath(path)
context.clip()
context.drawLinearGradient(gradient!, start: startPoint, end: endPoint, options: CGGradientDrawingOptions(rawValue: 0))
context.restoreGState()
// CGGradientRelease(gradient);
// CGColorSpaceRelease(colorSpace);
}
}
| mit | f5e20a7a8cc5c56dcdbc270906a5931a | 37.6875 | 461 | 0.603123 | 4.610228 | false | false | false | false |
ypcDota/DouYuZB | 斗鱼直播/斗鱼直播/Classes/Home/HomeViewController.swift | 1 | 3387 | //
// HomeViewController.swift
// 斗鱼直播
//
// Created by ypc on 17/1/2.
// Copyright © 2017年 com.ypc. All rights reserved.
//
import UIKit
private let kTitleViewH : CGFloat = 40
class HomeViewController: UIViewController {
// MARK: - 懒加载属性
fileprivate lazy var pageTitleView : PageTitleView = {
let rect = CGRect(x: 0, y: kStatusBarH + kNavigationBarH, width: kScreenW, height: kTitleViewH)
let titles = ["推荐","游戏","娱乐","趣玩"]
let titleView = PageTitleView(frame: rect, titles: titles)
titleView.delegate = self
return titleView
}()
fileprivate lazy var pageContentView : PageContentView = {[weak self] in
let contentX : CGFloat = 0
let contentY : CGFloat = kStatusBarH + kNavigationBarH + kTitleViewH
let contentW : CGFloat = kScreenW
let contentH : CGFloat = kScreenH - kStatusBarH - kNavigationBarH - kTitleViewH
let contentFrame = CGRect(x: contentX, y: contentY, width: contentW, height: contentH)
var childVcs = [UIViewController]()
childVcs.append(RecommendViewController())
for i in 0...2 {
let vc = UIViewController()
childVcs.append(vc)
vc.view.backgroundColor = UIColor.randomColor()
}
let contentView = PageContentView(frame: contentFrame, childVcs: childVcs, parentController: self)
// 设置代理
contentView.delegate = self
return contentView
}()
override func viewDidLoad() {
super.viewDidLoad()
// 设置导航栏
setUpUI()
}
}
// MARK - 设置UI
extension HomeViewController {
// 设置UI
func setUpUI() {
// 0.不需要调整 UIScrollView 的内边距
automaticallyAdjustsScrollViewInsets = false
// 1.设置导航栏
setUpNav()
// 添加pageTitleView
view.addSubview(pageTitleView)
// 添加 pageContentView
view.addSubview(pageContentView)
pageContentView.backgroundColor = UIColor.red
}
// MARK:设置导航栏
func setUpNav() {
// 1.设置左边的item
navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "logo")
// 2.设置右边的 item
let size = CGSize(width: 30, height: 30)
let historyItem = UIBarButtonItem(imageName: "image_my_history", highImageName: "Image_my_history_click", size: size)
let searchItem = UIBarButtonItem(imageName: "btn_search", highImageName: "btn_search_clicked", size: size)
let qrcodeItem = UIBarButtonItem(imageName: "Image_scan", highImageName: "Image_scan_click", size: size)
navigationItem.rightBarButtonItems = [historyItem,searchItem,qrcodeItem]
}
}
// MARK: 遵守 pageTitleViewDelegate
extension HomeViewController : pageTitleViewDelegate {
func pageTitleView(_ titleView: PageTitleView, selectIndex index: Int) {
pageContentView.setCurrentIndex(index)
}
}
extension HomeViewController : pageContentViewDelegate {
func pageContentView(_ contentView: PageContentView, progress: CGFloat, sourceIndex: Int, targetIndex: Int) {
pageTitleView.setUpTitleLabel(progress, sourceIndex: sourceIndex, targetIndex: targetIndex)
}
}
| mit | 3c2ccffbc5d482a746f4859c91bce9b1 | 31.217822 | 125 | 0.641364 | 5.10832 | false | false | false | false |
BeanstalkData/beanstalk-ios-sdk | BeanstalkEngageiOSSDK/Classes/Network/MockDataGenerator.swift | 1 | 4201 | //
// DummyDataGenerator.swift
// BeanstalkEngageiOSSDK
//
// 2016 Heartland Commerce, Inc. All rights reserved.
//
import Foundation
class MockDataGenerator {
var urls = [
"http://d1ivierdlu2fd9.cloudfront.net/260/30152.png",
"http://d1ivierdlu2fd9.cloudfront.net/260/30153.png",
"http://d1ivierdlu2fd9.cloudfront.net/260/30154.png",
"http://d1ivierdlu2fd9.cloudfront.net/260/30155.png"];
func getUserOffers () -> CouponResponse<BECoupon> {
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
let today = NSDate()
let calendar = NSCalendar.currentCalendar()
let items = [Int](count: 10, repeatedValue: 0)
let coupons = items.map({ (item)-> BECoupon in
let c = BECoupon(imageUrl: urls[item % urls.count])
c.text = "Description text \(item)"
c.number = "\(item)\(item)\(item)\(item)\(item)\(item)\(item)\(item)\(item)\(item)"
let date = calendar.dateByAddingUnit(
.Day,
value: 1,
toDate: today,
options: NSCalendarOptions(rawValue: 0))
c.expiration = formatter.stringFromDate(date!)
return c
})
return CouponResponse(coupons: coupons)
}
func getUserProgress() -> RewardsCountResponse {
let items = [Int](count: 4, repeatedValue: 0)
let coupons = items.map({ (item)->Category in
let c = Category(count : 1)
return c
})
return RewardsCountResponse(categories: coupons)
}
func getUserGiftCards() -> GiftCardsResponse {
return DummyGCResponse(count : 4)
}
func getUserGiftCardBalance() -> GiftCardBalanceResponse{
return DummyGCBResponse();
}
func getUserPayment() -> PaymentResponse {
return PaymentResponse(token : "\(arc4random_uniform(10))")
}
func getStores() -> StoresResponseProtocol {
return DummyStoresResponse()
}
}
private class DummyStoresResponse: StoresResponseProtocol {
private var stores : [BEStore]
init(){
self.stores = Array()
var store = BEStore(id: "5851a7249616259fa18034c4")
store.customerId = "318"
store.storeId = "506"
store.country = "USA"
store.address1 = "8521 N. Tryon St"
store.city = "Charlotte"
store.state = "NC"
store.zip = 28262
store.phone = "704-510-1194"
store.longitude = "-80.7325287"
store.latitude = "35.3301529"
store.geoEnabled = true
self.stores.append(store)
store = BEStore(id: "5851a7449616259fa18034ff")
store.customerId = "318"
store.storeId = "768"
store.country = "USA"
store.address1 = "10329 Mallard Creek Road"
store.city = "Charlotte"
store.state = "NC"
store.zip = 28262
store.phone = "704-503-4648"
store.longitude = "-80.7325287"
store.latitude = "35.3301529"
store.geoEnabled = true
self.stores.append(store)
store = BEStore(id: "5851a7319616259fa18034dc")
store.customerId = "318"
store.storeId = "609"
store.country = "USA"
store.address1 = "7701 Gateway Lane NW"
store.city = "Concord"
store.state = "NC"
store.zip = 28027
store.phone = "704-979-5347"
store.longitude = "-80.6548882"
store.latitude = "35.4002721"
store.geoEnabled = true
self.stores.append(store)
}
func failed() -> Bool{
return false
}
func getStores() -> [BEStore]? {
return stores
}
}
private class DummyGCResponse : GiftCardsResponse{
private let cards : [BEGiftCard]
init(count : Int){
let items = [Int](count: 4, repeatedValue: 0)
self.cards = items.map({ (item) -> BEGiftCard in
let c = BEGiftCard(id : "\(arc4random())",
number: "\(arc4random())\(arc4random())" ,
balance: String(format: "$%.2f", Double(arc4random_uniform(500))))
return c
})
}
func failed() -> Bool{
return false
}
func getCards() -> [BEGiftCard]?{
return cards
}
}
private class DummyGCBResponse : GiftCardBalanceResponse{
private let balance : String
init(){
self.balance = String(format: "$%.2f", Double(arc4random_uniform(500)))
}
func getCardBalance() -> String {
return balance;
}
}
| mit | c6d735bd33b3a86f98a208d5871f671a | 24.005952 | 89 | 0.629612 | 3.524329 | false | false | false | false |
ello/ello-ios | Sources/Controllers/Stream/Calculators/StreamImageCellSizeCalculator.swift | 1 | 3147 | ////
/// StreamImageCellSizeCalculator.swift
//
class StreamImageCellSizeCalculator: CellSizeCalculator {
let streamKind: StreamKind
static func aspectRatioForImageRegion(_ imageRegion: ImageRegion) -> CGFloat {
guard let asset = imageRegion.asset else { return 4 / 3 }
return asset.aspectRatio
}
init(streamKind: StreamKind, item: StreamCellItem, width: CGFloat, columnCount: Int) {
self.streamKind = streamKind
super.init(item: item, width: width, columnCount: columnCount)
}
override func process() {
let margin: CGFloat
if (cellItem.type.data as? Regionable)?.isRepost == true {
margin = StreamTextCell.Size.repostMargin
}
else if cellItem.jsonable is ElloComment {
margin = StreamTextCell.Size.commentMargin
}
else {
margin = 0
}
if let imageRegion = cellItem.type.data as? ImageRegion {
let oneColumnHeight = StreamImageCell.Size.bottomMargin
+ oneColumnImageHeight(imageRegion, margin: margin)
let multiColumnHeight = StreamImageCell.Size.bottomMargin
+ multiColumnImageHeight(imageRegion, margin: margin)
assignCellHeight(one: oneColumnHeight, multi: multiColumnHeight)
}
else if let embedRegion = cellItem.type.data as? EmbedRegion {
var ratio: CGFloat
if embedRegion.isAudioEmbed || embedRegion.service == .uStream {
ratio = 1
}
else {
ratio = 16 / 9
}
let multiWidth = calculateColumnWidth(
frameWidth: width,
columnSpacing: streamKind.horizontalColumnSpacing,
columnCount: columnCount
) - margin
let oneColumnHeight = StreamImageCell.Size.bottomMargin + (width - margin) / ratio
let multiColumnHeight = StreamImageCell.Size.bottomMargin + multiWidth / ratio
assignCellHeight(one: oneColumnHeight, multi: multiColumnHeight)
}
else {
finish()
}
}
private func oneColumnImageHeight(_ imageRegion: ImageRegion, margin: CGFloat) -> CGFloat {
var imageWidth = width - margin
if let assetWidth = imageRegion.asset?.oneColumnAttachment?.width {
imageWidth = min(imageWidth, CGFloat(assetWidth))
}
return ceil(
imageWidth / StreamImageCellSizeCalculator.aspectRatioForImageRegion(imageRegion)
)
}
private func multiColumnImageHeight(_ imageRegion: ImageRegion, margin: CGFloat) -> CGFloat {
var imageWidth = calculateColumnWidth(
frameWidth: width,
columnSpacing: StreamKind.unknown.horizontalColumnSpacing,
columnCount: columnCount
) - margin
if let assetWidth = imageRegion.asset?.gridLayoutAttachment?.width {
imageWidth = min(imageWidth, CGFloat(assetWidth))
}
return ceil(
imageWidth / StreamImageCellSizeCalculator.aspectRatioForImageRegion(imageRegion)
)
}
}
| mit | 66d1bacb1d7fd6cd58c4bc8b3a7027ff | 36.464286 | 97 | 0.627582 | 5.175987 | false | false | false | false |
eurofurence/ef-app_ios | Packages/EurofurenceKit/Sources/EurofurenceKit/Entities/Track.swift | 1 | 1782 | import CoreData
import EurofurenceWebAPI
@objc(Track)
public class Track: Entity {
@nonobjc class func fetchRequest() -> NSFetchRequest<Track> {
return NSFetchRequest<Track>(entityName: "Track")
}
@NSManaged public var name: String
@NSManaged public var events: Set<Event>
}
// MARK: - CanonicalTrack Adaptation
extension Track {
public var canonicalTrack: CanonicalTrack {
CanonicalTrack(trackName: name)
}
}
// MARK: - Fetching
extension Track {
/// Produces an `NSFetchRequest` for fetching all `Track` entities in alphabetical order.
/// - Returns: An `NSFetchRequest` for fetching all `Track` entities in alphabetical order.
public static func alphabeticallySortedFetchRequest() -> NSFetchRequest<Track> {
let fetchRequest: NSFetchRequest<Track> = Track.fetchRequest()
fetchRequest.sortDescriptors = [NSSortDescriptor(keyPath: \Track.name, ascending: true)]
return fetchRequest
}
}
// MARK: - Track + ConsumesRemoteResponse
extension Track: ConsumesRemoteResponse {
typealias RemoteObject = EurofurenceWebAPI.Track
func update(context: RemoteResponseConsumingContext<RemoteObject>) throws {
identifier = context.remoteObject.id
lastEdited = context.remoteObject.lastChangeDateTimeUtc
name = context.remoteObject.name
}
}
// MARK: Generated accessors for events
extension Track {
@objc(addEventsObject:)
@NSManaged func addToEvents(_ value: Event)
@objc(removeEventsObject:)
@NSManaged func removeFromEvents(_ value: Event)
@objc(addEvents:)
@NSManaged func addToEvents(_ values: Set<Event>)
@objc(removeEvents:)
@NSManaged func removeFromEvents(_ values: Set<Event>)
}
| mit | a433273d058979da7468b26404b9ab44 | 24.457143 | 96 | 0.699214 | 4.640625 | false | false | false | false |
rpistorello/rp-game-engine | rp-game-engine-src/Components/Transform.swift | 1 | 4901 | //
// Transform.swift
// rp-game-engine
//
// Created by Ricardo Pistorello on 02/12/15.
// Copyright © 2015 Ricardo Pistorello. All rights reserved.
//
import SpriteKit
internal class Root: SKNode {
var transform: Transform!
var gameObject: GameObject!
override init() {
super.init()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class Transform: Component {
private let root = Root()
override var active: Bool {
didSet {
active = true
}
}
var hidden: Bool {
get { return root.hidden }
set { root.hidden = newValue }
}
internal override init() {
super.init()
root.transform = self
}
//MARK: Parent
private var _parent: Transform?
var parent: Transform? {
get{ return _parent }
}
//MARK: Position
var localposition: CGPoint {
get{ return self.root.position }
set{
root.position = newValue
updateGlobalposition()
}
}
private var _position: CGPoint = CGPointZero
var position: CGPoint {
get {
guard let newParent = root.parent,
let scene = root.scene else {
print("Parent or scene not found \(gameObject.classForCoder)")
return self._position
}
_position = scene.convertPoint(root.position, fromNode: newParent)
return self._position
}
set {
self._position = newValue
updateLocalPosition()
}
}
//MARK: Rotation
private var _rotation = CGFloat(0)
var rotation: CGFloat {
get{ return _rotation }
set{
self._rotation = newValue
updateLocalRotation()
}
}
var localRotation: CGFloat {
get { return root.zRotation.radiansToDegrees() }
set { root.zRotation = newValue.degreesToRadians() }
}
//MARK: Scale
var lossyScale: CGPoint {
get {
let parentLossyScale = findParentLossyScale()
return CGPointMake(parentLossyScale.x * scale.x, parentLossyScale.y * scale.y)
}
}
var scale: CGPoint {
get { return root.scaleAsPoint }
set { root.scaleAsPoint = newValue }
}
//MARK: Collider
internal var physicsBody: SKPhysicsBody? {
get{ return root.physicsBody}
set{ root.physicsBody = newValue}
}
//MARK: Position Handlers
private func updateGlobalposition() {
guard let newParent = root.parent,
let scene = root.scene else { return }
_position = scene.convertPoint(root.position, fromNode: newParent)
}
private func updateLocalPosition() {
guard let parent = root.parent,
let scene = root.scene else { return }
root.position = parent.convertPoint(_position, fromNode: scene)
}
//MARK: Rotation Handlers
private func updateGlobalRotation() {
_rotation = findParentRotation() + root.zRotation.radiansToDegrees()
}
private func updateLocalRotation() {
localRotation = _rotation - findParentRotation()
}
func findParentRotation() -> CGFloat{
guard let parent = self.parent else {
return localRotation
}
return parent.findParentRotation() + localRotation
}
//MARK: Scale Handlers
func findParentLossyScale() -> CGPoint{
guard let parent = self.parent else {
return scale
}
let parentLossyScale = parent.findParentLossyScale()
return CGPointMake(parentLossyScale.x * scale.x, parentLossyScale.y * scale.y)
}
//MARK: Functions
func setParent(newParent: Transform?, worldPositionStays: Bool = true) {
self._parent = newParent
updateRoot()
if worldPositionStays { updateLocalPosition() }
updateLocalRotation()
}
func addChild(child: Transform) {
child.setParent(self)
}
internal func addSprite(sprite: SKSpriteNode) {
root.addChild(sprite)
}
override func OnComponentAdded() {
root.gameObject = gameObject
updateRoot()
}
private func updateRoot() {
if self.root.parent != nil { self.root.removeFromParent() }
guard let tparent = self.parent else {
self.gameObject.scene.addChild(root)
return
}
tparent.root.addChild(self.root)
}
func runAction(action: SKAction) {
root.runAction(action)
}
//MARK: Update
override func updateWithDeltaTime(seconds: NSTimeInterval) {
updateGlobalposition()
updateGlobalRotation()
}
}
| mit | c455df53d6573dc7b6858756a191fda7 | 24.65445 | 90 | 0.578571 | 4.697987 | false | false | false | false |
wlighting/WLMultiTableView | WLMultiTableView/SubVC/SubTableView.swift | 1 | 2562 | //
// SubTableView.swift
// WLMultiTableView
//
// Created by wlighting on 2017/7/22.
// Copyright © 2017年 wlighting. All rights reserved.
//
import UIKit
class SubTableView: UIView {
let subInfoTableViewID:String = "subInfoTableViewID"
private var contentView: UIView!
@IBOutlet weak var subInfoTableView: UITableView!
override func awakeFromNib() {
super.awakeFromNib()
WLLog(subInfoTableView)
self.subInfoTableView.register(UINib(nibName: "SubTableViewCell", bundle: nil), forCellReuseIdentifier: subInfoTableViewID)
self.subInfoTableView.delegate = self
self.subInfoTableView.dataSource = self
}
// 从storyboard上初始化时,会调用该方法
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
xibSetup()
}
private func xibSetup() {
contentView = Bundle.main.loadNibNamed("SubTableView", owner: self, options: nil)?.first as! UIView
contentView.frame = bounds
contentView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
addSubview(contentView)
}
/*
override init(frame: CGRect) {
super.init(frame: frame)
contentView = loadFromNib()
addSubview(contentView)
self.subInfoTableView.register(UINib(nibName: "SubTableViewCell", bundle: nil), forCellReuseIdentifier: subInfoTableViewID)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
contentView = loadFromNib()
addSubview(contentView)
self.subInfoTableView.register(UINib(nibName: "SubTableViewCell", bundle: nil), forCellReuseIdentifier: subInfoTableViewID)
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
contentView.frame = bounds
}
func loadFromNib() -> UIView {
return Bundle.main.loadNibNamed("SubTableView", owner: nil, options: nil)?.first as! UIView
}*/
}
extension SubTableView :UITableViewDelegate,UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return 20;
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let cell = tableView.dequeueReusableCell(withIdentifier: subInfoTableViewID)as?SubTableViewCell
cell?.infoLable.text = "第\(indexPath.row)行"
return cell!
}
}
| mit | 7e69eea36d077dbc9bc8673026f11ab7 | 26.48913 | 131 | 0.66034 | 4.844828 | false | false | false | false |
cburrows/swift-protobuf | Tests/SwiftProtobufTests/Test_FieldOrdering.swift | 3 | 1801 | // Tests/SwiftProtobufTests/Test_FieldOrdering.swift - Check ordering of binary fields
//
// Copyright (c) 2014 - 2016 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/main/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// Verify that binary protobuf serialization correctly emits fields
/// in order by field number. This is especially interesting when there
/// are extensions and/or unknown fields involved.
///
/// Proper ordering is recommended but not critical for writers since all
/// readers are required to accept fields out of order.
///
// -----------------------------------------------------------------------------
import Foundation
import XCTest
class Test_FieldOrdering: XCTestCase {
typealias MessageTestType = Swift_Protobuf_TestFieldOrderings
func test_FieldOrdering() throws {
var m = MessageTestType()
m.myString = "abc"
m.myInt = 1
m.myFloat = 1.0
var nest = MessageTestType.NestedMessage()
nest.oo = 1
nest.bb = 2
m.optionalNestedMessage = nest
m.Swift_Protobuf_myExtensionInt = 12
m.Swift_Protobuf_myExtensionString = "def"
m.oneofInt32 = 7
let encoded1 = try m.serializedBytes()
XCTAssertEqual([8, 1, 40, 12, 80, 7, 90, 3, 97, 98, 99, 146, 3, 3, 100, 101, 102, 173, 6, 0, 0, 128, 63, 194, 12, 4, 8, 2, 16, 1], encoded1)
m.oneofInt64 = 8
let encoded2 = try m.serializedBytes()
XCTAssertEqual([8, 1, 40, 12, 90, 3, 97, 98, 99, 146, 3, 3, 100, 101, 102, 224, 3, 8, 173, 6, 0, 0, 128, 63, 194, 12, 4, 8, 2, 16, 1], encoded2)
}
}
| apache-2.0 | c87d17981de69c0b145ba0ee212e2e7e | 38.152174 | 152 | 0.598556 | 4.002222 | false | true | false | false |
gcirone/Mama-non-mama | Mama non mama/iiFaderForAvAudioPlayer.swift | 1 | 5750 | //
// iiSoundPlayerFadeOut.swift
// iiFaderForAvAudioPlayer
//
// Created by Evgenii Neumerzhitckii on 31/12/2014.
// Copyright (c) 2014 Evgenii Neumerzhitckii. All rights reserved.
//
import Foundation
import AVFoundation
let iiFaderForAvAudioPlayer_defaultFadeDurationSeconds = 3.0
let iiFaderForAvAudioPlayer_defaultVelocity = 2.0
@objc
public class iiFaderForAvAudioPlayer {
let player: AVAudioPlayer
private var timer: NSTimer?
// The higher the number - the higher the quality of fade
// and it will consume more CPU.
var volumeAlterationsPerSecond = 30.0
private var fadeDurationSeconds = iiFaderForAvAudioPlayer_defaultFadeDurationSeconds
private var fadeVelocity = iiFaderForAvAudioPlayer_defaultVelocity
private var fromVolume = 0.0
private var toVolume = 0.0
private var currentStep = 0
private var onFinished: ((Bool)->())? = nil
init(player: AVAudioPlayer) {
self.player = player
}
deinit {
callOnFinished(false)
stop()
}
private var fadeIn: Bool {
return fromVolume < toVolume
}
func fadeIn(duration: Double = iiFaderForAvAudioPlayer_defaultFadeDurationSeconds,
velocity: Double = iiFaderForAvAudioPlayer_defaultVelocity, onFinished: ((Bool)->())? = nil) {
fade(
fromVolume: Double(player.volume), toVolume: 1,
duration: duration, velocity: velocity, onFinished: onFinished)
}
func fadeOut(duration: Double = iiFaderForAvAudioPlayer_defaultFadeDurationSeconds,
velocity: Double = iiFaderForAvAudioPlayer_defaultVelocity, onFinished: ((Bool)->())? = nil) {
fade(
fromVolume: Double(player.volume), toVolume: 0,
duration: duration, velocity: velocity, onFinished: onFinished)
}
func fade(#fromVolume: Double, toVolume: Double,
duration: Double = iiFaderForAvAudioPlayer_defaultFadeDurationSeconds,
velocity: Double = iiFaderForAvAudioPlayer_defaultVelocity, onFinished: ((Bool)->())? = nil) {
self.fromVolume = iiFaderForAvAudioPlayer.makeSureValueIsBetween0and1(fromVolume)
self.toVolume = iiFaderForAvAudioPlayer.makeSureValueIsBetween0and1(toVolume)
self.fadeDurationSeconds = duration
self.fadeVelocity = velocity
callOnFinished(false)
self.onFinished = onFinished
player.volume = Float(self.fromVolume)
if self.fromVolume == self.toVolume {
callOnFinished(true)
return
}
startTimer()
}
// Stop fading. Does not stop the sound.
func stop() {
stopTimer()
}
private func callOnFinished(finished: Bool) {
onFinished?(finished)
onFinished = nil
}
private func startTimer() {
stopTimer()
currentStep = 0
timer = NSTimer.scheduledTimerWithTimeInterval(1 / volumeAlterationsPerSecond, target: self,
selector: "timerFired:", userInfo: nil, repeats: true)
}
private func stopTimer() {
if let currentTimer = timer {
currentTimer.invalidate()
timer = nil
}
}
func timerFired(timer: NSTimer) {
if shouldStopTimer {
player.volume = Float(toVolume)
stopTimer()
callOnFinished(true)
return
}
let currentTimeFrom0To1 = iiFaderForAvAudioPlayer.timeFrom0To1(
currentStep, fadeDurationSeconds: fadeDurationSeconds, volumeAlterationsPerSecond: volumeAlterationsPerSecond)
var volumeMultiplier: Double
var newVolume: Double = 0
if fadeIn {
volumeMultiplier = iiFaderForAvAudioPlayer.fadeInVolumeMultiplier(currentTimeFrom0To1,
velocity: fadeVelocity)
newVolume = fromVolume + (toVolume - fromVolume) * volumeMultiplier
} else {
volumeMultiplier = iiFaderForAvAudioPlayer.fadeOutVolumeMultiplier(currentTimeFrom0To1,
velocity: fadeVelocity)
newVolume = toVolume - (toVolume - fromVolume) * volumeMultiplier
}
player.volume = Float(newVolume)
currentStep++
}
var shouldStopTimer: Bool {
let totalSteps = fadeDurationSeconds * volumeAlterationsPerSecond
return Double(currentStep) > totalSteps
}
public class func timeFrom0To1(currentStep: Int, fadeDurationSeconds: Double,
volumeAlterationsPerSecond: Double) -> Double {
let totalSteps = fadeDurationSeconds * volumeAlterationsPerSecond
var result = Double(currentStep) / totalSteps
result = makeSureValueIsBetween0and1(result)
return result
}
// Graph: https://www.desmos.com/calculator/wnstesdf0h
public class func fadeOutVolumeMultiplier(timeFrom0To1: Double, velocity: Double) -> Double {
var time = makeSureValueIsBetween0and1(timeFrom0To1)
return pow(M_E, -velocity * time) * (1 - time)
}
public class func fadeInVolumeMultiplier(timeFrom0To1: Double, velocity: Double) -> Double {
var time = makeSureValueIsBetween0and1(timeFrom0To1)
return pow(M_E, velocity * (time - 1)) * time
}
private class func makeSureValueIsBetween0and1(value: Double) -> Double {
if value < 0 { return 0 }
if value > 1 { return 1 }
return value
}
} | mit | a0a4c2f2cc60dca6a5b4d96fda99ef92 | 31.862857 | 122 | 0.621913 | 4.795663 | false | false | false | false |
DevZheng/LeetCode | Array/CombinationSumII.swift | 1 | 3157 | //
// CombinationSumII.swift
// A
//
// Created by zyx on 2017/6/29.
// Copyright © 2017年 bluelive. All rights reserved.
//
import Foundation
/*
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
Each number in C may only be used once in the combination.
Note:
All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.
For example, given candidate set [10, 1, 2, 7, 6, 1, 5] and target 8,
A solution set is:
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]
*/
class CombinationSumII {
func combinationSum2(_ candidates: [Int], _ target: Int) -> [[Int]] {
// if candidates.count == 0 {
// return []
// }
// // 1、 排序
// let candidates = candidates.sorted()
// // 2、target = target - nums[i]
// return helper(candidates, target, 0)
var res: [[Int]] = [], path: [Int] = []
dfs(&res, &path, candidates.sorted(), target, 0)
return res;
}
// reference
func dfs(_ res: inout [[Int]], _ path: inout [Int], _ candidates: [Int], _ target: Int, _ index: Int) {
if target == 0 {
res.append(Array(path));
return;
}
for i in index..<candidates.count {
if candidates[i] > target {
break
}
if i > 0 && candidates[i] == candidates[i - 1] && i != index {
continue
}
path.append(candidates[i]);
dfs(&res, &path, candidates, target - candidates[i], i + 1);
path.removeLast()
}
}
// DIY
func helper(_ nums: [Int], _ target: Int, _ start: Int) -> [[Int]] {
if start >= nums.count {
return []
}
var result: [[Int]] = []
var p = start
for i in start..<nums.count {
if nums[i] == nums[p] {
continue;
}
var sum = 0
var arrs: [Int] = []
for _ in 1...i - p {
sum += nums[p]
arrs.append(nums[p])
if target - sum == 0 {
result.append(arrs)
}
if target - sum > 0 {
var arr = helper(nums, target - sum, i)
arr = arr.map({ (element) -> [Int] in
var element = element
element.append(contentsOf: arrs)
return element
})
result.append(contentsOf: arr)
}
}
p = i
}
var sum = 0
var arrs: [Int] = []
for _ in 1...nums.count - p {
sum += nums[p]
arrs.append(nums[p])
if target - sum == 0 {
result.append(arrs)
}
}
return result;
}
}
| mit | 9bd95da53dcd1701de0c50af9fb70e40 | 25 | 142 | 0.430706 | 4.217158 | false | false | false | false |
Macostik/StreamView | Source/StreamReusableView.swift | 1 | 2041 | //
// StreamReusableView.swift
// StreamView
//
// Created by Yura Granchenko on 4/11/17.
// Copyright © 2017 Yura Granchenko. All rights reserved.
//
import Foundation
import UIKit
open class StreamReusableView: UIView, UIGestureRecognizerDelegate {
open func setEntry(entry: Any?) {}
open func getEntry() -> Any? { return nil }
open var metrics: StreamMetricsProtocol?
open var item: StreamItem?
open var selected: Bool = false
public let selectTapGestureRecognizer = UITapGestureRecognizer()
open func layoutWithMetrics(metrics: StreamMetricsProtocol) {}
open func didLoad() {
selectTapGestureRecognizer.addTarget(self, action: #selector(self.selectAction))
selectTapGestureRecognizer.delegate = self
self.addGestureRecognizer(selectTapGestureRecognizer)
}
@IBAction func selectAction() {
metrics?.select(view: self)
}
open func didDequeue() {}
open func willEnqueue() {}
open func resetup() {}
// MARK: - UIGestureRecognizerDelegate
override open func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
return gestureRecognizer != selectTapGestureRecognizer || metrics?.selectable ?? false
}
}
open class EntryStreamReusableView<T: Any>: StreamReusableView {
public init() {
super.init(frame: CGRect.zero)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override open func setEntry(entry: Any?) {
self.entry = entry as? T
}
override open func getEntry() -> Any? {
return entry
}
open var entry: T? {
didSet {
resetup()
}
}
open func setup(entry: T) {}
open func setupEmpty() {}
override open func resetup() {
if let entry = entry {
setup(entry: entry)
} else {
setupEmpty()
}
}
}
| mit | bb20986f81bf6508959f6f58dc0e4adf | 23.878049 | 103 | 0.62451 | 4.868735 | false | false | false | false |
fromkk/Valy | Validator-iOSTests/Validator_iOSTests.swift | 1 | 5920 | //
// Validator_iOSTests.swift
// Validator-iOSTests
//
// Created by Kazuya Ueoka on 2016/11/14.
//
//
import XCTest
@testable import Valy
/*
public enum ValyRule: AnyValidatorRule {
case required
case match(String)
case pattern(String)
case alphabet
case digit
case alnum
case number
case minLength(Int)
case maxLength(Int)
case exactLength(Int)
case numericMin(Double)
case numericMax(Double)
case numericBetween(min: Double, max: Double)
*/
class Validator_iOSTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testRequired() {
let value1: String? = nil
XCTAssertFalse(ValyRule.required.run(with: value1))
let value2: String? = "hello world"
XCTAssertTrue(ValyRule.required.run(with: value2))
}
func testMatch() {
let match = ValyRule.match("ABC")
let value1: String = "abc"
XCTAssertFalse(match.run(with: value1))
let value2: String = "ABC"
XCTAssertTrue(match.run(with: value2))
}
func testPattern() {
let pattern = ValyRule.pattern("^[a-z]+$")
let value1: String = "Hello!"
XCTAssertFalse(pattern.run(with: value1))
let value2: String = "Hello"
XCTAssertFalse(pattern.run(with: value2))
let value3: String = "hello"
XCTAssertTrue(pattern.run(with: value3))
}
func testAlphabet() {
let alphabet = ValyRule.alphabet
let value1: String = "Hello world!"
XCTAssertFalse(alphabet.run(with: value1))
let value2: String = "123"
XCTAssertFalse(alphabet.run(with: value2))
let value3: String = "HelloWorld"
XCTAssertTrue(alphabet.run(with: value3))
}
//digit
func testDigit() {
let digit = ValyRule.digit
let value1: String = "Hello world!"
XCTAssertFalse(digit.run(with: value1))
let value2: String = "0"
XCTAssertTrue(digit.run(with: value2))
let value3: String = "0123456789"
XCTAssertTrue(digit.run(with: value3))
let value4: String = "-1,234,567,890"
XCTAssertFalse(digit.run(with: value4))
}
//alnum
func testAlnum() {
let alnum = ValyRule.alnum
let value1: String = "Hello world!"
XCTAssertFalse(alnum.run(with: value1))
let value2: String = "0123456789"
XCTAssertTrue(alnum.run(with: value2))
let value3: String = "HelloWorld"
XCTAssertTrue(alnum.run(with: value3))
let value4: String = "Hello0123456789World"
XCTAssertTrue(alnum.run(with: value4))
}
//number
func testNumber() {
let number = ValyRule.number
let value1: String = "Hello world!"
XCTAssertFalse(number.run(with: value1))
let value2: String = "0"
XCTAssertTrue(number.run(with: value2))
let value3: String = "0123456789"
XCTAssertTrue(number.run(with: value3))
let value4: String = "-1,234,567,890"
XCTAssertTrue(number.run(with: value4))
}
//minLength(Int)
func testMinLength() {
let minLength = ValyRule.minLength(10)
let value1: String = "Hellooooo"
XCTAssertFalse(minLength.run(with: value1))
let value2: String = "Helloworld"
XCTAssertTrue(minLength.run(with: value2))
let value3: String = "helloworld!"
XCTAssertTrue(minLength.run(with: value3))
}
//maxLength(Int)
func testMaxLength() {
let maxLength = ValyRule.maxLength(10)
let value1: String = "Hellooooo"
XCTAssertTrue(maxLength.run(with: value1))
let value2: String = "Helloworld"
XCTAssertTrue(maxLength.run(with: value2))
let value3: String = "helloworld!"
XCTAssertFalse(maxLength.run(with: value3))
}
//exactLength(Int)
func exactLength() {
let exactLength = ValyRule.exactLength(10)
let value1: String = "Hellooooo"
XCTAssertFalse(exactLength.run(with: value1))
let value2: String = "Helloworld"
XCTAssertTrue(exactLength.run(with: value2))
let value3: String = "helloworld!"
XCTAssertFalse(exactLength.run(with: value3))
}
//numericMin(Double)
func numericMin() {
let min = ValyRule.numericMin(10)
let value1: String = "9"
XCTAssertFalse(min.run(with: value1))
let value2: String = "10"
XCTAssertTrue(min.run(with: value2))
let value3: String = "11"
XCTAssertTrue(min.run(with: value3))
}
//numericMax(Double)
func numericMax() {
let max = ValyRule.numericMax(10)
let value1: String = "9"
XCTAssertTrue(max.run(with: value1))
let value2: String = "10"
XCTAssertTrue(max.run(with: value2))
let value3: String = "11"
XCTAssertFalse(max.run(with: value3))
}
//numericBetween(min: Double, max: Double)
func numericBetween() {
let between = ValyRule.numericBetween(min: 10, max: 20)
let value1: String = "9"
XCTAssertFalse(between.run(with: value1))
let value2: String = "10"
XCTAssertTrue(between.run(with: value2))
let value3: String = "11"
XCTAssertTrue(between.run(with: value3))
let value4: String = "15"
XCTAssertTrue(between.run(with: value4))
let value5: String = "19"
XCTAssertTrue(between.run(with: value5))
let value6: String = "20"
XCTAssertTrue(between.run(with: value6))
let value7: String = "21"
XCTAssertFalse(between.run(with: value7))
}
}
| mit | b39a9bb8b90faf3687169350eacc21ff | 26.155963 | 111 | 0.616216 | 3.86423 | false | true | false | false |
HongxiangShe/DYZB | DY/DY/Class/Home/Model/AnchorModel.swift | 1 | 568 | //
// AnchorModel.swift
// DY
//
// Created by 佘红响 on 2016/12/20.
// Copyright © 2016年 佘红响. All rights reserved.
//
import UIKit
class AnchorModel: NSObject {
var room_id: Int = 0
var vertical_src: String = ""
var isVertical: Int = 0
var room_name: String = ""
var nickname: String = ""
var online: Int = 0
var anchor_city: String = ""
init(dict: [String: AnyObject]) {
super.init()
setValuesForKeys(dict)
}
override func setValue(_ value: Any?, forUndefinedKey key: String) {}
}
| mit | a5f407fdf1eb2431c3be6349b9026888 | 19.481481 | 73 | 0.594937 | 3.544872 | false | false | false | false |
xusader/firefox-ios | Client/Frontend/Home/BookmarksPanel.swift | 3 | 2821 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import Storage
class BookmarksPanel: SiteTableViewController, HomePanel {
weak var homePanelDelegate: HomePanelDelegate? = nil
var source: BookmarksModel?
override var profile: Profile! {
didSet {
profile.bookmarks.modelForRoot(self.onNewModel, failure: self.onModelFailure)
}
}
private func onNewModel(model: BookmarksModel) {
self.source = model
dispatch_async(dispatch_get_main_queue()) {
self.tableView.reloadData()
}
}
private func onModelFailure(e: Any) {
println("Error: failed to get data: \(e)")
}
override func reloadData() {
self.source?.reloadData(self.onNewModel, failure: self.onModelFailure)
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let source = source {
return source.current.count
}
return super.tableView(tableView, numberOfRowsInSection: section)
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = super.tableView(tableView, cellForRowAtIndexPath: indexPath)
if let source = source {
let bookmark = source.current[indexPath.row]
if let favicon = bookmark?.favicon {
cell.imageView?.sd_setImageWithURL(NSURL(string: favicon.url)!, placeholderImage: profile.favicons.defaultIcon)
}
cell.textLabel?.text = bookmark?.title
}
return cell
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return NSLocalizedString("Recent Bookmarks", comment: "Header for bookmarks list")
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: false)
if let source = source {
let bookmark = source.current[indexPath.row]
switch (bookmark) {
case let item as BookmarkItem:
homePanelDelegate?.homePanel(self, didSelectURL: NSURL(string: item.url)!)
break
case let folder as BookmarkFolder:
// Descend into the folder.
source.selectFolder(folder, success: self.onNewModel, failure: self.onModelFailure)
break
default:
// Weird.
break // Just here until there's another executable statement (compiler requires one).
}
}
}
}
| mpl-2.0 | 36746ed4c1e2f2e70560ab989d3a88d9 | 35.166667 | 127 | 0.640553 | 5.157221 | false | false | false | false |
box/box-ios-sdk | Tests/Requests/BodyData/SharedLinkDataSpecs.swift | 1 | 4575 | //
// SharedLinkDataSpecs.swift
// BoxSDKTests-iOS
//
// Created by Artur Jankowski on 21/06/2022.
// Copyright © 2022 box. All rights reserved.
//
@testable import BoxSDK
import Nimble
import Quick
class SharedLinkDataSpecs: QuickSpec {
override func spec() {
describe("SharedLinkData") {
context("init") {
it("should correctly create an object using init with all parameters") {
let sut = SharedLinkData(
access: .open,
password: .value("password123"),
unsharedAt: .value("2019-05-28T19:12:46Z".iso8601!),
vanityName: .value("vanity_name_123"),
canDownload: true,
canEdit: true
)
expect(sut.access).to(equal(.open))
expect(sut.password).to(equal(.value("password123")))
expect(sut.unsharedAt).to(equal(.value("2019-05-28T19:12:46Z".iso8601!)))
expect(sut.vanityName).to(equal(.value("vanity_name_123")))
expect(sut.permissions).to(equal(["can_download": true, "can_edit": true]))
}
it("should correctly create an object using init with access parameter only") {
let sut = SharedLinkData(
access: .open
)
expect(sut.access).to(equal(.open))
expect(sut.password).to(beNil())
expect(sut.unsharedAt).to(beNil())
expect(sut.vanityName).to(beNil())
expect(sut.permissions).to(beNil())
}
}
context("copyWithoutPermissions") {
it("should correctly copy an object using when excluded 1 permission from 2") {
let source = SharedLinkData(
access: .open,
password: .value("password123"),
unsharedAt: .value("2019-05-28T19:12:46Z".iso8601!),
vanityName: .value("vanity_name_123"),
canDownload: true,
canEdit: true
)
let sut = source.copyWithoutPermissions(["can_edit"])
expect(sut.access).to(equal(source.access))
expect(sut.password).to(equal(source.password))
expect(sut.unsharedAt).to(equal(.value("2019-05-28T19:12:46Z".iso8601!)))
expect(sut.vanityName).to(equal(source.vanityName))
expect(sut.permissions).to(equal(["can_download": true]))
}
it("should correctly copy an object using when excluded 2 permission from 2 available") {
let source = SharedLinkData(
access: .open,
password: .value("password123"),
unsharedAt: .value("2019-05-28T19:12:46Z".iso8601!),
vanityName: .value("vanity_name_123"),
canDownload: true,
canEdit: true
)
let sut = source.copyWithoutPermissions(["can_edit", "can_download"])
expect(sut.access).to(equal(source.access))
expect(sut.password).to(equal(source.password))
expect(sut.unsharedAt).to(equal(source.unsharedAt))
expect(sut.vanityName).to(equal(source.vanityName))
expect(sut.permissions).to(beNil())
}
it("should correctly copy an object using when excluded 2 permission from 0 available") {
let source = SharedLinkData(
access: .open,
password: .value("password123"),
unsharedAt: .value("2019-05-28T19:12:46Z".iso8601!),
vanityName: .value("vanity_name_123")
)
let sut = source.copyWithoutPermissions(["can_edit", "can_download"])
expect(sut.access).to(equal(source.access))
expect(sut.password).to(equal(source.password))
expect(sut.unsharedAt).to(equal(source.unsharedAt))
expect(sut.vanityName).to(equal(source.vanityName))
expect(sut.permissions).to(beNil())
}
}
}
}
}
| apache-2.0 | 2e11fc98d8fc0c9320b53dea0bcefa81 | 40.963303 | 106 | 0.491036 | 4.835095 | false | false | false | false |
niunaruto/DeDaoAppSwift | testSwift/Pods/RxSwift/RxSwift/Observables/SubscribeOn.swift | 20 | 2891 | //
// SubscribeOn.swift
// RxSwift
//
// Created by Krunoslav Zaher on 6/14/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
extension ObservableType {
/**
Wraps the source sequence in order to run its subscription and unsubscription logic on the specified
scheduler.
This operation is not commonly used.
This only performs the side-effects of subscription and unsubscription on the specified scheduler.
In order to invoke observer callbacks on a `scheduler`, use `observeOn`.
- seealso: [subscribeOn operator on reactivex.io](http://reactivex.io/documentation/operators/subscribeon.html)
- parameter scheduler: Scheduler to perform subscription and unsubscription actions on.
- returns: The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler.
*/
public func subscribeOn(_ scheduler: ImmediateSchedulerType)
-> Observable<Element> {
return SubscribeOn(source: self, scheduler: scheduler)
}
}
final private class SubscribeOnSink<Ob: ObservableType, Observer: ObserverType>: Sink<Observer>, ObserverType where Ob.Element == Observer.Element {
typealias Element = Observer.Element
typealias Parent = SubscribeOn<Ob>
let parent: Parent
init(parent: Parent, observer: Observer, cancel: Cancelable) {
self.parent = parent
super.init(observer: observer, cancel: cancel)
}
func on(_ event: Event<Element>) {
self.forwardOn(event)
if event.isStopEvent {
self.dispose()
}
}
func run() -> Disposable {
let disposeEverything = SerialDisposable()
let cancelSchedule = SingleAssignmentDisposable()
disposeEverything.disposable = cancelSchedule
let disposeSchedule = self.parent.scheduler.schedule(()) { _ -> Disposable in
let subscription = self.parent.source.subscribe(self)
disposeEverything.disposable = ScheduledDisposable(scheduler: self.parent.scheduler, disposable: subscription)
return Disposables.create()
}
cancelSchedule.setDisposable(disposeSchedule)
return disposeEverything
}
}
final private class SubscribeOn<Ob: ObservableType>: Producer<Ob.Element> {
let source: Ob
let scheduler: ImmediateSchedulerType
init(source: Ob, scheduler: ImmediateSchedulerType) {
self.source = source
self.scheduler = scheduler
}
override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Ob.Element {
let sink = SubscribeOnSink(parent: self, observer: observer, cancel: cancel)
let subscription = sink.run()
return (sink: sink, subscription: subscription)
}
}
| mit | c85a7234f85e4b3dd004725795f42814 | 33.819277 | 174 | 0.684775 | 5.04363 | false | false | false | false |
viviancrs/fanboy | FanBoy/Source/Infrastructure/Constants/Constants.swift | 1 | 1161 | //
// ServiceConstants.swift
// Example
//
// Created by SalmoJunior on 8/17/16.
// Copyright © 2016 CI&T. All rights reserved.
//
import Foundation
struct Constants {
/**
* Storyboad segues constants
*/
struct StoryboardSegues {
static let kCompletionPersonListSegue = "CompletionPersonListSegue"
static let kCompletionGroupListSegue = "CompletionGroupListSegue"
static let kCompletionItemListSegue = "CompletionItemListSegue"
static let kCompletionDetailListSegue = "CompletionDetailListSegue"
}
/**
* Network layer constants
*/
struct Services {
struct Api {
static var baseUrlPath: String {
//TODO: Do the treatment to get URL based on flavor
return "http://private-d2cea-swiftguidelines1.apiary-mock.com"
}
static var swapiUrlPath: String {
return "http://swapi.co/api"
}
}
struct Person {
static let kPath = "/person"
}
struct Group {
static let kPath = "/"
}
}
}
| gpl-3.0 | 44d049e32bb2e59a1c018af33957abae | 23.680851 | 78 | 0.571552 | 4.734694 | false | false | false | false |
DanilaVladi/Microsoft-Cognitive-Services-Swift-SDK | Sample Project/CognitiveServices/CognitiveServices/ViewController.swift | 1 | 3410 | //
// ViewController.swift
// CognitiveServices
//
// Created by Vladimir Danila on 13/04/16.
// Copyright © 2016 Vladimir Danila. All rights reserved.
//
import UIKit
import SafariServices
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
let cognitiveServices = CognitiveServices.sharedInstance
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - UITableView Delegate
@IBOutlet weak var tableView: UITableView!
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let identifier = tableView.cellForRow(at: indexPath)!.textLabel!.text!
switch identifier {
case "Powered by Microsoft Cognitive Services":
let url = URL(string: "https://microsoft.com/cognitive-services/")!
if #available(iOS 9.0, *) {
let sfViewController = SFSafariViewController(url: url)
self.present(sfViewController, animated: true, completion: nil)
} else {
UIApplication.shared.openURL(url)
}
case "Analyze Image", "OCR":
self.performSegue(withIdentifier: identifier, sender: self)
default:
let alert = UIAlertController(title: "Missing", message: "This hasn't been implemented yet.", preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "Ok", style: .cancel, handler: nil)
alert.addAction(cancelAction)
self.present(alert, animated: true, completion: nil)
tableView.deselectRow(at: indexPath, animated: true)
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as UITableViewCell
let text = demos[(indexPath as NSIndexPath).row]
cell.textLabel?.text = text
if text == "Powered by Microsoft Cognitive Services" {
cell.accessoryType = .none
cell.textLabel?.textColor = .blue
}
else {
cell.accessoryType = .disclosureIndicator
cell.textLabel?.textColor = .black
}
return cell
}
// MARK: - UITableViewDataSource Delegate
let demos = ["Analyze Image","Get Thumbnail","List Domain Specific Model","OCR","Recognize Domain Specfic Content","Tag Image", "Powered by Microsoft Cognitive Services"]
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return demos.count
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
segue.destination.navigationItem.title = demos[(tableView.indexPathForSelectedRow! as NSIndexPath).row]
tableView.deselectRow(at: tableView.indexPathForSelectedRow!, animated: true)
}
}
| apache-2.0 | 106353cdaa33001503fbead76668b266 | 31.160377 | 174 | 0.62071 | 5.463141 | false | false | false | false |
mrdepth/EVEUniverse | Neocom/Neocom/Mail/MailBox.swift | 2 | 3633 | //
// MailBox.swift
// Neocom
//
// Created by Artem Shimanski on 2/14/20.
// Copyright © 2020 Artem Shimanski. All rights reserved.
//
import SwiftUI
import EVEAPI
import Alamofire
import Combine
struct MailBox: View {
@EnvironmentObject private var sharedState: SharedState
@Environment(\.self) private var environment
@Environment(\.managedObjectContext) private var managedObjectContext
@FetchRequest(sortDescriptors: [NSSortDescriptor(keyPath: \MailDraft.date, ascending: false)]) private var drafts: FetchedResults<MailDraft>
//
@ObservedObject private var labels = Lazy<DataLoader<ESI.MailLabels, AFError>, Account>()
@State private var isComposeMailPresented = false
private var composeButton: some View {
BarButtonItems.compose {
self.isComposeMailPresented = true
}
}
private func getLabels(account: Account, cachePolicy: URLRequest.CachePolicy = .useProtocolCachePolicy) -> AnyPublisher<ESI.MailLabels, AFError> {
sharedState.esi.characters.characterID(Int(account.characterID)).mail().labels().get(cachePolicy: cachePolicy)
.map{$0.value}
.receive(on: RunLoop.main)
.eraseToAnyPublisher()
}
var body: some View {
let result = sharedState.account.map { account in
self.labels.get(account, initial: DataLoader(getLabels(account: account)))
}
let labels = result?.result?.value
// let draftsCount =
let list = List {
if labels?.labels != nil {
Section(footer: Text("Total Unread: \(UnitFormatter.localizedString(from: labels!.totalUnreadCount ?? 0, unit: .none, style: .long))").frame(maxWidth: .infinity, alignment: .trailing)) {
ForEach(labels!.labels!, id: \.labelID) { label in
MailLabel(label: label)
}
}
}
NavigationLink(destination: MailDrafts()) {
HStack {
Text("Drafts")
Spacer()
if drafts.count > 0 {
Text("\(drafts.count)").foregroundColor(.secondary)
}
}
}
}.listStyle(GroupedListStyle())
.overlay(result == nil ? Text(RuntimeError.noAccount).padding() : nil)
.overlay((result?.result?.error).map{Text($0)})
.overlay(labels?.labels?.isEmpty == true ? Text(RuntimeError.noResult).padding() : nil)
return Group {
if result != nil {
list.onRefresh(isRefreshing: Binding(result!, keyPath: \.isLoading)) {
guard let account = self.sharedState.account else {return}
result?.update(self.getLabels(account: account, cachePolicy: .reloadIgnoringLocalCacheData))
}
}
else {
list
}
}
.navigationBarTitle(Text("Mail"))
.navigationBarItems(trailing: composeButton)
.sheet(isPresented: $isComposeMailPresented) {
ComposeMail {
self.isComposeMailPresented = false
}
.modifier(ServicesViewModifier(environment: self.environment, sharedState: self.sharedState))
.navigationViewStyle(StackNavigationViewStyle())
}
}
}
#if DEBUG
struct MailBox_Previews: PreviewProvider {
static var previews: some View {
NavigationView {
MailBox()
.modifier(ServicesViewModifier.testModifier())
}
}
}
#endif
| lgpl-2.1 | 277c0ccf749319930d9bd387a452c80d | 35.32 | 202 | 0.590584 | 5.058496 | false | false | false | false |
almazrafi/Metatron | Tests/MetatronTests/ID3v2/ID3v2TagTest.swift | 1 | 44749 | //
// ID3v2TagTest.swift
// Metatron
//
// Copyright (c) 2016 Almaz Ibragimov
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import XCTest
@testable import Metatron
extension ID3v2Tag {
// MARK: Initializers
fileprivate convenience init?(fromData data: [UInt8], range: inout Range<UInt64>) {
let stream = MemoryStream(data: data)
guard stream.openForReading() else {
return nil
}
self.init(fromStream: stream, range: &range)
}
}
class ID3v2TagTest: XCTestCase {
// MARK: Instance Methods
func testSubscript() {
let tag = ID3v2Tag()
XCTAssert(tag.isEmpty && (tag.frameSetList.count == 0))
tag.appendFrameSet(ID3v2FrameID.aenc)
tag.appendFrameSet(ID3v2FrameID.apic)
XCTAssert((!tag.isEmpty) && (tag.frameSetList.count == 2))
guard let frameSet1 = tag[ID3v2FrameID.aenc] else {
return XCTFail()
}
guard let frameSet2 = tag[ID3v2FrameID.aenc] else {
return XCTFail()
}
guard let frameSet3 = tag[ID3v2FrameID.apic] else {
return XCTFail()
}
XCTAssert(frameSet1 === frameSet2)
XCTAssert(frameSet1 !== frameSet3)
XCTAssert(frameSet1.identifier == ID3v2FrameID.aenc)
XCTAssert(frameSet2.identifier == ID3v2FrameID.aenc)
XCTAssert(frameSet3.identifier == ID3v2FrameID.apic)
XCTAssert(tag[ID3v2FrameID.aspi] == nil)
XCTAssert(tag[ID3v2FrameID.comm] == nil)
}
// MARK:
func testAppendFrameSet() {
let tag = ID3v2Tag()
XCTAssert(tag.isEmpty && (tag.frameSetList.count == 0))
let frameSet1 = tag.appendFrameSet(ID3v2FrameID.aenc)
XCTAssert((!tag.isEmpty) && (tag.frameSetList.count == 1))
let frameSet2 = tag.appendFrameSet(ID3v2FrameID.aenc)
XCTAssert((!tag.isEmpty) && (tag.frameSetList.count == 1))
let frameSet3 = tag.appendFrameSet(ID3v2FrameID.apic)
XCTAssert((!tag.isEmpty) && (tag.frameSetList.count == 2))
XCTAssert(frameSet1 === frameSet2)
XCTAssert(frameSet1 !== frameSet3)
XCTAssert(frameSet1.identifier == ID3v2FrameID.aenc)
XCTAssert(frameSet2.identifier == ID3v2FrameID.aenc)
XCTAssert(frameSet3.identifier == ID3v2FrameID.apic)
XCTAssert(tag.appendFrameSet(ID3v2FrameID.aenc) === frameSet1)
XCTAssert(tag.appendFrameSet(ID3v2FrameID.apic) === frameSet3)
frameSet1.appendFrame()
frameSet1.appendFrame()
XCTAssert(tag.appendFrameSet(ID3v2FrameID.aenc) === frameSet1)
XCTAssert(tag.appendFrameSet(ID3v2FrameID.apic) === frameSet3)
XCTAssert(frameSet1.frames.count == 3)
XCTAssert(frameSet3.frames.count == 1)
}
func testResetFrameSet() {
let tag = ID3v2Tag()
XCTAssert(tag.isEmpty && (tag.frameSetList.count == 0))
let frameSet1 = tag.resetFrameSet(ID3v2FrameID.aenc)
XCTAssert((!tag.isEmpty) && (tag.frameSetList.count == 1))
let frameSet2 = tag.resetFrameSet(ID3v2FrameID.aenc)
XCTAssert((!tag.isEmpty) && (tag.frameSetList.count == 1))
let frameSet3 = tag.resetFrameSet(ID3v2FrameID.apic)
XCTAssert((!tag.isEmpty) && (tag.frameSetList.count == 2))
XCTAssert(frameSet1 === frameSet2)
XCTAssert(frameSet1 !== frameSet3)
XCTAssert(frameSet1.identifier == ID3v2FrameID.aenc)
XCTAssert(frameSet2.identifier == ID3v2FrameID.aenc)
XCTAssert(frameSet3.identifier == ID3v2FrameID.apic)
XCTAssert(tag.resetFrameSet(ID3v2FrameID.aenc) === frameSet1)
XCTAssert(tag.resetFrameSet(ID3v2FrameID.apic) === frameSet3)
frameSet1.appendFrame()
frameSet1.appendFrame()
XCTAssert(tag.resetFrameSet(ID3v2FrameID.aenc) === frameSet1)
XCTAssert(tag.resetFrameSet(ID3v2FrameID.apic) === frameSet3)
XCTAssert(frameSet1.frames.count == 1)
XCTAssert(frameSet3.frames.count == 1)
}
func testRemoveFrameSet() {
let tag = ID3v2Tag()
XCTAssert(tag.isEmpty && (tag.frameSetList.count == 0))
let frameSet1 = tag.appendFrameSet(ID3v2FrameID.aenc)
XCTAssert((!tag.isEmpty) && (tag.frameSetList.count == 1))
let frameSet2 = tag.appendFrameSet(ID3v2FrameID.apic)
XCTAssert((!tag.isEmpty) && (tag.frameSetList.count == 2))
XCTAssert(tag.removeFrameSet(frameSet1.identifier) == true)
XCTAssert(tag.removeFrameSet(frameSet1.identifier) == false)
XCTAssert((!tag.isEmpty) && (tag.frameSetList.count == 1))
XCTAssert(tag.removeFrameSet(frameSet2.identifier) == true)
XCTAssert(tag.removeFrameSet(frameSet2.identifier) == false)
XCTAssert(tag.isEmpty && (tag.frameSetList.count == 0))
}
func testRevise() {
let tag = ID3v2Tag()
let frameSet1 = tag.appendFrameSet(ID3v2FrameID.aenc)
let frameSet2 = tag.appendFrameSet(ID3v2FrameID.apic)
tag.appendFrameSet(ID3v2FrameID.comm)
XCTAssert((!tag.isEmpty) && (tag.frameSetList.count == 3))
let stuff1 = frameSet1.mainFrame.imposeStuff(format: ID3v2UnknownValueFormat.regular)
let stuff2 = frameSet2.mainFrame.imposeStuff(format: ID3v2UnknownValueFormat.regular)
stuff1.content = [1, 2, 3]
stuff2.content = [4, 5, 6]
tag.revise()
XCTAssert((!tag.isEmpty) && (tag.frameSetList.count == 2))
XCTAssert(tag.frameSetList[0] === frameSet1)
XCTAssert(tag.frameSetList[1] === frameSet2)
}
func testClear() {
let tag = ID3v2Tag()
XCTAssert(tag.isEmpty && (tag.frameSetList.count == 0))
let frameSet1 = tag.appendFrameSet(ID3v2FrameID.aenc)
let frameSet2 = tag.appendFrameSet(ID3v2FrameID.apic)
tag.appendFrameSet(ID3v2FrameID.comm)
XCTAssert((!tag.isEmpty) && (tag.frameSetList.count == 3))
let stuff1 = frameSet1.mainFrame.imposeStuff(format: ID3v2UnknownValueFormat.regular)
let stuff2 = frameSet2.mainFrame.imposeStuff(format: ID3v2UnknownValueFormat.regular)
stuff1.content = [1, 2, 3]
stuff2.content = [4, 5, 6]
tag.clear()
XCTAssert(tag.isEmpty && (tag.frameSetList.count == 0))
}
// MARK:
func testVersion2CaseA() {
let tag = ID3v2Tag(version: ID3v2Version.v2)
tag.revision = 123
tag.experimentalIndicator = true
tag.footerPresent = true
tag.fillingLength = 123456
XCTAssert(tag.isEmpty && (tag.toData() == nil))
tag.title = "Title"
tag.artists = ["Artist 1", "Artist 2"]
tag.album = "Album"
tag.genres = ["Genre 1", "Genre 2", "Genre 3"]
tag.releaseDate = TagDate(year: 1998, month: 12, day: 31, time: TagTime(hour: 12, minute: 34, second: 56))
tag.trackNumber = TagNumber(3, total: 4)
tag.discNumber = TagNumber(1, total: 2)
tag.coverArt = TagImage(data: [1, 2, 3], mainMimeType: "image/png", description: "Cover art")
tag.copyrights = ["Copyright"]
tag.comments = ["Comment 1", "Comment 2", "Comment 3", "Comment 4"]
tag.lyrics = TagLyrics(pieces: [TagLyrics.Piece("Lyrics piece 1", timeStamp: 1230),
TagLyrics.Piece("Lyrics piece 2", timeStamp: 4560)])
let extraFrameSet1 = tag.appendFrameSet(ID3v2FrameID.tcom)
let extraFrameSet2 = tag.appendFrameSet(ID3v2FrameID.tpub)
let extraStuff1 = extraFrameSet1.mainFrame.imposeStuff(format: ID3v2TextInformationFormat.regular)
let extraStuff2 = extraFrameSet2.mainFrame.imposeStuff(format: ID3v2TextInformationFormat.regular)
extraStuff1.timeValue = TagTime(hour: 12, minute: 34, second: 56)
extraStuff2.dateValue = TagDate(year: 1998, month: 12, day: 31)
XCTAssert(!tag.isEmpty)
guard let data = tag.toData() else {
return XCTFail()
}
XCTAssert(data.count == tag.fillingLength)
let prefixData = Array<UInt8>(repeating: 123, count: 123)
let suffixData = Array<UInt8>(repeating: 231, count: 231)
var range = Range<UInt64>(123..<(123 + UInt64(data.count)))
guard let other = ID3v2Tag(fromData: prefixData + data + suffixData, range: &range) else {
return XCTFail()
}
XCTAssert(range.lowerBound == 123)
XCTAssert(range.upperBound == 123 + UInt64(data.count))
XCTAssert(!other.isEmpty)
XCTAssert(other.version == tag.version)
XCTAssert(other.revision == tag.revision)
XCTAssert(other.experimentalIndicator == false)
XCTAssert(other.footerPresent == false)
XCTAssert(other.fillingLength == tag.fillingLength)
XCTAssert(other.title == tag.title)
XCTAssert(other.artists == tag.artists)
XCTAssert(other.album == tag.album)
XCTAssert(other.genres == tag.genres)
XCTAssert(other.releaseDate == TagDate(year: 1998, month: 12, day: 31, time: TagTime(hour: 12, minute: 34)))
XCTAssert(other.trackNumber == tag.trackNumber)
XCTAssert(other.discNumber == tag.discNumber)
XCTAssert(other.coverArt == tag.coverArt)
XCTAssert(other.copyrights == tag.copyrights)
XCTAssert(other.comments == tag.comments)
XCTAssert(other.lyrics == tag.lyrics)
guard let otherFrameSet1 = other[ID3v2FrameID.tcom] else {
return XCTFail()
}
guard let otherFrameSet2 = other[ID3v2FrameID.tpub] else {
return XCTFail()
}
let otherExtraStuff1 = otherFrameSet1.mainFrame.stuff(format: ID3v2TextInformationFormat.regular)
let otherExtraStuff2 = otherFrameSet2.mainFrame.stuff(format: ID3v2TextInformationFormat.regular)
XCTAssert(otherExtraStuff1.timeValue == TagTime(hour: 12, minute: 34))
XCTAssert(otherExtraStuff2.dateValue == TagDate(year: 1998, month: 12, day: 31))
XCTAssert(other.frameSetList.count == tag.frameSetList.count - 1)
}
func testVersion2CaseB() {
let tag = ID3v2Tag(version: ID3v2Version.v2)
tag.revision = 123
tag.experimentalIndicator = true
tag.footerPresent = false
tag.fillingLength = 0
XCTAssert(tag.isEmpty && (tag.toData() == nil))
tag.title = "Title"
tag.artists = ["Artist 1", "Artist 2"]
tag.album = "Album"
tag.genres = ["Genre 1", "Genre 2", "Genre 3"]
tag.releaseDate = TagDate(year: 1998, month: 12, day: 31, time: TagTime(hour: 12, minute: 34, second: 56))
tag.trackNumber = TagNumber(3, total: 4)
tag.discNumber = TagNumber(1, total: 2)
tag.coverArt = TagImage(data: [1, 2, 3], mainMimeType: "image/jpeg", description: "Cover art")
tag.copyrights = ["Copyright"]
tag.comments = ["Comment 1", "Comment 2", "Comment 3", "Comment 4"]
tag.lyrics = TagLyrics(pieces: [TagLyrics.Piece("Lyrics piece 1", timeStamp: 1230),
TagLyrics.Piece("Lyrics piece 2", timeStamp: 4560)])
let extraFrameSet1 = tag.appendFrameSet(ID3v2FrameID.tcom)
let extraFrameSet2 = tag.appendFrameSet(ID3v2FrameID.tpub)
let extraStuff1 = extraFrameSet1.mainFrame.imposeStuff(format: ID3v2TextInformationFormat.regular)
let extraStuff2 = extraFrameSet2.mainFrame.imposeStuff(format: ID3v2TextInformationFormat.regular)
extraStuff1.timeValue = TagTime(hour: 12, minute: 34, second: 56)
extraStuff2.dateValue = TagDate(year: 1998, month: 12, day: 31)
XCTAssert(!tag.isEmpty)
guard let data = tag.toData() else {
return XCTFail()
}
XCTAssert(!data.isEmpty)
let prefixData = Array<UInt8>(repeating: 123, count: 123)
let suffixData = Array<UInt8>(repeating: 231, count: 231)
var range = Range<UInt64>(123..<(354 + UInt64(data.count)))
guard let other = ID3v2Tag(fromData: prefixData + data + suffixData, range: &range) else {
return XCTFail()
}
XCTAssert(range.lowerBound == 123)
XCTAssert(range.upperBound == 123 + UInt64(data.count))
XCTAssert(!other.isEmpty)
XCTAssert(other.version == tag.version)
XCTAssert(other.revision == tag.revision)
XCTAssert(other.experimentalIndicator == false)
XCTAssert(other.footerPresent == false)
XCTAssert(other.fillingLength == tag.fillingLength)
XCTAssert(other.title == tag.title)
XCTAssert(other.artists == tag.artists)
XCTAssert(other.album == tag.album)
XCTAssert(other.genres == tag.genres)
XCTAssert(other.releaseDate == TagDate(year: 1998, month: 12, day: 31, time: TagTime(hour: 12, minute: 34)))
XCTAssert(other.trackNumber == tag.trackNumber)
XCTAssert(other.discNumber == tag.discNumber)
XCTAssert(other.coverArt == tag.coverArt)
XCTAssert(other.copyrights == tag.copyrights)
XCTAssert(other.comments == tag.comments)
XCTAssert(other.lyrics == tag.lyrics)
guard let otherFrameSet1 = other[ID3v2FrameID.tcom] else {
return XCTFail()
}
guard let otherFrameSet2 = other[ID3v2FrameID.tpub] else {
return XCTFail()
}
let otherExtraStuff1 = otherFrameSet1.mainFrame.stuff(format: ID3v2TextInformationFormat.regular)
let otherExtraStuff2 = otherFrameSet2.mainFrame.stuff(format: ID3v2TextInformationFormat.regular)
XCTAssert(otherExtraStuff1.timeValue == TagTime(hour: 12, minute: 34))
XCTAssert(otherExtraStuff2.dateValue == TagDate(year: 1998, month: 12, day: 31))
XCTAssert(other.frameSetList.count == tag.frameSetList.count - 1)
}
func testVersion2CaseC() {
let tag = ID3v2Tag(version: ID3v2Version.v2)
tag.revision = 0
tag.experimentalIndicator = false
tag.footerPresent = false
tag.fillingLength = 123456
XCTAssert(tag.isEmpty && (tag.toData() == nil))
tag.title = "Title"
tag.artists = ["Artist 1", "Artist 2"]
tag.album = "Album"
tag.genres = ["Genre 1", "Genre 2", "Genre 3"]
tag.releaseDate = TagDate(year: 1998, month: 12, day: 31, time: TagTime(hour: 12, minute: 34, second: 56))
tag.trackNumber = TagNumber(3, total: 4)
tag.discNumber = TagNumber(1, total: 2)
tag.coverArt = TagImage(data: [1, 2, 3], mainMimeType: "image/gif", description: "Cover art")
tag.copyrights = ["Copyright"]
tag.comments = ["Comment 1", "Comment 2", "Comment 3", "Comment 4"]
tag.lyrics = TagLyrics(pieces: [TagLyrics.Piece("Lyrics piece 1", timeStamp: 1230),
TagLyrics.Piece("Lyrics piece 2", timeStamp: 4560)])
let extraFrameSet1 = tag.appendFrameSet(ID3v2FrameID.tcom)
let extraFrameSet2 = tag.appendFrameSet(ID3v2FrameID.tpub)
let extraStuff1 = extraFrameSet1.mainFrame.imposeStuff(format: ID3v2TextInformationFormat.regular)
let extraStuff2 = extraFrameSet2.mainFrame.imposeStuff(format: ID3v2TextInformationFormat.regular)
extraStuff1.timeValue = TagTime(hour: 12, minute: 34, second: 56)
extraStuff2.dateValue = TagDate(year: 1998, month: 12, day: 31)
XCTAssert(!tag.isEmpty)
guard let data = tag.toData() else {
return XCTFail()
}
XCTAssert(data.count == tag.fillingLength)
var range = Range<UInt64>(0..<UInt64(data.count))
guard let other = ID3v2Tag(fromData: data, range: &range) else {
return XCTFail()
}
XCTAssert(range.lowerBound == 0)
XCTAssert(range.upperBound == UInt64(data.count))
XCTAssert(!other.isEmpty)
XCTAssert(other.version == tag.version)
XCTAssert(other.revision == tag.revision)
XCTAssert(other.experimentalIndicator == false)
XCTAssert(other.footerPresent == false)
XCTAssert(other.fillingLength == tag.fillingLength)
XCTAssert(other.title == tag.title)
XCTAssert(other.artists == tag.artists)
XCTAssert(other.album == tag.album)
XCTAssert(other.genres == tag.genres)
XCTAssert(other.releaseDate == TagDate(year: 1998, month: 12, day: 31, time: TagTime(hour: 12, minute: 34)))
XCTAssert(other.trackNumber == tag.trackNumber)
XCTAssert(other.discNumber == tag.discNumber)
XCTAssert(other.coverArt == TagImage())
XCTAssert(other.copyrights == tag.copyrights)
XCTAssert(other.comments == tag.comments)
XCTAssert(other.lyrics == tag.lyrics)
guard let otherFrameSet1 = other[ID3v2FrameID.tcom] else {
return XCTFail()
}
guard let otherFrameSet2 = other[ID3v2FrameID.tpub] else {
return XCTFail()
}
let otherExtraStuff1 = otherFrameSet1.mainFrame.stuff(format: ID3v2TextInformationFormat.regular)
let otherExtraStuff2 = otherFrameSet2.mainFrame.stuff(format: ID3v2TextInformationFormat.regular)
XCTAssert(otherExtraStuff1.timeValue == TagTime(hour: 12, minute: 34))
XCTAssert(otherExtraStuff2.dateValue == TagDate(year: 1998, month: 12, day: 31))
XCTAssert(other.frameSetList.count == tag.frameSetList.count - 2)
}
// MARK:
func testVersion3CaseA() {
let tag = ID3v2Tag(version: ID3v2Version.v3)
tag.revision = 123
tag.experimentalIndicator = true
tag.footerPresent = true
tag.fillingLength = 123456
XCTAssert(tag.isEmpty && (tag.toData() == nil))
tag.title = "Title"
tag.artists = ["Artist 1", "Artist 2"]
tag.album = "Album"
tag.genres = ["Genre 1", "Genre 2", "Genre 3"]
tag.releaseDate = TagDate(year: 1998, month: 12, day: 31, time: TagTime(hour: 12, minute: 34, second: 56))
tag.trackNumber = TagNumber(3, total: 4)
tag.discNumber = TagNumber(1, total: 2)
tag.coverArt = TagImage(data: [1, 2, 3], mainMimeType: "image/png", description: "Cover art")
tag.copyrights = ["Copyright"]
tag.comments = ["Comment 1", "Comment 2", "Comment 3", "Comment 4"]
tag.lyrics = TagLyrics(pieces: [TagLyrics.Piece("Lyrics piece 1", timeStamp: 1230),
TagLyrics.Piece("Lyrics piece 2", timeStamp: 4560)])
let extraFrameSet1 = tag.appendFrameSet(ID3v2FrameID.tcom)
let extraFrameSet2 = tag.appendFrameSet(ID3v2FrameID.tpub)
let extraStuff1 = extraFrameSet1.mainFrame.imposeStuff(format: ID3v2TextInformationFormat.regular)
let extraStuff2 = extraFrameSet2.mainFrame.imposeStuff(format: ID3v2TextInformationFormat.regular)
extraStuff1.timeValue = TagTime(hour: 12, minute: 34, second: 56)
extraStuff2.dateValue = TagDate(year: 1998, month: 12, day: 31)
XCTAssert(!tag.isEmpty)
guard let data = tag.toData() else {
return XCTFail()
}
XCTAssert(data.count == tag.fillingLength)
let prefixData = Array<UInt8>(repeating: 123, count: 123)
let suffixData = Array<UInt8>(repeating: 231, count: 231)
var range = Range<UInt64>(123..<(123 + UInt64(data.count)))
guard let other = ID3v2Tag(fromData: prefixData + data + suffixData, range: &range) else {
return XCTFail()
}
XCTAssert(range.lowerBound == 123)
XCTAssert(range.upperBound == 123 + UInt64(data.count))
XCTAssert(!other.isEmpty)
XCTAssert(other.version == tag.version)
XCTAssert(other.revision == tag.revision)
XCTAssert(other.experimentalIndicator == tag.experimentalIndicator)
XCTAssert(other.footerPresent == false)
XCTAssert(other.fillingLength == tag.fillingLength)
XCTAssert(other.title == tag.title)
XCTAssert(other.artists == tag.artists)
XCTAssert(other.album == tag.album)
XCTAssert(other.genres == tag.genres)
XCTAssert(other.releaseDate == TagDate(year: 1998, month: 12, day: 31, time: TagTime(hour: 12, minute: 34)))
XCTAssert(other.trackNumber == tag.trackNumber)
XCTAssert(other.discNumber == tag.discNumber)
XCTAssert(other.coverArt == tag.coverArt)
XCTAssert(other.copyrights == tag.copyrights)
XCTAssert(other.comments == tag.comments)
XCTAssert(other.lyrics == tag.lyrics)
guard let otherFrameSet1 = other[ID3v2FrameID.tcom] else {
return XCTFail()
}
guard let otherFrameSet2 = other[ID3v2FrameID.tpub] else {
return XCTFail()
}
let otherExtraStuff1 = otherFrameSet1.mainFrame.stuff(format: ID3v2TextInformationFormat.regular)
let otherExtraStuff2 = otherFrameSet2.mainFrame.stuff(format: ID3v2TextInformationFormat.regular)
XCTAssert(otherExtraStuff1.timeValue == TagTime(hour: 12, minute: 34))
XCTAssert(otherExtraStuff2.dateValue == TagDate(year: 1998, month: 12, day: 31))
XCTAssert(other.frameSetList.count == tag.frameSetList.count - 1)
}
func testVersion3CaseB() {
let tag = ID3v2Tag(version: ID3v2Version.v3)
tag.revision = 123
tag.experimentalIndicator = true
tag.footerPresent = false
tag.fillingLength = 0
XCTAssert(tag.isEmpty && (tag.toData() == nil))
tag.title = "Title"
tag.artists = ["Artist 1", "Artist 2"]
tag.album = "Album"
tag.genres = ["Genre 1", "Genre 2", "Genre 3"]
tag.releaseDate = TagDate(year: 1998, month: 12, day: 31, time: TagTime(hour: 12, minute: 34, second: 56))
tag.trackNumber = TagNumber(3, total: 4)
tag.discNumber = TagNumber(1, total: 2)
tag.coverArt = TagImage(data: [1, 2, 3], mainMimeType: "image/jpeg", description: "Cover art")
tag.copyrights = ["Copyright"]
tag.comments = ["Comment 1", "Comment 2", "Comment 3", "Comment 4"]
tag.lyrics = TagLyrics(pieces: [TagLyrics.Piece("Lyrics piece 1", timeStamp: 1230),
TagLyrics.Piece("Lyrics piece 2", timeStamp: 4560)])
let extraFrameSet1 = tag.appendFrameSet(ID3v2FrameID.tcom)
let extraFrameSet2 = tag.appendFrameSet(ID3v2FrameID.tpub)
let extraStuff1 = extraFrameSet1.mainFrame.imposeStuff(format: ID3v2TextInformationFormat.regular)
let extraStuff2 = extraFrameSet2.mainFrame.imposeStuff(format: ID3v2TextInformationFormat.regular)
extraStuff1.timeValue = TagTime(hour: 12, minute: 34, second: 56)
extraStuff2.dateValue = TagDate(year: 1998, month: 12, day: 31)
XCTAssert(!tag.isEmpty)
guard let data = tag.toData() else {
return XCTFail()
}
XCTAssert(!data.isEmpty)
let prefixData = Array<UInt8>(repeating: 123, count: 123)
let suffixData = Array<UInt8>(repeating: 231, count: 231)
var range = Range<UInt64>(123..<(354 + UInt64(data.count)))
guard let other = ID3v2Tag(fromData: prefixData + data + suffixData, range: &range) else {
return XCTFail()
}
XCTAssert(range.lowerBound == 123)
XCTAssert(range.upperBound == 123 + UInt64(data.count))
XCTAssert(!other.isEmpty)
XCTAssert(other.version == tag.version)
XCTAssert(other.revision == tag.revision)
XCTAssert(other.experimentalIndicator == tag.experimentalIndicator)
XCTAssert(other.footerPresent == false)
XCTAssert(other.fillingLength == tag.fillingLength)
XCTAssert(other.title == tag.title)
XCTAssert(other.artists == tag.artists)
XCTAssert(other.album == tag.album)
XCTAssert(other.genres == tag.genres)
XCTAssert(other.releaseDate == TagDate(year: 1998, month: 12, day: 31, time: TagTime(hour: 12, minute: 34)))
XCTAssert(other.trackNumber == tag.trackNumber)
XCTAssert(other.discNumber == tag.discNumber)
XCTAssert(other.coverArt == tag.coverArt)
XCTAssert(other.copyrights == tag.copyrights)
XCTAssert(other.comments == tag.comments)
XCTAssert(other.lyrics == tag.lyrics)
guard let otherFrameSet1 = other[ID3v2FrameID.tcom] else {
return XCTFail()
}
guard let otherFrameSet2 = other[ID3v2FrameID.tpub] else {
return XCTFail()
}
let otherExtraStuff1 = otherFrameSet1.mainFrame.stuff(format: ID3v2TextInformationFormat.regular)
let otherExtraStuff2 = otherFrameSet2.mainFrame.stuff(format: ID3v2TextInformationFormat.regular)
XCTAssert(otherExtraStuff1.timeValue == TagTime(hour: 12, minute: 34))
XCTAssert(otherExtraStuff2.dateValue == TagDate(year: 1998, month: 12, day: 31))
XCTAssert(other.frameSetList.count == tag.frameSetList.count - 1)
}
func testVersion3CaseC() {
let tag = ID3v2Tag(version: ID3v2Version.v3)
tag.revision = 0
tag.experimentalIndicator = false
tag.footerPresent = false
tag.fillingLength = 123456
XCTAssert(tag.isEmpty && (tag.toData() == nil))
tag.title = "Title"
tag.artists = ["Artist 1", "Artist 2"]
tag.album = "Album"
tag.genres = ["Genre 1", "Genre 2", "Genre 3"]
tag.releaseDate = TagDate(year: 1998, month: 12, day: 31, time: TagTime(hour: 12, minute: 34, second: 56))
tag.trackNumber = TagNumber(3, total: 4)
tag.discNumber = TagNumber(1, total: 2)
tag.coverArt = TagImage(data: [1, 2, 3], mainMimeType: "image/gif", description: "Cover art")
tag.copyrights = ["Copyright"]
tag.comments = ["Comment 1", "Comment 2", "Comment 3", "Comment 4"]
tag.lyrics = TagLyrics(pieces: [TagLyrics.Piece("Lyrics piece 1", timeStamp: 1230),
TagLyrics.Piece("Lyrics piece 2", timeStamp: 4560)])
let extraFrameSet1 = tag.appendFrameSet(ID3v2FrameID.tcom)
let extraFrameSet2 = tag.appendFrameSet(ID3v2FrameID.tpub)
let extraStuff1 = extraFrameSet1.mainFrame.imposeStuff(format: ID3v2TextInformationFormat.regular)
let extraStuff2 = extraFrameSet2.mainFrame.imposeStuff(format: ID3v2TextInformationFormat.regular)
extraStuff1.timeValue = TagTime(hour: 12, minute: 34, second: 56)
extraStuff2.dateValue = TagDate(year: 1998, month: 12, day: 31)
XCTAssert(!tag.isEmpty)
guard let data = tag.toData() else {
return XCTFail()
}
XCTAssert(data.count == tag.fillingLength)
var range = Range<UInt64>(0..<UInt64(data.count))
guard let other = ID3v2Tag(fromData: data, range: &range) else {
return XCTFail()
}
XCTAssert(range.lowerBound == 0)
XCTAssert(range.upperBound == UInt64(data.count))
XCTAssert(!other.isEmpty)
XCTAssert(other.version == tag.version)
XCTAssert(other.revision == tag.revision)
XCTAssert(other.experimentalIndicator == tag.experimentalIndicator)
XCTAssert(other.footerPresent == false)
XCTAssert(other.fillingLength == tag.fillingLength)
XCTAssert(other.title == tag.title)
XCTAssert(other.artists == tag.artists)
XCTAssert(other.album == tag.album)
XCTAssert(other.genres == tag.genres)
XCTAssert(other.releaseDate == TagDate(year: 1998, month: 12, day: 31, time: TagTime(hour: 12, minute: 34)))
XCTAssert(other.trackNumber == tag.trackNumber)
XCTAssert(other.discNumber == tag.discNumber)
XCTAssert(other.coverArt == tag.coverArt)
XCTAssert(other.copyrights == tag.copyrights)
XCTAssert(other.comments == tag.comments)
XCTAssert(other.lyrics == tag.lyrics)
guard let otherFrameSet1 = other[ID3v2FrameID.tcom] else {
return XCTFail()
}
guard let otherFrameSet2 = other[ID3v2FrameID.tpub] else {
return XCTFail()
}
let otherExtraStuff1 = otherFrameSet1.mainFrame.stuff(format: ID3v2TextInformationFormat.regular)
let otherExtraStuff2 = otherFrameSet2.mainFrame.stuff(format: ID3v2TextInformationFormat.regular)
XCTAssert(otherExtraStuff1.timeValue == TagTime(hour: 12, minute: 34))
XCTAssert(otherExtraStuff2.dateValue == TagDate(year: 1998, month: 12, day: 31))
XCTAssert(other.frameSetList.count == tag.frameSetList.count - 1)
}
// MARK:
func testVersion4CaseA() {
let tag = ID3v2Tag(version: ID3v2Version.v4)
tag.revision = 123
tag.experimentalIndicator = true
tag.footerPresent = true
tag.fillingLength = 123456
XCTAssert(tag.isEmpty && (tag.toData() == nil))
tag.title = "Title"
tag.artists = ["Artist 1", "Artist 2"]
tag.album = "Album"
tag.genres = ["Genre 1", "Genre 2", "Genre 3"]
tag.releaseDate = TagDate(year: 1998, month: 12, day: 31, time: TagTime(hour: 12, minute: 34, second: 56))
tag.trackNumber = TagNumber(3, total: 4)
tag.discNumber = TagNumber(1, total: 2)
tag.coverArt = TagImage(data: [1, 2, 3], mainMimeType: "image/png", description: "Cover art")
tag.copyrights = ["Copyright"]
tag.comments = ["Comment 1", "Comment 2", "Comment 3", "Comment 4"]
tag.lyrics = TagLyrics(pieces: [TagLyrics.Piece("Lyrics piece 1", timeStamp: 1230),
TagLyrics.Piece("Lyrics piece 2", timeStamp: 4560)])
let extraFrameSet1 = tag.appendFrameSet(ID3v2FrameID.tcom)
let extraFrameSet2 = tag.appendFrameSet(ID3v2FrameID.tpub)
let extraStuff1 = extraFrameSet1.mainFrame.imposeStuff(format: ID3v2TextInformationFormat.regular)
let extraStuff2 = extraFrameSet2.mainFrame.imposeStuff(format: ID3v2TextInformationFormat.regular)
extraStuff1.timeValue = TagTime(hour: 12, minute: 34, second: 56)
extraStuff2.dateValue = TagDate(year: 1998, month: 12, day: 31)
XCTAssert(!tag.isEmpty)
guard let data = tag.toData() else {
return XCTFail()
}
XCTAssert(data.count == tag.fillingLength)
let prefixData = Array<UInt8>(repeating: 123, count: 123)
let suffixData = Array<UInt8>(repeating: 231, count: 231)
var range = Range<UInt64>(0..<(123 + UInt64(data.count)))
guard let other = ID3v2Tag(fromData: prefixData + data + suffixData, range: &range) else {
return XCTFail()
}
XCTAssert(range.lowerBound == 123)
XCTAssert(range.upperBound == 123 + UInt64(data.count))
XCTAssert(!other.isEmpty)
XCTAssert(other.version == tag.version)
XCTAssert(other.revision == tag.revision)
XCTAssert(other.experimentalIndicator == tag.experimentalIndicator)
XCTAssert(other.footerPresent == tag.footerPresent)
XCTAssert(other.fillingLength == tag.fillingLength)
XCTAssert(other.title == tag.title)
XCTAssert(other.artists == tag.artists)
XCTAssert(other.album == tag.album)
XCTAssert(other.genres == tag.genres)
XCTAssert(other.releaseDate == tag.releaseDate)
XCTAssert(other.trackNumber == tag.trackNumber)
XCTAssert(other.discNumber == tag.discNumber)
XCTAssert(other.coverArt == tag.coverArt)
XCTAssert(other.copyrights == tag.copyrights)
XCTAssert(other.comments == tag.comments)
XCTAssert(other.lyrics == tag.lyrics)
guard let otherFrameSet1 = other[ID3v2FrameID.tcom] else {
return XCTFail()
}
guard let otherFrameSet2 = other[ID3v2FrameID.tpub] else {
return XCTFail()
}
let otherExtraStuff1 = otherFrameSet1.mainFrame.stuff(format: ID3v2TextInformationFormat.regular)
let otherExtraStuff2 = otherFrameSet2.mainFrame.stuff(format: ID3v2TextInformationFormat.regular)
XCTAssert(otherExtraStuff1.timeValue == TagTime(hour: 12, minute: 34))
XCTAssert(otherExtraStuff2.dateValue == TagDate(year: 1998, month: 12, day: 31))
XCTAssert(other.frameSetList.count == tag.frameSetList.count - 3)
}
func testVersion4CaseB() {
let tag = ID3v2Tag(version: ID3v2Version.v4)
tag.revision = 123
tag.experimentalIndicator = true
tag.footerPresent = false
tag.fillingLength = 0
XCTAssert(tag.isEmpty && (tag.toData() == nil))
tag.title = "Title"
tag.artists = ["Artist 1", "Artist 2"]
tag.album = "Album"
tag.genres = ["Genre 1", "Genre 2", "Genre 3"]
tag.releaseDate = TagDate(year: 1998, month: 12, day: 31, time: TagTime(hour: 12, minute: 34, second: 56))
tag.trackNumber = TagNumber(3, total: 4)
tag.discNumber = TagNumber(1, total: 2)
tag.coverArt = TagImage(data: [1, 2, 3], mainMimeType: "image/jpeg", description: "Cover art")
tag.copyrights = ["Copyright"]
tag.comments = ["Comment 1", "Comment 2", "Comment 3", "Comment 4"]
tag.lyrics = TagLyrics(pieces: [TagLyrics.Piece("Lyrics piece 1", timeStamp: 1230),
TagLyrics.Piece("Lyrics piece 2", timeStamp: 4560)])
let extraFrameSet1 = tag.appendFrameSet(ID3v2FrameID.tcom)
let extraFrameSet2 = tag.appendFrameSet(ID3v2FrameID.tpub)
let extraStuff1 = extraFrameSet1.mainFrame.imposeStuff(format: ID3v2TextInformationFormat.regular)
let extraStuff2 = extraFrameSet2.mainFrame.imposeStuff(format: ID3v2TextInformationFormat.regular)
extraStuff1.timeValue = TagTime(hour: 12, minute: 34, second: 56)
extraStuff2.dateValue = TagDate(year: 1998, month: 12, day: 31)
XCTAssert(!tag.isEmpty)
guard let data = tag.toData() else {
return XCTFail()
}
XCTAssert(!data.isEmpty)
let prefixData = Array<UInt8>(repeating: 123, count: 123)
let suffixData = Array<UInt8>(repeating: 231, count: 231)
var range = Range<UInt64>(123..<(354 + UInt64(data.count)))
guard let other = ID3v2Tag(fromData: prefixData + data + suffixData, range: &range) else {
return XCTFail()
}
XCTAssert(range.lowerBound == 123)
XCTAssert(range.upperBound == 123 + UInt64(data.count))
XCTAssert(!other.isEmpty)
XCTAssert(other.version == tag.version)
XCTAssert(other.revision == tag.revision)
XCTAssert(other.experimentalIndicator == tag.experimentalIndicator)
XCTAssert(other.footerPresent == tag.footerPresent)
XCTAssert(other.fillingLength == tag.fillingLength)
XCTAssert(other.title == tag.title)
XCTAssert(other.artists == tag.artists)
XCTAssert(other.album == tag.album)
XCTAssert(other.genres == tag.genres)
XCTAssert(other.releaseDate == tag.releaseDate)
XCTAssert(other.trackNumber == tag.trackNumber)
XCTAssert(other.discNumber == tag.discNumber)
XCTAssert(other.coverArt == tag.coverArt)
XCTAssert(other.copyrights == tag.copyrights)
XCTAssert(other.comments == tag.comments)
XCTAssert(other.lyrics == tag.lyrics)
guard let otherFrameSet1 = other[ID3v2FrameID.tcom] else {
return XCTFail()
}
guard let otherFrameSet2 = other[ID3v2FrameID.tpub] else {
return XCTFail()
}
let otherExtraStuff1 = otherFrameSet1.mainFrame.stuff(format: ID3v2TextInformationFormat.regular)
let otherExtraStuff2 = otherFrameSet2.mainFrame.stuff(format: ID3v2TextInformationFormat.regular)
XCTAssert(otherExtraStuff1.timeValue == TagTime(hour: 12, minute: 34))
XCTAssert(otherExtraStuff2.dateValue == TagDate(year: 1998, month: 12, day: 31))
XCTAssert(other.frameSetList.count == tag.frameSetList.count - 3)
}
func testVersion4CaseC() {
let tag = ID3v2Tag(version: ID3v2Version.v4)
tag.revision = 0
tag.experimentalIndicator = false
tag.footerPresent = false
tag.fillingLength = 123456
XCTAssert(tag.isEmpty && (tag.toData() == nil))
tag.title = "Title"
tag.artists = ["Artist 1", "Artist 2"]
tag.album = "Album"
tag.genres = ["Genre 1", "Genre 2", "Genre 3"]
tag.releaseDate = TagDate(year: 1998, month: 12, day: 31, time: TagTime(hour: 12, minute: 34, second: 56))
tag.trackNumber = TagNumber(3, total: 4)
tag.discNumber = TagNumber(1, total: 2)
tag.coverArt = TagImage(data: [1, 2, 3], mainMimeType: "image/gif", description: "Cover art")
tag.copyrights = ["Copyright"]
tag.comments = ["Comment 1", "Comment 2", "Comment 3", "Comment 4"]
tag.lyrics = TagLyrics(pieces: [TagLyrics.Piece("Lyrics piece 1", timeStamp: 1230),
TagLyrics.Piece("Lyrics piece 2", timeStamp: 4560)])
let extraFrameSet1 = tag.appendFrameSet(ID3v2FrameID.tcom)
let extraFrameSet2 = tag.appendFrameSet(ID3v2FrameID.tpub)
let extraStuff1 = extraFrameSet1.mainFrame.imposeStuff(format: ID3v2TextInformationFormat.regular)
let extraStuff2 = extraFrameSet2.mainFrame.imposeStuff(format: ID3v2TextInformationFormat.regular)
extraStuff1.timeValue = TagTime(hour: 12, minute: 34, second: 56)
extraStuff2.dateValue = TagDate(year: 1998, month: 12, day: 31)
XCTAssert(!tag.isEmpty)
guard let data = tag.toData() else {
return XCTFail()
}
XCTAssert(data.count == tag.fillingLength)
var range = Range<UInt64>(0..<UInt64(data.count))
guard let other = ID3v2Tag(fromData: data, range: &range) else {
return XCTFail()
}
XCTAssert(range.lowerBound == 0)
XCTAssert(range.upperBound == UInt64(data.count))
XCTAssert(!other.isEmpty)
XCTAssert(other.version == tag.version)
XCTAssert(other.revision == tag.revision)
XCTAssert(other.experimentalIndicator == tag.experimentalIndicator)
XCTAssert(other.footerPresent == tag.footerPresent)
XCTAssert(other.fillingLength == tag.fillingLength)
XCTAssert(other.title == tag.title)
XCTAssert(other.artists == tag.artists)
XCTAssert(other.album == tag.album)
XCTAssert(other.genres == tag.genres)
XCTAssert(other.releaseDate == tag.releaseDate)
XCTAssert(other.trackNumber == tag.trackNumber)
XCTAssert(other.discNumber == tag.discNumber)
XCTAssert(other.coverArt == tag.coverArt)
XCTAssert(other.copyrights == tag.copyrights)
XCTAssert(other.comments == tag.comments)
XCTAssert(other.lyrics == tag.lyrics)
guard let otherFrameSet1 = other[ID3v2FrameID.tcom] else {
return XCTFail()
}
guard let otherFrameSet2 = other[ID3v2FrameID.tpub] else {
return XCTFail()
}
let otherExtraStuff1 = otherFrameSet1.mainFrame.stuff(format: ID3v2TextInformationFormat.regular)
let otherExtraStuff2 = otherFrameSet2.mainFrame.stuff(format: ID3v2TextInformationFormat.regular)
XCTAssert(otherExtraStuff1.timeValue == TagTime(hour: 12, minute: 34))
XCTAssert(otherExtraStuff2.dateValue == TagDate(year: 1998, month: 12, day: 31))
XCTAssert(other.frameSetList.count == tag.frameSetList.count - 3)
}
// MARK:
func testFrameLengthV4File() {
guard let filePath = Bundle(for: type(of: self)).url(forResource: "frame_length_v4", withExtension: "id3") else {
return XCTFail()
}
guard let data = try? Data(contentsOf: filePath) else {
return XCTFail()
}
guard let tag = ID3v2Tag(fromData: [UInt8](data)) else {
return XCTFail()
}
XCTAssert(!tag.isEmpty)
XCTAssert(tag.version == ID3v2Version.v4)
XCTAssert(tag.revision == 0)
XCTAssert(tag.experimentalIndicator == false)
XCTAssert(tag.footerPresent == false)
XCTAssert(tag.fillingLength == 38402)
XCTAssert(tag.frameSetList.count == 9)
XCTAssert(tag.title == "Sunshine Superman")
XCTAssert(tag.artists == ["Donovan"])
XCTAssert(tag.album == "Sunshine Superman")
XCTAssert(tag.genres == ["Folk"])
XCTAssert(tag.releaseDate == TagDate(year: 1966))
XCTAssert(tag.trackNumber == TagNumber(1))
XCTAssert(tag.discNumber == TagNumber())
XCTAssert(!tag.coverArt.isEmpty)
XCTAssert(tag.copyrights == [])
XCTAssert(tag.comments == [])
XCTAssert(tag.lyrics == TagLyrics())
guard let otherFrameSet = tag[ID3v2FrameID.wcom] else {
return XCTFail()
}
XCTAssert(!otherFrameSet.mainFrame.stuff(format: ID3v2URLLinkFormat.regular).isEmpty)
}
func testUnsynchronisedFile() {
guard let filePath = Bundle(for: type(of: self)).url(forResource: "unsynchronised", withExtension: "id3") else {
return XCTFail()
}
guard let data = try? Data(contentsOf: filePath) else {
return XCTFail()
}
guard let tag = ID3v2Tag(fromData: [UInt8](data)) else {
return XCTFail()
}
XCTAssert(!tag.isEmpty)
XCTAssert(tag.version == ID3v2Version.v3)
XCTAssert(tag.revision == 0)
XCTAssert(tag.experimentalIndicator == false)
XCTAssert(tag.footerPresent == false)
XCTAssert(tag.fillingLength == 0)
XCTAssert(tag.frameSetList.count == 5)
XCTAssert(tag.title == "My babe just cares for me")
XCTAssert(tag.artists == ["Nina Simone"])
XCTAssert(tag.album == "100% Jazz")
XCTAssert(tag.genres == [])
XCTAssert(tag.releaseDate == TagDate())
XCTAssert(tag.trackNumber == TagNumber(3))
XCTAssert(tag.discNumber == TagNumber())
XCTAssert(tag.coverArt.isEmpty)
XCTAssert(tag.copyrights == [])
XCTAssert(tag.comments == [])
XCTAssert(tag.lyrics == TagLyrics())
guard let otherFrameSet = tag[ID3v2FrameID.tlen] else {
return XCTFail()
}
XCTAssert(!otherFrameSet.mainFrame.stuff(format: ID3v2TextInformationFormat.regular).isEmpty)
}
func testBrokenFrameFile() {
guard let filePath = Bundle(for: type(of: self)).url(forResource: "broken_frame", withExtension: "id3") else {
return XCTFail()
}
guard let data = try? Data(contentsOf: filePath) else {
return XCTFail()
}
guard let tag = ID3v2Tag(fromData: [UInt8](data)) else {
return XCTFail()
}
XCTAssert(tag.isEmpty)
XCTAssert(tag.version == ID3v2Version.v4)
XCTAssert(tag.revision == 0)
XCTAssert(tag.experimentalIndicator == false)
XCTAssert(tag.footerPresent == false)
XCTAssert(tag.fillingLength == 280)
XCTAssert(tag.frameSetList.isEmpty)
XCTAssert(tag.title == "")
XCTAssert(tag.artists == [])
XCTAssert(tag.album == "")
XCTAssert(tag.genres == [])
XCTAssert(tag.releaseDate == TagDate())
XCTAssert(tag.trackNumber == TagNumber())
XCTAssert(tag.discNumber == TagNumber())
XCTAssert(tag.coverArt.isEmpty)
XCTAssert(tag.copyrights == [])
XCTAssert(tag.comments == [])
XCTAssert(tag.lyrics == TagLyrics())
}
}
| mit | ff8e9cbe532e65bcf8b0eb5ce7b24f03 | 33.003799 | 121 | 0.638741 | 3.914363 | false | false | false | false |
nadejdanicolova/ios-project | Wallpapers/Pods/LIHAlert/Pod/Classes/LIHAlertManager.swift | 1 | 7028 | //
// LIHAlertManager.swift
// LIHAlert
//
// Created by Lasith Hettiarachchi on 10/15/15.
// Copyright © 2015 Lasith Hettiarachchi. All rights reserved.
//
import Foundation
import UIKit
@objc open class LIHAlertManager: NSObject {
open static func getTextAlert(message: String) -> LIHAlert {
let alertTextAlert: LIHAlert = LIHAlert()
alertTextAlert.alertType = LIHAlertType.text
alertTextAlert.contentText = message
alertTextAlert.alertColor = UIColor(red: 102.0/255.0, green: 197.0/255.0, blue: 241.0/255.0, alpha: 1.0)
alertTextAlert.alertHeight = 50.0
alertTextAlert.alertAlpha = 1.0
alertTextAlert.autoCloseEnabled=true
alertTextAlert.contentTextColor = UIColor.white
alertTextAlert.hasNavigationBar = true
alertTextAlert.paddingTop = 0.0
alertTextAlert.animationDuration = 0.35
alertTextAlert.autoCloseTimeInterval = 1.5
return alertTextAlert
}
open static func getTextWithTitleAlert(title: String, message:String) -> LIHAlert {
let alertTextAlert: LIHAlert = LIHAlert()
alertTextAlert.alertType = LIHAlertType.textWithTitle
alertTextAlert.contentText = message
alertTextAlert.titleText = title
alertTextAlert.contentTextFont = UIFont.systemFont(ofSize: 15)
alertTextAlert.alertColor = UIColor.orange
alertTextAlert.alertHeight = 85.0
alertTextAlert.alertAlpha = 1.0
alertTextAlert.autoCloseEnabled=true
alertTextAlert.contentTextColor = UIColor.white
alertTextAlert.titleTextColor = UIColor.white
alertTextAlert.hasNavigationBar = true
alertTextAlert.paddingTop = 0.0
alertTextAlert.animationDuration = 0.35
alertTextAlert.autoCloseTimeInterval = 2.5
return alertTextAlert
}
open static func getProcessingAlert(message: String) -> LIHAlert {
let processingAlert: LIHAlert = LIHAlert()
processingAlert.alertType = LIHAlertType.textWithLoading
processingAlert.contentText = message
processingAlert.alertColor = UIColor.gray
processingAlert.alertHeight = 50.0
processingAlert.alertAlpha = 1.0
processingAlert.autoCloseEnabled=false
processingAlert.contentTextColor = UIColor.white
processingAlert.hasNavigationBar = true
processingAlert.paddingTop = 0.0
processingAlert.animationDuration = 0.35
processingAlert.autoCloseTimeInterval = 2.5
return processingAlert
}
open static func getCustomViewAlert(customView: UIView) -> LIHAlert {
let customViewAlert: LIHAlert = LIHAlert()
customViewAlert.alertType = LIHAlertType.custom
customViewAlert.alertView = customView
customViewAlert.autoCloseEnabled=true
customViewAlert.hasNavigationBar = true
customViewAlert.animationDuration = 0.35
customViewAlert.autoCloseTimeInterval = 2.5
return customViewAlert
}
open static func getSuccessAlert(message: String) -> LIHAlert {
let successAlert: LIHAlert = LIHAlert()
successAlert.alertType = LIHAlertType.textWithIcon
successAlert.icon = UIImage(named: "SuccessIcon")
successAlert.contentText = message
successAlert.alertColor = UIColor(red: 17.0/255.0, green: 201.0/255.0, blue: 3.0/255.0, alpha: 1.0)
successAlert.alertHeight = 70.0
successAlert.alertAlpha = 1.0
successAlert.autoCloseEnabled=true
successAlert.contentTextColor = UIColor.white
successAlert.hasNavigationBar = true
successAlert.paddingTop = 0.0
successAlert.animationDuration = 0.35
successAlert.autoCloseTimeInterval = 2.5
return successAlert
}
open static func getErrorAlert(message: String) -> LIHAlert {
let errorAlert: LIHAlert = LIHAlert()
errorAlert.alertType = LIHAlertType.textWithIcon
errorAlert.icon = UIImage(named: "ErrorIcon")
errorAlert.contentText = message
errorAlert.alertColor = UIColor(red: 201.0/255.0, green: 3.0/255.0, blue: 3.0/255.0, alpha: 1.0)
errorAlert.alertHeight = 70.0
errorAlert.alertAlpha = 1.0
errorAlert.autoCloseEnabled=true
errorAlert.contentTextColor = UIColor.white
errorAlert.hasNavigationBar = true
errorAlert.paddingTop = 0.0
errorAlert.animationDuration = 0.35
errorAlert.autoCloseTimeInterval = 2.5
return errorAlert
}
open static func getTextWithButtonAlert(message: String, buttonText: String) -> LIHAlert {
let textWithButtonAlert: LIHAlert = LIHAlert()
textWithButtonAlert.alertType = LIHAlertType.textWithButton
textWithButtonAlert.contentText = message
textWithButtonAlert.buttonText = buttonText
textWithButtonAlert.buttonColor = UIColor(red: 22.0/255.0, green: 40.0/255.0, blue: 114.0/255.0, alpha: 1.0)
textWithButtonAlert.buttonWidth = 620.0
textWithButtonAlert.alertColor = UIColor(red: 22.0/255.0, green: 40.0/255.0, blue: 114.0/255.0, alpha: 1.0)
textWithButtonAlert.alertHeight = 130.0
textWithButtonAlert.alertAlpha = 1.0
textWithButtonAlert.autoCloseEnabled=false
textWithButtonAlert.contentTextColor = UIColor.white
textWithButtonAlert.hasNavigationBar = true
textWithButtonAlert.paddingTop = 0.0
textWithButtonAlert.animationDuration = 0.35
textWithButtonAlert.autoCloseTimeInterval = 2.5
return textWithButtonAlert
}
open static func getTextWithTwoButtonsAlert(message: String, buttonOneText: String, buttonTwoText: String) -> LIHAlert {
let textWithButtonsAlert: LIHAlert = LIHAlert()
textWithButtonsAlert.alertType = LIHAlertType.textWithTwoButtons
textWithButtonsAlert.contentText = message
textWithButtonsAlert.alertColor = UIColor(red: 22.0/255.0, green: 40.0/255.0, blue: 114.0/255.0, alpha: 1.0)
textWithButtonsAlert.buttonOneText = buttonOneText
textWithButtonsAlert.buttonOneColor = UIColor(red: 22.0/255.0, green: 40.0/255.0, blue: 114.0/255.0, alpha: 1.0)
textWithButtonsAlert.buttonTwoText = buttonTwoText
textWithButtonsAlert.buttonTwoColor = UIColor(red: 22.0/255.0, green: 40.0/255.0, blue: 114.0/255.0, alpha: 1.0)
textWithButtonsAlert.alertHeight = 130.0
textWithButtonsAlert.alertAlpha = 1.0
textWithButtonsAlert.autoCloseEnabled=false
textWithButtonsAlert.contentTextColor = UIColor.white
textWithButtonsAlert.hasNavigationBar = true
textWithButtonsAlert.paddingTop = 0.0
textWithButtonsAlert.animationDuration = 0.35
textWithButtonsAlert.autoCloseTimeInterval = 2.5
return textWithButtonsAlert
}
}
| apache-2.0 | 13fe51d5a3e93a8e50e74bf142b7e29e | 39.854651 | 124 | 0.685072 | 4.248489 | false | false | false | false |
hooman/swift | stdlib/public/Concurrency/Task.swift | 1 | 28907 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2020 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 Swift
@_implementationOnly import _SwiftConcurrencyShims
// ==== Task -------------------------------------------------------------------
/// An asynchronous task (just "Task" hereafter) is the analogue of a thread for
/// asynchronous functions. All asynchronous functions run as part of some task.
///
/// An instance of `Task` always represents a top-level task. The instance
/// can be used to await its completion, cancel the task, etc., The task will
/// run to completion even if there are no other instances of the `Task`.
///
/// `Task` also provides appropriate context-sensitive static functions which
/// operate on the "current" task, which might either be a detached task or
/// a child task. Because all such functions are `async` they can only
/// be invoked as part of an existing task, and therefore are guaranteed to be
/// effective.
///
/// A task's execution can be seen as a series of periods where the task was
/// running. Each such period ends at a suspension point or -- finally -- the
/// completion of the task.
///
/// These partial periods towards the task's completion are
/// individually schedulable as jobs. Jobs are generally not interacted
/// with by end-users directly, unless implementing a scheduler.
@available(SwiftStdlib 5.5, *)
@frozen
public struct Task<Success: Sendable, Failure: Error>: Sendable {
@usableFromInline
internal let _task: Builtin.NativeObject
@_alwaysEmitIntoClient
internal init(_ task: Builtin.NativeObject) {
self._task = task
}
}
@available(SwiftStdlib 5.5, *)
extension Task {
/// Wait for the task to complete, returning (or throwing) its result.
///
/// ### Priority
/// If the task has not completed yet, its priority will be elevated to the
/// priority of the current task. Note that this may not be as effective as
/// creating the task with the "right" priority to in the first place.
///
/// ### Cancellation
/// If the awaited on task gets cancelled externally the `get()` will throw
/// a cancellation error.
///
/// If the task gets cancelled internally, e.g. by checking for cancellation
/// and throwing a specific error or using `checkCancellation` the error
/// thrown out of the task will be re-thrown here.
public var value: Success {
get async throws {
return try await _taskFutureGetThrowing(_task)
}
}
/// Wait for the task to complete, returning (or throwing) its result.
///
/// ### Priority
/// If the task has not completed yet, its priority will be elevated to the
/// priority of the current task. Note that this may not be as effective as
/// creating the task with the "right" priority to in the first place.
///
/// ### Cancellation
/// If the awaited on task gets cancelled externally the `get()` will throw
/// a cancellation error.
///
/// If the task gets cancelled internally, e.g. by checking for cancellation
/// and throwing a specific error or using `checkCancellation` the error
/// thrown out of the task will be re-thrown here.
/// Wait for the task to complete, returning its `Result`.
///
/// ### Priority
/// If the task has not completed yet, its priority will be elevated to the
/// priority of the current task. Note that this may not be as effective as
/// creating the task with the "right" priority to in the first place.
///
/// ### Cancellation
/// If the awaited on task gets cancelled externally the `get()` will throw
/// a cancellation error.
///
/// If the task gets cancelled internally, e.g. by checking for cancellation
/// and throwing a specific error or using `checkCancellation` the error
/// thrown out of the task will be re-thrown here.
public var result: Result<Success, Failure> {
get async {
do {
return .success(try await value)
} catch {
return .failure(error as! Failure) // as!-safe, guaranteed to be Failure
}
}
}
/// Attempt to cancel the task.
///
/// Whether this function has any effect is task-dependent.
///
/// For a task to respect cancellation it must cooperatively check for it
/// while running. Many tasks will check for cancellation before beginning
/// their "actual work", however this is not a requirement nor is it guaranteed
/// how and when tasks check for cancellation in general.
public func cancel() {
Builtin.cancelAsyncTask(_task)
}
}
@available(SwiftStdlib 5.5, *)
extension Task where Failure == Never {
/// Wait for the task to complete, returning its result.
///
/// ### Priority
/// If the task has not completed yet, its priority will be elevated to the
/// priority of the current task. Note that this may not be as effective as
/// creating the task with the "right" priority to in the first place.
///
/// ### Cancellation
/// The task this refers to may check for cancellation, however
/// since it is not-throwing it would have to handle it using some other
/// way than throwing a `CancellationError`, e.g. it could provide a neutral
/// value of the `Success` type, or encode that cancellation has occurred in
/// that type itself.
public var value: Success {
get async {
return await _taskFutureGet(_task)
}
}
}
@available(SwiftStdlib 5.5, *)
extension Task: Hashable {
public func hash(into hasher: inout Hasher) {
UnsafeRawPointer(Builtin.bridgeToRawPointer(_task)).hash(into: &hasher)
}
}
@available(SwiftStdlib 5.5, *)
extension Task: Equatable {
public static func ==(lhs: Self, rhs: Self) -> Bool {
UnsafeRawPointer(Builtin.bridgeToRawPointer(lhs._task)) ==
UnsafeRawPointer(Builtin.bridgeToRawPointer(rhs._task))
}
}
// ==== Task Priority ----------------------------------------------------------
/// Task priority may inform decisions an `Executor` makes about how and when
/// to schedule tasks submitted to it.
///
/// ### Priority scheduling
/// An executor MAY utilize priority information to attempt running higher
/// priority tasks first, and then continuing to serve lower priority tasks.
///
/// The exact semantics of how priority is treated are left up to each
/// platform and `Executor` implementation.
///
/// ### Priority inheritance
/// Child tasks automatically inherit their parent task's priority.
///
/// Detached tasks (created by `Task.detached`) DO NOT inherit task priority,
/// as they are "detached" from their parent tasks after all.
///
/// ### Priority elevation
/// In some situations the priority of a task must be elevated (or "escalated", "raised"):
///
/// - if a `Task` running on behalf of an actor, and a new higher-priority
/// task is enqueued to the actor, its current task must be temporarily
/// elevated to the priority of the enqueued task, in order to allow the new
/// task to be processed at--effectively-- the priority it was enqueued with.
/// - this DOES NOT affect `Task.currentPriority()`.
/// - if a task is created with a `Task.Handle`, and a higher-priority task
/// calls the `await handle.get()` function the priority of this task must be
/// permanently increased until the task completes.
/// - this DOES affect `Task.currentPriority()`.
///
/// TODO: Define the details of task priority; It is likely to be a concept
/// similar to Darwin Dispatch's QoS; bearing in mind that priority is not as
/// much of a thing on other platforms (i.e. server side Linux systems).
@available(SwiftStdlib 5.5, *)
public struct TaskPriority: RawRepresentable, Sendable {
public typealias RawValue = UInt8
public var rawValue: UInt8
public init(rawValue: UInt8) {
self.rawValue = rawValue
}
public static let high: TaskPriority = .init(rawValue: 0x19)
@_alwaysEmitIntoClient
public static var medium: TaskPriority {
.init(rawValue: 0x15)
}
public static let low: TaskPriority = .init(rawValue: 0x11)
public static let userInitiated: TaskPriority = high
public static let utility: TaskPriority = low
public static let background: TaskPriority = .init(rawValue: 0x09)
@available(*, deprecated, renamed: "medium")
public static let `default`: TaskPriority = .init(rawValue: 0x15)
}
@available(SwiftStdlib 5.5, *)
extension TaskPriority: Equatable {
public static func == (lhs: TaskPriority, rhs: TaskPriority) -> Bool {
lhs.rawValue == rhs.rawValue
}
public static func != (lhs: TaskPriority, rhs: TaskPriority) -> Bool {
lhs.rawValue != rhs.rawValue
}
}
@available(SwiftStdlib 5.5, *)
extension TaskPriority: Comparable {
public static func < (lhs: TaskPriority, rhs: TaskPriority) -> Bool {
lhs.rawValue < rhs.rawValue
}
public static func <= (lhs: TaskPriority, rhs: TaskPriority) -> Bool {
lhs.rawValue <= rhs.rawValue
}
public static func > (lhs: TaskPriority, rhs: TaskPriority) -> Bool {
lhs.rawValue > rhs.rawValue
}
public static func >= (lhs: TaskPriority, rhs: TaskPriority) -> Bool {
lhs.rawValue >= rhs.rawValue
}
}
@available(SwiftStdlib 5.5, *)
extension TaskPriority: Codable { }
@available(SwiftStdlib 5.5, *)
extension Task where Success == Never, Failure == Never {
/// Returns the `current` task's priority.
///
/// If no current `Task` is available, queries the system to determine the
/// priority at which the current function is running. If the system cannot
/// provide an appropriate priority, returns `Priority.default`.
///
/// - SeeAlso: `TaskPriority`
public static var currentPriority: TaskPriority {
withUnsafeCurrentTask { task in
// If we are running on behalf of a task, use that task's priority.
if let task = task {
return task.priority
}
// Otherwise, query the system.
return TaskPriority(rawValue: UInt8(_getCurrentThreadPriority()))
}
}
}
@available(SwiftStdlib 5.5, *)
extension TaskPriority {
/// Downgrade user-interactive to user-initiated.
var _downgradeUserInteractive: TaskPriority {
return self
}
}
// ==== Job Flags --------------------------------------------------------------
/// Flags for schedulable jobs.
///
/// This is a port of the C++ FlagSet.
@available(SwiftStdlib 5.5, *)
struct JobFlags {
/// Kinds of schedulable jobs.
enum Kind: Int32 {
case task = 0
}
/// The actual bit representation of these flags.
var bits: Int32 = 0
/// The kind of job described by these flags.
var kind: Kind {
get {
Kind(rawValue: bits & 0xFF)!
}
set {
bits = (bits & ~0xFF) | newValue.rawValue
}
}
/// Whether this is an asynchronous task.
var isAsyncTask: Bool { kind == .task }
/// The priority given to the job.
var priority: TaskPriority? {
get {
let value = (Int(bits) & 0xFF00) >> 8
if value == 0 {
return nil
}
return TaskPriority(rawValue: UInt8(value))
}
set {
bits = (bits & ~0xFF00) | Int32((Int(newValue?.rawValue ?? 0) << 8))
}
}
/// Whether this is a child task.
var isChildTask: Bool {
get {
(bits & (1 << 24)) != 0
}
set {
if newValue {
bits = bits | 1 << 24
} else {
bits = (bits & ~(1 << 24))
}
}
}
/// Whether this is a future.
var isFuture: Bool {
get {
(bits & (1 << 25)) != 0
}
set {
if newValue {
bits = bits | 1 << 25
} else {
bits = (bits & ~(1 << 25))
}
}
}
/// Whether this is a group child.
var isGroupChildTask: Bool {
get {
(bits & (1 << 26)) != 0
}
set {
if newValue {
bits = bits | 1 << 26
} else {
bits = (bits & ~(1 << 26))
}
}
}
/// Whether this is a task created by the 'async' operation, which
/// conceptually continues the work of the synchronous code that invokes
/// it.
var isContinuingAsyncTask: Bool {
get {
(bits & (1 << 27)) != 0
}
set {
if newValue {
bits = bits | 1 << 27
} else {
bits = (bits & ~(1 << 27))
}
}
}
}
// ==== Task Creation Flags --------------------------------------------------
/// Form task creation flags for use with the createAsyncTask builtins.
@available(SwiftStdlib 5.5, *)
@_alwaysEmitIntoClient
func taskCreateFlags(
priority: TaskPriority?, isChildTask: Bool, copyTaskLocals: Bool,
inheritContext: Bool, enqueueJob: Bool,
addPendingGroupTaskUnconditionally: Bool
) -> Int {
var bits = 0
bits |= (bits & ~0xFF) | Int(priority?.rawValue ?? 0)
if isChildTask {
bits |= 1 << 8
}
if copyTaskLocals {
bits |= 1 << 10
}
if inheritContext {
bits |= 1 << 11
}
if enqueueJob {
bits |= 1 << 12
}
if addPendingGroupTaskUnconditionally {
bits |= 1 << 13
}
return bits
}
// ==== Task Creation ----------------------------------------------------------
@available(SwiftStdlib 5.5, *)
extension Task where Failure == Never {
/// Run given `operation` as asynchronously in its own top-level task.
///
/// The `async` function should be used when creating asynchronous work
/// that operates on behalf of the synchronous function that calls it.
/// Like `Task.detached`, the async function creates a separate, top-level
/// task.
///
/// Unlike `Task.detached`, the task creating by the `Task` initializer
/// inherits the priority and actor context of the caller, so the `operation`
/// is treated more like an asynchronous extension to the synchronous
/// operation.
///
/// - Parameters:
/// - priority: priority of the task. If nil, the priority will come from
/// Task.currentPriority.
/// - operation: the operation to execute
@discardableResult
@_alwaysEmitIntoClient
public init(
priority: TaskPriority? = nil,
@_inheritActorContext @_implicitSelfCapture operation: __owned @Sendable @escaping () async -> Success
) {
#if compiler(>=5.5) && $BuiltinCreateAsyncTaskInGroup
// Set up the job flags for a new task.
let flags = taskCreateFlags(
priority: priority, isChildTask: false, copyTaskLocals: true,
inheritContext: true, enqueueJob: true,
addPendingGroupTaskUnconditionally: false)
// Create the asynchronous task.
let (task, _) = Builtin.createAsyncTask(flags, operation)
self._task = task
#else
fatalError("Unsupported Swift compiler")
#endif
}
}
@available(SwiftStdlib 5.5, *)
extension Task where Failure == Error {
/// Run given `operation` as asynchronously in its own top-level task.
///
/// This initializer creates asynchronous work on behalf of the synchronous function that calls it.
/// Like `Task.detached`, this initializer creates a separate, top-level task.
/// Unlike `Task.detached`, the task created inherits the priority and
/// actor context of the caller, so the `operation` is treated more like an
/// asynchronous extension to the synchronous operation.
///
/// - Parameters:
/// - priority: priority of the task. If nil, the priority will come from
/// Task.currentPriority.
/// - operation: the operation to execute
@discardableResult
@_alwaysEmitIntoClient
public init(
priority: TaskPriority? = nil,
@_inheritActorContext @_implicitSelfCapture operation: __owned @Sendable @escaping () async throws -> Success
) {
#if compiler(>=5.5) && $BuiltinCreateAsyncTaskInGroup
// Set up the task flags for a new task.
let flags = taskCreateFlags(
priority: priority, isChildTask: false, copyTaskLocals: true,
inheritContext: true, enqueueJob: true,
addPendingGroupTaskUnconditionally: false
)
// Create the asynchronous task future.
let (task, _) = Builtin.createAsyncTask(flags, operation)
self._task = task
#else
fatalError("Unsupported Swift compiler")
#endif
}
}
// ==== Detached Tasks ---------------------------------------------------------
@available(SwiftStdlib 5.5, *)
extension Task where Failure == Never {
/// Run given throwing `operation` as part of a new top-level task.
///
/// Creating detached tasks should, generally, be avoided in favor of using
/// `async` functions, `async let` declarations and `await` expressions - as
/// those benefit from structured, bounded concurrency which is easier to reason
/// about, as well as automatically inheriting the parent tasks priority,
/// task-local storage, deadlines, as well as being cancelled automatically
/// when their parent task is cancelled. Detached tasks do not get any of those
/// benefits, and thus should only be used when an operation is impossible to
/// be modelled with child tasks.
///
/// ### Cancellation
/// A detached task always runs to completion unless it is explicitly cancelled.
/// Specifically, dropping a detached tasks `Task` does _not_ automatically
/// cancel given task.
///
/// Cancelling a task must be performed explicitly via `cancel()`.
///
/// - Note: it is generally preferable to use child tasks rather than detached
/// tasks. Child tasks automatically carry priorities, task-local state,
/// deadlines and have other benefits resulting from the structured
/// concurrency concepts that they model. Consider using detached tasks only
/// when strictly necessary and impossible to model operations otherwise.
///
/// - Parameters:
/// - priority: priority of the task
/// - operation: the operation to execute
/// - Returns: handle to the task, allowing to `await get()` on the
/// tasks result or `cancel` it. If the operation fails the handle will
/// throw the error the operation has thrown when awaited on.
@discardableResult
@_alwaysEmitIntoClient
public static func detached(
priority: TaskPriority? = nil,
operation: __owned @Sendable @escaping () async -> Success
) -> Task<Success, Failure> {
#if compiler(>=5.5) && $BuiltinCreateAsyncTaskInGroup
// Set up the job flags for a new task.
let flags = taskCreateFlags(
priority: priority, isChildTask: false, copyTaskLocals: false,
inheritContext: false, enqueueJob: true,
addPendingGroupTaskUnconditionally: false)
// Create the asynchronous task future.
let (task, _) = Builtin.createAsyncTask(flags, operation)
return Task(task)
#else
fatalError("Unsupported Swift compiler")
#endif
}
}
@available(SwiftStdlib 5.5, *)
extension Task where Failure == Error {
/// Run given throwing `operation` as part of a new top-level task.
///
/// Creating detached tasks should, generally, be avoided in favor of using
/// `async` functions, `async let` declarations and `await` expressions - as
/// those benefit from structured, bounded concurrency which is easier to reason
/// about, as well as automatically inheriting the parent tasks priority,
/// task-local storage, deadlines, as well as being cancelled automatically
/// when their parent task is cancelled. Detached tasks do not get any of those
/// benefits, and thus should only be used when an operation is impossible to
/// be modelled with child tasks.
///
/// ### Cancellation
/// A detached task always runs to completion unless it is explicitly cancelled.
/// Specifically, dropping a detached tasks `Task.Handle` does _not_ automatically
/// cancel given task.
///
/// Cancelling a task must be performed explicitly via `handle.cancel()`.
///
/// - Note: it is generally preferable to use child tasks rather than detached
/// tasks. Child tasks automatically carry priorities, task-local state,
/// deadlines and have other benefits resulting from the structured
/// concurrency concepts that they model. Consider using detached tasks only
/// when strictly necessary and impossible to model operations otherwise.
///
/// - Parameters:
/// - priority: priority of the task
/// - executor: the executor on which the detached closure should start
/// executing on.
/// - operation: the operation to execute
/// - Returns: handle to the task, allowing to `await handle.get()` on the
/// tasks result or `cancel` it. If the operation fails the handle will
/// throw the error the operation has thrown when awaited on.
@discardableResult
@_alwaysEmitIntoClient
public static func detached(
priority: TaskPriority? = nil,
operation: __owned @Sendable @escaping () async throws -> Success
) -> Task<Success, Failure> {
#if compiler(>=5.5) && $BuiltinCreateAsyncTaskInGroup
// Set up the job flags for a new task.
let flags = taskCreateFlags(
priority: priority, isChildTask: false, copyTaskLocals: false,
inheritContext: false, enqueueJob: true,
addPendingGroupTaskUnconditionally: false
)
// Create the asynchronous task future.
let (task, _) = Builtin.createAsyncTask(flags, operation)
return Task(task)
#else
fatalError("Unsupported Swift compiler")
#endif
}
}
// ==== Voluntary Suspension -----------------------------------------------------
@available(SwiftStdlib 5.5, *)
extension Task where Success == Never, Failure == Never {
/// Explicitly suspend the current task, potentially giving up execution actor
/// of current actor/task, allowing other tasks to execute.
///
/// This is not a perfect cure for starvation;
/// if the task is the highest-priority task in the system, it might go
/// immediately back to executing.
///
/// If this task is the highest-priority task in the system,
/// the executor immediately resumes execution of the same task.
/// As such,
/// this method isn't necessarily a way to avoid resource starvation.
public static func yield() async {
return await Builtin.withUnsafeContinuation { (continuation: Builtin.RawUnsafeContinuation) -> Void in
let job = _taskCreateNullaryContinuationJob(
priority: Int(Task.currentPriority.rawValue),
continuation: continuation)
_enqueueJobGlobal(job)
}
}
}
// ==== UnsafeCurrentTask ------------------------------------------------------
/// Calls the given closure with the with the "current" task in which this
/// function was invoked.
///
/// If invoked from an asynchronous function the task will always be non-nil,
/// as an asynchronous function is always running within some task.
/// However if invoked from a synchronous function the task may be nil,
/// meaning that the function is not executing within a task, i.e. there is no
/// asynchronous context available in the call stack.
///
/// It is generally not safe to escape/store the `UnsafeCurrentTask` for future
/// use, as some operations on it may only be performed from the same task
/// that it is representing.
///
/// It is possible to obtain a `Task` fom the `UnsafeCurrentTask` which is safe
/// to access from other tasks or even store for future reference e.g. equality
/// checks.
@available(SwiftStdlib 5.5, *)
public func withUnsafeCurrentTask<T>(body: (UnsafeCurrentTask?) throws -> T) rethrows -> T {
guard let _task = _getCurrentAsyncTask() else {
return try body(nil)
}
// FIXME: This retain seems pretty wrong, however if we don't we WILL crash
// with "destroying a task that never completed" in the task's destroy.
// How do we solve this properly?
Builtin.retain(_task)
return try body(UnsafeCurrentTask(_task))
}
/// An *unsafe* 'current' task handle.
///
/// An `UnsafeCurrentTask` should not be stored for "later" access.
///
/// Storing an `UnsafeCurrentTask` has no implication on the task's actual lifecycle.
///
/// The sub-set of APIs of `UnsafeCurrentTask` which also exist on `Task` are
/// generally safe to be invoked from any task/thread.
///
/// All other APIs must not, be called 'from' any other task than the one
/// represented by this handle itself. Doing so may result in undefined behavior,
/// and most certainly will break invariants in other places of the program
/// actively running on this task.
@available(SwiftStdlib 5.5, *)
public struct UnsafeCurrentTask {
internal let _task: Builtin.NativeObject
// May only be created by the standard library.
internal init(_ task: Builtin.NativeObject) {
self._task = task
}
/// Returns `true` if the task is cancelled, and should stop executing.
///
/// - SeeAlso: `checkCancellation()`
public var isCancelled: Bool {
_taskIsCancelled(_task)
}
/// Returns the `current` task's priority.
///
/// - SeeAlso: `TaskPriority`
/// - SeeAlso: `Task.currentPriority`
public var priority: TaskPriority {
getJobFlags(_task).priority ?? TaskPriority(
rawValue: UInt8(_getCurrentThreadPriority()))
}
/// Cancel the current task.
public func cancel() {
_taskCancel(_task)
}
}
@available(SwiftStdlib 5.5, *)
extension UnsafeCurrentTask: Hashable {
public func hash(into hasher: inout Hasher) {
UnsafeRawPointer(Builtin.bridgeToRawPointer(_task)).hash(into: &hasher)
}
}
@available(SwiftStdlib 5.5, *)
extension UnsafeCurrentTask: Equatable {
public static func ==(lhs: Self, rhs: Self) -> Bool {
UnsafeRawPointer(Builtin.bridgeToRawPointer(lhs._task)) ==
UnsafeRawPointer(Builtin.bridgeToRawPointer(rhs._task))
}
}
// ==== Internal ---------------------------------------------------------------
@available(SwiftStdlib 5.5, *)
@_silgen_name("swift_task_getCurrent")
func _getCurrentAsyncTask() -> Builtin.NativeObject?
@available(SwiftStdlib 5.5, *)
@_silgen_name("swift_task_getJobFlags")
func getJobFlags(_ task: Builtin.NativeObject) -> JobFlags
@available(SwiftStdlib 5.5, *)
@_silgen_name("swift_task_enqueueGlobal")
@usableFromInline
func _enqueueJobGlobal(_ task: Builtin.Job)
@available(SwiftStdlib 5.5, *)
@_silgen_name("swift_task_enqueueGlobalWithDelay")
@usableFromInline
func _enqueueJobGlobalWithDelay(_ delay: UInt64, _ task: Builtin.Job)
@available(SwiftStdlib 5.5, *)
@_silgen_name("swift_task_asyncMainDrainQueue")
public func _asyncMainDrainQueue() -> Never
@available(SwiftStdlib 5.5, *)
public func _runAsyncMain(@_unsafeSendable _ asyncFun: @escaping () async throws -> ()) {
Task.detached {
do {
#if !os(Windows)
#if compiler(>=5.5) && $BuiltinHopToActor
Builtin.hopToActor(MainActor.shared)
#else
fatalError("Swift compiler is incompatible with this SDK version")
#endif
#endif
try await asyncFun()
exit(0)
} catch {
_errorInMain(error)
}
}
_asyncMainDrainQueue()
}
// FIXME: both of these ought to take their arguments _owned so that
// we can do a move out of the future in the common case where it's
// unreferenced
@available(SwiftStdlib 5.5, *)
@_silgen_name("swift_task_future_wait")
public func _taskFutureGet<T>(_ task: Builtin.NativeObject) async -> T
@available(SwiftStdlib 5.5, *)
@_silgen_name("swift_task_future_wait_throwing")
public func _taskFutureGetThrowing<T>(_ task: Builtin.NativeObject) async throws -> T
@available(SwiftStdlib 5.5, *)
@_silgen_name("swift_task_cancel")
func _taskCancel(_ task: Builtin.NativeObject)
@available(SwiftStdlib 5.5, *)
@_silgen_name("swift_task_isCancelled")
func _taskIsCancelled(_ task: Builtin.NativeObject) -> Bool
@available(SwiftStdlib 5.5, *)
@_silgen_name("swift_task_createNullaryContinuationJob")
func _taskCreateNullaryContinuationJob(priority: Int, continuation: Builtin.RawUnsafeContinuation) -> Builtin.Job
@available(SwiftStdlib 5.5, *)
@usableFromInline
@_silgen_name("swift_task_isCurrentExecutor")
func _taskIsCurrentExecutor(_ executor: Builtin.Executor) -> Bool
@available(SwiftStdlib 5.5, *)
@usableFromInline
@_silgen_name("swift_task_reportUnexpectedExecutor")
func _reportUnexpectedExecutor(_ _filenameStart: Builtin.RawPointer,
_ _filenameLength: Builtin.Word,
_ _filenameIsASCII: Builtin.Int1,
_ _line: Builtin.Word,
_ _executor: Builtin.Executor)
@available(SwiftStdlib 5.5, *)
@_silgen_name("swift_task_getCurrentThreadPriority")
func _getCurrentThreadPriority() -> Int
#if _runtime(_ObjC)
/// Intrinsic used by SILGen to launch a task for bridging a Swift async method
/// which was called through its ObjC-exported completion-handler-based API.
@available(SwiftStdlib 5.5, *)
@_alwaysEmitIntoClient
@usableFromInline
internal func _runTaskForBridgedAsyncMethod(@_inheritActorContext _ body: __owned @Sendable @escaping () async -> Void) {
Task(operation: body)
}
#endif
| apache-2.0 | 6d587ee9f62242d7ac01bd303aa49227 | 33.827711 | 121 | 0.670945 | 4.339739 | false | false | false | false |
lorentey/swift | test/DebugInfo/generic_arg5.swift | 25 | 1315 | // RUN: %target-swift-frontend %s -emit-ir -g -o - | %FileCheck %s
public struct S<Type>
{
let value : Type
}
public func foo<Type>(_ values : [S<Type>])
{
// CHECK: define {{.*}}$s12generic_arg53fooyySayAA1SVyxGGlFAESgAEXEfU_
// CHECK: call void @llvm.dbg.declare
// CHECK: call void @llvm.dbg.declare(metadata %[[TY:.*]]** %[[ALLOCA:[^,]+]],
// CHECK-SAME: metadata ![[ARG:[0-9]+]],
// CHECK-SAME: metadata !DIExpression(DW_OP_deref))
// CHECK: store %[[TY]]* %1, %[[TY]]** %[[ALLOCA]], align
// CHECK: ![[TYP:[0-9]+]] = !DICompositeType({{.*}}, identifier: "$s12generic_arg51SVyxGD")
// The argument is a by-ref struct and thus needs to be dereferenced.
// CHECK: ![[ARG]] = !DILocalVariable(name: "arg", arg: 1,
// CHECK-SAME: line: [[@LINE+7]],
// CHECK-SAME: type: ![[LET_TYP:[0-9]+]])
// CHECK: ![[LET_TYP]] = !DIDerivedType(tag: DW_TAG_const_type,
// CHECK-SAME: baseType: ![[TYP_CONTAINER:[0-9]+]])
// CHECK: ![[TYP_CONTAINER]] = !DICompositeType({{.*}}elements: ![[TYP_ELTS:[0-9]+]]
// CHECK: ![[TYP_ELTS]] = !{![[TYP_MEMBER:[0-9]+]]}
// CHECK: ![[TYP_MEMBER]] = !DIDerivedType(tag: DW_TAG_member, {{.*}}baseType: ![[TYP]]
let _ = values.flatMap { arg in
return .some(arg)
}
}
| apache-2.0 | e08b5a2b4b66ac92045f0f92314406fe | 44.344828 | 93 | 0.548289 | 3.199513 | false | false | false | false |
xivol/MCS-V3-Mobile | examples/persistence/notes-archive/notes-archive/Note.swift | 1 | 1797 | //
// Note.swift
// notes-archive
//
// Created by Илья Лошкарёв on 18.03.17.
// Copyright © 2017 Илья Лошкарёв. All rights reserved.
//
import Foundation
import UIKit
class Note: NSObject, NSCoding {
let content: String
let date: Date
let color: UIColor
init(content: String, date: Date = Date(), color: UIColor = UIColor.random) {
self.content = content
self.date = date
self.color = color
}
// MARK: NSCoding
enum CodingKeys: String {
case content, date, color
}
required convenience init?(coder aDecoder: NSCoder) {
guard
let content = aDecoder.decodeObject(forKey: CodingKeys.content.rawValue) as? String,
let date = aDecoder.decodeObject(forKey: CodingKeys.date.rawValue) as? Date
else {
return nil
}
if let color = aDecoder.decodeObject(forKey: CodingKeys.color.rawValue) as? UIColor {
self.init(content: content, date: date, color: color)
} else {
self.init(content: content, date: date)
}
}
func encode(with aCoder: NSCoder) {
aCoder.encode(content, forKey: CodingKeys.content.rawValue)
aCoder.encode(date, forKey: CodingKeys.date.rawValue)
aCoder.encode(color, forKey: CodingKeys.color.rawValue)
}
// MARK: String Convertable
static let dateFormatter: DateFormatter = {
let df = DateFormatter()
df.dateFormat = "hh:mm:ss dd.MM.yyyy"
return df
}()
override var description: String {
return "(\(Note.dateFormatter.string(from: date))) \n" + content
}
}
//@available(*, unavailable, renamed: "Note4Codable")
//typealias Note = Note4Codable
| mit | 50e474c4e2c21978c1dcab084237baca | 26.261538 | 96 | 0.610045 | 4.353808 | false | false | false | false |
ArnavChawla/InteliChat | CodedayProject/AppDelegate.swift | 1 | 11922 | import UIKit
import GoogleSignIn
import UserNotifications
import Firebase
import FirebaseInstanceID
import FirebaseMessaging
import FBSDKCoreKit
import FacebookCore
import FacebookLogin
import FBSDKCoreKit
var s = false
var p = false
var se = false
var os = false
var ip1 = false
var ipb = false
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let gcmMessageIDKey = "gcm.message_id"
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
print(url)
return GIDSignIn.sharedInstance().handle(url, sourceApplication: options[UIApplicationOpenURLOptionsKey.sourceApplication] as? String, annotation: options[UIApplicationOpenURLOptionsKey.annotation])
}
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
return FBSDKApplicationDelegate.sharedInstance().application(application, open: url, sourceApplication: sourceApplication, annotation: annotation)
}
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Register for remote notifications. This shows a permission dialog on first run, to
// show the dialog at a more appropriate time move this registration accordingly.
// [START register_for_notifications]
if #available(iOS 10.0, *) {
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
UNUserNotificationCenter.current().requestAuthorization(
options: authOptions,
completionHandler: {_, _ in })
// For iOS 10 display notification (sent via APNS)
UNUserNotificationCenter.current().delegate = self
// For iOS 10 data message (sent via FCM)
FIRMessaging.messaging().remoteMessageDelegate = self
} else {
let settings: UIUserNotificationSettings =
UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
}
application.registerForRemoteNotifications()
// [END register_for_notifications]
FIRApp.configure()
// [START add_token_refresh_observer]
// Add observer for InstanceID token refresh callback.
NotificationCenter.default.addObserver(self,
selector: #selector(self.tokenRefreshNotification),
name: .firInstanceIDTokenRefresh,
object: nil)
// [END add_token_refresh_observer]
let settings : UIUserNotificationSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
application.registerUserNotificationSettings(settings)
let storyboard: UIStoryboard = self.grabStoryboard()
// display storyboard
self.window!.rootViewController = storyboard.instantiateInitialViewController()
self.window!.makeKeyAndVisible()
return true
}
func grabStoryboard() -> UIStoryboard {
// determine screen size
let screenHeight: CGFloat = UIScreen.main.bounds.size.height
var storyboard: UIStoryboard
switch screenHeight {
// iPhone 4s
case 480:
storyboard = UIStoryboard(name: "4s", bundle: nil)
os = true
// iPhone 5s
case 568:
storyboard = UIStoryboard(name: "se", bundle: nil)
se = true
// iPhone 6
case 667:
storyboard = UIStoryboard(name: "Main", bundle: nil)
s = true
// iPhone 6 Plus
case 736:
storyboard = UIStoryboard(name: "big", bundle: nil)
p = true
case 2048:
storyboard = UIStoryboard(name: "ipad1", bundle: nil)
ip1 = false
case 2732:
storyboard = UIStoryboard(name: "ipadbig", bundle: nil)
ipb = true
default:
// it's an iPad
storyboard = UIStoryboard(name: "Main", bundle: nil)
}
return storyboard
}
// [START receive_message]
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
// If you are receiving a notification message while your app is in the background,
// this callback will not be fired till the user taps on the notification launching the application.
// TODO: Handle data of notification
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
}
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 invalidate graphics rendering callbacks. Games should use this method to pause the game.
FBSDKAppEvents.activateApp()
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
// If you are receiving a notification message while your app is in the background,
// this callback will not be fired till the user taps on the notification launching the application.
// TODO: Handle data of notification
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
completionHandler(UIBackgroundFetchResult.newData)
}
// [END receive_message]
// [START refresh_token]
func tokenRefreshNotification(_ notification: Notification) {
if let refreshedToken = FIRInstanceID.instanceID().token() {
print("InstanceID token: \(refreshedToken)")
}
// Connect to FCM since connection may have failed when attempted before having a token.
connectToFcm()
}
// [END refresh_token]
// [START connect_to_fcm]
func connectToFcm() {
// Won't connect since there is no token
guard FIRInstanceID.instanceID().token() != nil else {
return;
}
// Disconnect previous FCM connection if it exists.
FIRMessaging.messaging().disconnect()
FIRMessaging.messaging().connect { (error) in
if error != nil {
print("Unable to connect with FCM. \(error)")
} else {
print("Connected to FCM.")
}
}
}
// [END connect_to_fcm]
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Unable to register for remote notifications: \(error.localizedDescription)")
}
// This function is added here only for debugging purposes, and can be removed if swizzling is enabled.
// If swizzling is disabled then this function must be implemented so that the APNs token can be paired to
// the InstanceID token.
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
print("APNs token retrieved: \(deviceToken)")
// With swizzling disabled you must set the APNs token here.
// FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.sandbox)
}
// [START connect_on_active]
func applicationDidBecomeActive(_ application: UIApplication) {
connectToFcm()
}
// [END connect_on_active]
// [START disconnect_from_fcm]
func applicationDidEnterBackground(_ application: UIApplication) {
let priority = DispatchQueue.GlobalQueuePriority.default
DispatchQueue.global(priority: priority).async(execute: {
var databaseRef = FIRDatabase.database().reference()
let uid = FIRAuth.auth()?.currentUser?.uid
databaseRef.child("posts").child(uid!).queryLimited(toLast: 1).observe(.childAdded, with: {
snapshot in
var username = ""
var bodyText = ""
if let dict = snapshot.value as? [String: AnyObject]
{
let mediaType = dict["MediaType"] as! String
let senderId = dict["senderId"] as! String
let senderName = dict["senderName"] as! String
username = senderName
let t = dict["text"] as! String
bodyText = t
}
DispatchQueue.main.async(execute: {
let notification = UILocalNotification()
notification.alertTitle = username
notification.alertBody = bodyText
notification.alertAction = "open"
notification.soundName = UILocalNotificationDefaultSoundName
notification.fireDate = Date(timeIntervalSinceNow: 0)
UIApplication.shared.scheduleLocalNotification(notification)
})
})
})
FIRMessaging.messaging().disconnect()
print("Disconnected from FCM.")
}
// [END disconnect_from_fcm]
}
// [START ios_10_message_handling]
@available(iOS 10, *)
extension AppDelegate : UNUserNotificationCenterDelegate {
// Receive displayed notifications for iOS 10 devices.
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
let userInfo = notification.request.content.userInfo
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
// Change this to your preferred presentation option
completionHandler([])
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
completionHandler()
}
}
// [END ios_10_message_handling]
// [START ios_10_data_message_handling]
extension AppDelegate : FIRMessagingDelegate {
// Receive data message on iOS 10 devices while app is in the foreground.
func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) {
print(remoteMessage.appData)
}
}
| mit | b5da32db45b139726d82291526e398cd | 39.68942 | 285 | 0.616088 | 5.745542 | false | false | false | false |
KrishMunot/swift | test/Constraints/overload.swift | 3 | 4073 | // RUN: %target-parse-verify-swift
func markUsed<T>(_ t: T) {}
func f0(_: Float) -> Float {}
func f0(_: Int) -> Int {}
func f1(_: Int) {}
func identity<T>(_: T) -> T {}
func f2<T>(_: T) -> T {}
// FIXME: Fun things happen when we make this T, U!
func f2<T>(_: T, _: T) -> (T, T) { }
struct X {}
var x : X
var i : Int
var f : Float
f0(i)
f0(1.0)
f0(1)
f1(f0(1))
f1(identity(1))
f0(x) // expected-error{{cannot invoke 'f0' with an argument list of type '(X)'}}
// expected-note @-1 {{overloads for 'f0' exist with these partially matching parameter lists: (Float), (Int)}}
_ = f + 1
f2(i)
f2((i, f))
class A {
init() {}
}
class B : A {
override init() { super.init() }
}
class C : B {
override init() { super.init() }
}
func bar(_ b: B) -> Int {} // #1
func bar(_ a: A) -> Float {} // #2
var barResult = bar(C()) // selects #1, which is more specialized
i = barResult // make sure we got #1
f = bar(C()) // selects #2 because of context
// Overload resolution for constructors
protocol P1 { }
struct X1a : P1 { }
struct X1b {
init(x : X1a) { }
init<T : P1>(x : T) { }
}
X1b(x: X1a()) // expected-warning{{unused}}
// Overload resolution for subscript operators.
class X2a { }
class X2b : X2a { }
class X2c : X2b { }
struct X2d {
subscript (index : X2a) -> Int {
return 5
}
subscript (index : X2b) -> Int {
return 7
}
func foo(_ x : X2c) -> Int {
return self[x]
}
}
// Invalid declarations
// FIXME: Suppress the diagnostic for the call below, because the invalid
// declaration would have matched.
func f3(_ x: Intthingy) -> Int { } // expected-error{{use of undeclared type 'Intthingy'}}
func f3(_ x: Float) -> Float { }
f3(i) // expected-error{{cannot convert value of type 'Int' to expected argument type 'Float'}}
func f4(_ i: Wonka) { } // expected-error{{use of undeclared type 'Wonka'}}
func f4(_ j: Wibble) { } // expected-error{{use of undeclared type 'Wibble'}}
f4(5)
func f1() {
var c : Class // expected-error{{use of undeclared type 'Class'}}
markUsed(c.x) // make sure error does not cascade here
}
// We don't provide return-type sensitivity unless there is context.
func f5(_ i: Int) -> A { return A() } // expected-note{{candidate}}
func f5(_ i: Int) -> B { return B() } // expected-note{{candidate}}
f5(5) // expected-error{{ambiguous use of 'f5'}}
struct HasX1aProperty {
func write(_: X1a) {}
func write(_: P1) {}
var prop = X1a()
func test() {
write(prop) // no error, not ambiguous
}
}
// rdar://problem/16554496
@available(*, unavailable)
func availTest(_ x: Int) {}
func availTest(_ x: Any) { markUsed("this one") }
func doAvailTest(_ x: Int) {
availTest(x)
}
// rdar://problem/20886179
func test20886179(_ handlers: [(Int) -> Void], buttonIndex: Int) {
handlers[buttonIndex](buttonIndex)
}
// The problem here is that the call has a contextual result type incompatible
// with *all* overload set candidates. This is not an ambiguity.
func overloaded_identity(_ a : Int) -> Int {}
func overloaded_identity(_ b : Float) -> Float {}
func test_contextual_result() {
return overloaded_identity() // expected-error {{no 'overloaded_identity' candidates produce the expected contextual result type '()'}}
// expected-note @-1 {{overloads for 'overloaded_identity' exist with these result types: Int, Float}}
}
// rdar://problem/24128153
struct X0 {
init(_ i: Any.Type) { }
init?(_ i: Any.Type, _ names: String...) { }
}
let x0 = X0(Int.self)
let x0check: X0 = x0 // okay: chooses first initializer
struct X1 {
init?(_ i: Any.Type) { }
init(_ i: Any.Type, _ names: String...) { }
}
let x1 = X1(Int.self)
let x1check: X1 = x1 // expected-error{{value of optional type 'X1?' not unwrapped; did you mean to use '!' or '?'?}}
struct X2 {
init?(_ i: Any.Type) { }
init(_ i: Any.Type, a: Int = 0) { }
init(_ i: Any.Type, a: Int = 0, b: Int = 0) { }
init(_ i: Any.Type, a: Int = 0, c: Int = 0) { }
}
let x2 = X2(Int.self)
let x2check: X2 = x2 // expected-error{{value of optional type 'X2?' not unwrapped; did you mean to use '!' or '?'?}}
| apache-2.0 | 4e6b44b21ec89b2716f8f5400817ecb1 | 23.98773 | 138 | 0.617726 | 2.95359 | false | false | false | false |
DannyvanSwieten/SwiftSignals | SwiftAudio/WaveTable.swift | 1 | 1217 | //
// WaveTable.swift
// SwiftAudio
//
// Created by Danny van Swieten on 1/9/16.
// Copyright © 2016 Danny van Swieten. All rights reserved.
//
import Foundation
class WaveTable
{
var table = [Float32]()
var tableSize = 0
init(size: Int)
{
tableSize = size
table = [Float32](count: tableSize, repeatedValue: 0)
}
subscript (index: Float32) -> Float32
{
let trueIndex = index * Float32(tableSize)
let floorIndex = Int(trueIndex) % tableSize
let nextIndex = (floorIndex + 1) % tableSize
let frac = trueIndex - Float32(floorIndex)
return (1 - frac) * table[floorIndex] + frac * table[nextIndex]
}
func createSpectrum(spectrum: [Float32])
{
table.removeAll()
for sample in 0..<tableSize
{
var sum = 0.0
for channel in 0..<spectrum.count
{
let phinc = 2.0 * M_PI / Double(tableSize) * Double(channel + 1)
sum += sin(phinc * Double(sample)) * Double(spectrum[channel])
}
table.append(Float32(sum / Double(spectrum.count)))
}
}
} | gpl-3.0 | 5c378a771e243255e5550efd24451697 | 24.354167 | 80 | 0.537007 | 3.835962 | false | false | false | false |
yisimeng/YSMFactory-swift | Pods/YSMCategory/YSMCategory/Classes/UIImage+Gif.swift | 1 | 2176 | //
// UIImage+Gif.swift
// YSMFactory-swift
//
// Created by 忆思梦 on 2016/12/22.
// Copyright © 2016年 忆思梦. All rights reserved.
//
import UIKit
import ImageIO
extension UIImage{
//gif图片其实是一张张的图片在连续切换,播放gif,需要拿到一张张的图片,和图片显示的时长,一张张替换
public class func gifImage(file path:String) -> UIImage?{
guard let data = NSData(contentsOfFile: path) else {
return nil
}
return UIImage.gifImage(with:data as Data)
}
public class func gifImage(with data:Data) -> UIImage? {
//data转为CGImageSource对象
guard let imageSource = CGImageSourceCreateWithData(data as CFData,nil) else {
return nil
}
//获取图片的张数
let imageCount = CGImageSourceGetCount(imageSource)
//gif图组
var imageArray = [UIImage]()
var timeCount:TimeInterval = 0
//遍历获取所有图片
for i in 0..<imageCount {
//根据下标创建图片
guard let cgImage = CGImageSourceCreateImageAtIndex(imageSource, i, nil) else { continue }
let image = UIImage(cgImage: cgImage)
imageArray.append(image)
//每张图片的持续时间
guard let imageInfo = CGImageSourceCopyPropertiesAtIndex(imageSource, i, nil) as? [String:Any] else { continue }
guard let gifInfo = imageInfo[kCGImagePropertyGIFDictionary as String] as? [String:Any] else { continue }
guard let delayTime = gifInfo[kCGImagePropertyGIFDelayTime as String] as? TimeInterval else { continue }
timeCount += delayTime
}
//将多张图片转化为一张图片
return UIImage.animatedImage(with: imageArray, duration: timeCount)
//设置imageView显示一组动画
// imageView.animationImages = imageArray
// imageView.animationDuration = timeCount
// imageView.startAnimating()
}
}
| mit | 2dec17fa8e674397bec68aca16e4ef16 | 27.333333 | 124 | 0.59335 | 4.80344 | false | false | false | false |
apple/swift-docc-symbolkit | Sources/SymbolKit/SymbolGraph/Symbol/DeclarationFragments/Fragment/FragmentKind.swift | 1 | 2800 | /*
This source file is part of the Swift.org open source project
Copyright (c) 2021 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 Swift project authors
*/
import Foundation
extension SymbolGraph.Symbol.DeclarationFragments.Fragment {
/**
The kind of declaration fragment.
*/
public struct Kind: Equatable, Codable, RawRepresentable {
public var rawValue: String
public init?(rawValue: String) {
self.rawValue = rawValue
}
/**
A keyword in the programming language, such as `return` in C or `func` in Swift.
*/
public static let keyword = Kind(rawValue: "keyword")!
/**
An attribute in the programming language.
*/
public static let attribute = Kind(rawValue: "attribute")!
/**
An integer or floating point literal, such as `0`, `1.0f`, or `0xFF`.
*/
public static let numberLiteral = Kind(rawValue: "number")!
/**
A string literal such as `"foo"`.
*/
public static let stringLiteral = Kind(rawValue: "string")!
/**
An identifier such as a parameter name.
*/
public static let identifier = Kind(rawValue: "identifier")!
/**
An identifier for a type.
*/
public static let typeIdentifier = Kind(rawValue: "typeIdentifier")!
/**
A generic parameter, such as the `T` in C++ `template <typename T>`.
*/
public static let genericParameter = Kind(rawValue: "genericParameter")!
/**
A function parameter when viewed externally as a client.
For example, in Swift:
```swift
func foo(ext int: Int) {}
```
`ext` is an external parameter name, whereas `int` is an internal
parameter name.
*/
public static let externalParameter = Kind(rawValue: "externalParam")!
/**
A function parameter when viewed internally from the implementation.
For example, in Swift:
```swift
func foo(ext int: Int) {}
```
`ext` is an external parameter name, whereas `int` is an internal
parameter name.
> Note: Although these are not a part of a function's interface,
> such as in Swift, they have historically been easier to refer
> to in prose.
*/
public static let internalParameter = Kind(rawValue: "internalParam")!
/**
General purpose or unlabeled text.
*/
public static let text = Kind(rawValue: "text")!
}
}
| apache-2.0 | e49002b033dafcfad00268664ce0cdbe | 28.473684 | 89 | 0.593929 | 4.938272 | false | false | false | false |
psharanda/Atributika | Demo/SnippetsViewController.swift | 1 | 1683 | //
// Created by Pavel Sharanda on 21.02.17.
// Copyright © 2017 Pavel Sharanda. All rights reserved.
//
import UIKit
class SnippetsViewController: UIViewController {
private lazy var tableView: UITableView = {
let tableView = UITableView(frame: CGRect(), style: .plain)
tableView.delegate = self
tableView.dataSource = self
#if swift(>=4.2)
tableView.rowHeight = UITableView.automaticDimension
#else
tableView.rowHeight = UITableViewAutomaticDimension
#endif
tableView.estimatedRowHeight = 50
return tableView
}()
private var snippets = allSnippets()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(tableView)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
tableView.frame = view.bounds
}
}
extension SnippetsViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return snippets.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellId = "CellId"
let cell = tableView.dequeueReusableCell(withIdentifier: cellId) ?? UITableViewCell(style: .default, reuseIdentifier: cellId)
cell.textLabel?.attributedText = snippets[indexPath.row]
cell.textLabel?.numberOfLines = 0
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
}
}
| mit | 759fa5c899c92d53e49ab01b2fa00603 | 29.035714 | 133 | 0.668252 | 5.443366 | false | false | false | false |
ualch9/onebusaway-iphone | Carthage/Checkouts/IGListKit/Examples/Examples-iOS/IGListKitExamples/SectionControllers/ExpandableSectionController.swift | 2 | 1906 | /**
Copyright (c) Facebook, Inc. and its affiliates.
The examples provided by Facebook are for non-commercial testing and evaluation
purposes only. Facebook reserves all rights not expressly granted.
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
FACEBOOK 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 IGListKit
import UIKit
final class ExpandableSectionController: ListSectionController {
private var expanded = false
private var object: String?
override func sizeForItem(at index: Int) -> CGSize {
let width = collectionContext!.containerSize.width
let height = expanded ? LabelCell.textHeight(object ?? "", width: width) : LabelCell.singleLineHeight
return CGSize(width: width, height: height)
}
override func cellForItem(at index: Int) -> UICollectionViewCell {
guard let cell = collectionContext?.dequeueReusableCell(of: LabelCell.self, for: self, at: index) as? LabelCell else {
fatalError()
}
cell.text = object
return cell
}
override func didUpdate(to object: Any) {
self.object = object as? String
}
override func didSelectItem(at index: Int) {
expanded = !expanded
UIView.animate(withDuration: 0.5,
delay: 0,
usingSpringWithDamping: 0.4,
initialSpringVelocity: 0.6,
options: [],
animations: {
self.collectionContext?.invalidateLayout(for: self)
})
}
}
| apache-2.0 | 25b8cb170fbeac46c9e30468af46abb8 | 34.962264 | 126 | 0.66212 | 5.137466 | false | false | false | false |
kaideyi/KDYSample | KYChat/KYChat/Helper/Extension/NSObject/NSNotificationCenter+Block.swift | 1 | 1891 | //
// NSNotificationCenter+Block.swift
// TSWeChat
//
// Created by Hilen on 12/18/15.
// Copyright © 2015 Hilen. All rights reserved.
//
//https://gist.github.com/brentdax/64845dc0b3fec0a27d87
import Foundation
public extension NotificationCenter {
func addObserver<T: AnyObject>(_ observer: T, name aName: String?, object anObject: AnyObject?, queue: OperationQueue? = OperationQueue.main, handler: @escaping (_ observer: T, _ notification: Notification) -> Void) -> AnyObject {
let observation = self.addObserver(forName: aName.map { NSNotification.Name(rawValue: $0) }, object: anObject, queue: queue) { [unowned observer] note in
handler(observer, note)
}
ObservationRemover(observation).makeRetainedBy(observer)
return observation
}
}
private class ObservationRemover: NSObject {
let observation: NSObjectProtocol
init(_ obs: NSObjectProtocol) {
observation = obs
super.init()
}
func makeRetainedBy(_ owner: AnyObject) {
observationRemoversForObject(owner).add(self)
}
deinit {
NotificationCenter.default.removeObserver(observation)
}
}
private var ObservationRemoverKey: UnsafeRawPointer? = nil
fileprivate func observationRemoversForObject(_ object: AnyObject) -> NSMutableArray {
if ObservationRemoverKey == nil {
withUnsafePointer(to: &ObservationRemoverKey) { pointer in
ObservationRemoverKey = UnsafeRawPointer(pointer)
}
}
var retainedRemovers = objc_getAssociatedObject(object, ObservationRemoverKey) as! NSMutableArray?
if retainedRemovers == nil {
retainedRemovers = NSMutableArray()
objc_setAssociatedObject(object, ObservationRemoverKey, retainedRemovers, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
}
return retainedRemovers!
}
| mit | c350c0d948d0bd37f934e41606355c8a | 30.5 | 234 | 0.69418 | 4.678218 | false | false | false | false |
mspvirajpatel/SwiftyBase | SwiftyBase/Classes/Utility/AppImageSelection.swift | 1 | 3507 | //
// AppImageSelection.swift
// Pods
//
// Created by MacMini-2 on 13/09/17.
//
//
import Foundation
//How to Use
//ImageSelection.manager.openImagePicker(from: self, allowEditing: true) { (imageSelectionManager, selectedImage) in
// if let image = selectedImage {
//
// }
//}
import UIKit
//This is the completion block used to get image back in calling viewController
typealias AppImageSelectionComplitionBlock = (_ imageSelect: AppImageSelection, _ selectedImage: UIImage?) -> ()
class AppImageSelection: NSObject {
static let manager = AppImageSelection()
var confirmBlock: AppImageSelectionComplitionBlock?
fileprivate var openInViewController: UIViewController!
//main function used to show imageSelection options
func openImagePicker(from viewController: UIViewController, allowEditing: Bool, confirm: @escaping AppImageSelectionComplitionBlock) {
confirmBlock = nil
confirmBlock = confirm
openInViewController = viewController
//create ActionSheet to show options to user
let alertController = UIAlertController(title: "Select photo", message: "Select photo", preferredStyle: .actionSheet)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { action in
}
let cameraAction = UIAlertAction(title: "Camera", style: .default) { action in
self.selectPictureFrom(UIImagePickerController.SourceType.camera, allowEditing: allowEditing)
}
let photoGelleryAction = UIAlertAction(title: "Photo Gallery", style: .default) { action in
self.selectPictureFrom(UIImagePickerController.SourceType.photoLibrary, allowEditing: allowEditing)
}
alertController.addAction(cancelAction)
alertController.addAction(cameraAction)
alertController.addAction(photoGelleryAction)
viewController.present(alertController, animated: true, completion: nil)
}
//used to open UIImagePickerController with selected sourceType
fileprivate func selectPictureFrom(_ sourceType: UIImagePickerController.SourceType, allowEditing: Bool)
{
let picker = UIImagePickerController()
picker.allowsEditing = allowEditing
picker.delegate = self
picker.sourceType = sourceType
openInViewController.present(picker, animated: true, completion: nil)
}
}
//MARK:- UIImagePickerControllerDelegate
extension AppImageSelection: UIImagePickerControllerDelegate, UINavigationControllerDelegate
{
//this method triggers when user select cancel In Photo selection screen
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
if confirmBlock != nil {
confirmBlock!(self, nil)
}
openInViewController.dismiss(animated: true, completion: nil)
}
//this method triggers when user select Photo
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
var newImage: UIImage? = nil
if let possibleImage = info[UIImagePickerController.InfoKey.editedImage] as? UIImage {
newImage = possibleImage
} else if let possibleImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
newImage = possibleImage
}
//give image back to calling ViewController
confirmBlock?(self, newImage)
openInViewController.dismiss(animated: true, completion: nil)
}
}
| mit | 9f780af48b8178c5b4cb6aff75ed801f | 35.53125 | 144 | 0.723981 | 5.297583 | false | false | false | false |
maxkatzmann/graphlibS | pushUpdate.swift | 1 | 2653 | #!/usr/bin/env xcrun swift
import Foundation
func shell(arguments: [String]) -> String
{
let task = Process()
task.launchPath = "/usr/bin/env"
task.arguments = arguments
let pipe = Pipe()
task.standardOutput = pipe
task.launch()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output: String = String(data: data, encoding: String.Encoding.utf8)!
return output
}
if CommandLine.arguments.count > 1 {
let currentVersionString = shell(arguments: ["git", "describe", "--tags"]).trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
print("Current Version is: \(currentVersionString)")
var versionComponents = currentVersionString.components(separatedBy: ".")
if let currentBuildNumberString = versionComponents.last,
let currentBuildNumber = Int(currentBuildNumberString) {
let newBuildNumber = currentBuildNumber + 1
versionComponents[versionComponents.count - 1] = String(newBuildNumber)
let newVersionString = versionComponents.joined(separator: ".")
print("New version will be: \(newVersionString)")
/**
* Now we update the readme to contain a badge showing the correct version.
*/
let path = URL(fileURLWithPath: FileManager.default.currentDirectoryPath).appendingPathComponent("README.md")
let readmeContent = try String(contentsOf: path)
var newReadme = ""
let lines = readmeContent.components(separatedBy: "\n")
for line in lines {
if line.range(of: "[GitHub tag]") != nil {
let newTagLine = "[-brightgreen.svg)](https://github.com/maxkatzmann/graphlibS/releases/tag/\(newVersionString))"
newReadme.append(newTagLine + "\n")
} else {
newReadme.append(line + "\n")
}
}
try newReadme.write(to: path, atomically: false,
encoding: .utf8)
let commitMessage = CommandLine.arguments[1]
print("Commiting with message: \(commitMessage)")
let _ = shell(arguments: ["git", "add", "."])
let gitCommitResult = shell(arguments: ["git", "commit", "-m", "\(commitMessage)"])
print("Commited: \(gitCommitResult)")
let gitTagResult = shell(arguments: ["git", "tag", "\(newVersionString)"])
print("Tagged: \(gitTagResult)")
let _ = shell(arguments: ["git", "push", "origin", "master", "--tags"])
print("Pushed.")
}
} else {
print("Usage: \(CommandLine.arguments[0]) \"commit message\"")
}
| gpl-3.0 | c2266c3b6a34ae1718f3c1f1f753bcc0 | 35.342466 | 199 | 0.634376 | 4.451342 | false | false | false | false |
nakau1/Formations | Formations/Sources/Modules/Team/Models/Team.swift | 1 | 3701 | // =============================================================================
// Formations
// Copyright 2017 yuichi.nakayasu All rights reserved.
// =============================================================================
import Foundation
import RealmSwift
class Team: RealmSwift.Object {
var info = [String : Any?]()
// MARK: - Properties
/// ID
@objc dynamic var id = ""
/// チーム名
@objc dynamic var name = "新しいクラブ"
/// チーム名(国際名)
@objc dynamic var internationalName = "Formation FC"
/// チーム名(短縮系)
@objc dynamic var shortenedName = "FFC"
/// チームカラー(メイン)RGB値
@objc dynamic var mainColorRGB = ""
/// チームカラー(サブ)RGB値
@objc dynamic var subColorRGB = ""
/// チームカラー(オプション1)RGB値
@objc dynamic var option1ColorRGB = ""
/// チームカラー(オプション2)RGB値
@objc dynamic var option2ColorRGB = ""
/// 所属選手
let players = List<Player>()
/// フォーメーション雛形
let formationTemplates = List<FormationTemplate>()
// MARK: - Images
/// エンブレム(オリジナル)画像
var emblemImage: UIImage?
func loadEmblemImage(force: Bool = false) -> Self {
if emblemImage == nil || force {
emblemImage = Image.teamEmblem(id: id).load()
}
return self
}
/// エンブレム(小)画像
var smallEmblemImage: UIImage?
func loadSmallEmblemImage(force: Bool = false) -> Self {
if smallEmblemImage == nil || force {
smallEmblemImage = Image.teamSmallEmblem(id: id).load()?.retina
}
return self
}
/// チーム画像(背景用)
var teamImage: UIImage?
func loadTeamImage(force: Bool = false) -> Self {
if teamImage == nil || force {
teamImage = Image.teamImage(id: id).load()
}
return self
}
// MARK: - Calculated Properties
/// チームカラー(メイン)
var mainColor: UIColor {
get {
return UIColor(hexString: mainColorRGB) ?? .white
}
set {
return mainColorRGB = newValue.hexString
}
}
/// チームカラー(サブ)
var subColor: UIColor {
get {
return UIColor(hexString: subColorRGB) ?? .white
}
set {
return subColorRGB = newValue.hexString
}
}
/// チームカラー(オプション1)
var option1Color: UIColor? {
get {
return UIColor(hexString: option1ColorRGB)
}
set {
guard let color = newValue else {
option1ColorRGB = ""
return
}
return option1ColorRGB = color.hexString
}
}
/// チームカラー(オプション2)
var option2Color: UIColor? {
get {
return UIColor(hexString: option2ColorRGB)
}
set {
guard let color = newValue else {
option2ColorRGB = ""
return
}
return option2ColorRGB = color.hexString
}
}
/// フォーメーション
var formation = Formation()
// MARK: - Specs
override class func primaryKey() -> String? { return "id" }
override class func ignoredProperties() -> [String] {
return ["emblemImage", "smallEmblemImage", "teamImage", "formation", "info"]
}
override var description: String {
return "\(name) <\(internationalName)>"
}
}
| apache-2.0 | 03cbd6e483bfad48b4412de520ceddeb | 24.103704 | 84 | 0.509 | 4.112864 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/FeatureAuthentication/Sources/FeatureAuthenticationDomain/NabuAuthentication/Services/NabuAuthenticationExecutor.swift | 1 | 15155 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import BlockchainNamespace
import Combine
import DIKit
import Foundation
import NetworkKit
import ToolKit
import WalletPayloadKit
public protocol NabuAuthenticationExecutorAPI {
/// Runs authentication flow if needed and passes it to the `networkResponsePublisher`
/// - Parameter networkResponsePublisher: the closure taking a token and returning a publisher for a request
func authenticate(
_ networkResponsePublisher: @escaping NetworkResponsePublisher
) -> AnyPublisher<ServerResponse, NetworkError>
}
public typealias NabuAuthenticationExecutorProvider = () -> NabuAuthenticationExecutorAPI
public typealias NabuUserEmailProvider = () -> AnyPublisher<String, Error>
public typealias CheckAuthenticated = (NetworkError) -> AnyPublisher<Bool, Never>
public enum NabuAuthenticationExecutorError: Error {
case failedToCreateUser(NetworkError)
case failedToRetrieveJWTToken(JWTServiceError)
case failedToRecoverUser(NetworkError)
case failedToFetchEmail(Error)
case failedToGetSessionToken(NetworkError)
case sessionTokenFetchTimedOut
case missingCredentials(MissingCredentialsError)
case failedToSaveOfflineToken(CredentialWritingError)
case communicatorError(NetworkError)
}
// swiftlint:disable type_body_length
struct NabuAuthenticationExecutor: NabuAuthenticationExecutorAPI {
private struct Token {
let sessionToken: NabuSessionToken
let offlineToken: NabuOfflineToken
}
private let app: AppProtocol
private let store: NabuTokenRepositoryAPI
private let errorBroadcaster: UserAlreadyRestoredHandlerAPI
private let credentialsRepository: CredentialsRepositoryAPI
private let nabuOfflineTokenRepository: NabuOfflineTokenRepositoryAPI
private let nabuRepository: NabuRepositoryAPI
private let nabuUserEmailProvider: NabuUserEmailProvider
private let deviceInfo: DeviceInfo
private let jwtService: JWTServiceAPI
private let siftService: SiftServiceAPI
private let checkAuthenticated: CheckAuthenticated
private let queue: DispatchQueue
private let fetchTokensPublisher: Atomic<AnyPublisher<Token, NabuAuthenticationExecutorError>?> = Atomic(nil)
init(
app: AppProtocol = resolve(),
store: NabuTokenRepositoryAPI = resolve(),
errorBroadcaster: UserAlreadyRestoredHandlerAPI = resolve(),
nabuRepository: NabuRepositoryAPI = resolve(),
nabuUserEmailProvider: @escaping NabuUserEmailProvider = resolve(),
siftService: SiftServiceAPI = resolve(),
checkAuthenticated: @escaping CheckAuthenticated = resolve(),
jwtService: JWTServiceAPI = resolve(),
credentialsRepository: CredentialsRepositoryAPI = resolve(),
nabuOfflineTokenRepository: NabuOfflineTokenRepositoryAPI = resolve(),
deviceInfo: DeviceInfo = resolve(),
queue: DispatchQueue = DispatchQueue(
label: "com.blockchain.NabuAuthenticationExecutor",
qos: .background
)
) {
self.app = app
self.store = store
self.errorBroadcaster = errorBroadcaster
self.nabuRepository = nabuRepository
self.nabuUserEmailProvider = nabuUserEmailProvider
self.siftService = siftService
self.checkAuthenticated = checkAuthenticated
self.credentialsRepository = credentialsRepository
self.nabuOfflineTokenRepository = nabuOfflineTokenRepository
self.jwtService = jwtService
self.deviceInfo = deviceInfo
self.queue = queue
}
func authenticate(
_ networkResponsePublisher: @escaping NetworkResponsePublisher
) -> AnyPublisher<ServerResponse, NetworkError> {
getToken()
.mapError { error in
NetworkError(request: nil, type: .authentication(error))
}
.flatMap { payload -> AnyPublisher<ServerResponse, NetworkError> in
networkResponsePublisher(payload.sessionToken.token)
.catch { communicatorError -> AnyPublisher<ServerResponse, NetworkError> in
refreshOrReturnError(
communicatorError: communicatorError,
offlineToken: payload.offlineToken,
publisherProvider: networkResponsePublisher
)
}
.eraseToAnyPublisher()
}
.eraseToAnyPublisher()
}
// MARK: - Private methods
private func getToken() -> AnyPublisher<Token, NabuAuthenticationExecutorError> {
Publishers
.Zip(
store.sessionTokenPublisher.prefix(1).mapError(),
retrieveOfflineTokenResponse()
)
.map { sessionToken, offlineToken
-> (sessionToken: NabuSessionToken?, offlineToken: NabuOfflineToken) in
(sessionToken: sessionToken, offlineToken: offlineToken)
}
// swiftlint:disable:next line_length
.catch { _ -> AnyPublisher<(sessionToken: NabuSessionToken?, offlineToken: NabuOfflineToken), NabuAuthenticationExecutorError> in
fetchTokens()
.map { token -> (sessionToken: NabuSessionToken?, offlineToken: NabuOfflineToken) in
(token.sessionToken, token.offlineToken)
}
.eraseToAnyPublisher()
}
.flatMap { payload -> AnyPublisher<Token, NabuAuthenticationExecutorError> in
guard let token = payload.sessionToken else {
return fetchTokens()
}
return .just(Token(sessionToken: token, offlineToken: payload.offlineToken))
}
.eraseToAnyPublisher()
}
private func fetchTokens() -> AnyPublisher<Token, NabuAuthenticationExecutorError> {
// Case A: We are already performing a token fetch, return current fetch publisher
if let publisher = fetchTokensPublisher.value {
return publisher
}
// Case B: We are not currently performing a token fetch, create a new fetch publisher
let publisher = createFetchTokens()
.handleEvents(receiveCompletion: { _ in
// We are done fetching the token, reset state
self.fetchTokensPublisher.mutate { $0 = nil }
})
.eraseToAnyPublisher()
fetchTokensPublisher.mutate { $0 = publisher }
return publisher
}
private func createFetchTokens() -> AnyPublisher<Token, NabuAuthenticationExecutorError> {
createUserIfNeeded()
.flatMap { offlineToken -> AnyPublisher<Token, NabuAuthenticationExecutorError> in
currentToken(offlineToken: offlineToken)
.map { Token(sessionToken: $0, offlineToken: offlineToken) }
.eraseToAnyPublisher()
}
.shareReplay()
.eraseToAnyPublisher()
}
private func currentToken(
offlineToken: NabuOfflineToken
) -> AnyPublisher<NabuSessionToken, NabuAuthenticationExecutorError> {
store.requiresRefresh
.mapError()
.flatMap { requiresRefresh -> AnyPublisher<NabuSessionToken, NabuAuthenticationExecutorError> in
guard !requiresRefresh else {
return refreshToken(offlineToken: offlineToken)
}
return store
.sessionTokenPublisher
.prefix(1)
.mapError()
.flatMap { sessionToken
-> AnyPublisher<NabuSessionToken, NabuAuthenticationExecutorError> in
guard let sessionToken = sessionToken else {
return .failure(.missingCredentials(MissingCredentialsError.sessionToken))
}
return .just(sessionToken)
}
.eraseToAnyPublisher()
}
.eraseToAnyPublisher()
}
private func refreshOrReturnError(
communicatorError: NetworkError,
offlineToken: NabuOfflineToken,
publisherProvider: @escaping (String) -> AnyPublisher<ServerResponse, NetworkError>
) -> AnyPublisher<ServerResponse, NetworkError> {
checkAuthenticated(communicatorError)
.mapError()
.flatMap { unauthenticated -> AnyPublisher<Void, NetworkError> in
guard unauthenticated else {
return .failure(communicatorError)
}
return clearAccessToken()
.mapError()
.eraseToAnyPublisher()
}
.flatMap { _ -> AnyPublisher<ServerResponse, NetworkError> in
refreshToken(offlineToken: offlineToken)
.mapError { error in
NetworkError(request: nil, type: .authentication(error))
}
.flatMap { sessionToken -> AnyPublisher<ServerResponse, NetworkError> in
publisherProvider(sessionToken.token)
}
.eraseToAnyPublisher()
}
.eraseToAnyPublisher()
}
private func refreshToken(
offlineToken: NabuOfflineToken
) -> AnyPublisher<NabuSessionToken, NabuAuthenticationExecutorError> {
getSessionToken(offlineTokenResponse: offlineToken)
.flatMap { sessionToken -> AnyPublisher<NabuSessionToken, Never> in
store.store(sessionToken)
}
.catch { error -> AnyPublisher<NabuSessionToken, NabuAuthenticationExecutorError> in
broadcastOrReturnError(error: error)
.ignoreOutput(setOutputType: NabuSessionToken.self)
.eraseToAnyPublisher()
}
.eraseToAnyPublisher()
}
private func clearAccessToken() -> AnyPublisher<Void, Never> {
store
.invalidate()
.mapError()
.eraseToAnyPublisher()
}
private func getSessionToken(
offlineTokenResponse: NabuOfflineToken
) -> AnyPublisher<NabuSessionToken, NabuAuthenticationExecutorError> {
let email = nabuUserEmailProvider()
.mapError(NabuAuthenticationExecutorError.failedToFetchEmail)
.eraseToAnyPublisher()
let guid = credentialsRepository.guid
.flatMap { guid -> AnyPublisher<String, NabuAuthenticationExecutorError> in
guard let guid = guid else {
return .failure(.missingCredentials(MissingCredentialsError.guid))
}
return .just(guid)
}
.eraseToAnyPublisher()
return Publishers.Zip(email, guid)
.flatMap { email, guid -> AnyPublisher<NabuSessionToken, NabuAuthenticationExecutorError> in
nabuRepository
.sessionToken(
for: guid,
userToken: offlineTokenResponse.token,
userIdentifier: offlineTokenResponse.userId,
deviceId: deviceInfo.uuidString,
email: email
)
.mapError(NabuAuthenticationExecutorError.failedToGetSessionToken)
.eraseToAnyPublisher()
}
.handleEvents(receiveOutput: { nabuSessionTokenResponse in
siftService.set(
userId: nabuSessionTokenResponse.userId
)
})
.eraseToAnyPublisher()
}
private func broadcastOrReturnError(
error: NabuAuthenticationExecutorError
) -> AnyPublisher<Void, NabuAuthenticationExecutorError> {
guard case .failedToGetSessionToken(let networkError) = error else {
return .failure(error)
}
return userAlreadyRestored(error: networkError)
.setFailureType(to: NabuAuthenticationExecutorError.self)
.broadcastErrorWithHint(
error: error,
errorBroadcaster: errorBroadcaster
)
}
private func userAlreadyRestored(
error: NetworkError
) -> AnyPublisher<String?, Never> {
guard let authenticationError = NabuAuthenticationError(error: error),
case .alreadyRegistered(_, let walletIdHint) = authenticationError
else {
return .just(nil)
}
return .just(walletIdHint)
}
// MARK: - User Creation
private func createUserIfNeeded() -> AnyPublisher<NabuOfflineToken, NabuAuthenticationExecutorError> {
nabuOfflineTokenRepository
.offlineToken
.catch { _ -> AnyPublisher<NabuOfflineToken, NabuAuthenticationExecutorError> in
createUser()
}
.eraseToAnyPublisher()
}
private func createUser() -> AnyPublisher<NabuOfflineToken, NabuAuthenticationExecutorError> {
jwtToken()
.flatMap { jwtToken -> AnyPublisher<NabuOfflineToken, NabuAuthenticationExecutorError> in
nabuRepository
.createUser(for: jwtToken)
.mapError(NabuAuthenticationExecutorError.failedToCreateUser)
.eraseToAnyPublisher()
}
.flatMap { offlineToken
-> AnyPublisher<NabuOfflineToken, NabuAuthenticationExecutorError> in
nabuOfflineTokenRepository
.set(offlineToken: offlineToken)
.replaceOutput(with: offlineToken)
.mapError(NabuAuthenticationExecutorError.failedToSaveOfflineToken)
.eraseToAnyPublisher()
}
.eraseToAnyPublisher()
}
// MARK: - Conveniences
private func jwtToken() -> AnyPublisher<String, NabuAuthenticationExecutorError> {
jwtService
.token
.mapError(NabuAuthenticationExecutorError.failedToRetrieveJWTToken)
.eraseToAnyPublisher()
}
private func retrieveOfflineTokenResponse()
-> AnyPublisher<NabuOfflineToken, NabuAuthenticationExecutorError>
{
nabuOfflineTokenRepository
.offlineToken
.mapError(NabuAuthenticationExecutorError.missingCredentials)
.eraseToAnyPublisher()
}
}
// MARK: - Extension
extension Publisher where Output == String?, Failure == NabuAuthenticationExecutorError {
fileprivate func broadcastErrorWithHint(
error: NabuAuthenticationExecutorError,
errorBroadcaster: UserAlreadyRestoredHandlerAPI
) -> AnyPublisher<Void, NabuAuthenticationExecutorError> {
flatMap { walletIdHint
-> AnyPublisher<Void, NabuAuthenticationExecutorError> in
guard let hint = walletIdHint else {
return .failure(error)
}
return errorBroadcaster.send(walletIdHint: hint)
}
.mapToVoid()
}
}
| lgpl-3.0 | 3bfddad2b625ab069d511c369bca93df | 39.627346 | 141 | 0.630065 | 6.018268 | false | false | false | false |
Skogetroll/ZLSwipeableViewSwift | ZLSwipeableViewSwiftDemo/Pods/Cartography/Cartography/ViewUtils.swift | 33 | 925 | //
// ViewUtils.swift
// Cartography
//
// Created by Garth Snyder on 11/23/14.
// Copyright (c) 2014 Robert Böhnke. All rights reserved.
//
#if os(iOS)
import UIKit
#else
import AppKit
#endif
internal func closestCommonAncestor(a: View, b: View) -> View? {
let (aSuper, bSuper) = (a.superview, b.superview)
if a === b { return a }
if a === bSuper { return a }
if b === aSuper { return b }
if aSuper === bSuper { return aSuper }
let ancestorsOfA = Set(ancestors(a))
for ancestor in ancestors(b) {
if ancestorsOfA.contains(ancestor) {
return ancestor
}
}
return .None
}
private func ancestors(v: View) -> AnySequence<View> {
return AnySequence { () -> AnyGenerator<View> in
var view: View? = v
return anyGenerator {
let current = view
view = view?.superview
return current
}
}
}
| mit | e07e3f05de373bde251d6f9c1c181ecf | 19.086957 | 64 | 0.584416 | 3.681275 | false | false | false | false |
shaps80/Peek | Pod/Classes/Helpers/Enum+Cases.swift | 1 | 744 | //
// Enum+Cases.swift
// Peek
//
// Created by Shaps Benkau on 26/02/2018.
//
import Foundation
extension RawRepresentable where RawValue == Int, Self: Hashable {
private static func cases() -> AnySequence<Self> {
return AnySequence { () -> AnyIterator<Self> in
var raw = 0
return AnyIterator {
let current: Self = withUnsafePointer(to: &raw) { $0.withMemoryRebound(to: self, capacity: 1) { $0.pointee } }
guard current.hashValue == raw else {
return nil
}
raw += 1
return current
}
}
}
internal static var all: [Self] {
return Array(self.cases())
}
}
| mit | 7f72194fd4520cc0f56a254157bd378f | 24.655172 | 126 | 0.520161 | 4.481928 | false | false | false | false |
Lollipop95/WeiBo | WeiBo/WeiBo/Classes/Tools/Emoticon/View/WBEmoticonToolbar.swift | 1 | 3571 | //
// WBEmoticonToolbar.swift
// WeiBo
//
// Created by Ning Li on 2017/5/8.
// Copyright © 2017年 Ning Li. All rights reserved.
//
import UIKit
@objc protocol WBEmoticonToolbarDelegate {
/// 表情工具栏选中分组项索引
///
/// - Parameters:
/// - toolbar: toolbar
/// - index: 分组项索引
@objc optional func emoticonToolbar(_ toolbar: WBEmoticonToolbar, didSelectedItemAt index: Int)
}
class WBEmoticonToolbar: UIView {
/// 代理属性
weak var delegate: WBEmoticonToolbarDelegate?
/// 选中的分组索引
var selectedIndex: Int = 0 {
didSet {
for btn in subviews as! [UIButton] {
btn.isSelected = false
}
(subviews[selectedIndex] as! UIButton).isSelected = true
}
}
override func awakeFromNib() {
super.awakeFromNib()
setupUI()
}
override func layoutSubviews() {
super.layoutSubviews()
let count: Int = subviews.count
let width: CGFloat = bounds.width / CGFloat(count)
let rect: CGRect = CGRect(x: 0, y: 0, width: width, height: bounds.height)
for (i, btn) in subviews.enumerated() {
btn.frame = rect.offsetBy(dx: CGFloat(i) * width, dy: 0)
}
}
// MARK: - 监听方法
/// 分组按钮监听方法
@objc fileprivate func clickItem(btn: UIButton) {
delegate?.emoticonToolbar?(self, didSelectedItemAt: btn.tag)
}
}
// MARK: - 设置界面
extension WBEmoticonToolbar {
fileprivate func setupUI() {
let manager = WBEmoticonManager.shared
for (i, package) in manager.packages.enumerated() {
let button: UIButton = UIButton()
button.tag = i
button.setTitle(package.groupName, for: [])
button.titleLabel?.font = UIFont.systemFont(ofSize: 14)
let imageName = "compose_emotion_table_\(package.bgImageName ?? "")_normal"
let imageNameHL = "compose_emotion_table_\(package.bgImageName ?? "")_selected"
var image = UIImage(named: imageName, in: manager.bundle, compatibleWith: nil)
var imageHL = UIImage(named: imageNameHL, in: manager.bundle, compatibleWith: nil)
// 拉伸图片
let size = image?.size ?? CGSize()
let inset = UIEdgeInsets(top: size.height * 0.5,
left: size.width * 0.5,
bottom: size.height * 0.5,
right: size.width * 0.5)
image = image?.resizableImage(withCapInsets: inset)
imageHL = imageHL?.resizableImage(withCapInsets: inset)
button.setBackgroundImage(image, for: [])
button.setBackgroundImage(imageHL, for: .highlighted)
button.setBackgroundImage(imageHL, for: .selected)
button.setTitleColor(UIColor.white, for: [])
button.setTitleColor(UIColor.darkGray, for: .highlighted)
button.setTitleColor(UIColor.darkGray, for: .selected)
button.addTarget(self, action: #selector(clickItem(btn:)), for: .touchUpInside)
addSubview(button)
}
// 默认选中第 0 组
(subviews[0] as! UIButton).isSelected = true
}
}
| mit | 2f6b4f7de7df4f3761ce100bab6772f6 | 29.350877 | 99 | 0.540751 | 4.701087 | false | false | false | false |
LawrenceHan/iOS-project-playground | Swift_Algorithm/Swift_Algorithm/Edge.swift | 1 | 1236 | //
// Edge.swift
// Swift_Algorithm
//
// Created by Hanguang on 23/11/2016.
// Copyright © 2016 Hanguang. All rights reserved.
//
import Foundation
public struct Edge<T>: Equatable where T: Equatable, T: Hashable {
public let from: Vertex<T>
public let to: Vertex<T>
public let weight: Double?
}
extension Edge: CustomStringConvertible {
public var description: String {
get {
guard let unwrappedWeight = weight else {
return "\(from.description) -> \(to.description)"
}
return "\(from.description) -(\(unwrappedWeight))-> \(to.description)"
}
}
}
extension Edge: Hashable {
public var hashValue: Int {
get {
var string = "\(from.description)\(to.description)"
if weight != nil {
string.append("\(weight)")
}
return string.hashValue
}
}
}
public func == <T>(lhs: Edge<T>, rhs: Edge<T>) -> Bool {
guard lhs.from == rhs.from else {
return false
}
guard lhs.to == rhs.to else {
return false
}
guard lhs.weight == rhs.weight else {
return false
}
return true
}
| mit | ed509765f1184be41bf7d6e508abfa9e | 19.932203 | 82 | 0.5417 | 4.258621 | false | false | false | false |
apple/swift-nio-http2 | Sources/NIOHTTP2Server/main.swift | 1 | 5702 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2017-2021 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// This example server currently does not know how to negotiate HTTP/2. That will come in a future enhancement. For now, you can
// hit it with curl like so: curl --http2-prior-knowledge http://localhost:8888/
import NIOCore
import NIOPosix
import NIOHTTP1
import NIOHTTP2
final class HTTP1TestServer: ChannelInboundHandler {
public typealias InboundIn = HTTPServerRequestPart
public typealias OutboundOut = HTTPServerResponsePart
public func channelRead(context: ChannelHandlerContext, data: NIOAny) {
guard case .end = self.unwrapInboundIn(data) else {
return
}
// Insert an event loop tick here. This more accurately represents real workloads in SwiftNIO, which will not
// re-entrantly write their response frames.
context.eventLoop.execute {
context.channel.getOption(HTTP2StreamChannelOptions.streamID).flatMap { (streamID) -> EventLoopFuture<Void> in
var headers = HTTPHeaders()
headers.add(name: "content-length", value: "5")
headers.add(name: "x-stream-id", value: String(Int(streamID)))
context.channel.write(self.wrapOutboundOut(HTTPServerResponsePart.head(HTTPResponseHead(version: .init(major: 2, minor: 0), status: .ok, headers: headers))), promise: nil)
var buffer = context.channel.allocator.buffer(capacity: 12)
buffer.writeStaticString("hello")
context.channel.write(self.wrapOutboundOut(HTTPServerResponsePart.body(.byteBuffer(buffer))), promise: nil)
return context.channel.writeAndFlush(self.wrapOutboundOut(HTTPServerResponsePart.end(nil)))
}.whenComplete { _ in
context.close(promise: nil)
}
}
}
}
final class ErrorHandler: ChannelInboundHandler {
typealias InboundIn = Never
func errorCaught(context: ChannelHandlerContext, error: Error) {
print("Server received error: \(error)")
context.close(promise: nil)
}
}
// First argument is the program path
let arguments = CommandLine.arguments
let arg1 = arguments.dropFirst().first
let arg2 = arguments.dropFirst().dropFirst().first
let arg3 = arguments.dropFirst().dropFirst().dropFirst().first
let defaultHost = "::1"
let defaultPort: Int = 8888
let defaultHtdocs = "/dev/null/"
enum BindTo {
case ip(host: String, port: Int)
case unixDomainSocket(path: String)
}
let htdocs: String
let bindTarget: BindTo
switch (arg1, arg1.flatMap { Int($0) }, arg2, arg2.flatMap { Int($0) }, arg3) {
case (.some(let h), _ , _, .some(let p), let maybeHtdocs):
/* second arg an integer --> host port [htdocs] */
bindTarget = .ip(host: h, port: p)
htdocs = maybeHtdocs ?? defaultHtdocs
case (_, .some(let p), let maybeHtdocs, _, _):
/* first arg an integer --> port [htdocs] */
bindTarget = .ip(host: defaultHost, port: p)
htdocs = maybeHtdocs ?? defaultHtdocs
case (.some(let portString), .none, let maybeHtdocs, .none, .none):
/* couldn't parse as number --> uds-path [htdocs] */
bindTarget = .unixDomainSocket(path: portString)
htdocs = maybeHtdocs ?? defaultHtdocs
default:
htdocs = defaultHtdocs
bindTarget = BindTo.ip(host: defaultHost, port: defaultPort)
}
let group = MultiThreadedEventLoopGroup(numberOfThreads: System.coreCount)
let bootstrap = ServerBootstrap(group: group)
// Specify backlog and enable SO_REUSEADDR for the server itself
.serverChannelOption(ChannelOptions.backlog, value: 256)
.serverChannelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1)
// Set the handlers that are applied to the accepted Channels
.childChannelInitializer { channel in
return channel.configureHTTP2Pipeline(mode: .server) { streamChannel -> EventLoopFuture<Void> in
return streamChannel.pipeline.addHandler(HTTP2FramePayloadToHTTP1ServerCodec()).flatMap { () -> EventLoopFuture<Void> in
streamChannel.pipeline.addHandler(HTTP1TestServer())
}.flatMap { () -> EventLoopFuture<Void> in
streamChannel.pipeline.addHandler(ErrorHandler())
}
}.flatMap { (_: HTTP2StreamMultiplexer) in
return channel.pipeline.addHandler(ErrorHandler())
}
}
// Enable TCP_NODELAY and SO_REUSEADDR for the accepted Channels
.childChannelOption(ChannelOptions.socket(IPPROTO_TCP, TCP_NODELAY), value: 1)
.childChannelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1)
.childChannelOption(ChannelOptions.maxMessagesPerRead, value: 1)
defer {
try! group.syncShutdownGracefully()
}
print("htdocs = \(htdocs)")
let channel = try { () -> Channel in
switch bindTarget {
case .ip(let host, let port):
return try bootstrap.bind(host: host, port: port).wait()
case .unixDomainSocket(let path):
return try bootstrap.bind(unixDomainSocketPath: path).wait()
}
}()
print("Server started and listening on \(channel.localAddress!), htdocs path \(htdocs)")
// This will never unblock as we don't close the ServerChannel
try channel.closeFuture.wait()
print("Server closed")
| apache-2.0 | 99715638bd1410b4df9feebff2bea2d7 | 38.874126 | 187 | 0.673974 | 4.38953 | false | false | false | false |
kevinmeresse/sefi-ios | sefi/DetailViewController.swift | 1 | 8957 | //
// DetailViewController.swift
// sefi
//
// Created by Kevin Meresse on 4/16/15.
// Copyright (c) 2015 KM. All rights reserved.
//
import UIKit
class DetailViewController: UIViewController {
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var contentView: UIView!
@IBOutlet weak var loadingView: UIView!
@IBOutlet weak var companyView: UIView!
@IBOutlet weak var applyButton: UIBarButtonItem!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var idLabel: UILabel!
@IBOutlet weak var locationLabel: UILabel!
@IBOutlet weak var contractTypeLabel: UILabel!
@IBOutlet weak var carLicenceLabel: UILabel!
@IBOutlet weak var degreeLabel: UILabel!
@IBOutlet weak var experienceLabel: UILabel!
@IBOutlet weak var numberLabel: UILabel!
@IBOutlet weak var availabilityLabel: UILabel!
@IBOutlet weak var boatLicenceLabel: UILabel!
@IBOutlet weak var studiesLevelLabel: UILabel!
@IBOutlet weak var experienceTimeLabel: UILabel!
@IBOutlet weak var jobDescriptionLabel: UILabel!
@IBOutlet weak var conditionsLabel: UILabel!
@IBOutlet weak var softwareExpertiseLabel: UILabel!
@IBOutlet weak var languageLabel: UILabel!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var applyDateLabel: UILabel!
@IBOutlet weak var offerIdLabel: UILabel!
@IBOutlet weak var offerDateLabel: UILabel!
@IBOutlet weak var companyLabel: UILabel!
@IBOutlet weak var contactLabel: UILabel!
var itemIndex: Int?
var detailItem: Offer? {
didSet {
// Update the view.
self.configureView()
}
}
@IBAction func apply(sender: AnyObject) {
// Show loading view and disable button
loadingView.hidden = false
applyButton.enabled = false
// Call webservice
if let offer: Offer = self.detailItem {
SOAPService
.POST(RequestFactory.applyOffer(offer))
.success({xml in {XMLParser.checkIfApplied(xml)} ~> {self.offerIsApplied($0, message: $1)}})
.failure(onFailure, queue: NSOperationQueue.mainQueue())
}
}
private func offerIsApplied(success: Bool, message: String?) {
// Hide loading view and re-enable button
loadingView.hidden = true
applyButton.enabled = true
if success {
println("SUCCESS: Offer is favorited!")
showInformationPopup("Félicitations", message: "Votre demande a bien été prise en compte !", whenDone: {
// Delete current offer from list
if self.splitViewController != nil && self.itemIndex != nil {
if let offersNC = self.splitViewController?.viewControllers.first as? UINavigationController {
if UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Pad {
if let offersVC = offersNC.visibleViewController as? ListOffersViewController {
offersVC.dataSource.offers.removeAtIndex(self.itemIndex!)
}
} else if offersNC.viewControllers.count > 1 {
if let offersVC = offersNC.viewControllers[offersNC.viewControllers.count - 2] as? ListOffersViewController {
offersVC.dataSource.offers.removeAtIndex(self.itemIndex!)
}
}
// Go back to the list
offersNC.popViewControllerAnimated(true)
}
}
// Show an "empty view" on the right-hand side, only on an iPad.
if UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Pad
{
let emptyVC = self.storyboard!.instantiateViewControllerWithIdentifier("EmptyOfferViewController") as! UIViewController
self.splitViewController!.showDetailViewController(emptyVC, sender: self)
}
})
} else {
println("FAILURE: Offer is NOT favorited...")
showInformationPopup("Ooops", message: "Une erreur s'est produite. Votre demande n'a pas été prise en compte...", whenDone: nil)
}
}
private func showInformationPopup(title: String, message: String, whenDone: (() -> ())?) {
let alert = UIAlertController(
title: title,
message: message,
preferredStyle: .Alert)
alert.addAction(UIAlertAction(
title: "OK",
style: .Default,
handler: { _ in
//self.dismissViewControllerAnimated(true, completion: nil)
if whenDone != nil {
whenDone!()
}
}))
presentViewController(alert, animated: true, completion: nil)
}
private func onFailure(statusCode: Int, error: NSError?)
{
println("HTTP status code \(statusCode)")
let
title = "Erreur",
msg = error?.localizedDescription ?? "Une erreur est survenue.",
alert = UIAlertController(
title: title,
message: msg,
preferredStyle: .Alert)
alert.addAction(UIAlertAction(
title: "OK",
style: .Default,
handler: { _ in
self.dismissViewControllerAnimated(true, completion: nil)
}))
presentViewController(alert, animated: true, completion: nil)
}
func configureView() {
// Update the user interface for the detail item.
if let offer: Offer = self.detailItem {
if let label = self.titleLabel {
label.text = offer.jobTitle
}
if let label = self.idLabel {
label.text = offer.id
}
if let label = self.locationLabel {
label.text = offer.location
}
if let label = self.contractTypeLabel {
label.text = offer.contractType
}
if let label = self.carLicenceLabel {
label.text = offer.carLicence
}
if let label = self.degreeLabel {
label.text = offer.degree
}
if let label = self.experienceLabel {
label.text = offer.experience
}
if let label = self.numberLabel {
label.text = offer.number
}
if let label = self.availabilityLabel {
label.text = offer.availability
}
if let label = self.boatLicenceLabel {
label.text = offer.boatLicence
}
if let label = self.studiesLevelLabel {
label.text = offer.studiesLevel
}
if let label = self.experienceTimeLabel {
label.text = offer.experienceTime
}
if let label = self.jobDescriptionLabel {
label.text = offer.jobDescription
}
if let label = self.conditionsLabel {
label.text = offer.conditions
}
if let label = self.softwareExpertiseLabel {
label.text = offer.softwareExpertise
}
if let label = self.languageLabel {
label.text = offer.languages
}
if let view = self.companyView {
if offer.applied {
// Hide Apply button
navigationItem.rightBarButtonItems = []
} else {
// Hide Company details
view.removeFromSuperview()
}
}
if let label = self.nameLabel {
label.text = "\(offer.lastName!) \(offer.firstName!)"
}
if let label = self.applyDateLabel {
label.text = offer.applyDate
}
if let label = self.offerIdLabel {
label.text = offer.id
}
if let label = self.offerDateLabel {
label.text = offer.offerDate
}
if let label = self.companyLabel {
label.text = offer.companyName
}
if let label = self.contactLabel {
label.text = offer.companyContact
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.scrollView.contentSize = CGSizeMake(600, 1000)
// Do any additional setup after loading the view.
self.configureView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| apache-2.0 | 026e85511794e40342dbd80f0bcea0c9 | 36.613445 | 140 | 0.555407 | 5.325402 | false | false | false | false |
chrisamanse/Codegen | Codegen iOS/ViewControllers/AddManualViewController.swift | 1 | 3735 | //
// AddManualViewController.swift
// Codegen
//
// Created by Chris Amanse on 10/09/2016.
//
//
import UIKit
import RealmSwift
import OTPKit
class AddManualViewController: UITableViewController {
@IBOutlet weak var issuerTextField: UITextField!
@IBOutlet weak var codeLabel: UILabel!
@IBOutlet weak var accountTextField: UITextField!
@IBOutlet weak var keyTextField: UITextField!
@IBOutlet weak var digitsLabel: UILabel!
@IBOutlet weak var digitsStepper: UIStepper!
@IBOutlet weak var timeBasedSwitch: UISwitch!
let estimatedRowHeight: CGFloat = 50
override func viewDidLoad() {
super.viewDidLoad()
tableView.estimatedRowHeight = estimatedRowHeight
tableView.rowHeight = UITableViewAutomaticDimension
}
@IBAction func didPressCancel(_ sender: UIBarButtonItem) {
dismiss(animated: true)
}
@IBAction func didPressAdd(_ sender: UIBarButtonItem) {
let feedbackGenerator = UINotificationFeedbackGenerator()
feedbackGenerator.prepare()
do {
let account = try createOTPAccount()
let realm = try Realm()
let store = try OTPAccountStore.defaultStore(in: realm)
try realm.write {
store.accounts.insert(account, at: 0)
}
feedbackGenerator.notificationOccurred(.success)
dismiss(animated: true)
} catch let error as AddAccountInvalidInput {
feedbackGenerator.notificationOccurred(.error)
let alertMessage = AppStrings.Alerts.AddAccountFailed.fixMessage + "\n" + error.errorMessages.joined(separator: "\n")
presentErrorAlert(title: AppStrings.Alerts.AddAccountFailed.title, message: alertMessage)
} catch let error {
print("Failed to add: \(error)")
feedbackGenerator.notificationOccurred(.error)
presentErrorAlert(title: AppStrings.Alerts.AddAccountFailed.title, message: AppStrings.Alerts.AddAccountFailed.unknownError)
}
}
@IBAction func didChangeStepperValue(_ sender: UIStepper) {
let digits = Int(sender.value)
digitsLabel.text = String(digits)
let dummyAccount = OTPAccount()
dummyAccount.digits = digits
codeLabel.text = dummyAccount.formattedPassword(obfuscated: true)
}
func createOTPAccount() throws -> OTPAccount {
let account = accountTextField.text ?? ""
let key = formatted(key: keyTextField.text ?? "")
let data = try? Base32.decode(key)
var errors: AddAccountInvalidInput = []
if account.isEmpty {
errors.insert(.noAccount)
}
if key.isEmpty {
errors.insert(.noKey)
}
if data == nil {
errors.insert(.invalidKey)
}
guard errors.isEmpty else {
throw errors
}
let newAccount = OTPAccount()
newAccount.account = account
newAccount.issuer = issuerTextField.text ?? ""
newAccount.digits = Int(digitsStepper.value)
newAccount.key = data!
if timeBasedSwitch.isOn {
newAccount.timeBased = true
newAccount.period = OTPAccount.Defaults.period
} else {
newAccount.counter = OTPAccount.Defaults.counter
}
return newAccount
}
func formatted(key: String) -> String {
return key.components(separatedBy: .whitespaces).joined(separator: "").uppercased()
}
}
| gpl-3.0 | 0babecab30b284c005462677d5207a68 | 29.867769 | 136 | 0.604016 | 5.253165 | false | false | false | false |
Rhumbix/SwiftyPaperTrail | SwiftyPaperTrailTests/SyslogFormatterTests.swift | 1 | 1990 | //
// SyslogFormatterTests.swift
// SwiftyPaperTrail
//
// Created by Majd Murad on 12/1/16.
// Copyright © 2016 Rhumbix, Inc. All rights reserved.
//
import XCTest
import SwiftyLogger
import SwiftyPaperTrail
class SyslogFormatterTests: XCTestCase {
func testDefaultSyslogFormat() {
var message = LogMessage()
message.message = "Testing Message"
let formattedString = SyslogFormatter().format(message: message)
let packet = RFC5424Packet.parse(packet: formattedString)
XCTAssertEqual(packet.message, "Testing Message")
}
func testDifferentMachineName() {
var message = LogMessage()
message.message = "Testing Machine Name Change"
let customMachineName = "my-custom-machine-name"
let formatter = SyslogFormatter()
formatter.machineName = customMachineName
let formattedString = formatter.format(message: message)
let packet = RFC5424Packet.parse(packet: formattedString)
XCTAssertEqual(packet.host, "my-custom-machine-name")
}
func testDifferentProgramName() {
var message = LogMessage()
message.message = "Testing Program Name Change"
let customProgramName = "My-Custom-Program-Name"
let formatter = SyslogFormatter()
formatter.programName = customProgramName
let formattedString = formatter.format(message: message)
let packet = RFC5424Packet.parse(packet: formattedString)
XCTAssertEqual(packet.application, customProgramName)
}
func test_syslogFacilityOverriden() {
var message = LogMessage()
message.message = "Testing Program for Syslog facility chnage"
let formatter = SyslogFormatter()
formatter.facility = .kernel
let formattedString = formatter.format(message: message)
let packet = RFC5424Packet.parse(packet: formattedString)
XCTAssertEqual(packet.facility, SyslogFacilities.kernel.rawValue)
}
}
| mit | 530eafb41286ad267d98838639f2d6df | 31.080645 | 73 | 0.690799 | 4.572414 | false | true | false | false |
Acidburn0zzz/firefox-ios | Client/Frontend/Settings/SettingsNavigationController.swift | 1 | 1800 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
class ThemedNavigationController: UINavigationController {
var presentingModalViewControllerDelegate: PresentingModalViewControllerDelegate?
@objc func done() {
if let delegate = presentingModalViewControllerDelegate {
delegate.dismissPresentedModalViewController(self, animated: true)
} else {
self.dismiss(animated: true, completion: nil)
}
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return topViewController?.preferredStatusBarStyle ?? ThemeManager.instance.statusBarStyle
}
override func viewDidLoad() {
super.viewDidLoad()
modalPresentationStyle = .formSheet
modalPresentationCapturesStatusBarAppearance = true
applyTheme()
}
}
extension ThemedNavigationController: Themeable {
func applyTheme() {
navigationBar.barTintColor = UIColor.theme.tableView.headerBackground
navigationBar.tintColor = UIColor.theme.general.controlTint
navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.theme.tableView.headerTextDark]
setNeedsStatusBarAppearanceUpdate()
viewControllers.forEach {
($0 as? Themeable)?.applyTheme()
}
}
}
protocol PresentingModalViewControllerDelegate: AnyObject {
func dismissPresentedModalViewController(_ modalViewController: UIViewController, animated: Bool)
}
class ModalSettingsNavigationController: UINavigationController {
override var preferredStatusBarStyle: UIStatusBarStyle {
return .default
}
}
| mpl-2.0 | 0fd9ea42ab84880e40cc447292265a07 | 35 | 124 | 0.733333 | 6.040268 | false | false | false | false |
itssofluffy/NanoMessage | Tests/NanoMessageTests/PairProtocolFamilyTests.swift | 1 | 4290 | /*
PairProtocolFamilyTests.swift
Copyright (c) 2016, 2017 Stephen Whittle All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom
the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
*/
import XCTest
import Foundation
import NanoMessage
class PairProtocolFamilyTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testPair(connectAddress: String, bindAddress: String = "") {
guard let connectURL = URL(string: connectAddress) else {
XCTAssert(false, "connectURL is invalid")
return
}
guard let bindURL = URL(string: (bindAddress.isEmpty) ? connectAddress : bindAddress) else {
XCTAssert(false, "bindURL is invalid")
return
}
var completed = false
do {
let node0 = try PairSocket(url: connectURL, type: .Connect)
let node1 = try PairSocket(url: bindURL, type: .Bind)
try node0.setSendTimeout(seconds: 1)
try node0.setReceiveTimeout(seconds: 1)
try node1.setSendTimeout(seconds: 1)
try node1.setReceiveTimeout(seconds: 1)
pauseForBind()
var node0Sent = try node0.sendMessage(payload)
XCTAssertEqual(node0Sent.bytes, payload.count, "node0Sent.bytes != payload.count")
let node1Received = try node1.receiveMessage()
XCTAssertEqual(node1Received.bytes, node1Received.message.count, "node1.bytes != node1Received.message.count")
XCTAssertEqual(node1Received.message, payload, "node1.message != payload")
node0Sent = try node1.sendMessage(payload)
XCTAssertEqual(node0Sent.bytes, payload.count, "node0Sent.bytes != payload.count")
let node0Received = try node0.receiveMessage()
XCTAssertEqual(node0Received.bytes, node0Received.message.count, "node0.bytes != node0Received.message.count")
XCTAssertEqual(node0Received.message, payload, "node0.message != payload")
completed = true
} catch let error as NanoMessageError {
XCTAssert(false, "\(error)")
} catch {
XCTAssert(false, "an unexpected error '\(error)' has occured in the library libNanoMessage.")
}
XCTAssert(completed, "test not completed")
}
func testTCPPair() {
testPair(connectAddress: "tcp://localhost:5200", bindAddress: "tcp://*:5200")
}
func testInProcessPair() {
testPair(connectAddress: "inproc:///tmp/pair.inproc")
}
func testInterProcessPair() {
testPair(connectAddress: "ipc:///tmp/pair.ipc")
}
func testWebSocketPair() {
testPair(connectAddress: "ws://localhost:5205", bindAddress: "ws://*:5205")
}
#if os(Linux)
static let allTests = [
("testTCPPair", testTCPPair),
("testInProcessPair", testInProcessPair),
("testInterProcessPair", testInterProcessPair),
("testWebSocketPair", testWebSocketPair)
]
#endif
}
| mit | e5e2a5d2f83ed05a9e264a50fda4b6d3 | 37.648649 | 122 | 0.66993 | 4.492147 | false | true | false | false |
PumpMagic/ostrich | gameboy/gameboy/Source/GameboyAPU/GameboyAPU.swift | 1 | 5887 | //
// GameboyAPU.swift
// audiotest
//
// Created by Ryan Conway on 3/27/16.
// Copyright © 2016 conwarez. All rights reserved.
//
import Foundation
import AudioKit
/// Get the value of a certain range of bits in a number, as though the bits were their own value
/// whose LSB is the lowest bit in the range and represents 1
/// For example, getValueOfBits(0b10101010, 2...4) selects bits 2-4 (010) and returns 2
public func getValueOfBits(_ num: UInt8, bits: CountableClosedRange<UInt8>) -> UInt8 {
guard let minIndex = bits.min() else {
exit(1)
}
var result: UInt8 = 0
for bitIndex in bits {
let relativeIndex = bitIndex - minIndex
if bitIsHigh(num, bit: bitIndex) {
result = result + (0x01 << relativeIndex)
}
}
return result
}
/// A Game Boy audio processing unit; the audio portion of the Game Boy's LR35902.
public class GameBoyAPU: Memory, HandlesWrites {
let FIRST_ADDRESS: Address = 0xFF10
let LAST_ADDRESS: Address = 0xFF3F
public let pulse1: Pulse
public let pulse2: Pulse
let ram: RAM
public var firstAddress: Address {
return FIRST_ADDRESS
}
public var lastAddress: Address {
return LAST_ADDRESS
}
public var addressRange: CountableClosedRange<Address> {
return Address(self.firstAddress) ... Address(self.lastAddress)
}
init(mixer: AKMixer) {
self.pulse1 = Pulse(mixer: mixer, hasFrequencySweep: true, connected: true)
self.pulse2 = Pulse(mixer: mixer, hasFrequencySweep: false, connected: true)
self.pulse1.initializeCounterCallbacks()
self.pulse2.initializeCounterCallbacks()
//@todo we can't use LAST or FIRST here for calculations. what can we do instead?
self.ram = RAM(size: 0x30, fillByte: 0x00, firstAddress: 0xFF10)
}
public func read(_ addr: Address) -> UInt8 {
// print("APU read! \(addr.hexString)")
return self.ram.read(addr)
}
public func write(_ val: UInt8, to addr: Address) {
// print("APU write! \(val.hexString) to \(addr.hexString)")
self.ram.write(val, to: addr)
// Update children
//@todo there's a better way to do this
switch addr {
// 0xFF10 - 0xFF14: Pulse 1
case 0xFF10:
pulse1.frequencySweepPeriod = getValueOfBits(val, bits: 4...6)
pulse1.frequencySweepNegate = getValueOfBits(val, bits: 3...3)
pulse1.frequencySweepShift = getValueOfBits(val, bits: 0...2)
break
case 0xFF11:
pulse1.duty = getValueOfBits(val, bits: 6...7)
pulse1.lengthCounterLoad = getValueOfBits(val, bits: 0...5)
case 0xFF12:
pulse1.startingVolume = getValueOfBits(val, bits: 4...7)
pulse1.envelopeAddMode = getValueOfBits(val, bits: 3...3)
pulse1.envelopePeriod = getValueOfBits(val, bits: 0...2)
case 0xFF13:
let frequencyLow = val
let ff14 = self.ram.read(0xFF14)
let frequencyHigh = getValueOfBits(ff14, bits: 0...2)
let frequency = make16(high: frequencyHigh, low: frequencyLow)
pulse1.frequency = frequency
case 0xFF14:
let frequencyLow = self.ram.read(0xFF13)
let ff14 = val
let frequencyHigh = getValueOfBits(ff14, bits: 0...2)
let frequency = make16(high: frequencyHigh, low: frequencyLow)
pulse1.frequency = frequency
pulse1.trigger = getValueOfBits(val, bits: 7...7)
pulse1.lengthEnable = getValueOfBits(val, bits: 6...6)
// 0xFF15 - 0xFF19: Pulse 2
case 0xFF15:
// unused
break
case 0xFF16:
pulse2.duty = getValueOfBits(val, bits: 6...7)
pulse2.lengthCounterLoad = getValueOfBits(val, bits: 0...5)
case 0xFF17:
pulse2.startingVolume = getValueOfBits(val, bits: 4...7)
pulse2.envelopeAddMode = getValueOfBits(val, bits: 3...3)
pulse2.envelopePeriod = getValueOfBits(val, bits: 0...2)
case 0xFF18:
let frequencyLow = val
let ff19 = self.ram.read(0xFF19)
let frequencyHigh = getValueOfBits(ff19, bits: 0...2)
let frequency = make16(high: frequencyHigh, low: frequencyLow)
pulse2.frequency = frequency
case 0xFF19:
let frequencyLow = self.ram.read(0xFF18)
let ff19 = val
let frequencyHigh = getValueOfBits(ff19, bits: 0...2)
let frequency = make16(high: frequencyHigh, low: frequencyLow)
pulse2.frequency = frequency
pulse2.trigger = getValueOfBits(val, bits: 7...7)
pulse2.lengthEnable = getValueOfBits(val, bits: 6...6)
// case 0xFF24, 0xFF25, 0xFF26:
// Power control / status
// print("Write to power control! \(addr.hexString) <- \(val.hexString)")
// exit(1)
default:
//print("Ignoring!")
//exit(1)
break
}
}
var clockIndex = 0 // 0-3
public func clock256() {
pulse1.clock256()
pulse2.clock256()
// 128Hz - every other 256Hz clock
if clockIndex == 1 || clockIndex == 3 {
pulse1.sweepTimerFired()
}
// 64Hz - every fourth 256Hz clock
if clockIndex == 3 {
pulse1.clock64()
pulse2.clock64()
}
clockIndex += 1
if clockIndex > 3 {
clockIndex = 0
}
}
}
| mit | 4e7af134932b0172e7b67c16627341c7 | 32.254237 | 97 | 0.562861 | 4.070539 | false | false | false | false |
honghaoz/CrackingTheCodingInterview | Swift/LeetCode/Prefix Sum/238_Product of Array Except Self.swift | 1 | 2082 | //
// 238. Product of Array Except Self.swift
// https://leetcode.com/problems/product-of-array-except-self/
//
// Created by Honghao Zhang on 2016-10-26.
// Copyright © 2016 Honghaoz. All rights reserved.
//
//Given an array of n integers where n > 1, nums, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].
//
//Solve it without division and in O(n).
//
//For example, given [1,2,3,4], return [24,12,8,6].
//
//Follow up:
//Could you solve it with constant space complexity? (Note: The output array does not count as extra space for the purpose of space complexity analysis.)
// 给出一个数组,求出除了self的乘积的数组
// Prefix Product
import Foundation
class Num238_ProductOfArrayExceptSelf: Solution {
/// Build two arrays:
/// 1) the product of left elements, except self
/// 2) the product of right elements,
/// 3) product of these two arrays
func productExceptSelf_readable(_ nums: [Int]) -> [Int] {
var running = 1 // the running product
var leftProduct: [Int] = []
for i in 0..<nums.count {
leftProduct.append(running)
running *= nums[i]
}
running = 1
var rightProduct: [Int] = []
for i in (0...(nums.count - 1)).reversed() {
rightProduct.append(running)
running *= nums[i]
}
rightProduct = rightProduct.reversed()
/// multiple two arrys
return zip(leftProduct, rightProduct).map { $0.0 * $0.1 }
}
func productExceptSelf_concise(_ nums: [Int]) -> [Int] {
var a = 1
var results: [Int] = []
for i in 0..<nums.count {
results.append(a)
a *= nums[i]
}
a = 1
for i in stride(from: nums.count - 1, to: -1, by: -1) {
results[i] *= a
a *= nums[i]
}
return results
}
/// Solution 2:
/// Reduce the space complexity
/// One idea is to just compute the result on the fly
/// scan the element from left to right, but you can keep the two running product, one for the left side, one for the right side
/// Then you can build the result.
func test() {
}
}
| mit | aecd321c97435ba157f8489ae1610aad | 26.662162 | 160 | 0.642892 | 3.350245 | false | false | false | false |
honghaoz/CrackingTheCodingInterview | Swift/LeetCode/Dynamic Programming/45_Jump Game II.swift | 1 | 3045 | // 45_Jump Game II
// https://leetcode.com/problems/jump-game-ii/
//
// Created by Honghao Zhang on 9/21/19.
// Copyright © 2019 Honghaoz. All rights reserved.
//
// Description:
// Given an array of non-negative integers, you are initially positioned at the first index of the array.
//
//Each element in the array represents your maximum jump length at that position.
//
//Your goal is to reach the last index in the minimum number of jumps.
//
//Example:
//
//Input: [2,3,1,1,4]
//Output: 2
//Explanation: The minimum number of jumps to reach the last index is 2.
// Jump 1 step from index 0 to 1, then 3 steps to the last index.
//Note:
//
//You can assume that you can always reach the last index.
//
import Foundation
class Num45 {
// Standard DP. However, time limit exceeded
func jump_dp(_ nums: [Int]) -> Int {
if nums.count == 0 {
return -1
}
if nums.count == 1 {
return 0
}
// s[i] means the min jumps to index i
var s: [Int] = Array(repeating: Int.max, count: nums.count)
s[0] = 0
// s[i] = min(s[j] + 1), j < i && j can reach i
for i in 1..<nums.count {
for j in 0..<i {
// s[j] != Int.max: j can be reached from 0
// j + nums[j] >= i: j can reach i
if s[j] != Int.max, j + nums[j] >= i {
s[i] = min(s[i], s[j] + 1)
}
}
}
return s[nums.count - 1]
}
// DP with greedy
func jump_dp_with_greedy(_ nums: [Int]) -> Int {
if nums.count == 0 {
return -1
}
if nums.count == 1 {
return 0
}
// s[i] means the min jumps to index i
var s: [Int] = Array(repeating: Int.max, count: nums.count)
s[0] = 0
// s[i] = min(s[j] + 1), j < i && j can reach i
for i in 1..<nums.count {
for j in 0..<i {
// s[j] != Int.max: j can be reached from 0
// j + nums[j] >= i: j can reach i
if s[j] != Int.max, j + nums[j] >= i {
s[i] = s[j] + 1 // greedy. why???
break // greedy
}
}
}
return s[nums.count - 1]
}
// Greedy
func jump_greedy(_ nums: [Int]) -> Int {
// greedy
// start from 0
// find the furthest index can be reached
// then check the indices between 0 to the furthest index
// (also need to record the jumps
// if there's a new furthest index, update it
// if found the furthest index >= nums.count - 1, stop
if nums.count == 0 {
return -1
}
if nums.count == 1{
return 0
}
// loop invariant:
// for jumps count, the end is the furthest index can reach.
var i = 0
var jumps = 0
var end = 0
while i <= end {
jumps += 1
// nextEnd is the furthest index can reach when jumps + 1
var nextEnd = end
while i <= end {
nextEnd = max(nextEnd, i + nums[i])
i += 1
}
if nextEnd >= nums.count - 1 {
return jumps
}
end = nextEnd
}
// should already returned
assertionFailure()
return jumps
}
}
| mit | bf3f589a17b939869c35f4af761f5168 | 23.95082 | 105 | 0.53975 | 3.370986 | false | false | false | false |
maxep/DiscogsAPI | Example-swift/DGMasterViewController.swift | 2 | 4201 | // DGMasterViewController.swift
//
// Copyright (c) 2017 Maxime Epain
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import DiscogsAPI
class DGMasterViewController: DGViewController {
fileprivate var response : DGMasterVersionsResponse! {
didSet { tableView.reloadData() }
}
override func viewDidLoad() {
super.viewDidLoad()
// Get master details
Discogs.api.database.get(master: objectID, success: { (master) in
self.titleLabel.text = master.title
self.detailLabel.text = master.artists.first?.name
self.yearLabel.text = master.year!.stringValue
self.styleLabel.text = master.genres.joined(separator: ", ")
// Get a Discogs image
if let image = master.images.first, let url = image.resourceURL {
Discogs.api.resource.get(image: url, success: { (image) in
self.coverView?.image = image
})
}
}) { (error) in
print(error)
}
// Get master versions
let request = DGMasterVersionsRequest()
request.masterID = objectID
request.pagination.perPage = 25
Discogs.api.database.get(request, success: { (response) in
self.response = response
}) { (error) in
print(error)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let indexPath = tableView.indexPathForSelectedRow, let destination = segue.destination as? DGViewController {
destination.objectID = response.versions[indexPath.row].id
}
}
// MARK: UITableViewDataSource
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return response?.versions.count ?? 0
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "Versions"
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ReleaseCell")!
let version = response.versions[indexPath.row]
cell.textLabel?.text = version.title
cell.detailTextLabel?.text = version.format
cell.imageView?.image = UIImage(named: "default-release")
// Get a Discogs image
if let thumb = version.thumb {
Discogs.api.resource.get(image: thumb, success: { (image) in
cell.imageView?.image = image
})
}
// Load the next response page
if version === response.versions.last {
response.loadNextPage(success: {
self.tableView.reloadData()
})
}
return cell
}
}
| mit | a446fcb1f25c9c96b97b7bfd5c50bef4 | 35.530435 | 120 | 0.629136 | 4.971598 | false | false | false | false |
YuriFox/YFVolumeView | Source/YFColor.swift | 1 | 1919 | //
// YFColor.swift
// YFVolumeController
//
// Created by Yuri Fox on 12.08.17.
// Copyright © 2017 Yuri Lysytsia. All rights reserved.
//
import UIKit
extension UIColor {
var rgbComponents: UIColorRGBComponents? {
return UIColorRGBComponents(color: self)
}
var whiteComponents: UIColorWhiteComponents? {
return UIColorWhiteComponents(color: self)
}
func colorWithSaturation(_ saturation: CGFloat) -> UIColor? {
if let rgbComponents = self.rgbComponents {
return rgbComponents.color(saturation: saturation)
}
if let whiteComponents = self.whiteComponents {
return whiteComponents.color(saturation: saturation)
}
return nil
}
}
struct UIColorRGBComponents {
var red, green, blue, alpha: CGFloat
init?(color: UIColor) {
guard let components = color.cgColor.components, components.count == 4 else { return nil }
self.red = components[0]
self.green = components[1]
self.blue = components[2]
self.alpha = color.cgColor.alpha
}
func color(saturation: CGFloat) -> UIColor {
let red = saturation * self.red
let green = saturation * self.green
let blue = saturation * self.blue
return UIColor(red: red, green: green, blue: blue, alpha: self.alpha)
}
}
struct UIColorWhiteComponents {
var white, alpha: CGFloat
init?(color: UIColor) {
guard let components = color.cgColor.components, components.count == 2 else { return nil }
self.white = components[0]
self.alpha = color.cgColor.alpha
}
func color(saturation: CGFloat) -> UIColor {
let white = saturation * self.white
return UIColor(white: white, alpha: self.alpha)
}
}
| apache-2.0 | f17f955851d9005c16e90d52e1781caf | 23.278481 | 98 | 0.598019 | 4.545024 | false | false | false | false |
ncalexan/firefox-ios | XCUITests/ClipBoardTests.swift | 2 | 1872 | /* 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 XCTest
class ClipBoardTests: BaseTestCase {
let url = "www.google.com"
var navigator: Navigator!
var app: XCUIApplication!
override func setUp() {
super.setUp()
app = XCUIApplication()
navigator = createScreenGraph(app).navigator(self)
}
override func tearDown() {
navigator = nil
app = nil
super.tearDown()
}
//Check for test url in the browser
func checkUrl() {
let urlTextField = app.textFields["url"]
waitForValueContains(urlTextField, value: "www.google")
}
//Copy url from the browser
func copyUrl() {
app.textFields["url"].tap()
app.textFields["address"].press(forDuration: 1.7)
app.menuItems["Select All"].tap()
app.menuItems["Copy"].tap()
}
//Check copied url is same as in browser
func checkCopiedUrl() {
if let myString = UIPasteboard.general.string {
var value = app.textFields["url"].value as! String
if myString.hasSuffix("/") {
value = "\(value)/"
}
XCTAssertNotNil(myString)
XCTAssertEqual(myString, value, "Url matches with the UIPasteboard")
}
}
// This test is disabled in release, but can still run on master
func testClipboard() {
navigator.openURL(urlString: url)
checkUrl()
copyUrl()
checkCopiedUrl()
restart(app)
dismissFirstRunUI()
app.textFields["url"].tap()
app.textFields["address"].press(forDuration: 1.7)
app.menuItems["Paste"].tap()
app.typeText("\r")
}
}
| mpl-2.0 | 5c171fb14ad236cfd6e36ef472d44b99 | 28.25 | 80 | 0.590278 | 4.478469 | false | true | false | false |
MattKiazyk/Operations | framework/Operations/Operations/CloudKitOperation.swift | 1 | 1159 | //
// CloudKitOperation.swift
// Operations
//
// Created by Daniel Thorpe on 22/07/2015.
// Copyright (c) 2015 Daniel Thorpe. All rights reserved.
//
import Foundation
import CloudKit
public protocol CloudKitOperationType: class {
var database: CKDatabase! { get set }
}
/**
A very simple wrapper for CloudKit database operations.
The database property is set on the operation, and suitable
for execution on an `OperationQueue`. This means that
observers and conditions can be attached.
*/
public class CloudKitOperation<CloudOperation where CloudOperation: CloudKitOperationType, CloudOperation: NSOperation>: GroupOperation {
public let operation: CloudOperation
public init(var operation: CloudOperation, database: CKDatabase = CKContainer.defaultContainer().privateCloudDatabase, completion: dispatch_block_t = { }) {
operation.database = database
let finished = NSBlockOperation(block: completion)
finished.addDependency(operation)
self.operation = operation
super.init(operations: [operation, finished])
}
}
extension CKDatabaseOperation: CloudKitOperationType {}
| mit | 3b816fa9b8809e2f3455bd1070f73415 | 31.194444 | 160 | 0.741156 | 4.952991 | false | false | false | false |
jamesjmtaylor/weg-ios | weg-ios/Extensions/UILabel+BoldUnderline.swift | 1 | 1417 | //
// UILabel+BoldUnderline.swift
// weg-ios
//
// Created by Taylor, James on 5/10/18.
// Copyright © 2018 James JM Taylor. All rights reserved.
//
import Foundation
import UIKit
extension UILabel {
func addAttributes(isBolded: Bool = false, isUnderlined: Bool = false){
var attrs = [NSAttributedString.Key:Any]()
let underline = [NSAttributedString.Key.underlineStyle : NSUnderlineStyle.single.rawValue]
let bold = [NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 17)]
if isBolded {attrs[bold.keys.first!] = (bold.values.first!)}
if isUnderlined {attrs[underline.keys.first!] = (underline.values.first!)}
let attributedString = NSMutableAttributedString(string: self.text ?? "",
attributes: attrs)
self.attributedText = attributedString
}
}
extension NSMutableAttributedString {
@discardableResult func bold(_ text: String) -> NSMutableAttributedString {
let attrs = [NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 17)]
let boldString = NSMutableAttributedString(string:text, attributes: attrs)
append(boldString)
return self
}
@discardableResult func normal(_ text: String) -> NSMutableAttributedString {
let normal = NSAttributedString(string: text)
append(normal)
return self
}
}
| mit | 620d8110630dccae0a4e9dc8715ec090 | 35.307692 | 98 | 0.663842 | 4.767677 | false | false | false | false |
groue/GRMustache.swift | Sources/MustacheBox.swift | 1 | 21285 | // The MIT License
//
// Copyright (c) 2015 Gwendal Roué
//
// 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
/// Mustache templates don't eat raw values: they eat values boxed
/// in `MustacheBox`.
///
/// Boxing is generally automatic:
///
/// // The render method automatically boxes the dictionary:
/// template.render(["name": "Arthur"])
///
/// **Warning**: the fact that `MustacheBox` is a subclass of NSObject is an
/// implementation detail that is enforced by the Swift language itself. This
/// may change in the future: do not rely on it.
final public class MustacheBox : NSObject {
// IMPLEMENTATION NOTE
//
// Why is MustacheBox a subclass of NSObject, and not, say, a Swift struct?
//
// Swift does not allow a class extension to override a method that is
// inherited from an extension to its superclass and incompatible with
// Objective-C.
//
// If MustacheBox were a pure Swift type, this Swift limit would prevent
// NSObject subclasses such as NSNull, NSNumber, etc. to override
// MustacheBoxable.mustacheBox, and provide custom rendering behavior.
//
// For an example of this limitation, see example below:
//
// import Foundation
//
// // A type that is not compatible with Objective-C
// struct MustacheBox { }
//
// // So far so good
// extension NSObject {
// var mustacheBox: MustacheBox { return MustacheBox() }
// }
//
// // Error: declarations in extensions cannot override yet
// extension NSNull {
// override var mustacheBox: MustacheBox { return MustacheBox() }
// }
//
// This problem does not apply to Objc-C compatible protocols:
//
// import Foundation
//
// // So far so good
// extension NSObject {
// var prop: String { return "NSObject" }
// }
//
// // No error
// extension NSNull {
// override var prop: String { return "NSNull" }
// }
//
// NSObject().prop // "NSObject"
// NSNull().prop // "NSNull"
//
// In order to let the user easily override NSObject.mustacheBox, we had to
// keep its return type compatible with Objective-C, that is to say make
// MustacheBox a subclass of NSObject.
// -------------------------------------------------------------------------
// MARK: - The boxed value
/// The boxed value.
public let value: Any?
/// The only empty box is `Box()`.
public let isEmpty: Bool
/// The boolean value of the box.
///
/// It tells whether the Box should trigger or prevent the rendering of
/// regular `{{#section}}...{{/}}` and inverted `{{^section}}...{{/}}`.
public let boolValue: Bool
/// If the boxed value can be iterated (array or set), returns an array
/// of `MustacheBox`.
public var arrayValue: [MustacheBox]? {
return converter?.arrayValue()
}
/// If the boxed value is a dictionary, returns a `[String: MustacheBox]`.
public var dictionaryValue: [String: MustacheBox]? {
return converter?.dictionaryValue()
}
/// Extracts a key out of a box.
///
/// let box = Box(["firstName": "Arthur"])
/// box.mustacheBox(forKey: "firstName").value // "Arthur"
///
/// - parameter key: A key.
/// - returns: The MustacheBox for *key*.
public func mustacheBox(forKey key: String) -> MustacheBox {
guard let keyedSubscript = keyedSubscript else {
return EmptyBox
}
return Box(keyedSubscript(key))
}
public func render(_ info: RenderingInfo) throws -> Rendering {
return try self._render(info)
}
// -------------------------------------------------------------------------
// MARK: - Other facets
fileprivate var _render: RenderFunction
/// See the documentation of `FilterFunction`.
public let filter: FilterFunction?
/// See the documentation of `WillRenderFunction`.
public let willRender: WillRenderFunction?
/// See the documentation of `DidRenderFunction`.
public let didRender: DidRenderFunction?
// -------------------------------------------------------------------------
// MARK: - Multi-facetted Box Initialization
/// This is the low-level initializer of MustacheBox, suited for building
/// "advanced" boxes.
///
/// This initializer can take up to seven parameters, all optional, that
/// define how the box interacts with the Mustache engine:
///
/// - `value`: an optional boxed value
/// - `boolValue`: an optional boolean value for the Box.
/// - `keyedSubscript`: an optional KeyedSubscriptFunction
/// - `filter`: an optional FilterFunction
/// - `render`: an optional RenderFunction
/// - `willRender`: an optional WillRenderFunction
/// - `didRender`: an optional DidRenderFunction
///
///
/// To illustrate the usage of all those parameters, let's look at how the
/// `{{f(a)}}` tag is rendered.
///
/// First the `a` and `f` expressions are evaluated. The Mustache engine
/// looks in the context stack for boxes whose *keyedSubscript* return
/// non-empty boxes for the keys "a" and "f". Let's call them aBox and fBox.
///
/// Then the *filter* of the fBox is evaluated with aBox as an argument. It
/// is likely that the result depends on the *value* of the aBox: it is the
/// resultBox.
///
/// Then the Mustache engine is ready to render resultBox. It looks in the
/// context stack for boxes whose *willRender* function is defined. Those
/// willRender functions have the opportunity to process the resultBox, and
/// eventually provide the box that will be actually rendered:
/// the renderedBox.
///
/// The renderedBox has a *render* function: it is evaluated by the Mustache
/// engine which appends its result to the final rendering.
///
/// Finally the Mustache engine looks in the context stack for boxes whose
/// *didRender* function is defined, and call them.
///
///
/// ### value
///
/// The optional `value` parameter gives the boxed value. The value is used
/// when the box is rendered (unless you provide a custom RenderFunction).
/// It is also returned by the `value` property of MustacheBox.
///
/// let aBox = MustacheBox(value: 1)
///
/// // Renders "1"
/// let template = try! Template(string: "{{a}}")
/// try! template.render(["a": aBox])
///
///
/// ### boolValue
///
/// The optional `boolValue` parameter tells whether the Box should trigger
/// or prevent the rendering of regular `{{#section}}...{{/}}` and inverted
/// `{{^section}}...{{/}}` tags. The default boolValue is true, unless the
/// Box is initialized without argument to build the empty box.
///
/// // Render "true", then "false"
/// let template = try! Template(string:"{{#.}}true{{/.}}{{^.}}false{{/.}}")
/// try! template.render(MustacheBox(boolValue: true))
/// try! template.render(MustacheBox(boolValue: false))
///
///
/// ### keyedSubscript
///
/// The optional `keyedSubscript` parameter is a `KeyedSubscriptFunction`
/// that lets the Mustache engine extract keys out of the box. For example,
/// the `{{a}}` tag would call the subscript function with `"a"` as an
/// argument, and render the returned box.
///
/// The default value is nil, which means that no key can be extracted.
///
/// See `KeyedSubscriptFunction` for a full discussion of this type.
///
/// let box = MustacheBox(keyedSubscript: { (key: String) in
/// return Box("key:\(key)")
/// })
///
/// // Renders "key:a"
/// let template = try! Template(string:"{{a}}")
/// try! template.render(box)
///
///
/// ### filter
///
/// The optional `filter` parameter is a `FilterFunction` that lets the
/// Mustache engine evaluate filtered expression that involve the box. The
/// default value is nil, which means that the box can not be used as
/// a filter.
///
/// See `FilterFunction` for a full discussion of this type.
///
/// let box = MustacheBox(filter: Filter { (x: Int?) in
/// return Box(x! * x!)
/// })
///
/// // Renders "100"
/// let template = try! Template(string:"{{square(x)}}")
/// try! template.render(["square": box, "x": 10])
///
///
/// ### render
///
/// The optional `render` parameter is a `RenderFunction` that is evaluated
/// when the Box is rendered.
///
/// The default value is nil, which makes the box perform default Mustache
/// rendering:
///
/// - `{{box}}` renders the built-in Swift String Interpolation of the value,
/// HTML-escaped.
///
/// - `{{{box}}}` renders the built-in Swift String Interpolation of the
/// value, not HTML-escaped.
///
/// - `{{#box}}...{{/box}}` does not render if `boolValue` is false.
/// Otherwise, it pushes the box on the top of the context stack, and
/// renders the section once.
///
/// - `{{^box}}...{{/box}}` renders once if `boolValue` is false. Otherwise,
/// it does not render.
///
/// See `RenderFunction` for a full discussion of this type.
///
/// let box = MustacheBox(render: { (info: RenderingInfo) in
/// return Rendering("foo")
/// })
///
/// // Renders "foo"
/// let template = try! Template(string:"{{.}}")
/// try! template.render(box)
///
///
/// ### willRender, didRender
///
/// The optional `willRender` and `didRender` parameters are a
/// `WillRenderFunction` and `DidRenderFunction` that are evaluated for all
/// tags as long as the box is in the context stack.
///
/// See `WillRenderFunction` and `DidRenderFunction` for a full discussion of
/// those types.
///
/// let box = MustacheBox(willRender: { (tag: Tag, box: MustacheBox) in
/// return Box("baz")
/// })
///
/// // Renders "baz baz"
/// let template = try! Template(string:"{{#.}}{{foo}} {{bar}}{{/.}}")
/// try! template.render(box)
///
///
/// ### Multi-facetted boxes
///
/// By mixing all those parameters, you can finely tune the behavior of
/// a box.
///
/// GRMustache source code ships a few multi-facetted boxes, which may
/// inspire you. See for example:
///
/// - Formatter.mustacheBox
/// - HTMLEscape.mustacheBox
/// - StandardLibrary.Localizer.mustacheBox
///
/// Let's give an example:
///
/// // A regular type:
///
/// struct Person {
/// let firstName: String
/// let lastName: String
/// }
///
/// We want:
///
/// 1. `{{person.firstName}}` and `{{person.lastName}}` should render the
/// matching properties.
/// 2. `{{person}}` should render the concatenation of the first and last names.
///
/// We'll provide a `KeyedSubscriptFunction` to implement 1, and a
/// `RenderFunction` to implement 2:
///
/// // Have Person conform to MustacheBoxable so that we can box people, and
/// // render them:
///
/// extension Person : MustacheBoxable {
///
/// // MustacheBoxable protocol requires objects to implement this property
/// // and return a MustacheBox:
///
/// var mustacheBox: MustacheBox {
///
/// // A person is a multi-facetted object:
/// return MustacheBox(
/// // It has a value:
/// value: self,
///
/// // It lets Mustache extracts properties by name:
/// keyedSubscript: { (key: String) -> Any? in
/// switch key {
/// case "firstName": return self.firstName
/// case "lastName": return self.lastName
/// default: return nil
/// }
/// },
///
/// // It performs custom rendering:
/// render: { (info: RenderingInfo) -> Rendering in
/// switch info.tag.type {
/// case .variable:
/// // {{ person }}
/// return Rendering("\(self.firstName) \(self.lastName)")
/// case .section:
/// // {{# person }}...{{/}}
/// //
/// // Perform the default rendering: push self on the top
/// // of the context stack, and render the section:
/// let context = info.context.extendedContext(Box(self))
/// return try info.tag.render(context)
/// }
/// }
/// )
/// }
/// }
///
/// // Renders "The person is Errol Flynn"
/// let person = Person(firstName: "Errol", lastName: "Flynn")
/// let template = try! Template(string: "{{# person }}The person is {{.}}{{/ person }}")
/// try! template.render(["person": person])
///
/// - parameter value: An optional boxed value.
/// - parameter boolValue: An optional boolean value for the Box.
/// - parameter keyedSubscript: An optional `KeyedSubscriptFunction`.
/// - parameter filter: An optional `FilterFunction`.
/// - parameter render: An optional `RenderFunction`.
/// - parameter willRender: An optional `WillRenderFunction`.
/// - parameter didRender: An optional `DidRenderFunction`.
/// - returns: A MustacheBox.
public convenience init(
value: Any? = nil,
boolValue: Bool? = nil,
keyedSubscript: KeyedSubscriptFunction? = nil,
filter: FilterFunction? = nil,
render: RenderFunction? = nil,
willRender: WillRenderFunction? = nil,
didRender: DidRenderFunction? = nil)
{
self.init(
converter: nil,
value: value,
boolValue: boolValue,
keyedSubscript: keyedSubscript,
filter: filter,
render: render,
willRender: willRender,
didRender: didRender)
}
// -------------------------------------------------------------------------
// MARK: - Internal
let keyedSubscript: KeyedSubscriptFunction?
let converter: Converter?
init(
converter: Converter?,
value: Any? = nil,
boolValue: Bool? = nil,
keyedSubscript: KeyedSubscriptFunction? = nil,
filter: FilterFunction? = nil,
render: RenderFunction? = nil,
willRender: WillRenderFunction? = nil,
didRender: DidRenderFunction? = nil)
{
let empty = (value == nil) && (keyedSubscript == nil) && (render == nil) && (filter == nil) && (willRender == nil) && (didRender == nil)
self.isEmpty = empty
self.value = value
self.converter = converter
self.boolValue = boolValue ?? !empty
self.keyedSubscript = keyedSubscript
self.filter = filter
self.willRender = willRender
self.didRender = didRender
if let render = render {
self.hasCustomRenderFunction = true
self._render = render
super.init()
} else {
// The default render function: it renders {{variable}} tags as the
// boxed value, and {{#section}}...{{/}} tags by adding the box to
// the context stack.
//
// IMPLEMENTATIN NOTE
//
// We have to set self.render twice in order to avoid the compiler
// error: "variable 'self.render' captured by a closure before being
// initialized"
self._render = { (_) in return Rendering("") }
self.hasCustomRenderFunction = false
super.init()
self._render = { [unowned self] (info: RenderingInfo) in
// Default rendering depends on the tag type:
switch info.tag.type {
case .variable:
// {{ box }} and {{{ box }}}
if let value = self.value {
// Use the built-in Swift String Interpolation:
return Rendering("\(value)", .text)
} else {
return Rendering("", .text)
}
case .section:
// {{# box }}...{{/ box }}
// Push the value on the top of the context stack:
let context = info.context.extendedContext(self)
// Renders the inner content of the section tag:
return try info.tag.render(context)
}
}
}
}
fileprivate let hasCustomRenderFunction: Bool
// Converter wraps all the conversion closures that help MustacheBox expose
// its raw value (typed Any) as useful types.
struct Converter {
let arrayValue: (() -> [MustacheBox]?)
let dictionaryValue: (() -> [String: MustacheBox]?)
init(
arrayValue: (() -> [MustacheBox])? = nil,
dictionaryValue: (() -> [String: MustacheBox]?)? = nil)
{
self.arrayValue = arrayValue ?? { nil }
self.dictionaryValue = dictionaryValue ?? { nil }
}
}
}
extension MustacheBox {
/// A textual representation of `self`.
override public var description: String {
let facets = self.facetsDescriptions
switch facets.count {
case 0:
return "MustacheBox(Empty)"
default:
let content = facets.joined(separator: ",")
return "MustacheBox(\(content))"
}
}
}
extension MustacheBox {
/// A textual representation of the boxed value. Useful for debugging.
public var valueDescription: String {
let facets = self.facetsDescriptions
switch facets.count {
case 0:
return "Empty"
case 1:
return facets.first!
default:
return "(" + facets.joined(separator: ",") + ")"
}
}
var facetsDescriptions: [String] {
var facets = [String]()
if let array = arrayValue {
let items = array.map { $0.valueDescription }.joined(separator: ",")
facets.append("[\(items)]")
} else if let dictionary = dictionaryValue {
if dictionary.isEmpty {
facets.append("[:]")
} else {
let items = dictionary.map { (key, box) in
return "\(String(reflecting: key)):\(box.valueDescription)"
}.joined(separator: ",")
facets.append("[\(items)]")
}
} else if let value = value {
facets.append(String(reflecting: value))
}
if let _ = filter {
facets.append("FilterFunction")
}
if let _ = willRender {
facets.append("WillRenderFunction")
}
if let _ = didRender {
facets.append("DidRenderFunction")
}
if value == nil && hasCustomRenderFunction {
facets.append("RenderFunction")
}
return facets
}
}
| mit | b14fc234c884e3fc7a5588439423755f | 37.007143 | 144 | 0.541393 | 4.841674 | false | false | false | false |
Avenroot/Yaz | Source/Yaz for Android/yazDice.swift | 1 | 1101 | public class yazDice: android.widget.ImageView {
var Locked = false
var Value = 0
let ytimer = yazTimer(1 * 1000, 100)
func Roll( timerOnFinishHandler: ()->() ) {
ytimer.onTickCallback = timerOnTickHandler // would be nice to put this in an init{}
ytimer.OnFinishCallback = { timerOnFinishHandler() }
ytimer.start()
}
func timerOnTickHandler() {
if !Locked {
let rand = Random()
var r = rand.NextInt(6)
Value = r + 1 // Zero Indexed and need the real value of the dice
var dice = diceNumberImages()
let drawableID = Context
.getResources()
.getIdentifier(dice[r], "drawable", Context.getPackageName())
self.setImageResource(drawableID)
}
}
func timerOnFinishHandler() -> Int32 {
return Value
}
private func diceNumberImages() -> [Integer: String]{
return [
0: "dice1",
1: "dice2",
2: "dice3",
3: "dice4",
4: "dice5",
5: "dice6"
]
}
} | mit | 47926305120c8a5c03e15fcb46a0fa77 | 23.444444 | 93 | 0.540491 | 3.981884 | false | false | false | false |
clwm01/RTKitDemo | RCToolsDemo/RCToolsDemo/MenuViewController.swift | 2 | 5842 | //
// MenuViewController.swift
// RCToolsDemo
//
// Created by Rex Tsao on 5/19/16.
// Copyright © 2016 rexcao. All rights reserved.
//
import UIKit
class MenuViewController: UIViewController {
private var table: UITableView?
private let list = ["custom menu button", "cell1", "cell2"]
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.whiteColor()
self.attachTable()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private func attachTable() {
self.table = UITableView(frame: self.view.bounds)
self.table?.delegate = self
self.table?.dataSource = self
self.table?.registerClass(UITableViewCell.self, forCellReuseIdentifier: "menu")
self.table?.tableFooterView = UIView()
// self.table?.separatorInset = UIEdgeInsetsZero
// self.table?.separatorStyle = UITableViewCellSeparatorStyle.SingleLine
self.view.addSubview(self.table!)
}
func handleLongPress(recognizer: UILongPressGestureRecognizer) {
if recognizer.state == .Began {
let cell = recognizer.view as! UITableViewCell
// if (cell as? UITableViewCell) != nil {
// RTPrint.shareInstance().prt("you hint cell")
// }
cell.becomeFirstResponder()
let headPhone = UIMenuItem(title: "headPhone", action: #selector(MenuViewController.headPhone(_:)))
let speaker = UIMenuItem(title: "speaker", action: #selector(MenuViewController.speaker(_:)))
let menu = UIMenuController.sharedMenuController()
menu.menuItems = [headPhone, speaker]
menu.setTargetRect(cell.frame, inView: cell.superview!)
menu.setMenuVisible(true, animated: true)
}
}
func handleLongPress1(recognizer: UILongPressGestureRecognizer) {
if recognizer.state == .Began {
let cell = recognizer.view as! UITableViewCell
// if (cell as? UITableViewCell) != nil {
// RTPrint.shareInstance().prt("you hint cell")
// }
cell.becomeFirstResponder()
let headPhone = UIMenuItem(title: "headPhone11", action: #selector(MenuViewController.headPhone(_:)))
let speaker = UIMenuItem(title: "speaker11", action: #selector(MenuViewController.speaker(_:)))
let menu = UIMenuController.sharedMenuController()
menu.menuItems = [headPhone, speaker]
menu.setTargetRect(cell.frame, inView: cell.superview!)
menu.setMenuVisible(true, animated: true)
}
}
override func canBecomeFirstResponder() -> Bool {
return true
}
func headPhone(sender: UIMenuItem) {
RTPrint.shareInstance().prt("tapped headPhone")
}
func speaker(sender: UIMenuItem) {
RTPrint.shareInstance().prt("tapped speaker")
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
RTPrint.shareInstance().prt(touches.first?.view)
if (touches.first?.view as? UITableViewCell) != nil {
RTPrint.shareInstance().prt("cell")
}
}
}
extension MenuViewController: UITableViewDelegate, UITableViewDataSource {
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
// Three methos below used to handle copy.
// Tell delegate to perform a copy or paste action.
// func tableView(tableView: UITableView, performAction action: Selector, forRowAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) {
// let board = UIPasteboard.generalPasteboard()
// board.string = self.list[indexPath.row]
// }
//
// func tableView(tableView: UITableView, canPerformAction action: Selector, forRowAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) -> Bool {
// if action == #selector(NSObject.copy(_:)) {
// return true
// }
// return false
// }
//
// // Ask the delegate whether the editing menu should show in a certain row.
// func tableView(tableView: UITableView, shouldShowMenuForRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// return true
// }
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.list.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("menu")! as UITableViewCell
cell.textLabel?.text = self.list[indexPath.row]
if indexPath.row == 1 {
let longGR = UILongPressGestureRecognizer(target: self, action: #selector(MenuViewController.handleLongPress1(_:)))
// cell.userInteractionEnabled = true
cell.separatorInset = UIEdgeInsetsZero
cell.addGestureRecognizer(longGR)
} else {
let longGR = UILongPressGestureRecognizer(target: self, action: #selector(MenuViewController.handleLongPress(_:)))
// cell.userInteractionEnabled = true
cell.separatorInset = UIEdgeInsetsZero
cell.addGestureRecognizer(longGR)
}
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
if indexPath.row == 0 {
self.navigationController?.pushViewController(MenuCustomCellViewController(), animated: true)
}
}
}
| mit | d9668ab6fcf8f226fd2b00e77728a58f | 37.94 | 162 | 0.637048 | 5.224508 | false | false | false | false |
ivankorobkov/net | swift/Netx/IO.swift | 2 | 2201 | //
// IO.swift
// Netx
//
// Created by Ivan Korobkov on 12/02/16.
// Copyright © 2016 Ivan Korobkov. All rights reserved.
//
import Foundation
let readChunkLen = (1 << 12) // 4Kb
let readAllMaxLength = (1 << 24) // 16Mb
public protocol Reader {
// Read data into a buffer up to its length.
func read(data: NSMutableData, callback: ReadCallback)
}
public protocol Writer {
// Write all data from a buffer.
func write(data: NSData, callback: WriteCallback)
}
public protocol Closer {
func close()
}
public typealias ReadWriter = protocol<Reader, Writer>
public typealias ReadCloser = protocol<Reader, Closer>
public typealias WriteCloser = protocol<Writer, Closer>
public typealias ReadWriteCloser = protocol<Reader, Writer, Closer>
public typealias ReadCallback = (Int, ErrorType?) -> Void
public typealias WriteCallback = (Int, ErrorType?) -> Void
public typealias CloseCallback = (ErrorType?) -> Void
// AnonymousCloser allows to use a closure as a closer callback.
public class AnonymousCloser: Closer {
private let callback: () -> Void
public init(callback: () -> Void) {
self.callback = callback
}
public func close() {
self.callback()
}
}
// SettableCloser can be used as a future closer.
public class SettableCloser: Closer {
private let queue: dispatch_queue_t
private var closer: Closer?
private var closed: Bool
public init() {
self.queue = dispatch_queue_create("com.github.ivankorobkov.netx.SettableCloser", DISPATCH_QUEUE_SERIAL)
self.closer = nil
self.closed = false
}
public func close() {
dispatch_sync(self.queue) {
guard !self.closed else {
return
}
self.closed = true
self.closer?.close()
}
}
public func set(closer: Closer) {
dispatch_sync(self.queue) {
self.closer = closer
if self.closed {
closer.close()
}
}
}
}
public extension SettableCloser {
public func set(callback: () -> Void) {
self.set(AnonymousCloser(callback: callback))
}
}
| apache-2.0 | 0c4ba53543f9e6be0794c590c5969d0f | 22.157895 | 112 | 0.626818 | 4.059041 | false | false | false | false |
Incipia/Elemental | Example/Pods/Bindable/Bindable/Classes/Bindable.swift | 2 | 4689 | //
// Bindable.swift
// GigSalad
//
// Created by Leif Meyer on 2/23/17.
// Copyright © 2017 Incipia. All rights reserved.
//
import Foundation
public enum BindableError: Error {
case invalidKey(name: String)
}
public protocol Bindable: IncKVCompliance, StringBindable {
static var bindableKeys: [Key] { get }
var bindingBlocks: [Key : [((targetObject: AnyObject, rawTargetKey: String)?, Any?) throws -> Bool?]] { get set }
var keysBeingSet: [Key] { get set }
func bind<T: Bindable>(key: Key, to target: T, key targetKey: T.Key) throws
func bindOneWay<T: Bindable>(key: Key, to target: T, key targetKey: T.Key) throws
func unbind<T: Bindable>(key: Key, to target: T, key targetKey: T.Key)
func unbindOneWay<T: Bindable>(key: Key, to target: T, key targetKey: T.Key)
func setBoundValue(_ value: Any?, for key: Key) throws
func setOwn(value: Any?, for key: Key) throws
func handleBindingError(_ error: Error, value: Any?, key: Key)
}
public extension Bindable {
static var bindableKeys: [Key] { return Key.all }
func bind<T: Bindable>(key: Key, to target: T, key targetKey: T.Key) throws {
guard Self.bindableKeys.contains(key) else { throw BindableError.invalidKey(name: key.rawValue) }
try target.bindOneWay(key: targetKey, to: self, key: key)
_bindOneWay(key: key, to: target, key: targetKey)
}
func bindOneWay<T: Bindable>(key: Key, to target: T, key targetKey: T.Key) throws {
guard Self.bindableKeys.contains(key) else { throw BindableError.invalidKey(name: key.rawValue) }
try target.set(value: value(for: key), for: targetKey)
_bindOneWay(key: key, to: target, key: targetKey)
}
func _bindOneWay<T: Bindable>(key: Key, to target: T, key targetKey: T.Key) {
let bindingBlock = { (match: (targetObject: AnyObject, rawTargetKey: String)?, value: Any?) -> Bool? in
if let (matchTarget, matchRawTargetKey) = match { return matchTarget === target && matchRawTargetKey == targetKey.rawValue}
try target.set(value: value, for: targetKey)
return nil
}
if var existingBindings = bindingBlocks[key] {
existingBindings.append(bindingBlock)
bindingBlocks[key] = existingBindings
} else {
bindingBlocks[key] = [bindingBlock]
}
}
func unbind<T: Bindable>(key: Key, to target: T, key targetKey: T.Key) {
target.unbindOneWay(key: targetKey, to: self, key: key)
unbindOneWay(key: key, to: target, key: targetKey)
}
func unbindOneWay<T: Bindable>(key: Key, to target: T, key targetKey: T.Key) {
let match = (targetObject: target as AnyObject, rawTargetKey: targetKey.rawValue)
bindingBlocks[key] = bindingBlocks[key]?.filter { !(try! $0(match, nil)!) }
}
func setBoundValue(_ value: Any?, for key: Key) throws {
guard !keysBeingSet.contains(key) else { return }
keysBeingSet.append(key)
defer { finishedSetting(bindableKey: key) }
guard let bindings = bindingBlocks[key] else { return }
try bindings.forEach { let _ = try $0(nil, value) }
}
func shouldSet(bindableKey: Key) -> Bool {
return !keysBeingSet.contains(bindableKey)
}
func finishedSetting(bindableKey: Key) {
if bindableKey == keysBeingSet.first { keysBeingSet = [] }
}
func handleBindingError(_ error: Error, value: Any?, key: Key) { fatalError("Binding error: Setting \(String(describing: value)) for \(key) threw \(error)") }
func set(value: Any?, for key: Key) throws {
try setAsBindable(value: value, for: key)
}
func setAsBindable(value: Any?, for key: Key) throws {
guard Self.bindableKeys.contains(key) else { try setOwn(value: value, for: key); return }
guard shouldSet(bindableKey: key) else { return }
try setOwn(value: value, for: key)
try setBoundValue(value, for: key)
}
public func trySetBoundValue(_ value: Any?, for key: Key) {
do { try setBoundValue(value, for: key) }
catch { handleBindingError(error, value: value, key: key) }
}
func value(for key: String) -> Any? {
guard let key = try? Key(keyString: key) else { return nil }
return value(for: key)
}
func set(value: Any?, for key: String) throws {
let key = try Key(keyString: key)
try set(value: value, for: key)
}
}
public func IncIterateEnum<T: Hashable>(_: T.Type) -> AnyIterator<T> {
var i = 0
return AnyIterator {
let next = withUnsafePointer(to: &i) {
$0.withMemoryRebound(to: T.self, capacity: 1) { $0.pointee }
}
if next.hashValue != i { return nil }
i += 1
return next
}
}
| mit | 663f19bed56715195ff8d567f32874f8 | 36.806452 | 161 | 0.647398 | 3.584098 | false | false | false | false |
alessiobrozzi/firefox-ios | SyncTests/HistorySynchronizerTests.swift | 2 | 8871 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Shared
import Storage
@testable import Sync
import XCGLogger
import Deferred
import XCTest
import SwiftyJSON
private let log = Logger.syncLogger
class MockSyncDelegate: SyncDelegate {
func displaySentTabForURL(_ URL: URL, title: String) {
}
}
class DBPlace: Place {
var isDeleted = false
var shouldUpload = false
var serverModified: Timestamp?
var localModified: Timestamp?
}
class MockSyncableHistory {
var wasReset: Bool = false
var places = [GUID: DBPlace]()
var remoteVisits = [GUID: Set<Visit>]()
var localVisits = [GUID: Set<Visit>]()
init() {
}
fileprivate func placeForURL(url: String) -> DBPlace? {
return findOneValue(places) { $0.url == url }
}
}
extension MockSyncableHistory: ResettableSyncStorage {
func resetClient() -> Success {
self.wasReset = true
return succeed()
}
}
extension MockSyncableHistory: SyncableHistory {
// TODO: consider comparing the timestamp to local visits, perhaps opting to
// not delete the local place (and instead to give it a new GUID) if the visits
// are newer than the deletion.
// Obviously this'll behave badly during reconciling on other devices:
// they might apply our new record first, renaming their local copy of
// the old record with that URL, and thus bring all the old visits back to life.
// Desktop just finds by GUID then deletes by URL.
func deleteByGUID(_ guid: GUID, deletedAt: Timestamp) -> Deferred<Maybe<()>> {
self.remoteVisits.removeValue(forKey: guid)
self.localVisits.removeValue(forKey: guid)
self.places.removeValue(forKey: guid)
return succeed()
}
func hasSyncedHistory() -> Deferred<Maybe<Bool>> {
let has = self.places.values.contains(where: { $0.serverModified != nil })
return deferMaybe(has)
}
/**
* This assumes that the provided GUID doesn't already map to a different URL!
*/
func ensurePlaceWithURL(_ url: String, hasGUID guid: GUID) -> Success {
// Find by URL.
if let existing = self.placeForURL(url: url) {
let p = DBPlace(guid: guid, url: url, title: existing.title)
p.isDeleted = existing.isDeleted
p.serverModified = existing.serverModified
p.localModified = existing.localModified
self.places.removeValue(forKey: existing.guid)
self.places[guid] = p
}
return succeed()
}
func storeRemoteVisits(_ visits: [Visit], forGUID guid: GUID) -> Success {
// Strip out existing local visits.
// We trust that an identical timestamp and type implies an identical visit.
var remote = Set<Visit>(visits)
if let local = self.localVisits[guid] {
remote.subtract(local)
}
// Visits are only ever added.
if var r = self.remoteVisits[guid] {
r.formUnion(remote)
} else {
self.remoteVisits[guid] = remote
}
return succeed()
}
func insertOrUpdatePlace(_ place: Place, modified: Timestamp) -> Deferred<Maybe<GUID>> {
// See if we've already applied this one.
if let existingModified = self.places[place.guid]?.serverModified {
if existingModified == modified {
log.debug("Already seen unchanged record \(place.guid).")
return deferMaybe(place.guid)
}
}
// Make sure that we collide with any matching URLs -- whether locally
// modified or not. Then overwrite the upstream and merge any local changes.
return self.ensurePlaceWithURL(place.url, hasGUID: place.guid)
>>> {
if let existingLocal = self.places[place.guid] {
if existingLocal.shouldUpload {
log.debug("Record \(existingLocal.guid) modified locally and remotely.")
log.debug("Local modified: \(existingLocal.localModified); remote: \(modified).")
// Should always be a value if marked as changed.
if existingLocal.localModified! > modified {
// Nothing to do: it's marked as changed.
log.debug("Discarding remote non-visit changes!")
self.places[place.guid]?.serverModified = modified
return deferMaybe(place.guid)
} else {
log.debug("Discarding local non-visit changes!")
self.places[place.guid]?.shouldUpload = false
}
} else {
log.debug("Remote record exists, but has no local changes.")
}
} else {
log.debug("Remote record doesn't exist locally.")
}
// Apply the new remote record.
let p = DBPlace(guid: place.guid, url: place.url, title: place.title)
p.localModified = Date.now()
p.serverModified = modified
p.isDeleted = false
self.places[place.guid] = p
return deferMaybe(place.guid)
}
}
func getModifiedHistoryToUpload() -> Deferred<Maybe<[(Place, [Visit])]>> {
// TODO.
return deferMaybe([])
}
func getDeletedHistoryToUpload() -> Deferred<Maybe<[GUID]>> {
// TODO.
return deferMaybe([])
}
func markAsSynchronized(_: [GUID], modified: Timestamp) -> Deferred<Maybe<Timestamp>> {
// TODO
return deferMaybe(0)
}
func markAsDeleted(_: [GUID]) -> Success {
// TODO
return succeed()
}
func onRemovedAccount() -> Success {
// TODO
return succeed()
}
func doneApplyingRecordsAfterDownload() -> Success {
return succeed()
}
func doneUpdatingMetadataAfterUpload() -> Success {
return succeed()
}
}
class HistorySynchronizerTests: XCTestCase {
private func applyRecords(records: [Record<HistoryPayload>], toStorage storage: SyncableHistory & ResettableSyncStorage) -> (synchronizer: HistorySynchronizer, prefs: Prefs, scratchpad: Scratchpad) {
let delegate = MockSyncDelegate()
// We can use these useless values because we're directly injecting decrypted
// payloads; no need for real keys etc.
let prefs = MockProfilePrefs()
let scratchpad = Scratchpad(b: KeyBundle.random(), persistingTo: prefs)
let synchronizer = HistorySynchronizer(scratchpad: scratchpad, delegate: delegate, basePrefs: prefs)
let expectation = self.expectation(description: "Waiting for application.")
var succeeded = false
synchronizer.applyIncomingToStorage(storage, records: records)
.upon({ result in
succeeded = result.isSuccess
expectation.fulfill()
})
waitForExpectations(timeout: 10, handler: nil)
XCTAssertTrue(succeeded, "Application succeeded.")
return (synchronizer, prefs, scratchpad)
}
func testApplyRecords() {
let earliest = Date.now()
let empty = MockSyncableHistory()
let noRecords = [Record<HistoryPayload>]()
// Apply no records.
self.applyRecords(records: noRecords, toStorage: empty)
// Hey look! Nothing changed.
XCTAssertTrue(empty.places.isEmpty)
XCTAssertTrue(empty.remoteVisits.isEmpty)
XCTAssertTrue(empty.localVisits.isEmpty)
// Apply one remote record.
let jA = "{\"id\":\"aaaaaa\",\"histUri\":\"http://foo.com/\",\"title\": \"ñ\",\"visits\":[{\"date\":1222222222222222,\"type\":1}]}"
let pA = HistoryPayload.fromJSON(JSON(parseJSON: jA))!
let rA = Record<HistoryPayload>(id: "aaaaaa", payload: pA, modified: earliest + 10000, sortindex: 123, ttl: 1000000)
let (_, prefs, _) = self.applyRecords(records: [rA], toStorage: empty)
// The record was stored. This is checking our mock implementation, but real storage should work, too!
XCTAssertEqual(1, empty.places.count)
XCTAssertEqual(1, empty.remoteVisits.count)
XCTAssertEqual(1, empty.remoteVisits["aaaaaa"]!.count)
XCTAssertTrue(empty.localVisits.isEmpty)
// Test resetting now that we have a timestamp.
XCTAssertFalse(empty.wasReset)
XCTAssertTrue(HistorySynchronizer.resetSynchronizerWithStorage(empty, basePrefs: prefs, collection: "history").value.isSuccess)
XCTAssertTrue(empty.wasReset)
}
}
| mpl-2.0 | 5f62b2afa447b24a9f8968e16cac8b8c | 35.958333 | 203 | 0.61274 | 4.919578 | false | false | false | false |
sora0077/AppleMusicKit | Demo/AppDelegate.swift | 1 | 2605 | //
// AppDelegate.swift
// Demo
//
// Created by 林達也 on 2017/06/28.
// Copyright © 2017年 jp.sora0077. All rights reserved.
//
import UIKit
import AppleMusicKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
window = UIWindow(frame: UIScreen.main.bounds)
window?.rootViewController = UINavigationController(rootViewController: TopViewController())
window?.makeKeyAndVisible()
window?.tintColor = UIColor(hex: 0x7A69F2)
if let token = UserDefaults.standard.string(forKey: "DeveloperToken") {
Session.shared.authorization = Authorization(developerToken: token)
}
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 invalidate graphics rendering callbacks. 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 active 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:.
}
}
| mit | 9b3405e10d5fcd4764c1ae2432f2ce1e | 48.923077 | 285 | 0.744607 | 5.5 | false | false | false | false |
wireapp/wire-ios | Wire-iOS/Sources/UserInterface/LegalHoldDetails/Sections/LegalHoldParticipantsSectionController.swift | 1 | 4460 | //
// Wire
// Copyright (C) 2019 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
import WireSyncEngine
private struct LegalHoldParticipantsSectionViewModel {
let participants: [UserType]
var sectionAccesibilityIdentifier = "label.groupdetails.participants"
var sectionTitle: String {
return "legalhold.participants.section.title".localized(uppercased: true, args: participants.count)
}
init(participants: [UserType]) {
self.participants = participants
}
}
protocol LegalHoldParticipantsSectionControllerDelegate: AnyObject {
func legalHoldParticipantsSectionWantsToPresentUserProfile(for user: UserType)
}
typealias LegalHoldDetailsConversation = Conversation & GroupDetailsConversation
private extension ConversationLike {
func createViewModel() -> LegalHoldParticipantsSectionViewModel {
return LegalHoldParticipantsSectionViewModel(participants: sortedActiveParticipantsUserTypes.filter(\.isUnderLegalHold))
}
}
final class LegalHoldParticipantsSectionController: GroupDetailsSectionController {
fileprivate weak var collectionView: UICollectionView?
private var viewModel: LegalHoldParticipantsSectionViewModel
private let conversation: LegalHoldDetailsConversation
private var token: AnyObject?
weak var delegate: LegalHoldParticipantsSectionControllerDelegate?
init(conversation: LegalHoldDetailsConversation) {
viewModel = conversation.createViewModel()
self.conversation = conversation
super.init()
if let userSession = ZMUserSession.shared() {
token = UserChangeInfo.add(userObserver: self, in: userSession)
}
}
private func setupViewModel() {
viewModel = LegalHoldParticipantsSectionViewModel(participants: conversation.sortedActiveParticipantsUserTypes.filter(\.isUnderLegalHold))
}
override func prepareForUse(in collectionView: UICollectionView?) {
super.prepareForUse(in: collectionView)
collectionView?.register(UserCell.self, forCellWithReuseIdentifier: UserCell.reuseIdentifier)
self.collectionView = collectionView
}
override var sectionTitle: String {
return viewModel.sectionTitle
}
override var sectionAccessibilityIdentifier: String {
return viewModel.sectionAccesibilityIdentifier
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return viewModel.participants.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let participant = viewModel.participants[indexPath.row]
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: UserCell.reuseIdentifier, for: indexPath) as! UserCell
let showSeparator = (viewModel.participants.count - 1) != indexPath.row
cell.configure(with: participant, selfUser: SelfUser.current, conversation: conversation)
cell.accessoryIconView.isHidden = false
cell.accessibilityIdentifier = "participants.section.participants.cell"
cell.showSeparator = showSeparator
return cell
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let user = viewModel.participants[indexPath.row]
delegate?.legalHoldParticipantsSectionWantsToPresentUserProfile(for: user)
}
}
extension LegalHoldParticipantsSectionController: ZMUserObserver {
func userDidChange(_ changeInfo: UserChangeInfo) {
guard changeInfo.connectionStateChanged || changeInfo.nameChanged || changeInfo.isUnderLegalHoldChanged else { return }
viewModel = conversation.createViewModel()
collectionView?.reloadData()
}
}
| gpl-3.0 | 6cab1bf4f7189fd3d622ae9b9a7b9c8d | 35.260163 | 146 | 0.757399 | 5.425791 | false | false | false | false |
haoking/SwiftyUI | Sources/ImageSettable.swift | 1 | 740 | //
// BackgroundImagable.swift
// WHCWSIFT
//
// Created by Haochen Wang on 10/1/17.
// Copyright © 2017 Haochen Wang. All rights reserved.
//
import UIKit
public protocol ImageSettable: AnyObject
{
var backgroundImage: UIImage? { get set }
}
public extension ImageSettable where Self: UIView
{
var backgroundImage: UIImage? {
get {
guard let obj = layer.contents else { return nil }
return UIImage(cgImage: obj as! CGImage)
}
set {
layer.contents = newValue?.cgImage
if newValue?.isOpaque == true
{
isOpaque = true
}
else
{
updateOpaque()
}
}
}
}
| mit | 3119faaecdd11f6ae420360548fbbebe | 20.114286 | 62 | 0.538566 | 4.451807 | false | false | false | false |
Pluto-tv/RxSwift | RxSwift/Observables/Observable+Binding.swift | 1 | 5934 | //
// Observable+Binding.swift
// Rx
//
// Created by Krunoslav Zaher on 3/1/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
// multicast
extension ObservableType {
/**
Multicasts the source sequence notifications through the specified subject to the resulting connectable observable.
Upon connection of the connectable observable, the subject is subscribed to the source exactly one, and messages are forwarded to the observers registered with the connectable observable.
For specializations with fixed subject types, see `publish` and `replay`.
- parameter subject: Subject to push source elements into.
- returns: A connectable observable sequence that upon connection causes the source sequence to push results into the specified subject.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func multicast<S: SubjectType where S.SubjectObserverType.E == E>(subject: S)
-> ConnectableObservable<S> {
return ConnectableObservable(source: self.asObservable(), subject: subject)
}
/**
Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function.
Each subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's invocation.
For specializations with fixed subject types, see `publish` and `replay`.
- parameter subjectSelector: Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function.
- parameter selector: Selector function which can use the multicasted source sequence subject to the policies enforced by the created subject.
- returns: An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func multicast<S: SubjectType, R where S.SubjectObserverType.E == E>(subjectSelector: () throws -> S, selector: (Observable<S.E>) throws -> Observable<R>)
-> Observable<R> {
return Multicast(
source: self.asObservable(),
subjectSelector: subjectSelector,
selector: selector
)
}
}
// publish
extension ObservableType {
/**
Returns a connectable observable sequence that shares a single subscription to the underlying sequence.
This operator is a specialization of `multicast` using a `PublishSubject`.
- returns: A connectable observable sequence that shares a single subscription to the underlying sequence.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func publish() -> ConnectableObservable<PublishSubject<E>> {
return self.multicast(PublishSubject())
}
}
// replay
extension ObservableType {
/**
Returns a connectable observable sequence that shares a single subscription to the underlying sequence replaying bufferSize elements.
This operator is a specialization of `multicast` using a `ReplaySubject`.
- parameter bufferSize: Maximum element count of the replay buffer.
- returns: A connectable observable sequence that shares a single subscription to the underlying sequence.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func replay(bufferSize: Int)
-> ConnectableObservable<ReplaySubject<E>> {
return self.multicast(ReplaySubject.create(bufferSize: bufferSize))
}
}
// refcount
extension ConnectableObservableType {
/**
Returns an observable sequence that stays connected to the source as long as there is at least one subscription to the observable sequence.
- returns: An observable sequence that stays connected to the source as long as there is at least one subscription to the observable sequence.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func refCount() -> Observable<E> {
return RefCount(source: self)
}
}
// share
extension ObservableType {
/**
Returns an observable sequence that shares a single subscription to the underlying sequence.
This operator is a specialization of publish which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
- returns: An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func share() -> Observable<E> {
return self.publish().refCount()
}
}
// shareReplay
extension ObservableType {
/**
Returns an observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer.
This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
- parameter bufferSize: Maximum element count of the replay buffer.
- returns: An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func shareReplay(bufferSize: Int)
-> Observable<E> {
if bufferSize == 1 {
return ShareReplay1(source: self.asObservable())
}
else {
return self.replay(bufferSize).refCount()
}
}
} | mit | 2fd1a2fbe4138f53cc566dbc7e7bdecf | 40.503497 | 281 | 0.72093 | 5.067464 | false | false | false | false |
LunaGao/cnblogs-Mac-Swift | CNBlogsForMac/Blogs/CNBBlogListCell.swift | 1 | 1997 | //
// CNBBlogListCell.swift
// CNBlogsForMac
//
// Created by Luna Gao on 15/11/25.
// Copyright © 2015年 gao.luna.com. All rights reserved.
//
import Cocoa
import Alamofire
class CNBBlogListCell: NSTableCellView {
@IBOutlet var TitleTextField: NSTextField!
@IBOutlet var DescriptionTextField: NSTextField!
@IBOutlet var PostDateTextField: NSTextField!
@IBOutlet var ViewCountTextField: NSTextField!
@IBOutlet var CommentCountTextField: NSTextField!
@IBOutlet var DiggCountTextField: NSTextField!
@IBOutlet weak var AuthorTextField: NSTextField!
@IBOutlet weak var UserHeaderImageView: NSImageView!
override func drawRect(dirtyRect: NSRect) {
super.drawRect(dirtyRect)
// Drawing code here.
}
func setData(entity:BlogsListEntity) {
TitleTextField!.stringValue = entity.Title!
DescriptionTextField!.stringValue = entity.Description!
AuthorTextField!.stringValue = entity.Author!
if entity.Avatar != nil {
let escapedAddress = URLEncodedString(entity.Avatar!)
Alamofire.request(.GET, escapedAddress!).response { (request, response, data, error) in
if (error != nil) {
NSLog("%@", error!)
} else {
self.UserHeaderImageView.image = NSImage.init(data:data!)
}
}
}
PostDateTextField!.stringValue = entity.PostDate!.stringByReplacingOccurrencesOfString("T", withString: " ")
ViewCountTextField!.stringValue = "阅读 \(entity.ViewCount!)"
CommentCountTextField!.stringValue = "评论 \(entity.CommentCount!)"
DiggCountTextField!.stringValue = "顶 \(entity.DiggCount!)"
}
func URLEncodedString(urlString:String) -> String? {
let customAllowedSet = NSCharacterSet(charactersInString:" ").invertedSet
return urlString.stringByAddingPercentEncodingWithAllowedCharacters(customAllowedSet)
}
}
| mit | c540a3c82320c346d246c815d5b8d0da | 35.740741 | 116 | 0.668851 | 5.035533 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.