repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
tuzaiz/ConciseCore
refs/heads/dev
src/CCDB.swift
mit
1
// // TZDB.swift // CloudCore // // Created by Henry on 2014/11/22. // Copyright (c) 2014年 Cloudbay. All rights reserved. // import Foundation import CoreData class CCDB : NSObject { lazy var context : NSManagedObjectContext = { var ctx = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.PrivateQueueConcurrencyType) ctx.parentContext = ConciseCore.managedObjectContext return ctx }() internal func save() { var error : NSError? self.context.performBlockAndWait { () -> Void in self.saveToContext(&error) } } internal func save(completion:((NSError?) -> Void)?) { self.context.performBlock { () -> Void in var error : NSError? self.context.performBlock({ () -> Void in self.saveToContext(&error) if let complete = completion { complete(error) } }) } } private func saveToContext(error:NSErrorPointer?) { var error : NSError? self.context.save(&error) var ctx : NSManagedObjectContext? = self.context while var context = ctx?.parentContext { context.save(&error) ctx = context } } }
e2c1ad14ba7be001785275f56bf2565f
26.851064
124
0.580275
false
false
false
false
witekbobrowski/Stanford-CS193p-Winter-2017
refs/heads/master
Smashtag/Smashtag/AppDelegate.swift
mit
1
// // AppDelegate.swift // Smashtag // // Created by Witek on 12/05/2017. // Copyright © 2017 Witek Bobrowski. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. 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:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "Smash") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
2e6ddb5d3df2c4030f299d88c3adb22a
47.989362
285
0.68317
false
false
false
false
JGiola/swift
refs/heads/main
stdlib/private/OSLog/OSLogPrivacy.swift
apache-2.0
14
//===----------------- OSLogPrivacy.swift ---------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 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 // //===----------------------------------------------------------------------===// // This file defines the APIs for specifying privacy in the log messages and also // the logic for encoding them in the byte buffer passed to the libtrace library. /// Privacy options for specifying privacy level of the interpolated expressions /// in the string interpolations passed to the log APIs. @frozen public struct OSLogPrivacy { @usableFromInline internal enum PrivacyOption { case `private` case `public` case auto } public enum Mask { /// Applies a salted hashing transformation to an interpolated value to redact it in the logs. /// /// Its purpose is to permit the correlation of identical values across multiple log lines /// without revealing the value itself. case hash case none } @usableFromInline internal var privacy: PrivacyOption @usableFromInline internal var mask: Mask @_transparent @usableFromInline internal init(privacy: PrivacyOption, mask: Mask) { self.privacy = privacy self.mask = mask } /// Sets the privacy level of an interpolated value to public. /// /// When the privacy level is public, the value will be displayed /// normally without any redaction in the logs. @_semantics("constant_evaluable") @_optimize(none) @inlinable public static var `public`: OSLogPrivacy { OSLogPrivacy(privacy: .public, mask: .none) } /// Sets the privacy level of an interpolated value to private. /// /// When the privacy level is private, the value will be redacted in the logs, /// subject to the privacy configuration of the logging system. @_semantics("constant_evaluable") @_optimize(none) @inlinable public static var `private`: OSLogPrivacy { OSLogPrivacy(privacy: .private, mask: .none) } /// Sets the privacy level of an interpolated value to private and /// applies a `mask` to the interpolated value to redacted it. /// /// When the privacy level is private, the value will be redacted in the logs, /// subject to the privacy configuration of the logging system. /// /// If the value need not be redacted in the logs, its full value is captured as normal. /// Otherwise (i.e. if the value would be redacted) the `mask` is applied to /// the argument value and the result of the transformation is recorded instead. /// /// - Parameters: /// - mask: Mask to use with the privacy option. @_semantics("constant_evaluable") @_optimize(none) @inlinable public static func `private`(mask: Mask) -> OSLogPrivacy { OSLogPrivacy(privacy: .private, mask: mask) } /// Auto-infers a privacy level for an interpolated value. /// /// The system will automatically decide whether the value should /// be captured fully in the logs or should be redacted. @_semantics("constant_evaluable") @_optimize(none) @inlinable public static var auto: OSLogPrivacy { OSLogPrivacy(privacy: .auto, mask: .none) } /// Auto-infers a privacy level for an interpolated value and applies a `mask` /// to the interpolated value to redacted it when necessary. /// /// The system will automatically decide whether the value should /// be captured fully in the logs or should be redacted. /// If the value need not be redacted in the logs, its full value is captured as normal. /// Otherwise (i.e. if the value would be redacted) the `mask` is applied to /// the argument value and the result of the transformation is recorded instead. /// /// - Parameters: /// - mask: Mask to use with the privacy option. @_semantics("constant_evaluable") @_optimize(none) @inlinable public static func auto(mask: Mask) -> OSLogPrivacy { OSLogPrivacy(privacy: .auto, mask: mask) } /// Return an argument flag for the privacy option., as defined by the /// os_log ABI, which occupies four least significant bits of the first byte of the /// argument header. The first two bits are used to indicate privacy and /// the other two are reserved. @inlinable @_semantics("constant_evaluable") @_optimize(none) internal var argumentFlag: UInt8 { switch privacy { case .private: return 0x1 case .public: return 0x2 default: return 0 } } @inlinable @_semantics("constant_evaluable") @_optimize(none) internal var isAtleastPrivate: Bool { switch privacy { case .public: return false case .auto: return false default: return true } } @inlinable @_semantics("constant_evaluable") @_optimize(none) internal var needsPrivacySpecifier: Bool { if case .hash = mask { return true } switch privacy { case .auto: return false default: return true } } @inlinable @_transparent internal var hasMask: Bool { if case .hash = mask { return true } return false } /// A 64-bit value obtained by interpreting the mask name as a little-endian unsigned /// integer. @inlinable @_transparent internal var maskValue: UInt64 { // Return the value of // 'h' | 'a' << 8 | 's' << 16 | 'h' << 24 which equals // 104 | (97 << 8) | (115 << 16) | (104 << 24) 1752392040 } /// Return an os log format specifier for this `privacy` level. The /// format specifier goes within curly braces e.g. %{private} in the format /// string passed to the os log ABI. @inlinable @_semantics("constant_evaluable") @_optimize(none) internal var privacySpecifier: String? { let hasMask = self.hasMask var isAuto = false if case .auto = privacy { isAuto = true } if isAuto, !hasMask { return nil } var specifier: String switch privacy { case .public: specifier = "public" case .private: specifier = "private" default: specifier = "" } if hasMask { if !isAuto { specifier += "," } specifier += "mask.hash" } return specifier } }
ec9f6403fdcb9a17e07a2c0c4064bf45
28.281818
98
0.65756
false
false
false
false
apple/swift-syntax
refs/heads/main
Sources/SwiftParser/Types.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2022 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 // //===----------------------------------------------------------------------===// @_spi(RawSyntax) import SwiftSyntax extension Parser { /// Parse a type. /// /// Grammar /// ======= /// /// type → function-type /// type → array-type /// type → dictionary-type /// type → type-identifier /// type → tuple-type /// type → optional-type /// type → implicitly-unwrapped-optional-type /// type → protocol-composition-type /// type → opaque-type /// type → metatype-type /// type → any-type /// type → self-type /// type → '(' type ')' @_spi(RawSyntax) public mutating func parseType(misplacedSpecifiers: [RawTokenSyntax] = []) -> RawTypeSyntax { let type = self.parseTypeScalar(misplacedSpecifiers: misplacedSpecifiers) // Parse pack expansion 'T...'. if self.currentToken.isEllipsis { let ellipsis = self.consumeAnyToken(remapping: .ellipsis) return RawTypeSyntax( RawPackExpansionTypeSyntax( patternType: type, ellipsis: ellipsis, arena: self.arena)) } return type } mutating func parseTypeScalar(misplacedSpecifiers: [RawTokenSyntax] = []) -> RawTypeSyntax { let (specifier, unexpectedBeforeAttrList, attrList) = self.parseTypeAttributeList(misplacedSpecifiers: misplacedSpecifiers) var base = RawTypeSyntax(self.parseSimpleOrCompositionType()) if self.lookahead().isAtFunctionTypeArrow() { let firstEffect = self.parseEffectsSpecifier() let secondEffect = self.parseEffectsSpecifier() let (unexpectedBeforeArrow, arrow) = self.expect(.arrow) let returnTy = self.parseType() let unexpectedBeforeLeftParen: RawUnexpectedNodesSyntax? let leftParen: RawTokenSyntax let unexpectedBetweenLeftParenAndElements: RawUnexpectedNodesSyntax? let arguments: RawTupleTypeElementListSyntax let unexpectedBetweenElementsAndRightParen: RawUnexpectedNodesSyntax? let rightParen: RawTokenSyntax if let input = base.as(RawTupleTypeSyntax.self) { unexpectedBeforeLeftParen = input.unexpectedBeforeLeftParen leftParen = input.leftParen unexpectedBetweenLeftParenAndElements = input.unexpectedBetweenLeftParenAndElements arguments = input.elements unexpectedBetweenElementsAndRightParen = input.unexpectedBetweenElementsAndRightParen rightParen = input.rightParen } else { unexpectedBeforeLeftParen = nil leftParen = RawTokenSyntax(missing: .leftParen, arena: self.arena) unexpectedBetweenLeftParenAndElements = nil arguments = RawTupleTypeElementListSyntax(elements: [ RawTupleTypeElementSyntax( inOut: nil, name: nil, secondName: nil, colon: nil, type: base, ellipsis: nil, initializer: nil, trailingComma: nil, arena: self.arena) ], arena: self.arena) unexpectedBetweenElementsAndRightParen = nil rightParen = RawTokenSyntax(missing: .rightParen, arena: self.arena) } base = RawTypeSyntax(RawFunctionTypeSyntax( unexpectedBeforeLeftParen, leftParen: leftParen, unexpectedBetweenLeftParenAndElements, arguments: arguments, unexpectedBetweenElementsAndRightParen, rightParen: rightParen, asyncKeyword: firstEffect, throwsOrRethrowsKeyword: secondEffect, unexpectedBeforeArrow, arrow: arrow, returnType: returnTy, arena: self.arena)) } if unexpectedBeforeAttrList != nil || specifier != nil || attrList != nil { return RawTypeSyntax(RawAttributedTypeSyntax( specifier: specifier, unexpectedBeforeAttrList, attributes: attrList, baseType: base, arena: self.arena)) } else { return RawTypeSyntax(base) } } /// Parse a protocol composition involving at least one element. /// /// Grammar /// ======= /// /// type-identifier → type-name generic-argument-clause? | type-name generic-argument-clause? '.' type-identifier /// type-name → identifier /// /// protocol-composition-type → type-identifier '&' protocol-composition-continuation /// protocol-composition-continuation → type-identifier | protocol-composition-type @_spi(RawSyntax) public mutating func parseSimpleOrCompositionType() -> RawTypeSyntax { let someOrAny = self.consume(ifAny: [], contextualKeywords: ["some", "any"]) var base = self.parseSimpleType() guard self.atContextualPunctuator("&") else { if let someOrAny = someOrAny { return RawTypeSyntax(RawConstrainedSugarTypeSyntax( someOrAnySpecifier: someOrAny, baseType: base, arena: self.arena)) } else { return base } } var elements = [RawCompositionTypeElementSyntax]() if let firstAmpersand = self.consumeIfContextualPunctuator("&") { elements.append(RawCompositionTypeElementSyntax( type: base, ampersand: firstAmpersand, arena: self.arena)) var keepGoing: RawTokenSyntax? = nil var loopProgress = LoopProgressCondition() repeat { let elementType = self.parseSimpleType() keepGoing = self.consumeIfContextualPunctuator("&") elements.append(RawCompositionTypeElementSyntax( type: elementType, ampersand: keepGoing, arena: self.arena )) } while keepGoing != nil && loopProgress.evaluate(currentToken) base = RawTypeSyntax(RawCompositionTypeSyntax( elements: RawCompositionTypeElementListSyntax(elements: elements, arena: self.arena), arena: self.arena)) } if let someOrAny = someOrAny { return RawTypeSyntax(RawConstrainedSugarTypeSyntax( someOrAnySpecifier: someOrAny, baseType: base, arena: self.arena)) } else { return base } } /// Parse a "simple" type /// /// Grammar /// ======= /// /// type → type-identifier /// type → tuple-type /// type → array-type /// type → dictionary-type /// type → metatype-type /// /// metatype-type → type '.' 'Type' | type '.' 'Protocol' @_spi(RawSyntax) public mutating func parseSimpleType( stopAtFirstPeriod: Bool = false ) -> RawTypeSyntax { var base: RawTypeSyntax switch self.currentToken.tokenKind { case .capitalSelfKeyword, .anyKeyword, .identifier: base = self.parseTypeIdentifier(stopAtFirstPeriod: stopAtFirstPeriod) case .leftParen: base = RawTypeSyntax(self.parseTupleTypeBody()) case .leftSquareBracket: base = RawTypeSyntax(self.parseCollectionType()) case .wildcardKeyword: base = RawTypeSyntax(self.parsePlaceholderType()) default: return RawTypeSyntax(RawMissingTypeSyntax(arena: self.arena)) } // '.Type', '.Protocol', '?', '!', and '[]' still leave us with type-simple. var loopCondition = LoopProgressCondition() while loopCondition.evaluate(currentToken) { if !stopAtFirstPeriod, let (period, type) = self.consume( if: { [.period, .prefixPeriod].contains($0.tokenKind) }, followedBy: { $0.isContextualKeyword(["Type", "Protocol"])} ) { base = RawTypeSyntax(RawMetatypeTypeSyntax( baseType: base, period: period, typeOrProtocol: type, arena: self.arena)) continue } if !self.currentToken.isAtStartOfLine { if self.currentToken.isOptionalToken { base = RawTypeSyntax(self.parseOptionalType(base)) continue } if self.currentToken.isImplicitlyUnwrappedOptionalToken { base = RawTypeSyntax(self.parseImplicitlyUnwrappedOptionalType(base)) continue } } break } return base } /// Parse an optional type. /// /// Grammar /// ======= /// /// optional-type → type '?' @_spi(RawSyntax) public mutating func parseOptionalType(_ base: RawTypeSyntax) -> RawOptionalTypeSyntax { let (unexpectedBeforeMark, mark) = self.expect(.postfixQuestionMark) return RawOptionalTypeSyntax( wrappedType: base, unexpectedBeforeMark, questionMark: mark, arena: self.arena ) } /// Parse an optional type. /// /// Grammar /// ======= /// /// implicitly-unwrapped-optional-type → type '!' @_spi(RawSyntax) public mutating func parseImplicitlyUnwrappedOptionalType(_ base: RawTypeSyntax) -> RawImplicitlyUnwrappedOptionalTypeSyntax { let (unexpectedBeforeMark, mark) = self.expect(.exclamationMark) return RawImplicitlyUnwrappedOptionalTypeSyntax( wrappedType: base, unexpectedBeforeMark, exclamationMark: mark, arena: self.arena ) } @_spi(RawSyntax) public mutating func parseTypeIdentifier( stopAtFirstPeriod: Bool = false ) -> RawTypeSyntax { if self.at(.anyKeyword) && !stopAtFirstPeriod { return RawTypeSyntax(self.parseAnyType()) } var result: RawTypeSyntax? var keepGoing: RawTokenSyntax? = nil var loopProgress = LoopProgressCondition() repeat { let (name, _) = self.parseDeclNameRef() let generics: RawGenericArgumentClauseSyntax? if self.atContextualPunctuator("<") { generics = self.parseGenericArguments() } else { generics = nil } if let keepGoing = keepGoing { result = RawTypeSyntax(RawMemberTypeIdentifierSyntax( baseType: result!, period: keepGoing, name: name, genericArgumentClause: generics, arena: self.arena)) } else { result = RawTypeSyntax(RawSimpleTypeIdentifierSyntax( name: name, genericArgumentClause: generics, arena: self.arena)) } if stopAtFirstPeriod { keepGoing = nil } else { keepGoing = self.consume(if: .period) ?? self.consume(if: .prefixPeriod) } } while keepGoing != nil && loopProgress.evaluate(currentToken) return result! } /// Parse the existential `Any` type. /// /// Grammar /// ======= /// /// any-type → Any @_spi(RawSyntax) public mutating func parseAnyType() -> RawSimpleTypeIdentifierSyntax { let (unexpectedBeforeName, name) = self.expect(.anyKeyword) return RawSimpleTypeIdentifierSyntax( unexpectedBeforeName, name: name, genericArgumentClause: nil, arena: self.arena ) } /// Parse a type placeholder. /// /// Grammar /// ======= /// /// placeholder-type → wildcard @_spi(RawSyntax) public mutating func parsePlaceholderType() -> RawSimpleTypeIdentifierSyntax { let (unexpectedBeforeName, name) = self.expect(.wildcardKeyword) // FIXME: Need a better syntax node than this return RawSimpleTypeIdentifierSyntax( unexpectedBeforeName, name: name, genericArgumentClause: nil, arena: self.arena ) } } extension Parser { /// Parse the generic arguments applied to a type. /// /// Grammar /// ======= /// /// generic-argument-clause → '<' generic-argument-list '>' /// generic-argument-list → generic-argument | generic-argument ',' generic-argument-list /// generic-argument → type @_spi(RawSyntax) public mutating func parseGenericArguments() -> RawGenericArgumentClauseSyntax { assert(self.currentToken.starts(with: "<")) let langle = self.consumePrefix("<", as: .leftAngle) var arguments = [RawGenericArgumentSyntax]() do { var keepGoing: RawTokenSyntax? = nil var loopProgress = LoopProgressCondition() repeat { let type = self.parseType() if arguments.isEmpty && type.is(RawMissingTypeSyntax.self) { break } keepGoing = self.consume(if: .comma) arguments.append(RawGenericArgumentSyntax( argumentType: type, trailingComma: keepGoing, arena: self.arena)) } while keepGoing != nil && loopProgress.evaluate(currentToken) } let rangle: RawTokenSyntax if self.currentToken.starts(with: ">") { rangle = self.consumePrefix(">", as: .rightAngle) } else { rangle = RawTokenSyntax(missing: .rightAngle, arena: self.arena) } let args: RawGenericArgumentListSyntax if arguments.isEmpty && rangle.isMissing { args = RawGenericArgumentListSyntax(elements: [], arena: self.arena) } else { args = RawGenericArgumentListSyntax(elements: arguments, arena: self.arena) } return RawGenericArgumentClauseSyntax( leftAngleBracket: langle, arguments: args, rightAngleBracket: rangle, arena: self.arena) } } extension Parser { /// Parse a tuple type. /// /// Grammar /// ======= /// /// tuple-type → '(' ')' | '(' tuple-type-element ',' tuple-type-element-list ')' /// tuple-type-element-list → tuple-type-element | tuple-type-element ',' tuple-type-element-list /// tuple-type-element → element-name type-annotation | type /// element-name → identifier @_spi(RawSyntax) public mutating func parseTupleTypeBody() -> RawTupleTypeSyntax { if let remainingTokens = remainingTokensIfMaximumNestingLevelReached() { return RawTupleTypeSyntax( remainingTokens, leftParen: missingToken(.leftParen), elements: RawTupleTypeElementListSyntax(elements: [], arena: self.arena), rightParen: missingToken(.rightParen), arena: self.arena ) } let (unexpectedBeforeLParen, lparen) = self.expect(.leftParen) var elements = [RawTupleTypeElementSyntax]() do { var keepGoing = true var loopProgress = LoopProgressCondition() while !self.at(any: [.eof, .rightParen]) && keepGoing && loopProgress.evaluate(currentToken) { let unexpectedBeforeFirst: RawUnexpectedNodesSyntax? let first: RawTokenSyntax? let unexpectedBeforeSecond: RawUnexpectedNodesSyntax? let second: RawTokenSyntax? let unexpectedBeforeColon: RawUnexpectedNodesSyntax? let colon: RawTokenSyntax? var misplacedSpecifiers: [RawTokenSyntax] = [] if self.withLookahead({ $0.startsParameterName(isClosure: false, allowMisplacedSpecifierRecovery: true) }) { while let specifier = self.consume(ifAnyIn: TypeSpecifier.self) { misplacedSpecifiers.append(specifier) } (unexpectedBeforeFirst, first) = self.parseArgumentLabel() if let parsedColon = self.consume(if: .colon) { unexpectedBeforeSecond = nil second = nil unexpectedBeforeColon = nil colon = parsedColon } else if self.currentToken.canBeArgumentLabel(allowDollarIdentifier: true) && self.peek().tokenKind == .colon { (unexpectedBeforeSecond, second) = self.parseArgumentLabel() (unexpectedBeforeColon, colon) = self.expect(.colon) } else { unexpectedBeforeSecond = nil second = nil unexpectedBeforeColon = nil colon = RawTokenSyntax(missing: .colon, arena: self.arena) } } else { unexpectedBeforeFirst = nil first = nil unexpectedBeforeSecond = nil second = nil unexpectedBeforeColon = nil colon = nil } // In the case that the input is "(foo bar)" we have to decide whether we parse it as "(foo: bar)" or "(foo, bar)". // As most people write identifiers lowercase and types capitalized, we decide on the first character of the first token if let first = first, second == nil, colon?.isMissing == true, first.tokenText.description.first?.isUppercase == true { elements.append(RawTupleTypeElementSyntax( inOut: nil, name: nil, secondName: nil, unexpectedBeforeColon, colon: nil, type: RawTypeSyntax(RawSimpleTypeIdentifierSyntax(name: first, genericArgumentClause: nil, arena: self.arena)), ellipsis: nil, initializer: nil, trailingComma: self.missingToken(.comma), arena: self.arena )) keepGoing = true continue } // Parse the type annotation. let type = self.parseType(misplacedSpecifiers: misplacedSpecifiers) let ellipsis = self.currentToken.isEllipsis ? self.consumeAnyToken() : nil var trailingComma = self.consume(if: .comma) if trailingComma == nil && self.withLookahead({ $0.canParseType() }) { // If the next token does not close the tuple, it is very likely the user forgot the comma. trailingComma = self.missingToken(.comma) } keepGoing = trailingComma != nil elements.append(RawTupleTypeElementSyntax( inOut: nil, RawUnexpectedNodesSyntax(combining: misplacedSpecifiers, unexpectedBeforeFirst, arena: self.arena), name: first, unexpectedBeforeSecond, secondName: second, unexpectedBeforeColon, colon: colon, type: type, ellipsis: ellipsis, initializer: nil, trailingComma: trailingComma, arena: self.arena )) } } let (unexpectedBeforeRParen, rparen) = self.expect(.rightParen) return RawTupleTypeSyntax( unexpectedBeforeLParen, leftParen: lparen, elements: RawTupleTypeElementListSyntax(elements: elements, arena: self.arena), unexpectedBeforeRParen, rightParen: rparen, arena: self.arena) } } extension Parser { /// Parse an array or dictionary type.. /// /// Grammar /// ======= /// /// array-type → '[' type ']' /// /// dictionary-type → '[' type ':' type ']' @_spi(RawSyntax) public mutating func parseCollectionType() -> RawTypeSyntax { if let remaingingTokens = remainingTokensIfMaximumNestingLevelReached() { return RawTypeSyntax(RawArrayTypeSyntax( remaingingTokens, leftSquareBracket: missingToken(.leftSquareBracket), elementType: RawTypeSyntax(RawMissingTypeSyntax(arena: self.arena)), rightSquareBracket: missingToken(.rightSquareBracket), arena: self.arena )) } let (unexpectedBeforeLSquare, lsquare) = self.expect(.leftSquareBracket) let firstType = self.parseType() if let colon = self.consume(if: .colon) { let secondType = self.parseType() let (unexpectedBeforeRSquareBracket, rSquareBracket) = self.expect(.rightSquareBracket) return RawTypeSyntax(RawDictionaryTypeSyntax( unexpectedBeforeLSquare, leftSquareBracket: lsquare, keyType: firstType, colon: colon, valueType: secondType, unexpectedBeforeRSquareBracket, rightSquareBracket: rSquareBracket, arena: self.arena )) } else { let (unexpectedBeforeRSquareBracket, rSquareBracket) = self.expect(.rightSquareBracket) return RawTypeSyntax(RawArrayTypeSyntax( unexpectedBeforeLSquare, leftSquareBracket: lsquare, elementType: firstType, unexpectedBeforeRSquareBracket, rightSquareBracket: rSquareBracket, arena: self.arena )) } } } extension Parser.Lookahead { mutating func canParseType() -> Bool { // Accept 'inout' at for better recovery. _ = self.consume(if: .inoutKeyword) if self.consumeIfContextualKeyword("some") != nil { } else { self.consumeIfContextualKeyword("any") } switch self.currentToken.tokenKind { case .capitalSelfKeyword, .anyKeyword: guard self.canParseTypeIdentifier() else { return false } case .protocolKeyword, // Deprecated composition syntax .identifier: guard self.canParseIdentifierTypeOrCompositionType() else { return false } case .leftParen: self.consumeAnyToken() guard self.canParseTupleBodyType() else { return false } case .atSign: self.consumeAnyToken() self.skipTypeAttribute() return self.canParseType() case .leftSquareBracket: self.consumeAnyToken() guard self.canParseType() else { return false } if self.consume(if: .colon) != nil { guard self.canParseType() else { return false } } guard self.consume(if: .rightSquareBracket) != nil else { return false } case .wildcardKeyword: self.consumeAnyToken() default: return false } // '.Type', '.Protocol', '?', and '!' still leave us with type-simple. var loopCondition = LoopProgressCondition() while loopCondition.evaluate(currentToken) { if let (_, _) = self.consume( if: { [.period, .prefixPeriod].contains($0.tokenKind) }, followedBy: { $0.isContextualKeyword(["Type", "Protocol"])}) { continue } if self.currentToken.isOptionalToken { self.consumePrefix("?", as: .postfixQuestionMark) continue } if self.currentToken.isImplicitlyUnwrappedOptionalToken { self.consumePrefix("!", as: .exclamationMark) continue } break } guard self.isAtFunctionTypeArrow() else { return true } // Handle type-function if we have an '->' with optional // 'async' and/or 'throws'. var loopProgress = LoopProgressCondition() while let (_, handle) = self.at(anyIn: EffectsSpecifier.self), loopProgress.evaluate(currentToken) { self.eat(handle) } guard self.consume(if: .arrow) != nil else { return false } return self.canParseType() } mutating func canParseTupleBodyType() -> Bool { guard !self.at(any: [.rightParen, .rightBrace]) && !self.atContextualPunctuator("...") && !self.atStartOfDeclaration() else { return self.consume(if: .rightParen) != nil } var loopProgress = LoopProgressCondition() repeat { // The contextual inout marker is part of argument lists. _ = self.consume(if: .inoutKeyword) // If the tuple element starts with "ident :", then it is followed // by a type annotation. if self.startsParameterName(isClosure: false, allowMisplacedSpecifierRecovery: false) { self.consumeAnyToken() if self.currentToken.canBeArgumentLabel() { self.consumeAnyToken() guard self.at(.colon) else { return false } } self.eat(.colon) // Parse a type. guard self.canParseType() else { return false } // Parse default values. This aren't actually allowed, but we recover // better if we skip over them. if self.consume(if: .equal) != nil { var skipProgress = LoopProgressCondition() while !self.at(any: [.eof, .rightParen, .rightBrace, .comma]) && !self.atContextualPunctuator("...") && !self.atStartOfDeclaration() && skipProgress.evaluate(currentToken) { self.skipSingle() } } continue } // Otherwise, this has to be a type. guard self.canParseType() else { return false } self.consumeIfContextualPunctuator("...") } while self.consume(if: .comma) != nil && loopProgress.evaluate(currentToken) return self.consume(if: .rightParen) != nil } mutating func canParseTypeIdentifier() -> Bool { var loopCondition = LoopProgressCondition() while loopCondition.evaluate(currentToken) { guard self.canParseSimpleTypeIdentifier() else { return false } // Treat 'Foo.<anything>' as an attempt to write a dotted type // unless <anything> is 'Type' or 'Protocol'. if self.at(any: [.period, .prefixPeriod]) && !self.peek().isContextualKeyword(["Type", "Protocol"]) { self.consumeAnyToken() } else { return true } } preconditionFailure("Should return from inside the loop") } func isAtFunctionTypeArrow() -> Bool { if self.at(.arrow) { return true } if self.at(anyIn: EffectsSpecifier.self) != nil { if self.peek().tokenKind == .arrow { return true } if EffectsSpecifier(lexeme: self.peek()) != nil { var backtrack = self.lookahead() backtrack.consumeAnyToken() backtrack.consumeAnyToken() return backtrack.isAtFunctionTypeArrow() } return false } return false } mutating func canParseIdentifierTypeOrCompositionType() -> Bool { if self.at(.protocolKeyword) { return self.canParseOldStyleProtocolComposition() } var loopCondition = LoopProgressCondition() while loopCondition.evaluate(currentToken) { guard self.canParseTypeIdentifier() else { return false } if self.atContextualPunctuator("&") { self.consumeAnyToken() continue } else { return true } } preconditionFailure("Should return from inside the loop") } mutating func canParseOldStyleProtocolComposition() -> Bool { self.eat(.protocolKeyword) // Check for the starting '<'. guard self.currentToken.starts(with: "<") else { return false } self.consumePrefix("<", as: .leftAngle) // Check for empty protocol composition. if self.currentToken.starts(with: ">") { self.consumePrefix(">", as: .rightAngle) return true } // Parse the type-composition-list. var loopProgress = LoopProgressCondition() repeat { guard self.canParseTypeIdentifier() else { return false; } } while self.consume(if: .comma) != nil && loopProgress.evaluate(currentToken) // Check for the terminating '>'. guard self.currentToken.starts(with: ">") else { return false } self.consumePrefix(">", as: .rightAngle) return true } mutating func canParseSimpleTypeIdentifier() -> Bool { // Parse an identifier. guard self.at(.identifier) || self.at(any: [.capitalSelfKeyword, .anyKeyword]) else { return false } self.consumeAnyToken() // Parse an optional generic argument list. if self.currentToken.starts(with: "<") && !self.consumeGenericArguments() { return false } return true } func canParseAsGenericArgumentList() -> Bool { guard self.atContextualPunctuator("<") else { return false } var lookahead = self.lookahead() guard lookahead.consumeGenericArguments() else { return false } return lookahead.currentToken.isGenericTypeDisambiguatingToken } mutating func consumeGenericArguments() -> Bool { // Parse the opening '<'. guard self.currentToken.starts(with: "<") else { return false } self.consumePrefix("<", as: .leftAngle) var loopProgress = LoopProgressCondition() repeat { guard self.canParseType() else { return false } // Parse the comma, if the list continues. } while self.consume(if: .comma) != nil && loopProgress.evaluate(currentToken) guard self.currentToken.starts(with: ">") else { return false } self.consumePrefix(">", as: .rightAngle) return true } } extension Parser { @_spi(RawSyntax) public mutating func parseTypeAttributeList(misplacedSpecifiers: [RawTokenSyntax] = []) -> ( specifier: RawTokenSyntax?, unexpectedBeforeAttributes: RawUnexpectedNodesSyntax?, attributes: RawAttributeListSyntax? ) { var specifier: RawTokenSyntax? = self.consume(ifAnyIn: TypeSpecifier.self) // We can only stick one specifier on this type. Let's pick the first one if specifier == nil, let misplacedSpecifier = misplacedSpecifiers.first { specifier = missingToken(misplacedSpecifier.tokenKind, text: misplacedSpecifier.tokenText) } var extraneousSpecifiers: [RawTokenSyntax] = [] while let extraSpecifier = self.consume(ifAny: [.inoutKeyword], contextualKeywords: ["__shared", "__owned", "isolated", "_const"]) { if specifier == nil { specifier = extraSpecifier } else { extraneousSpecifiers.append(extraSpecifier) } } let unexpectedBeforeAttributeList = RawUnexpectedNodesSyntax(extraneousSpecifiers, arena: self.arena) if self.at(any: [.atSign, .inoutKeyword]) { return (specifier, unexpectedBeforeAttributeList, self.parseTypeAttributeListPresent()) } return (specifier, unexpectedBeforeAttributeList, nil) } @_spi(RawSyntax) public mutating func parseTypeAttributeListPresent() -> RawAttributeListSyntax { var elements = [RawAttributeListSyntax.Element]() var attributeProgress = LoopProgressCondition() while self.at(.atSign) && attributeProgress.evaluate(currentToken) { elements.append(self.parseTypeAttribute()) } return RawAttributeListSyntax(elements: elements, arena: self.arena) } @_spi(RawSyntax) public mutating func parseTypeAttribute() -> RawAttributeListSyntax.Element { guard let typeAttr = Parser.TypeAttribute(rawValue: self.peek().tokenText) else { return .customAttribute(self.parseCustomAttribute()) } switch typeAttr { case .differentiable: return .attribute(self.parseDifferentiableAttribute()) case .convention: let (unexpectedBeforeAt, at) = self.expect(.atSign) let (unexpectedBeforeIdent, ident) = self.expectIdentifier() let (unexpectedBeforeLeftParen, leftParen) = self.expect(.leftParen) let arguments = self.parseConventionArguments() let (unexpectedBeforeRightParen, rightParen) = self.expect(.rightParen) return .attribute( RawAttributeSyntax( unexpectedBeforeAt, atSignToken: at, unexpectedBeforeIdent, attributeName: ident, unexpectedBeforeLeftParen, leftParen: leftParen, argument: arguments, unexpectedBeforeRightParen, rightParen: rightParen, tokenList: nil, arena: self.arena ) ) case ._opaqueReturnTypeOf: let (unexpectedBeforeAt, at) = self.expect(.atSign) let ident = self.expectIdentifierWithoutRecovery() let (unexpectedBeforeLeftParen, leftParen) = self.expect(.leftParen) let argument = self.parseOpaqueReturnTypeOfAttributeArguments() let (unexpectedBeforeRightParen, rightParen) = self.expect(.rightParen) return .attribute( RawAttributeSyntax( unexpectedBeforeAt, atSignToken: at, attributeName: ident, unexpectedBeforeLeftParen, leftParen: leftParen, argument: .opaqueReturnTypeOfAttributeArguments(argument), unexpectedBeforeRightParen, rightParen: rightParen, tokenList: nil, arena: self.arena ) ) default: let (unexpectedBeforeAt, at) = self.expect(.atSign) let ident = self.expectIdentifierWithoutRecovery() return .attribute( RawAttributeSyntax( unexpectedBeforeAt, atSignToken: at, attributeName: ident, leftParen: nil, argument: nil, rightParen: nil, tokenList: nil, arena: self.arena ) ) } } } extension Parser { mutating func parseResultType() -> RawTypeSyntax { if self.currentToken.starts(with: "<") { let generics = self.parseGenericParameters() let baseType = self.parseType() return RawTypeSyntax( RawNamedOpaqueReturnTypeSyntax( genericParameters: generics, baseType: baseType, arena: self.arena)) } else { return self.parseType() } } } extension Lexer.Lexeme { var isBinaryOperator: Bool { return self.tokenKind == .spacedBinaryOperator || self.tokenKind == .unspacedBinaryOperator } var isAnyOperator: Bool { return self.isBinaryOperator || self.tokenKind == .postfixOperator || self.tokenKind == .prefixOperator } var isEllipsis: Bool { return self.isAnyOperator && self.tokenText == "..." } var isOptionalToken: Bool { // A postfix '?' by itself is obviously optional. if self.tokenKind == .postfixQuestionMark { return true } // A postfix or bound infix operator token that begins with '?' can be // optional too. if self.tokenKind == .postfixOperator || self.tokenKind == .unspacedBinaryOperator { return self.tokenText.first == UInt8(ascii: "?") } return false } var isImplicitlyUnwrappedOptionalToken: Bool { // A postfix !?' by itself is obviously optional. if self.tokenKind == .exclamationMark { return true } // A postfix or bound infix operator token that begins with '?' can be // optional too. if self.tokenKind == .postfixOperator || self.tokenKind == .unspacedBinaryOperator { return self.tokenText.first == UInt8(ascii: "!") } return false } var isGenericTypeDisambiguatingToken: Bool { switch self.tokenKind { case .rightParen, .rightSquareBracket, .leftBrace, .rightBrace, .period, .prefixPeriod, .comma, .semicolon, .eof, .exclamationMark, .postfixQuestionMark, .colon: return true case .spacedBinaryOperator: return self.tokenText == "&" case .unspacedBinaryOperator, .postfixOperator: return self.isOptionalToken || self.isImplicitlyUnwrappedOptionalToken case .leftParen, .leftSquareBracket: // These only apply to the generic type if they don't start a new line. return !self.isAtStartOfLine default: return false } } }
a53abdb360fae1e0fe8ec0926a88c0d5
31.99422
136
0.642724
false
false
false
false
SummerHH/swift3.0WeBo
refs/heads/master
WeBo/Classes/UIKit/Emoticon/Model/Emoticon.swift
apache-2.0
1
// // Emoticon.swift // WeBo // // Created by Apple on 16/11/9. // Copyright © 2016年 叶炯. All rights reserved. // import UIKit class Emoticon: NSObject { // MARK:- 定义属性 var code : String? { // emoji的code didSet { guard let code = code else { return } // 1.创建扫描器 let scanner = Scanner(string: code) // 2.调用方法,扫描出code中的值 var value : UInt32 = 0 scanner.scanHexInt32(&value) // 3.将value转成字符 let c = Character(UnicodeScalar(value)!) // 4.将字符转成字符串 emojiCode = String(c) } } var png : String? { // 普通表情对应的图片名称 didSet { guard let png = png else { return } pngPath = Bundle.main.bundlePath + "/Emoticons.bundle/" + png } } var chs : String? // 普通表情对应的文字 // MARK:- 数据处理 var pngPath : String? var emojiCode : String? var isRemove: Bool = false var isEmpty: Bool = false // MARK:- 自定义构造函数 init(dict : [String : String]) { super.init() setValuesForKeys(dict) } init(isRemove: Bool) { self.isRemove = isRemove } init(isEmpty: Bool) { self.isEmpty = isEmpty } override func setValue(_ value: Any?, forUndefinedKey key: String) { } override var description : String { return dictionaryWithValues(forKeys: ["emojiCode", "pngPath", "chs"]).description } }
afe8d7cc21b1d6d90c663e07c4ff8de6
22.042857
89
0.491011
false
false
false
false
datomnurdin/SwiftCharts
refs/heads/master
Examples/Examples/DetailViewController.swift
apache-2.0
2
// // DetailViewController.swift // SwiftCharts // // Created by ischuetz on 20/04/15. // Copyright (c) 2015 ivanschuetz. All rights reserved. // import UIKit class DetailViewController: UIViewController, UISplitViewControllerDelegate { @IBOutlet weak var detailDescriptionLabel: UILabel! lazy var chartFrame: CGRect! = { CGRectMake(0, 80, self.view.frame.size.width, self.view.frame.size.height - 80) }() var detailItem: Example? { didSet { self.configureView() } } var currentExampleController: UIViewController? func configureView() { if let example: Example = self.detailItem { switch example { case .HelloWorld: self.setSplitSwipeEnabled(true) self.showExampleController(HelloWorld()) case .Bars: self.setSplitSwipeEnabled(true) self.showExampleController(BarsExample()) case .StackedBars: self.setSplitSwipeEnabled(true) self.showExampleController(StackedBarsExample()) case .BarsPlusMinus: self.setSplitSwipeEnabled(true) self.showExampleController(BarsPlusMinusWithGradientExample()) case .GroupedBars: self.setSplitSwipeEnabled(true) self.showExampleController(GroupedBarsExample()) case .BarsStackedGrouped: self.setSplitSwipeEnabled(true) self.showExampleController(GroupedAndStackedBarsExample()) case .Scatter: self.setSplitSwipeEnabled(true) self.showExampleController(ScatterExample()) case .Notifications: self.setSplitSwipeEnabled(true) self.showExampleController(NotificationsExample()) case .Target: self.setSplitSwipeEnabled(true) self.showExampleController(TargetExample()) case .Areas: self.setSplitSwipeEnabled(true) self.showExampleController(AreasExample()) case .Bubble: self.setSplitSwipeEnabled(true) self.showExampleController(BubbleExample()) case .Combination: self.setSplitSwipeEnabled(true) self.showExampleController(BarsPlusMinusAndLinesExample()) case .Scroll: self.setSplitSwipeEnabled(false) self.automaticallyAdjustsScrollViewInsets = false self.showExampleController(ScrollExample()) case .Coords: self.setSplitSwipeEnabled(true) self.showExampleController(CoordsExample()) case .Tracker: self.setSplitSwipeEnabled(false) self.showExampleController(TrackerExample()) case .EqualSpacing: self.setSplitSwipeEnabled(true) self.showExampleController(EqualSpacingExample()) case .CustomUnits: self.setSplitSwipeEnabled(true) self.showExampleController(CustomUnitsExample()) case .Multival: self.setSplitSwipeEnabled(true) self.showExampleController(MultipleLabelsExample()) case .MultiAxis: self.setSplitSwipeEnabled(true) self.showExampleController(MultipleAxesExample()) case .MultiAxisInteractive: self.setSplitSwipeEnabled(true) self.showExampleController(MultipleAxesInteractiveExample()) case .CandleStick: self.setSplitSwipeEnabled(true) self.showExampleController(CandleStickExample()) case .Cubiclines: self.setSplitSwipeEnabled(true) self.showExampleController(CubicLinesExample()) case .NotNumeric: self.setSplitSwipeEnabled(true) self.showExampleController(NotNumericExample()) case .CandleStickInteractive: self.setSplitSwipeEnabled(false) self.showExampleController(CandleStickInteractiveExample()) } } } private func showExampleController(controller: UIViewController) { if let currentExampleController = self.currentExampleController { currentExampleController.removeFromParentViewController() currentExampleController.view.removeFromSuperview() } self.addChildViewController(controller) self.view.addSubview(controller.view) self.currentExampleController = controller } private func setSplitSwipeEnabled(enabled: Bool) { if UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Pad { let splitViewController = UIApplication.sharedApplication().delegate?.window!!.rootViewController as! UISplitViewController splitViewController.presentsWithGesture = enabled } } }
6cbbff60c92931463fd2b232e24ced48
39.943548
135
0.620051
false
false
false
false
actorapp/actor-platform
refs/heads/master
actor-sdk/sdk-core-ios/ActorSDK/Sources/Controllers/User/AAUserViewController.swift
agpl-3.0
2
// // Copyright (c) 2014-2016 Actor LLC. <https://actor.im> // import UIKit class AAUserViewController: AAContentTableController { var headerRow: AAAvatarRow! var isContactRow: AACommonRow! init(uid: Int) { super.init(style: AAContentTableStyle.settingsPlain) self.uid = uid self.autoTrack = true self.title = AALocalized("ProfileTitle") } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func tableDidLoad() { // Profile section { (s) -> () in // Profile: Avatar self.headerRow = s.avatar { (r) -> () in r.bindAction = { (r) -> () in r.id = self.uid r.title = self.user.getNameModel().get() r.avatar = self.user.getAvatarModel().get() let presence = self.user.getPresenceModel().get() let presenceText = Actor.getFormatter().formatPresence(presence, with: self.user.getSex()) if !self.isBot { r.subtitle = presenceText if presence!.state.ordinal() == ACUserPresence_State.online().ordinal() { r.subtitleColor = self.appStyle.userOnlineColor } else { r.subtitleColor = self.appStyle.userOfflineColor } } else { r.subtitle = "bot" r.subtitleColor = self.appStyle.userOnlineColor } } r.avatarDidTap = { [unowned self] (view: UIView) -> () in let avatar = self.user.getAvatarModel().get() if avatar != nil && avatar?.fullImage != nil { let full = avatar?.fullImage.fileReference let small = avatar?.smallImage.fileReference let size = CGSize(width: Int((avatar?.fullImage.width)!), height: Int((avatar?.fullImage.height)!)) self.present(AAPhotoPreviewController(file: full!, previewFile: small, size: size, fromView: view), animated: true, completion: nil) } } } if (ActorSDK.sharedActor().enableCalls && !self.isBot) { // Profile: Starting Voice Call s.action("CallsStartAudio") { (r) -> () in r.selectAction = { () -> Bool in self.execute(Actor.doCall(withUid: jint(self.uid))) return false } } } // Profile: Send messages s.action("ProfileSendMessage") { (r) -> () in r.selectAction = { () -> Bool in if let customController = ActorSDK.sharedActor().delegate.actorControllerForConversation(ACPeer.user(with: jint(self.uid))) { self.navigateDetail(customController) } else { self.navigateDetail(ConversationViewController(peer: ACPeer.user(with: jint(self.uid)))) } self.popover?.dismiss(animated: true) return false } } } let nick = self.user.getNickModel().get() let about = self.user.getAboutModel().get() if !self.isBot || nick != nil || about != nil { // Contact section { (s) -> () in // Contact: Nickname if let n = nick { s.titled("ProfileUsername", content: "@\(n)") } // Contact: Phones s.arrays { (r: AAManagedArrayRows<ACUserPhone, AATitledCell>) -> () in r.height = 55 r.data = self.user.getPhonesModel().get().toSwiftArray() r.bindData = { (c: AATitledCell, d: ACUserPhone) -> () in c.setContent(AALocalized("SettingsMobilePhone"), content: "+\(d.phone)", isAction: false) } r.bindCopy = { (d: ACUserPhone) -> String? in return "+\(d.phone)" } r.selectAction = { (c: ACUserPhone) -> Bool in let phoneNumber = c.phone let hasPhone = UIApplication.shared.canOpenURL(URL(string: "telprompt://")!) if (!hasPhone) { UIPasteboard.general.string = "+\(phoneNumber)" self.alertUser("NumberCopied") } else { ActorSDK.sharedActor().openUrl("telprompt://+\(phoneNumber)") } return true } } // Contact: Emails s.arrays { (r: AAManagedArrayRows<ACUserEmail, AATitledCell>) -> () in r.height = 55 r.data = self.user.getEmailsModel().get().toSwiftArray() r.bindData = { (c: AATitledCell, d: ACUserEmail) -> () in c.setContent(d.title, content: d.email, isAction: false) } r.bindCopy = { (d: ACUserEmail) -> String? in return d.email } r.selectAction = { (c: ACUserEmail) -> Bool in ActorSDK.sharedActor().openUrl("mailto:\(c.email)") return true } } // Contact: About if let a = about { s.text("ProfileAbout", content: a) } } } section { (s) -> () in s.common { (r) -> () in let peer = ACPeer.user(with: jint(self.uid)) r.style = .switch r.content = AALocalized("ProfileNotifications") r.bindAction = { (r) -> () in r.switchOn = Actor.isNotificationsEnabled(with: peer) } r.switchAction = { (on: Bool) -> () in if !on && !self.user.isBot() { self.confirmAlertUser("ProfileNotificationsWarring", action: "ProfileNotificationsWarringAction", tapYes: { () -> () in Actor.changeNotificationsEnabled(with: peer, withValue: false) }, tapNo: { () -> () in r.reload() }) return } Actor.changeNotificationsEnabled(with: peer, withValue: on) } if(ActorSDK.sharedActor().enableChatGroupSound) { if(Actor.isNotificationsEnabled(with: peer)){ r.selectAction = {() -> Bool in // Sound: Choose sound let setRingtoneController = AARingtonesViewController() let sound = Actor.getNotificationsSound(with: peer) setRingtoneController.selectedRingtone = (sound != nil) ? sound! : "" setRingtoneController.completion = {(selectedSound:String) in Actor.changeNotificationsSound(peer, withValue: selectedSound) } let navigationController = AANavigationController(rootViewController: setRingtoneController) if (AADevice.isiPad) { navigationController.isModalInPopover = true navigationController.modalPresentationStyle = UIModalPresentationStyle.currentContext } self.present(navigationController, animated: true, completion: { } ) return false } } } } } // Edit contact section { (s) -> () in // Edit contact: Add/Remove self.isContactRow = s.common { (r) -> () in r.bindAction = { (r) -> () in if self.user.isContactModel().get().booleanValue() { r.content = AALocalized("ProfileRemoveFromContacts") r.style = .destructive } else { r.content = AALocalized("ProfileAddToContacts") r.style = .action } } r.selectAction = { () -> Bool in if (self.user.isContactModel().get().booleanValue()) { self.execute(Actor.removeContactCommand(withUid: jint(self.uid))!) } else { self.execute(Actor.addContactCommand(withUid: jint(self.uid))!) } return true } } if !self.isBot { // Edit contact: Renaming s.action("ProfileRename") { (r) -> () in r.selectAction = { () -> Bool in func renameUser() { self.startEditField { (c) -> () in c.title = "ProfileEditHeader" c.initialText = self.user.getNameModel().get() c.didDoneTap = { (d, c) in if d.length == 0 { return } c.executeSafeOnlySuccess(Actor.editNameCommand(withUid: jint(self.uid), withName: d)!, successBlock: { (val) -> Void in c.dismissController() }) } } } if (!Actor.isRenameHintShown()) { self.confirmAlertUser("ProfileRenameMessage", action: "ProfileRenameAction", tapYes: { () -> () in renameUser() }) } else { renameUser() } return true } } } } // Block Contact section { (s) -> () in s.common { (r) -> () in r.bindAction = { (r) -> () in if !self.user.isBlockedModel().get().booleanValue() { r.content = AALocalized("ProfileBlockContact") } else { r.content = AALocalized("ProfileUnblockContact") } r.style = .destructive } r.selectAction = { () -> Bool in if !self.user.isBlockedModel().get().booleanValue() { self.executePromise(Actor.blockUser(jint(self.uid)), successBlock: { success in DispatchQueue.main.async(execute: { r.reload() }) } ,failureBlock:nil) } else { self.executePromise(Actor.unblockUser(jint(self.uid)), successBlock: { success in DispatchQueue.main.async(execute: { r.reload() }) } ,failureBlock:nil) } r.reload() return true } } } } override func tableWillBind(_ binder: AABinder) { binder.bind(user.getAvatarModel(), closure: { (value: ACAvatar?) -> () in self.headerRow.reload() }) binder.bind(user.getNameModel(), closure: { ( name: String?) -> () in self.headerRow.reload() }) if !isBot { binder.bind(user.getPresenceModel(), closure: { (presence: ACUserPresence?) -> () in self.headerRow.reload() }) binder.bind(user.isContactModel(), closure: { (contect: ARValueModel?) -> () in self.isContactRow.reload() }) } } }
a55d8fceb2b82773aef7e80690578a58
41.742857
156
0.403001
false
false
false
false
JunDang/SwiftFoundation
refs/heads/develop
Sources/SwiftFoundation/DateComponents.swift
mit
1
// // DateComponents.swift // SwiftFoundation // // Created by David Ask on 07/12/15. // Copyright © 2015 PureSwift. All rights reserved. // #if os(OSX) || os(iOS) || os(watchOS) || os(tvOS) import Darwin.C #elseif os(Linux) import Glibc #endif public struct DateComponents { public enum Component { case Second case Minute case Hour case DayOfMonth case Month case Year case Weekday case DayOfYear } public var second: Int32 = 0 public var minute: Int32 = 0 public var hour: Int32 = 0 public var dayOfMonth: Int32 = 1 public var month: Int32 = 1 public var year: Int32 = 0 public var weekday: Int32 public var dayOfYear: Int32 = 1 public init(timeInterval: TimeInterval) { self.init( brokenDown: tm( UTCSecondsSince1970: timeval(timeInterval: timeInterval).tv_sec ) ) } public init() { weekday = 0 } public init(fromDate date: Date) { self.init(timeInterval: date.timeIntervalSince1970) } public var date: Date { return Date(timeIntervalSince1970: timeInterval) } public mutating func setValue(value: Int32, forComponent component: Component) { switch component { case .Second: second = value break case .Minute: minute = value break case .Hour: hour = value break case .DayOfMonth: dayOfMonth = value break case .Month: month = value break case .Year: year = value break case .Weekday: weekday = value break case .DayOfYear: dayOfYear = value break } } public func valueForComponent(component: Component) -> Int32 { switch component { case .Second: return second case .Minute: return minute case .Hour: return hour case .DayOfMonth: return dayOfMonth case .Month: return month case .Year: return year case .Weekday: return weekday case .DayOfYear: return dayOfYear } } private init(brokenDown: tm) { second = brokenDown.tm_sec minute = brokenDown.tm_min hour = brokenDown.tm_hour dayOfMonth = brokenDown.tm_mday month = brokenDown.tm_mon + 1 year = 1900 + brokenDown.tm_year weekday = brokenDown.tm_wday dayOfYear = brokenDown.tm_yday } private var brokenDown: tm { return tm.init( tm_sec: second, tm_min: minute, tm_hour: hour, tm_mday: dayOfMonth, tm_mon: month - 1, tm_year: year - 1900, tm_wday: weekday, tm_yday: dayOfYear, tm_isdst: -1, tm_gmtoff: 0, tm_zone: nil ) } private var timeInterval: TimeInterval { var time = brokenDown return TimeInterval(timegm(&time)) } }
a2df64cc22c2634049e7234e844b9277
22.89781
84
0.521991
false
false
false
false
Pyroh/Fluor
refs/heads/main
Fluor/Controllers/BehaviorController.swift
mit
1
// // BehaviorController.swift // // Fluor // // MIT License // // Copyright (c) 2020 Pierre Tacchi // // 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 Cocoa import os.log import UserNotifications class BehaviorController: NSObject, BehaviorDidChangeObserver, DefaultModeViewControllerDelegate, SwitchMethodDidChangeObserver, ActiveApplicationDidChangeObserver { @IBOutlet weak var statusMenuController: StatusMenuController! @IBOutlet var defaultModeViewController: DefaultModeViewController! @objc dynamic private var isKeySwitchCapable: Bool = false private var globalEventManager: Any? private var fnDownTimestamp: TimeInterval? = nil private var shouldHandleFNKey: Bool = false private var currentMode: FKeyMode = .media private var onLaunchKeyboardMode: FKeyMode = .media private var currentAppID: String = "" private var currentAppURL: URL? private var currentAppName: String? private var currentBehavior: AppBehavior = .inferred private var switchMethod: SwitchMethod = .window func setupController() { self.onLaunchKeyboardMode = AppManager.default.getCurrentFKeyMode() self.currentMode = self.onLaunchKeyboardMode self.switchMethod = AppManager.default.switchMethod self.applyAsObserver() NSWorkspace.shared.notificationCenter.addObserver(self, selector: #selector(appMustSleep(notification:)), name: NSWorkspace.sessionDidResignActiveNotification, object: nil) NSWorkspace.shared.notificationCenter.addObserver(self, selector: #selector(appMustSleep(notification:)), name: NSWorkspace.willSleepNotification, object: nil) NSWorkspace.shared.notificationCenter.addObserver(self, selector: #selector(appMustWake(notification:)), name: NSWorkspace.sessionDidBecomeActiveNotification, object: nil) NSWorkspace.shared.notificationCenter.addObserver(self, selector: #selector(appMustWake(notification:)), name: NSWorkspace.didWakeNotification, object: nil) guard !AppManager.default.isDisabled else { return } if let currentApp = NSWorkspace.shared.frontmostApplication, let id = currentApp.bundleIdentifier ?? currentApp.executableURL?.lastPathComponent { self.adaptModeForApp(withId: id) // self.updateAppBehaviorViewFor(app: currentApp, id: id) } } func setApplicationIsEnabled(_ enabled: Bool) { if enabled { self.adaptModeForApp(withId: self.currentAppID) } else { do { try FKeyManager.setCurrentFKeyMode(self.onLaunchKeyboardMode) } catch { AppErrorManager.terminateApp(withReason: error.localizedDescription) } } } func performTerminationCleaning() { if AppManager.default.shouldRestoreStateOnQuit { let state: FKeyMode if AppManager.default.shouldRestorePreviousState { state = self.onLaunchKeyboardMode } else { state = AppManager.default.onQuitState } do { try FKeyManager.setCurrentFKeyMode(state) } catch { fatalError() } } } func adaptToAccessibilityTrust() { if AXIsProcessTrusted() { self.isKeySwitchCapable = true self.ensureMonitoringFlagKey() } else { self.isKeySwitchCapable = false self.stopMonitoringFlagKey() } } // MARK: - ActiveApplicationDidChangeObserver func activeApplicationDidChangw(notification: Notification) { self.adaptToAccessibilityTrust() guard let app = notification.userInfo?[NSWorkspace.applicationUserInfoKey] as? NSRunningApplication, let id = app.bundleIdentifier ?? app.executableURL?.lastPathComponent else { return } self.currentAppName = app.localizedName self.currentAppID = id self.currentAppURL = app.bundleURL if !AppManager.default.isDisabled { self.adaptModeForApp(withId: id) } } // MARK: - BehaviorDidChangeObserver /// React to the change of the function keys behavior for one app. /// /// - parameter notification: The notification. func behaviorDidChangeForApp(notification: Notification) { guard let id = notification.userInfo?["id"] as? String else { return } if id == self.currentAppID { self.adaptModeForApp(withId: id) } } // MARK: - SwitchMethodDidChangeObserver func switchMethodDidChange(notification: Notification) { guard let userInfo = notification.userInfo, let method = userInfo["method"] as? SwitchMethod else { return } self.switchMethod = method switch method { case .window, .hybrid: self.startObservingBehaviorDidChange() self.adaptModeForApp(withId: self.currentAppID) case .key: self.stopObservingBehaviorDidChange() self.currentMode = AppManager.default.defaultFKeyMode self.changeKeyboard(mode: currentMode) } } // MARK: - DefaultModeViewControllerDelegate func defaultModeController(_ controller: DefaultModeViewController, didChangeModeTo mode: FKeyMode) { switch self.switchMethod { case .window, .hybrid: self.adaptModeForApp(withId: self.currentAppID) case .key: self.changeKeyboard(mode: mode) self.currentMode = mode } } // MARK: - Private functions /// Disable this session's Fluor instance in order to prevent it from messing when potential other sessions' ones. /// /// - Parameter notification: The notification. @objc private func appMustSleep(notification: Notification) { do { try FKeyManager.setCurrentFKeyMode(self.onLaunchKeyboardMode) } catch { os_log("Unable to reset FKey mode to pre-launch mode", type: .error) } self.resignAsObserver() } /// Reenable this session's Fluor instance. /// /// - Parameter notification: The notification. @objc private func appMustWake(notification: Notification) { self.changeKeyboard(mode: currentMode) self.applyAsObserver() } /// Register self as an observer for some notifications. private func applyAsObserver() { if self.switchMethod != .key { self.startObservingBehaviorDidChange() } self.startObservingSwitchMethodDidChange() self.startObservingActiveApplicationDidChange() self.adaptToAccessibilityTrust() } /// Unregister self as an observer for some notifications. private func resignAsObserver() { if self.switchMethod != .key { self.stopObservingBehaviorDidChange() } self.stopObservingSwitchMethodDidChange() self.stopObservingActiveApplicationDidChange() self.stopMonitoringFlagKey() } /// Set the function keys' behavior for the given app. /// /// - parameter id: The app's bundle id. private func adaptModeForApp(withId id: String) { guard self.switchMethod != .key else { return } let behavior = AppManager.default.behaviorForApp(id: id) let mode = AppManager.default.keyboardStateFor(behavior: behavior) guard mode != self.currentMode else { return } self.currentMode = mode self.changeKeyboard(mode: mode) } private func changeKeyboard(mode: FKeyMode) { do { try FKeyManager.setCurrentFKeyMode(mode) } catch { AppErrorManager.terminateApp(withReason: error.localizedDescription) } switch mode { case .media: os_log("Switch to Apple Mode for %@", self.currentAppID) self.statusMenuController.statusItem.image = AppManager.default.useLightIcon ? #imageLiteral(resourceName: "AppleMode") : #imageLiteral(resourceName: "IconAppleMode") case .function: NSLog("Switch to Other Mode for %@", self.currentAppID) self.statusMenuController.statusItem.image = AppManager.default.useLightIcon ? #imageLiteral(resourceName: "OtherMode") : #imageLiteral(resourceName: "IconOtherMode") } UserNotificationHelper.sendModeChangedTo(mode) } private func manageKeyPress(event: NSEvent) { guard self.switchMethod != .window else { return } if event.type == .flagsChanged { if event.modifierFlags.contains(.function) { if event.keyCode == 63 { self.fnDownTimestamp = event.timestamp self.shouldHandleFNKey = true } else { self.fnDownTimestamp = nil self.shouldHandleFNKey = false } } else { if self.shouldHandleFNKey, let timestamp = self.fnDownTimestamp { let delta = (event.timestamp - timestamp) * 1000 self.shouldHandleFNKey = false if event.keyCode == 63, delta <= AppManager.default.fnKeyMaximumDelay { switch self.switchMethod { case .key: self.fnKeyPressedImpactsGlobal() case .hybrid: self.fnKeyPressedImpactsApp() default: return } } } } } else if self.shouldHandleFNKey { self.shouldHandleFNKey = false self.fnDownTimestamp = nil } } private func fnKeyPressedImpactsGlobal() { let mode = self.currentMode.counterPart AppManager.default.defaultFKeyMode = mode UserNotificationHelper.holdNextModeChangedNotification = true self.changeKeyboard(mode: mode) self.currentMode = mode UserNotificationHelper.sendGlobalModeChangedTo(mode) } private func fnKeyPressedImpactsApp() { guard let url = self.currentAppURL else { AppErrorManager.terminateApp(withReason: "An unexpected error occured") } let appBehavior = AppManager.default.behaviorForApp(id: self.currentAppID) let defaultBehavior = AppManager.default.defaultFKeyMode.behavior let newAppBehavior: AppBehavior switch appBehavior { case .inferred: newAppBehavior = defaultBehavior.counterPart case defaultBehavior.counterPart: newAppBehavior = defaultBehavior case defaultBehavior: newAppBehavior = .inferred default: newAppBehavior = .inferred } UserNotificationHelper.holdNextModeChangedNotification = self.currentAppName != nil AppManager.default.propagate(behavior: newAppBehavior, forApp: self.currentAppID , at: url, from: .fnKey) if let name = self.currentAppName { UserNotificationHelper.sendFKeyChangedAppBehaviorTo(newAppBehavior, appName: name) } } private func ensureMonitoringFlagKey() { guard self.isKeySwitchCapable && self.globalEventManager == nil else { return } self.globalEventManager = NSEvent.addGlobalMonitorForEvents(matching: [.flagsChanged, .keyDown], handler: manageKeyPress) } private func stopMonitoringFlagKey() { guard let gem = self.globalEventManager else { return } NSEvent.removeMonitor(gem) if self.globalEventManager != nil { self.globalEventManager = nil } } }
10e16f10f6d31764fde24527f309bfdb
40.64918
180
0.659214
false
false
false
false
Stanbai/MultiThreadBasicDemo
refs/heads/master
Operation/Swift/NSOperation/NSOperation/BasicDemosVC.swift
mit
1
// // BasicDemosVC.swift // NSOperation // // Created by Stan on 2017-07-07. // Copyright © 2017 stan. All rights reserved. // import UIKit enum DemoType : Int{ case basic case priority case dependency case collection } class BasicDemosVC: UIViewController { @IBOutlet weak var activityIndicator: UIActivityIndicatorView! @IBOutlet weak var imageView1: UIImageView! @IBOutlet weak var imageView2: UIImageView! @IBOutlet weak var imageView3: UIImageView! @IBOutlet weak var imageView4: UIImageView! let operationQueue = OperationQueue.init() var imageViews : [UIImageView]? var demoType : DemoType? override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) guard let type = demoType else { return } switch type { case .basic: self.title = "Basic Demo" break case .priority : self.title = "Priority Demo" break case .dependency : self.title = "Dependency Demo" break default : break } } override func viewDidLoad() { super.viewDidLoad() imageViews = [imageView1,imageView2,imageView3,imageView4] } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func playItemClick(_ sender: Any) { guard let type = demoType else { return } switch type { case .basic: startBasicDemo() break case .priority : startPriorityDemo() break case .dependency : startDepencyDemo() break default : break } } } extension BasicDemosVC { fileprivate func startBasicDemo() { operationQueue.maxConcurrentOperationCount = 3 activityIndicator.startAnimating() // 使用数组给图片赋值 // use Array set image for imageView in imageViews! { operationQueue.addOperation { if let url = URL(string: "https://placebeard.it/355/140") { do { let image = UIImage(data:try Data(contentsOf: url)) DispatchQueue.main.async { imageView.image = image } } catch { print(error) } } } } // global queue DispatchQueue.global().async { [weak self] in // 等待所有操作都完成了,回到主线程停止刷新器。 // wait Until All Operations are finished, then stop animation of activity indicator self?.operationQueue.waitUntilAllOperationsAreFinished() DispatchQueue.main.async { self?.activityIndicator.stopAnimating() } } } fileprivate func startPriorityDemo() { operationQueue.maxConcurrentOperationCount = 2 activityIndicator.startAnimating() var operations = [Operation]() for (index, imageView) in (imageViews?.enumerated())! { if let url = URL(string: "https://placebeard.it/355/140") { // 使用构造方法创建operation let operation = convenienceOperation(setImageView: imageView, withURL: url) //根据索引设置优先级 switch index { case 0: operation.queuePriority = .veryHigh case 1: operation.queuePriority = .high case 2: operation.queuePriority = .normal case 3: operation.queuePriority = .low default: operation.queuePriority = .veryLow } operations.append(operation) } } // 把任务数组加入到线程中 DispatchQueue.global().async { [weak self] in self?.operationQueue.addOperations(operations, waitUntilFinished: true) DispatchQueue.main.async { self?.activityIndicator.stopAnimating() } } } fileprivate func startDepencyDemo() { operationQueue.maxConcurrentOperationCount = 4 self.activityIndicator.startAnimating() guard let url = URL(string: "https://placebeard.it/355/140") else {return } let op1 = convenienceOperation(setImageView: imageView1, withURL: url) let op2 = convenienceOperation(setImageView: imageView2, withURL: url) op2.addDependency(op1) let op3 = convenienceOperation(setImageView: imageView3, withURL: url) op3.addDependency(op2) let op4 = convenienceOperation(setImageView: imageView4, withURL: url) op4.addDependency(op3) DispatchQueue.global().async { [weak self] in self?.operationQueue.addOperations([op1,op2,op3,op4], waitUntilFinished: true) DispatchQueue.main.async { self?.activityIndicator.stopAnimating() } } } } class convenienceOperation: Operation { let url: URL let imageView: UIImageView init(setImageView: UIImageView, withURL: URL) { imageView = setImageView url = withURL super.init() } override func main() { do { // 当任务被取消的时候,立刻返回 if isCancelled { return } let imageData = try Data(contentsOf: url) let image = UIImage(data: imageData) DispatchQueue.main.async { [weak self] in self?.imageView.image = image } } catch { print(error) } } }
7770ada5b71183593df9d1f66884eb18
27.307339
107
0.524226
false
false
false
false
antonio081014/LeeCode-CodeBase
refs/heads/main
Swift/find-and-replace-pattern.swift
mit
2
/** * https://leetcode.com/problems/find-and-replace-pattern/ * * */ // Date: Fri May 21 11:51:49 PDT 2021 class Solution { func findAndReplacePattern(_ words: [String], _ pattern: String) -> [String] { var result = [String]() for w in words { if self.transformable(from: w, to: pattern) { result.append(w) } } return result } private func transformable(from a: String, to b: String) -> Bool { var map1 = [Character : Character]() var map2 = [Character : Character]() let a = Array(a) let b = Array(b) for index in 0 ..< a.count { if map1[a[index]] == nil { map1[a[index]] = b[index] } if map2[b[index]] == nil { map2[b[index]] = a[index] } if map1[a[index]]! != b[index] || map2[b[index]]! != a[index] { return false } } return true } }
bc2a6176871c4108786cd4694a540827
28
90
0.481218
false
false
false
false
padawan/smartphone-app
refs/heads/master
MT_iOS/MT_iOS/Classes/ViewController/CategoryListTableViewController.swift
mit
1
// // CategoryListTableViewController.swift // MT_iOS // // Created by CHEEBOW on 2015/06/08. // Copyright (c) 2015年 Six Apart, Ltd. All rights reserved. // import UIKit import SwiftyJSON class CategoryListTableViewController: BaseCategoryListTableViewController, PrimaryCategorySelectorDelegate { override func viewDidLoad() { super.viewDidLoad() self.title = NSLocalizedString("Select categories", comment: "Select categories") list = CategoryList() (list as! CategoryList).blog = self.blog // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() actionMessage = NSLocalizedString("Fetch categories", comment: "Fetch categories") self.fetch() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source /* override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as! UITableViewCell // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO 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 NO 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. } */ override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let selectedItem = self.list[indexPath.row] as! Category object.isDirty = true if let sel = selected[selectedItem.id] { selected[selectedItem.id] = !sel } else { selected[selectedItem.id] = true } self.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.None) } @IBAction override func saveButtonPushed(sender: UIBarButtonItem) { var selectedObjects = [Category]() for (id, value) in selected { if value { if !id.isEmpty { selectedObjects.append(list.objectWithID(id)! as! Category) } } } sort(&selectedObjects) { (cat1 : Category, cat2 : Category) -> Bool in return cat1.level < cat2.level } if selectedObjects.count > 1 { let vc = PrimaryCategorySelectorTableViewController() let nav = UINavigationController(rootViewController: vc) vc.items = selectedObjects vc.delegate = self self.presentViewController(nav, animated: true, completion: nil) } else { (object as! EntryCategoryItem).selected = selectedObjects self.navigationController?.popViewControllerAnimated(true) } } func primaryCategorySelectorDone(controller: PrimaryCategorySelectorTableViewController, selected: String) { self.dismissViewControllerAnimated(false, completion: { var selectedObjects = [Category]() for (id, value) in self.selected { if value { let item = self.list.objectWithID(id)! as! Category if id == selected { selectedObjects.insert(item, atIndex: 0) } else { selectedObjects.append(item) } } } (self.object as! EntryCategoryItem).selected = selectedObjects self.navigationController?.popViewControllerAnimated(true) } ) } }
a0eb2d326797a37dff5f48b99c91408b
35.432258
157
0.626173
false
false
false
false
marcorcb/SwiftSimplePhotoPicker
refs/heads/master
SwiftSimplePhotoPickerExample/SwiftSimplePhotoPickerExample/SwiftSimplePhotoPicker.swift
mit
1
// // SwiftSimplePhotoPicker.swift // SwiftSimplePhotoPickerExample // // Created by Marco Braga on 11/08/17. // Copyright © 2017 Marco Braga. All rights reserved. // import UIKit class SwiftSimpleImagePickerController: UIImagePickerController { override var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } } class SwiftSimplePhotoPicker: NSObject { static let shared = SwiftSimplePhotoPicker() var imagePickerController: SwiftSimpleImagePickerController var completionBlock: ((UIImage) -> Void)? override init() { self.imagePickerController = SwiftSimpleImagePickerController() super.init() self.imagePickerController.navigationBar.isTranslucent = false self.imagePickerController.delegate = self self.imagePickerController.allowsEditing = true } func showPicker(in viewController: UIViewController, completion: @escaping (UIImage) -> Void) { self.completionBlock = completion let actionSheet = UIAlertController(title: "Choose an option", message: nil, preferredStyle: .actionSheet) actionSheet.addAction(UIAlertAction(title: "Choose Photo", style: .default, handler: { (_) in self.imagePickerController.sourceType = .photoLibrary viewController.present(self.imagePickerController, animated: true, completion: nil) })) actionSheet.addAction(UIAlertAction(title: "Take Photo", style: .default, handler: { (_) in self.imagePickerController.sourceType = .camera self.imagePickerController.cameraDevice = .front self.imagePickerController.cameraFlashMode = .off viewController.present(self.imagePickerController, animated: true, completion: nil) })) actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) viewController.present(actionSheet, animated: true, completion: nil) } func fixOrientation(for image: UIImage) -> UIImage { if image.imageOrientation == .up { return image } var transform: CGAffineTransform = .identity switch image.imageOrientation { case .down, .downMirrored: transform = CGAffineTransform(translationX: image.size.width, y: image.size.height) transform = CGAffineTransform(rotationAngle: .pi) case .left, .leftMirrored: transform = CGAffineTransform(translationX: image.size.width, y: 0.0) transform = CGAffineTransform(rotationAngle: .pi / 2) case .right, .rightMirrored: transform = CGAffineTransform(translationX: 0, y: image.size.height) transform = CGAffineTransform(rotationAngle: -(.pi / 2)) case .up, .upMirrored: break @unknown default: break } switch image.imageOrientation { case .upMirrored, .downMirrored: transform = CGAffineTransform(translationX: image.size.width, y: 0.0) transform = CGAffineTransform(scaleX: -1.0, y: 1.0) case .leftMirrored, .rightMirrored: transform = CGAffineTransform(translationX: image.size.height, y: 0.0) transform = CGAffineTransform(scaleX: -1.0, y: 1.0) case .up, .down, .left, .right: break @unknown default: break } let context: CGContext = CGContext(data: nil, width: Int(image.size.width), height: Int(image.size.height), bitsPerComponent: image.cgImage!.bitsPerComponent, bytesPerRow: 0, space: image.cgImage!.colorSpace!, bitmapInfo: image.cgImage!.bitmapInfo.rawValue)! context.concatenate(transform) switch image.imageOrientation { case .left, .leftMirrored, .right, .rightMirrored: context.draw(image.cgImage!, in: CGRect(x: 0.0, y: 0.0, width: image.size.height, height: image.size.width)) default: context.draw(image.cgImage!, in: CGRect(x: 0.0, y: 0.0, width: image.size.width, height: image.size.height)) } let cgImage: CGImage = context.makeImage()! let fixedImage: UIImage = UIImage(cgImage: cgImage) return fixedImage } } extension UIAlertController { override open var preferredStatusBarStyle: UIStatusBarStyle { return .lightContent } } extension SwiftSimplePhotoPicker: UIImagePickerControllerDelegate, UINavigationControllerDelegate { func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) { picker.dismiss(animated: true, completion: nil) let editedImage: UIImage = fixOrientation(for: info[UIImagePickerController.InfoKey.editedImage] as? UIImage ?? UIImage()) if let completionBlock = self.completionBlock { DispatchQueue.main.async { completionBlock(editedImage) } } } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { picker.dismiss(animated: true, completion: nil) } }
2d1241cd58bdb4c4c6b7b0c90e502fe4
40.390625
120
0.64798
false
false
false
false
qiuncheng/CuteAttribute
refs/heads/master
CuteAttribute/CuteAttribute+NSRange.swift
mit
1
// // CuteAttribute+NSRange.swift // Cute // // Created by vsccw on 2017/8/11. // Copyright © 2017年 https://vsccw.com. All rights reserved. // import Foundation public extension CuteAttribute where Base: NSMutableAttributedString { /// Set the range. /// /// - Parameter range: NSRange value. /// - Returns: self func range(_ range: NSRange) -> CuteAttribute<Base> { assert(base.string.nsrange >> range, "range should be in range of string.") self.ranges = [range] return self } internal(set) var ranges: [NSRange] { get { let defaultRange = NSRange(location: 0, length: base.length) let value = (objc_getAssociatedObject(base, CuteAttributeKey.rangesKey) as? Box<[NSRange]>)?.value return value ?? [defaultRange] } set { let value = Box(newValue) objc_setAssociatedObject(base, CuteAttributeKey.rangesKey, value, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } /// Set the ranges. /// /// - Parameter ranges: [NSRange] value. /// - Returns: self func ranges(_ ranges: [NSRange]) -> CuteAttribute<Base> { let isValid = ranges .compactMap { return base.string.nsrange >> $0 } .reduce(true) { return $1 && $0 } assert(isValid, "ranges must in string.") self.ranges = ranges return self } }
04870746fc880653cce8c5667426d04e
28.541667
113
0.593794
false
false
false
false
Tonkpils/SpaceRun
refs/heads/master
SpaceRun/GameOverNode.swift
mit
1
// // GameOverNode.swift // SpaceRun // // Created by Leonardo Correa on 12/1/15. // Copyright © 2015 Leonardo Correa. All rights reserved. // import SpriteKit class GameOverNode: SKNode { override init() { super.init() let labelNode = SKLabelNode(fontNamed: "AvenirNext-Heavy") labelNode.fontSize = 32 labelNode.fontColor = SKColor.whiteColor() labelNode.text = "Game Over" self.addChild(labelNode) labelNode.alpha = 0 labelNode.xScale = 0.2 labelNode.yScale = 0.2 let fadeIn = SKAction.fadeAlphaTo(1, duration: 2) let scaleIn = SKAction.scaleTo(1, duration: 2) let fadeAndScale = SKAction.sequence([fadeIn, scaleIn]) labelNode.runAction(fadeAndScale) let instructionsNode = SKLabelNode(fontNamed: "AvenirNext-Medium") instructionsNode.fontSize = 14 instructionsNode.fontColor = SKColor.whiteColor() instructionsNode.text = "Tap to try again!" instructionsNode.position = CGPoint(x: 0, y: -45) self.addChild(instructionsNode) instructionsNode.alpha = 0 let wait = SKAction.waitForDuration(4) let appear = SKAction.fadeAlphaTo(1, duration: 0.2) let popUp = SKAction.scaleTo(1.1, duration: 0.1) let dropDown = SKAction.scaleTo(1, duration: 0.1) let pauseAndAppear = SKAction.sequence([wait, appear, popUp, dropDown]) instructionsNode.runAction(pauseAndAppear) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
e4a77cf85ead048027d2c6dd8756f5fe
28.777778
79
0.651741
false
false
false
false
nkennedydev/NF-Transit
refs/heads/master
NF-Transit/NF-Transit/Application/AppDelegate.swift
apache-2.0
1
// // AppDelegate.swift // NF-Transit // // Created by Niall on 2017-06-26. // Copyright © 2017 nkdev. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. 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:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "NF_Transit") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
59eb11f76eb3107af806a3063c22952b
48.301075
285
0.685278
false
false
false
false
tkremenek/swift
refs/heads/master
test/Concurrency/throwing.swift
apache-2.0
1
// RUN: %target-run-simple-swift(-Xfrontend -enable-experimental-concurrency -Xfrontend -disable-availability-checking -parse-as-library) // REQUIRES: executable_test // REQUIRES: concurrency // UNSUPPORTED: use_os_stdlib // UNSUPPORTED: back_deployment_runtime import _Concurrency import StdlibUnittest class P<T> { var t: T init(_ v: T) { t = v } } class A {} class B {} class C {} enum E : Error { case err } protocol MP { } class M : MP { @available(SwiftStdlib 5.5, *) func throwWithIndirectResult<T>(_ a: P<T>) async throws -> T { throw E.err } } extension MP { @available(SwiftStdlib 5.5, *) func l<A, B, C, D, E2, F> (_ a : P<A>, _ b: P<B>, _ c: P<C>, _ d : P<D>, _ e: P<E2>, _ f: P<F>) async throws -> (A, B, C, D, E2, F) { throw E.err } } @main struct Main { static func main() async { var tests = TestSuite("Async Throw") if #available(SwiftStdlib 5.5, *) { tests.test("throwing of naturally direct but indirect reabstration") { let task2 = detach { let m = M() await verifyCancelled { try await m.l(P(A()), P(B()), P(C()), P(A()), P(B()), P(C())) } func verifyCancelled<T>(execute operation: () async throws -> T) async { do { let _ = try await operation() assertionFailure("operation() threw") } catch _ as E { // This is what we expect to happen } catch { assertionFailure("unknown error thrown") } } } _ = await task2.get() } tests.test("throwing with indirect result") { let task2 = detach { let m = M() do { let _ = try await m.throwWithIndirectResult(P(A())) assertionFailure("operation() threw") } catch _ as E { // This is what we expect to happen } catch { assertionFailure("unknown error thrown") } } _ = await task2.get() } } await runAllTestsAsync() } }
cb982caf8ca059d41ee25833bc44826c
22.842697
137
0.520264
false
true
false
false
furuya02/ProvisioningProfileExplorer
refs/heads/master
ProvisioningProfileExplorer/Certificate.swift
mit
1
// // ertificate.swift // ProvisioningProfileExplorer // // Created by hirauchi.shinichi on 2016/04/16. // Copyright © 2016年 SAPPOROWORKS. All rights reserved. // import Cocoa class Certificate: NSObject { var summary: String = "" var expires: NSDate? = nil var lastDays = 0 init(summary:String,expires:NSDate?,lastDays:Int){ self.summary = summary self.expires = expires self.lastDays = lastDays } }
35400dd8a6c7545b813ce4bd7043e063
20.52381
56
0.661504
false
false
false
false
levyjm/SecureCoffee
refs/heads/master
SecureCoffee/CheckVitals.swift
mit
1
// // CheckVitals.swift // SecureCoffee // // Created by John on 1/9/17. // Copyright © 2017 john. All rights reserved. // import Foundation import Cocoa class CheckVitals: NSObject { let instanceOfSendText: SendText = SendText() let instanceOfCheckSMS: CheckSMS = CheckSMS() let instanceOfCheckPowerSource: CheckPowerSource = CheckPowerSource() var x = 0 var y = 0 func getStatus() -> Void { if (loggedBackIn == 0) { if (instanceOfCheckPowerSource.checkBattery() == -2 && y == 0) { watchBattery() y = 1 } } } func watchBattery() -> Void { while (loggedBackIn == 0) { usleep(100000) if (instanceOfCheckPowerSource.checkBattery() != -2) { instanceOfSendText.sendBatteryTextAlert() sleep(10) } } } func watchMovement() -> Void { let watchZValue: Double = instanceOfCheckSMS.run() var currentZValue: Double = watchZValue while (loggedBackIn == 0) { usleep(100000) if (currentZValue > (watchZValue + 0.10) || currentZValue < (watchZValue - 0.10)){ instanceOfSendText.sendMovementTextAlert() sleep(10) } currentZValue = instanceOfCheckSMS.run() } } }
ef0332b3ab47397fceb75b0700adaa08
23.810345
94
0.530229
false
false
false
false
PureSwift/Bluetooth
refs/heads/master
Sources/BluetoothHCI/HCIEncryptionKeyRefreshComplete.swift
mit
1
// // HCIEncryptionKeyRefreshComplete.swift // Bluetooth // // Created by Alsey Coleman Miller on 6/14/18. // Copyright © 2018 PureSwift. All rights reserved. // import Foundation /// Encryption Key Refresh Complete Event /// /// The Encryption Key Refresh Complete event is used to indicate to the Host that the encryption key was /// refreshed on the given Connection_Handle any time encryption is paused and then resumed. /// The BR/EDR Controller shall send this event when the encryption key has been refreshed /// due to encryption being started or resumed. /// /// If the Encryption Key Refresh Complete event was generated due to an encryption pause /// and resume operation embedded within a change connection link key procedure, t /// he Encryption Key Refresh Complete event shall be sent prior to the Change Connection Link Key Complete event. /// /// If the Encryption Key Refresh Complete event was generated due to an encryption pause and /// resume operation embedded within a role switch procedure, /// the Encryption Key Refresh Complete event shall be sent prior to the Role Change event. @frozen public struct HCIEncryptionKeyRefreshComplete: HCIEventParameter { public static let event = HCIGeneralEvent.encryptionKeyRefreshComplete // 0x30 public static let length: Int = 3 public let status: HCIStatus public let handle: UInt16 // Connection_Handle public init?(data: Data) { guard data.count == type(of: self).length else { return nil } let statusByte = data[0] let handle = UInt16(littleEndian: UInt16(bytes: (data[1], data[2]))) guard let status = HCIStatus(rawValue: statusByte) else { return nil } self.status = status self.handle = handle } }
de952958061d0516ce92339b86c5c831
35.156863
114
0.700108
false
false
false
false
vermont42/Conjugar
refs/heads/master
ConjugarTests/Controllers/InfoVCTests.swift
agpl-3.0
1
// // InfoVCTests.swift // ConjugarTests // // Created by Joshua Adams on 5/23/19. // Copyright © 2019 Josh Adams. All rights reserved. // import XCTest import UIKit @testable import Conjugar class InfoVCTests: XCTestCase, InfoDelegate { var newHeading = "" func infoSelectionDidChange(newHeading: String) { self.newHeading = newHeading } func testInfoVC() { var analytic = "" Current = World.unitTest Current.analytics = TestAnalyticsService(fire: { fired in analytic = fired }) let urlString = "https://racecondition.software" guard let url = URL(string: urlString) else { XCTFail("Could not create URL.") return } let nonURLInfoString = "info" guard let nonURLInfoURL = URL(string: nonURLInfoString) else { XCTFail("Could not create nonURLInfoURL.") return } let ivc = InfoVC(infoString: NSAttributedString(string: "\(nonURLInfoString)\(url)"), infoDelegate: self) XCTAssertNotNil(ivc) XCTAssertNotNil(ivc.infoView) ivc.viewWillAppear(true) XCTAssertEqual(analytic, "visited viewController: \(InfoVC.self) ") XCTAssertEqual(newHeading, "") var shouldInteract = ivc.textView(UITextView(), shouldInteractWith: nonURLInfoURL, in: NSRange(location: 0, length: nonURLInfoString.count)) XCTAssertFalse(shouldInteract) XCTAssertEqual(newHeading, nonURLInfoString) shouldInteract = ivc.textView(UITextView(), shouldInteractWith: url, in: NSRange(location: nonURLInfoString.count, length: "\(url)".count)) XCTAssert(shouldInteract) } }
0f622e66f100b9a70b457a2140facf0c
29.038462
144
0.711908
false
true
false
false
VitoNYang/VTAutoSlideView
refs/heads/master
VTAutoSlideViewDemo/UseInCodeViewController.swift
mit
1
// // UseInCodeViewController.swift // VTAutoSlideView // // Created by hao Mac Mini on 2017/2/8. // Copyright © 2017年 Vito. All rights reserved. // import UIKit import VTAutoSlideView class UseInCodeViewController: UIViewController { lazy var slideView: VTAutoSlideView = { let slideView = VTAutoSlideView(direction: .vertical, dataSource: self) return slideView }() lazy var imageList = { // compactMap 不同于 map 的是, compactMap 会筛选非空元素 (1...4).compactMap { UIImage(named: "0\($0)") } }() override func viewDidLoad() { super.viewDidLoad() slideView.register(nib: UINib(nibName: "DisplayImageCell", bundle: nibBundle)) slideView.dataList = imageList slideView.activated = false // 关闭自动轮播功能 view.addSubview(slideView) slideView.translatesAutoresizingMaskIntoConstraints = false // add constraints NSLayoutConstraint.activate([ slideView.leadingAnchor.constraint(equalTo: view.safeLeadingAnchor), slideView.topAnchor.constraint(equalTo: safeTopAnchor, constant: 20), slideView.trailingAnchor.constraint(equalTo: view.safeTrailingAnchor), slideView.heightAnchor.constraint(equalToConstant: view.bounds.height * 0.5) ]) } } extension UseInCodeViewController: VTAutoSlideViewDataSource { func configuration(cell: UICollectionViewCell, for index: Int) { guard let cell = cell as? DisplayImageCell else { return } cell.imageView.image = imageList[index] } } extension UIViewController { var safeTopAnchor: NSLayoutYAxisAnchor { if #available(iOS 11.0, *) { return view.safeAreaLayoutGuide.topAnchor } else { return topLayoutGuide.bottomAnchor } } } extension UIView { var safeTopAnchor: NSLayoutYAxisAnchor { if #available(iOS 11.0, *) { return self.safeAreaLayoutGuide.topAnchor } else { return self.topAnchor } } var safeBottomAnchor: NSLayoutYAxisAnchor { if #available(iOS 11.0, *) { return self.safeAreaLayoutGuide.bottomAnchor } else { return self.bottomAnchor } } var safeLeadingAnchor: NSLayoutXAxisAnchor { if #available(iOS 11.0, *) { return self.safeAreaLayoutGuide.leadingAnchor } else { return self.leadingAnchor } } var safeTrailingAnchor: NSLayoutXAxisAnchor { if #available(iOS 11.0, *) { return self.safeAreaLayoutGuide.trailingAnchor } else { return self.trailingAnchor } } }
4cb0fa654567474d2edae0a37e525cd4
27.65625
88
0.625954
false
false
false
false
leancloud/objc-sdk
refs/heads/master
AVOS/LeanCloudObjcTests/LCIMConversationTestCase.swift
apache-2.0
1
// // LCIMConversationTestCase.swift // LeanCloudObjcTests // // Created by 黄驿峰 on 2021/12/17. // Copyright © 2021 LeanCloud Inc. All rights reserved. // import XCTest import XCTest @testable import LeanCloudObjc import CoreMedia extension LCIMConversationTestCase { } class LCIMConversationTestCase: RTMBaseTestCase { func testCreateConversationThenErrorThrows() { let client: LCIMClient! = try? LCIMClient.init(clientId: uuid) XCTAssertNotNil(client) expecting(description: "not open") { exp in client.createConversation(withClientIds: []) { conversation, error in XCTAssertTrue(Thread.isMainThread) XCTAssertNotNil(error) XCTAssertNil(conversation) exp.fulfill() } } expecting { exp in let invalidID: String = Array<String>.init(repeating: "a", count: 65).joined() client.createConversation(withClientIds: [invalidID]) { conversation, error in XCTAssertTrue(Thread.isMainThread) XCTAssertNotNil(error) XCTAssertNil(conversation) exp.fulfill() } } } func testCreateNormalConversation() { let delegatorA = LCIMClientDelegator.init() let delegatorB = LCIMClientDelegator.init() let clientA = newOpenedClient(delegator: delegatorA) let clientB = newOpenedClient(delegator: delegatorB) let delegators = [delegatorA, delegatorB]; let name: String? = "normalConv" let attribution: [String: Any] = [ "String": "", "Int": 1, "Double": 1.0, "Bool": true, "Array": Array<String>(), "Dictionary": Dictionary<String, Any>() ] let convAssertion: (LCIMConversation, LCIMClient) -> Void = { conv, client in XCTAssertTrue(type(of: conv) == LCIMConversation.self) guard let convAttr = conv.attributes as? [String: Any] else { XCTFail() return } // XCTAssertEqual(conv["objectId"] as? String, conv.conversationId) XCTAssertEqual(conv.convType.rawValue, 1) // conv. == .normal XCTAssertEqual(conv.convType, .normal) XCTAssertEqual(conv.members?.count, 2) XCTAssertEqual(conv.members?.contains(clientA.clientId), true) XCTAssertEqual(conv.members?.contains(clientB.clientId), true) XCTAssertNotNil(conv.imClient) XCTAssertTrue(conv.imClient === client) XCTAssertEqual(conv.clientId, client.clientId) XCTAssertFalse(conv.unique) XCTAssertNil(conv.uniqueId) XCTAssertEqual(conv.creator, clientA.clientId) XCTAssertNotNil(conv.updatedAt ?? conv.createdAt) XCTAssertFalse(conv.muted) XCTAssertNil(conv.lastMessage) XCTAssertEqual(conv.unreadMessagesCount, 0) XCTAssertFalse(conv.unreadMessagesMentioned) if let name: String = name { XCTAssertEqual(name, conv.name) } else { XCTAssertNil(conv.name) } XCTAssertEqual(attribution.count, convAttr.count) for (key, value) in attribution { switch key { case "String": XCTAssertEqual(value as? String, convAttr[key] as? String) case "Int": XCTAssertEqual(value as? Int, convAttr[key] as? Int) case "Double": XCTAssertEqual(value as? Double, convAttr[key] as? Double) case "Bool": XCTAssertEqual(value as? Bool, convAttr[key] as? Bool) case "Array": XCTAssertEqual((value as? Array<String>)?.isEmpty, true) XCTAssertEqual((convAttr[key] as? Array<String>)?.isEmpty, true) case "Dictionary": XCTAssertEqual((value as? Dictionary<String, Any>)?.isEmpty, true) XCTAssertEqual((convAttr[key] as? Dictionary<String, Any>)?.isEmpty, true) default: XCTFail() } } } expecting(description: "create conversation", count: 5) { exp in delegators.forEach { $0.conversationEvent = { client, conv, event in XCTAssertTrue(Thread.isMainThread) convAssertion(conv, client) switch event { case .joined(byClientID: let cID): XCTAssertEqual(cID, clientA.ID) exp.fulfill() case .membersJoined(members: let members, byClientID: let byClientID): XCTAssertEqual(byClientID, clientA.ID) XCTAssertEqual(Set(members), Set([clientA.ID, clientB.ID])) exp.fulfill() default: break } } } let options = LCIMConversationCreationOption.init() options.name = name options.attributes = attribution options.isUnique = false clientA.createConversation(withClientIds: [clientA.ID, clientB.ID], option: options) { conv, error in XCTAssertTrue(Thread.isMainThread) if let conv = conv, let client = conv.imClient { convAssertion(conv, client) } else { XCTFail() } exp.fulfill() } } // delay(seconds: 5) XCTAssertEqual(clientA.convCollection.count, 1) XCTAssertEqual(clientB.convCollection.count, 1) XCTAssertEqual( clientA.convCollection.first?.value.ID, clientB.convCollection.first?.value.ID ) XCTAssertTrue(clientA.convQueryCallbackCollection.isEmpty) XCTAssertTrue(clientB.convQueryCallbackCollection.isEmpty) } func testCreateNormalAndUniqueConversation() { let delegatorA = LCIMClientDelegator.init() let delegatorB = LCIMClientDelegator.init() let clientA = newOpenedClient(delegator: delegatorA) let clientB = newOpenedClient(delegator: delegatorB) let existingKey = "existingKey" let existingValue = "existingValue" let delegators = [delegatorA, delegatorB]; expecting(description: "create unique conversation", count: 5) { exp in delegators.forEach { $0.conversationEvent = { _, _, event in switch event { case .joined: exp.fulfill() case .membersJoined: exp.fulfill() default: break } } } let options = LCIMConversationCreationOption.init() options.attributes = [existingKey : existingValue] clientA.createConversation(withClientIds: [clientA.ID, clientB.ID], option: options) { conv, error in XCTAssertTrue(Thread.isMainThread) if let conv = conv { XCTAssertEqual(conv.convType, .normal) XCTAssertTrue(conv.unique) XCTAssertNotNil(conv.uniqueId) XCTAssertEqual(conv.attributes?[existingKey] as? String, existingValue) } else { XCTFail() } exp.fulfill() } } delegatorA.conversationEvent = nil delegatorB.conversationEvent = nil delay(seconds: 5) clientB.convCollection.removeAll() expecting(description: "recreate unique conversation") { exp in clientB.createConversation(withClientIds: [clientA.ID, clientB.ID]) { conv, error in if let conv = conv { XCTAssertEqual(conv.convType, .normal) XCTAssertTrue(conv.unique) XCTAssertNotNil(conv.uniqueId) XCTAssertNil(conv.attributes?[existingKey]) conv.fetch { ret, error in XCTAssertNil(error) XCTAssertTrue(ret) XCTAssertEqual(conv.attributes?[existingKey] as? String, existingValue) exp.fulfill() } } else { XCTFail() exp.fulfill() } } } XCTAssertEqual( clientA.convCollection.first?.value.ID, clientB.convCollection.first?.value.ID ) XCTAssertEqual( clientA.convCollection.first?.value.uniqueID, clientB.convCollection.first?.value.uniqueID ) } func testCreateChatRoom() { let client = newOpenedClient() expecting(description: "create chat room") { exp in client.createChatRoom { chatRoom, error in XCTAssertTrue(Thread.isMainThread) XCTAssertEqual(chatRoom?.convType, .transient) XCTAssertEqual(chatRoom?.convType.rawValue, 2) XCTAssertEqual(chatRoom?.members?.count, 1) exp.fulfill() } } } func testCreateTemporaryConversation() { let delegatorA = LCIMClientDelegator.init() let delegatorB = LCIMClientDelegator.init() let clientA = newOpenedClient(delegator: delegatorA) let clientB = newOpenedClient(delegator: delegatorB) let delegators = [delegatorA, delegatorB]; let ttl: Int32 = 3600 expecting(description: "create conversation", count: 5) { exp in delegators.forEach { $0.conversationEvent = { client, conv, event in XCTAssertEqual(conv.convType, .temporary) XCTAssertEqual((conv as? LCIMTemporaryConversation)?.timeToLive, Int(ttl)) switch event { case .joined(byClientID: let cID): XCTAssertEqual(cID, clientA.ID) exp.fulfill() case .membersJoined(members: let members, byClientID: let byClientID): XCTAssertEqual(byClientID, clientA.ID) XCTAssertEqual(Set(members), Set([clientA.ID, clientB.ID])) exp.fulfill() default: break } } } let options = LCIMConversationCreationOption.init() options.timeToLive = UInt(ttl) clientA.createTemporaryConversation(withClientIds: [clientA.ID, clientB.ID], option: options) { conv, error in if let conv = conv { XCTAssertEqual(conv.convType, .temporary) XCTAssertEqual(conv.rawJSONDataCopy()["objectId"] as? String, conv.ID) XCTAssertEqual(conv.convType.rawValue, 4) XCTAssertEqual(conv.timeToLive, Int(ttl)) } else { XCTFail() } exp.fulfill() } } XCTAssertEqual( clientA.convCollection.first?.value.ID, clientB.convCollection.first?.value.ID ) XCTAssertEqual( clientA.convCollection.first?.value.ID.hasPrefix(kTemporaryConversationIdPrefix), true ) } func testServiceConversationSubscription() { let client = newOpenedClient() let serviceConversationID = newServiceConversation() var serviceConversation: LCIMServiceConversation! expecting { (exp) in client.conversationQuery().getConversationById(serviceConversationID) { conv, error in XCTAssertNotNil(conv) XCTAssertNil(error) XCTAssertEqual(conv?.rawJSONDataCopy()["objectId"] as? String, conv?.ID) XCTAssertEqual(conv?.convType.rawValue, 3) serviceConversation = conv as? LCIMServiceConversation exp.fulfill() } } XCTAssertNotNil(serviceConversation) expecting( description: "service conversation subscription", count: 1) { (exp) in serviceConversation.subscribe { ret, error in XCTAssertTrue(ret) XCTAssertNil(error) exp.fulfill() } } let query = client.conversationQuery() expecting { exp in query.getConversationById(serviceConversationID) { conv, error in XCTAssertNil(error) if let conv = conv { XCTAssertEqual(conv.muted, false) XCTAssertNotNil(conv.rawJSONDataCopy()["joinedAt"]) } else { XCTFail() } exp.fulfill() } } } func testNormalConversationUnreadEvent() { let clientA = newOpenedClient() let clientBID = uuid var conversation1: LCIMConversation! var conversation2: LCIMConversation! let message1 = LCIMMessage.init(content: uuid) let message2 = LCIMMessage.init(content: uuid) expecting( description: "create conversation, then send message", count: 4) { (exp) in let option = LCIMConversationCreationOption.init() option.isUnique = false clientA.createConversation(withClientIds: [clientBID], option: option) { conv1, error in XCTAssertNil(error) XCTAssertNotNil(conv1) conversation1 = conv1 exp.fulfill() conv1?.send(message1, callback: { ret, error in XCTAssertNil(error) XCTAssertTrue(ret) exp.fulfill() clientA.createConversation(withClientIds: [clientBID], option: option) { conv2, error in XCTAssertNil(error) XCTAssertNotNil(conv2) conversation2 = conv2 exp.fulfill() conv2?.send(message2, callback: { ret, error in XCTAssertNil(error) XCTAssertTrue(ret) exp.fulfill() }) } }) } } delay() XCTAssertNotNil(conversation1) XCTAssertNotNil(conversation2) LCRTMConnectionManager.shared().imProtobuf1Registry.removeAllObjects() LCRTMConnectionManager.shared().imProtobuf3Registry.removeAllObjects() let delegatorB = LCIMClientDelegator.init() let clientB: LCIMClient! = try? LCIMClient.init(clientId: clientBID) XCTAssertNotNil(clientB) clientB.delegate = delegatorB expecting( description: "open, then receive unread event", count: 5) { (exp) in delegatorB.conversationEvent = { client, conversation, event in if conversation.ID == conversation1.ID { switch event { case .lastMessageUpdated: let lastMessage = conversation.lastMessage XCTAssertEqual(lastMessage?.conversationID, message1.conversationID) XCTAssertEqual(lastMessage?.sentTimestamp, message1.sentTimestamp) XCTAssertEqual(lastMessage?.ID, message1.ID) exp.fulfill() case .unreadMessageCountUpdated: XCTAssertEqual(conversation.unreadMessageCount, 1) // XCTAssertTrue(conversation.isUnreadMessageContainMention) exp.fulfill() default: break } } else if conversation.ID == conversation2.ID { switch event { case .lastMessageUpdated: let lastMessage = conversation.lastMessage XCTAssertEqual(lastMessage?.conversationID, message2.conversationID) XCTAssertEqual(lastMessage?.sentTimestamp, message2.sentTimestamp) XCTAssertEqual(lastMessage?.ID, message2.ID) exp.fulfill() case .unreadMessageCountUpdated: XCTAssertEqual(conversation.unreadMessageCount, 1) XCTAssertFalse(conversation.isUnreadMessageContainMention) exp.fulfill() default: break } } } clientB.open { ret, error in XCTAssertTrue(ret) XCTAssertNil(error) exp.fulfill() } } expecting { (exp) in delegatorB.clientEvent = { client, event in switch event { case .sessionDidPause: exp.fulfill() default: break } } clientB.connection.disconnect() } delay() XCTAssertTrue(clientB.lastUnreadNotifTime != 0) let message3 = LCIMMessage.init(content: uuid) expecting { (exp) in conversation1.send(message3, callback: { ret, error in XCTAssertNil(error) XCTAssertTrue(ret) exp.fulfill() }) } expecting( description: "reconnect, then receive unread event", count: 3) { (exp) in delegatorB.clientEvent = { client, event in switch event { case .sessionDidOpen: exp.fulfill() default: break } } delegatorB.conversationEvent = { client, conversation, event in if conversation.ID == conversation1.ID { switch event { case .lastMessageUpdated: let lastMessage = conversation.lastMessage XCTAssertEqual(lastMessage?.conversationID, message3.conversationID) XCTAssertEqual(lastMessage?.sentTimestamp, message3.sentTimestamp) XCTAssertEqual(lastMessage?.ID, message3.ID) exp.fulfill() case .unreadMessageCountUpdated: XCTAssertEqual(conversation.unreadMessageCount, 2) // XCTAssertTrue(conversation.isUnreadMessageContainMention) exp.fulfill() default: break } } } clientB.connection.testConnect() } expecting( description: "read", count: 2) { (exp) in delegatorB.conversationEvent = { client, conversation, event in if conversation.ID == conversation1.ID { switch event { case .unreadMessageCountUpdated: XCTAssertEqual(conversation.unreadMessageCount, 0) exp.fulfill() default: break } } else if conversation.ID == conversation2.ID { switch event { case .unreadMessageCountUpdated: XCTAssertEqual(conversation.unreadMessageCount, 0) exp.fulfill() default: break } } } for (_, conv) in clientB.convCollection { conv.read() } } } func testTemporaryConversationUnreadEvent() { let clientA = newOpenedClient() let otherClientID: String = uuid let message = LCIMMessage.init(content: "test") message.isAllMembersMentioned = true expecting(description: "create temporary conversation and send message", count: 2) { exp in let options = LCIMConversationCreationOption.init() options.timeToLive = 3600 clientA.createTemporaryConversation(withClientIds: [otherClientID], option: options) { conv, error in XCTAssertNil(error) XCTAssertNotNil(conv) conv?.send(message, callback: { ret, error in XCTAssertNil(error) XCTAssertTrue(ret) exp.fulfill() }) exp.fulfill() } } let delegator = LCIMClientDelegator.init() let clientB: LCIMClient! = try? LCIMClient.init(clientId: otherClientID) XCTAssertNotNil(clientB) clientB.delegate = delegator expecting(description: "opened and get unread event", count: 3) { exp in delegator.conversationEvent = { client, conversation, event in if client === clientB, conversation.ID == message.conversationID { switch event { case .lastMessageUpdated: XCTAssertEqual(conversation.lastMessage?.conversationID, message.conversationID) XCTAssertEqual(conversation.lastMessage?.sentTimestamp, message.sentTimestamp) XCTAssertEqual(conversation.lastMessage?.ID, message.ID) exp.fulfill() case .unreadMessageCountUpdated: XCTAssertEqual(conversation.unreadMessageCount, 1) XCTAssertTrue(conversation.isUnreadMessageContainMention) exp.fulfill() default: break } } } clientB.open { ret, error in XCTAssertTrue(ret) XCTAssertNil(error) exp.fulfill() } } expecting(description: "read") { exp in delegator.conversationEvent = { client, conversation, event in if client === clientB, conversation.ID == message.conversationID { if case .unreadMessageCountUpdated = event { XCTAssertEqual(conversation.unreadMessageCount, 0) exp.fulfill() } } } for (_, conv) in clientB.convCollection { conv.read() } } } func testServiceConversationUnreadEvent() { let clientID = uuid let serviceConvID = newServiceConversation() XCTAssertTrue(subscribing(serviceConversation: serviceConvID, by: clientID)) broadcastingMessage(to: serviceConvID) delay(seconds: 15) let delegator = LCIMClientDelegator.init() let clientA: LCIMClient! = try? LCIMClient.init(clientId: clientID) XCTAssertNotNil(clientA) clientA.delegate = delegator expecting(description: "opened and get unread event", count: 3) { exp in delegator.conversationEvent = { client, conversation, event in if client === clientA, conversation.ID == serviceConvID { switch event { case .lastMessageUpdated: exp.fulfill() case .unreadMessageCountUpdated: exp.fulfill() default: break } } } clientA.open { ret, error in XCTAssertTrue(ret) XCTAssertNil(error) exp.fulfill() } } expecting(description: "read") { exp in delegator.conversationEvent = { client, conversation, event in if client === clientA, conversation.ID == serviceConvID { if case .unreadMessageCountUpdated = event { XCTAssertEqual(conversation.unreadMessageCount, 0) exp.fulfill() } } } for (_, conv) in clientA.convCollection { conv.read() } } } func testLargeUnreadEvent() { let clientA = newOpenedClient() let otherClientID: String = uuid let count: Int = 20 for i in 0..<count { let exp = expectation(description: "create conversation and send message") exp.expectedFulfillmentCount = 2 let message = LCIMMessage.init(content: "test") if i % 2 == 0 { let options = LCIMConversationCreationOption.init() options.timeToLive = 3600 clientA.createTemporaryConversation(withClientIds: [otherClientID], option: options) { conv, error in XCTAssertNil(error) XCTAssertNotNil(conv) conv?.send(message, callback: { ret, error in XCTAssertNil(error) XCTAssertTrue(ret) exp.fulfill() }) exp.fulfill() } wait(for: [exp], timeout: timeout) } else { let option = LCIMConversationCreationOption.init() option.isUnique = false clientA.createConversation(withClientIds: [otherClientID], option: option) { conv, error in XCTAssertNil(error) XCTAssertNotNil(conv) conv?.send(message, callback: { ret, error in XCTAssertNil(error) XCTAssertTrue(ret) exp.fulfill() }) exp.fulfill() } wait(for: [exp], timeout: timeout) } } let convIDSet = Set<String>(clientA.convCollection.keys) let delegator = LCIMClientDelegator.init() let clientB: LCIMClient! = try? LCIMClient.init(clientId: otherClientID) XCTAssertNotNil(clientB) clientB.delegate = delegator let largeUnreadExp = expectation(description: "opened and get large unread event") largeUnreadExp.expectedFulfillmentCount = (count + 2) + 1 // var lcount = 0 // var ucount = 0 delegator.conversationEvent = { client, conversaton, event in switch event { case .lastMessageUpdated: // lcount += 1 // print("lastMessageUpdated count---\(lcount)") largeUnreadExp.fulfill() case .unreadMessageCountUpdated: // ucount += 1 // print("unreadMessageCountUpdated count---\(ucount)") largeUnreadExp.fulfill() default: break } } clientB.open { ret, error in XCTAssertTrue(ret) XCTAssertNil(error) largeUnreadExp.fulfill() } wait(for: [largeUnreadExp], timeout: timeout) delay() XCTAssertNotNil(clientB.lastUnreadNotifTime) let allReadExp = expectation(description: "all read") allReadExp.expectedFulfillmentCount = count delegator.conversationEvent = { client, conversation, event in if client === clientB, convIDSet.contains(conversation.ID) { if case .unreadMessageCountUpdated = event { allReadExp.fulfill() } } } for (_, conv) in clientB.convCollection { conv.read() } wait(for: [allReadExp], timeout: timeout) delegator.reset() } func testMembersChange() { let delegatorA = LCIMClientDelegator.init() let delegatorB = LCIMClientDelegator.init() let clientA = newOpenedClient(delegator: delegatorA) let clientB = newOpenedClient(delegator: delegatorB) var convA: LCIMConversation! expecting( description: "create conversation", count: 5) { (exp) in delegatorA.conversationEvent = { client, conv, event in switch event { case let .joined(byClientID: byClientID): XCTAssertEqual(byClientID, clientA.ID) exp.fulfill() case let .membersJoined(members: members, byClientID: byClientID): XCTAssertEqual(members.count, 2) XCTAssertTrue(members.contains(clientA.ID)) XCTAssertTrue(members.contains(clientB.ID)) XCTAssertEqual(byClientID, clientA.ID) exp.fulfill() default: break } } delegatorB.conversationEvent = { client, conv, event in switch event { case let .joined(byClientID: byClientID): XCTAssertEqual(byClientID, clientA.ID) exp.fulfill() case let .membersJoined(members: members, byClientID: byClientID): XCTAssertEqual(members.count, 2) XCTAssertTrue(members.contains(clientA.ID)) XCTAssertTrue(members.contains(clientB.ID)) XCTAssertEqual(byClientID, clientA.ID) exp.fulfill() default: break } } clientA.createConversation(withClientIds: [clientB.ID]) { conv, error in XCTAssertNil(error) XCTAssertNotNil(conv) convA = conv exp.fulfill() } } let convB = clientB.convCollection[convA?.ID ?? ""] XCTAssertNotNil(convB) expecting( description: "leave", count: 3) { (exp) in delegatorA.conversationEvent = { client, conv, event in switch event { case let .membersLeft(members: members, byClientID: byClientID): XCTAssertEqual(byClientID, clientB.ID) XCTAssertEqual(members.count, 1) XCTAssertTrue(members.contains(clientB.ID)) XCTAssertEqual(conv.members?.count, 1) XCTAssertEqual(conv.members?.first, clientA.ID) exp.fulfill() default: break } } delegatorB.conversationEvent = { client, conv, event in switch event { case let .left(byClientID: byClientID): XCTAssertEqual(byClientID, clientB.ID) XCTAssertEqual(conv.members?.count, 1) XCTAssertEqual(conv.members?.first, clientA.ID) exp.fulfill() default: break } } convB?.quit(callback: { ret, error in XCTAssertTrue(Thread.isMainThread) XCTAssertTrue(ret) XCTAssertNil(error) exp.fulfill() }) } expecting( description: "join", count: 4) { (exp) in delegatorA.conversationEvent = { client, conv, event in switch event { case let .membersJoined(members: members, byClientID: byClientID): XCTAssertEqual(byClientID, clientB.ID) XCTAssertEqual(members.count, 1) XCTAssertTrue(members.contains(clientB.ID)) XCTAssertEqual(conv.members?.count, 2) XCTAssertEqual(conv.members?.contains(clientA.ID), true) XCTAssertEqual(conv.members?.contains(clientB.ID), true) exp.fulfill() default: break } } delegatorB.conversationEvent = { client, conv, event in switch event { case let .joined(byClientID: byClientID): XCTAssertEqual(byClientID, clientB.ID) XCTAssertEqual(conv.members?.count, 2) XCTAssertEqual(conv.members?.contains(clientA.ID), true) XCTAssertEqual(conv.members?.contains(clientB.ID), true) exp.fulfill() case let .membersJoined(members: members, byClientID: byClientID): XCTAssertEqual(byClientID, clientB.ID) XCTAssertEqual(members.count, 1) XCTAssertTrue(members.contains(clientB.ID)) XCTAssertEqual(conv.members?.count, 2) XCTAssertEqual(conv.members?.contains(clientA.ID), true) XCTAssertEqual(conv.members?.contains(clientB.ID), true) exp.fulfill() default: break } } convB?.join { ret, error in XCTAssertTrue(Thread.isMainThread) XCTAssertTrue(ret) XCTAssertNil(error) exp.fulfill() } } expecting( description: "remove", count: 3) { (exp) in delegatorA.conversationEvent = { client, conv, event in switch event { case let .membersLeft(members: members, byClientID: byClientID): XCTAssertEqual(byClientID, clientA.ID) XCTAssertEqual(members.count, 1) XCTAssertEqual(members.first, clientB.ID) XCTAssertEqual(conv.members?.count, 1) XCTAssertEqual(conv.members?.first, clientA.ID) exp.fulfill() default: break } } delegatorB.conversationEvent = { client, conv, event in switch event { case let .left(byClientID: byClientID): XCTAssertEqual(byClientID, clientA.ID) XCTAssertEqual(conv.members?.count, 1) XCTAssertEqual(conv.members?.first, clientA.ID) exp.fulfill() default: break } } convA?.removeMembers(withClientIds: [clientB.ID]) { ret, error in XCTAssertTrue(Thread.isMainThread) XCTAssertTrue(ret) XCTAssertNil(error) exp.fulfill() } } expecting( description: "add", count: 4) { (exp) in delegatorA.conversationEvent = { client, conv, event in switch event { case let .membersJoined(members: members, byClientID: byClientID): XCTAssertEqual(byClientID, clientA.ID) XCTAssertEqual(members.count, 1) XCTAssertEqual(members.first, clientB.ID) XCTAssertEqual(conv.members?.count, 2) XCTAssertEqual(conv.members?.contains(clientA.ID), true) XCTAssertEqual(conv.members?.contains(clientB.ID), true) exp.fulfill() default: break } } delegatorB.conversationEvent = { client, conv, event in switch event { case let .joined(byClientID: byClientID): XCTAssertEqual(byClientID, clientA.ID) XCTAssertEqual(conv.members?.count, 2) XCTAssertEqual(conv.members?.contains(clientA.ID), true) XCTAssertEqual(conv.members?.contains(clientB.ID), true) exp.fulfill() case let .membersJoined(members: members, byClientID: byClientID): XCTAssertEqual(byClientID, clientA.ID) XCTAssertEqual(members.count, 1) XCTAssertEqual(members.first, clientB.ID) XCTAssertEqual(conv.members?.count, 2) XCTAssertEqual(conv.members?.contains(clientA.ID), true) XCTAssertEqual(conv.members?.contains(clientB.ID), true) exp.fulfill() default: break } } convA?.addMembers(withClientIds: [clientB.ID], callback: { ret, error in XCTAssertTrue(Thread.isMainThread) XCTAssertTrue(ret) XCTAssertNil(error) exp.fulfill() }) } expecting { (exp) in convA?.countMembers(callback: { num, error in XCTAssertTrue(Thread.isMainThread) XCTAssertNil(error) XCTAssertEqual(num, 2); exp.fulfill() }) } } func testGetChatRoomOnlineMembers() { let clientA = newOpenedClient() let clientB = newOpenedClient() var chatRoomA: LCIMChatRoom? expecting { (exp) in clientA.createChatRoom { room, error in XCTAssertNil(error) XCTAssertNotNil(room) chatRoomA = room exp.fulfill() } } var chatRoomB: LCIMChatRoom? expecting { (exp) in if let ID = chatRoomA?.ID { clientB.conversationQuery().getConversationById(ID) { conv, error in XCTAssertNil(error) XCTAssertNotNil(conv) chatRoomB = conv as? LCIMChatRoom exp.fulfill() } } else { XCTFail() exp.fulfill() } } expecting( description: "get online count", count: 7) { (exp) in chatRoomA?.countMembers(callback: { num, error in XCTAssertNil(error) XCTAssertEqual(num, 1); exp.fulfill() chatRoomB?.join(callback: { ret, error in XCTAssertNil(error) XCTAssertTrue(ret) exp.fulfill() self.delay() chatRoomA?.countMembers(callback: { num, error in XCTAssertNil(error) XCTAssertEqual(num, 2); exp.fulfill() chatRoomA?.getAllMemberInfo(callback: { memberInfos, error in XCTAssertNil(error) //??? XCTAssertEqual(memberInfos?.count, 1) exp.fulfill() chatRoomB?.quit(callback: { ret, error in XCTAssertTrue(ret) XCTAssertNil(error) exp.fulfill() self.delay() chatRoomA?.countMembers(callback: { num, error in XCTAssertNil(error) XCTAssertEqual(num, 1); exp.fulfill() chatRoomA?.getAllMemberInfo(callback: { memberInfos, error in XCTAssertNil(error) XCTAssertEqual(memberInfos?.count, 1) exp.fulfill() }) }) }) }) }) }) }) } } func testMuteAndUnmute() { let client = newOpenedClient() var conversation: LCIMConversation? = nil // var previousUpdatedAt: Date? let createExp = expectation(description: "create conversation") let option = LCIMConversationCreationOption.init() option.isUnique = false client.createConversation(withClientIds: [uuid, uuid], option: option) { conv, error in XCTAssertNil(error) XCTAssertNotNil(conv) conversation = conv // previousUpdatedAt = conversation?.updatedAt ?? conversation?.createdAt createExp.fulfill() } wait(for: [createExp], timeout: timeout) delay() let muteExp = expectation(description: "mute") conversation?.mute(callback: {[weak conversation] ret, error in XCTAssertTrue(Thread.isMainThread) XCTAssertTrue(ret) XCTAssertNil(error) XCTAssertEqual(conversation?.isMuted, true) let mutedMembers = conversation?.rawJSONDataCopy()[LCIMConversationKey.mutedMembers] as? [String] XCTAssertEqual(mutedMembers?.count, 1) XCTAssertEqual(mutedMembers?.contains(client.ID), true) // if let updatedAt = conversation?.updatedAt, let preUpdatedAt = previousUpdatedAt { // XCTAssertGreaterThan(updatedAt, preUpdatedAt) // previousUpdatedAt = updatedAt // } else { // XCTFail() // } muteExp.fulfill() }) wait(for: [muteExp], timeout: timeout) delay() let unmuteExp = expectation(description: "unmute") conversation?.unmute(callback: { [weak conversation] ret, error in XCTAssertTrue(Thread.isMainThread) XCTAssertTrue(ret) XCTAssertNil(error) XCTAssertEqual(conversation?.isMuted, false) let mutedMembers = conversation?.rawJSONDataCopy()[LCIMConversationKey.mutedMembers] as? [String] XCTAssertEqual(mutedMembers?.count, 0) // if let updatedAt = conversation?.updatedAt, let preUpdatedAt = previousUpdatedAt { // XCTAssertGreaterThan(updatedAt, preUpdatedAt) // previousUpdatedAt = updatedAt // } else { // XCTFail() // } unmuteExp.fulfill() }) wait(for: [unmuteExp], timeout: timeout) } func testConversationQuery() { let clientA = newOpenedClient() var ID1: String? = nil var ID2: String? = nil var ID3: String? = nil var ID4: String? = nil for i in 0...3 { switch i { case 0: let createExp = expectation(description: "create normal conversation") createExp.expectedFulfillmentCount = 2 let option = LCIMConversationCreationOption.init() option.isUnique = false clientA.createConversation(withClientIds: [uuid], option: option) { conv, error in XCTAssertNil(error) XCTAssertNotNil(conv) ID1 = conv?.ID let message = LCIMMessage.init(content: "test") conv?.send(message, callback: { ret, error in XCTAssertNil(error) XCTAssertTrue(ret) createExp.fulfill() }) createExp.fulfill() } wait(for: [createExp], timeout: timeout) case 1: let createExp = expectation(description: "create chat room") clientA.createChatRoom { room, error in XCTAssertNil(error) XCTAssertNotNil(room) ID2 = room?.ID createExp.fulfill() } wait(for: [createExp], timeout: timeout) case 2: let ID = newServiceConversation() XCTAssertNotNil(ID) ID3 = ID case 3: let createExp = expectation(description: "create temporary conversation") let options = LCIMConversationCreationOption.init() options.timeToLive = 3600 clientA.createTemporaryConversation(withClientIds: [uuid], option: options) { conv, error in XCTAssertNil(error) XCTAssertNotNil(conv) ID4 = conv?.ID createExp.fulfill() } wait(for: [createExp], timeout: timeout) default: break } } guard let normalConvID = ID1, let chatRoomID = ID2, let serviceID = ID3, let tempID = ID4 else { XCTFail() return } delay() clientA.convCollection.removeAll() let queryExp1 = expectation(description: "query normal conversation with message and without member") let query1 = clientA.conversationQuery() query1.option = [.compact, .withMessage] query1.getConversationById(normalConvID) { conv, error in XCTAssertNil(error) XCTAssertNotNil(conv) XCTAssertEqual(conv?.convType, .normal) XCTAssertEqual(conv?.members ?? [], []) XCTAssertNotNil(conv?.lastMessage) queryExp1.fulfill() } wait(for: [queryExp1], timeout: timeout) let queryExp2 = expectation(description: "query chat room") clientA.conversationQuery().getConversationById(chatRoomID) { conv, error in XCTAssertNil(error) XCTAssertNotNil(conv) XCTAssertEqual(conv?.convType, .transient) queryExp2.fulfill() } wait(for: [queryExp2], timeout: timeout) let queryExp3 = expectation(description: "query service conversation") clientA.conversationQuery().getConversationById(serviceID) { conv, error in XCTAssertNil(error) XCTAssertNotNil(conv) XCTAssertEqual(conv?.convType, .system) queryExp3.fulfill() } wait(for: [queryExp3], timeout: timeout) clientA.convCollection.removeAll() let queryTempExp = expectation(description: "query temporary conversation") clientA.conversationQuery().findTemporaryConversations(with: [tempID]) { conv, error in XCTAssertNil(error) XCTAssertNotNil(conv) XCTAssertEqual(conv?.count, 1) if let tmpConv = conv?.first { XCTAssertEqual(tmpConv.convType.rawValue, 4) } else { XCTFail() } queryTempExp.fulfill() } wait(for: [queryTempExp], timeout: timeout) clientA.convCollection.removeAll() let generalQueryExp1 = expectation(description: "general query with default conditon") clientA.conversationQuery().findConversations { convs, error in XCTAssertNil(error) XCTAssertEqual(convs?.count, 1) XCTAssertEqual(convs?.first?.convType, .normal) XCTAssertEqual(convs?.first?.members?.contains(clientA.ID), true) generalQueryExp1.fulfill() } wait(for: [generalQueryExp1], timeout: timeout) let generalQueryExp2 = expectation(description: "general query with custom conditon") let generalQuery1 = clientA.conversationQuery() generalQuery1.whereKey(LCIMConversationKey.transient.rawValue, equalTo: true) let generalQuery2 = clientA.conversationQuery() generalQuery2.whereKey(LCIMConversationKey.system.rawValue, equalTo: true) let generalQuery3 = LCIMConversationQuery.orQuery(withSubqueries: [generalQuery1, generalQuery2]) generalQuery3?.addAscendingOrder(LCIMConversationKey.createdAt.rawValue) generalQuery3?.limit = 5 generalQuery3?.findConversations { convs, error in XCTAssertNil(error) XCTAssertLessThanOrEqual(convs?.count ?? .max, 5) if let convs = convs { let types: [LCIMConvType] = [.system, .transient] var date = Date(timeIntervalSince1970: 0) for conv in convs { XCTAssertTrue(types.contains(conv.convType)) XCTAssertNotNil(conv.createdAt) if let createdAt = conv.createdAt { XCTAssertGreaterThanOrEqual(createdAt, date) date = createdAt } } } generalQueryExp2.fulfill() } wait(for: [generalQueryExp2], timeout: timeout) } func testUpdateAttribution() { let delegatorA = LCIMClientDelegator.init() let clientA = newOpenedClient(delegator: delegatorA) LCRTMConnectionManager.shared().imProtobuf1Registry.removeAllObjects() LCRTMConnectionManager.shared().imProtobuf3Registry.removeAllObjects() let delegatorB = LCIMClientDelegator.init() let clientB = newOpenedClient(delegator: delegatorB) var convA: LCIMConversation? = nil var convB: LCIMConversation? = nil let nameKey = LCIMConversationKey.name.rawValue let attrKey = LCIMConversationKey.attributes.rawValue let createKey = "create" let deleteKey = "delete" let arrayKey = "array" let createConvExp = expectation(description: "create conversation") let option = LCIMConversationCreationOption.init() option.isUnique = false option.attributes = [ deleteKey: uuid, arrayKey: [uuid] ] option.name = uuid clientA.createConversation(withClientIds: [clientA.ID, clientB.ID], option: option) { conv, error in XCTAssertNil(error) XCTAssertNotNil(conv) convA = conv createConvExp.fulfill() } wait(for: [createConvExp], timeout: timeout) delay() let data: [String: Any] = [ nameKey: uuid, "\(attrKey).\(createKey)": uuid, "\(attrKey).\(deleteKey)": ["__op": "Delete"], "\(attrKey).\(arrayKey)": ["__op": "Add", "objects": [uuid]] ] let updateExp = expectation(description: "update") updateExp.expectedFulfillmentCount = 2 delegatorB.conversationEvent = { client, conv, event in if conv.ID == convA?.ID { switch event { case let .dataUpdated(updatingData: updatingData, updatedData: updatedData, byClientID: byClientID): XCTAssertNotNil(updatedData) XCTAssertNotNil(updatingData) XCTAssertEqual(byClientID, clientA.ID) convB = conv updateExp.fulfill() default: break } } } data.forEach { key, value in convA?[key] = value } convA?.update(callback: { ret, error in XCTAssertTrue(Thread.isMainThread) XCTAssertTrue(ret) XCTAssertNil(error) updateExp.fulfill() }) wait(for: [updateExp], timeout: timeout) let check = { (conv: LCIMConversation?) in XCTAssertEqual(conv?.name, data[nameKey] as? String) XCTAssertEqual(conv?.attributes?[createKey] as? String, data["\(attrKey).\(createKey)"] as? String) XCTAssertNil(conv?.attributes?[deleteKey]) XCTAssertNotNil(conv?.attributes?[arrayKey]) } check(convA) check(convB) XCTAssertEqual(convA?.attributes?[arrayKey] as? [String], convB?.attributes?[arrayKey] as? [String]) } func testOfflineEvents() { let delegatorA = LCIMClientDelegator.init() let clientA = newOpenedClient(delegator: delegatorA) LCRTMConnectionManager.shared().imProtobuf1Registry.removeAllObjects() LCRTMConnectionManager.shared().imProtobuf3Registry.removeAllObjects() let delegatorB = LCIMClientDelegator.init() let clientB = newOpenedClient(delegator: delegatorB) expecting(expectation: { () -> XCTestExpectation in let exp = self.expectation(description: "create conv and send msg with rcp") exp.expectedFulfillmentCount = 5 return exp }) { (exp) in delegatorA.messageEvent = { client, conv, event in switch event { case .received: exp.fulfill() default: break } } delegatorB.conversationEvent = { client, conv, event in switch event { case .joined: exp.fulfill() let message = LCIMTextMessage.init() message.text = "text" let msgOpt = LCIMMessageOption.init() msgOpt.receipt = true conv.send(message, option: msgOpt) { ret, error in XCTAssertTrue(ret) XCTAssertNil(error) exp.fulfill() } case .message(event: let msgEvent): switch msgEvent { case .delivered: exp.fulfill() default: break } default: break } } clientA.createConversation(withClientIds: [clientB.ID]) { conv, error in XCTAssertNotNil(conv) XCTAssertNil(error) exp.fulfill() } } delegatorA.reset() delegatorB.reset() delay() clientB.connection.disconnect() delay() expecting(expectation: { () -> XCTestExpectation in let exp = self.expectation(description: "conv read") exp.expectedFulfillmentCount = 1 return exp }) { (exp) in let conv = clientA.convCollection.first?.value delegatorA.conversationEvent = { client, conv, event in switch event { case .unreadMessageCountUpdated: exp.fulfill() default: break } } conv?.read() } delegatorA.reset() expecting(expectation: { () -> XCTestExpectation in let exp = self.expectation(description: "create another normal conv") exp.expectedFulfillmentCount = 3 return exp }) { exp in delegatorA.conversationEvent = { client, conv, event in switch event { case .joined: exp.fulfill() case .membersJoined: exp.fulfill() default: break } } let option = LCIMConversationCreationOption.init() option.isUnique = false clientA.createConversation(withClientIds: [clientB.ID], option: option) { conv, error in XCTAssertNil(error) XCTAssertNotNil(conv) exp.fulfill() } } delegatorA.reset() expecting(description: "update normal conv attr") { (exp) in let conv = clientA.convCollection.first?.value let name = self.uuid delegatorA.conversationEvent = { client, conv, event in switch event { case .dataUpdated: XCTAssertEqual(conv.name, name) exp.fulfill() default: break } } conv?["name"] = name conv?.update(callback: { ret, error in XCTAssertTrue(ret) XCTAssertNil(error) exp.fulfill() }) } delegatorA.reset() expecting(expectation: { () -> XCTestExpectation in let exp = self.expectation(description: "create temp conv") exp.expectedFulfillmentCount = 3 return exp }) { exp in delegatorA.conversationEvent = { client, conv, event in switch event { case .joined: exp.fulfill() case .membersJoined: exp.fulfill() default: break } } let option = LCIMConversationCreationOption.init() option.timeToLive = 3600 clientA.createTemporaryConversation(withClientIds: [clientB.ID], option: option) { conv, error in XCTAssertNil(error) XCTAssertNotNil(conv) exp.fulfill() } } // delegatorA.reset() // // delay() // // expecting(expectation: { () -> XCTestExpectation in // let exp = self.expectation(description: "get offline events") // exp.expectedFulfillmentCount = 6 // return exp // }) { (exp) in // delegatorB.conversationEvent = { client, conv, event in // switch event { // case .joined: // if conv is LCIMTemporaryConversation { // exp.fulfill() // } else { // exp.fulfill() // } // case .membersJoined: // if conv is LCIMTemporaryConversation { // exp.fulfill() // } else { // exp.fulfill() // } // case .dataUpdated: // exp.fulfill() // case .message(event: let msgEvent): // switch msgEvent { // case .read: // exp.fulfill() // default: // break // } // default: // break // } // } // clientB.connection.testConnect() // } // delegatorB.reset() } func testMemberInfo() { let delegatorA = LCIMClientDelegator.init() let clientA = newOpenedClient(delegator: delegatorA) let delegatorB = LCIMClientDelegator.init() let clientB = newOpenedClient(delegator: delegatorB) let clientCID: String = self.uuid var convA: LCIMConversation? expecting { (exp) in clientA.createConversation(withClientIds: [clientB.ID, clientCID]) { conv, error in XCTAssertNil(error) XCTAssertNotNil(conv) convA = conv exp.fulfill() } } expecting { (exp) in convA?.updateMemberRole(withMemberId: clientB.ID, role: .owner, callback: { ret, error in XCTAssertNotNil(error) XCTAssertFalse(ret) exp.fulfill() }) } expecting { (exp) in convA?.getAllMemberInfo(callback: {[weak convA] infos, error in XCTAssertTrue(Thread.isMainThread) XCTAssertNil(error) XCTAssertNotNil(convA?.memberInfoTable) XCTAssertEqual(convA?.memberInfoTable?.count, 1) exp.fulfill() }) } multiExpecting(expectations: { () -> [XCTestExpectation] in let exp = self.expectation(description: "change member role to manager") exp.expectedFulfillmentCount = 2 return [exp] }) { (exps) in let exp = exps[0] delegatorB.conversationEvent = { client, conv, event in switch event { case let .memberInfoChanged(memberId: memberId, role: role, byClientID: byClientID): XCTAssertTrue(Thread.isMainThread) XCTAssertEqual(role, .manager) XCTAssertEqual(memberId, clientB.ID) XCTAssertEqual(byClientID, clientA.ID) XCTAssertNotNil(convA?.memberInfoTable) exp.fulfill() default: break } } convA?.updateMemberRole(withMemberId: clientB.ID, role: .manager, callback: { ret, error in XCTAssertTrue(Thread.isMainThread) XCTAssertNil(error) XCTAssertTrue(ret) let info = convA?.memberInfoTable?[clientB.ID] as? LCIMConversationMemberInfo XCTAssertEqual(info?.role(), .manager) exp.fulfill() }) } delay() expecting { (exp) in let convB = clientB.convCollection.values.first XCTAssertNil(convB?.memberInfoTable) convB?.getMemberInfo(withMemberId: clientB.ID, callback: { info, error in XCTAssertTrue(Thread.isMainThread) XCTAssertNil(error) XCTAssertNotNil(info) exp.fulfill() }) } expecting { (exp) in convA?.getAllMemberInfo(callback: {[weak convA] infos, error in XCTAssertTrue(Thread.isMainThread) XCTAssertNil(error) XCTAssertNotNil(convA?.memberInfoTable) XCTAssertEqual(convA?.memberInfoTable?.count, 2) exp.fulfill() }) } multiExpecting(expectations: { () -> [XCTestExpectation] in let exp = self.expectation(description: "change member role to member") exp.expectedFulfillmentCount = 2 return [exp] }) { (exps) in let exp = exps[0] delegatorB.conversationEvent = { client, conv, event in switch event { case let .memberInfoChanged(memberId: memberId, role: role, byClientID: byClientID): XCTAssertEqual(role, .member) XCTAssertEqual(memberId, clientB.ID) XCTAssertEqual(byClientID, clientA.ID) let info = conv.memberInfoTable?[clientB.ID] as? LCIMConversationMemberInfo XCTAssertEqual(info?.role(), .member) exp.fulfill() default: break } } convA?.updateMemberRole(withMemberId: clientB.ID, role: .member, callback: { ret, error in XCTAssertTrue(Thread.isMainThread) XCTAssertNil(error) XCTAssertTrue(ret) let info = convA?.memberInfoTable?[clientB.ID] as? LCIMConversationMemberInfo XCTAssertEqual(info?.role(), .member) exp.fulfill() }) } } func testMemberBlock() { let delegatorA = LCIMClientDelegator.init() let clientA = newOpenedClient(delegator: delegatorA) let delegatorB = LCIMClientDelegator.init() let clientB = newOpenedClient(delegator: delegatorB) let delegatorC = LCIMClientDelegator.init() let clientC = newOpenedClient(delegator: delegatorC) var convA: LCIMConversation? expecting { (exp) in clientA.createConversation(withClientIds: [clientB.ID, clientC.ID]) { conv, error in XCTAssertNil(error) XCTAssertNotNil(conv) convA = conv exp.fulfill() } } multiExpecting(expectations: { () -> [XCTestExpectation] in let exp = self.expectation(description: "block member") exp.expectedFulfillmentCount = 7 return [exp] }) { (exps) in let exp = exps[0] delegatorA.conversationEvent = { client, conv, event in switch event { case let .membersBlocked(members: members, byClientID: byClientID): XCTAssertEqual(members.count, 2) XCTAssertTrue(members.contains(clientB.ID)) XCTAssertTrue(members.contains(clientC.ID)) XCTAssertEqual(byClientID, clientA.ID) exp.fulfill() case let .membersLeft(members: members, byClientID: byClientID): XCTAssertEqual(members.count, 2) XCTAssertTrue(members.contains(clientB.ID)) XCTAssertTrue(members.contains(clientC.ID)) XCTAssertEqual(byClientID, clientA.ID) exp.fulfill() default: break } } delegatorB.conversationEvent = { client, conv, event in switch event { case let .blocked(byClientID: byClientID): XCTAssertEqual(byClientID, clientA.ID) exp.fulfill() case let .left(byClientID: byClientID): XCTAssertEqual(byClientID, clientA.ID) exp.fulfill() default: break } } delegatorC.conversationEvent = { client, conv, event in switch event { case let .blocked(byClientID: byClientID): XCTAssertEqual(byClientID, clientA.ID) exp.fulfill() case let .left(byClientID: byClientID): XCTAssertEqual(byClientID, clientA.ID) exp.fulfill() default: break } } convA?.blockMembers([clientB.ID, clientC.ID], callback: { ids, oper, error in XCTAssertTrue(Thread.isMainThread) XCTAssertNil(error) XCTAssertNotNil(ids) exp.fulfill() }) } delegatorA.reset() delegatorB.reset() delegatorC.reset() var next: String? expecting { (exp) in convA?.queryBlockedMembers(withLimit: 1, next: nil, callback: { members, _next, error in XCTAssertTrue(Thread.isMainThread) XCTAssertNil(error) XCTAssertEqual(members?.count, 1) if let member = members?.first { XCTAssertTrue([clientB.ID, clientC.ID].contains(member)) } XCTAssertNotNil(_next) next = _next exp.fulfill() }) } expecting { (exp) in convA?.queryBlockedMembers(withLimit: 50, next: next, callback: { members, _next, error in XCTAssertNil(error) XCTAssertEqual(members?.count, 1) if let member = members?.first { XCTAssertTrue([clientB.ID, clientC.ID].contains(member)) } XCTAssertNil(_next) exp.fulfill() }) } multiExpecting(expectations: { () -> [XCTestExpectation] in let exp = self.expectation(description: "unblock member") exp.expectedFulfillmentCount = 4 return [exp] }) { (exps) in let exp = exps[0] delegatorA.conversationEvent = { client, conv, event in switch event { case let .membersUnblocked(members: members, byClientID: byClientID): XCTAssertEqual(members.count, 2) XCTAssertTrue(members.contains(clientB.ID)) XCTAssertTrue(members.contains(clientC.ID)) XCTAssertEqual(byClientID, clientA.ID) exp.fulfill() default: break } } delegatorB.conversationEvent = { client, conv, event in switch event { case let .unblocked(byClientID: byClientID): XCTAssertEqual(byClientID, clientA.ID) exp.fulfill() default: break } } delegatorC.conversationEvent = { client, conv, event in switch event { case let .unblocked(byClientID: byClientID): XCTAssertEqual(byClientID, clientA.ID) exp.fulfill() default: break } } convA?.unblockMembers([clientB.ID, clientC.ID], callback: { members, fails, error in XCTAssertTrue(Thread.isMainThread) XCTAssertNil(error) exp.fulfill() }) } } func testMemberMute() { let delegatorA = LCIMClientDelegator.init() let clientA = newOpenedClient(delegator: delegatorA) let delegatorB = LCIMClientDelegator.init() let clientB = newOpenedClient(delegator: delegatorB) let delegatorC = LCIMClientDelegator.init() let clientC = newOpenedClient(delegator: delegatorC) var convA: LCIMConversation? expecting { (exp) in clientA.createConversation(withClientIds: [clientB.ID, clientC.ID]) { conv, error in XCTAssertNil(error) XCTAssertNotNil(conv) convA = conv exp.fulfill() } } multiExpecting(expectations: { () -> [XCTestExpectation] in let exp = self.expectation(description: "mute member") exp.expectedFulfillmentCount = 4 return [exp] }) { (exps) in let exp = exps[0] delegatorA.conversationEvent = { client, conv, event in switch event { case let .membersMuted(members: members, byClientID: byClientID): XCTAssertEqual(members.count, 2) XCTAssertTrue(members.contains(clientB.ID)) XCTAssertTrue(members.contains(clientC.ID)) XCTAssertEqual(byClientID, clientA.ID) exp.fulfill() default: break } } delegatorB.conversationEvent = { client, conv, event in switch event { case let .muted(byClientID: byClientID): XCTAssertEqual(byClientID, clientA.ID) exp.fulfill() default: break } } delegatorC.conversationEvent = { client, conv, event in switch event { case let .muted(byClientID: byClientID): XCTAssertEqual(byClientID, clientA.ID) exp.fulfill() default: break } } convA?.muteMembers([clientB.ID, clientC.ID], callback: { members, fails, error in XCTAssertTrue(Thread.isMainThread) XCTAssertNil(error) exp.fulfill() }) } delegatorA.reset() delegatorB.reset() delegatorC.reset() var next: String? expecting { (exp) in convA?.queryMutedMembers(withLimit: 1, next: nil, callback: { members, _next, error in XCTAssertTrue(Thread.isMainThread) XCTAssertNil(error) XCTAssertEqual(members?.count, 1) if let member = members?.first { XCTAssertTrue([clientB.ID, clientC.ID].contains(member)) } XCTAssertNotNil(_next) next = _next exp.fulfill() }) } expecting { (exp) in convA?.queryMutedMembers(withLimit: 50, next: next, callback: { members, _next, error in XCTAssertNil(error) XCTAssertEqual(members?.count, 1) if let member = members?.first { XCTAssertTrue([clientB.ID, clientC.ID].contains(member)) } XCTAssertNil(_next) exp.fulfill() }) } multiExpecting(expectations: { () -> [XCTestExpectation] in let exp = self.expectation(description: "unmute member") exp.expectedFulfillmentCount = 4 return [exp] }) { (exps) in let exp = exps[0] delegatorA.conversationEvent = { client, conv, event in switch event { case let .membersUnmuted(members: members, byClientID: byClientID): XCTAssertEqual(members.count, 2) XCTAssertTrue(members.contains(clientB.ID)) XCTAssertTrue(members.contains(clientC.ID)) XCTAssertEqual(byClientID, clientA.ID) exp.fulfill() default: break } } delegatorB.conversationEvent = { client, conv, event in switch event { case let .unmuted(byClientID: byClientID): XCTAssertEqual(byClientID, clientA.ID) exp.fulfill() default: break } } delegatorC.conversationEvent = { client, conv, event in switch event { case let .unmuted(byClientID: byClientID): XCTAssertEqual(byClientID, clientA.ID) exp.fulfill() default: break } } convA?.unmuteMembers([clientB.ID, clientC.ID], callback: { members, fails, error in XCTAssertTrue(Thread.isMainThread) XCTAssertNil(error) exp.fulfill() }) } } } extension LCIMConversationTestCase { func subscribing(serviceConversation conversationID: String, by clientID: String) -> Bool { var success: Bool = false let paasClient = LCPaasClient.sharedInstance() let request = paasClient?.request(withPath: "https://s5vdi3ie.lc-cn-n1-shared.com/1.2/rtm/service-conversations/\(conversationID)/subscribers", method: "POST", headers: ["X-LC-Key": BaseTestCase.cnApp.masterKey], parameters: ["client_id": clientID]) expecting { exp in paasClient?.perform(request as URLRequest?, success: { response, responseObject in success = true exp.fulfill() }, failure: { _, _, _ in exp.fulfill() }) } return success } }
dd5c7b119001128004fe44c5cfab6e8f
38.287733
257
0.502178
false
false
false
false
jianwoo/WordPress-iOS
refs/heads/develop
WordPress/Classes/ViewRelated/Notifications/RichTextView/RichTextView.swift
gpl-2.0
1
import Foundation @objc public protocol RichTextViewDataSource { optional func textView(textView: UITextView, viewForTextAttachment attachment: NSTextAttachment) -> UIView? } @objc public protocol RichTextViewDelegate : UITextViewDelegate { optional func textView(textView: UITextView, didPressLink link: NSURL) } @objc public class RichTextView : UIView, UITextViewDelegate { public var dataSource: RichTextViewDataSource? public var delegate: RichTextViewDelegate? // MARK: - Initializers public override init() { super.init() setupSubviews() } public override init(frame: CGRect) { super.init(frame: frame) setupSubviews() } public required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupSubviews() } // MARK: - Properties public var contentInset: UIEdgeInsets { set { textView.contentInset = newValue } get { return textView.contentInset } } public var textContainerInset: UIEdgeInsets { set { textView.textContainerInset = newValue } get { return textView.textContainerInset } } public var attributedText: NSAttributedString! { set { textView.attributedText = newValue renderAttachments() } get { return textView.attributedText } } public var editable: Bool { set { textView.editable = newValue } get { return textView.editable } } public var selectable: Bool { set { textView.selectable = newValue } get { return textView.selectable } } public var dataDetectorTypes: UIDataDetectorTypes { set { textView.dataDetectorTypes = newValue } get { return textView.dataDetectorTypes } } public override var backgroundColor: UIColor? { didSet { textView?.backgroundColor = backgroundColor } } public var linkTextAttributes: [NSObject : AnyObject]! { set { textView.linkTextAttributes = newValue } get { return textView.linkTextAttributes } } // MARK: - TextKit Getters public var layoutManager: NSLayoutManager { get { return textView.layoutManager } } public var textStorage: NSTextStorage { get { return textView.textStorage } } public var textContainer: NSTextContainer { get { return textView.textContainer } } // MARK: - Autolayout Helpers public var preferredMaxLayoutWidth: CGFloat = 0 { didSet { invalidateIntrinsicContentSize() } } public override func intrinsicContentSize() -> CGSize { // Fix: Let's add 1pt extra size. There are few scenarios in which text gets clipped by 1 point let bottomPadding = CGFloat(1) let maxWidth = (preferredMaxLayoutWidth != 0) ? preferredMaxLayoutWidth : frame.width let maxSize = CGSize(width: maxWidth, height: CGFloat.max) let requiredSize = textView!.sizeThatFits(maxSize) let roundedSize = CGSize(width: ceil(requiredSize.width), height: ceil(requiredSize.height) + bottomPadding) return roundedSize } // MARK: - Private Methods private func setupSubviews() { gesturesRecognizer = UITapGestureRecognizer() gesturesRecognizer.addTarget(self, action: "handleTextViewTap:") textView = UITextView(frame: bounds) textView.backgroundColor = backgroundColor textView.contentInset = UIEdgeInsetsZero textView.textContainerInset = UIEdgeInsetsZero textView.textContainer.lineFragmentPadding = 0 textView.layoutManager.allowsNonContiguousLayout = false textView.editable = editable textView.dataDetectorTypes = dataDetectorTypes textView.delegate = self textView.gestureRecognizers = [gesturesRecognizer] addSubview(textView) // Setup Layout textView.setTranslatesAutoresizingMaskIntoConstraints(false) pinSubviewToAllEdges(textView) } private func renderAttachments() { // Nuke old attachments attachmentViews.map { $0.removeFromSuperview() } attachmentViews.removeAll(keepCapacity: false) // Proceed only if needed if attributedText == nil { return } // Load new attachments attributedText.enumerateAttachments { (attachment: NSTextAttachment, range: NSRange) -> () in let attachmentView = self.dataSource?.textView?(self.textView, viewForTextAttachment: attachment) if attachmentView == nil { return } let unwrappedView = attachmentView! unwrappedView.frame.origin = self.textView.frameForTextInRange(range).integerRect.origin self.textView.addSubview(unwrappedView) self.attachmentViews.append(unwrappedView) } } // MARK: - UITapGestureRecognizer Helpers public func handleTextViewTap(recognizer: UITapGestureRecognizer) { // NOTE: Why do we need this? // Because this mechanism allows us to disable DataDetectors, and yet, detect taps on links. // let textStorage = textView.textStorage let layoutManager = textView.layoutManager let textContainer = textView.textContainer let locationInTextView = recognizer.locationInView(textView) let characterIndex = layoutManager.characterIndexForPoint(locationInTextView, inTextContainer: textContainer, fractionOfDistanceBetweenInsertionPoints: nil) if characterIndex >= textStorage.length { return } // Load the NSURL instance, if any let rawURL = textStorage.attribute(NSLinkAttributeName, atIndex: characterIndex, effectiveRange: nil) as? NSURL if let unwrappedURL = rawURL { delegate?.textView?(textView, didPressLink: unwrappedURL) } } // MARK: - UITextViewDelegate Wrapped Methods public func textViewShouldBeginEditing(textView: UITextView) -> Bool { return delegate?.textViewShouldBeginEditing?(textView) ?? true } public func textViewShouldEndEditing(textView: UITextView) -> Bool { return delegate?.textViewShouldEndEditing?(textView) ?? true } public func textViewDidBeginEditing(textView: UITextView) { delegate?.textViewDidBeginEditing?(textView) } public func textViewDidEndEditing(textView: UITextView) { delegate?.textViewDidEndEditing?(textView) } public func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool { return delegate?.textView?(textView, shouldChangeTextInRange: range, replacementText: text) ?? true } public func textViewDidChange(textView: UITextView) { delegate?.textViewDidChange?(textView) } public func textViewDidChangeSelection(textView: UITextView) { delegate?.textViewDidChangeSelection?(textView) } public func textView(textView: UITextView, shouldInteractWithURL URL: NSURL, inRange characterRange: NSRange) -> Bool { return delegate?.textView?(textView, shouldInteractWithURL: URL, inRange: characterRange) ?? true } public func textView(textView: UITextView, shouldInteractWithTextAttachment textAttachment: NSTextAttachment, inRange characterRange: NSRange) -> Bool { return delegate?.textView?(textView, shouldInteractWithTextAttachment: textAttachment, inRange: characterRange) ?? true } // MARK: - Private Properites private var textView: UITextView! private var gesturesRecognizer: UITapGestureRecognizer! private var attachmentViews: [UIView] = [] }
c92f19b4bc881ba337d37b36c087d804
31.966292
156
0.601454
false
false
false
false
SmallElephant/FEAlgorithm-Swift
refs/heads/master
10-Number/10-Number/Statistics.swift
mit
1
// // Statistics.swift // 10-Number // // Created by FlyElephant on 17/2/28. // Copyright © 2017年 FlyElephant. All rights reserved. // import Foundation class Statistics { // 对于数abcde,c这位出现1的次数分以下情况: // 1.若c == 0,结轮是 ab * 100; // 2.若c == 1,结论是(ab)* 100 + de + 1; // 3.若c > 1,结论是(ab + 1)* 100; func sumls(num:Int) -> Int { var count:Int = 0 for i in 1...num { var temp:Int = i while temp != 0 { count += temp % 10 == 1 ? 1 : 0 temp /= 10 } } return count } func sumlsSimple(num:Int) -> Int { if num <= 0 { return 0 } var factor = 1 var lowNum:Int = 0 var curNum:Int = 0 var highNum:Int = 0 var count:Int = 0 let n:Int = num while n / factor != 0 { lowNum = n - (n / factor) * factor curNum = (n / factor) % 10 highNum = n / (factor * 10) if curNum == 0 { count += highNum * factor } else if curNum == 1 { count += highNum * factor + lowNum + 1 } else { count += (highNum + 1) * factor } factor *= 10 } return count } func sumlsCommon(num:Int,target:Int) -> Int { if num <= 0 || (target < 1 || target > 9){ return 0 } var factor = 1 var lowNum:Int = 0 var curNum:Int = 0 var highNum:Int = 0 var count:Int = 0 let n:Int = num while n / factor != 0 { lowNum = n - (n / factor) * factor curNum = (n / factor) % 10 highNum = n / (factor * 10) if curNum < target { count += highNum * factor } else if curNum == target { count += highNum * factor + lowNum + 1 } else { count += (highNum + 1) * factor } factor *= 10 } return count } }
3a006582a3064dc4a0f28d8be5c2149a
21.916667
55
0.395455
false
false
false
false
apple/swift-experimental-string-processing
refs/heads/main
Sources/_StringProcessing/_CharacterClassModel.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2021-2022 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 // //===----------------------------------------------------------------------===// @_implementationOnly import _RegexParser // NOTE: This is a model type. We want to be able to get one from // an AST, but this isn't a natural thing to produce in the context // of parsing or to store in an AST struct _CharacterClassModel: Hashable { /// The actual character class to match. let cc: Representation /// The level (character or Unicode scalar) at which to match. let matchLevel: MatchingOptions.SemanticLevel /// If this character character class only matches ascii characters let isStrictASCII: Bool /// Whether this character class matches against an inverse, /// e.g \D, \S, [^abc]. let isInverted: Bool init( cc: Representation, options: MatchingOptions, isInverted: Bool ) { self.cc = cc self.matchLevel = options.semanticLevel self.isStrictASCII = cc.isStrictAscii(options: options) self.isInverted = isInverted } enum Representation: UInt64, Hashable { /// Any character case any = 0 /// Any grapheme cluster case anyGrapheme /// Any Unicode scalar case anyScalar /// Character.isDigit case digit /// Horizontal whitespace: `[:blank:]`, i.e /// `[\p{gc=Space_Separator}\N{CHARACTER TABULATION}] case horizontalWhitespace /// Character.isNewline case newlineSequence /// Vertical whitespace: `[\u{0A}-\u{0D}\u{85}\u{2028}\u{2029}]` case verticalWhitespace /// Character.isWhitespace case whitespace /// Character.isLetter or Character.isDigit or Character == "_" case word } /// Returns the end of the match of this character class in the string. /// /// - Parameter str: The string to match against. /// - Parameter at: The index to start matching. /// - Parameter options: Options for the match operation. /// - Returns: The index of the end of the match, or `nil` if there is no match. func matches( in input: String, at currentPosition: String.Index ) -> String.Index? { // FIXME: This is only called in custom character classes that contain builtin // character classes as members (ie: [a\w] or set operations), is there // any way to avoid that? Can we remove this somehow? guard currentPosition != input.endIndex else { return nil } let char = input[currentPosition] let scalar = input.unicodeScalars[currentPosition] let isScalarSemantics = matchLevel == .unicodeScalar let asciiCheck = (char.isASCII && !isScalarSemantics) || (scalar.isASCII && isScalarSemantics) || !isStrictASCII var matched: Bool var next: String.Index switch (isScalarSemantics, cc) { case (_, .anyGrapheme): next = input.index(after: currentPosition) case (_, .anyScalar): // FIXME: This allows us to be not-scalar aligned when in grapheme mode // Should this even be allowed? next = input.unicodeScalars.index(after: currentPosition) case (true, _): next = input.unicodeScalars.index(after: currentPosition) case (false, _): next = input.index(after: currentPosition) } switch cc { case .any, .anyGrapheme, .anyScalar: matched = true case .digit: if isScalarSemantics { matched = scalar.properties.numericType != nil && asciiCheck } else { matched = char.isNumber && asciiCheck } case .horizontalWhitespace: if isScalarSemantics { matched = scalar.isHorizontalWhitespace && asciiCheck } else { matched = char._isHorizontalWhitespace && asciiCheck } case .verticalWhitespace: if isScalarSemantics { matched = scalar.isNewline && asciiCheck } else { matched = char._isNewline && asciiCheck } case .newlineSequence: if isScalarSemantics { matched = scalar.isNewline && asciiCheck if matched && scalar == "\r" && next != input.endIndex && input.unicodeScalars[next] == "\n" { // Match a full CR-LF sequence even in scalar sematnics input.unicodeScalars.formIndex(after: &next) } } else { matched = char._isNewline && asciiCheck } case .whitespace: if isScalarSemantics { matched = scalar.properties.isWhitespace && asciiCheck } else { matched = char.isWhitespace && asciiCheck } case .word: if isScalarSemantics { matched = scalar.properties.isAlphabetic && asciiCheck } else { matched = char.isWordCharacter && asciiCheck } } if isInverted { matched.toggle() } if matched { return next } else { return nil } } } extension _CharacterClassModel { var consumesSingleGrapheme: Bool { switch self.cc { case .anyScalar: return false default: return true } } } extension _CharacterClassModel.Representation { /// Returns true if this CharacterClass should be matched by strict ascii under the given options func isStrictAscii(options: MatchingOptions) -> Bool { switch self { case .digit: return options.usesASCIIDigits case .horizontalWhitespace: return options.usesASCIISpaces case .newlineSequence: return options.usesASCIISpaces case .verticalWhitespace: return options.usesASCIISpaces case .whitespace: return options.usesASCIISpaces case .word: return options.usesASCIIWord default: return false } } } extension _CharacterClassModel.Representation: CustomStringConvertible { var description: String { switch self { case .any: return "<any>" case .anyGrapheme: return "<any grapheme>" case .anyScalar: return "<any scalar>" case .digit: return "<digit>" case .horizontalWhitespace: return "<horizontal whitespace>" case .newlineSequence: return "<newline sequence>" case .verticalWhitespace: return "vertical whitespace" case .whitespace: return "<whitespace>" case .word: return "<word>" } } } extension _CharacterClassModel: CustomStringConvertible { var description: String { return "\(isInverted ? "not " : "")\(cc)" } } extension DSLTree.Atom.CharacterClass { /// Converts this DSLTree CharacterClass into our runtime representation func asRuntimeModel(_ options: MatchingOptions) -> _CharacterClassModel { let cc: _CharacterClassModel.Representation var inverted = false switch self { case .digit: cc = .digit case .notDigit: cc = .digit inverted = true case .horizontalWhitespace: cc = .horizontalWhitespace case .notHorizontalWhitespace: cc = .horizontalWhitespace inverted = true case .newlineSequence: cc = .newlineSequence // FIXME: This is more like '.' than inverted '\R', as it is affected // by e.g (*CR). We should therefore really be emitting it through // emitDot(). For now we treat it as semantically invalid. case .notNewline: cc = .newlineSequence inverted = true case .whitespace: cc = .whitespace case .notWhitespace: cc = .whitespace inverted = true case .verticalWhitespace: cc = .verticalWhitespace case .notVerticalWhitespace: cc = .verticalWhitespace inverted = true case .word: cc = .word case .notWord: cc = .word inverted = true case .anyGrapheme: cc = .anyGrapheme case .anyUnicodeScalar: cc = .anyScalar } return _CharacterClassModel(cc: cc, options: options, isInverted: inverted) } }
0a9b934980e844f06a95bf7d04410bef
29.74031
99
0.649098
false
false
false
false
PopcornTimeTV/PopcornTimeTV
refs/heads/master
PopcornTime/UI/iOS/Extensions/String+Truncation.swift
gpl-3.0
1
import Foundation extension String { func truncateToSize(size: CGSize, ellipsesString: String, trailingText: String, attributes: [NSAttributedString.Key : Any], trailingTextAttributes: [NSAttributedString.Key : Any]) -> NSAttributedString { if !willFit(to: size, attributes: attributes) { let indexOfLastCharacterThatFits = indexThatFits(size: size, ellipsesString: ellipsesString, trailingText: trailingText, attributes: attributes, minIndex: 0, maxIndex: count) let range = startIndex..<index(startIndex, offsetBy: indexOfLastCharacterThatFits) let substring = self[range] let attributedString = NSMutableAttributedString(string: substring + ellipsesString, attributes: attributes) let attributedTrailingString = NSAttributedString(string: trailingText, attributes: trailingTextAttributes) attributedString.append(attributedTrailingString) return attributedString } else { return NSAttributedString(string: self, attributes: attributes) } } func willFit(to size: CGSize, ellipsesString: String = "", trailingText: String = "", attributes: [NSAttributedString.Key : Any]) -> Bool { let text = (self + ellipsesString + trailingText) as NSString let boundedSize = CGSize(width: size.width, height: .greatestFiniteMagnitude) let options: NSStringDrawingOptions = [.usesLineFragmentOrigin, .usesFontLeading] let boundedRect = text.boundingRect(with: boundedSize, options: options, attributes: attributes, context: nil) return boundedRect.height <= size.height } // MARK: - Private private func indexThatFits(size: CGSize, ellipsesString: String, trailingText: String, attributes: [NSAttributedString.Key : Any], minIndex: Int, maxIndex: Int) -> Int { guard maxIndex - minIndex != 1 else { return minIndex } let midIndex = (minIndex + maxIndex) / 2 let range = startIndex..<index(startIndex, offsetBy: midIndex) let substring = String(self[range]) if !substring.willFit(to: size, ellipsesString: ellipsesString, trailingText: trailingText, attributes: attributes) { return indexThatFits(size: size, ellipsesString: ellipsesString, trailingText: trailingText, attributes: attributes, minIndex: minIndex, maxIndex: midIndex) } else { return indexThatFits(size: size, ellipsesString: ellipsesString, trailingText: trailingText, attributes: attributes, minIndex: midIndex, maxIndex: maxIndex) } } }
3cd6c51cbe73900667cee78743cb77cb
44.810127
125
0.505112
false
false
false
false
ShamylZakariya/Squizit
refs/heads/master
Squizit/Transitions/SaveToGalleryTransitionManager.swift
mit
1
// // SaveToGalleryTransitionManager.swift // Squizit // // Created by Shamyl Zakariya on 9/26/14. // Copyright (c) 2014 Shamyl Zakariya. All rights reserved. // import UIKit class SaveToGalleryTransitionManager: NSObject, UIViewControllerAnimatedTransitioning, UIViewControllerTransitioningDelegate { private var presenting = false func animateTransition(transitionContext: UIViewControllerContextTransitioning) { let presenting = self.presenting let scale:CGFloat = 1.075 let bigScale = CGAffineTransformMakeScale(scale, scale) let container = transitionContext.containerView()! let baseView = transitionContext.viewForKey(presenting ? UITransitionContextFromViewKey : UITransitionContextToViewKey)! let dialogView = transitionContext.viewForKey(presenting ? UITransitionContextToViewKey : UITransitionContextFromViewKey)! let dialogViewController = transitionContext.viewControllerForKey(presenting ? UITransitionContextToViewControllerKey : UITransitionContextFromViewControllerKey)! as! SaveToGalleryViewController container.addSubview(baseView) container.addSubview(dialogView) if presenting { dialogView.alpha = 0 dialogViewController.dialogView.transform = bigScale } let duration = self.transitionDuration(transitionContext) UIView.animateWithDuration(duration, delay: 0.0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0, options: [], animations: { if presenting { dialogView.alpha = 1 } else { dialogViewController.dialogView.transform = bigScale } }, completion: nil ) UIView.animateWithDuration(duration, delay: duration/6, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.5, options: [], animations: { if presenting { dialogViewController.dialogView.transform = CGAffineTransformIdentity } else { dialogView.alpha = 0 } }, completion: { finished in transitionContext.completeTransition(true) }) } // return how many seconds the transiton animation will take func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { return 0.5 } // MARK: UIViewControllerTransitioningDelegate protocol methods func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? { self.presenting = true return self } func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { self.presenting = false return self } }
becb060b6d186f031721b054da54e079
30.241379
217
0.761221
false
false
false
false
wordpress-mobile/AztecEditor-iOS
refs/heads/develop
Aztec/Classes/Formatters/Base/StandardAttributeFormatter.swift
gpl-2.0
2
import Foundation import UIKit /// Formatter to apply simple value (NSNumber, UIColor) attributes to an attributed string. class StandardAttributeFormatter: AttributeFormatter { var placeholderAttributes: [NSAttributedString.Key: Any]? { return nil } let attributeKey: NSAttributedString.Key var attributeValue: Any let htmlRepresentationKey: NSAttributedString.Key let needsToMatchValue: Bool // MARK: - Init init(attributeKey: NSAttributedString.Key, attributeValue: Any, htmlRepresentationKey: NSAttributedString.Key, needsToMatchValue: Bool = false) { self.attributeKey = attributeKey self.attributeValue = attributeValue self.htmlRepresentationKey = htmlRepresentationKey self.needsToMatchValue = needsToMatchValue } func applicationRange(for range: NSRange, in text: NSAttributedString) -> NSRange { return range } func apply(to attributes: [NSAttributedString.Key: Any], andStore representation: HTMLRepresentation?) -> [NSAttributedString.Key: Any] { var resultingAttributes = attributes resultingAttributes[attributeKey] = attributeValue resultingAttributes[htmlRepresentationKey] = representation return resultingAttributes } func remove(from attributes: [NSAttributedString.Key: Any]) -> [NSAttributedString.Key: Any] { var resultingAttributes = attributes resultingAttributes.removeValue(forKey: attributeKey) resultingAttributes.removeValue(forKey: htmlRepresentationKey) return resultingAttributes } func present(in attributes: [NSAttributedString.Key: Any]) -> Bool { let enabled = attributes[attributeKey] != nil if (!needsToMatchValue) { return enabled } if let value = attributes[attributeKey] as? NSObject, let attributeValue = attributeValue as? NSObject { return value.isEqual(attributeValue) } return false } }
ee91ef19c0c05f27123bca317b919413
31.983607
149
0.707753
false
false
false
false
FraDeliro/ISaMaterialLogIn
refs/heads/master
Example/Pods/Material/Sources/iOS/Bar.swift
mit
1
/* * Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of CosmicMind nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit @objc(ContentViewAlignment) public enum ContentViewAlignment: Int { case full case center } open class Bar: View { /// Will layout the view. open var willLayout: Bool { return 0 < width && 0 < height && nil != superview } open override var intrinsicContentSize: CGSize { return CGSize(width: width, height: height) } /// Should center the contentView. open var contentViewAlignment = ContentViewAlignment.full { didSet { layoutSubviews() } } /// A preset wrapper around contentEdgeInsets. open var contentEdgeInsetsPreset: EdgeInsetsPreset { get { return grid.contentEdgeInsetsPreset } set(value) { grid.contentEdgeInsetsPreset = value } } /// A reference to EdgeInsets. @IBInspectable open var contentEdgeInsets: EdgeInsets { get { return grid.contentEdgeInsets } set(value) { grid.contentEdgeInsets = value } } /// A preset wrapper around interimSpace. open var interimSpacePreset = InterimSpacePreset.none { didSet { interimSpace = InterimSpacePresetToValue(preset: interimSpacePreset) } } /// A wrapper around grid.interimSpace. @IBInspectable open var interimSpace: InterimSpace { get { return grid.interimSpace } set(value) { grid.interimSpace = value } } /// Grid cell factor. @IBInspectable open var gridFactor: CGFloat = 12 { didSet { assert(0 < gridFactor, "[Material Error: gridFactor must be greater than 0.]") layoutSubviews() } } /// ContentView that holds the any desired subviews. open let contentView = UIView() /// Left side UIViews. open var leftViews: [UIView] { didSet { for v in oldValue { v.removeFromSuperview() } layoutSubviews() } } /// Right side UIViews. open var rightViews: [UIView] { didSet { for v in oldValue { v.removeFromSuperview() } layoutSubviews() } } /// Center UIViews. open var centerViews: [UIView] { get { return contentView.grid.views } set(value) { contentView.grid.views = value } } /** An initializer that initializes the object with a NSCoder object. - Parameter aDecoder: A NSCoder instance. */ public required init?(coder aDecoder: NSCoder) { leftViews = [] rightViews = [] super.init(coder: aDecoder) } /** An initializer that initializes the object with a CGRect object. If AutoLayout is used, it is better to initilize the instance using the init() initializer. - Parameter frame: A CGRect instance. */ public override init(frame: CGRect) { leftViews = [] rightViews = [] super.init(frame: frame) } /// Convenience initializer. public convenience init() { self.init(frame: .zero) } /** A convenience initializer with parameter settings. - Parameter leftViews: An Array of UIViews that go on the left side. - Parameter rightViews: An Array of UIViews that go on the right side. - Parameter centerViews: An Array of UIViews that go in the center. */ public convenience init(leftViews: [UIView]? = nil, rightViews: [UIView]? = nil, centerViews: [UIView]? = nil) { self.init() self.leftViews = leftViews ?? [] self.rightViews = rightViews ?? [] self.centerViews = centerViews ?? [] } open override func layoutSubviews() { super.layoutSubviews() guard willLayout else { return } guard !grid.deferred else { return } reload() } /// Reloads the view. open func reload() { var lc = 0 var rc = 0 grid.begin() grid.views.removeAll() for v in leftViews { if let b = v as? UIButton { b.contentEdgeInsets = .zero b.titleEdgeInsets = .zero } v.width = v.intrinsicContentSize.width v.sizeToFit() v.grid.columns = Int(ceil(v.width / gridFactor)) + 2 lc += v.grid.columns grid.views.append(v) } grid.views.append(contentView) for v in rightViews { if let b = v as? UIButton { b.contentEdgeInsets = .zero b.titleEdgeInsets = .zero } v.width = v.intrinsicContentSize.width v.sizeToFit() v.grid.columns = Int(ceil(v.width / gridFactor)) + 2 rc += v.grid.columns grid.views.append(v) } contentView.grid.begin() contentView.grid.offset.columns = 0 var l: CGFloat = 0 var r: CGFloat = 0 if .center == contentViewAlignment { if leftViews.count < rightViews.count { r = CGFloat(rightViews.count) * interimSpace l = r } else { l = CGFloat(leftViews.count) * interimSpace r = l } } let p = width - l - r - contentEdgeInsets.left - contentEdgeInsets.right let columns = Int(ceil(p / gridFactor)) if .center == contentViewAlignment { if lc < rc { contentView.grid.columns = columns - 2 * rc contentView.grid.offset.columns = rc - lc } else { contentView.grid.columns = columns - 2 * lc rightViews.first?.grid.offset.columns = lc - rc } } else { contentView.grid.columns = columns - lc - rc } grid.axis.columns = columns grid.commit() contentView.grid.commit() divider.reload() } /** Prepares the view instance when intialized. When subclassing, it is recommended to override the prepare method to initialize property values and other setup operations. The super.prepare method should always be called immediately when subclassing. */ open override func prepare() { super.prepare() heightPreset = .normal autoresizingMask = .flexibleWidth interimSpacePreset = .interimSpace3 contentEdgeInsetsPreset = .square1 } }
e2b3b6368437134ef400e8dc23b3cd98
29.102837
116
0.579574
false
false
false
false
festrs/DotaComp
refs/heads/master
DotaComp/LiveGamesTableViewCell.swift
mit
1
// // EventSoonTableViewCell.swift // DotaComp // // Created by Felipe Dias Pereira on 2016-10-27. // Copyright © 2016 Felipe Dias Pereira. All rights reserved. // import UIKit class LiveGamesTableViewCell: UITableViewCell { @IBOutlet weak var team1Label: UILabel! @IBOutlet weak var team2Label: UILabel! @IBOutlet weak var bestOfLabel: UILabel! @IBOutlet weak var timeLabel: UILabel! @IBOutlet weak var backView: UIView! override func awakeFromNib() { super.awakeFromNib() backView.layer.cornerRadius = 8 backView.layer.masksToBounds = true } func setUpCell(liveGame: Game) { let direTeam = liveGame.direTeam?.teamName.map { $0 } ?? "" let radiantTeam = liveGame.radiantTeam?.teamName.map { $0 } ?? "" team1Label.text = radiantTeam team2Label.text = direTeam timeLabel.text = "LIVE" bestOfLabel.text = getSeriesType(seriesType: liveGame.seriesType!) } func getSeriesType(seriesType: Int) -> String { switch seriesType { case 0: return "Best of 1" case 1: return "Best of 3" case 2: return "Best of 5" default: return "" } } }
1fa2ab45495accbf876a62525a293aed
25.122449
74
0.603906
false
false
false
false
adamahrens/noisily
refs/heads/master
Noisily/Noisily/ViewControllers/NoiseLayeringViewController.swift
mit
1
// // NoiseLayeringViewController.swift // Noisily // // Created by Adam Ahrens on 3/19/15. // Copyright (c) 2015 Appsbyahrens. All rights reserved. // import UIKit class NoiseLayeringViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var multiSectorControl: SAMultisectorControl! private let dataSource = NoiseDataSource() private let selectedPaths = Set<NSIndexPath>() // Currently displayed sectors private var currentSectors = Array<Dictionary<String,SAMultisectorSector>>() override func viewDidLoad() { super.viewDidLoad() // Blur the background let blurEffect = UIBlurEffect(style: .Light) let blurView = UIVisualEffectView(effect: blurEffect) blurView.translatesAutoresizingMaskIntoConstraints = false self.view.insertSubview(blurView, atIndex: 0) // Have equal width and height let equalHeight = NSLayoutConstraint(item: blurView, attribute: .Height, relatedBy: .Equal, toItem: self.view, attribute: .Height, multiplier: 1.0, constant: 0.0) let equalWidth = NSLayoutConstraint(item: blurView, attribute: .Width, relatedBy: .Equal, toItem: self.view, attribute: .Width, multiplier: 1.0, constant: 0.0) self.view.addConstraints([equalHeight, equalWidth]) // Want white checkmarks for UItableViewCells UITableViewCell.appearance().tintColor = UIColor.whiteColor() } @IBAction func dismiss(sender: UIButton) { self.dismissViewControllerAnimated(true, completion: nil) } override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { self.multiSectorControl.setNeedsDisplay() coordinator.animateAlongsideTransition({ (coordinator) -> Void in self.multiSectorControl.layer.layoutIfNeeded() }, completion: nil) } //MARK: UITableView func numberOfSectionsInTableView(tableView: UITableView) -> Int { return dataSource.numberOfSections() } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataSource.numberOfNoises() } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("NoiseCell", forIndexPath: indexPath) cell.textLabel!.text = dataSource.noiseAtIndexPath(indexPath).name cell.textLabel!.textColor = UIColor.whiteColor() if selectedPaths.contains(indexPath) { cell.accessoryType = .Checkmark } else { cell.accessoryType = .None } return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if selectedPaths.contains(indexPath) { let noiseName = dataSource.noiseAtIndexPath(indexPath).name selectedPaths.remove(indexPath) let found = currentSectors.filter { $0.keys.first! == noiseName } if let dictionary = found.first { let sectorToRemove = dictionary.values.first! multiSectorControl.removeSector(sectorToRemove) currentSectors = currentSectors.filter{ $0.keys.first! != noiseName } } } else { // Add a sector selectedPaths.add(indexPath) let color = selectedPaths.size() % 2 == 0 ? UIColor.whiteColor() : UIColor.brightPink() let sector = SAMultisectorSector(color: color, minValue: 1.0, maxValue: 20.0) let noiseName = dataSource.noiseAtIndexPath(indexPath).name sector.tag = selectedPaths.size() multiSectorControl.addSector(sector) multiSectorControl.setNeedsDisplay() currentSectors.append([noiseName: sector]) } tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic) } }
c1ce876096f1ffd952a00a0eb30ad277
40.958763
170
0.674447
false
false
false
false
wireapp/wire-ios
refs/heads/develop
Wire-iOS/Sources/UserInterface/Components/Controllers/CallQualityController/CallQualityPresentationTransition.swift
gpl-3.0
1
// // Wire // Copyright (C) 2018 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 UIKit class CallQualityPresentationTransition: NSObject, UIViewControllerAnimatedTransitioning { func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 0.55 } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { guard let callQualityVC = transitionContext.viewController(forKey: .to) as? CallQualityViewController else { return } // Prepare view hierarchy let containerView = transitionContext.containerView let toView = callQualityVC.view! let contentView = callQualityVC.contentView let dimmingView = callQualityVC.dimmingView containerView.addSubview(toView) callQualityVC.updateLayout(for: containerView.traitCollection) switch containerView.traitCollection.horizontalSizeClass { case .regular: contentView.transform = CGAffineTransform(scaleX: 0, y: 0) default: contentView.transform = CGAffineTransform(translationX: 0, y: containerView.frame.height) } // Animate Presentation let duration = transitionDuration(using: transitionContext) let animations = { dimmingView.alpha = 1 contentView.transform = .identity } UIView.animate(withDuration: duration, delay: 0, options: .systemPresentationCurve, animations: animations) { finished in transitionContext.completeTransition((transitionContext.transitionWasCancelled == false) && finished) } } }
3db5e66e9b7f3d6742460c53747046df
34.015152
129
0.712678
false
false
false
false
Holmusk/HMRequestFramework-iOS
refs/heads/master
HMRequestFramework-FullDemo/AppDelegate.swift
apache-2.0
1
// // AppDelegate.swift // HMRequestFramework-FullDemo // // Created by Hai Pham on 17/1/18. // Copyright © 2018 Holmusk. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. let provider = Singleton.instance let topVC = (window?.rootViewController as? NavigationVC)! let navigator = NavigationService(topVC) let vm = NavigationViewModel(provider, navigator) topVC.viewModel = vm 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:. // // Saves changes in the application's managed object context before the // application terminates. } }
977cfea0f0e7b8a550c614a92d5afd8e
40.19403
114
0.689493
false
false
false
false
tgu/HAP
refs/heads/master
Sources/HAP/Accessories/ContactSensor.swift
mit
1
extension Accessory { open class ContactSensor: Accessory { public let contactSensor = Service.ContactSensor() public init(info: Service.Info, additionalServices: [Service] = []) { super.init(info: info, type: .sensor, services: [contactSensor] + additionalServices) } } } public enum ContactSensorState: Int, CharacteristicValueType { case detected = 0 case notDetected = 1 } extension Service { open class ContactSensor: Service { public let contactSensorState = GenericCharacteristic<ContactSensorState>( type: .contactSensorState, value: .notDetected, permissions: [.read, .events]) public init() { super.init(type: .contactSensor, characteristics: [contactSensorState]) } } }
b400315b0cc3da9fe4415ecc9fd5bac6
29.259259
97
0.647491
false
false
false
false
WLChopSticks/weiboCopy
refs/heads/master
weiboCopy/weiboCopy/Classes/Module/oAuth/CHSLogInViewController.swift
mit
2
// // CHSLogInViewController.swift // weiboCopy // // Created by 王 on 15/12/14. // Copyright © 2015年 王. All rights reserved. // import UIKit import AFNetworking class CHSLogInViewController: UIViewController, UIWebViewDelegate { let webView = UIWebView() override func viewDidLoad() { super.viewDidLoad() //change the view to the webView to show the oAhtu information view = webView //add a reurn button navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: .Plain, target: self, action: "returnToTheMainView") //add an autofill button navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填写", style: .Plain, target: self, action: "autoFillButton") //webView delegate webView.delegate = self //load the autho view loadAuthoView() } private func loadAuthoView() { let url = NSURL(string: "https://api.weibo.com/oauth2/authorize" + "?client_id=" + "235072683" + "&redirect_uri=" + callBackURL) let urlRequest = NSURLRequest(URL: url!) webView.loadRequest(urlRequest) } //return and autofill button method @objc private func autoFillButton() { let autofill = "document.getElementById('userId').value = '18602602808' ,document.getElementById('passwd').value = '1357924680'" webView.stringByEvaluatingJavaScriptFromString(autofill) } @objc private func returnToTheMainView() { dismissViewControllerAnimated(true, completion: nil) } //realize delegate method func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool { // print(request.URL?.absoluteString) //shield some unuseful web, eg.regist button and change account choice guard let urlString = request.URL?.absoluteString else { return false } if urlString.hasPrefix("http://weibo.cn/dpool/ttt/h5/reg.php") { return false } if urlString.hasPrefix("http://passport.sina.cn/sso/crossdomain") { return false } if urlString.hasPrefix("https://api.weibo.com/oauth2/") { return true } if urlString.hasPrefix("https://m.baidu.com/") { return false } //http://www.weibo.com/yes603020460?code=972944fad66aee898b8bfc296355e804&is_all=1 //get the code from the call back url let query = request.URL?.query if let q = query { let pre = "code=" let code = q.substringFromIndex(pre.endIndex) CHSUserAccountViewModel().getAccessTocken(code, finish: { (userLogIn) -> () in if userLogIn { print("success") self.returnToTheMainView() }else { print("fail to load") } }) } return true } }
82236e91238eb9442662f0b4d67888ae
28.87619
137
0.589735
false
false
false
false
shlyren/ONE-Swift
refs/heads/master
ONE_Swift/Classes/Reading-阅读/Model/JENReadCarouselItem.swift
mit
1
// // JENReadCarouselItem.swift // ONE_Swift // // Created by 任玉祥 on 16/5/2. // Copyright © 2016年 任玉祥. All rights reserved. // import UIKit // MARK: - 轮播列表模型 class JENReadCarouselListItem: NSObject { /// id var carousel_id: String? /// 标题 var title: String? /// 图片 var cover: String? /// 背景颜色 var bgcolor: String? /// 底部文字 var bottom_text: String? //var pv_url: String? } // MARK: - 轮播主题模型 class JENReadCarouselItem: NSObject { /// item id var item_id: String? /// 标题 var title: String? /// 内容 var introduction: String? /// 作者 var author: String? /// var number = "" /// 类型 var type = 0 var readType: JENReadType { get { var readType = JENReadType.Unknow switch type { case 1: readType = .Essay case 2: readType = .Serial case 3: readType = .Question default: readType = .Unknow } return readType } } }
2ff3dd9d2bb32c922749986892d795bb
18.637931
47
0.47891
false
false
false
false
ikesyo/Swiftz
refs/heads/master
SwiftzTests/EitherSpec.swift
bsd-3-clause
3
// // EitherSpec.swift // Swiftz // // Created by Robert Widmann on 1/19/15. // Copyright (c) 2015 TypeLift. All rights reserved. // import XCTest import Swiftz import SwiftCheck struct EitherOf<A : Arbitrary, B : Arbitrary> : Arbitrary { let getEither : Either<A, B> init(_ either : Either<A, B>) { self.getEither = either } var description : String { return "\(self.getEither)" } static var arbitrary : Gen<EitherOf<A, B>> { return EitherOf.init <^> Gen.oneOf([ Either.Left <^> A.arbitrary, Either.Right <^> B.arbitrary, ]) } static func shrink(bl : EitherOf<A, B>) -> [EitherOf<A, B>] { return bl.getEither.either(onLeft: { x in return A.shrink(x).map(EitherOf.init • Either.Left) }, onRight: { y in return B.shrink(y).map(EitherOf.init • Either.Right) }) } } class EitherSpec : XCTestCase { func divTwoEvenly(x: Int) -> Either<String, Int> { if x % 2 == 0 { return Either.Left("\(x) was div by 2") } else { return Either.Right(x / 2) } } func testProperties() { property("divTwoEvenly") <- forAll { (x : Int) in let first : Either<String, Int> = self.divTwoEvenly(x) return first.either(onLeft: { s in return s == "\(x) was div by 2" }, onRight: { r in return r == (x / 2) }) } property("fold returns its default on .Left") <- forAll { (e : EitherOf<String, Int>) in return e.getEither.isLeft ==> (e.getEither.fold(0, f: identity) == 0) } property("Either is a bifunctor") <- forAll { (e : EitherOf<String, Int>) in let y = e.getEither.bimap(identity, *2) if e.getEither.isLeft { return y == e.getEither } else { return y == ((*2) <^> e.getEither) } } // TODO: How in hell does this typecheck? // either XCTAssert(Either.Left("foo").either(onLeft: { l in l+"!" }, onRight: { r in r+1 }) == "foo!") XCTAssert(Either.Right(1).either(onLeft: { l in l+"!" }, onRight: { r in r+1 }) == 2) } }
e3af029cef339caf5471af6fdb4c21ac
23.948052
95
0.611661
false
false
false
false
superman-coder/pakr
refs/heads/master
pakr/pakr/Model/GoogleServices/GMPlace.swift
apache-2.0
1
// // GMPlace.swift // pakr // // Created by Tien on 4/18/16. // Copyright © 2016 Pakr. All rights reserved. // import UIKit class GMPlace: NSObject { let geometry:Coordinate! let name:String! let address:String! init(json:NSDictionary) { let geometryJson = json["geometry"] as! NSDictionary let location = geometryJson["location"] as! NSDictionary let lat = location["lat"] as! Double let lng = location["lng"] as! Double geometry = Coordinate(latitude: lat, longitude: lng) name = json["name"] as! String address = json["formatted_address"] as! String } }
10a6a29d287a16a2fead0794eb56652d
24.153846
64
0.616208
false
false
false
false
MenloHacks/ios-app
refs/heads/master
Menlo Hacks/Pods/Parchment/Parchment/Structs/PagingItems.swift
mit
1
import Foundation /// A data structure used to hold an array of `PagingItem`'s, with /// methods for getting the index path for a given `PagingItem` and /// vice versa. public struct PagingItems<T: PagingItem> where T: Hashable & Comparable { /// A sorted array of the currently visible `PagingItem`'s. public let items: [T] let hasItemsBefore: Bool let hasItemsAfter: Bool let itemsCache: Set<T> init(items: [T], hasItemsBefore: Bool = false, hasItemsAfter: Bool = false) { self.items = items self.hasItemsBefore = hasItemsBefore self.hasItemsAfter = hasItemsAfter self.itemsCache = Set(items) } /// The `IndexPath` for a given `PagingItem`. Returns nil if the /// `PagingItem` is not in the `items` array. /// /// - Parameter pagingItem: A `PagingItem` instance /// - Returns: The `IndexPath` for the given `PagingItem` public func indexPath(for pagingItem: T) -> IndexPath? { guard let index = items.index(of: pagingItem) else { return nil } return IndexPath(item: index, section: 0) } /// The `PagingItem` for a given `IndexPath`. This method will crash /// if you pass in an `IndexPath` that is currently not visible in /// the collection view. /// /// - Parameter indexPath: An `IndexPath` that is currently visible /// - Returns: The `PagingItem` for the given `IndexPath` public func pagingItem(for indexPath: IndexPath) -> T { return items[indexPath.item] } /// The direction from a given `PagingItem` to another `PagingItem`. /// If the `PagingItem`'s are equal the direction will be .none. /// /// - Parameter from: The current `PagingItem` /// - Parameter to: The `PagingItem` being scrolled towards /// - Returns: The `PagingDirection` for a given `PagingItem` public func direction(from: T, to: T) -> PagingDirection { if itemsCache.contains(from) == false { return .none } else if to > from { return .forward } else if to < from { return .reverse } return .none } }
3cd2d5095b9f82189c41ef1caa184b7c
33.931034
79
0.671273
false
false
false
false
atrick/swift
refs/heads/main
test/Generics/rdar86431977.swift
apache-2.0
3
// RUN: %target-swift-frontend -typecheck %s -debug-generic-signatures -requirement-machine-inferred-signatures=on 2>&1 | %FileCheck %s protocol P1 { associatedtype A associatedtype B : P1 where B.A == A, B.B == B } protocol P2 : P1 where A == Self {} struct G<T, U> {} // The GSB used to get the signature of bar() wrong. extension G { // CHECK-LABEL: rdar86431977.(file).G extension.foo()@ // CHECK: Generic signature: <T, U where T : P2, T == U> func foo() where T : P2, U == T {} // CHECK-LABEL: rdar86431977.(file).G extension.bar()@ // CHECK: Generic signature: <T, U where T : P2, T == U> func bar() where T : P2, T == U {} }
d23601c19de6e2ab933a1aeae0c35a5b
28.772727
135
0.630534
false
false
false
false
popwarsweet/StreamingProgressBar
refs/heads/master
Example/StreamingProgressBar/ViewController.swift
mit
1
// // ViewController.swift // StreamingProgressBar // // Created by Kyle Zaragoza on 08/23/2016. // Copyright (c) 2016 Kyle Zaragoza. All rights reserved. // import UIKit import StreamingProgressBar class ViewController: UIViewController { @IBOutlet weak var progressBar: StreamingProgressBar! var playTimer: Timer? var bufferTimer: Timer? override func viewDidLoad() { super.viewDidLoad() playTimer = Timer.scheduledTimer( timeInterval: 1/30, target: self, selector: #selector(incrementPlayTimer), userInfo: nil, repeats: true) bufferTimer = Timer.scheduledTimer( timeInterval: 0.5, target: self, selector: #selector(incrementBufferProgress), userInfo: nil, repeats: true) } func incrementPlayTimer() { let updatedProgress = progressBar.progress + 0.002 if updatedProgress > 1 { progressBar.progress = 0 progressBar.secondaryProgress = 0 } else { progressBar.progress = updatedProgress } } func incrementBufferProgress() { progressBar.secondaryProgress += 0.1 } }
a345cc49a8562c7e650741e14cb12a4e
24.916667
58
0.606913
false
false
false
false
JaSpa/swift
refs/heads/master
test/DebugInfo/return.swift
apache-2.0
3
// RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests %s -g -emit-ir -o - | %FileCheck %s class X { init (i : Int64) { x = i } var x : Int64 } // CHECK: define {{.*}}ifelseexpr public func ifelseexpr() -> Int64 { var x = X(i:0) // CHECK: [[META:%.*]] = call %swift.type* @_T06return1XCMa() // CHECK: [[X:%.*]] = call %C6return1X* @_T06return1XCACs5Int64V1i_tcfC( // CHECK-SAME: i64 0, %swift.type* [[META]]) // CHECK: @swift_rt_swift_release to void (%C6return1X*)*)(%C6return1X* [[X]]) if true { x.x += 1 } else { x.x -= 1 } // CHECK: @swift_rt_swift_release to void (%C6return1X*)*)(%C6return1X* [[X]]) // CHECK-SAME: , !dbg ![[RELEASE:.*]] // The ret instruction should be in the same scope as the return expression. // CHECK: ret{{.*}}, !dbg ![[RELEASE]] return x.x // CHECK: ![[RELEASE]] = !DILocation(line: [[@LINE]], column: 3 }
bf04d47572982758d674993e718359c2
33.888889
97
0.546709
false
false
false
false
suragch/MongolAppDevelopment-iOS
refs/heads/master
Mongol App Componants/QwertyKeyboard.swift
mit
1
import UIKit class QwertyKeyboard: UIView, KeyboardKeyDelegate { weak var delegate: KeyboardDelegate? // probably the view controller fileprivate let renderer = MongolUnicodeRenderer.sharedInstance fileprivate var punctuationOn = false fileprivate let nirugu = "\u{180a}" fileprivate let fvs1 = "\u{180b}" fileprivate let fvs2 = "\u{180c}" fileprivate let fvs3 = "\u{180d}" // Keyboard Keys // Row 1 fileprivate let keyQ = KeyboardTextKey() fileprivate let keyW = KeyboardTextKey() fileprivate let keyE = KeyboardTextKey() fileprivate let keyR = KeyboardTextKey() fileprivate let keyT = KeyboardTextKey() fileprivate let keyY = KeyboardTextKey() fileprivate let keyU = KeyboardTextKey() fileprivate let keyI = KeyboardTextKey() fileprivate let keyO = KeyboardTextKey() fileprivate let keyP = KeyboardTextKey() // Row 2 fileprivate let keyA = KeyboardTextKey() fileprivate let keyS = KeyboardTextKey() fileprivate let keyD = KeyboardTextKey() fileprivate let keyF = KeyboardTextKey() fileprivate let keyG = KeyboardTextKey() fileprivate let keyH = KeyboardTextKey() fileprivate let keyJ = KeyboardTextKey() fileprivate let keyK = KeyboardTextKey() fileprivate let keyL = KeyboardTextKey() fileprivate let keyNg = KeyboardTextKey() // Row 3 fileprivate let keyFVS = KeyboardFvsKey() fileprivate let keyZ = KeyboardTextKey() fileprivate let keyX = KeyboardTextKey() fileprivate let keyC = KeyboardTextKey() fileprivate let keyV = KeyboardTextKey() fileprivate let keyB = KeyboardTextKey() fileprivate let keyN = KeyboardTextKey() fileprivate let keyM = KeyboardTextKey() fileprivate let keyBackspace = KeyboardImageKey() // Row 4 fileprivate let keyKeyboard = KeyboardChooserKey() fileprivate let keyMVS = KeyboardTextKey() fileprivate let keyComma = KeyboardTextKey() fileprivate let keySpace = KeyboardImageKey() fileprivate let keyQuestion = KeyboardTextKey() fileprivate let keySuffix = KeyboardTextKey() fileprivate let keyReturn = KeyboardImageKey() // MARK:- keyboard initialization required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } override init(frame: CGRect) { super.init(frame: frame) setup() } func setup() { addSubviews() initializeNonChangingKeys() setMongolKeyStrings() assignDelegates() //print(renderer.unicodeToGlyphs("ᠠᠨ\u{180E}ᠠ ᠠᠮ\u{180E}ᠠ ᠠᠭ\u{180E}ᠠ")) //print(renderer.unicodeToGlyphs("\u{202F}ᠶᠢ\u{202F}ᠳᠦ\u{202F}ᠦᠨ")) } func addSubviews() { // Row 1 self.addSubview(keyQ) self.addSubview(keyW) self.addSubview(keyE) self.addSubview(keyR) self.addSubview(keyT) self.addSubview(keyY) self.addSubview(keyU) self.addSubview(keyI) self.addSubview(keyO) self.addSubview(keyP) // Row 2 self.addSubview(keyA) self.addSubview(keyS) self.addSubview(keyD) self.addSubview(keyF) self.addSubview(keyG) self.addSubview(keyH) self.addSubview(keyJ) self.addSubview(keyK) self.addSubview(keyL) self.addSubview(keyNg) // Row 3 self.addSubview(keyFVS) self.addSubview(keyZ) self.addSubview(keyX) self.addSubview(keyC) self.addSubview(keyV) self.addSubview(keyB) self.addSubview(keyN) self.addSubview(keyM) self.addSubview(keyBackspace) // Row 4 self.addSubview(keyKeyboard) self.addSubview(keyMVS) self.addSubview(keyComma) self.addSubview(keySpace) self.addSubview(keyQuestion) self.addSubview(keySuffix) self.addSubview(keyReturn) } func initializeNonChangingKeys() { // Row 3 keyFVS.setStrings("", fvs2Top: "", fvs3Top: "", fvs1Bottom: "", fvs2Bottom: "", fvs3Bottom: "") keyBackspace.image = UIImage(named: "backspace_dark") keyBackspace.keyType = KeyboardImageKey.KeyType.backspace keyBackspace.repeatOnLongPress = true // Row 4 keyKeyboard.image = UIImage(named: "keyboard_dark") keyMVS.primaryString = "\u{180E}" // MVS keyMVS.primaryStringDisplayOverride = "  " // na ma ga keyMVS.primaryStringFontSize = 14.0 keyMVS.secondaryString = "\u{200D}" // ZWJ keyMVS.secondaryStringDisplayOverride = "-" // TODO: keyComma.primaryString = "\u{1802}" // mongol comma keyComma.secondaryString = "\u{1803}" // mongol period keySpace.primaryString = " " keySpace.image = UIImage(named: "space_dark") keySpace.repeatOnLongPress = true keyQuestion.primaryString = "?" keyQuestion.secondaryString = "!" keySuffix.primaryString = "\u{202F}" // NNBS keySuffix.primaryStringDisplayOverride = "  " // yi du un keySuffix.primaryStringFontSize = 14.0 keyReturn.image = UIImage(named: "return_dark") } func setMongolKeyStrings() { // Row 1 keyQ.primaryString = "ᠴ" keyQ.secondaryString = "ᡂ" keyW.primaryString = "ᠸ" keyW.secondaryString = "" keyE.primaryString = "ᠡ" keyE.secondaryString = "ᠧ" keyR.primaryString = "ᠷ" keyR.secondaryString = "ᠿ" keyT.primaryString = "ᠲ" keyT.secondaryString = "" keyY.primaryString = "ᠶ" keyY.secondaryString = "" keyU.primaryString = "ᠦ" keyU.primaryStringDisplayOverride = "" keyU.secondaryString = "" keyI.primaryString = "ᠢ" keyI.secondaryString = "" keyO.primaryString = "ᠥ" keyO.secondaryString = "" keyP.primaryString = "ᠫ" keyP.secondaryString = "" // Row 2 keyA.primaryString = "ᠠ" keyS.primaryString = "ᠰ" keyD.primaryString = "ᠳ" keyF.primaryString = "ᠹ" keyG.primaryString = "ᠭ" keyH.primaryString = "ᠬ" keyH.secondaryString = "ᠾ" keyJ.primaryString = "ᠵ" keyJ.secondaryString = "ᡁ" keyK.primaryString = "ᠺ" keyL.primaryString = "ᠯ" keyL.secondaryString = "ᡀ" keyNg.primaryString = "ᠩ" // Row 3 keyZ.primaryString = "ᠽ" keyZ.secondaryString = "ᠼ" keyX.primaryString = "ᠱ" keyC.primaryString = "ᠣ" keyV.primaryString = "ᠤ" keyV.primaryStringDisplayOverride = "" keyB.primaryString = "ᠪ" keyN.primaryString = "ᠨ" keyM.primaryString = "ᠮ" } func setPunctuationKeyStrings() { // Row 1 keyQ.primaryString = "1" keyQ.secondaryString = "᠑" keyW.primaryString = "2" keyW.secondaryString = "᠒" keyE.primaryString = "3" keyE.secondaryString = "᠓" keyR.primaryString = "4" keyR.secondaryString = "᠔" keyT.primaryString = "5" keyT.secondaryString = "᠕" keyY.primaryString = "6" keyY.secondaryString = "᠖" keyU.primaryString = "7" keyU.secondaryString = "᠗" keyI.primaryString = "8" keyI.secondaryString = "᠘" keyO.primaryString = "9" keyO.secondaryString = "᠙" keyP.primaryString = "0" keyP.secondaryString = "᠐" // Row 2 keyA.primaryString = "(" keyS.primaryString = ")" keyD.primaryString = "<" keyF.primaryString = ">" keyG.primaryString = "«" keyH.primaryString = "»" keyH.secondaryString = "" keyJ.primaryString = "⁈" keyJ.secondaryString = "" keyK.primaryString = "⁉" keyL.primaryString = "‼" keyL.secondaryString = "" keyNg.primaryString = "᠄" // Row 3 keyZ.primaryString = "᠁" keyZ.secondaryString = "" keyX.primaryString = "᠅" keyC.primaryString = "·" keyV.primaryString = "." keyB.primaryString = "᠊" keyN.primaryString = "︱" keyM.primaryString = ";" } func assignDelegates() { // Row 1 keyQ.delegate = self keyW.delegate = self keyE.delegate = self keyR.delegate = self keyT.delegate = self keyY.delegate = self keyU.delegate = self keyI.delegate = self keyO.delegate = self keyP.delegate = self // Row 2 keyA.delegate = self keyS.delegate = self keyD.delegate = self keyF.delegate = self keyG.delegate = self keyH.delegate = self keyJ.delegate = self keyK.delegate = self keyL.delegate = self keyNg.delegate = self // Row 3 keyFVS.delegate = self keyZ.delegate = self keyX.delegate = self keyC.delegate = self keyV.delegate = self keyB.delegate = self keyN.delegate = self keyM.delegate = self keyBackspace.delegate = self // Row 4 //keyKeyboard.addTarget(self, action: "keyKeyboardTapped", forControlEvents: UIControlEvents.TouchUpInside) keyKeyboard.delegate = self keyMVS.delegate = self keyComma.delegate = self keySpace.delegate = self keyQuestion.delegate = self keySuffix.delegate = self keyReturn.addTarget(self, action: #selector(keyReturnTapped), for: UIControlEvents.touchUpInside) } override func layoutSubviews() { // TODO: - should add autolayout constraints instead // | Q | W | E | R | T | Y | U | I | O | P | Row 1 // | A | S | D | F | G | H | J | K | L | NG| Row 2 // | fvs | Z | X | C | V | B | N | M | del | Row 3 // | 123 |mvs| , | space | ? |nbs| ret | Row 4 //let suggestionBarWidth: CGFloat = 30 let numberOfRows: CGFloat = 4 let keyUnitsInRow1: CGFloat = 10 let rowHeight = self.bounds.height / numberOfRows let keyUnitWidth = self.bounds.width / keyUnitsInRow1 let wideKeyWidth = 1.5 * keyUnitWidth let spaceKeyWidth = 3 * keyUnitWidth // Row 1 keyQ.frame = CGRect(x: keyUnitWidth*0, y: 0, width: keyUnitWidth, height: rowHeight) keyW.frame = CGRect(x: keyUnitWidth*1, y: 0, width: keyUnitWidth, height: rowHeight) keyE.frame = CGRect(x: keyUnitWidth*2, y: 0, width: keyUnitWidth, height: rowHeight) keyR.frame = CGRect(x: keyUnitWidth*3, y: 0, width: keyUnitWidth, height: rowHeight) keyT.frame = CGRect(x: keyUnitWidth*4, y: 0, width: keyUnitWidth, height: rowHeight) keyY.frame = CGRect(x: keyUnitWidth*5, y: 0, width: keyUnitWidth, height: rowHeight) keyU.frame = CGRect(x: keyUnitWidth*6, y: 0, width: keyUnitWidth, height: rowHeight) keyI.frame = CGRect(x: keyUnitWidth*7, y: 0, width: keyUnitWidth, height: rowHeight) keyO.frame = CGRect(x: keyUnitWidth*8, y: 0, width: keyUnitWidth, height: rowHeight) keyP.frame = CGRect(x: keyUnitWidth*9, y: 0, width: keyUnitWidth, height: rowHeight) // Row 2 keyA.frame = CGRect(x: keyUnitWidth*0, y: rowHeight, width: keyUnitWidth, height: rowHeight) keyS.frame = CGRect(x: keyUnitWidth*1, y: rowHeight, width: keyUnitWidth, height: rowHeight) keyD.frame = CGRect(x: keyUnitWidth*2, y: rowHeight, width: keyUnitWidth, height: rowHeight) keyF.frame = CGRect(x: keyUnitWidth*3, y: rowHeight, width: keyUnitWidth, height: rowHeight) keyG.frame = CGRect(x: keyUnitWidth*4, y: rowHeight, width: keyUnitWidth, height: rowHeight) keyH.frame = CGRect(x: keyUnitWidth*5, y: rowHeight, width: keyUnitWidth, height: rowHeight) keyJ.frame = CGRect(x: keyUnitWidth*6, y: rowHeight, width: keyUnitWidth, height: rowHeight) keyK.frame = CGRect(x: keyUnitWidth*7, y: rowHeight, width: keyUnitWidth, height: rowHeight) keyL.frame = CGRect(x: keyUnitWidth*8, y: rowHeight, width: keyUnitWidth, height: rowHeight) keyNg.frame = CGRect(x: keyUnitWidth*9, y: rowHeight, width: keyUnitWidth, height: rowHeight) // Row 3 keyFVS.frame = CGRect(x: 0, y: rowHeight*2, width: wideKeyWidth, height: rowHeight) keyZ.frame = CGRect(x: wideKeyWidth, y: rowHeight*2, width: keyUnitWidth, height: rowHeight) keyX.frame = CGRect(x: wideKeyWidth + keyUnitWidth*1, y: rowHeight*2, width: keyUnitWidth, height: rowHeight) keyC.frame = CGRect(x: wideKeyWidth + keyUnitWidth*2, y: rowHeight*2, width: keyUnitWidth, height: rowHeight) keyV.frame = CGRect(x: wideKeyWidth + keyUnitWidth*3, y: rowHeight*2, width: keyUnitWidth, height: rowHeight) keyB.frame = CGRect(x: wideKeyWidth + keyUnitWidth*4, y: rowHeight*2, width: keyUnitWidth, height: rowHeight) keyN.frame = CGRect(x: wideKeyWidth + keyUnitWidth*5, y: rowHeight*2, width: keyUnitWidth, height: rowHeight) keyM.frame = CGRect(x: wideKeyWidth + keyUnitWidth*6, y: rowHeight*2, width: keyUnitWidth, height: rowHeight) keyBackspace.frame = CGRect(x: wideKeyWidth + keyUnitWidth*7, y: rowHeight*2, width: wideKeyWidth, height: rowHeight) // Row 4 keyKeyboard.frame = CGRect(x: 0, y: rowHeight*3, width: wideKeyWidth, height: rowHeight) keyMVS.frame = CGRect(x: wideKeyWidth, y: rowHeight*3, width: keyUnitWidth, height: rowHeight) keyComma.frame = CGRect(x: wideKeyWidth + keyUnitWidth*1, y: rowHeight*3, width: keyUnitWidth, height: rowHeight) keySpace.frame = CGRect(x: wideKeyWidth + keyUnitWidth*2, y: rowHeight*3, width: spaceKeyWidth, height: rowHeight) keyQuestion.frame = CGRect(x: wideKeyWidth + keyUnitWidth*5, y: rowHeight*3, width: keyUnitWidth, height: rowHeight) keySuffix.frame = CGRect(x: wideKeyWidth + keyUnitWidth*6, y: rowHeight*3, width: keyUnitWidth, height: rowHeight) keyReturn.frame = CGRect(x: wideKeyWidth + keyUnitWidth*7, y: rowHeight*3, width: wideKeyWidth, height: rowHeight) } // MARK: - Other func otherAvailableKeyboards(_ displayNames: [String]) { keyKeyboard.menuItems = displayNames } func updateFvsKey(_ previousChar: String?, currentChar: String) { // get the last character (previousChar is not necessarily a single char) var lastChar: UInt32 = 0 if let previous = previousChar { for c in previous.unicodeScalars { lastChar = c.value } } // lookup the strings and update the key if renderer.isMongolian(lastChar) { // Medial or Final // Medial on top var fvs1Top = "" if let search = renderer.medialGlyphForUnicode(currentChar + fvs1) { fvs1Top = search } var fvs2Top = "" if let search = renderer.medialGlyphForUnicode(currentChar + fvs2) { fvs2Top = search } var fvs3Top = "" if let search = renderer.medialGlyphForUnicode(currentChar + fvs3) { fvs3Top = search } // Final on bottom var fvs1Bottom = "" if let search = renderer.finalGlyphForUnicode(currentChar + fvs1) { fvs1Bottom = search } var fvs2Bottom = "" if let search = renderer.finalGlyphForUnicode(currentChar + fvs2) { fvs2Bottom = search } var fvs3Bottom = "" if let search = renderer.finalGlyphForUnicode(currentChar + fvs3) { fvs3Bottom = search } keyFVS.setStrings(fvs1Top, fvs2Top: fvs2Top, fvs3Top: fvs3Top, fvs1Bottom: fvs1Bottom, fvs2Bottom: fvs2Bottom, fvs3Bottom: fvs3Bottom) } else { // Initial or Isolate // Initial on top var fvs1Top = "" if let search = renderer.initialGlyphForUnicode(currentChar + fvs1) { fvs1Top = search } var fvs2Top = "" if let search = renderer.initialGlyphForUnicode(currentChar + fvs2) { fvs2Top = search } var fvs3Top = "" if let search = renderer.initialGlyphForUnicode(currentChar + fvs3) { fvs3Top = search } // Isolate on bottom var fvs1Bottom = "" if let search = renderer.isolateGlyphForUnicode(currentChar + fvs1) { fvs1Bottom = search } var fvs2Bottom = "" if let search = renderer.isolateGlyphForUnicode(currentChar + fvs2) { fvs2Bottom = search } var fvs3Bottom = "" if let search = renderer.isolateGlyphForUnicode(currentChar + fvs3) { fvs3Bottom = search } keyFVS.setStrings(fvs1Top, fvs2Top: fvs2Top, fvs3Top: fvs3Top, fvs1Bottom: fvs1Bottom, fvs2Bottom: fvs2Bottom, fvs3Bottom: fvs3Bottom) } } // MARK: - KeyboardKeyDelegate protocol func keyTextEntered(_ keyText: String) { print("key text: \(keyText)") // pass the input up to the Keyboard delegate let previousChar = self.delegate?.charBeforeCursor() updateFvsKey(previousChar, currentChar: keyText) self.delegate?.keyWasTapped(keyText) } func keyBackspaceTapped() { self.delegate?.keyBackspace() print("key text: backspace") updateFvsKey("", currentChar: "") } func keyReturnTapped() { self.delegate?.keyWasTapped("\n") print("key text: return") updateFvsKey("", currentChar: "") } func keyFvsTapped(_ fvs: String) { print("key text: fvs") self.delegate?.keyWasTapped(fvs) } func keyKeyboardTapped() { print("key text: keyboard") // switch punctuation punctuationOn = !punctuationOn if punctuationOn { setPunctuationKeyStrings() } else { setMongolKeyStrings() } updateFvsKey("", currentChar: "") } // tell the view controller to switch keyboards func keyNewKeyboardChosen(_ keyboardName: String) { delegate?.keyNewKeyboardChosen(keyboardName) updateFvsKey("", currentChar: "") } }
10bcd4768cd6ba101f865cc82e40a22e
35.456979
146
0.590864
false
false
false
false
bitjammer/swift
refs/heads/master
test/SILGen/collection_cast_crash.swift
apache-2.0
2
// RUN: %target-swift-frontend -O -Xllvm -sil-inline-generics=false -primary-file %s -emit-sil -o - | %FileCheck %s // check if the compiler does not crash if a function is specialized // which contains a collection cast class MyClass {} class KeyClass : Hashable { var hashValue : Int { return 0 } } func ==(lhs: KeyClass, rhs: KeyClass) -> Bool { return true } // CHECK-LABEL: sil hidden @{{.*}}arrayUpCast{{.*}} <Ct where Ct : MyClass> func arrayUpCast<Ct: MyClass>(_ arr: [Ct]) -> [MyClass] { // CHECK: apply %{{[0-9]*}}<Ct, MyClass>(%{{[0-9]*}}) return arr // CHECK: return } // CHECK-LABEL: sil hidden @{{.*}}arrayDownCast{{.*}} <Ct where Ct : MyClass> func arrayDownCast<Ct: MyClass>(_ arr: [MyClass]) -> [Ct] { // CHECK: apply %{{[0-9]*}}<MyClass, Ct>(%{{[0-9]*}}) return arr as! [Ct] // CHECK: return } // CHECK-LABEL: sil hidden @{{.*}}dictUpCast{{.*}} <Ct where Ct : MyClass> func dictUpCast<Ct: MyClass>(_ dict: [KeyClass:Ct]) -> [KeyClass:MyClass] { // CHECK: apply %{{[0-9]*}}<KeyClass, Ct, KeyClass, MyClass>(%{{[0-9]*}}) return dict as [KeyClass:MyClass] // CHECK: return } // CHECK-LABEL: sil hidden @{{.*}}dictDownCast{{.*}} <Ct where Ct : MyClass> func dictDownCast<Ct: MyClass>(_ dict: [KeyClass:MyClass]) -> [KeyClass:Ct] { // CHECK: apply %{{[0-9]*}}<KeyClass, MyClass, KeyClass, Ct>(%{{[0-9]*}}) return dict as! [KeyClass:Ct] // CHECK: return } func setUpCast<Ct: KeyClass>(_ s: Set<Ct>) -> Set<KeyClass> { // CHECK: apply %{{[0-9]*}}<Ct, KeyClass>(%{{[0-9]*}}) return s as Set<KeyClass> // CHECK: return } func setDownCast<Ct : KeyClass>(_ s : Set<KeyClass>) -> Set<Ct> { // CHECK: apply %{{[0-9]*}}<KeyClass, Ct>(%{{[0-9]*}}) return s as! Set<Ct> // CHECK: return } let arr: [MyClass] = [MyClass()] arrayUpCast(arr) arrayDownCast(arr) let dict: [KeyClass:MyClass] = [KeyClass() : MyClass()] dictUpCast(dict) dictDownCast(dict) let s: Set<KeyClass> = Set() setUpCast(s) setDownCast(s)
39fe0e34ec637b40a27c9d98ac6ec7e7
29
116
0.608586
false
false
false
false
coderZsq/coderZsq.target.swift
refs/heads/master
StudyNotes/iOS Collection/Business/Business/Bluetooth/BluetoothViewController.swift
mit
1
// // BluetoothViewController.swift // Business // // Created by 朱双泉 on 2018/12/6. // Copyright © 2018 Castie!. All rights reserved. // import UIKit import MultipeerConnectivity let serviceType = "castiel" class BluetoothViewController: UIViewController { @IBOutlet weak var inputTextField: UITextField! @IBOutlet weak var tableView: UITableView! lazy var assistant: MCAdvertiserAssistant = { let assistant = MCAdvertiserAssistant(serviceType: serviceType, discoveryInfo: ["advinfo" : "castiel"], session: session) return assistant }() lazy var session: MCSession = { let displayName = UIDevice.current.name let peer = MCPeerID(displayName: displayName) let session = MCSession(peer: peer) session.delegate = self return session }() lazy var browser: MCBrowserViewController = { let browser = MCBrowserViewController(serviceType: serviceType, session: session) browser.delegate = self return browser }() @IBAction func mcButtonClick(_ sender: UIButton) { present(browser, animated: true, completion: nil) } @IBAction func changeAdv(_ sender: UISwitch) { sender.isOn ? assistant.start() : assistant.stop() } var msgs: [String] = [] override func viewDidLoad() { super.viewDidLoad() title = "Multipeer" NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillChangeFrameNotification, object: nil, queue: OperationQueue.main) { (note) in if let beginFrame = note.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? CGRect, let endFrame = note.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect { let changeY = endFrame.minY - beginFrame.minY self.view.frame = CGRect(origin: CGPoint(x: 0, y: changeY), size: self.view.bounds.size) } } } } extension BluetoothViewController: MCBrowserViewControllerDelegate { func browserViewControllerDidFinish(_ browserViewController: MCBrowserViewController) { print(#function, #line) browserViewController.dismiss(animated: true, completion: nil) } func browserViewControllerWasCancelled(_ browserViewController: MCBrowserViewController) { print(#function, #line) browserViewController.dismiss(animated: true, completion: nil) } // func browserViewController(_ browserViewController: MCBrowserViewController, shouldPresentNearbyPeer peerID: MCPeerID, withDiscoveryInfo info: [String : String]?) -> Bool { // return true // } } extension BluetoothViewController: MCSessionDelegate { func session(_ session: MCSession, peer peerID: MCPeerID, didChange state: MCSessionState) { print(session, peerID, state) switch state { case .notConnected: print("notConnected") case .connecting: print("connecting") case .connected: print("connected") browser.dismiss(animated: true, completion: nil) } } func session(_ session: MCSession, didReceive data: Data, fromPeer peerID: MCPeerID) { print(data, peerID) let receive = "T: " + (String(data: data, encoding: .utf8) ?? "") msgs.append(receive) DispatchQueue.main.async { self.tableView.reloadData() self.assistant.stop() } } func session(_ session: MCSession, didReceive stream: InputStream, withName streamName: String, fromPeer peerID: MCPeerID) { } func session(_ session: MCSession, didStartReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, with progress: Progress) { } func session(_ session: MCSession, didFinishReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, at localURL: URL?, withError error: Error?) { } } extension BluetoothViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return msgs.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "identifier", for: indexPath) cell.textLabel?.text = msgs[indexPath.row]; return cell } } extension BluetoothViewController: UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { let text = textField.text guard session.connectedPeers.count > 0 else { print("error: there is no peers for textSend") return true } guard let data = text?.data(using: String.Encoding.utf8) else { return true } do { try session.send(data, toPeers: session.connectedPeers, with: .reliable) // session.sendResource(at: <#T##URL#>, withName: <#T##String#>, toPeer: <#T##MCPeerID#>, withCompletionHandler: <#T##((Error?) -> Void)?##((Error?) -> Void)?##(Error?) -> Void#>) // session.startStream(withName: <#T##String#>, toPeer: <#T##MCPeerID#>) } catch { print(error) return true } textField.text = nil textField.resignFirstResponder() msgs.append("Me: " + (text ?? "")); DispatchQueue.main.async { self.tableView.reloadData() } // perform(<#T##aSelector: Selector##Selector#>, on: <#T##Thread#>, with: <#T##Any?#>, waitUntilDone: <#T##Bool#>) return true } }
d092ebc95d07ce8bff505ed6269f0cf3
35.346154
190
0.644092
false
false
false
false
glennposadas/gpkit-ios
refs/heads/master
GPKit/GPNotification.swift
mit
1
// // GPNotification.swift // GPKit // // Created by Glenn Posadas on 6/17/17. // Copyright © 2017 Citus Labs. All rights reserved. // import UIKit import UserNotifications public class GPNotification { /** Public class function for presenting a local notification immediately. * @params - message. */ public class func presentLocalNotification(message: String) { let localNotification = UILocalNotification() localNotification.alertBody = message localNotification.soundName = UILocalNotificationDefaultSoundName; UIApplication.shared.presentLocalNotificationNow(localNotification) } /** A public class function for cancelling all scheduled local notifications */ public class func cancelScheduledLocalNotifications() { UIApplication.shared.cancelAllLocalNotifications() } /** A public class function used for scheduling local notification. * @params * - hour: Int (ex. 1 for 1 o'clock) * - minute: Int (ex. 30 for 30 minutes) */ public class func scheduleLocalNotification(hour: Int, minute: Int, notificationMessage: String, category: String? = nil) { // have to use NSCalendar for the components let calendar = NSCalendar(identifier: .gregorian)!; var dateFire = Date() var fireComponents = calendar.components( [NSCalendar.Unit.day, NSCalendar.Unit.month, NSCalendar.Unit.year, NSCalendar.Unit.hour, NSCalendar.Unit.minute], from:dateFire) // if today's date is passed, use tomorrow if (fireComponents.hour! > hour || (fireComponents.hour == hour && fireComponents.minute! >= minute) ) { dateFire = dateFire.addingTimeInterval(86400) // Use tomorrow's date fireComponents = calendar.components( [NSCalendar.Unit.day, NSCalendar.Unit.month, NSCalendar.Unit.year, NSCalendar.Unit.hour, NSCalendar.Unit.minute], from:dateFire); } // set up the time fireComponents.hour = hour fireComponents.minute = minute // schedule local notification dateFire = calendar.date(from: fireComponents)! let localNotification = UILocalNotification() localNotification.fireDate = dateFire localNotification.alertBody = notificationMessage localNotification.repeatInterval = NSCalendar.Unit.day localNotification.soundName = UILocalNotificationDefaultSoundName localNotification.category = category UIApplication.shared.scheduleLocalNotification(localNotification) } }
96ddf33d42ff64bf202b07274541cc60
33.337349
127
0.630877
false
false
false
false
bnickel/StackedDrafts
refs/heads/master
StackedDrafts/StackedDrafts/AllDraftsCollectionViewLayout.swift
mit
1
// // AllDraftsCollectionViewLayout.swift // StackedDrafts // // Created by Brian Nickel on 4/26/16. // Copyright © 2016 Stack Exchange. All rights reserved. // import UIKit func * (a: CATransform3D, b: CATransform3D) -> CATransform3D { return CATransform3DConcat(a, b) } struct PannedItem { let indexPath: IndexPath var translation: CGPoint } class AllDraftsCollectionViewLayout : UICollectionViewLayout { private var allAttributes: [UICollectionViewLayoutAttributes] = [] private var contentSize: CGSize = .zero private var changingBounds = false var pannedItem: PannedItem? { didSet { invalidateLayout() } } @NSCopying var lastPannedItemAttributes: UICollectionViewLayoutAttributes? var deletingPannedItem = false override func prepare() { guard let collectionView = collectionView else { return } precondition(collectionView.numberOfSections == 1) let count = collectionView.numberOfItems(inSection: 0) let size = collectionView.frame.size var topCenter = CGPoint(x: size.width / 2, y: 40) let scale = 1 - 12 / size.height let clampedCount = max(2, min(count, 5)) let verticalGap = (size.height - 80) / CGFloat(clampedCount) let angleInDegrees: CGFloat switch clampedCount { case 2: angleInDegrees = 30 case 3: angleInDegrees = 45 default: angleInDegrees = 61 } var allAttributes: [UICollectionViewLayoutAttributes] = [] for i in 0 ..< count { let indexPath = IndexPath(item: i, section: 0) let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath) let size = i == 0 ? size : UIEdgeInsetsInsetRect(CGRect(origin: .zero, size: size), DraftPresentationController.presentedInsets).size attributes.bounds = CGRect(origin: .zero, size: size) attributes.zIndex = i attributes.transform3D = rotateDown(degrees: angleInDegrees, itemHeight: size.height, scale: scale) attributes.center = topCenter let gapMultiplier: CGFloat if let pannedItem = pannedItem, pannedItem.indexPath.item == i { let delta = pannedItem.translation.x if delta > 0 { attributes.center.x += sqrt(delta) gapMultiplier = 1 } else { attributes.center.x += delta gapMultiplier = 1 - abs(delta) / size.width } lastPannedItemAttributes = attributes } else { gapMultiplier = 1 } allAttributes.append(attributes) topCenter.y += verticalGap * gapMultiplier } self.allAttributes = allAttributes if let lastAttribute = allAttributes.last { contentSize = CGSize(width: size.width, height: lastAttribute.frame.maxY - 40) } } private func rotateDown(degrees angleInDegrees: CGFloat, itemHeight: CGFloat, scale: CGFloat) -> CATransform3D { let angleOfRotation: CGFloat = (-angleInDegrees / 180) * .pi let rotation = CATransform3DMakeRotation(angleOfRotation, 1, 0, 0) let translateDown = CATransform3DMakeTranslation(0, itemHeight / 2, 0) let scale = CATransform3DMakeScale(scale, scale, scale) var perspective = CATransform3DIdentity perspective.m34 = -1/1500 return translateDown * rotation * scale * perspective } override var collectionViewContentSize : CGSize { return contentSize } override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { return allAttributes.filter({ $0.frame.intersects(rect) }) } override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { return allAttributes.indices.contains(indexPath.item) ? allAttributes[indexPath.item] : nil } override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool { return true } override func prepare(forAnimatedBoundsChange oldBounds: CGRect) { changingBounds = true super.prepare(forAnimatedBoundsChange: oldBounds) } override func finalizeAnimatedBoundsChange() { changingBounds = false super.finalizeAnimatedBoundsChange() } override func initialLayoutAttributesForAppearingItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { return allAttributes.indices.contains(indexPath.item) && !changingBounds ? allAttributes[indexPath.item] : nil } override func finalLayoutAttributesForDisappearingItem(at itemIndexPath: IndexPath) -> UICollectionViewLayoutAttributes? { if let lastPannedItemAttributes = lastPannedItemAttributes , deletingPannedItem && lastPannedItemAttributes.indexPath == itemIndexPath, let collectionView = collectionView { lastPannedItemAttributes.center.x = -collectionView.frame.width / 2 return lastPannedItemAttributes } else { return super.finalLayoutAttributesForDisappearingItem(at: itemIndexPath) } } }
ae5b2c959f9679ca80ba1e44d98e74a1
37.404255
181
0.644875
false
false
false
false
Ryan-Vanderhoef/Antlers
refs/heads/master
AppIdea/Frameworks/Bond/Bond/Bond+UITableView.swift
mit
1
// // Bond+UITableView.swift // Bond // // The MIT License (MIT) // // Copyright (c) 2015 Srdan Rasic (@srdanrasic) // // 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 extension NSIndexSet { convenience init(array: [Int]) { let set = NSMutableIndexSet() for index in array { set.addIndex(index) } self.init(indexSet: set) } } @objc class TableViewDynamicArrayDataSource: NSObject, UITableViewDataSource { weak var dynamic: DynamicArray<DynamicArray<UITableViewCell>>? @objc weak var nextDataSource: UITableViewDataSource? init(dynamic: DynamicArray<DynamicArray<UITableViewCell>>) { self.dynamic = dynamic super.init() } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return self.dynamic?.count ?? 0 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.dynamic?[section].count ?? 0 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { return self.dynamic?[indexPath.section][indexPath.item] ?? UITableViewCell() } // Forwards func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if let ds = self.nextDataSource { return ds.tableView?(tableView, titleForHeaderInSection: section) } else { return nil } } func tableView(tableView: UITableView, titleForFooterInSection section: Int) -> String? { if let ds = self.nextDataSource { return ds.tableView?(tableView, titleForFooterInSection: section) } else { return nil } } func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { if let ds = self.nextDataSource { return ds.tableView?(tableView, canEditRowAtIndexPath: indexPath) ?? false } else { return false } } func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { if let ds = self.nextDataSource { return ds.tableView?(tableView, canMoveRowAtIndexPath: indexPath) ?? false } else { return false } } func sectionIndexTitlesForTableView(tableView: UITableView) -> [AnyObject]! { if let ds = self.nextDataSource { return ds.sectionIndexTitlesForTableView?(tableView) ?? [] } else { return [] } } func tableView(tableView: UITableView, sectionForSectionIndexTitle title: String, atIndex index: Int) -> Int { if let ds = self.nextDataSource { return ds.tableView?(tableView, sectionForSectionIndexTitle: title, atIndex: index) ?? index } else { return index } } func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if let ds = self.nextDataSource { ds.tableView?(tableView, commitEditingStyle: editingStyle, forRowAtIndexPath: indexPath) } } func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) { if let ds = self.nextDataSource { ds.tableView?(tableView, moveRowAtIndexPath: sourceIndexPath, toIndexPath: destinationIndexPath) } } } private class UITableViewDataSourceSectionBond<T>: ArrayBond<UITableViewCell> { weak var tableView: UITableView? var section: Int init(tableView: UITableView?, section: Int) { self.tableView = tableView self.section = section super.init() self.didInsertListener = { [unowned self] a, i in if let tableView: UITableView = self.tableView { tableView.beginUpdates() tableView.insertRowsAtIndexPaths(i.map { NSIndexPath(forItem: $0, inSection: self.section) }, withRowAnimation: UITableViewRowAnimation.Automatic) tableView.endUpdates() } } self.didRemoveListener = { [unowned self] a, i in if let tableView = self.tableView { tableView.beginUpdates() tableView.deleteRowsAtIndexPaths(i.map { NSIndexPath(forItem: $0, inSection: self.section) }, withRowAnimation: UITableViewRowAnimation.Automatic) tableView.endUpdates() } } self.didUpdateListener = { [unowned self] a, i in if let tableView = self.tableView { tableView.beginUpdates() tableView.reloadRowsAtIndexPaths(i.map { NSIndexPath(forItem: $0, inSection: self.section) }, withRowAnimation: UITableViewRowAnimation.Automatic) tableView.endUpdates() } } } deinit { self.unbindAll() } } public class UITableViewDataSourceBond<T>: ArrayBond<DynamicArray<UITableViewCell>> { weak var tableView: UITableView? private var dataSource: TableViewDynamicArrayDataSource? private var sectionBonds: [UITableViewDataSourceSectionBond<Void>] = [] public weak var nextDataSource: UITableViewDataSource? { didSet(newValue) { dataSource?.nextDataSource = newValue } } public init(tableView: UITableView) { self.tableView = tableView super.init() self.didInsertListener = { [weak self] array, i in if let s = self { if let tableView: UITableView = self?.tableView { tableView.beginUpdates() tableView.insertSections(NSIndexSet(array: i), withRowAnimation: UITableViewRowAnimation.Automatic) for section in sorted(i, <) { let sectionBond = UITableViewDataSourceSectionBond<Void>(tableView: tableView, section: section) let sectionDynamic = array[section] sectionDynamic.bindTo(sectionBond) s.sectionBonds.insert(sectionBond, atIndex: section) for var idx = section + 1; idx < s.sectionBonds.count; idx++ { s.sectionBonds[idx].section += 1 } } tableView.endUpdates() } } } self.didRemoveListener = { [weak self] array, i in if let s = self { if let tableView = s.tableView { tableView.beginUpdates() tableView.deleteSections(NSIndexSet(array: i), withRowAnimation: UITableViewRowAnimation.Automatic) for section in sorted(i, >) { s.sectionBonds[section].unbindAll() s.sectionBonds.removeAtIndex(section) for var idx = section; idx < s.sectionBonds.count; idx++ { s.sectionBonds[idx].section -= 1 } } tableView.endUpdates() } } } self.didUpdateListener = { [weak self] array, i in if let tableView = self?.tableView { tableView.beginUpdates() tableView.reloadSections(NSIndexSet(array: i), withRowAnimation: UITableViewRowAnimation.Automatic) for section in i { let sectionBond = UITableViewDataSourceSectionBond<Void>(tableView: tableView, section: section) let sectionDynamic = array[section] sectionDynamic.bindTo(sectionBond) self?.sectionBonds[section].unbindAll() self?.sectionBonds[section] = sectionBond } tableView.endUpdates() } } } public func bind(dynamic: DynamicArray<UITableViewCell>) { bind(DynamicArray([dynamic])) } public override func bind(dynamic: Dynamic<Array<DynamicArray<UITableViewCell>>>, fire: Bool, strongly: Bool) { super.bind(dynamic, fire: false, strongly: strongly) if let dynamic = dynamic as? DynamicArray<DynamicArray<UITableViewCell>> { for section in 0..<dynamic.count { let sectionBond = UITableViewDataSourceSectionBond<Void>(tableView: self.tableView, section: section) let sectionDynamic = dynamic[section] sectionDynamic.bindTo(sectionBond) sectionBonds.append(sectionBond) } dataSource = TableViewDynamicArrayDataSource(dynamic: dynamic) dataSource?.nextDataSource = self.nextDataSource tableView?.dataSource = dataSource tableView?.reloadData() } } deinit { self.unbindAll() tableView?.dataSource = nil self.dataSource = nil } } public func ->> <T>(left: DynamicArray<UITableViewCell>, right: UITableViewDataSourceBond<T>) { right.bind(left) }
048faa1b2ce53e64df1910cfd2306697
33.540741
154
0.68057
false
false
false
false
iOSWizards/AwesomeUIMagic
refs/heads/master
Example/Pods/AwesomeUIMagic/AwesomeUIMagic/Classes/Old/DesignableTextField.swift
mit
1
// // DesignableTextField.swift // MV UI Hacks // // Created by Evandro Harrison Hoffmann on 26/07/2016. // Copyright © 2016 It's Day Off. All rights reserved. // import UIKit @IBDesignable open class DesignableTextField: UITextField { // MARK: - TextField @IBInspectable open var insetX: CGFloat = 0 @IBInspectable open var insetY: CGFloat = 0 // placeholder position open override func textRect(forBounds bounds: CGRect) -> CGRect { return bounds.insetBy(dx: insetX , dy: insetY) } // text position open override func editingRect(forBounds bounds: CGRect) -> CGRect { return bounds.insetBy(dx: insetX , dy: insetY) } @IBInspectable open var placeholderColor: UIColor = UIColor.white { didSet { if let placeholder = placeholder { attributedPlaceholder = NSAttributedString(string: placeholder, attributes: [NSAttributedString.Key.foregroundColor: placeholderColor]) } } } }
994712ad7c1972e174780a7f72db4ce3
26.052632
151
0.650778
false
false
false
false
jphacks/TK_08
refs/heads/master
iOS/Demo/PushCatchDemo/iBeaconDemo/AppDelegate.swift
mit
1
// // AppDelegate.swift // iBeaconDemo // // Created by Go Sato on 2015/11/21. // Copyright © 2015年 go. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var test: UIApplication? var notification = UILocalNotification() func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: [UIUserNotificationType.Sound, UIUserNotificationType.Alert], categories: nil)) // アプリに登録されている全ての通知を削除 UIApplication.sharedApplication().cancelAllLocalNotifications() //pushControll(application) return true } func pushControll(){ print(ViewController().isChange) // push設定 // 登録済みのスケジュールをすべてリセット print("push") //application!.cancelAllLocalNotifications() notification.alertAction = "AirMeet" notification.alertBody = "iBeacon範囲に入りました" notification.soundName = UILocalNotificationDefaultSoundName // あとのためにIdを割り振っておく notification.userInfo = ["notifyId": "AirMeet"] UIApplication.sharedApplication().scheduleLocalNotification(notification) } func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) { print("in") var alert = UIAlertView() alert.title = "Message" alert.message = notification.alertBody alert.addButtonWithTitle(notification.alertAction) alert.show() } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
a22980adb2b6dcd0e73b31c853326d8f
39.447059
285
0.709133
false
false
false
false
idomizrachi/Regen
refs/heads/master
regen/ArgumentsParser.swift
mit
1
// // ArgumentsParser.swift // Regen // // Created by Ido Mizrachi on 7/15/16. // import Foundation protocol CanBeInitializedWithString { init?(_ description: String) } extension Int: CanBeInitializedWithString {} extension String: CanBeInitializedWithString {} class ArgumentsParser { let arguments : [String] let operationType: OperationType init(arguments : [String]) { self.arguments = arguments self.operationType = ArgumentsParser.parseOperationType(arguments: arguments) } private static func parseOperationType(arguments: [String]) -> OperationType { let operationTypeKey = parseOperationTypeKey(arguments) switch operationTypeKey { case .localization: guard let parameters = parseLocalizationParameters(arguments) else { return .usage } return .localization(parameters: parameters) case .images: guard let parameters = parseImagesParameters(arguments) else { return .usage } return .images(parameters: parameters) case .version: return .version case .usage: return .usage } } private static func parseOperationTypeKey(_ arguments: [String]) -> OperationType.Keys { guard let firstArgument = arguments.first else { return .usage } return OperationType.Keys(rawValue: firstArgument) ?? .usage } private static func parseLocalizationParameters(_ arguments: [String]) -> Localization.Parameters? { let parser = LocalizationParametersParser(arguments: arguments) return parser.parse() } private static func parseImagesParameters(_ arguments: [String]) -> Images.Parameters? { let parser = ImagesParametersParser(arguments: arguments) return parser.parse() } // private static func parseAssetsFile(arguments: [String]) -> String? { // let assetsFile: String? = tryParse("--assets-file", from: arguments) // return assetsFile // } private static func isVersionOperation(_ arguments: [String]) -> Bool { guard let firstArgument = arguments.first else { return false } return firstArgument.lowercased() == OperationType.Keys.version.rawValue } }
13ab93d588782f10604db2425fd6f53f
29.881579
104
0.649766
false
false
false
false
johndpope/Cerberus
refs/heads/master
Cerberus/Classes/Extensions/String+MD5.swift
mit
1
import Foundation extension String { func md5() -> String! { let str = self.cStringUsingEncoding(NSUTF8StringEncoding) let strLen = CUnsignedInt(self.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)) let digestLen = Int(CC_MD5_DIGEST_LENGTH) let result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLen) CC_MD5(str!, strLen, result) var hash = NSMutableString() for i in 0..<digestLen { hash.appendFormat("%02x", result[i]) } result.destroy() return String(format: hash as String) } }
df1ad81f2e73950b433b69e5aaab8cc3
27.666667
88
0.63228
false
false
false
false
karstengresch/rw_studies
refs/heads/master
swift_playgrounds/EnumPlayground.playground/Contents.swift
unlicense
1
//: Playground - noun: a place where people can play import UIKit enum MicrosoftCEOs: Int { case BillGates = 1 case SteveBallmer case SatyaNadella init() { self = .SatyaNadella } func description() -> String { switch (self) { case .BillGates: return "Bill Gates" case .SteveBallmer: return "Steve Ballmer" case .SatyaNadella: return "Satya Nadella" } } } let currentCEO = MicrosoftCEOs() println(currentCEO.description()) let oFirstCEO = MicrosoftCEOs(rawValue: 1) if let firstCEO = oFirstCEO { println(firstCEO.description()) } else { println("No such value") }
0bc1b152c5267b28e925567941835e23
17
52
0.666667
false
false
false
false
belkevich/DTModelStorage
refs/heads/master
DTModelStorage/Memory/MemoryStorage.swift
mit
1
// // MemoryStorage.swift // DTModelStorageTests // // Created by Denys Telezhkin on 10.07.15. // Copyright (c) 2015 Denys Telezhkin. 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. /// This struct contains error types that can be thrown for various MemoryStorage errors public struct MemoryStorageErrors { /// Errors that can happen when inserting items into memory storage public enum Insertion: ErrorType { case IndexPathTooBig } /// Errors that can happen when replacing item in memory storage public enum Replacement: ErrorType { case ItemNotFound } /// Errors that can happen when removing item from memory storage public enum Removal : ErrorType { case ItemNotFound } } /// This class represents model storage in memory. /// /// `MemoryStorage` stores data models like array of `SectionModel` instances. It has various methods for changing storage contents - add, remove, insert, replace e.t.c. /// - Note: It also notifies it's delegate about underlying changes so that delegate can update interface accordingly /// - SeeAlso: `SectionModel` public class MemoryStorage: BaseStorage, StorageProtocol { /// sections of MemoryStorage public var sections: [Section] = [SectionModel]() /// Retrieve object at index path from `MemoryStorage` /// - Parameter path: NSIndexPath for object /// - Returns: model at indexPath or nil, if item not found public func objectAtIndexPath(path: NSIndexPath) -> Any? { let sectionModel : SectionModel if path.section >= self.sections.count { return nil } else { sectionModel = self.sections[path.section] as! SectionModel if path.item >= sectionModel.numberOfObjects { return nil } } return sectionModel.objects[path.item] } /// Set section header model for MemoryStorage /// - Note: This does not update UI /// - Parameter model: model for section header at index /// - Parameter sectionIndex: index of section for setting header public func setSectionHeaderModel<T>(model: T?, forSectionIndex sectionIndex: Int) { assert(self.supplementaryHeaderKind != nil, "supplementaryHeaderKind property was not set before calling setSectionHeaderModel: forSectionIndex: method") self.sectionAtIndex(sectionIndex).setSupplementaryModel(model, forKind: self.supplementaryHeaderKind!) } /// Set section footer model for MemoryStorage /// - Note: This does not update UI /// - Parameter model: model for section footer at index /// - Parameter sectionIndex: index of section for setting footer public func setSectionFooterModel<T>(model: T?, forSectionIndex sectionIndex: Int) { assert(self.supplementaryFooterKind != nil, "supplementaryFooterKind property was not set before calling setSectionFooterModel: forSectionIndex: method") self.sectionAtIndex(sectionIndex).setSupplementaryModel(model, forKind: self.supplementaryFooterKind!) } /// Set supplementaries for specific kind. Usually it's header or footer kinds. /// - Parameter models: supplementary models for sections /// - Parameter kind: supplementary kind public func setSupplementaries<T>(models : [T], forKind kind: String) { self.startUpdate() if models.count == 0 { for index in 0..<self.sections.count { let section = self.sections[index] as! SectionModel section.setSupplementaryModel(nil, forKind: kind) } return } self.getValidSection(models.count - 1) for index in 0..<models.count { let section = self.sections[index] as! SectionModel section.setSupplementaryModel(models[index], forKind: kind) } self.finishUpdate() } /// Set section header models. /// - Note: `supplementaryHeaderKind` property should be set before calling this method. /// - Parameter models: section header models public func setSectionHeaderModels<T>(models : [T]) { assert(self.supplementaryHeaderKind != nil, "Please set supplementaryHeaderKind property before setting section header models") self.setSupplementaries(models, forKind: self.supplementaryHeaderKind!) } /// Set section footer models. /// - Note: `supplementaryFooterKind` property should be set before calling this method. /// - Parameter models: section footer models public func setSectionFooterModels<T>(models : [T]) { assert(self.supplementaryFooterKind != nil, "Please set supplementaryFooterKind property before setting section header models") self.setSupplementaries(models, forKind: self.supplementaryFooterKind!) } /// Set items for specific section. This will reload UI after updating. /// - Parameter items: items to set for section /// - Parameter forSectionIndex: index of section to update public func setItems<T>(items: [T], forSectionIndex index: Int) { let section = self.sectionAtIndex(index) section.objects.removeAll(keepCapacity: false) for item in items { section.objects.append(item) } self.delegate?.storageNeedsReloading() } /// Add items to section with `toSection` number. /// - Parameter items: items to add /// - Parameter toSection: index of section to add items public func addItems<T>(items: [T], toSection index: Int = 0) { self.startUpdate() let section = self.getValidSection(index) for item in items { let numberOfItems = section.numberOfObjects section.objects.append(item) self.currentUpdate?.insertedRowIndexPaths.append(NSIndexPath(forItem: numberOfItems, inSection: index)) } self.finishUpdate() } /// Add item to section with `toSection` number. /// - Parameter item: item to add /// - Parameter toSection: index of section to add item public func addItem<T>(item: T, toSection index: Int = 0) { self.startUpdate() let section = self.getValidSection(index) let numberOfItems = section.numberOfObjects section.objects.append(item) self.currentUpdate?.insertedRowIndexPaths.append(NSIndexPath(forItem: numberOfItems, inSection: index)) self.finishUpdate() } /// Insert item to indexPath /// - Parameter item: item to insert /// - Parameter toIndexPath: indexPath to insert /// - Throws: if indexPath is too big, will throw MemoryStorageErrors.Insertion.IndexPathTooBig public func insertItem<T>(item: T, toIndexPath indexPath: NSIndexPath) throws { self.startUpdate() let section = self.getValidSection(indexPath.section) guard section.objects.count > indexPath.item else { throw MemoryStorageErrors.Insertion.IndexPathTooBig } section.objects.insert(item, atIndex: indexPath.item) self.currentUpdate?.insertedRowIndexPaths.append(indexPath) self.finishUpdate() } /// Reload item /// - Parameter item: item to reload. public func reloadItem<T:Equatable>(item: T) { self.startUpdate() if let indexPath = self.indexPathForItem(item) { self.currentUpdate?.updatedRowIndexPaths.append(indexPath) } self.finishUpdate() } /// Replace item `itemToReplace` with `replacingItem`. /// - Parameter itemToReplace: item to replace /// - Parameter replacingItem: replacing item /// - Throws: if `itemToReplace` is not found, will throw MemoryStorageErrors.Replacement.ItemNotFound public func replaceItem<T: Equatable, U:Equatable>(itemToReplace: T, replacingItem: U) throws { self.startUpdate() defer { self.finishUpdate() } guard let originalIndexPath = self.indexPathForItem(itemToReplace) else { throw MemoryStorageErrors.Replacement.ItemNotFound } let section = self.getValidSection(originalIndexPath.section) section.objects[originalIndexPath.item] = replacingItem self.currentUpdate?.updatedRowIndexPaths.append(originalIndexPath) } /// Remove item `item`. /// - Parameter item: item to remove /// - Throws: if item is not found, will throw MemoryStorageErrors.Removal.ItemNotFound public func removeItem<T:Equatable>(item: T) throws { self.startUpdate() defer { self.finishUpdate() } guard let indexPath = self.indexPathForItem(item) else { throw MemoryStorageErrors.Removal.ItemNotFound } self.getValidSection(indexPath.section).objects.removeAtIndex(indexPath.item) self.currentUpdate?.deletedRowIndexPaths.append(indexPath) } /// Remove items /// - Parameter items: items to remove /// - Note: Any items that were not found, will be skipped public func removeItems<T:Equatable>(items: [T]) { self.startUpdate() let indexPaths = self.indexPathArrayForItems(items) for item in items { if let indexPath = self.indexPathForItem(item) { self.getValidSection(indexPath.section).objects.removeAtIndex(indexPath.item) } } self.currentUpdate?.deletedRowIndexPaths.appendContentsOf(indexPaths) self.finishUpdate() } /// Remove items at index paths. /// - Parameter indexPaths: indexPaths to remove item from. Any indexPaths that will not be found, will be skipped public func removeItemsAtIndexPaths(indexPaths : [NSIndexPath]) { self.startUpdate() let reverseSortedIndexPaths = self.dynamicType.sortedArrayOfIndexPaths(indexPaths, ascending: false) for indexPath in reverseSortedIndexPaths { if let _ = self.objectAtIndexPath(indexPath) { self.getValidSection(indexPath.section).objects.removeAtIndex(indexPath.item) self.currentUpdate?.deletedRowIndexPaths.append(indexPath) } } self.finishUpdate() } /// Delete sections in indexSet /// - Parameter sections: sections to delete public func deleteSections(sections : NSIndexSet) { self.startUpdate() for var i = sections.lastIndex; i != NSNotFound; i = sections.indexLessThanIndex(i) { self.sections.removeAtIndex(i) } self.currentUpdate?.deletedSectionIndexes.addIndexes(sections) self.finishUpdate() } } // MARK: - Searching in storage extension MemoryStorage { /// Retrieve items in section /// - Parameter section: index of section /// - Returns array of items in section or nil, if section does not exist public func itemsInSection(section: Int) -> [Any]? { if self.sections.count > section { return self.sections[section].objects } return nil } /// Retrieve object at index path from `MemoryStorage` /// - Parameter path: NSIndexPath for object /// - Returns: model at indexPath or nil, if item not found public func itemAtIndexPath(indexPath: NSIndexPath) -> Any? { return self.objectAtIndexPath(indexPath) } /// Find index path of specific item in MemoryStorage /// - Parameter searchableItem: item to find /// - Returns: index path for found item, nil if not found public func indexPathForItem<T: Equatable>(searchableItem : T) -> NSIndexPath? { for sectionIndex in 0..<self.sections.count { let rows = self.sections[sectionIndex].objects for rowIndex in 0..<rows.count { if let item = rows[rowIndex] as? T { if item == searchableItem { return NSIndexPath(forItem: rowIndex, inSection: sectionIndex) } } } } return nil } /// Retrieve section model for specific section. /// - Parameter sectionIndex: index of section /// - Note: if section did not exist prior to calling this, it will be created, and UI updated. public func sectionAtIndex(sectionIndex : Int) -> SectionModel { self.startUpdate() let section = self.getValidSection(sectionIndex) self.finishUpdate() return section } /// Find-or-create section func getValidSection(sectionIndex : Int) -> SectionModel { if sectionIndex < self.sections.count { return self.sections[sectionIndex] as! SectionModel } else { for i in self.sections.count...sectionIndex { self.sections.append(SectionModel()) self.currentUpdate?.insertedSectionIndexes.addIndex(i) } } return self.sections.last as! SectionModel } /// Index path array for items func indexPathArrayForItems<T:Equatable>(items:[T]) -> [NSIndexPath] { var indexPaths = [NSIndexPath]() for index in 0..<items.count { if let indexPath = self.indexPathForItem(items[index]) { indexPaths.append(indexPath) } } return indexPaths } /// Sorted array of index paths - useful for deletion. class func sortedArrayOfIndexPaths(indexPaths: [NSIndexPath], ascending: Bool) -> [NSIndexPath] { let unsorted = NSMutableArray(array: indexPaths) let descriptor = NSSortDescriptor(key: "self", ascending: ascending) return unsorted.sortedArrayUsingDescriptors([descriptor]) as! [NSIndexPath] } } // MARK: - HeaderFooterStorageProtocol extension MemoryStorage :HeaderFooterStorageProtocol { /// Header model for section. /// - Requires: supplementaryHeaderKind to be set prior to calling this method /// - Parameter index: index of section /// - Returns: header model for section, or nil if there are no model public func headerModelForSectionIndex(index: Int) -> Any? { assert(self.supplementaryHeaderKind != nil, "supplementaryHeaderKind property was not set before calling headerModelForSectionIndex: method") return self.supplementaryModelOfKind(self.supplementaryHeaderKind!, sectionIndex: index) } /// Footer model for section. /// - Requires: supplementaryFooterKind to be set prior to calling this method /// - Parameter index: index of section /// - Returns: footer model for section, or nil if there are no model public func footerModelForSectionIndex(index: Int) -> Any? { assert(self.supplementaryFooterKind != nil, "supplementaryFooterKind property was not set before calling footerModelForSectionIndex: method") return self.supplementaryModelOfKind(self.supplementaryFooterKind!, sectionIndex: index) } } // MARK: - SupplementaryStorageProtocol extension MemoryStorage : SupplementaryStorageProtocol { /// Retrieve supplementary model of specific kind for section. /// - Parameter kind: kind of supplementary model /// - Parameter sectionIndex: index of section /// - SeeAlso: `headerModelForSectionIndex` /// - SeeAlso: `footerModelForSectionIndex` public func supplementaryModelOfKind(kind: String, sectionIndex: Int) -> Any? { let sectionModel : SectionModel if sectionIndex >= self.sections.count { return nil } else { sectionModel = self.sections[sectionIndex] as! SectionModel } return sectionModel.supplementaryModelOfKind(kind) } }
368f26d017b72705b845929bfcb8ea56
38.919811
170
0.664165
false
false
false
false
brentsimmons/Evergreen
refs/heads/ios-candidate
Widget/Shared Views/SizeCategories.swift
mit
1
// // SizeCategories.swift // NetNewsWire iOS Widget Extension // // Created by Stuart Breckenridge on 24/12/2020. // Copyright © 2020 Ranchero Software. All rights reserved. // import SwiftUI struct SizeCategories { let largeSizeCategories: [ContentSizeCategory] = [.extraExtraLarge, .extraExtraExtraLarge, .accessibilityMedium, .accessibilityLarge, .accessibilityExtraLarge, .accessibilityExtraExtraLarge, .accessibilityExtraExtraExtraLarge] func isSizeCategoryLarge(category: ContentSizeCategory) -> Bool { largeSizeCategories.filter{ $0 == category }.count == 1 } }
24a46e91cc395a0a63411e3fcabb4014
25.115385
68
0.670103
false
false
false
false
woshishui1243/QRCodeInSwift
refs/heads/master
QRCodeInSwift/Source/QRCode.swift
mit
1
// // QRCode.swift // QRCodeInSwift // // Created by 李禹 on 15/9/13. // Copyright (c) 2015年 dayu. All rights reserved. // import Foundation import AVFoundation public class QRCode: NSObject { public override init() {} // var completion: ((stringValue: String)->())? public func sayHello () { NSLog("hello"); } // // //摄像头输入 // lazy var videoInput: AVCaptureDeviceInput? = { // if let device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo) { // // return AVCaptureDeviceInput.deviceInputWithDevice(device, error: nil) as? AVCaptureDeviceInput; // } // return nil; // }() // // //输出数据 // lazy var output: AVCaptureMetadataOutput = { // return AVCaptureMetadataOutput(); // }(); // // //会话 // lazy var session: AVCaptureSession = { // let session = AVCaptureSession(); // // return session; // // }(); // // //预览图层 // lazy var previewLayer: AVCaptureVideoPreviewLayer? = { // let previewLayer = AVCaptureVideoPreviewLayer.layerWithSession(self.session) as? AVCaptureVideoPreviewLayer; // return previewLayer; // }() // // //二维码边框 // lazy var boundsView: UIView = { // let view = UIView(); // return view; // }() // // // public func startScan(fromView: UIView, previewFrame: CGRect, boarderColor: UIColor, boarderWidth: CGFloat, completion:(qrcode:String)->()) { // if (session.canAddInput(videoInput)) { // session.addInput(videoInput); // } // if (session.canAddOutput(output)) { // session.addOutput(output); // } // //设置扫描数据类型(全部支持) // output.metadataObjectTypes = output.availableMetadataObjectTypes; // println(output.availableMetadataObjectTypes); // // previewLayer?.frame = previewFrame; // fromView.layer.insertSublayer(previewLayer, atIndex: 0); // // fromView.frame = CGRectZero; // fromView.layer.borderWidth = boarderWidth; // fromView.layer.borderColor = boarderColor.CGColor; // fromView.addSubview(boundsView); // // output.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue()); // // session.startRunning(); // // } } extension QRCode: AVCaptureMetadataOutputObjectsDelegate { // public func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) { // if (metadataObjects == nil || metadataObjects.count == 0) { // return; // } // // let readableCodeObj = metadataObjects[0] as? AVMetadataMachineReadableCodeObject; // if (readableCodeObj == nil) { // return // } // if readableCodeObj!.type == AVMetadataObjectTypeQRCode { // let codeObject = previewLayer?.transformedMetadataObjectForMetadataObject(readableCodeObj!); // if codeObject != nil { // boundsView.frame = codeObject!.bounds; // let str = readableCodeObj!.stringValue; // if str == nil { return; } // self.completion?(stringValue: str); // // } // } // } }
d3563ae3b750e08c13c85d0122fd1653
31.970874
171
0.580094
false
false
false
false
apple/swift
refs/heads/main
stdlib/public/core/StringStorageBridge.swift
apache-2.0
2
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// import SwiftShims #if _runtime(_ObjC) internal var _cocoaASCIIEncoding:UInt { 1 } /* NSASCIIStringEncoding */ internal var _cocoaUTF8Encoding:UInt { 4 } /* NSUTF8StringEncoding */ extension String { @available(SwiftStdlib 5.6, *) @_spi(Foundation) public init?(_nativeStorage: AnyObject) { let knownOther = _KnownCocoaString(_nativeStorage) switch knownOther { case .storage: self = _unsafeUncheckedDowncast( _nativeStorage, to: __StringStorage.self ).asString case .shared: self = _unsafeUncheckedDowncast( _nativeStorage, to: __SharedStringStorage.self ).asString default: return nil } } } // ObjC interfaces. extension _AbstractStringStorage { @inline(__always) @_effects(releasenone) internal func _getCharacters( _ buffer: UnsafeMutablePointer<UInt16>, _ aRange: _SwiftNSRange ) { _precondition(aRange.location >= 0 && aRange.length >= 0, "Range out of bounds") _precondition(aRange.location + aRange.length <= Int(count), "Range out of bounds") let range = Range( _uncheckedBounds: (aRange.location, aRange.location+aRange.length)) let str = asString str._copyUTF16CodeUnits( into: UnsafeMutableBufferPointer(start: buffer, count: range.count), range: range) } @inline(__always) @_effects(releasenone) internal func _getCString( _ outputPtr: UnsafeMutablePointer<UInt8>, _ maxLength: Int, _ encoding: UInt ) -> Int8 { switch (encoding, isASCII) { case (_cocoaASCIIEncoding, true), (_cocoaUTF8Encoding, _): guard maxLength >= count + 1 else { return 0 } outputPtr.initialize(from: start, count: count) outputPtr[count] = 0 return 1 default: return _cocoaGetCStringTrampoline(self, outputPtr, maxLength, encoding) } } @inline(__always) @_effects(readonly) internal func _cString(encoding: UInt) -> UnsafePointer<UInt8>? { switch (encoding, isASCII) { case (_cocoaASCIIEncoding, true), (_cocoaUTF8Encoding, _): return start default: return _cocoaCStringUsingEncodingTrampoline(self, encoding) } } @_effects(readonly) internal func _nativeIsEqual<T:_AbstractStringStorage>( _ nativeOther: T ) -> Int8 { if count != nativeOther.count { return 0 } return (start == nativeOther.start || (memcmp(start, nativeOther.start, count) == 0)) ? 1 : 0 } @inline(__always) @_effects(readonly) internal func _isEqual(_ other: AnyObject?) -> Int8 { guard let other = other else { return 0 } if self === other { return 1 } // Handle the case where both strings were bridged from Swift. // We can't use String.== because it doesn't match NSString semantics. let knownOther = _KnownCocoaString(other) switch knownOther { case .storage: return _nativeIsEqual( _unsafeUncheckedDowncast(other, to: __StringStorage.self)) case .shared: return _nativeIsEqual( _unsafeUncheckedDowncast(other, to: __SharedStringStorage.self)) default: // We're allowed to crash, but for compatibility reasons NSCFString allows // non-strings here. if !_isNSString(other) { return 0 } // At this point we've proven that it is a non-Swift NSString let otherUTF16Length = _stdlib_binary_CFStringGetLength(other) // CFString will only give us ASCII bytes here, but that's fine. // We already handled non-ASCII UTF8 strings earlier since they're Swift. if let asciiEqual = withCocoaASCIIPointer(other, work: { (ascii) -> Bool in // UTF16 length == UTF8 length iff ASCII if otherUTF16Length == self.count { return (start == ascii || (memcmp(start, ascii, self.count) == 0)) } return false }) { return asciiEqual ? 1 : 0 } if self.UTF16Length != otherUTF16Length { return 0 } /* The abstract implementation of -isEqualToString: falls back to -compare: immediately, so when we run out of fast options to try, do the same. We can likely be more clever here if need be */ return _cocoaStringCompare(self, other) == 0 ? 1 : 0 } } } extension __StringStorage { @objc(length) final internal var UTF16Length: Int { @_effects(readonly) @inline(__always) get { return asString.utf16.count // UTF16View special-cases ASCII for us. } } @objc final internal var hash: UInt { @_effects(readonly) get { if isASCII { return _cocoaHashASCIIBytes(start, length: count) } return _cocoaHashString(self) } } @objc(characterAtIndex:) @_effects(readonly) final internal func character(at offset: Int) -> UInt16 { let str = asString return str.utf16[str._toUTF16Index(offset)] } @objc(getCharacters:range:) @_effects(releasenone) final internal func getCharacters( _ buffer: UnsafeMutablePointer<UInt16>, range aRange: _SwiftNSRange ) { _getCharacters(buffer, aRange) } @objc(_fastCStringContents:) @_effects(readonly) final internal func _fastCStringContents( _ requiresNulTermination: Int8 ) -> UnsafePointer<CChar>? { if isASCII { return start._asCChar } return nil } @objc(UTF8String) @_effects(readonly) final internal func _utf8String() -> UnsafePointer<UInt8>? { return start } @objc(cStringUsingEncoding:) @_effects(readonly) final internal func cString(encoding: UInt) -> UnsafePointer<UInt8>? { return _cString(encoding: encoding) } @objc(getCString:maxLength:encoding:) @_effects(releasenone) final internal func getCString( _ outputPtr: UnsafeMutablePointer<UInt8>, maxLength: Int, encoding: UInt ) -> Int8 { return _getCString(outputPtr, maxLength, encoding) } @objc final internal var fastestEncoding: UInt { @_effects(readonly) get { if isASCII { return _cocoaASCIIEncoding } return _cocoaUTF8Encoding } } @objc(isEqualToString:) @_effects(readonly) final internal func isEqualToString(to other: AnyObject?) -> Int8 { return _isEqual(other) } @objc(isEqual:) @_effects(readonly) final internal func isEqual(to other: AnyObject?) -> Int8 { return _isEqual(other) } @objc(copyWithZone:) final internal func copy(with zone: _SwiftNSZone?) -> AnyObject { // While __StringStorage instances aren't immutable in general, // mutations may only occur when instances are uniquely referenced. // Therefore, it is safe to return self here; any outstanding Objective-C // reference will make the instance non-unique. return self } } extension __SharedStringStorage { @objc(length) final internal var UTF16Length: Int { @_effects(readonly) get { return asString.utf16.count // UTF16View special-cases ASCII for us. } } @objc final internal var hash: UInt { @_effects(readonly) get { if isASCII { return _cocoaHashASCIIBytes(start, length: count) } return _cocoaHashString(self) } } @objc(characterAtIndex:) @_effects(readonly) final internal func character(at offset: Int) -> UInt16 { let str = asString return str.utf16[str._toUTF16Index(offset)] } @objc(getCharacters:range:) @_effects(releasenone) final internal func getCharacters( _ buffer: UnsafeMutablePointer<UInt16>, range aRange: _SwiftNSRange ) { _getCharacters(buffer, aRange) } @objc final internal var fastestEncoding: UInt { @_effects(readonly) get { if isASCII { return _cocoaASCIIEncoding } return _cocoaUTF8Encoding } } @objc(_fastCStringContents:) @_effects(readonly) final internal func _fastCStringContents( _ requiresNulTermination: Int8 ) -> UnsafePointer<CChar>? { if isASCII { return start._asCChar } return nil } @objc(UTF8String) @_effects(readonly) final internal func _utf8String() -> UnsafePointer<UInt8>? { return start } @objc(cStringUsingEncoding:) @_effects(readonly) final internal func cString(encoding: UInt) -> UnsafePointer<UInt8>? { return _cString(encoding: encoding) } @objc(getCString:maxLength:encoding:) @_effects(releasenone) final internal func getCString( _ outputPtr: UnsafeMutablePointer<UInt8>, maxLength: Int, encoding: UInt ) -> Int8 { return _getCString(outputPtr, maxLength, encoding) } @objc(isEqualToString:) @_effects(readonly) final internal func isEqualToString(to other: AnyObject?) -> Int8 { return _isEqual(other) } @objc(isEqual:) @_effects(readonly) final internal func isEqual(to other: AnyObject?) -> Int8 { return _isEqual(other) } @objc(copyWithZone:) final internal func copy(with zone: _SwiftNSZone?) -> AnyObject { // While __StringStorage instances aren't immutable in general, // mutations may only occur when instances are uniquely referenced. // Therefore, it is safe to return self here; any outstanding Objective-C // reference will make the instance non-unique. return self } } #endif // _runtime(_ObjC)
64d9ec07e1895745b36f62622bf558f2
26.789174
84
0.651117
false
false
false
false
orta/Tinker
refs/heads/master
Tinker/Library/TinkerObject.swift
mit
1
// // TinkerObject.swift // Relate // // Created by Orta on 8/23/14. // Copyright (c) 2014 Orta. All rights reserved. // public typealias voidClosure = () -> Void public class TinkerObject: Equatable { public let name: String public var id: String public var heldObjects: [TinkerObject] = [] private var inlineResponses: Dictionary <String, voidClosure> = [String: voidClosure]() public init(name: String) { self.name = name; self.id = name.lowercaseString } public func respondToCommand(command: String) -> Bool { for object in heldObjects { if object.respondsToCommand(command) { return true } } return false } private func respondsToCommand(command: String) -> Bool { for key in inlineResponses.keys { if key == command { inlineResponses[key]!() return true } } return false } public func addResponseToCommand(to: String, with: voidClosure) { inlineResponses[to] = with } } public func ==(lhs: TinkerObject, rhs: TinkerObject) -> Bool { return lhs.id == rhs.id }
9fc02756cdf3a7146d35a282d0ce1c9d
23.857143
91
0.582102
false
false
false
false
shiwwgis/MyDiaryForEvernote
refs/heads/master
MyDiraryForEvernote/SetBkgroundViewCtrller.swift
mit
1
// // SetBkgroundViewCtrller.swift // DrawingBoard // // Created by shiweiwei on 16/2/22. // Copyright © 2016年 shiww. All rights reserved. // import UIKit class SetBkgroundViewCtrller: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate{ @IBAction func doSelimageFromAlbum(sender: UIButton) { let pickerController = UIImagePickerController(); pickerController.delegate = self; self.presentViewController(pickerController, animated: true, completion: nil); } var mainViewController:ViewController?; private let strImageName=["background1","background2","background3","background4","background5","background6","background7","background8","background9"]; var imageIndex:Int=0; @IBAction func doSetbkCancel(sender: AnyObject) { self.dismissViewControllerAnimated(true, completion: nil);//关闭窗口 } @IBAction func doSetbkOK(sender: AnyObject) { //设置背景 let tempImage=imgBkground.image; if imageIndex<self.strImageName.count { mainViewController!.board.bkImgName=strImageName[imageIndex]; } mainViewController!.setBackgroundColor(tempImage!); self.dismissViewControllerAnimated(true, completion: nil); } @IBAction func doPrevImage(sender: UIButton) { if imageIndex<=0//已是第一个 { imageIndex=strImageName.count-1; } else { imageIndex=imageIndex-1; } let tempImage=UIImage(named: strImageName[imageIndex]); imgBkground.image=tempImage; } @IBAction func doNextImage(sender: UIButton) { if imageIndex>=strImageName.count-1//已是最后一个 { imageIndex=0 } else { imageIndex=imageIndex+1; } let tempImage=UIImage(named: strImageName[imageIndex]); imgBkground.image=tempImage; } @IBOutlet weak var imgBkground: UIImageView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. imageIndex=strImageName.indexOf((mainViewController?.board.bkImgName)!)!; assert(imageIndex<strImageName.count); let tempImage=UIImage(named: strImageName[imageIndex]); imgBkground.image=tempImage; } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ // MARK: UIImagePickerControllerDelegate Methods func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { let image = info[UIImagePickerControllerOriginalImage] as! UIImage self.imgBkground.image=image self.dismissViewControllerAnimated(true, completion: nil) } }
909cc779d548b7ef1ae6216f3586f2c5
30.495327
157
0.650445
false
false
false
false
cuzv/TinyCoordinator
refs/heads/master
Sources/TCDataSource.swift
mit
1
// // TCDataSource.swift // Copyright (c) 2016 Red Rain (https://github.com/cuzv). // // 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 /// Swift does not support generic protocol, so follow code can not compile: /// if self is TCDataSourceable { ..} // See: http://www.captechconsulting.com/blogs/ios-9-tutorial-series-protocol-oriented-programming-with-uikit /// > UIKit is still compiled from Objective-C, and Objective-C has no concept of protocol extendability. /// What this means in practice is that despite our ability to declare extensions on UIKit protocols, /// UIKit objects can't see the methods inside our extensions. /// So we can not extension `TCDataSourceable` implement `UITableViewDataSource`. /// The only thing we can do is provide helper func for `UITableViewDataSource` implement instance. open class TCDataSource: NSObject, UITableViewDataSource, UICollectionViewDataSource { open let tableView: UITableView! open let collectionView: UICollectionView! open var globalDataMetric: TCGlobalDataMetric #if DEBUG deinit { debugPrint("\(#file):\(#line):\(type(of: self)):\(#function)") } #endif fileprivate override init() { fatalError("Use init(tableView:) or init(collectionView:) instead.") } public init(tableView: UITableView) { self.tableView = tableView collectionView = nil globalDataMetric = TCGlobalDataMetric.empty() super.init() checkConforms() registereusableView() } public init(collectionView: UICollectionView) { self.collectionView = collectionView tableView = nil globalDataMetric = TCGlobalDataMetric.empty() super.init() checkConforms() registereusableView() } fileprivate func checkConforms() { guard self is TCDataSourceable else { fatalError("Must conforms protocol `TCDataSourceable`.") } } fileprivate func registereusableView() { guard let subclass = self as? TCDataSourceable else { fatalError("Must conforms protocol `TCDataSourceable`.") } subclass.registerReusableCell() if let subclass = self as? TCTableViewHeaderFooterViewibility { subclass.registerReusableHeaderFooterView() } else if let subclass = self as? TCCollectionSupplementaryViewibility { subclass.registerReusableSupplementaryView() collectionView.tc_registerReusableSupplementaryView(class: TCDefaultSupplementaryView.self, kind: .sectionHeader) collectionView.tc_registerReusableSupplementaryView(class: TCDefaultSupplementaryView.self, kind: .sectionFooter) } } open var delegate: TCDelegate? { if let tableView = tableView { return tableView.delegate as? TCDelegate } return collectionView.delegate as? TCDelegate } open var scrollingToTop: Bool? { return delegate?.scrollingToTop } open var isEmpty: Bool { return globalDataMetric.allData.count == 0 } }
1efd28cf8497bea35270988005b46186
38.698113
125
0.694629
false
false
false
false
mintrocket/MRKit
refs/heads/master
MRKit/Classes/Backend/Core/Response/ResponseData.swift
mit
1
// // ResponseData.swift // RedArmy // // Created by Kirill Kunst on 24/01/2017. // Copyright © 2017 MintRocket LLC. All rights reserved. // import Foundation public class ResponseData: CustomDebugStringConvertible, Equatable { public let statusCode: Int public let data: AnyObject public let request: URLRequest? public let response: URLResponse? /// ResponseData initialisation /// - parameter statusCode: code of response /// - parameter data: processed response data /// - parameter request: URLRequest /// - parameter response: URLResponse public init(statusCode: Int, data: AnyObject, request: URLRequest? = nil, response: URLResponse? = nil) { self.statusCode = statusCode self.data = data self.request = request self.response = response } /// ResponseData initialisation /// - parameter networkResponse: NetworkService response /// - parameter data: processed response data public init(from networkResponse: NetworkService.NetworkResponse, data: AnyObject) { self.statusCode = networkResponse.1 self.data = data self.request = networkResponse.3 self.response = networkResponse.2 } /// A text description of the `Response`. public var description: String { return "Status Code: \(statusCode), Data Length: \(data.count)" } /// A text description of the `Response`. Suitable for debugging. public var debugDescription: String { return description } public static func == (lhs: ResponseData, rhs: ResponseData) -> Bool { return lhs.statusCode == rhs.statusCode && lhs.response == rhs.response } }
e00274ac023461c6534db1fd0e58413f
30.071429
109
0.658046
false
false
false
false
Brightify/ReactantUI
refs/heads/master
Sources/Tokenizer/Util/Parsing/Lexer.swift
mit
1
// // Lexer.swift // ReactantUI // // Created by Tadeas Kriz on 4/29/17. // Copyright © 2017 Brightify. All rights reserved. // import Foundation struct Lexer { enum Token { case identifier(String) case number(value: Float, original: String) case parensOpen case parensClose case assignment case equals(value: Bool, original: String) case colon case semicolon case period case at case other(String) case whitespace(String) case comma case bracketsOpen case bracketsClose case exclamation case argument(String) } } extension Lexer.Token: Equatable { static func ==(lhs: Lexer.Token, rhs: Lexer.Token) -> Bool { switch (lhs, rhs) { case (.identifier(let lhsIdentifier), .identifier(let rhsIdentifier)): return lhsIdentifier == rhsIdentifier case (.number(let lhsNumber, let lhsOriginal), .number(let rhsNumber, let rhsOriginal)): return lhsNumber == rhsNumber && lhsOriginal == rhsOriginal case (.parensOpen, .parensOpen), (.parensClose, .parensClose), (.colon, .colon), (.semicolon, .semicolon), (.period, .period), (.assignment, .assignment), (.at, .at), (.comma, .comma), (.exclamation, .exclamation), (.bracketsOpen, .bracketsOpen), (.bracketsClose, .bracketsClose): return true case (.equals(let lhsBool), .equals(let rhsBool)): return lhsBool == rhsBool case (.other(let lhsOther), .other(let rhsOther)): return lhsOther == rhsOther case (.whitespace(let lhsWhitespace), .whitespace(let rhsWhitespace)): return lhsWhitespace == rhsWhitespace case (.argument(let lhsArgument), .argument(let rhsArgument)): return lhsArgument == rhsArgument default: return false } } } extension Lexer { typealias TokenGenerator = (String) -> Token? static let tokenList: [(String, TokenGenerator)] = [ ("[ \t\n]", { .whitespace($0) }), ("[a-zA-Z][a-zA-Z0-9]*", { .identifier($0) }), ("-?[0-9]+(\\.[0-9]+)?", { original in Float(original).map { Token.number(value: $0, original: original) } }), ("\\(", { _ in .parensOpen }), ("\\)", { _ in .parensClose }), ("\\[", { _ in .bracketsOpen }), ("]", { _ in .bracketsClose }), (":", { _ in .colon }), (";", { _ in .semicolon }), ("\\.", { _ in .period }), ("@", { _ in .at }), ("[!=][=]", { .equals(value: Bool(equalityOperator: $0), original: $0) }), ("=", { _ in .assignment }), (",", { _ in .comma }), ("!", { _ in .exclamation }), ("\\{\\{[a-zA-Z_][a-zA-Z_0-9]*\\}\\}", { argument in .argument(argument.argumentWithoutBrackets)}) ] static func tokenize(input: String, keepWhitespace: Bool = false) -> [Token] { var tokens = [] as [Token] var content = input while content.count > 0 { var matched = false for (pattern, generator) in tokenList { if let match = content.match(regex: pattern) { if let token = generator(match) { if case .whitespace = token, !keepWhitespace { // Ignoring } else { tokens.append(token) } } content = String(content[content.index(content.startIndex, offsetBy: match.count)...]) matched = true break } } if !matched { let index = content.index(after: content.startIndex) tokens.append(.other(String(content[..<index]))) content = String(content[index...]) } } return tokens } } private var expressions = [String: NSRegularExpression]() fileprivate extension String { func match(regex: String) -> String? { let expression: NSRegularExpression if let exists = expressions[regex] { expression = exists } else { expression = try! NSRegularExpression(pattern: "^\(regex)", options: []) expressions[regex] = expression } let range = expression.rangeOfFirstMatch(in: self, options: [], range: NSMakeRange(0, self.utf16.count)) if range.location != NSNotFound { return (self as NSString).substring(with: range) } return nil } } private extension Bool { init(equalityOperator: String) { guard equalityOperator == "==" || equalityOperator == "!=" else { fatalError("Wrong equality operator!") } self = equalityOperator == "==" } } private extension String { var argumentWithoutBrackets: String { var copy = self copy.removeFirst(2) copy.removeLast(2) return copy } }
74fd6e7fcbfc460e347321d2ccf7bc0f
33.401361
120
0.5351
false
false
false
false
kumabook/StickyNotesiOS
refs/heads/master
StickyNotes/SNWebViewController.swift
mit
1
// // HelpWebViewController.swift // StickyNotes // // Created by Hiroki Kumamoto on 2017/07/06. // Copyright © 2017 kumabook. All rights reserved. // import Foundation import UIKit class SNWebViewController: UIViewController { var url: URL! var webView: UIWebView! init(url: URL) { super.init(nibName: nil, bundle: nil) self.url = url } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() navigationItem.title = "Help".localize() navigationItem.backBarButtonItem?.title = "" webView = UIWebView(frame: view.frame) view.addSubview(webView) let req = URLRequest(url: url) webView.loadRequest(req) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func back() { let _ = navigationController?.popViewController(animated: true) } }
8657cf5991d7c1558eab2ff3fa151c5c
22.833333
71
0.627373
false
false
false
false
openHPI/xikolo-ios
refs/heads/dev
iOS/Extensions/Binge+Video.swift
gpl-3.0
1
// // Created for xikolo-ios under GPL-3.0 license. // Copyright © HPI. All rights reserved. // import AVFoundation import Binge import Common extension BingePlayerViewController { func configure(for video: Video) { self.initiallyShowControls = false self.assetTitle = video.item?.title self.assetSubtitle = video.item?.section?.course?.title self.preferredPeakBitRate = video.preferredPeakBitRate() if UserDefaults.standard.playbackRate > 0 { self.playbackRate = UserDefaults.standard.playbackRate } if video.lastPosition > 0 { self.startPosition = video.lastPosition } if let offlinePlayableAsset = self.offlinePlayableAsset(for: video) { self.asset = offlinePlayableAsset } else if let fallbackURL = video.streamURLForDownload ?? video.singleStream?.hdURL ?? video.singleStream?.sdURL { self.asset = AVURLAsset(url: fallbackURL) } else { self.asset = nil } if let posterImageURL = video.item?.section?.course?.imageURL { DispatchQueue.main.async { if let imageData = try? Data(contentsOf: posterImageURL), let image = UIImage(data: imageData) { self.posterImage = image } } } } private func offlinePlayableAsset(for video: Video) -> AVURLAsset? { guard let localFileLocation = StreamPersistenceManager.shared.localFileLocation(for: video) else { return nil } let asset = AVURLAsset(url: localFileLocation) return asset.assetCache?.isPlayableOffline == true ? asset : nil } } extension Video { func preferredPeakBitRate() -> Double? { guard StreamPersistenceManager.shared.localFileLocation(for: self) == nil else { return nil } let videoQuality = ReachabilityHelper.connection == .wifi ? UserDefaults.standard.videoQualityOnWifi : UserDefaults.standard.videoQualityOnCellular return Double(videoQuality.rawValue) } }
b12912146d9ee1a3e5ba019a339d82cc
33.813559
155
0.659688
false
false
false
false
liuxianghong/GreenBaby
refs/heads/master
工程/greenbaby/greenbaby/ViewController/MainViewController.swift
lgpl-3.0
1
// // MainViewController.swift // greenbaby // // Created by 刘向宏 on 15/12/3. // Copyright © 2015年 刘向宏. All rights reserved. // import UIKit class MainViewController: UITabBarController { var first : Bool = true override func viewDidLoad() { super.viewDidLoad() UINavigationBar.appearance().tintColor = UIColor.whiteColor() UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName : UIColor.whiteColor()] UIGraphicsBeginImageContext(CGSizeMake(1, 1)); let context = UIGraphicsGetCurrentContext(); CGContextSetFillColorWithColor(context,UIColor.mainGreenColor().CGColor); CGContextFillRect(context, CGRectMake(0, 0, 1, 1)); let img = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); UINavigationBar.appearance().setBackgroundImage(img, forBarPosition: .Any, barMetrics: .Default) UINavigationBar.appearance().shadowImage = UIImage() UINavigationBar.appearance().translucent = false UINavigationBar.appearance().backItem?.title = "返回" self.tabBar.tintColor = UIColor.mainGreenColor() for item in self.tabBar.items!{ item.setTitleTextAttributes( [NSForegroundColorAttributeName : UIColor.mainGreenColor()] , forState: .Selected) } UserInfo.CurrentUser().userId = nil // for _ in 1...10{ // let uuid = NSUUID() // print(uuid.UUIDString) // } // let byte : [UInt8] = [0xff, 0xd8]; // let data = NSData(bytes: byte, length: 2) // print(data) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func preferredStatusBarStyle() -> UIStatusBarStyle { return .LightContent } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) if first{ //UserInfo.CurrentUser().userId = 19 self.performSegueWithIdentifier("loginIdentifier", sender: nil) first = false } } // 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. if segue.identifier == "shareIdentifier"{ let vc = segue.destinationViewController as! ShareViewController vc.shareImage = sender as! UIImage } else if segue.identifier == "detailSeeIdentifier"{ let vc = segue.destinationViewController as! TrainingTipsViewController vc.type = sender as! Int } } }
f97f60c3fd70a79f716791f0002cbbcd
35.822785
123
0.653489
false
false
false
false
zakkhoyt/ColorPicKit
refs/heads/1.2.3
ColorPicKit/Classes/SliderGroup.swift
mit
1
// // SliderGroup.swift // ColorPicKitExample // // Created by Zakk Hoyt on 10/26/16. // Copyright © 2016 Zakk Hoyt. All rights reserved. // import UIKit @IBDesignable public class SliderGroup: UIControl, SliderControlGroup, Colorable { // MARK: Variables fileprivate var _realtimeMix: Bool = false @IBInspectable public var realtimeMix: Bool { get { return _realtimeMix } set { _realtimeMix = newValue commonInit() updateSliderColors() } } fileprivate var _showAlphaSlider: Bool = true @IBInspectable public var showAlphaSlider: Bool { get { return _showAlphaSlider } set { _showAlphaSlider = newValue for slider in sliders { slider.removeFromSuperview() } sliders.removeAll() commonInit() } } @IBInspectable public var color: UIColor { get { return colorFromSliders() } set { slidersFrom(color: newValue) } } private var _barHeight: CGFloat = 10 @IBInspectable public var barHeight: CGFloat { get { return _barHeight } set { if _barHeight != newValue { _barHeight = newValue for slider in sliders { slider.barHeight = newValue } } } } private var _knobSize: CGSize = CGSize(width: 30, height: 30) @IBInspectable public var knobSize: CGSize { get { return _knobSize } set { if _knobSize != newValue { _knobSize = newValue for slider in sliders { slider.knobSize = newValue } } } } private var _colorKnob: Bool = true @IBInspectable public var colorKnob: Bool { get { return _colorKnob } set { if _colorKnob != newValue { _colorKnob = newValue for slider in sliders { slider.colorKnob = newValue } } } } private var _borderColor: UIColor = .lightGray @IBInspectable public var borderColor: UIColor{ get { return _borderColor } set { if _borderColor != newValue { _borderColor = newValue for slider in sliders { slider.borderColor = newValue } } } } private var _borderWidth: CGFloat = 0.5 @IBInspectable public var borderWidth: CGFloat{ get { return _borderWidth } set { if _borderWidth != newValue { _borderWidth = newValue for slider in sliders { slider.borderWidth = newValue } } } } private var _roundedCornders: Bool = true @IBInspectable public var roundedCorners: Bool { get { return _roundedCornders } set { if _roundedCornders != newValue { _roundedCornders = newValue for slider in sliders { slider.roundedCorners = newValue } } } } func colorFromSliders() -> UIColor { assert(false, "child must implement"); return UIColor.clear } func slidersFrom(color: UIColor) { assert(false, "child must implement"); } let spacing: CGFloat = 4 let sliderHeight: CGFloat = 40 var sliders: [Slider] = [Slider]() // MARK: Init required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } public override init(frame: CGRect) { super.init(frame: frame) commonInit() } private func commonInit() { backgroundColor = UIColor.clear for slider in sliders { slider.removeFromSuperview() } sliders.removeAll() configureSliders() for slider in sliders { slider.roundedCorners = roundedCorners slider.borderColor = borderColor slider.borderWidth = borderWidth slider.barHeight = barHeight slider.knobSize = knobSize slider.colorKnob = colorKnob slider.addTarget(self, action: #selector(sliderValueChanged), for: .valueChanged) slider.addTarget(self, action: #selector(sliderTouchDown), for: .touchDown) slider.addTarget(self, action: #selector(sliderTouchUpInside), for: .touchUpInside) } } func configureSliders() { assert(false, "child must implement"); } override open func layoutSubviews() { super.layoutSubviews() for (index, slider) in sliders.enumerated() { let x = CGFloat(0) let y = (CGFloat(index) * spacing) + (CGFloat(index) * sliderHeight) let w = CGFloat(bounds.width) let h = CGFloat(sliderHeight) let frame = CGRect(x: x, y: y, width: w, height: h) slider.frame = frame } } // MARK: Private methods func touchDown() { self.sendActions(for: .touchDown) } func touchUpInside() { self.sendActions(for: .touchUpInside) } func valueChanged() { self.sendActions(for: .valueChanged) } @objc func sliderValueChanged(sender: GradientSlider) { valueChanged() updateSliderColors() } @objc func sliderTouchDown(sender: GradientSlider) { valueChanged() touchDown() updateSliderColors() } @objc func sliderTouchUpInside(sender: GradientSlider) { valueChanged() touchUpInside() updateSliderColors() } func updateSliderColors() { print("Child class CAN implement (not required)") } }
cd34d806d60c703ba7eeb0f3e1bd473d
23.041509
95
0.507613
false
false
false
false
byu-oit/ios-byuSuite
refs/heads/dev
byuSuite/Apps/LockerRental/controller/LockerRentalMyLockersViewController.swift
apache-2.0
1
// // LockerRentalMyLockersViewController.swift // byuSuite // // Created by Erik Brady on 7/19/17. // Copyright © 2017 Brigham Young University. All rights reserved. // protocol LockerRentalDelegate { func loadLockers() } class LockerRentalMyLockersViewController: ByuViewController2, UITableViewDataSource, LockerRentalDelegate { //MARK: Outlets @IBOutlet private weak var tableView: UITableView! @IBOutlet private weak var button: UIBarButtonItem! //MARK: Properties private var agreements = [LockerRentalAgreement]() private var loadedLockerCount: Int = 0 override func viewDidLoad() { super.viewDidLoad() loadLockers() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) tableView.deselectSelectedRow() } //MARK: Navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "myLockerDetail", let vc = segue.destination as? LockerRentalMyLockersDetailViewController, let sender = sender as? UITableViewCell, let indexPath = tableView.indexPath(for: sender) { vc.agreement = agreements[indexPath.row] vc.delegate = self } else if segue.identifier == "toBrowseLockers", let vc = segue.destination as? LockerRentalBuildingsViewController { vc.delegate = self } } //MARK: UITableViewDelegate/DataSource Methods func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if loadedLockerCount > 0 { return "My Lockers" } return nil } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return loadedLockerCount } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(for: indexPath) let agreement = agreements[indexPath.row] if let building = agreement.locker?.building, let floor = agreement.locker?.floor, let number = agreement.locker?.displayedLockerNumber { cell.textLabel?.text = "\(building) Floor \(floor) - \(number)" } cell.detailTextLabel?.text = "Expires on: \(agreement.expirationDateString())" return cell } //MARK: IBAction Methods @IBAction func browseAvailableLockersClicked(_ sender: Any) { if agreements.count >= 3 { super.displayAlert(error: nil, title: "Unable to Browse Lockers", message: "You have reached the maximum number of lockers you can rent.", alertHandler: nil) } else { self.performSegue(withIdentifier: "toBrowseLockers", sender: sender) } } //MARK: LockerRental Delegate Methods func loadLockers() { //loadedLockerCount tracks the number of lockers loaded. It must be reset here because this method can be called later in the feature to reload lockers. loadedLockerCount = 0 //Remove current rows from tableView tableView.reloadData() spinner?.startAnimating() LockerRentalClient.getAgreements { (agreements, error) in if let agreements = agreements { self.agreements = agreements if self.agreements.count == 0 { self.stopSpinnerIfReady() self.tableView.tableFooterView?.isHidden = false } else { //Reset footer in the case that they just rented a first locker self.tableView.tableFooterView?.isHidden = true //Sort locker agreements by Expiration Date self.agreements.sort() //Load lockers for each agreement for agreement in self.agreements { if let lockerId = agreement.lockerId { LockerRentalClient.getLocker(lockerId: lockerId, callback: { (locker, error) in if let locker = locker { agreement.locker = locker self.loadedLockerCount += 1 self.tableView.reloadData() self.stopSpinnerIfReady() } else { self.spinner?.stopAnimating() super.displayAlert(error: error) } }) } } } } else { super.displayAlert(error: error) } } } //MARK: Custom Methods private func stopSpinnerIfReady() { if agreements.count == loadedLockerCount { spinner?.stopAnimating() button.isEnabled = true } } }
b591c011e879a59b72971cf42de91bcc
36.058394
169
0.575734
false
false
false
false
Fenrikur/ef-app_ios
refs/heads/master
Eurofurence/Modules/Login/LoginModuleBuilder.swift
mit
1
import EurofurenceModel class LoginModuleBuilder { private var sceneFactory: LoginSceneFactory private let authenticationService: AuthenticationService private var alertRouter: AlertRouter init(authenticationService: AuthenticationService) { self.authenticationService = authenticationService sceneFactory = LoginViewControllerFactory() alertRouter = WindowAlertRouter.shared } func with(_ sceneFactory: LoginSceneFactory) -> LoginModuleBuilder { self.sceneFactory = sceneFactory return self } func with(_ alertRouter: AlertRouter) -> LoginModuleBuilder { self.alertRouter = alertRouter return self } func build() -> LoginModuleProviding { return LoginModule(sceneFactory: sceneFactory, authenticationService: authenticationService, alertRouter: alertRouter) } }
5d443d3942260bad1f482ee7d3c53f75
29.064516
72
0.689914
false
false
false
false
EdenShapiro/tip-calculator-with-yelp-review
refs/heads/master
SuperCoolTipCalculator/Business.swift
mit
1
// // Business.swift // SuperCoolTipCalculator // // Created by Eden on 3/22/17. // Copyright © 2017 Eden Shapiro. All rights reserved. // import UIKit class Business: NSObject { let name: String? let address: String? let imageURL: URL? let categories: String? let distance: String? let ratingImageURL: URL? let reviewCount: NSNumber? let id: String? init(dictionary: NSDictionary) { name = dictionary["name"] as? String let imageURLString = dictionary["image_url"] as? String if imageURLString != nil { imageURL = URL(string: imageURLString!)! } else { imageURL = nil } let location = dictionary["location"] as? NSDictionary var address = "" if location != nil { let addressArray = location!["address"] as? NSArray if addressArray != nil && addressArray!.count > 0 { address = addressArray![0] as! String } let neighborhoods = location!["neighborhoods"] as? NSArray if neighborhoods != nil && neighborhoods!.count > 0 { if !address.isEmpty { address += ", " } address += neighborhoods![0] as! String } } self.address = address let categoriesArray = dictionary["categories"] as? [[String]] if categoriesArray != nil { var categoryNames = [String]() for category in categoriesArray! { let categoryName = category[0] categoryNames.append(categoryName) } categories = categoryNames.joined(separator: ", ") } else { categories = nil } let distanceMeters = dictionary["distance"] as? NSNumber if distanceMeters != nil { let milesPerMeter = 0.000621371 distance = String(format: "%.2f mi", milesPerMeter * distanceMeters!.doubleValue) } else { distance = nil } let ratingImageURLString = dictionary["rating_img_url_large"] as? String if ratingImageURLString != nil { ratingImageURL = URL(string: ratingImageURLString!) } else { ratingImageURL = nil } reviewCount = dictionary["review_count"] as? NSNumber id = dictionary["id"] as? String } class func businesses(_ array: [NSDictionary]) -> [Business] { var businesses = [Business]() for dictionary in array { let business = Business(dictionary: dictionary) businesses.append(business) } return businesses } class func searchWithTerm(_ term: String, completion: @escaping ([Business]?, Error?) -> Void) { _ = YelpClient.sharedInstance.searchWithTerm(term, completion: completion) } class func searchWithTerm(_ term: String, userLocation: (Double, Double)?, sort: YelpSortMode?, categories: [String]?, deals: Bool?, completion: @escaping ([Business]?, Error?) -> Void) -> Void { _ = YelpClient.sharedInstance.searchWithTerm(term, userLocation: userLocation, sort: sort, categories: categories, deals: deals, completion: completion) } }
415ac1c64583465239e84bc4513751d6
32.108911
199
0.568182
false
false
false
false
devxoul/Umbrella
refs/heads/master
Tests/UmbrellaAppboyTests/AppboyProviderTests.swift
mit
1
import XCTest import Umbrella import UmbrellaAppboy import Appboy_iOS_SDK final class AppboyProviderTests: XCTestCase { private enum Swizzle { static let UNUserNotificationCenter_currentNotificationCenter: Void = { guard #available(iOS 10.0, *) else { return } let cls = UNUserNotificationCenter.self let oldSelector = NSSelectorFromString("currentNotificationCenter") let newSelector = #selector(UNUserNotificationCenter.swizzled_currentNotificationCenter) guard let oldMethod = class_getClassMethod(cls, oldSelector) else { return } guard let newMethod = class_getClassMethod(cls, newSelector) else { return } method_exchangeImplementations(oldMethod, newMethod) }() } override func setUp() { super.setUp() Swizzle.UNUserNotificationCenter_currentNotificationCenter Appboy.start(withApiKey: "TEST_TOKEN", in: UIApplication.shared, withLaunchOptions: [:], withAppboyOptions: [:]) } func testAppboyProvider() { let provider = AppboyProvider() XCTAssertTrue(provider.cls === Appboy.self) XCTAssertNotNil(provider.instance) XCTAssertTrue(provider.instance === Appboy.sharedInstance()) XCTAssertEqual(provider.selector, #selector(Appboy.logCustomEvent(_:withProperties:))) XCTAssertTrue(provider.responds) } } @available(iOS 10.0, *) extension UNUserNotificationCenter { private static let currentUserNotificationCenter = UNUserNotificationCenter.perform(NSSelectorFromString("alloc"))?.takeUnretainedValue() as! UNUserNotificationCenter @objc static func swizzled_currentNotificationCenter() -> UNUserNotificationCenter { return self.currentUserNotificationCenter } }
7afd81b3ff43a2f52927f89e738b17b9
38.97619
168
0.765932
false
true
false
false
society2012/PGDBK
refs/heads/master
PGDBK/PGDBK/Code/Home/View/NoteTableViewCell.swift
mit
1
// // NoteTableViewCell.swift // PGDBK // // Created by hupeng on 2017/7/6. // Copyright © 2017年 m.zintao. All rights reserved. // import UIKit import Kingfisher class NoteTableViewCell: UITableViewCell { @IBOutlet var noteImageView: UIImageView! @IBOutlet var timeLabel: UILabel! @IBOutlet var desLabel: UILabel! @IBOutlet var titleLabel: UILabel! var newModel:NoteModel?{ didSet { self.titleLabel.text = newModel?.title self.desLabel.text = newModel?.desc let time = Int((newModel?.time)!) let timeStamp:TimeInterval = TimeInterval(time!) let date = Date(timeIntervalSince1970: timeStamp) let dformatter = DateFormatter() dformatter.dateFormat = "MM-dd HH:mm" let timeOutput = dformatter.string(from: date) self.timeLabel.text = timeOutput guard let pic = newModel?.pic else{return} let str = SERVER_IP + pic let url = URL(string: str) self.noteImageView.kf.setImage(with: url!) } } override func awakeFromNib() { super.awakeFromNib() // Initialization code } }
5ccfcd32e9452e65df250a919559aa64
24.377358
61
0.545725
false
false
false
false
joshuamcshane/nessie-ios-sdk-swift2
refs/heads/test
NessieTestProj/NSEFunctionalTests.swift
mit
1
// // NSEFunctionalTests.swift // Nessie-iOS-Wrapper // // Created by Mecklenburg, William on 5/19/15. // Copyright (c) 2015 Nessie. All rights reserved. // import Foundation import NessieFmwk class AccountTests { let client = NSEClient.sharedInstance init() { client.setKey("2c54c85dc28e084930c0e06703711a14") testAccountGets() testAccountPost() } func testAccountGets() { //Test with my key let getAllRequest = AccountRequest(block: {(builder) in builder.requestType = HTTPType.GET }) getAllRequest?.send({(result) in var accounts = result.getAllAccounts() print("Accounts created:\(accounts)\n", terminator: "") let accountToGet = accounts![0] let accountToUpdateThenDelete = accounts![1] self.testAccountGetOne(accountToGet.accountId) self.testAccountPutDelete(accountToUpdateThenDelete.accountId) }) } func testAccountGetOne(identifier:String) { let getOneRequest = AccountRequest(block: {(builder) in builder.requestType = HTTPType.GET builder.accountId = identifier }) getOneRequest?.send({(result) in let account = result.getAccount() print("Account fetched:\(account)\n", terminator: "") }) } func testAccountPost() { let accountPostRequest = AccountRequest(block: {(builder:AccountRequestBuilder) in builder.requestType = HTTPType.POST builder.accountType = AccountType.SAVINGS builder.balance = 100 builder.nickname = "Madelyn's Savings Account" builder.rewards = 20000 builder.customerId = "55dd3baef8d87732af4687af" }) accountPostRequest?.send({(result:AccountResult) in //Should not be any result, should NSLog a message in console saying it was successful }) } func testAccountPutDelete(identifier:String) { let accountPutRequest = AccountRequest(block: {(builder:AccountRequestBuilder) in builder.requestType = HTTPType.PUT builder.accountId = identifier builder.nickname = "Victor" }) accountPutRequest?.send({(result:AccountResult) in //should not be any result let accountDeleteRequest = AccountRequest(block: {(builder:AccountRequestBuilder) in builder.requestType = HTTPType.DELETE builder.accountId = identifier }) accountDeleteRequest?.send({(result:AccountResult) in //no result }) }) } } class ATMTests { let client = NSEClient.sharedInstance init() { client.setKey("2c54c85dc28e084930c0e06703711a14") testATMGetAll() } func testATMGetAll() { let atmGetAllRequest = ATMRequest(block: {(builder:ATMRequestBuilder) in builder.requestType = HTTPType.GET builder.latitude = 38.9283 builder.longitude = -77.1753 builder.radius = "1" }) atmGetAllRequest?.send({(result:ATMResult) in var atms = result.getAllATMs() print("ATMs fetched:\(atms)\n", terminator: "") let atmToGetID = atms![0].atmId let getOneATMRequest = ATMRequest(block: {(builder:ATMRequestBuilder) in builder.requestType = HTTPType.GET builder.atmId = atmToGetID }) getOneATMRequest?.send({(result:ATMResult) in let atm = result.getATM() print("ATM fetched:\(atm)\n", terminator: "") }) }) } } class BillTests { let client = NSEClient.sharedInstance init() { client.setKey("2c54c85dc28e084930c0e06703711a14") testGetAllBills() } var accountToAccess:Account! var accountToPay:Account! func testGetAllBills() { let getAllRequest = AccountRequest(block: {(builder:AccountRequestBuilder) in builder.requestType = HTTPType.GET }) getAllRequest?.send({(result:AccountResult) in var accounts = result.getAllAccounts() self.accountToAccess = accounts![2] self.accountToPay = accounts![1] self.testPostBill() /********************* Get bills for customer **********************/ BillRequest(block: {(builder:BillRequestBuilder) in builder.requestType = HTTPType.GET builder.customerId = self.accountToAccess.customerId })?.send(completion: {(result:BillResult) in let bills = result.getAllBills() print(bills) }) //create and then send shortcut BillRequest(block: {(builder:BillRequestBuilder) in builder.requestType = HTTPType.GET builder.accountId = self.accountToAccess.accountId })?.send(completion: {(result:BillResult) in var bills = result.getAllBills() let billToGet = bills![0] let billToPutDelete = bills![0] /********************* Get bill by ID **********************/ self.testGetOneBill(billToGet) /********************* Put bill **********************/ self.testPutBill(billToPutDelete) }) }) } func testGetOneBill(bill:Bill) { BillRequest(block: {(builder:BillRequestBuilder) in builder.requestType = HTTPType.GET builder.billId = bill.billId })?.send(completion: {(result:BillResult) in let billresult = result.getBill() print(billresult) }) } func testPostBill() { BillRequest(block: {(builder:BillRequestBuilder) in builder.requestType = HTTPType.POST builder.status = BillStatus.RECURRING builder.accountId = self.accountToAccess.accountId builder.recurringDate = 15 builder.paymentAmount = 10 builder.payee = self.accountToPay.accountId builder.nickname = "bill" })?.send(completion: {(result:BillResult) in }) } func testPutBill(bill:Bill) { BillRequest(block: {(builder:BillRequestBuilder) in builder.billId = bill.billId builder.nickname = "newbill" builder.requestType = HTTPType.PUT })?.send(completion: {(result:BillResult) in self.testDeleteBill(bill) }) } func testDeleteBill(bill:Bill) { BillRequest(block: {(builder:BillRequestBuilder) in builder.billId = bill.billId builder.requestType = HTTPType.DELETE })?.send(completion: {(result) in }) } } class BranchTests { let client = NSEClient.sharedInstance init() { client.setKey("2c54c85dc28e084930c0e06703711a14") testBranchGetAll() } func testBranchGetAll() { /********************* Get branches **********************/ BranchRequest(block: {(builder:BranchRequestBuilder) in builder.requestType = HTTPType.GET })?.send({(result:BranchResult) in var branches = result.getAllBranches() var branchToGetID = branches![0].branchId /********************* Get 1 branch **********************/ BranchRequest(block: {(builder:BranchRequestBuilder) in builder.requestType = HTTPType.GET builder.branchId = branchToGetID })?.send({(result:BranchResult) in var branch = result.getBranch() }) }) } } class CustomerTests { let client = NSEClient.sharedInstance init() { client.setKey("2c54c85dc28e084930c0e06703711a14") testGetAllCustomers() } func testGetAllCustomers() { // self.testPostCustomer() /********************* Get all customers **********************/ CustomerRequest(block: {(builder:CustomerRequestBuilder) in builder.requestType = HTTPType.GET })?.send({(result:CustomerResult) in var customers = result.getAllCustomers() print("Customers fetched:\(customers)\n", terminator: "") var customerToGet = customers![3] var customerToGetFromAccount = customers![customers!.count-1] /********************* Get 1 customer **********************/ self.testGetOneCustomer(customerToGet) /********************* Get customer from account **********************/ self.testGetCustomerFromAccount(customerToGetFromAccount) /********************* Get accounts from customer **********************/ self.testGetAccountsFromCustomer(customerToGetFromAccount) /********************* Get put customer **********************/ self.testUpdateCustomer(customerToGet) }) } func testGetOneCustomer(customer:Customer) { CustomerRequest(block: {(builder:CustomerRequestBuilder) in builder.requestType = HTTPType.GET builder.customerId = customer.customerId })?.send({(result:CustomerResult) in var customer = result.getCustomer() print("Customer fetched:\(customer)\n", terminator: "") }) } func testGetCustomerFromAccount(customer:Customer) { CustomerRequest(block: {(builder:CustomerRequestBuilder) in builder.requestType = HTTPType.GET builder.accountId = customer.accountIds?[0] })?.send({(result:CustomerResult) in var customer = result.getCustomer() print("Customer from account fetched:\(customer)\n", terminator: "") }) } func testGetAccountsFromCustomer(customer:Customer) { AccountRequest(block: {(builder:AccountRequestBuilder) in builder.requestType = HTTPType.GET builder.customerId = customer.customerId })?.send({(result:AccountResult) in var accounts = result.getAllAccounts() print("Accounts from customer fetched:\(accounts)\n", terminator: "") }) } func testUpdateCustomer(customer:Customer) { CustomerRequest(block: {(builder:CustomerRequestBuilder) in builder.requestType = HTTPType.PUT builder.customerId = customer.customerId builder.address = Address(streetName: "streetname", streetNumber: "123", city: "city", state: "DC", zipCode: "12345") })?.send({(result) in //no result }) } func testPostCustomer() { CustomerRequest(block: {(builder:CustomerRequestBuilder) in builder.requestType = HTTPType.POST builder.firstName = "Elliot" builder.lastName = "Anderson" builder.address = Address(streetName: "streetname", streetNumber: "123", city: "city", state: "DC", zipCode: "12345") })?.send({(result) in //no result }) } } class DepositTests { let client = NSEClient.sharedInstance init() { client.setKey("2c54c85dc28e084930c0e06703711a14") testGetAllDeposits() } var accountToAccess:Account! func testGetAllDeposits() { //get an account var getAllRequest = AccountRequest(block: {(builder:AccountRequestBuilder) in builder.requestType = HTTPType.GET }) getAllRequest?.send({(result:AccountResult) in var accounts = result.getAllAccounts() self.accountToAccess = accounts![0] self.testPostDeposit() //test get all }) } func testGetOneDeposit(deposit:Transaction) { DepositRequest(block: {(builder:DepositRequestBuilder) in builder.requestType = HTTPType.GET builder.depositId = deposit.transactionId })?.send(completion: {(result:DepositResult) in var depositResult = result.getDeposit() print(depositResult, terminator: "") }) } func testPostDeposit() { DepositRequest(block: {(builder:DepositRequestBuilder) in builder.requestType = HTTPType.POST builder.amount = 10 builder.depositMedium = TransactionMedium.BALANCE builder.description = "test" builder.accountId = self.accountToAccess.accountId })?.send(completion: {(result) in DepositRequest(block: {(builder:DepositRequestBuilder) in builder.requestType = HTTPType.GET builder.accountId = self.accountToAccess.accountId })?.send(completion: {(result:DepositResult) in var deposits = result.getAllDeposits() if deposits!.count > 0 { let depositToGet = deposits![deposits!.count-1] var depositToDelete:Transaction? = nil; for deposit in deposits! { if deposit.status == "pending" { depositToDelete = deposit // self.testDeleteDeposit(depositToDelete) } } // self.testGetOneDeposit(depositToGet) self.testPutDeposit(depositToDelete) } }) }) } func testPutDeposit(deposit:Transaction?) { if (deposit == nil) { return } DepositRequest(block: {(builder:DepositRequestBuilder) in builder.depositId = deposit!.transactionId print(deposit!.status) builder.requestType = HTTPType.PUT builder.amount = 4300 builder.depositMedium = TransactionMedium.REWARDS builder.description = "updated" })?.send(completion: {(result:DepositResult) in // self.testDeleteDeposit(deposit!) }) } func testDeleteDeposit(deposit:Transaction?) { DepositRequest(block: {(builder:DepositRequestBuilder) in builder.depositId = deposit!.transactionId print(deposit!.status) builder.requestType = HTTPType.DELETE builder.accountId = self.accountToAccess.accountId })?.send(completion: {(result) in }) } } class PurchaseTests { let client = NSEClient.sharedInstance init() { client.setKey("2c54c85dc28e084930c0e06703711a14") testGetAllPurchases() } var accountToAccess:Account! func testGetAllPurchases() { //get an account var getAllRequest = AccountRequest(block: {(builder:AccountRequestBuilder) in builder.requestType = HTTPType.GET }) getAllRequest?.send({(result:AccountResult) in var accounts = result.getAllAccounts() self.accountToAccess = accounts![0] self.testPostPurchase() //test get all }) } func testGetOnePurchase(purchase:Transaction) { PurchaseRequest(block: {(builder:PurchaseRequestBuilder) in builder.requestType = HTTPType.GET builder.purchaseId = purchase.transactionId })?.send(completion: {(result:PurchaseResult) in var purchaseResult = result.getPurchase() print(purchaseResult, terminator: "") }) } func testPostPurchase() { PurchaseRequest(block: {(builder:PurchaseRequestBuilder) in builder.requestType = HTTPType.POST builder.amount = 10 builder.purchaseMedium = TransactionMedium.BALANCE builder.description = "test" builder.accountId = self.accountToAccess.accountId builder.merchantId = "55e9b7957bf47e14009404f0" })?.send(completion: {(result) in PurchaseRequest(block: {(builder:PurchaseRequestBuilder) in builder.requestType = HTTPType.GET builder.accountId = self.accountToAccess.accountId })?.send(completion: {(result:PurchaseResult) in var purchases = result.getAllPurchases() if purchases!.count > 0 { let purchaseToGet = purchases![purchases!.count-1] var purchaseToDelete:Purchase? = nil; for purchase in purchases! { if purchase.status == "pending" { purchaseToDelete = purchase // self.testDeletePurchase(purchaseToDelete) } } //self.testGetOnePurchase(purchaseToGet) self.testPutPurchase(purchaseToDelete) } }) }) } func testPutPurchase(purchase:Purchase?) { if (purchase == nil) { return } PurchaseRequest(block: {(builder:PurchaseRequestBuilder) in builder.purchaseId = purchase!.purchaseId print(purchase!.status) builder.requestType = HTTPType.PUT builder.amount = 4300 builder.purchaseMedium = TransactionMedium.REWARDS builder.description = "updated" builder.payerId = "55e94a1af8d877051ab4f6c2" })?.send(completion: {(result:PurchaseResult) in // self.testDeletePurchase(purchase!) }) } func testDeletePurchase(purchase:Purchase?) { PurchaseRequest(block: {(builder:PurchaseRequestBuilder) in builder.purchaseId = purchase!.purchaseId print(purchase!.status) builder.requestType = HTTPType.DELETE builder.accountId = self.accountToAccess.accountId })?.send(completion: {(result) in }) } } class TransferTests { let client = NSEClient.sharedInstance init() { client.setKey("2c54c85dc28e084930c0e06703711a14") testGetAllTransfers() } var accountToAccess:Account! func testGetAllTransfers() { //get an account var getAllRequest = AccountRequest(block: {(builder:AccountRequestBuilder) in builder.requestType = HTTPType.GET }) getAllRequest?.send({(result:AccountResult) in var accounts = result.getAllAccounts() self.accountToAccess = accounts![0] self.testPostTransfer() //test get all }) } func testGetOneTransfer(transfer:Transfer) { TransferRequest(block: {(builder:TransferRequestBuilder) in builder.requestType = HTTPType.GET builder.transferId = transfer.transferId })?.send(completion: {(result:TransferResult) in var transferResult = result.getTransfer() print(transferResult, terminator: "") }) } func testPostTransfer() { TransferRequest(block: {(builder:TransferRequestBuilder) in builder.requestType = HTTPType.POST builder.amount = 10 builder.transferMedium = TransactionMedium.BALANCE builder.description = "test" builder.accountId = self.accountToAccess.accountId builder.payeeId = "55e94a1af8d877051ab4f6c1" })?.send(completion: {(result) in TransferRequest(block: {(builder:TransferRequestBuilder) in builder.requestType = HTTPType.GET builder.accountId = self.accountToAccess.accountId })?.send(completion: {(result:TransferResult) in var transfers = result.getAllTransfers() if transfers!.count > 0 { let transferToGet = transfers![transfers!.count-1] var transferToDelete:Transfer? = nil; for transfer in transfers! { if transfer.status == "pending" { transferToDelete = transfer // self.testDeleteTransfer(transferToDelete) } } //self.testGetOneTransfer(transferToGet) //self.testPutTransfer(transferToDelete) } }) }) } func testPutTransfer(transfer:Transfer?) { if (transfer == nil) { return } TransferRequest(block: {(builder:TransferRequestBuilder) in builder.transferId = transfer!.transferId print(transfer!.status) builder.requestType = HTTPType.PUT builder.amount = 4300 builder.transferMedium = TransactionMedium.REWARDS builder.description = "updated" builder.payeeId = "55e94a1af8d877051ab4f6c2" })?.send(completion: {(result:TransferResult) in // self.testDeleteTransfer(transfer!) }) } func testDeleteTransfer(transfer:Transfer?) { TransferRequest(block: {(builder:TransferRequestBuilder) in builder.transferId = transfer!.transferId print(transfer!.status) builder.requestType = HTTPType.DELETE builder.accountId = self.accountToAccess.accountId })?.send(completion: {(result) in }) } } class WithdrawalTests { let client = NSEClient.sharedInstance init() { client.setKey("2c54c85dc28e084930c0e06703711a14") testGetAllWithdrawals() } var accountToAccess:Account! func testGetAllWithdrawals() { //get an account var getAllRequest = AccountRequest(block: {(builder:AccountRequestBuilder) in builder.requestType = HTTPType.GET }) getAllRequest?.send({(result:AccountResult) in var accounts = result.getAllAccounts() self.accountToAccess = accounts![0] self.testPostWithdrawal() //test get all }) } func testGetOneWithdrawal(withdrawal:Withdrawal) { WithdrawalRequest(block: {(builder:WithdrawalRequestBuilder) in builder.requestType = HTTPType.GET builder.withdrawalId = withdrawal.withdrawalId })?.send(completion: {(result:WithdrawalResult) in var withdrawalResult = result.getWithdrawal() print(withdrawalResult, terminator: "") }) } func testPostWithdrawal() { WithdrawalRequest(block: {(builder:WithdrawalRequestBuilder) in builder.requestType = HTTPType.POST builder.amount = 10 builder.withdrawalMedium = TransactionMedium.BALANCE builder.description = "test" builder.accountId = self.accountToAccess.accountId })?.send(completion: {(result) in WithdrawalRequest(block: {(builder:WithdrawalRequestBuilder) in builder.requestType = HTTPType.GET builder.accountId = self.accountToAccess.accountId })?.send(completion: {(result:WithdrawalResult) in var withdrawals = result.getAllWithdrawals() if withdrawals!.count > 0 { let withdrawalToGet = withdrawals![withdrawals!.count-1] var withdrawalToDelete:Withdrawal? = nil; for withdrawal in withdrawals! { if withdrawal.status == "pending" { withdrawalToDelete = withdrawal //self.testDeleteWithdrawal(withdrawalToDelete) } } //self.testGetOneWithdrawal(withdrawalToGet) self.testPutWithdrawal(withdrawalToDelete) } }) }) } func testPutWithdrawal(withdrawal:Withdrawal?) { if (withdrawal == nil) { return } WithdrawalRequest(block: {(builder:WithdrawalRequestBuilder) in builder.withdrawalId = withdrawal!.withdrawalId print(withdrawal!.status) builder.requestType = HTTPType.PUT builder.amount = 4300 builder.withdrawalMedium = TransactionMedium.REWARDS builder.description = "updated" })?.send(completion: {(result:WithdrawalResult) in // self.testDeleteWithdrawal(withdrawal!) }) } func testDeleteWithdrawal(withdrawal:Withdrawal?) { WithdrawalRequest(block: {(builder:WithdrawalRequestBuilder) in builder.withdrawalId = withdrawal!.withdrawalId print(withdrawal!.status) builder.requestType = HTTPType.DELETE builder.accountId = self.accountToAccess.accountId })?.send(completion: {(result) in }) } } class MerchantTests { let client = NSEClient.sharedInstance init() { client.setKey("2c54c85dc28e084930c0e06703711a14") testMerchants() } func testMerchants() { self.testPostMerchant() var merchantGetAllRequest = MerchantRequest(block: {(builder:MerchantRequestBuilder) in builder.requestType = HTTPType.GET builder.latitude = 38.9283 builder.longitude = -77.1753 builder.radius = "1000" }) merchantGetAllRequest?.send({(result:MerchantResult) in var merchants = result.getAllMerchants() print("Merchants fetched:\(merchants)\n", terminator: "") var merchantID = merchants![0].merchantId self.testPutMerchant(merchants![0]) var getOneMerchantRequest = MerchantRequest(block: {(builder:MerchantRequestBuilder) in builder.requestType = HTTPType.GET builder.merchantId = merchantID }) getOneMerchantRequest?.send({(result:MerchantResult) in var merchant = result.getMerchant() print("Merchant fetched:\(merchant)\n", terminator: "") }) }) } func testPutMerchant(merchant:Merchant?) { if (merchant == nil) { return } MerchantRequest(block: {(builder:MerchantRequestBuilder) in builder.merchantId = merchant!.merchantId builder.requestType = HTTPType.PUT builder.name = "Victorrrrr" builder.address = Address(streetName: "1", streetNumber: "1", city: "1", state: "DC", zipCode: "12312") builder.latitude = 38.9283 builder.longitude = -77.1753 })?.send({(result:MerchantResult) in }) } func testPostMerchant() { MerchantRequest(block: {(builder:MerchantRequestBuilder) in builder.requestType = HTTPType.POST builder.name = "Fun Merchant" builder.address = Address(streetName: "1", streetNumber: "1", city: "1", state: "DC", zipCode: "12312") builder.latitude = 38.9283 builder.longitude = -77.1753 })?.send({(result:MerchantResult) in }) } } class TransactionTests { let client = NSEClient.sharedInstance init() { client.setKey("2c54c85dc28e084930c0e06703711a14") testGetAllTransactions() } var accountToAccess:Account! var accountToPay:Account! func testGetAllTransactions() { //get an account var getAllRequest = AccountRequest(block: {(builder:AccountRequestBuilder) in builder.requestType = HTTPType.GET }) getAllRequest?.send({(result:AccountResult) in var accounts = result.getAllAccounts() self.accountToAccess = accounts![0] self.accountToPay = accounts![1] self.testPostTransaction() //test get all TransactionRequest(block: {(builder:TransactionRequestBuilder) in builder.requestType = HTTPType.GET builder.accountId = self.accountToAccess.accountId })?.send(completion: {(result:TransactionResult) in var transactions = result.getAllTransactions() let transactionToGet = transactions![0] var transactionToDelete:Transaction? = nil; for transaction in transactions! { if transaction.status == "pending" { transactionToDelete = transaction } } self.testGetOneTransaction(transactionToGet) self.testPutTransaction(transactionToDelete) }) }) } func testGetOneTransaction(transaction:Transaction) { TransactionRequest(block: {(builder:TransactionRequestBuilder) in builder.requestType = HTTPType.GET builder.accountId = self.accountToAccess.accountId builder.transactionId = transaction.transactionId })?.send(completion: {(result:TransactionResult) in var transactionResult = result.getTransaction() }) } func testPostTransaction() { TransactionRequest(block: {(builder:TransactionRequestBuilder) in builder.requestType = HTTPType.POST builder.amount = 10 builder.transactionMedium = TransactionMedium.BALANCE builder.description = "test" builder.accountId = self.accountToAccess.accountId builder.payeeId = self.accountToPay.accountId })?.send(completion: {(result) in }) } func testPutTransaction(transaction:Transaction?) { if (transaction == nil) { return } TransactionRequest(block: {(builder:TransactionRequestBuilder) in builder.transactionId = transaction!.transactionId print(transaction!.status) builder.requestType = HTTPType.PUT builder.accountId = self.accountToAccess.accountId builder.transactionMedium = TransactionMedium.REWARDS builder.description = "updated" })?.send(completion: {(result:TransactionResult) in self.testDeleteTransaction(transaction!) }) } func testDeleteTransaction(transaction:Transaction) { TransactionRequest(block: {(builder:TransactionRequestBuilder) in builder.transactionId = transaction.transactionId print(transaction.status) builder.requestType = HTTPType.DELETE builder.accountId = self.accountToAccess.accountId })?.send(completion: {(result) in }) } } class EnterpriseTests { let client = NSEClient.sharedInstance init() { client.setKey("2c54c85dc28e084930c0e06703711a14") testEnterpriseGets() } func testEnterpriseGets() { EnterpriseAccountRequest()?.send({(result:AccountResult) in var accounts = result.getAllAccounts() var bills = 0 for tmp in accounts! { if (tmp.billIds != nil) { bills += tmp.billIds!.count } } EnterpriseAccountRequest(accountId: accounts![0].accountId)?.send({(result:AccountResult) in var account = result.getAccount() }) }) EnterpriseBillRequest()?.send({(result:BillResult) in var bills = result.getAllBills() var x:NSMutableSet = NSMutableSet() for bill in bills! { x.addObject(bill.billId) } EnterpriseBillRequest(billId: bills![0].billId)?.send({(result:BillResult) in var bill = result.getBill() }) }) EnterpriseCustomerRequest()?.send({(result:CustomerResult) in var customers = result.getAllCustomers() EnterpriseCustomerRequest(customerId: customers![0].customerId)?.send({(result:CustomerResult) in var customer = result.getCustomer() }) }) EnterpriseTransferRequest()?.send({(result:TransferResult) in var transfers = result.getAllTransfers() print("\(transfers)\n", terminator: "") EnterpriseTransferRequest(transactionId: transfers![0].transferId)?.send({(result:TransferResult) in var transfer = result.getTransfer() print("\(transfer)\n", terminator: "") }) }) EnterpriseDepositRequest()?.send({(result:DepositResult) in var deposits = result.getAllDeposits() print("\(deposits)\n", terminator: "") EnterpriseDepositRequest(transactionId: deposits![0].transactionId)?.send({(result:DepositResult) in var deposit = result.getDeposit() print("\(deposit)\n", terminator: "") }) }) EnterpriseWithdrawalRequest()?.send({(result:WithdrawalResult) in var withdrawals = result.getAllWithdrawals() print("\(withdrawals)\n", terminator: "") EnterpriseWithdrawalRequest(transactionId: withdrawals![0].withdrawalId)?.send({(result:WithdrawalResult) in var withdrawal = result.getWithdrawal() print("\(withdrawal)\n", terminator: "") }) }) EnterpriseMerchantRequest()?.send({(result:MerchantResult) in var merchants = result.getAllMerchants() print("\(merchants)\n", terminator: "") EnterpriseMerchantRequest(merchantId: merchants![0].merchantId)?.send({(result:MerchantResult) in var merchant = result.getMerchant() print("\(merchant)\n", terminator: "") }) }) } }
b5b71de669cf65335c772c54ec5851b4
33.634051
129
0.557266
false
true
false
false
crazypoo/PTools
refs/heads/master
Pods/KakaJSON/Sources/KakaJSON/Metadata/Type/OptionalType.swift
mit
1
// // OptionalType.swift // KakaJSON // // Created by MJ Lee on 2019/8/2. // Copyright © 2019 MJ Lee. All rights reserved. // /// Optional metadata share the same basic layout as enum metadata public class OptionalType: EnumType { public private(set) var wrapType: Any.Type = Any.self override func build() { super.build() var wt: BaseType! = self while wt.kind == .optional { wt = Metadata.type((wt as! OptionalType).genericTypes![0]) } wrapType = wt.type } override public var description: String { return "\(name) { kind = \(kind), wrapType = \(wrapType) }" } }
8fedd5f5b36034bcc9ecbc049f59f81f
24.730769
70
0.590433
false
false
false
false
openHPI/xikolo-ios
refs/heads/dev
iOS/Extensions/EmptyState/EmptyState.swift
gpl-3.0
1
// // Created for xikolo-ios under GPL-3.0 license. // Copyright © HPI. All rights reserved. // import Foundation import UIKit public protocol EmptyStateDelegate: AnyObject { func didTapOnEmptyStateView() } /// This protocol provides the table view object with the information it needs to construct and modify a `EmptyStateView`. public protocol EmptyStateDataSource: AnyObject { var emptyStateTitleText: String { get } var emptyStateDetailText: String? { get } } // MARK: - EmptyStateDataSource Default public extension EmptyStateDataSource { var emptyStateDetailText: String? { nil } } enum AssociatedKeys { static var emptyStateDelegate = "emptyStateDelegate" static var emptyStateDataSource = "emptyStateDataSource" static var emptyStateView = "emptyStateView" } /// This protocol provides the basic needed to override emptyViewState on anyclass that supports it protocol EmptyStateProtocol: AnyObject { var emptyStateDelegate: EmptyStateDelegate? { get set } var emptyStateDataSource: EmptyStateDataSource? { get set } var emptyStateView: EmptyStateView { get set } var hasItemsToDisplay: Bool { get } func reloadEmptyState() } extension EmptyStateProtocol { var emptyStateView: EmptyStateView { get { guard let emptyStateView = objc_getAssociatedObject(self, &AssociatedKeys.emptyStateView) as? EmptyStateView else { let emptyStateView = EmptyStateView() emptyStateView.tapHandler = { [weak self] in self?.emptyStateDelegate?.didTapOnEmptyStateView() } self.emptyStateView = emptyStateView return emptyStateView } return emptyStateView } set { objc_setAssociatedObject(self, &AssociatedKeys.emptyStateView, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } /// The object that acts as the delegate of the empty state view. public weak var emptyStateDelegate: EmptyStateDelegate? { get { return objc_getAssociatedObject(self, &AssociatedKeys.emptyStateDelegate) as? EmptyStateDelegate } set { if let newValue = newValue { objc_setAssociatedObject(self, &AssociatedKeys.emptyStateDelegate, newValue, .OBJC_ASSOCIATION_ASSIGN) } } } /// The object that acts as the data source of the empty state view. public weak var emptyStateDataSource: EmptyStateDataSource? { get { return objc_getAssociatedObject(self, &AssociatedKeys.emptyStateDataSource) as? EmptyStateDataSource } set { if let newValue = newValue { objc_setAssociatedObject(self, &AssociatedKeys.emptyStateDataSource, newValue, .OBJC_ASSOCIATION_ASSIGN) self.reloadEmptyState() } } } }
93ddf40006cc7fa0a7f60bb48752e29b
32.045977
127
0.684522
false
false
false
false
KBryan/SwiftFoundation
refs/heads/develop
SwiftFoundation/SwiftFoundationTests/POSIXTimeTests.swift
mit
1
// // POSIXTimeTests.swift // SwiftFoundation // // Created by Alsey Coleman Miller on 7/22/15. // Copyright © 2015 PureSwift. All rights reserved. // import XCTest import SwiftFoundation class POSIXTimeTests: 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 testGetTimeOfDay() { do { try timeval.timeOfDay() } catch { XCTFail("Error getting time: \(error)") } } func testTimeVal() { let date = Date() let time = timeval(timeInterval: date.timeIntervalSince1970) XCTAssert(Int(time.timeIntervalValue) == Int(date.timeIntervalSince1970), "TimeVal derived interval: \(time.timeIntervalValue) must equal Date's timeIntervalSince1970 \(date.timeIntervalSince1970)") } func testStaticTimeVal() { let date = Date() let time = timeval(timeInterval: 123456.7898) //XCTAssert(Int(time.timeIntervalValue) == Int(date.timeIntervalSince1970), "TimeVal derived interval: \(time.timeIntervalValue) must equal original constant") } func testTimeSpec() { let date = Date() let time = timespec(timeInterval: date.timeIntervalSince1970) XCTAssert(time.timeIntervalValue == date.timeIntervalSince1970) } }
2e0d58ab9beea597155cf0b624738eb9
26.866667
206
0.619019
false
true
false
false
huangboju/Moots
refs/heads/master
Examples/UIScrollViewDemo/UIScrollViewDemo/ExpandingCollectionView/UltravisualLayout.swift
mit
1
// // UltravisualLayout.swift // ExpandingCollectionView // // Created by Vamshi Krishna on 30/04/17. // Copyright © 2017 VamshiKrishna. All rights reserved. // import UIKit /* The heights are declared as constants outside of the class so they can be easily referenced elsewhere */ struct UltravisualLayoutConstants { struct Cell { /* The height of the non-featured cell */ static let standardHeight: CGFloat = 100 /* The height of the first visible cell */ static let featuredHeight: CGFloat = 280 } } class UltravisualLayout: UICollectionViewFlowLayout { // MARK: Properties and Variables /* The amount the user needs to scroll before the featured cell changes */ let dragOffset: CGFloat = 180.0 var cache = [UICollectionViewLayoutAttributes]() /* Returns the item index of the currently featured cell */ var featuredItemIndex: Int { get { /* Use max to make sure the featureItemIndex is never < 0 */ return max(0, Int(collectionView!.contentOffset.y / dragOffset)) } } /* Returns a value between 0 and 1 that represents how close the next cell is to becoming the featured cell */ var nextItemPercentageOffset: CGFloat { get { return (collectionView!.contentOffset.y / dragOffset) - CGFloat(featuredItemIndex) } } /* Returns the width of the collection view */ var width: CGFloat { get { return collectionView!.bounds.width } } /* Returns the height of the collection view */ var height: CGFloat { get { return collectionView!.bounds.height } } /* Returns the number of items in the collection view */ var numberOfItems: Int { get { return collectionView!.numberOfItems(inSection: 0) } } // MARK: UICollectionViewLayout /* Return the size of all the content in the collection view */ override var collectionViewContentSize: CGSize { let contentHeight = (CGFloat(numberOfItems) * dragOffset) + (height - dragOffset) return CGSize(width: width, height: contentHeight) } override func prepare() { cache.removeAll(keepingCapacity: false) let standardHeight = UltravisualLayoutConstants.Cell.standardHeight let featuredHeight = UltravisualLayoutConstants.Cell.featuredHeight var frame = CGRect.zero var y: CGFloat = 0 for item in 0 ..< numberOfItems { // 1 let indexPath = IndexPath(item: item, section: 0) let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath) // 2 attributes.zIndex = item var height = standardHeight // 3 if indexPath.item == featuredItemIndex { // 4 let yOffset = standardHeight * nextItemPercentageOffset y = collectionView!.contentOffset.y - yOffset height = featuredHeight } else if indexPath.item == (featuredItemIndex + 1) && indexPath.item != numberOfItems { // 5 let maxY = y + standardHeight height = standardHeight + max((featuredHeight - standardHeight) * nextItemPercentageOffset, 0) y = maxY - height } // 6 frame = CGRect(x: collectionView!.contentInset.left, y: y, width: width, height: height) attributes.frame = frame cache.append(attributes) y = frame.maxY } } /* Return all attributes in the cache whose frame intersects with the rect passed to the method */ override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { return cache.filter { $0.frame.intersects(rect) } } /* Return true so that the layout is continuously invalidated as the user scrolls */ override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool { return true } override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint { let itemIndex = round(proposedContentOffset.y / dragOffset) let yOffset = itemIndex * dragOffset return CGPoint(x: 0, y: yOffset) } }
1ccf8006c27bb27fd4bf9f3ffa0760d6
33.80315
148
0.632805
false
false
false
false
laonayt/NewFreshBeen-Swift
refs/heads/master
WEFreshBeen/Classes/Other/AppDelegate.swift
apache-2.0
1
// // AppDelegate.swift // WEFreshBeen // // Created by 马玮 on 16/5/26. // Copyright © 2016年 马玮. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { window = UIWindow(frame: UIScreen.mainScreen().bounds) window?.backgroundColor = UIColor.whiteColor() let isFirstOpen = NSUserDefaults.standardUserDefaults().objectForKey("isFirst") if isFirstOpen == nil { window?.rootViewController = GuidViewController() NSUserDefaults.standardUserDefaults().setObject("haveOpen", forKey: "isFirst") } else { let adViewController = ADViewController() adViewController.view.layoutIfNeeded() adViewController.imageStr = "http://img01.bqstatic.com/upload/activity/2016011111271995.jpg" window?.rootViewController = adViewController } window?.makeKeyAndVisible() return true } func turnToMainTabViewController() { window?.rootViewController = WETabBarViewController() } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
eb21939557987f7aa9f1c253585461b9
42.397059
285
0.715351
false
false
false
false
iAugux/Zoom-Contacts
refs/heads/master
Phonetic/Extensions/TopMostViewController+Extension.swift
mit
1
// // TopMostViewController.swift // // Created by Augus on 9/26/15. // Copyright © 2015 iAugus. All rights reserved. // import UIKit /** Description: the toppest view controller of presenting view controller How to use: UIApplication.topMostViewController Where to use: controllers are not complex */ extension UIApplication { class var topMostViewController: UIViewController? { var topController = UIApplication.sharedApplication().keyWindow?.rootViewController while topController?.presentedViewController != nil { topController = topController?.presentedViewController } return topController } /// App has more than one window and just want to get topMostViewController of the AppDelegate window. class var appDelegateWindowTopMostViewController: UIViewController? { let delegate = UIApplication.sharedApplication().delegate as? AppDelegate var topController = delegate?.window?.rootViewController while topController?.presentedViewController != nil { topController = topController?.presentedViewController } return topController } } /** Description: the toppest view controller of presenting view controller How to use: UIApplication.sharedApplication().keyWindow?.rootViewController?.topMostViewController Where to use: There are lots of kinds of controllers (UINavigationControllers, UITabbarControllers, UIViewController) */ extension UIViewController { var topMostViewController: UIViewController? { // Handling Modal views if let presentedViewController = self.presentedViewController { return presentedViewController.topMostViewController } // Handling UIViewController's added as subviews to some other views. else { for view in self.view.subviews { // Key property which most of us are unaware of / rarely use. if let subViewController = view.nextResponder() { if subViewController is UIViewController { let viewController = subViewController as! UIViewController return viewController.topMostViewController } } } return self } } } extension UITabBarController { override var topMostViewController: UIViewController? { return self.selectedViewController?.topMostViewController } } extension UINavigationController { override var topMostViewController: UIViewController? { return self.visibleViewController?.topMostViewController } }
68e707b86c718027af9bea3d7372fd5b
33.818182
118
0.691045
false
false
false
false
stripe/stripe-ios
refs/heads/master
StripePayments/StripePayments/API Bindings/Models/SetupIntents/STPSetupIntentConfirmParams.swift
mit
1
// // STPSetupIntentConfirmParams.swift // StripePayments // // Created by Yuki Tokuhiro on 6/27/19. // Copyright © 2019 Stripe, Inc. All rights reserved. // import Foundation /// An object representing parameters to confirm a SetupIntent object. /// For example, you would confirm a SetupIntent when a customer hits the “Save” button on a payment method management view in your app. /// If the selected payment method does not require any additional steps from the customer, the SetupIntent's status will transition to `STPSetupIntentStatusSucceeded`. Otherwise, it will transition to `STPSetupIntentStatusRequiresAction`, and suggest additional actions via `nextAction`. /// Instead of passing this to `STPAPIClient.confirmSetupIntent(...)` directly, we recommend using `STPPaymentHandler` to handle any additional steps for you. /// - seealso: https://stripe.com/docs/api/setup_intents/confirm public class STPSetupIntentConfirmParams: NSObject, NSCopying, STPFormEncodable { @objc public var additionalAPIParameters: [AnyHashable: Any] = [:] /// Initialize this `STPSetupIntentConfirmParams` with a `clientSecret`. /// - Parameter clientSecret: the client secret for this SetupIntent @objc public init( clientSecret: String ) { self.clientSecret = clientSecret super.init() additionalAPIParameters = [:] } /// Initialize this `STPSetupIntentConfirmParams` with a `clientSecret` and `paymentMethodType`. /// Use this initializer for SetupIntents that already have a PaymentMethod attached. /// - Parameter clientSecret: the client secret for this SetupIntent /// - Parameter paymentMethodType: the known type of the SetupIntent's attached PaymentMethod @objc public init( clientSecret: String, paymentMethodType: STPPaymentMethodType ) { self.clientSecret = clientSecret self._paymentMethodType = paymentMethodType super.init() additionalAPIParameters = [:] } /// The client secret of the SetupIntent. Required. @objc public var clientSecret: String /// Provide a supported `STPPaymentMethodParams` object, and Stripe will create a /// PaymentMethod during PaymentIntent confirmation. /// @note alternative to `paymentMethodId` @objc public var paymentMethodParams: STPPaymentMethodParams? /// Provide an already created PaymentMethod's id, and it will be used to confirm the SetupIntent. /// @note alternative to `paymentMethodParams` @objc public var paymentMethodID: String? /// The URL to redirect your customer back to after they authenticate or cancel /// their payment on the payment method’s app or site. /// This should probably be a URL that opens your iOS app. @objc public var returnURL: String? /// A boolean number to indicate whether you intend to use the Stripe SDK's functionality to handle any SetupIntent next actions. /// If set to false, STPSetupIntent.nextAction will only ever contain a redirect url that can be opened in a webview or mobile browser. /// When set to true, the nextAction may contain information that the Stripe SDK can use to perform native authentication within your /// app. @objc public var useStripeSDK: NSNumber? /// Details about the Mandate to create. /// @note If this value is null and the `(self.paymentMethod.type == STPPaymentMethodTypeSEPADebit | | self.paymentMethodParams.type == STPPaymentMethodTypeAUBECSDebit || self.paymentMethodParams.type == STPPaymentMethodTypeBacsDebit) && self.mandate == nil`, the SDK will set this to an internal value indicating that the mandate data should be inferred from the current context. @objc public var mandateData: STPMandateDataParams? { set(newMandateData) { _mandateData = newMandateData } get { if let _mandateData = _mandateData { return _mandateData } switch paymentMethodType { case .AUBECSDebit, .bacsDebit, .bancontact, .iDEAL, .SEPADebit, .EPS, .sofort, .link, .USBankAccount: // Create default infer from client mandate_data let onlineParams = STPMandateOnlineParams(ipAddress: "", userAgent: "") onlineParams.inferFromClient = NSNumber(value: true) if let customerAcceptance = STPMandateCustomerAcceptanceParams( type: .online, onlineParams: onlineParams ) { return STPMandateDataParams(customerAcceptance: customerAcceptance) } default: break } return nil } } private var _mandateData: STPMandateDataParams? internal var _paymentMethodType: STPPaymentMethodType? internal var paymentMethodType: STPPaymentMethodType? { if let type = _paymentMethodType { return type } return paymentMethodParams?.type } override convenience init() { // Not a valid clientSecret, but at least it'll be non-null self.init(clientSecret: "") } /// :nodoc: @objc public override var description: String { let props = [ // Object String(format: "%@: %p", NSStringFromClass(STPSetupIntentConfirmParams.self), self), // SetupIntentParams details (alphabetical) "clientSecret = \(((clientSecret.count) > 0) ? "<redacted>" : "")", "returnURL = \(returnURL ?? "")", "paymentMethodId = \(paymentMethodID ?? "")", "paymentMethodParams = \(String(describing: paymentMethodParams))", "useStripeSDK = \(useStripeSDK ?? 0)", // Mandate "mandateData = \(String(describing: mandateData))", // Additional params set by app "additionalAPIParameters = \(additionalAPIParameters )", ] return "<\(props.joined(separator: "; "))>" } // MARK: - NSCopying /// :nodoc: @objc public func copy(with zone: NSZone? = nil) -> Any { let copy = STPSetupIntentConfirmParams() copy.clientSecret = clientSecret copy._paymentMethodType = _paymentMethodType copy.paymentMethodParams = paymentMethodParams copy.paymentMethodID = paymentMethodID copy.returnURL = returnURL copy.useStripeSDK = useStripeSDK copy.mandateData = mandateData copy.additionalAPIParameters = additionalAPIParameters return copy } // MARK: - STPFormEncodable public class func rootObjectName() -> String? { return nil } public class func propertyNamesToFormFieldNamesMapping() -> [String: String] { return [ NSStringFromSelector(#selector(getter:clientSecret)): "client_secret", NSStringFromSelector(#selector(getter:paymentMethodParams)): "payment_method_data", NSStringFromSelector(#selector(getter:paymentMethodID)): "payment_method", NSStringFromSelector(#selector(getter:returnURL)): "return_url", NSStringFromSelector(#selector(getter:useStripeSDK)): "use_stripe_sdk", NSStringFromSelector(#selector(getter:mandateData)): "mandate_data", ] } // MARK: - Utilities static private let regex = try! NSRegularExpression( pattern: "^seti_[^_]+_secret_[^_]+$", options: [] ) @_spi(STP) public static func isClientSecretValid(_ clientSecret: String) -> Bool { return (regex.numberOfMatches( in: clientSecret, options: .anchored, range: NSRange(location: 0, length: clientSecret.count) )) == 1 } }
1a0eb06b92ef1ec07587c74f3ac2755c
43.942197
384
0.661608
false
false
false
false
LonelyHusky/SCWeibo
refs/heads/master
SCWeibo/Classes/View/Home/View/SCStatusToolBar.swift
mit
1
// // SCStatusToolBar.swift // SCWeibo // // Created by 云卷云舒丶 on 16/7/24. // // import UIKit class SCStatusToolBar: UIView { override init(frame: CGRect) { super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupUI(){ // 添加控件 let retweetButton = addChildButton("转发", imgName: "timeline_icon_retweet") let commentButton = addChildButton("评论", imgName: "timeline_icon_comment") let likeButton = addChildButton("赞", imgName: "timeline_icon_unlike") let sp1 = UIImageView(image: UIImage(named: "timeline_card_bottom_line")) let sp2 = UIImageView(image: UIImage(named: "timeline_card_bottom_line")) addSubview(sp1);addSubview(sp2) // 添加约束 retweetButton.snp_makeConstraints { (make) in make.leading.top.bottom.equalTo(self) make.width.equalTo(commentButton) } commentButton.snp_makeConstraints { (make) in make.leading.equalTo(retweetButton.snp_trailing) make.top.bottom.equalTo(self) make.width.equalTo(likeButton) } likeButton.snp_makeConstraints { (make) in make.trailing.top.bottom.equalTo(self) make.leading.equalTo(commentButton.snp_trailing) make.width.equalTo(retweetButton ) } sp1.snp_makeConstraints { (make) in make.centerX.equalTo(retweetButton.snp_trailing) make.centerY.equalTo(self) } sp2.snp_makeConstraints { (make) in make.centerX.equalTo(commentButton.snp_trailing) make.centerY.equalTo(self) } } private func addChildButton(title: String ,imgName: String) -> UIButton{ let button = UIButton() button.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Normal) button.setTitle(title, forState: UIControlState.Normal) button.setBackgroundImage(UIImage(named: "timeline_card_bottom_background"), forState: UIControlState.Normal) button.setBackgroundImage(UIImage(named: "timeline_card_bottom_background_highlighted"), forState: UIControlState.Highlighted) button.setImage(UIImage(named:imgName), forState: UIControlState.Normal) addSubview(button) return button } }
e830ad32c492094871bf983cd805cb13
33.15493
134
0.643711
false
false
false
false
remirobert/Kinder
refs/heads/master
KinderSource/KinderViewController.swift
mit
1
// // RRVoteViewController.swift // tindView // // Created by Remi Robert on 04/03/15. // Copyright (c) 2015 Remi Robert. All rights reserved. // import UIKit extension UIButton { func hideButtonAnimation(centerPosition: CGPoint) { UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 0.2, initialSpringVelocity: 0.2, options: UIViewAnimationOptions(), animations: { () -> Void in self.frame.size = CGSizeMake(75, 75) self.layer.cornerRadius = 37.5 self.frame.origin = centerPosition }, completion: nil) } func displayButtonAnimation(centerPosition: CGPoint) { UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 0.4, initialSpringVelocity: 0.4, options: UIViewAnimationOptions(), animations: { () -> Void in self.frame.size = CGSizeMake(100, 100) self.layer.cornerRadius = 50 self.frame.origin = centerPosition }, completion: nil) } } protocol KinderDelegate { func acceptCard(card: KinderModelCard?) func cancelCard(card: KinderModelCard?) func signalReload() func reloadCard() -> [KinderModelCard]? } class KinderViewController: UIViewController { private var dataCards: Array<KinderModelCard>! = Array() private var isAccept: Bool = false private var isCancel: Bool = false private var recogniserGesture: UIGestureRecognizer! var delegate: KinderDelegate? private lazy var acceptButton: UIButton! = { let button = UIButton(frame: CGRectMake(self.view.frame.size.width - 95, self.view.frame.size.height - 95, 75, 75)) button.layer.cornerRadius = 37.5 button.backgroundColor = UIColor.whiteColor() button.setImage(UIImage(named: "accept")!.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate), forState: UIControlState.Normal) button.tintColor = UIColor(red:0.33, green:0.84, blue:0.41, alpha:1) return button }() private lazy var infoButton: UIButton! = { let button = UIButton() button.frame.size = CGSizeMake(50, 50) button.layer.cornerRadius = 25 button.backgroundColor = UIColor.whiteColor() button.center = CGPointMake(self.view.center.x, self.acceptButton.center.y) button.setImage(UIImage(named: "info")!.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate), forState: UIControlState.Normal) button.tintColor = UIColor.grayColor() return button }() private lazy var cancelButton: UIButton! = { let button = UIButton(frame: CGRectMake(20, self.view.frame.size.height - 95, 75, 75)) button.layer.cornerRadius = 37.5 button.backgroundColor = UIColor.whiteColor() button.setImage(UIImage(named: "cancel")!.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate), forState: UIControlState.Normal) button.tintColor = UIColor(red:0.99, green:0.24, blue:0.22, alpha:1) return button }() private var cards: Array<KinderCardView> = Array() func reloadData() { if let data = self.delegate?.reloadCard() { for currentData in data { self.dataCards.append(currentData) } } } private func initStyleCardView(index: Int) { switch index { case 0: UIView.animateWithDuration(1, delay: 0, usingSpringWithDamping: 0.4, initialSpringVelocity: 0.4, options: UIViewAnimationOptions(), animations: { () -> Void in self.cards[0].size = CGSizeMake(self.view.frame.size.width - 40, self.view.frame.size.width + 20) self.cards[0].center = CGPointMake(self.view.center.x, self.view.center.y - 50) self.cards[0].alpha = 1 }, completion: nil) cards[0].addGestureRecognizer(recogniserGesture) case 1: UIView.animateWithDuration(1, delay: 0, usingSpringWithDamping: 0.4, initialSpringVelocity: 0.4, options: UIViewAnimationOptions(), animations: { () -> Void in self.cards[1].size = CGSizeMake(self.view.frame.size.width - 55, self.view.frame.size.width + 5) self.cards[1].center = CGPointMake(self.view.center.x, self.view.center.y - 50 + 20) self.cards[1].alpha = 0.75 }, completion: nil) case 2: UIView.animateWithDuration(1, delay: 0, usingSpringWithDamping: 0.4, initialSpringVelocity: 0.4, options: UIViewAnimationOptions(), animations: { () -> Void in self.cards[2].size = CGSizeMake(self.view.frame.size.width - 65, self.view.frame.size.width - 5) self.cards[2].center = CGPointMake(self.view.center.x, self.view.center.y - 50 + 40) self.cards[2].alpha = 0.5 }, completion: nil) default: return } } private func addNewCard() { for var index = cards.count; index < 3; index++ { if dataCards.count > 0 { var newCard = KinderCardView(size: CGSizeZero) newCard.size = CGSizeMake(self.view.frame.size.width - 65, self.view.frame.size.width - 5) newCard.center = CGPointMake(self.view.center.x, 0) newCard.imageContent = dataCards.first?.image newCard.titleContent = dataCards.first?.content newCard.descContent = dataCards.first?.desc dataCards.removeAtIndex(0) cards.append(newCard) initStyleCardView(index) self.view.addSubview(newCard) } for (var index = cards.count - 1; index >= 0; index--) { self.view.bringSubviewToFront(cards[index]) } } } private func manageCards() { if dataCards.count < 3 - self.cards.count + 1 { self.delegate?.signalReload() } cards.removeAtIndex(0) for (var index = 0; index < cards.count; index++) { initStyleCardView(index) } for (var index = cards.count - 1; index >= 0; index--) { self.view.bringSubviewToFront(cards[index]) } } private func initCardView() { for (var index = 0; index <= 2 && index < dataCards.count; index++) { var newCard = KinderCardView(size: CGSizeZero) newCard.imageContent = dataCards[index].image newCard.titleContent = dataCards[index].content newCard.descContent = dataCards[index].desc cards.append(newCard) initStyleCardView(index) self.view.addSubview(cards[index]) } for (var index = cards.count - 1; index >= 0; index--) { self.view.bringSubviewToFront(cards[index]) dataCards.removeAtIndex(index) } } @objc private func flipCardView() { if let firstCard = cards.first { if firstCard.descContent != "" { firstCard.flipCard() } } } @objc private func acceptCardView() { if cards.count == 0 { return } acceptButton.displayButtonAnimation(CGPointMake(self.view.frame.size.width - 110, self.view.frame.size.height - 110)) UIView.animateWithDuration(1, animations: { () -> Void in self.acceptButton.hideButtonAnimation(CGPointMake(self.view.frame.size.width - 95, self.view.frame.size.height - 95)) }) self.delegate?.acceptCard(dataCards.first) var currentCard = cards[0] UIView.animateWithDuration(1, delay: 0.2, usingSpringWithDamping: 0.4, initialSpringVelocity: 1, options: UIViewAnimationOptions(), animations: { () -> Void in self.cards[0].frame.origin.x = self.view.frame.size.width self.cards[0].alpha = 0 }) { (anim: Bool) -> Void in currentCard.removeFromSuperview() self.addNewCard() } self.manageCards() } @objc private func cancelCardView() { if cards.count == 0 { return } cancelButton.displayButtonAnimation(CGPointMake(10, self.view.frame.size.height - 110)) UIView.animateWithDuration(1, animations: { () -> Void in self.cancelButton.hideButtonAnimation(CGPointMake(20, self.view.frame.size.height - 95)) }) self.delegate?.cancelCard(dataCards.first) var currentCard = cards[0] UIView.animateWithDuration(1, delay: 0.2, usingSpringWithDamping: 0.4, initialSpringVelocity: 0.4, options: UIViewAnimationOptions(), animations: { () -> Void in self.cards[0].center.x = -self.view.frame.size.width }) { (anim: Bool) -> Void in currentCard.removeFromSuperview() self.addNewCard() } self.manageCards() } override func viewDidLoad() { super.viewDidLoad() recogniserGesture = UIPanGestureRecognizer(target: self, action: "handleGesture:") acceptButton.addTarget(self, action: "acceptCardView", forControlEvents: UIControlEvents.TouchUpInside) cancelButton.addTarget(self, action: "cancelCardView", forControlEvents: UIControlEvents.TouchUpInside) infoButton.addTarget(self, action: "flipCardView", forControlEvents: UIControlEvents.TouchUpInside) self.view.addSubview(acceptButton) self.view.addSubview(cancelButton) self.view.addSubview(infoButton) self.view.backgroundColor = UIColor(red:0.93, green:0.93, blue:0.93, alpha:1) } override func viewDidAppear(animated: Bool) { if let data = self.delegate?.reloadCard() { for currentCard in data { dataCards.append(currentCard) } } initCardView() } @objc private func handleGesture(recognizer: UIPanGestureRecognizer) { var pointTranslation = recognizer.translationInView(self.view) pointTranslation = CGPointMake(recognizer.view!.center.x + pointTranslation.x, recognizer.view!.center.y + pointTranslation.y) var marginBotSecond = ((self.view.frame.size.width / 2 - pointTranslation.x) / 7) * ((pointTranslation.x < self.view.center.x) ? 1 : -1) var marginTopSecond = ((self.view.frame.size.height / 2 - (pointTranslation.y + 20)) / 7) * ((pointTranslation.y < self.view.center.y) ? 1 : -1) var marginBotThird = ((self.view.frame.size.width / 2 - pointTranslation.x) / 4) * ((pointTranslation.x < self.view.center.x) ? 1 : -1) var marginTopThird = ((self.view.frame.size.height / 2 - pointTranslation.y) / 4) * ((pointTranslation.y < self.view.center.y) ? 1 : -1) if pointTranslation.x > self.view.center.x { marginBotSecond *= -1 marginBotThird *= -1 } if pointTranslation.y > self.view.center.y { marginTopSecond *= -1 marginTopThird *= -1 } recognizer.view?.center = pointTranslation UIView.animateWithDuration(0.2, animations: { () -> Void in if 1 % self.cards.count == 1 { self.cards[1].center = CGPointMake(pointTranslation.x + marginBotSecond, pointTranslation.y + marginTopSecond) } if 2 % self.cards.count == 2 { self.cards[2].center = CGPointMake(pointTranslation.x + marginBotThird, pointTranslation.y + marginTopThird) } }) if recognizer.view?.center.x >= self.view.frame.size.width { acceptButton.displayButtonAnimation(CGPointMake(self.view.frame.size.width - 110, self.view.frame.size.height - 110)) isAccept = true } else { acceptButton.hideButtonAnimation(CGPointMake(self.view.frame.size.width - 95, self.view.frame.size.height - 95)) isAccept = false } if recognizer.view?.center.x <= 0 { cancelButton.displayButtonAnimation(CGPointMake(10, self.view.frame.size.height - 110)) isCancel = true } else { cancelButton.hideButtonAnimation(CGPointMake(20, self.view.frame.size.height - 95)) isCancel = false } recognizer.setTranslation(CGPointZero, inView: self.view) if recognizer.state == UIGestureRecognizerState.Ended { let velocity = recognizer.velocityInView(self.view) if isAccept { acceptCardView() } else if isCancel { cancelCardView() } if cards.count == 0 { return } UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 0.4, initialSpringVelocity: 0.4, options: UIViewAnimationOptions(), animations: { () -> Void in if !self.isAccept && !self.isCancel && recognizer.view != nil { recognizer.view!.center = CGPointMake(self.view.center.x, self.view.center.y - 50) } if 1 % self.cards.count == 1 { self.cards[1].center = CGPointMake(self.view.center.x, self.view.center.y - 50 + 20) } if 2 % self.cards.count == 2 { self.cards[2].center = CGPointMake(self.view.center.x, self.view.center.y - 50 + 40) } }, completion: nil) cancelButton.hideButtonAnimation(CGPointMake(20, self.view.frame.size.height - 95)) acceptButton.hideButtonAnimation(CGPointMake(self.view.frame.size.width - 95, self.view.frame.size.height - 95)) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() self.dismissViewControllerAnimated(true, completion: nil) } }
ba4be04a6abe26be2e8b767a395d6bdc
41.933535
152
0.595806
false
false
false
false
dasdom/DHTweak
refs/heads/master
Tweaks/TweakStore.swift
mit
2
// // TweakStore.swift // TweaksDemo // // Created by dasdom on 22.08.14. // Copyright (c) 2014 Dominik Hauser. All rights reserved. // import Foundation private let _TweakStoreSharedInstance = TweakStore(name: "DefaultTweakStore") public class TweakStore { class var sharedTweakStore: TweakStore { return _TweakStoreSharedInstance } let name: String private var namedCategories = [String:TweakCategory]() init(name: String) { self.name = name } func allCategories() -> [TweakCategory] { var categories = [TweakCategory]() for (key, value) in namedCategories { categories.append(value) } return categories } func addCategory(category: TweakCategory) { namedCategories[category.name] = category } func removeCategory(category: TweakCategory) { namedCategories.removeValueForKey(category.name) } func removeAllCategories() { namedCategories = [String:TweakCategory]() } func categoryWithName(name: String) -> TweakCategory? { return namedCategories[name] } }
481d513cd2ab4a680b0212952ef74869
22.673469
77
0.639344
false
false
false
false
ArnavChawla/InteliChat
refs/heads/master
Carthage/Checkouts/ios-sdk/Source/AlchemyDataNewsV1/Models/SAORelation.swift
apache-2.0
6
/** * Copyright IBM Corporation 2015 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ import Foundation import RestKit /** **SAORelation** Extracted Subject, Action, and Object parts of a sentence */ public struct SAORelation: JSONDecodable { /// see Action public let action: Action? /// an extracted Sentence public let sentence: String? /// see Subject public let subject: Subject? /// see RelationObject public let object: RelationObject? /// Used internally to initialize a SAORelation object public init(json: JSON) throws { action = try? json.decode(at: "action", type: Action.self) sentence = try? json.getString(at: "sentence") subject = try? json.decode(at: "subject", type: Subject.self) object = try? json.decode(at: "object", type: RelationObject.self) } } /** An action as defined by the AlchemyLanguage service */ public struct Action: JSONDecodable { /// text the action was extracted from public let text: String? /// the base or dictionary form of the word public let lemmatized: String? /// see Verb public let verb: Verb? /// Used internally to initialize an Action object public init(json: JSON) throws { text = try? json.getString(at: "text") lemmatized = try? json.getString(at: "lemmatized") verb = try? json.decode(at: "verb", type: Verb.self) } /** A verb as defined by the AlchemyLanguage service */ public struct Verb: JSONDecodable { /// text the verb was extracted from public let text: String? /// the tense of the verb public let tense: String? /// was the verb negated public let negated: Int? /// Used internally to initalize a Verb object public init(json: JSON) throws { text = try? json.getString(at: "text") tense = try? json.getString(at: "tense") if let negatedString = try? json.getString(at: "negated") { negated = Int(negatedString) } else { negated = 0 } } } } /** A subjet extracted by the AlchemyLanguage service */ public struct Subject: JSONDecodable { /// text the subject was extracted from public let text: String? /// see **Sentiment** public let sentiment: Sentiment? /// see **Entity** public let entity: Entity? /// Used internally to initialize a Subject object public init(json: JSON) throws { text = try? json.getString(at: "text") sentiment = try? json.decode(at: "sentiment", type: Sentiment.self) entity = try? json.decode(at: "entity", type: Entity.self) } } /** **Sentiment** related to the Subject-Action-Object extraction */ public struct RelationObject: JSONDecodable { /// text the relation object was extracted from public let text: String? /// see **Sentiment** public let sentiment: Sentiment? /// see **Sentiment** public let sentimentFromSubject: Sentiment? /// see **Entity** public let entity: Entity? /// Used internally to initialize a RelationObject object public init(json: JSON) throws { text = try? json.getString(at: "text") sentiment = try? json.decode(at: "sentiment", type: Sentiment.self) sentimentFromSubject = try? json.decode(at: "sentimentFromSubject", type: Sentiment.self) entity = try? json.decode(at: "entity", type: Entity.self) } }
eb2dd19748344c50779d34676757829b
27.074324
97
0.625511
false
false
false
false
airspeedswift/swift
refs/heads/master
test/decl/protocol/req/associated_type_inference.swift
apache-2.0
2
// RUN: %target-typecheck-verify-swift protocol P0 { associatedtype Assoc1 : PSimple // expected-note{{ambiguous inference of associated type 'Assoc1': 'Double' vs. 'Int'}} // expected-note@-1{{ambiguous inference of associated type 'Assoc1': 'Double' vs. 'Int'}} // expected-note@-2{{unable to infer associated type 'Assoc1' for protocol 'P0'}} // expected-note@-3{{unable to infer associated type 'Assoc1' for protocol 'P0'}} func f0(_: Assoc1) func g0(_: Assoc1) } protocol PSimple { } extension Int : PSimple { } extension Double : PSimple { } struct X0a : P0 { // okay: Assoc1 == Int func f0(_: Int) { } func g0(_: Int) { } } struct X0b : P0 { // expected-error{{type 'X0b' does not conform to protocol 'P0'}} func f0(_: Int) { } // expected-note{{matching requirement 'f0' to this declaration inferred associated type to 'Int'}} func g0(_: Double) { } // expected-note{{matching requirement 'g0' to this declaration inferred associated type to 'Double'}} } struct X0c : P0 { // okay: Assoc1 == Int func f0(_: Int) { } func g0(_: Float) { } func g0(_: Int) { } } struct X0d : P0 { // okay: Assoc1 == Int func f0(_: Int) { } func g0(_: Double) { } // viable, but no corresponding f0 func g0(_: Int) { } } struct X0e : P0 { // expected-error{{type 'X0e' does not conform to protocol 'P0'}} func f0(_: Double) { } // expected-note{{matching requirement 'f0' to this declaration inferred associated type to 'Double}} func f0(_: Int) { } // expected-note{{matching requirement 'f0' to this declaration inferred associated type to 'Int'}} func g0(_: Double) { } func g0(_: Int) { } } struct X0f : P0 { // okay: Assoc1 = Int because Float doesn't conform to PSimple func f0(_: Float) { } func f0(_: Int) { } func g0(_: Float) { } func g0(_: Int) { } } struct X0g : P0 { // expected-error{{type 'X0g' does not conform to protocol 'P0'}} func f0(_: Float) { } // expected-note{{candidate would match and infer 'Assoc1' = 'Float' if 'Float' conformed to 'PSimple'}} func g0(_: Float) { } // expected-note{{candidate would match and infer 'Assoc1' = 'Float' if 'Float' conformed to 'PSimple'}} } struct X0h<T : PSimple> : P0 { func f0(_: T) { } } extension X0h { func g0(_: T) { } } struct X0i<T : PSimple> { } extension X0i { func g0(_: T) { } } extension X0i : P0 { } extension X0i { func f0(_: T) { } } // Protocol extension used to infer requirements protocol P1 { } extension P1 { func f0(_ x: Int) { } func g0(_ x: Int) { } } struct X0j : P0, P1 { } protocol P2 { associatedtype P2Assoc func h0(_ x: P2Assoc) } extension P2 where Self.P2Assoc : PSimple { func f0(_ x: P2Assoc) { } // expected-note{{candidate would match and infer 'Assoc1' = 'Float' if 'Float' conformed to 'PSimple'}} func g0(_ x: P2Assoc) { } // expected-note{{candidate would match and infer 'Assoc1' = 'Float' if 'Float' conformed to 'PSimple'}} } struct X0k : P0, P2 { func h0(_ x: Int) { } } struct X0l : P0, P2 { // expected-error{{type 'X0l' does not conform to protocol 'P0'}} func h0(_ x: Float) { } } // Prefer declarations in the type to those in protocol extensions struct X0m : P0, P2 { func f0(_ x: Double) { } func g0(_ x: Double) { } func h0(_ x: Double) { } } // Inference from properties. protocol PropertyP0 { associatedtype Prop : PSimple // expected-note{{unable to infer associated type 'Prop' for protocol 'PropertyP0'}} var property: Prop { get } } struct XProp0a : PropertyP0 { // okay PropType = Int var property: Int } struct XProp0b : PropertyP0 { // expected-error{{type 'XProp0b' does not conform to protocol 'PropertyP0'}} var property: Float // expected-note{{candidate would match and infer 'Prop' = 'Float' if 'Float' conformed to 'PSimple'}} } // Inference from subscripts protocol SubscriptP0 { associatedtype Index // expected-note@-1 2 {{protocol requires nested type 'Index'; do you want to add it?}} associatedtype Element : PSimple // expected-note@-1 {{unable to infer associated type 'Element' for protocol 'SubscriptP0'}} // expected-note@-2 2 {{protocol requires nested type 'Element'; do you want to add it?}} subscript (i: Index) -> Element { get } } struct XSubP0a : SubscriptP0 { subscript (i: Int) -> Int { get { return i } } } struct XSubP0b : SubscriptP0 { // expected-error@-1{{type 'XSubP0b' does not conform to protocol 'SubscriptP0'}} subscript (i: Int) -> Float { get { return Float(i) } } // expected-note{{candidate would match and infer 'Element' = 'Float' if 'Float' conformed to 'PSimple'}} } struct XSubP0c : SubscriptP0 { // expected-error@-1 {{type 'XSubP0c' does not conform to protocol 'SubscriptP0'}} subscript (i: Index) -> Element { get { } } } struct XSubP0d : SubscriptP0 { // expected-error@-1 {{type 'XSubP0d' does not conform to protocol 'SubscriptP0'}} subscript (i: XSubP0d.Index) -> XSubP0d.Element { get { } } } // Inference from properties and subscripts protocol CollectionLikeP0 { associatedtype Index // expected-note@-1 {{protocol requires nested type 'Index'; do you want to add it?}} associatedtype Element // expected-note@-1 {{protocol requires nested type 'Element'; do you want to add it?}} var startIndex: Index { get } var endIndex: Index { get } subscript (i: Index) -> Element { get } } struct SomeSlice<T> { } struct XCollectionLikeP0a<T> : CollectionLikeP0 { var startIndex: Int var endIndex: Int subscript (i: Int) -> T { get { fatalError("blah") } } subscript (r: Range<Int>) -> SomeSlice<T> { get { return SomeSlice() } } } struct XCollectionLikeP0b : CollectionLikeP0 { // expected-error@-1 {{type 'XCollectionLikeP0b' does not conform to protocol 'CollectionLikeP0'}} var startIndex: XCollectionLikeP0b.Index // There was an error @-1 ("'startIndex' used within its own type"), // but it disappeared and doesn't seem like much of a loss. var startElement: XCollectionLikeP0b.Element } // rdar://problem/21304164 public protocol Thenable { associatedtype T // expected-note{{protocol requires nested type 'T'}} func then(_ success: (_: T) -> T) -> Self } public class CorePromise<U> : Thenable { // expected-error{{type 'CorePromise<U>' does not conform to protocol 'Thenable'}} public func then(_ success: @escaping (_ t: U, _: CorePromise<U>) -> U) -> Self { return self.then() { (t: U) -> U in // expected-error{{contextual closure type '(U, CorePromise<U>) -> U' expects 2 arguments, but 1 was used in closure body}} return success(t: t, self) // expected-error@-1 {{extraneous argument label 't:' in call}} } } } // rdar://problem/21559670 protocol P3 { associatedtype Assoc = Int associatedtype Assoc2 func foo(_ x: Assoc2) -> Assoc? } protocol P4 : P3 { } extension P4 { func foo(_ x: Int) -> Float? { return 0 } } extension P3 where Assoc == Int { func foo(_ x: Int) -> Assoc? { return nil } } struct X4 : P4 { } // rdar://problem/21738889 protocol P5 { associatedtype A = Int } struct X5<T : P5> : P5 { typealias A = T.A } protocol P6 : P5 { associatedtype A : P5 = X5<Self> } extension P6 where A == X5<Self> { } // rdar://problem/21774092 protocol P7 { associatedtype A associatedtype B func f() -> A func g() -> B } struct X7<T> { } extension P7 { func g() -> X7<A> { return X7() } } struct Y7<T> : P7 { func f() -> Int { return 0 } } struct MyAnySequence<Element> : MySequence { typealias SubSequence = MyAnySequence<Element> func makeIterator() -> MyAnyIterator<Element> { return MyAnyIterator<Element>() } } struct MyAnyIterator<T> : MyIteratorType { typealias Element = T } protocol MyIteratorType { associatedtype Element } protocol MySequence { associatedtype Iterator : MyIteratorType associatedtype SubSequence func foo() -> SubSequence func makeIterator() -> Iterator } extension MySequence { func foo() -> MyAnySequence<Iterator.Element> { return MyAnySequence() } } struct SomeStruct<Element> : MySequence { let element: Element init(_ element: Element) { self.element = element } func makeIterator() -> MyAnyIterator<Element> { return MyAnyIterator<Element>() } } // rdar://problem/21883828 - ranking of solutions protocol P8 { } protocol P9 : P8 { } protocol P10 { associatedtype A func foo() -> A } struct P8A { } struct P9A { } extension P8 { func foo() -> P8A { return P8A() } } extension P9 { func foo() -> P9A { return P9A() } } struct Z10 : P9, P10 { } func testZ10() -> Z10.A { var zA: Z10.A zA = P9A() return zA } // rdar://problem/21926788 protocol P11 { associatedtype A associatedtype B func foo() -> B } extension P11 where A == Int { func foo() -> Int { return 0 } } protocol P12 : P11 { } extension P12 { func foo() -> String { return "" } } struct X12 : P12 { typealias A = String } // Infinite recursion -- we would try to use the extension // initializer's argument type of 'Dough' as a candidate for // the associated type protocol Cookie { associatedtype Dough // expected-note@-1 {{protocol requires nested type 'Dough'; do you want to add it?}} init(t: Dough) } extension Cookie { init(t: Dough?) {} } struct Thumbprint : Cookie {} // expected-error@-1 {{type 'Thumbprint' does not conform to protocol 'Cookie'}} // Looking through typealiases protocol Vector { associatedtype Element typealias Elements = [Element] func process(elements: Elements) } struct Int8Vector : Vector { func process(elements: [Int8]) { } } // SR-4486 protocol P13 { associatedtype Arg // expected-note{{protocol requires nested type 'Arg'; do you want to add it?}} func foo(arg: Arg) } struct S13 : P13 { // expected-error{{type 'S13' does not conform to protocol 'P13'}} func foo(arg: inout Int) {} } // "Infer" associated type from generic parameter. protocol P14 { associatedtype Value } struct P14a<Value>: P14 { } struct P14b<Value> { } extension P14b: P14 { } // Associated type defaults in overridden associated types. struct X15 { } struct OtherX15 { } protocol P15a { associatedtype A = X15 } protocol P15b : P15a { associatedtype A } protocol P15c : P15b { associatedtype A } protocol P15d { associatedtype A = X15 } protocol P15e : P15b, P15d { associatedtype A } protocol P15f { associatedtype A = OtherX15 } protocol P15g: P15c, P15f { associatedtype A // expected-note{{protocol requires nested type 'A'; do you want to add it?}} } struct X15a : P15a { } struct X15b : P15b { } struct X15c : P15c { } struct X15d : P15d { } // Ambiguity. // FIXME: Better diagnostic here? struct X15g : P15g { } // expected-error{{type 'X15g' does not conform to protocol 'P15g'}} // Associated type defaults in overidden associated types that require // substitution. struct X16<T> { } protocol P16 { associatedtype A = X16<Self> } protocol P16a : P16 { associatedtype A } protocol P16b : P16a { associatedtype A } struct X16b : P16b { } // Refined protocols that tie associated types to a fixed type. protocol P17 { associatedtype T } protocol Q17 : P17 where T == Int { } struct S17 : Q17 { } // Typealiases from protocol extensions should not inhibit associated type // inference. protocol P18 { associatedtype A } protocol P19 : P18 { associatedtype B } extension P18 where Self: P19 { typealias A = B } struct X18<A> : P18 { } // rdar://problem/16316115 protocol HasAssoc { associatedtype Assoc } struct DefaultAssoc {} protocol RefinesAssocWithDefault: HasAssoc { associatedtype Assoc = DefaultAssoc } struct Foo: RefinesAssocWithDefault { } protocol P20 { associatedtype T // expected-note{{protocol requires nested type 'T'; do you want to add it?}} typealias TT = T? } struct S19 : P20 { // expected-error{{type 'S19' does not conform to protocol 'P20'}} typealias TT = Int? } // rdar://problem/44777661 struct S30<T> where T : P30 {} protocol P30 { static func bar() } protocol P31 { associatedtype T : P30 } extension S30 : P31 where T : P31 {} extension S30 { func foo() { T.bar() } } protocol P32 { associatedtype A associatedtype B associatedtype C func foo(arg: A) -> C var bar: B { get } } protocol P33 { associatedtype A var baz: A { get } // expected-note {{protocol requires property 'baz' with type 'S31<T>.A' (aka 'Never'); do you want to add a stub?}} } protocol P34 { associatedtype A func boo() -> A // expected-note {{protocol requires function 'boo()' with type '() -> S31<T>.A' (aka '() -> Never'); do you want to add a stub?}} } struct S31<T> {} extension S31: P32 where T == Int {} // OK extension S31 where T == Int { func foo(arg: Never) {} } extension S31 where T: Equatable { var bar: Bool { true } } extension S31: P33 where T == Never {} // expected-error {{type 'S31<T>' does not conform to protocol 'P33'}} extension S31 where T == String { var baz: Bool { true } // expected-note {{candidate has non-matching type 'Bool' [with A = S31<T>.A]}} } extension S31: P34 {} // expected-error {{type 'S31<T>' does not conform to protocol 'P34'}} extension S31 where T: P32 { func boo() -> Void {} // expected-note {{candidate has non-matching type '<T> () -> Void' [with A = S31<T>.A]}} } // SR-12707 class SR_12707_C<T> {} // Inference in the adoptee protocol SR_12707_P1 { associatedtype A associatedtype B: SR_12707_C<(A, Self)> func foo(arg: B) } struct SR_12707_Conform_P1: SR_12707_P1 { typealias A = Never func foo(arg: SR_12707_C<(A, SR_12707_Conform_P1)>) {} } // Inference in protocol extension protocol SR_12707_P2: SR_12707_P1 {} extension SR_12707_P2 { func foo(arg: SR_12707_C<(A, Self)>) {} } struct SR_12707_Conform_P2: SR_12707_P2 { typealias A = Never } // SR-13172: Inference when witness is an enum case protocol SR_13172_P1 { associatedtype Bar static func bar(_ value: Bar) -> Self } enum SR_13172_E1: SR_13172_P1 { case bar(String) // Okay } protocol SR_13172_P2 { associatedtype Bar static var bar: Bar { get } } enum SR_13172_E2: SR_13172_P2 { case bar // Okay } /** References to type parameters in type witnesses. */ // Circular reference through a fixed type witness. protocol P35a { associatedtype A = Array<B> // expected-note {{protocol requires nested type 'A'}} associatedtype B // expected-note {{protocol requires nested type 'B'}} } protocol P35b: P35a where B == A {} // expected-error@+2 {{type 'S35' does not conform to protocol 'P35a'}} // expected-error@+1 {{type 'S35' does not conform to protocol 'P35b'}} struct S35: P35b {} // Circular reference through a value witness. protocol P36a { associatedtype A // expected-note {{protocol requires nested type 'A'}} func foo(arg: A) } protocol P36b: P36a { associatedtype B = (Self) -> A // expected-note {{protocol requires nested type 'B'}} } // expected-error@+2 {{type 'S36' does not conform to protocol 'P36a'}} // expected-error@+1 {{type 'S36' does not conform to protocol 'P36b'}} struct S36: P36b { func foo(arg: Array<B>) {} } // Test that we can resolve abstract type witnesses that reference // other abstract type witnesses. protocol P37 { associatedtype A = Array<B> associatedtype B: Equatable = Never } struct S37: P37 {} protocol P38a { associatedtype A = Never associatedtype B: Equatable } protocol P38b: P38a where B == Array<A> {} struct S38: P38b {} protocol P39 where A: Sequence { associatedtype A = Array<B> associatedtype B } struct S39<B>: P39 {} // Test that we can handle an analogous complex case involving all kinds of // type witness resolution. protocol P40a { associatedtype A associatedtype B: P40a func foo(arg: A) } protocol P40b: P40a { associatedtype C = (A, B.A, D.D, E) -> Self associatedtype D: P40b associatedtype E: Equatable } protocol P40c: P40b where D == S40<Never> {} struct S40<E: Equatable>: P40c { func foo(arg: Never) {} typealias B = Self } // Self is not treated as a fixed type witness. protocol FIXME_P1a { associatedtype A // expected-note {{protocol requires nested type 'A'}} } protocol FIXME_P1b: FIXME_P1a where A == Self {} // expected-error@+2 {{type 'FIXME_S1' does not conform to protocol 'FIXME_P1a'}} // expected-error@+1 {{type 'FIXME_S1' does not conform to protocol 'FIXME_P1b'}} struct FIXME_S1: FIXME_P1b {} // Fails to find the fixed type witness B == FIXME_S2<A>. protocol FIXME_P2a { associatedtype A: Equatable = Never // expected-note {{protocol requires nested type 'A'}} associatedtype B: FIXME_P2a // expected-note {{protocol requires nested type 'B'}} } protocol FIXME_P2b: FIXME_P2a where B == FIXME_S2<A> {} // expected-error@+2 {{type 'FIXME_S2<T>' does not conform to protocol 'FIXME_P2a'}} // expected-error@+1 {{type 'FIXME_S2<T>' does not conform to protocol 'FIXME_P2b'}} struct FIXME_S2<T: Equatable>: FIXME_P2b {}
09527d8db466c4974a83b3a66e1528f1
23.191092
167
0.667815
false
false
false
false
rahulsend89/MemoryGame
refs/heads/master
MemoryGame/BlockCVC.swift
mit
1
// // BlockCVC.swift // MemoryGame // // Created by Rahul Malik on 7/15/17. // Copyright © 2017 aceenvisage. All rights reserved. // import UIKit.UICollectionViewCell class BlockCVC: UICollectionViewCell { // MARK: - Properties @IBOutlet weak var frontImageView: UIImageView! @IBOutlet weak var backImageView: UIImageView! var block: Block? { didSet { guard let block = block else { return } frontImageView.image = block.image } } fileprivate(set) var shown: Bool = false // MARK: - Methods func showBlock(_ show: Bool, animted: Bool) { frontImageView.isHidden = false backImageView.isHidden = false shown = show if animted { if show { UIView.transition(from: backImageView, to: frontImageView, duration: 0.5, options: [.transitionFlipFromRight, .showHideTransitionViews], completion: { (_: Bool) -> Void in }) } else { UIView.transition(from: frontImageView, to: backImageView, duration: 0.5, options: [.transitionFlipFromRight, .showHideTransitionViews], completion: { (_: Bool) -> Void in }) } } else { if show { bringSubview(toFront: frontImageView) backImageView.isHidden = true } else { bringSubview(toFront: backImageView) frontImageView.isHidden = true } } } }
5432e0866c13cedbc0880d3d671bc52d
28.633333
96
0.490439
false
false
false
false
Hout/DateInRegion
refs/heads/master
Example/Tests/DateInRegionHashableTests.swift
mit
1
// // DateInRegionEquationsTests.swift // DateInRegion // // Created by Jeroen Houtzager on 07/11/15. // Copyright © 2015 CocoaPods. All rights reserved. // import Quick import Nimble import DateInRegion class DateInRegionHashableTests: QuickSpec { override func spec() { let netherlands = DateRegion(calendarID: NSCalendarIdentifierGregorian, timeZoneID: "CET", localeID: "nl_NL") let utc = DateRegion(calendarID: NSCalendarIdentifierGregorian, timeZoneID: "UTC", localeID: "en_UK") describe("DateInRegionHashable") { it("should return an equal hash for the same date reference") { let date1 = DateInRegion(year: 1999, month: 12, day: 31)! expect(date1.hashValue) == date1.hashValue } it("should return an equal hash for the same date value") { let date1 = DateInRegion(year: 1999, month: 12, day: 31)! let date2 = DateInRegion(year: 1999, month: 12, day: 31)! expect(date1.hashValue) == date2.hashValue } it("should return an unequal hash for a different date value") { let date1 = DateInRegion(year: 1999, month: 12, day: 31)! let date2 = DateInRegion(year: 1999, month: 12, day: 30)! expect(date1.hashValue) != date2.hashValue } it("should return an unequal hash for a different time zone value") { let date = NSDate() let date1 = DateInRegion(date: date, region: netherlands) let date2 = DateInRegion(date: date, region: utc) expect(date1.hashValue) != date2.hashValue } } } }
a6c739cc2ee3081adf975589e4c63e40
31.490909
117
0.576945
false
false
false
false
ozgur/TestApp
refs/heads/master
TestApp/Extensions/Rx/MKMapView+Rx.swift
gpl-3.0
1
// // MKMapView+Rx.swift // RxCocoa // // Created by Spiros Gerokostas on 04/01/16. // Copyright © 2016 Spiros Gerokostas. All rights reserved. // import MapKit import RxSwift import RxCocoa // MARK: RxMKMapViewDelegateProxy class RxMKMapViewDelegateProxy: DelegateProxy, MKMapViewDelegate, DelegateProxyType { class func currentDelegateFor(_ object: AnyObject) -> AnyObject? { let mapView: MKMapView = (object as? MKMapView)! return mapView.delegate } class func setCurrentDelegate(_ delegate: AnyObject?, toObject object: AnyObject) { let mapView: MKMapView = (object as? MKMapView)! mapView.delegate = delegate as? MKMapViewDelegate } } // MARK: MKMapView extension Reactive where Base : MKMapView { /** Reactive wrapper for `delegate`. For more information take a look at `DelegateProxyType` protocol documentation. */ var delegate: DelegateProxy { return RxMKMapViewDelegateProxy.proxyForObject(base) } // MARK: Responding to Map Position Changes var regionWillChangeAnimated: ControlEvent<Bool> { let source = delegate .methodInvoked(#selector(MKMapViewDelegate.mapView(_:regionWillChangeAnimated:))) .map { a in return try castOrThrow(Bool.self, a[1]) } return ControlEvent(events: source) } var regionDidChangeAnimated: ControlEvent<Bool> { let source = delegate .methodInvoked(#selector(MKMapViewDelegate.mapView(_:regionDidChangeAnimated:))) .map { a in return try castOrThrow(Bool.self, a[1]) } return ControlEvent(events: source) } // MARK: Loading the Map Data var willStartLoadingMap: ControlEvent<Void>{ let source = delegate .methodInvoked(#selector(MKMapViewDelegate.mapViewWillStartLoadingMap(_:))) .mapToVoid() return ControlEvent(events: source) } var didFinishLoadingMap: ControlEvent<Void>{ let source = delegate .methodInvoked(#selector(MKMapViewDelegate.mapViewDidFinishLoadingMap(_:))) .mapToVoid() return ControlEvent(events: source) } var didFailLoadingMap: Observable<NSError>{ return delegate .methodInvoked(#selector(MKMapViewDelegate.mapViewDidFailLoadingMap(_:withError:))) .map { a in return try castOrThrow(NSError.self, a[1]) } } // MARK: Responding to Rendering Events var willStartRenderingMap: ControlEvent<Void>{ let source = delegate .methodInvoked(#selector(MKMapViewDelegate.mapViewWillStartRenderingMap(_:))) .mapToVoid() return ControlEvent(events: source) } var didFinishRenderingMap: ControlEvent<Bool> { let source = delegate .methodInvoked(#selector(MKMapViewDelegate.mapViewDidFinishRenderingMap(_:fullyRendered:))) .map { a in return try castOrThrow(Bool.self, a[1]) } return ControlEvent(events: source) } // MARK: Tracking the User Location var willStartLocatingUser: ControlEvent<Void> { let source = delegate .methodInvoked(#selector(MKMapViewDelegate.mapViewWillStartLocatingUser(_:))) .mapToVoid() return ControlEvent(events: source) } var didStopLocatingUser: ControlEvent<Void> { let source = delegate .methodInvoked(#selector(MKMapViewDelegate.mapViewDidStopLocatingUser(_:))) .mapToVoid() return ControlEvent(events: source) } var didUpdateUserLocation: ControlEvent<MKUserLocation> { let source = delegate .methodInvoked(#selector(MKMapViewDelegate.mapView(_:didUpdate:))) .map { a in return try castOrThrow(MKUserLocation.self, a[1]) } return ControlEvent(events: source) } var didUpdateUserRegion: ControlEvent<MKCoordinateRegion> { let source = didUpdateUserLocation .map { location -> MKCoordinateRegion in return MKCoordinateRegionMakeWithDistance(location.coordinate, 125.0) } return ControlEvent(events: source) } var didFailToLocateUserWithError: Observable<NSError> { return delegate .methodInvoked(#selector(MKMapViewDelegate.mapView(_:didFailToLocateUserWithError:))) .map { a in return try castOrThrow(NSError.self, a[1]) } } public var didChangeUserTrackingMode: ControlEvent<(mode: MKUserTrackingMode, animated: Bool)> { let source = delegate .methodInvoked(#selector(MKMapViewDelegate.mapView(_:didChange:animated:))) .map { a in return (mode: try castOrThrow(Int.self, a[1]), animated: try castOrThrow(Bool.self, a[2])) } .map { (mode, animated) in return (mode: MKUserTrackingMode(rawValue: mode)!, animated: animated) } return ControlEvent(events: source) } // MARK: Responding to Annotation Views var didAddAnnotationViews: ControlEvent<[MKAnnotationView]> { let source = delegate .methodInvoked(#selector( (MKMapViewDelegate.mapView(_:didAdd:))! as (MKMapViewDelegate) -> (MKMapView, [MKAnnotationView]) -> Void ) ) .map { a in return try castOrThrow([MKAnnotationView].self, a[1]) } return ControlEvent(events: source) } var annotationViewCalloutAccessoryControlTapped: ControlEvent<(view: MKAnnotationView, control: UIControl)> { let source = delegate .methodInvoked(#selector(MKMapViewDelegate.mapView(_:annotationView:calloutAccessoryControlTapped:))) .map { a in return (view: try castOrThrow(MKAnnotationView.self, a[1]), control: try castOrThrow(UIControl.self, a[2])) } return ControlEvent(events: source) } // MARK: Selecting Annotation Views var didSelectAnnotationView: ControlEvent<MKAnnotationView> { let source = delegate .methodInvoked(#selector(MKMapViewDelegate.mapView(_:didSelect:))) .map { a in return try castOrThrow(MKAnnotationView.self, a[1]) } return ControlEvent(events: source) } var didDeselectAnnotationView: ControlEvent<MKAnnotationView> { let source = delegate .methodInvoked(#selector(MKMapViewDelegate.mapView(_:didDeselect:))) .map { a in return try castOrThrow(MKAnnotationView.self, a[1]) } return ControlEvent(events: source) } var didChangeState: ControlEvent<(view: MKAnnotationView, newState: MKAnnotationViewDragState, oldState: MKAnnotationViewDragState)> { let source = delegate .methodInvoked(#selector(MKMapViewDelegate.mapView(_:annotationView:didChange:fromOldState:))) .map { a in return (view: try castOrThrow(MKAnnotationView.self, a[1]), newState: try castOrThrow(UInt.self, a[2]), oldState: try castOrThrow(UInt.self, a[3])) } .map { (view, newState, oldState) in return (view: view, newState: MKAnnotationViewDragState(rawValue: newState)!, oldState: MKAnnotationViewDragState(rawValue: oldState)!) } return ControlEvent(events: source) } // MARK: Managing the Display of Overlays var didAddOverlayRenderers: ControlEvent<[MKOverlayRenderer]> { let source = delegate .methodInvoked(#selector( (MKMapViewDelegate.mapView(_:didAdd:))! as (MKMapViewDelegate) -> (MKMapView, [MKOverlayRenderer]) -> Void ) ) .map { a in return try castOrThrow([MKOverlayRenderer].self, a[1]) } return ControlEvent(events: source) } var userLocation: Observable<MKUserLocation?> { return observeWeakly(MKUserLocation.self, "userLocation") } } extension Reactive where Base: MKMapView { var showUserLocation: UIBindingObserver<Base, Bool> { return UIBindingObserver(UIElement: base) { mapView, showsUserLocation in mapView.showsUserLocation = showsUserLocation } } }
84a14fa0216b334550b0ef0aeb16fb91
30.353414
118
0.686563
false
false
false
false
grpc/grpc-swift
refs/heads/main
Sources/GRPC/AsyncAwaitSupport/GRPCClient+AsyncAwaitSupport.swift
apache-2.0
1
/* * Copyright 2021, gRPC Authors All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if compiler(>=5.6) import SwiftProtobuf @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) extension GRPCClient { public func makeAsyncUnaryCall<Request: Message & Sendable, Response: Message & Sendable>( path: String, request: Request, callOptions: CallOptions? = nil, interceptors: [ClientInterceptor<Request, Response>] = [], responseType: Response.Type = Response.self ) -> GRPCAsyncUnaryCall<Request, Response> { return self.channel.makeAsyncUnaryCall( path: path, request: request, callOptions: callOptions ?? self.defaultCallOptions, interceptors: interceptors ) } public func makeAsyncUnaryCall<Request: GRPCPayload & Sendable, Response: GRPCPayload & Sendable>( path: String, request: Request, callOptions: CallOptions? = nil, interceptors: [ClientInterceptor<Request, Response>] = [], responseType: Response.Type = Response.self ) -> GRPCAsyncUnaryCall<Request, Response> { return self.channel.makeAsyncUnaryCall( path: path, request: request, callOptions: callOptions ?? self.defaultCallOptions, interceptors: interceptors ) } public func makeAsyncServerStreamingCall< Request: SwiftProtobuf.Message & Sendable, Response: SwiftProtobuf.Message & Sendable >( path: String, request: Request, callOptions: CallOptions? = nil, interceptors: [ClientInterceptor<Request, Response>] = [], responseType: Response.Type = Response.self ) -> GRPCAsyncServerStreamingCall<Request, Response> { return self.channel.makeAsyncServerStreamingCall( path: path, request: request, callOptions: callOptions ?? self.defaultCallOptions, interceptors: interceptors ) } public func makeAsyncServerStreamingCall< Request: GRPCPayload & Sendable, Response: GRPCPayload & Sendable >( path: String, request: Request, callOptions: CallOptions? = nil, interceptors: [ClientInterceptor<Request, Response>] = [], responseType: Response.Type = Response.self ) -> GRPCAsyncServerStreamingCall<Request, Response> { return self.channel.makeAsyncServerStreamingCall( path: path, request: request, callOptions: callOptions ?? self.defaultCallOptions, interceptors: interceptors ) } public func makeAsyncClientStreamingCall< Request: SwiftProtobuf.Message & Sendable, Response: SwiftProtobuf.Message & Sendable >( path: String, callOptions: CallOptions? = nil, interceptors: [ClientInterceptor<Request, Response>] = [], requestType: Request.Type = Request.self, responseType: Response.Type = Response.self ) -> GRPCAsyncClientStreamingCall<Request, Response> { return self.channel.makeAsyncClientStreamingCall( path: path, callOptions: callOptions ?? self.defaultCallOptions, interceptors: interceptors ) } public func makeAsyncClientStreamingCall< Request: GRPCPayload & Sendable, Response: GRPCPayload & Sendable >( path: String, callOptions: CallOptions? = nil, interceptors: [ClientInterceptor<Request, Response>] = [], requestType: Request.Type = Request.self, responseType: Response.Type = Response.self ) -> GRPCAsyncClientStreamingCall<Request, Response> { return self.channel.makeAsyncClientStreamingCall( path: path, callOptions: callOptions ?? self.defaultCallOptions, interceptors: interceptors ) } public func makeAsyncBidirectionalStreamingCall< Request: SwiftProtobuf.Message & Sendable, Response: SwiftProtobuf.Message & Sendable >( path: String, callOptions: CallOptions? = nil, interceptors: [ClientInterceptor<Request, Response>] = [], requestType: Request.Type = Request.self, responseType: Response.Type = Response.self ) -> GRPCAsyncBidirectionalStreamingCall<Request, Response> { return self.channel.makeAsyncBidirectionalStreamingCall( path: path, callOptions: callOptions ?? self.defaultCallOptions, interceptors: interceptors ) } public func makeAsyncBidirectionalStreamingCall< Request: GRPCPayload & Sendable, Response: GRPCPayload & Sendable >( path: String, callOptions: CallOptions? = nil, interceptors: [ClientInterceptor<Request, Response>] = [], requestType: Request.Type = Request.self, responseType: Response.Type = Response.self ) -> GRPCAsyncBidirectionalStreamingCall<Request, Response> { return self.channel.makeAsyncBidirectionalStreamingCall( path: path, callOptions: callOptions ?? self.defaultCallOptions, interceptors: interceptors ) } } // MARK: - "Simple, but safe" wrappers. @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) extension GRPCClient { public func performAsyncUnaryCall<Request: Message & Sendable, Response: Message & Sendable>( path: String, request: Request, callOptions: CallOptions? = nil, interceptors: [ClientInterceptor<Request, Response>] = [], responseType: Response.Type = Response.self ) async throws -> Response { let call = self.channel.makeAsyncUnaryCall( path: path, request: request, callOptions: callOptions ?? self.defaultCallOptions, interceptors: interceptors ) return try await withTaskCancellationHandler { try await call.response } onCancel: { call.cancel() } } public func performAsyncUnaryCall< Request: GRPCPayload & Sendable, Response: GRPCPayload & Sendable >( path: String, request: Request, callOptions: CallOptions? = nil, interceptors: [ClientInterceptor<Request, Response>] = [], responseType: Response.Type = Response.self ) async throws -> Response { let call = self.channel.makeAsyncUnaryCall( path: path, request: request, callOptions: callOptions ?? self.defaultCallOptions, interceptors: interceptors ) return try await withTaskCancellationHandler { try await call.response } onCancel: { call.cancel() } } public func performAsyncServerStreamingCall< Request: SwiftProtobuf.Message & Sendable, Response: SwiftProtobuf.Message & Sendable >( path: String, request: Request, callOptions: CallOptions? = nil, interceptors: [ClientInterceptor<Request, Response>] = [], responseType: Response.Type = Response.self ) -> GRPCAsyncResponseStream<Response> { return self.channel.makeAsyncServerStreamingCall( path: path, request: request, callOptions: callOptions ?? self.defaultCallOptions, interceptors: interceptors ).responseStream } public func performAsyncServerStreamingCall< Request: GRPCPayload & Sendable, Response: GRPCPayload & Sendable >( path: String, request: Request, callOptions: CallOptions? = nil, interceptors: [ClientInterceptor<Request, Response>] = [], responseType: Response.Type = Response.self ) -> GRPCAsyncResponseStream<Response> { return self.channel.makeAsyncServerStreamingCall( path: path, request: request, callOptions: callOptions ?? self.defaultCallOptions, interceptors: interceptors ).responseStream } public func performAsyncClientStreamingCall< Request: SwiftProtobuf.Message & Sendable, Response: SwiftProtobuf.Message & Sendable, RequestStream: AsyncSequence & Sendable >( path: String, requests: RequestStream, callOptions: CallOptions? = nil, interceptors: [ClientInterceptor<Request, Response>] = [], requestType: Request.Type = Request.self, responseType: Response.Type = Response.self ) async throws -> Response where RequestStream.Element == Request { let call = self.channel.makeAsyncClientStreamingCall( path: path, callOptions: callOptions ?? self.defaultCallOptions, interceptors: interceptors ) return try await self.perform(call, with: requests) } public func performAsyncClientStreamingCall< Request: GRPCPayload & Sendable, Response: GRPCPayload & Sendable, RequestStream: AsyncSequence & Sendable >( path: String, requests: RequestStream, callOptions: CallOptions? = nil, interceptors: [ClientInterceptor<Request, Response>] = [], requestType: Request.Type = Request.self, responseType: Response.Type = Response.self ) async throws -> Response where RequestStream.Element == Request { let call = self.channel.makeAsyncClientStreamingCall( path: path, callOptions: callOptions ?? self.defaultCallOptions, interceptors: interceptors ) return try await self.perform(call, with: requests) } public func performAsyncClientStreamingCall< Request: SwiftProtobuf.Message & Sendable, Response: SwiftProtobuf.Message & Sendable, RequestStream: Sequence >( path: String, requests: RequestStream, callOptions: CallOptions? = nil, interceptors: [ClientInterceptor<Request, Response>] = [], requestType: Request.Type = Request.self, responseType: Response.Type = Response.self ) async throws -> Response where RequestStream.Element == Request { let call = self.channel.makeAsyncClientStreamingCall( path: path, callOptions: callOptions ?? self.defaultCallOptions, interceptors: interceptors ) return try await self.perform(call, with: AsyncStream(wrapping: requests)) } public func performAsyncClientStreamingCall< Request: GRPCPayload & Sendable, Response: GRPCPayload & Sendable, RequestStream: Sequence >( path: String, requests: RequestStream, callOptions: CallOptions? = nil, interceptors: [ClientInterceptor<Request, Response>] = [], requestType: Request.Type = Request.self, responseType: Response.Type = Response.self ) async throws -> Response where RequestStream.Element == Request { let call = self.channel.makeAsyncClientStreamingCall( path: path, callOptions: callOptions ?? self.defaultCallOptions, interceptors: interceptors ) return try await self.perform(call, with: AsyncStream(wrapping: requests)) } public func performAsyncBidirectionalStreamingCall< Request: SwiftProtobuf.Message & Sendable, Response: SwiftProtobuf.Message & Sendable, RequestStream: AsyncSequence & Sendable >( path: String, requests: RequestStream, callOptions: CallOptions? = nil, interceptors: [ClientInterceptor<Request, Response>] = [], requestType: Request.Type = Request.self, responseType: Response.Type = Response.self ) -> GRPCAsyncResponseStream<Response> where RequestStream.Element == Request { let call = self.channel.makeAsyncBidirectionalStreamingCall( path: path, callOptions: callOptions ?? self.defaultCallOptions, interceptors: interceptors ) return self.perform(call, with: requests) } public func performAsyncBidirectionalStreamingCall< Request: GRPCPayload & Sendable, Response: GRPCPayload & Sendable, RequestStream: AsyncSequence & Sendable >( path: String, requests: RequestStream, callOptions: CallOptions? = nil, interceptors: [ClientInterceptor<Request, Response>] = [], requestType: Request.Type = Request.self, responseType: Response.Type = Response.self ) -> GRPCAsyncResponseStream<Response> where RequestStream.Element == Request { let call = self.channel.makeAsyncBidirectionalStreamingCall( path: path, callOptions: callOptions ?? self.defaultCallOptions, interceptors: interceptors ) return self.perform(call, with: requests) } public func performAsyncBidirectionalStreamingCall< Request: SwiftProtobuf.Message & Sendable, Response: SwiftProtobuf.Message & Sendable, RequestStream: Sequence >( path: String, requests: RequestStream, callOptions: CallOptions? = nil, interceptors: [ClientInterceptor<Request, Response>] = [], requestType: Request.Type = Request.self, responseType: Response.Type = Response.self ) -> GRPCAsyncResponseStream<Response> where RequestStream.Element == Request { let call = self.channel.makeAsyncBidirectionalStreamingCall( path: path, callOptions: callOptions ?? self.defaultCallOptions, interceptors: interceptors ) return self.perform(call, with: AsyncStream(wrapping: requests)) } public func performAsyncBidirectionalStreamingCall< Request: GRPCPayload & Sendable, Response: GRPCPayload & Sendable, RequestStream: Sequence >( path: String, requests: RequestStream, callOptions: CallOptions? = nil, interceptors: [ClientInterceptor<Request, Response>] = [], requestType: Request.Type = Request.self, responseType: Response.Type = Response.self ) -> GRPCAsyncResponseStream<Response> where RequestStream.Element == Request { let call = self.channel.makeAsyncBidirectionalStreamingCall( path: path, callOptions: callOptions ?? self.defaultCallOptions, interceptors: interceptors ) return self.perform(call, with: AsyncStream(wrapping: requests)) } } @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) extension GRPCClient { @inlinable internal func perform< Request: Sendable, Response: Sendable, RequestStream: AsyncSequence & Sendable >( _ call: GRPCAsyncClientStreamingCall<Request, Response>, with requests: RequestStream ) async throws -> Response where RequestStream.Element == Request { return try await withTaskCancellationHandler { Task { do { // `AsyncSequence`s are encouraged to co-operatively check for cancellation, and we will // cancel the call `onCancel` anyway, so there's no need to check here too. for try await request in requests { try await call.requestStream.send(request) } call.requestStream.finish() } catch { // If we throw then cancel the call. We will rely on the response throwing an appropriate // error below. call.cancel() } } return try await call.response } onCancel: { call.cancel() } } @inlinable internal func perform< Request: Sendable, Response: Sendable, RequestStream: AsyncSequence & Sendable >( _ call: GRPCAsyncBidirectionalStreamingCall<Request, Response>, with requests: RequestStream ) -> GRPCAsyncResponseStream<Response> where RequestStream.Element == Request { Task { do { try await withTaskCancellationHandler { // `AsyncSequence`s are encouraged to co-operatively check for cancellation, and we will // cancel the call `onCancel` anyway, so there's no need to check here too. for try await request in requests { try await call.requestStream.send(request) } call.requestStream.finish() } onCancel: { call.cancel() } } catch { call.cancel() } } return call.responseStream } } @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) extension AsyncStream { /// Create an `AsyncStream` from a regular (non-async) `Sequence`. /// /// - Note: This is just here to avoid duplicating the above two `perform(_:with:)` functions /// for `Sequence`. fileprivate init<T>(wrapping sequence: T) where T: Sequence, T.Element == Element { self.init { continuation in var iterator = sequence.makeIterator() while let value = iterator.next() { continuation.yield(value) } continuation.finish() } } } #endif
54ab7471f180bde15956a1b126343280
32.569072
100
0.699404
false
false
false
false
mahjouri/pokedex
refs/heads/master
pokedex-by-saamahn/ViewController.swift
bsd-3-clause
1
// // ViewController.swift // pokedex-by-saamahn // // Created by Saamahn Mahjouri on 3/6/16. // Copyright © 2016 Saamahn Mahjouri. All rights reserved. // import UIKit import AVFoundation class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UISearchBarDelegate { @IBOutlet weak var collection: UICollectionView! @IBOutlet weak var searchBar: UISearchBar! var pokemon = [Pokemon]() var filteredPokemon = [Pokemon]() var musicPlayer: AVAudioPlayer! var inSearchMode = false override func viewDidLoad() { super.viewDidLoad() collection.delegate = self collection.dataSource = self searchBar.delegate = self searchBar.returnKeyType = UIReturnKeyType.Done initAudio() parsePokemonCSV() } func initAudio() { let path = NSBundle.mainBundle().pathForResource("music", ofType: "mp3")! do { musicPlayer = try AVAudioPlayer(contentsOfURL: NSURL(string: path)!) musicPlayer.prepareToPlay() musicPlayer.numberOfLoops = -1 musicPlayer.play() } catch let err as NSError { print(err.debugDescription) } } func parsePokemonCSV() { let path = NSBundle.mainBundle().pathForResource("pokemon", ofType: "csv") do { let csv = try CSV(contentsOfURL: path!) let rows = csv.rows for row in rows { let pokeId = Int(row["id"]!)! let name = row["identifier"]! let poke = Pokemon(name: name, pokedexId: pokeId) pokemon.append(poke) } print(rows) } catch let err as NSError { print(err.debugDescription) } } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { if let cell = collectionView.dequeueReusableCellWithReuseIdentifier("PokeCell", forIndexPath: indexPath) as? PokeCell { let poke: Pokemon! if inSearchMode { poke = filteredPokemon[indexPath.row] } else { poke = pokemon[indexPath.row] } cell.configureCell(poke) return cell } else { return UICollectionViewCell() } } func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { let poke: Pokemon! if inSearchMode { poke = filteredPokemon[indexPath.row] } else { poke = pokemon[indexPath.row] } performSegueWithIdentifier("PokemonDetailVC", sender: poke) } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if inSearchMode { return filteredPokemon.count } return pokemon.count } func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { return CGSizeMake(105, 105) } @IBAction func musicBtnPressed(sender: UIButton!) { if musicPlayer.playing { musicPlayer.stop() sender.alpha = 0.2 } else { musicPlayer.play() sender.alpha = 1.0 } } func searchBarSearchButtonClicked(searchBar: UISearchBar) { view.endEditing(true) } func searchBar(searchBar: UISearchBar, textDidChange searchText: String) { if searchBar.text == nil || searchBar.text == "" { inSearchMode = false view.endEditing(true) collection.reloadData() } else { inSearchMode = true let lower = searchBar.text!.lowercaseString filteredPokemon = pokemon.filter({$0.name.rangeOfString(lower) != nil}) collection.reloadData() } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "PokemonDetailVC" { if let detailsVC = segue.destinationViewController as? PokemonDetailVC { if let poke = sender as? Pokemon { detailsVC.pokemon = poke } } } } }
3067c2b7030f4365213552558a54f9d2
29.302469
110
0.562233
false
false
false
false
Syerram/asphalos
refs/heads/master
asphalos/FormPickerCell.swift
mit
1
// // FormPickerCell.swift // SwiftForms // // Created by Miguel Angel Ortuno on 22/08/14. // Copyright (c) 2014 Miguel Angel Ortuño. All rights reserved. // import UIKit class FormPickerCell: FormValueCell, UIPickerViewDelegate, UIPickerViewDataSource { /// MARK: Properties private let picker = UIPickerView() private let hiddenTextField = UITextField(frame: CGRectZero) /// MARK: FormBaseCell override func configure() { super.configure() accessoryType = .None picker.delegate = self picker.dataSource = self hiddenTextField.inputView = picker contentView.addSubview(hiddenTextField) } override func update() { super.update() titleLabel.text = rowDescriptor.title if rowDescriptor.value != nil { valueLabel.text = rowDescriptor.titleForOptionValue(rowDescriptor.value) } } override class func formViewController(formViewController: FormViewController, didSelectRow selectedRow: FormBaseCell) { if selectedRow.rowDescriptor.value == nil { if let row = selectedRow as? FormPickerCell { let optionValue = selectedRow.rowDescriptor.options[0] as? NSObject selectedRow.rowDescriptor.value = optionValue row.valueLabel.text = selectedRow.rowDescriptor.titleForOptionValue(optionValue!) row.hiddenTextField.becomeFirstResponder() } } else { if let row = selectedRow as? FormPickerCell { let optionValue = selectedRow.rowDescriptor.value row.valueLabel.text = selectedRow.rowDescriptor.titleForOptionValue(optionValue) row.hiddenTextField.becomeFirstResponder() } } } /// MARK: UIPickerViewDelegate func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! { return rowDescriptor.titleForOptionAtIndex(row) } func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { let optionValue = rowDescriptor.options[row] as? NSObject rowDescriptor.value = optionValue valueLabel.text = rowDescriptor.titleForOptionValue(optionValue!) } /// MARK: UIPickerViewDataSource func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int { return 1 } func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return rowDescriptor.options.count } }
e8ee5219a5a1d3aa597af8f7a001ba9f
32.125
124
0.655472
false
false
false
false
kissybnts/v-project
refs/heads/develop
Sources/App/MarkDown/Relations/TagNoteRelation.swift
mit
1
import Vapor import FluentProvider import HTTP final class TagNoteRelation: Model { let storage = Storage() static let entity = "tag_note" let tagId: Identifier let noteId: Identifier internal struct Properties { internal static let id = PropertyKey.id internal static let tagId = Tag.foreinIdKey internal static let noteId = Note.foreinIdKey } init(tagId: Identifier, noteId: Identifier) { self.tagId = tagId self.noteId = noteId } convenience init(tag: Tag, note: Note) throws { guard let tagId = tag.id else { throw Abort.serverError } guard let noteId = note.id else { throw Abort.serverError } self.init(tagId: tagId, noteId: noteId) } init(row: Row) throws { tagId = try row.get(Properties.tagId) noteId = try row.get(Properties.noteId) } func makeRow() throws -> Row { var row = Row() try row.set(Properties.tagId, tagId) try row.set(Properties.noteId, noteId) return row } } extension TagNoteRelation: Preparation { static func prepare(_ database: Database) throws { try database.create(self) { builder in builder.id() builder.foreignId(for: Tag.self) builder.foreignId(for: Note.self) } } static func revert(_ database: Database) throws { try database.delete(self) } } extension TagNoteRelation: Timestampable {} extension TagNoteRelation { internal static func delteAllByTag(tag: Tag) throws -> Void { guard let tagId = tag.id else { return } try TagNoteRelation.makeQuery().filter(Properties.tagId, tagId).delete() } internal static func deleteAllByNote(note: Note) throws -> Void { guard let noteId = note.id else { return } try TagNoteRelation.makeQuery().filter(Properties.noteId, noteId).delete() } internal static func deleteAllByUserId(userId: Identifier) throws -> Void { try TagNoteRelation.database?.raw("DELETE `tag_note` from `tag_note` INNER JOIN `notes` ON `tag_note`.`note_id` = `notes`.`id` INNER JOIN `users` ON `notes`.`user_id` = `users`.`id` WHERE `users`.`id` = ?", [userId]) } }
27ee7db5ddc6fce0049a5c2706df046a
28.3
224
0.611348
false
false
false
false
gongmingqm10/DriftBook
refs/heads/master
DriftReading/DriftReading/DiscoveryViewController.swift
mit
1
// // DiscoveryViewController.swift // DriftReading // // Created by Ming Gong on 7/7/15. // Copyright © 2015 gongmingqm10. All rights reserved. // import UIKit class DiscoveryViewController: UITableViewController { let driftAPI = DriftAPI() @IBOutlet var booksTableView: UITableView! var books: [Book] = [] let TYPE_DRIFTING = "drifting" let TYPE_READING = "reading" var selectedBook: Book? var currentType: String? override func viewDidLoad() { currentType = TYPE_DRIFTING } override func viewDidAppear(animated: Bool) { loadBooksByType() } private func loadBooksByType() { driftAPI.getBooks(currentType!, success: { (books) -> Void in self.books = books self.booksTableView.reloadData() }) { (error) -> Void in print(error.description) } } @IBAction func switchSegment(sender: UISegmentedControl) { currentType = sender.selectedSegmentIndex == 0 ? TYPE_DRIFTING : TYPE_READING loadBooksByType() } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "BookDetailSegue" { let bookDetailController = segue.destinationViewController as! BookDetailViewController bookDetailController.bookId = selectedBook!.id } } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return books.count } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { self.selectedBook = books[indexPath.row] self.performSegueWithIdentifier("BookDetailSegue", sender: self) } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 150 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = booksTableView.dequeueReusableCellWithIdentifier("BookTableCell", forIndexPath: indexPath) as! BookTableCell let book = books[indexPath.row] cell.populate(book) return cell } }
5e2c82ad0fb0d01953d2c43e3ee39609
30.30137
127
0.661269
false
false
false
false
ldjhust/CircleBom
refs/heads/master
CircleBom/Circle.swift
mit
1
// // Circle.swift // CircleBom // // Created by ldjhust on 15/11/26. // Copyright © 2015年 ldj. All rights reserved. // import UIKit class Circle: UIView { var initialFrame = CGRectZero var progress:CGFloat = 0.5 override func drawRect(rect: CGRect) { // 获取当前画布 let offset = initialFrame.width / 3.6 let moveDistance = (initialFrame.width * 1 / 5) * CGFloat(fabs(progress - 0.5) * 2) NSLog ("%f", moveDistance) let originCenter = CGPoint(x: initialFrame.origin.x + initialFrame.width/2, y: initialFrame.origin.y + initialFrame.height/2) let pointA = CGPoint(x: originCenter.x, y: originCenter.y - initialFrame.height/2 + moveDistance) let pointB = CGPoint(x: originCenter.x + initialFrame.width/2, y: originCenter.y) let pointC = CGPoint(x: originCenter.x, y: originCenter.y + initialFrame.height/2 - moveDistance) let pointD = CGPoint(x: originCenter.x - initialFrame.width/2 - moveDistance, y: originCenter.y) let c1 = CGPoint(x: pointA.x + offset, y: pointA.y) let c2 = CGPoint(x: pointB.x, y: pointB.y - offset) let c3 = CGPoint(x: pointB.x, y: pointB.y + offset) let c4 = CGPoint(x: pointC.x + offset, y: pointC.y) let c5 = CGPoint(x: pointC.x - offset, y: pointC.y) let c6 = CGPoint(x: pointD.x, y: pointD.y + offset - moveDistance) let c7 = CGPoint(x: pointD.x, y: pointD.y - offset + moveDistance) let c8 = CGPoint(x: pointA.x - offset, y: pointA.y) let bezierPath = UIBezierPath() // 设置填充颜色 UIColor.redColor().setFill() // 开始画 bezierPath.moveToPoint(pointA) bezierPath.addCurveToPoint(pointB, controlPoint1: c1, controlPoint2: c2) bezierPath.addCurveToPoint(pointC, controlPoint1: c3, controlPoint2: c4) bezierPath.addCurveToPoint(pointD, controlPoint1: c5, controlPoint2: c6) bezierPath.addCurveToPoint(pointA, controlPoint1: c7, controlPoint2: c8) bezierPath.closePath() // 开始填充 bezierPath.fill() } }
02b01797caa131a38a18e4d3cd94bb4e
35.509091
101
0.664343
false
false
false
false
lucasharding/antenna
refs/heads/master
tvOS/Controllers/GuideChannelCollectionViewHeader.swift
gpl-3.0
1
// // GuideChannelCollectionViewHeader.swift // ustvnow-tvos // // Created by Lucas Harding on 2015-09-11. // Copyright © 2015 Lucas Harding. All rights reserved. // import UIKit open class GuideChannelCollectionViewHeader : UICollectionReusableView { var imageView: UIImageView! public override init(frame: CGRect) { super.init(frame: frame) commonInit() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } internal func commonInit() { let imageView = UIImageView() imageView.contentMode = .scaleAspectFit imageView.translatesAutoresizingMaskIntoConstraints = false self.addSubview(imageView) self.imageView = imageView addConstraint(NSLayoutConstraint(item: imageView, attribute: .width, relatedBy: .equal, toItem: imageView, attribute: .height, multiplier: 1.0, constant: 0.0)) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[imageView]-30-|", options: [], metrics: nil, views: ["imageView": imageView])) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-20-[imageView]-20-|", options: [], metrics: nil, views: ["imageView": imageView])) } } open class GuideChannelCollectionViewBackground : UICollectionReusableView { override init(frame: CGRect) { super.init(frame: frame) commonInit() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } internal func commonInit() { let view = UIVisualEffectView(frame: self.bounds) view.effect = UIBlurEffect(style: .dark) view.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight] self.addSubview(view) } }
ce9ccd64db1f647eb4eefd2f0aae81ae
31.189655
167
0.674879
false
false
false
false
ljshj/actor-platform
refs/heads/master
actor-sdk/sdk-core-ios/ActorSDK/Sources/Controllers/Auth/AAAuthOTPViewController.swift
agpl-3.0
2
// // Copyright (c) 2014-2016 Actor LLC. <https://actor.im> // import Foundation import MessageUI public class AAAuthOTPViewController: AAAuthViewController, MFMailComposeViewControllerDelegate { private static let DIAL_SECONDS: Int = 60 let scrollView = UIScrollView() let welcomeLabel = UILabel() let validateLabel = UILabel() let hintLabel = UILabel() let codeField = UITextField() let codeFieldLine = UIView() let haventReceivedCode = UIButton() let transactionHash: String let name: String! let email: String! let phone: String! private var counterTimer: NSTimer! private var dialed: Bool = false private var counter = AAAuthOTPViewController.DIAL_SECONDS public init(email: String, transactionHash: String) { self.transactionHash = transactionHash self.name = nil self.email = email self.phone = nil super.init() } public init(email: String, name: String, transactionHash: String) { self.transactionHash = transactionHash self.name = name self.email = email self.phone = nil super.init() } public init(phone: String, transactionHash: String) { self.transactionHash = transactionHash self.name = nil self.email = nil self.phone = phone super.init() } public init(phone: String, name: String, transactionHash: String) { self.transactionHash = transactionHash self.name = name self.email = nil self.phone = phone super.init() } public required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public override func viewDidLoad() { view.backgroundColor = UIColor.whiteColor() scrollView.keyboardDismissMode = .OnDrag scrollView.scrollEnabled = true scrollView.alwaysBounceVertical = true welcomeLabel.font = UIFont.lightSystemFontOfSize(23) if email != nil { welcomeLabel.text = AALocalized("AuthOTPEmailTitle") } else { welcomeLabel.text = AALocalized("AuthOTPPhoneTitle") } welcomeLabel.textColor = ActorSDK.sharedActor().style.authTitleColor welcomeLabel.textAlignment = .Center validateLabel.font = UIFont.systemFontOfSize(14) if email != nil { validateLabel.text = email } else { validateLabel.text = phone } validateLabel.textColor = ActorSDK.sharedActor().style.authTintColor validateLabel.textAlignment = .Center hintLabel.font = UIFont.systemFontOfSize(14) if email != nil { hintLabel.text = AALocalized("AuthOTPEmailHint") } else { hintLabel.text = AALocalized("AuthOTPPhoneHint") } hintLabel.textColor = ActorSDK.sharedActor().style.authHintColor hintLabel.textAlignment = .Center hintLabel.numberOfLines = 2 hintLabel.lineBreakMode = .ByWordWrapping codeField.font = UIFont.systemFontOfSize(17) codeField.textColor = ActorSDK.sharedActor().style.authTextColor codeField.placeholder = AALocalized("AuthOTPPlaceholder") codeField.keyboardType = .NumberPad codeField.autocapitalizationType = .None codeField.autocorrectionType = .No codeFieldLine.backgroundColor = ActorSDK.sharedActor().style.authSeparatorColor if ActorSDK.sharedActor().supportEmail != nil { haventReceivedCode.setTitle(AALocalized("AuthOTPNoCode"), forState: .Normal) } else { haventReceivedCode.hidden = true } haventReceivedCode.titleLabel?.font = UIFont.systemFontOfSize(14) haventReceivedCode.setTitleColor(ActorSDK.sharedActor().style.authTintColor, forState: .Normal) haventReceivedCode.setTitleColor(ActorSDK.sharedActor().style.authTintColor.alpha(0.64), forState: .Highlighted) haventReceivedCode.setTitleColor(ActorSDK.sharedActor().style.authHintColor, forState: .Disabled) haventReceivedCode.addTarget(self, action: #selector(AAAuthOTPViewController.haventReceivedCodeDidPressed), forControlEvents: .TouchUpInside) scrollView.addSubview(welcomeLabel) scrollView.addSubview(validateLabel) scrollView.addSubview(hintLabel) scrollView.addSubview(codeField) scrollView.addSubview(codeFieldLine) scrollView.addSubview(haventReceivedCode) view.addSubview(scrollView) super.viewDidLoad() } public override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() welcomeLabel.frame = CGRectMake(15, 90 - 66, view.width - 30, 28) validateLabel.frame = CGRectMake(10, 127 - 66, view.width - 20, 17) hintLabel.frame = CGRectMake(10, 154 - 66, view.width - 20, 56) codeField.frame = CGRectMake(20, 228 - 66, view.width - 40, 44) codeFieldLine.frame = CGRectMake(10, 228 + 44 - 66, view.width - 20, 0.5) haventReceivedCode.frame = CGRectMake(20, 297 - 66, view.width - 40, 56) scrollView.frame = view.bounds scrollView.contentSize = CGSizeMake(view.width, 240 - 66) } func haventReceivedCodeDidPressed() { if ActorSDK.sharedActor().supportEmail != nil { if self.email != nil { let emailController = MFMailComposeViewController() emailController.setSubject("Activation code problem (\(self.email))") emailController.setToRecipients([ActorSDK.sharedActor().supportEmail!]) emailController.setMessageBody("Hello, Dear Support!\n\nI can't receive any activation codes to the email: \(self.email).\n\nHope, you will answer soon. Thank you!", isHTML: false) emailController.delegate = self self.presentElegantViewController(emailController) } else if self.phone != nil { let emailController = MFMailComposeViewController() emailController.setSubject("Activation code problem (\(self.phone))") emailController.setToRecipients([ActorSDK.sharedActor().supportEmail!]) emailController.setMessageBody("Hello, Dear Support!\n\nI can't receive any activation codes to the phone: \(self.phone).\n\nHope, you will answer soon. Thank you!", isHTML: false) emailController.delegate = self self.presentElegantViewController(emailController) } } } public func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) { controller.dismissViewControllerAnimated(true, completion: nil) } public override func nextDidTap() { let code = codeField.text!.trim() if code.length == 0 { shakeField() return } let promise = Actor.doValidateCode(code, withTransaction: self.transactionHash) .startUserAction(["EMAIL_CODE_INVALID", "PHONE_CODE_INVALID", "EMAIL_CODE_EXPIRED", "PHONE_CODE_EXPIRED"]) promise.then { (r: ACAuthCodeRes!) -> () in if r.needToSignup { if self.name == nil { self.navigateNext(AAAuthNameViewController(transactionHash: r.transactionHash)) } else { let promise = Actor.doSignupWithName(self.name, withSex: ACSex.UNKNOWN(), withTransaction: r.transactionHash) promise.then { (r: ACAuthRes!) -> () in Actor.doCompleteAuth(r).startUserAction().then { (r: JavaLangBoolean!) -> () in self.codeField.resignFirstResponder() self.onAuthenticated() } } promise.startUserAction() } } else { Actor.doCompleteAuth(r.result).startUserAction().then { (r: JavaLangBoolean!) -> () in self.codeField.resignFirstResponder() self.onAuthenticated() } } } promise.failure { (e: JavaLangException!) -> () in if let rpc = e as? ACRpcException { if rpc.tag == "EMAIL_CODE_INVALID" || rpc.tag == "PHONE_CODE_INVALID" { self.shakeField() } else if rpc.tag == "EMAIL_CODE_EXPIRED" || rpc.tag == "PHONE_CODE_EXPIRED" { AAExecutions.errorWithTag(rpc.tag, rep: nil, cancel: { () -> () in self.navigateBack() }) } } } } private func shakeField() { shakeView(codeField, originalX: 20) shakeView(codeFieldLine, originalX: 10) } public override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if self.phone != nil { updateTimerText() if !dialed { counterTimer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(AAAuthOTPViewController.updateTimer), userInfo: nil, repeats: true) } } } func updateTimer() { counter -= 1 if counter == 0 { dialed = true if counterTimer != nil { counterTimer.invalidate() counterTimer = nil } Actor.doSendCodeViaCall(self.transactionHash) } updateTimerText() } func updateTimerText() { if dialed { if ActorSDK.sharedActor().supportEmail != nil { haventReceivedCode.setTitle(AALocalized("AuthOTPNoCode"), forState: .Normal) haventReceivedCode.hidden = false haventReceivedCode.enabled = true } else { haventReceivedCode.hidden = true } } else { let min = counter / 60 let sec = counter % 60 let minFormatted = min.format("02") let secFormatted = sec.format("02") let time = "\(minFormatted):\(secFormatted)" let text = AALocalized("AuthOTPCallHint") .replace("{app_name}", dest: ActorSDK.sharedActor().appName) .replace("{time}", dest: time) haventReceivedCode.setTitle(text, forState: .Normal) haventReceivedCode.enabled = false haventReceivedCode.hidden = false } } public override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) if counterTimer != nil { counterTimer.invalidate() counterTimer = nil } self.codeField.resignFirstResponder() } }
ba3a5b0e4539863186e9b25c070de842
37.040956
196
0.596896
false
false
false
false
frootloops/swift
refs/heads/master
test/SILGen/downcast_reabstraction.swift
apache-2.0
1
// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s // CHECK-LABEL: sil hidden @_T022downcast_reabstraction19condFunctionFromAnyyypF // CHECK: checked_cast_addr_br take_always Any in [[IN:%.*]] : $*Any to () -> () in [[OUT:%.*]] : $*@callee_guaranteed (@in ()) -> @out (), [[YES:bb[0-9]+]], [[NO:bb[0-9]+]] // CHECK: [[YES]]: // CHECK: [[ORIG_VAL:%.*]] = load [take] [[OUT]] // CHECK: [[REABSTRACT:%.*]] = function_ref @_T0ytytIegir_Ieg_TR // CHECK: [[SUBST_VAL:%.*]] = partial_apply [callee_guaranteed] [[REABSTRACT]]([[ORIG_VAL]]) func condFunctionFromAny(_ x: Any) { if let f = x as? () -> () { f() } } // CHECK-LABEL: sil hidden @_T022downcast_reabstraction21uncondFunctionFromAnyyypF : $@convention(thin) (@in Any) -> () { // CHECK: unconditional_checked_cast_addr Any in [[IN:%.*]] : $*Any to () -> () in [[OUT:%.*]] : $*@callee_guaranteed (@in ()) -> @out () // CHECK: [[ORIG_VAL:%.*]] = load [take] [[OUT]] // CHECK: [[REABSTRACT:%.*]] = function_ref @_T0ytytIegir_Ieg_TR // CHECK: [[SUBST_VAL:%.*]] = partial_apply [callee_guaranteed] [[REABSTRACT]]([[ORIG_VAL]]) // CHECK: [[BORROW:%.*]] = begin_borrow [[SUBST_VAL]] // CHECK: apply [[BORROW]]() // CHECK: end_borrow [[BORROW]] from [[SUBST_VAL]] // CHECK: destroy_value [[SUBST_VAL]] func uncondFunctionFromAny(_ x: Any) { (x as! () -> ())() }
adfe0a4836dcfc5e600f676b31158a96
52.851852
181
0.550206
false
false
false
false
andrea-prearo/SwiftExamples
refs/heads/master
RegionMonitor/RegionMonitor/RegionNotificationsTableViewController.swift
mit
1
// // RegionNotificationsTableViewController.swift // RegionMonitor // // Created by Andrea Prearo on 5/24/15. // Copyright (c) 2015 Andrea Prearo. All rights reserved. // import UIKit let RegionNotificationsTableViewCellId = "RegionNotificationsTableViewCell" class RegionNotificationsTableViewController: UITableViewController { var regionNotifications: [RegionNotification]? override func viewDidLoad() { super.viewDidLoad() title = NSLocalizedString("Region Notifications", comment: "Region Notifications") regionNotifications = RegionNotificationsStore.sharedInstance.storedItems regionNotifications?.sort(by: { $0.timestamp.timeIntervalSince1970 > $1.timestamp.timeIntervalSince1970 }) NotificationCenter.default.addObserver(self, selector: #selector(RegionNotificationsTableViewController.regionNotificationsItemsDidChange(_:)), name: NSNotification.Name(rawValue: RegionNotificationItemsDidChangeNotification), object: nil) } // MARK: UITableViewDataSource override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if regionNotifications != nil { return regionNotifications!.count } return 0 } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 66.0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: RegionNotificationsTableViewCellId, for: indexPath) as! RegionNotificationCell let row = (indexPath as NSIndexPath).row let regionNotification = regionNotifications?[row] cell.timestamp.text = regionNotification?.displayTimestamp() cell.status.text = regionNotification?.displayAppStatus() cell.message.text = regionNotification?.message cell.event.text = regionNotification?.displayEvent() return cell } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { switch editingStyle { case .delete: regionNotifications?.remove(at: (indexPath as NSIndexPath).row) tableView.deleteRows(at: [indexPath], with: .fade) default: return } } // MARK: NSNotificationCenter Events @objc func regionNotificationsItemsDidChange(_ notification: Notification) { regionNotifications = RegionNotificationsStore.sharedInstance.storedItems regionNotifications?.sort(by: { $0.timestamp.timeIntervalSince1970 > $1.timestamp.timeIntervalSince1970 }) DispatchQueue.main.async { self.tableView.reloadData() } } }
337b64935c2f8198869bb737cbe53318
37.213333
143
0.712142
false
false
false
false
inamiy/VTree
refs/heads/master
Tests/Fixtures/VPhantom.swift
mit
1
import VTree import Flexbox /// Phantom type for `VTree` without `Message` type (for testing). public final class VPhantom<👻>: VTree { public let key: Key? public let props: [String: Any] = [:] // NOTE: `Segmentation fault: 11` if removing this line public let flexbox: Flexbox.Node? = nil public let children: [AnyVTree<NoMsg>] public init( key: Key? = nil, children: [AnyVTree<NoMsg>] = [] ) { self.key = key self.children = children } public func createView<Msg2: Message>(_ msgMapper: @escaping (NoMsg) -> Msg2) -> View { let view = View() for child in self.children { view.addSubview(child.createView(msgMapper)) } return view } }
7ab36bab7d31c3cf62cde398db27fe02
23.709677
98
0.588773
false
false
false
false
epodkorytov/OCTextInput
refs/heads/master
OCTextInput/Classes/OCTextEdit.swift
mit
1
import UIKit final internal class OCTextEdit: UITextView { weak var textInputDelegate: TextInputDelegate? override init(frame: CGRect, textContainer: NSTextContainer?) { super.init(frame: frame, textContainer: textContainer) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } fileprivate func setup() { delegate = self } override func resignFirstResponder() -> Bool { return super.resignFirstResponder() } } extension OCTextEdit: TextInput { var currentText: String? { get { return text } set { self.text = newValue } } var textAttributes: [NSAttributedString.Key: Any] { get { return typingAttributes } set { self.typingAttributes = textAttributes } } var currentSelectedTextRange: UITextRange? { get { return self.selectedTextRange } set { self.selectedTextRange = newValue } } public var currentBeginningOfDocument: UITextPosition? { return self.beginningOfDocument } func changeReturnKeyType(with newReturnKeyType: UIReturnKeyType) { returnKeyType = newReturnKeyType } func currentPosition(from: UITextPosition, offset: Int) -> UITextPosition? { return position(from: from, offset: offset) } } extension OCTextEdit: UITextViewDelegate { func textViewDidBeginEditing(_ textView: UITextView) { textInputDelegate?.textInputDidBeginEditing(textInput: self) } func textViewDidEndEditing(_ textView: UITextView) { textInputDelegate?.textInputDidEndEditing(textInput: self) } func textViewDidChange(_ textView: UITextView) { textInputDelegate?.textInputDidChange(textInput: self) } func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { if text == "\n" { return textInputDelegate?.textInputShouldReturn(textInput: self) ?? true } return textInputDelegate?.textInput(textInput: self, shouldChangeCharactersInRange: range, replacementString: text) ?? true } func textViewShouldBeginEditing(_ textView: UITextView) -> Bool { return textInputDelegate?.textInputShouldBeginEditing(textInput: self) ?? true } func textViewShouldEndEditing(_ textView: UITextView) -> Bool { return textInputDelegate?.textInputShouldEndEditing(textInput: self) ?? true } }
d9c14df952405586b2e59fe969a21d83
28.953488
131
0.661491
false
false
false
false