repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
apple/swift-syntax
Sources/SwiftDiagnostics/FixIt.swift
1
2121
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// import SwiftSyntax /// Types conforming to this protocol represent Fix-It messages that can be /// shown to the client. /// The messages should describe the change that the Fix-It will perform public protocol FixItMessage { /// The Fix-It message that should be displayed in the client. var message: String { get } /// See ``MessageID``. var fixItID: MessageID { get } } /// A Fix-It that can be applied to resolve a diagnostic. public struct FixIt { public struct Changes: ExpressibleByArrayLiteral { public var changes: [Change] public init(changes: [Change]) { self.changes = changes } public init(arrayLiteral elements: FixIt.Change...) { self.init(changes: elements) } public init(combining: [Changes]) { self.init(changes: combining.flatMap(\.changes)) } } public enum Change { /// Replace `oldNode` by `newNode`. case replace(oldNode: Syntax, newNode: Syntax) /// Replace the leading trivia on the given token case replaceLeadingTrivia(token: TokenSyntax, newTrivia: Trivia) /// Replace the trailing trivia on the given token case replaceTrailingTrivia(token: TokenSyntax, newTrivia: Trivia) } /// A description of what this Fix-It performs. public let message: FixItMessage /// The changes that need to be performed when the Fix-It is applied. public let changes: Changes public init(message: FixItMessage, changes: Changes) { assert(!changes.changes.isEmpty, "A Fix-It must have at least one change associated with it") self.message = message self.changes = changes } }
apache-2.0
7e416cb8dbcec9882e210b426127043e
31.136364
97
0.655351
4.56129
false
false
false
false
s4cha/Stevia
Tests/SteviaTests/FlexibleMarginTests.swift
3
17426
// // FlexibleMarginTests.swift // Stevia // // Created by Sacha Durand Saint Omer on 21/02/16. // Copyright © 2016 Sacha Durand Saint Omer. All rights reserved. // import XCTest import Stevia class FlexibleMarginTests: XCTestCase { var win: UIWindow! var ctrler: UIViewController! var v: UIView! override func setUp() { super.setUp() win = UIWindow(frame: UIScreen.main.bounds) ctrler = UIViewController() win.rootViewController = ctrler v = UIView() ctrler.view.subviews { v! } v.size(100.0) } override func tearDown() { super.tearDown() } /// Todo stress test by pushing views func testGreaterTopDouble() { v.top(>=Double(23)) ctrler.view.layoutIfNeeded() XCTAssertEqual(v.frame.origin.y, 23, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.origin.x, 0, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.width, 100, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.height, 100, accuracy: CGFloat(Float.ulpOfOne)) } func testGreaterTopCGFloat() { v.top(>=CGFloat(23)) ctrler.view.layoutIfNeeded() XCTAssertEqual(v.frame.origin.y, 23, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.origin.x, 0, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.width, 100, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.height, 100, accuracy: CGFloat(Float.ulpOfOne)) } func testGreaterTopInt() { v.top(>=Int(23)) ctrler.view.layoutIfNeeded() XCTAssertEqual(v.frame.origin.y, 23, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.origin.x, 0, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.width, 100, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.height, 100, accuracy: CGFloat(Float.ulpOfOne)) } func testGreaterBottom() { v.bottom(>=45) ctrler.view.layoutIfNeeded() XCTAssertEqual(v.frame.origin.y, ctrler.view.frame.height - v.frame.height - 45, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.origin.x, 0, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.width, 100, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.height, 100, accuracy: CGFloat(Float.ulpOfOne)) } func testGreaterLeft() { v.left(>=23) ctrler.view.layoutIfNeeded() XCTAssertEqual(v.frame.origin.y, 0, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.origin.x, 23, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.width, 100, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.height, 100, accuracy: CGFloat(Float.ulpOfOne)) } func testGreaterLeading() { v.leading(>=23) ctrler.view.layoutIfNeeded() XCTAssertEqual(v.frame.origin.y, 0, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.origin.x, 23, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.width, 100, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.height, 100, accuracy: CGFloat(Float.ulpOfOne)) } func testGreaterLeadingRTL() { ctrler.view.semanticContentAttribute = .forceRightToLeft v.leading(>=23) ctrler.view.layoutIfNeeded() XCTAssertEqual(v.frame.origin.y, 0, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.origin.x, ctrler.view.frame.width - v.frame.width - 23, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.width, 100, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.height, 100, accuracy: CGFloat(Float.ulpOfOne)) } func testGreaterRight() { v.right(>=74) ctrler.view.layoutIfNeeded() XCTAssertEqual(v.frame.origin.y, 0, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.origin.x, ctrler.view.frame.width - v.frame.width - 74, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.width, 100, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.height, 100, accuracy: CGFloat(Float.ulpOfOne)) } func testGreaterTrailing() { v.trailing(>=74) ctrler.view.layoutIfNeeded() XCTAssertEqual(v.frame.origin.y, 0, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.origin.x, ctrler.view.frame.width - v.frame.width - 74, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.width, 100, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.height, 100, accuracy: CGFloat(Float.ulpOfOne)) } func testGreaterTrailingRTL() { ctrler.view.semanticContentAttribute = .forceRightToLeft v.trailing(>=74) ctrler.view.layoutIfNeeded() XCTAssertEqual(v.frame.origin.y, 0, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.origin.x, 74, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.width, 100, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.height, 100, accuracy: CGFloat(Float.ulpOfOne)) } func testLessTopDouble() { v.top(<=Double(23)) ctrler.view.layoutIfNeeded() XCTAssertEqual(v.frame.origin.y, 23, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.origin.x, 0, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.width, 100, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.height, 100, accuracy: CGFloat(Float.ulpOfOne)) } func testLessTopCGFloat() { v.top(<=CGFloat(23)) ctrler.view.layoutIfNeeded() XCTAssertEqual(v.frame.origin.y, 23, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.origin.x, 0, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.width, 100, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.height, 100, accuracy: CGFloat(Float.ulpOfOne)) } func testLessTopInt() { v.top(<=Int(23)) ctrler.view.layoutIfNeeded() XCTAssertEqual(v.frame.origin.y, 23, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.origin.x, 0, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.width, 100, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.height, 100, accuracy: CGFloat(Float.ulpOfOne)) } func testLessBottom() { v.bottom(<=45) ctrler.view.layoutIfNeeded() XCTAssertEqual(v.frame.origin.y, ctrler.view.frame.height - v.frame.height - 45, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.origin.x, 0, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.width, 100, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.height, 100, accuracy: CGFloat(Float.ulpOfOne)) } func testLessLeft() { v.left(<=23) ctrler.view.layoutIfNeeded() XCTAssertEqual(v.frame.origin.y, 0, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.origin.x, 23, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.width, 100, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.height, 100, accuracy: CGFloat(Float.ulpOfOne)) } func testLessLeading() { v.leading(<=23) ctrler.view.layoutIfNeeded() XCTAssertEqual(v.frame.origin.y, 0, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.origin.x, 23, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.width, 100, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.height, 100, accuracy: CGFloat(Float.ulpOfOne)) } func testLessLeadingRTL() { ctrler.view.semanticContentAttribute = .forceRightToLeft v.leading(<=23) ctrler.view.layoutIfNeeded() XCTAssertEqual(v.frame.origin.y, 0, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.origin.x, ctrler.view.frame.width - v.frame.width - 23, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.width, 100, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.height, 100, accuracy: CGFloat(Float.ulpOfOne)) } func testLessLeftOperator() { |-(<=23)-v ctrler.view.layoutIfNeeded() XCTAssertEqual(v.frame.origin.y, 0, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.origin.x, 23, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.width, 100, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.height, 100, accuracy: CGFloat(Float.ulpOfOne)) } func testLessLeftOperatorRTL() { ctrler.view.semanticContentAttribute = .forceRightToLeft |-(<=23)-v ctrler.view.layoutIfNeeded() XCTAssertEqual(v.frame.origin.y, 0, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.origin.x, ctrler.view.frame.width - v.frame.width - 23, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.width, 100, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.height, 100, accuracy: CGFloat(Float.ulpOfOne)) } func testLessRight() { v.right(<=74) ctrler.view.layoutIfNeeded() XCTAssertEqual(v.frame.origin.y, 0, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.origin.x, ctrler.view.frame.width - v.frame.width - 74, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.width, 100, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.height, 100, accuracy: CGFloat(Float.ulpOfOne)) } func testLessTrailing() { v.trailing(<=74) ctrler.view.layoutIfNeeded() XCTAssertEqual(v.frame.origin.y, 0, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.origin.x, ctrler.view.frame.width - v.frame.width - 74, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.width, 100, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.height, 100, accuracy: CGFloat(Float.ulpOfOne)) } func testLessTrailingRTL() { ctrler.view.semanticContentAttribute = .forceRightToLeft v.trailing(<=74) ctrler.view.layoutIfNeeded() XCTAssertEqual(v.frame.origin.y, 0, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.origin.x, 74, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.width, 100, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.height, 100, accuracy: CGFloat(Float.ulpOfOne)) } func testLessRightOperator() { v-(<=74)-| ctrler.view.layoutIfNeeded() XCTAssertEqual(v.frame.origin.y, 0, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.origin.x, ctrler.view.frame.width - v.frame.width - 74, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.width, 100, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.height, 100, accuracy: CGFloat(Float.ulpOfOne)) } func testLessRightOperatorRTL() { ctrler.view.semanticContentAttribute = .forceRightToLeft v-(<=74)-| ctrler.view.layoutIfNeeded() XCTAssertEqual(v.frame.origin.y, 0, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.origin.x, 74, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.width, 100, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v.frame.height, 100, accuracy: CGFloat(Float.ulpOfOne)) } func testMarginGreaterBetweenTwoViews() { let v1 = UIView() let v2 = UIView() v.removeFromSuperview() ctrler.view.subviews { v1; v2 } for view in ctrler.view.subviews { XCTAssertEqual(view.frame.origin.y, 0, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(view.frame.origin.x, 0, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(view.frame.width, 0, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(view.frame.height, 0, accuracy: CGFloat(Float.ulpOfOne)) } |v1.width(10)-(>=25)-v2 ctrler.view.layoutIfNeeded() XCTAssertEqual(v1.frame.origin.y, 0, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v1.frame.origin.x, 0, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v1.frame.width, 10, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v1.frame.height, 0, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v2.frame.origin.y, 0, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v2.frame.origin.x, 35, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v2.frame.width, 0, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v2.frame.height, 0, accuracy: CGFloat(Float.ulpOfOne)) } func testMarginGreaterBetweenTwoViewsRTL() { ctrler.view.semanticContentAttribute = .forceRightToLeft let v1 = UIView() let v2 = UIView() v.removeFromSuperview() ctrler.view.subviews { v1 v2 } for view in ctrler.view.subviews { XCTAssertEqual(view.frame.origin.y, 0, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(view.frame.origin.x, 0, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(view.frame.width, 0, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(view.frame.height, 0, accuracy: CGFloat(Float.ulpOfOne)) } |v1.width(10)-(>=25)-v2 ctrler.view.layoutIfNeeded() XCTAssertEqual(v1.frame.origin.y, 0, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v1.frame.origin.x, ctrler.view.frame.width - 10, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v1.frame.width, 10, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v1.frame.height, 0, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v2.frame.origin.y, 0, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v2.frame.origin.x, ctrler.view.frame.width - v1.frame.width - 25, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v2.frame.width, 0, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v2.frame.height, 0, accuracy: CGFloat(Float.ulpOfOne)) } func testMarginLesserBetweenTwoViews() { let v1 = UIView() let v2 = UIView() v.removeFromSuperview() ctrler.view.subviews { v1 v2 } for view in ctrler.view.subviews { XCTAssertEqual(view.frame.origin.y, 0, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(view.frame.origin.x, 0, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(view.frame.width, 0, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(view.frame.height, 0, accuracy: CGFloat(Float.ulpOfOne)) } |v1.width(10)-(<=25)-v2 ctrler.view.layoutIfNeeded() XCTAssertEqual(v1.frame.origin.y, 0, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v1.frame.origin.x, 0, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v1.frame.width, 10, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v1.frame.height, 0, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v2.frame.origin.y, 0, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v2.frame.origin.x, 35, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v2.frame.width, 0, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v2.frame.height, 0, accuracy: CGFloat(Float.ulpOfOne)) } func testMarginLesserBetweenTwoViewsRTL() { ctrler.view.semanticContentAttribute = .forceRightToLeft let v1 = UIView() let v2 = UIView() v.removeFromSuperview() ctrler.view.subviews { v1 v2 } for view in ctrler.view.subviews { XCTAssertEqual(view.frame.origin.y, 0, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(view.frame.origin.x, 0, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(view.frame.width, 0, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(view.frame.height, 0, accuracy: CGFloat(Float.ulpOfOne)) } |v1.width(10)-(<=25)-v2 ctrler.view.layoutIfNeeded() XCTAssertEqual(v1.frame.origin.y, 0, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v1.frame.origin.x, ctrler.view.frame.width - 10, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v1.frame.width, 10, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v1.frame.height, 0, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v2.frame.origin.y, 0, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v2.frame.origin.x, ctrler.view.frame.width - v1.frame.width - 25, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v2.frame.width, 0, accuracy: CGFloat(Float.ulpOfOne)) XCTAssertEqual(v2.frame.height, 0, accuracy: CGFloat(Float.ulpOfOne)) } }
mit
1a27644c27cd9046bd4c90981cdb61c6
45.097884
123
0.653544
4.045739
false
true
false
false
zerozheng/ZZQRCode
Source/QRImageDetector.swift
1
1003
// // QRImageDetector.swift // QRCode // // Created by zero on 17/2/7. // Copyright © 2017年 zero. All rights reserved. // import Foundation import CoreImage import UIKit public class QRImageDetector { public class func detectImage(image: UIImage, completeHandle:((_ result:String?, _ error: Bool)->())?) { guard let detector = CIDetector(ofType: CIDetectorTypeQRCode, context: nil, options: [CIDetectorAccuracy:CIDetectorAccuracyHigh]), let ciImage: CIImage = CIImage(image: image) else { if let _ = completeHandle { completeHandle!(nil,true) } return } guard let feature: CIQRCodeFeature = detector.features(in: ciImage).first as? CIQRCodeFeature else { if let _ = completeHandle { completeHandle!(nil,true) } return } if let _ = completeHandle { completeHandle!(feature.messageString,false) } } }
mit
0d8fcbca93aaab2456224b42c1592db9
28.411765
190
0.599
4.62963
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/Platform/Sources/PlatformKit/Services/SecureChannel/SecureChannelMessageService.swift
1
2619
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import CommonCryptoKit public enum MessageError: LocalizedError, Equatable { case decryptionFailed case encryptionFailed case jsonEncodingError public var errorDescription: String? { switch self { case .decryptionFailed: return "Message Error: Decryption failed." case .encryptionFailed: return "Message Error: Encryption failed." case .jsonEncodingError: return "Message Error: Error encoding JSON data." } } } final class SecureChannelMessageService { func decryptMessage( _ message: String, publicKey: Data, deviceKey: Data ) -> Result<SecureChannel.BrowserMessage, MessageError> { Result { let channelKey = try ECDH.derive(priv: deviceKey, pub: publicKey).get() let decrypted = try ECDH.decrypt(priv: channelKey, payload: Data(hex: message)).get() let decoder = JSONDecoder() return try decoder.decode(SecureChannel.BrowserMessage.self, from: decrypted) } .replaceError(with: MessageError.decryptionFailed) } func buildMessage<Message: Encodable>( message: Message, channelId: String, success: Bool, publicKey: Data, deviceKey: Data ) -> Result<SecureChannel.PairingResponse, MessageError> { Result { try JSONEncoder().encode(message) } .replaceError(with: .jsonEncodingError) .flatMap { serialisedData in buildMessage( data: serialisedData, channelId: channelId, success: success, publicKey: publicKey, deviceKey: deviceKey ) } } func buildMessage( data: Data, channelId: String, success: Bool, publicKey: Data, deviceKey: Data ) -> Result<SecureChannel.PairingResponse, MessageError> { Result { let devicePublicKey = try ECDH.publicFromPrivate(priv: deviceKey).get() let channelKey = try ECDH.derive(priv: deviceKey, pub: publicKey).get() let encrypted = try ECDH.encrypt(priv: channelKey, payload: data).get() return SecureChannel.PairingResponse( channelId: channelId, pubkey: devicePublicKey.hexValue, success: success, message: encrypted.hexValue ) } .replaceError(with: MessageError.encryptionFailed) } }
lgpl-3.0
bc1d384f42fc869773392a8d4232718e
32.564103
97
0.598167
5.015326
false
false
false
false
bjarnel/arkit-tictactoe
AR-TicTacToe/GameState.swift
1
4504
// // GameState.swift // AR-TicTacToe // // Created by Bjarne Møller Lundgren on 20/06/2017. // Copyright © 2017 Bjarne Møller Lundgren. All rights reserved. // import Foundation typealias GamePosition = (x:Int, y:Int) enum GamePlayerType:String { case human = "human" case ai = "ai" } enum GameMode:String { case put = "put" case move = "move" } enum GamePlayer:String { case x = "x" case o = "o" } /// we have made the game actions generic in order to make it easier to implement the AI enum GameAction { case put(at:GamePosition) case move(from:GamePosition, to:GamePosition) } /// our completely immutable implementation of Tic-Tac-Toe struct GameState { let currentPlayer:GamePlayer let mode:GameMode let board:[[String]] /// When you create a new game (GameState) you get a certain default state, which you cant /// modify in any way init() { self.init(currentPlayer: arc4random_uniform(2) == 0 ? .x : .o, // random start player mode: .put, // start mode is to put/drop pieces board: [["","",""],["","",""],["","",""]]) // board is empty } /// this private init allows the perform func to return a new GameState private init(currentPlayer:GamePlayer, mode:GameMode, board:[[String]]) { self.currentPlayer = currentPlayer self.mode = mode self.board = board } // perform action in the game, if successful returns new GameState func perform(action:GameAction) -> GameState? { switch action { case .put(let at): // are we in "put" mode and is the destination square empty? guard case .put = mode, board[at.x][at.y] == "" else { return nil } // generate a new board state var newBoard = board newBoard[at.x][at.y] = currentPlayer.rawValue // determine how many pieces has been placed let numberOfSquaresUsed = newBoard.reduce(0, { return $1.reduce($0, { return $0 + ($1 != "" ? 1 : 0) }) }) // generate new game state and return it return GameState(currentPlayer: currentPlayer == .x ? .o : .x, mode: numberOfSquaresUsed >= 6 ? .move : .put, board: newBoard) case .move(let from, let to): // are we in "move" mode and does the from piece match the current player // and is the destination square empty? guard case .move = mode, board[from.x][from.y] == currentPlayer.rawValue, board[to.x][to.y] == "" else { return nil } // generate a new board state var newBoard = board newBoard[from.x][from.y] = "" newBoard[to.x][to.y] = currentPlayer.rawValue // generate new game state and return it return GameState(currentPlayer: currentPlayer == .x ? .o : .x, mode: .move, board: newBoard) } } // is there a winner? var currentWinner:GamePlayer? { get { // checking lines for l in 0..<3 { if board[l][0] != "" && board[l][0] == board[l][1] && board[l][0] == board[l][2] { // horizontal line victory! return GamePlayer(rawValue: board[l][0]) } if board[0][l] != "" && board[0][l] == board[1][l] && board[0][l] == board[2][l] { // vertical line victory! return GamePlayer(rawValue: board[0][l]) } } // accross check if board[0][0] != "" && board[0][0] == board[1][1] && board[0][0] == board[2][2] { // top left - bottom right victory! return GamePlayer(rawValue: board[0][0]) } if board[0][2] != "" && board[0][2] == board[1][1] && board[0][2] == board[2][0] { // top right - bottom left victory! return GamePlayer(rawValue: board[0][2]) } return nil } } }
apache-2.0
386ac47872e7ea5f5dec15fdb6fb2fa9
32.842105
94
0.48878
4.319578
false
false
false
false
Daltron/NotificationBanner
Example/NotificationBanner/AppDelegate.swift
1
2798
// // AppDelegate.swift // NotificationBanner // // Created by Daltron on 03/18/2017. // Copyright (c) 2017 Daltron. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { let navigationController = UINavigationController(rootViewController: ExampleViewController()) let tabBarController = UITabBarController() tabBarController.viewControllers = [navigationController] let tab = tabBarController.tabBar.items![0] tab.image = #imageLiteral(resourceName: "tab_bar_icon").withRenderingMode(.alwaysOriginal) tab.imageInsets = UIEdgeInsets(top: 6, left: 0, bottom: -6, right: 0) tab.title = nil window = UIWindow(frame: UIScreen.main.bounds) window?.backgroundColor = .white window?.rootViewController = tabBarController window?.makeKeyAndVisible() return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
d8e503ecf267f8802cb2d7d3414de16b
46.423729
285
0.732666
5.596
false
false
false
false
zhenghuadong11/firstGitHub
旅游app_useSwift/旅游app_useSwift/MYFirstPageCell.swift
1
13529
// // MYFirstPageCell.swift // 旅游app_useSwift // // Created by zhenghuadong on 16/4/17. // Copyright © 2016年 zhenghuadong. All rights reserved. // import Foundation import UIKit import CoreLocation let cellID="MYFirstPageCell" class MYFirstPageCell:UITableViewCell,CLLocationManagerDelegate{ weak var _tableViewImageView: UIImageView? weak var _nameLabel: UILabel? weak var _one_wordLabel: UILabel? weak var _needMoneyLabel: UILabel? var _collectButton = UIButton() var _luckeyButton = UIButton() weak var _viewController:UIViewController? let lineGray = UIView() let distantLabel = UILabel() var _geocoder:CLGeocoder! = CLGeocoder() var _diffrentWithAgoModel:MYDiffrentWithAgoModel{ set{ self._diffrentWithAgoModelTmp = newValue self.setUpSubViewWithDiffrentWithAgoModel(newValue) } get { return _diffrentWithAgoModelTmp! } } lazy var _LM:CLLocationManager! = { let LM:CLLocationManager = CLLocationManager() LM.distanceFilter = 100 if Float.init(UIDevice.currentDevice().systemVersion)>8.0 { LM.requestAlwaysAuthorization() } return LM }() var _diffrentWithAgoModelTmp:MYDiffrentWithAgoModel? func setUpSubViewWithDiffrentWithAgoModel(diffrentWithAgoModel:MYDiffrentWithAgoModel) -> Void { _tableViewImageView?.image = UIImage(named: (diffrentWithAgoModel.picture!)) _nameLabel?.text = diffrentWithAgoModel.name _nameLabel?.textColor = UIColor.init(red: CGFloat(3*16+3)/256, green: CGFloat(3*16+3)/256, blue: CGFloat(3*16+3)/256, alpha: 1.0) let attributes:[String:AnyObject] = [NSFontAttributeName:UIFont.systemFontOfSize(14),NSForegroundColorAttributeName:UIColor.grayColor()] let attributeString = NSAttributedString.init(string:(diffrentWithAgoModel.oneWordToRecommend)! , attributes: attributes) _one_wordLabel?.attributedText = attributeString let attributes1:[String:AnyObject] = [NSFontAttributeName:UIFont.systemFontOfSize(10),NSForegroundColorAttributeName:UIColor.init(red: (CGFloat)(7*16+12)/256, green: (CGFloat)(12*16+13)/256, blue: (CGFloat)(7*16+12)/256, alpha: 1.0)] var attributedString1 = NSMutableAttributedString.init(string: "¥", attributes: attributes1) let attributes2:[String:AnyObject] = [NSFontAttributeName:UIFont.systemFontOfSize(20),NSForegroundColorAttributeName:UIColor.init(red: (CGFloat)(7*16+12)/256, green: (CGFloat)(12*16+13)/256, blue: (CGFloat)(7*16+12)/256, alpha: 1.0)] let attributeString2 = NSAttributedString.init(string:(diffrentWithAgoModel.money)! , attributes: attributes2) attributedString1.appendAttributedString(attributeString2) _needMoneyLabel?.attributedText = attributedString1 self.distantLabel.textAlignment = NSTextAlignment.Right self.distantLabel.textColor = UIColor.orangeColor() self._LM.delegate = self self._LM.startUpdatingLocation() } static func firstPageCellWithTableView(tableView:UITableView) -> MYFirstPageCell { var cell:MYFirstPageCell? = tableView.dequeueReusableCellWithIdentifier(cellID) as? MYFirstPageCell if cell == nil { cell = MYFirstPageCell(style: UITableViewCellStyle.Default , reuseIdentifier: cellID) } return cell! } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.contentView.addSubview(self.lineGray) lineGray.backgroundColor = UIColor.grayColor() lineGray.alpha = 0.5 let tableViewImageView = UIImageView() self.selectionStyle = UITableViewCellSelectionStyle.None self.contentView.addSubview(tableViewImageView) _tableViewImageView = tableViewImageView let nameLabel = UILabel() self.contentView.addSubview(nameLabel) _nameLabel = nameLabel let one_wordLabel = UILabel() self.contentView.addSubview(one_wordLabel) _one_wordLabel = one_wordLabel let needMoneyLabel = UILabel() self.contentView.addSubview(needMoneyLabel) _needMoneyLabel = needMoneyLabel self.contentView.addSubview(_collectButton) _collectButton.setImage(UIImage.init(named: "collect_none"), forState: UIControlState.Normal) _collectButton.setImage(UIImage.init(named: "collect"), forState: UIControlState.Selected) _collectButton.addTarget(self, action: #selector(collectButtonClick), forControlEvents: UIControlEvents.TouchUpInside) self.contentView.addSubview(_luckeyButton) _luckeyButton.setImage(UIImage.init(named: "turntable_none"), forState: UIControlState.Normal) _luckeyButton.setImage(UIImage.init(named: "turntable"), forState: UIControlState.Selected) _luckeyButton.addTarget(self, action: #selector(luckeyButtonClick), forControlEvents: UIControlEvents.TouchUpInside) self.contentView.addSubview(self.distantLabel) } func collectButtonClick() -> Void { if MYMineModel._shareMineModel.name == nil { _loginClick(_viewController!) return } if _collectButton.selected == true { let path:String? = NSBundle.mainBundle().pathForResource("collect", ofType: "plist") var array = NSArray.init(contentsOfFile: path!) as? Array<[String:AnyObject]> for var i1 in 0..<array!.count { var dict = array![i1] if dict["user"] as! String == MYMineModel._shareMineModel.name && dict["num"] as! String == _diffrentWithAgoModel.num { array?.removeAtIndex(i1) ( array as? NSArray)?.writeToFile(path!, atomically: true) _collectButton.selected = false return } } } else { let path:String? = NSBundle.mainBundle().pathForResource("collect", ofType: "plist") var array = NSArray.init(contentsOfFile: path!) as? Array<[String:AnyObject]> let dict:[String:AnyObject] = ["name":(_diffrentWithAgoModel.name)!,"num":_diffrentWithAgoModel.num!,"picture":(_diffrentWithAgoModel.picture)!,"oneWordToRecommend":(_diffrentWithAgoModel.oneWordToRecommend)!,"user":MYMineModel._shareMineModel.name!] array?.append(dict) (array as? NSArray)?.writeToFile(path!, atomically: true) _collectButton.selected = true } } func luckeyButtonState() -> Void { let path:String? = NSBundle.mainBundle().pathForResource("lukeyScenic", ofType: "plist") var array = NSArray.init(contentsOfFile: path!) as? Array<[String:AnyObject]> if array == nil || array?.count == 0 { self._luckeyButton.selected = false return } for var i1 in 0..<array!.count { var dict = array![i1] if dict["num"] as! String == _diffrentWithAgoModel.num { self._luckeyButton.selected = true return } } self._luckeyButton.selected = false return } func collectButtonState() -> Void { let path:String? = NSBundle.mainBundle().pathForResource("collect", ofType: "plist") var array = NSArray.init(contentsOfFile: path!) as? Array<[String:AnyObject]> for var i1 in 0..<array!.count { var dict = array![i1] if dict["user"] as! String == MYMineModel._shareMineModel.name && dict["num"] as! String == _diffrentWithAgoModel.num { _collectButton.selected = true return } } _collectButton.selected = false return } func luckeyButtonClick() -> Void { if _luckeyButton.selected == false { let path = NSBundle.mainBundle().pathForResource("lukeyScenic", ofType: "plist") var array:Array<[String:AnyObject]>? = (NSArray.init(contentsOfFile: path!) as? Array<[String:AnyObject]>) if array == nil { array = Array<[String:AnyObject]>() } if array!.count > 5 { return; } let dict:[String:AnyObject] = ["num":_diffrentWithAgoModel.num!,"name":_diffrentWithAgoModel.name!,"picture":_diffrentWithAgoModel.picture!] array! .append(dict) (array as! NSArray) .writeToFile(path!, atomically: true) _luckeyButton.selected = !_luckeyButton.selected } else { let path = NSBundle.mainBundle().pathForResource("lukeyScenic", ofType: "plist") var array = NSArray.init(contentsOfFile: path!) as! Array<[String:AnyObject]> var index:Int = 0 for var dict in array { if dict["num"] as! String == _diffrentWithAgoModel.num { array.removeAtIndex(index) } index += 1 } (array as! NSArray) .writeToFile(path!, atomically: true) _luckeyButton.selected = !_luckeyButton.selected } } func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let startLocation:CLLocation = locations.first! _geocoder.geocodeAddressString(self._diffrentWithAgoModel.spot!) { (placeMarks:[CLPlacemark]?,error: NSError?) in if placeMarks == nil { return } let placemark :CLPlacemark = (placeMarks?.first!)! var distance:CLLocationDistance = startLocation.distanceFromLocation(placemark.location!) var distanceInt = Int.init(distance) distance = Double.init(distanceInt) if distance<1000.0 { self.distantLabel.text = distance.description+"米" } else { distanceInt/=1000 self.distantLabel.text = distanceInt.description+"千米" } } } func locationManager(manager: CLLocationManager, didFailWithError error: NSError) { print("error") } override func layoutSubviews() { _tableViewImageView?.frame = CGRectMake(10, 10, self.frame.width * 0.25, self.frame.height - 20) self.lineGray.snp_makeConstraints { (make) in make.left.bottom.right.equalTo(self.contentView) make.height.equalTo(1) } _nameLabel?.snp_makeConstraints(closure: { (make) in make.left.equalTo(_tableViewImageView!.snp_right).offset(10) make.top.equalTo(self.contentView.snp_top).offset(10) make.right.equalTo(self.contentView.snp_right).offset(-50) make.height.equalTo(self.contentView.snp_height).multipliedBy(0.25) }) _one_wordLabel?.snp_makeConstraints(closure: { (make) in make.top.equalTo(_nameLabel!.snp_bottom).offset(10) make.right.equalTo(self.contentView.snp_right).offset(-10) make.left.equalTo(_tableViewImageView!.snp_right).offset(10) make.height.equalTo(self.snp_height).multipliedBy(0.25) }) _needMoneyLabel?.snp_makeConstraints(closure: { (make) in make.top.equalTo(_one_wordLabel!.snp_bottom).offset(10) make.right.equalTo(self.contentView.snp_right).offset(-10) make.left.equalTo(_tableViewImageView!.snp_right).offset(10) make.height.equalTo(self.contentView.snp_height).multipliedBy(0.25) }) _collectButton.snp_makeConstraints { (make) in make.top.equalTo(self.contentView).offset(10) make.height.equalTo((_nameLabel?.snp_height)!) make.right.equalTo(self.contentView) make.width.equalTo(25) } _luckeyButton.snp_makeConstraints { (make) in make.top.equalTo(self.contentView).offset(10) make.height.equalTo((_nameLabel?.snp_height)!) make.right.equalTo(_collectButton.snp_left) make.width.equalTo(25) } self.distantLabel.snp_makeConstraints { (make) in make.bottom.equalTo(self.contentView).offset(-10) make.right.equalTo(self.contentView).offset(-10) make.width.equalTo(100) make.height.equalTo(30) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
apache-2.0
08a801f0c57dc2594fb911f98c199747
35.828338
262
0.592379
4.921704
false
false
false
false
Dis3buted/OutlineView
FileItem.swift
1
1918
// // FileItem.swift // OutlineView // // Created by Dis3buted on 23/05/16. // Copyright © 2016 Seven Years Later. All rights reserved. // import Foundation class FileItem { var url: URL! var parent: FileItem? static let fileManager = FileManager() static let requiredAttributes: Set = [URLResourceKey.isDirectoryKey] // not using just for example static let options: FileManager.DirectoryEnumerationOptions = [.skipsHiddenFiles, .skipsPackageDescendants, .skipsSubdirectoryDescendants] lazy var children: [FileItem]? = { // empty [URLResourceKey]() don't include any properties, pass nil to get the default properties if let enumerator = fileManager.enumerator(at: self.url, includingPropertiesForKeys:[URLResourceKey](), options: FileItem.options, errorHandler: nil) { var files = [FileItem]() while let localURL = enumerator.nextObject() as? URL { do { // not using properties and if not used catch unnessary //let properties = try (localURL as NSURL).resourceValues(forKeys: FileItem.requiredAttributes) let properties = try localURL.resourceValues(forKeys: FileItem.requiredAttributes) files.append(FileItem(url: localURL, parent: self)) } catch { print("Error reading file attributes") } } return files } return nil }() init(url:URL, parent: FileItem?){ self.url = url self.parent = parent } var displayName: String { get { return self.url.lastPathComponent } } var count: Int { return (self.children?.count)! } func childAtIndex(_ n: Int) -> FileItem? { return self.children![n] } }
mit
5b2a5590a1f2bba55e9d08049eaff5f2
30.95
159
0.591549
4.992188
false
false
false
false
Alexiuce/Tip-for-day
Tip for Day Demo/Pods/RealmSwift/RealmSwift/Sync.swift
2
21057
//////////////////////////////////////////////////////////////////////////// // // Copyright 2016 Realm Inc. // // 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 Realm import Realm.Private import Foundation /** An object representing a Realm Object Server user. - see: `SyncUser` */ public typealias SyncUser = RLMSyncUser /** A singleton which configures and manages the Realm Object Server synchronization-related functionality. - see: `RLMSyncManager` */ public typealias SyncManager = RLMSyncManager extension SyncManager { #if swift(>=3.0) /// The sole instance of the singleton. public static var shared: SyncManager { return __shared() } #else /// The sole instance of the singleton. @nonobjc public static func sharedManager() -> SyncManager { return __sharedManager() } #endif } /** A session object which represents communication between the client and server for a specific Realm. - see: `RLMSyncSession` */ public typealias SyncSession = RLMSyncSession /** A closure type for a closure which can be set on the `SyncManager` to allow errors to be reported to the application. - see: `RLMSyncErrorReportingBlock` */ public typealias ErrorReportingBlock = RLMSyncErrorReportingBlock /** A closure type for a closure which is used by certain APIs to asynchronously return a `User` object to the application. - see: `RLMUserCompletionBlock` */ public typealias UserCompletionBlock = RLMUserCompletionBlock /** An error associated with the SDK's synchronization functionality. - see: `RLMSyncError` */ public typealias SyncError = RLMSyncError /** An enum which can be used to specify the level of logging. - see: `RLMSyncLogLevel` */ public typealias SyncLogLevel = RLMSyncLogLevel /** An enum representing the different states a sync management object can take. - see: `RLMSyncManagementObjectStatus` */ public typealias SyncManagementObjectStatus = RLMSyncManagementObjectStatus #if swift(>=3.0) /** A data type whose values represent different authentication providers that can be used with the Realm Object Server. - see: `RLMIdentityProvider` */ public typealias Provider = RLMIdentityProvider /// A `SyncConfiguration` represents configuration parameters for Realms intended to sync with a Realm Object Server. public struct SyncConfiguration { /// The `SyncUser` who owns the Realm that this configuration should open. public let user: SyncUser /** The URL of the Realm on the Realm Object Server that this configuration should open. - warning: The URL must be absolute (e.g. `realms://example.com/~/foo`), and cannot end with `.realm`, `.realm.lock` or `.realm.management`. */ public let realmURL: URL /// A policy that determines what should happen when all references to Realms opened by this configuration /// go out of scope. internal let stopPolicy: RLMSyncStopPolicy internal init(config: RLMSyncConfiguration) { self.user = config.user self.realmURL = config.realmURL self.stopPolicy = config.stopPolicy } func asConfig() -> RLMSyncConfiguration { let config = RLMSyncConfiguration(user: user, realmURL: realmURL) config.stopPolicy = stopPolicy return config } /** Initialize a sync configuration with a user and a Realm URL. - warning: The URL must be absolute (e.g. `realms://example.com/~/foo`), and cannot end with `.realm`, `.realm.lock` or `.realm.management`. */ public init(user: SyncUser, realmURL: URL) { self.user = user self.realmURL = realmURL self.stopPolicy = .afterChangesUploaded } } /// A `SyncCredentials` represents data that uniquely identifies a Realm Object Server user. public struct SyncCredentials { public typealias Token = String internal var token: Token internal var provider: Provider internal var userInfo: [String: Any] /// Initialize new credentials using a custom token, authentication provider, and user information dictionary. In /// most cases, the convenience initializers should be used instead. public init(customToken token: Token, provider: Provider, userInfo: [String: Any] = [:]) { self.token = token self.provider = provider self.userInfo = userInfo } private init(_ credentials: RLMSyncCredentials) { self.token = credentials.token self.provider = credentials.provider self.userInfo = credentials.userInfo } /// Initialize new credentials using a Facebook account token. public static func facebook(token: Token) -> SyncCredentials { return SyncCredentials(RLMSyncCredentials(facebookToken: token)) } /// Initialize new credentials using a Google account token. public static func google(token: Token) -> SyncCredentials { return SyncCredentials(RLMSyncCredentials(googleToken: token)) } /// Initialize new credentials using an iCloud account token. public static func iCloud(token: Token) -> SyncCredentials { return SyncCredentials(RLMSyncCredentials(iCloudToken: token)) } /// Initialize new credentials using a Realm Object Server username and password. public static func usernamePassword(username: String, password: String, register: Bool = false) -> SyncCredentials { return SyncCredentials(RLMSyncCredentials(username: username, password: password, register: register)) } /// Initialize new credentials using a Realm Object Server access token. public static func accessToken(_ accessToken: String, identity: String) -> SyncCredentials { return SyncCredentials(RLMSyncCredentials(accessToken: accessToken, identity: identity)) } } extension RLMSyncCredentials { fileprivate convenience init(_ credentials: SyncCredentials) { self.init(customToken: credentials.token, provider: credentials.provider, userInfo: credentials.userInfo) } } extension SyncUser { /// Given credentials and a server URL, log in a user and asynchronously return a `SyncUser` object which can be used to /// open Realms and Sessions. public static func logIn(with credentials: SyncCredentials, server authServerURL: URL, timeout: TimeInterval = 30, onCompletion completion: @escaping UserCompletionBlock) { return SyncUser.__logIn(with: RLMSyncCredentials(credentials), authServerURL: authServerURL, timeout: timeout, onCompletion: completion) } /// A dictionary of all valid, logged-in user identities corresponding to their `SyncUser` objects. public static var all: [String: SyncUser] { return __allUsers() } /** The logged-in user. `nil` if none exists. - warning: Throws an Objective-C exception if more than one logged-in user exists. */ public static var current: SyncUser? { return __current() } /** Returns an instance of the Management Realm owned by the user. This Realm can be used to control access permissions for Realms managed by the user. This includes granting other users access to Realms. */ public func managementRealm() throws -> Realm { var config = Realm.Configuration.fromRLMRealmConfiguration(rlmConfiguration: .managementConfiguration(for: self)) config.objectTypes = [SyncPermissionChange.self] return try Realm(configuration: config) } } /** This model is used for requesting changes to a Realm's permissions. It should be used in conjunction with an `SyncUser`'s management Realm. See https://realm.io/docs/realm-object-server/#permissions for general documentation. */ public final class SyncPermissionChange: Object { /// The globally unique ID string of this permission change object. public dynamic var id = UUID().uuidString /// The date this object was initially created. public dynamic var createdAt = Date() /// The date this object was last modified. public dynamic var updatedAt = Date() /// The status code of the object that was processed by Realm Object Server. public let statusCode = RealmOptional<Int>() /// An error or informational message, typically written to by the Realm Object Server. public dynamic var statusMessage: String? /// Sync management object status. public var status: SyncManagementObjectStatus { guard let statusCode = statusCode.value else { return .notProcessed } if statusCode == 0 { return .success } return .error } /// The remote URL to the realm. public dynamic var realmUrl = "*" /// The identity of a user affected by this permission change. public dynamic var userId = "*" /// Define read access. Set to `true` or `false` to update this value. Leave unset to preserve the existing setting. public let mayRead = RealmOptional<Bool>() /// Define write access. Set to `true` or `false` to update this value. Leave unset to preserve the existing setting. public let mayWrite = RealmOptional<Bool>() /// Define management access. Set to `true` or `false` to update this value. Leave unset to preserve the existing setting. public let mayManage = RealmOptional<Bool>() /** Construct a permission change object used to change the access permissions for a user on a Realm. - parameter realmURL: The Realm URL whose permissions settings should be changed. Use `*` to change the permissions of all Realms managed by the management Realm's `SyncUser`. - parameter userID: The user or users who should be granted these permission changes. Use `*` to change the permissions for all users. - parameter mayRead: Define read access. Set to `true` or `false` to update this value. Leave unset to preserve the existing setting. - parameter mayWrite: Define write access. Set to `true` or `false` to update this value. Leave unset to preserve the existing setting. - parameter mayManage: Define management access. Set to `true` or `false` to update this value. Leave unset to preserve the existing setting. */ public convenience init(realmURL: String, userID: String, mayRead: Bool?, mayWrite: Bool?, mayManage: Bool?) { self.init() self.realmUrl = realmURL self.userId = userID self.mayRead.value = mayRead self.mayWrite.value = mayWrite self.mayManage.value = mayManage } /// :nodoc: override public class func shouldIncludeInDefaultSchema() -> Bool { return false } /// :nodoc: override public class func _realmObjectName() -> String? { return "PermissionChange" } } #else /** A data type whose values represent different authentication providers that can be used with the Realm Object Server. - see: `RLMIdentityProvider` */ public typealias Provider = String // `RLMIdentityProvider` imports as `NSString` /// A `SyncConfiguration` represents configuration parameters for Realms intended to sync with a Realm Object Server. public struct SyncConfiguration { /// The `SyncUser` who owns the Realm that this configuration should open. public let user: SyncUser /** The URL of the Realm on the Realm Object Server that this configuration should open. - warning: The URL must be absolute (e.g. `realms://example.com/~/foo`), and cannot end with `.realm`, `.realm.lock` or `.realm.management`. */ public let realmURL: NSURL /// A policy that determines what should happen when all references to Realms opened by this configuration /// go out of scope. internal let stopPolicy: RLMSyncStopPolicy internal init(config: RLMSyncConfiguration) { self.user = config.user self.realmURL = config.realmURL self.stopPolicy = config.stopPolicy } func asConfig() -> RLMSyncConfiguration { let config = RLMSyncConfiguration(user: user, realmURL: realmURL) config.stopPolicy = stopPolicy return config } /** Initialize a sync configuration with a user and a Realm URL. - warning: The URL must be absolute (e.g. `realms://example.com/~/foo`), and cannot end with `.realm`, `.realm.lock` or `.realm.management`. */ public init(user: SyncUser, realmURL: NSURL) { self.user = user self.realmURL = realmURL self.stopPolicy = .AfterChangesUploaded } } /// A `SyncCredentials` represents data that uniquely identifies a Realm Object Server user. public struct SyncCredentials { public typealias Token = String internal var token: Token internal var provider: Provider internal var userInfo: [String: AnyObject] // swiftlint:disable valid_docs /// Initialize new credentials using a custom token, authentication provider, and user information dictionary. In /// most cases, the convenience initializers should be used instead. public init(customToken token: Token, provider: Provider, userInfo: [String: AnyObject] = [:]) { self.token = token self.provider = provider self.userInfo = userInfo } private init(_ credentials: RLMSyncCredentials) { self.token = credentials.token self.provider = credentials.provider self.userInfo = credentials.userInfo } /// Initialize new credentials using a Facebook account token. public static func facebook(token: Token) -> SyncCredentials { return SyncCredentials(RLMSyncCredentials(facebookToken: token)) } /// Initialize new credentials using a Google account token. public static func google(token: Token) -> SyncCredentials { return SyncCredentials(RLMSyncCredentials(googleToken: token)) } /// Initialize new credentials using an iCloud account token. public static func iCloud(token: Token) -> SyncCredentials { return SyncCredentials(RLMSyncCredentials(ICloudToken: token)) } /// Initialize new credentials using a Realm Object Server username and password. public static func usernamePassword(username: String, password: String, register: Bool = false) -> SyncCredentials { return SyncCredentials(RLMSyncCredentials(username: username, password: password, register: register)) } /// Initialize new credentials using a Realm Object Server access token. public static func accessToken(accessToken: String, identity: String) -> SyncCredentials { return SyncCredentials(RLMSyncCredentials(accessToken: accessToken, identity: identity)) } } extension RLMSyncCredentials { private convenience init(_ credentials: SyncCredentials) { self.init(customToken: credentials.token, provider: credentials.provider, userInfo: credentials.userInfo) } } extension SyncUser { /// Given credentials and a server URL, log in a user and asynchronously return a `SyncUser` object which can be used to /// open Realms and Sessions. public static func logInWithCredentials(credentials: SyncCredentials, authServerURL: NSURL, timeout: NSTimeInterval = 30, onCompletion completion: UserCompletionBlock) { return __logInWithCredentials(RLMSyncCredentials(credentials), authServerURL: authServerURL, timeout: timeout, onCompletion: completion) } /// A dictionary of all valid, logged-in user identities corresponding to their `SyncUser` objects. @nonobjc public static func allUsers() -> [String: SyncUser] { return __allUsers() } /** The logged-in user. `nil` if none exists. - warning: Throws an Objective-C exception if more than one logged-in user exists. */ @nonobjc public static func currentUser() -> SyncUser? { return __currentUser() } /** Returns an instance of the Management Realm owned by the user. This Realm can be used to control access permissions for Realms managed by the user. This includes granting other users access to Realms. */ public func managementRealm() throws -> Realm { var config = Realm.Configuration.fromRLMRealmConfiguration(.managementConfigurationForUser(self)) config.objectTypes = [SyncPermissionChange.self] return try Realm(configuration: config) } } /** This model is used for requesting changes to a Realm's permissions. It should be used in conjunction with an `SyncUser`'s management Realm. See https://realm.io/docs/realm-object-server/#permissions for general documentation. */ public final class SyncPermissionChange: Object { /// The globally unique ID string of this permission change object. public dynamic var id = NSUUID().UUIDString /// The date this object was initially created. public dynamic var createdAt = NSDate() /// The date this object was last modified. public dynamic var updatedAt = NSDate() /// The status code of the object that was processed by Realm Object Server. public let statusCode = RealmOptional<Int>() /// An error or informational message, typically written to by the Realm Object Server. public dynamic var statusMessage: String? /// Sync management object status. public var status: SyncManagementObjectStatus { guard let statusCode = statusCode.value else { return .NotProcessed } if statusCode == 0 { return .Success } return .Error } /// The remote URL to the realm. public dynamic var realmUrl = "*" /// The identity of a user affected by this permission change. public dynamic var userId = "*" /// Define read access. Set to `true` or `false` to update this value. Leave unset to preserve the existing setting. public let mayRead = RealmOptional<Bool>() /// Define write access. Set to `true` or `false` to update this value. Leave unset to preserve the existing setting. public let mayWrite = RealmOptional<Bool>() /// Define management access. Set to `true` or `false` to update this value. Leave unset to preserve the existing setting. public let mayManage = RealmOptional<Bool>() /** Construct a permission change object used to change the access permissions for a user on a Realm. - parameter realmURL: The Realm URL whose permissions settings should be changed. Use `*` to change the permissions of all Realms managed by the management Realm's `SyncUser`. - parameter userID: The user or users who should be granted these permission changes. Use `*` to change the permissions for all users. - parameter mayRead: Define read access. Set to `true` or `false` to update this value. Leave unset to preserve the existing setting. - parameter mayWrite: Define write access. Set to `true` or `false` to update this value. Leave unset to preserve the existing setting. - parameter mayManage: Define management access. Set to `true` or `false` to update this value. Leave unset to preserve the existing setting. */ public convenience init(realmURL: String, userID: String, mayRead: Bool?, mayWrite: Bool?, mayManage: Bool?) { self.init() self.realmUrl = realmURL self.userId = userID self.mayRead.value = mayRead self.mayWrite.value = mayWrite self.mayManage.value = mayManage } /// :nodoc: override public class func shouldIncludeInDefaultSchema() -> Bool { return false } /// :nodoc: override public class func _realmObjectName() -> String? { return "PermissionChange" } } #endif
mit
8a825877c48e26c81e1dd43205702caf
37.779006
126
0.672176
5.107203
false
true
false
false
mathewsheets/SwiftLearningExercises
Exercise_15.playground/Sources/PersonMockService.swift
1
561
import Foundation public class PersonMockService: PersonService { var persons = [Person]() public init() { let person1 = Person() person1.id = "65372789-c4a8-4fd2-8480-2cf771e9b0bd" person1.first = "Mathew" person1.last = "Mock" person1.phone = "1-555-555-5555" self.persons.append(person1) } public func getPersons(completion: @escaping (HandlerPersons) -> Void) throws { completion() { return persons } } }
mit
98224917c422152b40f66130d8960171
21.44
83
0.543672
3.950704
false
false
false
false
cameronpit/Unblocker
Unblocker/Solver.swift
1
13863
// // Solver.swift // // Unblocker // Swift 3.1 // // Copyright © 2017 Cameron C. Pitcairn. // See the file license.txt in the Unblocker project. // import Foundation struct Solution { var timeInterval: TimeInterval = 0.0 var numMoves = 0 var initialBoard: Board = [] var winningBoard: Board = [] var numBoardsExamined: Int = 0 var numBoardsEnqueued: Int = 0 var finalQSize: Int = 0 var maxQSize: Int = 0 var numBoardsExaminedAtLevel: [Int] = [] var numBoardsEnqueuedAtLevel: [Int] = [] var boardAtLevel: [Board] = [] var moves: [SolutionMove] = [] var isUnsolvable = false } /******************************************************************************* Solution is by a breadth-first search. Each node of the queue named q is a tuple consisting of a board and a level. The level is the number of moves by which the board was reached from initialBoard. To start with, q has just one entry, initialBoard at level 0. As the solution progresses, boards are added to the bottom of q and other boards are removed from the top of q. Since the added boards are in non-decreasing order of level, every possible board at level n is dequeued and examined before any board at level n+1. Therefore a solution, if it exists, will eventually be found (provided there is enough memory available), and there will be no solution at any lower level. The procedure in more detail: The method solve() removes a board from the top of the queue (call it currentBoard, with level currentLevel) and generates every board which can be obtained by moving just one block in currentBoard. If a generated board, call it newBoard, is a key in the dictionary lookUpMoveForBoard[:], then newBoard was already encountered earlier (i.e. on a lower level) so it is discarded. Otherwise, the program sets lookupMoveForBoard[newBoard] = move, where move is the move which was applied to currentBoard to reach newBoard. Then newBoard is added to the bottom of q, with a level of currentLevel + 1. Finally, if the most recently moved block is the prisoner block and is adjacent to the escape chute, then newBoard is the winning board and the solution has been found. All that remains is to finish setting the properties in var solution (which is an instance of struct Solution). *******************************************************************************/ // MARK: - // class Solver { // UnblockerViewController, which runs in the main thread, will set // abortingSolve = true in order to abort method solve(), which runs in // a different thread. var abortingSolve = false var solution = Solution() var currentLevel = 0 var initialBoard:Board = [] var winColumn = 0 var offstageColumn = 0 var puzzle: Puzzle! private var q = Queue<(board: Board, level:Int)>() private var startTime = Date() // For a given board, dictionary lookupMoveForBoard returns the move which // was applied to the previous board to arrive at the given board. The move // identifies the block which was moved and its position in the previous // board. private var lookupMoveForBoard: [Board : Move] = [:] //*************************************************************************** // MARK: - // Solve for given initial board. Return nil if solving is aborted; // otherwise return solution. If puzzle is unsolvabe, return "solution" // with isUnsolvable set to true. func solve(puzzle aPuzzle: Puzzle) -> Solution? { puzzle = aPuzzle initialBoard = puzzle.initialBoard if initialBoard.isEmpty {return nil} if abortingSolve {return nil} solution = Solution() solution.initialBoard = initialBoard switch puzzle.escapeSite.side { case .left: winColumn = 0 offstageColumn = -3 case .right: winColumn = 4 offstageColumn = 7 } startTime = Date() solution.numBoardsEnqueuedAtLevel.append(1) solution.numBoardsExaminedAtLevel.append(1) var allDone = false lookupMoveForBoard = [:] // Set blockID to -1 as sentinel lookupMoveForBoard[initialBoard] = Move(blockID: -1, col:0, row:0) q.clearQueue() q.enQueue((initialBoard,0)) solution.maxQSize = q.size // MARK: Outer loop while !q.isEmpty && !allDone { let node = q.deQueue()! let currentBoard = node.board currentLevel = node.level var isOccupied = Matrix<Bool>(cols: Const.cols, rows: Const.rows, defaultElement: false) // Mark occupied tiles for block in currentBoard { let width = block.isHorizontal ? block.length : 1 let height = block.isHorizontal ? 1 : block.length for col in block.col..<block.col+width { for row in block.row..<block.row+height { isOccupied[col, row] = true } } } // MARK: Inner loop // may be executed tens of thousands of times // for block in currentBoard where !block.isFixed{ let length = block.length if block.isHorizontal { // Check tiles to left of block until encountering an // occupied tile or the left edge of the board. var col = block.col - 1 while col >= 0 && !isOccupied[col, block.row] && !allDone { allDone = registerBoard(currentBoard, block: block, col: col, row: block.row, level: currentLevel+1) col -= 1 } // Check tiles to right of block until encountering an // occupied tile or the right edge of the board. col = block.col + length while col < Const.cols && !isOccupied[col, block.row] && !allDone { allDone = registerBoard(currentBoard, block: block, col: col-length+1, row: block.row, level: currentLevel+1) col += 1 } } else { // Block is vertical // Check tiles above block until encountering an // occupied tile or the top edge of the board. var row = block.row - 1 while row >= 0 && !isOccupied[block.col, row] && !allDone { allDone = registerBoard(currentBoard, block: block, col: block.col, row: row, level: currentLevel+1) row -= 1 } // Check tiles below block until encountering an // occupied tile or the bottom edge of the board. row = block.row + length while row < Const.rows && !isOccupied[block.col, row] && !allDone { allDone = registerBoard(currentBoard, block: block, col: block.col, row: row-length+1, level: currentLevel+1) row += 1 } } if allDone {break} } // for block in currentBoard (Inner loop) } // while !q.isEmpty && !allDone (Outer loop) if abortingSolve { abortingSolve = false return nil } if q.isEmpty && !allDone { updateSolution(forWinningLevel: currentLevel, winningBoard: [], isUnsolvable: true) } return solution } //*************************************************************************** // MARK: - // Move block in board to (col, row). If resulting newBoard is not in // dictionary lookupMoveForBoard, compute move and add [newBoard:move] to // dictionary. Also in this case enqueue (newBoard, level). Then check if // a solution has been found. Return true if a solution has been found or // solve() is being aborted; otherwise return false. private func registerBoard( _ board: Board, block: Block, col:Int, row:Int, level:Int) -> Bool { // Any board is only enqueued once. When dequeuing // there is no need to check whether the board // has already been visited. // Create new board by moving a block if abortingSolve {return true} var newBoard = board var newBlock = newBoard.remove(block)! newBlock.col = col newBlock.row = row newBoard.insert(newBlock) // Bump counter if level == solution.numBoardsExaminedAtLevel.count { solution.numBoardsExaminedAtLevel.append(0) } solution.numBoardsExaminedAtLevel[level] += 1 // If newBoard was already enqueued, ignore it if lookupMoveForBoard[newBoard] != nil {return false} // Bump other counter if level == solution.numBoardsEnqueuedAtLevel.count { solution.numBoardsEnqueuedAtLevel.append(0) } solution.numBoardsEnqueuedAtLevel[level] += 1 // Compute move from board to newBoard, update dictionary and queue let move = Move(blockID: block.id, col: block.col, row: block.row) lookupMoveForBoard[newBoard] = move q.enQueue((newBoard,level)) if solution.maxQSize < q.size {solution.maxQSize = q.size} // If newBoard is a winning board, wrap it up; // otherwise keep on truckin'. if newBlock.isPrisoner && newBlock.col == winColumn { updateSolution(forWinningLevel: level, winningBoard: newBoard, isUnsolvable: false) return true } else { return false } } //*************************************************************************** // MARK: - // Finish up after solution has been found private func updateSolution(forWinningLevel level:Int, winningBoard board:Board, isUnsolvable: Bool) { solution.numBoardsEnqueued = 0 solution.numBoardsExamined = 0 for index in 0...level { solution.numBoardsEnqueued += solution.numBoardsEnqueuedAtLevel[index] solution.numBoardsExamined += solution.numBoardsExaminedAtLevel[index] } // Set properties which were not set previously solution.winningBoard = board solution.numMoves = level solution.finalQSize = q.size solution.timeInterval = Date().timeIntervalSince(startTime) solution.isUnsolvable = isUnsolvable if isUnsolvable {return} //************************************************************************ // Change winning board to have prisoner block offstage // Get last move var board = solution.winningBoard let move = lookupMoveForBoard[board]! // Delete old winning board from dictionary lookupMoveForBoard[board] = nil // Get last block moved let block = board.first(where: {$0.id == move.blockID})! // Last block moved must be prisoner assert(block.isPrisoner) // Move prisoner "offstage" var newBlock = board.remove(block)! newBlock.col = offstageColumn board.insert(newBlock) // Add new winning board to dictionary lookupMoveForBoard[board] = move solution.winningBoard = board //************************************************************************ // Populate arrays solution.moves and solution.boardAtLevel while true { // "infinite" loop will exit when blockID = -1 // We traverse the solution "backwards", i.e., from the final (winning) // board to the initial board. // Insert board at beginning of solution.boardAtLevel solution.boardAtLevel.insert(board, at: 0) //********************************************************************* // Compute solutionMove and insert it at beginning of solution.moves let move = lookupMoveForBoard[board]! if move.blockID == -1 {break} // -1 blockID is sentinel // Get the block which moves let block = board.first(where: {$0.id == move.blockID})! // Remove it from the board var newBlock = board.remove(block)! // Update its position newBlock.col = move.col newBlock.row = move.row // Put it back in the board, ready for the next pass through the loop board.insert(newBlock) // Although we can think of 'newBlock' as "the same block as 'block,' // but in a different position," they are in fact two distinct // elements of 'board,' which is just a set of blocks. That is why we // remove 'block' from the board and put 'newBlock' in. // Generate the corresponding 'solutionMove' let solutionMove = SolutionMove( blockID: block.id, colFwd: block.col, rowFwd: block.row, colBack: newBlock.col, rowBack: newBlock.row ) solution.moves.insert(solutionMove, at: 0) } // while true // moves[n].blockID identifies the sole block whose position in // boardAtLevel[n] differs from its position in boardAtLevel[n+1]. That // block's coordinates in boardAtLevel[n] are (moves[n].colBack, moves[n].rowBack), // and its coordinates in boardAtLevel[n+1] are (moves[n].colFwd, moves[n].rowFwd). } // private func updateSolution } // class Solver
mit
e24db31542f72812a5cda469b7249539
38.158192
97
0.574015
4.672059
false
false
false
false
ishkawa/APIKit
Tests/APIKitTests/BodyParametersType/URLEncodedSerializationTests.swift
1
2396
import Foundation import XCTest import APIKit class URLEncodedSerializationTests: XCTestCase { // MARK: NSData -> Any func testObjectFromData() throws { let data = try XCTUnwrap("key1=value1&key2=value2".data(using: .utf8)) let object = try? URLEncodedSerialization.object(from: data, encoding: .utf8) XCTAssertEqual(object?["key1"], "value1") XCTAssertEqual(object?["key2"], "value2") } func testInvalidFormatString() throws { let string = "key==value&" let data = try XCTUnwrap(string.data(using: .utf8)) XCTAssertThrowsError(try URLEncodedSerialization.object(from: data, encoding: .utf8)) { error in guard let error = error as? URLEncodedSerialization.Error, case .invalidFormatString(let invalidString) = error else { XCTFail() return } XCTAssertEqual(string, invalidString) } } func testInvalidString() { var bytes = [UInt8]([0xed, 0xa0, 0x80]) // U+D800 (high surrogate) let data = Data(bytes: &bytes, count: bytes.count) XCTAssertThrowsError(try URLEncodedSerialization.object(from: data, encoding: .utf8)) { error in guard let error = error as? URLEncodedSerialization.Error, case .cannotGetStringFromData(let invalidData, let encoding) = error else { XCTFail() return } XCTAssertEqual(data, invalidData) XCTAssertEqual(encoding, .utf8) } } // MARK: Any -> NSData func testDataFromObject() { let object = ["hey": "yo"] as Any let data = try? URLEncodedSerialization.data(from: object, encoding: .utf8) let string = data.flatMap { String(data: $0, encoding: .utf8) } XCTAssertEqual(string, "hey=yo") } func testNonDictionaryObject() { let dictionaries = [["hey": "yo"]] as Any XCTAssertThrowsError(try URLEncodedSerialization.data(from: dictionaries, encoding: .utf8)) { error in guard let error = error as? URLEncodedSerialization.Error, case .cannotCastObjectToDictionary(let object) = error else { XCTFail() return } XCTAssertEqual((object as AnyObject)["hey"], (dictionaries as AnyObject)["hey"]) } } }
mit
e88af78c138f489d899c7bed998c4d0b
35.30303
110
0.605593
4.735178
false
true
false
false
wikimedia/wikipedia-ios
Wikipedia/Code/StatusTextBarButtonItem.swift
1
2038
import UIKit /// A Themeable UIBarButtonItem with status text that mimics Apple Mail class StatusTextBarButtonItem: UIBarButtonItem, Themeable { // MARK: - Properties private var theme: Theme? override var isEnabled: Bool { get { return super.isEnabled } set { super.isEnabled = newValue if let theme = theme { apply(theme: theme) } } } // MARK: - UI Elements fileprivate var containerView: UIView? lazy var label: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.adjustsFontForContentSizeCategory = true label.numberOfLines = 0 label.textAlignment = .center label.font = UIFontMetrics(forTextStyle: .caption2).scaledFont(for: UIFont.systemFont(ofSize: 11), maximumPointSize: 12) label.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal) label.setContentCompressionResistancePriority(.defaultHigh, for: .vertical) return label }() // MARK: - Lifecycle @objc convenience init(text: String) { let containerView = UIView() containerView.translatesAutoresizingMaskIntoConstraints = false self.init(customView: containerView) self.containerView = containerView label.text = text containerView.addSubview(label) NSLayoutConstraint.activate([ label.leadingAnchor.constraint(equalTo: containerView.leadingAnchor), label.trailingAnchor.constraint(equalTo: containerView.trailingAnchor), label.topAnchor.constraint(equalTo: containerView.topAnchor), label.bottomAnchor.constraint(equalTo: containerView.bottomAnchor) ]) } // MARK: - Themeable public func apply(theme: Theme) { self.theme = theme tintColor = isEnabled ? theme.colors.link : theme.colors.disabledLink label.textColor = theme.colors.primaryText } }
mit
f9a4843733fc82ae0d245249ef04c038
29.878788
128
0.660942
5.538043
false
false
false
false
brave/browser-ios
Client/Extensions/UIAlertControllerExtensions.swift
2
9116
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import UIKit import Shared typealias UIAlertActionCallback = (UIAlertAction) -> Void // TODO: Build out this functionality a bit more (and remove FF code). // We have a number of "cancel" "yes" type alerts, should abstract here // MARK: - Extension methods for building specific UIAlertController instances used across the app extension UIAlertController { class func clearPrivateDataAlert(_ okayCallback: @escaping (UIAlertAction) -> Void) -> UIAlertController { let alert = UIAlertController( title: "", message: Strings.ThisWillClearAllPrivateDataItCannotBeUndone, preferredStyle: UIAlertControllerStyle.alert ) let noOption = UIAlertAction( title: Strings.Cancel, style: UIAlertActionStyle.cancel, handler: nil ) let okayOption = UIAlertAction( title: Strings.OK, style: UIAlertActionStyle.destructive, handler: okayCallback ) alert.addAction(okayOption) alert.addAction(noOption) return alert } /** Creates an alert view to warn the user that their logins will either be completely deleted in the case of local-only logins or deleted across synced devices in synced account logins. - parameter deleteCallback: Block to run when delete is tapped. - parameter hasSyncedLogins: Boolean indicating the user has logins that have been synced. - returns: UIAlertController instance */ class func deleteLoginAlertWithDeleteCallback( _ deleteCallback: @escaping UIAlertActionCallback, hasSyncedLogins: Bool) -> UIAlertController { let areYouSureTitle = Strings.AreYouSure let deleteLocalMessage = Strings.LoginsWillBePermanentlyRemoved let deleteSyncedDevicesMessage = Strings.LoginsWillBeRemovedFromAllConnectedDevices let cancelActionTitle = Strings.Cancel let deleteActionTitle = Strings.Delete let deleteAlert: UIAlertController if hasSyncedLogins { deleteAlert = UIAlertController(title: areYouSureTitle, message: deleteSyncedDevicesMessage, preferredStyle: .alert) } else { deleteAlert = UIAlertController(title: areYouSureTitle, message: deleteLocalMessage, preferredStyle: .alert) } let cancelAction = UIAlertAction(title: cancelActionTitle, style: .cancel, handler: nil) let deleteAction = UIAlertAction(title: deleteActionTitle, style: .destructive, handler: deleteCallback) deleteAlert.addAction(cancelAction) deleteAlert.addAction(deleteAction) return deleteAlert } // Enabled this facade for much easier discoverability, instead of using class directly /** Creates an alert view to collect a string from the user - parameter title: String to display as the alert title. - parameter message: String to display as the alert message. - parameter startingText: String to prefill the textfield with. - parameter placeholder: String to use for the placeholder text on the text field. - parameter keyboardType: Keyboard type of the text field. - parameter startingText2: String to prefill the second optional textfield with. - parameter placeholder2: String to use for the placeholder text on the second optional text field. - parameter keyboardType2: Keyboard type of the text second optional field. - parameter forcedInput: Bool whether the user needs to enter _something_ in order to enable OK button. - parameter callbackOnMain: Block to run on main thread when the user performs an action. - returns: UIAlertController instance */ class func userTextInputAlert(title: String, message: String, startingText: String? = nil, placeholder: String? = Strings.Name, keyboardType: UIKeyboardType? = nil, startingText2: String? = nil, placeholder2: String? = Strings.Name, keyboardType2: UIKeyboardType? = nil, forcedInput: Bool = true, callbackOnMain: @escaping (_ input: String?, _ input2: String?) -> ()) -> UIAlertController { // Returning alert, so no external, strong reference to initial instance return UserTextInputAlert(title: title, message: message, startingText: startingText, placeholder: placeholder, keyboardType: keyboardType, startingText2: startingText2, placeholder2: placeholder2, keyboardType2: keyboardType2, forcedInput: forcedInput, callbackOnMain: callbackOnMain).alert } } // Not part of extension due to needing observing // Would make private but objc runtime cannot find textfield observing callback class UserTextInputAlert { private weak var okAction: UIAlertAction! private(set) var alert: UIAlertController! required init(title: String, message: String, startingText: String?, placeholder: String?, keyboardType: UIKeyboardType? = nil, startingText2: String? = nil, placeholder2: String? = nil, keyboardType2: UIKeyboardType? = nil, forcedInput: Bool = true, callbackOnMain: @escaping (_ input: String?, _ input2: String?) -> ()) { alert = UIAlertController(title: title, message: message, preferredStyle: .alert) func actionSelected(input: String?, input2: String?) { postAsyncToMain { callbackOnMain(input, input2) } NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UITextFieldTextDidChange, object: alert.textFields?.first) } let okAlertAction = UIAlertAction(title: Strings.OK, style: .default) { _ in guard let textFields = self.alert.textFields else { return } let secondOptionalInput = textFields.count > 1 ? textFields[1].text : nil actionSelected(input: textFields.first?.text, input2: secondOptionalInput) } okAction = okAlertAction let cancelAction = UIAlertAction(title: Strings.Cancel, style: UIAlertActionStyle.cancel) { (alertA: UIAlertAction!) in actionSelected(input: nil, input2: nil) } self.okAction.isEnabled = !forcedInput alert.addAction(self.okAction) alert.addAction(cancelAction) alert.addTextField(configurationHandler: textFieldConfig(text: startingText, placeholder: placeholder, keyboardType: keyboardType, forcedInput: forcedInput)) if startingText2 != nil { alert.addTextField(configurationHandler: textFieldConfig(text: startingText2, placeholder: placeholder2, keyboardType: keyboardType2, forcedInput: forcedInput)) } } private func textFieldConfig(text: String?, placeholder: String?, keyboardType: UIKeyboardType?, forcedInput: Bool) -> (UITextField) -> () { return { textField in textField.placeholder = placeholder textField.isSecureTextEntry = false textField.keyboardAppearance = .dark textField.autocapitalizationType = keyboardType == .URL ? .none : .words textField.autocorrectionType = keyboardType == .URL ? .no : .default textField.returnKeyType = .done textField.text = text textField.keyboardType = keyboardType ?? .default if forcedInput { NotificationCenter.default.addObserver(self, selector: #selector(self.notificationReceived(notification:)), name: NSNotification.Name.UITextFieldTextDidChange, object: textField) } } } @objc func notificationReceived(notification: NSNotification) { guard let textFields = alert.textFields, let firstText = textFields.first?.text else { return } switch textFields.count { case 1: okAction.isEnabled = !firstText.isEmpty case 2: guard let lastText = textFields.last?.text else { break } okAction.isEnabled = !firstText.isEmpty && !lastText.isEmpty default: return } } }
mpl-2.0
0b169d8f09d5a59156cfc92844df5882
44.809045
194
0.624945
5.676214
false
false
false
false
swizzlr/ffmailman
app/Sources/main.swift
1
940
import Curassow import Inquiline import Underwood import Foundation final class FuckFuckingMailman: 🇺🇸 { override init() { super.init() get("/fuckit/searchit") { _, query in let query = NSString(string: query["search"] ?? "You gotta give me a search term mate") return redirectForQuery(query) } get("/:query") { params, _ in let query = NSString(string: params["query"]!) return redirectForQuery(query) } } } private func redirectForQuery(query: NSString) -> Response { let url = NSString(string: "https://encrypted.google.com/search?as_sitesearch=lists.swift.org&q=") let escapedQuery = query .stringByAddingPercentEncodingWithAllowedCharacters( NSCharacterSet.URLQueryAllowedCharacterSet() )! let redirectURL = url.stringByAppendingString(escapedQuery) return Response(.Found, headers: [("Location", redirectURL)]) } serve(FuckFuckingMailman().application)
mit
206bff7e1ef6176263fcff9812509a0a
29.129032
100
0.70985
4.114537
false
false
false
false
bogosmer/UnitKit
UnitKit/Source/Units/VolumeUnitType.swift
1
4304
// // VolumeUnitType.swift // UnitKit // // Created by Bo Gosmer on 09/02/2016. // Copyright © 2016 Deadlock Baby. All rights reserved. // import Foundation public enum VolumeUnitType: String, UnitType { // MARK: - Enum // MARK: Metric case Millilitre case Litre case CubicMetre // MARK: Imperial case CubicInch case CubicFoot case FluidOunce case Gill case Pint case Quart case Gallon case Bushel // MARK: US case USFluidOunce case USLiquidGill case USLiquidPint case USDryPint case USLiquidQuart case USDryQuart case USLiquidGallon case USDryGallon case USBushel // MARK: - Public properties public var description:String { return self.rawValue } // MARK: - Public functions // // TODO - use localization // public func localizedName(locale: NSLocale?) -> String { // return localizedAbbreviation(locale) // } // // // TODO - use localization // public func localizedAbbreviation(locale: NSLocale?) -> String { // let result: String // switch self { // case .Millilitre: // result = "ml" // case .Litre: // result = "l" // case .CubicMetre: // result = "m³" // case .CubicInch: // result = "cu in" // case .CubicFoot: // result = "cu ft" // case .FluidOunce: // result = "fl oz" // case .Gill: // result = "gill" // case .Pint: // result = "pt" // case .Quart: // result = "qt" // case .Gallon: // result = "gal" // case .Bushel: // result = "bu" // case .USFluidOunce: // result = "fl oz" // case .USLiquidGill: // result = "liquid gill" // case .USLiquidPint: // result = "liquid pint" // case .USDryPint: // result = "dry pint" // case .USLiquidQuart: // result = "liquid quart" // case .USDryQuart: // result = "dry pint" // case .USLiquidGallon: // result = "liquid gallon" // case .USDryGallon: // result = "dry gallon" // case .USBushel: // result = "bu" // } // return result // } public func baseUnitTypePerUnit() -> NSDecimalNumber { return millilitresPerUnit() } // MARK: - Private functions private func millilitresPerUnit() -> NSDecimalNumber { let result: NSDecimalNumber switch self { case .Millilitre: result = NSDecimalNumber.integer(1) case .Litre: result = NSDecimalNumber.integer(1000) case .CubicMetre: result = NSDecimalNumber.integer(1000000) case .CubicInch: result = NSDecimalNumber.double(16.387064) case .CubicFoot: result = NSDecimalNumber.double(28316.846592) case .FluidOunce: result = NSDecimalNumber.double(28.4130625) case .Gill: result = NSDecimalNumber.double(142.0653125) case .Pint: result = NSDecimalNumber.double(568.26125) case .Quart: result = NSDecimalNumber.double(1136.5225) case .Gallon: result = NSDecimalNumber.double(4546.09) case .Bushel: result = NSDecimalNumber.double(36368.72) case .USFluidOunce: result = NSDecimalNumber.double(29.5735295625) case .USLiquidGill: result = NSDecimalNumber.double(118.29411825) case .USLiquidPint: result = NSDecimalNumber.double(473.176473) case .USDryPint: result = NSDecimalNumber.double(550.6104713575) case .USLiquidQuart: result = NSDecimalNumber.double(946.352946) case .USDryQuart: result = NSDecimalNumber.double(1101.220942715) case .USLiquidGallon: result = NSDecimalNumber.double(3785.411784) case .USDryGallon: result = NSDecimalNumber.double(4404.88377086) case .USBushel: result = NSDecimalNumber.double(131.2266797761942) } return result } }
mit
0d1bec07671cb209d55a533035b6625f
26.941558
70
0.551836
4.097143
false
false
false
false
sabyapradhan/IBM-Ready-App-for-Banking
HatchReadyApp/apps/Hatch/iphone/native/Hatch/Controllers/Watson/WatsonViewController.swift
1
10599
/* Licensed Materials - Property of IBM © Copyright IBM Corporation 2015. All Rights Reserved. */ import UIKit /** * This view controller controls logic for the UIPageViewController that is inside of a container view. This will begin the Watson questionnaire. */ class WatsonViewController: UIViewController, UIPageViewControllerDataSource { /// menu button @IBOutlet weak var menuBar: UIButton! /// PageViewController to present Watson questionnaire var pageViewController : UIPageViewController! /// back button @IBOutlet weak var backButton: UIButton! /// custom UIPageControl @IBOutlet weak var hatchPage: HatchPageControl! /// the array containing the user's choice for each Question. watsonChoice[0] = 1 for example means that the user pressed option 2 for question 1 var watsonChoice : [Int] = [-1,-1,-1] /// boolean to only allow user to swipe forward to next viewcontroller if they have already answered the next question var touchEnabled : Bool = false override func viewDidLoad() { super.viewDidLoad() //setup menubar action menuBar.addTarget(self.navigationController, action: "menuButtonTapped:", forControlEvents: UIControlEvents.TouchUpInside) self.backButton.hidden = true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /** This method takes in a view controller, and based on its type will set the check mark associated with the option the user has previously selected in watsonChoice :param: startingViewController the view controller whose checkmark will be updated */ func updateChecks(startingViewController : UIViewController){ if (startingViewController.isKindOfClass(WatsonFrequencyViewController)) { var vc = startingViewController as! WatsonFrequencyViewController vc.watsonChoice = watsonChoice } if (startingViewController.isKindOfClass(WatsonImportanceViewController)) { var vc = startingViewController as! WatsonImportanceViewController vc.watsonChoice = watsonChoice } if (startingViewController.isKindOfClass(WatsonOverdraftViewController)) { var vc = startingViewController as! WatsonOverdraftViewController vc.watsonChoice = watsonChoice } } /** This method will either set the back button as hidden or not based on the index. :param: index index of view controller */ func setBackButtonHidden(index: Int){ switch index { case 2...3: self.backButton.hidden = false default: self.backButton.hidden = true } } /** This method will either set the hatch page control as hidden or not based on the index. :param: index index of the view controller */ func setHatchPageControlHidden(index: Int){ switch index { case 1...3: self.hatchPage.hidden = false default: self.hatchPage.hidden = true } } /** This method will either hide or unhide both the back button and the hatch page control based on the index. Also, the hatch page control is updated to the correct page. :param: index index of the view controller */ func setOutletAttributes(index: Int){ self.hatchPage.setCurrentPageIndex(index-1) setBackButtonHidden(index) setHatchPageControlHidden(index) } /** This method is called when the back button is tapped. The hatchPageControl is updated to the correct state and the correct view controller is displayed with animation :param: sender */ @IBAction func backButtonTapped(sender: AnyObject) { var vc : UIViewController = pageViewController.viewControllers.last as! UIViewController //set next view controller to be presented var startingViewController : UIViewController = self.viewControllerAtIndex(vc.view.tag-1)! self.setOutletAttributes(vc.view.tag-1) var viewControllers : [UIViewController] = [startingViewController] pageViewController.setViewControllers(viewControllers, direction: UIPageViewControllerNavigationDirection.Reverse, animated: true, completion: nil) } /** This method is called initially to connect the navigation view controller + WatsonViewController to the pageViewController + the controllers it will show :param: segue :param: sender */ override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "watsonPageSegue"{ pageViewController = segue.destinationViewController as! UIPageViewController pageViewController.view.backgroundColor = UIColor.greenHatch() pageViewController.dataSource = self pageViewController.delegate = self var startingViewController : UIViewController = self.viewControllerAtIndex(0)! self.setOutletAttributes(startingViewController.view.tag) var viewControllers : [UIViewController] = [startingViewController] pageViewController.setViewControllers(viewControllers, direction: UIPageViewControllerNavigationDirection.Forward, animated: false, completion: nil) } } /** This method returns the view controller at a particular index passed in :param: index desired index of view controller to return :returns: a UIViewController */ func viewControllerAtIndex(index : NSInteger) -> UIViewController? { if (index > 3 || index < 0) { return nil } //create new vc based on index var vc : UIViewController = UIViewController() switch (index){ case 0: vc = self.storyboard?.instantiateViewControllerWithIdentifier("start") as! WatsonStartViewController case 1: vc = self.storyboard?.instantiateViewControllerWithIdentifier("frequency") as! WatsonFrequencyViewController case 2: vc = self.storyboard?.instantiateViewControllerWithIdentifier("important") as! WatsonImportanceViewController case 3: vc = self.storyboard?.instantiateViewControllerWithIdentifier("overdraft") as! WatsonOverdraftViewController default: break } touchEnabled = false //update check marks for next view controller shown self.updateChecks(vc) MQALogger.log("pageIndex = \(vc.view.tag)") return vc } } extension WatsonViewController: UIPageViewControllerDataSource { /** This method must be implemented since WatsonViewController uses UIPageViewControllerDataSource. It will return the viewcontroller to be shown before whichever viewcontroller is currently being shown Note: This method is only used if pageViewController.dataSource is set (not set for Watson flow to disable touch to slide) :param: pageViewController :param: viewController :returns: */ func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? { var index : NSInteger index = viewController.view.tag if ((index <= 1) || (index == NSNotFound)) { return nil } index-- return self.viewControllerAtIndex(index) } /** This method must be implemented since WatsonViewController uses UIPageViewControllerDataSource. It will return the viewcontroller to be shown after whichever viewcontroller is currently being shown Note: This method is only used if pageViewController.dataSource is set (not set for Watson flow to disable touch to slide) :param: pageViewController :param: viewController :returns: */ func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? { var index : NSInteger if (viewController.view.tag < 3 && viewController.view.tag != 0) { if (watsonChoice[viewController.view.tag - 1] != -1) { touchEnabled = true //only allow user to swipe forward if question has already been answered } } else { return nil } if (touchEnabled == true) { index = viewController.view.tag //use the following if touch to swipe is needed (and set pageViewController.dataSource) : viewController.view.tag } else { return nil } if (index == NSNotFound) { return nil } index++ if (index > 3) { return nil } return self.viewControllerAtIndex(index) } func presentationCountForPageViewController(pageViewController: UIPageViewController) -> Int { return 0 //set to 0 so default pagecontrol does not show up } func presentationIndexForPageViewController(pageViewController: UIPageViewController) -> Int { return 0 } } extension WatsonViewController: UIPageViewControllerDelegate { /** This method should update the hatchPageControl's current page (shows correct dot based on page being shown) and hide or show the back button Note: This method is only used if pageViewController.dataSource is set (not set for Watson flow to disable touch to slide) :param: pageViewController :param: finished :param: previousViewControllers :param: completed */ func pageViewController(pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [AnyObject], transitionCompleted completed: Bool) { if !completed { return } var vc : UIViewController = pageViewController.viewControllers.last as! UIViewController MQALogger.log("PAGEINDEX HERE : \(vc.view.tag)") self.setOutletAttributes(vc.view.tag) MILLoadViewManager.sharedInstance.hide() } }
epl-1.0
8dee56a81e4dfff1d176603ca94056fa
33.861842
202
0.663616
5.794423
false
false
false
false
ben-ng/swift
validation-test/compiler_crashers_fixed/00396-llvm-raw-fd-ostream-write-impl.random.swift
1
2571
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck let h> T -> U) import Foundation let f = { } typealias h struct c == 0 } typealias e : I.init(array: Int typealias F } deinit { } typealias F>(f: P { struct c == { } 0 } class A where T class func a(e: Int = c> T) { } } } } return nil } } convenience init(x: AnyObject) { let t: AnyObject) -> { } print(") extension NSSet { extension NSSet { class A { struct S<T>() return $0) -> T where T] in enum A where T> Int = { return g<T: AnyObject) { } } } b: H.E == a protocol c == { struct d: C<H : a { var e: NSObject { } b } struct Q<D> : Int = { protocol A : Array) { let c = [unowned self.B == 0 typealias R } class A where T>() protocol P { } return $0 } } protocol e = nil } struct B? { class A : e, object2)? protocol a = T, b { struct e = compose(x) var d = b.c { } return nil } let t: I.E } func a(g(b } class A where T: T> String { self.E == " } return $0 func compose(self.init() func g(b<(x: C { struct B<C) { func f) } } struct Q<T>(f: (x: NSObject { struct c = " let d<U -> (array: A? = D> Int -> Void>(n: C } } self.h = { } typealias E } } typealias e { import CoreData print(f) let t: e: NSManagedObject { struct B<C> : A.c : AnyObject.c = e!.d } b> : B()-> String = B()-> V, g() -> String { } } protocol a { } return [T func a } convenience init() let c>) { if true { import Foundation class B<T>]()"") } struct e : A"") return [T, g<T> Self { } return "") } convenience init(v: Array<T { protocol b in protocol A { var e: Int = { deinit { } } self.c> V { struct c : c() protocol P { } func g, e) var b in x } } } typealias F>(() { let d: $0) -> { protocol A : I) { let c : NSObject { static let v: P> T>()? let c(x: P { let c protocol A { import Foundation protocol b : $0 var f: T -> U, f<c(#object1: T { } typealias e = B return nil } let t: I.Type) { class d.c = c() enum S<I : Int } } typealias h: B<T { let t: Array<T>() } enum A : C { func a(self.h: U -> : B<T>: A(g: T>>) { private let i: e = B<T.a func g: A>(self) return nil } func b(b: C<I : AnyObject, b = e: I.b = { protocol A { } let g = c) { func a() var b = B(T extension NSSet { } } let a = { } b: B? = compose() -> : A: P { } import Foundation 0 func a(f<T> U, f, e: e == { var f = 1, object2)
apache-2.0
3dcc048046f4ebb5a9493a402081ac92
12.822581
79
0.596266
2.48646
false
false
false
false
worchyld/EYPlayground
Payout.playground/Pages/salesRoutine.xcplaygroundpage/Contents.swift
1
4121
//: [Previous](@previous) import Foundation struct SalesRule { fileprivate var _orders: [Int] fileprivate var orders: [Int] { print(">> outstanding orders: \(_orders) <<") return _orders } init(orders: [Int]) { _orders = orders } private func match(_ good: Int) -> (Int, Int)? { var match = _orders.enumerated().filter { good == $0.element } match = match.flatMap { [($0.offset, $0.element)] } return match.first } private func lower(_ good: Int) -> (Int, Int)? { let lower = _orders.enumerated().max { a, b in return a.element > b.element } let upper = _orders.enumerated().max { a, b in return a.element < b.element } guard let lowerValue = lower?.1, let upperValue = upper?.1 else { return nil } let range = Range(uncheckedBounds: (lowerValue, upperValue)) let inRange = range.contains(good) if inRange || good < range.lowerBound { return upper } else { return nil } } private func higher(_ good: Int) -> (Int, Int)? { let upper = _orders.enumerated().max { a, b in return a.element < b.element } guard let upperValue = upper?.element else { return nil } if good > upperValue { return upper } else { return nil } } func getSalesTupleForGoods(goods:Int) -> (Int, Int) { if let match = self.match(goods) { print("Found perfect match for: \(goods) in orders \(self.orders) at index: \(match.0) which is the value \(match.1)") return (match.0, match.1) } else { if let lower = self.lower(goods) { print("Found lower match for: \(goods) in orders \(self.orders) at index: \(lower.0) which is the value \(lower.1)") return (lower.0, lower.1) } else { if let higher = self.higher(goods) { print("Found higher match for: \(goods) in orders \(self.orders) at index: \(higher.0) which is the value \(higher.1)") return (higher.0, higher.1) } else { assertionFailure("Failure") return (0,0) } } } } } struct SellingRound { var orders:[Int] = [Int]() var income: Int = 0 init(orders:[Int]) { self.orders = orders } mutating func sell(goods:Int, unitPrice:Int = 0) -> Int { let goods = goods let sellingRule = SalesRule( orders: self.orders ) let salesTuple = sellingRule.getSalesTupleForGoods(goods: goods) print ("------") print ("Units supplying: \(goods)") let orderIndex = salesTuple.0 let orderValue = salesTuple.1 var sum = goods if ((orderValue - sum) < 0) { sum = orderValue } self.orders[orderIndex] = (orderValue - sum) let goodsRemaining:Int = (goods - sum) let goodsSold = sum self.income = (goodsSold * unitPrice) print ("... Orders remaining: \(self.orders)") print ("Units sold: \(goodsSold), income: $\(income)") print ("Units remaining: \(goodsRemaining)") return goodsRemaining } } class Player { var goods:Int = 0 init(goods:Int) { self.goods = goods } } class Factory { var orders = [3,5,2] var unitPrice = 1 } var andy:Player = Player.init(goods:11) var f0 = Factory.init() // Selling rounds // How many rounds of selling will it take to sell all my goods var goodsRemaining = andy.goods var saleRounds: Int = 0 while goodsRemaining > 0 { var sellingRoundObj = SellingRound(orders: f0.orders) goodsRemaining = sellingRoundObj.sell(goods: goodsRemaining, unitPrice: f0.unitPrice) saleRounds += 1 } print ("It will take \(saleRounds) selling rounds to sell all my goods")
gpl-3.0
17e857ca4e9fdb894bba137b61694009
24.438272
140
0.537734
4.060099
false
false
false
false
qianqian2/ocStudy1
weibotext/weibotext/Class/Home/HomeTableViewController.swift
1
3122
// // HomeTableViewController.swift // weiboText // // Created by arang on 16/12/2. // Copyright © 2016年 arang. All rights reserved. // import UIKit class HomeTableViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() // 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() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 0 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return 0 } /* override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) // Configure the cell... return cell } */ /* // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
apache-2.0
9c189fcc1e495b3112c6fbf5fd66114f
31.831579
136
0.670087
5.331624
false
false
false
false
brentdax/swift
test/attr/attr_availability_osx.swift
10
5293
// RUN: %swift -typecheck -verify -parse-stdlib -module-name Swift -target x86_64-apple-macosx10.10 %s // Fake declarations of some standard library features for -parse-stdlib. precedencegroup AssignmentPrecedence {} enum Optional<T> { case none case some(T) } @available(OSX, introduced: 10.5, deprecated: 10.8, obsoleted: 10.9, message: "you don't want to do that anyway") func doSomething() { } // expected-note @-1{{'doSomething()' was obsoleted in OS X 10.9}} doSomething() // expected-error{{'doSomething()' is unavailable: you don't want to do that anyway}} // Preservation of major.minor.micro @available(OSX, introduced: 10.5, deprecated: 10.8, obsoleted: 10.9.1) func doSomethingElse() { } // expected-note @-1{{'doSomethingElse()' was obsoleted in OS X 10.9.1}} doSomethingElse() // expected-error{{'doSomethingElse()' is unavailable}} // Preservation of minor-only version @available(OSX, introduced: 8.0, deprecated: 8.5, obsoleted: 10) func doSomethingReallyOld() { } // expected-note @-1{{'doSomethingReallyOld()' was obsoleted in OS X 10}} doSomethingReallyOld() // expected-error{{'doSomethingReallyOld()' is unavailable}} // Test deprecations in 10.10 and later @available(OSX, introduced: 10.5, deprecated: 10.10, message: "Use another function") func deprecatedFunctionWithMessage() { } deprecatedFunctionWithMessage() // expected-warning{{'deprecatedFunctionWithMessage()' was deprecated in OS X 10.10: Use another function}} @available(OSX, introduced: 10.5, deprecated: 10.10) func deprecatedFunctionWithoutMessage() { } deprecatedFunctionWithoutMessage() // expected-warning{{'deprecatedFunctionWithoutMessage()' was deprecated in OS X 10.10}} @available(OSX, introduced: 10.5, deprecated: 10.10, message: "Use BetterClass instead") class DeprecatedClass { } func functionWithDeprecatedParameter(p: DeprecatedClass) { } // expected-warning{{'DeprecatedClass' was deprecated in OS X 10.10: Use BetterClass instead}} @available(OSX, introduced: 10.5, deprecated: 10.11, message: "Use BetterClass instead") class DeprecatedClassIn10_11 { } // Elements deprecated later than the minimum deployment target (which is 10.10, in this case) should not generate warnings func functionWithDeprecatedLaterParameter(p: DeprecatedClassIn10_11) { } // Unconditional platform unavailability @available(OSX, unavailable) func doSomethingNotOnOSX() { } // expected-note @-1{{'doSomethingNotOnOSX()' has been explicitly marked unavailable here}} doSomethingNotOnOSX() // expected-error{{'doSomethingNotOnOSX()' is unavailable}} @available(iOS, unavailable) func doSomethingNotOniOS() { } doSomethingNotOniOS() // okay // Unconditional platform deprecation @available(OSX, deprecated) func doSomethingDeprecatedOnOSX() { } doSomethingDeprecatedOnOSX() // expected-warning{{'doSomethingDeprecatedOnOSX()' is deprecated on OS X}} @available(iOS, deprecated) func doSomethingDeprecatedOniOS() { } doSomethingDeprecatedOniOS() // okay struct TestStruct {} @available(macOS 10.10, *) extension TestStruct { // expected-note {{enclosing scope here}} @available(swift 400) func doTheThing() {} // expected-note {{'doTheThing()' was introduced in Swift 400}} @available(macOS 10.9, *) // expected-error {{declaration cannot be more available than enclosing scope}} @available(swift 400) func doAnotherThing() {} // expected-note {{'doAnotherThing()' was introduced in Swift 400}} @available(macOS 10.12, *) @available(swift 400) func doThirdThing() {} // expected-note {{'doThirdThing()' was introduced in Swift 400}} @available(macOS 10.12, *) @available(swift 1) func doFourthThing() {} @available(*, deprecated) func doDeprecatedThing() {} } @available(macOS 10.11, *) func testMemberAvailability() { TestStruct().doTheThing() // expected-error {{'doTheThing()' is unavailable}} TestStruct().doAnotherThing() // expected-error {{'doAnotherThing()' is unavailable}} TestStruct().doThirdThing() // expected-error {{'doThirdThing()' is unavailable}} TestStruct().doFourthThing() // expected-error {{'doFourthThing()' is only available on OS X 10.12 or newer}} expected-note {{'if #available'}} TestStruct().doDeprecatedThing() // expected-warning {{'doDeprecatedThing()' is deprecated}} } extension TestStruct { struct Data { mutating func mutate() {} } var unavailableGetter: Data { @available(macOS, unavailable, message: "bad getter") get { return Data() } // expected-note 2 {{here}} set {} } var unavailableSetter: Data { get { return Data() } @available(macOS, obsoleted: 10.5, message: "bad setter") set {} // expected-note 2 {{setter for 'unavailableSetter' was obsoleted in OS X 10.5}} } } func testAccessors() { var t = TestStruct() _ = t.unavailableGetter // expected-error {{getter for 'unavailableGetter' is unavailable}} t.unavailableGetter = .init() t.unavailableGetter.mutate() // expected-error {{getter for 'unavailableGetter' is unavailable}} _ = t.unavailableSetter t.unavailableSetter = .init() // expected-error {{setter for 'unavailableSetter' is unavailable: bad setter}} t.unavailableSetter.mutate() // expected-error {{setter for 'unavailableSetter' is unavailable: bad setter}} }
apache-2.0
1c1fa331a320d9f19b10cd9542fea592
36.013986
155
0.723975
4.037376
false
true
false
false
orta/RxSwift
RxCocoa/RxCocoa/RxCocoa.swift
1
1661
// // RxCocoa.swift // RxCocoa // // Created by Krunoslav Zaher on 2/21/15. // Copyright (c) 2015 Krunoslav Zaher. All rights reserved. // import Foundation import RxSwift public enum RxCocoaError : Int { case Unknown = 0 case NetworkError = 1 case InvalidOperation = 2 } public let RxCocoaErrorDomain = "RxCocoaError" public let RxCocoaErrorHTTPResponseKey = "RxCocoaErrorHTTPResponseKey" func rxError(errorCode: RxCocoaError, message: String) -> NSError { return NSError(domain: RxCocoaErrorDomain, code: errorCode.rawValue, userInfo: [NSLocalizedDescriptionKey: message]) } func rxError(errorCode: RxCocoaError, message: String, userInfo: NSDictionary) -> NSError { let mutableDictionary = NSMutableDictionary(dictionary: userInfo as! [NSObject : AnyObject]) mutableDictionary[NSLocalizedDescriptionKey] = message // swift compiler :( let resultInfo: [NSObject: AnyObject] = (userInfo as NSObject) as! [NSObject: AnyObject] return NSError(domain: RxCocoaErrorDomain, code: Int(errorCode.rawValue), userInfo: resultInfo) } func removingObserverFailed() { rxFatalError("Removing observer for key failed") } func handleVoidObserverResult(result: Result<Void>) { handleObserverResult(result) } func rxFatalError(lastMessage: String) { // The temptation to comment this line is great, but please don't, it's for your own good. The choice is yours. fatalError(lastMessage) } func handleObserverResult<T>(result: Result<T>) { switch result { case .Error(let error): print("Error happened \(error)") rxFatalError("Error '\(error)' happened while "); default: break } }
mit
9aced6d1ed716b3f89386eaeb8de593f
29.777778
120
0.732089
4.35958
false
false
false
false
BluechipSystems/viper-module-generator
VIPERGenDemo/VIPERGenDemo/Shared/Vendor/AccountManager/TwitterAccountManager.swift
4
2770
// // AccountManager.swift // VIPERGenDemo // // Created by AUTHOR on 10/11/14. // Copyright (c) 2014 AUTHOR. All rights reserved. // import Foundation class TwitterAccountManager: TwitterAccountManagerProtocol { //MARK: - AccountManagerProtocol /** Returns if the user has already logged :returns: Bool indicating if the user is logged */ class func isUserLogged() -> Bool { return userDictionary().count != 0 } /** Persist an account attribute into the local account persistance :param: accountAttribute Account attribute to be persisted :param: value Value of the persisted attribute */ class func set(#accountAttribute: TwitterAccountAttribute, value: AnyObject) { var dict: [String: AnyObject] = userDictionary() dict[accountAttribute.rawValue] = value persistUserDictionary(dict) } class func attribute(attribute: TwitterAccountAttribute) -> AnyObject? { var dict: [String: AnyObject] = userDictionary() let value: AnyObject? = dict[attribute.rawValue] return value } /** Removes the persisted account */ class func clean() { persistUserDictionary(nil) } //MARK: - Private private struct Constants { private static let NSUSERDEFAULTS_KEY = "UserDefaultsAccountKey" } private class func userDictionary() -> [String: AnyObject] { var userDictionary: [String: AnyObject]? = NSUserDefaults.standardUserDefaults().objectForKey(Constants.NSUSERDEFAULTS_KEY) as [String: AnyObject]? if userDictionary != nil { return userDictionary! } return [String: AnyObject]() } private class func persistUserDictionary(userAccount: [String: AnyObject]?) { NSUserDefaults.standardUserDefaults().setObject(userAccount, forKey: Constants.NSUSERDEFAULTS_KEY) NSUserDefaults.standardUserDefaults().synchronize() } } /** * AccountManager + TwitterLoginItem Extension */ extension TwitterAccountManager { class func persistAccount(fromLoginItem loginItem: TwitterLoginItem) { var dict: [String: AnyObject] = userDictionary() dict[TwitterAccountAttribute.TwitterAccountAttributeKey.rawValue] = loginItem.key dict[TwitterAccountAttribute.TwitterAccountAttributeSecret.rawValue] = loginItem.secret dict[TwitterAccountAttribute.TwitterAccountAttributeVerifier.rawValue] = loginItem.verifier dict[TwitterAccountAttribute.TwitterAccountAttributeScreenName.rawValue] = loginItem.screenName dict[TwitterAccountAttribute.TwitterAccountAttributeUserID.rawValue] = loginItem.userID persistUserDictionary(dict) } }
mit
354d5da061bf50a5291e87a4164628c7
29.450549
155
0.69278
4.982014
false
false
false
false
fiveagency/ios-five-utils
Sources/Int+Five.swift
1
782
// // Int+Five.swift // FiveUtils // // Created by Denis Mendica on 5/27/16. // Copyright © 2016 Five Agency. All rights reserved. // import Foundation // MARK: Ordinal extension Int { /** Returns a string that represents this integer as an ordinal number, e.g. "1st" for 1, "2nd" for 2 etc. */ public var ordinalString: String { let ones = self % 10 let tens = self / 10 % 10 var suffix: String if tens == 1 { suffix = "th" } else if ones == 1 { suffix = "st" } else if ones == 2 { suffix = "nd" } else if ones == 3 { suffix = "rd" } else { suffix = "th" } return String(self) + suffix } }
mit
b153b7c19c9cca687a5654fd214c94a4
20.694444
107
0.486556
3.772947
false
false
false
false
carlospaelinck/pokebattle
PokéBattle/TeamArchiverController.swift
1
989
// // TeamArchiverController.swift // PokéBattle // // Created by Carlos Paelinck on 4/12/16. // Copyright © 2016 Carlos Paelinck. All rights reserved. // import Foundation class TeamArchiverController { class func archiveTeam(team: Team, toFile fileName: String = "team.pokéBattle") -> Bool { let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) let docDirectory = paths.first! let filePath = docDirectory.stringByAppendingString("/\(fileName)") return NSKeyedArchiver.archiveRootObject(team, toFile: filePath) } class func unarchiveTeam(fromFile fileName: String = "team.pokéBattle") -> Team? { let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) let docDirectory = paths.first! let filePath = docDirectory.stringByAppendingString("/\(fileName)") return NSKeyedUnarchiver.unarchiveObjectWithFile(filePath) as? Team } }
mit
1ed1cf25c4d254b7bbf201e40a6cb0a1
38.44
98
0.722843
4.804878
false
false
false
false
niunaruto/DeDaoAppSwift
testSwift/Pods/SteviaLayout/Source/Stevia+Equation.swift
2
9924
// // Stevia+Equation.swift // Stevia // // Created by Sacha Durand Saint Omer on 21/01/2017. // Copyright © 2017 Sacha Durand Saint Omer. All rights reserved. // #if canImport(UIKit) import UIKit public struct SteviaAttribute { let view: UIView let attribute: NSLayoutConstraint.Attribute let constant: CGFloat? let multiplier: CGFloat? init(view: UIView, attribute: NSLayoutConstraint.Attribute) { self.view = view self.attribute = attribute self.constant = nil self.multiplier = nil } init(view: UIView, attribute: NSLayoutConstraint.Attribute, constant: CGFloat?, multiplier: CGFloat?) { self.view = view self.attribute = attribute self.constant = constant self.multiplier = multiplier } } public extension UIView { var Width: SteviaAttribute { return SteviaAttribute(view: self, attribute: .width) } var Height: SteviaAttribute { return SteviaAttribute(view: self, attribute: .height) } var Top: SteviaAttribute { return SteviaAttribute(view: self, attribute: .top) } var Bottom: SteviaAttribute { return SteviaAttribute(view: self, attribute: .bottom) } var Left: SteviaAttribute { return SteviaAttribute(view: self, attribute: .left) } var Right: SteviaAttribute { return SteviaAttribute(view: self, attribute: .right) } var Leading: SteviaAttribute { return SteviaAttribute(view: self, attribute: .leading) } var Trailing: SteviaAttribute { return SteviaAttribute(view: self, attribute: .trailing) } var CenterX: SteviaAttribute { return SteviaAttribute(view: self, attribute: .centerX) } var CenterY: SteviaAttribute { return SteviaAttribute(view: self, attribute: .centerY) } var FirstBaseline: SteviaAttribute { return SteviaAttribute(view: self, attribute: .firstBaseline) } var LastBaseline: SteviaAttribute { return SteviaAttribute(view: self, attribute: .lastBaseline) } } // MARK: - Equations of type v.P == v'.P' + X @discardableResult public func == (left: SteviaAttribute, right: SteviaAttribute) -> NSLayoutConstraint { let constant = right.constant ?? left.constant ?? 0 let multiplier = right.multiplier ?? left.multiplier ?? 1 if left.view.superview == right.view.superview { // A and B are at the same level // Old code if let spv = left.view.superview { return spv.addConstraint(item: left.view, attribute: left.attribute, toItem: right.view, attribute: right.attribute, multiplier: multiplier, constant: constant) } } else if left.view.superview == right.view { // A is in B (first level) return right.view.addConstraint(item: left.view, attribute: left.attribute, toItem: right.view, attribute: right.attribute, multiplier: multiplier, constant: constant) } else if right.view.superview == left.view { // B is in A (first level) return left.view.addConstraint(item: right.view, attribute: right.attribute, toItem: left.view, attribute: left.attribute, multiplier: multiplier, constant: constant) } else if left.view.isDescendant(of: right.view) { // A is in B (LOW level) return right.view.addConstraint(item: left.view, attribute: left.attribute, toItem: right.view, attribute: right.attribute, multiplier: multiplier, constant: constant) } else if right.view.isDescendant(of: left.view) { // B is in A (LOW level) return left.view.addConstraint(item: left.view, attribute: left.attribute, toItem: right.view, attribute: right.attribute, multiplier: multiplier, constant: constant) } else if let commonParent = commonParent(with: left.view, and: right.view) { // Look for common ancestor return commonParent.addConstraint(item: left.view, attribute: left.attribute, toItem: right.view, attribute: right.attribute, multiplier: multiplier, constant: constant) } return NSLayoutConstraint() } func commonParent(with viewA: UIView, and viewB: UIView) -> UIView? { // Both views should have a superview guard viewA.superview != nil && viewB.superview != nil else { return nil } // Find the common parent var spv = viewA.superview while spv != nil { if viewA.isDescendant(of: spv!) && viewB.isDescendant(of: spv!) { return spv } else { spv = spv?.superview } } return nil } @discardableResult public func >= (left: SteviaAttribute, right: SteviaAttribute) -> NSLayoutConstraint { return applyRelation(left: left, right: right, relateBy: .greaterThanOrEqual) } @discardableResult public func <= (left: SteviaAttribute, right: SteviaAttribute) -> NSLayoutConstraint { return applyRelation(left: left, right: right, relateBy: .lessThanOrEqual) } private func applyRelation(left: SteviaAttribute, right: SteviaAttribute, relateBy: NSLayoutConstraint.Relation) -> NSLayoutConstraint { let constant = right.constant ?? 0 let multiplier = right.multiplier ?? 1 if let spv = left.view.superview { return spv.addConstraint(item: left.view, attribute: left.attribute, relatedBy: relateBy, toItem: right.view, attribute: right.attribute, multiplier: multiplier, constant: constant) } return NSLayoutConstraint() } @discardableResult public func + (left: SteviaAttribute, right: CGFloat) -> SteviaAttribute { return SteviaAttribute(view: left.view, attribute: left.attribute, constant: right, multiplier: left.multiplier) } @discardableResult public func - (left: SteviaAttribute, right: CGFloat) -> SteviaAttribute { return SteviaAttribute(view: left.view, attribute: left.attribute, constant: -right, multiplier: left.multiplier) } @discardableResult public func * (left: SteviaAttribute, right: CGFloat) -> SteviaAttribute { return SteviaAttribute(view: left.view, attribute: left.attribute, constant: left.constant, multiplier: right) } @discardableResult public func / (left: SteviaAttribute, right: CGFloat) -> SteviaAttribute { return left * (1/right) } @discardableResult public func % (left: CGFloat, right: SteviaAttribute) -> SteviaAttribute { return right * (left/100) } // MARK: - Equations of type v.P == X @discardableResult public func == (left: SteviaAttribute, right: CGFloat) -> NSLayoutConstraint { if let spv = left.view.superview { var toItem: UIView? = spv var constant: CGFloat = right if left.attribute == .width || left.attribute == .height { toItem = nil } if left.attribute == .bottom || left.attribute == .right { constant = -constant } return spv.addConstraint(item: left.view, attribute: left.attribute, toItem: toItem, constant: constant) } return NSLayoutConstraint() } @discardableResult public func >= (left: SteviaAttribute, right: CGFloat) -> NSLayoutConstraint { if let spv = left.view.superview { var toItem: UIView? = spv var constant: CGFloat = right if left.attribute == .width || left.attribute == .height { toItem = nil } if left.attribute == .bottom || left.attribute == .right { constant = -constant } return spv.addConstraint(item: left.view, attribute: left.attribute, relatedBy: .greaterThanOrEqual, toItem: toItem, constant: constant) } return NSLayoutConstraint() } @discardableResult public func <= (left: SteviaAttribute, right: CGFloat) -> NSLayoutConstraint { if let spv = left.view.superview { var toItem: UIView? = spv var constant: CGFloat = right if left.attribute == .width || left.attribute == .height { toItem = nil } if left.attribute == .bottom || left.attribute == .right { constant = -constant } return spv.addConstraint(item: left.view, attribute: left.attribute, relatedBy: .lessThanOrEqual, toItem: toItem, constant: constant) } return NSLayoutConstraint() } #endif
mit
f2ae05138a403ba244fe9868072b190c
35.751852
136
0.555679
5.144116
false
false
false
false
Yummypets/YPImagePicker
Source/Pages/Gallery/LibraryMediaManager.swift
1
10433
// // LibraryMediaManager.swift // YPImagePicker // // Created by Sacha DSO on 26/01/2018. // Copyright © 2018 Yummypets. All rights reserved. // import UIKit import Photos class LibraryMediaManager { weak var v: YPLibraryView? var collection: PHAssetCollection? internal var fetchResult: PHFetchResult<PHAsset>? internal var previousPreheatRect: CGRect = .zero internal var imageManager: PHCachingImageManager? internal var exportTimer: Timer? internal var currentExportSessions: [AVAssetExportSession] = [] /// If true then library has items to show. If false the user didn't allow any item to show in picker library. internal var hasResultItems: Bool { if let fetchResult = self.fetchResult { return fetchResult.count > 0 } else { return false } } func initialize() { imageManager = PHCachingImageManager() resetCachedAssets() } func resetCachedAssets() { imageManager?.stopCachingImagesForAllAssets() previousPreheatRect = .zero } func updateCachedAssets(in collectionView: UICollectionView) { let screenWidth = YPImagePickerConfiguration.screenWidth let size = screenWidth / 4 * UIScreen.main.scale let cellSize = CGSize(width: size, height: size) var preheatRect = collectionView.bounds preheatRect = preheatRect.insetBy(dx: 0.0, dy: -0.5 * preheatRect.height) let delta = abs(preheatRect.midY - previousPreheatRect.midY) if delta > collectionView.bounds.height / 3.0 { var addedIndexPaths: [IndexPath] = [] var removedIndexPaths: [IndexPath] = [] previousPreheatRect.differenceWith(rect: preheatRect, removedHandler: { removedRect in let indexPaths = collectionView.aapl_indexPathsForElementsInRect(removedRect) removedIndexPaths += indexPaths }, addedHandler: { addedRect in let indexPaths = collectionView.aapl_indexPathsForElementsInRect(addedRect) addedIndexPaths += indexPaths }) guard let assetsToStartCaching = fetchResult?.assetsAtIndexPaths(addedIndexPaths), let assetsToStopCaching = fetchResult?.assetsAtIndexPaths(removedIndexPaths) else { print("Some problems in fetching and caching assets.") return } imageManager?.startCachingImages(for: assetsToStartCaching, targetSize: cellSize, contentMode: .aspectFill, options: nil) imageManager?.stopCachingImages(for: assetsToStopCaching, targetSize: cellSize, contentMode: .aspectFill, options: nil) previousPreheatRect = preheatRect } } func fetchVideoUrlAndCrop(for videoAsset: PHAsset, cropRect: CGRect, callback: @escaping (_ videoURL: URL?) -> Void) { fetchVideoUrlAndCropWithDuration(for: videoAsset, cropRect: cropRect, duration: nil, callback: callback) } func fetchVideoUrlAndCropWithDuration(for videoAsset: PHAsset, cropRect: CGRect, duration: CMTime?, callback: @escaping (_ videoURL: URL?) -> Void) { let videosOptions = PHVideoRequestOptions() videosOptions.isNetworkAccessAllowed = true videosOptions.deliveryMode = .highQualityFormat imageManager?.requestAVAsset(forVideo: videoAsset, options: videosOptions) { asset, _, _ in do { guard let asset = asset else { ypLog("Don't have the asset"); return } let assetComposition = AVMutableComposition() let assetMaxDuration = self.getMaxVideoDuration(between: duration, andAssetDuration: asset.duration) let trackTimeRange = CMTimeRangeMake(start: CMTime.zero, duration: assetMaxDuration) // 1. Inserting audio and video tracks in composition guard let videoTrack = asset.tracks(withMediaType: AVMediaType.video).first, let videoCompositionTrack = assetComposition .addMutableTrack(withMediaType: .video, preferredTrackID: kCMPersistentTrackID_Invalid) else { ypLog("Problems with video track") return } if let audioTrack = asset.tracks(withMediaType: AVMediaType.audio).first, let audioCompositionTrack = assetComposition .addMutableTrack(withMediaType: AVMediaType.audio, preferredTrackID: kCMPersistentTrackID_Invalid) { try audioCompositionTrack.insertTimeRange(trackTimeRange, of: audioTrack, at: CMTime.zero) } try videoCompositionTrack.insertTimeRange(trackTimeRange, of: videoTrack, at: CMTime.zero) // Layer Instructions let layerInstructions = AVMutableVideoCompositionLayerInstruction(assetTrack: videoCompositionTrack) var transform = videoTrack.preferredTransform let videoSize = videoTrack.naturalSize.applying(transform) transform.tx = (videoSize.width < 0) ? abs(videoSize.width) : 0.0 transform.ty = (videoSize.height < 0) ? abs(videoSize.height) : 0.0 transform.tx -= cropRect.minX transform.ty -= cropRect.minY layerInstructions.setTransform(transform, at: CMTime.zero) videoCompositionTrack.preferredTransform = transform // CompositionInstruction let mainInstructions = AVMutableVideoCompositionInstruction() mainInstructions.timeRange = trackTimeRange mainInstructions.layerInstructions = [layerInstructions] // Video Composition let videoComposition = AVMutableVideoComposition(propertiesOf: asset) videoComposition.instructions = [mainInstructions] videoComposition.renderSize = cropRect.size // needed? // 5. Configuring export session let fileURL = URL(fileURLWithPath: NSTemporaryDirectory()) .appendingUniquePathComponent(pathExtension: YPConfig.video.fileType.fileExtension) let exportSession = assetComposition .export(to: fileURL, videoComposition: videoComposition, removeOldFile: true) { [weak self] session in DispatchQueue.main.async { switch session.status { case .completed: if let url = session.outputURL { if let index = self?.currentExportSessions.firstIndex(of: session) { self?.currentExportSessions.remove(at: index) } callback(url) } else { ypLog("Don't have URL.") callback(nil) } case .failed: ypLog("Export of the video failed : \(String(describing: session.error))") callback(nil) default: ypLog("Export session completed with \(session.status) status. Not handled.") callback(nil) } } } // 6. Exporting DispatchQueue.main.async { self.exportTimer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(self.onTickExportTimer), userInfo: exportSession, repeats: true) } if let s = exportSession { self.currentExportSessions.append(s) } } catch let error { ypLog("Error: \(error)") } } } private func getMaxVideoDuration(between duration: CMTime?, andAssetDuration assetDuration: CMTime) -> CMTime { guard let duration = duration else { return assetDuration } if assetDuration <= duration { return assetDuration } else { return duration } } @objc func onTickExportTimer(sender: Timer) { if let exportSession = sender.userInfo as? AVAssetExportSession { if let v = v { if exportSession.progress > 0 { v.updateProgress(exportSession.progress) } } if exportSession.progress > 0.99 { sender.invalidate() v?.updateProgress(0) self.exportTimer = nil } } } func forseCancelExporting() { for s in self.currentExportSessions { s.cancelExport() } } func getAsset(at index: Int) -> PHAsset? { guard let fetchResult = fetchResult else { print("FetchResult not contain this index: \(index)") return nil } guard fetchResult.count > index else { print("FetchResult not contain this index: \(index)") return nil } return fetchResult.object(at: index) } }
mit
c2c039b5113c38df70f41216a765c220
43.772532
116
0.530196
6.364857
false
false
false
false
bmichotte/HSTracker
HSTracker/Database/Models/GameStats.swift
1
7675
// // GameStats.swift // HSTracker // // Created by Benjamin Michotte on 29/12/16. // Copyright © 2016 Benjamin Michotte. All rights reserved. // import Foundation import RealmSwift class InternalGameStats { var statId: String = generateId() var playerHero: CardClass = .neutral var opponentHero: CardClass = .neutral var coin = false var gameMode: GameMode = .none var result: GameResult = .unknown var turns = -1 var startTime = Date() var endTime = Date() var note = "" var playerName = "" var opponentName = "" var wasConceded = false var rank = -1 var stars = -1 var legendRank = -1 var opponentLegendRank = -1 var opponentRank = -1 var hearthstoneBuild: Int? var playerCardbackId = -1 var opponentCardbackId = -1 var friendlyPlayerId = -1 var scenarioId = -1 var serverInfo: ServerInfo? var season = 0 var gameType: GameType = .gt_unknown var hsDeckId: Int64? var brawlSeasonId = -1 var rankedSeasonId = -1 var arenaWins = 0 var arenaLosses = 0 var brawlWins = 0 var brawlLosses = 0 private var _format: Format? var format: Format? { get { return gameMode == .ranked || gameMode == .casual ? _format : nil } set { _format = newValue } } var hsReplayId: String? var opponentCards: [Card] = [] var revealedCards: [Card] = [] func toGameStats() -> GameStats { let gameStats = GameStats() gameStats.statId = statId gameStats.hearthstoneBuild.value = hearthstoneBuild gameStats.playerCardbackId = playerCardbackId gameStats.opponentCardbackId = opponentCardbackId gameStats.opponentHero = opponentHero gameStats.friendlyPlayerId = friendlyPlayerId gameStats.opponentName = opponentName gameStats.opponentRank = opponentRank gameStats.opponentLegendRank = opponentLegendRank gameStats.playerName = playerName gameStats.rank = rank gameStats.legendRank = legendRank gameStats.stars = stars gameStats.wasConceded = wasConceded gameStats.turns = turns gameStats.scenarioId = scenarioId gameStats.serverInfo = serverInfo gameStats.season = season gameStats.gameMode = gameMode gameStats.gameType = gameType gameStats.hsDeckId.value = hsDeckId gameStats.brawlSeasonId = brawlSeasonId gameStats.rankedSeasonId = rankedSeasonId gameStats.arenaWins = arenaWins gameStats.arenaLosses = arenaLosses gameStats.brawlWins = brawlWins gameStats.brawlLosses = brawlLosses gameStats.format = format gameStats.hsReplayId = hsReplayId gameStats.result = result opponentCards.forEach { let card = RealmCard(id: $0.id, count: $0.count) gameStats.opponentCards.append(card) } revealedCards.forEach { let card = RealmCard(id: $0.id, count: $0.count) gameStats.revealedCards.append(card) } return gameStats } } extension InternalGameStats: CustomStringConvertible { var description: String { return "playerHero: \(playerHero), " + "opponentHero: \(opponentHero), " + "coin: \(coin), " + "gameMode: \(gameMode), " + "result: \(result), " + "turns: \(turns), " + "startTime: \(startTime), " + "endTime: \(endTime), " + "note: \(note), " + "playerName: \(playerName), " + "opponentName: \(opponentName), " + "wasConceded: \(wasConceded), " + "rank: \(rank), " + "stars: \(stars), " + "legendRank: \(legendRank), " + "opponentLegendRank: \(opponentLegendRank), " + "opponentRank: \(opponentRank), " + "hearthstoneBuild: \(String(describing: hearthstoneBuild)), " + "playerCardbackId: \(playerCardbackId), " + "opponentCardbackId: \(opponentCardbackId), " + "friendlyPlayerId: \(friendlyPlayerId), " + "scenarioId: \(scenarioId), " + "serverInfo: \(String(describing: serverInfo)), " + "season: \(season), " + "gameType: \(gameType), " + "hsDeckId: \(String(describing: hsDeckId)), " + "brawlSeasonId: \(brawlSeasonId), " + "rankedSeasonId: \(rankedSeasonId), " + "arenaWins: \(arenaWins), " + "arenaLosses: \(arenaLosses), " + "brawlWins: \(brawlWins), " + "brawlLosses: \(brawlLosses), " + "format: \(String(describing: format)), " + "hsReplayId: \(String(describing: hsReplayId)), " + "opponentCards: \(opponentCards), " + "revealedCards: \(revealedCards)" } } class GameStats: Object { dynamic var statId = "" override static func primaryKey() -> String? { return "statId" } private dynamic var _playerHero = CardClass.neutral.rawValue var playerHero: CardClass { get { return CardClass(rawValue: _playerHero)! } set { _playerHero = newValue.rawValue } } private dynamic var _opponentHero = CardClass.neutral.rawValue var opponentHero: CardClass { get { return CardClass(rawValue: _opponentHero)! } set { _opponentHero = newValue.rawValue } } dynamic var coin = false private dynamic var _gameMode = GameMode.none.rawValue var gameMode: GameMode { get { return GameMode(rawValue: _gameMode)! } set { _gameMode = newValue.rawValue } } private dynamic var _result = GameResult.unknown.rawValue var result: GameResult { get { return GameResult(rawValue: _result)! } set { _result = newValue.rawValue } } dynamic var turns = -1 dynamic var startTime = Date() dynamic var endTime = Date() dynamic var note = "" dynamic var playerName = "" dynamic var opponentName = "" dynamic var wasConceded = false dynamic var rank = -1 dynamic var stars = -1 dynamic var legendRank = -1 dynamic var opponentLegendRank = -1 dynamic var opponentRank = -1 var hearthstoneBuild = RealmOptional<Int>() dynamic var playerCardbackId = -1 dynamic var opponentCardbackId = -1 dynamic var friendlyPlayerId = -1 dynamic var scenarioId = -1 dynamic var serverInfo: ServerInfo? dynamic var season = 0 private dynamic var _gameType = GameType.gt_unknown.rawValue var gameType: GameType { get { return GameType(rawValue: _gameType)! } set { _gameType = newValue.rawValue } } var hsDeckId = RealmOptional<Int64>() dynamic var brawlSeasonId = -1 dynamic var rankedSeasonId = -1 dynamic var arenaWins = 0 dynamic var arenaLosses = 0 dynamic var brawlWins = 0 dynamic var brawlLosses = 0 dynamic var __format: String? private var _format: Format? { get { if let __format = __format { return Format(rawValue: __format) } return nil } set { __format = newValue?.rawValue ?? nil } } var format: Format? { get { return gameMode == .ranked || gameMode == .casual ? _format : nil } set { _format = newValue } } dynamic var hsReplayId: String? let opponentCards = List<RealmCard>() let revealedCards = List<RealmCard>() let deck = LinkingObjects(fromType: Deck.self, property: "gameStats") }
mit
55c0e2d49fd4ced966c589594a25f5b8
31.516949
77
0.599427
4.438404
false
false
false
false
tomburns/ios
FiveCalls/Pods/Pantry/Pantry/Storable.swift
1
3689
// // Storable.swift // Storable // // Created by Nick O'Neill on 10/29/15. // Copyright © 2015 That Thing in Swift. All rights reserved. // import Foundation /** ## Storable protocol The struct should conform to this protocol. ### sample ```swift struct Basic: Storable { let name: String let age: Float let number: Int init(warehouse: JSONWarehouse) { self.name = warehouse.get("name") ?? "default" self.age = warehouse.get("age") ?? 20.5 self.number = warehouse.get("number") ?? 10 } } ``` */ public protocol Storable { /** Struct initialization - parameter warehouse: the `Warehouseable` object from which you can extract your struct's properties */ init?(warehouse: Warehouseable) /** Dictionary representation Returns the dictioanry representation of the current struct - returns: [String: Any] */ func toDictionary() -> [String: Any] } public extension Storable { /** Dictionary representation Returns the dictioanry representation of the current struct - returns: [String: Any] */ func toDictionary() -> [String: Any] { return Mirror(reflecting: self).toDictionary() } } /** Storage expiry */ public enum StorageExpiry { /// the storage never expires case never /// the storage expires after a given timeout in seconds (`NSTimeInterval`) case seconds(TimeInterval) /// the storage expires at a given date (`NSDate`) case date(Foundation.Date) /** Expiry date Returns the date of the storage expiration - returns NSDate */ func toDate() -> Foundation.Date { switch self { case .never: return Foundation.Date.distantFuture case .seconds(let timeInterval): return Foundation.Date(timeIntervalSinceNow: timeInterval) case .date(let date): return date } } } // MARK: default types that are supported /** Default storable types Default types are `Bool`, `String`, `Int`, `Float`, `Double`, `Date` */ public protocol StorableDefaultType { } extension Bool: StorableDefaultType { } extension String: StorableDefaultType { } extension Int: StorableDefaultType { } extension Float: StorableDefaultType { } extension Double: StorableDefaultType { } // MARK: Provide Storable implementation compatible with JSONSerialization extension Date: Storable { public init?(warehouse: Warehouseable) { if let value: TimeInterval = warehouse.get("timeSince1970") { self.init(timeIntervalSince1970: value) return } return nil } public func toDictionary() -> [String: Any] { return ["timeSince1970": self.timeIntervalSince1970 as Any] } } // MARK: Enums with Raw Values /** * For enums with a raw value such as ```enum: Int```, adding this protocol makes the enum storable. * * You should not need to implement any of the methods or properties in this protocol. * Enums without a raw value e.g. with associated types are not supported. */ public protocol StorableRawEnum: Storable { associatedtype StorableRawType: StorableDefaultType /// Provided automatically for enum's that have a raw value var rawValue: StorableRawType { get } init?(rawValue: StorableRawType) } public extension StorableRawEnum { init?(warehouse: Warehouseable) { if let value: StorableRawType = warehouse.get("rawValue") { self.init(rawValue: value) return } return nil } func toDictionary() -> [String: Any] { return ["rawValue": rawValue as Any] } }
mit
c3ee647b9cc41a941839f7b9de0b24d5
23.918919
106
0.6532
4.385256
false
false
false
false
SimonFairbairn/SwiftyMarkdown
Sources/SwiftyMarkdown/CharacterRule.swift
2
2615
// // CharacterRule.swift // SwiftyMarkdown // // Created by Simon Fairbairn on 04/02/2020. // import Foundation public enum SpaceAllowed { case no case bothSides case oneSide case leadingSide case trailingSide } public enum Cancel { case none case allRemaining case currentSet } public enum CharacterRuleTagType { case open case close case metadataOpen case metadataClose case repeating } public struct CharacterRuleTag { let tag : String let type : CharacterRuleTagType public init( tag : String, type : CharacterRuleTagType ) { self.tag = tag self.type = type } } public struct CharacterRule : CustomStringConvertible { public let primaryTag : CharacterRuleTag public let tags : [CharacterRuleTag] public let escapeCharacters : [Character] public let styles : [Int : CharacterStyling] public let minTags : Int public let maxTags : Int public var metadataLookup : Bool = false public var isRepeatingTag : Bool { return self.primaryTag.type == .repeating } public var definesBoundary = false public var shouldCancelRemainingRules = false public var balancedTags = false public var description: String { return "Character Rule with Open tag: \(self.primaryTag.tag) and current styles : \(self.styles) " } public func tag( for type : CharacterRuleTagType ) -> CharacterRuleTag? { return self.tags.filter({ $0.type == type }).first ?? nil } public init(primaryTag: CharacterRuleTag, otherTags: [CharacterRuleTag], escapeCharacters : [Character] = ["\\"], styles: [Int : CharacterStyling] = [:], minTags : Int = 1, maxTags : Int = 1, metadataLookup : Bool = false, definesBoundary : Bool = false, shouldCancelRemainingRules : Bool = false, balancedTags : Bool = false) { self.primaryTag = primaryTag self.tags = otherTags self.escapeCharacters = escapeCharacters self.styles = styles self.metadataLookup = metadataLookup self.definesBoundary = definesBoundary self.shouldCancelRemainingRules = shouldCancelRemainingRules self.minTags = maxTags < minTags ? maxTags : minTags self.maxTags = minTags > maxTags ? minTags : maxTags self.balancedTags = balancedTags } } enum ElementType { case tag case escape case string case space case newline case metadata } struct Element { let character : Character var type : ElementType var boundaryCount : Int = 0 var isComplete : Bool = false var styles : [CharacterStyling] = [] var metadata : [String] = [] } extension CharacterSet { func containsUnicodeScalars(of character: Character) -> Bool { return character.unicodeScalars.allSatisfy(contains(_:)) } }
mit
83310bc7090ed0b8e2ceff17e316848f
23.212963
329
0.736138
3.70922
false
false
false
false
saitjr/STLoadingGroup
STLoadingGroup/Loading/STArchLoading.swift
1
5931
// // STSpotLoadView.swift // STSpotLoadView-Arch // // Created by TangJR on 1/4/16. // Copyright © 2016 tangjr. All rights reserved. // /* The MIT License (MIT) Copyright (c) 2016 saitjr 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 class STArchLoading: UIView { fileprivate let spotCount = 3 fileprivate var spotGroup: [CAShapeLayer] = [] fileprivate var shadowGroup: [CALayer] = [] internal var isLoading: Bool = false override init(frame: CGRect) { super.init(frame: frame) setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func awakeFromNib() { super.awakeFromNib() setupUI() } override func didMoveToWindow() { super.didMoveToWindow() updateUI() } } extension STArchLoading { fileprivate func setupUI() { for _ in 0 ..< spotCount { let spotLayer = CAShapeLayer() spotLayer.lineCap = "round" spotLayer.lineJoin = "round" spotLayer.lineWidth = lineWidth spotLayer.fillColor = UIColor.clear.cgColor spotLayer.strokeColor = loadingTintColor.cgColor spotLayer.strokeEnd = 0.000001 layer.addSublayer(spotLayer) spotGroup.append(spotLayer) spotLayer.shadowColor = UIColor.black.cgColor spotLayer.shadowOffset = CGSize(width: 10, height: 10) spotLayer.shadowOpacity = 0.2 spotLayer.shadowRadius = 10 } } fileprivate func updateUI() { for i in 0 ..< spotCount { let spotLayer = spotGroup[i] let spotWidth = bounds.width * CGFloat((spotCount - i)) * 0.6 spotLayer.bounds = CGRect(x: 0, y: 0, width: spotWidth, height: spotWidth) spotLayer.position = CGPoint(x: bounds.width * 1.1, y: bounds.height / 2.0) spotLayer.path = UIBezierPath(arcCenter: CGPoint(x: spotWidth / 2.0 - bounds.width * 0.3, y: spotWidth / 2.0), radius: spotWidth * 0.25, startAngle: CGFloat(Double.pi), endAngle: CGFloat(Double.pi * 2), clockwise: true).cgPath } } } extension STArchLoading: STLoadingConfig { var animationDuration: TimeInterval { return 1 } var lineWidth: CGFloat { return 8 } var loadingTintColor: UIColor { return .white } } extension STArchLoading: STLoadingable { internal func startLoading() { guard !isLoading else { return } isLoading = true alpha = 1 for i in 0 ..< spotCount { let spotLayer = spotGroup[i] let transformAnimation = CABasicAnimation(keyPath: "position.x") transformAnimation.fromValue = bounds.width * 1.1 transformAnimation.toValue = bounds.width * 0.5 transformAnimation.duration = animationDuration transformAnimation.fillMode = kCAFillModeForwards transformAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear) transformAnimation.isRemovedOnCompletion = false let strokeEndAnimation = CABasicAnimation(keyPath: "strokeEnd") strokeEndAnimation.fromValue = 0 strokeEndAnimation.toValue = 1 let strokeStartAniamtion = CABasicAnimation(keyPath: "strokeStart") strokeStartAniamtion.fromValue = -1 strokeStartAniamtion.toValue = 1 let strokeAnimationGroup = CAAnimationGroup() strokeAnimationGroup.duration = (animationDuration - TimeInterval(3 - i) * animationDuration * 0.1) * 0.8 strokeAnimationGroup.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) strokeAnimationGroup.fillMode = kCAFillModeForwards strokeAnimationGroup.isRemovedOnCompletion = false strokeAnimationGroup.animations = [strokeStartAniamtion, strokeEndAnimation] let animationGroup = CAAnimationGroup() animationGroup.duration = animationDuration animationGroup.repeatCount = Float.infinity animationGroup.animations = [transformAnimation, strokeAnimationGroup] spotLayer.add(animationGroup, forKey: "animationGroup") } } internal func stopLoading(finish: STEmptyCallback? = nil) { guard isLoading else { return } UIView.animate(withDuration: 0.5, animations: { self.alpha = 0 }, completion: { _ in self.isLoading = false for spotLayer in self.spotGroup { spotLayer.removeAllAnimations() } finish?() }) } }
mit
7cb8a93694617b925d9950a0844c4e17
35.158537
238
0.639798
5.098882
false
false
false
false
syoung-smallwisdom/ResearchUXFactory-iOS
ResearchUXFactoryTests/SurveyNavigationTests.swift
1
21671
// // SBASurveyNavigationTests.swift // ResearchUXFactory // // Copyright © 2016 Sage Bionetworks. All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // 3. Neither the name of the copyright holder(s) nor the names of any contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. No license is granted to the trademarks of // the copyright holders even if such marks are included in this software. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // import XCTest import ResearchUXFactory import ResearchKit class SBASurveyNavigationTests: 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 testQuizStep_Boolean_YES_Passed() { // Create the form step question let formStep = self.createBooleanQuizStep([true]) let result = self.createBooleanTaskResult([true]) // If the question should skip failed passed then the next step identifier is nil // which results in a navigation drop through formStep.failedSkipIdentifier = "skip" let nextStepIdentifier1 = formStep.nextStepIdentifier(with: result, and: nil) XCTAssertNil(nextStepIdentifier1) // If the question should skip if it passes then the next step identifier should // be for the step to skip to formStep.failedSkipIdentifier = nil let nextStepIdentifier2 = formStep.nextStepIdentifier(with: result, and: nil) XCTAssertNotNil(nextStepIdentifier2) XCTAssertEqual(nextStepIdentifier2, "skip") } func testQuizStep_Boolean_YES_Failed() { // Create the form step question let formStep = self.createBooleanQuizStep([true]) let result = self.createBooleanTaskResult([false]) // If the question should skip if it passes then a FAILED result should drop through formStep.failedSkipIdentifier = nil let nextStepIdentifier1 = formStep.nextStepIdentifier(with: result, and: nil) XCTAssertNil(nextStepIdentifier1) // If the question should NOT skip if it passes then a FAILED result should return the // skip step identifier formStep.failedSkipIdentifier = "skip" let nextStepIdentifier2 = formStep.nextStepIdentifier(with: result, and: nil) XCTAssertNotNil(nextStepIdentifier2) XCTAssertEqual(nextStepIdentifier2, "skip") } func testQuizStep_Boolean_NO_Passed() { // Create the form step question let formStep = self.createBooleanQuizStep([false]) let result = self.createBooleanTaskResult([false]) // If the question should skip failed passed then the next step identifier is nil // which results in a navigation drop through formStep.failedSkipIdentifier = "skip" let nextStepIdentifier1 = formStep.nextStepIdentifier(with: result, and: nil) XCTAssertNil(nextStepIdentifier1) // If the question should skip if it passes then the next step identifier should // be for the step to skip to formStep.failedSkipIdentifier = nil let nextStepIdentifier2 = formStep.nextStepIdentifier(with: result, and: nil) XCTAssertNotNil(nextStepIdentifier2) XCTAssertEqual(nextStepIdentifier2, "skip") } func testQuizStep_Boolean_NO_Failed() { // Create the form step question let formStep = self.createBooleanQuizStep([false]) let result = self.createBooleanTaskResult([true]) // If the question should skip if it passes then a FAILED result should drop through formStep.failedSkipIdentifier = nil let nextStepIdentifier1 = formStep.nextStepIdentifier(with: result, and: nil) XCTAssertNil(nextStepIdentifier1) // If the question should NOT skip if it passes then a FAILED result should return the // skip step identifier formStep.failedSkipIdentifier = "skip" let nextStepIdentifier2 = formStep.nextStepIdentifier(with: result, and: nil) XCTAssertNotNil(nextStepIdentifier2) XCTAssertEqual(nextStepIdentifier2, "skip") } func testMultipleFormItemQuizStep_Passed() { // Create the form step question let formStep = self.createBooleanQuizStep([true, false, true]) let result = self.createBooleanTaskResult([true, false, true]) // If the question should skip failed passed then the next step identifier is nil // which results in a navigation drop through formStep.failedSkipIdentifier = "skip" let nextStepIdentifier1 = formStep.nextStepIdentifier(with: result, and: nil) XCTAssertNil(nextStepIdentifier1) // If the question should skip if it passes then the next step identifier should // be for the step to skip to formStep.failedSkipIdentifier = nil let nextStepIdentifier2 = formStep.nextStepIdentifier(with: result, and: nil) XCTAssertNotNil(nextStepIdentifier2) XCTAssertEqual(nextStepIdentifier2, "skip") } func testMultipleFormItemQuizStep_Failed() { // Create the form step question let formStep = self.self.createBooleanQuizStep([true, false, true]) let result = self.createBooleanTaskResult([true, true, true]) // If the question should skip if it passes then a FAILED result should drop through formStep.failedSkipIdentifier = nil let nextStepIdentifier1 = formStep.nextStepIdentifier(with: result, and: nil) XCTAssertNil(nextStepIdentifier1) // If the question should NOT skip if it passes then a FAILED result should return the // skip step identifier formStep.failedSkipIdentifier = "skip" let nextStepIdentifier2 = formStep.nextStepIdentifier(with: result, and: nil) XCTAssertNotNil(nextStepIdentifier2) XCTAssertEqual(nextStepIdentifier2, "skip") } func testTextChoiceQuizStep_Passed() { // Create the form step question let formStep = self.createTextChoiceQuizStep() let result = self.createTextChoiceTaskResult(true) // If the question should skip failed passed then the next step identifier is nil // which results in a navigation drop through formStep.failedSkipIdentifier = "skip" let nextStepIdentifier1 = formStep.nextStepIdentifier(with: result, and: nil) XCTAssertNil(nextStepIdentifier1) // If the question should skip if it passes then the next step identifier should // be for the step to skip to formStep.failedSkipIdentifier = nil let nextStepIdentifier2 = formStep.nextStepIdentifier(with: result, and: nil) XCTAssertNotNil(nextStepIdentifier2) XCTAssertEqual(nextStepIdentifier2, "skip") } func testTextChoiceQuizStep_Failed() { // Create the form step question let formStep = self.createTextChoiceQuizStep() let result = self.createTextChoiceTaskResult(false) // If the question should skip failed passed then the next step identifier is nil // which results in a navigation drop through formStep.failedSkipIdentifier = nil let nextStepIdentifier1 = formStep.nextStepIdentifier(with: result, and: nil) XCTAssertNil(nextStepIdentifier1) // If the question should skip if it passes then the next step identifier should // be for the step to skip to formStep.failedSkipIdentifier = "skip" let nextStepIdentifier2 = formStep.nextStepIdentifier(with: result, and: nil) XCTAssertNotNil(nextStepIdentifier2) XCTAssertEqual(nextStepIdentifier2, "skip") } func testTextChoiceQuizStep_Skipped() { // Create the form step question let formStep = self.createTextChoiceQuizStep() let result = self.createTaskResult("quiz", questionResults: nil) // If the question should skip failed passed then the next step identifier is nil // which results in a navigation drop through formStep.failedSkipIdentifier = nil let nextStepIdentifier1 = formStep.nextStepIdentifier(with: result, and: nil) XCTAssertNil(nextStepIdentifier1) // If the question should skip if it passes then the next step identifier should // be for the step to skip to formStep.failedSkipIdentifier = "skip" let nextStepIdentifier2 = formStep.nextStepIdentifier(with: result, and: nil) XCTAssertNotNil(nextStepIdentifier2) XCTAssertEqual(nextStepIdentifier2, "skip") } func testSubtaskQuizStep_Passed() { let subtaskStep = self.createSubtaskQuizStep([true as AnyObject, false as AnyObject, "b" as AnyObject]) let result = self.createSubtaskTaskResult([true as AnyObject, false as AnyObject, "b" as AnyObject]) // If the question should skip failed passed then the next step identifier is nil // which results in a navigation drop through subtaskStep.failedSkipIdentifier = "skip" let nextStepIdentifier1 = subtaskStep.nextStepIdentifier(with: result, and: nil) XCTAssertNil(nextStepIdentifier1) // If the question should skip if it passes then the next step identifier should // be for the step to skip to subtaskStep.failedSkipIdentifier = nil let nextStepIdentifier2 = subtaskStep.nextStepIdentifier(with: result, and: nil) XCTAssertNotNil(nextStepIdentifier2) XCTAssertEqual(nextStepIdentifier2, "skip") } func testSubtaskQuizStep_Failed() { let subtaskStep = self.createSubtaskQuizStep([true as AnyObject, false as AnyObject, "b" as AnyObject]) let result = self.createSubtaskTaskResult([true as AnyObject, true as AnyObject, "b" as AnyObject]) // If the question should skip failed passed then the next step identifier is nil // which results in a navigation drop through subtaskStep.failedSkipIdentifier = nil let nextStepIdentifier1 = subtaskStep.nextStepIdentifier(with: result, and: nil) XCTAssertNil(nextStepIdentifier1) // If the question should skip if it passes then the next step identifier should // be for the step to skip to subtaskStep.failedSkipIdentifier = "skip" let nextStepIdentifier2 = subtaskStep.nextStepIdentifier(with: result, and: nil) XCTAssertNotNil(nextStepIdentifier2) XCTAssertEqual(nextStepIdentifier2, "skip") } func testSubtaskQuizStep_Loop() { let subtaskStep = self.createSubtaskQuizStep([true as AnyObject, false as AnyObject, "b" as AnyObject]) let result = self.createSubtaskTaskResult(loopResults:[ [true as AnyObject, true as AnyObject, "b" as AnyObject], // failed results [true as AnyObject, false as AnyObject, "b" as AnyObject]]) // passed results // If the question should skip failed passed then the next step identifier is nil // which results in a navigation drop through subtaskStep.failedSkipIdentifier = "skip" let nextStepIdentifier1 = subtaskStep.nextStepIdentifier(with: result, and: nil) XCTAssertNil(nextStepIdentifier1) // If the question should skip if it passes then the next step identifier should // be for the step to skip to subtaskStep.failedSkipIdentifier = nil let nextStepIdentifier2 = subtaskStep.nextStepIdentifier(with: result, and: nil) XCTAssertNotNil(nextStepIdentifier2) XCTAssertEqual(nextStepIdentifier2, "skip") } func testSubtaskQuizStep_Skipped() { let subtaskStep = self.createSubtaskQuizStep([true as AnyObject, false as AnyObject, "b" as AnyObject]) let result = self.createSubtaskTaskResult([true as AnyObject, false as AnyObject, NSNull()]) // If the question should skip failed passed then the next step identifier is nil // which results in a navigation drop through subtaskStep.failedSkipIdentifier = nil let nextStepIdentifier1 = subtaskStep.nextStepIdentifier(with: result, and: nil) XCTAssertNil(nextStepIdentifier1) // If the question should skip if it passes then the next step identifier should // be for the step to skip to subtaskStep.failedSkipIdentifier = "skip" let nextStepIdentifier2 = subtaskStep.nextStepIdentifier(with: result, and: nil) XCTAssertNotNil(nextStepIdentifier2) XCTAssertEqual(nextStepIdentifier2, "skip") } // MARK: helper methods func createSubtaskQuizStep(_ expectedAnswers: [AnyObject]) -> SBANavigationSubtaskStep { var steps: [ORKStep] = [ORKInstructionStep(identifier: "introduction")] var rules: [SBASurveyRuleObject] = [] for (index, expectedAnswer) in expectedAnswers.enumerated() { let identifier = "question\(index+1)" let formStep = ORKFormStep(identifier: identifier, title: "Question \(index+1)", text: nil) if let expectedAnswer = expectedAnswer as? Bool { let (formItem, rule) = self.createBooleanSurveyFormItem(identifier, text: nil, expectedAnswer: expectedAnswer, optional: true) formStep.formItems = [formItem] rules.append(rule) } else if let expectedAnswer = expectedAnswer as? String { let (formItem, rule) = self.createSingleTextChoiceSurveyFormItem(identifier, text: nil, choices: ["a","b","c"], values: nil, expectedAnswer: expectedAnswer as NSCoding & NSCopying & NSObjectProtocol, optional: true) formStep.formItems = [formItem] rules.append(rule) } steps.append(formStep) } let subtaskStep = SBANavigationSubtaskStep(identifier: "quiz", steps: steps) subtaskStep.rules = rules return subtaskStep } func createBooleanQuizStep(_ expectedAnswers: [Bool]) -> SBANavigationFormStep { // Create the form step question let formStep = self.createQuizStep() var formItems: [ORKFormItem] = [] var rules: [SBASurveyRuleObject] = [] for (index, expectedAnswer) in expectedAnswers.enumerated() { let identifier = "question\(index+1)" let (formItem, rule) = self.createBooleanSurveyFormItem(identifier, text: nil, expectedAnswer: expectedAnswer, optional: true) formItems.append(formItem) rules.append(rule) } formStep.formItems = formItems formStep.rules = rules return formStep; } func createBooleanSurveyFormItem(_ identifier:String, text:String?, expectedAnswer: Bool, optional:Bool) -> (ORKFormItem, SBASurveyRuleObject) { let answerFormat = ORKBooleanAnswerFormat() let formItem = ORKFormItem(identifier: identifier, text: text, answerFormat: answerFormat, optional: optional) let rule = SBASurveyRuleObject(identifier: identifier) rule.skipIdentifier = "skip" rule.rulePredicate = NSPredicate(format: "answer = %@", expectedAnswer as CVarArg) return (formItem, rule) } func createSingleTextChoiceSurveyFormItem(_ identifier:String, text:String?, choices:[String], values:[NSCoding & NSCopying & NSObjectProtocol]?, expectedAnswer: NSCoding & NSCopying & NSObjectProtocol, optional:Bool) -> (ORKFormItem, SBASurveyRuleObject) { let answerFormat = self.createSingleTextChoiceAnswerFormat(choices, values: values) let formItem = ORKFormItem(identifier: identifier, text: text, answerFormat: answerFormat, optional: optional) let rule = SBASurveyRuleObject(identifier: identifier) rule.skipIdentifier = "skip" rule.rulePredicate = NSPredicate(format: "answer = %@", [expectedAnswer]) return (formItem, rule) } func createSingleTextChoiceAnswerFormat(_ choices:[String], values:[NSCoding & NSCopying & NSObjectProtocol]?) -> ORKTextChoiceAnswerFormat { // Create the text choices object from the choices and associated values var textChoices: [ORKTextChoice] = [] for (index, choice) in choices.enumerated() { let value = values?[index] ?? choice as NSCoding & NSCopying & NSObjectProtocol textChoices += [ORKTextChoice(text: choice, value: value)] } // Return a survey item of the appropriate type return ORKTextChoiceAnswerFormat(style: .singleChoice, textChoices: textChoices) } func createBooleanTaskResult(_ answers: [Bool]) -> ORKTaskResult { var questionResults: [ORKQuestionResult] = [] for (index, answer) in answers.enumerated() { let identifier = "question\(index+1)" let questionResult = ORKBooleanQuestionResult(identifier:identifier) questionResult.booleanAnswer = answer as NSNumber? questionResults += [questionResult] } return self.createTaskResult("quiz", questionResults: questionResults) } func createTextChoiceQuizStep() -> SBANavigationFormStep { // Create the form step question let formStep = self.createQuizStep() let (formItem, rule) = self.createSingleTextChoiceSurveyFormItem("question1", text: nil, choices: ["a","b","c"], values: nil, expectedAnswer: "b" as NSCoding & NSCopying & NSObjectProtocol, optional: true) formStep.formItems = [formItem] formStep.rules = [rule] return formStep; } func createTextChoiceTaskResult(_ passed: Bool) -> ORKTaskResult { let questionResult = ORKChoiceQuestionResult(identifier: "question1") questionResult.choiceAnswers = passed ? ["b"] : ["a"] return self.createTaskResult("quiz", questionResults: [questionResult]) } func createQuizStep() -> SBANavigationFormStep { let step = SBANavigationFormStep(identifier: "quiz") return step } func createTaskResult(_ quizIdentifier: String, questionResults: [ORKQuestionResult]?) -> ORKTaskResult { let introStepResult = ORKStepResult(identifier: "introduction") let quizStepResult = ORKStepResult(stepIdentifier: quizIdentifier, results:questionResults) let taskResult = ORKTaskResult(identifier: "test"); taskResult.results = [introStepResult, quizStepResult] return taskResult } func createSubtaskTaskResult(_ questionResults: [AnyObject]) -> ORKTaskResult { return createSubtaskTaskResult(loopResults: [questionResults]) } func createSubtaskTaskResult(loopResults: [[AnyObject]]) -> ORKTaskResult { var results: [ORKStepResult] = [ORKStepResult(identifier: "introduction"), ORKStepResult(identifier: "quiz.introduction")] for questionResults in loopResults { for (index, answer) in questionResults.enumerated() { let identifier = "question\(index+1)" var itemResults: [ORKResult]? if let answer = answer as? Bool { let questionResult = ORKBooleanQuestionResult(identifier: identifier) questionResult.booleanAnswer = answer as NSNumber? itemResults = [questionResult] } else if let answer = answer as? String { let questionResult = ORKChoiceQuestionResult(identifier: identifier) questionResult.choiceAnswers = [answer] itemResults = [questionResult] } let stepResult = ORKStepResult(stepIdentifier: "quiz.\(identifier)", results: itemResults) results.append(stepResult) } } let taskResult = ORKTaskResult(identifier: "test") taskResult.results = results return taskResult } }
bsd-3-clause
a1556bcd87e3854b1040a3f8532cfd4d
48.701835
261
0.681264
5.100024
false
false
false
false
zigglzworth/GitHub-Trends
GitHub-Trends/APIEndpointRequest.swift
1
4844
// // APIEndpointRequest.swift // GitHub-Trends // // Created by noasis on 10/1/17. // Copyright © 2017 iyedah. All rights reserved. // import UIKit /* The APIEndpointRequest object is a wrapper for a URLSession request for cleanliness and convinience */ extension String { /// Percent escapes values to be added to a URL query as specified in RFC 3986 /// /// This percent-escapes all characters besides the alphanumeric character set and "-", ".", "_", and "~". /// /// http://www.ietf.org/rfc/rfc3986.txt /// /// - returns: Returns percent-escaped string. func addingPercentEncodingForURLQueryValue() -> String? { let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4 let subDelimitersToEncode = "!$&'()*+,;=" var allowed = CharacterSet.urlQueryAllowed allowed.remove(charactersIn: generalDelimitersToEncode + subDelimitersToEncode) return addingPercentEncoding(withAllowedCharacters: allowed) } } extension Dictionary { /// Build string representation of HTTP parameter dictionary of keys and objects /// /// This percent escapes in compliance with RFC 3986 /// /// http://www.ietf.org/rfc/rfc3986.txt /// /// - returns: String representation in the form of key1=value1&key2=value2 where the keys and values are percent escaped func stringFromHttpParameters() -> String { let parameterArray = map { key, value -> String in let percentEscapedKey = (key as! String).addingPercentEncodingForURLQueryValue()! let percentEscapedValue = (value as! String).addingPercentEncodingForURLQueryValue()! return "\(percentEscapedKey)=\(percentEscapedValue)" } return parameterArray.joined(separator: "&") } } class APIEndpointRequest: NSObject, URLSessionDelegate { var params:[AnyHashable: Any] = [:] var endpointURLString:String? var url:URL? var httpMethod:String = "GET" var currentTask:URLSessionDataTask? func sendRequest(completion:@escaping(Data?, URLResponse?, Error?) -> ()) -> () { let request = NSMutableURLRequest() request.httpMethod = httpMethod request.setValue("application/json", forHTTPHeaderField: "Accept") request.setValue("application/json", forHTTPHeaderField: "Content-Type") do { if (params.count > 0 && request.httpMethod != "GET") { let json = try JSONSerialization.data(withJSONObject: params as Any, options: []) request.httpBody = json if self.url == nil { self.url = URL(string: endpointURLString!)! } } else if request.httpMethod == "GET" { if self.url == nil { if params.count > 0 { let parameterString = params.stringFromHttpParameters() self.url = URL(string: endpointURLString! + "?" + parameterString)! } else { self.url = URL(string: endpointURLString!)! } } } request.url = self.url let config = URLSessionConfiguration.default let session = URLSession.init(configuration: config) let task = session.dataTask(with: request as URLRequest) { (data, response, err) in if (err != nil) { print("sendRequest error \(String(describing: err))") } completion(data, response, err) } task.resume() } catch { let userInfo: [AnyHashable : Any] = [ NSLocalizedDescriptionKey : NSLocalizedString("RequestError", value: "The URLSession request failed", comment: "") , NSLocalizedFailureReasonErrorKey : NSLocalizedString("RequestError", value: "Failed \(self.httpMethod) request to \(String(describing: self.endpointURLString))", comment: "") ] let err = NSError(domain: "APIEndpointRequest", code: 404, userInfo: userInfo) completion(nil, nil, err) } } func cancel() { if currentTask != nil { currentTask?.cancel() } } }
mit
ef8ce9f01d4546fd7dac88e015cdf4ba
28.895062
194
0.534792
5.690952
false
false
false
false
Estimote/iOS-SDK
Examples/swift/Configuration/Extras/Scanner/Estimote/MajorMinorID.swift
1
638
struct MajorMinorID: Equatable, Hashable, CustomStringConvertible { let major: CLBeaconMajorValue let minor: CLBeaconMinorValue fileprivate let majorMinorString: String init(major: CLBeaconMajorValue, minor: CLBeaconMinorValue) { self.major = major self.minor = minor majorMinorString = "\(major):\(minor)" } var description: String { get { return majorMinorString } } var hashValue: Int { get { return majorMinorString.hashValue } } } func ==(lhs: MajorMinorID, rhs: MajorMinorID) -> Bool { return lhs.major == rhs.major && lhs.minor == rhs.minor }
mit
56bb676deba628d521576dd7feee862c
22.62963
67
0.658307
4.340136
false
false
false
false
PGSSoft/ParallaxView
Sources/Extensions/ParallaxableView+Extensions.swift
1
6098
// // ParallaxableView+Extensions.swift // ParallaxView // // Created by Łukasz Śliwiński on 20/06/16. // // import UIKit /// Actions for a parallax view open class ParallaxViewActions<T: UIView> where T: ParallaxableView { /// Closure will be called in animation block by ParallaxableView when view should change its appearance to the focused state open var setupUnfocusedState: ((T) -> Void)? /// Closure will be called in animation block by ParallaxableView when view should change its appearance to the unfocused state open var setupFocusedState: ((T) -> Void)? /// Closure will be called by ParallaxableView before the animation to the focused state start open var beforeBecomeFocusedAnimation: ((T) -> Void)? /// Closure will be called by ParallaxableView before the animation to the unfocused state start open var beforeResignFocusAnimation: ((T) -> Void)? /// Closure will be called when didFocusChange happened. In most cases default implementation should work open var becomeFocused: ((T, _ context: UIFocusUpdateContext, _ animationCoordinator: UIFocusAnimationCoordinator) -> Void)? /// Closure will be called when didFocusChange happened. In most cases default implementation should work open var resignFocus: ((T, _ context: UIFocusUpdateContext, _ animationCoordinator: UIFocusAnimationCoordinator) -> Void)? /// Default implementation of the press begin animation for the ParallaxableView open var animatePressIn: ((T, _ presses: Set<UIPress>, _ event: UIPressesEvent?) -> Void)? /// Default implementation of the press ended animation for the ParallaxableView open var animatePressOut: ((T, _ presses: Set<UIPress>, _ event: UIPressesEvent?) -> Void)? /// Creates actions for parallax view with default behaviours public init() { becomeFocused = { [weak self] (view: T, context, coordinator) in self?.beforeBecomeFocusedAnimation?(view) if #available(tvOS 11.0, *) { coordinator.addCoordinatedFocusingAnimations( { (context) in self?.setupFocusedState?(view) view.addParallaxMotionEffects(with: &view.parallaxEffectOptions) }, completion: nil ) } else { coordinator.addCoordinatedAnimations( { view.addParallaxMotionEffects(with: &view.parallaxEffectOptions) self?.setupFocusedState?(view) }, completion: nil ) } } resignFocus = { [weak self] (view: T, context, coordinator) in self?.beforeResignFocusAnimation?(view) if #available(tvOS 11.0, *) { coordinator.addCoordinatedUnfocusingAnimations( { (context) in view.removeParallaxMotionEffects(with: view.parallaxEffectOptions) self?.setupUnfocusedState?(view) }, completion: nil ) } else { coordinator.addCoordinatedAnimations( { view.removeParallaxMotionEffects(with: view.parallaxEffectOptions) self?.setupUnfocusedState?(view) }, completion: nil ) } } animatePressIn = { (view: T, presses, event) in for press in presses { if case .select = press.type { UIView.animate( withDuration: 0.12, animations: { view.transform = CGAffineTransform(scaleX: 0.95, y: 0.95) } ) } } } animatePressOut = { [weak self] (view: T, presses, event) in for press in presses { if case .select = press.type { UIView.animate( withDuration: 0.12, animations: { if view.isFocused { view.transform = CGAffineTransform.identity self?.setupFocusedState?(view) } else { view.transform = CGAffineTransform.identity self?.setupUnfocusedState?(view) } } ) } } } } } extension ParallaxableView where Self: UIView { // MARK: Properties /// The corner radius for the parallax view and if applicable also applied to the glow effect public var cornerRadius: CGFloat { get { return self.layer.cornerRadius } set { self.layer.cornerRadius = newValue // Change the glowEffectContainerView corner radius only if it is a direct subview of the parallax view if let glowEffectContainerView = parallaxEffectOptions.glowContainerView, self.subviews.contains(glowEffectContainerView) { glowEffectContainerView.layer.cornerRadius = newValue } } } // MARK: ParallaxableView /// Get the glow image view that can be used to create the glow effect /// - Returns: Image with radial gradient/shadow to imitate glow public func getGlowImageView() -> UIImageView? { return parallaxEffectOptions.glowContainerView?.subviews.filter({ (view) -> Bool in if let glowImageView = view as? UIImageView, let glowImage = glowImageView.image, glowImage.accessibilityIdentifier == glowImageAccessibilityIdentifier { return true } return false }).first as? UIImageView } }
mit
01149037ce6d6511da91bcdcc74c2342
39.633333
131
0.55767
5.540909
false
false
false
false
ishkawa/APIKit
Sources/APIKit/BodyParameters/MultipartFormDataBodyParameters.swift
1
12354
import Foundation #if os(iOS) || os(watchOS) || os(tvOS) import MobileCoreServices #elseif os(OSX) import CoreServices #endif #if SWIFT_PACKAGE class AbstractInputStream: InputStream { init() { super.init(data: Data()) } } #endif /// `FormURLEncodedBodyParameters` serializes array of `Part` for HTTP body and states its content type is multipart/form-data. public struct MultipartFormDataBodyParameters: BodyParameters { /// `EntityType` represents whether the entity is expressed as `Data` or `InputStream`. public enum EntityType { /// Expresses the entity as `Data`, which has faster upload speed and larger memory usage. case data /// Expresses the entity as `InputStream`, which has smaller memory usage and slower upload speed. case inputStream } public let parts: [Part] public let boundary: String public let entityType: EntityType public init(parts: [Part], boundary: String = String(format: "%08x%08x", arc4random(), arc4random()), entityType: EntityType = .data) { self.parts = parts self.boundary = boundary self.entityType = entityType } // MARK: BodyParameters /// `Content-Type` to send. The value for this property will be set to `Accept` HTTP header field. public var contentType: String { return "multipart/form-data; boundary=\(boundary)" } /// Builds `RequestBodyEntity.data` that represents `form`. public func buildEntity() throws -> RequestBodyEntity { let inputStream = MultipartInputStream(parts: parts, boundary: boundary) switch entityType { case .inputStream: return .inputStream(inputStream) case .data: return .data(try Data(inputStream: inputStream)) } } } public extension MultipartFormDataBodyParameters { /// Part represents single part of multipart/form-data. struct Part { public enum Error: Swift.Error { case illegalValue(Any) case illegalFileURL(URL) case cannotGetFileSize(URL) } public let inputStream: InputStream public let name: String public let mimeType: String? public let fileName: String? public let count: Int /// Returns Part instance that has data presentation of passed value. /// `value` will be converted via `String(_:)` and serialized via `String.dataUsingEncoding(_:)`. /// If `mimeType` or `fileName` are `nil`, the fields will be omitted. public init(value: Any, name: String, mimeType: String? = nil, fileName: String? = nil, encoding: String.Encoding = .utf8) throws { guard let data = String(describing: value).data(using: encoding) else { throw Error.illegalValue(value) } self.inputStream = InputStream(data: data) self.name = name self.mimeType = mimeType self.fileName = fileName self.count = data.count } /// Returns Part instance that has input stream of specified data. /// If `mimeType` or `fileName` are `nil`, the fields will be omitted. public init(data: Data, name: String, mimeType: String? = nil, fileName: String? = nil) { self.inputStream = InputStream(data: data) self.name = name self.mimeType = mimeType self.fileName = fileName self.count = data.count } /// Returns Part instance that has input stream of specified file URL. /// If `mimeType` or `fileName` are `nil`, values for the fields will be detected from URL. public init(fileURL: URL, name: String, mimeType: String? = nil, fileName: String? = nil) throws { guard let inputStream = InputStream(url: fileURL) else { throw Error.illegalFileURL(fileURL) } let fileSize = (try? FileManager.default.attributesOfItem(atPath: fileURL.path)) .flatMap { $0[FileAttributeKey.size] as? NSNumber } .map { $0.intValue } guard let bodyLength = fileSize else { throw Error.cannotGetFileSize(fileURL) } let detectedMimeType = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, fileURL.pathExtension as CFString, nil) .map { $0.takeRetainedValue() } .flatMap { UTTypeCopyPreferredTagWithClass($0, kUTTagClassMIMEType)?.takeRetainedValue() } .map { $0 as String } self.inputStream = inputStream self.name = name self.mimeType = mimeType ?? detectedMimeType ?? "application/octet-stream" self.fileName = fileName ?? fileURL.lastPathComponent self.count = bodyLength } } internal class PartInputStream: AbstractInputStream { let headerData: Data let footerData: Data let bodyPart: Part let totalLength: Int var totalSentLength: Int init(part: Part, boundary: String) { let header: String switch (part.mimeType, part.fileName) { case (let mimeType?, let fileName?): header = "--\(boundary)\r\nContent-Disposition: form-data; name=\"\(part.name)\"; filename=\"\(fileName)\"\r\nContent-Type: \(mimeType)\r\n\r\n" case (let mimeType?, _): header = "--\(boundary)\r\nContent-Disposition: form-data; name=\"\(part.name)\"; \r\nContent-Type: \(mimeType)\r\n\r\n" default: header = "--\(boundary)\r\nContent-Disposition: form-data; name=\"\(part.name)\"\r\n\r\n" } headerData = header.data(using: .utf8)! footerData = "\r\n".data(using: .utf8)! bodyPart = part totalLength = headerData.count + bodyPart.count + footerData.count totalSentLength = 0 super.init() } var headerRange: Range<Int> { return 0..<headerData.count } var bodyRange: Range<Int> { return headerRange.upperBound..<(headerRange.upperBound + bodyPart.count) } var footerRange: Range<Int> { return bodyRange.upperBound..<(bodyRange.upperBound + footerData.count) } // MARK: InputStream override var hasBytesAvailable: Bool { return totalSentLength < totalLength } override func read(_ buffer: UnsafeMutablePointer<UInt8>, maxLength: Int) -> Int { var sentLength = 0 while sentLength < maxLength && totalSentLength < totalLength { let offsetBuffer = buffer + sentLength let availableLength = maxLength - sentLength switch totalSentLength { case headerRange: let readLength = min(headerRange.upperBound - totalSentLength, availableLength) let readRange = NSRange(location: totalSentLength - headerRange.lowerBound, length: readLength) (headerData as NSData).getBytes(offsetBuffer, range: readRange) sentLength += readLength totalSentLength += sentLength case bodyRange: if bodyPart.inputStream.streamStatus == .notOpen { bodyPart.inputStream.open() } let readLength = bodyPart.inputStream.read(offsetBuffer, maxLength: availableLength) sentLength += readLength totalSentLength += readLength case footerRange: let readLength = min(footerRange.upperBound - totalSentLength, availableLength) let range = NSRange(location: totalSentLength - footerRange.lowerBound, length: readLength) (footerData as NSData).getBytes(offsetBuffer, range: range) sentLength += readLength totalSentLength += readLength default: print("Illegal range access: \(totalSentLength) is out of \(headerRange.lowerBound)..<\(footerRange.upperBound)") return -1 } } return sentLength; } } internal class MultipartInputStream: AbstractInputStream { let boundary: String let partStreams: [PartInputStream] let footerData: Data let totalLength: Int var totalSentLength: Int private var privateStreamStatus = Stream.Status.notOpen init(parts: [Part], boundary: String) { self.boundary = boundary self.partStreams = parts.map { PartInputStream(part: $0, boundary: boundary) } self.footerData = "--\(boundary)--\r\n".data(using: .utf8)! self.totalLength = partStreams.reduce(footerData.count) { $0 + $1.totalLength } self.totalSentLength = 0 super.init() } var partsRange: Range<Int> { return 0..<partStreams.reduce(0) { $0 + $1.totalLength } } var footerRange: Range<Int> { return partsRange.upperBound..<(partsRange.upperBound + footerData.count) } var currentPartInputStream: PartInputStream? { var currentOffset = 0 for partStream in partStreams { let partStreamRange = currentOffset..<(currentOffset + partStream.totalLength) if partStreamRange.contains(totalSentLength) { return partStream } currentOffset += partStream.totalLength } return nil } // MARK: InputStream // NOTE: InputStream does not have its own implementation because it is a class cluster. override var streamStatus: Stream.Status { return privateStreamStatus } override var hasBytesAvailable: Bool { return totalSentLength < totalLength } override func open() { privateStreamStatus = .open } override func close() { privateStreamStatus = .closed } override func read(_ buffer: UnsafeMutablePointer<UInt8>, maxLength: Int) -> Int { privateStreamStatus = .reading var sentLength = 0 while sentLength < maxLength && totalSentLength < totalLength { let offsetBuffer = buffer + sentLength let availableLength = maxLength - sentLength switch totalSentLength { case partsRange: guard let partStream = currentPartInputStream else { print("Illegal offset \(totalLength) for part streams \(partsRange)") return -1 } let readLength = partStream.read(offsetBuffer, maxLength: availableLength) sentLength += readLength totalSentLength += readLength case footerRange: let readLength = min(footerRange.upperBound - totalSentLength, availableLength) let range = NSRange(location: totalSentLength - footerRange.lowerBound, length: readLength) (footerData as NSData).getBytes(offsetBuffer, range: range) sentLength += readLength totalSentLength += readLength default: print("Illegal range access: \(totalSentLength) is out of \(partsRange.lowerBound)..<\(footerRange.upperBound)") return -1 } if privateStreamStatus != .closed && !hasBytesAvailable { privateStreamStatus = .atEnd } } return sentLength } override var delegate: StreamDelegate? { get { return nil } set { } } override func schedule(in aRunLoop: RunLoop, forMode mode: RunLoop.Mode) { } override func remove(from aRunLoop: RunLoop, forMode mode: RunLoop.Mode) { } } } #if !swift(>=4.2) extension RunLoop { internal typealias Mode = RunLoopMode } #endif
mit
02e097f6bbe17d06144c8dfb4d1f82c5
35.988024
160
0.587016
5.166876
false
false
false
false
kstaring/swift
test/Interpreter/SDK/autolinking.swift
14
1077
// RUN: rm -rf %t && mkdir -p %t // RUN: echo "int global() { return 42; }" | %clang -dynamiclib -o %t/libLinkMe.dylib -x c - // RUN: %target-swift-frontend -emit-module -parse-stdlib -o %t -module-name LinkMe -module-link-name LinkMe %S/../../Inputs/empty.swift // RUN: %target-jit-run -DIMPORT %s -I %t -L %t 2>&1 // RUN: %target-jit-run -lLinkMe %s -L %t 2>&1 // RUN: not %target-jit-run -lLinkMe %s 2>&1 // RUN: %target-jit-run -lLinkMe -DUSE_DIRECTLY %s -L %t 2>&1 // RUN: not %target-jit-run -DUSE_DIRECTLY -lLinkMe %s 2>&1 // REQUIRES: executable_test // This is specifically testing autolinking for immediate mode. Please do not // change it to use %target-build/%target-run // REQUIRES: swift_interpreter // REQUIRES: OS=macosx import Darwin #if IMPORT import LinkMe #endif #if USE_DIRECTLY @_silgen_name("global") func global() -> Int32 if global() != 42 { exit(EXIT_FAILURE) } #else let RTLD_DEFAULT = UnsafeMutableRawPointer(bitPattern: -2) if dlsym(RTLD_DEFAULT, "global") == nil { print(String(cString: dlerror())) exit(EXIT_FAILURE) } #endif
apache-2.0
679941ad3f38e9e542eeb74f1a66d4dd
24.642857
136
0.669452
2.826772
false
false
false
false
huangboju/Moots
Examples/SwiftUI/Combine/CombineSwiftPlayground-master/Combine.playground/Pages/Debugging.xcplaygroundpage/Contents.swift
1
1828
//: [Previous](@previous) import Foundation import UIKit import Combine /*: ## Debugging Operators which help debug Combine publishers More info: [https://www.avanderlee.com/debugging/combine-swift/‎](https://www.avanderlee.com/debugging/combine-swift/‎) */ enum ExampleError: Swift.Error { case somethingWentWrong } /*: ### Handling events Can be used combined with breakpoints for further insights. - exposes all the possible events happening inside a publisher / subscription couple - very useful when developing your own publishers */ let subject = PassthroughSubject<String, ExampleError>() let subscription = subject .handleEvents(receiveSubscription: { (subscription) in print("Receive subscription") }, receiveOutput: { output in print("Received output: \(output)") }, receiveCompletion: { _ in print("Receive completion") }, receiveCancel: { print("Receive cancel") }, receiveRequest: { demand in print("Receive request: \(demand)") }).replaceError(with: "Error occurred").sink { _ in } subject.send("Hello!") subscription.cancel() // Prints out: // Receive request: unlimited // Receive subscription // Received output: Hello! // Receive cancel //subject.send(completion: .finished) /*: ### `print(_:)` Prints log messages for every event */ let printSubscription = subject .print("Print example") .replaceError(with: "Error occurred") .sink { _ in } subject.send("Hello!") printSubscription.cancel() // Prints out: // Print example: receive subscription: (PassthroughSubject) // Print example: request unlimited // Print example: receive value: (Hello!) // Print example: receive cancel /*: ### `breakpoint(_:)` Conditionally break in the debugger when specific values pass through */ let breakSubscription = subject .breakpoint(receiveOutput: { value in value == "Hello!" })
mit
cceb15ac531efc6eb03a77d13d14eadc
23.648649
119
0.730811
3.922581
false
false
false
false
luksfarris/SwiftRandomForest
SwiftRandomForest/DataStructures/MatrixReference.swift
1
3771
//MIT License // //Copyright (c) 2017 Lucas Farris // //Permission is hereby granted, free of charge, to any person obtaining a copy //of this software and associated documentation files (the "Software"), to deal //in the Software without restriction, including without limitation the rights //to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //copies of the Software, and to permit persons to whom the Software is //furnished to do so, subject to the following conditions: // //The above copyright notice and this permission notice shall be included in all //copies or substantial portions of the Software. // //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE //SOFTWARE. import Foundation class MatrixReference<T:Numeric> { public private(set) var matrix:Matrix<T> public private(set) var rows:Array<Int> = [] public private(set) var count:Int = 0 public private(set) var maxCount:Int = 0 public private(set) var columns:Int = 0 init (matrix:Matrix<T>) { self.matrix = matrix self.maxCount = matrix.rows self.columns = matrix.columns } init (matrixReference:MatrixReference<T>, count:Int) { self.matrix = matrixReference.matrix self.maxCount = count self.columns = matrixReference.columns } public func elementAt(_ row:Int, _ column:Int) -> T { let realRow = self.rows[row] return self.matrix[realRow,column] } public func rowAtIndex(_ index: Int) -> ArraySlice<T> { let realIndex = self.rows[index] return self.matrix.rowAtIndex(realIndex) } public func remove(_ index:Int) -> Int { let poppedIndex:Int = self.rows.remove(at: index) self.count -= 1 self.maxCount -= 1 return poppedIndex } public func append(index:Int) { self.count += 1 self.rows.append(index) } public func append(otherMatrix:MatrixReference<T>) { self.count += otherMatrix.count for i in 0..<otherMatrix.count { let value = otherMatrix.rows[i] self.rows.append(value) } } public func fill(_ count:Int) { self.count = count for i in 0..<self.count { self.rows.append(i) } } func makeIterator() -> MatrixReferenceIterator<T> { return MatrixReferenceIterator<T>(rows: self.rows, count:self.count, matrix:self.matrix) } } struct MatrixReferenceIterator<T:Numeric> : IteratorProtocol { private var rows:Array<Int> private var matrix:Matrix<T> private var count:Int private var index = 0 init(rows:Array<Int>, count:Int, matrix:Matrix<T>) { self.rows = rows self.count = count self.matrix = matrix } mutating func next() -> ArraySlice<T>? { if self.index < self.count { let realIndex = self.rows[self.index] self.index += 1 return self.matrix.rowAtIndex(realIndex) } else { return nil } } } extension MatrixReference { var outputs: Array<T> { var outputsArray:Array<T> = [] for i in 0..<self.count { let row = self.rows[i] outputsArray.append(self.matrix[row,self.columns - 1]) } return outputsArray } }
mit
be0d523cfbd46c1299cdf53a81c99c29
30.957627
96
0.639883
4.116812
false
false
false
false
huangboju/Moots
UICollectionViewLayout/SpreadsheetView-master/Examples/Timetable/Sources/Models.swift
2
949
// // Models.swift // SpreadsheetView // // Created by Kishikawa Katsumi on 5/11/17. // Copyright © 2017 Kishikawa Katsumi. All rights reserved. // import UIKit struct Table { var slots = [String: [Slot]]() mutating func add(slot: Slot) { let slots = self[slot.channelId] if var slots = slots { slots.append(slot) self[slot.channelId] = slots } else { var slots = [Slot]() slots.append(slot) self[slot.channelId] = slots } } subscript(key: String) -> [Slot]? { get { return slots[key] } set(newValue) { return slots[key] = newValue } } } struct Channel { let id: String let name: String let order: Int } struct Slot { let id: String let title: String let startAt: Int let endAt: Int let tableHighlight: String let channelId: String }
mit
59d57bd5c6f294cc873565987f5388de
18.346939
60
0.545359
3.93361
false
false
false
false
cezarywojcik/Operations
Sources/Core/iOS/BackgroundObserver.swift
1
2895
// // BackgroundObserver.swift // Operations // // Created by Daniel Thorpe on 19/07/2015. // Copyright © 2015 Daniel Thorpe. All rights reserved. // import UIKit public protocol BackgroundTaskApplicationInterface { var applicationState: UIApplication.State { get } func beginBackgroundTask(withName taskName: String?, expirationHandler handler: (() -> Void)?) -> UIBackgroundTaskIdentifier func endBackgroundTask(_ identifier: UIBackgroundTaskIdentifier) } extension UIApplication: BackgroundTaskApplicationInterface { } /** An observer which will automatically start & stop a background task if the application enters the background. Attach a `BackgroundObserver` to an operation which must be completed even if the app goes in the background. */ open class BackgroundObserver: NSObject { static let backgroundTaskName = "Background Operation Observer" fileprivate var identifier: UIBackgroundTaskIdentifier? = .none fileprivate let application: BackgroundTaskApplicationInterface fileprivate var isInBackground: Bool { return application.applicationState == .background } /// Initialize a `BackgroundObserver`, takes no parameters. public override convenience init() { self.init(app: UIApplication.shared) } init(app: BackgroundTaskApplicationInterface) { application = app super.init() let nc = NotificationCenter.default nc.addObserver(self, selector: #selector(BackgroundObserver.didEnterBackground(_:)), name: UIApplication.didEnterBackgroundNotification, object: .none) nc.addObserver(self, selector: #selector(BackgroundObserver.didBecomeActive(_:)), name: UIApplication.didBecomeActiveNotification, object: .none) if isInBackground { startBackgroundTask() } } deinit { NotificationCenter.default.removeObserver(self) } @objc func didEnterBackground(_ notification: Notification) { if isInBackground { startBackgroundTask() } } @objc func didBecomeActive(_ notification: Notification) { if !isInBackground { endBackgroundTask() } } fileprivate func startBackgroundTask() { if identifier == nil { identifier = application.beginBackgroundTask(withName: type(of: self).backgroundTaskName) { self.endBackgroundTask() } } } fileprivate func endBackgroundTask() { if let id = identifier { application.endBackgroundTask(id) identifier = .none } } } extension BackgroundObserver: OperationDidFinishObserver { /// Conforms to `OperationDidFinishObserver`, will end any background task that has been started. public func didFinishOperation(_ operation: AdvancedOperation, errors: [Error]) { endBackgroundTask() } }
mit
de68760ff009161b280ad6a2d4880e6f
29.787234
159
0.697996
5.491461
false
false
false
false
bikemap/reachability
Reachability.swift
1
6304
// // Reachability.swift // Bikemap // // Created by Adam Eri on 12/07/2017. // Copyright © 2017 Bikemap GmbH. All rights reserved. // import Foundation import SystemConfiguration /// Possible statuses of reachability /// /// - reachable: Reachable, there is connection /// - cellular: Reachable, there is connection via cellular network /// - offline: Not reachable, we are offline public enum ReachabilityStatus { /// Reachable, there is connection case online /// Reachable, there is connection via cellular network case cellular /// Not reachable, we are offline case offline /// There was an error initiating the network status, so we do not know /// if there is a connection. case unknown } /// Closure for receiveing reachability change events. /// It receives two statuses, `from` and `to`, so you can have /// custom logic based on the previous status. public typealias ReachabilityStatusChangeHandler = (ReachabilityStatus, ReachabilityStatus) -> Void /// Reachability is a dead-simple wrapper for SCNetworkReachability /// It provides very simple interaction with the network status. And /// honestly, that is all you need, no-one cares about the /// `interventionRequired` state. /// /// You have three options: /// - online /// - cellular /// - offline /// /// And there is a convenience `isOnline` parameter. /// /// You can register for receving status by setting the `onChange` closure. /// See `ReachabilityStatusChangeHandler` /// /// You need to `init()` the class, and it might throw you an error if there /// is a problem. See `ReachabilityError`. /// final public class Reachability { /// The reference to the actual SCNetworkReachability class. private var networkReachability: SCNetworkReachability? fileprivate let queue = DispatchQueue(label: "net.bikemap.reachability") /// The current reachability status. public var status: ReachabilityStatus = .offline /// Convenience method for checking if we are online and not caring about /// whether it is cellular or not. public var isOnline: Bool { return self.status == .cellular || self.status == .online } /// Closure executed when there is a change in the network status public var onChange: ReachabilityStatusChangeHandler? /// Initiates a Reachability object. /// Reachability treats the 0.0.0.0 address as a special token that causes /// it to monitor the general routing status of the device, /// both IPv4 and IPv6. @discardableResult init(onChange: ReachabilityStatusChangeHandler? = nil) { var address = sockaddr_in() address.sin_len = UInt8(MemoryLayout<sockaddr_in>.size) address.sin_family = sa_family_t(AF_INET) self.networkReachability = withUnsafePointer(to: &address, { pointer in return pointer.withMemoryRebound( to: sockaddr.self, capacity: MemoryLayout<sockaddr>.size) { return SCNetworkReachabilityCreateWithAddress(nil, $0) } }) guard self.networkReachability != nil, self.flags != nil else { self.status = .unknown return } if self.processReachabilityFlags(self.flags!) == .unknown { return } if onChange != nil { self.onChange = onChange self.listen() } } /// Stop listener on deinit deinit { stopListening() } // MARK: - Private Utils /// Processes the incoming SCNetworkReachabilityFlags and returns a /// ReachabilityStatus. /// /// - Parameter flags: SCNetworkReachabilityFlags received from the system /// - Returns: ReachabilityStatus private func processReachabilityFlags( _ flags: SCNetworkReachabilityFlags) -> ReachabilityStatus { guard self.isReachable(with: flags) == true else { return .offline } self.status = .online #if os(iOS) if flags.contains(.isWWAN) { self.status = .cellular } #endif return self.status } private var flags: SCNetworkReachabilityFlags? { var flags = SCNetworkReachabilityFlags() if SCNetworkReachabilityGetFlags(self.networkReachability!, &flags) { return flags } return nil } /// Being actually reachable is not trivial... private func isReachable(with flags: SCNetworkReachabilityFlags) -> Bool { let isReachable = flags.contains(.reachable) let needsConnection = flags.contains(.connectionRequired) let canConnectAutomatically = flags.contains(.connectionOnDemand) || flags.contains(.connectionOnTraffic) let canConnectWithoutUserInteraction = canConnectAutomatically && !flags.contains(.interventionRequired) return isReachable && (!needsConnection || canConnectWithoutUserInteraction) } /// Starts the listener for changes to network reachability private func listen() { var context = SCNetworkReachabilityContext( version: 0, info: nil, retain: nil, release: nil, copyDescription: nil) // Mind the `passRetained` here. As the class might not be retained at // the caller function, we retain it here. context.info = UnsafeMutableRawPointer( Unmanaged<Reachability>.passRetained(self).toOpaque()) let callback: SCNetworkReachabilityCallBack? = { (reachability: SCNetworkReachability, flags: SCNetworkReachabilityFlags, info: UnsafeMutableRawPointer?) in guard info != nil else { return } let handler = Unmanaged<Reachability> .fromOpaque(info!).takeUnretainedValue() DispatchQueue.main.async { let oldStatus = handler.status let newStatus = handler.processReachabilityFlags(flags) handler.onChange!(newStatus, oldStatus) } } if SCNetworkReachabilitySetCallback( self.networkReachability!, callback, &context) == false { self.status = .unknown } if SCNetworkReachabilitySetDispatchQueue( self.networkReachability!, queue) == false { self.status = .unknown } // Initial call of the handler, to notifiy the listener on the current // status. self.onChange!(self.status, self.status) } // Stops the listener private func stopListening() { SCNetworkReachabilitySetCallback(self.networkReachability!, nil, nil) SCNetworkReachabilitySetDispatchQueue(self.networkReachability!, nil) } }
mit
37c9adb8a5757b8a7eb3d74be699e9a9
28.872038
80
0.701253
4.87471
false
false
false
false
ruter/Strap-in-Swift
GuessTheFlag/GuessTheFlag/ViewController.swift
1
2286
// // ViewController.swift // GuessTheFlag // // Created by Ruter on 16/4/13. // Copyright © 2016年 Ruter. All rights reserved. // import UIKit import GameplayKit class ViewController: UIViewController { @IBOutlet weak var button1: UIButton! @IBOutlet weak var button2: UIButton! @IBOutlet weak var button3: UIButton! var countries = [String]() var correctAnswer = 0 var score = 0 override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. countries += ["estonia", "france", "germany", "ireland", "italy", "monaco", "nigeria", "poland", "russia", "spain", "uk", "us"] button1.layer.borderWidth = 1 button2.layer.borderWidth = 1 button3.layer.borderWidth = 1 button1.layer.borderColor = UIColor.lightGrayColor().CGColor button2.layer.borderColor = UIColor.lightGrayColor().CGColor button3.layer.borderColor = UIColor.lightGrayColor().CGColor askQuestion() } func askQuestion(action: UIAlertAction! = nil) { // Shuffling objects in array countries = GKRandomSource.sharedRandom().arrayByShufflingObjectsInArray(countries) as! [String] button1.setImage(UIImage(named: countries[0]), forState: .Normal) button2.setImage(UIImage(named: countries[1]), forState: .Normal) button3.setImage(UIImage(named: countries[2]), forState: .Normal) // Generate a random number between 0 and (upper bound - 1) correctAnswer = GKRandomSource.sharedRandom().nextIntWithUpperBound(3) // Set title for navigation bar title = countries[correctAnswer].uppercaseString } @IBAction func buttonTapped(sender: UIButton) { var title: String if sender.tag == correctAnswer { title = "Correct" score += 1 } else { title = "Wrong" score -= 1 } let ac = UIAlertController(title: title, message: "Your score is \(score).", preferredStyle: .Alert) ac.addAction(UIAlertAction(title: "Continue", style: .Default, handler: askQuestion)) presentViewController(ac, animated: true, completion: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
apache-2.0
d71873e994d013698709175bfc2f9228
28.649351
131
0.683749
4.323864
false
false
false
false
413738916/ZhiBoTest
ZhiBoSwift/ZhiBoSwift/Classes/Tools/Extension/UIBarButtonItem-Extension.swift
1
1319
// // UIBarButtonItem-Extension.swift // ZhiBoSwift // // Created by 123 on 2017/10/24. // Copyright © 2017年 ct. All rights reserved. // import Foundation import UIKit extension UIBarButtonItem { /* //类方法 class func createItem(imageName : String, highImageName : String, size : CGSize) -> UIBarButtonItem { let btn = UIButton() btn.setImage(UIImage(named: imageName), for: .normal) btn.setImage(UIImage(named: highImageName), for: .highlighted) btn.frame = CGRect(origin: CGPoint.zero, size: size) return UIBarButtonItem(customView: btn) } */ // 便利构造函数: 1> convenience开头 2> 在构造函数中必须明确调用一个设计的构造函数(self) convenience init(imageName : String, highImageName : String = "", size : CGSize = CGSize.zero) { let btn = UIButton() btn.setImage(UIImage(named: imageName), for: UIControlState()) if highImageName != "" { btn.setImage(UIImage(named: highImageName), for: .highlighted) } if size == CGSize.zero { btn.sizeToFit() } else { btn.frame = CGRect(origin: CGPoint.zero, size: size) } self.init(customView:btn) } }
mit
68671d33d327ddad1c4aaa3b587f5f51
25.638298
105
0.590256
4.347222
false
false
false
false
Eonil/Editor
Editor4/FileNavigatorViewController.swift
1
15367
// // FileNavigatorViewController.swift // Editor4 // // Created by Hoon H. on 2016/04/20. // Copyright © 2016 Eonil. All rights reserved. // import AppKit import BoltsSwift import EonilToolbox private enum ColumnID: String { case Name } private struct LocalState { /// TODO: Need to reduce to only required data. var workspace: (id: WorkspaceID, state: WorkspaceState)? } final class FileNavigatorViewController: WorkspaceRenderableViewController, DriverAccessible { private let scrollView = NSScrollView() private let outlineView = FileNavigatorOutlineView() private let nameColumn = NSTableColumn(identifier: ColumnID.Name.rawValue) private let menuPalette = FileNavigatorMenuPalette() private var installer = ViewInstaller() private var localState = LocalState() private var runningMenu = false private let selectionController = TemporalLazyCollectionController<FileID2>() private var sourceFilesVersion: Version? private var proxyMapping = [FileID2: FileUIProxy2]() private var rootProxy: FileUIProxy2? deinit { // This is required to clean up temporal lazy sequence. selectionController.source = AnyRandomAccessCollection([]) } override func render(state: UserInteractionState, workspace: (id: WorkspaceID, state: WorkspaceState)?) { // Download. localState.workspace = workspace // Render. installer.installIfNeeded { view.translatesAutoresizingMaskIntoConstraints = false view.addSubview(scrollView) scrollView.translatesAutoresizingMaskIntoConstraints = false scrollView.documentView = outlineView outlineView.addTableColumn(nameColumn) outlineView.outlineTableColumn = nameColumn outlineView.headerView = nil outlineView.rowSizeStyle = .Small outlineView.allowsMultipleSelection = true outlineView.setDataSource(self) outlineView.setDelegate(self) outlineView.target = self outlineView.action = #selector(EDITOR_action(_:)) // This prevents immediate rename editing. Mimics Xcode/Finder behaviour. outlineView.menu = menuPalette.context.item.submenu outlineView.onEvent = { [weak self] in self?.process($0) } } renderLayoutOnly() renderStatesOnly(localState.workspace) renderMenuStatesOnly(localState.workspace?.state) } private func renderLayoutOnly() { scrollView.frame = view.bounds } private func renderStatesOnly(workspace: (id: WorkspaceID, state: WorkspaceState)?) { guard sourceFilesVersion != workspace?.state.files.version else { return } // TODO: Not optimized. Do it later... if let workspaceState = workspace?.state { let oldMappingCopy = proxyMapping proxyMapping = [:] for (fileID, fileState) in workspaceState.files { proxyMapping[fileID] = oldMappingCopy[fileID]?.renewSourceFileState(fileState) ?? FileUIProxy2(sourceFileID: fileID, sourceFileState: fileState) } rootProxy = proxyMapping[workspaceState.files.rootID] } else { proxyMapping = [:] } sourceFilesVersion = workspace?.state.files.version outlineView.reloadData() renderCurrentFileStateOnly(workspace?.state) } private func renderCurrentFileStateOnly(workspaceState: WorkspaceState?) { guard let currentFileID = workspaceState?.window.navigatorPane.file.selection.current else { return } guard let currentFileProxy = proxyMapping[currentFileID] else { return } guard let rowIndex = outlineView.getRowIndexForItem(currentFileProxy) else { return } outlineView.selectRowIndexes(NSIndexSet(index: rowIndex), byExtendingSelection: false) } private func renderMenuStatesOnly(workspaceState: WorkspaceState?) { // let hasClickedFile = (outlineView.getClickedRowIndex() != nil) // let selectionContainsClickedFile = outlineView.isSelectedRowIndexesContainClickedRow() // let isFileOperationAvailable = hasClickedFile || selectionContainsClickedFile let optionalHighlightOrCurrentFileID = workspaceState?.window.navigatorPane.file.selection.getHighlightOrCurrent() let isFileOperationAvailable = (optionalHighlightOrCurrentFileID != nil) // let isContainerFile = (optionalHighlightOrCurrentFileID == nil ? false : (workspaceState?.files[optionalHighlightOrCurrentFileID!].form == .Container)) menuPalette.context.enabled = true menuPalette.showInFinder.enabled = isFileOperationAvailable menuPalette.showInTerminal.enabled = isFileOperationAvailable menuPalette.createNewFolder.enabled = isFileOperationAvailable // If selected file is non-container, new entry will be created beside of them. menuPalette.createNewFile.enabled = isFileOperationAvailable // If selected file is non-container, new entry will be created beside of them. menuPalette.delete.enabled = isFileOperationAvailable } // private func scan() { // // This must be done first because it uses temporal lazy sequence, // // and that needs immediate synchronization. // scanSelectedFilesOnly() // scanCurrentFileOnly() // } private func scanHighlightedFileOnly() { guard let workspaceID = localState.workspace?.id else { return reportErrorToDevelopers("Missing `FileNavigatorViewController.workspaceID`.") } let optionalFileID = runningMenu ? outlineView.getClickedFileID2() : nil driver.operation.workspace(workspaceID, setHighlightedFile: optionalFileID) } private func process(event: FileNavigatorOutlineViewEvent) { switch event { case .WillOpenMenu: runningMenu = true case .DidCloseMenu: runningMenu = false } renderMenuStatesOnly(localState.workspace?.state) scanHighlightedFileOnly() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() renderLayoutOnly() } } //extension FileNavigatorViewController { // override func viewDidLayoutSubviews() { // super.viewDidLayoutSubviews() // renderLayoutOnly() // } //} extension FileNavigatorViewController { @objc private func EDITOR_action(_: AnyObject?) { } @objc private func EDITOR_doubleAction(_: AnyObject?) { } } extension FileNavigatorViewController: NSOutlineViewDataSource { func outlineView(outlineView: NSOutlineView, isItemExpandable item: AnyObject) -> Bool { guard let proxy = item as? FileUIProxy2 else { return false } return proxy.sourceFileState.form == .Container } func outlineView(outlineView: NSOutlineView, numberOfChildrenOfItem item: AnyObject?) -> Int { if item == nil { // Root nodes. guard rootProxy != nil else { return 0 } return 1 } else { guard let proxy = item as? FileUIProxy2 else { return 0 } return proxy.sourceFileState.subfileIDs.count } } func outlineView(outlineView: NSOutlineView, child index: Int, ofItem item: AnyObject?) -> AnyObject { if item == nil { // Root nodes. assert(rootProxy != nil) guard let rootProxy = rootProxy else { fatalError() } return rootProxy } else { guard let proxy = item as? FileUIProxy2 else { return 0 } let subfileID = proxy.sourceFileState.subfileIDs[index] guard let childProxy = proxyMapping[subfileID] else { fatalError() } return childProxy } } func outlineView(outlineView: NSOutlineView, heightOfRowByItem item: AnyObject) -> CGFloat { return 16 } func outlineView(outlineView: NSOutlineView, viewForTableColumn tableColumn: NSTableColumn?, item: AnyObject) -> NSView? { guard let proxy = item as? FileUIProxy2 else { return nil } let imageView = NSImageView() let textField = NSTextField() let cell = NSTableCellView() cell.addSubview(imageView) cell.addSubview(textField) cell.imageView = imageView cell.textField = textField // func getIcon() -> NSImage? { // guard let path = workspaceState?.files.resolvePathFor(proxy.sourceFileID) else { return nil } // guard let path1 = workspaceState?.location?.appending(path).path else { return nil } // return NSWorkspace.sharedWorkspace().iconForFile(path1) // } imageView.image = nil textField.bordered = false textField.drawsBackground = false textField.stringValue = proxy.sourceFileState.name textField.delegate = self return cell } } extension FileNavigatorViewController: NSOutlineViewDelegate { func outlineViewSelectionDidChange(notification: NSNotification) { let rowIndexToOptionalFileID = { [weak self] (rowIndex: Int) -> FileID2? in guard let S = self else { return nil } guard rowIndex != -1 else { return nil } guard let proxy = S.outlineView.itemAtRow(rowIndex) as? FileUIProxy2 else { return nil } return proxy.sourceFileID } /// Must be called only from `SelectionDidChange` event. /// Because we cannot determine version of `selectedRowIndexes`, /// the only thing what we can do is just tracking event precisely. /// Extra or redundant scanning of selected files will prevent access to lazy sequence. func scanSelectedFilesOnly() { guard let workspaceID = localState.workspace?.id else { return reportErrorToDevelopers("Missing `FileNavigatorViewController.workspaceID`.") } guard let current = rowIndexToOptionalFileID(outlineView.selectedRow) else { return } debugLog(outlineView.selectedRowIndexes) debugLog(outlineView.selectedRowIndexes.lazy.flatMap(rowIndexToOptionalFileID)) let c = AnyRandomAccessCollection(outlineView.selectedRowIndexes.lazy.flatMap(rowIndexToOptionalFileID)) selectionController.source = c let items = selectionController.sequence driver.operation.workspace(workspaceID, resetSelection: (current, items)) } // This must come first to keep state consistency. scanSelectedFilesOnly() } } extension FileNavigatorViewController: NSTextFieldDelegate { // func control(control: NSControl, textShouldBeginEditing fieldEditor: NSText) -> Bool { // return true // } // func control(control: NSControl, textShouldEndEditing fieldEditor: NSText) -> Bool { // return true // } // override func controlTextDidBeginEditing(obj: NSNotification) { // // } func control(control: NSControl, isValidObject obj: AnyObject) -> Bool { return true } /// This it the only event that works. All above events won't be sent. override func controlTextDidEndEditing(notification: NSNotification) { // TODO: Improve this to a regular solution. // Currently this is a bit hacky. I don't know better solution. guard let textField = notification.object as? NSTextField else { return reportErrorToDevelopers("Cannot find sender of end-editing notification in file outline view.") } // guard let cellView = textField.superview as? NSTableCellView else { return reportErrorToDevelopers("Cannot find cell that ended editing in file outline view.") } // guard let rowView = cellView.superview as? NSTableRowView else { return reportErrorToDevelopers("Cannot find row that ended editing in file outline view.") } let rowIndex = outlineView.rowForView(textField) guard rowIndex != -1 else { return reportErrorToDevelopers("Cannot find row that ended editing in file outline view.") } guard let proxy = outlineView.itemAtRow(rowIndex) as? FileUIProxy2 else { return reportErrorToDevelopers("") } guard let workspaceID = localState.workspace?.id else { return reportErrorToDevelopers("Cannot determine workspace ID.") } let fileID = proxy.sourceFileID let newFileName = textField.stringValue // Let the action processor to detect errors in the new name. driver.operation.workspace(workspaceID, file: fileID, renameTo: newFileName) // Calling `render()` will be no-op because journal should be empty. // Set text-field manually. driver.operation.invalidateRendering() } } private extension NSOutlineView { private func getRowIndexForItem(proxy: FileUIProxy2?) -> Int? { let legacyIndex = rowForItem(proxy) guard legacyIndex != -1 else { return nil } return legacyIndex } private func getClickedRowIndex() -> Int? { return clickedRow == -1 ? nil : clickedRow } private func getClickedFileUIProxy2() -> FileUIProxy2? { guard let index = getClickedRowIndex() else { return nil } guard let proxy = itemAtRow(index) as? FileUIProxy2 else { return nil } return proxy } private func getClickedFileID2() -> FileID2? { return getClickedFileUIProxy2()?.sourceFileID } private func isSelectedRowIndexesContainClickedRow() -> Bool { return selectedRowIndexes.containsIndex(clickedRow) } private func getSelectedFileID2() -> FileID2? { guard selectedRow != -1 else { return nil } guard let proxy = itemAtRow(selectedRow) as? FileUIProxy2 else { return nil } return proxy.sourceFileID } } extension NSURL { func appending(path: FileNodePath) -> NSURL { guard let (first, tail) = path.splitFirst() else { return self } return URLByAppendingPathComponent(first).appending(tail) } } private final class FileUIProxy2 { let sourceFileID: FileID2 var sourceFileState: FileState2 init(sourceFileID: FileID2, sourceFileState: FileState2) { self.sourceFileID = sourceFileID self.sourceFileState = sourceFileState } func renewSourceFileState(sourceFileState: FileState2) -> FileUIProxy2 { self.sourceFileState = sourceFileState return self } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // MARK: - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// private enum FileNavigatorOutlineViewEvent { case WillOpenMenu case DidCloseMenu } /// - Note: /// Take care that we should not touch Auto Layout stuffs of this class /// to make it work properly. /// private final class FileNavigatorOutlineView: NSOutlineView { var onEvent: (FileNavigatorOutlineViewEvent -> ())? private override func willOpenMenu(menu: NSMenu, withEvent event: NSEvent) { super.willOpenMenu(menu, withEvent: event) onEvent?(.WillOpenMenu) } private override func didCloseMenu(menu: NSMenu, withEvent event: NSEvent?) { super.didCloseMenu(menu, withEvent: event) onEvent?(.DidCloseMenu) } }
mit
82005650c94fdbdfb29ef7d847a32295
39.120104
177
0.672589
4.967992
false
false
false
false
kiliankoe/ParkenDD
fastlane/SnapshotHelper.swift
1
2034
// // SnapshotHelper.swift // Example // // Created by Felix Krause on 10/8/15. // Copyright © 2015 Felix Krause. All rights reserved. // import Foundation import XCTest var deviceLanguage = "" @available(iOS 9.0, *) func setLanguage(app: XCUIApplication) { Snapshot.setLanguage(app) } @available(iOS 9.0, *) func snapshot(name: String, waitForLoadingIndicator: Bool = true) { Snapshot.snapshot(name, waitForLoadingIndicator: waitForLoadingIndicator) } @available(iOS 9.0, *) @objc class Snapshot: NSObject { class func setLanguage(app: XCUIApplication) { let path = "/tmp/language.txt" do { let locale = try NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding) as String deviceLanguage = locale.substringToIndex(locale.startIndex.advancedBy(2, limit:locale.endIndex)) app.launchArguments = ["-AppleLanguages", "(\(deviceLanguage))", "-AppleLocale", "\"\(locale)\"","-ui_testing"] } catch { print("Couldn't detect/set language...") } } class func snapshot(name: String, waitForLoadingIndicator: Bool = false) { if waitForLoadingIndicator { waitForLoadingIndicatorToDisappear() } print("snapshot: \(name)") // more information about this, check out https://github.com/krausefx/snapshot let view = XCUIApplication() let start = view.coordinateWithNormalizedOffset(CGVectorMake(32.10, 30000)) let finish = view.coordinateWithNormalizedOffset(CGVectorMake(31, 30000)) start.pressForDuration(0, thenDragToCoordinate: finish) sleep(1) } class func waitForLoadingIndicatorToDisappear() { let query = XCUIApplication().statusBars.childrenMatchingType(.Other).elementBoundByIndex(1).childrenMatchingType(.Other) while query.count > 4 { sleep(1) print("Number of Elements in Status Bar: \(query.count)... waiting for status bar to disappear") } } }
mit
34c65305744350c8c73c0d31a912172e
32.327869
129
0.659616
4.716937
false
false
false
false
mercadopago/sdk-ios
MercadoPagoSDK/MercadoPagoSDK/Customer.swift
1
2480
// // Customer.swift // MercadoPagoSDK // // Created by Matias Gualino on 31/12/14. // Copyright (c) 2014 com.mercadopago. All rights reserved. // import Foundation import UIKit public class Customer : NSObject { public var address : Address? public var cards : [Card]? public var defaultCard : NSNumber? public var _description : String? public var dateCreated : NSDate? public var dateLastUpdated : NSDate? public var email : String? public var firstName : String? public var _id : String? public var identification : Identification? public var lastName : String? public var liveMode : Bool? public var metadata : NSDictionary? public var phone : Phone? public var registrationDate : NSDate? public class func fromJSON(json : NSDictionary) -> Customer { let customer : Customer = Customer() customer._id = json["id"] as! String! customer.liveMode = json["live_mode"] as? Bool! customer.email = json["email"] as? String! customer.firstName = json["first_name"] as? String! customer.lastName = json["last_name"] as? String! customer._description = json["description"] as? String! if json["default_card"] != nil { customer.defaultCard = NSNumber(longLong: (json["default_card"] as? NSString)!.longLongValue) } if let identificationDic = json["identification"] as? NSDictionary { customer.identification = Identification.fromJSON(identificationDic) } if let phoneDic = json["phone"] as? NSDictionary { customer.phone = Phone.fromJSON(phoneDic) } if let addressDic = json["address"] as? NSDictionary { customer.address = Address.fromJSON(addressDic) } customer.metadata = json["metadata"]! as? NSDictionary customer.dateCreated = Utils.getDateFromString(json["date_created"] as? String) customer.dateLastUpdated = Utils.getDateFromString(json["date_last_updated"] as? String) customer.registrationDate = Utils.getDateFromString(json["date_registered"] as? String) var cards : [Card] = [Card]() if let cardsArray = json["cards"] as? NSArray { for i in 0..<cardsArray.count { if let cardDic = cardsArray[i] as? NSDictionary { cards.append(Card.fromJSON(cardDic)) } } } customer.cards = cards return customer } }
mit
1a14e02e60e20b1f5f25e9905ba80fcc
37.765625
96
0.63871
4.436494
false
false
false
false
snazzware/SNZSpriteKitUI
SNZSpriteKitUI/SNZLabelWidget.swift
3
1914
// // SNZDialog.swift // SNZSpriteKitUI // // Created by Josh McKee on 11/13/15. // Copyright © 2016 Josh McKee. All rights reserved. // import Foundation import SpriteKit import GameplayKit open class SNZLabelWidget : SNZWidget { open var caption: String = "Untitled" open var color: UIColor = SNZSpriteKitUITheme.instance.labelColor open var backgroundColor: UIColor = SNZSpriteKitUITheme.instance.labelBackground open var labelSprite: SKLabelNode? override public init() { super.init() self.size = CGSize(width: 200, height: 48) } override open func render() { self.labelSprite = SKLabelNode(fontNamed: "Avenir-Black") self.labelSprite!.text = self.caption self.labelSprite!.fontColor = self.color self.labelSprite!.fontSize = 20 self.labelSprite!.horizontalAlignmentMode = .left self.labelSprite!.verticalAlignmentMode = .bottom self.labelSprite!.position = CGPoint(x: SNZSpriteKitUITheme.instance.uiInnerMargins.left, y: SNZSpriteKitUITheme.instance.uiInnerMargins.bottom) self.labelSprite!.ignoreTouches = true // Automatically resize self.size.width = self.labelSprite!.frame.size.width + SNZSpriteKitUITheme.instance.uiInnerMargins.horizontal self.size.height = self.labelSprite!.frame.size.height + SNZSpriteKitUITheme.instance.uiInnerMargins.vertical let frameRect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height) let frameSprite = SKShapeNode(rect: frameRect) frameSprite.fillColor = self.backgroundColor frameSprite.position = self.position frameSprite.lineWidth = 0 frameSprite.ignoreTouches = true frameSprite.addChild(self.labelSprite!) self.sprite = frameSprite super.render() } }
mit
e0c5478321ec1b718cc6548fb37a52ad
33.160714
152
0.678515
4.36758
false
false
false
false
netguru/inbbbox-ios
Inbbbox/Source Files/Views/UICollectionViewCell/SmallUserCollectionViewCell.swift
1
4898
// // SmallUserCollectionViewCell.swift // Inbbbox // // Created by Aleksander Popko on 27.01.2016. // Copyright © 2016 Netguru Sp. z o.o. All rights reserved. // import UIKit class SmallUserCollectionViewCell: BaseInfoShotsCollectionViewCell, Reusable, WidthDependentHeight, InfoShotsCellConfigurable, AvatarSettable { let firstShotImageView = UIImageView.newAutoLayout() let secondShotImageView = UIImageView.newAutoLayout() let thirdShotImageView = UIImageView.newAutoLayout() let fourthShotImageView = UIImageView.newAutoLayout() var avatarView: AvatarView! let avatarSize = CGSize(width: 16, height: 16) fileprivate var didSetConstraints = false // MARK: - Lifecycle override func commonInit() { super.commonInit() setupAvatar() setupShotsView() } override func prepareForReuse() { super.prepareForReuse() clearImages() } // MARK: - UIView override func updateConstraints() { if !didSetConstraints { setShotsViewConstraints() setInfoViewConstraints() didSetConstraints = true } super.updateConstraints() } // MARK: Avatar settable func setupAvatar() { avatarView = AvatarView(avatarFrame: CGRect(origin: CGPoint.zero, size: avatarSize), bordered: false) avatarView.imageView.backgroundColor = UIColor.backgroundGrayColor() avatarView.configureForAutoLayout() infoView.addSubview(avatarView) } // MARK: - Info Shots Cell Configurable func setupShotsView() { for view in [firstShotImageView, secondShotImageView, thirdShotImageView, fourthShotImageView] { shotsView.addSubview(view) } } func updateImageViewsWith(_ color: UIColor) { for view in [firstShotImageView, secondShotImageView, thirdShotImageView, fourthShotImageView] { view.backgroundColor = color } } func setShotsViewConstraints() { let spacings = CollectionViewLayoutSpacings() let shotImageViewWidth = contentView.bounds.width / 2 let shotImageViewHeight = shotImageViewWidth * spacings.smallerShotHeightToWidthRatio firstShotImageView.autoSetDimension(.height, toSize: shotImageViewHeight) firstShotImageView.autoSetDimension(.width, toSize: shotImageViewWidth) secondShotImageView.autoSetDimension(.height, toSize: shotImageViewHeight) secondShotImageView.autoSetDimension(.width, toSize: shotImageViewWidth) thirdShotImageView.autoSetDimension(.height, toSize: shotImageViewHeight) thirdShotImageView.autoSetDimension(.width, toSize: shotImageViewWidth) fourthShotImageView.autoSetDimension(.height, toSize: shotImageViewHeight) fourthShotImageView.autoSetDimension(.width, toSize: shotImageViewWidth) firstShotImageView.autoPinEdge(.top, to: .top, of: shotsView) firstShotImageView.autoPinEdge(.left, to: .left, of: shotsView) firstShotImageView.autoPinEdge(.bottom, to: .top, of: thirdShotImageView) firstShotImageView.autoPinEdge(.right, to: .left, of: secondShotImageView) secondShotImageView.autoPinEdge(.top, to: .top, of: shotsView) secondShotImageView.autoPinEdge(.right, to: .right, of: shotsView) secondShotImageView.autoPinEdge(.bottom, to: .top, of: fourthShotImageView) thirdShotImageView.autoPinEdge(.left, to: .left, of: shotsView) thirdShotImageView.autoPinEdge(.bottom, to: .bottom, of: shotsView) thirdShotImageView.autoPinEdge(.right, to: .left, of: fourthShotImageView) fourthShotImageView.autoPinEdge(.bottom, to: .bottom, of: shotsView) fourthShotImageView.autoPinEdge(.right, to: .right, of: shotsView) } func setInfoViewConstraints() { avatarView.autoSetDimensions(to: avatarSize) avatarView.autoPinEdge(.left, to: .left, of: infoView) avatarView.autoPinEdge(.top, to: .top, of: infoView, withOffset: 6.5) nameLabel.autoPinEdge(.bottom, to: .top, of: numberOfShotsLabel) nameLabel.autoAlignAxis(.horizontal, toSameAxisOf: avatarView) nameLabel.autoPinEdge(.left, to: .right, of: avatarView, withOffset: 3) nameLabel.autoPinEdge(.right, to: .right, of: infoView) numberOfShotsLabel.autoPinEdge(.left, to: .left, of: nameLabel) } func clearImages() { for imageView in [avatarView.imageView, firstShotImageView, secondShotImageView, thirdShotImageView, fourthShotImageView] { imageView.image = nil } } // MARK: - Reusable static var identifier: String { return String(describing: SmallUserCollectionViewCell.self) } // MARK: - Width dependent height static var heightToWidthRatio: CGFloat { return CGFloat(1) } }
gpl-3.0
8a0a80b004b961f6bc834b2c0222ed8e
34.485507
109
0.695936
4.782227
false
false
false
false
CPRTeam/CCIP-iOS
Pods/CryptoSwift/Sources/CryptoSwift/AEAD/AEADChaCha20Poly1305.swift
3
2839
// // ChaCha20Poly1305.swift // CryptoSwift // // Copyright (C) 2014-2017 Marcin Krzyżanowski <[email protected]> // This software is provided 'as-is', without any express or implied warranty. // // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: // // - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required. // - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. // - This notice may not be removed or altered from any source or binary distribution. // // // https://tools.ietf.org/html/rfc7539#section-2.8.1 /// AEAD_CHACHA20_POLY1305 public final class AEADChaCha20Poly1305: AEAD { public static let kLen = 32 // key length public static var ivRange = Range<Int>(12...12) /// Authenticated encryption public static func encrypt(_ plainText: Array<UInt8>, key: Array<UInt8>, iv: Array<UInt8>, authenticationHeader: Array<UInt8>) throws -> (cipherText: Array<UInt8>, authenticationTag: Array<UInt8>) { let cipher = try ChaCha20(key: key, iv: iv) var polykey = Array<UInt8>(repeating: 0, count: kLen) var toEncrypt = polykey polykey = try cipher.encrypt(polykey) toEncrypt += polykey toEncrypt += plainText let fullCipherText = try cipher.encrypt(toEncrypt) let cipherText = Array(fullCipherText.dropFirst(64)) let tag = try calculateAuthenticationTag(authenticator: Poly1305(key: polykey), cipherText: cipherText, authenticationHeader: authenticationHeader) return (cipherText, tag) } /// Authenticated decryption public static func decrypt(_ cipherText: Array<UInt8>, key: Array<UInt8>, iv: Array<UInt8>, authenticationHeader: Array<UInt8>, authenticationTag: Array<UInt8>) throws -> (plainText: Array<UInt8>, success: Bool) { let chacha = try ChaCha20(key: key, iv: iv) let polykey = try chacha.encrypt(Array<UInt8>(repeating: 0, count: self.kLen)) let mac = try calculateAuthenticationTag(authenticator: Poly1305(key: polykey), cipherText: cipherText, authenticationHeader: authenticationHeader) guard mac == authenticationTag else { return (cipherText, false) } var toDecrypt = Array<UInt8>(reserveCapacity: cipherText.count + 64) toDecrypt += polykey toDecrypt += polykey toDecrypt += cipherText let fullPlainText = try chacha.decrypt(toDecrypt) let plainText = Array(fullPlainText.dropFirst(64)) return (plainText, true) } }
gpl-3.0
088a331d09791b94191a832b9dda3d84
47.101695
217
0.738196
4.071736
false
false
false
false
jollyjoester/Schoo-iOS-App-Development-Basic
AnimalFortuneTelling/ViewController.swift
1
10349
// // ViewController.swift // AnimalFortuneTelling // // Created by jollyjoester_pro on 3/4/16. // Copyright © 2016 jollyjoester. All rights reserved. // import UIKit import AVFoundation import Repro class ViewController: UIViewController { @IBOutlet weak var animalLabel: UILabel! @IBOutlet weak var resultLabel: UILabel! var player: AVAudioPlayer! var bgmPlayer: AVAudioPlayer! override func viewDidLoad() { super.viewDidLoad() print("ViewController.viewDidLoad()") self.navigationController?.setNavigationBarHidden(true, animated: false) let url = NSBundle.mainBundle().bundleURL.URLByAppendingPathComponent("bgm.mp3") do { bgmPlayer = try AVAudioPlayer(contentsOfURL: url) bgmPlayer.numberOfLoops = -1 bgmPlayer.volume = 0.5 // bgmPlayer.enableRate = true // bgmPlayer.rate = 0.5 // bgmPlayer.currentTime = 5 // bgmPlayer.pan = -1.0 bgmPlayer.prepareToPlay() bgmPlayer.play() } catch { print("bgmエラーです") } } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) print("ViewController.viewWillAppear()") if !bgmPlayer.playing { bgmPlayer.play() } } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) print("ViewController.viewDidAppear()") } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) print("ViewController.viewWillDisAppear()") if bgmPlayer.playing { bgmPlayer.pause() } } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) print("ViewController.viewDidDisAppear()") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func tellFortunes(sender: AnyObject) { if let swipe = sender as? UISwipeGestureRecognizer { switch swipe.direction { case UISwipeGestureRecognizerDirection.Right: swipeRight() case UISwipeGestureRecognizerDirection.Left: swipeLeft() case UISwipeGestureRecognizerDirection.Up: swipeUp() case UISwipeGestureRecognizerDirection.Down: swipeDown() default: break } } else { tappedButton() } } func tappedButton() { Repro.track("tappedButton", properties: nil) UIView.animateWithDuration(1.0, animations: { self.animalLabel.transform = CGAffineTransformMakeScale(0.2, 0.2) self.animalLabel.alpha = 0.0 self.resultLabel.hidden = true }, completion: { (Bool) -> Void in self.animalLabel.transform = CGAffineTransformIdentity self.animalLabel.alpha = 1.0 self.resultLabel.hidden = false self.changeLabel() UIView.animateWithDuration(0.1, animations: { UIView.setAnimationRepeatCount(5) self.animalLabel.transform = CGAffineTransformMakeTranslation(10, 0) }, completion: { (Bool) -> Void in self.animalLabel.transform = CGAffineTransformIdentity }) }) } func swipeRight() { Repro.track("swipeRight", properties: nil) UIView.animateWithDuration(1.0, animations: { self.animalLabel.transform = CGAffineTransformMakeTranslation(200, 0) self.animalLabel.alpha = 0.0 self.resultLabel.hidden = true }, completion: { (Bool) -> Void in self.animalLabel.transform = CGAffineTransformIdentity self.animalLabel.alpha = 1.0 self.resultLabel.hidden = false self.changeLabel() UIView.animateWithDuration(0.1, animations: { UIView.setAnimationRepeatCount(5) self.animalLabel.transform = CGAffineTransformMakeTranslation(10, 0) }, completion: { (Bool) -> Void in self.animalLabel.transform = CGAffineTransformIdentity }) }) } func swipeLeft() { Repro.track("swipeLeft", properties: nil) UIView.animateWithDuration(1.0, animations: { self.animalLabel.transform = CGAffineTransformMakeTranslation(-200, 0) self.animalLabel.alpha = 0.0 self.resultLabel.hidden = true }, completion: { (Bool) -> Void in self.animalLabel.transform = CGAffineTransformIdentity self.animalLabel.alpha = 1.0 self.resultLabel.hidden = false self.changeLabel() UIView.animateWithDuration(0.1, animations: { UIView.setAnimationRepeatCount(5) self.animalLabel.transform = CGAffineTransformMakeTranslation(10, 0) }, completion: { (Bool) -> Void in self.animalLabel.transform = CGAffineTransformIdentity }) }) } func swipeUp() { Repro.track("swipeUp", properties: nil) UIView.animateWithDuration(1.0, animations: { self.animalLabel.transform = CGAffineTransformMakeTranslation(0, -200) self.animalLabel.alpha = 0.0 self.resultLabel.hidden = true }, completion: { (Bool) -> Void in self.animalLabel.transform = CGAffineTransformIdentity self.animalLabel.alpha = 1.0 self.resultLabel.hidden = false self.changeLabel() UIView.animateWithDuration(0.1, animations: { UIView.setAnimationRepeatCount(5) self.animalLabel.transform = CGAffineTransformMakeTranslation(10, 0) }, completion: { (Bool) -> Void in self.animalLabel.transform = CGAffineTransformIdentity }) }) } func swipeDown() { Repro.track("swipeDown", properties: nil) UIView.animateWithDuration(1.0, animations: { self.animalLabel.transform = CGAffineTransformMakeTranslation(0, 200) self.animalLabel.alpha = 0.0 self.resultLabel.hidden = true }, completion: { (Bool) -> Void in self.animalLabel.transform = CGAffineTransformIdentity self.animalLabel.alpha = 1.0 self.resultLabel.hidden = false self.changeLabel() UIView.animateWithDuration(0.1, animations: { UIView.setAnimationRepeatCount(5) self.animalLabel.transform = CGAffineTransformMakeTranslation(10, 0) }, completion: { (Bool) -> Void in self.animalLabel.transform = CGAffineTransformIdentity }) }) } func shake() { Repro.track("shake", properties: nil) UIView.animateWithDuration(1.0, animations: { self.animalLabel.transform = CGAffineTransformMakeScale(3.0, 3.0) self.animalLabel.alpha = 0.0 self.resultLabel.hidden = true }, completion: { (Bool) -> Void in self.animalLabel.transform = CGAffineTransformIdentity self.animalLabel.alpha = 1.0 self.resultLabel.hidden = false self.changeLabel() UIView.animateWithDuration(0.1, animations: { UIView.setAnimationRepeatCount(5) self.animalLabel.transform = CGAffineTransformMakeTranslation(10, 0) }, completion: { (Bool) -> Void in self.animalLabel.transform = CGAffineTransformIdentity }) }) } func changeLabel() { let random = arc4random_uniform(100) var soundName = "" switch random { case 0..<10: animalLabel.text = "🐶" resultLabel.text = NSLocalizedString("Daikichi", comment: "") soundName = "dog.mp3" case 10..<30: animalLabel.text = "🐱" resultLabel.text = NSLocalizedString("Chukichi", comment: "") soundName = "cat.mp3" case 30..<50: animalLabel.text = "🐔" resultLabel.text = NSLocalizedString("Kichi", comment: "") soundName = "chicken.mp3" case 50..<70: animalLabel.text = "🐑" resultLabel.text = NSLocalizedString("Suekichi", comment: "") soundName = "sheep.mp3" case 70..<90: animalLabel.text = "🐘" resultLabel.text = NSLocalizedString("Kyo", comment: "") soundName = "elephant.mp3" default: animalLabel.text = "🐯" resultLabel.text = NSLocalizedString("Daikyo", comment: "") soundName = "tiger.mp3" } let url = NSBundle.mainBundle().bundleURL.URLByAppendingPathComponent(soundName) do { player = try AVAudioPlayer(contentsOfURL: url) player.play() } catch { print("エラーです") } // if bgmPlayer.playing { // bgmPlayer.pause() // } else { // bgmPlayer.play() // } // bgmPlayer.stop() } override func canBecomeFirstResponder() -> Bool { return true } override func motionBegan(motion: UIEventSubtype, withEvent event: UIEvent?) { print("motionBegan") if event?.type == UIEventType.Motion && event?.subtype == UIEventSubtype.MotionShake { shake() } } override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent?) { print("motionEnded") } override func motionCancelled(motion: UIEventSubtype, withEvent event: UIEvent?) { print("motionCanceled") } }
mit
5063120ba76b2be3461d2e4f20d147e2
30.820988
94
0.564791
5.254842
false
false
false
false
tardieu/swift
validation-test/stdlib/Hashing.swift
14
4023
// RUN: %target-run-stdlib-swift // REQUIRES: executable_test import Swift import SwiftPrivate import StdlibUnittest var HashingTestSuite = TestSuite("Hashing") HashingTestSuite.test("_mixUInt32/GoldenValues") { expectEqual(0x11b882c9, _mixUInt32(0x0)) expectEqual(0x60d0aafb, _mixUInt32(0x1)) expectEqual(0x636847b5, _mixUInt32(0xffff)) expectEqual(0x203f5350, _mixUInt32(0xffff_ffff)) expectEqual(0xb8747ef6, _mixUInt32(0xa62301f9)) expectEqual(0xef4eeeb2, _mixUInt32(0xfe1b46c6)) expectEqual(0xd44c9cf1, _mixUInt32(0xe4daf7ca)) expectEqual(0xfc1eb1de, _mixUInt32(0x33ff6f5c)) expectEqual(0x5605f0c0, _mixUInt32(0x13c2a2b8)) expectEqual(0xd9c48026, _mixUInt32(0xf3ad1745)) expectEqual(0x471ab8d0, _mixUInt32(0x656eff5a)) expectEqual(0xfe265934, _mixUInt32(0xfd2268c9)) } HashingTestSuite.test("_mixInt32/GoldenValues") { expectEqual(Int32(bitPattern: 0x11b882c9), _mixInt32(0x0)) } HashingTestSuite.test("_mixUInt64/GoldenValues") { expectEqual(0xb2b2_4f68_8dc4_164d, _mixUInt64(0x0)) expectEqual(0x792e_33eb_0685_57de, _mixUInt64(0x1)) expectEqual(0x9ec4_3423_1b42_3dab, _mixUInt64(0xffff)) expectEqual(0x4cec_e9c9_01fa_9a84, _mixUInt64(0xffff_ffff)) expectEqual(0xcba5_b650_bed5_b87c, _mixUInt64(0xffff_ffff_ffff)) expectEqual(0xe583_5646_3fb8_ac99, _mixUInt64(0xffff_ffff_ffff_ffff)) expectEqual(0xf5d0079f828d43a5, _mixUInt64(0x94ce7d9319f8d233)) expectEqual(0x61900a6be9db9c3f, _mixUInt64(0x2728821e8c5b1f7)) expectEqual(0xf2fd34b1b7d4b46e, _mixUInt64(0xe7f67ec98c64f482)) expectEqual(0x216199ed628c821, _mixUInt64(0xd7c277b5438873ac)) expectEqual(0xb1b486ff5f2e0e53, _mixUInt64(0x8399f1d563c42f82)) expectEqual(0x61acc92bd91c030, _mixUInt64(0x488cefd48a2c4bfd)) expectEqual(0xa7a52d6e4a8e3ddf, _mixUInt64(0x270a15116c351f95)) expectEqual(0x98ceedc363c4e56a, _mixUInt64(0xe5fb9b5f6c426a84)) } HashingTestSuite.test("_mixUInt64/GoldenValues") { expectEqual(Int64(bitPattern: 0xb2b2_4f68_8dc4_164d), _mixInt64(0x0)) } HashingTestSuite.test("_mixUInt/GoldenValues") { #if arch(i386) || arch(arm) expectEqual(0x11b8_82c9, _mixUInt(0x0)) #elseif arch(x86_64) || arch(arm64) || arch(powerpc64) || arch(powerpc64le) || arch(s390x) expectEqual(0xb2b2_4f68_8dc4_164d, _mixUInt(0x0)) #else fatalError("unimplemented") #endif } HashingTestSuite.test("_mixInt/GoldenValues") { #if arch(i386) || arch(arm) expectEqual(Int(bitPattern: 0x11b8_82c9), _mixInt(0x0)) #elseif arch(x86_64) || arch(arm64) || arch(powerpc64) || arch(powerpc64le) || arch(s390x) expectEqual(Int(bitPattern: 0xb2b2_4f68_8dc4_164d), _mixInt(0x0)) #else fatalError("unimplemented") #endif } HashingTestSuite.test("_squeezeHashValue/Int") { // Check that the function can return values that cover the whole range. func checkRange(_ r: Int) { var results = Set<Int>() for _ in 0..<(14 * r) { let v = _squeezeHashValue(randInt(), r) expectTrue(v < r) results.insert(v) } expectEqual(r, results.count) } checkRange(1) checkRange(2) checkRange(4) checkRange(8) checkRange(16) } HashingTestSuite.test("String/hashValue/topBitsSet") { #if _runtime(_ObjC) #if arch(x86_64) || arch(arm64) // Make sure that we don't accidentally throw away bits by storing the result // of NSString.hash into an int in the runtime. // This is the bit pattern that we xor to NSString's hash value. let hashOffset = UInt(bitPattern: 0x429b_1266_0000_0000) let hash = "efghijkl".hashValue // When we are not equal to the top bit of the xor'ed hashOffset pattern // there where some bits set. let topHashBits = UInt(bitPattern: hash) & 0xffff_ffff_0000_0000 expectTrue(hash > 0) expectTrue(topHashBits != hashOffset) #endif #endif } HashingTestSuite.test("overridePerExecutionHashSeed/overflow") { // Test that we don't use checked arithmetic on the seed. _HashingDetail.fixedSeedOverride = UInt64.max expectEqual(0x4344_dc3a_239c_3e81, _mixUInt64(0xffff_ffff_ffff_ffff)) _HashingDetail.fixedSeedOverride = 0 } runAllTests()
apache-2.0
6054a9a5c39c01edcef86001c4eaa57f
33.384615
90
0.752175
2.69097
false
true
false
false
waynezhang/JLCloudKitSync
JLCloudKitSync/JLCloudKitSync.swift
1
27071
// // JLCloudKitSync.swift // JLCloudKitSync.h // // Created by Linghua Zhang on 2015/03/13. // Copyright (c) 2015年 Linghua Zhang. All rights reserved. // import Foundation import CoreData import CloudKit public enum JLCloudKitFullSyncPolicy { case ReplaceDataOnCloudKit // Replace data on cloudkit with local data case ReplaceDataOnLocal // Replace data in local database with data in the cloud } public let JLCloudKitSyncWillBeginNotification = "JLCloudKitSyncWillBeginNotification" public let JLCloudKitSyncDidEndNotification = "JLCloudKitSyncDidEndNotification" public class JLCloudKitSync: NSObject { public typealias DiscoveryCompletionHandler = (entitiesExist: Bool, error: NSError?) -> Void // Whether auto sync after local context is saved public var autoSyncOnSave = true private var context: NSManagedObjectContext! private var backingContext: NSManagedObjectContext! private var zoneName: String? private let metaEntityName = "JTCloudKitMeta" private var zoneID: CKRecordZoneID { get { return CKRecordZoneID(zoneName: zoneName!, ownerName: CKOwnerDefaultName) } } private var previousToken: CKServerChangeToken? { set { var object: NSManagedObject? let req = NSFetchRequest(entityName: metaEntityName) req.predicate = NSPredicate(format: "name = %@", "server_token") if let results = try? backingContext.executeFetchRequest(req) where results.count > 0 { object = results.first as? NSManagedObject } else { let entity = NSEntityDescription.entityForName(metaEntityName, inManagedObjectContext: backingContext) object = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: backingContext) object?.setValue("server_token", forKey: "name") } if newValue != nil { let data = NSKeyedArchiver.archivedDataWithRootObject(newValue!) object?.setValue(data, forKey: "value") } else { backingContext.deleteObject(object!) } _ = try? backingContext.save() } get { let req = NSFetchRequest(entityName: metaEntityName) req.predicate = NSPredicate(format: "name = %@", "server_token") if let results = try? backingContext.executeFetchRequest(req), object = results.first as? NSManagedObject, data = object.valueForKey("value") as? NSData, token = NSKeyedUnarchiver.unarchiveObjectWithData(data) as? CKServerChangeToken { return token } return nil } } private lazy var storeURL: NSURL = { let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) let url = urls.last! return url.URLByAppendingPathComponent("JLCloudKitSync.sqlite") }() // MARK: - APIs public init(context: NSManagedObjectContext) { self.context = context super.init() setupContextStack(context) } // Set work zone name, must be called before other APIs public func setupWorkZone(name: String, completionHandler: (NSError?) -> Void) { NSNotificationCenter.defaultCenter().removeObserver(self, name: NSManagedObjectContextDidSaveNotification, object: self.context) let zonesToSave = [ CKRecordZone(zoneName: name) ] let operation = CKModifyRecordZonesOperation(recordZonesToSave: zonesToSave, recordZoneIDsToDelete: nil) operation.modifyRecordZonesCompletionBlock = { [unowned self] savedZones, _, error in self.info("Work Zone \( name ) save result: \( error )") self.zoneName = name NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("contextDidSave:"), name: NSManagedObjectContextDidSaveNotification, object: self.context) AsyncOnMainQueue { completionHandler(error) } } executeOperation(operation) } // Find if there is data in the cloud public func discoverEntities(recordType: String, completionHandler: DiscoveryCompletionHandler) { var exists = false let query = CKQuery(recordType: recordType, predicate: NSPredicate(value: true)) let operation = CKQueryOperation(query: query) operation.zoneID = self.zoneID operation.resultsLimit = 1 operation.desiredKeys = [ ] operation.recordFetchedBlock = { exists = $0 != nil } operation.completionBlock = { AsyncOnMainQueue { completionHandler(entitiesExist: exists, error: nil) } } executeOperation(operation) } // Fully sync public func performFullSync(policy: JLCloudKitFullSyncPolicy) { self.notifySyncBegin() self.previousToken = nil switch policy { case .ReplaceDataOnCloudKit: performFullSyncFromLocal() case .ReplaceDataOnLocal: performFullSyncFromRemote() } } // Incremental sync public func performSync() { self.notifySyncBegin() self.performSyncInternal() } // Wipe cloud data and sync queue public func wipeDataInCloudKitAndCleanQueue(completionHandler: (NSError?) -> Void) { clearDataInCloudKit { [unowned self] error in self.clearData(self.backingContext, entityName: JLCloudKitItem.entityName()) completionHandler(error) } } // Stop sync public func stopSync() { NSNotificationCenter.defaultCenter().removeObserver(self, name: NSManagedObjectContextDidSaveNotification, object: self.context) } } // MARK: - Sync extension JLCloudKitSync { // Full sync, replace data in local with cloud private func performFullSyncFromRemote() { clearSyncQueue() clearDataInLocalContext() performSyncInternal() } // Full sync, replace data in cloud with local private func performFullSyncFromLocal() { wipeDataInCloudKitAndCleanQueue { [unowned self] _ in self.addAllLocalDataToSyncQueue() self.saveBackingContext() self.performSyncInternal() } } private func mergeServerChanges(changedRecords: [CKRecord], deleteRecordIDs: [CKRecordID]) { var changedRecordMappings = changedRecords.reduce([CKRecordID:CKRecord]()) { (var map, record) in map[record.recordID] = record return map } var needProcessAgain = [(CKRecord, NSManagedObject, JLCloudKitItem)]() // modified self.fetchSyncItems(changedRecordMappings.keys).forEach { item in let record = changedRecordMappings[CKRecordID(recordName: item.recordID!, zoneID: zoneID)]! info("merge item \(item.lastModified) vs \(record.modificationDate)") defer { changedRecordMappings.removeValueForKey(record.recordID) } guard item.lastModified! < record.modificationDate! else { return } // server record is newer let object = fetchLocalObjects([item.recordID!]).values.first! if updateLocalObjectWithRecord(object, record: record) { updateSyncItem(item, object: object, status: .Clean, date: record.modificationDate!, recordName: record.recordID.recordName) } else { needProcessAgain.append(record, object, item) } } // newly inserted changedRecordMappings.values.forEach { record in info("insert item \(record.modificationDate)") let entities = context.persistentStoreCoordinator!.managedObjectModel.entities.filter { ($0 ).name! == record.recordType } guard entities.count > 0 else { warn("entity \(record.recordType) not exists") return } let object = NSManagedObject(entity: entities[0] , insertIntoManagedObjectContext: context) let item = JLCloudKitItem(managedObjectContext: backingContext) _ = try? context.obtainPermanentIDsForObjects([object]) if updateLocalObjectWithRecord(object, record: record) { updateSyncItem(item, object: object, status: .Clean, date: record.modificationDate!, recordName: record.recordID.recordName) } else { needProcessAgain.append(record, object, item) } } needProcessAgain.forEach { record, object, item in info("process again \(record.recordType), \(record.recordID.recordName)") updateLocalObjectWithRecord(object, record: record) updateSyncItem(item, object: object, status: .Clean, date: record.modificationDate!, recordName: record.recordID.recordName) } // deleted let deletedRecordIDStrings = deleteRecordIDs.map { $0.recordName } removeLocalObject(deletedRecordIDStrings) removeFromSyncQueue(deletedRecordIDStrings) saveBackingContext() saveContext(context, name: "Content") } // Sync private func performSyncInternal() { var toSave = [JLCloudKitItem]() var toDelete = [CKRecordID]() let request = NSFetchRequest(entityName: JLCloudKitItem.entityName()) request.predicate = NSPredicate(format: "\(JLCloudKitItemAttribute.status.rawValue) != %@", JLCloudKitItemStatus.Clean.rawValue) if let items = (try? backingContext.executeFetchRequest(request)) as? [JLCloudKitItem] { toSave.appendContentsOf(items.filter { $0.status!.integerValue == JLCloudKitItemStatus.Dirty.rawValue }) toDelete.appendContentsOf(items .filter { $0.status!.integerValue == JLCloudKitItemStatus.Deleted.rawValue } .map { CKRecordID(recordName: $0.recordID!, zoneID: self.zoneID) }) } info("sync queue \( toSave.count ) inserted, \( toDelete.count ) deleted") self.fetchOrCreateRecords(toSave) { [unowned self] records in let operation = CKModifyRecordsOperation(recordsToSave: records, recordIDsToDelete: toDelete) operation.modifyRecordsCompletionBlock = { [unowned self] saved, deleted, err in self.info("modifications applied to server, \( saved?.count ?? 0 ) saved, \( deleted?.count ?? 0 ) deleted, error: \( err )") self.markSyncQueueClean(saved ?? [ ]) self.removeFromSyncQueue((deleted ?? [ ]).map { $0.recordName }) self.saveBackingContext() self.fetchServerChanges (self.previousToken) { [unowned self] changedRecords, deletedIDs, serverToken in self.mergeServerChanges(changedRecords, deleteRecordIDs: deletedIDs) if serverToken != nil { self.previousToken = serverToken } self.saveBackingContext() } self.notifySyncEnd(err) } operation.savePolicy = .IfServerRecordUnchanged self.executeOperation(operation) } } private func fetchServerChanges(previousToken: CKServerChangeToken!, completionHandler: ([CKRecord], [CKRecordID], CKServerChangeToken!) -> Void) { var changed = [CKRecord]() var deleted = [CKRecordID]() let ope = CKFetchRecordChangesOperation(recordZoneID: zoneID, previousServerChangeToken: previousToken) ope.recordChangedBlock = { changed.append($0) } ope.recordWithIDWasDeletedBlock = { deleted.append($0) } ope.fetchRecordChangesCompletionBlock = { token, data, err in self.info("Server change: \(changed.count) changed, \(deleted.count) deleted, error \(err)") completionHandler(changed, deleted, token) } executeOperation(ope) } func contextDidSave(notification: NSNotification) { let inserted = addLocalObjectsToSyncQueue((notification.userInfo![NSInsertedObjectsKey] as? NSSet)?.allObjects as? [NSManagedObject], status: .Dirty) let updated = addLocalObjectsToSyncQueue((notification.userInfo![NSUpdatedObjectsKey] as? NSSet)?.allObjects as? [NSManagedObject], status: .Dirty) let deleted = addLocalObjectsToSyncQueue((notification.userInfo![NSDeletedObjectsKey] as? NSSet)?.allObjects as? [NSManagedObject], status: .Deleted) info("context changed, \( inserted ) inserted, \( updated ) updated, \( deleted )") self.saveBackingContext() if self.autoSyncOnSave { self.performSync() } } } // MARK: - Local Cache extension JLCloudKitSync { // Map local objects to sync items private func addLocalObjectsToSyncQueue<T: SequenceType where T.Generator.Element: NSManagedObject>(set: T?, status: JLCloudKitItemStatus) -> Int { guard let objects = set else { return 0 } objects.forEach { obj in let item = self.fetchSyncItem(obj.objectID) ?? JLCloudKitItem(managedObjectContext: self.backingContext) self.updateSyncItem(item, object: obj, status: status) } return objects.underestimateCount() } private func removeLocalObject(recordIDs: [String]) { self.fetchLocalObjects(recordIDs).values.forEach { self.context.deleteObject($0) } } // Map a single local object to record private func updateRecordWithLocalObject(record: CKRecord, object: NSManagedObject) { object.entity.attributesByName.keys.forEach { k in record.setValue(object.valueForKey(k), forKey: k) } for (name, rel) in object.entity.relationshipsByName where !rel.toMany { if let relObj = object.valueForKey(name) as? NSManagedObject, recordName = self.fetchRecordName(relObj.objectID) { let recordID = CKRecordID(recordName: recordName, zoneID: self.zoneID) let ref = CKReference(recordID: recordID, action: CKReferenceAction.DeleteSelf) record.setObject(ref, forKey: name) } else { warn("Can not find \( name ) for \( object )") } } } // Create a new record and set values from a local object private func recordWithLocalObject(recordName: String, object: NSManagedObject) -> CKRecord { let id = CKRecordID(recordName: recordName, zoneID: self.zoneID) let record = CKRecord(recordType: object.entity.name!, recordID: id) updateRecordWithLocalObject(record, object: object) return record } // Map all local objects to records, modified on exist ones, or newly created if necessary private func fetchOrCreateRecords(syncItems: [JLCloudKitItem], completionBlock: ([CKRecord]) -> Void) { var syncItemMappings = syncItems.reduce([String:JLCloudKitItem]()) { (var map, item) in map[item.recordID!] = item return map } let recordIDs = syncItems.map { $0.recordID! } var objects = fetchLocalObjects(recordIDs) var records: [CKRecord] = [ ] let operation = CKFetchRecordsOperation(recordIDs: recordIDs.map { CKRecordID(recordName: $0, zoneID: self.zoneID) }) operation.fetchRecordsCompletionBlock = { p, err in guard let results = p else { return } for (recordID, record) in results { let item = syncItemMappings[recordID.recordName]! let object = objects.removeValueForKey(recordID.recordName)! if item.lastModified! > record.modificationDate! { // newer than server self.updateRecordWithLocalObject(record, object: object) records.append(record) } } for (recordName, object) in objects { records.append(self.recordWithLocalObject(recordName, object: object)) } completionBlock(records) } executeOperation(operation) } // Get record name by local object id private func fetchRecordName(managedObjectID: NSManagedObjectID) -> String? { return fetchSyncItem(managedObjectID)?.recordID } // MARK: Local Objects to Sync Item private func addAllLocalDataToSyncQueue() { var count = 0 for e in context.persistentStoreCoordinator!.managedObjectModel.entities { let req = NSFetchRequest(entityName: e.name!) req.predicate = NSPredicate(value: true) let results = (try? context.executeFetchRequest(req)) as? [NSManagedObject] count += addLocalObjectsToSyncQueue(results, status: .Dirty) } info("\( count ) items added to sync queue") } // MARK: CKRecord to Local Objects // Map a single record to local object private func updateLocalObjectWithRecord(object: NSManagedObject, record: CKRecord) -> Bool { var clean = true object.entity.attributesByName.keys.forEach { k in object.setValue(record.valueForKey(k), forKey: k) } for (name, rel) in object.entity.relationshipsByName where !rel.toMany { if let refObj = record.valueForKey(name) as? CKReference { let relatedObjects = fetchLocalObjects([ refObj.recordID.recordName ]) if relatedObjects.count > 0 { // related object exists let relObj = relatedObjects.values.first! object.setValue(relObj, forKey: name) } else { info("related \( name ) object not found") clean = false } } } return clean } private func fetchLocalObjects(recordIDs: [String]) -> [String : NSManagedObject] { let req = NSFetchRequest(entityName: JLCloudKitItem.entityName()) req.predicate = NSPredicate(format: "\( JLCloudKitItemAttribute.recordID.rawValue ) IN %@", recordIDs) guard let results = try? self.backingContext.executeFetchRequest(req) else { return [ : ] } var objects = [String : NSManagedObject]() for item in results as! [JLCloudKitItem] { if let objectID = context.persistentStoreCoordinator!.managedObjectIDForURIRepresentation(NSURL(string: item.localObjectID! as String)!), object = try? context.existingObjectWithID(objectID) { objects[item.recordID!] = object } else { warn("object no exists any more \( item.recordID! )") } } return objects } // MARK: CKRecord to Sync Items private func fetchSyncItems<T: SequenceType where T.Generator.Element: CKRecordID>(recordIDs: T) -> [JLCloudKitItem] { let recordNames = recordIDs.map { $0.recordName } let request = NSFetchRequest(entityName: JLCloudKitItem.entityName()) request.predicate = NSPredicate(format: "\( JLCloudKitItemAttribute.recordID.rawValue ) IN %@", recordNames) if let results = try? backingContext.executeFetchRequest(request) { return results as! [JLCloudKitItem] } return [ ] } // MARK: Local Object to Sync Item private func fetchSyncItem(managedObjectID: NSManagedObjectID) -> JLCloudKitItem? { let request = NSFetchRequest(entityName: JLCloudKitItem.entityName()) request.predicate = NSPredicate(format: "\( JLCloudKitItemAttribute.localObjectID.rawValue ) = %@", managedObjectID.URIRepresentation()) if let results = try? backingContext.executeFetchRequest(request), item = results.first as? JLCloudKitItem { return item } return nil } private func updateSyncItem(item: JLCloudKitItem, object: NSManagedObject, status: JLCloudKitItemStatus, date: NSDate = NSDate(), recordName: String? = nil) { if item.valueForKey(JLCloudKitItemAttribute.recordID.rawValue) == nil { let value = recordName ?? NSUUID().UUIDString item.setValue(value, forKey: JLCloudKitItemAttribute.recordID.rawValue) } item.setValue(object.objectID.URIRepresentation().absoluteString, forKey: JLCloudKitItemAttribute.localObjectID.rawValue) item.setValue(object.entity.name, forKey: JLCloudKitItemAttribute.type.rawValue) item.setValue(date, forKey: JLCloudKitItemAttribute.lastModified.rawValue) item.setValue(NSNumber(integer: status.rawValue), forKey: JLCloudKitItemAttribute.status.rawValue) } } // MARK: - Setup extension JLCloudKitSync { private func setupContextStack(context: NSManagedObjectContext) { let model = generateModel() let persistentCoordinator = NSPersistentStoreCoordinator(managedObjectModel: model) do { try persistentCoordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeURL, options: nil) backingContext = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType) backingContext.persistentStoreCoordinator = persistentCoordinator info("Store added to \(storeURL)") } catch { err("Failedto add store \(storeURL) since \(error)") } } private func generateModel() -> NSManagedObjectModel { let model = NSManagedObjectModel() let entity = NSEntityDescription() entity.name = JLCloudKitItem.entityName() entity.managedObjectClassName = JLCloudKitItem.entityName() let ckIDAttr = NSAttributeDescription() ckIDAttr.name = JLCloudKitItemAttribute.recordID.rawValue ckIDAttr.attributeType = .StringAttributeType ckIDAttr.indexed = true let localIDAttr = NSAttributeDescription() localIDAttr.name = JLCloudKitItemAttribute.localObjectID.rawValue localIDAttr.attributeType = .StringAttributeType localIDAttr.indexed = true let typeAttr = NSAttributeDescription() typeAttr.name = JLCloudKitItemAttribute.type.rawValue typeAttr.attributeType = .StringAttributeType let lastModifiedAttr = NSAttributeDescription() lastModifiedAttr.name = JLCloudKitItemAttribute.lastModified.rawValue lastModifiedAttr.attributeType = .DateAttributeType let statusAttr = NSAttributeDescription() statusAttr.name = JLCloudKitItemAttribute.status.rawValue statusAttr.attributeType = .Integer16AttributeType statusAttr.indexed = true entity.properties = [ ckIDAttr, localIDAttr, typeAttr, lastModifiedAttr, statusAttr ] let metaEntity = NSEntityDescription() metaEntity.name = metaEntityName let metaNameAttr = NSAttributeDescription() metaNameAttr.name = "name" metaNameAttr.attributeType = .StringAttributeType metaNameAttr.indexed = true let metaValueAttr = NSAttributeDescription() metaValueAttr.name = "value" metaValueAttr.attributeType = .BinaryDataAttributeType metaEntity.properties = [ metaNameAttr, metaValueAttr ] model.entities = [ entity, metaEntity ] return model } } // MARK: - Utilities extension JLCloudKitSync { private func saveBackingContext() { saveContext(backingContext, name: "Backing") } private func saveContext(context: NSManagedObjectContext, name: String) { context.performBlockAndWait { guard context.hasChanges else { return } do { try context.save() self.info("\(name) context saved") } catch { self.info("Failed to save \(name) context. \(error)") } } } func clearSyncQueue() { clearData(backingContext, entityName: JLCloudKitItem.entityName()) } private func clearDataInCloudKit(completionHandler: (NSError?) -> Void) { let db = CKContainer.defaultContainer().privateCloudDatabase db.deleteRecordZoneWithID(self.zoneID) { zoneID, error in self.info("Zone \( self.zoneName! ) cleared result \( error )") self.setupWorkZone( self.zoneName!, completionHandler: completionHandler) } } private func clearDataInLocalContext() { context.persistentStoreCoordinator!.managedObjectModel.entities.forEach { e in clearData(context, entityName: e.name!) } } private func clearData(context: NSManagedObjectContext, entityName: String) { let req = NSFetchRequest(entityName: entityName) _ = try? context.executeFetchRequest(req).forEach { context.deleteObject($0 as! NSManagedObject) } } private func removeFromSyncQueue(recordIDs: [String]) { let req = NSFetchRequest(entityName: JLCloudKitItem.entityName()) req.predicate = NSPredicate(format: "\( JLCloudKitItemAttribute.recordID.rawValue ) IN %@", recordIDs) _ = try? backingContext.executeFetchRequest(req).forEach { backingContext.deleteObject($0 as! NSManagedObject) } } private func markSyncQueueClean(records: [CKRecord]) { let items = fetchSyncItems(records.map { $0.recordID }) let recordMappings:[CKRecordID:CKRecord] = records.reduce([:]) { (var map, record) in map[record.recordID] = record return map } items.forEach { item in let recordID = CKRecordID(recordName: item.recordID!, zoneID: zoneID) let record = recordMappings[recordID]! item.lastModified = record.modificationDate item.status = NSNumber(integer: JLCloudKitItemStatus.Clean.rawValue) } } private func notifySyncBegin() { AsyncOnMainQueue { NSNotificationCenter.defaultCenter().postNotificationName(JLCloudKitSyncWillBeginNotification, object: nil) } } private func notifySyncEnd(error: NSError?) { AsyncOnMainQueue { var info: [NSObject: AnyObject] = [ : ] if error != nil { info["error"] = error } NSNotificationCenter.defaultCenter().postNotificationName(JLCloudKitSyncDidEndNotification, object: nil, userInfo: info) } } private func executeOperation(operation: CKDatabaseOperation) { CKContainer.defaultContainer().privateCloudDatabase.addOperation(operation) } }
mit
fa388ce654557c50f9aa83691e2547c0
42.451043
162
0.640992
5.169786
false
false
false
false
yogomi/cordova-plugin-iosrtc
src/PluginMediaStreamRenderer.swift
1
6950
import Foundation import AVFoundation @objc(PluginMediaStreamRenderer) // Needed. class PluginMediaStreamRenderer : RTCEAGLVideoViewDelegate { var webView: UIWebView var eventListener: (data: NSDictionary) -> Void var elementView: UIView var videoView: RTCEAGLVideoView var pluginMediaStream: PluginMediaStream? var rtcAudioTrack: RTCAudioTrack? var rtcVideoTrack: RTCVideoTrack? init( webView: UIWebView, eventListener: (data: NSDictionary) -> Void ) { NSLog("PluginMediaStreamRenderer#init()") // The browser HTML view. self.webView = webView self.eventListener = eventListener // The video element view. self.elementView = UIView() // The effective video view in which the the video stream is shown. // It's placed over the elementView. self.videoView = RTCEAGLVideoView() self.webView.addSubview(self.elementView) self.webView.bringSubviewToFront(self.elementView) // TODO: TEST // self.webView.sendSubviewToBack(self.elementView) // self.webView.backgroundColor = UIColor.clearColor() self.elementView.userInteractionEnabled = false self.elementView.hidden = true self.elementView.backgroundColor = UIColor.blackColor() self.elementView.addSubview(self.videoView) self.elementView.layer.masksToBounds = true self.videoView.userInteractionEnabled = false } func run() { NSLog("PluginMediaStreamRenderer#run()") self.videoView.delegate = self } func render(pluginMediaStream: PluginMediaStream) { NSLog("PluginMediaStreamRenderer#render()") if self.pluginMediaStream != nil { self.reset() } self.pluginMediaStream = pluginMediaStream // Take the first audio track. for (id, track) in pluginMediaStream.audioTracks { self.rtcAudioTrack = track.rtcMediaStreamTrack as? RTCAudioTrack break } // Take the first video track. for (id, track) in pluginMediaStream.videoTracks { self.rtcVideoTrack = track.rtcMediaStreamTrack as? RTCVideoTrack break } if self.rtcVideoTrack != nil { self.rtcVideoTrack!.addRenderer(self.videoView) } } func mediaStreamChanged() { NSLog("PluginMediaStreamRenderer#mediaStreamChanged()") if self.pluginMediaStream == nil { return } let oldRtcVideoTrack: RTCVideoTrack? = self.rtcVideoTrack self.rtcAudioTrack = nil self.rtcVideoTrack = nil // Take the first audio track. for (id, track) in self.pluginMediaStream!.audioTracks { self.rtcAudioTrack = track.rtcMediaStreamTrack as? RTCAudioTrack break } // Take the first video track. for (id, track) in pluginMediaStream!.videoTracks { self.rtcVideoTrack = track.rtcMediaStreamTrack as? RTCVideoTrack break } // If same video track as before do nothing. if oldRtcVideoTrack != nil && self.rtcVideoTrack != nil && oldRtcVideoTrack!.label == self.rtcVideoTrack!.label { NSLog("PluginMediaStreamRenderer#mediaStreamChanged() | same video track as before") } // Different video track. else if oldRtcVideoTrack != nil && self.rtcVideoTrack != nil && oldRtcVideoTrack!.label != self.rtcVideoTrack!.label { NSLog("PluginMediaStreamRenderer#mediaStreamChanged() | has a new video track") oldRtcVideoTrack!.removeRenderer(self.videoView) self.rtcVideoTrack!.addRenderer(self.videoView) } // Did not have video but now it has. else if oldRtcVideoTrack == nil && self.rtcVideoTrack != nil { NSLog("PluginMediaStreamRenderer#mediaStreamChanged() | video track added") self.rtcVideoTrack!.addRenderer(self.videoView) } // Had video but now it has not. else if oldRtcVideoTrack != nil && self.rtcVideoTrack == nil { NSLog("PluginMediaStreamRenderer#mediaStreamChanged() | video track removed") oldRtcVideoTrack!.removeRenderer(self.videoView) } } func refresh(data: NSDictionary) { let elementLeft = data.objectForKey("elementLeft") as? Float ?? 0 let elementTop = data.objectForKey("elementTop") as? Float ?? 0 let elementWidth = data.objectForKey("elementWidth") as? Float ?? 0 let elementHeight = data.objectForKey("elementHeight") as? Float ?? 0 var videoViewWidth = data.objectForKey("videoViewWidth") as? Float ?? 0 var videoViewHeight = data.objectForKey("videoViewHeight") as? Float ?? 0 let visible = data.objectForKey("visible") as? Bool ?? true let opacity = data.objectForKey("opacity") as? Float ?? 1 let zIndex = data.objectForKey("zIndex") as? Float ?? 0 let mirrored = data.objectForKey("mirrored") as? Bool ?? false let clip = data.objectForKey("clip") as? Bool ?? true var borderRadius = data.objectForKey("borderRadius") as? Float ?? 0 NSLog("PluginMediaStreamRenderer#refresh() [elementLeft:\(elementLeft), elementTop:\(elementTop), elementWidth:\(elementWidth), elementHeight:\(elementHeight), videoViewWidth:\(videoViewWidth), videoViewHeight:\(videoViewHeight), visible:\(visible), opacity:\(opacity), zIndex:\(zIndex), mirrored:\(mirrored), clip:\(clip), borderRadius:\(borderRadius)]") let videoViewLeft: Float = (elementWidth - videoViewWidth) / 2 let videoViewTop: Float = (elementHeight - videoViewHeight) / 2 self.elementView.frame = CGRectMake( CGFloat(elementLeft), CGFloat(elementTop), CGFloat(elementWidth), CGFloat(elementHeight) ) // NOTE: Avoid a zero-size UIView for the video (the library complains). if videoViewWidth == 0 || videoViewHeight == 0 { videoViewWidth = 1 videoViewHeight = 1 self.videoView.hidden = true } else { self.videoView.hidden = false } self.videoView.frame = CGRectMake( CGFloat(videoViewLeft), CGFloat(videoViewTop), CGFloat(videoViewWidth), CGFloat(videoViewHeight) ) if visible { self.elementView.hidden = false } else { self.elementView.hidden = true } self.elementView.alpha = CGFloat(opacity) self.elementView.layer.zPosition = CGFloat(zIndex) if !mirrored { self.elementView.transform = CGAffineTransformIdentity } else { self.elementView.transform = CGAffineTransformMakeScale(-1.0, 1.0) } if clip { self.elementView.clipsToBounds = true } else { self.elementView.clipsToBounds = false } self.elementView.layer.cornerRadius = CGFloat(borderRadius) } func close() { NSLog("PluginMediaStreamRenderer#close()") self.reset() self.elementView.removeFromSuperview() } /** * Private API. */ private func reset() { NSLog("PluginMediaStreamRenderer#reset()") if self.rtcVideoTrack != nil { self.rtcVideoTrack!.removeRenderer(self.videoView) } self.pluginMediaStream = nil self.rtcAudioTrack = nil self.rtcVideoTrack = nil } /** * Methods inherited from RTCEAGLVideoViewDelegate. */ func videoView(videoView: RTCEAGLVideoView!, didChangeVideoSize size: CGSize) { NSLog("PluginMediaStreamRenderer | video size changed [width:\(size.width), height:\(size.height)]") self.eventListener(data: [ "type": "videoresize", "size": [ "width": Int(size.width), "height": Int(size.height) ] ]) } }
mit
0c445fb801bfeaf03b2e647554e13681
27.252033
357
0.728201
3.801969
false
false
false
false
modocache/swift
test/SILGen/enum_resilience.swift
3
2120
// RUN: %target-swift-frontend -I %S/../Inputs -enable-source-import -emit-silgen -enable-resilience %s | %FileCheck %s import resilient_enum // Resilient enums are always address-only, and switches must include // a default case // CHECK-LABEL: sil hidden @_TF15enum_resilience15resilientSwitchFO14resilient_enum6MediumT_ : $@convention(thin) (@in Medium) -> () // CHECK: [[BOX:%.*]] = alloc_stack $Medium // CHECK-NEXT: copy_addr %0 to [initialization] [[BOX]] // CHECK-NEXT: switch_enum_addr [[BOX]] : $*Medium, case #Medium.Paper!enumelt: bb1, case #Medium.Canvas!enumelt: bb2, case #Medium.Pamphlet!enumelt.1: bb3, case #Medium.Postcard!enumelt.1: bb4, default bb5 // CHECK: bb1: // CHECK-NEXT: dealloc_stack [[BOX]] // CHECK-NEXT: br bb6 // CHECK: bb2: // CHECK-NEXT: dealloc_stack [[BOX]] // CHECK-NEXT: br bb6 // CHECK: bb3: // CHECK-NEXT: [[INDIRECT_ADDR:%.*]] = unchecked_take_enum_data_addr [[BOX]] // CHECK-NEXT: [[INDIRECT:%.*]] = load [[INDIRECT_ADDR]] // CHECK-NEXT: [[PAYLOAD:%.*]] = project_box [[INDIRECT]] // CHECK-NEXT: strong_release [[INDIRECT]] // CHECK-NEXT: dealloc_stack [[BOX]] // CHECK-NEXT: br bb6 // CHECK: bb4: // CHECK-NEXT: [[PAYLOAD_ADDR:%.*]] = unchecked_take_enum_data_addr [[BOX]] // CHECK-NEXT: destroy_addr [[PAYLOAD_ADDR]] // CHECK-NEXT: dealloc_stack [[BOX]] // CHECK-NEXT: br bb6 // CHECK: bb5: // CHECK-NEXT: unreachable // CHECK: bb6: // CHECK-NEXT: destroy_addr %0 // CHECK-NEXT: [[RESULT:%.*]] = tuple () // CHECK-NEXT: return [[RESULT]] func resilientSwitch(_ m: Medium) { switch m { case .Paper: () case .Canvas: () case .Pamphlet: () case .Postcard: () } } // Indirect enums are still address-only, because the discriminator is stored // as part of the value, so we cannot resiliently make assumptions about the // enum's size // CHECK-LABEL: sil hidden @_TF15enum_resilience21indirectResilientEnumFO14resilient_enum16IndirectApproachT_ : $@convention(thin) (@in IndirectApproach) -> () func indirectResilientEnum(_ ia: IndirectApproach) {}
apache-2.0
affa5f610de9a5db507096187ee1acba
40.568627
209
0.646698
3.365079
false
false
false
false
modum-io/ios_client
PharmaSupplyChain/NSManagedObjectContext+Extension.swift
1
4980
// // NSManagedObjectContext+Extension.swift // PharmaSupplyChain // // Created by Yury Belevskiy on 08.11.16. // Copyright © 2016 Modum. All rights reserved. // import CoreData extension NSManagedObjectContext { /* Saves current NSManagedObjectContext and all it's parent contexts, apart from the topmost NSManagedObjectContext If current NSManagedObjectContext has no parent contexts, returns self */ func saveRecursively() -> NSManagedObjectContext { //if parent == nil, we reached topmost context guard parent != nil else { return self } var successfullySaved = true performAndWait ({ [weak self] in if let context = self, context.hasChanges { do { try context.save() } catch let error as NSError { successfullySaved = false log("NSManagedObjectContext.saveRecursively(): \(error.localizedDescription). Detailed information: \(error.userInfo.description)") } } else { successfullySaved = false } }) if !successfullySaved { return self } else { return parent!.saveRecursively() } } /* Given list of 'identifier' from UniqueManagedObject, fetches corresponding NSManagedObject Identifier format: <entity name>.<UUID> */ func fetchRecords(WithIdentifiers ids: [String]) -> [NSManagedObject] { /* Extract entity name from identifier */ var recordTypes = Set<String>() for id in ids { if let dotIndex = id.characters.index(of: ".") { let recordType = id.substring(to: dotIndex) recordTypes.insert(recordType) } } /* Form fetch request for every entity */ var results: [NSManagedObject] = [] for recordType in recordTypes { let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: recordType) fetchRequest.predicate = NSPredicate(format: "identifier IN %@", ids) do { if let response = try fetch(fetchRequest) as? [NSManagedObject] { results.append(contentsOf: response) } } catch let error { log("Failed to execute fetch request: \(error.localizedDescription)") } } return results } func getEntities(IfUserInfoKeyPresent userInfoKey: String) -> [String] { var entities: [String] = [] if let persistentStoreCoordinator = persistentStoreCoordinator { let availableEntities = persistentStoreCoordinator.managedObjectModel.entities for entity in availableEntities { if let userInfo = entity.userInfo, let entityName = entity.name { if userInfo.keys.contains(userInfoKey) { entities.append(entityName) } } } } return entities } /* Returns NSManagedObject array containing NSManagedObject instances with given @name registered within the context If no matching objects are found within this context, return empty array */ func dumpRegisteredObjects(ForEntityName entityName: String) -> [NSManagedObject] { var results: [NSManagedObject] = [] for registeredObject in registeredObjects { if let entityName = registeredObject.entity.name { if entityName.compare(entityName) == .orderedSame { results.append(registeredObject) } } } return results } /* Prints description of all object registered within the context */ func dumpRegisteredObjects() { for registeredObject in registeredObjects { log(registeredObject.description) } } /* wipes entire contents of associated persistent store */ func deleteAllObjects() { if let entitiesByName = persistentStoreCoordinator?.managedObjectModel.entitiesByName { for (_, entityDescription) in entitiesByName { deleteAllObjectsForEntity(entityDescription) } } } /* wipes all objects for given entity type in associated store coordinator */ func deleteAllObjectsForEntity(_ entity: NSEntityDescription) { let fetchRequest = NSFetchRequest<NSManagedObject>() fetchRequest.entity = entity do { let fetchResults = try fetch(fetchRequest) for result in fetchResults { log("Deleting object \(result.objectID)...") delete(result) } } catch let error { log("Error clearing CoreData entity \(entity): \(error.localizedDescription)") return } } }
apache-2.0
319a66289db62d646e4265a91d7ed630
35.881481
150
0.592488
5.843897
false
false
false
false
modum-io/ios_client
PharmaSupplyChain/ServerDateTransform.swift
1
1323
// // ServerDateTransform.swift // PharmaSupplyChain // // Created by Yury Belevskiy on 06.03.17. // Copyright © 2017 Modum. All rights reserved. // import ObjectMapper /* Converts server date format into Date and vice versa */ class ServerDateTransform : TransformType { // MARK: Constants /* If date from the server-side is to set to nil, server automatically sets this value */ static let serverNilDateString: String = "0001-01-01T00:34:08+00:34" // MARK: TransformType typealias Object = Date typealias JSON = String public init() {} public func transformFromJSON(_ value: Any?) -> Date? { let dateFormatter = Date.iso8601Formatter if let dateValue = value as? String { if dateValue == ServerDateTransform.serverNilDateString { return nil } else { return dateFormatter.date(from: dateValue) } } else { return nil } } public func transformToJSON(_ value: Date?) -> String? { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'" if let date = value { return dateFormatter.string(from: date) } else { return nil } } }
apache-2.0
e8ea258fb1f24c417efa34941c1370ff
25.979592
93
0.593041
4.558621
false
false
false
false
wilmarvh/Bounce
Hooops/Home/HomeFilterCell.swift
1
2162
import Foundation import UIKit class HomeFilterCell: UICollectionViewCell { static let width: CGFloat = 130 static let height: CGFloat = 32 // MARK: required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) configureViews() } override init(frame: CGRect) { super.init(frame: frame) configureViews() } // MARK: Views lazy var button: FilterButton = { let button = FilterButton(type: .custom) button.translatesAutoresizingMaskIntoConstraints = false button.layer.cornerRadius = HomeFilterCell.height / 2 button.backgroundColor = UIColor.grayButton() button.titleLabel?.font = UIFont.systemFont(ofSize: 17, weight: UIFont.Weight.semibold) button.titleLabel?.textAlignment = .center button.setTitleColor(UIColor.darkBlueGrey(), for: .normal) button.setTitleColor(.white, for: .highlighted) button.setTitleColor(.white, for: .selected) return button }() func configureViews() { contentView.addSubview(button) contentView.addConstraint(NSLayoutConstraint(item: button, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: HomeFilterCell.height)) contentView.addConstraint(NSLayoutConstraint(item: button, attribute: .width, relatedBy: .equal, toItem: contentView, attribute: .width, multiplier: 1.0, constant: 0)) } } class FilterButton: UIButton { var action: (() -> Void)? required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) addTarget(self, action: #selector(tapped), for: .touchUpInside) } override init(frame: CGRect) { super.init(frame: frame) addTarget(self, action: #selector(tapped), for: .touchUpInside) } override open var isHighlighted: Bool { didSet { backgroundColor = isHighlighted ? UIColor.hooopsGreen() : UIColor.grayButton() } } @objc func tapped() { if let action = action { action() } } }
mit
4e3743adb485c29e7e38dd9ac3a66c2b
30.333333
197
0.637373
4.7
false
false
false
false
lorentey/swift
benchmark/single-source/ByteSwap.swift
18
1914
//===--- ByteSwap.swift ---------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // This test checks performance of Swift byte swap. // rdar://problem/22151907 import TestsUtils public let ByteSwap = BenchmarkInfo( name: "ByteSwap", runFunction: run_ByteSwap, tags: [.validation, .algorithm]) // a naive O(n) implementation of byteswap. @inline(never) func byteswap_n(_ a: UInt64) -> UInt64 { return ((a & 0x00000000000000FF) &<< 56) | ((a & 0x000000000000FF00) &<< 40) | ((a & 0x0000000000FF0000) &<< 24) | ((a & 0x00000000FF000000) &<< 8) | ((a & 0x000000FF00000000) &>> 8) | ((a & 0x0000FF0000000000) &>> 24) | ((a & 0x00FF000000000000) &>> 40) | ((a & 0xFF00000000000000) &>> 56) } // a O(logn) implementation of byteswap. @inline(never) func byteswap_logn(_ a: UInt64) -> UInt64 { var a = a a = (a & 0x00000000FFFFFFFF) << 32 | (a & 0xFFFFFFFF00000000) >> 32 a = (a & 0x0000FFFF0000FFFF) << 16 | (a & 0xFFFF0000FFFF0000) >> 16 a = (a & 0x00FF00FF00FF00FF) << 8 | (a & 0xFF00FF00FF00FF00) >> 8 return a } @inline(never) public func run_ByteSwap(_ N: Int) { var s: UInt64 = 0 for _ in 1...10000*N { // Check some results. let x : UInt64 = UInt64(getInt(0)) s = s &+ byteswap_logn(byteswap_n(x &+ 2457)) &+ byteswap_logn(byteswap_n(x &+ 9129)) &+ byteswap_logn(byteswap_n(x &+ 3333)) } CheckResults(s == (2457 &+ 9129 &+ 3333) &* 10000 &* N) }
apache-2.0
6e16b7da772412b08837ed3652aa4d8e
32.578947
80
0.574713
3.430108
false
false
false
false
uraimo/SwiftyLISP
SwiftyLisp.playground/Contents.swift
1
501
import SwiftyLisp let expr:SExpr = "(cond ((atom (quote A)) (quote B)) ((quote true) (quote C)))" print(expr) print(expr.eval()!) //B let e2:SExpr = "(defun TEST (x y) (atom x))" print(e2) print(e2.eval()!) //B print(localContext) var e3:SExpr = "(TEST b (quote (a b c)))" print(e3) print(e3.eval()!) // true e3 = "(TEST (quote (a b c)) b)" print(e3) print(e3.eval()!) // false () e3 = "( (lambda (x y) (atom x)) a b)" print(e3) print(e3.eval()!) print(e3.eval()!) print(localContext)
mit
9023bfa99e3ad659d660839b7a08449b
15.16129
79
0.586826
2.42029
false
true
false
false
vector-im/vector-ios
Riot/Modules/CrossSigning/CrossSigningService.swift
1
4224
/* Copyright 2020 New Vector Ltd 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 enum CrossSigningServiceError: Int, Error { case authenticationRequired case unknown } extension CrossSigningServiceError: CustomNSError { public static let errorDomain = "CrossSigningService" public var errorCode: Int { return Int(rawValue) } public var errorUserInfo: [String: Any] { return [:] } } @objcMembers final class CrossSigningService: NSObject { // MARK - Properties private var supportSetupKeyVerificationByUser: [String: Bool] = [:] // Cached server response private var userInteractiveAuthenticationService: UserInteractiveAuthenticationService? // MARK - Public @discardableResult func canSetupCrossSigning(for session: MXSession, success: @escaping ((Bool) -> Void), failure: @escaping ((Error) -> Void)) -> MXHTTPOperation? { guard let crossSigning = session.crypto?.crossSigning, crossSigning.state == .notBootstrapped else { // Cross-signing already setup success(false) return nil } let userId: String = session.myUserId if let supportSetupKeyVerification = self.supportSetupKeyVerificationByUser[userId] { // Return cached response success(supportSetupKeyVerification) return nil } let userInteractiveAuthenticationService = UserInteractiveAuthenticationService(session: session) self.userInteractiveAuthenticationService = userInteractiveAuthenticationService let request = self.setupCrossSigningRequest() return userInteractiveAuthenticationService.canAuthenticate(with: request) { (result) in switch result { case .success(let succeeded): success(succeeded) case .failure(let error): failure(error) } } } func setupCrossSigningRequest() -> AuthenticatedEndpointRequest { let path = "\(kMXAPIPrefixPathUnstable)/keys/device_signing/upload" return AuthenticatedEndpointRequest(path: path, httpMethod: "POST") } /// Setup cross-signing without authentication. Useful when a grace period is enabled. @discardableResult func setupCrossSigningWithoutAuthentication(for session: MXSession, success: @escaping (() -> Void), failure: @escaping ((Error) -> Void)) -> MXHTTPOperation? { guard let crossSigning = session.crypto.crossSigning else { failure(CrossSigningServiceError.unknown) return nil } let userInteractiveAuthenticationService = UserInteractiveAuthenticationService(session: session) self.userInteractiveAuthenticationService = userInteractiveAuthenticationService let request = self.setupCrossSigningRequest() return userInteractiveAuthenticationService.authenticatedEndpointStatus(for: request) { result in switch result { case .success(let authenticatedEnpointStatus): switch authenticatedEnpointStatus { case .authenticationNeeded: failure(CrossSigningServiceError.authenticationRequired) case .authenticationNotNeeded: crossSigning.setup(withAuthParams: [:]) { success() } failure: { error in failure(error) } } case .failure(let error): failure(error) } } } }
apache-2.0
b020cf92fe8dc5a6849b9cb010a52493
35.413793
164
0.648674
5.723577
false
false
false
false
IAskWind/IAWExtensionTool
Pods/Easy/Easy/Classes/Core/EasyLoading.swift
1
1254
// // EasyLoading.swift // Easy // // Created by OctMon on 2018/10/12. // import UIKit #if canImport(MBProgressHUD) import MBProgressHUD #endif public extension UIView { func showLoading(_ text: String? = EasyGlobal.loadingText) { #if canImport(MBProgressHUD) endEditing(true) show(mode: .indeterminate, text: text) #endif } func hideLoading() { #if canImport(MBProgressHUD) MBProgressHUD.hide(for: self, animated: true) #endif } func showText(_ text: String?, afterDelay: TimeInterval = 1) { #if canImport(MBProgressHUD) guard let text = text, !text.isEmpty else { return } show(mode: .text, text: text, afterDelay: afterDelay) #endif } #if canImport(MBProgressHUD) func show(mode: MBProgressHUDMode, text: String?, afterDelay: TimeInterval = 1) { let hud = MBProgressHUD.showAdded(to: self, animated: true) hud.animationType = .fade hud.mode = mode hud.label.numberOfLines = 0 hud.label.text = text hud.removeFromSuperViewOnHide = true if mode == .text { hud.hide(animated: true, afterDelay: afterDelay) } } #endif }
mit
f7c6b47daf0b454ea0905c61972ae47c
24.08
85
0.606858
4.265306
false
false
false
false
ratreya/lipika-ime
Input Source/ClientManager.swift
1
6567
/* * LipikaIME is a user-configurable phonetic Input Method Engine for Mac OS X. * Copyright (C) 2018 Ranganath Atreya * * 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. */ import InputMethodKit import LipikaEngine_OSX class ClientManager: CustomStringConvertible { private let notFoundRange = NSMakeRange(NSNotFound, NSNotFound) private let config = LipikaConfig() private let client: IMKTextInput // This is the position of the cursor within the marked text public var markedCursorLocation: Int? = nil private var candidatesWindow: IMKCandidates { return (NSApp.delegate as! AppDelegate).candidatesWindow } private (set) var candidates = autoreleasepool { return [String]() } // Cache, otherwise clients quitting can sometimes SEGFAULT us private var _description: String var description: String { return _description } private var attributes: [NSAttributedString.Key: Any]! { var rect = NSMakeRect(0, 0, 0, 0) return client.attributes(forCharacterIndex: 0, lineHeightRectangle: &rect) as? [NSAttributedString.Key : Any] } init?(client: IMKTextInput) { guard let bundleId = client.bundleIdentifier(), let clientId = client.uniqueClientIdentifierString() else { Logger.log.warning("bundleIdentifier: \(client.bundleIdentifier() ?? "nil") or uniqueClientIdentifierString: \(client.uniqueClientIdentifierString() ?? "nil") - failing ClientManager.init()") return nil } Logger.log.debug("Initializing client: \(bundleId) with Id: \(clientId)") self.client = client if !client.supportsUnicode() { Logger.log.warning("Client: \(bundleId) does not support Unicode!") } if !client.supportsProperty(TSMDocumentPropertyTag(kTSMDocumentSupportDocumentAccessPropertyTag)) { Logger.log.warning("Client: \(bundleId) does not support Document Access!") } _description = "\(bundleId) with Id: \(clientId)" } func setGlobalCursorLocation(_ location: Int) { Logger.log.debug("Setting global cursor location to: \(location)") client.setMarkedText("|", selectionRange: NSMakeRange(0, 0), replacementRange: NSMakeRange(location, 0)) client.setMarkedText("", selectionRange: NSMakeRange(0, 0), replacementRange: NSMakeRange(location, 0)) } func updateMarkedCursorLocation(_ delta: Int) -> Bool { Logger.log.debug("Cursor moved: \(delta) with selectedRange: \(client.selectedRange()), markedRange: \(client.markedRange()) and cursorPosition: \(markedCursorLocation?.description ?? "nil")") if client.markedRange().length == NSNotFound { return false } let nextPosition = (markedCursorLocation ?? client.markedRange().length) + delta if (0...client.markedRange().length).contains(nextPosition) { Logger.log.debug("Still within markedRange") markedCursorLocation = nextPosition return true } Logger.log.debug("Outside of markedRange") markedCursorLocation = nil return false } func showActive(clientText: NSAttributedString, candidateText: String, replacementRange: NSRange? = nil) { Logger.log.debug("Showing clientText: \(clientText) and candidateText: \(candidateText)") client.setMarkedText(clientText, selectionRange: NSMakeRange(markedCursorLocation ?? clientText.length, 0), replacementRange: replacementRange ?? notFoundRange) candidates = [candidateText] if clientText.string.isEmpty { candidatesWindow.hide() } else { candidatesWindow.update() if config.showCandidates { candidatesWindow.show() } } } func finalize(_ output: String) { Logger.log.debug("Finalizing with: \(output)") client.insertText(output, replacementRange: notFoundRange) candidatesWindow.hide() markedCursorLocation = nil } func clear() { Logger.log.debug("Clearing MarkedText and Candidate window") client.setMarkedText("", selectionRange: NSMakeRange(0, 0), replacementRange: notFoundRange) candidatesWindow.hide() markedCursorLocation = nil } func findWord(at current: Int) -> NSRange? { let maxLength = client.length() var exponent = 2 var wordStart = -1, wordEnd = -1 Logger.log.debug("Finding word at: \(current) with max: \(maxLength)") repeat { let low = wordStart == -1 ? max(current - 2 << exponent, 0): wordStart let high = wordEnd == -1 ? min(current + 2 << exponent, maxLength): wordEnd Logger.log.debug("Looking for word between \(low) and \(high)") var real = NSRange() guard let text = client.string(from: NSMakeRange(low, high - low), actualRange: &real) else { return nil } Logger.log.debug("Looking for word in text: \(text)") if wordStart == -1, let startOffset = text.unicodeScalars[text.unicodeScalars.startIndex..<text.unicodeScalars.index(text.unicodeScalars.startIndex, offsetBy: current - real.location)].reversed().firstIndex(where: { CharacterSet.whitespacesAndNewlines.contains($0) })?.base.utf16Offset(in: text) { wordStart = real.location + startOffset Logger.log.debug("Found wordStart: \(wordStart)") } if wordEnd == -1, let endOffset = text.unicodeScalars[text.unicodeScalars.index(text.unicodeScalars.startIndex, offsetBy: current - real.location)..<text.unicodeScalars.endIndex].firstIndex(where: { CharacterSet.whitespacesAndNewlines.contains($0) })?.utf16Offset(in: text) { wordEnd = real.location + endOffset Logger.log.debug("Found wordEnd: \(wordEnd)") } exponent += 1 if wordStart == -1, low == 0 { wordStart = low Logger.log.debug("Starting word at beginning of document") } if wordEnd == -1, high == maxLength { wordEnd = high Logger.log.debug("Ending word at end of document") } } while(wordStart == -1 || wordEnd == -1) Logger.log.debug("Found word between \(wordStart) and \(wordEnd)") return NSMakeRange(wordStart, wordEnd - wordStart) } }
gpl-3.0
bd85732c7b01f7a24c527755c94432ba
49.129771
309
0.651591
4.886161
false
false
false
false
roambotics/swift
validation-test/compiler_crashers_2_fixed/issue-52260.swift
2
411
// RUN: %target-swift-frontend -Xllvm -sil-verify-after-pass=loadable-address -emit-ir -o %t.ll %s // https://github.com/apple/swift/issues/52260 // Just make sure we don't crash. struct Large { var a: Int = 1 var b: Int = 1 var c: Int = 1 var d: Int = 1 var e: Int = 1 var f: Int = 1 var g: Int = 1 var h: Int = 1 } func test(_ x: Large) -> (Large, (Large) -> Large) { return (x, {$0}) }
apache-2.0
d1365ad4abb01093d59bd7404f7d59f4
19.55
98
0.586375
2.634615
false
false
false
false
chenchangqing/travelMapMvvm
travelMapMvvm/travelMapMvvm/Helper/ValidHelper.swift
1
1134
// // ValidHelper.swift // travelMapMvvm // // Created by green on 15/9/8. // Copyright (c) 2015年 travelMapMvvm. All rights reserved. // import UIKit class ValidHelper: NSObject { /** * 校验手机号 */ class func isValidTelephone(telephoneStr:NSString) -> Bool { return String(telephoneStr).length == 11 } /** * 校验密码 */ class func isValidPassword(password:NSString) -> Bool { return String(password).length > 0 } /** * 校验验证码 */ class func isValidVerifyCode(verifyCode:NSString) -> Bool { return String(verifyCode).length == 4 } /** * 校验用户名 */ class func isValidUsername(userName:NSString) -> Bool { return String(userName).length > 0 } /** * 校验邮箱 */ class func isValidEmail(email:NSString) -> Bool { let predicate = NSPredicate(format: "SELF MATCHES %@", "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}") return predicate.evaluateWithObject(email) } }
apache-2.0
891a9b26ae22ed9e8a196ece093fce58
19.111111
114
0.539595
3.878571
false
false
false
false
honghaoz/CrackingTheCodingInterview
Swift/LeetCode/Tree/111_Minimum Depth of Binary Tree.swift
2
2864
// 111_Minimum Depth of Binary Tree // https://leetcode.com/problems/minimum-depth-of-binary-tree/ // // Created by Honghao Zhang on 9/17/19. // Copyright © 2019 Honghaoz. All rights reserved. // // Description: // Given a binary tree, find its minimum depth. // //The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. // //Note: A leaf is a node with no children. // //Example: // //Given binary tree [3,9,20,null,null,15,7], // // 3 // / \ // 9 20 // / \ // 15 7 //return its minimum depth = 2. // // // import Foundation class Num111 { /// DFS but check if the there's real branch func minDepth(_ root: TreeNode?) -> Int { return minDepthHelper(root) ?? 0 } /// Returns the min depth of a node, returns nil if this node is nil. private func minDepthHelper(_ root: TreeNode?) -> Int? { if root == nil { return nil } let left = minDepthHelper(root?.left) let right = minDepthHelper(root?.right) if let realLeft = left, let realRight = right { return min(realLeft, realRight) + 1 } else if let realLeft = left, right == nil { return realLeft + 1 } else if let realRight = right, left == nil { return realRight + 1 } else { return 1 } } /// DFS with stack func minDepth_iterative(_ root: TreeNode?) -> Int { guard root != nil else { return 0 } var stack: [TreeNode] = [] var depths: [Int] = [] stack.append(root!) depths.append(1) // the current min depth var result: Int = Int.max while !stack.isEmpty { let last = stack.popLast()! let currentDepth = depths.popLast()! // this is the leaf, record the min depth if last.left == nil && last.right == nil { result = min(result, currentDepth) } if let left = last.left { stack.append(left) depths.append(currentDepth + 1) } if let right = last.right { stack.append(right) depths.append(currentDepth + 1) } } return result } /// BFS with queue func minDepth_iterative_bfs(_ root: TreeNode?) -> Int { guard root != nil else { return 0 } var queue: [TreeNode] = [] var depths: [Int] = [] queue.append(root!) depths.append(1) while !queue.isEmpty { let last = queue.removeFirst() let currentDepth = depths.removeFirst() // this is the leaf, since this is BFS, we find the min depth if last.left == nil && last.right == nil { return currentDepth } if let left = last.left { queue.append(left) depths.append(currentDepth + 1) } if let right = last.right { queue.append(right) depths.append(currentDepth + 1) } } assertionFailure() return -1 } }
mit
24649c5ee88c2f510f981a155bb85e69
22.467213
116
0.587845
3.605793
false
false
false
false
AdeptusAstartes/HHiTunesRSSFeedChecker
HHiTunesRSSFeedChecker/HHiTunesRSSFeedChecker.swift
1
6319
// // HHiTunesRSSFeedChecker.swift // HHiTunesRSSFeedChecker // // Created by Donald Angelillo on 8/24/17. // Copyright © 2017 Donald Angelillo. All rights reserved. // import Foundation import Alamofire enum HHiTunesRSSFeedCheckerFeedType: String { case newReleases = "new-music-heavy-metal" case recentReleases = "recent-releases-heavy-metal" case hotTracks = "hot-tracks-heavy-metal" } struct HHiTunesRSSFeedChecker { var showDetailedOutput: Bool = true mutating func findElegibleStoreFrontsForNewItunesFeeds(simultaneously: Bool, showDetailedOutput: Bool, completion: @escaping (_ results: [String: [String]]) -> ()) { self.showDetailedOutput = showDetailedOutput if (simultaneously) { self.runSimultaneously(completion: completion) } else { self.runInBatches(completion: completion) } } private func runInBatches(completion: @escaping (_ results: [String: [String]]) -> ()) { let feedTypes: [HHiTunesRSSFeedCheckerFeedType] = [.newReleases, .recentReleases, .hotTracks] var results: [String: [String]] = Dictionary() self.checkStoreFrontsFor(feedType: feedTypes[0]) { (feedType, eligibleCountryCodes) in results[feedType.rawValue] = eligibleCountryCodes self.checkStoreFrontsFor(feedType: feedTypes[1]) { (feedType, eligibleCountryCodes) in results[feedType.rawValue] = eligibleCountryCodes self.checkStoreFrontsFor(feedType: feedTypes[2]) { (feedType, eligibleCountryCodes) in results[feedType.rawValue] = eligibleCountryCodes completion(results) } } } } private func runSimultaneously(completion: @escaping (_ results: [String: [String]]) -> ()) { let feedTypes: [HHiTunesRSSFeedCheckerFeedType] = [.newReleases, .recentReleases, .hotTracks] var totalComplete = 0 var results: [String: [String]] = Dictionary() for feedType in feedTypes { self.checkStoreFrontsFor(feedType: feedType, completion: { (feedType, eligibleCountryCodes) in results[feedType.rawValue] = eligibleCountryCodes totalComplete+=1 if (totalComplete == feedTypes.count) { completion(results) } }) } } private func checkStoreFrontsFor(feedType: HHiTunesRSSFeedCheckerFeedType, completion: @escaping (_ feedType: HHiTunesRSSFeedCheckerFeedType, _ eligibleCountryCodes: [String]) -> ()) { var eligibleCountryCodes: [String] = Array() var totalComplete = 0 let countryCodes = self.getAllCountryCodes(lowercase: true) for countryCode in countryCodes { if let url = URL(string: String(format: "https://rss.itunes.apple.com/api/v1/%@/itunes-music/%@/10/explicit.json", countryCode, feedType.rawValue)) { Alamofire.request(url).validate().responseJSON(completionHandler: { (response) in if (response.result.isFailure) { totalComplete+=1 if (self.showDetailedOutput) { print(totalComplete, "of", countryCodes.count, "for", feedType.rawValue, "FAILURE for", countryCode, "ERROR:", response.error!.localizedDescription) } if (totalComplete == countryCodes.count) { completion(feedType, eligibleCountryCodes.sorted()) } } else { if let json = response.result.value as? [String: Any], let feed = json["feed"] as? [String: Any], let _ = feed["results"] as? [[String: Any]] { eligibleCountryCodes.append(countryCode) totalComplete+=1 if (self.showDetailedOutput) { print(totalComplete, "of", countryCodes.count, "for", feedType.rawValue, "SUCCESS for", countryCode) } if (totalComplete == countryCodes.count) { completion(feedType, eligibleCountryCodes.sorted()) } } else { totalComplete+=1 if (self.showDetailedOutput) { print(totalComplete, "of", countryCodes.count, "for", feedType.rawValue, "FEED NOT AVAILABLE for", countryCode) } if (totalComplete == countryCodes.count) { completion(feedType, eligibleCountryCodes.sorted()) } } } }) } } } private func getAllCountryCodes(lowercase: Bool) -> [String] { var countryCodes: [String] = Array() for country in HHiTunesStorefrontFinder.countryData { if let countryCode = country["countryCode"] { if (lowercase) { countryCodes.append(countryCode.lowercased()) } else { countryCodes.append(countryCode) } } } return countryCodes } func printResults(results: [String: [String]]) { let countryCodes = self.getAllCountryCodes(lowercase: true) if (self.showDetailedOutput) { print("\n") } for (key, value) in results { print("Feed Type:", key) print("Feeds found for", value.count, "of", countryCodes.count, "countries") print("Countries found:", value) print(countryCodes.count - value.count, "either missing or timed out") print("\n") } } }
mit
c226ff9d78b138aaab8bd1ded2a86407
40.565789
188
0.526749
5.336149
false
false
false
false
fly2xj/zhihu_xjing
zhihu.study/zhihu.study/LaunchImageViewController.swift
1
1783
// // LaunchImageViewController.swift // zhihu.study // // Created by shawn on 22/7/15. // Copyright (c) 2015 shawn. All rights reserved. // import UIKit import Haneke import SwiftyJSON struct URL { static let lanuchImage = "https://news-at.zhihu.com/api/4/start-image/640*1136?client=0" } class LaunchImageViewController: UIViewController { @IBOutlet weak var imageView: UIImageView! override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) prefersStatusBarHidden() setNeedsStatusBarAppearanceUpdate() } override func viewDidLoad() { super.viewDidLoad() cacheLaunchImage() } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) UIView.animateWithDuration(10, delay: 0, options: UIViewAnimationOptions.TransitionCrossDissolve, animations: { () -> Void in self.imageView.transform = CGAffineTransformMakeScale(1.2, 1.2) }, completion: nil) } func cacheLaunchImage() { let defaults = NSUserDefaults.standardUserDefaults() if let image = defaults.stringForKey("launchImageUrl"), let imageUrl = NSURL(string: image){ imageView.hnk_setImageFromURL(imageUrl) } else { dispatch_async(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0)) { if let url = NSURL(string: URL.lanuchImage), let data = NSData(contentsOfURL: url) { let json = JSON(data: data) if let newUrl = json["img"].string { defaults.setValue(newUrl, forKey: "launchImageUrl") } } } } } }
mit
0db37bed9f70d12cf849f2b1c07d3868
29.220339
133
0.601795
4.831978
false
false
false
false
CoderYLiu/30DaysOfSwift
Project 20 - CollectionViewAnimation/CollectionViewAnimation/AnimationCollectionViewCell.swift
1
1346
// // AnimationCollectionViewCell.swift // CollectionViewAnimation <https://github.com/DeveloperLY/30DaysOfSwift> // // Created by Liu Y on 16/4/26. // Copyright © 2016年 DeveloperLY. All rights reserved. // // This source code is licensed under the MIT-style license found in the // LICENSE file in the root directory of this source tree. // import UIKit class AnimationCollectionViewCell: UICollectionViewCell { @IBOutlet weak var backButton: UIButton! @IBOutlet weak var animationImageView: UIImageView! @IBOutlet weak var animationTextView: UITextView! var backButtonTapped: (() -> Void)? func prepareCell(_ viewModel: AnimationCellModel) { animationImageView.image = UIImage(named: viewModel.imagePath) animationTextView.isScrollEnabled = false backButton.isHidden = true addTapEventHandler() } func handleCellSelected() { animationTextView.isScrollEnabled = false backButton.isHidden = false self.superview?.bringSubview(toFront: self) } fileprivate func addTapEventHandler() { backButton.addTarget(self, action: #selector(AnimationCollectionViewCell.backButtonDidTouch(_:)), for: .touchUpInside) } func backButtonDidTouch(_ sender: UIGestureRecognizer) { backButtonTapped?() } }
mit
f6f9cd19244aa8a32d44bbe35b68dd5b
30.97619
126
0.704393
4.992565
false
false
false
false
movabletype/smartphone-app
MT_iOS/MT_iOS/Classes/Model/EntryDateTimeItem.swift
1
1467
// // EntryDateTimeItem.swift // MT_iOS // // Created by CHEEBOW on 2015/06/02. // Copyright (c) 2015年 Six Apart, Ltd. All rights reserved. // import UIKit class EntryDateTimeItem: BaseEntryItem { var datetime: NSDate? override init() { super.init() type = "datetime" } override func encodeWithCoder(aCoder: NSCoder) { super.encodeWithCoder(aCoder) aCoder.encodeObject(self.datetime, forKey: "datetime") } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder)! self.datetime = aDecoder.decodeObjectForKey("datetime") as? NSDate } override func value()-> String { if let date = self.datetime { let api = DataAPI.sharedInstance if api.apiVersion.isEmpty { return Utils.dateTimeTextFromDate(date) } else { let dateTime = Utils.ISO8601StringFromDate(date) return dateTime } } return "" } override func dispValue()-> String { if let date = self.datetime { return Utils.dateTimeFromDate(date) } return "" } override func makeParams()-> [String : AnyObject] { if let _ = self.datetime { return [self.id:self.value()] } return [self.id:""] } override func clear() { datetime = nil } }
mit
ad875face3eab99b8c02543ae09a7189
22.253968
74
0.548123
4.578125
false
false
false
false
jerrypupu111/LearnDrawingToolSet
SwiftGL-Demo/Source/iOS/PlayBackControlPanel.swift
1
1435
// // PlayBackControlPanel.swift // SwiftGL // // Created by jerry on 2016/2/13. // Copyright © 2016年 Jerry Chan. All rights reserved. // import Foundation import CGUtility class PlayBackControlPanel:UIView { var enabled:Bool = true var UITimer:Timer! var counter:Int = 0 override func awakeFromNib() { layer.cornerRadius = 10 } override func layoutSubviews() { super.layoutSubviews() } func show() { animateShow(0.5) enabled = true UITimer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(PlayBackControlPanel.timeUp), userInfo: nil, repeats: false) } func timeUp() { UITimer.invalidate() hide() } func hide() { animateHide(0.5) enabled = false } func toggle() { if enabled == true { hide() } else { show() } } func pause() { UITimer.invalidate() } func reactivate() { if UITimer != nil { UITimer.invalidate() } UITimer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(PlayBackControlPanel.timeUp), userInfo: nil, repeats: false) } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { reactivate() DLog("panel touched") } }
mit
511d754bddcd904918440a09167e80de
21.030769
150
0.560754
4.236686
false
false
false
false
kstaring/swift
test/attr/attr_nonobjc.swift
8
3479
// RUN: %target-parse-verify-swift // REQUIRES: objc_interop import Foundation @objc class LightSaber { init() { caloriesBurned = 5 } func defeatEnemy(_ b: Bool) -> Bool { // expected-note {{'defeatEnemy' previously declared here}} return !b } // Make sure we can overload a method with @nonobjc methods @nonobjc func defeatEnemy(_ i: Int) -> Bool { return (i > 0) } // This is not allowed, though func defeatEnemy(_ s: String) -> Bool { // expected-error {{method 'defeatEnemy' with Objective-C selector 'defeatEnemy:' conflicts with previous declaration with the same Objective-C selector}} return s != "" } @nonobjc subscript(index: Int) -> Int { return index } @nonobjc var caloriesBurned: Float } class BlueLightSaber : LightSaber { @nonobjc override func defeatEnemy(_ b: Bool) -> Bool { } } @objc class InchoateToad { init(x: Int) {} // expected-note {{previously declared}} @nonobjc init(x: Float) {} init(x: String) {} // expected-error {{conflicts with previous declaration with the same Objective-C selector}} } @nonobjc class NonObjCClassNotAllowed { } // expected-error {{@nonobjc cannot be applied to this declaration}} {{1-10=}} class NonObjCDeallocNotAllowed { @nonobjc deinit { // expected-error {{@nonobjc cannot be applied to this declaration}} {{3-12=}} } } @objc protocol ObjCProtocol { func protocolMethod() // expected-note {{}} @nonobjc func nonObjCProtocolMethodNotAllowed() // expected-error {{declaration is a member of an @objc protocol, and cannot be marked @nonobjc}} @nonobjc subscript(index: Int) -> Int { get } // expected-error {{declaration is a member of an @objc protocol, and cannot be marked @nonobjc}} var surfaceArea: Float { @nonobjc get } // expected-error {{declaration is implicitly @objc, and cannot be marked @nonobjc}} var displacement: Float { get } } class SillyClass { @objc var description: String { @nonobjc get { return "" } } // expected-error {{declaration is implicitly @objc, and cannot be marked @nonobjc}} } class ObjCAndNonObjCNotAllowed { @objc @nonobjc func redundantAttributes() { } // expected-error {{declaration is marked @objc, and cannot be marked @nonobjc}} } class DynamicAndNonObjCNotAllowed { @nonobjc dynamic func redundantAttributes() { } // expected-error {{declaration is marked dynamic, and cannot be marked @nonobjc}} } class IBOutletAndNonObjCNotAllowed { @nonobjc @IBOutlet var leeloo : String? = "Hello world" // expected-error {{declaration is marked @IBOutlet, and cannot be marked @nonobjc}} } class NSManagedAndNonObjCNotAllowed { @nonobjc @NSManaged var rosie : NSObject // expected-error {{declaration is marked @NSManaged, and cannot be marked @nonobjc}} } @nonobjc func nonObjCTopLevelFuncNotAllowed() { } // expected-error {{only methods, initializers, properties and subscript declarations can be declared @nonobjc}} {{1-10=}} @objc class NonObjCPropertyObjCProtocolNotAllowed : ObjCProtocol { // expected-error {{does not conform to protocol}} @nonobjc func protocolMethod() { } // expected-note {{candidate is explicitly '@nonobjc'}} func nonObjCProtocolMethodNotAllowed() { } subscript(index: Int) -> Int { return index } var displacement: Float { @nonobjc get { // expected-error {{declaration is implicitly @objc, and cannot be marked @nonobjc}} return Float(self[10]) } } var surfaceArea: Float { get { return Float(100) } } }
apache-2.0
4a9a0a7d2051427307624440b3641ed7
32.451923
196
0.705663
4.146603
false
false
false
false
jengelsma/cis657-summer2016-class-demos
Lecture12-PuppyFlixDemoWithUnitTests/PuppyFlix/AppDelegate.swift
1
6522
// // AppDelegate.swift // PuppyFlix // // Created by Jonathan Engelsma on 10/14/15. // Copyright © 2015 Jonathan Engelsma. All rights reserved. // import UIKit import OHHTTPStubs @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate { var window: UIWindow? var count: Int? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. let splitViewController = self.window!.rootViewController as! UISplitViewController let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem() splitViewController.delegate = self // wire up the video API let nav2 = splitViewController.viewControllers[0] as? UINavigationController let controller = nav2?.topViewController as? MasterViewController let arguments = NSProcessInfo.processInfo().arguments let mock = arguments.contains("UI_TESTING_MODE") let errorMock = arguments.contains("UI_TESTING_MODE_NO_NETWORK") if mock { // hijack the HTTP fetch let url : String = YouTubeAPI.url + "&q=puppy" stub(isHost(url), response: fixture("VideoStubSuccess.json")) } else if errorMock { let url : String = YouTubeAPI.url + "&q=puppy" let notConnectedError = NSError(domain:NSURLErrorDomain, code:Int(CFNetworkErrors.CFURLErrorNotConnectedToInternet.rawValue), userInfo:nil) stub(isHost(url), response: fixture(notConnectedError)) } controller?.videoAPI = YouTubeAPI.sharedInstance self.count = 0 return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } // MARK: - Split view func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController, ontoPrimaryViewController primaryViewController:UIViewController) -> Bool { guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false } guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false } if topAsDetailController.detailItem == nil { // Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded. return true } return false } func incrementNetworkActivity() { self.count! += 1 UIApplication.sharedApplication().networkActivityIndicatorVisible = true } func decrementNetworkActivity() { if self.count! > 0 { self.count! -= 1 } if self.count! == 0 { UIApplication.sharedApplication().networkActivityIndicatorVisible = false } } func resetNetworkActivity() { self.count! = 0 UIApplication.sharedApplication().networkActivityIndicatorVisible = false } // NOTE: Should try to implement these as a protocol extension!!! (new in Swift 2.x) /** * Helper function which tests host URL request to see if it is contained in given host. */ func isHost(host: String) -> (NSURLRequest -> Bool) { return { req in req.URL?.absoluteString == host } } /** * Helper function which returns stubbed response for given file */ func fixture(filename: String, status: Int32 = 200) -> (NSURLRequest -> OHHTTPStubsResponse) { let filePath = OHPathForFile(filename, self.dynamicType) return { _ in OHHTTPStubsResponse(fileAtPath: filePath!, statusCode: status, headers: ["Content-Type":"application/json"]) } } /** * Helper function which returns stubbed response for given data */ func fixture(data: NSData, returnStatus: Int32 = 200) -> (NSURLRequest -> OHHTTPStubsResponse) { return { _ in OHHTTPStubsResponse(data: data, statusCode: returnStatus, headers: ["Content-Type":"application/json"]) } } /** * Helper function which returns stubbed response for given error */ func fixture(error: NSError) -> (NSURLRequest -> OHHTTPStubsResponse) { return { _ in return OHHTTPStubsResponse(error: error) } } /** * Helper function that takes a request and response and sets up stub. */ func stub(condition: NSURLRequest -> Bool, response: NSURLRequest -> OHHTTPStubsResponse) { OHHTTPStubs.stubRequestsPassingTest({ condition($0) }, withStubResponse: response) } }
mit
f42311ee8f761bd03564a04db93c5f5b
44.601399
285
0.70296
5.61671
false
false
false
false
ps2/rileylink_ios
NightscoutUploadKit/Models/Treatments/TempBasalNightscoutTreatment.swift
1
2263
// // TempBasalNightscoutTreatment.swift // RileyLink // // Created by Pete Schwamb on 4/18/16. // Copyright © 2016 Pete Schwamb. All rights reserved. // import Foundation public class TempBasalNightscoutTreatment: NightscoutTreatment { public enum RateType: String { case Absolute = "absolute" case Percentage = "percentage" } public let rate: Double public let amount: Double? public let absolute: Double? public let temp: RateType public let duration: TimeInterval public let automatic: Bool public init(timestamp: Date, enteredBy: String, temp: RateType, rate: Double, absolute: Double?, duration: TimeInterval, amount: Double? = nil, automatic: Bool = true, id: String? = nil, syncIdentifier: String? = nil, insulinType: String?) { self.rate = rate self.absolute = absolute self.temp = temp self.duration = duration self.amount = amount self.automatic = automatic // Commenting out usage of surrogate ID until supported by Nightscout super.init(timestamp: timestamp, enteredBy: enteredBy, id: id, eventType: .tempBasal, syncIdentifier: syncIdentifier, insulinType: insulinType) } required public init?(_ entry: [String : Any]) { guard let rate = entry["rate"] as? Double, let rateTypeRaw = entry["temp"] as? String, let rateType = RateType(rawValue: rateTypeRaw), let durationMinutes = entry["duration"] as? Double else { return nil } self.rate = rate self.temp = rateType self.duration = TimeInterval(minutes: durationMinutes) self.amount = entry["amount"] as? Double self.absolute = entry["absolute"] as? Double self.automatic = entry["automatic"] as? Bool ?? true super.init(entry) } override public var dictionaryRepresentation: [String: Any] { var rval = super.dictionaryRepresentation rval["temp"] = temp.rawValue rval["rate"] = rate rval["absolute"] = absolute rval["duration"] = duration.minutes rval["amount"] = amount rval["automatic"] = automatic return rval } }
mit
67d08e81f279089adc36ff59c53fdff9
32.264706
245
0.628647
4.606925
false
false
false
false
MrSongzj/MSDouYuZB
MSDouYuZB/MSDouYuZB/Classes/Home/Controller/BaseTVCateViewController.swift
1
3726
// // BaseTVCateViewController.swift // MSDouYuZB // // Created by jiayuan on 2017/8/8. // Copyright © 2017年 mrsong. All rights reserved. // import UIKit private let kItemMargin: CGFloat = 10 let kItemW: CGFloat = (kScreenW - 3*kItemMargin)/2 let kNormalItemH: CGFloat = kItemW * 3/4 private let kHeaderH: CGFloat = 50 private let kNormalCellID = "kNormalCellID" private let kHeaderID = "kHeaderID" protocol BaseTVCateVCDataSource { var tvCateArr: [TVCate] { get } } class BaseTVCateViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate { // MARK: - 属性 var dataSource: BaseTVCateVCDataSource! lazy var collectionV: UICollectionView = { let layout = UICollectionViewFlowLayout() layout.itemSize = CGSize(width: kItemW, height: kNormalItemH) layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.sectionInset = UIEdgeInsets(top: 0, left: kItemMargin, bottom: 0, right: kItemMargin) layout.headerReferenceSize = CGSize(width: kScreenW, height: kHeaderH) let collectionV = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout) collectionV.backgroundColor = UIColor.white collectionV.dataSource = self collectionV.delegate = self collectionV.autoresizingMask = [.flexibleWidth, .flexibleHeight] collectionV.register(UINib(nibName: "CollectionNormalCell", bundle: nil), forCellWithReuseIdentifier: kNormalCellID) collectionV.register(UINib(nibName: "HomeSectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderID) return collectionV }() override func viewDidLoad() { super.viewDidLoad() setupUI() loadData() } // MARK: - Public Methods func loadData() { } // MARK: - UICollectionViewDataSource func numberOfSections(in collectionView: UICollectionView) -> Int { return dataSource.tvCateArr.count } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return dataSource.tvCateArr[section].roomArr.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionV.dequeueReusableCell(withReuseIdentifier: kNormalCellID, for: indexPath) as! CollectionNormalCell cell.tvRoom = dataSource.tvCateArr[indexPath.section].roomArr[indexPath.row] return cell } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { let view = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: kHeaderID, for: indexPath) as! HomeSectionHeaderView view.cate = dataSource.tvCateArr[indexPath.section] return view } // MARK: - UICollectionViewDelegate func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let room = dataSource.tvCateArr[indexPath.section].roomArr[indexPath.row] room.isVertical == 0 ? // push 普通房间 navigationController?.pushViewController(NormalRoomViewController(), animated: true) : // present 秀场房间 present(ShowRoomViewController(), animated: true, completion: nil) } // MARK: - UI func setupUI() { view.addSubview(collectionV) } }
mit
61846c20cd8c9fa7d7108a994dc687b4
33.607477
180
0.691061
5.3589
false
false
false
false
kevintavog/Radish
src/Radish/Application/Notifications.swift
1
671
// // Radish // import Foundation import RangicCore open class Notifications : CoreNotifications { open class FileInformationController { static let ClearedWikipediaDetails = "FileInformationController.ClearedWikipediaDetails" static let SetWikipediaDetails = "FileInformationController.SetWikipediaDetails" } open class SingleView { static let MediaData = "SingleView.MediaData" static let ShowPlacenameDetails = "SingleView.ShowPlacenameDetails" static let ShowWikipediaOnMap = "SingleView.ShowWikipediaOnMap" } open class Selection { static let MediaData = "Selection.MediaData" } }
mit
fc9debcec5b84622297e70ab3588433b
24.807692
96
0.725782
4.692308
false
false
false
false
clwm01/RTKitDemo
RCToolsDemo/RCToolsDemo/ControlsTableViewController.swift
2
3610
// // IndexTableViewController.swift // RCToolsDemo // // Created by Rex Cao on 30/10/15. // Copyright (c) 2015 rexcao. All rights reserved. // import UIKit class ControlsTableViewController: UITableViewController { let actions = ["UICollectionView", "CustomizedNavigation", "RedLayer", "UILabel", "UIImage", "TextField", "Button", "Menu"] override func viewDidLoad() { super.viewDidLoad() // 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() self.navigationItem.title = "Controls" } func popVC(row: Int) { if row == 0 { let destVC = RTView.viewController("Controls", storyboardID: "ZeroGapViewController") as! ZeroGapViewController self.navigationController?.pushViewController(destVC, animated: true) } else if row == 1 { let destVC = RTView.viewController("Controls", storyboardID: "CustomizedNavigationController") as! CustomizedNavigationController self.presentViewController(destVC, animated: true, completion: nil) } else if row == 2 { let destVC = RTView.viewController("Controls", storyboardID: "BadgeViewController") as! BadgeViewController self.presentViewController(destVC, animated: true, completion: nil) } else if row == 3 { let destVC = RTView.viewController("Controls", storyboardID: "LabelViewController") as! LabelViewController self.presentViewController(destVC, animated: true, completion: nil) } else if row == 4 { let destVC = RTView.viewController("Controls", storyboardID: "ImageViewController") as! ImageViewController self.presentViewController(destVC, animated: true, completion: nil) } else if row == 5 { let destVC = RTView.viewController("Controls", storyboardID: "TextFieldViewController") as! TextFieldViewController self.navigationController?.pushViewController(destVC, animated: true) } else if row == 6 { self.navigationController?.pushViewController(ButtonViewController(), animated: true) } else if row == 7 { self.navigationController?.pushViewController(MenuViewController(), animated: true) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Potentially incomplete method implementation. // Return the number of sections. return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete method implementation. // Return the number of rows in the section. return self.actions.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("controls", forIndexPath: indexPath) cell.textLabel?.text = self.actions[indexPath.row] return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { self.popVC(indexPath.row) } }
mit
dd4cc88e280d9a1232e95bc5d8682a3b
43.02439
141
0.68615
5.332349
false
false
false
false
baottran/nSURE
nSURE/IntakeReviewViewController.swift
1
5104
// // IntakeReviewViewController.swift // nSURE // // Created by Bao Tran on 7/14/15. // Copyright (c) 2015 Sprout Designs. All rights reserved. // import UIKit class IntakeReviewViewController: UIViewController { var chosenDate: NSDate? var customerObj: PFObject? var chosenVehicle: PFObject? var chosenLocation: PFObject? @IBOutlet weak var customerNameLabel: UILabel! @IBOutlet weak var customerVehicleLabel: UILabel! @IBOutlet weak var dateLabel: UILabel! @IBOutlet weak var timeLabel: UILabel! @IBOutlet weak var locationLabel: UITextView! @IBOutlet weak var notesField: UITextField! @IBAction func createNewRepair(sender: AnyObject) { let newRepair = PFObject(className: "Repair") newRepair["customer"] = customerObj! newRepair["assessmentDate"] = chosenDate! newRepair["intakeNotes"] = notesField.text newRepair["assessmentCompleted"] = false newRepair["estimateCompleted"] = false newRepair["assessmentCreated"] = NSDate() newRepair["damagedVehicle"] = chosenVehicle newRepair["assessmentLocation"] = chosenLocation newRepair["createdBy"] = PFUser.currentUser() if let user = PFUser.currentUser() { newRepair["company"] = user["company"] as! PFObject } newRepair.saveInBackgroundWithBlock{ success, error in if success { self.dismissViewControllerAnimated(true, completion: nil) } else { let alert = UIAlertController(title: "Error", message: "Something went wrong. New assessment not created.", preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) } } } override func viewDidLoad() { super.viewDidLoad() let currentUser = CurrentUser() currentUser.company() dateLabel.text = chosenDate?.toLongDateString() timeLabel.text = chosenDate?.toShortTimeString() if let selectedCustomer = customerObj { let firstName = selectedCustomer["firstName"] as! String let lastName = selectedCustomer["lastName"] as! String customerNameLabel.text = "\(firstName) \(lastName)" if let customerAddress = selectedCustomer["defaultAddress"] as? PFObject { buildAddress(customerAddress.objectId!) } if let customerVehicle = selectedCustomer["defaultVehicle"] as? PFObject { buildVehicle(customerVehicle.objectId!) } } NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name:UIKeyboardWillShowNotification, object: nil); NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name:UIKeyboardWillHideNotification, object: nil); } func keyboardWillShow(sender: NSNotification) { self.view.frame.origin.y -= 200 } func keyboardWillHide(sender: NSNotification) { self.view.frame.origin.y += 200 } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func queryObject(className: String, objId: String) -> PFQuery { let query = PFQuery(className: className) query.getObjectWithId(objId) return query } func buildAddress(objId: String){ let addressQuery = queryObject("Address", objId: objId) let results = addressQuery.findObjects() if let addy = results as? [PFObject] { let street = addy[0]["street"] as! String let apartment = addy[0]["apartment"] as! String let city = addy[0]["city"] as! String let zip = addy[0]["zip"] as! String let state = addy[0]["state"] as! String self.locationLabel.text = "\(street), \(apartment)\n\(city), \(state) \(zip)" self.locationLabel.font = UIFont.systemFontOfSize(25) self.chosenLocation = addy[0] } else { print("not address", terminator: "") } } func buildVehicle(objId: String){ let vehicleQuery = queryObject("Vehicle", objId: objId) let results = vehicleQuery.findObjects() if let car = results as? [PFObject] { let make = car[0]["make"] as! String let model = car[0]["model"] as! String let year = car[0]["year"] as! String self.customerVehicleLabel.text = "\(year) \(make) \(model)" self.customerVehicleLabel.font = UIFont.systemFontOfSize(25) self.chosenVehicle = car[0] } } }
mit
6fecd347c480cb9429b6c3cb5b4e8720
34.943662
169
0.606779
4.960155
false
false
false
false
gcharita/XMLMapper
XMLMapper/Classes/Requests/XMLMappableArrayResponseSerializer.swift
1
3074
// // XMLMappableArrayResponseSerializer.swift // XMLMapper // // Created by Giorgos Charitakis on 26/6/20. // import Foundation import Alamofire extension Array: EmptyResponse where Element: XMLBaseMappable & EmptyResponse { public static func emptyValue() -> Array { return [] } } public final class XMLMappableArrayResponseSerializer<T: XMLBaseMappable>: ResponseSerializer { public let dataPreprocessor: DataPreprocessor public let emptyResponseCodes: Set<Int> public let emptyRequestMethods: Set<HTTPMethod> public let serializeCallback: (_ request: URLRequest?, _ response: HTTPURLResponse?, _ data: Data?, _ error: Error?) throws -> [T] /// Creates an instance using the values provided. /// /// - Parameters: /// - dataPreprocessor: `DataPreprocessor` used to prepare the received `Data` for serialization. /// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. Defaults to `[204, 205]`. /// - emptyRequestMethods: The HTTP request methods for which empty responses are allowed. Defaults to `[.head]`. /// - serializeCallback: Block that performs the serialization of the response Data into the provided type. /// - request: URLRequest which was used to perform the request, if any. /// - response: HTTPURLResponse received from the server, if any. /// - data: Data returned from the server, if any. /// - error: Error produced by Alamofire or the underlying URLSession during the request. public init( dataPreprocessor: DataPreprocessor = XMLMappableArrayResponseSerializer.defaultDataPreprocessor, emptyResponseCodes: Set<Int> = XMLMappableArrayResponseSerializer.defaultEmptyResponseCodes, emptyRequestMethods: Set<HTTPMethod> = XMLMappableArrayResponseSerializer.defaultEmptyRequestMethods, serializeCallback: @escaping (_ request: URLRequest?, _ response: HTTPURLResponse?, _ data: Data?, _ error: Error?) throws -> [T] ) { self.dataPreprocessor = dataPreprocessor self.emptyResponseCodes = emptyResponseCodes self.emptyRequestMethods = emptyRequestMethods self.serializeCallback = serializeCallback } public func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> [T] { if let error = error { throw error } guard let data = data, !data.isEmpty else { guard emptyResponseAllowed(forRequest: request, response: response) else { throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength) } guard let emptyResponseType = [T].self as? EmptyResponse.Type, let emptyValue = emptyResponseType.emptyValue() as? [T] else { throw AFError.responseSerializationFailed(reason: .invalidEmptyResponse(type: "\([T].self)")) } return emptyValue } return try serializeCallback(request, response, data, error) } }
mit
b2a98ad73e45a9f2c52f2c40605e4246
48.580645
137
0.690306
4.958065
false
false
false
false
einsteinx2/iSub
Classes/Server Loading/ISMSStreamManager/DownloadQueue.swift
1
8598
// // DownloadQueue.swift // iSub // // Created by Benjamin Baron on 1/9/17. // Copyright © 2017 Ben Baron. All rights reserved. // import Foundation fileprivate let maxReconnects = 5 final class DownloadQueue: StreamHandlerDelegate { struct Notifications { static let started = Notification.Name("DownloadQueue_started") static let stopped = Notification.Name("DownloadQueue_stopped") static let songFailed = Notification.Name("DownloadQueue_songFailed") } public static let si = DownloadQueue() fileprivate(set) var isDownloading = false fileprivate(set) var currentSong: Song? fileprivate(set) var streamHandler: StreamHandler? func add(song: Song) { Playlist.downloadQueue.add(song: song) start() } func remove(song: Song) { Playlist.downloadQueue.remove(song: song) if song == currentSong { stop() start() } } func contains(song: Song) -> Bool { return Playlist.downloadQueue.contains(song: song) } func start() { guard !isDownloading else { return } currentSong = Playlist.downloadQueue.song(atIndex: 0) log.debug("currentSong: \(String(describing: self.currentSong))") guard let currentSong = currentSong, (AppDelegate.si.networkStatus.isReachableWifi || SavedSettings.si.isManualCachingOnWWANEnabled), !SavedSettings.si.isOfflineMode else { return } // TODO: Better logic // For simplicity sake, just make sure we never go under 25 MB and let the cache check process take care of the rest guard CacheManager.si.freeSpace > 25 * 1024 * 1024 else { /*[EX2Dispatch runInMainThread:^ { [cacheS showNoFreeSpaceMessage:NSLocalizedString(@"Your device has run out of space and cannot download any more music. Please free some space and try again", @"Download manager, device out of space message")]; }];*/ return } // Make sure it's a song guard currentSong.basicType == .audio else { removeFromDownloadQueue(song: currentSong) start() return } // Make sure it's not already cached guard !currentSong.isFullyCached else { removeFromDownloadQueue(song: currentSong) start() return } isDownloading = true // TODO: Download the art // Create the stream handler if StreamQueue.si.song == currentSong, let handler = StreamQueue.si.streamHandler { log.debug("stealing handler from StreamQueue") // It's in the stream queue so steal the handler StreamQueue.si.streamHandler = nil StreamQueue.si.stop() StreamQueue.si.start() handler.delegate = self if !handler.isDownloading { handler.start() } } else { log.debug("creating handler") streamHandler = StreamHandler(song: currentSong, isTemp: false, delegate: self) streamHandler?.start() } NotificationCenter.postOnMainThread(name: Notifications.started) } func stop() { isDownloading = false streamHandler?.cancel() streamHandler = nil currentSong = nil NotificationCenter.postOnMainThread(name: Notifications.stopped) } func resume() { if !SavedSettings.si.isOfflineMode { streamHandler?.start() } } func removeCurrentSong() { if isDownloading { stop() } if let currentSong = currentSong { removeFromDownloadQueue(song: currentSong) } } // MARK: - Helper Functions - fileprivate func removeFile(forHandler handler: StreamHandler) { // TODO: Error handling try? FileManager.default.removeItem(atPath: handler.filePath) } fileprivate func removeFromDownloadQueue(song: Song) { Playlist.downloadQueue.remove(song: song, notify: true) } // MARK: - Stream Handler Delegate - func streamHandlerStarted(_ handler: StreamHandler) { } func streamHandlerConnectionFinished(_ handler: StreamHandler) { isDownloading = false var isSuccess = true if handler.totalBytesTransferred == 0 { let alert = UIAlertController(title: "Uh oh!", message: "We asked to cache a song, but the server didn't send anything!\n\nIt's likely that Subsonic's transcoding failed.\n\nIf you need help, please tap the Support button on the Home tab.", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) AppDelegate.si.sidePanelController.present(alert, animated: true, completion: nil) // TODO: Error handling removeFile(forHandler: handler) isSuccess = false } else if handler.totalBytesTransferred < 2000 { var isLicenceIssue = false if let receivedData = try? Data(contentsOf: URL(fileURLWithPath: handler.filePath)) { if let root = RXMLElement(fromXMLData: receivedData), root.isValid { if let error = root.child("error"), error.isValid { if let code = error.attribute("code"), code == "60" { isLicenceIssue = true } } } } else { isSuccess = false } if isLicenceIssue { // This is a trial period message, alert the user and stop streaming // TODO: Update this error message to better explain and to point to free alternatives let alert = UIAlertController(title: "Subsonic API Trial Expired", message: "You can purchase a license for Subsonic by logging in to the web interface and clicking the red Donate link on the top right.\n\nPlease remember, iSub is a 3rd party client for Subsonic, and this license and trial is for Subsonic and not iSub.\n\nIf you didn't know about the Subsonic license requirement, and do not wish to purchase it, please tap the Support button on the Home tab and contact iSub support for a refund.", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil)) AppDelegate.si.sidePanelController.present(alert, animated: true, completion: nil) removeFile(forHandler: handler) isSuccess = false } } if isSuccess { if let currentSong = currentSong { currentSong.isFullyCached = true removeFromDownloadQueue(song: currentSong) } currentSong = nil streamHandler = nil start() } } func streamHandlerConnectionFailed(_ handler: StreamHandler, withError error: Error?) { isDownloading = false if handler.allowReconnects && handler.numberOfReconnects < maxReconnects { // Less than max number of reconnections, so try again handler.numberOfReconnects += 1; // Retry connection after a delay to prevent a tight loop DispatchQueue.main.async(after: 2.0) { self.resume() } } else { // TODO: Use a different mechanism //[[EX2SlidingNotification slidingNotificationOnTopViewWithMessage:NSLocalizedString(@"Song failed to download", @"Download manager, download failed message") image:nil] showAndHideSlidingNotification]; // Tried max number of times so remove streamHandler = nil; if let currentSong = currentSong { removeFromDownloadQueue(song: currentSong) } NotificationCenter.postOnMainThread(name: Notifications.songFailed) start() } } }
gpl-3.0
bd7a2bd4db4a42c0d8298e139b71e92e
36.378261
480
0.574968
5.336437
false
false
false
false
allright/ASFloatingHeadersFlowLayout
FloatingHeadersDemo/ASFloatingHeadersFlowLayout/ASFloatingHeadersFlowLayout.swift
1
5948
// // ASFloatingHeadersFlowLayout.swift // FloatingHeadersDemo // // Created by Andrey Syvrachev on 22.04.15. // Copyright (c) 2015 Andrey Syvrachev. All rights reserved. // import UIKit class ASFloatingHeadersFlowLayout: UICollectionViewFlowLayout { var sectionAttributes:[(header:UICollectionViewLayoutAttributes!,sectionEnd:CGFloat!)] = [] let offsets = NSMutableOrderedSet() var floatingSectionIndex:Int! = nil var width:CGFloat! = nil override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool { return true } override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? { let attrs = super.layoutAttributesForElementsInRect(rect) let ret = attrs?.map() { (attribute) -> UICollectionViewLayoutAttributes in let attr = attribute if let elementKind = attr.representedElementKind { if (elementKind == UICollectionElementKindSectionHeader){ return self.sectionAttributes[attr.indexPath.section].header } } return attr } return ret } override func layoutAttributesForSupplementaryViewOfKind(elementKind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes? { let collectionView = self.collectionView! let offset:CGFloat = collectionView.contentOffset.y + collectionView.contentInset.top let index = indexForOffset(offset) let section = self.sectionAttributes[index] let maxOffsetForHeader = section.sectionEnd - section.header.frame.size.height let headerResultOffset = offset > 0 ? min(offset,maxOffsetForHeader) : 0 let headerAttrs = section.header headerAttrs.frame = CGRectMake(0, headerResultOffset, headerAttrs.frame.size.width, headerAttrs.frame.size.height) headerAttrs.zIndex = 1024 let attrs = self.sectionAttributes[indexPath.section] return elementKind == UICollectionElementKindSectionHeader ? attrs.header : self.layoutAttributesForSupplementaryViewOfKind(elementKind, atIndexPath: indexPath) } private func testWidthChanged(newWidth:CGFloat!) -> Bool { if let width = self.width{ if (width != newWidth){ self.width = newWidth return true } } self.width = newWidth return false } override func invalidationContextForBoundsChange(newBounds: CGRect) -> UICollectionViewLayoutInvalidationContext { let context = super.invalidationContextForBoundsChange(newBounds) if (self.testWidthChanged(newBounds.size.width)){ return context } let collectionView = self.collectionView! let offset:CGFloat = newBounds.origin.y + collectionView.contentInset.top let index = indexForOffset(offset) var invalidatedIndexPaths = [NSIndexPath(forItem: 0, inSection:index)]; if let floatingSectionIndex = self.floatingSectionIndex { if (self.floatingSectionIndex != index){ // have to restore previous section attributes to default self.sectionAttributes[floatingSectionIndex].header = super.layoutAttributesForSupplementaryViewOfKind(UICollectionElementKindSectionHeader,atIndexPath: NSIndexPath(forItem: 0, inSection: floatingSectionIndex)) invalidatedIndexPaths.append(NSIndexPath(forItem: 0, inSection:floatingSectionIndex)) } } self.floatingSectionIndex = index context.invalidateSupplementaryElementsOfKind(UICollectionElementKindSectionHeader,atIndexPaths:invalidatedIndexPaths) return context } override func prepareLayout() { super.prepareLayout() self.sectionAttributes.removeAll(keepCapacity: true) self.offsets.removeAllObjects() let collectionView = self.collectionView! let numberOfSections = collectionView.numberOfSections() for var section = 0; section < numberOfSections; ++section { let indexPath = NSIndexPath(forItem: 0, inSection: section) let header = super.layoutAttributesForSupplementaryViewOfKind(UICollectionElementKindSectionHeader,atIndexPath:indexPath) var sectionEnd = header!.frame.origin.y + header!.frame.size.height let numberOfItemsInSection = collectionView.numberOfItemsInSection(section) if (numberOfItemsInSection > 0){ let lastItemAttrs = super.layoutAttributesForItemAtIndexPath(NSIndexPath(forItem: numberOfItemsInSection - 1, inSection: section)) sectionEnd = lastItemAttrs!.frame.origin.y + lastItemAttrs!.frame.size.height + self.sectionInset.bottom } let sectionInfo:(header:UICollectionViewLayoutAttributes!,sectionEnd:CGFloat!) = (header:header,sectionEnd:sectionEnd) self.sectionAttributes.append(sectionInfo) if (section > 0){ self.offsets.addObject(header!.frame.origin.y) } } } private func indexForOffset(offset: CGFloat) -> Int { let range = NSRange(location:0, length:self.offsets.count) return self.offsets.indexOfObject(offset, inSortedRange: range, options: .InsertionIndex, usingComparator: { (section0:AnyObject!, section1:AnyObject!) -> NSComparisonResult in let s0:CGFloat = section0 as! CGFloat let s1:CGFloat = section1 as! CGFloat return s0 < s1 ? .OrderedAscending : .OrderedDescending }) } }
mit
55c9c41ed268c76a69dcd14f079d71e6
40.02069
226
0.655178
5.774757
false
false
false
false
lee0741/Glider
Glider/AppDelegate.swift
1
3939
// // AppDelegate.swift // Glider // // Created by Yancen Li on 2/24/17. // Copyright © 2017 Yancen Li. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { window = UIWindow(frame: UIScreen.main.bounds) window?.makeKeyAndVisible() window?.rootViewController = MainController() UINavigationBar.appearance().barTintColor = .mainColor UINavigationBar.appearance().tintColor = .white UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white] UITabBar.appearance().tintColor = .mainColor let categoryItem = UIApplicationShortcutItem(type: "org.yancen.Glider.category", localizedTitle: "Categories", localizedSubtitle: nil, icon: UIApplicationShortcutIcon(templateImageName: "ic_option"), userInfo: nil) let searchItem = UIApplicationShortcutItem(type: "org.yancen.Glider.search", localizedTitle: "Search", localizedSubtitle: nil, icon: UIApplicationShortcutIcon(type: .search), userInfo: nil) UIApplication.shared.shortcutItems = [categoryItem, searchItem] if let item = launchOptions?[UIApplicationLaunchOptionsKey.shortcutItem] as? UIApplicationShortcutItem { switch item.type { case "org.yancen.Glider.category": launchListController() case "org.yancen.Glider.search": launchSearchController() default: break } } return true } func applicationWillResignActive(_ application: UIApplication) {} func applicationDidEnterBackground(_ application: UIApplication) {} func applicationWillEnterForeground(_ application: UIApplication) {} func applicationDidBecomeActive(_ application: UIApplication) {} func applicationWillTerminate(_ application: UIApplication) {} // MARK: - Spotlight Search func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([Any]?) -> Void) -> Bool { (window?.rootViewController as! MainController).selectedIndex = 0 let viewController = (window?.rootViewController as! MainController).childViewControllers[0].childViewControllers[0] as! HomeController viewController.restoreUserActivityState(userActivity) return true } // MARK: - URL Scheme func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool { guard let query = url.host else { return true } let commentController = CommentController() commentController.itemId = Int(query) (window?.rootViewController as! MainController).selectedIndex = 0 (window?.rootViewController as! MainController).childViewControllers[0].childViewControllers[0].navigationController?.pushViewController(commentController, animated: true) return true } // MARK: - 3D Touch func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) { switch shortcutItem.type { case "org.yancen.Glider.category": launchListController() case "org.yancen.Glider.search": launchSearchController() default: return } } func launchListController() { (window?.rootViewController as! MainController).selectedIndex = 1 } func launchSearchController() { (window?.rootViewController as! MainController).selectedIndex = 2 } }
mit
9538829c4d986cae9f34bb3cc8e2a5c7
38.777778
222
0.678517
5.799705
false
false
false
false
richardpiazza/MiseEnPlace
Sources/MiseEnPlace/Ingredient.swift
1
2169
import Foundation /// Represents any raw material/ingredient used in cooking. /// /// A `Ingredient` is one of the primary protocols for interacting with an /// object graph utilizing the `MiseEnPlace` framework. /// /// ## Required Conformance /// /// *none* /// /// ## Protocol Conformance /// /// _Unique_ /// ```swift /// var uuid: UUID { get set } /// var creationDate: Date { get set } /// var modificationDate: Date { get set } /// ``` /// /// _Descriptive_ /// ```swift /// var name: String? { get set } /// var commentary: String? { get set } /// var classification: String? { get set } /// ``` /// /// _Multimedia_ /// ```swift /// var imagePath: String? { get set } /// ``` /// /// _Proportioned_ /// ```swift /// var volume: Double { get set } /// var weight: Double { get set } /// ``` /// /// _Quantifiable_ /// ```swift /// var amount: Double { get set } /// var unit: MeasurementUnit { get set } /// ``` /// /// - note: The `Quantifiable` conformance on an `Ingredient` will represent an _each_ measurement. /// i.e. *What is the equivalent measurement for one (1) of this item?* /// /// ## Example /// /// ```swift /// struct FoodStuff: Ingredient { /// var uuid: UUID = UUID() /// var creationDate: Date = Date() /// var modificationDate: Date = Date() /// var name: String? = "Whole Milk" /// var commentary: String? = "The mammary lactations from a bovine." /// var classification: String? = "Dairy, Milk, Cow, Whole/Full Fat" /// var imagePath: String? /// var volume: Double = 1.0 /// var weight: Double = 1.0 /// var amount: Double = 1.0 /// var unit: MeasurementUnit = .gallon /// } /// ``` public protocol Ingredient: Unique, Descriptive, Multimedia, Proportioned, Quantifiable { } public extension Ingredient { /// `Quantification` that represents to which one (1) of this item is approximately equivalent. /// /// For example: 1 egg ≅ 50 grams var eachQuantification: Quantification { get { return Quantification(amount: amount, unit: unit) } set { amount = newValue.amount unit = newValue.unit } } }
mit
4a8ab8fdf2323cd34c0d9172cbd1ac51
25.426829
99
0.596677
3.691652
false
false
false
false
lixiangzhou/ZZLib
Source/ZZExtension/ZZUIExtension/UIAlertController+ZZExtension.swift
1
1396
// // UIAlertController+ZZExtension.swift // ZZLib // // Created by lixiangzhou on 2017/3/10. // Copyright © 2017年 lixiangzhou. All rights reserved. // import UIKit public extension UIAlertController { /// 快捷弹窗,Alert 样式或者 ActionSheet样式 /// /// - parameter fromController: 弹窗所在的控制器 /// - parameter style: 弹窗样式,UIAlertControllerStyle.alert 或者 UIAlertControllerStyle.actionSheet /// - parameter title: title /// - parameter message: message /// - parameter actions: actions /// - parameter completion: 弹窗消失执行的操作 /// /// - returns: 弹窗对象 UIAlertController @discardableResult static func zz_show(fromController: UIViewController, style: UIAlertControllerStyle = .alert, title: String? = nil, message: String? = nil, actions: [UIAlertAction], completion: (() -> Void)? = nil) -> UIAlertController { let alertVc = UIAlertController(title: title, message: message, preferredStyle: style) for action in actions { alertVc.addAction(action) } fromController.present(alertVc, animated: true, completion: completion) return alertVc } }
mit
94a1fd139446c3950436e29ee26f14f2
32.717949
107
0.587072
4.962264
false
false
false
false
BurntCaramel/BurntCocoaUI
BurntCocoaUI/Renderers.swift
1
1642
// // Renderers.swift // BurntCocoaUI // // Created by Patrick Smith on 27/04/2016. // Copyright © 2016 Burnt Caramel. All rights reserved. // import Cocoa public func textFieldRenderer <TextField : NSTextField> (onChange: @escaping (String) -> ()) -> (String?) -> TextField { let textField = TextField() textField.cell?.sendsActionOnEndEditing = true let target = textField.setActionHandler { _ in onChange(textField.stringValue) } return { stringValue in withExtendedLifetime(target) { textField.stringValue = stringValue ?? "" } return textField } } public func checkboxRenderer <Button : NSButton> (onChange: @escaping (NSCell.StateValue) -> (), title: String) -> (NSCell.StateValue) -> Button { let button = Button() button.title = title button.setButtonType(.switch) let target = button.setActionHandler { _ in onChange(button.state) } return { state in withExtendedLifetime(target) { button.state = state } return button } } public func popUpButtonRenderer< PopUpButton : NSPopUpButton, Value : UIChoiceRepresentative> (onChange: @escaping (Value?) -> ()) -> (Value?) -> PopUpButton where Value : UIChoiceEnumerable { let popUpButton = PopUpButton() let assistant = PopUpButtonAssistant<Value>(popUpButton: popUpButton) assistant.menuItemRepresentatives = Value.allChoices.map{ $0 } assistant.update() let target = assistant.popUpButton.setActionHandler { _ in onChange(assistant.selectedItemRepresentative) } return { value in withExtendedLifetime(target) { assistant.selectedUniqueIdentifier = value?.uniqueIdentifier } return popUpButton } }
mit
510e9da4ced4437549906675e05978c7
20.311688
70
0.722121
3.638581
false
false
false
false
oneWarcraft/PictureBrowser-Swift
PictureBrowser/PictureBrowser/Classes/PictureBrowser/PictureBrowserController.swift
1
4973
// // PictureBrowserController.swift // PictureBrowser // // Created by 王继伟 on 16/7/14. // Copyright © 2016年 WangJiwei. All rights reserved. // // import UIKit class PictureBrowserController: UIViewController { // MARK: - 定义的属性 var indexPath : NSIndexPath? var shops : [Shop]? let pictureBrowseCellID = "pictureBrowseCellID" lazy var collectionView : UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: pictureBrowserLayout()) lazy var closeBtn : UIButton = UIButton() lazy var saveBtn : UIButton = UIButton() // MARK:- 系统回调函数 override func viewDidLoad() { super.viewDidLoad() view.frame.size.width += 15 // 1.设置UI界面 setupUI() // 2.滚动到对应的位置 collectionView.scrollToItemAtIndexPath(indexPath!, atScrollPosition: .Left, animated: false) } } extension PictureBrowserController { func setupUI() { // 1. 添加子控件 view.addSubview(collectionView) view.addSubview(closeBtn) view.addSubview(saveBtn) // 2. 设置子控件的位置 collectionView.frame = view.bounds let margin : CGFloat = 20 let btnW : CGFloat = 90 let btnH : CGFloat = 32 let y : CGFloat = UIScreen.mainScreen().bounds.height - margin - btnH closeBtn.frame = CGRect(x: margin, y: y, width: btnW, height: btnH) let x : CGFloat = UIScreen.mainScreen().bounds.width - margin - btnW saveBtn.frame = CGRect(x: x, y: y, width: btnW, height: btnH) // 3. 设置btn的相关属性 prepareBTN() // 4. 设置CollectionView的相关属性 prepareCollectionView() } func prepareBTN() { setupBtn(closeBtn, title: "关 闭", action: "closeBtnClick") setupBtn(saveBtn, title: "保 存", action: "saveBtnClick") } func setupBtn(btn : UIButton, title : String, action : String) { btn.setTitle(title, forState: .Normal) btn.backgroundColor = UIColor.darkGrayColor() btn.titleLabel?.font = UIFont.systemFontOfSize(14.0) btn.addTarget(self, action: Selector(action), forControlEvents: .TouchUpInside) } func prepareCollectionView() { collectionView.dataSource = self collectionView.delegate = self collectionView.registerClass(PictureBrowserViewCell.self, forCellWithReuseIdentifier: pictureBrowseCellID) } } extension PictureBrowserController { @objc private func closeBtnClick() { dismissViewControllerAnimated(true, completion: nil) } @objc private func saveBtnClick() { // 1. 取出当前正在显示的图片 let cell = collectionView.visibleCells().first as! PictureBrowserViewCell guard let image = cell.imageView.image else { return } // 2. 保存图片 UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil) } } // MARK:- collectionView的数据源和代理方法 extension PictureBrowserController :UICollectionViewDataSource, UICollectionViewDelegate { func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return shops?.count ?? 0 } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { // 1.创建cell let cell = collectionView.dequeueReusableCellWithReuseIdentifier(pictureBrowseCellID, forIndexPath: indexPath) as! PictureBrowserViewCell // 2.设置cell的内容 // cell.backgroundColor = indexPath.item % 2 == 0 ? UIColor.redColor() : UIColor.blueColor() cell.shop = shops![indexPath.item] return cell } func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { closeBtnClick() } } // MARK:- 实现dismissProtocol的代理方法 extension PictureBrowserController : DismissProtocol { func getImageView() -> UIImageView { // 1. 创建UIImageView对象 let imageView = UIImageView() // 2. 设置imageView的image let cell = collectionView.visibleCells().first as! PictureBrowserViewCell imageView.image = cell.imageView.image // 3. 设置imageView的frame imageView.frame = cell.imageView.frame // 4. 设置imageView的属性 imageView.contentMode = .ScaleAspectFill imageView.clipsToBounds = true return imageView } func getIndexPath() -> NSIndexPath { // 获取正在显示的Cell let cell = collectionView.visibleCells().first as! PictureBrowserViewCell return collectionView.indexPathForCell(cell)! } }
apache-2.0
9421889a57176ee995e92648f05ea66f
27.190476
145
0.641047
5.032944
false
false
false
false
Velhotes/Vinyl
Vinyl/EncodingDecoding/EncodingDecoding.swift
1
1603
// // EncodingDecoding.swift // Vinyl // // Created by Rui Peres on 12/02/2016. // Copyright © 2016 Velhotes. All rights reserved. // import Foundation // Heavily inspired by Venmo's work on DVR (https://github.com/venmo/DVR). func encode(body: Data?, headers: HTTPHeaders) -> Any? { guard let body = body, let contentType = headers["Content-Type"] else { return nil } switch contentType { case _ where contentType.hasPrefix("text/"): return String(data: body, encoding: .utf8) as Any? case _ where contentType.hasPrefix("application/json"): return try! JSONSerialization.jsonObject(with: body) as Any? default: return body.base64EncodedString(options: []) as Any? } } func decode(body: Any?, headers: HTTPHeaders) -> Data? { guard let body = body else { return nil } guard let contentType = headers["Content-Type"] else { // As last resource, we will check if the bodyData is a string and if so convert it if let string = body as? String { return string.data(using: .utf8) } else { return nil } } if let string = body as? String, contentType.hasPrefix("text/") { return string.data(using: .utf8) } if contentType.hasPrefix("application/json") { return try? JSONSerialization.data(withJSONObject: body) } if let string = body as? String { return Data(base64Encoded: string, options: []) } return nil }
mit
b8d28476b08cbce4486455a0ed857aa7
24.83871
91
0.591136
4.204724
false
false
false
false
vbergae/SwiftReflector
SwiftReflector/Reflector.swift
1
2435
// // Reflector.swift // SwiftReflector // // Created by Víctor on 23/8/14. // Copyright (c) 2014 Víctor Berga. All rights reserved. // import Foundation public class Reflector<T:NSObject> { lazy public var name: String = self.loadName() lazy public var properties: Array<String> = self.loadProperties() lazy public var methods: Array<String> = self.loadMethods() private let rawPropertiesCount:UInt32 private let rawProperties: UnsafeMutablePointer<objc_property_t> private let rawMethodscount:UInt32 private let rawMethods: UnsafeMutablePointer<Method> private let `class`:NSObject.Type public init() { var count: UInt32 = 0 self.`class` = T.self self.rawProperties = class_copyPropertyList(self.`class`, &count) self.rawPropertiesCount = count self.rawMethods = class_copyMethodList(self.`class`, &count) self.rawMethodscount = count } deinit { free(self.rawProperties) free(self.rawMethods) } public func createInstance() -> T { return T() } public class func createInstance(className:String) -> AnyObject? { return SRClassBuilder.createInstanceFromString(className) } public func execute(code: (`self`:T) -> (), instance:T) { code(`self`: instance) } public func execute<U>(code: (`self`:T) -> U, instance:T) -> U { return code(`self`: instance) } private func loadName() -> String { return NSString(UTF8String: class_getName(self.`class`)) } private func loadProperties() -> Array<String> { var propertyNames : [String] = [] let intCount = Int(self.rawPropertiesCount) for var i = 0; i < intCount; i++ { let property : objc_property_t = self.rawProperties[i] let propertyName = NSString(UTF8String: property_getName(property)) propertyNames.append(propertyName) } return propertyNames } private func loadMethods() -> Array<String> { var methodNames : [String] = [] let intCount = Int(self.rawMethodscount) for var i = 0; i < intCount; i++ { let method: Method = self.rawMethods[i] let selector: Selector = method_getName(method) let methodName = NSString(UTF8String: sel_getName(selector)) methodNames.append(methodName) } return methodNames } }
mit
ba9b799463db437189e40d0ec124ba95
26.965517
88
0.633785
3.936893
false
false
false
false
Fenrikur/ef-app_ios
Domain Model/EurofurenceModelTests/Deletions/WhenDeletingKnowledgeGroup_AfterSuccessfulSync_ApplicationShould.swift
1
817
import EurofurenceModel import EurofurenceModelTestDoubles import XCTest class WhenDeletingKnowledgeGroup_AfterSuccessfulSync_ApplicationShould: XCTestCase { func testTellTheStoreToDeleteTheGroup() { let dataStore = InMemoryDataStore() var response = ModelCharacteristics.randomWithoutDeletions let context = EurofurenceSessionTestBuilder().with(dataStore).build() context.refreshLocalStore() context.api.simulateSuccessfulSync(response) let groupToDelete = response.knowledgeGroups.changed.remove(at: 0) response.knowledgeGroups.deleted = [groupToDelete.identifier] context.refreshLocalStore() context.api.simulateSuccessfulSync(response) XCTAssertEqual(false, dataStore.fetchKnowledgeGroups()?.contains(groupToDelete)) } }
mit
84b17f646e68ac4f07492041f0a041c5
37.904762
88
0.76377
5.92029
false
true
false
false
mohssenfathi/MTLImage
MTLImage/Sources/Filters/Buffer.swift
1
802
// // Buffer.swift // Pods // // Created by Mohssen Fathi on 6/15/17. // public class Buffer: Filter { var textureQueue = [MTLTexture]() public init() { super.init(functionName: "EmptyShader") title = "Buffer" properties = [] } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public override func process() { guard let texture = input?.texture?.copy(device: device) else { return } textureQueue.insert(texture, at: 0) if textureQueue.count > bufferLength { self.texture = textureQueue.popLast() } } // MARK: - Properties public var bufferLength: Int = 10 { didSet { needsUpdate = true } } }
mit
38b82020a7daa9e41a12cd348ec50e85
20.105263
80
0.551122
4.358696
false
false
false
false
LipliStyle/Liplis-iOS
Liplis/CtvCellMenuTitle.swift
1
1106
// // CtvCellMenuTitle.swift // Liplis // //設定メニュー画面 要素 タイトル // //アップデート履歴 // 2015/05/04 ver0.1.0 作成 // 2015/05/09 ver1.0.0 リリース // 2015/05/16 ver1.4.0 リファクタリング // // Created by sachin on 2015/05/04. // Copyright (c) 2015年 sachin. All rights reserved. // import UIKit class CtvCellMenuTitle: UITableViewCell { ///============================= ///カスタムセル要素 internal var lblTitle = UILabel(); internal override init(style: UITableViewCellStyle, reuseIdentifier: String!) { super.init(style: style, reuseIdentifier: reuseIdentifier) //ラベル設定 self.lblTitle = UILabel(frame: CGRectMake(10, 5, 300, 15)); self.lblTitle.text = ""; self.lblTitle.font = UIFont.systemFontOfSize(20) self.addSubview(self.lblTitle); //背景色設定 self.backgroundColor = UIColor.hexStr("FEE360", alpha: 255) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } }
mit
da2b7fffb3e9cb3a8b00512f32512514
23.243902
81
0.60161
3.588448
false
false
false
false
NghiaTranUIT/Unofficial-Uber-macOS
UberGo/UberGo/SearchBarView.swift
1
8139
// // SearchBarView.swift // UberGo // // Created by Nghia Tran on 6/5/17. // Copyright © 2017 Nghia Tran. All rights reserved. // import Cocoa import RxCocoa import RxSwift import UberGoCore protocol SearchBarViewDelegate: class { func searchBar(_ sender: SearchBarView, layoutStateDidChanged state: MapViewLayoutState) } class SearchBarView: NSView { // MARK: - OUTLET @IBOutlet fileprivate weak var originTxt: UberTextField! @IBOutlet fileprivate weak var destinationTxt: UberTextField! @IBOutlet fileprivate weak var roundBarView: NSView! @IBOutlet fileprivate weak var squareBarView: NSView! @IBOutlet fileprivate weak var lineVerticalView: NSView! @IBOutlet fileprivate weak var backBtn: NSButton! @IBOutlet fileprivate weak var backBtnTop: NSLayoutConstraint! @IBOutlet fileprivate weak var searchContainerView: NSView! @IBOutlet fileprivate weak var loaderView: NSProgressIndicator! // Container @IBOutlet fileprivate weak var originContainerView: NSView! @IBOutlet fileprivate weak var destinationContainerView: NSView! // MARK: - Variable weak var delegate: SearchBarViewDelegate? var layoutState = MapViewLayoutState.minimal { didSet { animateSearchBarState() } } public var textSearchDidChangedDriver: Driver<String> { return destinationTxt.rx.text .asObservable() .filterNil() .asDriver(onErrorJustReturn: "") } public var textSearch: String { return destinationTxt.stringValue } fileprivate var viewModel: SearchViewModelProtocol! fileprivate var actionSearchView: ActionSearchBarView! fileprivate let disposeBag = DisposeBag() // Constraint fileprivate var topConstraint: NSLayoutConstraint! fileprivate var leftConstraint: NSLayoutConstraint! fileprivate var rightConstraint: NSLayoutConstraint! fileprivate var heightConstraint: NSLayoutConstraint! // MARK: - Init override func awakeFromNib() { super.awakeFromNib() initCommon() initActionSearchView() } fileprivate func binding() { // Nearest place viewModel.output.currentPlaceDriver .drive(onNext: { [weak self] nearestPlaceObj in guard let `self` = self else { return } self.updateOriginPlace(nearestPlaceObj) }) .addDisposableTo(disposeBag) // Input search textSearchDidChangedDriver .drive(onNext: {[weak self] text in guard let `self` = self else { return } self.viewModel.input.textSearchPublish.onNext(text) }) .addDisposableTo(disposeBag) // Loader viewModel.output.loadingDriver .drive(onNext: {[weak self] (isLoading) in guard let `self` = self else { return } self.loaderIndicatorView(isLoading) }).addDisposableTo(disposeBag) } public func setupViewModel(_ viewModel: SearchViewModelProtocol) { self.viewModel = viewModel binding() } fileprivate func updateOriginPlace(_ place: PlaceObj) { originTxt.stringValue = place.name } func makeDestinationFirstResponse() { destinationTxt.window?.makeFirstResponder(destinationTxt) } func resetTextSearch() { destinationTxt.stringValue = "" loaderIndicatorView(false) } func loaderIndicatorView(_ isLoading: Bool) { if isLoading { loaderView.isHidden = false loaderView.startAnimation(nil) } else { loaderView.isHidden = true loaderView.stopAnimation(nil) } } // MARK: - Action @IBAction func backBtnOnTap(_ sender: Any) { viewModel.input.enableFullSearchModePublisher.onNext(false) delegate?.searchBar(self, layoutStateDidChanged: .minimal) } } extension SearchBarView { fileprivate func initCommon() { // Background backgroundColor = NSColor.white squareBarView.backgroundColor = NSColor.black lineVerticalView.backgroundColor = NSColor(hexString: "#A4A4AC") roundBarView.backgroundColor = NSColor(hexString: "#A4A4AC") roundBarView.wantsLayer = true roundBarView.layer?.masksToBounds = true roundBarView.layer?.cornerRadius = 3 // Default searchContainerView.alphaValue = 0 } fileprivate func initActionSearchView() { let actionView = ActionSearchBarView.viewFromNib(with: BundleType.app)! actionView.configureView(with: self) actionView.delegate = self actionSearchView = actionView } } // MARK: - Layout extension SearchBarView { func configureView(with parentView: NSView) { translatesAutoresizingMaskIntoConstraints = false topConstraint = top(to: parentView, offset: 28) leftConstraint = left(to: parentView, offset: 28) rightConstraint = right(to: parentView, offset: -28) heightConstraint = height(56) } fileprivate func animateSearchBarState() { switch layoutState { case .expand: expandAnimation() case .minimal: minimalAnimation() case .searchFullScreen: searchFullScreenAnimation() case .tripMinimunActivity, .tripFullActivity, .productSelection: hideAllAnimation() } } fileprivate func expandAnimation() { // Focus makeDestinationFirstResponse() isHidden = false leftConstraint.constant = 0 topConstraint.constant = 0 rightConstraint.constant = 0 heightConstraint.constant = 142 backBtnTop.constant = 15 // Animate NSAnimationContext.defaultAnimate({ _ in self.alphaValue = 1 self.originContainerView.alphaValue = 1 self.roundBarView.alphaValue = 1 self.squareBarView.alphaValue = 1 self.lineVerticalView.alphaValue = 1 self.actionSearchView.alphaValue = 0 self.searchContainerView.alphaValue = 1 self.superview?.layoutSubtreeIfNeeded() }) } fileprivate func minimalAnimation() { isHidden = false leftConstraint.constant = 28 topConstraint.constant = 28 rightConstraint.constant = -28 heightConstraint.constant = 56 backBtnTop.constant = 15 NSAnimationContext.defaultAnimate({ _ in self.alphaValue = 1 self.actionSearchView.alphaValue = 1 self.searchContainerView.alphaValue = 0 self.superview?.layoutSubtreeIfNeeded() }) } fileprivate func searchFullScreenAnimation() { // Focus makeDestinationFirstResponse() isHidden = false leftConstraint.constant = 0 topConstraint.constant = 0 rightConstraint.constant = 0 heightConstraint.constant = 48 backBtnTop.constant = 8 // Animate NSAnimationContext.defaultAnimate({ _ in self.alphaValue = 1 self.originContainerView.alphaValue = 0 self.roundBarView.alphaValue = 0 self.squareBarView.alphaValue = 0 self.lineVerticalView.alphaValue = 0 self.actionSearchView.alphaValue = 0 self.searchContainerView.alphaValue = 1 self.superview?.layoutSubtreeIfNeeded() }) } fileprivate func hideAllAnimation() { NSAnimationContext.defaultAnimate({ _ in self.alphaValue = 0 self.superview?.layoutSubtreeIfNeeded() }, completion: { self.isHidden = true }) } } // MARK: - ActionSearchBarViewDelegate extension SearchBarView: ActionSearchBarViewDelegate { func shouldOpenFullSearch() { delegate?.searchBar(self, layoutStateDidChanged: .expand) } } // MARK: - XIBInitializable extension SearchBarView: XIBInitializable { typealias XibType = SearchBarView }
mit
6b3394b496bc8b8046a9934e867bd1fb
29.140741
92
0.646965
5.425333
false
false
false
false
ahoppen/swift
validation-test/compiler_crashers_2_fixed/0012-rdar20270240.swift
38
569
// RUN: %target-swift-frontend %s -emit-silgen protocol FooProtocol { associatedtype Element } protocol Bar { associatedtype Foo : FooProtocol typealias Element = Foo.Element mutating func extend< C : FooProtocol >(elements: C) where C.Element == Element } struct FooImpl<T> : FooProtocol { typealias Element = T } struct BarImpl<T> : Bar { typealias Foo = FooImpl<T> // Uncomment this line to make it compile: // typealias Element = T mutating func extend< C : FooProtocol >(elements: C) where C.Element == T {} }
apache-2.0
81b7422c3a8f683c56e94abaf95701a8
15.735294
46
0.664323
3.844595
false
false
false
false
mmrmmlrr/ModelsTreeKit
JetPack/Signal.swift
1
1513
// // Signal.swift // SessionSwift // // Created by aleksey on 14.10.15. // Copyright © 2015 aleksey chernish. All rights reserved. // import Foundation precedencegroup Chaining { higherThan: MultiplicationPrecedence } infix operator >>> : Chaining public func >>><T> (signal: Signal<T>, handler: @escaping ((T) -> Void)) -> Disposable { return signal.subscribeNext(handler) } public class Signal<T> { public var hashValue = ProcessInfo.processInfo.globallyUniqueString.hash public typealias SignalHandler = (T) -> Void public typealias StateHandler = (Bool) -> Void var nextHandlers = [Invocable]() var completedHandlers = [Invocable]() //Destructor is executed before the signal's deallocation. A good place to cancel your network operation. var destructor: ((Void) -> Void)? var pool = AutodisposePool() deinit { destructor?() pool.drain() } public func sendNext(_ newValue: T) { nextHandlers.forEach { $0.invoke(newValue) } } public func sendCompleted() { completedHandlers.forEach { $0.invokeState(true) } } //Adds handler to signal and returns subscription public func subscribeNext(_ handler: @escaping SignalHandler) -> Disposable { let wrapper = Subscription(handler: handler, signal: self) nextHandlers.append(wrapper) return wrapper } } extension Signal: Hashable, Equatable {} public func ==<T>(lhs: Signal<T>, rhs: Signal<T>) -> Bool { return lhs.hashValue == rhs.hashValue }
mit
d41010edc72719cbcb73aa5d16cc40ad
23.387097
107
0.685185
4.211699
false
false
false
false
vimask/ClientCodeGen
ClientCodeGen/Lang data models/Author.swift
1
2004
// // Author.swift // // Create by Ahmed Ali on 23/5/2016 // Copyright © 2016. All rights reserved. // Model file Generated using JSONExport: https://github.com/Ahmed-Ali/JSONExport import Foundation class Author : NSObject, NSCoding{ var website : String! var email : String! var name : String! /** * Instantiate the instance using the passed dictionary values to set the properties values */ init(fromDictionary dictionary: NSDictionary){ website = dictionary["website"] as? String email = dictionary["email"] as? String name = dictionary["name"] as? String } /** * Returns all the available property values in the form of NSDictionary object where the key is the approperiate json key and the value is the value of the corresponding property */ func toDictionary() -> NSDictionary { let dictionary = NSMutableDictionary() if website != nil{ dictionary["website"] = website } if email != nil{ dictionary["email"] = email } if name != nil{ dictionary["name"] = name } return dictionary } /** * NSCoding required initializer. * Fills the data from the passed decoder */ @objc required init(coder aDecoder: NSCoder) { website = aDecoder.decodeObject(forKey: "website") as? String email = aDecoder.decodeObject(forKey: "email") as? String name = aDecoder.decodeObject(forKey: "name") as? String } /** * NSCoding required method. * Encodes mode properties into the decoder */ @objc func encode(with aCoder: NSCoder) { if website != nil{ aCoder.encode(website, forKey: "website") } if email != nil{ aCoder.encode(email, forKey: "email") } if name != nil{ aCoder.encode(name, forKey: "name") } } }
mit
6504fb669b2f979952cf8de1ed8c1f32
25.706667
183
0.583625
4.75772
false
false
false
false
taketo1024/SwiftyAlgebra
Playgrounds/Numbers.playground/Contents.swift
1
2526
import SwmCore // MARK: Integers do { typealias Z = 𝐙 // == Int let a = 7 let b = 3 a + b a - b a * b b % a } // MARK: Rational Numbers do { typealias Q = 𝐐 let a = 4 ./ 5 // 4/5 let b = 3 ./ 2 // 3/2 a + b a - b a * b a / b } // MARK: Real Numbers (actually not) do { typealias R = 𝐑 // == Double let a = 2.0 let b = -4.5 a + b a - b a * b a / b √a } // MARK: ComplexNumbers do { typealias C = 𝐂 // == Complex<𝐑> let i: C = .imaginaryUnit i * i == -1 let a: C = 3 + i let b: C = 4 + 2 * i a + b a - b a * b i.inverse a.inverse b.inverse a / b let π = C(.pi) exp(i * π).isApproximatelyEqualTo(-1, error: 0.000001) } do { typealias C = Complex<𝐙> // Gaussian integers 𝐙[i] let i: C = .imaginaryUnit let a: C = 3 + i let b: C = 4 + 2 * i a + b a - b a * b i.inverse a.inverse b.inverse // a / b // this is not available, since 𝐙 is not a field. } // MARK: Quaternions do { typealias H = 𝐇 // == Quaternion<𝐑> let i: H = .i let j: H = .j let k: H = .k i * i == -1 j * j == -1 k * k == -1 i * j == k j * k == i k * i == j let a: H = 1 + 2 * i let b: H = 3 - 2 * j a + b a - b a * b i.inverse a.inverse b.inverse a / b } // MARK: IntegerQuotients do { typealias Z3 = IntegerQuotientRing<_3> // this a field let a: Z3 = 2 let b: Z3 = 1 a + b a - b a * b a.inverse b.inverse b / a } do { typealias Z4 = IntegerQuotientRing<_4> // this not a field let a: Z4 = 2 let b: Z4 = 1 a + b a - b a * b a.inverse b.inverse // a / b // this is unavailable, since 4 is not a prime. } // MARK: Algebraic extension do { typealias P = Polynomial<𝐐, StandardPolynomialIndeterminates.x> struct p: IrrPolynomialTP { static let value = P(coeffs: -2, 0, 1) // x^2 - 2 } typealias A = PolynomialQuotientRing<P, p> // 𝐐[x]/(x^2 - 2) = 𝐐(√2) let x = A(.indeterminate) // x ∈ 𝐐[x]/(x^2 - 2) x * x == 2 // x = √2 x.isInvertible x.inverse x * x.inverse! == 1 let a: A = 1 + x let b: A = 2 - x a + b a - b a * b a / b }
cc0-1.0
9aa5d595ea8194e6183536dba66f69fd
12.744444
72
0.430477
2.876744
false
false
false
false
velvetroom/columbus
Source/Model/Store/MStorePerkUnlimited.swift
1
532
import UIKit import StoreKit final class MStorePerkUnlimited:MStorePerkProtocol { var status:MStorePerkStatusProtocol? let perkType:DPerkType = DPerkType.unlimited let identifier:String = "iturbide.columbus.unlimited" let icon:UIImage let title:String let descr:String init() { icon = #imageLiteral(resourceName: "assetStoreUnlimited") title = String.localizedModel(key:"MStorePerkUnlimited_title") descr = String.localizedModel(key:"MStorePerkUnlimited_descr") } }
mit
4a45c3ca2cc361304e70dbe077e7ed92
27
70
0.721805
4
false
false
false
false
rnystrom/GitHawk
Pods/ContextMenu/ContextMenu/ContextMenu+UIViewControllerTransitioningDelegate.swift
1
1212
// // ContextMenu+UIViewControllerTransitioningDelegate.swift // ThingsUI // // Created by Ryan Nystrom on 3/10/18. // Copyright © 2018 Ryan Nystrom. All rights reserved. // import UIKit extension ContextMenu: UIViewControllerTransitioningDelegate { public func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { guard let item = self.item else { return nil } return ContextMenuDismissing(item: item) } public func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { guard let item = self.item else { return nil } return ContextMenuPresenting(item: item) } public func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? { guard let item = self.item else { return nil } let controller = ContextMenuPresentationController(presentedViewController: presented, presenting: presenting, item: item) controller.contextDelegate = self return controller } }
mit
a4851a4026649054395126df425cbf7a
39.366667
177
0.753097
5.794258
false
false
false
false
LiulietLee/BilibiliCD
BCD/ViewController/Feedback/FeedbackController.swift
1
5716
// // FeedbackController.swift // BCD // // Created by Liuliet.Lee on 11/7/2019. // Copyright © 2019 Liuliet.Lee. All rights reserved. // import UIKit import LLDialog class FeedbackController: UIViewController, UITableViewDelegate, UITableViewDataSource, EditControllerDelegate { @IBOutlet weak var menuButton: UIBarButtonItem! @IBOutlet weak var tableView: UITableView! @IBOutlet weak var newCommentButton: UIButton! private var refreshControl = UIRefreshControl() private var isLoading = false private let commentProvider = CommentProvider.shared override func viewDidLoad() { super.viewDidLoad() view.tintColor = UIColor.systemOrange tableView.dataSource = self tableView.delegate = self tableView.tableFooterView = UIView() newCommentButton.layer.masksToBounds = true newCommentButton.layer.cornerRadius = 28.0 menuButton.target = revealViewController() menuButton.action = #selector(revealViewController().revealToggle(_:)) view.addGestureRecognizer(revealViewController().panGestureRecognizer()) refreshControl.addTarget(self, action: #selector(reload), for: .valueChanged) tableView.addSubview(refreshControl) refreshControl.beginRefreshing() reload() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) tableView.reloadData() } @objc private func reload() { load(reset: true) } private func load(reset: Bool = false) { if isLoading { return } isLoading = true commentProvider.getNextCommentList(reset: reset) { [weak self] in guard let self = self else { return } DispatchQueue.main.async { [weak self] in guard let self = self else { return } self.tableView.reloadData() self.isLoading = false self.refreshControl.endRefreshing() } } } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return commentProvider.comments.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CommentCell let idx = indexPath.row cell.data = commentProvider.comments[idx] cell.liked = commentProvider.buttonStatus[idx].liked cell.disliked = commentProvider.buttonStatus[idx].disliked return cell } func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { let count = commentProvider.comments.count if indexPath.row == count - 1, count < commentProvider.commentCount { load() } } @IBAction func likeButtonTapped(_ sender: UIButton) { if let superView = sender.superview, let cell = superView.superview as? CommentCell, let index = tableView.indexPath(for: cell) { sender.isEnabled = false commentProvider.likeComment(commentIndex: index.row) { [weak self] in DispatchQueue.main.async { guard let self = self else { return } self.tableView.reloadRows(at: [index], with: .none) sender.isEnabled = true } } } } @IBAction func dislikeButtonTapped(_ sender: UIButton) { if let superView = sender.superview, let cell = superView.superview as? CommentCell, let index = tableView.indexPath(for: cell) { sender.isEnabled = false commentProvider.dislikeComment(commentIndex: index.row) { [weak self] in DispatchQueue.main.async { guard let self = self else { return } self.tableView.reloadRows(at: [index], with: .none) sender.isEnabled = true } } } } @IBAction func helpButtonTapped(_ sender: UIBarButtonItem) { // TODO } func editFinished(username: String, content: String) { commentProvider.newComment(username: username, content: content) { [weak self] (comment) in guard let self = self else { return } if comment == nil { DispatchQueue.main.async { [weak self] in guard self != nil else { return } LLDialog() .set(title: "咦") .set(title: "哪里出了问题……") .show() } } else { self.reload() } } } @IBAction func showHelp(_ sender: UIBarButtonItem) { let vc = HisTutViewController() vc.page = "AboutFeedback" present(vc, animated: true) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let backItem = UIBarButtonItem() backItem.title = "" navigationItem.backBarButtonItem = backItem if segue.destination is ReplyController, let cell = sender as? UITableViewCell, let index = tableView.indexPath(for: cell), commentProvider.comments.count > index.row { commentProvider.currentCommentIndex = index.row } else if let vc = segue.destination as? EditController { vc.delegate = self vc.model = .comment } } }
gpl-3.0
bc2a18379ff72a395ff93d11a52de31c
34.166667
112
0.592242
5.217033
false
false
false
false
ben-ng/swift
validation-test/compiler_crashers_fixed/01258-swift-constraints-constraintsystem-gettypeofmemberreference.swift
1
861
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck func n<w>() -> (w, w -> w) -> w { o m o.q = { } { w) { k } } protocol n { } class o: n{ class func q {} func p(e: Int = x) { } let c = p protocol p : p { } protocol p { } class e: p { } k e.w == l> { } func p(c: Any, m: Any) -> (((Any, b(c) -> <d>(() -> d) { } class d<c>: NSObject { <D> { init <A: A where A.B == D { } } protocol A { } class C<D> { init <A: A where A.B == D>(e: A.B) { } } } struct D : C { func g<T where T.E == F>(f: B<T>) { } } func b(c) ->
apache-2.0
b596a954651593f200196d733d59b7e1
16.9375
79
0.583043
2.532353
false
false
false
false